diff --git a/android/CMakeLists.txt b/android/CMakeLists.txt index 5ed961be..23e2fb0e 100644 --- a/android/CMakeLists.txt +++ b/android/CMakeLists.txt @@ -51,6 +51,14 @@ set_target_properties(z PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${platform_spec_path}/include/zlib ) +add_library(android_platform + ${CMAKE_ANDROID_NDK}/sources/android/cpufeatures/cpu-features.c + ${CMAKE_ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c +) +target_include_directories(android_platform PUBLIC + ${CMAKE_ANDROID_NDK}/sources/android/cpufeatures + ${CMAKE_ANDROID_NDK}/sources/android/native_app_glue +) set(se_libs_name) @@ -165,18 +173,22 @@ if(USE_SE_V8 AND USE_V8_DEBUGGER) ) endif() + list(APPEND CC_EXTERNAL_LIBS freetype jpeg png uv webp - OpenSLES ${se_libs_name} z + android_platform ) list(APPEND CC_EXTERNAL_INCLUDES ${platform_spec_path}/include + ${platform_spec_path}/include/v8 + ${platform_spec_path}/include/uv + ${CMAKE_ANDROID_NDK}/sources/android/native_app_glue ) \ No newline at end of file diff --git a/cmake/CocosExternalConfig.cmake b/cmake/CocosExternalConfig.cmake index 51dc1292..08dbcee4 100644 --- a/cmake/CocosExternalConfig.cmake +++ b/cmake/CocosExternalConfig.cmake @@ -1,22 +1,5 @@ # set friendly platform define - if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(WINDOWS TRUE) - set(SYSTEM_STRING "Windows Desktop") - elseif(${CMAKE_SYSTEM_NAME} MATCHES "Android") - set(ANDROID TRUE) - set(SYSTEM_STRING "Android") - elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - if(IOS) - set(APPLE TRUE) - set(SYSTEM_STRING "IOS") - else() - set(APPLE TRUE) - set(MACOSX TRUE) - set(SYSTEM_STRING "Mac OSX") - endif() - endif() - if(IOS) set(platform_name ios) set(platform_spec_path ios) diff --git a/ios/include/spidermonkey/fdlibm.h b/ios/include/spidermonkey/fdlibm.h deleted file mode 100644 index 0ad21591..00000000 --- a/ios/include/spidermonkey/fdlibm.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ==================================================== - * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. - * - * Developed at SunPro, a Sun Microsystems, Inc. business. - * Permission to use, copy, modify, and distribute this - * software is freely granted, provided that this notice - * is preserved. - * ==================================================== - */ - -/* - * from: @(#)fdlibm.h 5.1 93/09/24 - * $FreeBSD$ - */ - -#ifndef mozilla_imported_fdlibm_h -#define mozilla_imported_fdlibm_h - -namespace fdlibm { - -double acos(double); -double asin(double); -double atan(double); -double atan2(double, double); - -double cosh(double); -double sinh(double); -double tanh(double); - -double exp(double); -double log(double); -double log10(double); - -double pow(double, double); -double sqrt(double); -double fabs(double); - -double floor(double); -double trunc(double); -double ceil(double); - -double acosh(double); -double asinh(double); -double atanh(double); -double cbrt(double); -double expm1(double); -double hypot(double, double); -double log1p(double); -double log2(double); -double rint(double); -double copysign(double, double); -double nearbyint(double); -double scalbn(double, int); - -float ceilf(float); -float floorf(float); - -float nearbyintf(float); -float rintf(float); -float truncf(float); - -} /* namespace fdlibm */ - -#endif /* mozilla_imported_fdlibm_h */ diff --git a/ios/include/spidermonkey/jemalloc_types.h b/ios/include/spidermonkey/jemalloc_types.h deleted file mode 100644 index ae8dc441..00000000 --- a/ios/include/spidermonkey/jemalloc_types.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -*- Mode: C; tab-width: 8; c-basic-offset: 8 -*- */ -/* vim:set softtabstop=8 shiftwidth=8: */ -/*- - * Copyright (C) 2006-2008 Jason Evans . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice(s), this list of conditions and the following disclaimer as - * the first lines of this file unmodified other than the possible - * addition of one or more copyright notices. - * 2. Redistributions in binary form must reproduce the above copyright - * notice(s), this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _JEMALLOC_TYPES_H_ -#define _JEMALLOC_TYPES_H_ - -/* grab size_t */ -#ifdef _MSC_VER -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef unsigned char jemalloc_bool; - -/* - * jemalloc_stats() is not a stable interface. When using jemalloc_stats_t, be - * sure that the compiled results of jemalloc.c are in sync with this header - * file. - */ -typedef struct { - /* - * Run-time configuration settings. - */ - jemalloc_bool opt_abort; /* abort(3) on error? */ - jemalloc_bool opt_junk; /* Fill allocated memory with 0xe4? */ - jemalloc_bool opt_poison; /* Fill free memory with 0xe5? */ - jemalloc_bool opt_utrace; /* Trace all allocation events? */ - jemalloc_bool opt_sysv; /* SysV semantics? */ - jemalloc_bool opt_xmalloc; /* abort(3) on OOM? */ - jemalloc_bool opt_zero; /* Fill allocated memory with 0x0? */ - size_t narenas; /* Number of arenas. */ - size_t balance_threshold; /* Arena contention rebalance threshold. */ - size_t quantum; /* Allocation quantum. */ - size_t small_max; /* Max quantum-spaced allocation size. */ - size_t large_max; /* Max sub-chunksize allocation size. */ - size_t chunksize; /* Size of each virtual memory mapping. */ - size_t dirty_max; /* Max dirty pages per arena. */ - - /* - * Current memory usage statistics. - */ - size_t mapped; /* Bytes mapped (not necessarily committed). */ - size_t allocated; /* Bytes allocated (committed, in use by application). */ - size_t waste; /* Bytes committed, not in use by the - application, and not intentionally left - unused (i.e., not dirty). */ - size_t page_cache; /* Committed, unused pages kept around as a - cache. (jemalloc calls these "dirty".) */ - size_t bookkeeping; /* Committed bytes used internally by the - allocator. */ - size_t bin_unused; /* Bytes committed to a bin but currently unused. */ -} jemalloc_stats_t; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* _JEMALLOC_TYPES_H_ */ diff --git a/ios/include/spidermonkey/js-config-32.h b/ios/include/spidermonkey/js-config-32.h deleted file mode 100644 index f21bdf41..00000000 --- a/ios/include/spidermonkey/js-config-32.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=78: - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_config_h -#define js_config_h - -/* Definitions set at build time that affect SpiderMonkey's public API. - This header file is generated by the SpiderMonkey configure script, - and installed along with jsapi.h. */ - -/* Define to 1 if SpiderMonkey is in debug mode. */ -/* #undef JS_DEBUG */ - -/* - * NB: We have a special case for rust-bindgen, which wants to be able to - * generate both debug and release bindings on a single objdir. - */ -#ifdef JS_DEBUG -#if !defined(DEBUG) && !defined(RUST_BINDGEN) -# error "SpiderMonkey was configured with --enable-debug, so DEBUG must be defined when including this header" -# endif -#else -# if defined(DEBUG) && !defined(RUST_BINDGEN) -# error "SpiderMonkey was configured with --disable-debug, so DEBUG must be not defined when including this header" -# endif -#endif - -/* Define to 1 if SpiderMonkey should not use struct types in debug builds. */ -/* #undef JS_NO_JSVAL_JSID_STRUCT_TYPES */ - -/* Define to 1 if SpiderMonkey should support multi-threaded clients. */ -/* #undef JS_THREADSAFE */ - -/* Define to 1 if SpiderMonkey should include ctypes support. */ -/* #undef JS_HAS_CTYPES */ - -/* Define to 1 if SpiderMonkey should support the ability to perform - entirely too much GC. */ -/* #undef JS_GC_ZEAL */ - -/* Define to 1 if SpiderMonkey should use small chunks. */ -/* #undef JS_GC_SMALL_CHUNK_SIZE */ - -/* Define to 1 to perform extra assertions and heap poisoning. */ -/* #undef JS_CRASH_DIAGNOSTICS */ - -/* Define to 1 if SpiderMonkey is in NUNBOX32 mode. */ -#define JS_NUNBOX32 1 - -/* Define to 1 if SpiderMonkey is in PUNBOX64 mode. */ -/* #undef JS_PUNBOX64 */ - -/* MOZILLA JSAPI version number components */ -#define MOZJS_MAJOR_VERSION 52 -#define MOZJS_MINOR_VERSION 0 - -#endif /* js_config_h */ diff --git a/ios/include/spidermonkey/js-config-64.h b/ios/include/spidermonkey/js-config-64.h deleted file mode 100644 index 6909f6c7..00000000 --- a/ios/include/spidermonkey/js-config-64.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=78: - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_config_h -#define js_config_h - -/* Definitions set at build time that affect SpiderMonkey's public API. - This header file is generated by the SpiderMonkey configure script, - and installed along with jsapi.h. */ - -/* Define to 1 if SpiderMonkey is in debug mode. */ -/* #undef JS_DEBUG */ - -/* - * NB: We have a special case for rust-bindgen, which wants to be able to - * generate both debug and release bindings on a single objdir. - */ -#ifdef JS_DEBUG -#if !defined(DEBUG) && !defined(RUST_BINDGEN) -# error "SpiderMonkey was configured with --enable-debug, so DEBUG must be defined when including this header" -# endif -#else -# if defined(DEBUG) && !defined(RUST_BINDGEN) -# error "SpiderMonkey was configured with --disable-debug, so DEBUG must be not defined when including this header" -# endif -#endif - -/* Define to 1 if SpiderMonkey should not use struct types in debug builds. */ -/* #undef JS_NO_JSVAL_JSID_STRUCT_TYPES */ - -/* Define to 1 if SpiderMonkey should support multi-threaded clients. */ -/* #undef JS_THREADSAFE */ - -/* Define to 1 if SpiderMonkey should include ctypes support. */ -/* #undef JS_HAS_CTYPES */ - -/* Define to 1 if SpiderMonkey should support the ability to perform - entirely too much GC. */ -/* #undef JS_GC_ZEAL */ - -/* Define to 1 if SpiderMonkey should use small chunks. */ -/* #undef JS_GC_SMALL_CHUNK_SIZE */ - -/* Define to 1 to perform extra assertions and heap poisoning. */ -/* #undef JS_CRASH_DIAGNOSTICS */ - -/* Define to 1 if SpiderMonkey is in NUNBOX32 mode. */ -/* #undef JS_NUNBOX32 */ - -/* Define to 1 if SpiderMonkey is in PUNBOX64 mode. */ -#define JS_PUNBOX64 1 - -/* MOZILLA JSAPI version number components */ -#define MOZJS_MAJOR_VERSION 52 -#define MOZJS_MINOR_VERSION 0 - -#endif /* js_config_h */ diff --git a/ios/include/spidermonkey/js-config.h b/ios/include/spidermonkey/js-config.h deleted file mode 100644 index a1ded849..00000000 --- a/ios/include/spidermonkey/js-config.h +++ /dev/null @@ -1,5 +0,0 @@ -#if defined(__LP64__) && __LP64__ -#include"js-config-64.h" -#else -#include"js-config-32.h" -#endif diff --git a/ios/include/spidermonkey/js.msg b/ios/include/spidermonkey/js.msg deleted file mode 100644 index 246e363c..00000000 --- a/ios/include/spidermonkey/js.msg +++ /dev/null @@ -1,581 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * This is the JavaScript error message file. - * - * The format for each JS error message is: - * - * MSG_DEF(, , , - * ) - * - * where ; - * is a legal C identifer that will be used in the - * JS engine source. - * - * is an integer literal specifying the total number of - * replaceable arguments in the following format string. - * - * is an exception index from the enum in jsexn.c; - * JSEXN_NONE for none. The given exception index will be raised by the - * engine when the corresponding error occurs. - * - * is a string literal, optionally containing sequences - * {X} where X is an integer representing the argument number that will - * be replaced with a string value when the error is reported. - * - * e.g. - * - * MSG_DEF(JSMSG_NOT_A_SUBSPECIES, 2, JSEXN_NONE, - * "{0} is not a member of the {1} family") - * - * can be used: - * - * JS_ReportErrorNumberASCII(JSMSG_NOT_A_SUBSPECIES, "Rhino", "Monkey"); - * - * to report: - * - * "Rhino is not a member of the Monkey family" - */ - -MSG_DEF(JSMSG_NOT_AN_ERROR, 0, JSEXN_ERR, "") -MSG_DEF(JSMSG_NOT_DEFINED, 1, JSEXN_REFERENCEERR, "{0} is not defined") -MSG_DEF(JSMSG_MORE_ARGS_NEEDED, 3, JSEXN_TYPEERR, "{0} requires more than {1} argument{2}") -MSG_DEF(JSMSG_INCOMPATIBLE_PROTO, 3, JSEXN_TYPEERR, "{0}.prototype.{1} called on incompatible {2}") -MSG_DEF(JSMSG_NO_CONSTRUCTOR, 1, JSEXN_TYPEERR, "{0} has no constructor") -MSG_DEF(JSMSG_BAD_SORT_ARG, 0, JSEXN_TYPEERR, "invalid Array.prototype.sort argument") -MSG_DEF(JSMSG_CANT_WATCH, 1, JSEXN_TYPEERR, "can't watch non-native objects of class {0}") -MSG_DEF(JSMSG_READ_ONLY, 1, JSEXN_TYPEERR, "{0} is read-only") -MSG_DEF(JSMSG_CANT_DELETE, 1, JSEXN_TYPEERR, "property {0} is non-configurable and can't be deleted") -MSG_DEF(JSMSG_CANT_TRUNCATE_ARRAY, 0, JSEXN_TYPEERR, "can't delete non-configurable array element") -MSG_DEF(JSMSG_NOT_FUNCTION, 1, JSEXN_TYPEERR, "{0} is not a function") -MSG_DEF(JSMSG_NOT_CONSTRUCTOR, 1, JSEXN_TYPEERR, "{0} is not a constructor") -MSG_DEF(JSMSG_CANT_CONVERT_TO, 2, JSEXN_TYPEERR, "can't convert {0} to {1}") -MSG_DEF(JSMSG_TOPRIMITIVE_NOT_CALLABLE, 2, JSEXN_TYPEERR, "can't convert {0} to {1}: its [Symbol.toPrimitive] property is not a function") -MSG_DEF(JSMSG_TOPRIMITIVE_RETURNED_OBJECT, 2, JSEXN_TYPEERR, "can't convert {0} to {1}: its [Symbol.toPrimitive] method returned an object") -MSG_DEF(JSMSG_NO_PROPERTIES, 1, JSEXN_TYPEERR, "{0} has no properties") -MSG_DEF(JSMSG_BAD_REGEXP_FLAG, 1, JSEXN_SYNTAXERR, "invalid regular expression flag {0}") -MSG_DEF(JSMSG_ARG_INDEX_OUT_OF_RANGE, 1, JSEXN_RANGEERR, "argument {0} accesses an index that is out of range") -MSG_DEF(JSMSG_SPREAD_TOO_LARGE, 0, JSEXN_RANGEERR, "array too large due to spread operand(s)") -MSG_DEF(JSMSG_BAD_WEAKMAP_KEY, 0, JSEXN_TYPEERR, "cannot use the given object as a weak map key") -MSG_DEF(JSMSG_BAD_GETTER_OR_SETTER, 1, JSEXN_TYPEERR, "invalid {0} usage") -MSG_DEF(JSMSG_BAD_ARRAY_LENGTH, 0, JSEXN_RANGEERR, "invalid array length") -MSG_DEF(JSMSG_REDECLARED_VAR, 2, JSEXN_SYNTAXERR, "redeclaration of {0} {1}") -MSG_DEF(JSMSG_UNDECLARED_VAR, 1, JSEXN_REFERENCEERR, "assignment to undeclared variable {0}") -MSG_DEF(JSMSG_GETTER_ONLY, 0, JSEXN_TYPEERR, "setting a property that has only a getter") -MSG_DEF(JSMSG_OVERWRITING_ACCESSOR, 1, JSEXN_TYPEERR, "can't overwrite accessor property {0}") -MSG_DEF(JSMSG_UNDEFINED_PROP, 1, JSEXN_REFERENCEERR, "reference to undefined property {0}") -MSG_DEF(JSMSG_INVALID_MAP_ITERABLE, 1, JSEXN_TYPEERR, "iterable for {0} should have array-like objects") -MSG_DEF(JSMSG_NESTING_GENERATOR, 0, JSEXN_TYPEERR, "already executing generator") -MSG_DEF(JSMSG_INCOMPATIBLE_METHOD, 3, JSEXN_TYPEERR, "{0} {1} called on incompatible {2}") -MSG_DEF(JSMSG_OBJECT_WATCH_DEPRECATED, 0, JSEXN_WARN, "Object.prototype.watch and unwatch are very slow, non-standard, and deprecated; use a getter/setter instead") -MSG_DEF(JSMSG_ARRAYBUFFER_SLICE_DEPRECATED, 0, JSEXN_WARN, "ArrayBuffer.slice is deprecated; use ArrayBuffer.prototype.slice instead") -MSG_DEF(JSMSG_BAD_SURROGATE_CHAR, 1, JSEXN_TYPEERR, "bad surrogate character {0}") -MSG_DEF(JSMSG_UTF8_CHAR_TOO_LARGE, 1, JSEXN_TYPEERR, "UTF-8 character {0} too large") -MSG_DEF(JSMSG_MALFORMED_UTF8_CHAR, 1, JSEXN_TYPEERR, "malformed UTF-8 character sequence at offset {0}") -MSG_DEF(JSMSG_BUILTIN_CTOR_NO_NEW, 1, JSEXN_TYPEERR, "calling a builtin {0} constructor without new is forbidden") -MSG_DEF(JSMSG_BAD_GENERATOR_YIELD, 1, JSEXN_TYPEERR, "yield from closing generator {0}") -MSG_DEF(JSMSG_EMPTY_ARRAY_REDUCE, 0, JSEXN_TYPEERR, "reduce of empty array with no initial value") -MSG_DEF(JSMSG_UNEXPECTED_TYPE, 2, JSEXN_TYPEERR, "{0} is {1}") -MSG_DEF(JSMSG_MISSING_FUN_ARG, 2, JSEXN_TYPEERR, "missing argument {0} when calling function {1}") -MSG_DEF(JSMSG_NOT_NONNULL_OBJECT, 1, JSEXN_TYPEERR, "{0} is not a non-null object") -MSG_DEF(JSMSG_SET_NON_OBJECT_RECEIVER, 1, JSEXN_TYPEERR, "can't assign to properties of {0}: not an object") -MSG_DEF(JSMSG_INVALID_DESCRIPTOR, 0, JSEXN_TYPEERR, "property descriptors must not specify a value or be writable when a getter or setter has been specified") -MSG_DEF(JSMSG_OBJECT_NOT_EXTENSIBLE, 1, JSEXN_TYPEERR, "{0}: Object is not extensible") -MSG_DEF(JSMSG_CANT_DEFINE_PROP_OBJECT_NOT_EXTENSIBLE, 2, JSEXN_TYPEERR, "can't define property {1}: {0} is not extensible") -MSG_DEF(JSMSG_CANT_REDEFINE_PROP, 1, JSEXN_TYPEERR, "can't redefine non-configurable property {0}") -MSG_DEF(JSMSG_CANT_REDEFINE_ARRAY_LENGTH, 0, JSEXN_TYPEERR, "can't redefine array length") -MSG_DEF(JSMSG_CANT_DEFINE_PAST_ARRAY_LENGTH, 0, JSEXN_TYPEERR, "can't define array index property past the end of an array with non-writable length") -MSG_DEF(JSMSG_BAD_GET_SET_FIELD, 1, JSEXN_TYPEERR, "property descriptor's {0} field is neither undefined nor a function") -MSG_DEF(JSMSG_THROW_TYPE_ERROR, 0, JSEXN_TYPEERR, "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them") -MSG_DEF(JSMSG_NOT_EXPECTED_TYPE, 3, JSEXN_TYPEERR, "{0}: expected {1}, got {2}") -MSG_DEF(JSMSG_NOT_ITERABLE, 1, JSEXN_TYPEERR, "{0} is not iterable") -MSG_DEF(JSMSG_NOT_ITERATOR, 1, JSEXN_TYPEERR, "{0} is not iterator") -MSG_DEF(JSMSG_ALREADY_HAS_PRAGMA, 2, JSEXN_WARN, "{0} is being assigned a {1}, but already has one") -MSG_DEF(JSMSG_GET_ITER_RETURNED_PRIMITIVE, 0, JSEXN_TYPEERR, "[Symbol.iterator]() returned a non-object value") -MSG_DEF(JSMSG_NEXT_RETURNED_PRIMITIVE, 0, JSEXN_TYPEERR, "iterator.next() returned a non-object value") -MSG_DEF(JSMSG_CANT_SET_PROTO, 0, JSEXN_TYPEERR, "can't set prototype of this object") -MSG_DEF(JSMSG_CANT_SET_PROTO_OF, 1, JSEXN_TYPEERR, "can't set prototype of {0}") -MSG_DEF(JSMSG_CANT_SET_PROTO_CYCLE, 0, JSEXN_TYPEERR, "can't set prototype: it would cause a prototype chain cycle") -MSG_DEF(JSMSG_INVALID_ARG_TYPE, 3, JSEXN_TYPEERR, "Invalid type: {0} can't be a{1} {2}") -MSG_DEF(JSMSG_TERMINATED, 1, JSEXN_ERR, "Script terminated by timeout at:\n{0}") -MSG_DEF(JSMSG_PROTO_NOT_OBJORNULL, 1, JSEXN_TYPEERR, "{0}.prototype is not an object or null") -MSG_DEF(JSMSG_CANT_CALL_CLASS_CONSTRUCTOR, 0, JSEXN_TYPEERR, "class constructors must be invoked with |new|") -MSG_DEF(JSMSG_UNINITIALIZED_THIS, 1, JSEXN_REFERENCEERR, "|this| used uninitialized in {0} class constructor") -MSG_DEF(JSMSG_UNINITIALIZED_THIS_ARROW, 0, JSEXN_REFERENCEERR, "|this| used uninitialized in arrow function in class constructor") -MSG_DEF(JSMSG_BAD_DERIVED_RETURN, 1, JSEXN_TYPEERR, "derived class constructor returned invalid value {0}") - -// JSON -MSG_DEF(JSMSG_JSON_BAD_PARSE, 3, JSEXN_SYNTAXERR, "JSON.parse: {0} at line {1} column {2} of the JSON data") -MSG_DEF(JSMSG_JSON_CYCLIC_VALUE, 0, JSEXN_TYPEERR, "cyclic object value") - -// Runtime errors -MSG_DEF(JSMSG_BAD_INSTANCEOF_RHS, 1, JSEXN_TYPEERR, "invalid 'instanceof' operand {0}") -MSG_DEF(JSMSG_BAD_LEFTSIDE_OF_ASS, 0, JSEXN_REFERENCEERR, "invalid assignment left-hand side") -MSG_DEF(JSMSG_BAD_PROTOTYPE, 1, JSEXN_TYPEERR, "'prototype' property of {0} is not an object") -MSG_DEF(JSMSG_IN_NOT_OBJECT, 1, JSEXN_TYPEERR, "invalid 'in' operand {0}") -MSG_DEF(JSMSG_TOO_MANY_CON_SPREADARGS, 0, JSEXN_RANGEERR, "too many constructor arguments") -MSG_DEF(JSMSG_TOO_MANY_FUN_SPREADARGS, 0, JSEXN_RANGEERR, "too many function arguments") -MSG_DEF(JSMSG_UNINITIALIZED_LEXICAL, 1, JSEXN_REFERENCEERR, "can't access lexical declaration `{0}' before initialization") -MSG_DEF(JSMSG_BAD_CONST_ASSIGN, 1, JSEXN_TYPEERR, "invalid assignment to const `{0}'") -MSG_DEF(JSMSG_CANT_DECLARE_GLOBAL_BINDING, 2, JSEXN_TYPEERR, "cannot declare global binding `{0}': {1}") - -// Date -MSG_DEF(JSMSG_INVALID_DATE, 0, JSEXN_RANGEERR, "invalid date") -MSG_DEF(JSMSG_BAD_TOISOSTRING_PROP, 0, JSEXN_TYPEERR, "toISOString property is not callable") - -// String -MSG_DEF(JSMSG_BAD_URI, 0, JSEXN_URIERR, "malformed URI sequence") -MSG_DEF(JSMSG_INVALID_NORMALIZE_FORM, 0, JSEXN_RANGEERR, "form must be one of 'NFC', 'NFD', 'NFKC', or 'NFKD'") -MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 0, JSEXN_RANGEERR, "repeat count must be non-negative") -MSG_DEF(JSMSG_NOT_A_CODEPOINT, 1, JSEXN_RANGEERR, "{0} is not a valid code point") -MSG_DEF(JSMSG_RESULTING_STRING_TOO_LARGE, 0, JSEXN_RANGEERR, "repeat count must be less than infinity and not overflow maximum string size") - -// Number -MSG_DEF(JSMSG_BAD_RADIX, 0, JSEXN_RANGEERR, "radix must be an integer at least 2 and no greater than 36") -MSG_DEF(JSMSG_PRECISION_RANGE, 1, JSEXN_RANGEERR, "precision {0} out of range") - -// Function -MSG_DEF(JSMSG_BAD_APPLY_ARGS, 1, JSEXN_TYPEERR, "second argument to Function.prototype.{0} must be an array") -MSG_DEF(JSMSG_BAD_FORMAL, 0, JSEXN_SYNTAXERR, "malformed formal parameter") -MSG_DEF(JSMSG_CALLER_IS_STRICT, 0, JSEXN_TYPEERR, "access to strict mode caller function is censored") -MSG_DEF(JSMSG_DEPRECATED_USAGE, 1, JSEXN_REFERENCEERR, "deprecated {0} usage") -MSG_DEF(JSMSG_NOT_SCRIPTED_FUNCTION, 1, JSEXN_TYPEERR, "{0} is not a scripted function") -MSG_DEF(JSMSG_NO_REST_NAME, 0, JSEXN_SYNTAXERR, "no parameter name after ...") -MSG_DEF(JSMSG_PARAMETER_AFTER_REST, 0, JSEXN_SYNTAXERR, "parameter after rest parameter") -MSG_DEF(JSMSG_TOO_MANY_ARGUMENTS, 0, JSEXN_RANGEERR, "too many arguments provided for a function call") - -// CSP -MSG_DEF(JSMSG_CSP_BLOCKED_EVAL, 0, JSEXN_ERR, "call to eval() blocked by CSP") -MSG_DEF(JSMSG_CSP_BLOCKED_FUNCTION, 0, JSEXN_ERR, "call to Function() blocked by CSP") - -// Wrappers -MSG_DEF(JSMSG_ACCESSOR_DEF_DENIED, 1, JSEXN_ERR, "Permission denied to define accessor property {0}") -MSG_DEF(JSMSG_DEAD_OBJECT, 0, JSEXN_TYPEERR, "can't access dead object") -MSG_DEF(JSMSG_UNWRAP_DENIED, 0, JSEXN_ERR, "permission denied to unwrap object") - -// JSAPI-only (Not thrown as JS exceptions) -MSG_DEF(JSMSG_BAD_CLONE_FUNOBJ_SCOPE, 0, JSEXN_TYPEERR, "bad cloned function scope chain") -MSG_DEF(JSMSG_CANT_CLONE_OBJECT, 0, JSEXN_TYPEERR, "can't clone object") -MSG_DEF(JSMSG_CANT_OPEN, 2, JSEXN_ERR, "can't open {0}: {1}") -MSG_DEF(JSMSG_USER_DEFINED_ERROR, 0, JSEXN_ERR, "JS_ReportError was called") - -// Internal errors -MSG_DEF(JSMSG_ALLOC_OVERFLOW, 0, JSEXN_INTERNALERR, "allocation size overflow") -MSG_DEF(JSMSG_BAD_BYTECODE, 1, JSEXN_INTERNALERR, "unimplemented JavaScript bytecode {0}") -MSG_DEF(JSMSG_BUFFER_TOO_SMALL, 0, JSEXN_INTERNALERR, "buffer too small") -MSG_DEF(JSMSG_BUILD_ID_NOT_AVAILABLE, 0, JSEXN_INTERNALERR, "build ID is not available") -MSG_DEF(JSMSG_BYTECODE_TOO_BIG, 2, JSEXN_INTERNALERR, "bytecode {0} too large (limit {1})") -MSG_DEF(JSMSG_ERR_DURING_THROW, 0, JSEXN_INTERNALERR, "an internal error occurred while throwing an exception") -MSG_DEF(JSMSG_NEED_DIET, 1, JSEXN_INTERNALERR, "{0} too large") -MSG_DEF(JSMSG_OUT_OF_MEMORY, 0, JSEXN_INTERNALERR, "out of memory") -MSG_DEF(JSMSG_OVER_RECURSED, 0, JSEXN_INTERNALERR, "too much recursion") -MSG_DEF(JSMSG_TOO_BIG_TO_ENCODE, 0, JSEXN_INTERNALERR, "data are to big to encode") -MSG_DEF(JSMSG_TOO_DEEP, 1, JSEXN_INTERNALERR, "{0} nested too deeply") -MSG_DEF(JSMSG_UNCAUGHT_EXCEPTION, 1, JSEXN_INTERNALERR, "uncaught exception: {0}") -MSG_DEF(JSMSG_UNKNOWN_FORMAT, 1, JSEXN_INTERNALERR, "unknown bytecode format {0}") - -// Frontend -MSG_DEF(JSMSG_ACCESSOR_WRONG_ARGS, 3, JSEXN_SYNTAXERR, "{0} functions must have {1} argument{2}") -MSG_DEF(JSMSG_ARRAY_COMP_LEFTSIDE, 0, JSEXN_SYNTAXERR, "invalid array comprehension left-hand side") -MSG_DEF(JSMSG_ARRAY_INIT_TOO_BIG, 0, JSEXN_INTERNALERR, "array initializer too large") -MSG_DEF(JSMSG_AS_AFTER_IMPORT_STAR, 0, JSEXN_SYNTAXERR, "missing keyword 'as' after import *") -MSG_DEF(JSMSG_AS_AFTER_RESERVED_WORD, 1, JSEXN_SYNTAXERR, "missing keyword 'as' after reserved word '{0}'") -MSG_DEF(JSMSG_ASYNC_GENERATOR, 0, JSEXN_SYNTAXERR, "generator function or method can't be async") -MSG_DEF(JSMSG_AWAIT_IN_DEFAULT, 0, JSEXN_SYNTAXERR, "await can't be used in default expression") -MSG_DEF(JSMSG_BAD_ANON_GENERATOR_RETURN, 0, JSEXN_TYPEERR, "anonymous generator function returns a value") -MSG_DEF(JSMSG_BAD_ARROW_ARGS, 0, JSEXN_SYNTAXERR, "invalid arrow-function arguments (parentheses around the arrow-function may help)") -MSG_DEF(JSMSG_BAD_BINDING, 1, JSEXN_SYNTAXERR, "redefining {0} is deprecated") -MSG_DEF(JSMSG_BAD_CONST_DECL, 0, JSEXN_SYNTAXERR, "missing = in const declaration") -MSG_DEF(JSMSG_BAD_CONTINUE, 0, JSEXN_SYNTAXERR, "continue must be inside loop") -MSG_DEF(JSMSG_BAD_DESTRUCT_ASS, 0, JSEXN_REFERENCEERR, "invalid destructuring assignment operator") -MSG_DEF(JSMSG_BAD_DESTRUCT_TARGET, 0, JSEXN_SYNTAXERR, "invalid destructuring target") -MSG_DEF(JSMSG_BAD_DESTRUCT_PARENS, 0, JSEXN_SYNTAXERR, "destructuring patterns in assignments can't be parenthesized") -MSG_DEF(JSMSG_BAD_DESTRUCT_DECL, 0, JSEXN_SYNTAXERR, "missing = in destructuring declaration") -MSG_DEF(JSMSG_BAD_DUP_ARGS, 0, JSEXN_SYNTAXERR, "duplicate argument names not allowed in this context") -MSG_DEF(JSMSG_BAD_FOR_EACH_LOOP, 0, JSEXN_SYNTAXERR, "invalid for each loop") -MSG_DEF(JSMSG_BAD_FOR_LEFTSIDE, 0, JSEXN_SYNTAXERR, "invalid for-in/of left-hand side") -MSG_DEF(JSMSG_LEXICAL_DECL_DEFINES_LET,0, JSEXN_SYNTAXERR, "a lexical declaration can't define a 'let' binding") -MSG_DEF(JSMSG_LET_STARTING_FOROF_LHS, 0, JSEXN_SYNTAXERR, "an expression X in 'for (X of Y)' must not start with 'let'") -MSG_DEF(JSMSG_BAD_GENERATOR_RETURN, 1, JSEXN_TYPEERR, "generator function {0} returns a value") -MSG_DEF(JSMSG_BAD_GENEXP_BODY, 1, JSEXN_SYNTAXERR, "illegal use of {0} in generator expression") -MSG_DEF(JSMSG_BAD_INCOP_OPERAND, 0, JSEXN_REFERENCEERR, "invalid increment/decrement operand") -MSG_DEF(JSMSG_BAD_METHOD_DEF, 0, JSEXN_SYNTAXERR, "bad method definition") -MSG_DEF(JSMSG_BAD_OCTAL, 1, JSEXN_SYNTAXERR, "{0} is not a legal ECMA-262 octal constant") -MSG_DEF(JSMSG_BAD_OPERAND, 1, JSEXN_SYNTAXERR, "invalid {0} operand") -MSG_DEF(JSMSG_BAD_POW_LEFTSIDE, 0, JSEXN_SYNTAXERR, "unparenthesized unary expression can't appear on the left-hand side of '**'") -MSG_DEF(JSMSG_BAD_PROP_ID, 0, JSEXN_SYNTAXERR, "invalid property id") -MSG_DEF(JSMSG_BAD_RETURN_OR_YIELD, 1, JSEXN_SYNTAXERR, "{0} not in function") -MSG_DEF(JSMSG_BAD_STRICT_ASSIGN, 1, JSEXN_SYNTAXERR, "'{0}' can't be defined or assigned to in strict mode code") -MSG_DEF(JSMSG_BAD_SWITCH, 0, JSEXN_SYNTAXERR, "invalid switch statement") -MSG_DEF(JSMSG_BAD_SUPER, 0, JSEXN_SYNTAXERR, "invalid use of keyword 'super'") -MSG_DEF(JSMSG_BAD_SUPERPROP, 1, JSEXN_SYNTAXERR, "use of super {0} accesses only valid within methods or eval code within methods") -MSG_DEF(JSMSG_BAD_SUPERCALL, 0, JSEXN_SYNTAXERR, "super() is only valid in derived class constructors") -MSG_DEF(JSMSG_BRACKET_AFTER_ARRAY_COMPREHENSION, 0, JSEXN_SYNTAXERR, "missing ] after array comprehension") -MSG_DEF(JSMSG_BRACKET_AFTER_LIST, 0, JSEXN_SYNTAXERR, "missing ] after element list") -MSG_DEF(JSMSG_BRACKET_IN_INDEX, 0, JSEXN_SYNTAXERR, "missing ] in index expression") -MSG_DEF(JSMSG_CATCH_AFTER_GENERAL, 0, JSEXN_SYNTAXERR, "catch after unconditional catch") -MSG_DEF(JSMSG_CATCH_IDENTIFIER, 0, JSEXN_SYNTAXERR, "missing identifier in catch") -MSG_DEF(JSMSG_CATCH_OR_FINALLY, 0, JSEXN_SYNTAXERR, "missing catch or finally after try") -MSG_DEF(JSMSG_CATCH_WITHOUT_TRY, 0, JSEXN_SYNTAXERR, "catch without try") -MSG_DEF(JSMSG_COLON_AFTER_CASE, 0, JSEXN_SYNTAXERR, "missing : after case label") -MSG_DEF(JSMSG_COLON_AFTER_ID, 0, JSEXN_SYNTAXERR, "missing : after property id") -MSG_DEF(JSMSG_COLON_IN_COND, 0, JSEXN_SYNTAXERR, "missing : in conditional expression") -MSG_DEF(JSMSG_COMP_PROP_UNTERM_EXPR, 0, JSEXN_SYNTAXERR, "missing ] in computed property name") -MSG_DEF(JSMSG_CONTRARY_NONDIRECTIVE, 1, JSEXN_SYNTAXERR, "'{0}' statement won't be enforced as a directive because it isn't in directive prologue position") -MSG_DEF(JSMSG_CURLY_AFTER_BODY, 0, JSEXN_SYNTAXERR, "missing } after function body") -MSG_DEF(JSMSG_CURLY_AFTER_CATCH, 0, JSEXN_SYNTAXERR, "missing } after catch block") -MSG_DEF(JSMSG_CURLY_AFTER_FINALLY, 0, JSEXN_SYNTAXERR, "missing } after finally block") -MSG_DEF(JSMSG_CURLY_AFTER_LIST, 0, JSEXN_SYNTAXERR, "missing } after property list") -MSG_DEF(JSMSG_CURLY_AFTER_TRY, 0, JSEXN_SYNTAXERR, "missing } after try block") -MSG_DEF(JSMSG_CURLY_BEFORE_BODY, 0, JSEXN_SYNTAXERR, "missing { before function body") -MSG_DEF(JSMSG_CURLY_BEFORE_CATCH, 0, JSEXN_SYNTAXERR, "missing { before catch block") -MSG_DEF(JSMSG_CURLY_BEFORE_CLASS, 0, JSEXN_SYNTAXERR, "missing { before class body") -MSG_DEF(JSMSG_CURLY_BEFORE_FINALLY, 0, JSEXN_SYNTAXERR, "missing { before finally block") -MSG_DEF(JSMSG_CURLY_BEFORE_SWITCH, 0, JSEXN_SYNTAXERR, "missing { before switch body") -MSG_DEF(JSMSG_CURLY_BEFORE_TRY, 0, JSEXN_SYNTAXERR, "missing { before try block") -MSG_DEF(JSMSG_CURLY_IN_COMPOUND, 0, JSEXN_SYNTAXERR, "missing } in compound statement") -MSG_DEF(JSMSG_DECLARATION_AFTER_EXPORT,0, JSEXN_SYNTAXERR, "missing declaration after 'export' keyword") -MSG_DEF(JSMSG_DECLARATION_AFTER_IMPORT,0, JSEXN_SYNTAXERR, "missing declaration after 'import' keyword") -MSG_DEF(JSMSG_DEPRECATED_DELETE_OPERAND, 0, JSEXN_SYNTAXERR, "applying the 'delete' operator to an unqualified name is deprecated") -MSG_DEF(JSMSG_DEPRECATED_EXPR_CLOSURE, 0, JSEXN_WARN, "expression closures are deprecated") -MSG_DEF(JSMSG_DEPRECATED_FOR_EACH, 0, JSEXN_WARN, "JavaScript 1.6's for-each-in loops are deprecated; consider using ES6 for-of instead") -MSG_DEF(JSMSG_DEPRECATED_OCTAL, 0, JSEXN_SYNTAXERR, "\"0\"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the \"0o\" prefix instead") -MSG_DEF(JSMSG_DEPRECATED_PRAGMA, 1, JSEXN_WARN, "Using //@ to indicate {0} pragmas is deprecated. Use //# instead") -MSG_DEF(JSMSG_DEPRECATED_BLOCK_SCOPE_FUN_REDECL, 1, JSEXN_WARN, "redeclaration of block-scoped function `{0}' is deprecated") -MSG_DEF(JSMSG_DUPLICATE_EXPORT_NAME, 1, JSEXN_SYNTAXERR, "duplicate export name '{0}'") -MSG_DEF(JSMSG_DUPLICATE_FORMAL, 1, JSEXN_SYNTAXERR, "duplicate formal argument {0}") -MSG_DEF(JSMSG_DUPLICATE_LABEL, 0, JSEXN_SYNTAXERR, "duplicate label") -MSG_DEF(JSMSG_DUPLICATE_PROPERTY, 1, JSEXN_SYNTAXERR, "property name {0} appears more than once in object literal") -MSG_DEF(JSMSG_DUPLICATE_PROTO_PROPERTY, 0, JSEXN_SYNTAXERR, "property name __proto__ appears more than once in object literal") -MSG_DEF(JSMSG_EMPTY_CONSEQUENT, 0, JSEXN_SYNTAXERR, "mistyped ; after conditional?") -MSG_DEF(JSMSG_EQUAL_AS_ASSIGN, 0, JSEXN_SYNTAXERR, "test for equality (==) mistyped as assignment (=)?") -MSG_DEF(JSMSG_EXPORT_DECL_AT_TOP_LEVEL,0, JSEXN_SYNTAXERR, "export declarations may only appear at top level of a module") -MSG_DEF(JSMSG_FINALLY_WITHOUT_TRY, 0, JSEXN_SYNTAXERR, "finally without try") -MSG_DEF(JSMSG_FORBIDDEN_AS_STATEMENT, 1, JSEXN_SYNTAXERR, "{0} can't appear in single-statement context") -MSG_DEF(JSMSG_FROM_AFTER_IMPORT_CLAUSE, 0, JSEXN_SYNTAXERR, "missing keyword 'from' after import clause") -MSG_DEF(JSMSG_FROM_AFTER_EXPORT_STAR, 0, JSEXN_SYNTAXERR, "missing keyword 'from' after export *") -MSG_DEF(JSMSG_GARBAGE_AFTER_INPUT, 2, JSEXN_SYNTAXERR, "unexpected garbage after {0}, starting with {1}") -MSG_DEF(JSMSG_IDSTART_AFTER_NUMBER, 0, JSEXN_SYNTAXERR, "identifier starts immediately after numeric literal") -MSG_DEF(JSMSG_ILLEGAL_CHARACTER, 0, JSEXN_SYNTAXERR, "illegal character") -MSG_DEF(JSMSG_IMPORT_DECL_AT_TOP_LEVEL, 0, JSEXN_SYNTAXERR, "import declarations may only appear at top level of a module") -MSG_DEF(JSMSG_INVALID_FOR_IN_DECL_WITH_INIT,0,JSEXN_SYNTAXERR,"for-in loop head declarations may not have initializers") -MSG_DEF(JSMSG_LABEL_NOT_FOUND, 0, JSEXN_SYNTAXERR, "label not found") -MSG_DEF(JSMSG_LET_COMP_BINDING, 0, JSEXN_SYNTAXERR, "'let' is not a valid name for a comprehension variable") -MSG_DEF(JSMSG_LEXICAL_DECL_NOT_IN_BLOCK, 1, JSEXN_SYNTAXERR, "{0} declaration not directly within block") -MSG_DEF(JSMSG_LEXICAL_DECL_LABEL, 1, JSEXN_SYNTAXERR, "{0} declarations cannot be labelled") -MSG_DEF(JSMSG_GENERATOR_LABEL, 0, JSEXN_SYNTAXERR, "generator functions cannot be labelled") -MSG_DEF(JSMSG_FUNCTION_LABEL, 0, JSEXN_SYNTAXERR, "functions cannot be labelled") -MSG_DEF(JSMSG_SLOPPY_FUNCTION_LABEL, 0, JSEXN_SYNTAXERR, "functions can only be labelled inside blocks") -MSG_DEF(JSMSG_LINE_BREAK_AFTER_THROW, 0, JSEXN_SYNTAXERR, "no line break is allowed between 'throw' and its expression") -MSG_DEF(JSMSG_LINE_BREAK_BEFORE_ARROW, 0, JSEXN_SYNTAXERR, "no line break is allowed before '=>'") -MSG_DEF(JSMSG_MALFORMED_ESCAPE, 1, JSEXN_SYNTAXERR, "malformed {0} character escape sequence") -MSG_DEF(JSMSG_MISSING_BINARY_DIGITS, 0, JSEXN_SYNTAXERR, "missing binary digits after '0b'") -MSG_DEF(JSMSG_MISSING_EXPONENT, 0, JSEXN_SYNTAXERR, "missing exponent") -MSG_DEF(JSMSG_MISSING_EXPR_AFTER_THROW,0, JSEXN_SYNTAXERR, "throw statement is missing an expression") -MSG_DEF(JSMSG_MISSING_FORMAL, 0, JSEXN_SYNTAXERR, "missing formal parameter") -MSG_DEF(JSMSG_MISSING_HEXDIGITS, 0, JSEXN_SYNTAXERR, "missing hexadecimal digits after '0x'") -MSG_DEF(JSMSG_MISSING_OCTAL_DIGITS, 0, JSEXN_SYNTAXERR, "missing octal digits after '0o'") -MSG_DEF(JSMSG_MODULE_SPEC_AFTER_FROM, 0, JSEXN_SYNTAXERR, "missing module specifier after 'from' keyword") -MSG_DEF(JSMSG_NAME_AFTER_DOT, 0, JSEXN_SYNTAXERR, "missing name after . operator") -MSG_DEF(JSMSG_NAMED_IMPORTS_OR_NAMESPACE_IMPORT, 0, JSEXN_SYNTAXERR, "expected named imports or namespace import after comma") -MSG_DEF(JSMSG_NO_BINDING_NAME, 0, JSEXN_SYNTAXERR, "missing binding name") -MSG_DEF(JSMSG_NO_EXPORT_NAME, 0, JSEXN_SYNTAXERR, "missing export name") -MSG_DEF(JSMSG_NO_IMPORT_NAME, 0, JSEXN_SYNTAXERR, "missing import name") -MSG_DEF(JSMSG_NO_VARIABLE_NAME, 0, JSEXN_SYNTAXERR, "missing variable name") -MSG_DEF(JSMSG_OF_AFTER_FOR_NAME, 0, JSEXN_SYNTAXERR, "missing 'of' after for") -MSG_DEF(JSMSG_PAREN_AFTER_ARGS, 0, JSEXN_SYNTAXERR, "missing ) after argument list") -MSG_DEF(JSMSG_PAREN_AFTER_CATCH, 0, JSEXN_SYNTAXERR, "missing ) after catch") -MSG_DEF(JSMSG_PAREN_AFTER_COND, 0, JSEXN_SYNTAXERR, "missing ) after condition") -MSG_DEF(JSMSG_PAREN_AFTER_FOR, 0, JSEXN_SYNTAXERR, "missing ( after for") -MSG_DEF(JSMSG_PAREN_AFTER_FORMAL, 0, JSEXN_SYNTAXERR, "missing ) after formal parameters") -MSG_DEF(JSMSG_PAREN_AFTER_FOR_CTRL, 0, JSEXN_SYNTAXERR, "missing ) after for-loop control") -MSG_DEF(JSMSG_PAREN_AFTER_FOR_OF_ITERABLE, 0, JSEXN_SYNTAXERR, "missing ) after for-of iterable") -MSG_DEF(JSMSG_PAREN_AFTER_SWITCH, 0, JSEXN_SYNTAXERR, "missing ) after switch expression") -MSG_DEF(JSMSG_PAREN_AFTER_WITH, 0, JSEXN_SYNTAXERR, "missing ) after with-statement object") -MSG_DEF(JSMSG_PAREN_BEFORE_CATCH, 0, JSEXN_SYNTAXERR, "missing ( before catch") -MSG_DEF(JSMSG_PAREN_BEFORE_COND, 0, JSEXN_SYNTAXERR, "missing ( before condition") -MSG_DEF(JSMSG_PAREN_BEFORE_FORMAL, 0, JSEXN_SYNTAXERR, "missing ( before formal parameters") -MSG_DEF(JSMSG_PAREN_BEFORE_SWITCH, 0, JSEXN_SYNTAXERR, "missing ( before switch expression") -MSG_DEF(JSMSG_PAREN_BEFORE_WITH, 0, JSEXN_SYNTAXERR, "missing ( before with-statement object") -MSG_DEF(JSMSG_PAREN_IN_PAREN, 0, JSEXN_SYNTAXERR, "missing ) in parenthetical") -MSG_DEF(JSMSG_RC_AFTER_EXPORT_SPEC_LIST, 0, JSEXN_SYNTAXERR, "missing '}' after export specifier list") -MSG_DEF(JSMSG_RC_AFTER_IMPORT_SPEC_LIST, 0, JSEXN_SYNTAXERR, "missing '}' after module specifier list") -MSG_DEF(JSMSG_REDECLARED_CATCH_IDENTIFIER, 1, JSEXN_SYNTAXERR, "redeclaration of identifier '{0}' in catch") -MSG_DEF(JSMSG_RESERVED_ID, 1, JSEXN_SYNTAXERR, "{0} is a reserved identifier") -MSG_DEF(JSMSG_REST_WITH_COMMA, 0, JSEXN_SYNTAXERR, "rest element may not have a trailing comma") -MSG_DEF(JSMSG_REST_WITH_DEFAULT, 0, JSEXN_SYNTAXERR, "rest parameter may not have a default") -MSG_DEF(JSMSG_SELFHOSTED_TOP_LEVEL_LEXICAL, 1, JSEXN_SYNTAXERR, "self-hosted code cannot contain top-level {0} declarations") -MSG_DEF(JSMSG_SELFHOSTED_METHOD_CALL, 0, JSEXN_SYNTAXERR, "self-hosted code may not contain direct method calls. Use callFunction() or callContentFunction()") -MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") -MSG_DEF(JSMSG_SEMI_AFTER_FOR_COND, 0, JSEXN_SYNTAXERR, "missing ; after for-loop condition") -MSG_DEF(JSMSG_SEMI_AFTER_FOR_INIT, 0, JSEXN_SYNTAXERR, "missing ; after for-loop initializer") -MSG_DEF(JSMSG_SEMI_BEFORE_STMNT, 0, JSEXN_SYNTAXERR, "missing ; before statement") -MSG_DEF(JSMSG_SOURCE_TOO_LONG, 0, JSEXN_RANGEERR, "source is too long") -MSG_DEF(JSMSG_STMT_AFTER_RETURN, 0, JSEXN_WARN, "unreachable code after return statement") -MSG_DEF(JSMSG_STRICT_CODE_WITH, 0, JSEXN_SYNTAXERR, "strict mode code may not contain 'with' statements") -MSG_DEF(JSMSG_STRICT_NON_SIMPLE_PARAMS, 1, JSEXN_SYNTAXERR, "\"use strict\" not allowed in function with {0} parameter") -MSG_DEF(JSMSG_TEMPLSTR_UNTERM_EXPR, 0, JSEXN_SYNTAXERR, "missing } in template string") -MSG_DEF(JSMSG_SIMD_NOT_A_VECTOR, 2, JSEXN_TYPEERR, "expecting a SIMD {0} object as argument {1}") -MSG_DEF(JSMSG_TOO_MANY_CASES, 0, JSEXN_INTERNALERR, "too many switch cases") -MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 0, JSEXN_SYNTAXERR, "too many catch variables") -MSG_DEF(JSMSG_TOO_MANY_CON_ARGS, 0, JSEXN_SYNTAXERR, "too many constructor arguments") -MSG_DEF(JSMSG_TOO_MANY_DEFAULTS, 0, JSEXN_SYNTAXERR, "more than one switch default") -MSG_DEF(JSMSG_TOO_MANY_FUN_ARGS, 0, JSEXN_SYNTAXERR, "too many function arguments") -MSG_DEF(JSMSG_TOO_MANY_LOCALS, 0, JSEXN_SYNTAXERR, "too many local variables") -MSG_DEF(JSMSG_TOO_MANY_YIELDS, 0, JSEXN_SYNTAXERR, "too many yield expressions") -MSG_DEF(JSMSG_TOUGH_BREAK, 0, JSEXN_SYNTAXERR, "unlabeled break must be inside loop or switch") -MSG_DEF(JSMSG_UNEXPECTED_TOKEN, 2, JSEXN_SYNTAXERR, "expected {0}, got {1}") -MSG_DEF(JSMSG_UNNAMED_CLASS_STMT, 0, JSEXN_SYNTAXERR, "class statement requires a name") -MSG_DEF(JSMSG_UNNAMED_FUNCTION_STMT, 0, JSEXN_SYNTAXERR, "function statement requires a name") -MSG_DEF(JSMSG_UNTERMINATED_COMMENT, 0, JSEXN_SYNTAXERR, "unterminated comment") -MSG_DEF(JSMSG_UNTERMINATED_REGEXP, 0, JSEXN_SYNTAXERR, "unterminated regular expression literal") -MSG_DEF(JSMSG_UNTERMINATED_STRING, 0, JSEXN_SYNTAXERR, "unterminated string literal") -MSG_DEF(JSMSG_USELESS_EXPR, 0, JSEXN_TYPEERR, "useless expression") -MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 0, JSEXN_SYNTAXERR, "\"use asm\" is only meaningful in the Directive Prologue of a function body") -MSG_DEF(JSMSG_VAR_HIDES_ARG, 1, JSEXN_TYPEERR, "variable {0} redeclares argument") -MSG_DEF(JSMSG_WHILE_AFTER_DO, 0, JSEXN_SYNTAXERR, "missing while after do-loop body") -MSG_DEF(JSMSG_YIELD_IN_ARROW, 0, JSEXN_SYNTAXERR, "arrow function may not contain yield") -MSG_DEF(JSMSG_YIELD_IN_DEFAULT, 0, JSEXN_SYNTAXERR, "yield in default expression") -MSG_DEF(JSMSG_YIELD_IN_METHOD, 0, JSEXN_SYNTAXERR, "non-generator method definitions may not contain yield") -MSG_DEF(JSMSG_BAD_COLUMN_NUMBER, 0, JSEXN_RANGEERR, "column number out of range") -MSG_DEF(JSMSG_COMPUTED_NAME_IN_PATTERN,0, JSEXN_SYNTAXERR, "computed property names aren't supported in this destructuring declaration") -MSG_DEF(JSMSG_DEFAULT_IN_PATTERN, 0, JSEXN_SYNTAXERR, "destructuring defaults aren't supported in this destructuring declaration") -MSG_DEF(JSMSG_BAD_NEWTARGET, 0, JSEXN_SYNTAXERR, "new.target only allowed within functions") -MSG_DEF(JSMSG_ESCAPED_KEYWORD, 0, JSEXN_SYNTAXERR, "keywords must be written literally, without embedded escapes") - -// asm.js -MSG_DEF(JSMSG_USE_ASM_TYPE_FAIL, 1, JSEXN_TYPEERR, "asm.js type error: {0}") -MSG_DEF(JSMSG_USE_ASM_LINK_FAIL, 1, JSEXN_TYPEERR, "asm.js link error: {0}") -MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 1, JSEXN_WARN, "Successfully compiled asm.js code ({0})") - -// wasm -MSG_DEF(JSMSG_WASM_COMPILE_ERROR, 1, JSEXN_WASMCOMPILEERROR, "{0}") -MSG_DEF(JSMSG_WASM_IND_CALL_TO_NULL, 0, JSEXN_WASMRUNTIMEERROR, "indirect call to null") -MSG_DEF(JSMSG_WASM_IND_CALL_BAD_SIG, 0, JSEXN_WASMRUNTIMEERROR, "indirect call signature mismatch") -MSG_DEF(JSMSG_WASM_UNREACHABLE, 0, JSEXN_WASMRUNTIMEERROR, "unreachable executed") -MSG_DEF(JSMSG_WASM_INTEGER_OVERFLOW, 0, JSEXN_WASMRUNTIMEERROR, "integer overflow") -MSG_DEF(JSMSG_WASM_INVALID_CONVERSION, 0, JSEXN_WASMRUNTIMEERROR, "invalid conversion to integer") -MSG_DEF(JSMSG_WASM_INT_DIVIDE_BY_ZERO, 0, JSEXN_WASMRUNTIMEERROR, "integer divide by zero") -MSG_DEF(JSMSG_WASM_OUT_OF_BOUNDS, 0, JSEXN_WASMRUNTIMEERROR, "index out of bounds") -MSG_DEF(JSMSG_WASM_UNALIGNED_ACCESS, 0, JSEXN_WASMRUNTIMEERROR, "unaligned memory access") -MSG_DEF(JSMSG_WASM_BAD_UINT32, 2, JSEXN_RANGEERR, "bad {0} {1}") -MSG_DEF(JSMSG_WASM_BAD_GROW, 1, JSEXN_RANGEERR, "failed to grow {0}") -MSG_DEF(JSMSG_WASM_BAD_FIT, 2, JSEXN_RANGEERR, "{0} segment does not fit in {1}") -MSG_DEF(JSMSG_WASM_BAD_BUF_ARG, 0, JSEXN_TYPEERR, "first argument must be an ArrayBuffer or typed array object") -MSG_DEF(JSMSG_WASM_BAD_MOD_ARG, 0, JSEXN_TYPEERR, "first argument must be a WebAssembly.Module") -MSG_DEF(JSMSG_WASM_BAD_BUF_MOD_ARG, 0, JSEXN_TYPEERR, "first argument must be a WebAssembly.Module, ArrayBuffer or typed array object") -MSG_DEF(JSMSG_WASM_BAD_DESC_ARG, 1, JSEXN_TYPEERR, "first argument must be a {0} descriptor") -MSG_DEF(JSMSG_WASM_BAD_IMP_SIZE, 1, JSEXN_TYPEERR, "imported {0} with incompatible size") -MSG_DEF(JSMSG_WASM_BAD_IMP_MAX, 1, JSEXN_TYPEERR, "imported {0} with incompatible maximum size") -MSG_DEF(JSMSG_WASM_BAD_ELEMENT, 0, JSEXN_TYPEERR, "\"element\" property of table descriptor must be \"anyfunc\"") -MSG_DEF(JSMSG_WASM_BAD_IMPORT_ARG, 0, JSEXN_TYPEERR, "second argument must be an object") -MSG_DEF(JSMSG_WASM_BAD_IMPORT_FIELD, 2, JSEXN_TYPEERR, "import object field '{0}' is not {1}") -MSG_DEF(JSMSG_WASM_BAD_IMPORT_SIG, 0, JSEXN_TYPEERR, "imported function signature mismatch") -MSG_DEF(JSMSG_WASM_BAD_TABLE_VALUE, 0, JSEXN_TYPEERR, "can only assign WebAssembly exported functions to Table") -MSG_DEF(JSMSG_WASM_BAD_I64, 0, JSEXN_TYPEERR, "cannot pass i64 to or from JS") -MSG_DEF(JSMSG_WASM_NO_TRANSFER, 0, JSEXN_TYPEERR, "cannot transfer WebAssembly/asm.js ArrayBuffer") -MSG_DEF(JSMSG_WASM_TEXT_FAIL, 1, JSEXN_SYNTAXERR, "wasm text error: {0}") - -// Proxy -MSG_DEF(JSMSG_BAD_TRAP_RETURN_VALUE, 2, JSEXN_TYPEERR,"trap {1} for {0} returned a primitive value") -MSG_DEF(JSMSG_BAD_GETPROTOTYPEOF_TRAP_RETURN,0,JSEXN_TYPEERR,"proxy getPrototypeOf handler returned a non-object, non-null value") -MSG_DEF(JSMSG_INCONSISTENT_GETPROTOTYPEOF_TRAP,0,JSEXN_TYPEERR,"proxy getPrototypeOf handler didn't return the target object's prototype") -MSG_DEF(JSMSG_PROXY_SETPROTOTYPEOF_RETURNED_FALSE, 0, JSEXN_TYPEERR, "proxy setPrototypeOf handler returned false") -MSG_DEF(JSMSG_PROXY_ISEXTENSIBLE_RETURNED_FALSE,0,JSEXN_TYPEERR,"proxy isExtensible handler must return the same extensibility as target") -MSG_DEF(JSMSG_INCONSISTENT_SETPROTOTYPEOF_TRAP,0,JSEXN_TYPEERR,"proxy setPrototypeOf handler returned true, even though the target's prototype is immutable because the target is non-extensible") -MSG_DEF(JSMSG_CANT_CHANGE_EXTENSIBILITY, 0, JSEXN_TYPEERR, "can't change object's extensibility") -MSG_DEF(JSMSG_CANT_DEFINE_INVALID, 0, JSEXN_TYPEERR, "proxy can't define an incompatible property descriptor") -MSG_DEF(JSMSG_CANT_DEFINE_NEW, 0, JSEXN_TYPEERR, "proxy can't define a new property on a non-extensible object") -MSG_DEF(JSMSG_CANT_DEFINE_NE_AS_NC, 0, JSEXN_TYPEERR, "proxy can't define a non-existent property as non-configurable") -MSG_DEF(JSMSG_PROXY_DEFINE_RETURNED_FALSE, 1, JSEXN_TYPEERR, "proxy defineProperty handler returned false for property '{0}'") -MSG_DEF(JSMSG_PROXY_DELETE_RETURNED_FALSE, 1, JSEXN_TYPEERR, "can't delete property '{0}': proxy deleteProperty handler returned false") -MSG_DEF(JSMSG_PROXY_PREVENTEXTENSIONS_RETURNED_FALSE, 0, JSEXN_TYPEERR, "proxy preventExtensions handler returned false") -MSG_DEF(JSMSG_PROXY_SET_RETURNED_FALSE, 1, JSEXN_TYPEERR, "proxy set handler returned false for property '{0}'") -MSG_DEF(JSMSG_CANT_REPORT_AS_NON_EXTENSIBLE, 0, JSEXN_TYPEERR, "proxy can't report an extensible object as non-extensible") -MSG_DEF(JSMSG_CANT_REPORT_C_AS_NC, 0, JSEXN_TYPEERR, "proxy can't report existing configurable property as non-configurable") -MSG_DEF(JSMSG_CANT_REPORT_E_AS_NE, 0, JSEXN_TYPEERR, "proxy can't report an existing own property as non-existent on a non-extensible object") -MSG_DEF(JSMSG_CANT_REPORT_INVALID, 0, JSEXN_TYPEERR, "proxy can't report an incompatible property descriptor") -MSG_DEF(JSMSG_CANT_REPORT_NC_AS_NE, 0, JSEXN_TYPEERR, "proxy can't report a non-configurable own property as non-existent") -MSG_DEF(JSMSG_CANT_REPORT_NEW, 0, JSEXN_TYPEERR, "proxy can't report a new property on a non-extensible object") -MSG_DEF(JSMSG_CANT_REPORT_NE_AS_NC, 0, JSEXN_TYPEERR, "proxy can't report a non-existent property as non-configurable") -MSG_DEF(JSMSG_CANT_SET_NW_NC, 0, JSEXN_TYPEERR, "proxy can't successfully set a non-writable, non-configurable property") -MSG_DEF(JSMSG_CANT_SET_WO_SETTER, 0, JSEXN_TYPEERR, "proxy can't succesfully set an accessor property without a setter") -MSG_DEF(JSMSG_CANT_SKIP_NC, 0, JSEXN_TYPEERR, "proxy can't skip a non-configurable property") -MSG_DEF(JSMSG_ONWKEYS_STR_SYM, 0, JSEXN_TYPEERR, "proxy [[OwnPropertyKeys]] must return an array with only string and symbol elements") -MSG_DEF(JSMSG_MUST_REPORT_SAME_VALUE, 0, JSEXN_TYPEERR, "proxy must report the same value for a non-writable, non-configurable property") -MSG_DEF(JSMSG_MUST_REPORT_UNDEFINED, 0, JSEXN_TYPEERR, "proxy must report undefined for a non-configurable accessor property without a getter") -MSG_DEF(JSMSG_OBJECT_ACCESS_DENIED, 0, JSEXN_ERR, "Permission denied to access object") -MSG_DEF(JSMSG_PROPERTY_ACCESS_DENIED, 1, JSEXN_ERR, "Permission denied to access property {0}") -MSG_DEF(JSMSG_PROXY_CONSTRUCT_OBJECT, 0, JSEXN_TYPEERR, "proxy [[Construct]] must return an object") -MSG_DEF(JSMSG_PROXY_EXTENSIBILITY, 0, JSEXN_TYPEERR, "proxy must report same extensiblitity as target") -MSG_DEF(JSMSG_PROXY_GETOWN_OBJORUNDEF, 0, JSEXN_TYPEERR, "proxy [[GetOwnProperty]] must return an object or undefined") -MSG_DEF(JSMSG_PROXY_REVOKED, 0, JSEXN_TYPEERR, "illegal operation attempted on a revoked proxy") -MSG_DEF(JSMSG_PROXY_ARG_REVOKED, 1, JSEXN_TYPEERR, "argument {0} cannot be a revoked proxy") -MSG_DEF(JSMSG_BAD_TRAP, 1, JSEXN_TYPEERR, "proxy handler's {0} trap wasn't undefined, null, or callable") - -// Structured cloning -MSG_DEF(JSMSG_SC_BAD_CLONE_VERSION, 0, JSEXN_ERR, "unsupported structured clone version") -MSG_DEF(JSMSG_SC_BAD_SERIALIZED_DATA, 1, JSEXN_INTERNALERR, "bad serialized structured data ({0})") -MSG_DEF(JSMSG_SC_DUP_TRANSFERABLE, 0, JSEXN_TYPEERR, "duplicate transferable for structured clone") -MSG_DEF(JSMSG_SC_NOT_TRANSFERABLE, 0, JSEXN_TYPEERR, "invalid transferable array for structured clone") -MSG_DEF(JSMSG_SC_UNSUPPORTED_TYPE, 0, JSEXN_TYPEERR, "unsupported type for structured data") -MSG_DEF(JSMSG_SC_NOT_CLONABLE, 1, JSEXN_TYPEERR, "{0} cannot be cloned in this context") -MSG_DEF(JSMSG_SC_SAB_TRANSFER, 0, JSEXN_WARN, "SharedArrayBuffer must not be in the transfer list") -MSG_DEF(JSMSG_SC_SAB_DISABLED, 0, JSEXN_TYPEERR, "SharedArrayBuffer not cloned - shared memory disabled in receiver") - -// Debugger -MSG_DEF(JSMSG_ASSIGN_FUNCTION_OR_NULL, 1, JSEXN_TYPEERR, "value assigned to {0} must be a function or null") -MSG_DEF(JSMSG_DEBUG_BAD_AWAIT, 0, JSEXN_TYPEERR, "await expression received invalid value") -MSG_DEF(JSMSG_DEBUG_BAD_LINE, 0, JSEXN_TYPEERR, "invalid line number") -MSG_DEF(JSMSG_DEBUG_BAD_OFFSET, 0, JSEXN_TYPEERR, "invalid script offset") -MSG_DEF(JSMSG_DEBUG_BAD_REFERENT, 2, JSEXN_TYPEERR, "{0} does not refer to {1}") -MSG_DEF(JSMSG_DEBUG_BAD_RESUMPTION, 0, JSEXN_TYPEERR, "debugger resumption value must be undefined, {throw: val}, {return: val}, or null") -MSG_DEF(JSMSG_DEBUG_BAD_YIELD, 0, JSEXN_TYPEERR, "generator yielded invalid value") -MSG_DEF(JSMSG_DEBUG_CANT_DEBUG_GLOBAL, 0, JSEXN_TYPEERR, "passing non-debuggable global to addDebuggee") -MSG_DEF(JSMSG_DEBUG_CCW_REQUIRED, 1, JSEXN_TYPEERR, "{0}: argument must be an object from a different compartment") -MSG_DEF(JSMSG_DEBUG_COMPARTMENT_MISMATCH, 2, JSEXN_TYPEERR, "{0}: descriptor .{1} property is an object in a different compartment than the target object") -MSG_DEF(JSMSG_DEBUG_LOOP, 0, JSEXN_TYPEERR, "cannot debug an object in same compartment as debugger or a compartment that is already debugging the debugger") -MSG_DEF(JSMSG_DEBUG_NOT_DEBUGGEE, 2, JSEXN_ERR, "{0} is not a debuggee {1}") -MSG_DEF(JSMSG_DEBUG_NOT_DEBUGGING, 0, JSEXN_ERR, "can't set breakpoint: script global is not a debuggee") -MSG_DEF(JSMSG_DEBUG_NOT_IDLE, 0, JSEXN_ERR, "can't start debugging: a debuggee script is on the stack") -MSG_DEF(JSMSG_DEBUG_NOT_LIVE, 1, JSEXN_ERR, "{0} is not live") -MSG_DEF(JSMSG_DEBUG_NO_ENV_OBJECT, 0, JSEXN_TYPEERR, "declarative Environments don't have binding objects") -MSG_DEF(JSMSG_DEBUG_PROTO, 2, JSEXN_TYPEERR, "{0}.prototype is not a valid {1} instance") -MSG_DEF(JSMSG_DEBUG_WRONG_OWNER, 1, JSEXN_TYPEERR, "{0} belongs to a different Debugger") -MSG_DEF(JSMSG_DEBUG_OPTIMIZED_OUT, 1, JSEXN_ERR, "variable `{0}' has been optimized out") -MSG_DEF(JSMSG_DEBUG_RESUMPTION_VALUE_DISALLOWED, 0, JSEXN_TYPEERR, "resumption values are disallowed in this hook") -MSG_DEF(JSMSG_DEBUG_VARIABLE_NOT_FOUND,0, JSEXN_TYPEERR, "variable not found in environment") -MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 3, JSEXN_TYPEERR, "{0} is {1}{2}a global object, but a direct reference is required") -MSG_DEF(JSMSG_DEBUGGEE_WOULD_RUN, 2, JSEXN_DEBUGGEEWOULDRUN, "debuggee `{0}:{1}' would run") -MSG_DEF(JSMSG_NOT_CALLABLE_OR_UNDEFINED, 0, JSEXN_TYPEERR, "value is not a function or undefined") -MSG_DEF(JSMSG_NOT_TRACKING_ALLOCATIONS, 1, JSEXN_ERR, "Cannot call {0} without setting trackingAllocationSites to true") -MSG_DEF(JSMSG_OBJECT_METADATA_CALLBACK_ALREADY_SET, 0, JSEXN_ERR, "Cannot track object allocation, because other tools are already doing so") -MSG_DEF(JSMSG_QUERY_INNERMOST_WITHOUT_LINE_URL, 0, JSEXN_TYPEERR, "findScripts query object with 'innermost' property must have 'line' and either 'displayURL', 'url', or 'source'") -MSG_DEF(JSMSG_QUERY_LINE_WITHOUT_URL, 0, JSEXN_TYPEERR, "findScripts query object has 'line' property, but no 'displayURL', 'url', or 'source' property") -MSG_DEF(JSMSG_DEBUG_CANT_SET_OPT_ENV, 1, JSEXN_REFERENCEERR, "can't set `{0}' in an optimized-out environment") -MSG_DEF(JSMSG_DEBUG_INVISIBLE_COMPARTMENT, 0, JSEXN_TYPEERR, "object in compartment marked as invisible to Debugger") -MSG_DEF(JSMSG_DEBUG_CENSUS_BREAKDOWN, 1, JSEXN_TYPEERR, "unrecognized 'by' value in takeCensus breakdown: {0}") -MSG_DEF(JSMSG_DEBUG_PROMISE_NOT_RESOLVED, 0, JSEXN_TYPEERR, "Promise hasn't been resolved") -MSG_DEF(JSMSG_DEBUG_PROMISE_NOT_FULFILLED, 0, JSEXN_TYPEERR, "Promise hasn't been fulfilled") -MSG_DEF(JSMSG_DEBUG_PROMISE_NOT_REJECTED, 0, JSEXN_TYPEERR, "Promise hasn't been rejected") - -// Tracelogger -MSG_DEF(JSMSG_TRACELOGGER_ENABLE_FAIL, 1, JSEXN_ERR, "enabling tracelogger failed: {0}") - -// Intl -MSG_DEF(JSMSG_DATE_NOT_FINITE, 0, JSEXN_RANGEERR, "date value is not finite in DateTimeFormat.format()") -MSG_DEF(JSMSG_INTERNAL_INTL_ERROR, 0, JSEXN_ERR, "internal error while computing Intl data") -MSG_DEF(JSMSG_INTL_OBJECT_NOT_INITED, 3, JSEXN_TYPEERR, "Intl.{0}.prototype.{1} called on value that's not an object initialized as a {2}") -MSG_DEF(JSMSG_INTL_OBJECT_REINITED, 0, JSEXN_TYPEERR, "can't initialize object twice as an object of an Intl constructor") -MSG_DEF(JSMSG_INVALID_CURRENCY_CODE, 1, JSEXN_RANGEERR, "invalid currency code in NumberFormat(): {0}") -MSG_DEF(JSMSG_INVALID_DIGITS_VALUE, 1, JSEXN_RANGEERR, "invalid digits value: {0}") -MSG_DEF(JSMSG_INVALID_LANGUAGE_TAG, 1, JSEXN_RANGEERR, "invalid language tag: {0}") -MSG_DEF(JSMSG_INVALID_LOCALES_ELEMENT, 0, JSEXN_TYPEERR, "invalid element in locales argument") -MSG_DEF(JSMSG_INVALID_LOCALE_MATCHER, 1, JSEXN_RANGEERR, "invalid locale matcher in supportedLocalesOf(): {0}") -MSG_DEF(JSMSG_INVALID_OPTION_VALUE, 2, JSEXN_RANGEERR, "invalid value {1} for option {0}") -MSG_DEF(JSMSG_INVALID_TIME_ZONE, 1, JSEXN_RANGEERR, "invalid time zone in DateTimeFormat(): {0}") -MSG_DEF(JSMSG_UNDEFINED_CURRENCY, 0, JSEXN_TYPEERR, "undefined currency in NumberFormat() with currency style") - -// RegExp -MSG_DEF(JSMSG_BACK_REF_OUT_OF_RANGE, 0, JSEXN_SYNTAXERR, "back reference out of range in regular expression") -MSG_DEF(JSMSG_BAD_CLASS_RANGE, 0, JSEXN_SYNTAXERR, "invalid range in character class") -MSG_DEF(JSMSG_ESCAPE_AT_END_OF_REGEXP, 0, JSEXN_SYNTAXERR, "\\ at end of pattern") -MSG_DEF(JSMSG_EXEC_NOT_OBJORNULL, 0, JSEXN_TYPEERR, "RegExp exec method should return object or null") -MSG_DEF(JSMSG_INVALID_DECIMAL_ESCAPE, 0, JSEXN_SYNTAXERR, "invalid decimal escape in regular expression") -MSG_DEF(JSMSG_INVALID_GROUP, 0, JSEXN_SYNTAXERR, "invalid regexp group") -MSG_DEF(JSMSG_INVALID_IDENTITY_ESCAPE, 0, JSEXN_SYNTAXERR, "invalid identity escape in regular expression") -MSG_DEF(JSMSG_INVALID_UNICODE_ESCAPE, 0, JSEXN_SYNTAXERR, "invalid unicode escape in regular expression") -MSG_DEF(JSMSG_MISSING_PAREN, 0, JSEXN_SYNTAXERR, "unterminated parenthetical") -MSG_DEF(JSMSG_NEWREGEXP_FLAGGED, 0, JSEXN_TYPEERR, "can't supply flags when constructing one RegExp from another") -MSG_DEF(JSMSG_NOTHING_TO_REPEAT, 0, JSEXN_SYNTAXERR, "nothing to repeat") -MSG_DEF(JSMSG_NUMBERS_OUT_OF_ORDER, 0, JSEXN_SYNTAXERR, "numbers out of order in {} quantifier.") -MSG_DEF(JSMSG_RANGE_WITH_CLASS_ESCAPE, 0, JSEXN_SYNTAXERR, "character class escape cannot be used in class range in regular expression") -MSG_DEF(JSMSG_RAW_BRACE_IN_REGEP, 0, JSEXN_SYNTAXERR, "raw brace is not allowed in regular expression with unicode flag") -MSG_DEF(JSMSG_RAW_BRACKET_IN_REGEP, 0, JSEXN_SYNTAXERR, "raw bracket is not allowed in regular expression with unicode flag") -MSG_DEF(JSMSG_TOO_MANY_PARENS, 0, JSEXN_INTERNALERR, "too many parentheses in regular expression") -MSG_DEF(JSMSG_UNICODE_OVERFLOW, 0, JSEXN_SYNTAXERR, "unicode codepoint should not be greater than 0x10FFFF in regular expression") -MSG_DEF(JSMSG_UNMATCHED_RIGHT_PAREN, 0, JSEXN_SYNTAXERR, "unmatched ) in regular expression") -MSG_DEF(JSMSG_UNTERM_CLASS, 0, JSEXN_SYNTAXERR, "unterminated character class") - -// Self-hosting -MSG_DEF(JSMSG_DEFAULT_LOCALE_ERROR, 0, JSEXN_ERR, "internal error getting the default locale") -MSG_DEF(JSMSG_NO_SUCH_SELF_HOSTED_PROP,1, JSEXN_ERR, "No such property on self-hosted object: {0}") - -// Typed object / SIMD -MSG_DEF(JSMSG_INVALID_PROTOTYPE, 0, JSEXN_TYPEERR, "prototype field is not an object") -MSG_DEF(JSMSG_TYPEDOBJECT_BAD_ARGS, 0, JSEXN_TYPEERR, "invalid arguments") -MSG_DEF(JSMSG_TYPEDOBJECT_BINARYARRAY_BAD_INDEX, 0, JSEXN_RANGEERR, "invalid or out-of-range index") -MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_UNATTACHED, 0, JSEXN_TYPEERR, "handle unattached") -MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_ARGS, 0, JSEXN_RANGEERR, "invalid field descriptor") -MSG_DEF(JSMSG_TYPEDOBJECT_TOO_BIG, 0, JSEXN_ERR, "Type is too large to allocate") -MSG_DEF(JSMSG_SIMD_FAILED_CONVERSION, 0, JSEXN_RANGEERR, "SIMD conversion loses precision") -MSG_DEF(JSMSG_SIMD_TO_NUMBER, 0, JSEXN_TYPEERR, "can't convert SIMD value to number") - -// Array -MSG_DEF(JSMSG_TOO_LONG_ARRAY, 0, JSEXN_TYPEERR, "Too long array") - -// Typed array -MSG_DEF(JSMSG_BAD_INDEX, 0, JSEXN_RANGEERR, "invalid or out-of-range index") -MSG_DEF(JSMSG_NON_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected ArrayBuffer, but species constructor returned non-ArrayBuffer") -MSG_DEF(JSMSG_SAME_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected different ArrayBuffer, but species constructor returned same ArrayBuffer") -MSG_DEF(JSMSG_SHORT_ARRAY_BUFFER_RETURNED, 2, JSEXN_TYPEERR, "expected ArrayBuffer with at least {0} bytes, but species constructor returns ArrayBuffer with {1} bytes") -MSG_DEF(JSMSG_TYPED_ARRAY_BAD_ARGS, 0, JSEXN_TYPEERR, "invalid arguments") -MSG_DEF(JSMSG_TYPED_ARRAY_NEGATIVE_ARG,1, JSEXN_RANGEERR, "argument {0} must be >= 0") -MSG_DEF(JSMSG_TYPED_ARRAY_DETACHED, 0, JSEXN_TYPEERR, "attempting to access detached ArrayBuffer") -MSG_DEF(JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS, 0, JSEXN_RANGEERR, "attempting to construct out-of-bounds TypedArray on ArrayBuffer") -MSG_DEF(JSMSG_TYPED_ARRAY_CALL_OR_CONSTRUCT, 1, JSEXN_TYPEERR, "cannot directly {0} builtin %TypedArray%") -MSG_DEF(JSMSG_NON_TYPED_ARRAY_RETURNED, 0, JSEXN_TYPEERR, "constructor didn't return TypedArray object") -MSG_DEF(JSMSG_SHORT_TYPED_ARRAY_RETURNED, 2, JSEXN_TYPEERR, "expected TypedArray of at least length {0}, but constructor returned TypedArray of length {1}") - -// Shared array buffer -MSG_DEF(JSMSG_SHARED_ARRAY_BAD_LENGTH, 0, JSEXN_RANGEERR, "length argument out of range") -MSG_DEF(JSMSG_NON_SHARED_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected SharedArrayBuffer, but species constructor returned non-SharedArrayBuffer") -MSG_DEF(JSMSG_SAME_SHARED_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected different SharedArrayBuffer, but species constructor returned same SharedArrayBuffer") -MSG_DEF(JSMSG_SHORT_SHARED_ARRAY_BUFFER_RETURNED, 2, JSEXN_TYPEERR, "expected SharedArrayBuffer with at least {0} bytes, but species constructor returns SharedArrayBuffer with {1} bytes") - -// Reflect -MSG_DEF(JSMSG_BAD_PARSE_NODE, 0, JSEXN_INTERNALERR, "bad parse node") - -// Symbol -MSG_DEF(JSMSG_SYMBOL_TO_STRING, 0, JSEXN_TYPEERR, "can't convert symbol to string") -MSG_DEF(JSMSG_SYMBOL_TO_NUMBER, 0, JSEXN_TYPEERR, "can't convert symbol to number") - -// Atomics and futexes -MSG_DEF(JSMSG_ATOMICS_BAD_ARRAY, 0, JSEXN_TYPEERR, "invalid array type for the operation") -MSG_DEF(JSMSG_ATOMICS_TOO_LONG, 0, JSEXN_RANGEERR, "timeout value too large") -MSG_DEF(JSMSG_ATOMICS_WAIT_NOT_ALLOWED, 0, JSEXN_ERR, "waiting is not allowed on this thread") - -// XPConnect wrappers and DOM bindings -MSG_DEF(JSMSG_CANT_SET_INTERPOSED, 1, JSEXN_TYPEERR, "unable to set interposed data property '{0}'") -MSG_DEF(JSMSG_CANT_DEFINE_WINDOW_ELEMENT, 0, JSEXN_TYPEERR, "can't define elements on a Window object") -MSG_DEF(JSMSG_CANT_DELETE_WINDOW_ELEMENT, 0, JSEXN_TYPEERR, "can't delete elements from a Window object") -MSG_DEF(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY, 1, JSEXN_TYPEERR, "can't delete property {0} from window's named properties object") -MSG_DEF(JSMSG_CANT_PREVENT_EXTENSIONS, 0, JSEXN_TYPEERR, "can't prevent extensions on this proxy object") -MSG_DEF(JSMSG_NO_NAMED_SETTER, 2, JSEXN_TYPEERR, "{0} doesn't have a named property setter for '{1}'") -MSG_DEF(JSMSG_NO_INDEXED_SETTER, 2, JSEXN_TYPEERR, "{0} doesn't have an indexed property setter for '{1}'") - -// Super -MSG_DEF(JSMSG_CANT_DELETE_SUPER, 0, JSEXN_REFERENCEERR, "invalid delete involving 'super'") -MSG_DEF(JSMSG_REINIT_THIS, 0, JSEXN_REFERENCEERR, "super() called twice in derived class constructor") - -// Modules -MSG_DEF(JSMSG_BAD_DEFAULT_EXPORT, 0, JSEXN_SYNTAXERR, "default export cannot be provided by export *") -MSG_DEF(JSMSG_MISSING_INDIRECT_EXPORT, 1, JSEXN_SYNTAXERR, "indirect export '{0}' not found") -MSG_DEF(JSMSG_AMBIGUOUS_INDIRECT_EXPORT, 1, JSEXN_SYNTAXERR, "ambiguous indirect export '{0}'") -MSG_DEF(JSMSG_MISSING_IMPORT, 1, JSEXN_SYNTAXERR, "import '{0}' not found") -MSG_DEF(JSMSG_AMBIGUOUS_IMPORT, 1, JSEXN_SYNTAXERR, "ambiguous import '{0}'") -MSG_DEF(JSMSG_MISSING_NAMESPACE_EXPORT, 0, JSEXN_SYNTAXERR, "export not found for namespace") -MSG_DEF(JSMSG_MISSING_EXPORT, 1, JSEXN_SYNTAXERR, "local binding for export '{0}' not found") -MSG_DEF(JSMSG_MODULE_INSTANTIATE_FAILED, 0, JSEXN_INTERNALERR, "attempt to re-instantiate module after failure") -MSG_DEF(JSMSG_BAD_MODULE_STATE, 0, JSEXN_INTERNALERR, "module record in unexpected state") - -// Promise -MSG_DEF(JSMSG_CANNOT_RESOLVE_PROMISE_WITH_ITSELF, 0, JSEXN_TYPEERR, "A promise cannot be resolved with itself.") -MSG_DEF(JSMSG_PROMISE_CAPABILITY_HAS_SOMETHING_ALREADY, 0, JSEXN_TYPEERR, "GetCapabilitiesExecutor function already invoked with non-undefined values.") -MSG_DEF(JSMSG_PROMISE_RESOLVE_FUNCTION_NOT_CALLABLE, 0, JSEXN_TYPEERR, "A Promise subclass passed a non-callable value as the resolve function.") -MSG_DEF(JSMSG_PROMISE_REJECT_FUNCTION_NOT_CALLABLE, 0, JSEXN_TYPEERR, "A Promise subclass passed a non-callable value as the reject function.") -MSG_DEF(JSMSG_PROMISE_ERROR_IN_WRAPPED_REJECTION_REASON,0, JSEXN_INTERNALERR, "Promise rejection value is a non-unwrappable cross-compartment wrapper.") diff --git a/ios/include/spidermonkey/js/CallArgs.h b/ios/include/spidermonkey/js/CallArgs.h deleted file mode 100644 index 1e0d909a..00000000 --- a/ios/include/spidermonkey/js/CallArgs.h +++ /dev/null @@ -1,369 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Helper classes encapsulating access to the callee, |this| value, arguments, - * and argument count for a call/construct operation. - * - * JS::CallArgs encapsulates access to a JSNative's un-abstracted - * |unsigned argc, Value* vp| arguments. The principal way to create a - * JS::CallArgs is using JS::CallArgsFromVp: - * - * // If provided no arguments or a non-numeric first argument, return zero. - * // Otherwise return |this| exactly as given, without boxing. - * static bool - * Func(JSContext* cx, unsigned argc, JS::Value* vp) - * { - * JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - * - * // Guard against no arguments or a non-numeric arg0. - * if (args.length() == 0 || !args[0].isNumber()) { - * args.rval().setInt32(0); - * return true; - * } - * - * // Access to the callee must occur before accessing/setting - * // the return value. - * JSObject& callee = args.callee(); - * args.rval().setObject(callee); - * - * // callee() and calleev() will now assert. - * - * // It's always fine to access thisv(). - * HandleValue thisv = args.thisv(); - * args.rval().set(thisv); - * - * // As the return value was last set to |this|, returns |this|. - * return true; - * } - * - * CallArgs is exposed publicly and used internally. Not all parts of its - * public interface are meant to be used by embedders! See inline comments to - * for details. - * - * It's possible (albeit deprecated) to manually index into |vp| to access the - * callee, |this|, and arguments of a function, and to set its return value. - * It's also possible to use the supported API of JS_CALLEE, JS_THIS, JS_ARGV, - * JS_RVAL, and JS_SET_RVAL to the same ends. - * - * But neither API has the error-handling or moving-GC correctness of CallArgs. - * New code should use CallArgs instead whenever possible. - * - * The eventual plan is to change JSNative to take |const CallArgs&| directly, - * for automatic assertion of correct use and to make calling functions more - * efficient. Embedders should start internally switching away from using - * |argc| and |vp| directly, except to create a |CallArgs|. Then, when an - * eventual release making that change occurs, porting efforts will require - * changing methods' signatures but won't require invasive changes to the - * methods' implementations, potentially under time pressure. - */ - -#ifndef js_CallArgs_h -#define js_CallArgs_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -#include "jstypes.h" - -#include "js/RootingAPI.h" -#include "js/Value.h" - -/* Typedef for native functions called by the JS VM. */ -typedef bool -(* JSNative)(JSContext* cx, unsigned argc, JS::Value* vp); - -namespace JS { - -extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; - -namespace detail { - -/* - * Compute |this| for the |vp| inside a JSNative, either boxing primitives or - * replacing with the global object as necessary. - */ -extern JS_PUBLIC_API(Value) -ComputeThis(JSContext* cx, JS::Value* vp); - -#ifdef JS_DEBUG -extern JS_PUBLIC_API(void) -CheckIsValidConstructible(const Value& v); -#endif - -class MOZ_STACK_CLASS IncludeUsedRval -{ - protected: -#ifdef JS_DEBUG - mutable bool usedRval_; - void setUsedRval() const { usedRval_ = true; } - void clearUsedRval() const { usedRval_ = false; } - void assertUnusedRval() const { MOZ_ASSERT(!usedRval_); } -#else - void setUsedRval() const {} - void clearUsedRval() const {} - void assertUnusedRval() const {} -#endif -}; - -class MOZ_STACK_CLASS NoUsedRval -{ - protected: - void setUsedRval() const {} - void clearUsedRval() const {} - void assertUnusedRval() const {} -}; - -template -class MOZ_STACK_CLASS CallArgsBase : public WantUsedRval -{ - static_assert(mozilla::IsSame::value || - mozilla::IsSame::value, - "WantUsedRval can only be IncludeUsedRval or NoUsedRval"); - - protected: - Value* argv_; - unsigned argc_; - bool constructing_; - - public: - // CALLEE ACCESS - - /* - * Returns the function being called, as a value. Must not be called after - * rval() has been used! - */ - HandleValue calleev() const { - this->assertUnusedRval(); - return HandleValue::fromMarkedLocation(&argv_[-2]); - } - - /* - * Returns the function being called, as an object. Must not be called - * after rval() has been used! - */ - JSObject& callee() const { - return calleev().toObject(); - } - - // CALLING/CONSTRUCTING-DIFFERENTIATIONS - - bool isConstructing() const { - if (!argv_[-1].isMagic()) - return false; - -#ifdef JS_DEBUG - if (!this->usedRval_) - CheckIsValidConstructible(calleev()); -#endif - - return true; - } - - MutableHandleValue newTarget() const { - MOZ_ASSERT(constructing_); - return MutableHandleValue::fromMarkedLocation(&this->argv_[argc_]); - } - - /* - * Returns the |this| value passed to the function. This method must not - * be called when the function is being called as a constructor via |new|. - * The value may or may not be an object: it is the individual function's - * responsibility to box the value if needed. - */ - HandleValue thisv() const { - // Some internal code uses thisv() in constructing cases, so don't do - // this yet. - // MOZ_ASSERT(!argv_[-1].isMagic(JS_IS_CONSTRUCTING)); - return HandleValue::fromMarkedLocation(&argv_[-1]); - } - - Value computeThis(JSContext* cx) const { - if (thisv().isObject()) - return thisv(); - - return ComputeThis(cx, base()); - } - - // ARGUMENTS - - /* Returns the number of arguments. */ - unsigned length() const { return argc_; } - - /* Returns the i-th zero-indexed argument. */ - MutableHandleValue operator[](unsigned i) const { - MOZ_ASSERT(i < argc_); - return MutableHandleValue::fromMarkedLocation(&this->argv_[i]); - } - - /* - * Returns the i-th zero-indexed argument, or |undefined| if there's no - * such argument. - */ - HandleValue get(unsigned i) const { - return i < length() - ? HandleValue::fromMarkedLocation(&this->argv_[i]) - : UndefinedHandleValue; - } - - /* - * Returns true if the i-th zero-indexed argument is present and is not - * |undefined|. - */ - bool hasDefined(unsigned i) const { - return i < argc_ && !this->argv_[i].isUndefined(); - } - - // RETURN VALUE - - /* - * Returns the currently-set return value. The initial contents of this - * value are unspecified. Once this method has been called, callee() and - * calleev() can no longer be used. (If you're compiling against a debug - * build of SpiderMonkey, these methods will assert to aid debugging.) - * - * If the method you're implementing succeeds by returning true, you *must* - * set this. (SpiderMonkey doesn't currently assert this, but it will do - * so eventually.) You don't need to use or change this if your method - * fails. - */ - MutableHandleValue rval() const { - this->setUsedRval(); - return MutableHandleValue::fromMarkedLocation(&argv_[-2]); - } - - public: - // These methods are publicly exposed, but they are *not* to be used when - // implementing a JSNative method and encapsulating access to |vp| within - // it. You probably don't want to use these! - - void setCallee(const Value& aCalleev) const { - this->clearUsedRval(); - argv_[-2] = aCalleev; - } - - void setThis(const Value& aThisv) const { - argv_[-1] = aThisv; - } - - MutableHandleValue mutableThisv() const { - return MutableHandleValue::fromMarkedLocation(&argv_[-1]); - } - - public: - // These methods are publicly exposed, but we're unsure of the interfaces - // (because they're hackish and drop assertions). Avoid using these if you - // can. - - Value* array() const { return argv_; } - Value* end() const { return argv_ + argc_ + constructing_; } - - public: - // These methods are only intended for internal use. Embedders shouldn't - // use them! - - Value* base() const { return argv_ - 2; } - - Value* spAfterCall() const { - this->setUsedRval(); - return argv_ - 1; - } -}; - -} // namespace detail - -class MOZ_STACK_CLASS CallArgs : public detail::CallArgsBase -{ - private: - friend CallArgs CallArgsFromVp(unsigned argc, Value* vp); - friend CallArgs CallArgsFromSp(unsigned stackSlots, Value* sp, bool constructing); - - static CallArgs create(unsigned argc, Value* argv, bool constructing) { - CallArgs args; - args.clearUsedRval(); - args.argv_ = argv; - args.argc_ = argc; - args.constructing_ = constructing; -#ifdef DEBUG - for (unsigned i = 0; i < argc; ++i) - MOZ_ASSERT_IF(argv[i].isMarkable(), !GCThingIsMarkedGray(GCCellPtr(argv[i]))); -#endif - return args; - } - - public: - /* - * Returns true if there are at least |required| arguments passed in. If - * false, it reports an error message on the context. - */ - bool requireAtLeast(JSContext* cx, const char* fnname, unsigned required) const; - -}; - -MOZ_ALWAYS_INLINE CallArgs -CallArgsFromVp(unsigned argc, Value* vp) -{ - return CallArgs::create(argc, vp + 2, vp[1].isMagic(JS_IS_CONSTRUCTING)); -} - -// This method is only intended for internal use in SpiderMonkey. We may -// eventually move it to an internal header. Embedders should use -// JS::CallArgsFromVp! -MOZ_ALWAYS_INLINE CallArgs -CallArgsFromSp(unsigned stackSlots, Value* sp, bool constructing = false) -{ - return CallArgs::create(stackSlots - constructing, sp - stackSlots, constructing); -} - -} // namespace JS - -/* - * Macros to hide interpreter stack layout details from a JSNative using its - * JS::Value* vp parameter. DO NOT USE THESE! Instead use JS::CallArgs and - * friends, above. These macros will be removed when we change JSNative to - * take a const JS::CallArgs&. - */ - -/* - * Return |this| if |this| is an object. Otherwise, return the global object - * if |this| is null or undefined, and finally return a boxed version of any - * other primitive. - * - * Note: if this method returns null, an error has occurred and must be - * propagated or caught. - */ -MOZ_ALWAYS_INLINE JS::Value -JS_THIS(JSContext* cx, JS::Value* vp) -{ - return vp[1].isPrimitive() ? JS::detail::ComputeThis(cx, vp) : vp[1]; -} - -/* - * A note on JS_THIS_OBJECT: no equivalent method is part of the CallArgs - * interface, and we're unlikely to add one (functions shouldn't be implicitly - * exposing the global object to arbitrary callers). Continue using |vp| - * directly for this case, but be aware this API will eventually be replaced - * with a function that operates directly upon |args.thisv()|. - */ -#define JS_THIS_OBJECT(cx,vp) (JS_THIS(cx,vp).toObjectOrNull()) - -/* - * |this| is passed to functions in ES5 without change. Functions themselves - * do any post-processing they desire to box |this|, compute the global object, - * &c. This macro retrieves a function's unboxed |this| value. - * - * This macro must not be used in conjunction with JS_THIS or JS_THIS_OBJECT, - * or vice versa. Either use the provided this value with this macro, or - * compute the boxed |this| value using those. JS_THIS_VALUE must not be used - * if the function is being called as a constructor. - * - * But: DO NOT USE THIS! Instead use JS::CallArgs::thisv(), above. - * - */ -#define JS_THIS_VALUE(cx,vp) ((vp)[1]) - -#endif /* js_CallArgs_h */ diff --git a/ios/include/spidermonkey/js/CallNonGenericMethod.h b/ios/include/spidermonkey/js/CallNonGenericMethod.h deleted file mode 100644 index 9a1cf010..00000000 --- a/ios/include/spidermonkey/js/CallNonGenericMethod.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_CallNonGenericMethod_h -#define js_CallNonGenericMethod_h - -#include "jstypes.h" - -#include "js/CallArgs.h" - -namespace JS { - -// Returns true if |v| is considered an acceptable this-value. -typedef bool (*IsAcceptableThis)(HandleValue v); - -// Implements the guts of a method; guaranteed to be provided an acceptable -// this-value, as determined by a corresponding IsAcceptableThis method. -typedef bool (*NativeImpl)(JSContext* cx, const CallArgs& args); - -namespace detail { - -// DON'T CALL THIS DIRECTLY. It's for use only by CallNonGenericMethod! -extern JS_PUBLIC_API(bool) -CallMethodIfWrapped(JSContext* cx, IsAcceptableThis test, NativeImpl impl, const CallArgs& args); - -} // namespace detail - -// Methods usually act upon |this| objects only from a single global object and -// compartment. Sometimes, however, a method must act upon |this| values from -// multiple global objects or compartments. In such cases the |this| value a -// method might see will be wrapped, such that various access to the object -- -// to its class, its private data, its reserved slots, and so on -- will not -// work properly without entering that object's compartment. This method -// implements a solution to this problem. -// -// To implement a method that accepts |this| values from multiple compartments, -// define two functions. The first function matches the IsAcceptableThis type -// and indicates whether the provided value is an acceptable |this| for the -// method; it must be a pure function only of its argument. -// -// static const JSClass AnswerClass = { ... }; -// -// static bool -// IsAnswerObject(const Value& v) -// { -// if (!v.isObject()) -// return false; -// return JS_GetClass(&v.toObject()) == &AnswerClass; -// } -// -// The second function implements the NativeImpl signature and defines the -// behavior of the method when it is provided an acceptable |this| value. -// Aside from some typing niceties -- see the CallArgs interface for details -- -// its interface is the same as that of JSNative. -// -// static bool -// answer_getAnswer_impl(JSContext* cx, JS::CallArgs args) -// { -// args.rval().setInt32(42); -// return true; -// } -// -// The implementation function is guaranteed to be called *only* with a |this| -// value which is considered acceptable. -// -// Now to implement the actual method, write a JSNative that calls the method -// declared below, passing the appropriate template and runtime arguments. -// -// static bool -// answer_getAnswer(JSContext* cx, unsigned argc, JS::Value* vp) -// { -// JS::CallArgs args = JS::CallArgsFromVp(argc, vp); -// return JS::CallNonGenericMethod(cx, args); -// } -// -// Note that, because they are used as template arguments, the predicate -// and implementation functions must have external linkage. (This is -// unfortunate, but GCC wasn't inlining things as one would hope when we -// passed them as function arguments.) -// -// JS::CallNonGenericMethod will test whether |args.thisv()| is acceptable. If -// it is, it will call the provided implementation function, which will return -// a value and indicate success. If it is not, it will attempt to unwrap -// |this| and call the implementation function on the unwrapped |this|. If -// that succeeds, all well and good. If it doesn't succeed, a TypeError will -// be thrown. -// -// Note: JS::CallNonGenericMethod will only work correctly if it's called in -// tail position in a JSNative. Do not call it from any other place. -// -template -MOZ_ALWAYS_INLINE bool -CallNonGenericMethod(JSContext* cx, const CallArgs& args) -{ - HandleValue thisv = args.thisv(); - if (Test(thisv)) - return Impl(cx, args); - - return detail::CallMethodIfWrapped(cx, Test, Impl, args); -} - -MOZ_ALWAYS_INLINE bool -CallNonGenericMethod(JSContext* cx, IsAcceptableThis Test, NativeImpl Impl, const CallArgs& args) -{ - HandleValue thisv = args.thisv(); - if (Test(thisv)) - return Impl(cx, args); - - return detail::CallMethodIfWrapped(cx, Test, Impl, args); -} - -} // namespace JS - -#endif /* js_CallNonGenericMethod_h */ diff --git a/ios/include/spidermonkey/js/CharacterEncoding.h b/ios/include/spidermonkey/js/CharacterEncoding.h deleted file mode 100644 index fe39a415..00000000 --- a/ios/include/spidermonkey/js/CharacterEncoding.h +++ /dev/null @@ -1,338 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_CharacterEncoding_h -#define js_CharacterEncoding_h - -#include "mozilla/Range.h" - -#include "js/TypeDecls.h" -#include "js/Utility.h" - -namespace js { -class ExclusiveContext; -} // namespace js - -class JSFlatString; - -namespace JS { - -/* - * By default, all C/C++ 1-byte-per-character strings passed into the JSAPI - * are treated as ISO/IEC 8859-1, also known as Latin-1. That is, each - * byte is treated as a 2-byte character, and there is no way to pass in a - * string containing characters beyond U+00FF. - */ -class Latin1Chars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = Latin1Char; - - Latin1Chars() : Base() {} - Latin1Chars(char* aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) {} - Latin1Chars(const Latin1Char* aBytes, size_t aLength) - : Base(const_cast(aBytes), aLength) - {} - Latin1Chars(const char* aBytes, size_t aLength) - : Base(reinterpret_cast(const_cast(aBytes)), aLength) - {} -}; - -/* - * A Latin1Chars, but with \0 termination for C compatibility. - */ -class Latin1CharsZ : public mozilla::RangedPtr -{ - typedef mozilla::RangedPtr Base; - - public: - using CharT = Latin1Char; - - Latin1CharsZ() : Base(nullptr, 0) {} - - Latin1CharsZ(char* aBytes, size_t aLength) - : Base(reinterpret_cast(aBytes), aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - Latin1CharsZ(Latin1Char* aBytes, size_t aLength) - : Base(aBytes, aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - using Base::operator=; - - char* c_str() { return reinterpret_cast(get()); } -}; - -class UTF8Chars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = unsigned char; - - UTF8Chars() : Base() {} - UTF8Chars(char* aBytes, size_t aLength) - : Base(reinterpret_cast(aBytes), aLength) - {} - UTF8Chars(const char* aBytes, size_t aLength) - : Base(reinterpret_cast(const_cast(aBytes)), aLength) - {} -}; - -/* - * SpiderMonkey also deals directly with UTF-8 encoded text in some places. - */ -class UTF8CharsZ : public mozilla::RangedPtr -{ - typedef mozilla::RangedPtr Base; - - public: - using CharT = unsigned char; - - UTF8CharsZ() : Base(nullptr, 0) {} - - UTF8CharsZ(char* aBytes, size_t aLength) - : Base(reinterpret_cast(aBytes), aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - UTF8CharsZ(unsigned char* aBytes, size_t aLength) - : Base(aBytes, aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - using Base::operator=; - - char* c_str() { return reinterpret_cast(get()); } -}; - -/* - * A wrapper for a "const char*" that is encoded using UTF-8. - * This class does not manage ownership of the data; that is left - * to others. This differs from UTF8CharsZ in that the chars are - * const and it allows assignment. - */ -class ConstUTF8CharsZ -{ - const char* data_; - - public: - using CharT = unsigned char; - - ConstUTF8CharsZ() : data_(nullptr) - {} - - ConstUTF8CharsZ(const char* aBytes, size_t aLength) - : data_(aBytes) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); -#ifdef DEBUG - validate(aLength); -#endif - } - - const void* get() const { return data_; } - - const char* c_str() const { return data_; } - - explicit operator bool() const { return data_ != nullptr; } - - private: -#ifdef DEBUG - void validate(size_t aLength); -#endif -}; - -/* - * SpiderMonkey uses a 2-byte character representation: it is a - * 2-byte-at-a-time view of a UTF-16 byte stream. This is similar to UCS-2, - * but unlike UCS-2, we do not strip UTF-16 extension bytes. This allows a - * sufficiently dedicated JavaScript program to be fully unicode-aware by - * manually interpreting UTF-16 extension characters embedded in the JS - * string. - */ -class TwoByteChars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = char16_t; - - TwoByteChars() : Base() {} - TwoByteChars(char16_t* aChars, size_t aLength) : Base(aChars, aLength) {} - TwoByteChars(const char16_t* aChars, size_t aLength) : Base(const_cast(aChars), aLength) {} -}; - -/* - * A TwoByteChars, but \0 terminated for compatibility with JSFlatString. - */ -class TwoByteCharsZ : public mozilla::RangedPtr -{ - typedef mozilla::RangedPtr Base; - - public: - using CharT = char16_t; - - TwoByteCharsZ() : Base(nullptr, 0) {} - - TwoByteCharsZ(char16_t* chars, size_t length) - : Base(chars, length) - { - MOZ_ASSERT(chars[length] == '\0'); - } - - using Base::operator=; -}; - -typedef mozilla::RangedPtr ConstCharPtr; - -/* - * Like TwoByteChars, but the chars are const. - */ -class ConstTwoByteChars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = char16_t; - - ConstTwoByteChars() : Base() {} - ConstTwoByteChars(const char16_t* aChars, size_t aLength) : Base(aChars, aLength) {} -}; - -/* - * Convert a 2-byte character sequence to "ISO-Latin-1". This works by - * truncating each 2-byte pair in the sequence to a 1-byte pair. If the source - * contains any UTF-16 extension characters, then this may give invalid Latin1 - * output. The returned string is zero terminated. The returned string or the - * returned string's |start()| must be freed with JS_free or js_free, - * respectively. If allocation fails, an OOM error will be set and the method - * will return a nullptr chars (which can be tested for with the ! operator). - * This method cannot trigger GC. - */ -extern Latin1CharsZ -LossyTwoByteCharsToNewLatin1CharsZ(js::ExclusiveContext* cx, - const mozilla::Range tbchars); - -inline Latin1CharsZ -LossyTwoByteCharsToNewLatin1CharsZ(js::ExclusiveContext* cx, const char16_t* begin, size_t length) -{ - const mozilla::Range tbchars(begin, length); - return JS::LossyTwoByteCharsToNewLatin1CharsZ(cx, tbchars); -} - -template -extern UTF8CharsZ -CharsToNewUTF8CharsZ(js::ExclusiveContext* maybeCx, const mozilla::Range chars); - -uint32_t -Utf8ToOneUcs4Char(const uint8_t* utf8Buffer, int utf8Length); - -/* - * Inflate bytes in UTF-8 encoding to char16_t. - * - On error, returns an empty TwoByteCharsZ. - * - On success, returns a malloc'd TwoByteCharsZ, and updates |outlen| to hold - * its length; the length value excludes the trailing null. - */ -extern TwoByteCharsZ -UTF8CharsToNewTwoByteCharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -/* - * Like UTF8CharsToNewTwoByteCharsZ, but for ConstUTF8CharsZ. - */ -extern TwoByteCharsZ -UTF8CharsToNewTwoByteCharsZ(JSContext* cx, const ConstUTF8CharsZ& utf8, size_t* outlen); - -/* - * The same as UTF8CharsToNewTwoByteCharsZ(), except that any malformed UTF-8 characters - * will be replaced by \uFFFD. No exception will be thrown for malformed UTF-8 - * input. - */ -extern TwoByteCharsZ -LossyUTF8CharsToNewTwoByteCharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -extern TwoByteCharsZ -LossyUTF8CharsToNewTwoByteCharsZ(JSContext* cx, const ConstUTF8CharsZ& utf8, size_t* outlen); - -/* - * Returns the length of the char buffer required to encode |s| as UTF8. - * Does not include the null-terminator. - */ -JS_PUBLIC_API(size_t) -GetDeflatedUTF8StringLength(JSFlatString* s); - -/* - * Encode |src| as UTF8. The caller must either ensure |dst| has enough space - * to encode the entire string or pass the length of the buffer as |dstlenp|, - * in which case the function will encode characters from the string until - * the buffer is exhausted. Does not write the null terminator. - * - * If |dstlenp| is provided, it will be updated to hold the number of bytes - * written to the buffer. If |numcharsp| is provided, it will be updated to hold - * the number of Unicode characters written to the buffer (which can be less - * than the length of the string, if the buffer is exhausted before the string - * is fully encoded). - */ -JS_PUBLIC_API(void) -DeflateStringToUTF8Buffer(JSFlatString* src, mozilla::RangedPtr dst, - size_t* dstlenp = nullptr, size_t* numcharsp = nullptr); - -/* - * The smallest character encoding capable of fully representing a particular - * string. - */ -enum class SmallestEncoding { - ASCII, - Latin1, - UTF16 -}; - -/* - * Returns the smallest encoding possible for the given string: if all - * codepoints are <128 then ASCII, otherwise if all codepoints are <256 - * Latin-1, else UTF16. - */ -JS_PUBLIC_API(SmallestEncoding) -FindSmallestEncoding(UTF8Chars utf8); - -/* - * Return a null-terminated Latin-1 string copied from the input string, - * storing its length (excluding null terminator) in |*outlen|. Fail and - * report an error if the string contains non-Latin-1 codepoints. Returns - * Latin1CharsZ() on failure. - */ -extern Latin1CharsZ -UTF8CharsToNewLatin1CharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -/* - * Return a null-terminated Latin-1 string copied from the input string, - * storing its length (excluding null terminator) in |*outlen|. Non-Latin-1 - * codepoints are replaced by '?'. Returns Latin1CharsZ() on failure. - */ -extern Latin1CharsZ -LossyUTF8CharsToNewLatin1CharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -/* - * Returns true if all characters in the given null-terminated string are - * ASCII, i.e. < 0x80, false otherwise. - */ -extern bool -StringIsASCII(const char* s); - -} // namespace JS - -inline void JS_free(JS::Latin1CharsZ& ptr) { js_free((void*)ptr.get()); } -inline void JS_free(JS::UTF8CharsZ& ptr) { js_free((void*)ptr.get()); } - -#endif /* js_CharacterEncoding_h */ diff --git a/ios/include/spidermonkey/js/Class.h b/ios/include/spidermonkey/js/Class.h deleted file mode 100644 index 3b502387..00000000 --- a/ios/include/spidermonkey/js/Class.h +++ /dev/null @@ -1,995 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JSClass definition and its component types, plus related interfaces. */ - -#ifndef js_Class_h -#define js_Class_h - -#include "jstypes.h" - -#include "js/CallArgs.h" -#include "js/Id.h" -#include "js/TypeDecls.h" - -/* - * A JSClass acts as a vtable for JS objects that allows JSAPI clients to - * control various aspects of the behavior of an object like property lookup. - * js::Class is an engine-private extension that allows more control over - * object behavior and, e.g., allows custom slow layout. - */ - -struct JSAtomState; -struct JSFreeOp; -struct JSFunctionSpec; - -namespace js { - -struct Class; -class FreeOp; -class Shape; - -// This is equal to JSFunction::class_. Use it in places where you don't want -// to #include jsfun.h. -extern JS_FRIEND_DATA(const js::Class* const) FunctionClassPtr; - -} // namespace js - -namespace JS { - -class AutoIdVector; - -/** - * The answer to a successful query as to whether an object is an Array per - * ES6's internal |IsArray| operation (as exposed by |Array.isArray|). - */ -enum class IsArrayAnswer -{ - Array, - NotArray, - RevokedProxy -}; - -/** - * ES6 7.2.2. - * - * Returns false on failure, otherwise returns true and sets |*isArray| - * indicating whether the object passes ECMAScript's IsArray test. This is the - * same test performed by |Array.isArray|. - * - * This is NOT the same as asking whether |obj| is an Array or a wrapper around - * one. If |obj| is a proxy created by |Proxy.revocable()| and has been - * revoked, or if |obj| is a proxy whose target (at any number of hops) is a - * revoked proxy, this method throws a TypeError and returns false. - */ -extern JS_PUBLIC_API(bool) -IsArray(JSContext* cx, HandleObject obj, bool* isArray); - -/** - * Identical to IsArray above, but the nature of the object (if successfully - * determined) is communicated via |*answer|. In particular this method - * returns true and sets |*answer = IsArrayAnswer::RevokedProxy| when called on - * a revoked proxy. - * - * Most users will want the overload above, not this one. - */ -extern JS_PUBLIC_API(bool) -IsArray(JSContext* cx, HandleObject obj, IsArrayAnswer* answer); - -/** - * Per ES6, the [[DefineOwnProperty]] internal method has three different - * possible outcomes: - * - * - It can throw an exception (which we indicate by returning false). - * - * - It can return true, indicating unvarnished success. - * - * - It can return false, indicating "strict failure". The property could - * not be defined. It's an error, but no exception was thrown. - * - * It's not just [[DefineOwnProperty]]: all the mutating internal methods have - * the same three outcomes. (The other affected internal methods are [[Set]], - * [[Delete]], [[SetPrototypeOf]], and [[PreventExtensions]].) - * - * If you think this design is awful, you're not alone. But as it's the - * standard, we must represent these boolean "success" values somehow. - * ObjectOpSuccess is the class for this. It's like a bool, but when it's false - * it also stores an error code. - * - * Typical usage: - * - * ObjectOpResult result; - * if (!DefineProperty(cx, obj, id, ..., result)) - * return false; - * if (!result) - * return result.reportError(cx, obj, id); - * - * Users don't have to call `result.report()`; another possible ending is: - * - * argv.rval().setBoolean(bool(result)); - * return true; - */ -class ObjectOpResult -{ - private: - /** - * code_ is either one of the special codes OkCode or Uninitialized, or - * an error code. For now the error codes are private to the JS engine; - * they're defined in js/src/js.msg. - * - * code_ is uintptr_t (rather than uint32_t) for the convenience of the - * JITs, which would otherwise have to deal with either padding or stack - * alignment on 64-bit platforms. - */ - uintptr_t code_; - - public: - enum SpecialCodes : uintptr_t { - OkCode = 0, - Uninitialized = uintptr_t(-1) - }; - - ObjectOpResult() : code_(Uninitialized) {} - - /* Return true if succeed() was called. */ - bool ok() const { - MOZ_ASSERT(code_ != Uninitialized); - return code_ == OkCode; - } - - explicit operator bool() const { return ok(); } - - /* Set this ObjectOpResult to true and return true. */ - bool succeed() { - code_ = OkCode; - return true; - } - - /* - * Set this ObjectOpResult to false with an error code. - * - * Always returns true, as a convenience. Typical usage will be: - * - * if (funny condition) - * return result.fail(JSMSG_CANT_DO_THE_THINGS); - * - * The true return value indicates that no exception is pending, and it - * would be OK to ignore the failure and continue. - */ - bool fail(uint32_t msg) { - MOZ_ASSERT(msg != OkCode); - code_ = msg; - return true; - } - - JS_PUBLIC_API(bool) failCantRedefineProp(); - JS_PUBLIC_API(bool) failReadOnly(); - JS_PUBLIC_API(bool) failGetterOnly(); - JS_PUBLIC_API(bool) failCantDelete(); - - JS_PUBLIC_API(bool) failCantSetInterposed(); - JS_PUBLIC_API(bool) failCantDefineWindowElement(); - JS_PUBLIC_API(bool) failCantDeleteWindowElement(); - JS_PUBLIC_API(bool) failCantDeleteWindowNamedProperty(); - JS_PUBLIC_API(bool) failCantPreventExtensions(); - JS_PUBLIC_API(bool) failCantSetProto(); - JS_PUBLIC_API(bool) failNoNamedSetter(); - JS_PUBLIC_API(bool) failNoIndexedSetter(); - - uint32_t failureCode() const { - MOZ_ASSERT(!ok()); - return uint32_t(code_); - } - - /* - * Report an error or warning if necessary; return true to proceed and - * false if an error was reported. Call this when failure should cause - * a warning if extraWarnings are enabled. - * - * The precise rules are like this: - * - * - If ok(), then we succeeded. Do nothing and return true. - * - Otherwise, if |strict| is true, or if cx has both extraWarnings and - * werrorOption enabled, throw a TypeError and return false. - * - Otherwise, if cx has extraWarnings enabled, emit a warning and - * return true. - * - Otherwise, do nothing and return true. - */ - bool checkStrictErrorOrWarning(JSContext* cx, HandleObject obj, HandleId id, bool strict) { - if (ok()) - return true; - return reportStrictErrorOrWarning(cx, obj, id, strict); - } - - /* - * The same as checkStrictErrorOrWarning(cx, id, strict), except the - * operation is not associated with a particular property id. This is - * used for [[PreventExtensions]] and [[SetPrototypeOf]]. failureCode() - * must not be an error that has "{0}" in the error message. - */ - bool checkStrictErrorOrWarning(JSContext* cx, HandleObject obj, bool strict) { - return ok() || reportStrictErrorOrWarning(cx, obj, strict); - } - - /* Throw a TypeError. Call this only if !ok(). */ - bool reportError(JSContext* cx, HandleObject obj, HandleId id) { - return reportStrictErrorOrWarning(cx, obj, id, true); - } - - /* - * The same as reportError(cx, obj, id), except the operation is not - * associated with a particular property id. - */ - bool reportError(JSContext* cx, HandleObject obj) { - return reportStrictErrorOrWarning(cx, obj, true); - } - - /* Helper function for checkStrictErrorOrWarning's slow path. */ - JS_PUBLIC_API(bool) reportStrictErrorOrWarning(JSContext* cx, HandleObject obj, HandleId id, bool strict); - JS_PUBLIC_API(bool) reportStrictErrorOrWarning(JSContext* cx, HandleObject obj, bool strict); - - /* - * Convenience method. Return true if ok() or if strict is false; otherwise - * throw a TypeError and return false. - */ - bool checkStrict(JSContext* cx, HandleObject obj, HandleId id) { - return checkStrictErrorOrWarning(cx, obj, id, true); - } - - /* - * Convenience method. The same as checkStrict(cx, id), except the - * operation is not associated with a particular property id. - */ - bool checkStrict(JSContext* cx, HandleObject obj) { - return checkStrictErrorOrWarning(cx, obj, true); - } -}; - -} // namespace JS - -// JSClass operation signatures. - -/** - * Get a property named by id in obj. Note the jsid id type -- id may - * be a string (Unicode property identifier) or an int (element index). The - * *vp out parameter, on success, is the new property value after the action. - */ -typedef bool -(* JSGetterOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp); - -/** Add a property named by id to obj. */ -typedef bool -(* JSAddPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v); - -/** - * Set a property named by id in obj, treating the assignment as strict - * mode code if strict is true. Note the jsid id type -- id may be a string - * (Unicode property identifier) or an int (element index). The *vp out - * parameter, on success, is the new property value after the - * set. - */ -typedef bool -(* JSSetterOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp, JS::ObjectOpResult& result); - -/** - * Delete a property named by id in obj. - * - * If an error occurred, return false as per normal JSAPI error practice. - * - * If no error occurred, but the deletion attempt wasn't allowed (perhaps - * because the property was non-configurable), call result.fail() and - * return true. This will cause |delete obj[id]| to evaluate to false in - * non-strict mode code, and to throw a TypeError in strict mode code. - * - * If no error occurred and the deletion wasn't disallowed (this is *not* the - * same as saying that a deletion actually occurred -- deleting a non-existent - * property, or an inherited property, is allowed -- it's just pointless), - * call result.succeed() and return true. - */ -typedef bool -(* JSDeletePropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -/** - * The type of ObjectOps::enumerate. This callback overrides a portion of - * SpiderMonkey's default [[Enumerate]] internal method. When an ordinary object - * is enumerated, that object and each object on its prototype chain is tested - * for an enumerate op, and those ops are called in order. The properties each - * op adds to the 'properties' vector are added to the set of values the for-in - * loop will iterate over. All of this is nonstandard. - * - * An object is "enumerated" when it's the target of a for-in loop or - * JS_Enumerate(). The callback's job is to populate 'properties' with the - * object's property keys. If `enumerableOnly` is true, the callback should only - * add enumerable properties. - */ -typedef bool -(* JSNewEnumerateOp)(JSContext* cx, JS::HandleObject obj, JS::AutoIdVector& properties, - bool enumerableOnly); - -/** - * The old-style JSClass.enumerate op should define all lazy properties not - * yet reflected in obj. - */ -typedef bool -(* JSEnumerateOp)(JSContext* cx, JS::HandleObject obj); - -/** - * The type of ObjectOps::funToString. This callback allows an object to - * provide a custom string to use when Function.prototype.toString is invoked on - * that object. A null return value means OOM. - */ -typedef JSString* -(* JSFunToStringOp)(JSContext* cx, JS::HandleObject obj, unsigned indent); - -/** - * Resolve a lazy property named by id in obj by defining it directly in obj. - * Lazy properties are those reflected from some peer native property space - * (e.g., the DOM attributes for a given node reflected as obj) on demand. - * - * JS looks for a property in an object, and if not found, tries to resolve - * the given id. *resolvedp should be set to true iff the property was defined - * on |obj|. - */ -typedef bool -(* JSResolveOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - bool* resolvedp); - -/** - * A class with a resolve hook can optionally have a mayResolve hook. This hook - * must have no side effects and must return true for a given id if the resolve - * hook may resolve this id. This is useful when we're doing a "pure" lookup: if - * mayResolve returns false, we know we don't have to call the effectful resolve - * hook. - * - * maybeObj, if non-null, is the object on which we're doing the lookup. This - * can be nullptr: during JIT compilation we sometimes know the Class but not - * the object. - */ -typedef bool -(* JSMayResolveOp)(const JSAtomState& names, jsid id, JSObject* maybeObj); - -/** - * Finalize obj, which the garbage collector has determined to be unreachable - * from other live objects or from GC roots. Obviously, finalizers must never - * store a reference to obj. - */ -typedef void -(* JSFinalizeOp)(JSFreeOp* fop, JSObject* obj); - -/** Finalizes external strings created by JS_NewExternalString. */ -struct JSStringFinalizer { - void (*finalize)(JS::Zone* zone, const JSStringFinalizer* fin, char16_t* chars); -}; - -/** - * Check whether v is an instance of obj. Return false on error or exception, - * true on success with true in *bp if v is an instance of obj, false in - * *bp otherwise. - */ -typedef bool -(* JSHasInstanceOp)(JSContext* cx, JS::HandleObject obj, JS::MutableHandleValue vp, - bool* bp); - -/** - * Function type for trace operation of the class called to enumerate all - * traceable things reachable from obj's private data structure. For each such - * thing, a trace implementation must call JS::TraceEdge on the thing's - * location. - * - * JSTraceOp implementation can assume that no other threads mutates object - * state. It must not change state of the object or corresponding native - * structures. The only exception for this rule is the case when the embedding - * needs a tight integration with GC. In that case the embedding can check if - * the traversal is a part of the marking phase through calling - * JS_IsGCMarkingTracer and apply a special code like emptying caches or - * marking its native structures. - */ -typedef void -(* JSTraceOp)(JSTracer* trc, JSObject* obj); - -typedef JSObject* -(* JSWeakmapKeyDelegateOp)(JSObject* obj); - -typedef void -(* JSObjectMovedOp)(JSObject* obj, const JSObject* old); - -/* js::Class operation signatures. */ - -namespace js { - -typedef bool -(* LookupPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleObject objp, JS::MutableHandle propp); -typedef bool -(* DefinePropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc, - JS::ObjectOpResult& result); -typedef bool -(* HasPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); -typedef bool -(* GetPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleValue receiver, JS::HandleId id, - JS::MutableHandleValue vp); -typedef bool -(* SetPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v, - JS::HandleValue receiver, JS::ObjectOpResult& result); -typedef bool -(* GetOwnPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); -typedef bool -(* DeletePropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -typedef bool -(* WatchOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); - -typedef bool -(* UnwatchOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id); - -class JS_FRIEND_API(ElementAdder) -{ - public: - enum GetBehavior { - // Check if the element exists before performing the Get and preserve - // holes. - CheckHasElemPreserveHoles, - - // Perform a Get operation, like obj[index] in JS. - GetElement - }; - - private: - // Only one of these is used. - JS::RootedObject resObj_; - JS::Value* vp_; - - uint32_t index_; -#ifdef DEBUG - uint32_t length_; -#endif - GetBehavior getBehavior_; - - public: - ElementAdder(JSContext* cx, JSObject* obj, uint32_t length, GetBehavior behavior) - : resObj_(cx, obj), vp_(nullptr), index_(0), -#ifdef DEBUG - length_(length), -#endif - getBehavior_(behavior) - {} - ElementAdder(JSContext* cx, JS::Value* vp, uint32_t length, GetBehavior behavior) - : resObj_(cx), vp_(vp), index_(0), -#ifdef DEBUG - length_(length), -#endif - getBehavior_(behavior) - {} - - GetBehavior getBehavior() const { return getBehavior_; } - - bool append(JSContext* cx, JS::HandleValue v); - void appendHole(); -}; - -typedef bool -(* GetElementsOp)(JSContext* cx, JS::HandleObject obj, uint32_t begin, uint32_t end, - ElementAdder* adder); - -typedef void -(* FinalizeOp)(FreeOp* fop, JSObject* obj); - -// The special treatment of |finalize| and |trace| is necessary because if we -// assign either of those hooks to a local variable and then call it -- as is -// done with the other hooks -- the GC hazard analysis gets confused. -#define JS_CLASS_MEMBERS(ClassOpsType, FreeOpType) \ - const char* name; \ - uint32_t flags; \ - const ClassOpsType* cOps; \ - \ - JSAddPropertyOp getAddProperty() const { return cOps ? cOps->addProperty : nullptr; } \ - JSDeletePropertyOp getDelProperty() const { return cOps ? cOps->delProperty : nullptr; } \ - JSGetterOp getGetProperty() const { return cOps ? cOps->getProperty : nullptr; } \ - JSSetterOp getSetProperty() const { return cOps ? cOps->setProperty : nullptr; } \ - JSEnumerateOp getEnumerate() const { return cOps ? cOps->enumerate : nullptr; } \ - JSResolveOp getResolve() const { return cOps ? cOps->resolve : nullptr; } \ - JSMayResolveOp getMayResolve() const { return cOps ? cOps->mayResolve : nullptr; } \ - JSNative getCall() const { return cOps ? cOps->call : nullptr; } \ - JSHasInstanceOp getHasInstance() const { return cOps ? cOps->hasInstance : nullptr; } \ - JSNative getConstruct() const { return cOps ? cOps->construct : nullptr; } \ - \ - bool hasFinalize() const { return cOps && cOps->finalize; } \ - bool hasTrace() const { return cOps && cOps->trace; } \ - \ - bool isTrace(JSTraceOp trace) const { return cOps && cOps->trace == trace; } \ - \ - void doFinalize(FreeOpType* fop, JSObject* obj) const { \ - MOZ_ASSERT(cOps && cOps->finalize); \ - cOps->finalize(fop, obj); \ - } \ - void doTrace(JSTracer* trc, JSObject* obj) const { \ - MOZ_ASSERT(cOps && cOps->trace); \ - cOps->trace(trc, obj); \ - } - -struct ClassOps -{ - /* Function pointer members (may be null). */ - JSAddPropertyOp addProperty; - JSDeletePropertyOp delProperty; - JSGetterOp getProperty; - JSSetterOp setProperty; - JSEnumerateOp enumerate; - JSResolveOp resolve; - JSMayResolveOp mayResolve; - FinalizeOp finalize; - JSNative call; - JSHasInstanceOp hasInstance; - JSNative construct; - JSTraceOp trace; -}; - -/** Callback for the creation of constructor and prototype objects. */ -typedef JSObject* (*ClassObjectCreationOp)(JSContext* cx, JSProtoKey key); - -/** Callback for custom post-processing after class initialization via ClassSpec. */ -typedef bool (*FinishClassInitOp)(JSContext* cx, JS::HandleObject ctor, - JS::HandleObject proto); - -const size_t JSCLASS_CACHED_PROTO_WIDTH = 6; - -struct ClassSpec -{ - // All properties except flags should be accessed through accessor. - ClassObjectCreationOp createConstructor_; - ClassObjectCreationOp createPrototype_; - const JSFunctionSpec* constructorFunctions_; - const JSPropertySpec* constructorProperties_; - const JSFunctionSpec* prototypeFunctions_; - const JSPropertySpec* prototypeProperties_; - FinishClassInitOp finishInit_; - uintptr_t flags; - - static const size_t ProtoKeyWidth = JSCLASS_CACHED_PROTO_WIDTH; - - static const uintptr_t ProtoKeyMask = (1 << ProtoKeyWidth) - 1; - static const uintptr_t DontDefineConstructor = 1 << ProtoKeyWidth; - static const uintptr_t IsDelegated = 1 << (ProtoKeyWidth + 1); - - bool defined() const { return !!createConstructor_; } - - bool delegated() const { - return (flags & IsDelegated); - } - - // The ProtoKey this class inherits from. - JSProtoKey inheritanceProtoKey() const { - MOZ_ASSERT(defined()); - static_assert(JSProto_Null == 0, "zeroed key must be null"); - - // Default: Inherit from Object. - if (!(flags & ProtoKeyMask)) - return JSProto_Object; - - return JSProtoKey(flags & ProtoKeyMask); - } - - bool shouldDefineConstructor() const { - MOZ_ASSERT(defined()); - return !(flags & DontDefineConstructor); - } - - const ClassSpec* delegatedClassSpec() const { - MOZ_ASSERT(delegated()); - return reinterpret_cast(createConstructor_); - } - - ClassObjectCreationOp createConstructorHook() const { - if (delegated()) - return delegatedClassSpec()->createConstructorHook(); - return createConstructor_; - } - ClassObjectCreationOp createPrototypeHook() const { - if (delegated()) - return delegatedClassSpec()->createPrototypeHook(); - return createPrototype_; - } - const JSFunctionSpec* constructorFunctions() const { - if (delegated()) - return delegatedClassSpec()->constructorFunctions(); - return constructorFunctions_; - } - const JSPropertySpec* constructorProperties() const { - if (delegated()) - return delegatedClassSpec()->constructorProperties(); - return constructorProperties_; - } - const JSFunctionSpec* prototypeFunctions() const { - if (delegated()) - return delegatedClassSpec()->prototypeFunctions(); - return prototypeFunctions_; - } - const JSPropertySpec* prototypeProperties() const { - if (delegated()) - return delegatedClassSpec()->prototypeProperties(); - return prototypeProperties_; - } - FinishClassInitOp finishInitHook() const { - if (delegated()) - return delegatedClassSpec()->finishInitHook(); - return finishInit_; - } -}; - -struct ClassExtension -{ - /** - * If an object is used as a key in a weakmap, it may be desirable for the - * garbage collector to keep that object around longer than it otherwise - * would. A common case is when the key is a wrapper around an object in - * another compartment, and we want to avoid collecting the wrapper (and - * removing the weakmap entry) as long as the wrapped object is alive. In - * that case, the wrapped object is returned by the wrapper's - * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap - * key, it will not be collected (and remain in the weakmap) until the - * wrapped object is collected. - */ - JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; - - /** - * Optional hook called when an object is moved by a compacting GC. - * - * There may exist weak pointers to an object that are not traced through - * when the normal trace APIs are used, for example objects in the wrapper - * cache. This hook allows these pointers to be updated. - * - * Note that this hook can be called before JS_NewObject() returns if a GC - * is triggered during construction of the object. This can happen for - * global objects for example. - */ - JSObjectMovedOp objectMovedOp; -}; - -inline ClassObjectCreationOp DELEGATED_CLASSSPEC(const ClassSpec* spec) { - return reinterpret_cast(const_cast(spec)); -} - -#define JS_NULL_CLASS_SPEC nullptr -#define JS_NULL_CLASS_EXT nullptr - -struct ObjectOps -{ - LookupPropertyOp lookupProperty; - DefinePropertyOp defineProperty; - HasPropertyOp hasProperty; - GetPropertyOp getProperty; - SetPropertyOp setProperty; - GetOwnPropertyOp getOwnPropertyDescriptor; - DeletePropertyOp deleteProperty; - WatchOp watch; - UnwatchOp unwatch; - GetElementsOp getElements; - JSNewEnumerateOp enumerate; - JSFunToStringOp funToString; -}; - -#define JS_NULL_OBJECT_OPS nullptr - -} // namespace js - -// Classes, objects, and properties. - -typedef void (*JSClassInternal)(); - -struct JSClassOps -{ - /* Function pointer members (may be null). */ - JSAddPropertyOp addProperty; - JSDeletePropertyOp delProperty; - JSGetterOp getProperty; - JSSetterOp setProperty; - JSEnumerateOp enumerate; - JSResolveOp resolve; - JSMayResolveOp mayResolve; - JSFinalizeOp finalize; - JSNative call; - JSHasInstanceOp hasInstance; - JSNative construct; - JSTraceOp trace; -}; - -#define JS_NULL_CLASS_OPS nullptr - -struct JSClass { - JS_CLASS_MEMBERS(JSClassOps, JSFreeOp); - - void* reserved[3]; -}; - -#define JSCLASS_HAS_PRIVATE (1<<0) // objects have private slot -#define JSCLASS_DELAY_METADATA_BUILDER (1<<1) // class's initialization code - // will call - // SetNewObjectMetadata itself -#define JSCLASS_IS_WRAPPED_NATIVE (1<<2) // class is an XPCWrappedNative. - // WeakMaps use this to override - // the wrapper disposal - // mechanism. -#define JSCLASS_PRIVATE_IS_NSISUPPORTS (1<<3) // private is (nsISupports*) -#define JSCLASS_IS_DOMJSCLASS (1<<4) // objects are DOM -#define JSCLASS_HAS_XRAYED_CONSTRUCTOR (1<<5) // if wrapped by an xray - // wrapper, the builtin - // class's constructor won't - // be unwrapped and invoked. - // Instead, the constructor is - // resolved in the caller's - // compartment and invoked - // with a wrapped newTarget. - // The constructor has to - // detect and handle this - // situation. - // See PromiseConstructor for - // details. -#define JSCLASS_EMULATES_UNDEFINED (1<<6) // objects of this class act - // like the value undefined, - // in some contexts -#define JSCLASS_USERBIT1 (1<<7) // Reserved for embeddings. - -// To reserve slots fetched and stored via JS_Get/SetReservedSlot, bitwise-or -// JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where -// n is a constant in [1, 255]. Reserved slots are indexed from 0 to n-1. -#define JSCLASS_RESERVED_SLOTS_SHIFT 8 // room for 8 flags below */ -#define JSCLASS_RESERVED_SLOTS_WIDTH 8 // and 16 above this field */ -#define JSCLASS_RESERVED_SLOTS_MASK JS_BITMASK(JSCLASS_RESERVED_SLOTS_WIDTH) -#define JSCLASS_HAS_RESERVED_SLOTS(n) (((n) & JSCLASS_RESERVED_SLOTS_MASK) \ - << JSCLASS_RESERVED_SLOTS_SHIFT) -#define JSCLASS_RESERVED_SLOTS(clasp) (((clasp)->flags \ - >> JSCLASS_RESERVED_SLOTS_SHIFT) \ - & JSCLASS_RESERVED_SLOTS_MASK) - -#define JSCLASS_HIGH_FLAGS_SHIFT (JSCLASS_RESERVED_SLOTS_SHIFT + \ - JSCLASS_RESERVED_SLOTS_WIDTH) - -#define JSCLASS_IS_ANONYMOUS (1<<(JSCLASS_HIGH_FLAGS_SHIFT+0)) -#define JSCLASS_IS_GLOBAL (1<<(JSCLASS_HIGH_FLAGS_SHIFT+1)) -#define JSCLASS_INTERNAL_FLAG2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+2)) -#define JSCLASS_INTERNAL_FLAG3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+3)) - -#define JSCLASS_IS_PROXY (1<<(JSCLASS_HIGH_FLAGS_SHIFT+4)) - -#define JSCLASS_SKIP_NURSERY_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+5)) - -// Reserved for embeddings. -#define JSCLASS_USERBIT2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+6)) -#define JSCLASS_USERBIT3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+7)) - -#define JSCLASS_BACKGROUND_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+8)) -#define JSCLASS_FOREGROUND_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+9)) - -// Bits 26 through 31 are reserved for the CACHED_PROTO_KEY mechanism, see -// below. - -// ECMA-262 requires that most constructors used internally create objects -// with "the original Foo.prototype value" as their [[Prototype]] (__proto__) -// member initial value. The "original ... value" verbiage is there because -// in ECMA-262, global properties naming class objects are read/write and -// deleteable, for the most part. -// -// Implementing this efficiently requires that global objects have classes -// with the following flags. Failure to use JSCLASS_GLOBAL_FLAGS was -// previously allowed, but is now an ES5 violation and thus unsupported. -// -// JSCLASS_GLOBAL_APPLICATION_SLOTS is the number of slots reserved at -// the beginning of every global object's slots for use by the -// application. -#define JSCLASS_GLOBAL_APPLICATION_SLOTS 5 -#define JSCLASS_GLOBAL_SLOT_COUNT \ - (JSCLASS_GLOBAL_APPLICATION_SLOTS + JSProto_LIMIT * 2 + 39) -#define JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(n) \ - (JSCLASS_IS_GLOBAL | JSCLASS_HAS_RESERVED_SLOTS(JSCLASS_GLOBAL_SLOT_COUNT + (n))) -#define JSCLASS_GLOBAL_FLAGS \ - JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(0) -#define JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(clasp) \ - (((clasp)->flags & JSCLASS_IS_GLOBAL) \ - && JSCLASS_RESERVED_SLOTS(clasp) >= JSCLASS_GLOBAL_SLOT_COUNT) - -// Fast access to the original value of each standard class's prototype. -#define JSCLASS_CACHED_PROTO_SHIFT (JSCLASS_HIGH_FLAGS_SHIFT + 10) -#define JSCLASS_CACHED_PROTO_MASK JS_BITMASK(js::JSCLASS_CACHED_PROTO_WIDTH) -#define JSCLASS_HAS_CACHED_PROTO(key) (uint32_t(key) << JSCLASS_CACHED_PROTO_SHIFT) -#define JSCLASS_CACHED_PROTO_KEY(clasp) ((JSProtoKey) \ - (((clasp)->flags \ - >> JSCLASS_CACHED_PROTO_SHIFT) \ - & JSCLASS_CACHED_PROTO_MASK)) - -// Initializer for unused members of statically initialized JSClass structs. -#define JSCLASS_NO_INTERNAL_MEMBERS {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} -#define JSCLASS_NO_OPTIONAL_MEMBERS 0,0,0,0,0,JSCLASS_NO_INTERNAL_MEMBERS - -namespace js { - -struct Class -{ - JS_CLASS_MEMBERS(js::ClassOps, FreeOp); - const ClassSpec* spec; - const ClassExtension* ext; - const ObjectOps* oOps; - - /* - * Objects of this class aren't native objects. They don't have Shapes that - * describe their properties and layout. Classes using this flag must - * provide their own property behavior, either by being proxy classes (do - * this) or by overriding all the ObjectOps except getElements, watch and - * unwatch (don't do this). - */ - static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; - - bool isNative() const { - return !(flags & NON_NATIVE); - } - - bool hasPrivate() const { - return !!(flags & JSCLASS_HAS_PRIVATE); - } - - bool emulatesUndefined() const { - return flags & JSCLASS_EMULATES_UNDEFINED; - } - - bool isJSFunction() const { - return this == js::FunctionClassPtr; - } - - bool nonProxyCallable() const { - MOZ_ASSERT(!isProxy()); - return isJSFunction() || getCall(); - } - - bool isProxy() const { - return flags & JSCLASS_IS_PROXY; - } - - bool isDOMClass() const { - return flags & JSCLASS_IS_DOMJSCLASS; - } - - bool shouldDelayMetadataBuilder() const { - return flags & JSCLASS_DELAY_METADATA_BUILDER; - } - - bool isWrappedNative() const { - return flags & JSCLASS_IS_WRAPPED_NATIVE; - } - - static size_t offsetOfFlags() { return offsetof(Class, flags); } - - bool specDefined() const { return spec ? spec->defined() : false; } - JSProtoKey specInheritanceProtoKey() - const { return spec ? spec->inheritanceProtoKey() : JSProto_Null; } - bool specShouldDefineConstructor() - const { return spec ? spec->shouldDefineConstructor() : true; } - ClassObjectCreationOp specCreateConstructorHook() - const { return spec ? spec->createConstructorHook() : nullptr; } - ClassObjectCreationOp specCreatePrototypeHook() - const { return spec ? spec->createPrototypeHook() : nullptr; } - const JSFunctionSpec* specConstructorFunctions() - const { return spec ? spec->constructorFunctions() : nullptr; } - const JSPropertySpec* specConstructorProperties() - const { return spec ? spec->constructorProperties() : nullptr; } - const JSFunctionSpec* specPrototypeFunctions() - const { return spec ? spec->prototypeFunctions() : nullptr; } - const JSPropertySpec* specPrototypeProperties() - const { return spec ? spec->prototypeProperties() : nullptr; } - FinishClassInitOp specFinishInitHook() - const { return spec ? spec->finishInitHook() : nullptr; } - - JSWeakmapKeyDelegateOp extWeakmapKeyDelegateOp() - const { return ext ? ext->weakmapKeyDelegateOp : nullptr; } - JSObjectMovedOp extObjectMovedOp() - const { return ext ? ext->objectMovedOp : nullptr; } - - LookupPropertyOp getOpsLookupProperty() const { return oOps ? oOps->lookupProperty : nullptr; } - DefinePropertyOp getOpsDefineProperty() const { return oOps ? oOps->defineProperty : nullptr; } - HasPropertyOp getOpsHasProperty() const { return oOps ? oOps->hasProperty : nullptr; } - GetPropertyOp getOpsGetProperty() const { return oOps ? oOps->getProperty : nullptr; } - SetPropertyOp getOpsSetProperty() const { return oOps ? oOps->setProperty : nullptr; } - GetOwnPropertyOp getOpsGetOwnPropertyDescriptor() - const { return oOps ? oOps->getOwnPropertyDescriptor - : nullptr; } - DeletePropertyOp getOpsDeleteProperty() const { return oOps ? oOps->deleteProperty : nullptr; } - WatchOp getOpsWatch() const { return oOps ? oOps->watch : nullptr; } - UnwatchOp getOpsUnwatch() const { return oOps ? oOps->unwatch : nullptr; } - GetElementsOp getOpsGetElements() const { return oOps ? oOps->getElements : nullptr; } - JSNewEnumerateOp getOpsEnumerate() const { return oOps ? oOps->enumerate : nullptr; } - JSFunToStringOp getOpsFunToString() const { return oOps ? oOps->funToString : nullptr; } -}; - -static_assert(offsetof(JSClassOps, addProperty) == offsetof(ClassOps, addProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, delProperty) == offsetof(ClassOps, delProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, getProperty) == offsetof(ClassOps, getProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, setProperty) == offsetof(ClassOps, setProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, enumerate) == offsetof(ClassOps, enumerate), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, resolve) == offsetof(ClassOps, resolve), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, mayResolve) == offsetof(ClassOps, mayResolve), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, finalize) == offsetof(ClassOps, finalize), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, call) == offsetof(ClassOps, call), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, construct) == offsetof(ClassOps, construct), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, hasInstance) == offsetof(ClassOps, hasInstance), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, trace) == offsetof(ClassOps, trace), - "ClassOps and JSClassOps must be consistent"); -static_assert(sizeof(JSClassOps) == sizeof(ClassOps), - "ClassOps and JSClassOps must be consistent"); - -static_assert(offsetof(JSClass, name) == offsetof(Class, name), - "Class and JSClass must be consistent"); -static_assert(offsetof(JSClass, flags) == offsetof(Class, flags), - "Class and JSClass must be consistent"); -static_assert(offsetof(JSClass, cOps) == offsetof(Class, cOps), - "Class and JSClass must be consistent"); -static_assert(sizeof(JSClass) == sizeof(Class), - "Class and JSClass must be consistent"); - -static MOZ_ALWAYS_INLINE const JSClass* -Jsvalify(const Class* c) -{ - return (const JSClass*)c; -} - -static MOZ_ALWAYS_INLINE const Class* -Valueify(const JSClass* c) -{ - return (const Class*)c; -} - -/** - * Enumeration describing possible values of the [[Class]] internal property - * value of objects. - */ -enum class ESClass { - Object, - Array, - Number, - String, - Boolean, - RegExp, - ArrayBuffer, - SharedArrayBuffer, - Date, - Set, - Map, - Promise, - MapIterator, - SetIterator, - Arguments, - Error, - - /** None of the above. */ - Other -}; - -/* Fills |vp| with the unboxed value for boxed types, or undefined otherwise. */ -bool -Unbox(JSContext* cx, JS::HandleObject obj, JS::MutableHandleValue vp); - -#ifdef DEBUG -JS_FRIEND_API(bool) -HasObjectMovedOp(JSObject* obj); -#endif - -} /* namespace js */ - -#endif /* js_Class_h */ diff --git a/ios/include/spidermonkey/js/Conversions.h b/ios/include/spidermonkey/js/Conversions.h deleted file mode 100644 index 1cee31c5..00000000 --- a/ios/include/spidermonkey/js/Conversions.h +++ /dev/null @@ -1,581 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* ECMAScript conversion operations. */ - -#ifndef js_Conversions_h -#define js_Conversions_h - -#include "mozilla/Casting.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/TypeTraits.h" - -#include - -#include "jspubtd.h" - -#include "js/RootingAPI.h" -#include "js/Value.h" - -struct JSContext; - -namespace js { - -/* DO NOT CALL THIS. Use JS::ToBoolean. */ -extern JS_PUBLIC_API(bool) -ToBooleanSlow(JS::HandleValue v); - -/* DO NOT CALL THIS. Use JS::ToNumber. */ -extern JS_PUBLIC_API(bool) -ToNumberSlow(JSContext* cx, JS::HandleValue v, double* dp); - -/* DO NOT CALL THIS. Use JS::ToInt8. */ -extern JS_PUBLIC_API(bool) -ToInt8Slow(JSContext *cx, JS::HandleValue v, int8_t *out); - -/* DO NOT CALL THIS. Use JS::ToUint8. */ -extern JS_PUBLIC_API(bool) -ToUint8Slow(JSContext *cx, JS::HandleValue v, uint8_t *out); - -/* DO NOT CALL THIS. Use JS::ToInt16. */ -extern JS_PUBLIC_API(bool) -ToInt16Slow(JSContext *cx, JS::HandleValue v, int16_t *out); - -/* DO NOT CALL THIS. Use JS::ToInt32. */ -extern JS_PUBLIC_API(bool) -ToInt32Slow(JSContext* cx, JS::HandleValue v, int32_t* out); - -/* DO NOT CALL THIS. Use JS::ToUint32. */ -extern JS_PUBLIC_API(bool) -ToUint32Slow(JSContext* cx, JS::HandleValue v, uint32_t* out); - -/* DO NOT CALL THIS. Use JS::ToUint16. */ -extern JS_PUBLIC_API(bool) -ToUint16Slow(JSContext* cx, JS::HandleValue v, uint16_t* out); - -/* DO NOT CALL THIS. Use JS::ToInt64. */ -extern JS_PUBLIC_API(bool) -ToInt64Slow(JSContext* cx, JS::HandleValue v, int64_t* out); - -/* DO NOT CALL THIS. Use JS::ToUint64. */ -extern JS_PUBLIC_API(bool) -ToUint64Slow(JSContext* cx, JS::HandleValue v, uint64_t* out); - -/* DO NOT CALL THIS. Use JS::ToString. */ -extern JS_PUBLIC_API(JSString*) -ToStringSlow(JSContext* cx, JS::HandleValue v); - -/* DO NOT CALL THIS. Use JS::ToObject. */ -extern JS_PUBLIC_API(JSObject*) -ToObjectSlow(JSContext* cx, JS::HandleValue v, bool reportScanStack); - -} // namespace js - -namespace JS { - -namespace detail { - -#ifdef JS_DEBUG -/** - * Assert that we're not doing GC on cx, that we're in a request as - * needed, and that the compartments for cx and v are correct. - * Also check that GC would be safe at this point. - */ -extern JS_PUBLIC_API(void) -AssertArgumentsAreSane(JSContext* cx, HandleValue v); -#else -inline void AssertArgumentsAreSane(JSContext* cx, HandleValue v) -{} -#endif /* JS_DEBUG */ - -} // namespace detail - -/** - * ES6 draft 20141224, 7.1.1, second algorithm. - * - * Most users shouldn't call this -- use JS::ToBoolean, ToNumber, or ToString - * instead. This will typically only be called from custom convert hooks that - * wish to fall back to the ES6 default conversion behavior shared by most - * objects in JS, codified as OrdinaryToPrimitive. - */ -extern JS_PUBLIC_API(bool) -OrdinaryToPrimitive(JSContext* cx, HandleObject obj, JSType type, MutableHandleValue vp); - -/* ES6 draft 20141224, 7.1.2. */ -MOZ_ALWAYS_INLINE bool -ToBoolean(HandleValue v) -{ - if (v.isBoolean()) - return v.toBoolean(); - if (v.isInt32()) - return v.toInt32() != 0; - if (v.isNullOrUndefined()) - return false; - if (v.isDouble()) { - double d = v.toDouble(); - return !mozilla::IsNaN(d) && d != 0; - } - if (v.isSymbol()) - return true; - - /* The slow path handles strings and objects. */ - return js::ToBooleanSlow(v); -} - -/* ES6 draft 20141224, 7.1.3. */ -MOZ_ALWAYS_INLINE bool -ToNumber(JSContext* cx, HandleValue v, double* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isNumber()) { - *out = v.toNumber(); - return true; - } - return js::ToNumberSlow(cx, v, out); -} - -/* ES6 draft 20141224, ToInteger (specialized for doubles). */ -inline double -ToInteger(double d) -{ - if (d == 0) - return d; - - if (!mozilla::IsFinite(d)) { - if (mozilla::IsNaN(d)) - return 0; - return d; - } - - return d < 0 ? ceil(d) : floor(d); -} - -/* ES6 draft 20141224, 7.1.5. */ -MOZ_ALWAYS_INLINE bool -ToInt32(JSContext* cx, JS::HandleValue v, int32_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = v.toInt32(); - return true; - } - return js::ToInt32Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.6. */ -MOZ_ALWAYS_INLINE bool -ToUint32(JSContext* cx, HandleValue v, uint32_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint32_t(v.toInt32()); - return true; - } - return js::ToUint32Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.7. */ -MOZ_ALWAYS_INLINE bool -ToInt16(JSContext *cx, JS::HandleValue v, int16_t *out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = int16_t(v.toInt32()); - return true; - } - return js::ToInt16Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.8. */ -MOZ_ALWAYS_INLINE bool -ToUint16(JSContext* cx, HandleValue v, uint16_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint16_t(v.toInt32()); - return true; - } - return js::ToUint16Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.9 */ -MOZ_ALWAYS_INLINE bool -ToInt8(JSContext *cx, JS::HandleValue v, int8_t *out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = int8_t(v.toInt32()); - return true; - } - return js::ToInt8Slow(cx, v, out); -} - -/* ES6 ECMA-262, 7.1.10 */ -MOZ_ALWAYS_INLINE bool -ToUint8(JSContext *cx, JS::HandleValue v, uint8_t *out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint8_t(v.toInt32()); - return true; - } - return js::ToUint8Slow(cx, v, out); -} - -/* - * Non-standard, with behavior similar to that of ToInt32, except in its - * producing an int64_t. - */ -MOZ_ALWAYS_INLINE bool -ToInt64(JSContext* cx, HandleValue v, int64_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = int64_t(v.toInt32()); - return true; - } - return js::ToInt64Slow(cx, v, out); -} - -/* - * Non-standard, with behavior similar to that of ToUint32, except in its - * producing a uint64_t. - */ -MOZ_ALWAYS_INLINE bool -ToUint64(JSContext* cx, HandleValue v, uint64_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint64_t(v.toInt32()); - return true; - } - return js::ToUint64Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.12. */ -MOZ_ALWAYS_INLINE JSString* -ToString(JSContext* cx, HandleValue v) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isString()) - return v.toString(); - return js::ToStringSlow(cx, v); -} - -/* ES6 draft 20141224, 7.1.13. */ -inline JSObject* -ToObject(JSContext* cx, HandleValue v) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isObject()) - return &v.toObject(); - return js::ToObjectSlow(cx, v, false); -} - -namespace detail { - -/* - * Convert a double value to ResultType (an unsigned integral type) using - * ECMAScript-style semantics (that is, in like manner to how ECMAScript's - * ToInt32 converts to int32_t). - * - * If d is infinite or NaN, return 0. - * Otherwise compute d2 = sign(d) * floor(abs(d)), and return the ResultType - * value congruent to d2 mod 2**(bit width of ResultType). - * - * The algorithm below is inspired by that found in - * - * but has been generalized to all integer widths. - */ -template -inline ResultType -ToUintWidth(double d) -{ - static_assert(mozilla::IsUnsigned::value, - "ResultType must be an unsigned type"); - - uint64_t bits = mozilla::BitwiseCast(d); - unsigned DoubleExponentShift = mozilla::FloatingPoint::kExponentShift; - - // Extract the exponent component. (Be careful here! It's not technically - // the exponent in NaN, infinities, and subnormals.) - int_fast16_t exp = - int_fast16_t((bits & mozilla::FloatingPoint::kExponentBits) >> DoubleExponentShift) - - int_fast16_t(mozilla::FloatingPoint::kExponentBias); - - // If the exponent's less than zero, abs(d) < 1, so the result is 0. (This - // also handles subnormals.) - if (exp < 0) - return 0; - - uint_fast16_t exponent = mozilla::AssertedCast(exp); - - // If the exponent is greater than or equal to the bits of precision of a - // double plus ResultType's width, the number is either infinite, NaN, or - // too large to have lower-order bits in the congruent value. (Example: - // 2**84 is exactly representable as a double. The next exact double is - // 2**84 + 2**32. Thus if ResultType is int32_t, an exponent >= 84 implies - // floor(abs(d)) == 0 mod 2**32.) Return 0 in all these cases. - const size_t ResultWidth = CHAR_BIT * sizeof(ResultType); - if (exponent >= DoubleExponentShift + ResultWidth) - return 0; - - // The significand contains the bits that will determine the final result. - // Shift those bits left or right, according to the exponent, to their - // locations in the unsigned binary representation of floor(abs(d)). - static_assert(sizeof(ResultType) <= sizeof(uint64_t), - "Left-shifting below would lose upper bits"); - ResultType result = (exponent > DoubleExponentShift) - ? ResultType(bits << (exponent - DoubleExponentShift)) - : ResultType(bits >> (DoubleExponentShift - exponent)); - - // Two further complications remain. First, |result| may contain bogus - // sign/exponent bits. Second, IEEE-754 numbers' significands (excluding - // subnormals, but we already handled those) have an implicit leading 1 - // which may affect the final result. - // - // It may appear that there's complexity here depending on how ResultWidth - // and DoubleExponentShift relate, but it turns out there's not. - // - // Assume ResultWidth < DoubleExponentShift: - // Only right-shifts leave bogus bits in |result|. For this to happen, - // we must right-shift by > |DoubleExponentShift - ResultWidth|, implying - // |exponent < ResultWidth|. - // The implicit leading bit only matters if it appears in the final - // result -- if |2**exponent mod 2**ResultWidth != 0|. This implies - // |exponent < ResultWidth|. - // Otherwise assume ResultWidth >= DoubleExponentShift: - // Any left-shift less than |ResultWidth - DoubleExponentShift| leaves - // bogus bits in |result|. This implies |exponent < ResultWidth|. Any - // right-shift less than |ResultWidth| does too, which implies - // |DoubleExponentShift - ResultWidth < exponent|. By assumption, then, - // |exponent| is negative, but we excluded that above. So bogus bits - // need only |exponent < ResultWidth|. - // The implicit leading bit matters identically to the other case, so - // again, |exponent < ResultWidth|. - if (exponent < ResultWidth) { - ResultType implicitOne = ResultType(1) << exponent; - result &= implicitOne - 1; // remove bogus bits - result += implicitOne; // add the implicit bit - } - - // Compute the congruent value in the signed range. - return (bits & mozilla::FloatingPoint::kSignBit) ? ~result + 1 : result; -} - -template -inline ResultType -ToIntWidth(double d) -{ - static_assert(mozilla::IsSigned::value, - "ResultType must be a signed type"); - - const ResultType MaxValue = (1ULL << (CHAR_BIT * sizeof(ResultType) - 1)) - 1; - const ResultType MinValue = -MaxValue - 1; - - typedef typename mozilla::MakeUnsigned::Type UnsignedResult; - UnsignedResult u = ToUintWidth(d); - if (u <= UnsignedResult(MaxValue)) - return static_cast(u); - return (MinValue + static_cast(u - MaxValue)) - 1; -} - -} // namespace detail - -/* ES5 9.5 ToInt32 (specialized for doubles). */ -inline int32_t -ToInt32(double d) -{ - // clang crashes compiling this when targeting arm: - // https://llvm.org/bugs/show_bug.cgi?id=22974 -#if defined (__arm__) && defined (__GNUC__) && !defined(__clang__) - int32_t i; - uint32_t tmp0; - uint32_t tmp1; - uint32_t tmp2; - asm ( - // We use a pure integer solution here. In the 'softfp' ABI, the argument - // will start in r0 and r1, and VFP can't do all of the necessary ECMA - // conversions by itself so some integer code will be required anyway. A - // hybrid solution is faster on A9, but this pure integer solution is - // notably faster for A8. - - // %0 is the result register, and may alias either of the %[QR]1 registers. - // %Q4 holds the lower part of the mantissa. - // %R4 holds the sign, exponent, and the upper part of the mantissa. - // %1, %2 and %3 are used as temporary values. - - // Extract the exponent. -" mov %1, %R4, LSR #20\n" -" bic %1, %1, #(1 << 11)\n" // Clear the sign. - - // Set the implicit top bit of the mantissa. This clobbers a bit of the - // exponent, but we have already extracted that. -" orr %R4, %R4, #(1 << 20)\n" - - // Special Cases - // We should return zero in the following special cases: - // - Exponent is 0x000 - 1023: +/-0 or subnormal. - // - Exponent is 0x7ff - 1023: +/-INFINITY or NaN - // - This case is implicitly handled by the standard code path anyway, - // as shifting the mantissa up by the exponent will result in '0'. - // - // The result is composed of the mantissa, prepended with '1' and - // bit-shifted left by the (decoded) exponent. Note that because the r1[20] - // is the bit with value '1', r1 is effectively already shifted (left) by - // 20 bits, and r0 is already shifted by 52 bits. - - // Adjust the exponent to remove the encoding offset. If the decoded - // exponent is negative, quickly bail out with '0' as such values round to - // zero anyway. This also catches +/-0 and subnormals. -" sub %1, %1, #0xff\n" -" subs %1, %1, #0x300\n" -" bmi 8f\n" - - // %1 = (decoded) exponent >= 0 - // %R4 = upper mantissa and sign - - // ---- Lower Mantissa ---- -" subs %3, %1, #52\n" // Calculate exp-52 -" bmi 1f\n" - - // Shift r0 left by exp-52. - // Ensure that we don't overflow ARM's 8-bit shift operand range. - // We need to handle anything up to an 11-bit value here as we know that - // 52 <= exp <= 1024 (0x400). Any shift beyond 31 bits results in zero - // anyway, so as long as we don't touch the bottom 5 bits, we can use - // a logical OR to push long shifts into the 32 <= (exp&0xff) <= 255 range. -" bic %2, %3, #0xff\n" -" orr %3, %3, %2, LSR #3\n" - // We can now perform a straight shift, avoiding the need for any - // conditional instructions or extra branches. -" mov %Q4, %Q4, LSL %3\n" -" b 2f\n" -"1:\n" // Shift r0 right by 52-exp. - // We know that 0 <= exp < 52, and we can shift up to 255 bits so 52-exp - // will always be a valid shift and we can sk%3 the range check for this case. -" rsb %3, %1, #52\n" -" mov %Q4, %Q4, LSR %3\n" - - // %1 = (decoded) exponent - // %R4 = upper mantissa and sign - // %Q4 = partially-converted integer - -"2:\n" - // ---- Upper Mantissa ---- - // This is much the same as the lower mantissa, with a few different - // boundary checks and some masking to hide the exponent & sign bit in the - // upper word. - // Note that the upper mantissa is pre-shifted by 20 in %R4, but we shift - // it left more to remove the sign and exponent so it is effectively - // pre-shifted by 31 bits. -" subs %3, %1, #31\n" // Calculate exp-31 -" mov %1, %R4, LSL #11\n" // Re-use %1 as a temporary register. -" bmi 3f\n" - - // Shift %R4 left by exp-31. - // Avoid overflowing the 8-bit shift range, as before. -" bic %2, %3, #0xff\n" -" orr %3, %3, %2, LSR #3\n" - // Perform the shift. -" mov %2, %1, LSL %3\n" -" b 4f\n" -"3:\n" // Shift r1 right by 31-exp. - // We know that 0 <= exp < 31, and we can shift up to 255 bits so 31-exp - // will always be a valid shift and we can skip the range check for this case. -" rsb %3, %3, #0\n" // Calculate 31-exp from -(exp-31) -" mov %2, %1, LSR %3\n" // Thumb-2 can't do "LSR %3" in "orr". - - // %Q4 = partially-converted integer (lower) - // %R4 = upper mantissa and sign - // %2 = partially-converted integer (upper) - -"4:\n" - // Combine the converted parts. -" orr %Q4, %Q4, %2\n" - // Negate the result if we have to, and move it to %0 in the process. To - // avoid conditionals, we can do this by inverting on %R4[31], then adding - // %R4[31]>>31. -" eor %Q4, %Q4, %R4, ASR #31\n" -" add %0, %Q4, %R4, LSR #31\n" -" b 9f\n" -"8:\n" - // +/-INFINITY, +/-0, subnormals, NaNs, and anything else out-of-range that - // will result in a conversion of '0'. -" mov %0, #0\n" -"9:\n" - : "=r" (i), "=&r" (tmp0), "=&r" (tmp1), "=&r" (tmp2), "=&r" (d) - : "4" (d) - : "cc" - ); - return i; -#else - return detail::ToIntWidth(d); -#endif -} - -/* ES5 9.6 (specialized for doubles). */ -inline uint32_t -ToUint32(double d) -{ - return detail::ToUintWidth(d); -} - -/* WEBIDL 4.2.4 */ -inline int8_t -ToInt8(double d) -{ - return detail::ToIntWidth(d); -} - -/* ECMA-262 7.1.10 ToUInt8() specialized for doubles. */ -inline int8_t -ToUint8(double d) -{ - return detail::ToUintWidth(d); -} - -/* WEBIDL 4.2.6 */ -inline int16_t -ToInt16(double d) -{ - return detail::ToIntWidth(d); -} - -inline uint16_t -ToUint16(double d) -{ - return detail::ToUintWidth(d); -} - -/* WEBIDL 4.2.10 */ -inline int64_t -ToInt64(double d) -{ - return detail::ToIntWidth(d); -} - -/* WEBIDL 4.2.11 */ -inline uint64_t -ToUint64(double d) -{ - return detail::ToUintWidth(d); -} - -} // namespace JS - -#endif /* js_Conversions_h */ diff --git a/ios/include/spidermonkey/js/Date.h b/ios/include/spidermonkey/js/Date.h deleted file mode 100644 index cba0ea87..00000000 --- a/ios/include/spidermonkey/js/Date.h +++ /dev/null @@ -1,170 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JavaScript date/time computation and creation functions. */ - -#ifndef js_Date_h -#define js_Date_h - -/* - * Dates in JavaScript are defined by IEEE-754 double precision numbers from - * the set: - * - * { t ∈ ℕ : -8.64e15 ≤ t ≤ +8.64e15 } ∪ { NaN } - * - * The single NaN value represents any invalid-date value. All other values - * represent idealized durations in milliseconds since the UTC epoch. (Leap - * seconds are ignored; leap days are not.) +0 is the only zero in this set. - * The limit represented by 8.64e15 milliseconds is 100 million days either - * side of 00:00 January 1, 1970 UTC. - * - * Dates in the above set are represented by the |ClippedTime| class. The - * double type is a superset of the above set, so it *may* (but need not) - * represent a date. Use ECMAScript's |TimeClip| method to produce a date from - * a double. - * - * Date *objects* are simply wrappers around |TimeClip|'d numbers, with a bunch - * of accessor methods to the various aspects of the represented date. - */ - -#include "mozilla/FloatingPoint.h" -#include "mozilla/MathAlgorithms.h" - -#include "js/Conversions.h" -#include "js/Value.h" - -struct JSContext; - -namespace JS { - -/** - * Re-query the system to determine the current time zone adjustment from UTC, - * including any component due to DST. If the time zone has changed, this will - * cause all Date object non-UTC methods and formatting functions to produce - * appropriately adjusted results. - * - * Left to its own devices, SpiderMonkey itself may occasionally call this - * method to attempt to keep up with system time changes. However, no - * particular frequency of checking is guaranteed. Embedders unable to accept - * occasional inaccuracies should call this method in response to system time - * changes, or immediately before operations requiring instantaneous - * correctness, to guarantee correct behavior. - */ -extern JS_PUBLIC_API(void) -ResetTimeZone(); - -class ClippedTime; -inline ClippedTime TimeClip(double time); - -/* - * |ClippedTime| represents the limited subset of dates/times described above. - * - * An invalid date/time may be created through the |ClippedTime::invalid| - * method. Otherwise, a |ClippedTime| may be created using the |TimeClip| - * method. - * - * In typical use, the user might wish to manipulate a timestamp. The user - * performs a series of operations on it, but the final value might not be a - * date as defined above -- it could have overflowed, acquired a fractional - * component, &c. So as a *final* step, the user passes that value through - * |TimeClip| to produce a number restricted to JavaScript's date range. - * - * APIs that accept a JavaScript date value thus accept a |ClippedTime|, not a - * double. This ensures that date/time APIs will only ever receive acceptable - * JavaScript dates. This also forces users to perform any desired clipping, - * as only the user knows what behavior is desired when clipping occurs. - */ -class ClippedTime -{ - double t; - - explicit ClippedTime(double time) : t(time) {} - friend ClippedTime TimeClip(double time); - - public: - // Create an invalid date. - ClippedTime() : t(mozilla::UnspecifiedNaN()) {} - - // Create an invalid date/time, more explicitly; prefer this to the default - // constructor. - static ClippedTime invalid() { return ClippedTime(); } - - double toDouble() const { return t; } - - bool isValid() const { return !mozilla::IsNaN(t); } -}; - -// ES6 20.3.1.15. -// -// Clip a double to JavaScript's date range (or to an invalid date) using the -// ECMAScript TimeClip algorithm. -inline ClippedTime -TimeClip(double time) -{ - // Steps 1-2. - const double MaxTimeMagnitude = 8.64e15; - if (!mozilla::IsFinite(time) || mozilla::Abs(time) > MaxTimeMagnitude) - return ClippedTime(mozilla::UnspecifiedNaN()); - - // Step 3. - return ClippedTime(ToInteger(time) + (+0.0)); -} - -// Produce a double Value from the given time. Because times may be NaN, -// prefer using this to manual canonicalization. -inline Value -TimeValue(ClippedTime time) -{ - return DoubleValue(JS::CanonicalizeNaN(time.toDouble())); -} - -// Create a new Date object whose [[DateValue]] internal slot contains the -// clipped |time|. (Users who must represent times outside that range must use -// another representation.) -extern JS_PUBLIC_API(JSObject*) -NewDateObject(JSContext* cx, ClippedTime time); - -// Year is a year, month is 0-11, day is 1-based. The return value is a number -// of milliseconds since the epoch. -// -// Consistent with the MakeDate algorithm defined in ECMAScript, this value is -// *not* clipped! Use JS::TimeClip if you need a clipped date. -JS_PUBLIC_API(double) -MakeDate(double year, unsigned month, unsigned day); - -// Takes an integer number of milliseconds since the epoch and returns the -// year. Can return NaN, and will do so if NaN is passed in. -JS_PUBLIC_API(double) -YearFromTime(double time); - -// Takes an integer number of milliseconds since the epoch and returns the -// month (0-11). Can return NaN, and will do so if NaN is passed in. -JS_PUBLIC_API(double) -MonthFromTime(double time); - -// Takes an integer number of milliseconds since the epoch and returns the -// day (1-based). Can return NaN, and will do so if NaN is passed in. -JS_PUBLIC_API(double) -DayFromTime(double time); - -// Takes an integer year and returns the number of days from epoch to the given -// year. -// NOTE: The calculation performed by this function is literally that given in -// the ECMAScript specification. Nonfinite years, years containing fractional -// components, and years outside ECMAScript's date range are not handled with -// any particular intelligence. Garbage in, garbage out. -JS_PUBLIC_API(double) -DayFromYear(double year); - -// Takes an integer number of milliseconds since the epoch and an integer year, -// returns the number of days in that year. If |time| is nonfinite, returns NaN. -// Otherwise |time| *must* correspond to a time within the valid year |year|. -// This should usually be ensured by computing |year| as |JS::DayFromYear(time)|. -JS_PUBLIC_API(double) -DayWithinYear(double time, double year); - -} // namespace JS - -#endif /* js_Date_h */ diff --git a/ios/include/spidermonkey/js/Debug.h b/ios/include/spidermonkey/js/Debug.h deleted file mode 100644 index 3e4183f0..00000000 --- a/ios/include/spidermonkey/js/Debug.h +++ /dev/null @@ -1,384 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// Interfaces by which the embedding can interact with the Debugger API. - -#ifndef js_Debug_h -#define js_Debug_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/MemoryReporting.h" - -#include "jsapi.h" -#include "jspubtd.h" - -#include "js/GCAPI.h" -#include "js/RootingAPI.h" -#include "js/TypeDecls.h" - -namespace js { -class Debugger; -} // namespace js - -namespace JS { -namespace dbg { - -// Helping embedding code build objects for Debugger -// ------------------------------------------------- -// -// Some Debugger API features lean on the embedding application to construct -// their result values. For example, Debugger.Frame.prototype.scriptEntryReason -// calls hooks provided by the embedding to construct values explaining why it -// invoked JavaScript; if F is a frame called from a mouse click event handler, -// F.scriptEntryReason would return an object of the form: -// -// { eventType: "mousedown", event: } -// -// where is a Debugger.Object whose referent is the event being -// dispatched. -// -// However, Debugger implements a trust boundary. Debuggee code may be -// considered untrusted; debugger code needs to be protected from debuggee -// getters, setters, proxies, Object.watch watchpoints, and any other feature -// that might accidentally cause debugger code to set the debuggee running. The -// Debugger API tries to make it easy to write safe debugger code by only -// offering access to debuggee objects via Debugger.Object instances, which -// ensure that only those operations whose explicit purpose is to invoke -// debuggee code do so. But this protective membrane is only helpful if we -// interpose Debugger.Object instances in all the necessary spots. -// -// SpiderMonkey's compartment system also implements a trust boundary. The -// debuggee and debugger are always in different compartments. Inter-compartment -// work requires carefully tracking which compartment each JSObject or JS::Value -// belongs to, and ensuring that is is correctly wrapped for each operation. -// -// It seems precarious to expect the embedding's hooks to implement these trust -// boundaries. Instead, the JS::dbg::Builder API segregates the code which -// constructs trusted objects from that which deals with untrusted objects. -// Trusted objects have an entirely different C++ type, so code that improperly -// mixes trusted and untrusted objects is caught at compile time. -// -// In the structure shown above, there are two trusted objects, and one -// untrusted object: -// -// - The overall object, with the 'eventType' and 'event' properties, is a -// trusted object. We're going to return it to D.F.p.scriptEntryReason's -// caller, which will handle it directly. -// -// - The Debugger.Object instance appearing as the value of the 'event' property -// is a trusted object. It belongs to the same Debugger instance as the -// Debugger.Frame instance whose scriptEntryReason accessor was called, and -// presents a safe reflection-oriented API for inspecting its referent, which -// is: -// -// - The actual event object, an untrusted object, and the referent of the -// Debugger.Object above. (Content can do things like replacing accessors on -// Event.prototype.) -// -// Using JS::dbg::Builder, all objects and values the embedding deals with -// directly are considered untrusted, and are assumed to be debuggee values. The -// only way to construct trusted objects is to use Builder's own methods, which -// return a separate Object type. The only way to set a property on a trusted -// object is through that Object type. The actual trusted object is never -// exposed to the embedding. -// -// So, for example, the embedding might use code like the following to construct -// the object shown above, given a Builder passed to it by Debugger: -// -// bool -// MyScriptEntryReason::explain(JSContext* cx, -// Builder& builder, -// Builder::Object& result) -// { -// JSObject* eventObject = ... obtain debuggee event object somehow ...; -// if (!eventObject) -// return false; -// result = builder.newObject(cx); -// return result && -// result.defineProperty(cx, "eventType", SafelyFetchType(eventObject)) && -// result.defineProperty(cx, "event", eventObject); -// } -// -// -// Object::defineProperty also accepts an Object as the value to store on the -// property. By its type, we know that the value is trusted, so we set it -// directly as the property's value, without interposing a Debugger.Object -// wrapper. This allows the embedding to builted nested structures of trusted -// objects. -// -// The Builder and Builder::Object methods take care of doing whatever -// compartment switching and wrapping are necessary to construct the trusted -// values in the Debugger's compartment. -// -// The Object type is self-rooting. Construction, assignment, and destruction -// all properly root the referent object. - -class BuilderOrigin; - -class Builder { - // The Debugger instance whose client we are building a value for. We build - // objects in this object's compartment. - PersistentRootedObject debuggerObject; - - // debuggerObject's Debugger structure, for convenience. - js::Debugger* debugger; - - // Check that |thing| is in the same compartment as our debuggerObject. Used - // for assertions when constructing BuiltThings. We can overload this as we - // add more instantiations of BuiltThing. -#if DEBUG - void assertBuilt(JSObject* obj); -#else - void assertBuilt(JSObject* obj) { } -#endif - - protected: - // A reference to a trusted object or value. At the moment, we only use it - // with JSObject*. - template - class BuiltThing { - friend class BuilderOrigin; - - protected: - // The Builder to which this trusted thing belongs. - Builder& owner; - - // A rooted reference to our value. - PersistentRooted value; - - BuiltThing(JSContext* cx, Builder& owner_, T value_ = GCPolicy::initial()) - : owner(owner_), value(cx, value_) - { - owner.assertBuilt(value_); - } - - // Forward some things from our owner, for convenience. - js::Debugger* debugger() const { return owner.debugger; } - JSObject* debuggerObject() const { return owner.debuggerObject; } - - public: - BuiltThing(const BuiltThing& rhs) : owner(rhs.owner), value(rhs.value) { } - BuiltThing& operator=(const BuiltThing& rhs) { - MOZ_ASSERT(&owner == &rhs.owner); - owner.assertBuilt(rhs.value); - value = rhs.value; - return *this; - } - - explicit operator bool() const { - // If we ever instantiate BuiltThing, this might not suffice. - return value; - } - - private: - BuiltThing() = delete; - }; - - public: - // A reference to a trusted object, possibly null. Instances of Object are - // always properly rooted. They can be copied and assigned, as if they were - // pointers. - class Object: private BuiltThing { - friend class Builder; // for construction - friend class BuilderOrigin; // for unwrapping - - typedef BuiltThing Base; - - // This is private, because only Builders can create Objects that - // actually point to something (hence the 'friend' declaration). - Object(JSContext* cx, Builder& owner_, HandleObject obj) : Base(cx, owner_, obj.get()) { } - - bool definePropertyToTrusted(JSContext* cx, const char* name, - JS::MutableHandleValue value); - - public: - Object(JSContext* cx, Builder& owner_) : Base(cx, owner_, nullptr) { } - Object(const Object& rhs) : Base(rhs) { } - - // Our automatically-generated assignment operator can see our base - // class's assignment operator, so we don't need to write one out here. - - // Set the property named |name| on this object to |value|. - // - // If |value| is a string or primitive, re-wrap it for the debugger's - // compartment. - // - // If |value| is an object, assume it is a debuggee object and make a - // Debugger.Object instance referring to it. Set that as the propery's - // value. - // - // If |value| is another trusted object, store it directly as the - // property's value. - // - // On error, report the problem on cx and return false. - bool defineProperty(JSContext* cx, const char* name, JS::HandleValue value); - bool defineProperty(JSContext* cx, const char* name, JS::HandleObject value); - bool defineProperty(JSContext* cx, const char* name, Object& value); - - using Base::operator bool; - }; - - // Build an empty object for direct use by debugger code, owned by this - // Builder. If an error occurs, report it on cx and return a false Object. - Object newObject(JSContext* cx); - - protected: - Builder(JSContext* cx, js::Debugger* debugger); -}; - -// Debugger itself instantiates this subclass of Builder, which can unwrap -// BuiltThings that belong to it. -class BuilderOrigin : public Builder { - template - T unwrapAny(const BuiltThing& thing) { - MOZ_ASSERT(&thing.owner == this); - return thing.value.get(); - } - - public: - BuilderOrigin(JSContext* cx, js::Debugger* debugger_) - : Builder(cx, debugger_) - { } - - JSObject* unwrap(Object& object) { return unwrapAny(object); } -}; - - - -// Finding the size of blocks allocated with malloc -// ------------------------------------------------ -// -// Debugger.Memory wants to be able to report how many bytes items in memory are -// consuming. To do this, it needs a function that accepts a pointer to a block, -// and returns the number of bytes allocated to that block. SpiderMonkey itself -// doesn't know which function is appropriate to use, but the embedding does. - -// Tell Debuggers in |cx| to use |mallocSizeOf| to find the size of -// malloc'd blocks. -JS_PUBLIC_API(void) -SetDebuggerMallocSizeOf(JSContext* cx, mozilla::MallocSizeOf mallocSizeOf); - -// Get the MallocSizeOf function that the given context is using to find the -// size of malloc'd blocks. -JS_PUBLIC_API(mozilla::MallocSizeOf) -GetDebuggerMallocSizeOf(JSContext* cx); - - - -// Debugger and Garbage Collection Events -// -------------------------------------- -// -// The Debugger wants to report about its debuggees' GC cycles, however entering -// JS after a GC is troublesome since SpiderMonkey will often do something like -// force a GC and then rely on the nursery being empty. If we call into some -// Debugger's hook after the GC, then JS runs and the nursery won't be -// empty. Instead, we rely on embedders to call back into SpiderMonkey after a -// GC and notify Debuggers to call their onGarbageCollection hook. - - -// For each Debugger that observed a debuggee involved in the given GC event, -// call its `onGarbageCollection` hook. -JS_PUBLIC_API(bool) -FireOnGarbageCollectionHook(JSContext* cx, GarbageCollectionEvent::Ptr&& data); - - - -// Handlers for observing Promises -// ------------------------------- -// -// The Debugger wants to observe behavior of promises, which are implemented by -// Gecko with webidl and which SpiderMonkey knows nothing about. On the other -// hand, Gecko knows nothing about which (if any) debuggers are observing a -// promise's global. The compromise is that Gecko is responsible for calling -// these handlers at the appropriate times, and SpiderMonkey will handle -// notifying any Debugger instances that are observing the given promise's -// global. - -// Notify any Debugger instances observing this promise's global that a new -// promise was allocated. -JS_PUBLIC_API(void) -onNewPromise(JSContext* cx, HandleObject promise); - -// Notify any Debugger instances observing this promise's global that the -// promise has settled (ie, it has either been fulfilled or rejected). Note that -// this is *not* equivalent to the promise resolution (ie, the promise's fate -// getting locked in) because you can resolve a promise with another pending -// promise, in which case neither promise has settled yet. -// -// It is Gecko's responsibility to ensure that this is never called on the same -// promise more than once (because a promise can only make the transition from -// unsettled to settled once). -JS_PUBLIC_API(void) -onPromiseSettled(JSContext* cx, HandleObject promise); - - - -// Return true if the given value is a Debugger object, false otherwise. -JS_PUBLIC_API(bool) -IsDebugger(JSObject& obj); - -// Append each of the debuggee global objects observed by the Debugger object -// |dbgObj| to |vector|. Returns true on success, false on failure. -JS_PUBLIC_API(bool) -GetDebuggeeGlobals(JSContext* cx, JSObject& dbgObj, AutoObjectVector& vector); - - -// Hooks for reporting where JavaScript execution began. -// -// Our performance tools would like to be able to label blocks of JavaScript -// execution with the function name and source location where execution began: -// the event handler, the callback, etc. -// -// Construct an instance of this class on the stack, providing a JSContext -// belonging to the runtime in which execution will occur. Each time we enter -// JavaScript --- specifically, each time we push a JavaScript stack frame that -// has no older JS frames younger than this AutoEntryMonitor --- we will -// call the appropriate |Entry| member function to indicate where we've begun -// execution. - -class MOZ_STACK_CLASS AutoEntryMonitor { - JSRuntime* runtime_; - AutoEntryMonitor* savedMonitor_; - - public: - explicit AutoEntryMonitor(JSContext* cx); - ~AutoEntryMonitor(); - - // SpiderMonkey reports the JavaScript entry points occuring within this - // AutoEntryMonitor's scope to the following member functions, which the - // embedding is expected to override. - // - // It is important to note that |asyncCause| is owned by the caller and its - // lifetime must outlive the lifetime of the AutoEntryMonitor object. It is - // strongly encouraged that |asyncCause| be a string constant or similar - // statically allocated string. - - // We have begun executing |function|. Note that |function| may not be the - // actual closure we are running, but only the canonical function object to - // which the script refers. - virtual void Entry(JSContext* cx, JSFunction* function, - HandleValue asyncStack, - const char* asyncCause) = 0; - - // Execution has begun at the entry point of |script|, which is not a - // function body. (This is probably being executed by 'eval' or some - // JSAPI equivalent.) - virtual void Entry(JSContext* cx, JSScript* script, - HandleValue asyncStack, - const char* asyncCause) = 0; - - // Execution of the function or script has ended. - virtual void Exit(JSContext* cx) { } -}; - - - -} // namespace dbg -} // namespace JS - - -#endif /* js_Debug_h */ diff --git a/ios/include/spidermonkey/js/GCAPI.h b/ios/include/spidermonkey/js/GCAPI.h deleted file mode 100644 index 7a6675ca..00000000 --- a/ios/include/spidermonkey/js/GCAPI.h +++ /dev/null @@ -1,723 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCAPI_h -#define js_GCAPI_h - -#include "mozilla/Vector.h" - -#include "js/GCAnnotations.h" -#include "js/HeapAPI.h" -#include "js/UniquePtr.h" - -namespace js { -namespace gc { -class GCRuntime; -} // namespace gc -namespace gcstats { -struct Statistics; -} // namespace gcstats -} // namespace js - -typedef enum JSGCMode { - /** Perform only global GCs. */ - JSGC_MODE_GLOBAL = 0, - - /** Perform per-zone GCs until too much garbage has accumulated. */ - JSGC_MODE_ZONE = 1, - - /** - * Collect in short time slices rather than all at once. Implies - * JSGC_MODE_ZONE. - */ - JSGC_MODE_INCREMENTAL = 2 -} JSGCMode; - -/** - * Kinds of js_GC invocation. - */ -typedef enum JSGCInvocationKind { - /* Normal invocation. */ - GC_NORMAL = 0, - - /* Minimize GC triggers and release empty GC chunks right away. */ - GC_SHRINK = 1 -} JSGCInvocationKind; - -namespace JS { - -#define GCREASONS(D) \ - /* Reasons internal to the JS engine */ \ - D(API) \ - D(EAGER_ALLOC_TRIGGER) \ - D(DESTROY_RUNTIME) \ - D(UNUSED0) \ - D(LAST_DITCH) \ - D(TOO_MUCH_MALLOC) \ - D(ALLOC_TRIGGER) \ - D(DEBUG_GC) \ - D(COMPARTMENT_REVIVED) \ - D(RESET) \ - D(OUT_OF_NURSERY) \ - D(EVICT_NURSERY) \ - D(FULL_STORE_BUFFER) \ - D(SHARED_MEMORY_LIMIT) \ - D(UNUSED1) \ - D(INCREMENTAL_TOO_SLOW) \ - D(ABORT_GC) \ - \ - /* These are reserved for future use. */ \ - D(RESERVED0) \ - D(RESERVED1) \ - D(RESERVED2) \ - D(RESERVED3) \ - D(RESERVED4) \ - D(RESERVED5) \ - D(RESERVED6) \ - D(RESERVED7) \ - D(RESERVED8) \ - D(RESERVED9) \ - D(RESERVED10) \ - D(RESERVED11) \ - D(RESERVED12) \ - D(RESERVED13) \ - D(RESERVED14) \ - D(RESERVED15) \ - \ - /* Reasons from Firefox */ \ - D(DOM_WINDOW_UTILS) \ - D(COMPONENT_UTILS) \ - D(MEM_PRESSURE) \ - D(CC_WAITING) \ - D(CC_FORCED) \ - D(LOAD_END) \ - D(POST_COMPARTMENT) \ - D(PAGE_HIDE) \ - D(NSJSCONTEXT_DESTROY) \ - D(SET_NEW_DOCUMENT) \ - D(SET_DOC_SHELL) \ - D(DOM_UTILS) \ - D(DOM_IPC) \ - D(DOM_WORKER) \ - D(INTER_SLICE_GC) \ - D(REFRESH_FRAME) \ - D(FULL_GC_TIMER) \ - D(SHUTDOWN_CC) \ - D(FINISH_LARGE_EVALUATE) \ - D(USER_INACTIVE) \ - D(XPCONNECT_SHUTDOWN) - -namespace gcreason { - -/* GCReasons will end up looking like JSGC_MAYBEGC */ -enum Reason { -#define MAKE_REASON(name) name, - GCREASONS(MAKE_REASON) -#undef MAKE_REASON - NO_REASON, - NUM_REASONS, - - /* - * For telemetry, we want to keep a fixed max bucket size over time so we - * don't have to switch histograms. 100 is conservative; as of this writing - * there are 52. But the cost of extra buckets seems to be low while the - * cost of switching histograms is high. - */ - NUM_TELEMETRY_REASONS = 100 -}; - -/** - * Get a statically allocated C string explaining the given GC reason. - */ -extern JS_PUBLIC_API(const char*) -ExplainReason(JS::gcreason::Reason reason); - -} /* namespace gcreason */ - -/* - * Zone GC: - * - * SpiderMonkey's GC is capable of performing a collection on an arbitrary - * subset of the zones in the system. This allows an embedding to minimize - * collection time by only collecting zones that have run code recently, - * ignoring the parts of the heap that are unlikely to have changed. - * - * When triggering a GC using one of the functions below, it is first necessary - * to select the zones to be collected. To do this, you can call - * PrepareZoneForGC on each zone, or you can call PrepareForFullGC to select - * all zones. Failing to select any zone is an error. - */ - -/** - * Schedule the given zone to be collected as part of the next GC. - */ -extern JS_PUBLIC_API(void) -PrepareZoneForGC(Zone* zone); - -/** - * Schedule all zones to be collected in the next GC. - */ -extern JS_PUBLIC_API(void) -PrepareForFullGC(JSContext* cx); - -/** - * When performing an incremental GC, the zones that were selected for the - * previous incremental slice must be selected in subsequent slices as well. - * This function selects those slices automatically. - */ -extern JS_PUBLIC_API(void) -PrepareForIncrementalGC(JSContext* cx); - -/** - * Returns true if any zone in the system has been scheduled for GC with one of - * the functions above or by the JS engine. - */ -extern JS_PUBLIC_API(bool) -IsGCScheduled(JSContext* cx); - -/** - * Undoes the effect of the Prepare methods above. The given zone will not be - * collected in the next GC. - */ -extern JS_PUBLIC_API(void) -SkipZoneForGC(Zone* zone); - -/* - * Non-Incremental GC: - * - * The following functions perform a non-incremental GC. - */ - -/** - * Performs a non-incremental collection of all selected zones. - * - * If the gckind argument is GC_NORMAL, then some objects that are unreachable - * from the program may still be alive afterwards because of internal - * references; if GC_SHRINK is passed then caches and other temporary references - * to objects will be cleared and all unreferenced objects will be removed from - * the system. - */ -extern JS_PUBLIC_API(void) -GCForReason(JSContext* cx, JSGCInvocationKind gckind, gcreason::Reason reason); - -/* - * Incremental GC: - * - * Incremental GC divides the full mark-and-sweep collection into multiple - * slices, allowing client JavaScript code to run between each slice. This - * allows interactive apps to avoid long collection pauses. Incremental GC does - * not make collection take less time, it merely spreads that time out so that - * the pauses are less noticable. - * - * For a collection to be carried out incrementally the following conditions - * must be met: - * - The collection must be run by calling JS::IncrementalGC() rather than - * JS_GC(). - * - The GC mode must have been set to JSGC_MODE_INCREMENTAL with - * JS_SetGCParameter(). - * - * Note: Even if incremental GC is enabled and working correctly, - * non-incremental collections can still happen when low on memory. - */ - -/** - * Begin an incremental collection and perform one slice worth of work. When - * this function returns, the collection may not be complete. - * IncrementalGCSlice() must be called repeatedly until - * !IsIncrementalGCInProgress(cx). - * - * Note: SpiderMonkey's GC is not realtime. Slices in practice may be longer or - * shorter than the requested interval. - */ -extern JS_PUBLIC_API(void) -StartIncrementalGC(JSContext* cx, JSGCInvocationKind gckind, gcreason::Reason reason, - int64_t millis = 0); - -/** - * Perform a slice of an ongoing incremental collection. When this function - * returns, the collection may not be complete. It must be called repeatedly - * until !IsIncrementalGCInProgress(cx). - * - * Note: SpiderMonkey's GC is not realtime. Slices in practice may be longer or - * shorter than the requested interval. - */ -extern JS_PUBLIC_API(void) -IncrementalGCSlice(JSContext* cx, gcreason::Reason reason, int64_t millis = 0); - -/** - * If IsIncrementalGCInProgress(cx), this call finishes the ongoing collection - * by performing an arbitrarily long slice. If !IsIncrementalGCInProgress(cx), - * this is equivalent to GCForReason. When this function returns, - * IsIncrementalGCInProgress(cx) will always be false. - */ -extern JS_PUBLIC_API(void) -FinishIncrementalGC(JSContext* cx, gcreason::Reason reason); - -/** - * If IsIncrementalGCInProgress(cx), this call aborts the ongoing collection and - * performs whatever work needs to be done to return the collector to its idle - * state. This may take an arbitrarily long time. When this function returns, - * IsIncrementalGCInProgress(cx) will always be false. - */ -extern JS_PUBLIC_API(void) -AbortIncrementalGC(JSContext* cx); - -namespace dbg { - -// The `JS::dbg::GarbageCollectionEvent` class is essentially a view of the -// `js::gcstats::Statistics` data without the uber implementation-specific bits. -// It should generally be palatable for web developers. -class GarbageCollectionEvent -{ - // The major GC number of the GC cycle this data pertains to. - uint64_t majorGCNumber_; - - // Reference to a non-owned, statically allocated C string. This is a very - // short reason explaining why a GC was triggered. - const char* reason; - - // Reference to a nullable, non-owned, statically allocated C string. If the - // collection was forced to be non-incremental, this is a short reason of - // why the GC could not perform an incremental collection. - const char* nonincrementalReason; - - // Represents a single slice of a possibly multi-slice incremental garbage - // collection. - struct Collection { - double startTimestamp; - double endTimestamp; - }; - - // The set of garbage collection slices that made up this GC cycle. - mozilla::Vector collections; - - GarbageCollectionEvent(const GarbageCollectionEvent& rhs) = delete; - GarbageCollectionEvent& operator=(const GarbageCollectionEvent& rhs) = delete; - - public: - explicit GarbageCollectionEvent(uint64_t majorGCNum) - : majorGCNumber_(majorGCNum) - , reason(nullptr) - , nonincrementalReason(nullptr) - , collections() - { } - - using Ptr = js::UniquePtr; - static Ptr Create(JSRuntime* rt, ::js::gcstats::Statistics& stats, uint64_t majorGCNumber); - - JSObject* toJSObject(JSContext* cx) const; - - uint64_t majorGCNumber() const { return majorGCNumber_; } -}; - -} // namespace dbg - -enum GCProgress { - /* - * During non-incremental GC, the GC is bracketed by JSGC_CYCLE_BEGIN/END - * callbacks. During an incremental GC, the sequence of callbacks is as - * follows: - * JSGC_CYCLE_BEGIN, JSGC_SLICE_END (first slice) - * JSGC_SLICE_BEGIN, JSGC_SLICE_END (second slice) - * ... - * JSGC_SLICE_BEGIN, JSGC_CYCLE_END (last slice) - */ - - GC_CYCLE_BEGIN, - GC_SLICE_BEGIN, - GC_SLICE_END, - GC_CYCLE_END -}; - -struct JS_PUBLIC_API(GCDescription) { - bool isZone_; - JSGCInvocationKind invocationKind_; - gcreason::Reason reason_; - - GCDescription(bool isZone, JSGCInvocationKind kind, gcreason::Reason reason) - : isZone_(isZone), invocationKind_(kind), reason_(reason) {} - - char16_t* formatSliceMessage(JSContext* cx) const; - char16_t* formatSummaryMessage(JSContext* cx) const; - char16_t* formatJSON(JSContext* cx, uint64_t timestamp) const; - - JS::dbg::GarbageCollectionEvent::Ptr toGCEvent(JSContext* cx) const; -}; - -typedef void -(* GCSliceCallback)(JSContext* cx, GCProgress progress, const GCDescription& desc); - -/** - * The GC slice callback is called at the beginning and end of each slice. This - * callback may be used for GC notifications as well as to perform additional - * marking. - */ -extern JS_PUBLIC_API(GCSliceCallback) -SetGCSliceCallback(JSContext* cx, GCSliceCallback callback); - -/** - * Describes the progress of an observed nursery collection. - */ -enum class GCNurseryProgress { - /** - * The nursery collection is starting. - */ - GC_NURSERY_COLLECTION_START, - /** - * The nursery collection is ending. - */ - GC_NURSERY_COLLECTION_END -}; - -/** - * A nursery collection callback receives the progress of the nursery collection - * and the reason for the collection. - */ -using GCNurseryCollectionCallback = void(*)(JSContext* cx, GCNurseryProgress progress, - gcreason::Reason reason); - -/** - * Set the nursery collection callback for the given runtime. When set, it will - * be called at the start and end of every nursery collection. - */ -extern JS_PUBLIC_API(GCNurseryCollectionCallback) -SetGCNurseryCollectionCallback(JSContext* cx, GCNurseryCollectionCallback callback); - -typedef void -(* DoCycleCollectionCallback)(JSContext* cx); - -/** - * The purge gray callback is called after any COMPARTMENT_REVIVED GC in which - * the majority of compartments have been marked gray. - */ -extern JS_PUBLIC_API(DoCycleCollectionCallback) -SetDoCycleCollectionCallback(JSContext* cx, DoCycleCollectionCallback callback); - -/** - * Incremental GC defaults to enabled, but may be disabled for testing or in - * embeddings that have not yet implemented barriers on their native classes. - * There is not currently a way to re-enable incremental GC once it has been - * disabled on the runtime. - */ -extern JS_PUBLIC_API(void) -DisableIncrementalGC(JSContext* cx); - -/** - * Returns true if incremental GC is enabled. Simply having incremental GC - * enabled is not sufficient to ensure incremental collections are happening. - * See the comment "Incremental GC" above for reasons why incremental GC may be - * suppressed. Inspection of the "nonincremental reason" field of the - * GCDescription returned by GCSliceCallback may help narrow down the cause if - * collections are not happening incrementally when expected. - */ -extern JS_PUBLIC_API(bool) -IsIncrementalGCEnabled(JSContext* cx); - -/** - * Returns true while an incremental GC is ongoing, both when actively - * collecting and between slices. - */ -extern JS_PUBLIC_API(bool) -IsIncrementalGCInProgress(JSContext* cx); - -/* - * Returns true when writes to GC things must call an incremental (pre) barrier. - * This is generally only true when running mutator code in-between GC slices. - * At other times, the barrier may be elided for performance. - */ -extern JS_PUBLIC_API(bool) -IsIncrementalBarrierNeeded(JSContext* cx); - -/* - * Notify the GC that a reference to a GC thing is about to be overwritten. - * These methods must be called if IsIncrementalBarrierNeeded. - */ -extern JS_PUBLIC_API(void) -IncrementalReferenceBarrier(GCCellPtr thing); - -extern JS_PUBLIC_API(void) -IncrementalValueBarrier(const Value& v); - -extern JS_PUBLIC_API(void) -IncrementalObjectBarrier(JSObject* obj); - -/** - * Returns true if the most recent GC ran incrementally. - */ -extern JS_PUBLIC_API(bool) -WasIncrementalGC(JSContext* cx); - -/* - * Generational GC: - * - * Note: Generational GC is not yet enabled by default. The following class - * is non-functional unless SpiderMonkey was configured with - * --enable-gcgenerational. - */ - -/** Ensure that generational GC is disabled within some scope. */ -class JS_PUBLIC_API(AutoDisableGenerationalGC) -{ - js::gc::GCRuntime* gc; - - public: - explicit AutoDisableGenerationalGC(JSRuntime* rt); - ~AutoDisableGenerationalGC(); -}; - -/** - * Returns true if generational allocation and collection is currently enabled - * on the given runtime. - */ -extern JS_PUBLIC_API(bool) -IsGenerationalGCEnabled(JSRuntime* rt); - -/** - * Returns the GC's "number". This does not correspond directly to the number - * of GCs that have been run, but is guaranteed to be monotonically increasing - * with GC activity. - */ -extern JS_PUBLIC_API(size_t) -GetGCNumber(); - -/** - * Pass a subclass of this "abstract" class to callees to require that they - * never GC. Subclasses can use assertions or the hazard analysis to ensure no - * GC happens. - */ -class JS_PUBLIC_API(AutoRequireNoGC) -{ - protected: - AutoRequireNoGC() {} - ~AutoRequireNoGC() {} -}; - -/** - * Diagnostic assert (see MOZ_DIAGNOSTIC_ASSERT) that GC cannot occur while this - * class is live. This class does not disable the static rooting hazard - * analysis. - * - * This works by entering a GC unsafe region, which is checked on allocation and - * on GC. - */ -class JS_PUBLIC_API(AutoAssertNoGC) : public AutoRequireNoGC -{ - js::gc::GCRuntime* gc; - size_t gcNumber; - - public: - AutoAssertNoGC(); - explicit AutoAssertNoGC(JSRuntime* rt); - explicit AutoAssertNoGC(JSContext* cx); - ~AutoAssertNoGC(); -}; - -/** - * Assert if an allocation of a GC thing occurs while this class is live. This - * class does not disable the static rooting hazard analysis. - */ -class JS_PUBLIC_API(AutoAssertNoAlloc) -{ -#ifdef JS_DEBUG - js::gc::GCRuntime* gc; - - public: - AutoAssertNoAlloc() : gc(nullptr) {} - explicit AutoAssertNoAlloc(JSContext* cx); - void disallowAlloc(JSRuntime* rt); - ~AutoAssertNoAlloc(); -#else - public: - AutoAssertNoAlloc() {} - explicit AutoAssertNoAlloc(JSContext* cx) {} - void disallowAlloc(JSRuntime* rt) {} -#endif -}; - -/** - * Assert if a GC barrier is invoked while this class is live. This class does - * not disable the static rooting hazard analysis. - */ -class JS_PUBLIC_API(AutoAssertOnBarrier) -{ - JSContext* context; - bool prev; - - public: - explicit AutoAssertOnBarrier(JSContext* cx); - ~AutoAssertOnBarrier(); -}; - -/** - * Disable the static rooting hazard analysis in the live region and assert if - * any allocation that could potentially trigger a GC occurs while this guard - * object is live. This is most useful to help the exact rooting hazard analysis - * in complex regions, since it cannot understand dataflow. - * - * Note: GC behavior is unpredictable even when deterministic and is generally - * non-deterministic in practice. The fact that this guard has not - * asserted is not a guarantee that a GC cannot happen in the guarded - * region. As a rule, anyone performing a GC unsafe action should - * understand the GC properties of all code in that region and ensure - * that the hazard analysis is correct for that code, rather than relying - * on this class. - */ -class JS_PUBLIC_API(AutoSuppressGCAnalysis) : public AutoAssertNoAlloc -{ - public: - AutoSuppressGCAnalysis() : AutoAssertNoAlloc() {} - explicit AutoSuppressGCAnalysis(JSContext* cx) : AutoAssertNoAlloc(cx) {} -} JS_HAZ_GC_SUPPRESSED; - -/** - * Assert that code is only ever called from a GC callback, disable the static - * rooting hazard analysis and assert if any allocation that could potentially - * trigger a GC occurs while this guard object is live. - * - * This is useful to make the static analysis ignore code that runs in GC - * callbacks. - */ -class JS_PUBLIC_API(AutoAssertGCCallback) : public AutoSuppressGCAnalysis -{ - public: - explicit AutoAssertGCCallback(JSObject* obj); -}; - -/** - * Place AutoCheckCannotGC in scopes that you believe can never GC. These - * annotations will be verified both dynamically via AutoAssertNoGC, and - * statically with the rooting hazard analysis (implemented by making the - * analysis consider AutoCheckCannotGC to be a GC pointer, and therefore - * complain if it is live across a GC call.) It is useful when dealing with - * internal pointers to GC things where the GC thing itself may not be present - * for the static analysis: e.g. acquiring inline chars from a JSString* on the - * heap. - * - * We only do the assertion checking in DEBUG builds. - */ -#ifdef DEBUG -class JS_PUBLIC_API(AutoCheckCannotGC) : public AutoAssertNoGC -{ - public: - AutoCheckCannotGC() : AutoAssertNoGC() {} - explicit AutoCheckCannotGC(JSContext* cx) : AutoAssertNoGC(cx) {} -} JS_HAZ_GC_INVALIDATED; -#else -class JS_PUBLIC_API(AutoCheckCannotGC) : public AutoRequireNoGC -{ - public: - AutoCheckCannotGC() {} - explicit AutoCheckCannotGC(JSContext* cx) {} -} JS_HAZ_GC_INVALIDATED; -#endif - -/** - * Unsets the gray bit for anything reachable from |thing|. |kind| should not be - * JS::TraceKind::Shape. |thing| should be non-null. The return value indicates - * if anything was unmarked. - */ -extern JS_FRIEND_API(bool) -UnmarkGrayGCThingRecursively(GCCellPtr thing); - -} /* namespace JS */ - -namespace js { -namespace gc { - -static MOZ_ALWAYS_INLINE void -ExposeGCThingToActiveJS(JS::GCCellPtr thing) -{ - // GC things residing in the nursery cannot be gray: they have no mark bits. - // All live objects in the nursery are moved to tenured at the beginning of - // each GC slice, so the gray marker never sees nursery things. - if (IsInsideNursery(thing.asCell())) - return; - - // There's nothing to do for permanent GC things that might be owned by - // another runtime. - if (thing.mayBeOwnedByOtherRuntime()) - return; - - JS::shadow::Runtime* rt = detail::GetCellRuntime(thing.asCell()); - MOZ_DIAGNOSTIC_ASSERT(rt->allowGCBarriers()); - - if (IsIncrementalBarrierNeededOnTenuredGCThing(rt, thing)) - JS::IncrementalReferenceBarrier(thing); - else if (!thing.mayBeOwnedByOtherRuntime() && js::gc::detail::CellIsMarkedGray(thing.asCell())) - JS::UnmarkGrayGCThingRecursively(thing); -} - -static MOZ_ALWAYS_INLINE void -MarkGCThingAsLive(JSRuntime* aRt, JS::GCCellPtr thing) -{ - // Any object in the nursery will not be freed during any GC running at that - // time. - if (IsInsideNursery(thing.asCell())) - return; - - // There's nothing to do for permanent GC things that might be owned by - // another runtime. - if (thing.mayBeOwnedByOtherRuntime()) - return; - - JS::shadow::Runtime* rt = JS::shadow::Runtime::asShadowRuntime(aRt); - MOZ_DIAGNOSTIC_ASSERT(rt->allowGCBarriers()); - - if (IsIncrementalBarrierNeededOnTenuredGCThing(rt, thing)) - JS::IncrementalReferenceBarrier(thing); -} - -} /* namespace gc */ -} /* namespace js */ - -namespace JS { - -/* - * This should be called when an object that is marked gray is exposed to the JS - * engine (by handing it to running JS code or writing it into live JS - * data). During incremental GC, since the gray bits haven't been computed yet, - * we conservatively mark the object black. - */ -static MOZ_ALWAYS_INLINE void -ExposeObjectToActiveJS(JSObject* obj) -{ - MOZ_ASSERT(obj); - js::gc::ExposeGCThingToActiveJS(GCCellPtr(obj)); -} - -static MOZ_ALWAYS_INLINE void -ExposeScriptToActiveJS(JSScript* script) -{ - js::gc::ExposeGCThingToActiveJS(GCCellPtr(script)); -} - -/* - * If a GC is currently marking, mark the string black. - */ -static MOZ_ALWAYS_INLINE void -MarkStringAsLive(Zone* zone, JSString* string) -{ - JSRuntime* rt = JS::shadow::Zone::asShadowZone(zone)->runtimeFromMainThread(); - js::gc::MarkGCThingAsLive(rt, GCCellPtr(string)); -} - -/* - * Internal to Firefox. - * - * Note: this is not related to the PokeGC in nsJSEnvironment. - */ -extern JS_FRIEND_API(void) -PokeGC(JSContext* cx); - -/* - * Internal to Firefox. - */ -extern JS_FRIEND_API(void) -NotifyDidPaint(JSContext* cx); - -} /* namespace JS */ - -#endif /* js_GCAPI_h */ diff --git a/ios/include/spidermonkey/js/GCAnnotations.h b/ios/include/spidermonkey/js/GCAnnotations.h deleted file mode 100644 index 366d787b..00000000 --- a/ios/include/spidermonkey/js/GCAnnotations.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCAnnotations_h -#define js_GCAnnotations_h - -// Set of annotations for the rooting hazard analysis, used to categorize types -// and functions. -#ifdef XGILL_PLUGIN - -// Mark a type as being a GC thing (eg js::gc::Cell has this annotation). -# define JS_HAZ_GC_THING __attribute__((tag("GC Thing"))) - -// Mark a type as holding a pointer to a GC thing (eg JS::Value has this -// annotation.) -# define JS_HAZ_GC_POINTER __attribute__((tag("GC Pointer"))) - -// Mark a type as a rooted pointer, suitable for use on the stack (eg all -// Rooted instantiations should have this.) -# define JS_HAZ_ROOTED __attribute__((tag("Rooted Pointer"))) - -// Mark a type as something that should not be held live across a GC, but which -// is not itself a GC pointer. -# define JS_HAZ_GC_INVALIDATED __attribute__((tag("Invalidated by GC"))) - -// Mark a type that would otherwise be considered a GC Pointer (eg because it -// contains a JS::Value field) as a non-GC pointer. It is handled almost the -// same in the analysis as a rooted pointer, except it will not be reported as -// an unnecessary root if used across a GC call. This should rarely be used, -// but makes sense for something like ErrorResult, which only contains a GC -// pointer when it holds an exception (and it does its own rooting, -// conditionally.) -# define JS_HAZ_NON_GC_POINTER __attribute__((tag("Suppressed GC Pointer"))) - -// Mark a function as something that runs a garbage collection, potentially -// invalidating GC pointers. -# define JS_HAZ_GC_CALL __attribute__((tag("GC Call"))) - -// Mark an RAII class as suppressing GC within its scope. -# define JS_HAZ_GC_SUPPRESSED __attribute__((tag("Suppress GC"))) - -#else - -# define JS_HAZ_GC_THING -# define JS_HAZ_GC_POINTER -# define JS_HAZ_ROOTED -# define JS_HAZ_GC_INVALIDATED -# define JS_HAZ_NON_GC_POINTER -# define JS_HAZ_GC_CALL -# define JS_HAZ_GC_SUPPRESSED - -#endif - -#endif /* js_GCAnnotations_h */ diff --git a/ios/include/spidermonkey/js/GCHashTable.h b/ios/include/spidermonkey/js/GCHashTable.h deleted file mode 100644 index d6c2ce75..00000000 --- a/ios/include/spidermonkey/js/GCHashTable.h +++ /dev/null @@ -1,399 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef GCHashTable_h -#define GCHashTable_h - -#include "js/GCPolicyAPI.h" -#include "js/HashTable.h" -#include "js/RootingAPI.h" -#include "js/SweepingAPI.h" -#include "js/TracingAPI.h" - -namespace JS { - -// Define a reasonable default GC policy for GC-aware Maps. -template -struct DefaultMapSweepPolicy { - static bool needsSweep(Key* key, Value* value) { - return GCPolicy::needsSweep(key) || GCPolicy::needsSweep(value); - } -}; - -// A GCHashMap is a GC-aware HashMap, meaning that it has additional trace and -// sweep methods that know how to visit all keys and values in the table. -// HashMaps that contain GC pointers will generally want to use this GCHashMap -// specialization instead of HashMap, because this conveniently supports tracing -// keys and values, and cleaning up weak entries. -// -// GCHashMap::trace applies GCPolicy::trace to each entry's key and value. -// Most types of GC pointers already have appropriate specializations of -// GCPolicy, so they should just work as keys and values. Any struct type with a -// default constructor and trace and sweep functions should work as well. If you -// need to define your own GCPolicy specialization, generic helpers can be found -// in js/public/TracingAPI.h. -// -// The MapSweepPolicy template parameter controls how the table drops entries -// when swept. GCHashMap::sweep applies MapSweepPolicy::needsSweep to each table -// entry; if it returns true, the entry is dropped. The default MapSweepPolicy -// drops the entry if either the key or value is about to be finalized, -// according to its GCPolicy::needsSweep method. (This default is almost -// always fine: it's hard to imagine keeping such an entry around anyway.) -// -// Note that this HashMap only knows *how* to trace and sweep, but it does not -// itself cause tracing or sweeping to be invoked. For tracing, it must be used -// with Rooted or PersistentRooted, or barriered and traced manually. For -// sweeping, currently it requires an explicit call to .sweep(). -template , - typename AllocPolicy = js::TempAllocPolicy, - typename MapSweepPolicy = DefaultMapSweepPolicy> -class GCHashMap : public js::HashMap -{ - using Base = js::HashMap; - - public: - explicit GCHashMap(AllocPolicy a = AllocPolicy()) : Base(a) {} - - static void trace(GCHashMap* map, JSTracer* trc) { map->trace(trc); } - void trace(JSTracer* trc) { - if (!this->initialized()) - return; - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - GCPolicy::trace(trc, &e.front().value(), "hashmap value"); - GCPolicy::trace(trc, &e.front().mutableKey(), "hashmap key"); - } - } - - void sweep() { - if (!this->initialized()) - return; - - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - if (MapSweepPolicy::needsSweep(&e.front().mutableKey(), &e.front().value())) - e.removeFront(); - } - } - - // GCHashMap is movable - GCHashMap(GCHashMap&& rhs) : Base(mozilla::Move(rhs)) {} - void operator=(GCHashMap&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - Base::operator=(mozilla::Move(rhs)); - } - - private: - // GCHashMap is not copyable or assignable - GCHashMap(const GCHashMap& hm) = delete; - GCHashMap& operator=(const GCHashMap& hm) = delete; -}; - -} // namespace JS - -namespace js { - -// HashMap that supports rekeying. -// -// If your keys are pointers to something like JSObject that can be tenured or -// compacted, prefer to use GCHashMap with MovableCellHasher, which takes -// advantage of the Zone's stable id table to make rekeying unnecessary. -template , - typename AllocPolicy = TempAllocPolicy, - typename MapSweepPolicy = JS::DefaultMapSweepPolicy> -class GCRekeyableHashMap : public JS::GCHashMap -{ - using Base = JS::GCHashMap; - - public: - explicit GCRekeyableHashMap(AllocPolicy a = AllocPolicy()) : Base(a) {} - - void sweep() { - if (!this->initialized()) - return; - - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - Key key(e.front().key()); - if (MapSweepPolicy::needsSweep(&key, &e.front().value())) - e.removeFront(); - else if (!HashPolicy::match(key, e.front().key())) - e.rekeyFront(key); - } - } - - // GCRekeyableHashMap is movable - GCRekeyableHashMap(GCRekeyableHashMap&& rhs) : Base(mozilla::Move(rhs)) {} - void operator=(GCRekeyableHashMap&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - Base::operator=(mozilla::Move(rhs)); - } -}; - -template -class GCHashMapOperations -{ - using Map = JS::GCHashMap; - using Lookup = typename Map::Lookup; - - const Map& map() const { return static_cast(this)->get(); } - - public: - using AddPtr = typename Map::AddPtr; - using Ptr = typename Map::Ptr; - using Range = typename Map::Range; - - bool initialized() const { return map().initialized(); } - Ptr lookup(const Lookup& l) const { return map().lookup(l); } - AddPtr lookupForAdd(const Lookup& l) const { return map().lookupForAdd(l); } - Range all() const { return map().all(); } - bool empty() const { return map().empty(); } - uint32_t count() const { return map().count(); } - size_t capacity() const { return map().capacity(); } - bool has(const Lookup& l) const { return map().lookup(l).found(); } - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return map().sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + map().sizeOfExcludingThis(mallocSizeOf); - } -}; - -template -class MutableGCHashMapOperations - : public GCHashMapOperations -{ - using Map = JS::GCHashMap; - using Lookup = typename Map::Lookup; - - Map& map() { return static_cast(this)->get(); } - - public: - using AddPtr = typename Map::AddPtr; - struct Enum : public Map::Enum { explicit Enum(Outer& o) : Map::Enum(o.map()) {} }; - using Ptr = typename Map::Ptr; - using Range = typename Map::Range; - - bool init(uint32_t len = 16) { return map().init(len); } - void clear() { map().clear(); } - void finish() { map().finish(); } - void remove(Ptr p) { map().remove(p); } - - template - bool add(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return map().add(p, mozilla::Forward(k), mozilla::Forward(v)); - } - - template - bool add(AddPtr& p, KeyInput&& k) { - return map().add(p, mozilla::Forward(k), Map::Value()); - } - - template - bool relookupOrAdd(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return map().relookupOrAdd(p, k, - mozilla::Forward(k), - mozilla::Forward(v)); - } - - template - bool put(KeyInput&& k, ValueInput&& v) { - return map().put(mozilla::Forward(k), mozilla::Forward(v)); - } - - template - bool putNew(KeyInput&& k, ValueInput&& v) { - return map().putNew(mozilla::Forward(k), mozilla::Forward(v)); - } -}; - -template -class RootedBase> - : public MutableGCHashMapOperations>, A,B,C,D,E> -{}; - -template -class MutableHandleBase> - : public MutableGCHashMapOperations>, A,B,C,D,E> -{}; - -template -class HandleBase> - : public GCHashMapOperations>, A,B,C,D,E> -{}; - -template -class WeakCacheBase> - : public MutableGCHashMapOperations>, A,B,C,D,E> -{}; - -} // namespace js - -namespace JS { - -// A GCHashSet is a HashSet with an additional trace method that knows -// be traced to be kept alive will generally want to use this GCHashSet -// specialization in lieu of HashSet. -// -// Most types of GC pointers can be traced with no extra infrastructure. For -// structs and non-gc-pointer members, ensure that there is a specialization of -// GCPolicy with an appropriate trace method available to handle the custom -// type. Generic helpers can be found in js/public/TracingAPI.h. -// -// Note that although this HashSet's trace will deal correctly with moved -// elements, it does not itself know when to barrier or trace elements. To -// function properly it must either be used with Rooted or barriered and traced -// manually. -template , - typename AllocPolicy = js::TempAllocPolicy> -class GCHashSet : public js::HashSet -{ - using Base = js::HashSet; - - public: - explicit GCHashSet(AllocPolicy a = AllocPolicy()) : Base(a) {} - - static void trace(GCHashSet* set, JSTracer* trc) { set->trace(trc); } - void trace(JSTracer* trc) { - if (!this->initialized()) - return; - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) - GCPolicy::trace(trc, &e.mutableFront(), "hashset element"); - } - - void sweep() { - if (!this->initialized()) - return; - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - if (GCPolicy::needsSweep(&e.mutableFront())) - e.removeFront(); - } - } - - // GCHashSet is movable - GCHashSet(GCHashSet&& rhs) : Base(mozilla::Move(rhs)) {} - void operator=(GCHashSet&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - Base::operator=(mozilla::Move(rhs)); - } - - private: - // GCHashSet is not copyable or assignable - GCHashSet(const GCHashSet& hs) = delete; - GCHashSet& operator=(const GCHashSet& hs) = delete; -}; - -} // namespace JS - -namespace js { - -template -class GCHashSetOperations -{ - using Set = JS::GCHashSet; - using Lookup = typename Set::Lookup; - - const Set& set() const { return static_cast(this)->get(); } - - public: - using AddPtr = typename Set::AddPtr; - using Entry = typename Set::Entry; - using Ptr = typename Set::Ptr; - using Range = typename Set::Range; - - bool initialized() const { return set().initialized(); } - Ptr lookup(const Lookup& l) const { return set().lookup(l); } - AddPtr lookupForAdd(const Lookup& l) const { return set().lookupForAdd(l); } - Range all() const { return set().all(); } - bool empty() const { return set().empty(); } - uint32_t count() const { return set().count(); } - size_t capacity() const { return set().capacity(); } - bool has(const Lookup& l) const { return set().lookup(l).found(); } - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return set().sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + set().sizeOfExcludingThis(mallocSizeOf); - } -}; - -template -class MutableGCHashSetOperations - : public GCHashSetOperations -{ - using Set = JS::GCHashSet; - using Lookup = typename Set::Lookup; - - Set& set() { return static_cast(this)->get(); } - - public: - using AddPtr = typename Set::AddPtr; - using Entry = typename Set::Entry; - struct Enum : public Set::Enum { explicit Enum(Outer& o) : Set::Enum(o.set()) {} }; - using Ptr = typename Set::Ptr; - using Range = typename Set::Range; - - bool init(uint32_t len = 16) { return set().init(len); } - void clear() { set().clear(); } - void finish() { set().finish(); } - void remove(Ptr p) { set().remove(p); } - void remove(const Lookup& l) { set().remove(l); } - - template - bool add(AddPtr& p, TInput&& t) { - return set().add(p, mozilla::Forward(t)); - } - - template - bool relookupOrAdd(AddPtr& p, const Lookup& l, TInput&& t) { - return set().relookupOrAdd(p, l, mozilla::Forward(t)); - } - - template - bool put(TInput&& t) { - return set().put(mozilla::Forward(t)); - } - - template - bool putNew(TInput&& t) { - return set().putNew(mozilla::Forward(t)); - } - - template - bool putNew(const Lookup& l, TInput&& t) { - return set().putNew(l, mozilla::Forward(t)); - } -}; - -template -class RootedBase> - : public MutableGCHashSetOperations>, T, HP, AP> -{ -}; - -template -class MutableHandleBase> - : public MutableGCHashSetOperations>, T, HP, AP> -{ -}; - -template -class HandleBase> - : public GCHashSetOperations>, T, HP, AP> -{ -}; - -template -class WeakCacheBase> - : public MutableGCHashSetOperations>, T, HP, AP> -{ -}; - -} /* namespace js */ - -#endif /* GCHashTable_h */ diff --git a/ios/include/spidermonkey/js/GCPolicyAPI.h b/ios/include/spidermonkey/js/GCPolicyAPI.h deleted file mode 100644 index 054e397a..00000000 --- a/ios/include/spidermonkey/js/GCPolicyAPI.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// GC Policy Mechanism - -// A GCPolicy controls how the GC interacts with both direct pointers to GC -// things (e.g. JSObject* or JSString*), tagged and/or optional pointers to GC -// things (e.g. Value or jsid), and C++ container types (e.g. -// JSPropertyDescriptor or GCHashMap). -// -// The GCPolicy provides at a minimum: -// -// static T initial() -// - Construct and return an empty T. -// -// static void trace(JSTracer, T* tp, const char* name) -// - Trace the edge |*tp|, calling the edge |name|. Containers like -// GCHashMap and GCHashSet use this method to trace their children. -// -// static bool needsSweep(T* tp) -// - Return true if |*tp| is about to be finalized. Otherwise, update the -// edge for moving GC, and return false. Containers like GCHashMap and -// GCHashSet use this method to decide when to remove an entry: if this -// function returns true on a key/value/member/etc, its entry is dropped -// from the container. Specializing this method is the standard way to -// get custom weak behavior from a container type. -// -// The default GCPolicy assumes that T has a default constructor and |trace| -// and |needsSweep| methods, and forwards to them. GCPolicy has appropriate -// specializations for pointers to GC things and pointer-like types like -// JS::Heap and mozilla::UniquePtr. -// -// There are some stock structs your specializations can inherit from. -// IgnoreGCPolicy does nothing. StructGCPolicy forwards the methods to the -// referent type T. - -#ifndef GCPolicyAPI_h -#define GCPolicyAPI_h - -#include "mozilla/UniquePtr.h" - -#include "js/TraceKind.h" -#include "js/TracingAPI.h" - -// Expand the given macro D for each public GC pointer. -#define FOR_EACH_PUBLIC_GC_POINTER_TYPE(D) \ - D(JS::Symbol*) \ - D(JSAtom*) \ - D(JSFunction*) \ - D(JSObject*) \ - D(JSScript*) \ - D(JSString*) - -// Expand the given macro D for each public tagged GC pointer type. -#define FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(D) \ - D(JS::Value) \ - D(jsid) - -#define FOR_EACH_PUBLIC_AGGREGATE_GC_POINTER_TYPE(D) \ - D(JSPropertyDescriptor) - -class JSAtom; -class JSFunction; -class JSObject; -class JSScript; -class JSString; -namespace JS { -class Symbol; -} - -namespace JS { - -// Defines a policy for container types with non-GC, i.e. C storage. This -// policy dispatches to the underlying struct for GC interactions. -template -struct StructGCPolicy -{ - static T initial() { - return T(); - } - - static void trace(JSTracer* trc, T* tp, const char* name) { - tp->trace(trc); - } - - static void sweep(T* tp) { - return tp->sweep(); - } - - static bool needsSweep(T* tp) { - return tp->needsSweep(); - } -}; - -// The default GC policy attempts to defer to methods on the underlying type. -// Most C++ structures that contain a default constructor, a trace function and -// a sweep function will work out of the box with Rooted, Handle, GCVector, -// and GCHash{Set,Map}. -template struct GCPolicy : public StructGCPolicy {}; - -// This policy ignores any GC interaction, e.g. for non-GC types. -template -struct IgnoreGCPolicy { - static T initial() { return T(); } - static void trace(JSTracer* trc, T* t, const char* name) {} - static bool needsSweep(T* v) { return false; } -}; -template <> struct GCPolicy : public IgnoreGCPolicy {}; -template <> struct GCPolicy : public IgnoreGCPolicy {}; - -template -struct GCPointerPolicy -{ - static T initial() { return nullptr; } - static void trace(JSTracer* trc, T* vp, const char* name) { - if (*vp) - js::UnsafeTraceManuallyBarrieredEdge(trc, vp, name); - } - static bool needsSweep(T* vp) { - if (*vp) - return js::gc::IsAboutToBeFinalizedUnbarriered(vp); - return false; - } -}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; - -template -struct GCPolicy> -{ - static void trace(JSTracer* trc, JS::Heap* thingp, const char* name) { - TraceEdge(trc, thingp, name); - } - static bool needsSweep(JS::Heap* thingp) { - return js::gc::EdgeNeedsSweep(thingp); - } -}; - -// GCPolicy> forwards the contained pointer to GCPolicy. -template -struct GCPolicy> -{ - static mozilla::UniquePtr initial() { return mozilla::UniquePtr(); } - static void trace(JSTracer* trc, mozilla::UniquePtr* tp, const char* name) { - if (tp->get()) - GCPolicy::trace(trc, tp->get(), name); - } - static bool needsSweep(mozilla::UniquePtr* tp) { - if (tp->get()) - return GCPolicy::needsSweep(tp->get()); - return false; - } -}; - -} // namespace JS - -#endif // GCPolicyAPI_h diff --git a/ios/include/spidermonkey/js/GCVariant.h b/ios/include/spidermonkey/js/GCVariant.h deleted file mode 100644 index 31ab23f5..00000000 --- a/ios/include/spidermonkey/js/GCVariant.h +++ /dev/null @@ -1,198 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCVariant_h -#define js_GCVariant_h - -#include "mozilla/Variant.h" - -#include "js/GCPolicyAPI.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" - -namespace JS { - -// These template specializations allow Variant to be used inside GC wrappers. -// -// When matching on GC wrappers around Variants, matching should be done on -// the wrapper itself. The matcher class's methods should take Handles or -// MutableHandles. For example, -// -// struct MyMatcher -// { -// using ReturnType = const char*; -// ReturnType match(HandleObject o) { return "object"; } -// ReturnType match(HandleScript s) { return "script"; } -// }; -// -// Rooted> v(cx, someScript); -// MyMatcher mm; -// v.match(mm); -// -// If you get compile errors about inability to upcast subclasses (e.g., from -// NativeObject* to JSObject*) and are inside js/src, be sure to also include -// "gc/Policy.h". - -namespace detail { - -template -struct GCVariantImplementation; - -// The base case. -template -struct GCVariantImplementation -{ - template - static void trace(JSTracer* trc, ConcreteVariant* v, const char* name) { - T& thing = v->template as(); - if (!mozilla::IsPointer::value || thing) - GCPolicy::trace(trc, &thing, name); - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, Handle v) { - const T& thing = v.get().template as(); - return matcher.match(Handle::fromMarkedLocation(&thing)); - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, MutableHandle v) { - T& thing = v.get().template as(); - return matcher.match(MutableHandle::fromMarkedLocation(&thing)); - } -}; - -// The inductive case. -template -struct GCVariantImplementation -{ - using Next = GCVariantImplementation; - - template - static void trace(JSTracer* trc, ConcreteVariant* v, const char* name) { - if (v->template is()) { - T& thing = v->template as(); - if (!mozilla::IsPointer::value || thing) - GCPolicy::trace(trc, &thing, name); - } else { - Next::trace(trc, v, name); - } - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, Handle v) { - if (v.get().template is()) { - const T& thing = v.get().template as(); - return matcher.match(Handle::fromMarkedLocation(&thing)); - } - return Next::match(matcher, v); - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, MutableHandle v) { - if (v.get().template is()) { - T& thing = v.get().template as(); - return matcher.match(MutableHandle::fromMarkedLocation(&thing)); - } - return Next::match(matcher, v); - } -}; - -} // namespace detail - -template -struct GCPolicy> -{ - using Impl = detail::GCVariantImplementation; - - // Variants do not provide initial(). They do not have a default initial - // value and one must be provided. - - static void trace(JSTracer* trc, mozilla::Variant* v, const char* name) { - Impl::trace(trc, v, name); - } -}; - -} // namespace JS - -namespace js { - -template -class GCVariantOperations -{ - using Impl = JS::detail::GCVariantImplementation; - using Variant = mozilla::Variant; - - const Variant& variant() const { return static_cast(this)->get(); } - - public: - template - bool is() const { - return variant().template is(); - } - - template - JS::Handle as() const { - return Handle::fromMarkedLocation(&variant().template as()); - } - - template - typename Matcher::ReturnType - match(Matcher& matcher) const { - return Impl::match(matcher, JS::Handle::fromMarkedLocation(&variant())); - } -}; - -template -class MutableGCVariantOperations - : public GCVariantOperations -{ - using Impl = JS::detail::GCVariantImplementation; - using Variant = mozilla::Variant; - - const Variant& variant() const { return static_cast(this)->get(); } - Variant& variant() { return static_cast(this)->get(); } - - public: - template - JS::MutableHandle as() { - return JS::MutableHandle::fromMarkedLocation(&variant().template as()); - } - - template - typename Matcher::ReturnType - match(Matcher& matcher) { - return Impl::match(matcher, JS::MutableHandle::fromMarkedLocation(&variant())); - } -}; - -template -class RootedBase> - : public MutableGCVariantOperations>, Ts...> -{ }; - -template -class MutableHandleBase> - : public MutableGCVariantOperations>, Ts...> -{ }; - -template -class HandleBase> - : public GCVariantOperations>, Ts...> -{ }; - -template -class PersistentRootedBase> - : public MutableGCVariantOperations>, Ts...> -{ }; - -} // namespace js - -#endif // js_GCVariant_h diff --git a/ios/include/spidermonkey/js/GCVector.h b/ios/include/spidermonkey/js/GCVector.h deleted file mode 100644 index 2668e65b..00000000 --- a/ios/include/spidermonkey/js/GCVector.h +++ /dev/null @@ -1,249 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCVector_h -#define js_GCVector_h - -#include "mozilla/Vector.h" - -#include "js/GCPolicyAPI.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" -#include "js/Vector.h" - -namespace JS { - -// A GCVector is a Vector with an additional trace method that knows how -// to visit all of the items stored in the Vector. For vectors that contain GC -// things, this is usually more convenient than manually iterating and marking -// the contents. -// -// Most types of GC pointers as keys and values can be traced with no extra -// infrastructure. For structs and non-gc-pointer members, ensure that there is -// a specialization of GCPolicy with an appropriate trace method available -// to handle the custom type. Generic helpers can be found in -// js/public/TracingAPI.h. -// -// Note that although this Vector's trace will deal correctly with moved items, -// it does not itself know when to barrier or trace items. To function properly -// it must either be used with Rooted, or barriered and traced manually. -template -class GCVector -{ - mozilla::Vector vector; - - public: - explicit GCVector(AllocPolicy alloc = AllocPolicy()) - : vector(alloc) - {} - - GCVector(GCVector&& vec) - : vector(mozilla::Move(vec.vector)) - {} - - GCVector& operator=(GCVector&& vec) { - vector = mozilla::Move(vec.vector); - return *this; - } - - size_t length() const { return vector.length(); } - bool empty() const { return vector.empty(); } - size_t capacity() const { return vector.capacity(); } - - T* begin() { return vector.begin(); } - const T* begin() const { return vector.begin(); } - - T* end() { return vector.end(); } - const T* end() const { return vector.end(); } - - T& operator[](size_t i) { return vector[i]; } - const T& operator[](size_t i) const { return vector[i]; } - - T& back() { return vector.back(); } - const T& back() const { return vector.back(); } - - bool initCapacity(size_t cap) { return vector.initCapacity(cap); } - bool reserve(size_t req) { return vector.reserve(req); } - void shrinkBy(size_t amount) { return vector.shrinkBy(amount); } - bool growBy(size_t amount) { return vector.growBy(amount); } - bool resize(size_t newLen) { return vector.resize(newLen); } - - void clear() { return vector.clear(); } - - template bool append(U&& item) { return vector.append(mozilla::Forward(item)); } - - template - bool - emplaceBack(Args&&... args) { - return vector.emplaceBack(mozilla::Forward(args)...); - } - - template - void infallibleAppend(U&& aU) { - return vector.infallibleAppend(mozilla::Forward(aU)); - } - void infallibleAppendN(const T& aT, size_t aN) { - return vector.infallibleAppendN(aT, aN); - } - template void - infallibleAppend(const U* aBegin, const U* aEnd) { - return vector.infallibleAppend(aBegin, aEnd); - } - template void infallibleAppend(const U* aBegin, size_t aLength) { - return vector.infallibleAppend(aBegin, aLength); - } - - template - bool appendAll(const mozilla::Vector& aU) { return vector.appendAll(aU); } - template - bool appendAll(const GCVector& aU) { return vector.append(aU.begin(), aU.length()); } - - bool appendN(const T& val, size_t count) { return vector.appendN(val, count); } - - template bool append(const U* aBegin, const U* aEnd) { - return vector.append(aBegin, aEnd); - } - template bool append(const U* aBegin, size_t aLength) { - return vector.append(aBegin, aLength); - } - - void popBack() { return vector.popBack(); } - T popCopy() { return vector.popCopy(); } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return vector.sizeOfExcludingThis(mallocSizeOf); - } - - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return vector.sizeOfIncludingThis(mallocSizeOf); - } - - static void trace(GCVector* vec, JSTracer* trc) { vec->trace(trc); } - - void trace(JSTracer* trc) { - for (auto& elem : vector) - GCPolicy::trace(trc, &elem, "vector element"); - } -}; - -} // namespace JS - -namespace js { - -template -class GCVectorOperations -{ - using Vec = JS::GCVector; - const Vec& vec() const { return static_cast(this)->get(); } - - public: - const AllocPolicy& allocPolicy() const { return vec().allocPolicy(); } - size_t length() const { return vec().length(); } - bool empty() const { return vec().empty(); } - size_t capacity() const { return vec().capacity(); } - const T* begin() const { return vec().begin(); } - const T* end() const { return vec().end(); } - const T& back() const { return vec().back(); } - - JS::Handle operator[](size_t aIndex) const { - return JS::Handle::fromMarkedLocation(&vec().operator[](aIndex)); - } -}; - -template -class MutableGCVectorOperations - : public GCVectorOperations -{ - using Vec = JS::GCVector; - const Vec& vec() const { return static_cast(this)->get(); } - Vec& vec() { return static_cast(this)->get(); } - - public: - const AllocPolicy& allocPolicy() const { return vec().allocPolicy(); } - AllocPolicy& allocPolicy() { return vec().allocPolicy(); } - const T* begin() const { return vec().begin(); } - T* begin() { return vec().begin(); } - const T* end() const { return vec().end(); } - T* end() { return vec().end(); } - const T& back() const { return vec().back(); } - T& back() { return vec().back(); } - - JS::Handle operator[](size_t aIndex) const { - return JS::Handle::fromMarkedLocation(&vec().operator[](aIndex)); - } - JS::MutableHandle operator[](size_t aIndex) { - return JS::MutableHandle::fromMarkedLocation(&vec().operator[](aIndex)); - } - - bool initCapacity(size_t aRequest) { return vec().initCapacity(aRequest); } - bool reserve(size_t aRequest) { return vec().reserve(aRequest); } - void shrinkBy(size_t aIncr) { vec().shrinkBy(aIncr); } - bool growBy(size_t aIncr) { return vec().growBy(aIncr); } - bool resize(size_t aNewLength) { return vec().resize(aNewLength); } - bool growByUninitialized(size_t aIncr) { return vec().growByUninitialized(aIncr); } - void infallibleGrowByUninitialized(size_t aIncr) { vec().infallibleGrowByUninitialized(aIncr); } - bool resizeUninitialized(size_t aNewLength) { return vec().resizeUninitialized(aNewLength); } - void clear() { vec().clear(); } - void clearAndFree() { vec().clearAndFree(); } - template bool append(U&& aU) { return vec().append(mozilla::Forward(aU)); } - template bool emplaceBack(Args&&... aArgs) { - return vec().emplaceBack(mozilla::Forward(aArgs...)); - } - template - bool appendAll(const mozilla::Vector& aU) { return vec().appendAll(aU); } - template - bool appendAll(const JS::GCVector& aU) { return vec().appendAll(aU); } - bool appendN(const T& aT, size_t aN) { return vec().appendN(aT, aN); } - template bool append(const U* aBegin, const U* aEnd) { - return vec().append(aBegin, aEnd); - } - template bool append(const U* aBegin, size_t aLength) { - return vec().append(aBegin, aLength); - } - template void infallibleAppend(U&& aU) { - vec().infallibleAppend(mozilla::Forward(aU)); - } - void infallibleAppendN(const T& aT, size_t aN) { vec().infallibleAppendN(aT, aN); } - template void infallibleAppend(const U* aBegin, const U* aEnd) { - vec().infallibleAppend(aBegin, aEnd); - } - template void infallibleAppend(const U* aBegin, size_t aLength) { - vec().infallibleAppend(aBegin, aLength); - } - void popBack() { vec().popBack(); } - T popCopy() { return vec().popCopy(); } - template T* insert(T* aP, U&& aVal) { - return vec().insert(aP, mozilla::Forward(aVal)); - } - void erase(T* aT) { vec().erase(aT); } - void erase(T* aBegin, T* aEnd) { vec().erase(aBegin, aEnd); } -}; - -template -class RootedBase> - : public MutableGCVectorOperations>, T,N,AP> -{}; - -template -class MutableHandleBase> - : public MutableGCVectorOperations>, T,N,AP> -{}; - -template -class HandleBase> - : public GCVectorOperations>, T,N,AP> -{}; - -template -class PersistentRootedBase> - : public MutableGCVectorOperations>, T,N,AP> -{}; - -} // namespace js - -#endif // js_GCVector_h diff --git a/ios/include/spidermonkey/js/HashTable.h b/ios/include/spidermonkey/js/HashTable.h deleted file mode 100644 index 5d4c0665..00000000 --- a/ios/include/spidermonkey/js/HashTable.h +++ /dev/null @@ -1,1880 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_HashTable_h -#define js_HashTable_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/HashFunctions.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/Opaque.h" -#include "mozilla/PodOperations.h" -#include "mozilla/ReentrancyGuard.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/UniquePtr.h" - -#include "js/Utility.h" - -namespace js { - -class TempAllocPolicy; -template struct DefaultHasher; -template class HashMapEntry; -namespace detail { - template class HashTableEntry; - template class HashTable; -} // namespace detail - -/*****************************************************************************/ - -// The "generation" of a hash table is an opaque value indicating the state of -// modification of the hash table through its lifetime. If the generation of -// a hash table compares equal at times T1 and T2, then lookups in the hash -// table, pointers to (or into) hash table entries, etc. at time T1 are valid -// at time T2. If the generation compares unequal, these computations are all -// invalid and must be performed again to be used. -// -// Generations are meaningfully comparable only with respect to a single hash -// table. It's always nonsensical to compare the generation of distinct hash -// tables H1 and H2. -using Generation = mozilla::Opaque; - -// A JS-friendly, STL-like container providing a hash-based map from keys to -// values. In particular, HashMap calls constructors and destructors of all -// objects added so non-PODs may be used safely. -// -// Key/Value requirements: -// - movable, destructible, assignable -// HashPolicy requirements: -// - see Hash Policy section below -// AllocPolicy: -// - see jsalloc.h -// -// Note: -// - HashMap is not reentrant: Key/Value/HashPolicy/AllocPolicy members -// called by HashMap must not call back into the same HashMap object. -// - Due to the lack of exception handling, the user must call |init()|. -template , - class AllocPolicy = TempAllocPolicy> -class HashMap -{ - typedef HashMapEntry TableEntry; - - struct MapHashPolicy : HashPolicy - { - using Base = HashPolicy; - typedef Key KeyType; - static const Key& getKey(TableEntry& e) { return e.key(); } - static void setKey(TableEntry& e, Key& k) { HashPolicy::rekey(e.mutableKey(), k); } - }; - - typedef detail::HashTable Impl; - Impl impl; - - public: - typedef typename HashPolicy::Lookup Lookup; - typedef TableEntry Entry; - - // HashMap construction is fallible (due to OOM); thus the user must call - // init after constructing a HashMap and check the return value. - explicit HashMap(AllocPolicy a = AllocPolicy()) : impl(a) {} - MOZ_MUST_USE bool init(uint32_t len = 16) { return impl.init(len); } - bool initialized() const { return impl.initialized(); } - - // Return whether the given lookup value is present in the map. E.g.: - // - // typedef HashMap HM; - // HM h; - // if (HM::Ptr p = h.lookup(3)) { - // const HM::Entry& e = *p; // p acts like a pointer to Entry - // assert(p->key == 3); // Entry contains the key - // char val = p->value; // and value - // } - // - // Also see the definition of Ptr in HashTable above (with T = Entry). - typedef typename Impl::Ptr Ptr; - Ptr lookup(const Lookup& l) const { return impl.lookup(l); } - - // Like lookup, but does not assert if two threads call lookup at the same - // time. Only use this method when none of the threads will modify the map. - Ptr readonlyThreadsafeLookup(const Lookup& l) const { return impl.readonlyThreadsafeLookup(l); } - - // Assuming |p.found()|, remove |*p|. - void remove(Ptr p) { impl.remove(p); } - - // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient - // insertion of Key |k| (where |HashPolicy::match(k,l) == true|) using - // |add(p,k,v)|. After |add(p,k,v)|, |p| points to the new Entry. E.g.: - // - // typedef HashMap HM; - // HM h; - // HM::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // if (!h.add(p, 3, 'a')) - // return false; - // } - // const HM::Entry& e = *p; // p acts like a pointer to Entry - // assert(p->key == 3); // Entry contains the key - // char val = p->value; // and value - // - // Also see the definition of AddPtr in HashTable above (with T = Entry). - // - // N.B. The caller must ensure that no mutating hash table operations - // occur between a pair of |lookupForAdd| and |add| calls. To avoid - // looking up the key a second time, the caller may use the more efficient - // relookupOrAdd method. This method reuses part of the hashing computation - // to more efficiently insert the key if it has not been added. For - // example, a mutation-handling version of the previous example: - // - // HM::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // call_that_may_mutate_h(); - // if (!h.relookupOrAdd(p, 3, 'a')) - // return false; - // } - // const HM::Entry& e = *p; - // assert(p->key == 3); - // char val = p->value; - typedef typename Impl::AddPtr AddPtr; - AddPtr lookupForAdd(const Lookup& l) const { - return impl.lookupForAdd(l); - } - - template - MOZ_MUST_USE bool add(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return impl.add(p, - mozilla::Forward(k), - mozilla::Forward(v)); - } - - template - MOZ_MUST_USE bool add(AddPtr& p, KeyInput&& k) { - return impl.add(p, mozilla::Forward(k), Value()); - } - - template - MOZ_MUST_USE bool relookupOrAdd(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return impl.relookupOrAdd(p, k, - mozilla::Forward(k), - mozilla::Forward(v)); - } - - // |all()| returns a Range containing |count()| elements. E.g.: - // - // typedef HashMap HM; - // HM h; - // for (HM::Range r = h.all(); !r.empty(); r.popFront()) - // char c = r.front().value(); - // - // Also see the definition of Range in HashTable above (with T = Entry). - typedef typename Impl::Range Range; - Range all() const { return impl.all(); } - - // Typedef for the enumeration class. An Enum may be used to examine and - // remove table entries: - // - // typedef HashMap HM; - // HM s; - // for (HM::Enum e(s); !e.empty(); e.popFront()) - // if (e.front().value() == 'l') - // e.removeFront(); - // - // Table resize may occur in Enum's destructor. Also see the definition of - // Enum in HashTable above (with T = Entry). - typedef typename Impl::Enum Enum; - - // Remove all entries. This does not shrink the table. For that consider - // using the finish() method. - void clear() { impl.clear(); } - - // Remove all the entries and release all internal buffers. The map must - // be initialized again before any use. - void finish() { impl.finish(); } - - // Does the table contain any entries? - bool empty() const { return impl.empty(); } - - // Number of live elements in the map. - uint32_t count() const { return impl.count(); } - - // Total number of allocation in the dynamic table. Note: resize will - // happen well before count() == capacity(). - size_t capacity() const { return impl.capacity(); } - - // Don't just call |impl.sizeOfExcludingThis()| because there's no - // guarantee that |impl| is the first field in HashMap. - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return impl.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); - } - - Generation generation() const { - return impl.generation(); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return impl.lookup(l).found(); - } - - // Overwrite existing value with v. Return false on oom. - template - MOZ_MUST_USE bool put(KeyInput&& k, ValueInput&& v) { - AddPtr p = lookupForAdd(k); - if (p) { - p->value() = mozilla::Forward(v); - return true; - } - return add(p, mozilla::Forward(k), mozilla::Forward(v)); - } - - // Like put, but assert that the given key is not already present. - template - MOZ_MUST_USE bool putNew(KeyInput&& k, ValueInput&& v) { - return impl.putNew(k, mozilla::Forward(k), mozilla::Forward(v)); - } - - // Only call this to populate an empty map after reserving space with init(). - template - void putNewInfallible(KeyInput&& k, ValueInput&& v) { - impl.putNewInfallible(k, mozilla::Forward(k), mozilla::Forward(v)); - } - - // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. - Ptr lookupWithDefault(const Key& k, const Value& defaultValue) { - AddPtr p = lookupForAdd(k); - if (p) - return p; - bool ok = add(p, k, defaultValue); - MOZ_ASSERT_IF(!ok, !p); // p is left false-y on oom. - (void)ok; - return p; - } - - // Remove if present. - void remove(const Lookup& l) { - if (Ptr p = lookup(l)) - remove(p); - } - - // Infallibly rekey one entry, if necessary. - // Requires template parameters Key and HashPolicy::Lookup to be the same type. - void rekeyIfMoved(const Key& old_key, const Key& new_key) { - if (old_key != new_key) - rekeyAs(old_key, new_key, new_key); - } - - // Infallibly rekey one entry if present, and return whether that happened. - bool rekeyAs(const Lookup& old_lookup, const Lookup& new_lookup, const Key& new_key) { - if (Ptr p = lookup(old_lookup)) { - impl.rekeyAndMaybeRehash(p, new_lookup, new_key); - return true; - } - return false; - } - - // HashMap is movable - HashMap(HashMap&& rhs) : impl(mozilla::Move(rhs.impl)) {} - void operator=(HashMap&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - impl = mozilla::Move(rhs.impl); - } - - private: - // HashMap is not copyable or assignable - HashMap(const HashMap& hm) = delete; - HashMap& operator=(const HashMap& hm) = delete; - - friend class Impl::Enum; -}; - -/*****************************************************************************/ - -// A JS-friendly, STL-like container providing a hash-based set of values. In -// particular, HashSet calls constructors and destructors of all objects added -// so non-PODs may be used safely. -// -// T requirements: -// - movable, destructible, assignable -// HashPolicy requirements: -// - see Hash Policy section below -// AllocPolicy: -// - see jsalloc.h -// -// Note: -// - HashSet is not reentrant: T/HashPolicy/AllocPolicy members called by -// HashSet must not call back into the same HashSet object. -// - Due to the lack of exception handling, the user must call |init()|. -template , - class AllocPolicy = TempAllocPolicy> -class HashSet -{ - struct SetOps : HashPolicy - { - using Base = HashPolicy; - typedef T KeyType; - static const KeyType& getKey(const T& t) { return t; } - static void setKey(T& t, KeyType& k) { HashPolicy::rekey(t, k); } - }; - - typedef detail::HashTable Impl; - Impl impl; - - public: - typedef typename HashPolicy::Lookup Lookup; - typedef T Entry; - - // HashSet construction is fallible (due to OOM); thus the user must call - // init after constructing a HashSet and check the return value. - explicit HashSet(AllocPolicy a = AllocPolicy()) : impl(a) {} - MOZ_MUST_USE bool init(uint32_t len = 16) { return impl.init(len); } - bool initialized() const { return impl.initialized(); } - - // Return whether the given lookup value is present in the map. E.g.: - // - // typedef HashSet HS; - // HS h; - // if (HS::Ptr p = h.lookup(3)) { - // assert(*p == 3); // p acts like a pointer to int - // } - // - // Also see the definition of Ptr in HashTable above. - typedef typename Impl::Ptr Ptr; - Ptr lookup(const Lookup& l) const { return impl.lookup(l); } - - // Like lookup, but does not assert if two threads call lookup at the same - // time. Only use this method when none of the threads will modify the map. - Ptr readonlyThreadsafeLookup(const Lookup& l) const { return impl.readonlyThreadsafeLookup(l); } - - // Assuming |p.found()|, remove |*p|. - void remove(Ptr p) { impl.remove(p); } - - // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient - // insertion of T value |t| (where |HashPolicy::match(t,l) == true|) using - // |add(p,t)|. After |add(p,t)|, |p| points to the new element. E.g.: - // - // typedef HashSet HS; - // HS h; - // HS::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // if (!h.add(p, 3)) - // return false; - // } - // assert(*p == 3); // p acts like a pointer to int - // - // Also see the definition of AddPtr in HashTable above. - // - // N.B. The caller must ensure that no mutating hash table operations - // occur between a pair of |lookupForAdd| and |add| calls. To avoid - // looking up the key a second time, the caller may use the more efficient - // relookupOrAdd method. This method reuses part of the hashing computation - // to more efficiently insert the key if it has not been added. For - // example, a mutation-handling version of the previous example: - // - // HS::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // call_that_may_mutate_h(); - // if (!h.relookupOrAdd(p, 3, 3)) - // return false; - // } - // assert(*p == 3); - // - // Note that relookupOrAdd(p,l,t) performs Lookup using |l| and adds the - // entry |t|, where the caller ensures match(l,t). - typedef typename Impl::AddPtr AddPtr; - AddPtr lookupForAdd(const Lookup& l) const { return impl.lookupForAdd(l); } - - template - MOZ_MUST_USE bool add(AddPtr& p, U&& u) { - return impl.add(p, mozilla::Forward(u)); - } - - template - MOZ_MUST_USE bool relookupOrAdd(AddPtr& p, const Lookup& l, U&& u) { - return impl.relookupOrAdd(p, l, mozilla::Forward(u)); - } - - // |all()| returns a Range containing |count()| elements: - // - // typedef HashSet HS; - // HS h; - // for (HS::Range r = h.all(); !r.empty(); r.popFront()) - // int i = r.front(); - // - // Also see the definition of Range in HashTable above. - typedef typename Impl::Range Range; - Range all() const { return impl.all(); } - - // Typedef for the enumeration class. An Enum may be used to examine and - // remove table entries: - // - // typedef HashSet HS; - // HS s; - // for (HS::Enum e(s); !e.empty(); e.popFront()) - // if (e.front() == 42) - // e.removeFront(); - // - // Table resize may occur in Enum's destructor. Also see the definition of - // Enum in HashTable above. - typedef typename Impl::Enum Enum; - - // Remove all entries. This does not shrink the table. For that consider - // using the finish() method. - void clear() { impl.clear(); } - - // Remove all the entries and release all internal buffers. The set must - // be initialized again before any use. - void finish() { impl.finish(); } - - // Does the table contain any entries? - bool empty() const { return impl.empty(); } - - // Number of live elements in the map. - uint32_t count() const { return impl.count(); } - - // Total number of allocation in the dynamic table. Note: resize will - // happen well before count() == capacity(). - size_t capacity() const { return impl.capacity(); } - - // Don't just call |impl.sizeOfExcludingThis()| because there's no - // guarantee that |impl| is the first field in HashSet. - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return impl.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); - } - - Generation generation() const { - return impl.generation(); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return impl.lookup(l).found(); - } - - // Add |u| if it is not present already. Return false on oom. - template - MOZ_MUST_USE bool put(U&& u) { - AddPtr p = lookupForAdd(u); - return p ? true : add(p, mozilla::Forward(u)); - } - - // Like put, but assert that the given key is not already present. - template - MOZ_MUST_USE bool putNew(U&& u) { - return impl.putNew(u, mozilla::Forward(u)); - } - - template - MOZ_MUST_USE bool putNew(const Lookup& l, U&& u) { - return impl.putNew(l, mozilla::Forward(u)); - } - - // Only call this to populate an empty set after reserving space with init(). - template - void putNewInfallible(const Lookup& l, U&& u) { - impl.putNewInfallible(l, mozilla::Forward(u)); - } - - void remove(const Lookup& l) { - if (Ptr p = lookup(l)) - remove(p); - } - - // Infallibly rekey one entry, if present. - // Requires template parameters T and HashPolicy::Lookup to be the same type. - void rekeyIfMoved(const Lookup& old_value, const T& new_value) { - if (old_value != new_value) - rekeyAs(old_value, new_value, new_value); - } - - // Infallibly rekey one entry if present, and return whether that happened. - bool rekeyAs(const Lookup& old_lookup, const Lookup& new_lookup, const T& new_value) { - if (Ptr p = lookup(old_lookup)) { - impl.rekeyAndMaybeRehash(p, new_lookup, new_value); - return true; - } - return false; - } - - // Infallibly replace the current key at |p| with an equivalent key. - // Specifically, both HashPolicy::hash and HashPolicy::match must return - // identical results for the new and old key when applied against all - // possible matching values. - void replaceKey(Ptr p, const T& new_value) { - MOZ_ASSERT(p.found()); - MOZ_ASSERT(*p != new_value); - MOZ_ASSERT(HashPolicy::hash(*p) == HashPolicy::hash(new_value)); - MOZ_ASSERT(HashPolicy::match(*p, new_value)); - const_cast(*p) = new_value; - } - - // HashSet is movable - HashSet(HashSet&& rhs) : impl(mozilla::Move(rhs.impl)) {} - void operator=(HashSet&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - impl = mozilla::Move(rhs.impl); - } - - private: - // HashSet is not copyable or assignable - HashSet(const HashSet& hs) = delete; - HashSet& operator=(const HashSet& hs) = delete; - - friend class Impl::Enum; -}; - -/*****************************************************************************/ - -// Hash Policy -// -// A hash policy P for a hash table with key-type Key must provide: -// - a type |P::Lookup| to use to lookup table entries; -// - a static member function |P::hash| with signature -// -// static js::HashNumber hash(Lookup) -// -// to use to hash the lookup type; and -// - a static member function |P::match| with signature -// -// static bool match(Key, Lookup) -// -// to use to test equality of key and lookup values. -// -// Normally, Lookup = Key. In general, though, different values and types of -// values can be used to lookup and store. If a Lookup value |l| is != to the -// added Key value |k|, the user must ensure that |P::match(k,l)|. E.g.: -// -// js::HashSet::AddPtr p = h.lookup(l); -// if (!p) { -// assert(P::match(k, l)); // must hold -// h.add(p, k); -// } - -// Pointer hashing policy that strips the lowest zeroBits when calculating the -// hash to improve key distribution. -template -struct PointerHasher -{ - typedef Key Lookup; - static HashNumber hash(const Lookup& l) { - size_t word = reinterpret_cast(l) >> zeroBits; - static_assert(sizeof(HashNumber) == 4, - "subsequent code assumes a four-byte hash"); -#if JS_BITS_PER_WORD == 32 - return HashNumber(word); -#else - static_assert(sizeof(word) == 8, - "unexpected word size, new hashing strategy required to " - "properly incorporate all bits"); - return HashNumber((word >> 32) ^ word); -#endif - } - static bool match(const Key& k, const Lookup& l) { - return k == l; - } - static void rekey(Key& k, const Key& newKey) { - k = newKey; - } -}; - -// Default hash policy: just use the 'lookup' value. This of course only -// works if the lookup value is integral. HashTable applies ScrambleHashCode to -// the result of the 'hash' which means that it is 'ok' if the lookup value is -// not well distributed over the HashNumber domain. -template -struct DefaultHasher -{ - typedef Key Lookup; - static HashNumber hash(const Lookup& l) { - // Hash if can implicitly cast to hash number type. - return l; - } - static bool match(const Key& k, const Lookup& l) { - // Use builtin or overloaded operator==. - return k == l; - } - static void rekey(Key& k, const Key& newKey) { - k = newKey; - } -}; - -// Specialize hashing policy for pointer types. It assumes that the type is -// at least word-aligned. For types with smaller size use PointerHasher. -template -struct DefaultHasher : PointerHasher::value> -{}; - -// Specialize hashing policy for mozilla::UniquePtr to proxy the UniquePtr's -// raw pointer to PointerHasher. -template -struct DefaultHasher> -{ - using Lookup = mozilla::UniquePtr; - using PtrHasher = PointerHasher::value>; - - static HashNumber hash(const Lookup& l) { - return PtrHasher::hash(l.get()); - } - static bool match(const mozilla::UniquePtr& k, const Lookup& l) { - return PtrHasher::match(k.get(), l.get()); - } - static void rekey(mozilla::UniquePtr& k, mozilla::UniquePtr&& newKey) { - k = mozilla::Move(newKey); - } -}; - -// For doubles, we can xor the two uint32s. -template <> -struct DefaultHasher -{ - typedef double Lookup; - static HashNumber hash(double d) { - static_assert(sizeof(HashNumber) == 4, - "subsequent code assumes a four-byte hash"); - uint64_t u = mozilla::BitwiseCast(d); - return HashNumber(u ^ (u >> 32)); - } - static bool match(double lhs, double rhs) { - return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); - } -}; - -template <> -struct DefaultHasher -{ - typedef float Lookup; - static HashNumber hash(float f) { - static_assert(sizeof(HashNumber) == 4, - "subsequent code assumes a four-byte hash"); - return HashNumber(mozilla::BitwiseCast(f)); - } - static bool match(float lhs, float rhs) { - return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); - } -}; - -// A hash policy that compares C strings. -struct CStringHasher -{ - typedef const char* Lookup; - static js::HashNumber hash(Lookup l) { - return mozilla::HashString(l); - } - static bool match(const char* key, Lookup lookup) { - return strcmp(key, lookup) == 0; - } -}; - -// Fallible hashing interface. -// -// Most of the time generating a hash code is infallible so this class provides -// default methods that always succeed. Specialize this class for your own hash -// policy to provide fallible hashing. -// -// This is used by MovableCellHasher to handle the fact that generating a unique -// ID for cell pointer may fail due to OOM. -template -struct FallibleHashMethods -{ - // Return true if a hashcode is already available for its argument. Once - // this returns true for a specific argument it must continue to do so. - template static bool hasHash(Lookup&& l) { return true; } - - // Fallible method to ensure a hashcode exists for its argument and create - // one if not. Returns false on error, e.g. out of memory. - template static bool ensureHash(Lookup&& l) { return true; } -}; - -template -static bool -HasHash(Lookup&& l) { - return FallibleHashMethods::hasHash(mozilla::Forward(l)); -} - -template -static bool -EnsureHash(Lookup&& l) { - return FallibleHashMethods::ensureHash(mozilla::Forward(l)); -} - -/*****************************************************************************/ - -// Both HashMap and HashSet are implemented by a single HashTable that is even -// more heavily parameterized than the other two. This leaves HashTable gnarly -// and extremely coupled to HashMap and HashSet; thus code should not use -// HashTable directly. - -template -class HashMapEntry -{ - Key key_; - Value value_; - - template friend class detail::HashTable; - template friend class detail::HashTableEntry; - template friend class HashMap; - - public: - template - HashMapEntry(KeyInput&& k, ValueInput&& v) - : key_(mozilla::Forward(k)), - value_(mozilla::Forward(v)) - {} - - HashMapEntry(HashMapEntry&& rhs) - : key_(mozilla::Move(rhs.key_)), - value_(mozilla::Move(rhs.value_)) - {} - - void operator=(HashMapEntry&& rhs) { - key_ = mozilla::Move(rhs.key_); - value_ = mozilla::Move(rhs.value_); - } - - typedef Key KeyType; - typedef Value ValueType; - - const Key& key() const { return key_; } - Key& mutableKey() { return key_; } - const Value& value() const { return value_; } - Value& value() { return value_; } - - private: - HashMapEntry(const HashMapEntry&) = delete; - void operator=(const HashMapEntry&) = delete; -}; - -} // namespace js - -namespace mozilla { - -template -struct IsPod > : IsPod {}; - -template -struct IsPod > - : IntegralConstant::value && IsPod::value> -{}; - -} // namespace mozilla - -namespace js { - -namespace detail { - -template -class HashTable; - -template -class HashTableEntry -{ - template friend class HashTable; - typedef typename mozilla::RemoveConst::Type NonConstT; - - HashNumber keyHash; - mozilla::AlignedStorage2 mem; - - static const HashNumber sFreeKey = 0; - static const HashNumber sRemovedKey = 1; - static const HashNumber sCollisionBit = 1; - - static bool isLiveHash(HashNumber hash) - { - return hash > sRemovedKey; - } - - HashTableEntry(const HashTableEntry&) = delete; - void operator=(const HashTableEntry&) = delete; - ~HashTableEntry() = delete; - - public: - // NB: HashTableEntry is treated as a POD: no constructor or destructor calls. - - void destroyIfLive() { - if (isLive()) - mem.addr()->~T(); - } - - void destroy() { - MOZ_ASSERT(isLive()); - mem.addr()->~T(); - } - - void swap(HashTableEntry* other) { - if (this == other) - return; - MOZ_ASSERT(isLive()); - if (other->isLive()) { - mozilla::Swap(*mem.addr(), *other->mem.addr()); - } else { - *other->mem.addr() = mozilla::Move(*mem.addr()); - destroy(); - } - mozilla::Swap(keyHash, other->keyHash); - } - - T& get() { MOZ_ASSERT(isLive()); return *mem.addr(); } - NonConstT& getMutable() { MOZ_ASSERT(isLive()); return *mem.addr(); } - - bool isFree() const { return keyHash == sFreeKey; } - void clearLive() { MOZ_ASSERT(isLive()); keyHash = sFreeKey; mem.addr()->~T(); } - void clear() { if (isLive()) mem.addr()->~T(); keyHash = sFreeKey; } - bool isRemoved() const { return keyHash == sRemovedKey; } - void removeLive() { MOZ_ASSERT(isLive()); keyHash = sRemovedKey; mem.addr()->~T(); } - bool isLive() const { return isLiveHash(keyHash); } - void setCollision() { MOZ_ASSERT(isLive()); keyHash |= sCollisionBit; } - void unsetCollision() { keyHash &= ~sCollisionBit; } - bool hasCollision() const { return keyHash & sCollisionBit; } - bool matchHash(HashNumber hn) { return (keyHash & ~sCollisionBit) == hn; } - HashNumber getKeyHash() const { return keyHash & ~sCollisionBit; } - - template - void setLive(HashNumber hn, Args&&... args) - { - MOZ_ASSERT(!isLive()); - keyHash = hn; - new(mem.addr()) T(mozilla::Forward(args)...); - MOZ_ASSERT(isLive()); - } -}; - -template -class HashTable : private AllocPolicy -{ - friend class mozilla::ReentrancyGuard; - - typedef typename mozilla::RemoveConst::Type NonConstT; - typedef typename HashPolicy::KeyType Key; - typedef typename HashPolicy::Lookup Lookup; - - public: - typedef HashTableEntry Entry; - - // A nullable pointer to a hash table element. A Ptr |p| can be tested - // either explicitly |if (p.found()) p->...| or using boolean conversion - // |if (p) p->...|. Ptr objects must not be used after any mutating hash - // table operations unless |generation()| is tested. - class Ptr - { - friend class HashTable; - - Entry* entry_; -#ifdef JS_DEBUG - const HashTable* table_; - Generation generation; -#endif - - protected: - Ptr(Entry& entry, const HashTable& tableArg) - : entry_(&entry) -#ifdef JS_DEBUG - , table_(&tableArg) - , generation(tableArg.generation()) -#endif - {} - - public: - Ptr() - : entry_(nullptr) -#ifdef JS_DEBUG - , table_(nullptr) - , generation(0) -#endif - {} - - bool isValid() const { - return !entry_; - } - - bool found() const { - if (isValid()) - return false; -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); -#endif - return entry_->isLive(); - } - - explicit operator bool() const { - return found(); - } - - bool operator==(const Ptr& rhs) const { - MOZ_ASSERT(found() && rhs.found()); - return entry_ == rhs.entry_; - } - - bool operator!=(const Ptr& rhs) const { -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); -#endif - return !(*this == rhs); - } - - T& operator*() const { -#ifdef JS_DEBUG - MOZ_ASSERT(found()); - MOZ_ASSERT(generation == table_->generation()); -#endif - return entry_->get(); - } - - T* operator->() const { -#ifdef JS_DEBUG - MOZ_ASSERT(found()); - MOZ_ASSERT(generation == table_->generation()); -#endif - return &entry_->get(); - } - }; - - // A Ptr that can be used to add a key after a failed lookup. - class AddPtr : public Ptr - { - friend class HashTable; - HashNumber keyHash; -#ifdef JS_DEBUG - uint64_t mutationCount; -#endif - - AddPtr(Entry& entry, const HashTable& tableArg, HashNumber hn) - : Ptr(entry, tableArg) - , keyHash(hn) -#ifdef JS_DEBUG - , mutationCount(tableArg.mutationCount) -#endif - {} - - public: - AddPtr() : keyHash(0) {} - }; - - // A collection of hash table entries. The collection is enumerated by - // calling |front()| followed by |popFront()| as long as |!empty()|. As - // with Ptr/AddPtr, Range objects must not be used after any mutating hash - // table operation unless the |generation()| is tested. - class Range - { - protected: - friend class HashTable; - - Range(const HashTable& tableArg, Entry* c, Entry* e) - : cur(c) - , end(e) -#ifdef JS_DEBUG - , table_(&tableArg) - , mutationCount(tableArg.mutationCount) - , generation(tableArg.generation()) - , validEntry(true) -#endif - { - while (cur < end && !cur->isLive()) - ++cur; - } - - Entry* cur; - Entry* end; -#ifdef JS_DEBUG - const HashTable* table_; - uint64_t mutationCount; - Generation generation; - bool validEntry; -#endif - - public: - Range() - : cur(nullptr) - , end(nullptr) -#ifdef JS_DEBUG - , table_(nullptr) - , mutationCount(0) - , generation(0) - , validEntry(false) -#endif - {} - - bool empty() const { -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); - MOZ_ASSERT(mutationCount == table_->mutationCount); -#endif - return cur == end; - } - - T& front() const { - MOZ_ASSERT(!empty()); -#ifdef JS_DEBUG - MOZ_ASSERT(validEntry); - MOZ_ASSERT(generation == table_->generation()); - MOZ_ASSERT(mutationCount == table_->mutationCount); -#endif - return cur->get(); - } - - void popFront() { - MOZ_ASSERT(!empty()); -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); - MOZ_ASSERT(mutationCount == table_->mutationCount); -#endif - while (++cur < end && !cur->isLive()) - continue; -#ifdef JS_DEBUG - validEntry = true; -#endif - } - }; - - // A Range whose lifetime delimits a mutating enumeration of a hash table. - // Since rehashing when elements were removed during enumeration would be - // bad, it is postponed until the Enum is destructed. Since the Enum's - // destructor touches the hash table, the user must ensure that the hash - // table is still alive when the destructor runs. - class Enum : public Range - { - friend class HashTable; - - HashTable& table_; - bool rekeyed; - bool removed; - - /* Not copyable. */ - Enum(const Enum&) = delete; - void operator=(const Enum&) = delete; - - public: - template explicit - Enum(Map& map) : Range(map.all()), table_(map.impl), rekeyed(false), removed(false) {} - - // Removes the |front()| element from the table, leaving |front()| - // invalid until the next call to |popFront()|. For example: - // - // HashSet s; - // for (HashSet::Enum e(s); !e.empty(); e.popFront()) - // if (e.front() == 42) - // e.removeFront(); - void removeFront() { - table_.remove(*this->cur); - removed = true; -#ifdef JS_DEBUG - this->validEntry = false; - this->mutationCount = table_.mutationCount; -#endif - } - - NonConstT& mutableFront() { - MOZ_ASSERT(!this->empty()); -#ifdef JS_DEBUG - MOZ_ASSERT(this->validEntry); - MOZ_ASSERT(this->generation == this->Range::table_->generation()); - MOZ_ASSERT(this->mutationCount == this->Range::table_->mutationCount); -#endif - return this->cur->getMutable(); - } - - // Removes the |front()| element and re-inserts it into the table with - // a new key at the new Lookup position. |front()| is invalid after - // this operation until the next call to |popFront()|. - void rekeyFront(const Lookup& l, const Key& k) { - MOZ_ASSERT(&k != &HashPolicy::getKey(this->cur->get())); - Ptr p(*this->cur, table_); - table_.rekeyWithoutRehash(p, l, k); - rekeyed = true; -#ifdef JS_DEBUG - this->validEntry = false; - this->mutationCount = table_.mutationCount; -#endif - } - - void rekeyFront(const Key& k) { - rekeyFront(k, k); - } - - // Potentially rehashes the table. - ~Enum() { - if (rekeyed) { - table_.gen++; - table_.checkOverRemoved(); - } - - if (removed) - table_.compactIfUnderloaded(); - } - }; - - // HashTable is movable - HashTable(HashTable&& rhs) - : AllocPolicy(rhs) - { - mozilla::PodAssign(this, &rhs); - rhs.table = nullptr; - } - void operator=(HashTable&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - if (table) - destroyTable(*this, table, capacity()); - mozilla::PodAssign(this, &rhs); - rhs.table = nullptr; - } - - private: - // HashTable is not copyable or assignable - HashTable(const HashTable&) = delete; - void operator=(const HashTable&) = delete; - - private: - static const size_t CAP_BITS = 30; - - public: - uint64_t gen:56; // entry storage generation number - uint64_t hashShift:8; // multiplicative hash shift - Entry* table; // entry storage - uint32_t entryCount; // number of entries in table - uint32_t removedCount; // removed entry sentinels in table - -#ifdef JS_DEBUG - uint64_t mutationCount; - mutable bool mEntered; - // Note that some updates to these stats are not thread-safe. See the - // comment on the three-argument overloading of HashTable::lookup(). - mutable struct Stats - { - uint32_t searches; // total number of table searches - uint32_t steps; // hash chain links traversed - uint32_t hits; // searches that found key - uint32_t misses; // searches that didn't find key - uint32_t addOverRemoved; // adds that recycled a removed entry - uint32_t removes; // calls to remove - uint32_t removeFrees; // calls to remove that freed the entry - uint32_t grows; // table expansions - uint32_t shrinks; // table contractions - uint32_t compresses; // table compressions - uint32_t rehashes; // tombstone decontaminations - } stats; -# define METER(x) x -#else -# define METER(x) -#endif - - // The default initial capacity is 32 (enough to hold 16 elements), but it - // can be as low as 4. - static const unsigned sMinCapacityLog2 = 2; - static const unsigned sMinCapacity = 1 << sMinCapacityLog2; - static const unsigned sMaxInit = JS_BIT(CAP_BITS - 1); - static const unsigned sMaxCapacity = JS_BIT(CAP_BITS); - static const unsigned sHashBits = mozilla::tl::BitSize::value; - - // Hash-table alpha is conceptually a fraction, but to avoid floating-point - // math we implement it as a ratio of integers. - static const uint8_t sAlphaDenominator = 4; - static const uint8_t sMinAlphaNumerator = 1; // min alpha: 1/4 - static const uint8_t sMaxAlphaNumerator = 3; // max alpha: 3/4 - - static const HashNumber sFreeKey = Entry::sFreeKey; - static const HashNumber sRemovedKey = Entry::sRemovedKey; - static const HashNumber sCollisionBit = Entry::sCollisionBit; - - void setTableSizeLog2(unsigned sizeLog2) - { - hashShift = sHashBits - sizeLog2; - } - - static bool isLiveHash(HashNumber hash) - { - return Entry::isLiveHash(hash); - } - - static HashNumber prepareHash(const Lookup& l) - { - HashNumber keyHash = ScrambleHashCode(HashPolicy::hash(l)); - - // Avoid reserved hash codes. - if (!isLiveHash(keyHash)) - keyHash -= (sRemovedKey + 1); - return keyHash & ~sCollisionBit; - } - - enum FailureBehavior { DontReportFailure = false, ReportFailure = true }; - - static Entry* createTable(AllocPolicy& alloc, uint32_t capacity, - FailureBehavior reportFailure = ReportFailure) - { - static_assert(sFreeKey == 0, - "newly-calloc'd tables have to be considered empty"); - if (reportFailure) - return alloc.template pod_calloc(capacity); - - return alloc.template maybe_pod_calloc(capacity); - } - - static Entry* maybeCreateTable(AllocPolicy& alloc, uint32_t capacity) - { - static_assert(sFreeKey == 0, - "newly-calloc'd tables have to be considered empty"); - return alloc.template maybe_pod_calloc(capacity); - } - - static void destroyTable(AllocPolicy& alloc, Entry* oldTable, uint32_t capacity) - { - Entry* end = oldTable + capacity; - for (Entry* e = oldTable; e < end; ++e) - e->destroyIfLive(); - alloc.free_(oldTable); - } - - public: - explicit HashTable(AllocPolicy ap) - : AllocPolicy(ap) - , gen(0) - , hashShift(sHashBits) - , table(nullptr) - , entryCount(0) - , removedCount(0) -#ifdef JS_DEBUG - , mutationCount(0) - , mEntered(false) -#endif - {} - - MOZ_MUST_USE bool init(uint32_t length) - { - MOZ_ASSERT(!initialized()); - - // Reject all lengths whose initial computed capacity would exceed - // sMaxCapacity. Round that maximum length down to the nearest power - // of two for speedier code. - if (MOZ_UNLIKELY(length > sMaxInit)) { - this->reportAllocOverflow(); - return false; - } - - static_assert((sMaxInit * sAlphaDenominator) / sAlphaDenominator == sMaxInit, - "multiplication in numerator below could overflow"); - static_assert(sMaxInit * sAlphaDenominator <= UINT32_MAX - sMaxAlphaNumerator, - "numerator calculation below could potentially overflow"); - - // Compute the smallest capacity allowing |length| elements to be - // inserted without rehashing: ceil(length / max-alpha). (Ceiling - // integral division: .) - uint32_t newCapacity = - (length * sAlphaDenominator + sMaxAlphaNumerator - 1) / sMaxAlphaNumerator; - if (newCapacity < sMinCapacity) - newCapacity = sMinCapacity; - - // FIXME: use JS_CEILING_LOG2 when PGO stops crashing (bug 543034). - uint32_t roundUp = sMinCapacity, roundUpLog2 = sMinCapacityLog2; - while (roundUp < newCapacity) { - roundUp <<= 1; - ++roundUpLog2; - } - - newCapacity = roundUp; - MOZ_ASSERT(newCapacity >= length); - MOZ_ASSERT(newCapacity <= sMaxCapacity); - - table = createTable(*this, newCapacity); - if (!table) - return false; - - setTableSizeLog2(roundUpLog2); - METER(memset(&stats, 0, sizeof(stats))); - return true; - } - - bool initialized() const - { - return !!table; - } - - ~HashTable() - { - if (table) - destroyTable(*this, table, capacity()); - } - - private: - HashNumber hash1(HashNumber hash0) const - { - return hash0 >> hashShift; - } - - struct DoubleHash - { - HashNumber h2; - HashNumber sizeMask; - }; - - DoubleHash hash2(HashNumber curKeyHash) const - { - unsigned sizeLog2 = sHashBits - hashShift; - DoubleHash dh = { - ((curKeyHash << sizeLog2) >> hashShift) | 1, - (HashNumber(1) << sizeLog2) - 1 - }; - return dh; - } - - static HashNumber applyDoubleHash(HashNumber h1, const DoubleHash& dh) - { - return (h1 - dh.h2) & dh.sizeMask; - } - - bool overloaded() - { - static_assert(sMaxCapacity <= UINT32_MAX / sMaxAlphaNumerator, - "multiplication below could overflow"); - return entryCount + removedCount >= - capacity() * sMaxAlphaNumerator / sAlphaDenominator; - } - - // Would the table be underloaded if it had the given capacity and entryCount? - static bool wouldBeUnderloaded(uint32_t capacity, uint32_t entryCount) - { - static_assert(sMaxCapacity <= UINT32_MAX / sMinAlphaNumerator, - "multiplication below could overflow"); - return capacity > sMinCapacity && - entryCount <= capacity * sMinAlphaNumerator / sAlphaDenominator; - } - - bool underloaded() - { - return wouldBeUnderloaded(capacity(), entryCount); - } - - static bool match(Entry& e, const Lookup& l) - { - return HashPolicy::match(HashPolicy::getKey(e.get()), l); - } - - // Warning: in order for readonlyThreadsafeLookup() to be safe this - // function must not modify the table in any way when |collisionBit| is 0. - // (The use of the METER() macro to increment stats violates this - // restriction but we will live with that for now because it's enabled so - // rarely.) - Entry& lookup(const Lookup& l, HashNumber keyHash, unsigned collisionBit) const - { - MOZ_ASSERT(isLiveHash(keyHash)); - MOZ_ASSERT(!(keyHash & sCollisionBit)); - MOZ_ASSERT(collisionBit == 0 || collisionBit == sCollisionBit); - MOZ_ASSERT(table); - METER(stats.searches++); - - // Compute the primary hash address. - HashNumber h1 = hash1(keyHash); - Entry* entry = &table[h1]; - - // Miss: return space for a new entry. - if (entry->isFree()) { - METER(stats.misses++); - return *entry; - } - - // Hit: return entry. - if (entry->matchHash(keyHash) && match(*entry, l)) { - METER(stats.hits++); - return *entry; - } - - // Collision: double hash. - DoubleHash dh = hash2(keyHash); - - // Save the first removed entry pointer so we can recycle later. - Entry* firstRemoved = nullptr; - - while (true) { - if (MOZ_UNLIKELY(entry->isRemoved())) { - if (!firstRemoved) - firstRemoved = entry; - } else { - if (collisionBit == sCollisionBit) - entry->setCollision(); - } - - METER(stats.steps++); - h1 = applyDoubleHash(h1, dh); - - entry = &table[h1]; - if (entry->isFree()) { - METER(stats.misses++); - return firstRemoved ? *firstRemoved : *entry; - } - - if (entry->matchHash(keyHash) && match(*entry, l)) { - METER(stats.hits++); - return *entry; - } - } - } - - // This is a copy of lookup hardcoded to the assumptions: - // 1. the lookup is a lookupForAdd - // 2. the key, whose |keyHash| has been passed is not in the table, - // 3. no entries have been removed from the table. - // This specialized search avoids the need for recovering lookup values - // from entries, which allows more flexible Lookup/Key types. - Entry& findFreeEntry(HashNumber keyHash) - { - MOZ_ASSERT(!(keyHash & sCollisionBit)); - MOZ_ASSERT(table); - METER(stats.searches++); - - // We assume 'keyHash' has already been distributed. - - // Compute the primary hash address. - HashNumber h1 = hash1(keyHash); - Entry* entry = &table[h1]; - - // Miss: return space for a new entry. - if (!entry->isLive()) { - METER(stats.misses++); - return *entry; - } - - // Collision: double hash. - DoubleHash dh = hash2(keyHash); - - while (true) { - MOZ_ASSERT(!entry->isRemoved()); - entry->setCollision(); - - METER(stats.steps++); - h1 = applyDoubleHash(h1, dh); - - entry = &table[h1]; - if (!entry->isLive()) { - METER(stats.misses++); - return *entry; - } - } - } - - enum RebuildStatus { NotOverloaded, Rehashed, RehashFailed }; - - RebuildStatus changeTableSize(int deltaLog2, FailureBehavior reportFailure = ReportFailure) - { - // Look, but don't touch, until we succeed in getting new entry store. - Entry* oldTable = table; - uint32_t oldCap = capacity(); - uint32_t newLog2 = sHashBits - hashShift + deltaLog2; - uint32_t newCapacity = JS_BIT(newLog2); - if (MOZ_UNLIKELY(newCapacity > sMaxCapacity)) { - if (reportFailure) - this->reportAllocOverflow(); - return RehashFailed; - } - - Entry* newTable = createTable(*this, newCapacity, reportFailure); - if (!newTable) - return RehashFailed; - - // We can't fail from here on, so update table parameters. - setTableSizeLog2(newLog2); - removedCount = 0; - gen++; - table = newTable; - - // Copy only live entries, leaving removed ones behind. - Entry* end = oldTable + oldCap; - for (Entry* src = oldTable; src < end; ++src) { - if (src->isLive()) { - HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive( - hn, mozilla::Move(const_cast(src->get()))); - src->destroy(); - } - } - - // All entries have been destroyed, no need to destroyTable. - this->free_(oldTable); - return Rehashed; - } - - bool shouldCompressTable() - { - // Compress if a quarter or more of all entries are removed. - return removedCount >= (capacity() >> 2); - } - - RebuildStatus checkOverloaded(FailureBehavior reportFailure = ReportFailure) - { - if (!overloaded()) - return NotOverloaded; - - int deltaLog2; - if (shouldCompressTable()) { - METER(stats.compresses++); - deltaLog2 = 0; - } else { - METER(stats.grows++); - deltaLog2 = 1; - } - - return changeTableSize(deltaLog2, reportFailure); - } - - // Infallibly rehash the table if we are overloaded with removals. - void checkOverRemoved() - { - if (overloaded()) { - if (checkOverloaded(DontReportFailure) == RehashFailed) - rehashTableInPlace(); - } - } - - void remove(Entry& e) - { - MOZ_ASSERT(table); - METER(stats.removes++); - - if (e.hasCollision()) { - e.removeLive(); - removedCount++; - } else { - METER(stats.removeFrees++); - e.clearLive(); - } - entryCount--; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - void checkUnderloaded() - { - if (underloaded()) { - METER(stats.shrinks++); - (void) changeTableSize(-1, DontReportFailure); - } - } - - // Resize the table down to the largest capacity which doesn't underload the - // table. Since we call checkUnderloaded() on every remove, you only need - // to call this after a bulk removal of items done without calling remove(). - void compactIfUnderloaded() - { - int32_t resizeLog2 = 0; - uint32_t newCapacity = capacity(); - while (wouldBeUnderloaded(newCapacity, entryCount)) { - newCapacity = newCapacity >> 1; - resizeLog2--; - } - - if (resizeLog2 != 0) - (void) changeTableSize(resizeLog2, DontReportFailure); - } - - // This is identical to changeTableSize(currentSize), but without requiring - // a second table. We do this by recycling the collision bits to tell us if - // the element is already inserted or still waiting to be inserted. Since - // already-inserted elements win any conflicts, we get the same table as we - // would have gotten through random insertion order. - void rehashTableInPlace() - { - METER(stats.rehashes++); - removedCount = 0; - for (size_t i = 0; i < capacity(); ++i) - table[i].unsetCollision(); - - for (size_t i = 0; i < capacity();) { - Entry* src = &table[i]; - - if (!src->isLive() || src->hasCollision()) { - ++i; - continue; - } - - HashNumber keyHash = src->getKeyHash(); - HashNumber h1 = hash1(keyHash); - DoubleHash dh = hash2(keyHash); - Entry* tgt = &table[h1]; - while (true) { - if (!tgt->hasCollision()) { - src->swap(tgt); - tgt->setCollision(); - break; - } - - h1 = applyDoubleHash(h1, dh); - tgt = &table[h1]; - } - } - - // TODO: this algorithm leaves collision bits on *all* elements, even if - // they are on no collision path. We have the option of setting the - // collision bits correctly on a subsequent pass or skipping the rehash - // unless we are totally filled with tombstones: benchmark to find out - // which approach is best. - } - - // Note: |l| may be a reference to a piece of |u|, so this function - // must take care not to use |l| after moving |u|. - // - // Prefer to use putNewInfallible; this function does not check - // invariants. - template - void putNewInfallibleInternal(const Lookup& l, Args&&... args) - { - MOZ_ASSERT(table); - - HashNumber keyHash = prepareHash(l); - Entry* entry = &findFreeEntry(keyHash); - MOZ_ASSERT(entry); - - if (entry->isRemoved()) { - METER(stats.addOverRemoved++); - removedCount--; - keyHash |= sCollisionBit; - } - - entry->setLive(keyHash, mozilla::Forward(args)...); - entryCount++; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - public: - void clear() - { - if (mozilla::IsPod::value) { - memset(table, 0, sizeof(*table) * capacity()); - } else { - uint32_t tableCapacity = capacity(); - Entry* end = table + tableCapacity; - for (Entry* e = table; e < end; ++e) - e->clear(); - } - removedCount = 0; - entryCount = 0; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - void finish() - { -#ifdef JS_DEBUG - MOZ_ASSERT(!mEntered); -#endif - if (!table) - return; - - destroyTable(*this, table, capacity()); - table = nullptr; - gen++; - entryCount = 0; - removedCount = 0; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - Range all() const - { - MOZ_ASSERT(table); - return Range(*this, table, table + capacity()); - } - - bool empty() const - { - MOZ_ASSERT(table); - return !entryCount; - } - - uint32_t count() const - { - MOZ_ASSERT(table); - return entryCount; - } - - uint32_t capacity() const - { - MOZ_ASSERT(table); - return JS_BIT(sHashBits - hashShift); - } - - Generation generation() const - { - MOZ_ASSERT(table); - return Generation(gen); - } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const - { - return mallocSizeOf(table); - } - - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const - { - return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); - } - - Ptr lookup(const Lookup& l) const - { - mozilla::ReentrancyGuard g(*this); - if (!HasHash(l)) - return Ptr(); - HashNumber keyHash = prepareHash(l); - return Ptr(lookup(l, keyHash, 0), *this); - } - - Ptr readonlyThreadsafeLookup(const Lookup& l) const - { - if (!HasHash(l)) - return Ptr(); - HashNumber keyHash = prepareHash(l); - return Ptr(lookup(l, keyHash, 0), *this); - } - - AddPtr lookupForAdd(const Lookup& l) const - { - mozilla::ReentrancyGuard g(*this); - if (!EnsureHash(l)) - return AddPtr(); - HashNumber keyHash = prepareHash(l); - Entry& entry = lookup(l, keyHash, sCollisionBit); - AddPtr p(entry, *this, keyHash); - return p; - } - - template - MOZ_MUST_USE bool add(AddPtr& p, Args&&... args) - { - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(table); - MOZ_ASSERT(!p.found()); - MOZ_ASSERT(!(p.keyHash & sCollisionBit)); - - // Check for error from ensureHash() here. - if (p.isValid()) - return false; - - // Changing an entry from removed to live does not affect whether we - // are overloaded and can be handled separately. - if (p.entry_->isRemoved()) { - if (!this->checkSimulatedOOM()) - return false; - METER(stats.addOverRemoved++); - removedCount--; - p.keyHash |= sCollisionBit; - } else { - // Preserve the validity of |p.entry_|. - RebuildStatus status = checkOverloaded(); - if (status == RehashFailed) - return false; - if (status == NotOverloaded && !this->checkSimulatedOOM()) - return false; - if (status == Rehashed) - p.entry_ = &findFreeEntry(p.keyHash); - } - - p.entry_->setLive(p.keyHash, mozilla::Forward(args)...); - entryCount++; -#ifdef JS_DEBUG - mutationCount++; - p.generation = generation(); - p.mutationCount = mutationCount; -#endif - return true; - } - - // Note: |l| may be a reference to a piece of |u|, so this function - // must take care not to use |l| after moving |u|. - template - void putNewInfallible(const Lookup& l, Args&&... args) - { - MOZ_ASSERT(!lookup(l).found()); - mozilla::ReentrancyGuard g(*this); - putNewInfallibleInternal(l, mozilla::Forward(args)...); - } - - // Note: |l| may be alias arguments in |args|, so this function must take - // care not to use |l| after moving |args|. - template - MOZ_MUST_USE bool putNew(const Lookup& l, Args&&... args) - { - if (!this->checkSimulatedOOM()) - return false; - - if (!EnsureHash(l)) - return false; - - if (checkOverloaded() == RehashFailed) - return false; - - putNewInfallible(l, mozilla::Forward(args)...); - return true; - } - - // Note: |l| may be a reference to a piece of |u|, so this function - // must take care not to use |l| after moving |u|. - template - MOZ_MUST_USE bool relookupOrAdd(AddPtr& p, const Lookup& l, Args&&... args) - { - // Check for error from ensureHash() here. - if (p.isValid()) - return false; - -#ifdef JS_DEBUG - p.generation = generation(); - p.mutationCount = mutationCount; -#endif - { - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(prepareHash(l) == p.keyHash); // l has not been destroyed - p.entry_ = &lookup(l, p.keyHash, sCollisionBit); - } - return p.found() || add(p, mozilla::Forward(args)...); - } - - void remove(Ptr p) - { - MOZ_ASSERT(table); - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(p.found()); - remove(*p.entry_); - checkUnderloaded(); - } - - void rekeyWithoutRehash(Ptr p, const Lookup& l, const Key& k) - { - MOZ_ASSERT(table); - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(p.found()); - typename HashTableEntry::NonConstT t(mozilla::Move(*p)); - HashPolicy::setKey(t, const_cast(k)); - remove(*p.entry_); - putNewInfallibleInternal(l, mozilla::Move(t)); - } - - void rekeyAndMaybeRehash(Ptr p, const Lookup& l, const Key& k) - { - rekeyWithoutRehash(p, l, k); - checkOverRemoved(); - } - -#undef METER -}; - -} // namespace detail -} // namespace js - -#endif /* js_HashTable_h */ diff --git a/ios/include/spidermonkey/js/HeapAPI.h b/ios/include/spidermonkey/js/HeapAPI.h deleted file mode 100644 index e37d13e9..00000000 --- a/ios/include/spidermonkey/js/HeapAPI.h +++ /dev/null @@ -1,406 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_HeapAPI_h -#define js_HeapAPI_h - -#include - -#include "jspubtd.h" - -#include "js/TraceKind.h" -#include "js/Utility.h" - -/* These values are private to the JS engine. */ -namespace js { - -JS_FRIEND_API(bool) -CurrentThreadCanAccessZone(JS::Zone* zone); - -namespace gc { - -struct Cell; - -const size_t ArenaShift = 12; -const size_t ArenaSize = size_t(1) << ArenaShift; -const size_t ArenaMask = ArenaSize - 1; - -#ifdef JS_GC_SMALL_CHUNK_SIZE -const size_t ChunkShift = 18; -#else -const size_t ChunkShift = 20; -#endif -const size_t ChunkSize = size_t(1) << ChunkShift; -const size_t ChunkMask = ChunkSize - 1; - -const size_t CellShift = 3; -const size_t CellSize = size_t(1) << CellShift; -const size_t CellMask = CellSize - 1; - -/* These are magic constants derived from actual offsets in gc/Heap.h. */ -#ifdef JS_GC_SMALL_CHUNK_SIZE -const size_t ChunkMarkBitmapOffset = 258104; -const size_t ChunkMarkBitmapBits = 31744; -#else -const size_t ChunkMarkBitmapOffset = 1032352; -const size_t ChunkMarkBitmapBits = 129024; -#endif -const size_t ChunkRuntimeOffset = ChunkSize - sizeof(void*); -const size_t ChunkTrailerSize = 2 * sizeof(uintptr_t) + sizeof(uint64_t); -const size_t ChunkLocationOffset = ChunkSize - ChunkTrailerSize; -const size_t ArenaZoneOffset = sizeof(size_t); -const size_t ArenaHeaderSize = sizeof(size_t) + 2 * sizeof(uintptr_t) + - sizeof(size_t) + sizeof(uintptr_t); - -/* - * Live objects are marked black. How many other additional colors are available - * depends on the size of the GCThing. Objects marked gray are eligible for - * cycle collection. - */ -static const uint32_t BLACK = 0; -static const uint32_t GRAY = 1; - -/* - * The "location" field in the Chunk trailer is a enum indicating various roles - * of the chunk. - */ -enum class ChunkLocation : uint32_t -{ - Invalid = 0, - Nursery = 1, - TenuredHeap = 2 -}; - -#ifdef JS_DEBUG -/* When downcasting, ensure we are actually the right type. */ -extern JS_FRIEND_API(void) -AssertGCThingHasType(js::gc::Cell* cell, JS::TraceKind kind); -#else -inline void -AssertGCThingHasType(js::gc::Cell* cell, JS::TraceKind kind) {} -#endif - -MOZ_ALWAYS_INLINE bool IsInsideNursery(const js::gc::Cell* cell); - -} /* namespace gc */ -} /* namespace js */ - -namespace JS { -struct Zone; - -/* Default size for the generational nursery in bytes. */ -const uint32_t DefaultNurseryBytes = 16 * js::gc::ChunkSize; - -/* Default maximum heap size in bytes to pass to JS_NewRuntime(). */ -const uint32_t DefaultHeapMaxBytes = 32 * 1024 * 1024; - -namespace shadow { - -struct Zone -{ - protected: - JSRuntime* const runtime_; - JSTracer* const barrierTracer_; // A pointer to the JSRuntime's |gcMarker|. - - public: - // Stack GC roots for Rooted GC pointers. - js::RootedListHeads stackRoots_; - template friend class JS::Rooted; - - bool needsIncrementalBarrier_; - - Zone(JSRuntime* runtime, JSTracer* barrierTracerArg) - : runtime_(runtime), - barrierTracer_(barrierTracerArg), - needsIncrementalBarrier_(false) - { - for (auto& stackRootPtr : stackRoots_) - stackRootPtr = nullptr; - } - - bool needsIncrementalBarrier() const { - return needsIncrementalBarrier_; - } - - JSTracer* barrierTracer() { - MOZ_ASSERT(needsIncrementalBarrier_); - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); - return barrierTracer_; - } - - JSRuntime* runtimeFromMainThread() const { - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); - return runtime_; - } - - // Note: Unrestricted access to the zone's runtime from an arbitrary - // thread can easily lead to races. Use this method very carefully. - JSRuntime* runtimeFromAnyThread() const { - return runtime_; - } - - static MOZ_ALWAYS_INLINE JS::shadow::Zone* asShadowZone(JS::Zone* zone) { - return reinterpret_cast(zone); - } -}; - -} /* namespace shadow */ - -/** - * A GC pointer, tagged with the trace kind. - * - * In general, a GC pointer should be stored with an exact type. This class - * is for use when that is not possible because a single pointer must point - * to several kinds of GC thing. - */ -class JS_FRIEND_API(GCCellPtr) -{ - public: - // Construction from a void* and trace kind. - GCCellPtr(void* gcthing, JS::TraceKind traceKind) : ptr(checkedCast(gcthing, traceKind)) {} - - // Automatically construct a null GCCellPtr from nullptr. - MOZ_IMPLICIT GCCellPtr(decltype(nullptr)) : ptr(checkedCast(nullptr, JS::TraceKind::Null)) {} - - // Construction from an explicit type. - template - explicit GCCellPtr(T* p) : ptr(checkedCast(p, JS::MapTypeToTraceKind::kind)) { } - explicit GCCellPtr(JSFunction* p) : ptr(checkedCast(p, JS::TraceKind::Object)) { } - explicit GCCellPtr(JSFlatString* str) : ptr(checkedCast(str, JS::TraceKind::String)) { } - explicit GCCellPtr(const Value& v); - - JS::TraceKind kind() const { - JS::TraceKind traceKind = JS::TraceKind(ptr & OutOfLineTraceKindMask); - if (uintptr_t(traceKind) != OutOfLineTraceKindMask) - return traceKind; - return outOfLineKind(); - } - - // Allow GCCellPtr to be used in a boolean context. - explicit operator bool() const { - MOZ_ASSERT(bool(asCell()) == (kind() != JS::TraceKind::Null)); - return asCell(); - } - - // Simplify checks to the kind. - template - bool is() const { return kind() == JS::MapTypeToTraceKind::kind; } - - // Conversions to more specific types must match the kind. Access to - // further refined types is not allowed directly from a GCCellPtr. - template - T& as() const { - MOZ_ASSERT(kind() == JS::MapTypeToTraceKind::kind); - // We can't use static_cast here, because the fact that JSObject - // inherits from js::gc::Cell is not part of the public API. - return *reinterpret_cast(asCell()); - } - - // Return a pointer to the cell this |GCCellPtr| refers to, or |nullptr|. - // (It would be more symmetrical with |to| for this to return a |Cell&|, but - // the result can be |nullptr|, and null references are undefined behavior.) - js::gc::Cell* asCell() const { - return reinterpret_cast(ptr & ~OutOfLineTraceKindMask); - } - - // The CC's trace logger needs an identity that is XPIDL serializable. - uint64_t unsafeAsInteger() const { - return static_cast(unsafeAsUIntPtr()); - } - // Inline mark bitmap access requires direct pointer arithmetic. - uintptr_t unsafeAsUIntPtr() const { - MOZ_ASSERT(asCell()); - MOZ_ASSERT(!js::gc::IsInsideNursery(asCell())); - return reinterpret_cast(asCell()); - } - - bool mayBeOwnedByOtherRuntime() const; - - private: - static uintptr_t checkedCast(void* p, JS::TraceKind traceKind) { - js::gc::Cell* cell = static_cast(p); - MOZ_ASSERT((uintptr_t(p) & OutOfLineTraceKindMask) == 0); - AssertGCThingHasType(cell, traceKind); - // Note: the OutOfLineTraceKindMask bits are set on all out-of-line kinds - // so that we can mask instead of branching. - MOZ_ASSERT_IF(uintptr_t(traceKind) >= OutOfLineTraceKindMask, - (uintptr_t(traceKind) & OutOfLineTraceKindMask) == OutOfLineTraceKindMask); - return uintptr_t(p) | (uintptr_t(traceKind) & OutOfLineTraceKindMask); - } - - JS::TraceKind outOfLineKind() const; - - uintptr_t ptr; -}; - -inline bool -operator==(const GCCellPtr& ptr1, const GCCellPtr& ptr2) -{ - return ptr1.asCell() == ptr2.asCell(); -} - -inline bool -operator!=(const GCCellPtr& ptr1, const GCCellPtr& ptr2) -{ - return !(ptr1 == ptr2); -} - -// Unwraps the given GCCellPtr and calls the given functor with a template -// argument of the actual type of the pointer. -template -auto -DispatchTyped(F f, GCCellPtr thing, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - switch (thing.kind()) { -#define JS_EXPAND_DEF(name, type, _) \ - case JS::TraceKind::name: \ - return f(&thing.as(), mozilla::Forward(args)...); - JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - default: - MOZ_CRASH("Invalid trace kind in DispatchTyped for GCCellPtr."); - } -} - -} /* namespace JS */ - -namespace js { -namespace gc { -namespace detail { - -static MOZ_ALWAYS_INLINE uintptr_t* -GetGCThingMarkBitmap(const uintptr_t addr) -{ - MOZ_ASSERT(addr); - const uintptr_t bmap_addr = (addr & ~ChunkMask) | ChunkMarkBitmapOffset; - return reinterpret_cast(bmap_addr); -} - -static MOZ_ALWAYS_INLINE void -GetGCThingMarkWordAndMask(const uintptr_t addr, uint32_t color, - uintptr_t** wordp, uintptr_t* maskp) -{ - MOZ_ASSERT(addr); - const size_t bit = (addr & js::gc::ChunkMask) / js::gc::CellSize + color; - MOZ_ASSERT(bit < js::gc::ChunkMarkBitmapBits); - uintptr_t* bitmap = GetGCThingMarkBitmap(addr); - const uintptr_t nbits = sizeof(*bitmap) * CHAR_BIT; - *maskp = uintptr_t(1) << (bit % nbits); - *wordp = &bitmap[bit / nbits]; -} - -static MOZ_ALWAYS_INLINE JS::Zone* -GetGCThingZone(const uintptr_t addr) -{ - MOZ_ASSERT(addr); - const uintptr_t zone_addr = (addr & ~ArenaMask) | ArenaZoneOffset; - return *reinterpret_cast(zone_addr); - -} - -static MOZ_ALWAYS_INLINE JS::shadow::Runtime* -GetCellRuntime(const Cell* cell) -{ - MOZ_ASSERT(cell); - const uintptr_t addr = uintptr_t(cell); - const uintptr_t rt_addr = (addr & ~ChunkMask) | ChunkRuntimeOffset; - return *reinterpret_cast(rt_addr); -} - -static MOZ_ALWAYS_INLINE bool -CellIsMarkedGray(const Cell* cell) -{ - MOZ_ASSERT(cell); - if (js::gc::IsInsideNursery(cell)) - return false; - - uintptr_t* word, mask; - js::gc::detail::GetGCThingMarkWordAndMask(uintptr_t(cell), js::gc::GRAY, &word, &mask); - return *word & mask; -} - -extern JS_PUBLIC_API(bool) -CellIsMarkedGrayIfKnown(const Cell* cell); - -} /* namespace detail */ - -MOZ_ALWAYS_INLINE bool -IsInsideNursery(const js::gc::Cell* cell) -{ - if (!cell) - return false; - uintptr_t addr = uintptr_t(cell); - addr &= ~js::gc::ChunkMask; - addr |= js::gc::ChunkLocationOffset; - auto location = *reinterpret_cast(addr); - MOZ_ASSERT(location == ChunkLocation::Nursery || location == ChunkLocation::TenuredHeap); - return location == ChunkLocation::Nursery; -} - -} /* namespace gc */ -} /* namespace js */ - -namespace JS { - -static MOZ_ALWAYS_INLINE Zone* -GetTenuredGCThingZone(GCCellPtr thing) -{ - MOZ_ASSERT(!js::gc::IsInsideNursery(thing.asCell())); - return js::gc::detail::GetGCThingZone(thing.unsafeAsUIntPtr()); -} - -static MOZ_ALWAYS_INLINE Zone* -GetStringZone(JSString* str) -{ - return js::gc::detail::GetGCThingZone(uintptr_t(str)); -} - -extern JS_PUBLIC_API(Zone*) -GetObjectZone(JSObject* obj); - -static MOZ_ALWAYS_INLINE bool -GCThingIsMarkedGray(GCCellPtr thing) -{ - if (thing.mayBeOwnedByOtherRuntime()) - return false; - return js::gc::detail::CellIsMarkedGrayIfKnown(thing.asCell()); -} - -extern JS_PUBLIC_API(JS::TraceKind) -GCThingTraceKind(void* thing); - -} /* namespace JS */ - -namespace js { -namespace gc { - -static MOZ_ALWAYS_INLINE bool -IsIncrementalBarrierNeededOnTenuredGCThing(JS::shadow::Runtime* rt, const JS::GCCellPtr thing) -{ - MOZ_ASSERT(thing); - MOZ_ASSERT(!js::gc::IsInsideNursery(thing.asCell())); - - // TODO: I'd like to assert !isHeapBusy() here but this gets called while we - // are tracing the heap, e.g. during memory reporting (see bug 1313318). - MOZ_ASSERT(!rt->isHeapCollecting()); - - JS::Zone* zone = JS::GetTenuredGCThingZone(thing); - return JS::shadow::Zone::asShadowZone(zone)->needsIncrementalBarrier(); -} - -/** - * Create an object providing access to the garbage collector's internal notion - * of the current state of memory (both GC heap memory and GCthing-controlled - * malloc memory. - */ -extern JS_PUBLIC_API(JSObject*) -NewMemoryInfoObject(JSContext* cx); - -} /* namespace gc */ -} /* namespace js */ - -#endif /* js_HeapAPI_h */ diff --git a/ios/include/spidermonkey/js/Id.h b/ios/include/spidermonkey/js/Id.h deleted file mode 100644 index d474e784..00000000 --- a/ios/include/spidermonkey/js/Id.h +++ /dev/null @@ -1,207 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Id_h -#define js_Id_h - -// A jsid is an identifier for a property or method of an object which is -// either a 31-bit unsigned integer, interned string or symbol. -// -// Also, there is an additional jsid value, JSID_VOID, which does not occur in -// JS scripts but may be used to indicate the absence of a valid jsid. A void -// jsid is not a valid id and only arises as an exceptional API return value, -// such as in JS_NextProperty. Embeddings must not pass JSID_VOID into JSAPI -// entry points expecting a jsid and do not need to handle JSID_VOID in hooks -// receiving a jsid except when explicitly noted in the API contract. -// -// A jsid is not implicitly convertible to or from a Value; JS_ValueToId or -// JS_IdToValue must be used instead. - -#include "jstypes.h" - -#include "js/HeapAPI.h" -#include "js/RootingAPI.h" -#include "js/TypeDecls.h" -#include "js/Utility.h" - -struct jsid -{ - size_t asBits; - bool operator==(const jsid& rhs) const { return asBits == rhs.asBits; } - bool operator!=(const jsid& rhs) const { return asBits != rhs.asBits; } -} JS_HAZ_GC_POINTER; -#define JSID_BITS(id) (id.asBits) - -#define JSID_TYPE_STRING 0x0 -#define JSID_TYPE_INT 0x1 -#define JSID_TYPE_VOID 0x2 -#define JSID_TYPE_SYMBOL 0x4 -#define JSID_TYPE_MASK 0x7 - -// Avoid using canonical 'id' for jsid parameters since this is a magic word in -// Objective-C++ which, apparently, wants to be able to #include jsapi.h. -#define id iden - -static MOZ_ALWAYS_INLINE bool -JSID_IS_STRING(jsid id) -{ - return (JSID_BITS(id) & JSID_TYPE_MASK) == 0; -} - -static MOZ_ALWAYS_INLINE JSString* -JSID_TO_STRING(jsid id) -{ - MOZ_ASSERT(JSID_IS_STRING(id)); - return (JSString*)JSID_BITS(id); -} - -/** - * Only JSStrings that have been interned via the JSAPI can be turned into - * jsids by API clients. - * - * N.B. if a jsid is backed by a string which has not been interned, that - * string must be appropriately rooted to avoid being collected by the GC. - */ -JS_PUBLIC_API(jsid) -INTERNED_STRING_TO_JSID(JSContext* cx, JSString* str); - -static MOZ_ALWAYS_INLINE bool -JSID_IS_INT(jsid id) -{ - return !!(JSID_BITS(id) & JSID_TYPE_INT); -} - -static MOZ_ALWAYS_INLINE int32_t -JSID_TO_INT(jsid id) -{ - MOZ_ASSERT(JSID_IS_INT(id)); - return ((uint32_t)JSID_BITS(id)) >> 1; -} - -#define JSID_INT_MIN 0 -#define JSID_INT_MAX INT32_MAX - -static MOZ_ALWAYS_INLINE bool -INT_FITS_IN_JSID(int32_t i) -{ - return i >= 0; -} - -static MOZ_ALWAYS_INLINE jsid -INT_TO_JSID(int32_t i) -{ - jsid id; - MOZ_ASSERT(INT_FITS_IN_JSID(i)); - JSID_BITS(id) = ((i << 1) | JSID_TYPE_INT); - return id; -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_SYMBOL(jsid id) -{ - return (JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_SYMBOL && - JSID_BITS(id) != JSID_TYPE_SYMBOL; -} - -static MOZ_ALWAYS_INLINE JS::Symbol* -JSID_TO_SYMBOL(jsid id) -{ - MOZ_ASSERT(JSID_IS_SYMBOL(id)); - return (JS::Symbol*)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); -} - -static MOZ_ALWAYS_INLINE jsid -SYMBOL_TO_JSID(JS::Symbol* sym) -{ - jsid id; - MOZ_ASSERT(sym != nullptr); - MOZ_ASSERT((size_t(sym) & JSID_TYPE_MASK) == 0); - MOZ_ASSERT(!js::gc::IsInsideNursery(reinterpret_cast(sym))); - JSID_BITS(id) = (size_t(sym) | JSID_TYPE_SYMBOL); - return id; -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_GCTHING(jsid id) -{ - return JSID_IS_STRING(id) || JSID_IS_SYMBOL(id); -} - -static MOZ_ALWAYS_INLINE JS::GCCellPtr -JSID_TO_GCTHING(jsid id) -{ - void* thing = (void*)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); - if (JSID_IS_STRING(id)) - return JS::GCCellPtr(thing, JS::TraceKind::String); - MOZ_ASSERT(JSID_IS_SYMBOL(id)); - return JS::GCCellPtr(thing, JS::TraceKind::Symbol); -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_VOID(const jsid id) -{ - MOZ_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_VOID, - JSID_BITS(id) == JSID_TYPE_VOID); - return (size_t)JSID_BITS(id) == JSID_TYPE_VOID; -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_EMPTY(const jsid id) -{ - return (size_t)JSID_BITS(id) == JSID_TYPE_SYMBOL; -} - -extern JS_PUBLIC_DATA(const jsid) JSID_VOID; -extern JS_PUBLIC_DATA(const jsid) JSID_EMPTY; - -extern JS_PUBLIC_DATA(const JS::HandleId) JSID_VOIDHANDLE; -extern JS_PUBLIC_DATA(const JS::HandleId) JSID_EMPTYHANDLE; - -namespace JS { - -template <> -struct GCPolicy -{ - static jsid initial() { return JSID_VOID; } - static void trace(JSTracer* trc, jsid* idp, const char* name) { - js::UnsafeTraceManuallyBarrieredEdge(trc, idp, name); - } -}; - -} // namespace JS - -namespace js { - -template <> -struct BarrierMethods -{ - static void postBarrier(jsid* idp, jsid prev, jsid next) {} - static void exposeToJS(jsid id) { - if (JSID_IS_GCTHING(id)) - js::gc::ExposeGCThingToActiveJS(JSID_TO_GCTHING(id)); - } -}; - -// If the jsid is a GC pointer type, convert to that type and call |f| with -// the pointer. If the jsid is not a GC type, calls F::defaultValue. -template -auto -DispatchTyped(F f, const jsid& id, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - if (JSID_IS_STRING(id)) - return f(JSID_TO_STRING(id), mozilla::Forward(args)...); - if (JSID_IS_SYMBOL(id)) - return f(JSID_TO_SYMBOL(id), mozilla::Forward(args)...); - MOZ_ASSERT(!JSID_IS_GCTHING(id)); - return F::defaultValue(id); -} - -#undef id - -} // namespace js - -#endif /* js_Id_h */ diff --git a/ios/include/spidermonkey/js/Initialization.h b/ios/include/spidermonkey/js/Initialization.h deleted file mode 100644 index 8a1cf910..00000000 --- a/ios/include/spidermonkey/js/Initialization.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* SpiderMonkey initialization and shutdown APIs. */ - -#ifndef js_Initialization_h -#define js_Initialization_h - -#include "jstypes.h" - -namespace JS { -namespace detail { - -enum class InitState { Uninitialized = 0, Running, ShutDown }; - -/** - * SpiderMonkey's initialization status is tracked here, and it controls things - * that should happen only once across all runtimes. It's an API requirement - * that JS_Init (and JS_ShutDown, if called) be called in a thread-aware - * manner, so this (internal -- embedders, don't use!) variable doesn't need to - * be atomic. - */ -extern JS_PUBLIC_DATA(InitState) -libraryInitState; - -extern JS_PUBLIC_API(const char*) -InitWithFailureDiagnostic(bool isDebugBuild); - -} // namespace detail -} // namespace JS - -// These are equivalent to ICU's |UMemAllocFn|, |UMemReallocFn|, and -// |UMemFreeFn| types. The first argument (called |context| in the ICU docs) -// will always be nullptr and should be ignored. -typedef void* (*JS_ICUAllocFn)(const void*, size_t size); -typedef void* (*JS_ICUReallocFn)(const void*, void* p, size_t size); -typedef void (*JS_ICUFreeFn)(const void*, void* p); - -/** - * This function can be used to track memory used by ICU. If it is called, it - * *must* be called before JS_Init. Don't use it unless you know what you're - * doing! - */ -extern JS_PUBLIC_API(bool) -JS_SetICUMemoryFunctions(JS_ICUAllocFn allocFn, - JS_ICUReallocFn reallocFn, - JS_ICUFreeFn freeFn); - -/** - * Initialize SpiderMonkey, returning true only if initialization succeeded. - * Once this method has succeeded, it is safe to call JS_NewRuntime and other - * JSAPI methods. - * - * This method must be called before any other JSAPI method is used on any - * thread. Once it has been used, it is safe to call any JSAPI method, and it - * remains safe to do so until JS_ShutDown is correctly called. - * - * It is currently not possible to initialize SpiderMonkey multiple times (that - * is, calling JS_Init/JSAPI methods/JS_ShutDown in that order, then doing so - * again). This restriction may eventually be lifted. - */ -inline bool -JS_Init(void) -{ -#ifdef DEBUG - return !JS::detail::InitWithFailureDiagnostic(true); -#else - return !JS::detail::InitWithFailureDiagnostic(false); -#endif -} - -/** - * A variant of JS_Init. On success it returns nullptr. On failure it returns a - * pointer to a string literal that describes how initialization failed, which - * can be useful for debugging purposes. - */ -inline const char* -JS_InitWithFailureDiagnostic(void) -{ -#ifdef DEBUG - return JS::detail::InitWithFailureDiagnostic(true); -#else - return JS::detail::InitWithFailureDiagnostic(false); -#endif -} - -/* - * Returns true if SpiderMonkey has been initialized successfully, even if it has - * possibly been shut down. - * - * Note that it is the responsibility of the embedder to call JS_Init() and - * JS_ShutDown() at the correct times, and therefore this API should ideally not - * be necessary to use. This is only intended to be used in cases where the - * embedder isn't in full control of deciding whether to initialize SpiderMonkey - * or hand off the task to another consumer. - */ -inline bool -JS_IsInitialized(void) -{ - return JS::detail::libraryInitState != JS::detail::InitState::Uninitialized; -} - -/** - * Destroy free-standing resources allocated by SpiderMonkey, not associated - * with any runtime, context, or other structure. - * - * This method should be called after all other JSAPI data has been properly - * cleaned up: every new runtime must have been destroyed, every new context - * must have been destroyed, and so on. Calling this method before all other - * resources have been destroyed has undefined behavior. - * - * Failure to call this method, at present, has no adverse effects other than - * leaking memory. This may not always be the case; it's recommended that all - * embedders call this method when all other JSAPI operations have completed. - * - * It is currently not possible to initialize SpiderMonkey multiple times (that - * is, calling JS_Init/JSAPI methods/JS_ShutDown in that order, then doing so - * again). This restriction may eventually be lifted. - */ -extern JS_PUBLIC_API(void) -JS_ShutDown(void); - -#endif /* js_Initialization_h */ diff --git a/ios/include/spidermonkey/js/LegacyIntTypes.h b/ios/include/spidermonkey/js/LegacyIntTypes.h deleted file mode 100644 index 2c8498c8..00000000 --- a/ios/include/spidermonkey/js/LegacyIntTypes.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * This section typedefs the old 'native' types to the new types. - * These redefinitions are provided solely to allow JSAPI users to more easily - * transition to types. They are not to be used in the JSAPI, and - * new JSAPI user code should not use them. This mapping file may eventually - * be removed from SpiderMonkey, so don't depend on it in the long run. - */ - -/* - * BEWARE: Comity with other implementers of these types is not guaranteed. - * Indeed, if you use this header and third-party code defining these - * types, *expect* to encounter either compile errors or link errors, - * depending how these types are used and on the order of inclusion. - * It is safest to use only the types. - */ -#ifndef js_LegacyIntTypes_h -#define js_LegacyIntTypes_h - -#include - -#include "js-config.h" - -typedef uint8_t uint8; -typedef uint16_t uint16; -typedef uint32_t uint32; -typedef uint64_t uint64; - -/* - * On AIX 4.3, sys/inttypes.h (which is included by sys/types.h, a very - * common header file) defines the types int8, int16, int32, and int64. - * So we don't define these four types here to avoid conflicts in case - * the code also includes sys/types.h. - */ -#if defined(AIX) && defined(HAVE_SYS_INTTYPES_H) -#include -#else -typedef int8_t int8; -typedef int16_t int16; -typedef int32_t int32; -typedef int64_t int64; -#endif /* AIX && HAVE_SYS_INTTYPES_H */ - -typedef uint8_t JSUint8; -typedef uint16_t JSUint16; -typedef uint32_t JSUint32; -typedef uint64_t JSUint64; - -typedef int8_t JSInt8; -typedef int16_t JSInt16; -typedef int32_t JSInt32; -typedef int64_t JSInt64; - -#endif /* js_LegacyIntTypes_h */ diff --git a/ios/include/spidermonkey/js/MemoryMetrics.h b/ios/include/spidermonkey/js/MemoryMetrics.h deleted file mode 100644 index 9b5caa24..00000000 --- a/ios/include/spidermonkey/js/MemoryMetrics.h +++ /dev/null @@ -1,971 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_MemoryMetrics_h -#define js_MemoryMetrics_h - -// These declarations are highly likely to change in the future. Depend on them -// at your own risk. - -#include "mozilla/MemoryReporting.h" -#include "mozilla/PodOperations.h" -#include "mozilla/TypeTraits.h" - -#include - -#include "jsalloc.h" -#include "jspubtd.h" - -#include "js/HashTable.h" -#include "js/TracingAPI.h" -#include "js/Utility.h" -#include "js/Vector.h" - -class nsISupports; // Needed for ObjectPrivateVisitor. - -namespace JS { - -struct TabSizes -{ - enum Kind { - Objects, - Strings, - Private, - Other - }; - - TabSizes() { mozilla::PodZero(this); } - - void add(Kind kind, size_t n) { - switch (kind) { - case Objects: objects += n; break; - case Strings: strings += n; break; - case Private: private_ += n; break; - case Other: other += n; break; - default: MOZ_CRASH("bad TabSizes kind"); - } - } - - size_t objects; - size_t strings; - size_t private_; - size_t other; -}; - -/** These are the measurements used by Servo. */ -struct ServoSizes -{ - enum Kind { - GCHeapUsed, - GCHeapUnused, - GCHeapAdmin, - GCHeapDecommitted, - MallocHeap, - NonHeap, - Ignore - }; - - ServoSizes() { mozilla::PodZero(this); } - - void add(Kind kind, size_t n) { - switch (kind) { - case GCHeapUsed: gcHeapUsed += n; break; - case GCHeapUnused: gcHeapUnused += n; break; - case GCHeapAdmin: gcHeapAdmin += n; break; - case GCHeapDecommitted: gcHeapDecommitted += n; break; - case MallocHeap: mallocHeap += n; break; - case NonHeap: nonHeap += n; break; - case Ignore: /* do nothing */ break; - default: MOZ_CRASH("bad ServoSizes kind"); - } - } - - size_t gcHeapUsed; - size_t gcHeapUnused; - size_t gcHeapAdmin; - size_t gcHeapDecommitted; - size_t mallocHeap; - size_t nonHeap; -}; - -} // namespace JS - -namespace js { - -/** - * In memory reporting, we have concept of "sundries", line items which are too - * small to be worth reporting individually. Under some circumstances, a memory - * reporter gets tossed into the sundries bucket if it's smaller than - * MemoryReportingSundriesThreshold() bytes. - * - * We need to define this value here, rather than in the code which actually - * generates the memory reports, because NotableStringInfo uses this value. - */ -JS_FRIEND_API(size_t) MemoryReportingSundriesThreshold(); - -/** - * This hash policy avoids flattening ropes (which perturbs the site being - * measured and requires a JSContext) at the expense of doing a FULL ROPE COPY - * on every hash and match! Beware. - */ -struct InefficientNonFlatteningStringHashPolicy -{ - typedef JSString* Lookup; - static HashNumber hash(const Lookup& l); - static bool match(const JSString* const& k, const Lookup& l); -}; - -struct CStringHashPolicy -{ - typedef const char* Lookup; - static HashNumber hash(const Lookup& l); - static bool match(const char* const& k, const Lookup& l); -}; - -// This file features many classes with numerous size_t fields, and each such -// class has one or more methods that need to operate on all of these fields. -// Writing these individually is error-prone -- it's easy to add a new field -// without updating all the required methods. So we define a single macro list -// in each class to name the fields (and notable characteristics of them), and -// then use the following macros to transform those lists into the required -// methods. -// -// - The |tabKind| value is used when measuring TabSizes. -// -// - The |servoKind| value is used when measuring ServoSizes and also for -// the various sizeOfLiveGCThings() methods. -// -// In some classes, one or more of the macro arguments aren't used. We use '_' -// for those. -// -#define DECL_SIZE(tabKind, servoKind, mSize) size_t mSize; -#define ZERO_SIZE(tabKind, servoKind, mSize) mSize(0), -#define COPY_OTHER_SIZE(tabKind, servoKind, mSize) mSize(other.mSize), -#define ADD_OTHER_SIZE(tabKind, servoKind, mSize) mSize += other.mSize; -#define SUB_OTHER_SIZE(tabKind, servoKind, mSize) \ - MOZ_ASSERT(mSize >= other.mSize); \ - mSize -= other.mSize; -#define ADD_SIZE_TO_N(tabKind, servoKind, mSize) n += mSize; -#define ADD_SIZE_TO_N_IF_LIVE_GC_THING(tabKind, servoKind, mSize) \ - /* Avoid self-comparison warnings by comparing enums indirectly. */ \ - n += (mozilla::IsSame::value) \ - ? mSize \ - : 0; -#define ADD_TO_TAB_SIZES(tabKind, servoKind, mSize) sizes->add(JS::TabSizes::tabKind, mSize); -#define ADD_TO_SERVO_SIZES(tabKind, servoKind, mSize) sizes->add(JS::ServoSizes::servoKind, mSize); - -} // namespace js - -namespace JS { - -struct ClassInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(Objects, GCHeapUsed, objectsGCHeap) \ - macro(Objects, MallocHeap, objectsMallocHeapSlots) \ - macro(Objects, MallocHeap, objectsMallocHeapElementsNormal) \ - macro(Objects, MallocHeap, objectsMallocHeapElementsAsmJS) \ - macro(Objects, MallocHeap, objectsMallocHeapMisc) \ - macro(Objects, NonHeap, objectsNonHeapElementsNormal) \ - macro(Objects, NonHeap, objectsNonHeapElementsShared) \ - macro(Objects, NonHeap, objectsNonHeapElementsWasm) \ - macro(Objects, NonHeap, objectsNonHeapCodeWasm) - - ClassInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - wasmGuardPages(0) - {} - - void add(const ClassInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - } - - void subtract(const ClassInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE) - } - - size_t sizeOfAllThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n; - } - - bool isNotable() const { - static const size_t NotabilityThreshold = 16 * 1024; - return sizeOfAllThings() >= NotabilityThreshold; - } - - size_t sizeOfLiveGCThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - size_t wasmGuardPages; - -#undef FOR_EACH_SIZE -}; - -struct ShapeInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(Other, GCHeapUsed, shapesGCHeapTree) \ - macro(Other, GCHeapUsed, shapesGCHeapDict) \ - macro(Other, GCHeapUsed, shapesGCHeapBase) \ - macro(Other, MallocHeap, shapesMallocHeapTreeTables) \ - macro(Other, MallocHeap, shapesMallocHeapDictTables) \ - macro(Other, MallocHeap, shapesMallocHeapTreeKids) - - ShapeInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - void add(const ShapeInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - } - - void subtract(const ShapeInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE) - } - - size_t sizeOfAllThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n; - } - - size_t sizeOfLiveGCThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -/** - * Holds data about a notable class (one whose combined object and shape - * instances use more than a certain amount of memory) so we can report it - * individually. - * - * The only difference between this class and ClassInfo is that this class - * holds a copy of the filename. - */ -struct NotableClassInfo : public ClassInfo -{ - NotableClassInfo(); - NotableClassInfo(const char* className, const ClassInfo& info); - NotableClassInfo(NotableClassInfo&& info); - NotableClassInfo& operator=(NotableClassInfo&& info); - - ~NotableClassInfo() { - js_free(className_); - } - - char* className_; - - private: - NotableClassInfo(const NotableClassInfo& info) = delete; -}; - -/** Data for tracking JIT-code memory usage. */ -struct CodeSizes -{ -#define FOR_EACH_SIZE(macro) \ - macro(_, NonHeap, ion) \ - macro(_, NonHeap, baseline) \ - macro(_, NonHeap, regexp) \ - macro(_, NonHeap, other) \ - macro(_, NonHeap, unused) - - CodeSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -/** Data for tracking GC memory usage. */ -struct GCSizes -{ - // |nurseryDecommitted| is marked as NonHeap rather than GCHeapDecommitted - // because we don't consider the nursery to be part of the GC heap. -#define FOR_EACH_SIZE(macro) \ - macro(_, MallocHeap, marker) \ - macro(_, NonHeap, nurseryCommitted) \ - macro(_, MallocHeap, nurseryMallocedBuffers) \ - macro(_, MallocHeap, storeBufferVals) \ - macro(_, MallocHeap, storeBufferCells) \ - macro(_, MallocHeap, storeBufferSlots) \ - macro(_, MallocHeap, storeBufferWholeCells) \ - macro(_, MallocHeap, storeBufferGenerics) - - GCSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -/** - * This class holds information about the memory taken up by identical copies of - * a particular string. Multiple JSStrings may have their sizes aggregated - * together into one StringInfo object. Note that two strings with identical - * chars will not be aggregated together if one is a short string and the other - * is not. - */ -struct StringInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(Strings, GCHeapUsed, gcHeapLatin1) \ - macro(Strings, GCHeapUsed, gcHeapTwoByte) \ - macro(Strings, MallocHeap, mallocHeapLatin1) \ - macro(Strings, MallocHeap, mallocHeapTwoByte) - - StringInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - numCopies(0) - {} - - void add(const StringInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE); - numCopies++; - } - - void subtract(const StringInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE); - numCopies--; - } - - bool isNotable() const { - static const size_t NotabilityThreshold = 16 * 1024; - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n >= NotabilityThreshold; - } - - size_t sizeOfLiveGCThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - uint32_t numCopies; // How many copies of the string have we seen? - -#undef FOR_EACH_SIZE -}; - -/** - * Holds data about a notable string (one which, counting all duplicates, uses - * more than a certain amount of memory) so we can report it individually. - * - * The only difference between this class and StringInfo is that - * NotableStringInfo holds a copy of some or all of the string's chars. - */ -struct NotableStringInfo : public StringInfo -{ - static const size_t MAX_SAVED_CHARS = 1024; - - NotableStringInfo(); - NotableStringInfo(JSString* str, const StringInfo& info); - NotableStringInfo(NotableStringInfo&& info); - NotableStringInfo& operator=(NotableStringInfo&& info); - - ~NotableStringInfo() { - js_free(buffer); - } - - char* buffer; - size_t length; - - private: - NotableStringInfo(const NotableStringInfo& info) = delete; -}; - -/** - * This class holds information about the memory taken up by script sources - * from a particular file. - */ -struct ScriptSourceInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(_, MallocHeap, misc) - - ScriptSourceInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - numScripts(0) - {} - - void add(const ScriptSourceInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - numScripts++; - } - - void subtract(const ScriptSourceInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE) - numScripts--; - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - bool isNotable() const { - static const size_t NotabilityThreshold = 16 * 1024; - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n >= NotabilityThreshold; - } - - FOR_EACH_SIZE(DECL_SIZE) - uint32_t numScripts; // How many ScriptSources come from this file? (It - // can be more than one in XML files that have - // multiple scripts in CDATA sections.) -#undef FOR_EACH_SIZE -}; - -/** - * Holds data about a notable script source file (one whose combined - * script sources use more than a certain amount of memory) so we can report it - * individually. - * - * The only difference between this class and ScriptSourceInfo is that this - * class holds a copy of the filename. - */ -struct NotableScriptSourceInfo : public ScriptSourceInfo -{ - NotableScriptSourceInfo(); - NotableScriptSourceInfo(const char* filename, const ScriptSourceInfo& info); - NotableScriptSourceInfo(NotableScriptSourceInfo&& info); - NotableScriptSourceInfo& operator=(NotableScriptSourceInfo&& info); - - ~NotableScriptSourceInfo() { - js_free(filename_); - } - - char* filename_; - - private: - NotableScriptSourceInfo(const NotableScriptSourceInfo& info) = delete; -}; - -/** - * These measurements relate directly to the JSRuntime, and not to zones and - * compartments within it. - */ -struct RuntimeSizes -{ -#define FOR_EACH_SIZE(macro) \ - macro(_, MallocHeap, object) \ - macro(_, MallocHeap, atomsTable) \ - macro(_, MallocHeap, contexts) \ - macro(_, MallocHeap, temporary) \ - macro(_, MallocHeap, interpreterStack) \ - macro(_, MallocHeap, mathCache) \ - macro(_, MallocHeap, sharedImmutableStringsCache) \ - macro(_, MallocHeap, sharedIntlData) \ - macro(_, MallocHeap, uncompressedSourceCache) \ - macro(_, MallocHeap, scriptData) - - RuntimeSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - scriptSourceInfo(), - code(), - gc(), - notableScriptSources() - { - allScriptSources = js_new(); - if (!allScriptSources || !allScriptSources->init()) - MOZ_CRASH("oom"); - } - - ~RuntimeSizes() { - // |allScriptSources| is usually deleted and set to nullptr before this - // destructor runs. But there are failure cases due to OOMs that may - // prevent that, so it doesn't hurt to try again here. - js_delete(allScriptSources); - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - scriptSourceInfo.addToServoSizes(sizes); - code.addToServoSizes(sizes); - gc.addToServoSizes(sizes); - } - - // The script source measurements in |scriptSourceInfo| are initially for - // all script sources. At the end, if the measurement granularity is - // FineGrained, we subtract the measurements of the notable script sources - // and move them into |notableScriptSources|. - FOR_EACH_SIZE(DECL_SIZE) - ScriptSourceInfo scriptSourceInfo; - CodeSizes code; - GCSizes gc; - - typedef js::HashMap ScriptSourcesHashMap; - - // |allScriptSources| is only used transiently. During the reporting phase - // it is filled with info about every script source in the runtime. It's - // then used to fill in |notableScriptSources| (which actually gets - // reported), and immediately discarded afterwards. - ScriptSourcesHashMap* allScriptSources; - js::Vector notableScriptSources; - -#undef FOR_EACH_SIZE -}; - -struct UnusedGCThingSizes -{ -#define FOR_EACH_SIZE(macro) \ - macro(Other, GCHeapUnused, object) \ - macro(Other, GCHeapUnused, script) \ - macro(Other, GCHeapUnused, lazyScript) \ - macro(Other, GCHeapUnused, shape) \ - macro(Other, GCHeapUnused, baseShape) \ - macro(Other, GCHeapUnused, objectGroup) \ - macro(Other, GCHeapUnused, string) \ - macro(Other, GCHeapUnused, symbol) \ - macro(Other, GCHeapUnused, jitcode) \ - macro(Other, GCHeapUnused, scope) - - UnusedGCThingSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - UnusedGCThingSizes(UnusedGCThingSizes&& other) - : FOR_EACH_SIZE(COPY_OTHER_SIZE) - dummy() - {} - - void addToKind(JS::TraceKind kind, intptr_t n) { - switch (kind) { - case JS::TraceKind::Object: object += n; break; - case JS::TraceKind::String: string += n; break; - case JS::TraceKind::Symbol: symbol += n; break; - case JS::TraceKind::Script: script += n; break; - case JS::TraceKind::Shape: shape += n; break; - case JS::TraceKind::BaseShape: baseShape += n; break; - case JS::TraceKind::JitCode: jitcode += n; break; - case JS::TraceKind::LazyScript: lazyScript += n; break; - case JS::TraceKind::ObjectGroup: objectGroup += n; break; - case JS::TraceKind::Scope: scope += n; break; - default: - MOZ_CRASH("Bad trace kind for UnusedGCThingSizes"); - } - } - - void addSizes(const UnusedGCThingSizes& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - } - - size_t totalSize() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n; - } - - void addToTabSizes(JS::TabSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(JS::ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -struct ZoneStats -{ -#define FOR_EACH_SIZE(macro) \ - macro(Other, GCHeapUsed, symbolsGCHeap) \ - macro(Other, GCHeapAdmin, gcHeapArenaAdmin) \ - macro(Other, GCHeapUsed, lazyScriptsGCHeap) \ - macro(Other, MallocHeap, lazyScriptsMallocHeap) \ - macro(Other, GCHeapUsed, jitCodesGCHeap) \ - macro(Other, GCHeapUsed, objectGroupsGCHeap) \ - macro(Other, MallocHeap, objectGroupsMallocHeap) \ - macro(Other, GCHeapUsed, scopesGCHeap) \ - macro(Other, MallocHeap, scopesMallocHeap) \ - macro(Other, MallocHeap, typePool) \ - macro(Other, MallocHeap, baselineStubsOptimized) \ - macro(Other, MallocHeap, uniqueIdMap) \ - macro(Other, MallocHeap, shapeTables) - - ZoneStats() - : FOR_EACH_SIZE(ZERO_SIZE) - unusedGCThings(), - stringInfo(), - shapeInfo(), - extra(), - allStrings(nullptr), - notableStrings(), - isTotals(true) - {} - - ZoneStats(ZoneStats&& other) - : FOR_EACH_SIZE(COPY_OTHER_SIZE) - unusedGCThings(mozilla::Move(other.unusedGCThings)), - stringInfo(mozilla::Move(other.stringInfo)), - shapeInfo(mozilla::Move(other.shapeInfo)), - extra(other.extra), - allStrings(other.allStrings), - notableStrings(mozilla::Move(other.notableStrings)), - isTotals(other.isTotals) - { - other.allStrings = nullptr; - MOZ_ASSERT(!other.isTotals); - } - - ~ZoneStats() { - // |allStrings| is usually deleted and set to nullptr before this - // destructor runs. But there are failure cases due to OOMs that may - // prevent that, so it doesn't hurt to try again here. - js_delete(allStrings); - } - - bool initStrings(JSRuntime* rt); - - void addSizes(const ZoneStats& other) { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_OTHER_SIZE) - unusedGCThings.addSizes(other.unusedGCThings); - stringInfo.add(other.stringInfo); - shapeInfo.add(other.shapeInfo); - } - - size_t sizeOfLiveGCThings() const { - MOZ_ASSERT(isTotals); - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - n += stringInfo.sizeOfLiveGCThings(); - n += shapeInfo.sizeOfLiveGCThings(); - return n; - } - - void addToTabSizes(JS::TabSizes* sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - unusedGCThings.addToTabSizes(sizes); - stringInfo.addToTabSizes(sizes); - shapeInfo.addToTabSizes(sizes); - } - - void addToServoSizes(JS::ServoSizes *sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - unusedGCThings.addToServoSizes(sizes); - stringInfo.addToServoSizes(sizes); - shapeInfo.addToServoSizes(sizes); - } - - // These string measurements are initially for all strings. At the end, - // if the measurement granularity is FineGrained, we subtract the - // measurements of the notable script sources and move them into - // |notableStrings|. - FOR_EACH_SIZE(DECL_SIZE) - UnusedGCThingSizes unusedGCThings; - StringInfo stringInfo; - ShapeInfo shapeInfo; - void* extra; // This field can be used by embedders. - - typedef js::HashMap StringsHashMap; - - // |allStrings| is only used transiently. During the zone traversal it is - // filled with info about every string in the zone. It's then used to fill - // in |notableStrings| (which actually gets reported), and immediately - // discarded afterwards. - StringsHashMap* allStrings; - js::Vector notableStrings; - bool isTotals; - -#undef FOR_EACH_SIZE -}; - -struct CompartmentStats -{ - // We assume that |objectsPrivate| is on the malloc heap, but it's not - // actually guaranteed. But for Servo, at least, it's a moot point because - // it doesn't provide an ObjectPrivateVisitor so the value will always be - // zero. -#define FOR_EACH_SIZE(macro) \ - macro(Private, MallocHeap, objectsPrivate) \ - macro(Other, GCHeapUsed, scriptsGCHeap) \ - macro(Other, MallocHeap, scriptsMallocHeapData) \ - macro(Other, MallocHeap, baselineData) \ - macro(Other, MallocHeap, baselineStubsFallback) \ - macro(Other, MallocHeap, ionData) \ - macro(Other, MallocHeap, typeInferenceTypeScripts) \ - macro(Other, MallocHeap, typeInferenceAllocationSiteTables) \ - macro(Other, MallocHeap, typeInferenceArrayTypeTables) \ - macro(Other, MallocHeap, typeInferenceObjectTypeTables) \ - macro(Other, MallocHeap, compartmentObject) \ - macro(Other, MallocHeap, compartmentTables) \ - macro(Other, MallocHeap, innerViewsTable) \ - macro(Other, MallocHeap, lazyArrayBuffersTable) \ - macro(Other, MallocHeap, objectMetadataTable) \ - macro(Other, MallocHeap, crossCompartmentWrappersTable) \ - macro(Other, MallocHeap, regexpCompartment) \ - macro(Other, MallocHeap, savedStacksSet) \ - macro(Other, MallocHeap, varNamesSet) \ - macro(Other, MallocHeap, nonSyntacticLexicalScopesTable) \ - macro(Other, MallocHeap, jitCompartment) \ - macro(Other, MallocHeap, privateData) - - CompartmentStats() - : FOR_EACH_SIZE(ZERO_SIZE) - classInfo(), - extra(), - allClasses(nullptr), - notableClasses(), - isTotals(true) - {} - - CompartmentStats(CompartmentStats&& other) - : FOR_EACH_SIZE(COPY_OTHER_SIZE) - classInfo(mozilla::Move(other.classInfo)), - extra(other.extra), - allClasses(other.allClasses), - notableClasses(mozilla::Move(other.notableClasses)), - isTotals(other.isTotals) - { - other.allClasses = nullptr; - MOZ_ASSERT(!other.isTotals); - } - - CompartmentStats(const CompartmentStats&) = delete; // disallow copying - - ~CompartmentStats() { - // |allClasses| is usually deleted and set to nullptr before this - // destructor runs. But there are failure cases due to OOMs that may - // prevent that, so it doesn't hurt to try again here. - js_delete(allClasses); - } - - bool initClasses(JSRuntime* rt); - - void addSizes(const CompartmentStats& other) { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_OTHER_SIZE) - classInfo.add(other.classInfo); - } - - size_t sizeOfLiveGCThings() const { - MOZ_ASSERT(isTotals); - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - n += classInfo.sizeOfLiveGCThings(); - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_TAB_SIZES); - classInfo.addToTabSizes(sizes); - } - - void addToServoSizes(ServoSizes *sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES); - classInfo.addToServoSizes(sizes); - } - - // The class measurements in |classInfo| are initially for all classes. At - // the end, if the measurement granularity is FineGrained, we subtract the - // measurements of the notable classes and move them into |notableClasses|. - FOR_EACH_SIZE(DECL_SIZE) - ClassInfo classInfo; - void* extra; // This field can be used by embedders. - - typedef js::HashMap ClassesHashMap; - - // These are similar to |allStrings| and |notableStrings| in ZoneStats. - ClassesHashMap* allClasses; - js::Vector notableClasses; - bool isTotals; - -#undef FOR_EACH_SIZE -}; - -typedef js::Vector CompartmentStatsVector; -typedef js::Vector ZoneStatsVector; - -struct RuntimeStats -{ - // |gcHeapChunkTotal| is ignored because it's the sum of all the other - // values. |gcHeapGCThings| is ignored because it's the sum of some of the - // values from the zones and compartments. Both of those values are not - // reported directly, but are just present for sanity-checking other - // values. -#define FOR_EACH_SIZE(macro) \ - macro(_, Ignore, gcHeapChunkTotal) \ - macro(_, GCHeapDecommitted, gcHeapDecommittedArenas) \ - macro(_, GCHeapUnused, gcHeapUnusedChunks) \ - macro(_, GCHeapUnused, gcHeapUnusedArenas) \ - macro(_, GCHeapAdmin, gcHeapChunkAdmin) \ - macro(_, Ignore, gcHeapGCThings) - - explicit RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) - : FOR_EACH_SIZE(ZERO_SIZE) - runtime(), - cTotals(), - zTotals(), - compartmentStatsVector(), - zoneStatsVector(), - currZoneStats(nullptr), - mallocSizeOf_(mallocSizeOf) - {} - - // Here's a useful breakdown of the GC heap. - // - // - rtStats.gcHeapChunkTotal - // - decommitted bytes - // - rtStats.gcHeapDecommittedArenas (decommitted arenas in non-empty chunks) - // - unused bytes - // - rtStats.gcHeapUnusedChunks (empty chunks) - // - rtStats.gcHeapUnusedArenas (empty arenas within non-empty chunks) - // - rtStats.zTotals.unusedGCThings.totalSize() (empty GC thing slots within non-empty arenas) - // - used bytes - // - rtStats.gcHeapChunkAdmin - // - rtStats.zTotals.gcHeapArenaAdmin - // - rtStats.gcHeapGCThings (in-use GC things) - // == rtStats.zTotals.sizeOfLiveGCThings() + rtStats.cTotals.sizeOfLiveGCThings() - // - // It's possible that some arenas in empty chunks may be decommitted, but - // we don't count those under rtStats.gcHeapDecommittedArenas because (a) - // it's rare, and (b) this means that rtStats.gcHeapUnusedChunks is a - // multiple of the chunk size, which is good. - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - runtime.addToServoSizes(sizes); - } - - FOR_EACH_SIZE(DECL_SIZE) - - RuntimeSizes runtime; - - CompartmentStats cTotals; // The sum of this runtime's compartments' measurements. - ZoneStats zTotals; // The sum of this runtime's zones' measurements. - - CompartmentStatsVector compartmentStatsVector; - ZoneStatsVector zoneStatsVector; - - ZoneStats* currZoneStats; - - mozilla::MallocSizeOf mallocSizeOf_; - - virtual void initExtraCompartmentStats(JSCompartment* c, CompartmentStats* cstats) = 0; - virtual void initExtraZoneStats(JS::Zone* zone, ZoneStats* zstats) = 0; - -#undef FOR_EACH_SIZE -}; - -class ObjectPrivateVisitor -{ - public: - // Within CollectRuntimeStats, this method is called for each JS object - // that has an nsISupports pointer. - virtual size_t sizeOfIncludingThis(nsISupports* aSupports) = 0; - - // A callback that gets a JSObject's nsISupports pointer, if it has one. - // Note: this function does *not* addref |iface|. - typedef bool(*GetISupportsFun)(JSObject* obj, nsISupports** iface); - GetISupportsFun getISupports_; - - explicit ObjectPrivateVisitor(GetISupportsFun getISupports) - : getISupports_(getISupports) - {} -}; - -extern JS_PUBLIC_API(bool) -CollectRuntimeStats(JSContext* cx, RuntimeStats* rtStats, ObjectPrivateVisitor* opv, bool anonymize); - -extern JS_PUBLIC_API(size_t) -SystemCompartmentCount(JSContext* cx); - -extern JS_PUBLIC_API(size_t) -UserCompartmentCount(JSContext* cx); - -extern JS_PUBLIC_API(size_t) -PeakSizeOfTemporary(const JSContext* cx); - -extern JS_PUBLIC_API(bool) -AddSizeOfTab(JSContext* cx, JS::HandleObject obj, mozilla::MallocSizeOf mallocSizeOf, - ObjectPrivateVisitor* opv, TabSizes* sizes); - -extern JS_PUBLIC_API(bool) -AddServoSizeOf(JSContext* cx, mozilla::MallocSizeOf mallocSizeOf, - ObjectPrivateVisitor *opv, ServoSizes *sizes); - -} // namespace JS - -#undef DECL_SIZE -#undef ZERO_SIZE -#undef COPY_OTHER_SIZE -#undef ADD_OTHER_SIZE -#undef SUB_OTHER_SIZE -#undef ADD_SIZE_TO_N -#undef ADD_SIZE_TO_N_IF_LIVE_GC_THING -#undef ADD_TO_TAB_SIZES - -#endif /* js_MemoryMetrics_h */ diff --git a/ios/include/spidermonkey/js/Principals.h b/ios/include/spidermonkey/js/Principals.h deleted file mode 100644 index cf6c813a..00000000 --- a/ios/include/spidermonkey/js/Principals.h +++ /dev/null @@ -1,132 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JSPrincipals and related interfaces. */ - -#ifndef js_Principals_h -#define js_Principals_h - -#include "mozilla/Atomics.h" - -#include - -#include "jspubtd.h" - -#include "js/StructuredClone.h" - -namespace js { - struct PerformanceGroup; -} // namespace js - -struct JSPrincipals { - /* Don't call "destroy"; use reference counting macros below. */ - mozilla::Atomic refcount; - -#ifdef JS_DEBUG - /* A helper to facilitate principals debugging. */ - uint32_t debugToken; -#endif - - JSPrincipals() : refcount(0) {} - - void setDebugToken(uint32_t token) { -# ifdef JS_DEBUG - debugToken = token; -# endif - } - - /* - * Write the principals with the given |writer|. Return false on failure, - * true on success. - */ - virtual bool write(JSContext* cx, JSStructuredCloneWriter* writer) = 0; - - /* - * This is not defined by the JS engine but should be provided by the - * embedding. - */ - JS_PUBLIC_API(void) dump(); -}; - -extern JS_PUBLIC_API(void) -JS_HoldPrincipals(JSPrincipals* principals); - -extern JS_PUBLIC_API(void) -JS_DropPrincipals(JSContext* cx, JSPrincipals* principals); - -// Return whether the first principal subsumes the second. The exact meaning of -// 'subsumes' is left up to the browser. Subsumption is checked inside the JS -// engine when determining, e.g., which stack frames to display in a backtrace. -typedef bool -(* JSSubsumesOp)(JSPrincipals* first, JSPrincipals* second); - -/* - * Used to check if a CSP instance wants to disable eval() and friends. - * See js_CheckCSPPermitsJSAction() in jsobj. - */ -typedef bool -(* JSCSPEvalChecker)(JSContext* cx); - -struct JSSecurityCallbacks { - JSCSPEvalChecker contentSecurityPolicyAllows; - JSSubsumesOp subsumes; -}; - -extern JS_PUBLIC_API(void) -JS_SetSecurityCallbacks(JSContext* cx, const JSSecurityCallbacks* callbacks); - -extern JS_PUBLIC_API(const JSSecurityCallbacks*) -JS_GetSecurityCallbacks(JSContext* cx); - -/* - * Code running with "trusted" principals will be given a deeper stack - * allocation than ordinary scripts. This allows trusted script to run after - * untrusted script has exhausted the stack. This function sets the - * runtime-wide trusted principal. - * - * This principals is not held (via JS_HoldPrincipals/JS_DropPrincipals). - * Instead, the caller must ensure that the given principals stays valid for as - * long as 'cx' may point to it. If the principals would be destroyed before - * 'cx', JS_SetTrustedPrincipals must be called again, passing nullptr for - * 'prin'. - */ -extern JS_PUBLIC_API(void) -JS_SetTrustedPrincipals(JSContext* cx, JSPrincipals* prin); - -typedef void -(* JSDestroyPrincipalsOp)(JSPrincipals* principals); - -/* - * Initialize the callback that is called to destroy JSPrincipals instance - * when its reference counter drops to zero. The initialization can be done - * only once per JS runtime. - */ -extern JS_PUBLIC_API(void) -JS_InitDestroyPrincipalsCallback(JSContext* cx, JSDestroyPrincipalsOp destroyPrincipals); - -/* - * Read a JSPrincipals instance from the given |reader| and initialize the out - * paratemer |outPrincipals| to the JSPrincipals instance read. - * - * Return false on failure, true on success. The |outPrincipals| parameter - * should not be modified if false is returned. - * - * The caller is not responsible for calling JS_HoldPrincipals on the resulting - * JSPrincipals instance, the JSReadPrincipalsOp must increment the refcount of - * the resulting JSPrincipals on behalf of the caller. - */ -using JSReadPrincipalsOp = bool (*)(JSContext* cx, JSStructuredCloneReader* reader, - JSPrincipals** outPrincipals); - -/* - * Initialize the callback that is called to read JSPrincipals instances from a - * buffer. The initialization can be done only once per JS runtime. - */ -extern JS_PUBLIC_API(void) -JS_InitReadPrincipalsCallback(JSContext* cx, JSReadPrincipalsOp read); - - -#endif /* js_Principals_h */ diff --git a/ios/include/spidermonkey/js/ProfilingFrameIterator.h b/ios/include/spidermonkey/js/ProfilingFrameIterator.h deleted file mode 100644 index d082213d..00000000 --- a/ios/include/spidermonkey/js/ProfilingFrameIterator.h +++ /dev/null @@ -1,203 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_ProfilingFrameIterator_h -#define js_ProfilingFrameIterator_h - -#include "mozilla/Alignment.h" -#include "mozilla/Maybe.h" - -#include "jsbytecode.h" -#include "js/GCAPI.h" -#include "js/TypeDecls.h" -#include "js/Utility.h" - -struct JSContext; -struct JSRuntime; -class JSScript; - -namespace js { - class Activation; - namespace jit { - class JitActivation; - class JitProfilingFrameIterator; - class JitcodeGlobalEntry; - } // namespace jit - namespace wasm { - class ProfilingFrameIterator; - } // namespace wasm -} // namespace js - -namespace JS { - -struct ForEachTrackedOptimizationAttemptOp; -struct ForEachTrackedOptimizationTypeInfoOp; - -// This iterator can be used to walk the stack of a thread suspended at an -// arbitrary pc. To provide acurate results, profiling must have been enabled -// (via EnableRuntimeProfilingStack) before executing the callstack being -// unwound. -// -// Note that the caller must not do anything that could cause GC to happen while -// the iterator is alive, since this could invalidate Ion code and cause its -// contents to become out of date. -class JS_PUBLIC_API(ProfilingFrameIterator) -{ - JSRuntime* rt_; - uint32_t sampleBufferGen_; - js::Activation* activation_; - - // When moving past a JitActivation, we need to save the prevJitTop - // from it to use as the exit-frame pointer when the next caller jit - // activation (if any) comes around. - void* savedPrevJitTop_; - - JS::AutoCheckCannotGC nogc_; - - static const unsigned StorageSpace = 8 * sizeof(void*); - mozilla::AlignedStorage storage_; - js::wasm::ProfilingFrameIterator& wasmIter() { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isWasm()); - return *reinterpret_cast(storage_.addr()); - } - const js::wasm::ProfilingFrameIterator& wasmIter() const { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isWasm()); - return *reinterpret_cast(storage_.addr()); - } - - js::jit::JitProfilingFrameIterator& jitIter() { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isJit()); - return *reinterpret_cast(storage_.addr()); - } - - const js::jit::JitProfilingFrameIterator& jitIter() const { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isJit()); - return *reinterpret_cast(storage_.addr()); - } - - void settle(); - - bool hasSampleBufferGen() const { - return sampleBufferGen_ != UINT32_MAX; - } - - public: - struct RegisterState - { - RegisterState() : pc(nullptr), sp(nullptr), lr(nullptr) {} - void* pc; - void* sp; - void* lr; - }; - - ProfilingFrameIterator(JSContext* cx, const RegisterState& state, - uint32_t sampleBufferGen = UINT32_MAX); - ~ProfilingFrameIterator(); - void operator++(); - bool done() const { return !activation_; } - - // Assuming the stack grows down (we do), the return value: - // - always points into the stack - // - is weakly monotonically increasing (may be equal for successive frames) - // - will compare greater than newer native and psuedo-stack frame addresses - // and less than older native and psuedo-stack frame addresses - void* stackAddress() const; - - enum FrameKind - { - Frame_Baseline, - Frame_Ion, - Frame_Wasm - }; - - struct Frame - { - FrameKind kind; - void* stackAddress; - void* returnAddress; - void* activation; - UniqueChars label; - }; - - bool isWasm() const; - bool isJit() const; - - uint32_t extractStack(Frame* frames, uint32_t offset, uint32_t end) const; - - mozilla::Maybe getPhysicalFrameWithoutLabel() const; - - private: - mozilla::Maybe getPhysicalFrameAndEntry(js::jit::JitcodeGlobalEntry* entry) const; - - void iteratorConstruct(const RegisterState& state); - void iteratorConstruct(); - void iteratorDestroy(); - bool iteratorDone(); -}; - -JS_FRIEND_API(bool) -IsProfilingEnabledForContext(JSContext* cx); - -/** - * After each sample run, this method should be called with the latest sample - * buffer generation, and the lapCount. It will update corresponding fields on - * JSRuntime. - * - * See fields |profilerSampleBufferGen|, |profilerSampleBufferLapCount| on - * JSRuntime for documentation about what these values are used for. - */ -JS_FRIEND_API(void) -UpdateJSContextProfilerSampleBufferGen(JSContext* cx, uint32_t generation, - uint32_t lapCount); - -struct ForEachProfiledFrameOp -{ - // A handle to the underlying JitcodeGlobalEntry, so as to avoid repeated - // lookups on JitcodeGlobalTable. - class MOZ_STACK_CLASS FrameHandle - { - friend JS_PUBLIC_API(void) ForEachProfiledFrame(JSContext* cx, void* addr, - ForEachProfiledFrameOp& op); - - JSRuntime* rt_; - js::jit::JitcodeGlobalEntry& entry_; - void* addr_; - void* canonicalAddr_; - const char* label_; - uint32_t depth_; - mozilla::Maybe optsIndex_; - - FrameHandle(JSRuntime* rt, js::jit::JitcodeGlobalEntry& entry, void* addr, - const char* label, uint32_t depth); - - void updateHasTrackedOptimizations(); - - public: - const char* label() const { return label_; } - uint32_t depth() const { return depth_; } - bool hasTrackedOptimizations() const { return optsIndex_.isSome(); } - void* canonicalAddress() const { return canonicalAddr_; } - - ProfilingFrameIterator::FrameKind frameKind() const; - void forEachOptimizationAttempt(ForEachTrackedOptimizationAttemptOp& op, - JSScript** scriptOut, jsbytecode** pcOut) const; - void forEachOptimizationTypeInfo(ForEachTrackedOptimizationTypeInfoOp& op) const; - }; - - // Called once per frame. - virtual void operator()(const FrameHandle& frame) = 0; -}; - -JS_PUBLIC_API(void) -ForEachProfiledFrame(JSContext* cx, void* addr, ForEachProfiledFrameOp& op); - -} // namespace JS - -#endif /* js_ProfilingFrameIterator_h */ diff --git a/ios/include/spidermonkey/js/ProfilingStack.h b/ios/include/spidermonkey/js/ProfilingStack.h deleted file mode 100644 index 6b6c9701..00000000 --- a/ios/include/spidermonkey/js/ProfilingStack.h +++ /dev/null @@ -1,208 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_ProfilingStack_h -#define js_ProfilingStack_h - -#include "jsbytecode.h" -#include "jstypes.h" -#include "js/TypeDecls.h" - -#include "js/Utility.h" - -struct JSRuntime; -class JSTracer; - -namespace js { - -// A call stack can be specified to the JS engine such that all JS entry/exits -// to functions push/pop an entry to/from the specified stack. -// -// For more detailed information, see vm/SPSProfiler.h. -// -class ProfileEntry -{ - // All fields are marked volatile to prevent the compiler from re-ordering - // instructions. Namely this sequence: - // - // entry[size] = ...; - // size++; - // - // If the size modification were somehow reordered before the stores, then - // if a sample were taken it would be examining bogus information. - // - // A ProfileEntry represents both a C++ profile entry and a JS one. - - // Descriptive string of this entry. - const char * volatile string; - - // Stack pointer for non-JS entries, the script pointer otherwise. - void * volatile spOrScript; - - // Line number for non-JS entries, the bytecode offset otherwise. - int32_t volatile lineOrPcOffset; - - // General purpose storage describing this frame. - uint32_t volatile flags_; - - public: - // These traits are bit masks. Make sure they're powers of 2. - enum Flags : uint32_t { - // Indicate whether a profile entry represents a CPP frame. If not set, - // a JS frame is assumed by default. You're not allowed to publicly - // change the frame type. Instead, initialize the ProfileEntry as either - // a JS or CPP frame with `initJsFrame` or `initCppFrame` respectively. - IS_CPP_ENTRY = 0x01, - - // Indicate that copying the frame label is not necessary when taking a - // sample of the pseudostack. - FRAME_LABEL_COPY = 0x02, - - // This ProfileEntry is a dummy entry indicating the start of a run - // of JS pseudostack entries. - BEGIN_PSEUDO_JS = 0x04, - - // This flag is used to indicate that an interpreter JS entry has OSR-ed - // into baseline. - OSR = 0x08, - - // Union of all flags. - ALL = IS_CPP_ENTRY|FRAME_LABEL_COPY|BEGIN_PSEUDO_JS|OSR, - - // Mask for removing all flags except the category information. - CATEGORY_MASK = ~ALL - }; - - // Keep these in sync with devtools/client/performance/modules/categories.js - enum class Category : uint32_t { - OTHER = 0x10, - CSS = 0x20, - JS = 0x40, - GC = 0x80, - CC = 0x100, - NETWORK = 0x200, - GRAPHICS = 0x400, - STORAGE = 0x800, - EVENTS = 0x1000, - - FIRST = OTHER, - LAST = EVENTS - }; - - static_assert((static_cast(Category::FIRST) & Flags::ALL) == 0, - "The category bitflags should not intersect with the other flags!"); - - // All of these methods are marked with the 'volatile' keyword because SPS's - // representation of the stack is stored such that all ProfileEntry - // instances are volatile. These methods would not be available unless they - // were marked as volatile as well. - - bool isCpp() const volatile { return hasFlag(IS_CPP_ENTRY); } - bool isJs() const volatile { return !isCpp(); } - - bool isCopyLabel() const volatile { return hasFlag(FRAME_LABEL_COPY); } - - void setLabel(const char* aString) volatile { string = aString; } - const char* label() const volatile { return string; } - - void initJsFrame(JSScript* aScript, jsbytecode* aPc) volatile { - flags_ = 0; - spOrScript = aScript; - setPC(aPc); - } - void initCppFrame(void* aSp, uint32_t aLine) volatile { - flags_ = IS_CPP_ENTRY; - spOrScript = aSp; - lineOrPcOffset = static_cast(aLine); - } - - void setFlag(uint32_t flag) volatile { - MOZ_ASSERT(flag != IS_CPP_ENTRY); - flags_ |= flag; - } - void unsetFlag(uint32_t flag) volatile { - MOZ_ASSERT(flag != IS_CPP_ENTRY); - flags_ &= ~flag; - } - bool hasFlag(uint32_t flag) const volatile { - return bool(flags_ & flag); - } - - uint32_t flags() const volatile { - return flags_; - } - - uint32_t category() const volatile { - return flags_ & CATEGORY_MASK; - } - void setCategory(Category c) volatile { - MOZ_ASSERT(c >= Category::FIRST); - MOZ_ASSERT(c <= Category::LAST); - flags_ &= ~CATEGORY_MASK; - setFlag(static_cast(c)); - } - - void setOSR() volatile { - MOZ_ASSERT(isJs()); - setFlag(OSR); - } - void unsetOSR() volatile { - MOZ_ASSERT(isJs()); - unsetFlag(OSR); - } - bool isOSR() const volatile { - return hasFlag(OSR); - } - - void* stackAddress() const volatile { - MOZ_ASSERT(!isJs()); - return spOrScript; - } - JSScript* script() const volatile; - uint32_t line() const volatile { - MOZ_ASSERT(!isJs()); - return static_cast(lineOrPcOffset); - } - - // Note that the pointer returned might be invalid. - JSScript* rawScript() const volatile { - MOZ_ASSERT(isJs()); - return (JSScript*)spOrScript; - } - - // We can't know the layout of JSScript, so look in vm/SPSProfiler.cpp. - JS_FRIEND_API(jsbytecode*) pc() const volatile; - JS_FRIEND_API(void) setPC(jsbytecode* pc) volatile; - - void trace(JSTracer* trc); - - // The offset of a pc into a script's code can actually be 0, so to - // signify a nullptr pc, use a -1 index. This is checked against in - // pc() and setPC() to set/get the right pc. - static const int32_t NullPCOffset = -1; - - static size_t offsetOfLabel() { return offsetof(ProfileEntry, string); } - static size_t offsetOfSpOrScript() { return offsetof(ProfileEntry, spOrScript); } - static size_t offsetOfLineOrPcOffset() { return offsetof(ProfileEntry, lineOrPcOffset); } - static size_t offsetOfFlags() { return offsetof(ProfileEntry, flags_); } -}; - -JS_FRIEND_API(void) -SetContextProfilingStack(JSContext* cx, ProfileEntry* stack, uint32_t* size, - uint32_t max); - -JS_FRIEND_API(void) -EnableContextProfilingStack(JSContext* cx, bool enabled); - -JS_FRIEND_API(void) -RegisterContextProfilingEventMarker(JSContext* cx, void (*fn)(const char*)); - -JS_FRIEND_API(jsbytecode*) -ProfilingGetPC(JSContext* cx, JSScript* script, void* ip); - -} // namespace js - -#endif /* js_ProfilingStack_h */ diff --git a/ios/include/spidermonkey/js/Proxy.h b/ios/include/spidermonkey/js/Proxy.h deleted file mode 100644 index 3e95538d..00000000 --- a/ios/include/spidermonkey/js/Proxy.h +++ /dev/null @@ -1,632 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Proxy_h -#define js_Proxy_h - -#include "mozilla/Maybe.h" - -#include "jsfriendapi.h" - -#include "js/CallNonGenericMethod.h" -#include "js/Class.h" - -namespace js { - -using JS::AutoIdVector; -using JS::CallArgs; -using JS::Handle; -using JS::HandleId; -using JS::HandleObject; -using JS::HandleValue; -using JS::IsAcceptableThis; -using JS::MutableHandle; -using JS::MutableHandleObject; -using JS::MutableHandleValue; -using JS::NativeImpl; -using JS::ObjectOpResult; -using JS::PrivateValue; -using JS::PropertyDescriptor; -using JS::Value; - -class RegExpGuard; -class JS_FRIEND_API(Wrapper); - -/* - * A proxy is a JSObject with highly customizable behavior. ES6 specifies a - * single kind of proxy, but the customization mechanisms we use to implement - * ES6 Proxy objects are also useful wherever an object with weird behavior is - * wanted. Proxies are used to implement: - * - * - the scope objects used by the Debugger's frame.eval() method - * (see js::GetDebugScopeForFunction) - * - * - the khuey hack, whereby a whole compartment can be blown away - * even if other compartments hold references to objects in it - * (see js::NukeCrossCompartmentWrappers) - * - * - XPConnect security wrappers, which protect chrome from malicious content - * (js/xpconnect/wrappers) - * - * - DOM objects with special property behavior, like named getters - * (dom/bindings/Codegen.py generates these proxies from WebIDL) - * - * - semi-transparent use of objects that live in other processes - * (CPOWs, implemented in js/ipc) - * - * ### Proxies and internal methods - * - * ES2016 specifies 13 internal methods. The runtime semantics of just - * about everything a script can do to an object is specified in terms - * of these internal methods. For example: - * - * JS code ES6 internal method that gets called - * --------------------------- -------------------------------- - * obj.prop obj.[[Get]](obj, "prop") - * "prop" in obj obj.[[HasProperty]]("prop") - * new obj() obj.[[Construct]]() - * - * With regard to the implementation of these internal methods, there are three - * very different kinds of object in SpiderMonkey. - * - * 1. Native objects' internal methods are implemented in vm/NativeObject.cpp, - * with duplicate (but functionally identical) implementations scattered - * through the ICs and JITs. - * - * 2. Certain non-native objects have internal methods that are implemented as - * magical js::ObjectOps hooks. We're trying to get rid of these. - * - * 3. All other objects are proxies. A proxy's internal methods are - * implemented in C++, as the virtual methods of a C++ object stored on the - * proxy, known as its handler. - * - * This means that just about anything you do to a proxy will end up going - * through a C++ virtual method call. Possibly several. There's no reason the - * JITs and ICs can't specialize for particular proxies, based on the handler; - * but currently we don't do much of this, so the virtual method overhead - * typically is actually incurred. - * - * ### The proxy handler hierarchy - * - * A major use case for proxies is to forward each internal method call to - * another object, known as its target. The target can be an arbitrary JS - * object. Not every proxy has the notion of a target, however. - * - * To minimize code duplication, a set of abstract proxy handler classes is - * provided, from which other handlers may inherit. These abstract classes are - * organized in the following hierarchy: - * - * BaseProxyHandler - * | - * Wrapper // has a target, can be unwrapped to reveal - * | // target (see js::CheckedUnwrap) - * | - * CrossCompartmentWrapper // target is in another compartment; - * // implements membrane between compartments - * - * Example: Some DOM objects (including all the arraylike DOM objects) are - * implemented as proxies. Since these objects don't need to forward operations - * to any underlying JS object, DOMJSProxyHandler directly subclasses - * BaseProxyHandler. - * - * Gecko's security wrappers are examples of cross-compartment wrappers. - * - * ### Proxy prototype chains - * - * In addition to the normal methods, there are two models for proxy prototype - * chains. - * - * 1. Proxies can use the standard prototype mechanism used throughout the - * engine. To do so, simply pass a prototype to NewProxyObject() at - * creation time. All prototype accesses will then "just work" to treat the - * proxy as a "normal" object. - * - * 2. A proxy can implement more complicated prototype semantics (if, for - * example, it wants to delegate the prototype lookup to a wrapped object) - * by passing Proxy::LazyProto as the prototype at create time. This - * guarantees that the getPrototype() handler method will be called every - * time the object's prototype chain is accessed. - * - * This system is implemented with two methods: {get,set}Prototype. The - * default implementation of setPrototype throws a TypeError. Since it is - * not possible to create an object without a sense of prototype chain, - * handlers must implement getPrototype if opting in to the dynamic - * prototype system. - */ - -/* - * BaseProxyHandler is the most generic kind of proxy handler. It does not make - * any assumptions about the target. Consequently, it does not provide any - * default implementation for most methods. As a convenience, a few high-level - * methods, like get() and set(), are given default implementations that work by - * calling the low-level methods, like getOwnPropertyDescriptor(). - * - * Important: If you add a method here, you should probably also add a - * Proxy::foo entry point with an AutoEnterPolicy. If you don't, you need an - * explicit override for the method in SecurityWrapper. See bug 945826 comment 0. - */ -class JS_FRIEND_API(BaseProxyHandler) -{ - /* - * Sometimes it's desirable to designate groups of proxy handlers as "similar". - * For this, we use the notion of a "family": A consumer-provided opaque pointer - * that designates the larger group to which this proxy belongs. - * - * If it will never be important to differentiate this proxy from others as - * part of a distinct group, nullptr may be used instead. - */ - const void* mFamily; - - /* - * Proxy handlers can use mHasPrototype to request the following special - * treatment from the JS engine: - * - * - When mHasPrototype is true, the engine never calls these methods: - * getPropertyDescriptor, has, set, enumerate, iterate. Instead, for - * these operations, it calls the "own" methods like - * getOwnPropertyDescriptor, hasOwn, defineProperty, - * getOwnEnumerablePropertyKeys, etc., and consults the prototype chain - * if needed. - * - * - When mHasPrototype is true, the engine calls handler->get() only if - * handler->hasOwn() says an own property exists on the proxy. If not, - * it consults the prototype chain. - * - * This is useful because it frees the ProxyHandler from having to implement - * any behavior having to do with the prototype chain. - */ - bool mHasPrototype; - - /* - * All proxies indicate whether they have any sort of interesting security - * policy that might prevent the caller from doing something it wants to - * the object. In the case of wrappers, this distinction is used to - * determine whether the caller may strip off the wrapper if it so desires. - */ - bool mHasSecurityPolicy; - - public: - explicit constexpr BaseProxyHandler(const void* aFamily, bool aHasPrototype = false, - bool aHasSecurityPolicy = false) - : mFamily(aFamily), - mHasPrototype(aHasPrototype), - mHasSecurityPolicy(aHasSecurityPolicy) - { } - - bool hasPrototype() const { - return mHasPrototype; - } - - bool hasSecurityPolicy() const { - return mHasSecurityPolicy; - } - - inline const void* family() const { - return mFamily; - } - static size_t offsetOfFamily() { - return offsetof(BaseProxyHandler, mFamily); - } - - virtual bool finalizeInBackground(const Value& priv) const { - /* - * Called on creation of a proxy to determine whether its finalize - * method can be finalized on the background thread. - */ - return true; - } - - virtual bool canNurseryAllocate() const { - /* - * Nursery allocation is allowed if and only if it is safe to not - * run |finalize| when the ProxyObject dies. - */ - return false; - } - - /* Policy enforcement methods. - * - * enter() allows the policy to specify whether the caller may perform |act| - * on the proxy's |id| property. In the case when |act| is CALL, |id| is - * generally JSID_VOID. - * - * The |act| parameter to enter() specifies the action being performed. - * If |bp| is false, the method suggests that the caller throw (though it - * may still decide to squelch the error). - * - * We make these OR-able so that assertEnteredPolicy can pass a union of them. - * For example, get{,Own}PropertyDescriptor is invoked by calls to ::get() - * ::set(), in addition to being invoked on its own, so there are several - * valid Actions that could have been entered. - */ - typedef uint32_t Action; - enum { - NONE = 0x00, - GET = 0x01, - SET = 0x02, - CALL = 0x04, - ENUMERATE = 0x08, - GET_PROPERTY_DESCRIPTOR = 0x10 - }; - - virtual bool enter(JSContext* cx, HandleObject wrapper, HandleId id, Action act, - bool* bp) const; - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const = 0; - virtual bool defineProperty(JSContext* cx, HandleObject proxy, HandleId id, - Handle desc, - ObjectOpResult& result) const = 0; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const = 0; - virtual bool delete_(JSContext* cx, HandleObject proxy, HandleId id, - ObjectOpResult& result) const = 0; - - /* - * These methods are standard, but the engine does not normally call them. - * They're opt-in. See "Proxy prototype chains" above. - * - * getPrototype() crashes if called. setPrototype() throws a TypeError. - */ - virtual bool getPrototype(JSContext* cx, HandleObject proxy, MutableHandleObject protop) const; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const; - - /* Non-standard but conceptual kin to {g,s}etPrototype, so these live here. */ - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, - MutableHandleObject protop) const = 0; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, bool* succeeded) const; - - virtual bool preventExtensions(JSContext* cx, HandleObject proxy, - ObjectOpResult& result) const = 0; - virtual bool isExtensible(JSContext* cx, HandleObject proxy, bool* extensible) const = 0; - - /* - * These standard internal methods are implemented, as a convenience, so - * that ProxyHandler subclasses don't have to provide every single method. - * - * The base-class implementations work by calling getPropertyDescriptor(). - * They do not follow any standard. When in doubt, override them. - */ - virtual bool has(JSContext* cx, HandleObject proxy, HandleId id, bool* bp) const; - virtual bool get(JSContext* cx, HandleObject proxy, HandleValue receiver, - HandleId id, MutableHandleValue vp) const; - virtual bool set(JSContext* cx, HandleObject proxy, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const; - - /* - * [[Call]] and [[Construct]] are standard internal methods but according - * to the spec, they are not present on every object. - * - * SpiderMonkey never calls a proxy's call()/construct() internal method - * unless isCallable()/isConstructor() returns true for that proxy. - * - * BaseProxyHandler::isCallable()/isConstructor() always return false, and - * BaseProxyHandler::call()/construct() crash if called. So if you're - * creating a kind of that is never callable, you don't have to override - * anything, but otherwise you probably want to override all four. - */ - virtual bool call(JSContext* cx, HandleObject proxy, const CallArgs& args) const; - virtual bool construct(JSContext* cx, HandleObject proxy, const CallArgs& args) const; - - /* SpiderMonkey extensions. */ - virtual bool enumerate(JSContext* cx, HandleObject proxy, MutableHandleObject objp) const; - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const; - virtual bool hasOwn(JSContext* cx, HandleObject proxy, HandleId id, bool* bp) const; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const; - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const; - virtual bool hasInstance(JSContext* cx, HandleObject proxy, MutableHandleValue v, bool* bp) const; - virtual bool getBuiltinClass(JSContext* cx, HandleObject proxy, - ESClass* cls) const; - virtual bool isArray(JSContext* cx, HandleObject proxy, JS::IsArrayAnswer* answer) const; - virtual const char* className(JSContext* cx, HandleObject proxy) const; - virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, unsigned indent) const; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const; - virtual void trace(JSTracer* trc, JSObject* proxy) const; - virtual void finalize(JSFreeOp* fop, JSObject* proxy) const; - virtual void objectMoved(JSObject* proxy, const JSObject* old) const; - - // Allow proxies, wrappers in particular, to specify callability at runtime. - // Note: These do not take const JSObject*, but they do in spirit. - // We are not prepared to do this, as there's little const correctness - // in the external APIs that handle proxies. - virtual bool isCallable(JSObject* obj) const; - virtual bool isConstructor(JSObject* obj) const; - - // These two hooks must be overridden, or not overridden, in tandem -- no - // overriding just one! - virtual bool watch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, - JS::HandleObject callable) const; - virtual bool unwatch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id) const; - - virtual bool getElements(JSContext* cx, HandleObject proxy, uint32_t begin, uint32_t end, - ElementAdder* adder) const; - - /* See comment for weakmapKeyDelegateOp in js/Class.h. */ - virtual JSObject* weakmapKeyDelegate(JSObject* proxy) const; - virtual bool isScripted() const { return false; } -}; - -extern JS_FRIEND_DATA(const js::Class* const) ProxyClassPtr; - -inline bool IsProxy(const JSObject* obj) -{ - return GetObjectClass(obj)->isProxy(); -} - -namespace detail { -const uint32_t PROXY_EXTRA_SLOTS = 2; - -// Layout of the values stored by a proxy. Note that API clients require the -// private slot to be the first slot in the proxy's values, so that the private -// slot can be accessed in the same fashion as the first reserved slot, via -// {Get,Set}ReservedOrProxyPrivateSlot. - -struct ProxyValueArray -{ - Value privateSlot; - Value extraSlots[PROXY_EXTRA_SLOTS]; - - ProxyValueArray() - : privateSlot(JS::UndefinedValue()) - { - for (size_t i = 0; i < PROXY_EXTRA_SLOTS; i++) - extraSlots[i] = JS::UndefinedValue(); - } -}; - -// All proxies share the same data layout. Following the object's shape and -// type, the proxy has a ProxyDataLayout structure with a pointer to an array -// of values and the proxy's handler. This is designed both so that proxies can -// be easily swapped with other objects (via RemapWrapper) and to mimic the -// layout of other objects (proxies and other objects have the same size) so -// that common code can access either type of object. -// -// See GetReservedOrProxyPrivateSlot below. -struct ProxyDataLayout -{ - ProxyValueArray* values; - const BaseProxyHandler* handler; -}; - -const uint32_t ProxyDataOffset = 2 * sizeof(void*); - -inline ProxyDataLayout* -GetProxyDataLayout(JSObject* obj) -{ - MOZ_ASSERT(IsProxy(obj)); - return reinterpret_cast(reinterpret_cast(obj) + ProxyDataOffset); -} - -inline const ProxyDataLayout* -GetProxyDataLayout(const JSObject* obj) -{ - MOZ_ASSERT(IsProxy(obj)); - return reinterpret_cast(reinterpret_cast(obj) + - ProxyDataOffset); -} -} // namespace detail - -inline const BaseProxyHandler* -GetProxyHandler(const JSObject* obj) -{ - return detail::GetProxyDataLayout(obj)->handler; -} - -inline const Value& -GetProxyPrivate(const JSObject* obj) -{ - return detail::GetProxyDataLayout(obj)->values->privateSlot; -} - -inline JSObject* -GetProxyTargetObject(JSObject* obj) -{ - return GetProxyPrivate(obj).toObjectOrNull(); -} - -inline const Value& -GetProxyExtra(const JSObject* obj, size_t n) -{ - MOZ_ASSERT(n < detail::PROXY_EXTRA_SLOTS); - return detail::GetProxyDataLayout(obj)->values->extraSlots[n]; -} - -inline void -SetProxyHandler(JSObject* obj, const BaseProxyHandler* handler) -{ - detail::GetProxyDataLayout(obj)->handler = handler; -} - -JS_FRIEND_API(void) -SetValueInProxy(Value* slot, const Value& value); - -inline void -SetProxyExtra(JSObject* obj, size_t n, const Value& extra) -{ - MOZ_ASSERT(n < detail::PROXY_EXTRA_SLOTS); - Value* vp = &detail::GetProxyDataLayout(obj)->values->extraSlots[n]; - - // Trigger a barrier before writing the slot. - if (vp->isMarkable() || extra.isMarkable()) - SetValueInProxy(vp, extra); - else - *vp = extra; -} - -inline bool -IsScriptedProxy(const JSObject* obj) -{ - return IsProxy(obj) && GetProxyHandler(obj)->isScripted(); -} - -inline const Value& -GetReservedOrProxyPrivateSlot(const JSObject* obj, size_t slot) -{ - MOZ_ASSERT(slot == 0); - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj)) || IsProxy(obj)); - return reinterpret_cast(obj)->slotRef(slot); -} - -inline void -SetReservedOrProxyPrivateSlot(JSObject* obj, size_t slot, const Value& value) -{ - MOZ_ASSERT(slot == 0); - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj)) || IsProxy(obj)); - shadow::Object* sobj = reinterpret_cast(obj); - if (sobj->slotRef(slot).isMarkable() || value.isMarkable()) - SetReservedOrProxyPrivateSlotWithBarrier(obj, slot, value); - else - sobj->slotRef(slot) = value; -} - -class MOZ_STACK_CLASS ProxyOptions { - protected: - /* protected constructor for subclass */ - explicit ProxyOptions(bool singletonArg, bool lazyProtoArg = false) - : singleton_(singletonArg), - lazyProto_(lazyProtoArg), - clasp_(ProxyClassPtr) - {} - - public: - ProxyOptions() : singleton_(false), - lazyProto_(false), - clasp_(ProxyClassPtr) - {} - - bool singleton() const { return singleton_; } - ProxyOptions& setSingleton(bool flag) { - singleton_ = flag; - return *this; - } - - bool lazyProto() const { return lazyProto_; } - ProxyOptions& setLazyProto(bool flag) { - lazyProto_ = flag; - return *this; - } - - const Class* clasp() const { - return clasp_; - } - ProxyOptions& setClass(const Class* claspArg) { - clasp_ = claspArg; - return *this; - } - - private: - bool singleton_; - bool lazyProto_; - const Class* clasp_; -}; - -JS_FRIEND_API(JSObject*) -NewProxyObject(JSContext* cx, const BaseProxyHandler* handler, HandleValue priv, - JSObject* proto, const ProxyOptions& options = ProxyOptions()); - -JSObject* -RenewProxyObject(JSContext* cx, JSObject* obj, BaseProxyHandler* handler, const Value& priv); - -class JS_FRIEND_API(AutoEnterPolicy) -{ - public: - typedef BaseProxyHandler::Action Action; - AutoEnterPolicy(JSContext* cx, const BaseProxyHandler* handler, - HandleObject wrapper, HandleId id, Action act, bool mayThrow) -#ifdef JS_DEBUG - : context(nullptr) -#endif - { - allow = handler->hasSecurityPolicy() ? handler->enter(cx, wrapper, id, act, &rv) - : true; - recordEnter(cx, wrapper, id, act); - // We want to throw an exception if all of the following are true: - // * The policy disallowed access. - // * The policy set rv to false, indicating that we should throw. - // * The caller did not instruct us to ignore exceptions. - // * The policy did not throw itself. - if (!allow && !rv && mayThrow) - reportErrorIfExceptionIsNotPending(cx, id); - } - - virtual ~AutoEnterPolicy() { recordLeave(); } - inline bool allowed() { return allow; } - inline bool returnValue() { MOZ_ASSERT(!allowed()); return rv; } - - protected: - // no-op constructor for subclass - AutoEnterPolicy() -#ifdef JS_DEBUG - : context(nullptr) - , enteredAction(BaseProxyHandler::NONE) -#endif - {} - void reportErrorIfExceptionIsNotPending(JSContext* cx, jsid id); - bool allow; - bool rv; - -#ifdef JS_DEBUG - JSContext* context; - mozilla::Maybe enteredProxy; - mozilla::Maybe enteredId; - Action enteredAction; - - // NB: We explicitly don't track the entered action here, because sometimes - // set() methods do an implicit get() during their implementation, leading - // to spurious assertions. - AutoEnterPolicy* prev; - void recordEnter(JSContext* cx, HandleObject proxy, HandleId id, Action act); - void recordLeave(); - - friend JS_FRIEND_API(void) assertEnteredPolicy(JSContext* cx, JSObject* proxy, jsid id, Action act); -#else - inline void recordEnter(JSContext* cx, JSObject* proxy, jsid id, Action act) {} - inline void recordLeave() {} -#endif - -}; - -#ifdef JS_DEBUG -class JS_FRIEND_API(AutoWaivePolicy) : public AutoEnterPolicy { -public: - AutoWaivePolicy(JSContext* cx, HandleObject proxy, HandleId id, - BaseProxyHandler::Action act) - { - allow = true; - recordEnter(cx, proxy, id, act); - } -}; -#else -class JS_FRIEND_API(AutoWaivePolicy) { - public: - AutoWaivePolicy(JSContext* cx, HandleObject proxy, HandleId id, - BaseProxyHandler::Action act) - {} -}; -#endif - -#ifdef JS_DEBUG -extern JS_FRIEND_API(void) -assertEnteredPolicy(JSContext* cx, JSObject* obj, jsid id, - BaseProxyHandler::Action act); -#else -inline void assertEnteredPolicy(JSContext* cx, JSObject* obj, jsid id, - BaseProxyHandler::Action act) -{} -#endif - -extern JS_FRIEND_API(JSObject*) -InitProxyClass(JSContext* cx, JS::HandleObject obj); - -} /* namespace js */ - -#endif /* js_Proxy_h */ diff --git a/ios/include/spidermonkey/js/Realm.h b/ios/include/spidermonkey/js/Realm.h deleted file mode 100644 index 13a22c70..00000000 --- a/ios/include/spidermonkey/js/Realm.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Ways to get various per-Realm objects. All the getters declared in this - * header operate on the Realm corresponding to the current compartment on the - * JSContext. - */ - -#ifndef js_Realm_h -#define js_Realm_h - -#include "jstypes.h" - -struct JSContext; -class JSObject; - -namespace JS { - -extern JS_PUBLIC_API(JSObject*) -GetRealmObjectPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmFunctionPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmArrayPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmErrorPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmIteratorPrototype(JSContext* cx); - -} // namespace JS - -#endif // js_Realm_h - - diff --git a/ios/include/spidermonkey/js/RequiredDefines.h b/ios/include/spidermonkey/js/RequiredDefines.h deleted file mode 100644 index 308fd7d6..00000000 --- a/ios/include/spidermonkey/js/RequiredDefines.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Various #defines required to build SpiderMonkey. Embedders should add this - * file to the start of the command line via -include or a similar mechanism, - * or SpiderMonkey public headers may not work correctly. - */ - -#ifndef js_RequiredDefines_h -#define js_RequiredDefines_h - -/* - * The c99 defining the limit macros (UINT32_MAX for example), says: - * - * C++ implementations should define these macros only when - * __STDC_LIMIT_MACROS is defined before is included. - * - * The same also occurs with __STDC_CONSTANT_MACROS for the constant macros - * (INT8_C for example) used to specify a literal constant of the proper type, - * and with __STDC_FORMAT_MACROS for the format macros (PRId32 for example) used - * with the fprintf function family. - */ -#define __STDC_LIMIT_MACROS -#define __STDC_CONSTANT_MACROS -#define __STDC_FORMAT_MACROS - -/* Also define a char16_t type if not provided by the compiler. */ -#include "mozilla/Char16.h" - -#endif /* js_RequiredDefines_h */ diff --git a/ios/include/spidermonkey/js/RootingAPI.h b/ios/include/spidermonkey/js/RootingAPI.h deleted file mode 100644 index a99ac4ec..00000000 --- a/ios/include/spidermonkey/js/RootingAPI.h +++ /dev/null @@ -1,1308 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_RootingAPI_h -#define js_RootingAPI_h - -#include "mozilla/Attributes.h" -#include "mozilla/DebugOnly.h" -#include "mozilla/GuardObjects.h" -#include "mozilla/LinkedList.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include - -#include "jspubtd.h" - -#include "js/GCAnnotations.h" -#include "js/GCAPI.h" -#include "js/GCPolicyAPI.h" -#include "js/HeapAPI.h" -#include "js/TypeDecls.h" -#include "js/UniquePtr.h" -#include "js/Utility.h" - -/* - * Moving GC Stack Rooting - * - * A moving GC may change the physical location of GC allocated things, even - * when they are rooted, updating all pointers to the thing to refer to its new - * location. The GC must therefore know about all live pointers to a thing, - * not just one of them, in order to behave correctly. - * - * The |Rooted| and |Handle| classes below are used to root stack locations - * whose value may be held live across a call that can trigger GC. For a - * code fragment such as: - * - * JSObject* obj = NewObject(cx); - * DoSomething(cx); - * ... = obj->lastProperty(); - * - * If |DoSomething()| can trigger a GC, the stack location of |obj| must be - * rooted to ensure that the GC does not move the JSObject referred to by - * |obj| without updating |obj|'s location itself. This rooting must happen - * regardless of whether there are other roots which ensure that the object - * itself will not be collected. - * - * If |DoSomething()| cannot trigger a GC, and the same holds for all other - * calls made between |obj|'s definitions and its last uses, then no rooting - * is required. - * - * SpiderMonkey can trigger a GC at almost any time and in ways that are not - * always clear. For example, the following innocuous-looking actions can - * cause a GC: allocation of any new GC thing; JSObject::hasProperty; - * JS_ReportError and friends; and ToNumber, among many others. The following - * dangerous-looking actions cannot trigger a GC: js_malloc, cx->malloc_, - * rt->malloc_, and friends and JS_ReportOutOfMemory. - * - * The following family of three classes will exactly root a stack location. - * Incorrect usage of these classes will result in a compile error in almost - * all cases. Therefore, it is very hard to be incorrectly rooted if you use - * these classes exclusively. These classes are all templated on the type T of - * the value being rooted. - * - * - Rooted declares a variable of type T, whose value is always rooted. - * Rooted may be automatically coerced to a Handle, below. Rooted - * should be used whenever a local variable's value may be held live across a - * call which can trigger a GC. - * - * - Handle is a const reference to a Rooted. Functions which take GC - * things or values as arguments and need to root those arguments should - * generally use handles for those arguments and avoid any explicit rooting. - * This has two benefits. First, when several such functions call each other - * then redundant rooting of multiple copies of the GC thing can be avoided. - * Second, if the caller does not pass a rooted value a compile error will be - * generated, which is quicker and easier to fix than when relying on a - * separate rooting analysis. - * - * - MutableHandle is a non-const reference to Rooted. It is used in the - * same way as Handle and includes a |set(const T& v)| method to allow - * updating the value of the referenced Rooted. A MutableHandle can be - * created with an implicit cast from a Rooted*. - * - * In some cases the small performance overhead of exact rooting (measured to - * be a few nanoseconds on desktop) is too much. In these cases, try the - * following: - * - * - Move all Rooted above inner loops: this allows you to re-use the root - * on each iteration of the loop. - * - * - Pass Handle through your hot call stack to avoid re-rooting costs at - * every invocation. - * - * The following diagram explains the list of supported, implicit type - * conversions between classes of this family: - * - * Rooted ----> Handle - * | ^ - * | | - * | | - * +---> MutableHandle - * (via &) - * - * All of these types have an implicit conversion to raw pointers. - */ - -namespace js { - -template -struct BarrierMethods { -}; - -template -class RootedBase {}; - -template -class HandleBase {}; - -template -class MutableHandleBase {}; - -template -class HeapBase {}; - -// Cannot use FOR_EACH_HEAP_ABLE_GC_POINTER_TYPE, as this would import too many macros into scope -template struct IsHeapConstructibleType { static constexpr bool value = false; }; -#define DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE(T) \ - template <> struct IsHeapConstructibleType { static constexpr bool value = true; }; -FOR_EACH_PUBLIC_GC_POINTER_TYPE(DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE) -FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE) -#undef DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE - -template -class PersistentRootedBase {}; - -static void* const ConstNullValue = nullptr; - -namespace gc { -struct Cell; -template -struct PersistentRootedMarker; -} /* namespace gc */ - -#define DECLARE_POINTER_COMPARISON_OPS(T) \ - bool operator==(const T& other) const { return get() == other; } \ - bool operator!=(const T& other) const { return get() != other; } - -// Important: Return a reference so passing a Rooted, etc. to -// something that takes a |const T&| is not a GC hazard. -#define DECLARE_POINTER_CONSTREF_OPS(T) \ - operator const T&() const { return get(); } \ - const T& operator->() const { return get(); } - -// Assignment operators on a base class are hidden by the implicitly defined -// operator= on the derived class. Thus, define the operator= directly on the -// class as we would need to manually pass it through anyway. -#define DECLARE_POINTER_ASSIGN_OPS(Wrapper, T) \ - Wrapper& operator=(const T& p) { \ - set(p); \ - return *this; \ - } \ - Wrapper& operator=(const Wrapper& other) { \ - set(other.get()); \ - return *this; \ - } \ - -#define DELETE_ASSIGNMENT_OPS(Wrapper, T) \ - template Wrapper& operator=(S) = delete; \ - Wrapper& operator=(const Wrapper&) = delete; - -#define DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr) \ - const T* address() const { return &(ptr); } \ - const T& get() const { return (ptr); } \ - -#define DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr) \ - T* address() { return &(ptr); } \ - T& get() { return (ptr); } \ - -} /* namespace js */ - -namespace JS { - -template class Rooted; -template class PersistentRooted; - -/* This is exposing internal state of the GC for inlining purposes. */ -JS_FRIEND_API(bool) isGCEnabled(); - -JS_FRIEND_API(void) HeapObjectPostBarrier(JSObject** objp, JSObject* prev, JSObject* next); - -#ifdef JS_DEBUG -/** - * For generational GC, assert that an object is in the tenured generation as - * opposed to being in the nursery. - */ -extern JS_FRIEND_API(void) -AssertGCThingMustBeTenured(JSObject* obj); -extern JS_FRIEND_API(void) -AssertGCThingIsNotAnObjectSubclass(js::gc::Cell* cell); -#else -inline void -AssertGCThingMustBeTenured(JSObject* obj) {} -inline void -AssertGCThingIsNotAnObjectSubclass(js::gc::Cell* cell) {} -#endif - -/** - * The Heap class is a heap-stored reference to a JS GC thing. All members of - * heap classes that refer to GC things should use Heap (or possibly - * TenuredHeap, described below). - * - * Heap is an abstraction that hides some of the complexity required to - * maintain GC invariants for the contained reference. It uses operator - * overloading to provide a normal pointer interface, but notifies the GC every - * time the value it contains is updated. This is necessary for generational GC, - * which keeps track of all pointers into the nursery. - * - * Heap instances must be traced when their containing object is traced to - * keep the pointed-to GC thing alive. - * - * Heap objects should only be used on the heap. GC references stored on the - * C/C++ stack must use Rooted/Handle/MutableHandle instead. - * - * Type T must be a public GC pointer type. - */ -template -class Heap : public js::HeapBase -{ - // Please note: this can actually also be used by nsXBLMaybeCompiled, for legacy reasons. - static_assert(js::IsHeapConstructibleType::value, - "Type T must be a public GC pointer type"); - public: - Heap() { - static_assert(sizeof(T) == sizeof(Heap), - "Heap must be binary compatible with T."); - init(GCPolicy::initial()); - } - explicit Heap(const T& p) { init(p); } - - /* - * For Heap, move semantics are equivalent to copy semantics. In C++, a - * copy constructor taking const-ref is the way to get a single function - * that will be used for both lvalue and rvalue copies, so we can simply - * omit the rvalue variant. - */ - explicit Heap(const Heap& p) { init(p.ptr); } - - ~Heap() { - post(ptr, GCPolicy::initial()); - } - - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(Heap, T); - - const T* address() const { return &ptr; } - - void exposeToActiveJS() const { - js::BarrierMethods::exposeToJS(ptr); - } - const T& get() const { - exposeToActiveJS(); - return ptr; - } - const T& unbarrieredGet() const { - return ptr; - } - - T* unsafeGet() { return &ptr; } - - explicit operator bool() const { - return bool(js::BarrierMethods::asGCThingOrNull(ptr)); - } - explicit operator bool() { - return bool(js::BarrierMethods::asGCThingOrNull(ptr)); - } - - private: - void init(const T& newPtr) { - ptr = newPtr; - post(GCPolicy::initial(), ptr); - } - - void set(const T& newPtr) { - T tmp = ptr; - ptr = newPtr; - post(tmp, ptr); - } - - void post(const T& prev, const T& next) { - js::BarrierMethods::postBarrier(&ptr, prev, next); - } - - T ptr; -}; - -static MOZ_ALWAYS_INLINE bool -ObjectIsTenured(JSObject* obj) -{ - return !js::gc::IsInsideNursery(reinterpret_cast(obj)); -} - -static MOZ_ALWAYS_INLINE bool -ObjectIsTenured(const Heap& obj) -{ - return ObjectIsTenured(obj.unbarrieredGet()); -} - -static MOZ_ALWAYS_INLINE bool -ObjectIsMarkedGray(JSObject* obj) -{ - auto cell = reinterpret_cast(obj); - return js::gc::detail::CellIsMarkedGrayIfKnown(cell); -} - -static MOZ_ALWAYS_INLINE bool -ObjectIsMarkedGray(const JS::Heap& obj) -{ - return ObjectIsMarkedGray(obj.unbarrieredGet()); -} - -static MOZ_ALWAYS_INLINE bool -ScriptIsMarkedGray(JSScript* script) -{ - auto cell = reinterpret_cast(script); - return js::gc::detail::CellIsMarkedGrayIfKnown(cell); -} - -static MOZ_ALWAYS_INLINE bool -ScriptIsMarkedGray(const Heap& script) -{ - return ScriptIsMarkedGray(script.unbarrieredGet()); -} - -/** - * The TenuredHeap class is similar to the Heap class above in that it - * encapsulates the GC concerns of an on-heap reference to a JS object. However, - * it has two important differences: - * - * 1) Pointers which are statically known to only reference "tenured" objects - * can avoid the extra overhead of SpiderMonkey's write barriers. - * - * 2) Objects in the "tenured" heap have stronger alignment restrictions than - * those in the "nursery", so it is possible to store flags in the lower - * bits of pointers known to be tenured. TenuredHeap wraps a normal tagged - * pointer with a nice API for accessing the flag bits and adds various - * assertions to ensure that it is not mis-used. - * - * GC things are said to be "tenured" when they are located in the long-lived - * heap: e.g. they have gained tenure as an object by surviving past at least - * one GC. For performance, SpiderMonkey allocates some things which are known - * to normally be long lived directly into the tenured generation; for example, - * global objects. Additionally, SpiderMonkey does not visit individual objects - * when deleting non-tenured objects, so object with finalizers are also always - * tenured; for instance, this includes most DOM objects. - * - * The considerations to keep in mind when using a TenuredHeap vs a normal - * Heap are: - * - * - It is invalid for a TenuredHeap to refer to a non-tenured thing. - * - It is however valid for a Heap to refer to a tenured thing. - * - It is not possible to store flag bits in a Heap. - */ -template -class TenuredHeap : public js::HeapBase -{ - public: - TenuredHeap() : bits(0) { - static_assert(sizeof(T) == sizeof(TenuredHeap), - "TenuredHeap must be binary compatible with T."); - } - explicit TenuredHeap(T p) : bits(0) { setPtr(p); } - explicit TenuredHeap(const TenuredHeap& p) : bits(0) { setPtr(p.getPtr()); } - - bool operator==(const TenuredHeap& other) { return bits == other.bits; } - bool operator!=(const TenuredHeap& other) { return bits != other.bits; } - - void setPtr(T newPtr) { - MOZ_ASSERT((reinterpret_cast(newPtr) & flagsMask) == 0); - if (newPtr) - AssertGCThingMustBeTenured(newPtr); - bits = (bits & flagsMask) | reinterpret_cast(newPtr); - } - - void setFlags(uintptr_t flagsToSet) { - MOZ_ASSERT((flagsToSet & ~flagsMask) == 0); - bits |= flagsToSet; - } - - void unsetFlags(uintptr_t flagsToUnset) { - MOZ_ASSERT((flagsToUnset & ~flagsMask) == 0); - bits &= ~flagsToUnset; - } - - bool hasFlag(uintptr_t flag) const { - MOZ_ASSERT((flag & ~flagsMask) == 0); - return (bits & flag) != 0; - } - - T unbarrieredGetPtr() const { return reinterpret_cast(bits & ~flagsMask); } - uintptr_t getFlags() const { return bits & flagsMask; } - - void exposeToActiveJS() const { - js::BarrierMethods::exposeToJS(unbarrieredGetPtr()); - } - T getPtr() const { - exposeToActiveJS(); - return unbarrieredGetPtr(); - } - - operator T() const { return getPtr(); } - T operator->() const { return getPtr(); } - - explicit operator bool() const { - return bool(js::BarrierMethods::asGCThingOrNull(unbarrieredGetPtr())); - } - explicit operator bool() { - return bool(js::BarrierMethods::asGCThingOrNull(unbarrieredGetPtr())); - } - - TenuredHeap& operator=(T p) { - setPtr(p); - return *this; - } - - TenuredHeap& operator=(const TenuredHeap& other) { - bits = other.bits; - return *this; - } - - private: - enum { - maskBits = 3, - flagsMask = (1 << maskBits) - 1, - }; - - uintptr_t bits; -}; - -/** - * Reference to a T that has been rooted elsewhere. This is most useful - * as a parameter type, which guarantees that the T lvalue is properly - * rooted. See "Move GC Stack Rooting" above. - * - * If you want to add additional methods to Handle for a specific - * specialization, define a HandleBase specialization containing them. - */ -template -class MOZ_NONHEAP_CLASS Handle : public js::HandleBase -{ - friend class JS::MutableHandle; - - public: - /* Creates a handle from a handle of a type convertible to T. */ - template - MOZ_IMPLICIT Handle(Handle handle, - typename mozilla::EnableIf::value, int>::Type dummy = 0) - { - static_assert(sizeof(Handle) == sizeof(T*), - "Handle must be binary compatible with T*."); - ptr = reinterpret_cast(handle.address()); - } - - MOZ_IMPLICIT Handle(decltype(nullptr)) { - static_assert(mozilla::IsPointer::value, - "nullptr_t overload not valid for non-pointer types"); - ptr = reinterpret_cast(&js::ConstNullValue); - } - - MOZ_IMPLICIT Handle(MutableHandle handle) { - ptr = handle.address(); - } - - /* - * Take care when calling this method! - * - * This creates a Handle from the raw location of a T. - * - * It should be called only if the following conditions hold: - * - * 1) the location of the T is guaranteed to be marked (for some reason - * other than being a Rooted), e.g., if it is guaranteed to be reachable - * from an implicit root. - * - * 2) the contents of the location are immutable, or at least cannot change - * for the lifetime of the handle, as its users may not expect its value - * to change underneath them. - */ - static constexpr Handle fromMarkedLocation(const T* p) { - return Handle(p, DeliberatelyChoosingThisOverload, - ImUsingThisOnlyInFromFromMarkedLocation); - } - - /* - * Construct a handle from an explicitly rooted location. This is the - * normal way to create a handle, and normally happens implicitly. - */ - template - inline - MOZ_IMPLICIT Handle(const Rooted& root, - typename mozilla::EnableIf::value, int>::Type dummy = 0); - - template - inline - MOZ_IMPLICIT Handle(const PersistentRooted& root, - typename mozilla::EnableIf::value, int>::Type dummy = 0); - - /* Construct a read only handle from a mutable handle. */ - template - inline - MOZ_IMPLICIT Handle(MutableHandle& root, - typename mozilla::EnableIf::value, int>::Type dummy = 0); - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr); - - private: - Handle() {} - DELETE_ASSIGNMENT_OPS(Handle, T); - - enum Disambiguator { DeliberatelyChoosingThisOverload = 42 }; - enum CallerIdentity { ImUsingThisOnlyInFromFromMarkedLocation = 17 }; - constexpr Handle(const T* p, Disambiguator, CallerIdentity) : ptr(p) {} - - const T* ptr; -}; - -/** - * Similar to a handle, but the underlying storage can be changed. This is - * useful for outparams. - * - * If you want to add additional methods to MutableHandle for a specific - * specialization, define a MutableHandleBase specialization containing - * them. - */ -template -class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase -{ - public: - inline MOZ_IMPLICIT MutableHandle(Rooted* root); - inline MOZ_IMPLICIT MutableHandle(PersistentRooted* root); - - private: - // Disallow nullptr for overloading purposes. - MutableHandle(decltype(nullptr)) = delete; - - public: - void set(const T& v) { - *ptr = v; - } - - /* - * This may be called only if the location of the T is guaranteed - * to be marked (for some reason other than being a Rooted), - * e.g., if it is guaranteed to be reachable from an implicit root. - * - * Create a MutableHandle from a raw location of a T. - */ - static MutableHandle fromMarkedLocation(T* p) { - MutableHandle h; - h.ptr = p; - return h; - } - - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(*ptr); - - private: - MutableHandle() {} - DELETE_ASSIGNMENT_OPS(MutableHandle, T); - - T* ptr; -}; - -} /* namespace JS */ - -namespace js { - -template -struct BarrierMethods -{ - static T* initial() { return nullptr; } - static gc::Cell* asGCThingOrNull(T* v) { - if (!v) - return nullptr; - MOZ_ASSERT(uintptr_t(v) > 32); - return reinterpret_cast(v); - } - static void postBarrier(T** vp, T* prev, T* next) { - if (next) - JS::AssertGCThingIsNotAnObjectSubclass(reinterpret_cast(next)); - } - static void exposeToJS(T* t) { - if (t) - js::gc::ExposeGCThingToActiveJS(JS::GCCellPtr(t)); - } -}; - -template <> -struct BarrierMethods -{ - static JSObject* initial() { return nullptr; } - static gc::Cell* asGCThingOrNull(JSObject* v) { - if (!v) - return nullptr; - MOZ_ASSERT(uintptr_t(v) > 32); - return reinterpret_cast(v); - } - static void postBarrier(JSObject** vp, JSObject* prev, JSObject* next) { - JS::HeapObjectPostBarrier(vp, prev, next); - } - static void exposeToJS(JSObject* obj) { - if (obj) - JS::ExposeObjectToActiveJS(obj); - } -}; - -template <> -struct BarrierMethods -{ - static JSFunction* initial() { return nullptr; } - static gc::Cell* asGCThingOrNull(JSFunction* v) { - if (!v) - return nullptr; - MOZ_ASSERT(uintptr_t(v) > 32); - return reinterpret_cast(v); - } - static void postBarrier(JSFunction** vp, JSFunction* prev, JSFunction* next) { - JS::HeapObjectPostBarrier(reinterpret_cast(vp), - reinterpret_cast(prev), - reinterpret_cast(next)); - } - static void exposeToJS(JSFunction* fun) { - if (fun) - JS::ExposeObjectToActiveJS(reinterpret_cast(fun)); - } -}; - -// Provide hash codes for Cell kinds that may be relocated and, thus, not have -// a stable address to use as the base for a hash code. Instead of the address, -// this hasher uses Cell::getUniqueId to provide exact matches and as a base -// for generating hash codes. -// -// Note: this hasher, like PointerHasher can "hash" a nullptr. While a nullptr -// would not likely be a useful key, there are some cases where being able to -// hash a nullptr is useful, either on purpose or because of bugs: -// (1) existence checks where the key may happen to be null and (2) some -// aggregate Lookup kinds embed a JSObject* that is frequently null and do not -// null test before dispatching to the hasher. -template -struct JS_PUBLIC_API(MovableCellHasher) -{ - using Key = T; - using Lookup = T; - - static bool hasHash(const Lookup& l); - static bool ensureHash(const Lookup& l); - static HashNumber hash(const Lookup& l); - static bool match(const Key& k, const Lookup& l); - static void rekey(Key& k, const Key& newKey) { k = newKey; } -}; - -template -struct JS_PUBLIC_API(MovableCellHasher>) -{ - using Key = JS::Heap; - using Lookup = T; - - static bool hasHash(const Lookup& l) { return MovableCellHasher::hasHash(l); } - static bool ensureHash(const Lookup& l) { return MovableCellHasher::ensureHash(l); } - static HashNumber hash(const Lookup& l) { return MovableCellHasher::hash(l); } - static bool match(const Key& k, const Lookup& l) { - return MovableCellHasher::match(k.unbarrieredGet(), l); - } - static void rekey(Key& k, const Key& newKey) { k.unsafeSet(newKey); } -}; - -template -struct FallibleHashMethods> -{ - template static bool hasHash(Lookup&& l) { - return MovableCellHasher::hasHash(mozilla::Forward(l)); - } - template static bool ensureHash(Lookup&& l) { - return MovableCellHasher::ensureHash(mozilla::Forward(l)); - } -}; - -} /* namespace js */ - -namespace js { - -// The alignment must be set because the Rooted and PersistentRooted ptr fields -// may be accessed through reinterpret_cast*>, and -// the compiler may choose a different alignment for the ptr field when it -// knows the actual type stored in DispatchWrapper. -// -// It would make more sense to align only those specific fields of type -// DispatchWrapper, rather than DispatchWrapper itself, but that causes MSVC to -// fail when Rooted is used in an IsConvertible test. -template -class alignas(8) DispatchWrapper -{ - static_assert(JS::MapTypeToRootKind::kind == JS::RootKind::Traceable, - "DispatchWrapper is intended only for usage with a Traceable"); - - using TraceFn = void (*)(JSTracer*, T*, const char*); - TraceFn tracer; - alignas(gc::CellSize) T storage; - - public: - template - MOZ_IMPLICIT DispatchWrapper(U&& initial) - : tracer(&JS::GCPolicy::trace), - storage(mozilla::Forward(initial)) - { } - - // Mimic a pointer type, so that we can drop into Rooted. - T* operator &() { return &storage; } - const T* operator &() const { return &storage; } - operator T&() { return storage; } - operator const T&() const { return storage; } - - // Trace the contained storage (of unknown type) using the trace function - // we set aside when we did know the type. - static void TraceWrapped(JSTracer* trc, T* thingp, const char* name) { - auto wrapper = reinterpret_cast( - uintptr_t(thingp) - offsetof(DispatchWrapper, storage)); - wrapper->tracer(trc, &wrapper->storage, name); - } -}; - -} /* namespace js */ - -namespace JS { - -/** - * Local variable of type T whose value is always rooted. This is typically - * used for local variables, or for non-rooted values being passed to a - * function that requires a handle, e.g. Foo(Root(cx, x)). - * - * If you want to add additional methods to Rooted for a specific - * specialization, define a RootedBase specialization containing them. - */ -template -class MOZ_RAII Rooted : public js::RootedBase -{ - inline void registerWithRootLists(js::RootedListHeads& roots) { - this->stack = &roots[JS::MapTypeToRootKind::kind]; - this->prev = *stack; - *stack = reinterpret_cast*>(this); - } - - inline js::RootedListHeads& rootLists(JS::RootingContext* cx) { - return rootLists(static_cast(cx)); - } - inline js::RootedListHeads& rootLists(js::ContextFriendFields* cx) { - if (JS::Zone* zone = cx->zone_) - return JS::shadow::Zone::asShadowZone(zone)->stackRoots_; - MOZ_ASSERT(cx->isJSContext); - return cx->roots.stackRoots_; - } - inline js::RootedListHeads& rootLists(JSContext* cx) { - return rootLists(js::ContextFriendFields::get(cx)); - } - - public: - template - explicit Rooted(const RootingContext& cx) - : ptr(GCPolicy::initial()) - { - registerWithRootLists(rootLists(cx)); - } - - template - Rooted(const RootingContext& cx, S&& initial) - : ptr(mozilla::Forward(initial)) - { - registerWithRootLists(rootLists(cx)); - } - - ~Rooted() { - MOZ_ASSERT(*stack == reinterpret_cast*>(this)); - *stack = prev; - } - - Rooted* previous() { return reinterpret_cast*>(prev); } - - /* - * This method is public for Rooted so that Codegen.py can use a Rooted - * interchangeably with a MutableHandleValue. - */ - void set(const T& value) { - ptr = value; - } - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(Rooted, T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr); - - private: - /* - * These need to be templated on void* to avoid aliasing issues between, for - * example, Rooted and Rooted, which use the same - * stack head pointer for different classes. - */ - Rooted** stack; - Rooted* prev; - - /* - * For pointer types, the TraceKind for tracing is based on the list it is - * in (selected via MapTypeToRootKind), so no additional storage is - * required here. Non-pointer types, however, share the same list, so the - * function to call for tracing is stored adjacent to the struct. Since C++ - * cannot templatize on storage class, this is implemented via the wrapper - * class DispatchWrapper. - */ - using MaybeWrapped = typename mozilla::Conditional< - MapTypeToRootKind::kind == JS::RootKind::Traceable, - js::DispatchWrapper, - T>::Type; - MaybeWrapped ptr; - - Rooted(const Rooted&) = delete; -} JS_HAZ_ROOTED; - -} /* namespace JS */ - -namespace js { - -/** - * Augment the generic Rooted interface when T = JSObject* with - * class-querying and downcasting operations. - * - * Given a Rooted obj, one can view - * Handle h = obj.as(); - * as an optimization of - * Rooted rooted(cx, &obj->as()); - * Handle h = rooted; - */ -template <> -class RootedBase -{ - public: - template - JS::Handle as() const; -}; - -/** - * Augment the generic Handle interface when T = JSObject* with - * downcasting operations. - * - * Given a Handle obj, one can view - * Handle h = obj.as(); - * as an optimization of - * Rooted rooted(cx, &obj->as()); - * Handle h = rooted; - */ -template <> -class HandleBase -{ - public: - template - JS::Handle as() const; -}; - -/** Interface substitute for Rooted which does not root the variable's memory. */ -template -class MOZ_RAII FakeRooted : public RootedBase -{ - public: - template - explicit FakeRooted(CX* cx) : ptr(JS::GCPolicy::initial()) {} - - template - FakeRooted(CX* cx, T initial) : ptr(initial) {} - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(FakeRooted, T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr); - - private: - T ptr; - - void set(const T& value) { - ptr = value; - } - - FakeRooted(const FakeRooted&) = delete; -}; - -/** Interface substitute for MutableHandle which is not required to point to rooted memory. */ -template -class FakeMutableHandle : public js::MutableHandleBase -{ - public: - MOZ_IMPLICIT FakeMutableHandle(T* t) { - ptr = t; - } - - MOZ_IMPLICIT FakeMutableHandle(FakeRooted* root) { - ptr = root->address(); - } - - void set(const T& v) { - *ptr = v; - } - - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(*ptr); - - private: - FakeMutableHandle() {} - DELETE_ASSIGNMENT_OPS(FakeMutableHandle, T); - - T* ptr; -}; - -/** - * Types for a variable that either should or shouldn't be rooted, depending on - * the template parameter allowGC. Used for implementing functions that can - * operate on either rooted or unrooted data. - * - * The toHandle() and toMutableHandle() functions are for calling functions - * which require handle types and are only called in the CanGC case. These - * allow the calling code to type check. - */ -enum AllowGC { - NoGC = 0, - CanGC = 1 -}; -template -class MaybeRooted -{ -}; - -template class MaybeRooted -{ - public: - typedef JS::Handle HandleType; - typedef JS::Rooted RootType; - typedef JS::MutableHandle MutableHandleType; - - static inline JS::Handle toHandle(HandleType v) { - return v; - } - - static inline JS::MutableHandle toMutableHandle(MutableHandleType v) { - return v; - } - - template - static inline JS::Handle downcastHandle(HandleType v) { - return v.template as(); - } -}; - -template class MaybeRooted -{ - public: - typedef const T& HandleType; - typedef FakeRooted RootType; - typedef FakeMutableHandle MutableHandleType; - - static JS::Handle toHandle(HandleType v) { - MOZ_CRASH("Bad conversion"); - } - - static JS::MutableHandle toMutableHandle(MutableHandleType v) { - MOZ_CRASH("Bad conversion"); - } - - template - static inline T2* downcastHandle(HandleType v) { - return &v->template as(); - } -}; - -} /* namespace js */ - -namespace JS { - -template template -inline -Handle::Handle(const Rooted& root, - typename mozilla::EnableIf::value, int>::Type dummy) -{ - ptr = reinterpret_cast(root.address()); -} - -template template -inline -Handle::Handle(const PersistentRooted& root, - typename mozilla::EnableIf::value, int>::Type dummy) -{ - ptr = reinterpret_cast(root.address()); -} - -template template -inline -Handle::Handle(MutableHandle& root, - typename mozilla::EnableIf::value, int>::Type dummy) -{ - ptr = reinterpret_cast(root.address()); -} - -template -inline -MutableHandle::MutableHandle(Rooted* root) -{ - static_assert(sizeof(MutableHandle) == sizeof(T*), - "MutableHandle must be binary compatible with T*."); - ptr = root->address(); -} - -template -inline -MutableHandle::MutableHandle(PersistentRooted* root) -{ - static_assert(sizeof(MutableHandle) == sizeof(T*), - "MutableHandle must be binary compatible with T*."); - ptr = root->address(); -} - -/** - * A copyable, assignable global GC root type with arbitrary lifetime, an - * infallible constructor, and automatic unrooting on destruction. - * - * These roots can be used in heap-allocated data structures, so they are not - * associated with any particular JSContext or stack. They are registered with - * the JSRuntime itself, without locking, so they require a full JSContext to be - * initialized, not one of its more restricted superclasses. Initialization may - * take place on construction, or in two phases if the no-argument constructor - * is called followed by init(). - * - * Note that you must not use an PersistentRooted in an object owned by a JS - * object: - * - * Whenever one object whose lifetime is decided by the GC refers to another - * such object, that edge must be traced only if the owning JS object is traced. - * This applies not only to JS objects (which obviously are managed by the GC) - * but also to C++ objects owned by JS objects. - * - * If you put a PersistentRooted in such a C++ object, that is almost certainly - * a leak. When a GC begins, the referent of the PersistentRooted is treated as - * live, unconditionally (because a PersistentRooted is a *root*), even if the - * JS object that owns it is unreachable. If there is any path from that - * referent back to the JS object, then the C++ object containing the - * PersistentRooted will not be destructed, and the whole blob of objects will - * not be freed, even if there are no references to them from the outside. - * - * In the context of Firefox, this is a severe restriction: almost everything in - * Firefox is owned by some JS object or another, so using PersistentRooted in - * such objects would introduce leaks. For these kinds of edges, Heap or - * TenuredHeap would be better types. It's up to the implementor of the type - * containing Heap or TenuredHeap members to make sure their referents get - * marked when the object itself is marked. - */ -template -class PersistentRooted : public js::PersistentRootedBase, - private mozilla::LinkedListElement> -{ - using ListBase = mozilla::LinkedListElement>; - - friend class mozilla::LinkedList; - friend class mozilla::LinkedListElement; - - void registerWithRootLists(js::RootLists& roots) { - MOZ_ASSERT(!initialized()); - JS::RootKind kind = JS::MapTypeToRootKind::kind; - roots.heapRoots_[kind].insertBack(reinterpret_cast*>(this)); - } - - js::RootLists& rootLists(JSContext* cx) { - return rootLists(JS::RootingContext::get(cx)); - } - js::RootLists& rootLists(JS::RootingContext* cx) { - MOZ_ASSERT(cx->isJSContext); - return cx->roots; - } - - // Disallow ExclusiveContext*. - js::RootLists& rootLists(js::ContextFriendFields* cx) = delete; - - public: - PersistentRooted() : ptr(GCPolicy::initial()) {} - - template - explicit PersistentRooted(const RootingContext& cx) - : ptr(GCPolicy::initial()) - { - registerWithRootLists(rootLists(cx)); - } - - template - PersistentRooted(const RootingContext& cx, U&& initial) - : ptr(mozilla::Forward(initial)) - { - registerWithRootLists(rootLists(cx)); - } - - PersistentRooted(const PersistentRooted& rhs) - : mozilla::LinkedListElement>(), - ptr(rhs.ptr) - { - /* - * Copy construction takes advantage of the fact that the original - * is already inserted, and simply adds itself to whatever list the - * original was on - no JSRuntime pointer needed. - * - * This requires mutating rhs's links, but those should be 'mutable' - * anyway. C++ doesn't let us declare mutable base classes. - */ - const_cast(rhs).setNext(this); - } - - bool initialized() { - return ListBase::isInList(); - } - - template - void init(const RootingContext& cx) { - init(cx, GCPolicy::initial()); - } - - template - void init(const RootingContext& cx, U&& initial) { - ptr = mozilla::Forward(initial); - registerWithRootLists(rootLists(cx)); - } - - void reset() { - if (initialized()) { - set(GCPolicy::initial()); - ListBase::remove(); - } - } - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(PersistentRooted, T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr); - - // These are the same as DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS, except - // they check that |this| is initialized in case the caller later stores - // something in |ptr|. - T* address() { - MOZ_ASSERT(initialized()); - return &ptr; - } - T& get() { - MOZ_ASSERT(initialized()); - return ptr; - } - - private: - template - void set(U&& value) { - MOZ_ASSERT(initialized()); - ptr = mozilla::Forward(value); - } - - // See the comment above Rooted::ptr. - using MaybeWrapped = typename mozilla::Conditional< - MapTypeToRootKind::kind == JS::RootKind::Traceable, - js::DispatchWrapper, - T>::Type; - MaybeWrapped ptr; -} JS_HAZ_ROOTED; - -class JS_PUBLIC_API(ObjectPtr) -{ - Heap value; - - public: - ObjectPtr() : value(nullptr) {} - - explicit ObjectPtr(JSObject* obj) : value(obj) {} - - /* Always call finalize before the destructor. */ - ~ObjectPtr() { MOZ_ASSERT(!value); } - - void finalize(JSRuntime* rt); - void finalize(JSContext* cx); - - void init(JSObject* obj) { value = obj; } - - JSObject* get() const { return value; } - JSObject* unbarrieredGet() const { return value.unbarrieredGet(); } - - void writeBarrierPre(JSContext* cx) { - IncrementalObjectBarrier(value); - } - - void updateWeakPointerAfterGC(); - - ObjectPtr& operator=(JSObject* obj) { - IncrementalObjectBarrier(value); - value = obj; - return *this; - } - - void trace(JSTracer* trc, const char* name); - - JSObject& operator*() const { return *value; } - JSObject* operator->() const { return value; } - operator JSObject*() const { return value; } - - explicit operator bool() const { return value.unbarrieredGet(); } - explicit operator bool() { return value.unbarrieredGet(); } -}; - -} /* namespace JS */ - -namespace js { - -template -class UniquePtrOperations -{ - const UniquePtr& uniquePtr() const { return static_cast(this)->get(); } - - public: - explicit operator bool() const { return !!uniquePtr(); } -}; - -template -class MutableUniquePtrOperations : public UniquePtrOperations -{ - UniquePtr& uniquePtr() { return static_cast(this)->get(); } - - public: - MOZ_MUST_USE typename UniquePtr::Pointer release() { return uniquePtr().release(); } -}; - -template -class RootedBase> - : public MutableUniquePtrOperations>, T, D> -{ }; - -template -class MutableHandleBase> - : public MutableUniquePtrOperations>, T, D> -{ }; - -template -class HandleBase> - : public UniquePtrOperations>, T, D> -{ }; - -template -class PersistentRootedBase> - : public MutableUniquePtrOperations>, T, D> -{ }; - -namespace gc { - -template -void -CallTraceCallbackOnNonHeap(T* v, const TraceCallbacks& aCallbacks, const char* aName, void* aClosure) -{ - static_assert(sizeof(T) == sizeof(JS::Heap), "T and Heap must be compatible."); - MOZ_ASSERT(v); - mozilla::DebugOnly cell = BarrierMethods::asGCThingOrNull(*v); - MOZ_ASSERT(cell); - MOZ_ASSERT(!IsInsideNursery(cell)); - JS::Heap* asHeapT = reinterpret_cast*>(v); - aCallbacks.Trace(asHeapT, aName, aClosure); -} - -} /* namespace gc */ -} /* namespace js */ - -// mozilla::Swap uses a stack temporary, which prevents classes like Heap -// from being declared MOZ_HEAP_CLASS. -namespace mozilla { - -template -inline void -Swap(JS::Heap& aX, JS::Heap& aY) -{ - T tmp = aX; - aX = aY; - aY = tmp; -} - -template -inline void -Swap(JS::TenuredHeap& aX, JS::TenuredHeap& aY) -{ - T tmp = aX; - aX = aY; - aY = tmp; -} - -} /* namespace mozilla */ - -#undef DELETE_ASSIGNMENT_OPS - -#endif /* js_RootingAPI_h */ diff --git a/ios/include/spidermonkey/js/SliceBudget.h b/ios/include/spidermonkey/js/SliceBudget.h deleted file mode 100644 index 78982df0..00000000 --- a/ios/include/spidermonkey/js/SliceBudget.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_SliceBudget_h -#define js_SliceBudget_h - -#include - -namespace js { - -struct JS_PUBLIC_API(TimeBudget) -{ - int64_t budget; - - explicit TimeBudget(int64_t milliseconds) { budget = milliseconds; } -}; - -struct JS_PUBLIC_API(WorkBudget) -{ - int64_t budget; - - explicit WorkBudget(int64_t work) { budget = work; } -}; - -/* - * This class records how much work has been done in a given collection slice, - * so that we can return before pausing for too long. Some slices are allowed - * to run for unlimited time, and others are bounded. To reduce the number of - * gettimeofday calls, we only check the time every 1000 operations. - */ -class JS_PUBLIC_API(SliceBudget) -{ - static const int64_t unlimitedDeadline = INT64_MAX; - static const intptr_t unlimitedStartCounter = INTPTR_MAX; - - bool checkOverBudget(); - - SliceBudget(); - - public: - // Memory of the originally requested budget. If isUnlimited, neither of - // these are in use. If deadline==0, then workBudget is valid. Otherwise - // timeBudget is valid. - TimeBudget timeBudget; - WorkBudget workBudget; - - int64_t deadline; /* in microseconds */ - intptr_t counter; - - static const intptr_t CounterReset = 1000; - - static const int64_t UnlimitedTimeBudget = -1; - static const int64_t UnlimitedWorkBudget = -1; - - /* Use to create an unlimited budget. */ - static SliceBudget unlimited() { return SliceBudget(); } - - /* Instantiate as SliceBudget(TimeBudget(n)). */ - explicit SliceBudget(TimeBudget time); - - /* Instantiate as SliceBudget(WorkBudget(n)). */ - explicit SliceBudget(WorkBudget work); - - void makeUnlimited() { - deadline = unlimitedDeadline; - counter = unlimitedStartCounter; - } - - void step(intptr_t amt = 1) { - counter -= amt; - } - - bool isOverBudget() { - if (counter > 0) - return false; - return checkOverBudget(); - } - - bool isWorkBudget() const { return deadline == 0; } - bool isTimeBudget() const { return deadline > 0 && !isUnlimited(); } - bool isUnlimited() const { return deadline == unlimitedDeadline; } - - int describe(char* buffer, size_t maxlen) const; -}; - -} // namespace js - -#endif /* js_SliceBudget_h */ diff --git a/ios/include/spidermonkey/js/StructuredClone.h b/ios/include/spidermonkey/js/StructuredClone.h deleted file mode 100644 index e10a3073..00000000 --- a/ios/include/spidermonkey/js/StructuredClone.h +++ /dev/null @@ -1,358 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_StructuredClone_h -#define js_StructuredClone_h - -#include "mozilla/Attributes.h" -#include "mozilla/BufferList.h" - -#include - -#include "jstypes.h" - -#include "js/RootingAPI.h" -#include "js/TypeDecls.h" -#include "js/Value.h" - -struct JSRuntime; -struct JSStructuredCloneReader; -struct JSStructuredCloneWriter; - -// API for the HTML5 internal structured cloning algorithm. - -namespace JS { - -enum class StructuredCloneScope : uint32_t { - SameProcessSameThread, - SameProcessDifferentThread, - DifferentProcess -}; - -enum TransferableOwnership { - /** Transferable data has not been filled in yet */ - SCTAG_TMO_UNFILLED = 0, - - /** Structured clone buffer does not yet own the data */ - SCTAG_TMO_UNOWNED = 1, - - /** All values at least this large are owned by the clone buffer */ - SCTAG_TMO_FIRST_OWNED = 2, - - /** Data is a pointer that can be freed */ - SCTAG_TMO_ALLOC_DATA = 2, - - /** Data is a memory mapped pointer */ - SCTAG_TMO_MAPPED_DATA = 3, - - /** - * Data is embedding-specific. The engine can free it by calling the - * freeTransfer op. The embedding can also use SCTAG_TMO_USER_MIN and - * greater, up to 32 bits, to distinguish specific ownership variants. - */ - SCTAG_TMO_CUSTOM = 4, - - SCTAG_TMO_USER_MIN -}; - -class CloneDataPolicy -{ - bool sharedArrayBuffer_; - - public: - // The default is to allow all policy-controlled aspects. - - CloneDataPolicy() : - sharedArrayBuffer_(true) - {} - - // In the JS engine, SharedArrayBuffers can only be cloned intra-process - // because the shared memory areas are allocated in process-private memory. - // Clients should therefore deny SharedArrayBuffers when cloning data that - // are to be transmitted inter-process. - // - // Clients should also deny SharedArrayBuffers when cloning data that are to - // be transmitted intra-process if policy needs dictate such denial. - - CloneDataPolicy& denySharedArrayBuffer() { - sharedArrayBuffer_ = false; - return *this; - } - - bool isSharedArrayBufferAllowed() const { - return sharedArrayBuffer_; - } -}; - -} /* namespace JS */ - -/** - * Read structured data from the reader r. This hook is used to read a value - * previously serialized by a call to the WriteStructuredCloneOp hook. - * - * tag and data are the pair of uint32_t values from the header. The callback - * may use the JS_Read* APIs to read any other relevant parts of the object - * from the reader r. closure is any value passed to the JS_ReadStructuredClone - * function. Return the new object on success, nullptr on error/exception. - */ -typedef JSObject* (*ReadStructuredCloneOp)(JSContext* cx, JSStructuredCloneReader* r, - uint32_t tag, uint32_t data, void* closure); - -/** - * Structured data serialization hook. The engine can write primitive values, - * Objects, Arrays, Dates, RegExps, TypedArrays, ArrayBuffers, Sets, Maps, - * and SharedTypedArrays. Any other type of object requires application support. - * This callback must first use the JS_WriteUint32Pair API to write an object - * header, passing a value greater than JS_SCTAG_USER to the tag parameter. - * Then it can use the JS_Write* APIs to write any other relevant parts of - * the value v to the writer w. closure is any value passed to the - * JS_WriteStructuredClone function. - * - * Return true on success, false on error/exception. - */ -typedef bool (*WriteStructuredCloneOp)(JSContext* cx, JSStructuredCloneWriter* w, - JS::HandleObject obj, void* closure); - -/** - * This is called when JS_WriteStructuredClone is given an invalid transferable. - * To follow HTML5, the application must throw a DATA_CLONE_ERR DOMException - * with error set to one of the JS_SCERR_* values. - */ -typedef void (*StructuredCloneErrorOp)(JSContext* cx, uint32_t errorid); - -/** - * This is called when JS_ReadStructuredClone receives a transferable object - * not known to the engine. If this hook does not exist or returns false, the - * JS engine calls the reportError op if set, otherwise it throws a - * DATA_CLONE_ERR DOM Exception. This method is called before any other - * callback and must return a non-null object in returnObject on success. - */ -typedef bool (*ReadTransferStructuredCloneOp)(JSContext* cx, JSStructuredCloneReader* r, - uint32_t tag, void* content, uint64_t extraData, - void* closure, - JS::MutableHandleObject returnObject); - -/** - * Called when JS_WriteStructuredClone receives a transferable object not - * handled by the engine. If this hook does not exist or returns false, the JS - * engine will call the reportError hook or fall back to throwing a - * DATA_CLONE_ERR DOM Exception. This method is called before any other - * callback. - * - * tag: indicates what type of transferable this is. Must be greater than - * 0xFFFF0201 (value of the internal SCTAG_TRANSFER_MAP_PENDING_ENTRY) - * - * ownership: see TransferableOwnership, above. Used to communicate any needed - * ownership info to the FreeTransferStructuredCloneOp. - * - * content, extraData: what the ReadTransferStructuredCloneOp will receive - */ -typedef bool (*TransferStructuredCloneOp)(JSContext* cx, - JS::Handle obj, - void* closure, - // Output: - uint32_t* tag, - JS::TransferableOwnership* ownership, - void** content, - uint64_t* extraData); - -/** - * Called when freeing an unknown transferable object. Note that it - * should never trigger a garbage collection (and will assert in a - * debug build if it does.) - */ -typedef void (*FreeTransferStructuredCloneOp)(uint32_t tag, JS::TransferableOwnership ownership, - void* content, uint64_t extraData, void* closure); - -// The maximum supported structured-clone serialization format version. -// Increment this when anything at all changes in the serialization format. -// (Note that this does not need to be bumped for Transferable-only changes, -// since they are never saved to persistent storage.) -#define JS_STRUCTURED_CLONE_VERSION 8 - -struct JSStructuredCloneCallbacks { - ReadStructuredCloneOp read; - WriteStructuredCloneOp write; - StructuredCloneErrorOp reportError; - ReadTransferStructuredCloneOp readTransfer; - TransferStructuredCloneOp writeTransfer; - FreeTransferStructuredCloneOp freeTransfer; -}; - -enum OwnTransferablePolicy { - OwnsTransferablesIfAny, - IgnoreTransferablesIfAny, - NoTransferables -}; - -class MOZ_NON_MEMMOVABLE JSStructuredCloneData : public mozilla::BufferList -{ - typedef js::SystemAllocPolicy AllocPolicy; - typedef mozilla::BufferList BufferList; - - static const size_t kInitialSize = 0; - static const size_t kInitialCapacity = 4096; - static const size_t kStandardCapacity = 4096; - - const JSStructuredCloneCallbacks* callbacks_; - void* closure_; - OwnTransferablePolicy ownTransferables_; - - void setOptionalCallbacks(const JSStructuredCloneCallbacks* callbacks, - void* closure, - OwnTransferablePolicy policy) { - callbacks_ = callbacks; - closure_ = closure; - ownTransferables_ = policy; - } - - friend struct JSStructuredCloneWriter; - friend class JS_PUBLIC_API(JSAutoStructuredCloneBuffer); - -public: - explicit JSStructuredCloneData(AllocPolicy aAP = AllocPolicy()) - : BufferList(kInitialSize, kInitialCapacity, kStandardCapacity, aAP) - , callbacks_(nullptr) - , closure_(nullptr) - , ownTransferables_(OwnTransferablePolicy::NoTransferables) - {} - MOZ_IMPLICIT JSStructuredCloneData(BufferList&& buffers) - : BufferList(Move(buffers)) - , callbacks_(nullptr) - , closure_(nullptr) - , ownTransferables_(OwnTransferablePolicy::NoTransferables) - {} - JSStructuredCloneData(JSStructuredCloneData&& other) = default; - JSStructuredCloneData& operator=(JSStructuredCloneData&& other) = default; - ~JSStructuredCloneData(); - - using BufferList::BufferList; -}; - -/** Note: if the *data contains transferable objects, it can be read only once. */ -JS_PUBLIC_API(bool) -JS_ReadStructuredClone(JSContext* cx, JSStructuredCloneData& data, uint32_t version, - JS::StructuredCloneScope scope, - JS::MutableHandleValue vp, - const JSStructuredCloneCallbacks* optionalCallbacks, void* closure); - -JS_PUBLIC_API(bool) -JS_WriteStructuredClone(JSContext* cx, JS::HandleValue v, JSStructuredCloneData* data, - JS::StructuredCloneScope scope, - JS::CloneDataPolicy cloneDataPolicy, - const JSStructuredCloneCallbacks* optionalCallbacks, - void* closure, JS::HandleValue transferable); - -JS_PUBLIC_API(bool) -JS_StructuredCloneHasTransferables(JSStructuredCloneData& data, bool* hasTransferable); - -JS_PUBLIC_API(bool) -JS_StructuredClone(JSContext* cx, JS::HandleValue v, JS::MutableHandleValue vp, - const JSStructuredCloneCallbacks* optionalCallbacks, void* closure); - -/** RAII sugar for JS_WriteStructuredClone. */ -class JS_PUBLIC_API(JSAutoStructuredCloneBuffer) { - const JS::StructuredCloneScope scope_; - JSStructuredCloneData data_; - uint32_t version_; - - public: - JSAutoStructuredCloneBuffer(JS::StructuredCloneScope scope, - const JSStructuredCloneCallbacks* callbacks, void* closure) - : scope_(scope), version_(JS_STRUCTURED_CLONE_VERSION) - { - data_.setOptionalCallbacks(callbacks, closure, OwnTransferablePolicy::NoTransferables); - } - - JSAutoStructuredCloneBuffer(JSAutoStructuredCloneBuffer&& other); - JSAutoStructuredCloneBuffer& operator=(JSAutoStructuredCloneBuffer&& other); - - ~JSAutoStructuredCloneBuffer() { clear(); } - - JSStructuredCloneData& data() { return data_; } - bool empty() const { return !data_.Size(); } - - void clear(const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - /** Copy some memory. It will be automatically freed by the destructor. */ - bool copy(const JSStructuredCloneData& data, uint32_t version=JS_STRUCTURED_CLONE_VERSION, - const JSStructuredCloneCallbacks* callbacks=nullptr, void* closure=nullptr); - - /** - * Adopt some memory. It will be automatically freed by the destructor. - * data must have been allocated by the JS engine (e.g., extracted via - * JSAutoStructuredCloneBuffer::steal). - */ - void adopt(JSStructuredCloneData&& data, uint32_t version=JS_STRUCTURED_CLONE_VERSION, - const JSStructuredCloneCallbacks* callbacks=nullptr, void* closure=nullptr); - - /** - * Release the buffer and transfer ownership to the caller. - */ - void steal(JSStructuredCloneData* data, uint32_t* versionp=nullptr, - const JSStructuredCloneCallbacks** callbacks=nullptr, void** closure=nullptr); - - /** - * Abandon ownership of any transferable objects stored in the buffer, - * without freeing the buffer itself. Useful when copying the data out into - * an external container, though note that you will need to use adopt() to - * properly release that data eventually. - */ - void abandon() { data_.ownTransferables_ = OwnTransferablePolicy::IgnoreTransferablesIfAny; } - - bool read(JSContext* cx, JS::MutableHandleValue vp, - const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - bool write(JSContext* cx, JS::HandleValue v, - const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - bool write(JSContext* cx, JS::HandleValue v, JS::HandleValue transferable, - JS::CloneDataPolicy cloneDataPolicy, - const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - private: - // Copy and assignment are not supported. - JSAutoStructuredCloneBuffer(const JSAutoStructuredCloneBuffer& other) = delete; - JSAutoStructuredCloneBuffer& operator=(const JSAutoStructuredCloneBuffer& other) = delete; -}; - -// The range of tag values the application may use for its own custom object types. -#define JS_SCTAG_USER_MIN ((uint32_t) 0xFFFF8000) -#define JS_SCTAG_USER_MAX ((uint32_t) 0xFFFFFFFF) - -#define JS_SCERR_RECURSION 0 -#define JS_SCERR_TRANSFERABLE 1 -#define JS_SCERR_DUP_TRANSFERABLE 2 -#define JS_SCERR_UNSUPPORTED_TYPE 3 - -JS_PUBLIC_API(bool) -JS_ReadUint32Pair(JSStructuredCloneReader* r, uint32_t* p1, uint32_t* p2); - -JS_PUBLIC_API(bool) -JS_ReadBytes(JSStructuredCloneReader* r, void* p, size_t len); - -JS_PUBLIC_API(bool) -JS_ReadTypedArray(JSStructuredCloneReader* r, JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_WriteUint32Pair(JSStructuredCloneWriter* w, uint32_t tag, uint32_t data); - -JS_PUBLIC_API(bool) -JS_WriteBytes(JSStructuredCloneWriter* w, const void* p, size_t len); - -JS_PUBLIC_API(bool) -JS_WriteString(JSStructuredCloneWriter* w, JS::HandleString str); - -JS_PUBLIC_API(bool) -JS_WriteTypedArray(JSStructuredCloneWriter* w, JS::HandleValue v); - -JS_PUBLIC_API(bool) -JS_ObjectNotWritten(JSStructuredCloneWriter* w, JS::HandleObject obj); - -JS_PUBLIC_API(JS::StructuredCloneScope) -JS_GetStructuredCloneScope(JSStructuredCloneWriter* w); - -#endif /* js_StructuredClone_h */ diff --git a/ios/include/spidermonkey/js/SweepingAPI.h b/ios/include/spidermonkey/js/SweepingAPI.h deleted file mode 100644 index 0eb29ae4..00000000 --- a/ios/include/spidermonkey/js/SweepingAPI.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_SweepingAPI_h -#define js_SweepingAPI_h - -#include "js/HeapAPI.h" - -namespace js { -template -class WeakCacheBase {}; -} // namespace js - -namespace JS { -template class WeakCache; - -namespace shadow { -JS_PUBLIC_API(void) -RegisterWeakCache(JS::Zone* zone, JS::WeakCache* cachep); -} // namespace shadow - -// A WeakCache stores the given Sweepable container and links itself into a -// list of such caches that are swept during each GC. -template -class WeakCache : public js::WeakCacheBase, - private mozilla::LinkedListElement> -{ - friend class mozilla::LinkedListElement>; - friend class mozilla::LinkedList>; - - WeakCache() = delete; - WeakCache(const WeakCache&) = delete; - - using SweepFn = void (*)(T*); - SweepFn sweeper; - T cache; - - public: - using Type = T; - - template - WeakCache(Zone* zone, U&& initial) - : cache(mozilla::Forward(initial)) - { - sweeper = GCPolicy::sweep; - shadow::RegisterWeakCache(zone, reinterpret_cast*>(this)); - } - WeakCache(WeakCache&& other) - : sweeper(other.sweeper), - cache(mozilla::Move(other.cache)) - { - } - - const T& get() const { return cache; } - T& get() { return cache; } - - void sweep() { sweeper(&cache); } -}; - -} // namespace JS - -#endif // js_SweepingAPI_h diff --git a/ios/include/spidermonkey/js/TraceKind.h b/ios/include/spidermonkey/js/TraceKind.h deleted file mode 100644 index 2eda9cb2..00000000 --- a/ios/include/spidermonkey/js/TraceKind.h +++ /dev/null @@ -1,212 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_TraceKind_h -#define js_TraceKind_h - -#include "mozilla/UniquePtr.h" - -#include "js/TypeDecls.h" - -// Forward declarations of all the types a TraceKind can denote. -namespace js { -class BaseShape; -class LazyScript; -class ObjectGroup; -class Shape; -class Scope; -namespace jit { -class JitCode; -} // namespace jit -} // namespace js - -namespace JS { - -// When tracing a thing, the GC needs to know about the layout of the object it -// is looking at. There are a fixed number of different layouts that the GC -// knows about. The "trace kind" is a static map which tells which layout a GC -// thing has. -// -// Although this map is public, the details are completely hidden. Not all of -// the matching C++ types are exposed, and those that are, are opaque. -// -// See Value::gcKind() and JSTraceCallback in Tracer.h for more details. -enum class TraceKind -{ - // These trace kinds have a publicly exposed, although opaque, C++ type. - // Note: The order here is determined by our Value packing. Other users - // should sort alphabetically, for consistency. - Object = 0x00, - String = 0x01, - Symbol = 0x02, - Script = 0x03, - - // Shape details are exposed through JS_TraceShapeCycleCollectorChildren. - Shape = 0x04, - - // ObjectGroup details are exposed through JS_TraceObjectGroupCycleCollectorChildren. - ObjectGroup = 0x05, - - // The kind associated with a nullptr. - Null = 0x06, - - // The following kinds do not have an exposed C++ idiom. - BaseShape = 0x0F, - JitCode = 0x1F, - LazyScript = 0x2F, - Scope = 0x3F -}; -const static uintptr_t OutOfLineTraceKindMask = 0x07; -static_assert(uintptr_t(JS::TraceKind::BaseShape) & OutOfLineTraceKindMask, "mask bits are set"); -static_assert(uintptr_t(JS::TraceKind::JitCode) & OutOfLineTraceKindMask, "mask bits are set"); -static_assert(uintptr_t(JS::TraceKind::LazyScript) & OutOfLineTraceKindMask, "mask bits are set"); -static_assert(uintptr_t(JS::TraceKind::Scope) & OutOfLineTraceKindMask, "mask bits are set"); - -// When this header is imported inside SpiderMonkey, the class definitions are -// available and we can query those definitions to find the correct kind -// directly from the class hierarchy. -template -struct MapTypeToTraceKind { - static const JS::TraceKind kind = T::TraceKind; -}; - -// When this header is used outside SpiderMonkey, the class definitions are not -// available, so the following table containing all public GC types is used. -#define JS_FOR_EACH_TRACEKIND(D) \ - /* PrettyName TypeName AddToCCKind */ \ - D(BaseShape, js::BaseShape, true) \ - D(JitCode, js::jit::JitCode, true) \ - D(LazyScript, js::LazyScript, true) \ - D(Scope, js::Scope, true) \ - D(Object, JSObject, true) \ - D(ObjectGroup, js::ObjectGroup, true) \ - D(Script, JSScript, true) \ - D(Shape, js::Shape, true) \ - D(String, JSString, false) \ - D(Symbol, JS::Symbol, false) - -// Map from all public types to their trace kind. -#define JS_EXPAND_DEF(name, type, _) \ - template <> struct MapTypeToTraceKind { \ - static const JS::TraceKind kind = JS::TraceKind::name; \ - }; -JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - -// RootKind is closely related to TraceKind. Whereas TraceKind's indices are -// laid out for convenient embedding as a pointer tag, the indicies of RootKind -// are designed for use as array keys via EnumeratedArray. -enum class RootKind : int8_t -{ - // These map 1:1 with trace kinds. -#define EXPAND_ROOT_KIND(name, _0, _1) \ - name, -JS_FOR_EACH_TRACEKIND(EXPAND_ROOT_KIND) -#undef EXPAND_ROOT_KIND - - // These tagged pointers are special-cased for performance. - Id, - Value, - - // Everything else. - Traceable, - - Limit -}; - -// Most RootKind correspond directly to a trace kind. -template struct MapTraceKindToRootKind {}; -#define JS_EXPAND_DEF(name, _0, _1) \ - template <> struct MapTraceKindToRootKind { \ - static const JS::RootKind kind = JS::RootKind::name; \ - }; -JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF) -#undef JS_EXPAND_DEF - -// Specify the RootKind for all types. Value and jsid map to special cases; -// pointer types we can derive directly from the TraceKind; everything else -// should go in the Traceable list and use GCPolicy::trace for tracing. -template -struct MapTypeToRootKind { - static const JS::RootKind kind = JS::RootKind::Traceable; -}; -template -struct MapTypeToRootKind { - static const JS::RootKind kind = - JS::MapTraceKindToRootKind::kind>::kind; -}; -template -struct MapTypeToRootKind> { - static const JS::RootKind kind = JS::MapTypeToRootKind::kind; -}; -template <> struct MapTypeToRootKind { - static const JS::RootKind kind = JS::RootKind::Value; -}; -template <> struct MapTypeToRootKind { - static const JS::RootKind kind = JS::RootKind::Id; -}; -template <> struct MapTypeToRootKind : public MapTypeToRootKind {}; - -// Fortunately, few places in the system need to deal with fully abstract -// cells. In those places that do, we generally want to move to a layout -// templated function as soon as possible. This template wraps the upcast -// for that dispatch. -// -// Given a call: -// -// DispatchTraceKindTyped(f, thing, traceKind, ... args) -// -// Downcast the |void *thing| to the specific type designated by |traceKind|, -// and pass it to the functor |f| along with |... args|, forwarded. Pass the -// type designated by |traceKind| as the functor's template argument. The -// |thing| parameter is optional; without it, we simply pass through |... args|. - -// GCC and Clang require an explicit template declaration in front of the -// specialization of operator() because it is a dependent template. MSVC, on -// the other hand, gets very confused if we have a |template| token there. -// The clang-cl front end defines _MSC_VER, but still requires the explicit -// template declaration, so we must test for __clang__ here as well. -#if defined(_MSC_VER) && !defined(__clang__) -# define JS_DEPENDENT_TEMPLATE_HINT -#else -# define JS_DEPENDENT_TEMPLATE_HINT template -#endif -template -auto -DispatchTraceKindTyped(F f, JS::TraceKind traceKind, Args&&... args) - -> decltype(f. JS_DEPENDENT_TEMPLATE_HINT operator()(mozilla::Forward(args)...)) -{ - switch (traceKind) { -#define JS_EXPAND_DEF(name, type, _) \ - case JS::TraceKind::name: \ - return f. JS_DEPENDENT_TEMPLATE_HINT operator()(mozilla::Forward(args)...); - JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - default: - MOZ_CRASH("Invalid trace kind in DispatchTraceKindTyped."); - } -} -#undef JS_DEPENDENT_TEMPLATE_HINT - -template -auto -DispatchTraceKindTyped(F f, void* thing, JS::TraceKind traceKind, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - switch (traceKind) { -#define JS_EXPAND_DEF(name, type, _) \ - case JS::TraceKind::name: \ - return f(static_cast(thing), mozilla::Forward(args)...); - JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - default: - MOZ_CRASH("Invalid trace kind in DispatchTraceKindTyped."); - } -} - -} // namespace JS - -#endif // js_TraceKind_h diff --git a/ios/include/spidermonkey/js/TracingAPI.h b/ios/include/spidermonkey/js/TracingAPI.h deleted file mode 100644 index 37c69aca..00000000 --- a/ios/include/spidermonkey/js/TracingAPI.h +++ /dev/null @@ -1,403 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_TracingAPI_h -#define js_TracingAPI_h - -#include "jsalloc.h" - -#include "js/HashTable.h" -#include "js/HeapAPI.h" -#include "js/TraceKind.h" - -class JS_PUBLIC_API(JSTracer); - -namespace JS { -class JS_PUBLIC_API(CallbackTracer); -template class Heap; -template class TenuredHeap; - -/** Returns a static string equivalent of |kind|. */ -JS_FRIEND_API(const char*) -GCTraceKindToAscii(JS::TraceKind kind); - -} // namespace JS - -enum WeakMapTraceKind { - /** - * Do not trace into weak map keys or values during traversal. Users must - * handle weak maps manually. - */ - DoNotTraceWeakMaps, - - /** - * Do true ephemeron marking with a weak key lookup marking phase. This is - * the default for GCMarker. - */ - ExpandWeakMaps, - - /** - * Trace through to all values, irrespective of whether the keys are live - * or not. Used for non-marking tracers. - */ - TraceWeakMapValues, - - /** - * Trace through to all keys and values, irrespective of whether the keys - * are live or not. Used for non-marking tracers. - */ - TraceWeakMapKeysValues -}; - -class JS_PUBLIC_API(JSTracer) -{ - public: - // Return the runtime set on the tracer. - JSRuntime* runtime() const { return runtime_; } - - // Return the weak map tracing behavior currently set on this tracer. - WeakMapTraceKind weakMapAction() const { return weakMapAction_; } - - enum class TracerKindTag { - // Marking path: a tracer used only for marking liveness of cells, not - // for moving them. The kind will transition to WeakMarking after - // everything reachable by regular edges has been marked. - Marking, - - // Same as Marking, except we have now moved on to the "weak marking - // phase", in which every marked obj/script is immediately looked up to - // see if it is a weak map key (and therefore might require marking its - // weak map value). - WeakMarking, - - // A tracer that traverses the graph for the purposes of moving objects - // from the nursery to the tenured area. - Tenuring, - - // General-purpose traversal that invokes a callback on each cell. - // Traversing children is the responsibility of the callback. - Callback - }; - bool isMarkingTracer() const { return tag_ == TracerKindTag::Marking || tag_ == TracerKindTag::WeakMarking; } - bool isWeakMarkingTracer() const { return tag_ == TracerKindTag::WeakMarking; } - bool isTenuringTracer() const { return tag_ == TracerKindTag::Tenuring; } - bool isCallbackTracer() const { return tag_ == TracerKindTag::Callback; } - inline JS::CallbackTracer* asCallbackTracer(); -#ifdef DEBUG - bool checkEdges() { return checkEdges_; } -#endif - - protected: - JSTracer(JSRuntime* rt, TracerKindTag tag, - WeakMapTraceKind weakTraceKind = TraceWeakMapValues) - : runtime_(rt) - , weakMapAction_(weakTraceKind) -#ifdef DEBUG - , checkEdges_(true) -#endif - , tag_(tag) - {} - -#ifdef DEBUG - // Set whether to check edges are valid in debug builds. - void setCheckEdges(bool check) { - checkEdges_ = check; - } -#endif - - private: - JSRuntime* runtime_; - WeakMapTraceKind weakMapAction_; -#ifdef DEBUG - bool checkEdges_; -#endif - - protected: - TracerKindTag tag_; -}; - -namespace JS { - -class AutoTracingName; -class AutoTracingIndex; -class AutoTracingCallback; - -class JS_PUBLIC_API(CallbackTracer) : public JSTracer -{ - public: - CallbackTracer(JSRuntime* rt, WeakMapTraceKind weakTraceKind = TraceWeakMapValues) - : JSTracer(rt, JSTracer::TracerKindTag::Callback, weakTraceKind), - contextName_(nullptr), contextIndex_(InvalidIndex), contextFunctor_(nullptr) - {} - CallbackTracer(JSContext* cx, WeakMapTraceKind weakTraceKind = TraceWeakMapValues); - - // Override these methods to receive notification when an edge is visited - // with the type contained in the callback. The default implementation - // dispatches to the fully-generic onChild implementation, so for cases that - // do not care about boxing overhead and do not need the actual edges, - // just override the generic onChild. - virtual void onObjectEdge(JSObject** objp) { onChild(JS::GCCellPtr(*objp)); } - virtual void onStringEdge(JSString** strp) { onChild(JS::GCCellPtr(*strp)); } - virtual void onSymbolEdge(JS::Symbol** symp) { onChild(JS::GCCellPtr(*symp)); } - virtual void onScriptEdge(JSScript** scriptp) { onChild(JS::GCCellPtr(*scriptp)); } - virtual void onShapeEdge(js::Shape** shapep) { - onChild(JS::GCCellPtr(*shapep, JS::TraceKind::Shape)); - } - virtual void onObjectGroupEdge(js::ObjectGroup** groupp) { - onChild(JS::GCCellPtr(*groupp, JS::TraceKind::ObjectGroup)); - } - virtual void onBaseShapeEdge(js::BaseShape** basep) { - onChild(JS::GCCellPtr(*basep, JS::TraceKind::BaseShape)); - } - virtual void onJitCodeEdge(js::jit::JitCode** codep) { - onChild(JS::GCCellPtr(*codep, JS::TraceKind::JitCode)); - } - virtual void onLazyScriptEdge(js::LazyScript** lazyp) { - onChild(JS::GCCellPtr(*lazyp, JS::TraceKind::LazyScript)); - } - virtual void onScopeEdge(js::Scope** scopep) { - onChild(JS::GCCellPtr(*scopep, JS::TraceKind::Scope)); - } - - // Override this method to receive notification when a node in the GC - // heap graph is visited. - virtual void onChild(const JS::GCCellPtr& thing) = 0; - - // Access to the tracing context: - // When tracing with a JS::CallbackTracer, we invoke the callback with the - // edge location and the type of target. This is useful for operating on - // the edge in the abstract or on the target thing, satisfying most common - // use cases. However, some tracers need additional detail about the - // specific edge that is being traced in order to be useful. Unfortunately, - // the raw pointer to the edge that we provide is not enough information to - // infer much of anything useful about that edge. - // - // In order to better support use cases that care in particular about edges - // -- as opposed to the target thing -- tracing implementations are - // responsible for providing extra context information about each edge they - // trace, as it is traced. This contains, at a minimum, an edge name and, - // when tracing an array, the index. Further specialization can be achived - // (with some complexity), by associating a functor with the tracer so - // that, when requested, the user can generate totally custom edge - // descriptions. - - // Returns the current edge's name. It is only valid to call this when - // inside the trace callback, however, the edge name will always be set. - const char* contextName() const { MOZ_ASSERT(contextName_); return contextName_; } - - // Returns the current edge's index, if marked as part of an array of edges. - // This must be called only inside the trace callback. When not tracing an - // array, the value will be InvalidIndex. - const static size_t InvalidIndex = size_t(-1); - size_t contextIndex() const { return contextIndex_; } - - // Build a description of this edge in the heap graph. This call may invoke - // the context functor, if set, which may inspect arbitrary areas of the - // heap. On the other hand, the description provided by this method may be - // substantially more accurate and useful than those provided by only the - // contextName and contextIndex. - void getTracingEdgeName(char* buffer, size_t bufferSize); - - // The trace implementation may associate a callback with one or more edges - // using AutoTracingDetails. This functor is called by getTracingEdgeName - // and is responsible for providing a textual representation of the - // currently being traced edge. The callback has access to the full heap, - // including the currently set tracing context. - class ContextFunctor { - public: - virtual void operator()(CallbackTracer* trc, char* buf, size_t bufsize) = 0; - }; - -#ifdef DEBUG - enum class TracerKind { DoNotCare, Moving, GrayBuffering, VerifyTraceProtoAndIface }; - virtual TracerKind getTracerKind() const { return TracerKind::DoNotCare; } -#endif - - // In C++, overriding a method hides all methods in the base class with - // that name, not just methods with that signature. Thus, the typed edge - // methods have to have distinct names to allow us to override them - // individually, which is freqently useful if, for example, we only want to - // process only one type of edge. - void dispatchToOnEdge(JSObject** objp) { onObjectEdge(objp); } - void dispatchToOnEdge(JSString** strp) { onStringEdge(strp); } - void dispatchToOnEdge(JS::Symbol** symp) { onSymbolEdge(symp); } - void dispatchToOnEdge(JSScript** scriptp) { onScriptEdge(scriptp); } - void dispatchToOnEdge(js::Shape** shapep) { onShapeEdge(shapep); } - void dispatchToOnEdge(js::ObjectGroup** groupp) { onObjectGroupEdge(groupp); } - void dispatchToOnEdge(js::BaseShape** basep) { onBaseShapeEdge(basep); } - void dispatchToOnEdge(js::jit::JitCode** codep) { onJitCodeEdge(codep); } - void dispatchToOnEdge(js::LazyScript** lazyp) { onLazyScriptEdge(lazyp); } - void dispatchToOnEdge(js::Scope** scopep) { onScopeEdge(scopep); } - - private: - friend class AutoTracingName; - const char* contextName_; - - friend class AutoTracingIndex; - size_t contextIndex_; - - friend class AutoTracingDetails; - ContextFunctor* contextFunctor_; -}; - -// Set the name portion of the tracer's context for the current edge. -class MOZ_RAII AutoTracingName -{ - CallbackTracer* trc_; - const char* prior_; - - public: - AutoTracingName(CallbackTracer* trc, const char* name) : trc_(trc), prior_(trc->contextName_) { - MOZ_ASSERT(name); - trc->contextName_ = name; - } - ~AutoTracingName() { - MOZ_ASSERT(trc_->contextName_); - trc_->contextName_ = prior_; - } -}; - -// Set the index portion of the tracer's context for the current range. -class MOZ_RAII AutoTracingIndex -{ - CallbackTracer* trc_; - - public: - explicit AutoTracingIndex(JSTracer* trc, size_t initial = 0) : trc_(nullptr) { - if (trc->isCallbackTracer()) { - trc_ = trc->asCallbackTracer(); - MOZ_ASSERT(trc_->contextIndex_ == CallbackTracer::InvalidIndex); - trc_->contextIndex_ = initial; - } - } - ~AutoTracingIndex() { - if (trc_) { - MOZ_ASSERT(trc_->contextIndex_ != CallbackTracer::InvalidIndex); - trc_->contextIndex_ = CallbackTracer::InvalidIndex; - } - } - - void operator++() { - if (trc_) { - MOZ_ASSERT(trc_->contextIndex_ != CallbackTracer::InvalidIndex); - ++trc_->contextIndex_; - } - } -}; - -// Set a context callback for the trace callback to use, if it needs a detailed -// edge description. -class MOZ_RAII AutoTracingDetails -{ - CallbackTracer* trc_; - - public: - AutoTracingDetails(JSTracer* trc, CallbackTracer::ContextFunctor& func) : trc_(nullptr) { - if (trc->isCallbackTracer()) { - trc_ = trc->asCallbackTracer(); - MOZ_ASSERT(trc_->contextFunctor_ == nullptr); - trc_->contextFunctor_ = &func; - } - } - ~AutoTracingDetails() { - if (trc_) { - MOZ_ASSERT(trc_->contextFunctor_); - trc_->contextFunctor_ = nullptr; - } - } -}; - -} // namespace JS - -JS::CallbackTracer* -JSTracer::asCallbackTracer() -{ - MOZ_ASSERT(isCallbackTracer()); - return static_cast(this); -} - -namespace JS { - -// The JS::TraceEdge family of functions traces the given GC thing reference. -// This performs the tracing action configured on the given JSTracer: typically -// calling the JSTracer::callback or marking the thing as live. -// -// The argument to JS::TraceEdge is an in-out param: when the function returns, -// the garbage collector might have moved the GC thing. In this case, the -// reference passed to JS::TraceEdge will be updated to the thing's new -// location. Callers of this method are responsible for updating any state that -// is dependent on the object's address. For example, if the object's address -// is used as a key in a hashtable, then the object must be removed and -// re-inserted with the correct hash. -// -// Note that while |edgep| must never be null, it is fine for |*edgep| to be -// nullptr. -template -extern JS_PUBLIC_API(void) -TraceEdge(JSTracer* trc, JS::Heap* edgep, const char* name); - -extern JS_PUBLIC_API(void) -TraceEdge(JSTracer* trc, JS::TenuredHeap* edgep, const char* name); - -// Edges that are always traced as part of root marking do not require -// incremental barriers. This function allows for marking non-barriered -// pointers, but asserts that this happens during root marking. -// -// Note that while |edgep| must never be null, it is fine for |*edgep| to be -// nullptr. -template -extern JS_PUBLIC_API(void) -UnsafeTraceRoot(JSTracer* trc, T* edgep, const char* name); - -extern JS_PUBLIC_API(void) -TraceChildren(JSTracer* trc, GCCellPtr thing); - -using ZoneSet = js::HashSet, js::SystemAllocPolicy>; -using CompartmentSet = js::HashSet, - js::SystemAllocPolicy>; - -/** - * Trace every value within |compartments| that is wrapped by a - * cross-compartment wrapper from a compartment that is not an element of - * |compartments|. - */ -extern JS_PUBLIC_API(void) -TraceIncomingCCWs(JSTracer* trc, const JS::CompartmentSet& compartments); - -} // namespace JS - -extern JS_PUBLIC_API(void) -JS_GetTraceThingInfo(char* buf, size_t bufsize, JSTracer* trc, - void* thing, JS::TraceKind kind, bool includeDetails); - -namespace js { - -// Trace an edge that is not a GC root and is not wrapped in a barriered -// wrapper for some reason. -// -// This method does not check if |*edgep| is non-null before tracing through -// it, so callers must check any nullable pointer before calling this method. -template -extern JS_PUBLIC_API(void) -UnsafeTraceManuallyBarrieredEdge(JSTracer* trc, T* edgep, const char* name); - -namespace gc { - -// Return true if the given edge is not live and is about to be swept. -template -extern JS_PUBLIC_API(bool) -EdgeNeedsSweep(JS::Heap* edgep); - -// Not part of the public API, but declared here so we can use it in GCPolicy -// which is. -template -bool -IsAboutToBeFinalizedUnbarriered(T* thingp); - -} // namespace gc -} // namespace js - -#endif /* js_TracingAPI_h */ diff --git a/ios/include/spidermonkey/js/TrackedOptimizationInfo.h b/ios/include/spidermonkey/js/TrackedOptimizationInfo.h deleted file mode 100644 index b697765c..00000000 --- a/ios/include/spidermonkey/js/TrackedOptimizationInfo.h +++ /dev/null @@ -1,285 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_TrackedOptimizationInfo_h -#define js_TrackedOptimizationInfo_h - -#include "mozilla/Maybe.h" - -namespace JS { - -#define TRACKED_STRATEGY_LIST(_) \ - _(GetProp_ArgumentsLength) \ - _(GetProp_ArgumentsCallee) \ - _(GetProp_InferredConstant) \ - _(GetProp_Constant) \ - _(GetProp_NotDefined) \ - _(GetProp_StaticName) \ - _(GetProp_SimdGetter) \ - _(GetProp_TypedObject) \ - _(GetProp_DefiniteSlot) \ - _(GetProp_Unboxed) \ - _(GetProp_CommonGetter) \ - _(GetProp_InlineAccess) \ - _(GetProp_Innerize) \ - _(GetProp_InlineCache) \ - _(GetProp_SharedCache) \ - _(GetProp_ModuleNamespace) \ - \ - _(SetProp_CommonSetter) \ - _(SetProp_TypedObject) \ - _(SetProp_DefiniteSlot) \ - _(SetProp_Unboxed) \ - _(SetProp_InlineAccess) \ - _(SetProp_InlineCache) \ - \ - _(GetElem_TypedObject) \ - _(GetElem_Dense) \ - _(GetElem_TypedStatic) \ - _(GetElem_TypedArray) \ - _(GetElem_String) \ - _(GetElem_Arguments) \ - _(GetElem_ArgumentsInlined) \ - _(GetElem_InlineCache) \ - \ - _(SetElem_TypedObject) \ - _(SetElem_TypedStatic) \ - _(SetElem_TypedArray) \ - _(SetElem_Dense) \ - _(SetElem_Arguments) \ - _(SetElem_InlineCache) \ - \ - _(BinaryArith_Concat) \ - _(BinaryArith_SpecializedTypes) \ - _(BinaryArith_SpecializedOnBaselineTypes) \ - _(BinaryArith_SharedCache) \ - _(BinaryArith_Call) \ - \ - _(InlineCache_OptimizedStub) \ - \ - _(Call_Inline) - - -// Ordering is important below. All outcomes before GenericSuccess will be -// considered failures, and all outcomes after GenericSuccess will be -// considered successes. -#define TRACKED_OUTCOME_LIST(_) \ - _(GenericFailure) \ - _(Disabled) \ - _(NoTypeInfo) \ - _(NoAnalysisInfo) \ - _(NoShapeInfo) \ - _(UnknownObject) \ - _(UnknownProperties) \ - _(Singleton) \ - _(NotSingleton) \ - _(NotFixedSlot) \ - _(InconsistentFixedSlot) \ - _(NotObject) \ - _(NotStruct) \ - _(NotUnboxed) \ - _(NotUndefined) \ - _(UnboxedConvertedToNative) \ - _(StructNoField) \ - _(InconsistentFieldType) \ - _(InconsistentFieldOffset) \ - _(NeedsTypeBarrier) \ - _(InDictionaryMode) \ - _(NoProtoFound) \ - _(MultiProtoPaths) \ - _(NonWritableProperty) \ - _(ProtoIndexedProps) \ - _(ArrayBadFlags) \ - _(ArrayDoubleConversion) \ - _(ArrayRange) \ - _(ArraySeenNegativeIndex) \ - _(TypedObjectHasDetachedBuffer) \ - _(TypedObjectArrayRange) \ - _(AccessNotDense) \ - _(AccessNotSimdObject) \ - _(AccessNotTypedObject) \ - _(AccessNotTypedArray) \ - _(AccessNotString) \ - _(OperandNotString) \ - _(OperandNotNumber) \ - _(OperandNotStringOrNumber) \ - _(OperandNotSimpleArith) \ - _(StaticTypedArrayUint32) \ - _(StaticTypedArrayCantComputeMask) \ - _(OutOfBounds) \ - _(GetElemStringNotCached) \ - _(NonNativeReceiver) \ - _(IndexType) \ - _(SetElemNonDenseNonTANotCached) \ - _(NoSimdJitSupport) \ - _(SimdTypeNotOptimized) \ - _(UnknownSimdProperty) \ - _(NotModuleNamespace) \ - _(UnknownProperty) \ - \ - _(ICOptStub_GenericSuccess) \ - \ - _(ICGetPropStub_ReadSlot) \ - _(ICGetPropStub_CallGetter) \ - _(ICGetPropStub_ArrayLength) \ - _(ICGetPropStub_UnboxedRead) \ - _(ICGetPropStub_UnboxedReadExpando) \ - _(ICGetPropStub_UnboxedArrayLength) \ - _(ICGetPropStub_TypedArrayLength) \ - _(ICGetPropStub_DOMProxyShadowed) \ - _(ICGetPropStub_DOMProxyUnshadowed) \ - _(ICGetPropStub_GenericProxy) \ - _(ICGetPropStub_ArgumentsLength) \ - \ - _(ICSetPropStub_Slot) \ - _(ICSetPropStub_GenericProxy) \ - _(ICSetPropStub_DOMProxyShadowed) \ - _(ICSetPropStub_DOMProxyUnshadowed) \ - _(ICSetPropStub_CallSetter) \ - _(ICSetPropStub_AddSlot) \ - _(ICSetPropStub_SetUnboxed) \ - \ - _(ICGetElemStub_ReadSlot) \ - _(ICGetElemStub_CallGetter) \ - _(ICGetElemStub_ReadUnboxed) \ - _(ICGetElemStub_Dense) \ - _(ICGetElemStub_DenseHole) \ - _(ICGetElemStub_TypedArray) \ - _(ICGetElemStub_ArgsElementMapped) \ - _(ICGetElemStub_ArgsElementUnmapped) \ - \ - _(ICSetElemStub_Dense) \ - _(ICSetElemStub_TypedArray) \ - \ - _(ICNameStub_ReadSlot) \ - _(ICNameStub_CallGetter) \ - _(ICNameStub_TypeOfNoProperty) \ - \ - _(CantInlineGeneric) \ - _(CantInlineNoTarget) \ - _(CantInlineNotInterpreted) \ - _(CantInlineNoBaseline) \ - _(CantInlineLazy) \ - _(CantInlineNotConstructor) \ - _(CantInlineClassConstructor) \ - _(CantInlineDisabledIon) \ - _(CantInlineTooManyArgs) \ - _(CantInlineNeedsArgsObj) \ - _(CantInlineDebuggee) \ - _(CantInlineUnknownProps) \ - _(CantInlineExceededDepth) \ - _(CantInlineExceededTotalBytecodeLength) \ - _(CantInlineBigCaller) \ - _(CantInlineBigCallee) \ - _(CantInlineBigCalleeInlinedBytecodeLength) \ - _(CantInlineNotHot) \ - _(CantInlineNotInDispatch) \ - _(CantInlineUnreachable) \ - _(CantInlineNativeBadForm) \ - _(CantInlineNativeBadType) \ - _(CantInlineNativeNoTemplateObj) \ - _(CantInlineBound) \ - _(CantInlineNativeNoSpecialization) \ - _(HasCommonInliningPath) \ - \ - _(GenericSuccess) \ - _(Inlined) \ - _(DOM) \ - _(Monomorphic) \ - _(Polymorphic) - -#define TRACKED_TYPESITE_LIST(_) \ - _(Receiver) \ - _(Operand) \ - _(Index) \ - _(Value) \ - _(Call_Target) \ - _(Call_This) \ - _(Call_Arg) \ - _(Call_Return) - -enum class TrackedStrategy : uint32_t { -#define STRATEGY_OP(name) name, - TRACKED_STRATEGY_LIST(STRATEGY_OP) -#undef STRATEGY_OPT - - Count -}; - -enum class TrackedOutcome : uint32_t { -#define OUTCOME_OP(name) name, - TRACKED_OUTCOME_LIST(OUTCOME_OP) -#undef OUTCOME_OP - - Count -}; - -enum class TrackedTypeSite : uint32_t { -#define TYPESITE_OP(name) name, - TRACKED_TYPESITE_LIST(TYPESITE_OP) -#undef TYPESITE_OP - - Count -}; - -JS_PUBLIC_API(const char*) -TrackedStrategyString(TrackedStrategy strategy); - -JS_PUBLIC_API(const char*) -TrackedOutcomeString(TrackedOutcome outcome); - -JS_PUBLIC_API(const char*) -TrackedTypeSiteString(TrackedTypeSite site); - -struct ForEachTrackedOptimizationAttemptOp -{ - virtual void operator()(TrackedStrategy strategy, TrackedOutcome outcome) = 0; -}; - -struct ForEachTrackedOptimizationTypeInfoOp -{ - // Called 0+ times per entry, once for each type in the type set that Ion - // saw during MIR construction. readType is always called _before_ - // operator() on the same entry. - // - // The keyedBy parameter describes how the type is keyed: - // - "primitive" for primitive types - // - "constructor" for object types tied to a scripted constructor - // function. - // - "alloc site" for object types tied to an allocation site. - // - "prototype" for object types tied neither to a constructor nor - // to an allocation site, but to a prototype. - // - "singleton" for object types which only has a single value. - // - "function" for object types referring to scripted functions. - // - "native" for object types referring to native functions. - // - // The name parameter is the string representation of the type. If the - // type is keyed by "constructor", or if the type itself refers to a - // scripted function, the name is the function's displayAtom. If the type - // is keyed by "native", this is nullptr. - // - // The location parameter is the filename if the type is keyed by - // "constructor", "alloc site", or if the type itself refers to a scripted - // function. If the type is keyed by "native", it is the offset of the - // native function, suitable for use with addr2line on Linux or atos on OS - // X. Otherwise it is nullptr. - // - // The lineno parameter is the line number if the type is keyed by - // "constructor", "alloc site", or if the type itself refers to a scripted - // function. Otherwise it is Nothing(). - // - // The location parameter is the only one that may need escaping if being - // quoted. - virtual void readType(const char* keyedBy, const char* name, - const char* location, mozilla::Maybe lineno) = 0; - - // Called once per entry. - virtual void operator()(TrackedTypeSite site, const char* mirType) = 0; -}; - -} // namespace JS - -#endif // js_TrackedOptimizationInfo_h diff --git a/ios/include/spidermonkey/js/TypeDecls.h b/ios/include/spidermonkey/js/TypeDecls.h deleted file mode 100644 index acb93f97..00000000 --- a/ios/include/spidermonkey/js/TypeDecls.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// This file contains public type declarations that are used *frequently*. If -// it doesn't occur at least 10 times in Gecko, it probably shouldn't be in -// here. -// -// It includes only: -// - forward declarations of structs and classes; -// - typedefs; -// - enums (maybe). -// It does *not* contain any struct or class definitions. - -#ifndef js_TypeDecls_h -#define js_TypeDecls_h - -#include -#include - -#include "js-config.h" - -struct JSContext; -class JSFunction; -class JSObject; -class JSScript; -class JSString; -class JSAddonId; - -struct jsid; - -namespace JS { - -typedef unsigned char Latin1Char; - -class Symbol; -class Value; -template class Handle; -template class MutableHandle; -template class Rooted; -template class PersistentRooted; - -typedef Handle HandleFunction; -typedef Handle HandleId; -typedef Handle HandleObject; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleSymbol; -typedef Handle HandleValue; - -typedef MutableHandle MutableHandleFunction; -typedef MutableHandle MutableHandleId; -typedef MutableHandle MutableHandleObject; -typedef MutableHandle MutableHandleScript; -typedef MutableHandle MutableHandleString; -typedef MutableHandle MutableHandleSymbol; -typedef MutableHandle MutableHandleValue; - -typedef Rooted RootedObject; -typedef Rooted RootedFunction; -typedef Rooted RootedScript; -typedef Rooted RootedString; -typedef Rooted RootedSymbol; -typedef Rooted RootedId; -typedef Rooted RootedValue; - -typedef PersistentRooted PersistentRootedFunction; -typedef PersistentRooted PersistentRootedId; -typedef PersistentRooted PersistentRootedObject; -typedef PersistentRooted PersistentRootedScript; -typedef PersistentRooted PersistentRootedString; -typedef PersistentRooted PersistentRootedSymbol; -typedef PersistentRooted PersistentRootedValue; - -} // namespace JS - -#endif /* js_TypeDecls_h */ diff --git a/ios/include/spidermonkey/js/UbiNode.h b/ios/include/spidermonkey/js/UbiNode.h deleted file mode 100644 index c8742f33..00000000 --- a/ios/include/spidermonkey/js/UbiNode.h +++ /dev/null @@ -1,1144 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNode_h -#define js_UbiNode_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Maybe.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/RangedPtr.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Variant.h" - -#include "jspubtd.h" - -#include "js/GCAPI.h" -#include "js/HashTable.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" -#include "js/TypeDecls.h" -#include "js/UniquePtr.h" -#include "js/Value.h" -#include "js/Vector.h" - -// JS::ubi::Node -// -// JS::ubi::Node is a pointer-like type designed for internal use by heap -// analysis tools. A ubi::Node can refer to: -// -// - a JS value, like a string, object, or symbol; -// - an internal SpiderMonkey structure, like a shape or a scope chain object -// - an instance of some embedding-provided type: in Firefox, an XPCOM -// object, or an internal DOM node class instance -// -// A ubi::Node instance provides metadata about its referent, and can -// enumerate its referent's outgoing edges, so you can implement heap analysis -// algorithms that walk the graph - finding paths between objects, or -// computing heap dominator trees, say - using ubi::Node, while remaining -// ignorant of the details of the types you're operating on. -// -// Of course, when it comes to presenting the results in a developer-facing -// tool, you'll need to stop being ignorant of those details, because you have -// to discuss the ubi::Nodes' referents with the developer. Here, ubi::Node -// can hand you dynamically checked, properly typed pointers to the original -// objects via the as method, or generate descriptions of the referent -// itself. -// -// ubi::Node instances are lightweight (two-word) value types. Instances: -// - compare equal if and only if they refer to the same object; -// - have hash values that respect their equality relation; and -// - have serializations that are only equal if the ubi::Nodes are equal. -// -// A ubi::Node is only valid for as long as its referent is alive; if its -// referent goes away, the ubi::Node becomes a dangling pointer. A ubi::Node -// that refers to a GC-managed object is not automatically a GC root; if the -// GC frees or relocates its referent, the ubi::Node becomes invalid. A -// ubi::Node that refers to a reference-counted object does not bump the -// reference count. -// -// ubi::Node values require no supporting data structures, making them -// feasible for use in memory-constrained devices --- ideally, the memory -// requirements of the algorithm which uses them will be the limiting factor, -// not the demands of ubi::Node itself. -// -// One can construct a ubi::Node value given a pointer to a type that ubi::Node -// supports. In the other direction, one can convert a ubi::Node back to a -// pointer; these downcasts are checked dynamically. In particular, one can -// convert a 'JSContext*' to a ubi::Node, yielding a node with an outgoing edge -// for every root registered with the runtime; starting from this, one can walk -// the entire heap. (Of course, one could also start traversal at any other kind -// of type to which one has a pointer.) -// -// -// Extending ubi::Node To Handle Your Embedding's Types -// -// To add support for a new ubi::Node referent type R, you must define a -// specialization of the ubi::Concrete template, ubi::Concrete, which -// inherits from ubi::Base. ubi::Node itself uses the specialization for -// compile-time information (i.e. the checked conversions between R * and -// ubi::Node), and the inheritance for run-time dispatching. -// -// -// ubi::Node Exposes Implementation Details -// -// In many cases, a JavaScript developer's view of their data differs -// substantially from its actual implementation. For example, while the -// ECMAScript specification describes objects as maps from property names to -// sets of attributes (like ECMAScript's [[Value]]), in practice many objects -// have only a pointer to a shape, shared with other similar objects, and -// indexed slots that contain the [[Value]] attributes. As another example, a -// string produced by concatenating two other strings may sometimes be -// represented by a "rope", a structure that points to the two original -// strings. -// -// We intend to use ubi::Node to write tools that report memory usage, so it's -// important that ubi::Node accurately portray how much memory nodes consume. -// Thus, for example, when data that apparently belongs to multiple nodes is -// in fact shared in a common structure, ubi::Node's graph uses a separate -// node for that shared structure, and presents edges to it from the data's -// apparent owners. For example, ubi::Node exposes SpiderMonkey objects' -// shapes and base shapes, and exposes rope string and substring structure, -// because these optimizations become visible when a tool reports how much -// memory a structure consumes. -// -// However, fine granularity is not a goal. When a particular object is the -// exclusive owner of a separate block of memory, ubi::Node may present the -// object and its block as a single node, and add their sizes together when -// reporting the node's size, as there is no meaningful loss of data in this -// case. Thus, for example, a ubi::Node referring to a JavaScript object, when -// asked for the object's size in bytes, includes the object's slot and -// element arrays' sizes in the total. There is no separate ubi::Node value -// representing the slot and element arrays, since they are owned exclusively -// by the object. -// -// -// Presenting Analysis Results To JavaScript Developers -// -// If an analysis provides its results in terms of ubi::Node values, a user -// interface presenting those results will generally need to clean them up -// before they can be understood by JavaScript developers. For example, -// JavaScript developers should not need to understand shapes, only JavaScript -// objects. Similarly, they should not need to understand the distinction -// between DOM nodes and the JavaScript shadow objects that represent them. -// -// -// Rooting Restrictions -// -// At present there is no way to root ubi::Node instances, so instances can't be -// live across any operation that might GC. Analyses using ubi::Node must either -// run to completion and convert their results to some other rootable type, or -// save their intermediate state in some rooted structure if they must GC before -// they complete. (For algorithms like path-finding and dominator tree -// computation, we implement the algorithm avoiding any operation that could -// cause a GC --- and use AutoCheckCannotGC to verify this.) -// -// If this restriction prevents us from implementing interesting tools, we may -// teach the GC how to root ubi::Nodes, fix up hash tables that use them as -// keys, etc. -// -// -// Hostile Graph Structure -// -// Analyses consuming ubi::Node graphs must be robust when presented with graphs -// that are deliberately constructed to exploit their weaknesses. When operating -// on live graphs, web content has control over the object graph, and less -// direct control over shape and string structure, and analyses should be -// prepared to handle extreme cases gracefully. For example, if an analysis were -// to use the C++ stack in a depth-first traversal, carefully constructed -// content could cause the analysis to overflow the stack. -// -// When ubi::Nodes refer to nodes deserialized from a heap snapshot, analyses -// must be even more careful: since snapshots often come from potentially -// compromised e10s content processes, even properties normally guaranteed by -// the platform (the proper linking of DOM nodes, for example) might be -// corrupted. While it is the deserializer's responsibility to check the basic -// structure of the snapshot file, the analyses should be prepared for ubi::Node -// graphs constructed from snapshots to be even more bizarre. - -class JSAtom; - -namespace JS { -namespace ubi { - -class Edge; -class EdgeRange; -class StackFrame; - -} // namespace ubi -} // namespace JS - -namespace JS { -namespace ubi { - -using mozilla::Forward; -using mozilla::Maybe; -using mozilla::Move; -using mozilla::RangedPtr; -using mozilla::Variant; - -template -using Vector = mozilla::Vector; - -/*** ubi::StackFrame ******************************************************************************/ - -// Concrete JS::ubi::StackFrame instances backed by a live SavedFrame object -// store their strings as JSAtom*, while deserialized stack frames from offline -// heap snapshots store their strings as const char16_t*. In order to provide -// zero-cost accessors to these strings in a single interface that works with -// both cases, we use this variant type. -class AtomOrTwoByteChars : public Variant { - using Base = Variant; - - public: - template - MOZ_IMPLICIT AtomOrTwoByteChars(T&& rhs) : Base(Forward(rhs)) { } - - template - AtomOrTwoByteChars& operator=(T&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move disallowed"); - this->~AtomOrTwoByteChars(); - new (this) AtomOrTwoByteChars(Forward(rhs)); - return *this; - } - - // Return the length of the given AtomOrTwoByteChars string. - size_t length(); - - // Copy the given AtomOrTwoByteChars string into the destination buffer, - // inflating if necessary. Does NOT null terminate. Returns the number of - // characters written to destination. - size_t copyToBuffer(RangedPtr destination, size_t length); -}; - -// The base class implemented by each ConcreteStackFrame type. Subclasses -// must not add data members to this class. -class BaseStackFrame { - friend class StackFrame; - - BaseStackFrame(const StackFrame&) = delete; - BaseStackFrame& operator=(const StackFrame&) = delete; - - protected: - void* ptr; - explicit BaseStackFrame(void* ptr) : ptr(ptr) { } - - public: - // This is a value type that should not have a virtual destructor. Don't add - // destructors in subclasses! - - // Get a unique identifier for this StackFrame. The identifier is not valid - // across garbage collections. - virtual uint64_t identifier() const { return uint64_t(uintptr_t(ptr)); } - - // Get this frame's parent frame. - virtual StackFrame parent() const = 0; - - // Get this frame's line number. - virtual uint32_t line() const = 0; - - // Get this frame's column number. - virtual uint32_t column() const = 0; - - // Get this frame's source name. Never null. - virtual AtomOrTwoByteChars source() const = 0; - - // Return this frame's function name if named, otherwise the inferred - // display name. Can be null. - virtual AtomOrTwoByteChars functionDisplayName() const = 0; - - // Returns true if this frame's function is system JavaScript running with - // trusted principals, false otherwise. - virtual bool isSystem() const = 0; - - // Return true if this frame's function is a self-hosted JavaScript builtin, - // false otherwise. - virtual bool isSelfHosted(JSContext* cx) const = 0; - - // Construct a SavedFrame stack for the stack starting with this frame and - // containing all of its parents. The SavedFrame objects will be placed into - // cx's current compartment. - // - // Note that the process of - // - // SavedFrame - // | - // V - // JS::ubi::StackFrame - // | - // V - // offline heap snapshot - // | - // V - // JS::ubi::StackFrame - // | - // V - // SavedFrame - // - // is lossy because we cannot serialize and deserialize the SavedFrame's - // principals in the offline heap snapshot, so JS::ubi::StackFrame - // simplifies the principals check into the boolean isSystem() state. This - // is fine because we only expose JS::ubi::Stack to devtools and chrome - // code, and not to the web platform. - virtual MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx, - MutableHandleObject outSavedFrameStack) - const = 0; - - // Trace the concrete implementation of JS::ubi::StackFrame. - virtual void trace(JSTracer* trc) = 0; -}; - -// A traits template with a specialization for each backing type that implements -// the ubi::BaseStackFrame interface. Each specialization must be the a subclass -// of ubi::BaseStackFrame. -template class ConcreteStackFrame; - -// A JS::ubi::StackFrame represents a frame in a recorded stack. It can be -// backed either by a live SavedFrame object or by a structure deserialized from -// an offline heap snapshot. -// -// It is a value type that may be memcpy'd hither and thither without worrying -// about constructors or destructors, similar to POD types. -// -// Its lifetime is the same as the lifetime of the graph that is being analyzed -// by the JS::ubi::Node that the JS::ubi::StackFrame came from. That is, if the -// graph being analyzed is the live heap graph, the JS::ubi::StackFrame is only -// valid within the scope of an AutoCheckCannotGC; if the graph being analyzed -// is an offline heap snapshot, the JS::ubi::StackFrame is valid as long as the -// offline heap snapshot is alive. -class StackFrame { - // Storage in which we allocate BaseStackFrame subclasses. - mozilla::AlignedStorage2 storage; - - BaseStackFrame* base() { return storage.addr(); } - const BaseStackFrame* base() const { return storage.addr(); } - - template - void construct(T* ptr) { - static_assert(mozilla::IsBaseOf>::value, - "ConcreteStackFrame must inherit from BaseStackFrame"); - static_assert(sizeof(ConcreteStackFrame) == sizeof(*base()), - "ubi::ConcreteStackFrame specializations must be the same size as " - "ubi::BaseStackFrame"); - ConcreteStackFrame::construct(base(), ptr); - } - struct ConstructFunctor; - - public: - StackFrame() { construct(nullptr); } - - template - MOZ_IMPLICIT StackFrame(T* ptr) { - construct(ptr); - } - - template - StackFrame& operator=(T* ptr) { - construct(ptr); - return *this; - } - - // Constructors accepting SpiderMonkey's generic-pointer-ish types. - - template - explicit StackFrame(const JS::Handle& handle) { - construct(handle.get()); - } - - template - StackFrame& operator=(const JS::Handle& handle) { - construct(handle.get()); - return *this; - } - - template - explicit StackFrame(const JS::Rooted& root) { - construct(root.get()); - } - - template - StackFrame& operator=(const JS::Rooted& root) { - construct(root.get()); - return *this; - } - - // Because StackFrame is just a vtable pointer and an instance pointer, we - // can memcpy everything around instead of making concrete classes define - // virtual constructors. See the comment above Node's copy constructor for - // more details; that comment applies here as well. - StackFrame(const StackFrame& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - } - - StackFrame& operator=(const StackFrame& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - return *this; - } - - bool operator==(const StackFrame& rhs) const { return base()->ptr == rhs.base()->ptr; } - bool operator!=(const StackFrame& rhs) const { return !(*this == rhs); } - - explicit operator bool() const { - return base()->ptr != nullptr; - } - - // Copy this StackFrame's source name into the given |destination| - // buffer. Copy no more than |length| characters. The result is *not* null - // terminated. Returns how many characters were written into the buffer. - size_t source(RangedPtr destination, size_t length) const; - - // Copy this StackFrame's function display name into the given |destination| - // buffer. Copy no more than |length| characters. The result is *not* null - // terminated. Returns how many characters were written into the buffer. - size_t functionDisplayName(RangedPtr destination, size_t length) const; - - // Get the size of the respective strings. 0 is returned for null strings. - size_t sourceLength(); - size_t functionDisplayNameLength(); - - // Methods that forward to virtual calls through BaseStackFrame. - - void trace(JSTracer* trc) { base()->trace(trc); } - uint64_t identifier() const { - auto id = base()->identifier(); - MOZ_ASSERT(JS::Value::isNumberRepresentable(id)); - return id; - } - uint32_t line() const { return base()->line(); } - uint32_t column() const { return base()->column(); } - AtomOrTwoByteChars source() const { return base()->source(); } - AtomOrTwoByteChars functionDisplayName() const { return base()->functionDisplayName(); } - StackFrame parent() const { return base()->parent(); } - bool isSystem() const { return base()->isSystem(); } - bool isSelfHosted(JSContext* cx) const { return base()->isSelfHosted(cx); } - MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx, - MutableHandleObject outSavedFrameStack) const { - return base()->constructSavedFrameStack(cx, outSavedFrameStack); - } - - struct HashPolicy { - using Lookup = JS::ubi::StackFrame; - - static js::HashNumber hash(const Lookup& lookup) { - return lookup.identifier(); - } - - static bool match(const StackFrame& key, const Lookup& lookup) { - return key == lookup; - } - - static void rekey(StackFrame& k, const StackFrame& newKey) { - k = newKey; - } - }; -}; - -// The ubi::StackFrame null pointer. Any attempt to operate on a null -// ubi::StackFrame crashes. -template<> -class ConcreteStackFrame : public BaseStackFrame { - explicit ConcreteStackFrame(void* ptr) : BaseStackFrame(ptr) { } - - public: - static void construct(void* storage, void*) { new (storage) ConcreteStackFrame(nullptr); } - - uint64_t identifier() const override { return 0; } - void trace(JSTracer* trc) override { } - MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx, MutableHandleObject out) - const override - { - out.set(nullptr); - return true; - } - - uint32_t line() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - uint32_t column() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - AtomOrTwoByteChars source() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - AtomOrTwoByteChars functionDisplayName() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - StackFrame parent() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - bool isSystem() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - bool isSelfHosted(JSContext* cx) const override { MOZ_CRASH("null JS::ubi::StackFrame"); } -}; - -MOZ_MUST_USE bool ConstructSavedFrameStackSlow(JSContext* cx, JS::ubi::StackFrame& frame, - MutableHandleObject outSavedFrameStack); - - -/*** ubi::Node ************************************************************************************/ - -// A concrete node specialization can claim its referent is a member of a -// particular "coarse type" which is less specific than the actual -// implementation type but generally more palatable for web developers. For -// example, JitCode can be considered to have a coarse type of "Script". This is -// used by some analyses for putting nodes into different buckets. The default, -// if a concrete specialization does not provide its own mapping to a CoarseType -// variant, is "Other". -// -// NB: the values associated with a particular enum variant must not change or -// be reused for new variants. Doing so will cause inspecting ubi::Nodes backed -// by an offline heap snapshot from an older SpiderMonkey/Firefox version to -// break. Consider this enum append only. -enum class CoarseType: uint32_t { - Other = 0, - Object = 1, - Script = 2, - String = 3, - - FIRST = Other, - LAST = String -}; - -inline uint32_t -CoarseTypeToUint32(CoarseType type) -{ - return static_cast(type); -} - -inline bool -Uint32IsValidCoarseType(uint32_t n) -{ - auto first = static_cast(CoarseType::FIRST); - auto last = static_cast(CoarseType::LAST); - MOZ_ASSERT(first < last); - return first <= n && n <= last; -} - -inline CoarseType -Uint32ToCoarseType(uint32_t n) -{ - MOZ_ASSERT(Uint32IsValidCoarseType(n)); - return static_cast(n); -} - -// The base class implemented by each ubi::Node referent type. Subclasses must -// not add data members to this class. -class Base { - friend class Node; - - // For performance's sake, we'd prefer to avoid a virtual destructor; and - // an empty constructor seems consistent with the 'lightweight value type' - // visible behavior we're trying to achieve. But if the destructor isn't - // virtual, and a subclass overrides it, the subclass's destructor will be - // ignored. Is there a way to make the compiler catch that error? - - protected: - // Space for the actual pointer. Concrete subclasses should define a - // properly typed 'get' member function to access this. - void* ptr; - - explicit Base(void* ptr) : ptr(ptr) { } - - public: - bool operator==(const Base& rhs) const { - // Some compilers will indeed place objects of different types at - // the same address, so technically, we should include the vtable - // in this comparison. But it seems unlikely to cause problems in - // practice. - return ptr == rhs.ptr; - } - bool operator!=(const Base& rhs) const { return !(*this == rhs); } - - // An identifier for this node, guaranteed to be stable and unique for as - // long as this ubi::Node's referent is alive and at the same address. - // - // This is probably suitable for use in serializations, as it is an integral - // type. It may also help save memory when constructing HashSets of - // ubi::Nodes: since a uint64_t will always be smaller-or-equal-to the size - // of a ubi::Node, a HashSet may use less space per element - // than a HashSet. - // - // (Note that 'unique' only means 'up to equality on ubi::Node'; see the - // caveats about multiple objects allocated at the same address for - // 'ubi::Node::operator=='.) - using Id = uint64_t; - virtual Id identifier() const { return Id(uintptr_t(ptr)); } - - // Returns true if this node is pointing to something on the live heap, as - // opposed to something from a deserialized core dump. Returns false, - // otherwise. - virtual bool isLive() const { return true; }; - - // Return the coarse-grained type-of-thing that this node represents. - virtual CoarseType coarseType() const { return CoarseType::Other; } - - // Return a human-readable name for the referent's type. The result should - // be statically allocated. (You can use u"strings" for this.) - // - // This must always return Concrete::concreteTypeName; we use that - // pointer as a tag for this particular referent type. - virtual const char16_t* typeName() const = 0; - - // Return the size of this node, in bytes. Include any structures that this - // node owns exclusively that are not exposed as their own ubi::Nodes. - // |mallocSizeOf| should be a malloc block sizing function; see - // |mfbt/MemoryReporting.h|. - // - // Because we can use |JS::ubi::Node|s backed by a snapshot that was taken - // on a 64-bit platform when we are currently on a 32-bit platform, we - // cannot rely on |size_t| for node sizes. Instead, |Size| is uint64_t on - // all platforms. - using Size = uint64_t; - virtual Size size(mozilla::MallocSizeOf mallocSizeof) const { return 1; } - - // Return an EdgeRange that initially contains all the referent's outgoing - // edges. The caller takes ownership of the EdgeRange. - // - // If wantNames is true, compute names for edges. Doing so can be expensive - // in time and memory. - virtual js::UniquePtr edges(JSContext* cx, bool wantNames) const = 0; - - // Return the Zone to which this node's referent belongs, or nullptr if the - // referent is not of a type allocated in SpiderMonkey Zones. - virtual JS::Zone* zone() const { return nullptr; } - - // Return the compartment for this node. Some ubi::Node referents are not - // associated with JSCompartments, such as JSStrings (which are associated - // with Zones). When the referent is not associated with a compartment, - // nullptr is returned. - virtual JSCompartment* compartment() const { return nullptr; } - - // Return whether this node's referent's allocation stack was captured. - virtual bool hasAllocationStack() const { return false; } - - // Get the stack recorded at the time this node's referent was - // allocated. This must only be called when hasAllocationStack() is true. - virtual StackFrame allocationStack() const { - MOZ_CRASH("Concrete classes that have an allocation stack must override both " - "hasAllocationStack and allocationStack."); - } - - // Methods for JSObject Referents - // - // These methods are only semantically valid if the referent is either a - // JSObject in the live heap, or represents a previously existing JSObject - // from some deserialized heap snapshot. - - // Return the object's [[Class]]'s name. - virtual const char* jsObjectClassName() const { return nullptr; } - - // If this object was constructed with `new` and we have the data available, - // place the contructor function's display name in the out parameter. - // Otherwise, place nullptr in the out parameter. Caller maintains ownership - // of the out parameter. True is returned on success, false is returned on - // OOM. - virtual MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) - const - { - outName.reset(nullptr); - return true; - } - - // Methods for CoarseType::Script referents - - // Return the script's source's filename if available. If unavailable, - // return nullptr. - virtual const char* scriptFilename() const { return nullptr; } - - private: - Base(const Base& rhs) = delete; - Base& operator=(const Base& rhs) = delete; -}; - -// A traits template with a specialization for each referent type that -// ubi::Node supports. The specialization must be the concrete subclass of Base -// that represents a pointer to the referent type. It must include these -// members: -// -// // The specific char16_t array returned by Concrete::typeName(). -// static const char16_t concreteTypeName[]; -// -// // Construct an instance of this concrete class in |storage| referring -// // to |referent|. Implementations typically use a placement 'new'. -// // -// // In some cases, |referent| will contain dynamic type information that -// // identifies it a some more specific subclass of |Referent|. For -// // example, when |Referent| is |JSObject|, then |referent->getClass()| -// // could tell us that it's actually a JSFunction. Similarly, if -// // |Referent| is |nsISupports|, we would like a ubi::Node that knows its -// // final implementation type. -// // -// // So we delegate the actual construction to this specialization, which -// // knows Referent's details. -// static void construct(void* storage, Referent* referent); -template -class Concrete; - -// A container for a Base instance; all members simply forward to the contained -// instance. This container allows us to pass ubi::Node instances by value. -class Node { - // Storage in which we allocate Base subclasses. - mozilla::AlignedStorage2 storage; - Base* base() { return storage.addr(); } - const Base* base() const { return storage.addr(); } - - template - void construct(T* ptr) { - static_assert(sizeof(Concrete) == sizeof(*base()), - "ubi::Base specializations must be the same size as ubi::Base"); - static_assert(mozilla::IsBaseOf>::value, - "ubi::Concrete must inherit from ubi::Base"); - Concrete::construct(base(), ptr); - } - struct ConstructFunctor; - - public: - Node() { construct(nullptr); } - - template - MOZ_IMPLICIT Node(T* ptr) { - construct(ptr); - } - template - Node& operator=(T* ptr) { - construct(ptr); - return *this; - } - - // We can construct and assign from rooted forms of pointers. - template - MOZ_IMPLICIT Node(const Rooted& root) { - construct(root.get()); - } - template - Node& operator=(const Rooted& root) { - construct(root.get()); - return *this; - } - - // Constructors accepting SpiderMonkey's other generic-pointer-ish types. - // Note that we *do* want an implicit constructor here: JS::Value and - // JS::ubi::Node are both essentially tagged references to other sorts of - // objects, so letting conversions happen automatically is appropriate. - MOZ_IMPLICIT Node(JS::HandleValue value); - explicit Node(const JS::GCCellPtr& thing); - - // copy construction and copy assignment just use memcpy, since we know - // instances contain nothing but a vtable pointer and a data pointer. - // - // To be completely correct, concrete classes could provide a virtual - // 'construct' member function, which we could invoke on rhs to construct an - // instance in our storage. But this is good enough; there's no need to jump - // through vtables for copying and assignment that are just going to move - // two words around. The compiler knows how to optimize memcpy. - Node(const Node& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - } - - Node& operator=(const Node& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - return *this; - } - - bool operator==(const Node& rhs) const { return *base() == *rhs.base(); } - bool operator!=(const Node& rhs) const { return *base() != *rhs.base(); } - - explicit operator bool() const { - return base()->ptr != nullptr; - } - - bool isLive() const { return base()->isLive(); } - - // Get the canonical type name for the given type T. - template - static const char16_t* canonicalTypeName() { return Concrete::concreteTypeName; } - - template - bool is() const { - return base()->typeName() == canonicalTypeName(); - } - - template - T* as() const { - MOZ_ASSERT(isLive()); - MOZ_ASSERT(is()); - return static_cast(base()->ptr); - } - - template - T* asOrNull() const { - MOZ_ASSERT(isLive()); - return is() ? static_cast(base()->ptr) : nullptr; - } - - // If this node refers to something that can be represented as a JavaScript - // value that is safe to expose to JavaScript code, return that value. - // Otherwise return UndefinedValue(). JSStrings, JS::Symbols, and some (but - // not all!) JSObjects can be exposed. - JS::Value exposeToJS() const; - - CoarseType coarseType() const { return base()->coarseType(); } - const char16_t* typeName() const { return base()->typeName(); } - JS::Zone* zone() const { return base()->zone(); } - JSCompartment* compartment() const { return base()->compartment(); } - const char* jsObjectClassName() const { return base()->jsObjectClassName(); } - MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) const { - return base()->jsObjectConstructorName(cx, outName); - } - - const char* scriptFilename() const { return base()->scriptFilename(); } - - using Size = Base::Size; - Size size(mozilla::MallocSizeOf mallocSizeof) const { - auto size = base()->size(mallocSizeof); - MOZ_ASSERT(size > 0, - "C++ does not have zero-sized types! Choose 1 if you just need a " - "conservative default."); - return size; - } - - js::UniquePtr edges(JSContext* cx, bool wantNames = true) const { - return base()->edges(cx, wantNames); - } - - bool hasAllocationStack() const { return base()->hasAllocationStack(); } - StackFrame allocationStack() const { - return base()->allocationStack(); - } - - using Id = Base::Id; - Id identifier() const { - auto id = base()->identifier(); - MOZ_ASSERT(JS::Value::isNumberRepresentable(id)); - return id; - } - - // A hash policy for ubi::Nodes. - // This simply uses the stock PointerHasher on the ubi::Node's pointer. - // We specialize DefaultHasher below to make this the default. - class HashPolicy { - typedef js::PointerHasher::value> PtrHash; - - public: - typedef Node Lookup; - - static js::HashNumber hash(const Lookup& l) { return PtrHash::hash(l.base()->ptr); } - static bool match(const Node& k, const Lookup& l) { return k == l; } - static void rekey(Node& k, const Node& newKey) { k = newKey; } - }; -}; - -using NodeSet = js::HashSet, js::SystemAllocPolicy>; -using NodeSetPtr = mozilla::UniquePtr>; - -/*** Edge and EdgeRange ***************************************************************************/ - -using EdgeName = UniqueTwoByteChars; - -// An outgoing edge to a referent node. -class Edge { - public: - Edge() : name(nullptr), referent() { } - - // Construct an initialized Edge, taking ownership of |name|. - Edge(char16_t* name, const Node& referent) - : name(name) - , referent(referent) - { } - - // Move construction and assignment. - Edge(Edge&& rhs) - : name(mozilla::Move(rhs.name)) - , referent(rhs.referent) - { } - - Edge& operator=(Edge&& rhs) { - MOZ_ASSERT(&rhs != this); - this->~Edge(); - new (this) Edge(mozilla::Move(rhs)); - return *this; - } - - Edge(const Edge&) = delete; - Edge& operator=(const Edge&) = delete; - - // This edge's name. This may be nullptr, if Node::edges was called with - // false as the wantNames parameter. - // - // The storage is owned by this Edge, and will be freed when this Edge is - // destructed. You may take ownership of the name by `mozilla::Move`ing it - // out of the edge; it is just a UniquePtr. - // - // (In real life we'll want a better representation for names, to avoid - // creating tons of strings when the names follow a pattern; and we'll need - // to think about lifetimes carefully to ensure traversal stays cheap.) - EdgeName name; - - // This edge's referent. - Node referent; -}; - -// EdgeRange is an abstract base class for iterating over a node's outgoing -// edges. (This is modeled after js::HashTable::Range.) -// -// Concrete instances of this class need not be as lightweight as Node itself, -// since they're usually only instantiated while iterating over a particular -// object's edges. For example, a dumb implementation for JS Cells might use -// JS::TraceChildren to to get the outgoing edges, and then store them in an -// array internal to the EdgeRange. -class EdgeRange { - protected: - // The current front edge of this range, or nullptr if this range is empty. - Edge* front_; - - EdgeRange() : front_(nullptr) { } - - public: - virtual ~EdgeRange() { } - - // True if there are no more edges in this range. - bool empty() const { return !front_; } - - // The front edge of this range. This is owned by the EdgeRange, and is - // only guaranteed to live until the next call to popFront, or until - // the EdgeRange is destructed. - const Edge& front() const { return *front_; } - Edge& front() { return *front_; } - - // Remove the front edge from this range. This should only be called if - // !empty(). - virtual void popFront() = 0; - - private: - EdgeRange(const EdgeRange&) = delete; - EdgeRange& operator=(const EdgeRange&) = delete; -}; - - -typedef mozilla::Vector EdgeVector; - -// An EdgeRange concrete class that holds a pre-existing vector of -// Edges. A PreComputedEdgeRange does not take ownership of its -// EdgeVector; it is up to the PreComputedEdgeRange's consumer to manage -// that lifetime. -class PreComputedEdgeRange : public EdgeRange { - EdgeVector& edges; - size_t i; - - void settle() { - front_ = i < edges.length() ? &edges[i] : nullptr; - } - - public: - explicit PreComputedEdgeRange(EdgeVector& edges) - : edges(edges), - i(0) - { - settle(); - } - - void popFront() override { - MOZ_ASSERT(!empty()); - i++; - settle(); - } -}; - -/*** RootList *************************************************************************************/ - -// RootList is a class that can be pointed to by a |ubi::Node|, creating a -// fictional root-of-roots which has edges to every GC root in the JS -// runtime. Having a single root |ubi::Node| is useful for algorithms written -// with the assumption that there aren't multiple roots (such as computing -// dominator trees) and you want a single point of entry. It also ensures that -// the roots themselves get visited by |ubi::BreadthFirst| (they would otherwise -// only be used as starting points). -// -// RootList::init itself causes a minor collection, but once the list of roots -// has been created, GC must not occur, as the referent ubi::Nodes are not -// stable across GC. The init calls emplace on |noGC|'s AutoCheckCannotGC, whose -// lifetime must extend at least as long as the RootList itself. -// -// Example usage: -// -// { -// mozilla::Maybe maybeNoGC; -// JS::ubi::RootList rootList(cx, maybeNoGC); -// if (!rootList.init()) -// return false; -// -// // The AutoCheckCannotGC is guaranteed to exist if init returned true. -// MOZ_ASSERT(maybeNoGC.isSome()); -// -// JS::ubi::Node root(&rootList); -// -// ... -// } -class MOZ_STACK_CLASS RootList { - Maybe& noGC; - - public: - JSContext* cx; - EdgeVector edges; - bool wantNames; - - RootList(JSContext* cx, Maybe& noGC, bool wantNames = false); - - // Find all GC roots. - MOZ_MUST_USE bool init(); - // Find only GC roots in the provided set of |JSCompartment|s. - MOZ_MUST_USE bool init(CompartmentSet& debuggees); - // Find only GC roots in the given Debugger object's set of debuggee - // compartments. - MOZ_MUST_USE bool init(HandleObject debuggees); - - // Returns true if the RootList has been initialized successfully, false - // otherwise. - bool initialized() { return noGC.isSome(); } - - // Explicitly add the given Node as a root in this RootList. If wantNames is - // true, you must pass an edgeName. The RootList does not take ownership of - // edgeName. - MOZ_MUST_USE bool addRoot(Node node, const char16_t* edgeName = nullptr); -}; - - -/*** Concrete classes for ubi::Node referent types ************************************************/ - -template<> -class Concrete : public Base { - protected: - explicit Concrete(RootList* ptr) : Base(ptr) { } - RootList& get() const { return *static_cast(ptr); } - - public: - static void construct(void* storage, RootList* ptr) { new (storage) Concrete(ptr); } - - js::UniquePtr edges(JSContext* cx, bool wantNames) const override; - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// A reusable ubi::Concrete specialization base class for types supported by -// JS::TraceChildren. -template -class TracerConcrete : public Base { - js::UniquePtr edges(JSContext* cx, bool wantNames) const override; - JS::Zone* zone() const override; - - protected: - explicit TracerConcrete(Referent* ptr) : Base(ptr) { } - Referent& get() const { return *static_cast(ptr); } -}; - -// For JS::TraceChildren-based types that have a 'compartment' method. -template -class TracerConcreteWithCompartment : public TracerConcrete { - typedef TracerConcrete TracerBase; - JSCompartment* compartment() const override; - - protected: - explicit TracerConcreteWithCompartment(Referent* ptr) : TracerBase(ptr) { } -}; - -// Define specializations for some commonly-used public JSAPI types. -// These can use the generic templates above. -template<> -class Concrete : TracerConcrete { - protected: - explicit Concrete(JS::Symbol* ptr) : TracerConcrete(ptr) { } - - public: - static void construct(void* storage, JS::Symbol* ptr) { - new (storage) Concrete(ptr); - } - - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -template<> -class Concrete : TracerConcreteWithCompartment { - protected: - explicit Concrete(JSScript *ptr) : TracerConcreteWithCompartment(ptr) { } - - public: - static void construct(void *storage, JSScript *ptr) { new (storage) Concrete(ptr); } - - CoarseType coarseType() const final { return CoarseType::Script; } - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - const char* scriptFilename() const final; - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// The JSObject specialization. -template<> -class Concrete : public TracerConcreteWithCompartment { - protected: - explicit Concrete(JSObject* ptr) : TracerConcreteWithCompartment(ptr) { } - - public: - static void construct(void* storage, JSObject* ptr) { - new (storage) Concrete(ptr); - } - - const char* jsObjectClassName() const override; - MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) - const override; - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - - bool hasAllocationStack() const override; - StackFrame allocationStack() const override; - - CoarseType coarseType() const final { return CoarseType::Object; } - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// For JSString, we extend the generic template with a 'size' implementation. -template<> -class Concrete : TracerConcrete { - protected: - explicit Concrete(JSString *ptr) : TracerConcrete(ptr) { } - - public: - static void construct(void *storage, JSString *ptr) { new (storage) Concrete(ptr); } - - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - - CoarseType coarseType() const final { return CoarseType::String; } - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// The ubi::Node null pointer. Any attempt to operate on a null ubi::Node asserts. -template<> -class Concrete : public Base { - const char16_t* typeName() const override; - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - js::UniquePtr edges(JSContext* cx, bool wantNames) const override; - JS::Zone* zone() const override; - JSCompartment* compartment() const override; - CoarseType coarseType() const final; - - explicit Concrete(void* ptr) : Base(ptr) { } - - public: - static void construct(void* storage, void* ptr) { new (storage) Concrete(ptr); } -}; - - -} // namespace ubi -} // namespace JS - -namespace js { - -// Make ubi::Node::HashPolicy the default hash policy for ubi::Node. -template<> struct DefaultHasher : JS::ubi::Node::HashPolicy { }; -template<> struct DefaultHasher : JS::ubi::StackFrame::HashPolicy { }; - -} // namespace js - -#endif // js_UbiNode_h diff --git a/ios/include/spidermonkey/js/UbiNodeBreadthFirst.h b/ios/include/spidermonkey/js/UbiNodeBreadthFirst.h deleted file mode 100644 index 8446dbc6..00000000 --- a/ios/include/spidermonkey/js/UbiNodeBreadthFirst.h +++ /dev/null @@ -1,244 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeBreadthFirst_h -#define js_UbiNodeBreadthFirst_h - -#include "js/UbiNode.h" -#include "js/Utility.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -// A breadth-first traversal template for graphs of ubi::Nodes. -// -// No GC may occur while an instance of this template is live. -// -// The provided Handler type should have two members: -// -// typename NodeData; -// -// The value type of |BreadthFirst::visited|, the HashMap of -// ubi::Nodes that have been visited so far. Since the algorithm needs a -// hash table like this for its own use anyway, it is simple to let -// Handler store its own metadata about each node in the same table. -// -// For example, if you want to find a shortest path to each node from any -// traversal starting point, your |NodeData| type could record the first -// edge to reach each node, and the node from which it originates. Then, -// when the traversal is complete, you can walk backwards from any node -// to some starting point, and the path recorded will be a shortest path. -// -// This type must have a default constructor. If this type owns any other -// resources, move constructors and assignment operators are probably a -// good idea, too. -// -// bool operator() (BreadthFirst& traversal, -// Node origin, const Edge& edge, -// Handler::NodeData* referentData, bool first); -// -// The visitor function, called to report that we have traversed -// |edge| from |origin|. This is called once for each edge we traverse. -// As this is a breadth-first search, any prior calls to the visitor function -// were for origin nodes not further from the start nodes than |origin|. -// -// |traversal| is this traversal object, passed along for convenience. -// -// |referentData| is a pointer to the value of the entry in -// |traversal.visited| for |edge.referent|; the visitor function can -// store whatever metadata it likes about |edge.referent| there. -// -// |first| is true if this is the first time we have visited an edge -// leading to |edge.referent|. This could be stored in NodeData, but -// the algorithm knows whether it has just created the entry in -// |traversal.visited|, so it passes it along for convenience. -// -// The visitor function may call |traversal.abandonReferent()| if it -// doesn't want to traverse the outgoing edges of |edge.referent|. You can -// use this to limit the traversal to a given portion of the graph: it will -// never visit nodes reachable only through nodes that you have abandoned. -// Note that |abandonReferent| must be called the first time the given node -// is reached; that is, |first| must be true. -// -// The visitor function may call |traversal.stop()| if it doesn't want -// to visit any more nodes at all. -// -// The visitor function may consult |traversal.visited| for information -// about other nodes, but it should not add or remove entries. -// -// The visitor function should return true on success, or false if an -// error occurs. A false return value terminates the traversal -// immediately, and causes BreadthFirst::traverse to return -// false. -template -struct BreadthFirst { - - // Construct a breadth-first traversal object that reports the nodes it - // reaches to |handler|. The traversal asserts that no GC happens in its - // runtime during its lifetime. - // - // We do nothing with noGC, other than require it to exist, with a lifetime - // that encloses our own. - BreadthFirst(JSContext* cx, Handler& handler, const JS::AutoCheckCannotGC& noGC) - : wantNames(true), cx(cx), visited(), handler(handler), pending(), - traversalBegun(false), stopRequested(false), abandonRequested(false) - { } - - // Initialize this traversal object. Return false on OOM. - bool init() { return visited.init(); } - - // Add |node| as a starting point for the traversal. You may add - // as many starting points as you like. Return false on OOM. - bool addStart(Node node) { return pending.append(node); } - - // Add |node| as a starting point for the traversal (see addStart) and also - // add it to the |visited| set. Return false on OOM. - bool addStartVisited(Node node) { - typename NodeMap::AddPtr ptr = visited.lookupForAdd(node); - if (!ptr && !visited.add(ptr, node, typename Handler::NodeData())) - return false; - return addStart(node); - } - - // True if the handler wants us to compute edge names; doing so can be - // expensive in time and memory. True by default. - bool wantNames; - - // Traverse the graph in breadth-first order, starting at the given - // start nodes, applying |handler::operator()| for each edge traversed - // as described above. - // - // This should be called only once per instance of this class. - // - // Return false on OOM or error return from |handler::operator()|. - bool traverse() - { - MOZ_ASSERT(!traversalBegun); - traversalBegun = true; - - // While there are pending nodes, visit them. - while (!pending.empty()) { - Node origin = pending.front(); - pending.popFront(); - - // Get a range containing all origin's outgoing edges. - auto range = origin.edges(cx, wantNames); - if (!range) - return false; - - // Traverse each edge. - for (; !range->empty(); range->popFront()) { - MOZ_ASSERT(!stopRequested); - - Edge& edge = range->front(); - typename NodeMap::AddPtr a = visited.lookupForAdd(edge.referent); - bool first = !a; - - if (first) { - // This is the first time we've reached |edge.referent|. - // Mark it as visited. - if (!visited.add(a, edge.referent, typename Handler::NodeData())) - return false; - } - - MOZ_ASSERT(a); - - // Report this edge to the visitor function. - if (!handler(*this, origin, edge, &a->value(), first)) - return false; - - if (stopRequested) - return true; - - // Arrange to traverse this edge's referent's outgoing edges - // later --- unless |handler| asked us not to. - if (abandonRequested) { - // Skip the enqueue; reset flag for future iterations. - abandonRequested = false; - } else if (first) { - if (!pending.append(edge.referent)) - return false; - } - } - } - - return true; - } - - // Stop traversal, and return true from |traverse| without visiting any - // more nodes. Only |handler::operator()| should call this function; it - // may do so to stop the traversal early, without returning false and - // then making |traverse|'s caller disambiguate that result from a real - // error. - void stop() { stopRequested = true; } - - // Request that the current edge's referent's outgoing edges not be - // traversed. This must be called the first time that referent is reached. - // Other edges *to* that referent will still be traversed. - void abandonReferent() { abandonRequested = true; } - - // The context with which we were constructed. - JSContext* cx; - - // A map associating each node N that we have reached with a - // Handler::NodeData, for |handler|'s use. This is public, so that - // |handler| can access it to see the traversal thus far. - using NodeMap = js::HashMap, - js::SystemAllocPolicy>; - NodeMap visited; - - private: - // Our handler object. - Handler& handler; - - // A queue template. Appending and popping the front are constant time. - // Wasted space is never more than some recent actual population plus the - // current population. - template - class Queue { - js::Vector head, tail; - size_t frontIndex; - public: - Queue() : head(), tail(), frontIndex(0) { } - bool empty() { return frontIndex >= head.length(); } - T& front() { - MOZ_ASSERT(!empty()); - return head[frontIndex]; - } - void popFront() { - MOZ_ASSERT(!empty()); - frontIndex++; - if (frontIndex >= head.length()) { - head.clearAndFree(); - head.swap(tail); - frontIndex = 0; - } - } - bool append(const T& elt) { - return frontIndex == 0 ? head.append(elt) : tail.append(elt); - } - }; - - // A queue of nodes that we have reached, but whose outgoing edges we - // have not yet traversed. Nodes reachable in fewer edges are enqueued - // earlier. - Queue pending; - - // True if our traverse function has been called. - bool traversalBegun; - - // True if we've been asked to stop the traversal. - bool stopRequested; - - // True if we've been asked to abandon the current edge's referent. - bool abandonRequested; -}; - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeBreadthFirst_h diff --git a/ios/include/spidermonkey/js/UbiNodeCensus.h b/ios/include/spidermonkey/js/UbiNodeCensus.h deleted file mode 100644 index c0859ec5..00000000 --- a/ios/include/spidermonkey/js/UbiNodeCensus.h +++ /dev/null @@ -1,251 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeCensus_h -#define js_UbiNodeCensus_h - -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" - -#include - -#include "jsapi.h" - -#include "js/UbiNode.h" -#include "js/UbiNodeBreadthFirst.h" - -// A census is a ubi::Node traversal that assigns each node to one or more -// buckets, and returns a report with the size of each bucket. -// -// We summarize the results of a census with counts broken down according to -// criteria selected by the API consumer code that is requesting the census. For -// example, the following breakdown might give an interesting overview of the -// heap: -// -// - all nodes -// - objects -// - objects with a specific [[Class]] * -// - strings -// - scripts -// - all other Node types -// - nodes with a specific ubi::Node::typeName * -// -// Obviously, the parts of this tree marked with * represent many separate -// counts, depending on how many distinct [[Class]] values and ubi::Node type -// names we encounter. -// -// The supported types of breakdowns are documented in -// js/src/doc/Debugger/Debugger.Memory.md. -// -// When we parse the 'breakdown' argument to takeCensus, we build a tree of -// CountType nodes. For example, for the breakdown shown in the -// Debugger.Memory.prototype.takeCensus, documentation: -// -// { -// by: "coarseType", -// objects: { by: "objectClass" }, -// other: { by: "internalType" } -// } -// -// we would build the following tree of CountType subclasses: -// -// ByCoarseType -// objects: ByObjectClass -// each class: SimpleCount -// scripts: SimpleCount -// strings: SimpleCount -// other: ByUbinodeType -// each type: SimpleCount -// -// The interior nodes are all breakdown types that categorize nodes according to -// one characteristic or another; and the leaf nodes are all SimpleType. -// -// Each CountType has its own concrete C++ type that holds the counts it -// produces. SimpleCount::Count just holds totals. ByObjectClass::Count has a -// hash table whose keys are object class names and whose values are counts of -// some other type (in the example above, SimpleCount). -// -// To keep actual count nodes small, they have no vtable. Instead, each count -// points to its CountType, which knows how to carry out all the operations we -// need on a Count. A CountType can produce new count nodes; process nodes as we -// visit them; build a JS object reporting the results; and destruct count -// nodes. - - -namespace JS { -namespace ubi { - -struct Census; - -class CountBase; - -struct CountDeleter { - void operator()(CountBase*); -}; - -using CountBasePtr = js::UniquePtr; - -// Abstract base class for CountType nodes. -struct CountType { - explicit CountType() { } - virtual ~CountType() { } - - // Destruct a count tree node that this type instance constructed. - virtual void destructCount(CountBase& count) = 0; - - // Return a fresh node for the count tree that categorizes nodes according - // to this type. Return a nullptr on OOM. - virtual CountBasePtr makeCount() = 0; - - // Trace |count| and all its children, for garbage collection. - virtual void traceCount(CountBase& count, JSTracer* trc) = 0; - - // Implement the 'count' method for counts returned by this CountType - // instance's 'newCount' method. - virtual MOZ_MUST_USE bool count(CountBase& count, - mozilla::MallocSizeOf mallocSizeOf, - const Node& node) = 0; - - // Implement the 'report' method for counts returned by this CountType - // instance's 'newCount' method. - virtual MOZ_MUST_USE bool report(JSContext* cx, CountBase& count, - MutableHandleValue report) = 0; -}; - -using CountTypePtr = js::UniquePtr; - -// An abstract base class for count tree nodes. -class CountBase { - // In lieu of a vtable, each CountBase points to its type, which - // carries not only the implementations of the CountBase methods, but also - // additional parameters for the type's behavior, as specified in the - // breakdown argument passed to takeCensus. - CountType& type; - - protected: - ~CountBase() { } - - public: - explicit CountBase(CountType& type) - : type(type) - , total_(0) - , smallestNodeIdCounted_(SIZE_MAX) - { } - - // Categorize and count |node| as appropriate for this count's type. - MOZ_MUST_USE bool count(mozilla::MallocSizeOf mallocSizeOf, const Node& node) { - total_++; - - auto id = node.identifier(); - if (id < smallestNodeIdCounted_) { - smallestNodeIdCounted_ = id; - } - -#ifdef DEBUG - size_t oldTotal = total_; -#endif - - bool ret = type.count(*this, mallocSizeOf, node); - - MOZ_ASSERT(total_ == oldTotal, - "CountType::count should not increment total_, CountBase::count handles that"); - - return ret; - } - - // Construct a JavaScript object reporting the counts recorded in this - // count, and store it in |report|. Return true on success, or false on - // failure. - MOZ_MUST_USE bool report(JSContext* cx, MutableHandleValue report) { - return type.report(cx, *this, report); - } - - // Down-cast this CountBase to its true type, based on its 'type' member, - // and run its destructor. - void destruct() { return type.destructCount(*this); } - - // Trace this count for garbage collection. - void trace(JSTracer* trc) { type.traceCount(*this, trc); } - - size_t total_; - - // The smallest JS::ubi::Node::identifier() passed to this instance's - // count() method. This provides a stable way to sort sets. - Node::Id smallestNodeIdCounted_; -}; - -class RootedCount : JS::CustomAutoRooter { - CountBasePtr count; - - void trace(JSTracer* trc) override { count->trace(trc); } - - public: - RootedCount(JSContext* cx, CountBasePtr&& count) - : CustomAutoRooter(cx), - count(Move(count)) - { } - CountBase* operator->() const { return count.get(); } - explicit operator bool() const { return count.get(); } - operator CountBasePtr&() { return count; } -}; - -// Common data for a census traversal, shared across all CountType nodes. -struct Census { - JSContext* const cx; - // If the targetZones set is non-empty, then only consider nodes whose zone - // is an element of the set. If the targetZones set is empty, then nodes in - // all zones are considered. - JS::ZoneSet targetZones; - Zone* atomsZone; - - explicit Census(JSContext* cx) : cx(cx), atomsZone(nullptr) { } - - MOZ_MUST_USE bool init(); -}; - -// A BreadthFirst handler type that conducts a census, using a CountBase to -// categorize and count each node. -class CensusHandler { - Census& census; - CountBasePtr& rootCount; - mozilla::MallocSizeOf mallocSizeOf; - - public: - CensusHandler(Census& census, CountBasePtr& rootCount, mozilla::MallocSizeOf mallocSizeOf) - : census(census), - rootCount(rootCount), - mallocSizeOf(mallocSizeOf) - { } - - MOZ_MUST_USE bool report(JSContext* cx, MutableHandleValue report) { - return rootCount->report(cx, report); - } - - // This class needs to retain no per-node data. - class NodeData { }; - - MOZ_MUST_USE bool operator() (BreadthFirst& traversal, - Node origin, const Edge& edge, - NodeData* referentData, bool first); -}; - -using CensusTraversal = BreadthFirst; - -// Examine the census options supplied by the API consumer, and (among other -// things) use that to build a CountType tree. -MOZ_MUST_USE bool ParseCensusOptions(JSContext* cx, Census& census, HandleObject options, - CountTypePtr& outResult); - -// Parse the breakdown language (as described in -// js/src/doc/Debugger/Debugger.Memory.md) into a CountTypePtr. A null pointer -// is returned on error and is reported to the cx. -CountTypePtr ParseBreakdown(JSContext* cx, HandleValue breakdownValue); - - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeCensus_h diff --git a/ios/include/spidermonkey/js/UbiNodeDominatorTree.h b/ios/include/spidermonkey/js/UbiNodeDominatorTree.h deleted file mode 100644 index 3422b76b..00000000 --- a/ios/include/spidermonkey/js/UbiNodeDominatorTree.h +++ /dev/null @@ -1,677 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeDominatorTree_h -#define js_UbiNodeDominatorTree_h - -#include "mozilla/Attributes.h" -#include "mozilla/DebugOnly.h" -#include "mozilla/Maybe.h" -#include "mozilla/Move.h" -#include "mozilla/UniquePtr.h" - -#include "jsalloc.h" - -#include "js/UbiNode.h" -#include "js/UbiNodePostOrder.h" -#include "js/Utility.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -/** - * In a directed graph with a root node `R`, a node `A` is said to "dominate" a - * node `B` iff every path from `R` to `B` contains `A`. A node `A` is said to - * be the "immediate dominator" of a node `B` iff it dominates `B`, is not `B` - * itself, and does not dominate any other nodes which also dominate `B` in - * turn. - * - * If we take every node from a graph `G` and create a new graph `T` with edges - * to each node from its immediate dominator, then `T` is a tree (each node has - * only one immediate dominator, or none if it is the root). This tree is called - * a "dominator tree". - * - * This class represents a dominator tree constructed from a `JS::ubi::Node` - * heap graph. The domination relationship and dominator trees are useful tools - * for analyzing heap graphs because they tell you: - * - * - Exactly what could be reclaimed by the GC if some node `A` became - * unreachable: those nodes which are dominated by `A`, - * - * - The "retained size" of a node in the heap graph, in contrast to its - * "shallow size". The "shallow size" is the space taken by a node itself, - * not counting anything it references. The "retained size" of a node is its - * shallow size plus the size of all the things that would be collected if - * the original node wasn't (directly or indirectly) referencing them. In - * other words, the retained size is the shallow size of a node plus the - * shallow sizes of every other node it dominates. For example, the root - * node in a binary tree might have a small shallow size that does not take - * up much space itself, but it dominates the rest of the binary tree and - * its retained size is therefore significant (assuming no external - * references into the tree). - * - * The simple, engineered algorithm presented in "A Simple, Fast Dominance - * Algorithm" by Cooper el al[0] is used to find dominators and construct the - * dominator tree. This algorithm runs in O(n^2) time, but is faster in practice - * than alternative algorithms with better theoretical running times, such as - * Lengauer-Tarjan which runs in O(e * log(n)). The big caveat to that statement - * is that Cooper et al found it is faster in practice *on control flow graphs* - * and I'm not convinced that this property also holds on *heap* graphs. That - * said, the implementation of this algorithm is *much* simpler than - * Lengauer-Tarjan and has been found to be fast enough at least for the time - * being. - * - * [0]: http://www.cs.rice.edu/~keith/EMBED/dom.pdf - */ -class JS_PUBLIC_API(DominatorTree) -{ - private: - // Types. - - using PredecessorSets = js::HashMap, - js::SystemAllocPolicy>; - using NodeToIndexMap = js::HashMap, - js::SystemAllocPolicy>; - class DominatedSets; - - public: - class DominatedSetRange; - - /** - * A pointer to an immediately dominated node. - * - * Don't use this type directly; it is no safer than regular pointers. This - * is only for use indirectly with range-based for loops and - * `DominatedSetRange`. - * - * @see JS::ubi::DominatorTree::getDominatedSet - */ - class DominatedNodePtr - { - friend class DominatedSetRange; - - const JS::ubi::Vector& postOrder; - const uint32_t* ptr; - - DominatedNodePtr(const JS::ubi::Vector& postOrder, const uint32_t* ptr) - : postOrder(postOrder) - , ptr(ptr) - { } - - public: - bool operator!=(const DominatedNodePtr& rhs) const { return ptr != rhs.ptr; } - void operator++() { ptr++; } - const Node& operator*() const { return postOrder[*ptr]; } - }; - - /** - * A range of immediately dominated `JS::ubi::Node`s for use with - * range-based for loops. - * - * @see JS::ubi::DominatorTree::getDominatedSet - */ - class DominatedSetRange - { - friend class DominatedSets; - - const JS::ubi::Vector& postOrder; - const uint32_t* beginPtr; - const uint32_t* endPtr; - - DominatedSetRange(JS::ubi::Vector& postOrder, const uint32_t* begin, const uint32_t* end) - : postOrder(postOrder) - , beginPtr(begin) - , endPtr(end) - { - MOZ_ASSERT(begin <= end); - } - - public: - DominatedNodePtr begin() const { - MOZ_ASSERT(beginPtr <= endPtr); - return DominatedNodePtr(postOrder, beginPtr); - } - - DominatedNodePtr end() const { - return DominatedNodePtr(postOrder, endPtr); - } - - size_t length() const { - MOZ_ASSERT(beginPtr <= endPtr); - return endPtr - beginPtr; - } - - /** - * Safely skip ahead `n` dominators in the range, in O(1) time. - * - * Example usage: - * - * mozilla::Maybe range = myDominatorTree.getDominatedSet(myNode); - * if (range.isNothing()) { - * // Handle unknown nodes however you see fit... - * return false; - * } - * - * // Don't care about the first ten, for whatever reason. - * range->skip(10); - * for (const JS::ubi::Node& dominatedNode : *range) { - * // ... - * } - */ - void skip(size_t n) { - beginPtr += n; - if (beginPtr > endPtr) - beginPtr = endPtr; - } - }; - - private: - /** - * The set of all dominated sets in a dominator tree. - * - * Internally stores the sets in a contiguous array, with a side table of - * indices into that contiguous array to denote the start index of each - * individual set. - */ - class DominatedSets - { - JS::ubi::Vector dominated; - JS::ubi::Vector indices; - - DominatedSets(JS::ubi::Vector&& dominated, JS::ubi::Vector&& indices) - : dominated(mozilla::Move(dominated)) - , indices(mozilla::Move(indices)) - { } - - public: - // DominatedSets is not copy-able. - DominatedSets(const DominatedSets& rhs) = delete; - DominatedSets& operator=(const DominatedSets& rhs) = delete; - - // DominatedSets is move-able. - DominatedSets(DominatedSets&& rhs) - : dominated(mozilla::Move(rhs.dominated)) - , indices(mozilla::Move(rhs.indices)) - { - MOZ_ASSERT(this != &rhs, "self-move not allowed"); - } - DominatedSets& operator=(DominatedSets&& rhs) { - this->~DominatedSets(); - new (this) DominatedSets(mozilla::Move(rhs)); - return *this; - } - - /** - * Create the DominatedSets given the mapping of a node index to its - * immediate dominator. Returns `Some` on success, `Nothing` on OOM - * failure. - */ - static mozilla::Maybe Create(const JS::ubi::Vector& doms) { - auto length = doms.length(); - MOZ_ASSERT(length < UINT32_MAX); - - // Create a vector `dominated` holding a flattened set of buckets of - // immediately dominated children nodes, with a lookup table - // `indices` mapping from each node to the beginning of its bucket. - // - // This has three phases: - // - // 1. Iterate over the full set of nodes and count up the size of - // each bucket. These bucket sizes are temporarily stored in the - // `indices` vector. - // - // 2. Convert the `indices` vector to store the cumulative sum of - // the sizes of all buckets before each index, resulting in a - // mapping from node index to one past the end of that node's - // bucket. - // - // 3. Iterate over the full set of nodes again, filling in bucket - // entries from the end of the bucket's range to its - // beginning. This decrements each index as a bucket entry is - // filled in. After having filled in all of a bucket's entries, - // the index points to the start of the bucket. - - JS::ubi::Vector dominated; - JS::ubi::Vector indices; - if (!dominated.growBy(length) || !indices.growBy(length)) - return mozilla::Nothing(); - - // 1 - memset(indices.begin(), 0, length * sizeof(uint32_t)); - for (uint32_t i = 0; i < length; i++) - indices[doms[i]]++; - - // 2 - uint32_t sumOfSizes = 0; - for (uint32_t i = 0; i < length; i++) { - sumOfSizes += indices[i]; - MOZ_ASSERT(sumOfSizes <= length); - indices[i] = sumOfSizes; - } - - // 3 - for (uint32_t i = 0; i < length; i++) { - auto idxOfDom = doms[i]; - indices[idxOfDom]--; - dominated[indices[idxOfDom]] = i; - } - -#ifdef DEBUG - // Assert that our buckets are non-overlapping and don't run off the - // end of the vector. - uint32_t lastIndex = 0; - for (uint32_t i = 0; i < length; i++) { - MOZ_ASSERT(indices[i] >= lastIndex); - MOZ_ASSERT(indices[i] < length); - lastIndex = indices[i]; - } -#endif - - return mozilla::Some(DominatedSets(mozilla::Move(dominated), mozilla::Move(indices))); - } - - /** - * Get the set of nodes immediately dominated by the node at - * `postOrder[nodeIndex]`. - */ - DominatedSetRange dominatedSet(JS::ubi::Vector& postOrder, uint32_t nodeIndex) const { - MOZ_ASSERT(postOrder.length() == indices.length()); - MOZ_ASSERT(nodeIndex < indices.length()); - auto end = nodeIndex == indices.length() - 1 - ? dominated.end() - : &dominated[indices[nodeIndex + 1]]; - return DominatedSetRange(postOrder, &dominated[indices[nodeIndex]], end); - } - }; - - private: - // Data members. - JS::ubi::Vector postOrder; - NodeToIndexMap nodeToPostOrderIndex; - JS::ubi::Vector doms; - DominatedSets dominatedSets; - mozilla::Maybe> retainedSizes; - - private: - // We use `UNDEFINED` as a sentinel value in the `doms` vector to signal - // that we haven't found any dominators for the node at the corresponding - // index in `postOrder` yet. - static const uint32_t UNDEFINED = UINT32_MAX; - - DominatorTree(JS::ubi::Vector&& postOrder, NodeToIndexMap&& nodeToPostOrderIndex, - JS::ubi::Vector&& doms, DominatedSets&& dominatedSets) - : postOrder(mozilla::Move(postOrder)) - , nodeToPostOrderIndex(mozilla::Move(nodeToPostOrderIndex)) - , doms(mozilla::Move(doms)) - , dominatedSets(mozilla::Move(dominatedSets)) - , retainedSizes(mozilla::Nothing()) - { } - - static uint32_t intersect(JS::ubi::Vector& doms, uint32_t finger1, uint32_t finger2) { - while (finger1 != finger2) { - if (finger1 < finger2) - finger1 = doms[finger1]; - else if (finger2 < finger1) - finger2 = doms[finger2]; - } - return finger1; - } - - // Do the post order traversal of the heap graph and populate our - // predecessor sets. - static MOZ_MUST_USE bool doTraversal(JSContext* cx, AutoCheckCannotGC& noGC, const Node& root, - JS::ubi::Vector& postOrder, - PredecessorSets& predecessorSets) { - uint32_t nodeCount = 0; - auto onNode = [&](const Node& node) { - nodeCount++; - if (MOZ_UNLIKELY(nodeCount == UINT32_MAX)) - return false; - return postOrder.append(node); - }; - - auto onEdge = [&](const Node& origin, const Edge& edge) { - auto p = predecessorSets.lookupForAdd(edge.referent); - if (!p) { - mozilla::UniquePtr> set(js_new()); - if (!set || - !set->init() || - !predecessorSets.add(p, edge.referent, mozilla::Move(set))) - { - return false; - } - } - MOZ_ASSERT(p && p->value()); - return p->value()->put(origin); - }; - - PostOrder traversal(cx, noGC); - return traversal.init() && - traversal.addStart(root) && - traversal.traverse(onNode, onEdge); - } - - // Populates the given `map` with an entry for each node to its index in - // `postOrder`. - static MOZ_MUST_USE bool mapNodesToTheirIndices(JS::ubi::Vector& postOrder, - NodeToIndexMap& map) { - MOZ_ASSERT(!map.initialized()); - MOZ_ASSERT(postOrder.length() < UINT32_MAX); - uint32_t length = postOrder.length(); - if (!map.init(length)) - return false; - for (uint32_t i = 0; i < length; i++) - map.putNewInfallible(postOrder[i], i); - return true; - } - - // Convert the Node -> NodeSet predecessorSets to a index -> Vector - // form. - static MOZ_MUST_USE bool convertPredecessorSetsToVectors( - const Node& root, - JS::ubi::Vector& postOrder, - PredecessorSets& predecessorSets, - NodeToIndexMap& nodeToPostOrderIndex, - JS::ubi::Vector>& predecessorVectors) - { - MOZ_ASSERT(postOrder.length() < UINT32_MAX); - uint32_t length = postOrder.length(); - - MOZ_ASSERT(predecessorVectors.length() == 0); - if (!predecessorVectors.growBy(length)) - return false; - - for (uint32_t i = 0; i < length - 1; i++) { - auto& node = postOrder[i]; - MOZ_ASSERT(node != root, - "Only the last node should be root, since this was a post order traversal."); - - auto ptr = predecessorSets.lookup(node); - MOZ_ASSERT(ptr, - "Because this isn't the root, it had better have predecessors, or else how " - "did we even find it."); - - auto& predecessors = ptr->value(); - if (!predecessorVectors[i].reserve(predecessors->count())) - return false; - for (auto range = predecessors->all(); !range.empty(); range.popFront()) { - auto ptr = nodeToPostOrderIndex.lookup(range.front()); - MOZ_ASSERT(ptr); - predecessorVectors[i].infallibleAppend(ptr->value()); - } - } - predecessorSets.finish(); - return true; - } - - // Initialize `doms` such that the immediate dominator of the `root` is the - // `root` itself and all others are `UNDEFINED`. - static MOZ_MUST_USE bool initializeDominators(JS::ubi::Vector& doms, - uint32_t length) { - MOZ_ASSERT(doms.length() == 0); - if (!doms.growByUninitialized(length)) - return false; - doms[length - 1] = length - 1; - for (uint32_t i = 0; i < length - 1; i++) - doms[i] = UNDEFINED; - return true; - } - - void assertSanity() const { - MOZ_ASSERT(postOrder.length() == doms.length()); - MOZ_ASSERT(postOrder.length() == nodeToPostOrderIndex.count()); - MOZ_ASSERT_IF(retainedSizes.isSome(), postOrder.length() == retainedSizes->length()); - } - - MOZ_MUST_USE bool computeRetainedSizes(mozilla::MallocSizeOf mallocSizeOf) { - MOZ_ASSERT(retainedSizes.isNothing()); - auto length = postOrder.length(); - - retainedSizes.emplace(); - if (!retainedSizes->growBy(length)) { - retainedSizes = mozilla::Nothing(); - return false; - } - - // Iterate in forward order so that we know all of a node's children in - // the dominator tree have already had their retained size - // computed. Then we can simply say that the retained size of a node is - // its shallow size (JS::ubi::Node::size) plus the retained sizes of its - // immediate children in the tree. - - for (uint32_t i = 0; i < length; i++) { - auto size = postOrder[i].size(mallocSizeOf); - - for (const auto& dominated : dominatedSets.dominatedSet(postOrder, i)) { - // The root node dominates itself, but shouldn't contribute to - // its own retained size. - if (dominated == postOrder[length - 1]) { - MOZ_ASSERT(i == length - 1); - continue; - } - - auto ptr = nodeToPostOrderIndex.lookup(dominated); - MOZ_ASSERT(ptr); - auto idxOfDominated = ptr->value(); - MOZ_ASSERT(idxOfDominated < i); - size += retainedSizes.ref()[idxOfDominated]; - } - - retainedSizes.ref()[i] = size; - } - - return true; - } - - public: - // DominatorTree is not copy-able. - DominatorTree(const DominatorTree&) = delete; - DominatorTree& operator=(const DominatorTree&) = delete; - - // DominatorTree is move-able. - DominatorTree(DominatorTree&& rhs) - : postOrder(mozilla::Move(rhs.postOrder)) - , nodeToPostOrderIndex(mozilla::Move(rhs.nodeToPostOrderIndex)) - , doms(mozilla::Move(rhs.doms)) - , dominatedSets(mozilla::Move(rhs.dominatedSets)) - , retainedSizes(mozilla::Move(rhs.retainedSizes)) - { - MOZ_ASSERT(this != &rhs, "self-move is not allowed"); - } - DominatorTree& operator=(DominatorTree&& rhs) { - this->~DominatorTree(); - new (this) DominatorTree(mozilla::Move(rhs)); - return *this; - } - - /** - * Construct a `DominatorTree` of the heap graph visible from `root`. The - * `root` is also used as the root of the resulting dominator tree. - * - * The resulting `DominatorTree` instance must not outlive the - * `JS::ubi::Node` graph it was constructed from. - * - * - For `JS::ubi::Node` graphs backed by the live heap graph, this means - * that the `DominatorTree`'s lifetime _must_ be contained within the - * scope of the provided `AutoCheckCannotGC` reference because a GC will - * invalidate the nodes. - * - * - For `JS::ubi::Node` graphs backed by some other offline structure - * provided by the embedder, the resulting `DominatorTree`'s lifetime is - * bounded by that offline structure's lifetime. - * - * In practice, this means that within SpiderMonkey we must treat - * `DominatorTree` as if it were backed by the live heap graph and trust - * that embedders with knowledge of the graph's implementation will do the - * Right Thing. - * - * Returns `mozilla::Nothing()` on OOM failure. It is the caller's - * responsibility to handle and report the OOM. - */ - static mozilla::Maybe - Create(JSContext* cx, AutoCheckCannotGC& noGC, const Node& root) { - JS::ubi::Vector postOrder; - PredecessorSets predecessorSets; - if (!predecessorSets.init() || !doTraversal(cx, noGC, root, postOrder, predecessorSets)) - return mozilla::Nothing(); - - MOZ_ASSERT(postOrder.length() < UINT32_MAX); - uint32_t length = postOrder.length(); - MOZ_ASSERT(postOrder[length - 1] == root); - - // From here on out we wish to avoid hash table lookups, and we use - // indices into `postOrder` instead of actual nodes wherever - // possible. This greatly improves the performance of this - // implementation, but we have to pay a little bit of upfront cost to - // convert our data structures to play along first. - - NodeToIndexMap nodeToPostOrderIndex; - if (!mapNodesToTheirIndices(postOrder, nodeToPostOrderIndex)) - return mozilla::Nothing(); - - JS::ubi::Vector> predecessorVectors; - if (!convertPredecessorSetsToVectors(root, postOrder, predecessorSets, nodeToPostOrderIndex, - predecessorVectors)) - return mozilla::Nothing(); - - JS::ubi::Vector doms; - if (!initializeDominators(doms, length)) - return mozilla::Nothing(); - - bool changed = true; - while (changed) { - changed = false; - - // Iterate over the non-root nodes in reverse post order. - for (uint32_t indexPlusOne = length - 1; indexPlusOne > 0; indexPlusOne--) { - MOZ_ASSERT(postOrder[indexPlusOne - 1] != root); - - // Take the intersection of every predecessor's dominator set; - // that is the current best guess at the immediate dominator for - // this node. - - uint32_t newIDomIdx = UNDEFINED; - - auto& predecessors = predecessorVectors[indexPlusOne - 1]; - auto range = predecessors.all(); - for ( ; !range.empty(); range.popFront()) { - auto idx = range.front(); - if (doms[idx] != UNDEFINED) { - newIDomIdx = idx; - break; - } - } - - MOZ_ASSERT(newIDomIdx != UNDEFINED, - "Because the root is initialized to dominate itself and is the first " - "node in every path, there must exist a predecessor to this node that " - "also has a dominator."); - - for ( ; !range.empty(); range.popFront()) { - auto idx = range.front(); - if (doms[idx] != UNDEFINED) - newIDomIdx = intersect(doms, newIDomIdx, idx); - } - - // If the immediate dominator changed, we will have to do - // another pass of the outer while loop to continue the forward - // dataflow. - if (newIDomIdx != doms[indexPlusOne - 1]) { - doms[indexPlusOne - 1] = newIDomIdx; - changed = true; - } - } - } - - auto maybeDominatedSets = DominatedSets::Create(doms); - if (maybeDominatedSets.isNothing()) - return mozilla::Nothing(); - - return mozilla::Some(DominatorTree(mozilla::Move(postOrder), - mozilla::Move(nodeToPostOrderIndex), - mozilla::Move(doms), - mozilla::Move(*maybeDominatedSets))); - } - - /** - * Get the root node for this dominator tree. - */ - const Node& root() const { - return postOrder[postOrder.length() - 1]; - } - - /** - * Return the immediate dominator of the given `node`. If `node` was not - * reachable from the `root` that this dominator tree was constructed from, - * then return the null `JS::ubi::Node`. - */ - Node getImmediateDominator(const Node& node) const { - assertSanity(); - auto ptr = nodeToPostOrderIndex.lookup(node); - if (!ptr) - return Node(); - - auto idx = ptr->value(); - MOZ_ASSERT(idx < postOrder.length()); - return postOrder[doms[idx]]; - } - - /** - * Get the set of nodes immediately dominated by the given `node`. If `node` - * is not a member of this dominator tree, return `Nothing`. - * - * Example usage: - * - * mozilla::Maybe range = myDominatorTree.getDominatedSet(myNode); - * if (range.isNothing()) { - * // Handle unknown node however you see fit... - * return false; - * } - * - * for (const JS::ubi::Node& dominatedNode : *range) { - * // Do something with each immediately dominated node... - * } - */ - mozilla::Maybe getDominatedSet(const Node& node) { - assertSanity(); - auto ptr = nodeToPostOrderIndex.lookup(node); - if (!ptr) - return mozilla::Nothing(); - - auto idx = ptr->value(); - MOZ_ASSERT(idx < postOrder.length()); - return mozilla::Some(dominatedSets.dominatedSet(postOrder, idx)); - } - - /** - * Get the retained size of the given `node`. The size is placed in - * `outSize`, or 0 if `node` is not a member of the dominator tree. Returns - * false on OOM failure, leaving `outSize` unchanged. - */ - MOZ_MUST_USE bool getRetainedSize(const Node& node, mozilla::MallocSizeOf mallocSizeOf, - Node::Size& outSize) { - assertSanity(); - auto ptr = nodeToPostOrderIndex.lookup(node); - if (!ptr) { - outSize = 0; - return true; - } - - if (retainedSizes.isNothing() && !computeRetainedSizes(mallocSizeOf)) - return false; - - auto idx = ptr->value(); - MOZ_ASSERT(idx < postOrder.length()); - outSize = retainedSizes.ref()[idx]; - return true; - } -}; - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeDominatorTree_h diff --git a/ios/include/spidermonkey/js/UbiNodePostOrder.h b/ios/include/spidermonkey/js/UbiNodePostOrder.h deleted file mode 100644 index a5042677..00000000 --- a/ios/include/spidermonkey/js/UbiNodePostOrder.h +++ /dev/null @@ -1,191 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodePostOrder_h -#define js_UbiNodePostOrder_h - -#include "mozilla/Attributes.h" -#include "mozilla/Maybe.h" -#include "mozilla/Move.h" - -#include "jsalloc.h" - -#include "js/UbiNode.h" -#include "js/Utility.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -/** - * A post-order depth-first traversal of `ubi::Node` graphs. - * - * No GC may occur while an instance of `PostOrder` is live. - * - * The `NodeVisitor` type provided to `PostOrder::traverse` must have the - * following member: - * - * bool operator()(Node& node) - * - * The node visitor method. This method is called once for each `node` - * reachable from the start set in post-order. - * - * This visitor function should return true on success, or false if an error - * occurs. A false return value terminates the traversal immediately, and - * causes `PostOrder::traverse` to return false. - * - * The `EdgeVisitor` type provided to `PostOrder::traverse` must have the - * following member: - * - * bool operator()(Node& origin, Edge& edge) - * - * The edge visitor method. This method is called once for each outgoing - * `edge` from `origin` that is reachable from the start set. - * - * NB: UNLIKE NODES, THERE IS NO GUARANTEED ORDER IN WHICH EDGES AND THEIR - * ORIGINS ARE VISITED! - * - * This visitor function should return true on success, or false if an error - * occurs. A false return value terminates the traversal immediately, and - * causes `PostOrder::traverse` to return false. - */ -struct PostOrder { - private: - struct OriginAndEdges { - Node origin; - EdgeVector edges; - - OriginAndEdges(const Node& node, EdgeVector&& edges) - : origin(node) - , edges(mozilla::Move(edges)) - { } - - OriginAndEdges(const OriginAndEdges& rhs) = delete; - OriginAndEdges& operator=(const OriginAndEdges& rhs) = delete; - - OriginAndEdges(OriginAndEdges&& rhs) - : origin(rhs.origin) - , edges(mozilla::Move(rhs.edges)) - { - MOZ_ASSERT(&rhs != this, "self-move disallowed"); - } - - OriginAndEdges& operator=(OriginAndEdges&& rhs) { - this->~OriginAndEdges(); - new (this) OriginAndEdges(mozilla::Move(rhs)); - return *this; - } - }; - - using Stack = js::Vector; - using Set = js::HashSet, js::SystemAllocPolicy>; - - JSContext* cx; - Set seen; - Stack stack; -#ifdef DEBUG - bool traversed; -#endif - - private: - MOZ_MUST_USE bool fillEdgesFromRange(EdgeVector& edges, js::UniquePtr& range) { - MOZ_ASSERT(range); - for ( ; !range->empty(); range->popFront()) { - if (!edges.append(mozilla::Move(range->front()))) - return false; - } - return true; - } - - MOZ_MUST_USE bool pushForTraversing(const Node& node) { - EdgeVector edges; - auto range = node.edges(cx, /* wantNames */ false); - return range && - fillEdgesFromRange(edges, range) && - stack.append(OriginAndEdges(node, mozilla::Move(edges))); - } - - - public: - // Construct a post-order traversal object. - // - // The traversal asserts that no GC happens in its runtime during its - // lifetime via the `AutoCheckCannotGC&` parameter. We do nothing with it, - // other than require it to exist with a lifetime that encloses our own. - PostOrder(JSContext* cx, AutoCheckCannotGC&) - : cx(cx) - , seen() - , stack() -#ifdef DEBUG - , traversed(false) -#endif - { } - - // Initialize this traversal object. Return false on OOM. - MOZ_MUST_USE bool init() { return seen.init(); } - - // Add `node` as a starting point for the traversal. You may add - // as many starting points as you like. Returns false on OOM. - MOZ_MUST_USE bool addStart(const Node& node) { - if (!seen.put(node)) - return false; - return pushForTraversing(node); - } - - // Traverse the graph in post-order, starting with the set of nodes passed - // to `addStart` and applying `onNode::operator()` for each node in the - // graph and `onEdge::operator()` for each edge in the graph, as described - // above. - // - // This should be called only once per instance of this class. - // - // Return false on OOM or error return from `onNode::operator()` or - // `onEdge::operator()`. - template - MOZ_MUST_USE bool traverse(NodeVisitor onNode, EdgeVisitor onEdge) { -#ifdef DEBUG - MOZ_ASSERT(!traversed, "Can only traverse() once!"); - traversed = true; -#endif - - while (!stack.empty()) { - auto& origin = stack.back().origin; - auto& edges = stack.back().edges; - - if (edges.empty()) { - if (!onNode(origin)) - return false; - stack.popBack(); - continue; - } - - Edge edge = mozilla::Move(edges.back()); - edges.popBack(); - - if (!onEdge(origin, edge)) - return false; - - auto ptr = seen.lookupForAdd(edge.referent); - // We've already seen this node, don't follow its edges. - if (ptr) - continue; - - // Mark the referent as seen and follow its edges. - if (!seen.add(ptr, edge.referent) || - !pushForTraversing(edge.referent)) - { - return false; - } - } - - return true; - } -}; - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodePostOrder_h diff --git a/ios/include/spidermonkey/js/UbiNodeShortestPaths.h b/ios/include/spidermonkey/js/UbiNodeShortestPaths.h deleted file mode 100644 index edd5aebb..00000000 --- a/ios/include/spidermonkey/js/UbiNodeShortestPaths.h +++ /dev/null @@ -1,350 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeShortestPaths_h -#define js_UbiNodeShortestPaths_h - -#include "mozilla/Attributes.h" -#include "mozilla/Maybe.h" -#include "mozilla/Move.h" - -#include "jsalloc.h" - -#include "js/UbiNodeBreadthFirst.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -/** - * A back edge along a path in the heap graph. - */ -struct JS_PUBLIC_API(BackEdge) -{ - private: - Node predecessor_; - EdgeName name_; - - public: - using Ptr = mozilla::UniquePtr>; - - BackEdge() : predecessor_(), name_(nullptr) { } - - MOZ_MUST_USE bool init(const Node& predecessor, Edge& edge) { - MOZ_ASSERT(!predecessor_); - MOZ_ASSERT(!name_); - - predecessor_ = predecessor; - name_ = mozilla::Move(edge.name); - return true; - } - - BackEdge(const BackEdge&) = delete; - BackEdge& operator=(const BackEdge&) = delete; - - BackEdge(BackEdge&& rhs) - : predecessor_(rhs.predecessor_) - , name_(mozilla::Move(rhs.name_)) - { - MOZ_ASSERT(&rhs != this); - } - - BackEdge& operator=(BackEdge&& rhs) { - this->~BackEdge(); - new(this) BackEdge(Move(rhs)); - return *this; - } - - Ptr clone() const; - - const EdgeName& name() const { return name_; } - EdgeName& name() { return name_; } - - const JS::ubi::Node& predecessor() const { return predecessor_; } -}; - -/** - * A path is a series of back edges from which we discovered a target node. - */ -using Path = JS::ubi::Vector; - -/** - * The `JS::ubi::ShortestPaths` type represents a collection of up to N shortest - * retaining paths for each of a target set of nodes, starting from the same - * root node. - */ -struct JS_PUBLIC_API(ShortestPaths) -{ - private: - // Types, type aliases, and data members. - - using BackEdgeVector = JS::ubi::Vector; - using NodeToBackEdgeVectorMap = js::HashMap, - js::SystemAllocPolicy>; - - struct Handler; - using Traversal = BreadthFirst; - - /** - * A `JS::ubi::BreadthFirst` traversal handler that records back edges for - * how we reached each node, allowing us to reconstruct the shortest - * retaining paths after the traversal. - */ - struct Handler - { - using NodeData = BackEdge; - - ShortestPaths& shortestPaths; - size_t totalMaxPathsToRecord; - size_t totalPathsRecorded; - - explicit Handler(ShortestPaths& shortestPaths) - : shortestPaths(shortestPaths) - , totalMaxPathsToRecord(shortestPaths.targets_.count() * shortestPaths.maxNumPaths_) - , totalPathsRecorded(0) - { - } - - bool - operator()(Traversal& traversal, JS::ubi::Node origin, JS::ubi::Edge& edge, - BackEdge* back, bool first) - { - MOZ_ASSERT(back); - MOZ_ASSERT(origin == shortestPaths.root_ || traversal.visited.has(origin)); - MOZ_ASSERT(totalPathsRecorded < totalMaxPathsToRecord); - - if (first && !back->init(origin, edge)) - return false; - - if (!shortestPaths.targets_.has(edge.referent)) - return true; - - // If `first` is true, then we moved the edge's name into `back` in - // the above call to `init`. So clone that back edge to get the - // correct edge name. If `first` is not true, then our edge name is - // still in `edge`. This accounts for the asymmetry between - // `back->clone()` in the first branch, and the `init` call in the - // second branch. - - if (first) { - BackEdgeVector paths; - if (!paths.reserve(shortestPaths.maxNumPaths_)) - return false; - auto cloned = back->clone(); - if (!cloned) - return false; - paths.infallibleAppend(mozilla::Move(cloned)); - if (!shortestPaths.paths_.putNew(edge.referent, mozilla::Move(paths))) - return false; - totalPathsRecorded++; - } else { - auto ptr = shortestPaths.paths_.lookup(edge.referent); - MOZ_ASSERT(ptr, - "This isn't the first time we have seen the target node `edge.referent`. " - "We should have inserted it into shortestPaths.paths_ the first time we " - "saw it."); - - if (ptr->value().length() < shortestPaths.maxNumPaths_) { - BackEdge::Ptr thisBackEdge(js_new()); - if (!thisBackEdge || !thisBackEdge->init(origin, edge)) - return false; - ptr->value().infallibleAppend(mozilla::Move(thisBackEdge)); - totalPathsRecorded++; - } - } - - MOZ_ASSERT(totalPathsRecorded <= totalMaxPathsToRecord); - if (totalPathsRecorded == totalMaxPathsToRecord) - traversal.stop(); - - return true; - } - - }; - - // The maximum number of paths to record for each node. - uint32_t maxNumPaths_; - - // The root node we are starting the search from. - Node root_; - - // The set of nodes we are searching for paths to. - NodeSet targets_; - - // The resulting paths. - NodeToBackEdgeVectorMap paths_; - - // Need to keep alive the traversal's back edges so we can walk them later - // when the traversal is over when recreating the shortest paths. - Traversal::NodeMap backEdges_; - - private: - // Private methods. - - ShortestPaths(uint32_t maxNumPaths, const Node& root, NodeSet&& targets) - : maxNumPaths_(maxNumPaths) - , root_(root) - , targets_(mozilla::Move(targets)) - , paths_() - , backEdges_() - { - MOZ_ASSERT(maxNumPaths_ > 0); - MOZ_ASSERT(root_); - MOZ_ASSERT(targets_.initialized()); - } - - bool initialized() const { - return targets_.initialized() && - paths_.initialized() && - backEdges_.initialized(); - } - - public: - // Public methods. - - ShortestPaths(ShortestPaths&& rhs) - : maxNumPaths_(rhs.maxNumPaths_) - , root_(rhs.root_) - , targets_(mozilla::Move(rhs.targets_)) - , paths_(mozilla::Move(rhs.paths_)) - , backEdges_(mozilla::Move(rhs.backEdges_)) - { - MOZ_ASSERT(this != &rhs, "self-move is not allowed"); - } - - ShortestPaths& operator=(ShortestPaths&& rhs) { - this->~ShortestPaths(); - new (this) ShortestPaths(mozilla::Move(rhs)); - return *this; - } - - ShortestPaths(const ShortestPaths&) = delete; - ShortestPaths& operator=(const ShortestPaths&) = delete; - - /** - * Construct a new `JS::ubi::ShortestPaths`, finding up to `maxNumPaths` - * shortest retaining paths for each target node in `targets` starting from - * `root`. - * - * The resulting `ShortestPaths` instance must not outlive the - * `JS::ubi::Node` graph it was constructed from. - * - * - For `JS::ubi::Node` graphs backed by the live heap graph, this means - * that the `ShortestPaths`'s lifetime _must_ be contained within the - * scope of the provided `AutoCheckCannotGC` reference because a GC will - * invalidate the nodes. - * - * - For `JS::ubi::Node` graphs backed by some other offline structure - * provided by the embedder, the resulting `ShortestPaths`'s lifetime is - * bounded by that offline structure's lifetime. - * - * Returns `mozilla::Nothing()` on OOM failure. It is the caller's - * responsibility to handle and report the OOM. - */ - static mozilla::Maybe - Create(JSContext* cx, AutoCheckCannotGC& noGC, uint32_t maxNumPaths, const Node& root, NodeSet&& targets) { - MOZ_ASSERT(targets.count() > 0); - MOZ_ASSERT(maxNumPaths > 0); - - size_t count = targets.count(); - ShortestPaths paths(maxNumPaths, root, mozilla::Move(targets)); - if (!paths.paths_.init(count)) - return mozilla::Nothing(); - - Handler handler(paths); - Traversal traversal(cx, handler, noGC); - traversal.wantNames = true; - if (!traversal.init() || !traversal.addStart(root) || !traversal.traverse()) - return mozilla::Nothing(); - - // Take ownership of the back edges we created while traversing the - // graph so that we can follow them from `paths_` and don't - // use-after-free. - paths.backEdges_ = mozilla::Move(traversal.visited); - - MOZ_ASSERT(paths.initialized()); - return mozilla::Some(mozilla::Move(paths)); - } - - /** - * Get a range that iterates over each target node we searched for retaining - * paths for. The returned range must not outlive the `ShortestPaths` - * instance. - */ - NodeSet::Range eachTarget() const { - MOZ_ASSERT(initialized()); - return targets_.all(); - } - - /** - * Invoke the provided functor/lambda/callable once for each retaining path - * discovered for `target`. The `func` is passed a single `JS::ubi::Path&` - * argument, which contains each edge along the path ordered starting from - * the root and ending at the target, and must not outlive the scope of the - * call. - * - * Note that it is possible that we did not find any paths from the root to - * the given target, in which case `func` will not be invoked. - */ - template - MOZ_MUST_USE bool forEachPath(const Node& target, Func func) { - MOZ_ASSERT(initialized()); - MOZ_ASSERT(targets_.has(target)); - - auto ptr = paths_.lookup(target); - - // We didn't find any paths to this target, so nothing to do here. - if (!ptr) - return true; - - MOZ_ASSERT(ptr->value().length() <= maxNumPaths_); - - Path path; - for (const auto& backEdge : ptr->value()) { - path.clear(); - - if (!path.append(backEdge.get())) - return false; - - Node here = backEdge->predecessor(); - MOZ_ASSERT(here); - - while (here != root_) { - auto p = backEdges_.lookup(here); - MOZ_ASSERT(p); - if (!path.append(&p->value())) - return false; - here = p->value().predecessor(); - MOZ_ASSERT(here); - } - - path.reverse(); - - if (!func(path)) - return false; - } - - return true; - } -}; - -#ifdef DEBUG -// A helper function to dump the first `maxNumPaths` shortest retaining paths to -// `node` from the GC roots. Useful when GC things you expect to have been -// reclaimed by the collector haven't been! -// -// Usage: -// -// JSObject* foo = ...; -// JS::ubi::dumpPaths(rt, JS::ubi::Node(foo)); -JS_PUBLIC_API(void) -dumpPaths(JSRuntime* rt, Node node, uint32_t maxNumPaths = 10); -#endif - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeShortestPaths_h diff --git a/ios/include/spidermonkey/js/UniquePtr.h b/ios/include/spidermonkey/js/UniquePtr.h deleted file mode 100644 index 0236bab4..00000000 --- a/ios/include/spidermonkey/js/UniquePtr.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UniquePtr_h -#define js_UniquePtr_h - -#include "mozilla/UniquePtr.h" - -#include "js/Utility.h" - -namespace js { - -// Replacement for mozilla::UniquePtr that defaults to js::DefaultDelete. -template > -using UniquePtr = mozilla::UniquePtr; - -namespace detail { - -template -struct UniqueSelector -{ - typedef UniquePtr SingleObject; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr UnknownBound; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr KnownBound; -}; - -} // namespace detail - -// Replacement for mozilla::MakeUnique that correctly calls js_new and produces -// a js::UniquePtr. -template -typename detail::UniqueSelector::SingleObject -MakeUnique(Args&&... aArgs) -{ - return UniquePtr(js_new(mozilla::Forward(aArgs)...)); -} - -template -typename detail::UniqueSelector::UnknownBound -MakeUnique(decltype(sizeof(int)) aN) = delete; - -template -typename detail::UniqueSelector::KnownBound -MakeUnique(Args&&... aArgs) = delete; - -} // namespace js - -#endif /* js_UniquePtr_h */ diff --git a/ios/include/spidermonkey/js/Utility.h b/ios/include/spidermonkey/js/Utility.h deleted file mode 100644 index e95e8ecc..00000000 --- a/ios/include/spidermonkey/js/Utility.h +++ /dev/null @@ -1,577 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Utility_h -#define js_Utility_h - -#include "mozilla/Assertions.h" -#include "mozilla/Atomics.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/Move.h" -#include "mozilla/Scoped.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/UniquePtr.h" - -#include -#include - -#ifdef JS_OOM_DO_BACKTRACES -#include -#include -#endif - -#include "jstypes.h" - -/* The public JS engine namespace. */ -namespace JS {} - -/* The mozilla-shared reusable template/utility namespace. */ -namespace mozilla {} - -/* The private JS engine namespace. */ -namespace js {} - -#define JS_STATIC_ASSERT(cond) static_assert(cond, "JS_STATIC_ASSERT") -#define JS_STATIC_ASSERT_IF(cond, expr) MOZ_STATIC_ASSERT_IF(cond, expr, "JS_STATIC_ASSERT_IF") - -extern MOZ_NORETURN MOZ_COLD JS_PUBLIC_API(void) -JS_Assert(const char* s, const char* file, int ln); - -/* - * Custom allocator support for SpiderMonkey - */ -#if defined JS_USE_CUSTOM_ALLOCATOR -# include "jscustomallocator.h" -#else - -namespace js { -namespace oom { - -/* - * To make testing OOM in certain helper threads more effective, - * allow restricting the OOM testing to a certain helper thread - * type. This allows us to fail e.g. in off-thread script parsing - * without causing an OOM in the main thread first. - */ -enum ThreadType { - THREAD_TYPE_NONE = 0, // 0 - THREAD_TYPE_MAIN, // 1 - THREAD_TYPE_ASMJS, // 2 - THREAD_TYPE_ION, // 3 - THREAD_TYPE_PARSE, // 4 - THREAD_TYPE_COMPRESS, // 5 - THREAD_TYPE_GCHELPER, // 6 - THREAD_TYPE_GCPARALLEL, // 7 - THREAD_TYPE_PROMISE_TASK, // 8 - THREAD_TYPE_MAX // Used to check shell function arguments -}; - -/* - * Getter/Setter functions to encapsulate mozilla::ThreadLocal, - * implementation is in jsutil.cpp. - */ -# if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) -extern bool InitThreadType(void); -extern void SetThreadType(ThreadType); -extern JS_PUBLIC_API(uint32_t) GetThreadType(void); -# else -inline bool InitThreadType(void) { return true; } -inline void SetThreadType(ThreadType t) {}; -inline JS_PUBLIC_API(uint32_t) GetThreadType(void) { return 0; } -# endif - -} /* namespace oom */ -} /* namespace js */ - -# if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) - -#ifdef JS_OOM_BREAKPOINT -static MOZ_NEVER_INLINE void js_failedAllocBreakpoint() { asm(""); } -#define JS_OOM_CALL_BP_FUNC() js_failedAllocBreakpoint() -#else -#define JS_OOM_CALL_BP_FUNC() do {} while(0) -#endif - -namespace js { -namespace oom { - -/* - * Out of memory testing support. We provide various testing functions to - * simulate OOM conditions and so we can test that they are handled correctly. - */ - -extern JS_PUBLIC_DATA(uint32_t) targetThread; -extern JS_PUBLIC_DATA(uint64_t) maxAllocations; -extern JS_PUBLIC_DATA(uint64_t) counter; -extern JS_PUBLIC_DATA(bool) failAlways; - -extern void -SimulateOOMAfter(uint64_t allocations, uint32_t thread, bool always); - -extern void -ResetSimulatedOOM(); - -inline bool -IsThreadSimulatingOOM() -{ - return js::oom::targetThread && js::oom::targetThread == js::oom::GetThreadType(); -} - -inline bool -IsSimulatedOOMAllocation() -{ - return IsThreadSimulatingOOM() && - (counter == maxAllocations || (counter > maxAllocations && failAlways)); -} - -inline bool -ShouldFailWithOOM() -{ - if (!IsThreadSimulatingOOM()) - return false; - - counter++; - if (IsSimulatedOOMAllocation()) { - JS_OOM_CALL_BP_FUNC(); - return true; - } - return false; -} - -inline bool -HadSimulatedOOM() { - return counter >= maxAllocations; -} - -} /* namespace oom */ -} /* namespace js */ - -# define JS_OOM_POSSIBLY_FAIL() \ - do { \ - if (js::oom::ShouldFailWithOOM()) \ - return nullptr; \ - } while (0) - -# define JS_OOM_POSSIBLY_FAIL_BOOL() \ - do { \ - if (js::oom::ShouldFailWithOOM()) \ - return false; \ - } while (0) - -# else - -# define JS_OOM_POSSIBLY_FAIL() do {} while(0) -# define JS_OOM_POSSIBLY_FAIL_BOOL() do {} while(0) -namespace js { -namespace oom { -static inline bool IsSimulatedOOMAllocation() { return false; } -static inline bool ShouldFailWithOOM() { return false; } -} /* namespace oom */ -} /* namespace js */ - -# endif /* DEBUG || JS_OOM_BREAKPOINT */ - -namespace js { - -/* Disable OOM testing in sections which are not OOM safe. */ -struct MOZ_RAII AutoEnterOOMUnsafeRegion -{ - MOZ_NORETURN MOZ_COLD void crash(const char* reason); - MOZ_NORETURN MOZ_COLD void crash(size_t size, const char* reason); - - using AnnotateOOMAllocationSizeCallback = void(*)(size_t); - static AnnotateOOMAllocationSizeCallback annotateOOMSizeCallback; - static void setAnnotateOOMAllocationSizeCallback(AnnotateOOMAllocationSizeCallback callback) { - annotateOOMSizeCallback = callback; - } - -#if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) - AutoEnterOOMUnsafeRegion() - : oomEnabled_(oom::IsThreadSimulatingOOM() && oom::maxAllocations != UINT64_MAX), - oomAfter_(0) - { - if (oomEnabled_) { - MOZ_ALWAYS_TRUE(owner_.compareExchange(nullptr, this)); - oomAfter_ = int64_t(oom::maxAllocations) - int64_t(oom::counter); - oom::maxAllocations = UINT64_MAX; - } - } - - ~AutoEnterOOMUnsafeRegion() { - if (oomEnabled_) { - MOZ_ASSERT(oom::maxAllocations == UINT64_MAX); - int64_t maxAllocations = int64_t(oom::counter) + oomAfter_; - MOZ_ASSERT(maxAllocations >= 0, - "alloc count + oom limit exceeds range, your oom limit is probably too large"); - oom::maxAllocations = uint64_t(maxAllocations); - MOZ_ALWAYS_TRUE(owner_.compareExchange(this, nullptr)); - } - } - - private: - // Used to catch concurrent use from other threads. - static mozilla::Atomic owner_; - - bool oomEnabled_; - int64_t oomAfter_; -#endif -}; - -} /* namespace js */ - -static inline void* js_malloc(size_t bytes) -{ - JS_OOM_POSSIBLY_FAIL(); - return malloc(bytes); -} - -static inline void* js_calloc(size_t bytes) -{ - JS_OOM_POSSIBLY_FAIL(); - return calloc(bytes, 1); -} - -static inline void* js_calloc(size_t nmemb, size_t size) -{ - JS_OOM_POSSIBLY_FAIL(); - return calloc(nmemb, size); -} - -static inline void* js_realloc(void* p, size_t bytes) -{ - // realloc() with zero size is not portable, as some implementations may - // return nullptr on success and free |p| for this. We assume nullptr - // indicates failure and that |p| is still valid. - MOZ_ASSERT(bytes != 0); - - JS_OOM_POSSIBLY_FAIL(); - return realloc(p, bytes); -} - -static inline void js_free(void* p) -{ - free(p); -} - -static inline char* js_strdup(const char* s) -{ - JS_OOM_POSSIBLY_FAIL(); - return strdup(s); -} -#endif/* JS_USE_CUSTOM_ALLOCATOR */ - -#include - -/* - * Low-level memory management in SpiderMonkey: - * - * ** Do not use the standard malloc/free/realloc: SpiderMonkey allows these - * to be redefined (via JS_USE_CUSTOM_ALLOCATOR) and Gecko even #define's - * these symbols. - * - * ** Do not use the builtin C++ operator new and delete: these throw on - * error and we cannot override them not to. - * - * Allocation: - * - * - If the lifetime of the allocation is tied to the lifetime of a GC-thing - * (that is, finalizing the GC-thing will free the allocation), call one of - * the following functions: - * - * JSContext::{malloc_,realloc_,calloc_,new_} - * JSRuntime::{malloc_,realloc_,calloc_,new_} - * - * These functions accumulate the number of bytes allocated which is used as - * part of the GC-triggering heuristic. - * - * The difference between the JSContext and JSRuntime versions is that the - * cx version reports an out-of-memory error on OOM. (This follows from the - * general SpiderMonkey idiom that a JSContext-taking function reports its - * own errors.) - * - * - Otherwise, use js_malloc/js_realloc/js_calloc/js_new - * - * Deallocation: - * - * - Ordinarily, use js_free/js_delete. - * - * - For deallocations during GC finalization, use one of the following - * operations on the FreeOp provided to the finalizer: - * - * FreeOp::{free_,delete_} - * - * The advantage of these operations is that the memory is batched and freed - * on another thread. - */ - -/* - * Given a class which should provide a 'new' method, add - * JS_DECLARE_NEW_METHODS (see js::MallocProvider for an example). - * - * Note: Do not add a ; at the end of a use of JS_DECLARE_NEW_METHODS, - * or the build will break. - */ -#define JS_DECLARE_NEW_METHODS(NEWNAME, ALLOCATOR, QUALIFIERS) \ - template \ - QUALIFIERS T * \ - NEWNAME(Args&&... args) MOZ_HEAP_ALLOCATOR { \ - void* memory = ALLOCATOR(sizeof(T)); \ - return MOZ_LIKELY(memory) \ - ? new(memory) T(mozilla::Forward(args)...) \ - : nullptr; \ - } - -/* - * Given a class which should provide 'make' methods, add - * JS_DECLARE_MAKE_METHODS (see js::MallocProvider for an example). This - * method is functionally the same as JS_DECLARE_NEW_METHODS: it just declares - * methods that return mozilla::UniquePtr instances that will singly-manage - * ownership of the created object. - * - * Note: Do not add a ; at the end of a use of JS_DECLARE_MAKE_METHODS, - * or the build will break. - */ -#define JS_DECLARE_MAKE_METHODS(MAKENAME, NEWNAME, QUALIFIERS)\ - template \ - QUALIFIERS mozilla::UniquePtr> \ - MAKENAME(Args&&... args) MOZ_HEAP_ALLOCATOR { \ - T* ptr = NEWNAME(mozilla::Forward(args)...); \ - return mozilla::UniquePtr>(ptr); \ - } - -JS_DECLARE_NEW_METHODS(js_new, js_malloc, static MOZ_ALWAYS_INLINE) - -namespace js { - -/* - * Calculate the number of bytes needed to allocate |numElems| contiguous - * instances of type |T|. Return false if the calculation overflowed. - */ -template -MOZ_MUST_USE inline bool -CalculateAllocSize(size_t numElems, size_t* bytesOut) -{ - *bytesOut = numElems * sizeof(T); - return (numElems & mozilla::tl::MulOverflowMask::value) == 0; -} - -/* - * Calculate the number of bytes needed to allocate a single instance of type - * |T| followed by |numExtra| contiguous instances of type |Extra|. Return - * false if the calculation overflowed. - */ -template -MOZ_MUST_USE inline bool -CalculateAllocSizeWithExtra(size_t numExtra, size_t* bytesOut) -{ - *bytesOut = sizeof(T) + numExtra * sizeof(Extra); - return (numExtra & mozilla::tl::MulOverflowMask::value) == 0 && - *bytesOut >= sizeof(T); -} - -} /* namespace js */ - -template -static MOZ_ALWAYS_INLINE void -js_delete(const T* p) -{ - if (p) { - p->~T(); - js_free(const_cast(p)); - } -} - -template -static MOZ_ALWAYS_INLINE void -js_delete_poison(const T* p) -{ - if (p) { - p->~T(); - memset(const_cast(p), 0x3B, sizeof(T)); - js_free(const_cast(p)); - } -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_malloc() -{ - return static_cast(js_malloc(sizeof(T))); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_calloc() -{ - return static_cast(js_calloc(sizeof(T))); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_malloc(size_t numElems) -{ - size_t bytes; - if (MOZ_UNLIKELY(!js::CalculateAllocSize(numElems, &bytes))) - return nullptr; - return static_cast(js_malloc(bytes)); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_calloc(size_t numElems) -{ - size_t bytes; - if (MOZ_UNLIKELY(!js::CalculateAllocSize(numElems, &bytes))) - return nullptr; - return static_cast(js_calloc(bytes)); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_realloc(T* prior, size_t oldSize, size_t newSize) -{ - MOZ_ASSERT(!(oldSize & mozilla::tl::MulOverflowMask::value)); - size_t bytes; - if (MOZ_UNLIKELY(!js::CalculateAllocSize(newSize, &bytes))) - return nullptr; - return static_cast(js_realloc(prior, bytes)); -} - -namespace js { - -template -struct ScopedFreePtrTraits -{ - typedef T* type; - static T* empty() { return nullptr; } - static void release(T* ptr) { js_free(ptr); } -}; -SCOPED_TEMPLATE(ScopedJSFreePtr, ScopedFreePtrTraits) - -template -struct ScopedDeletePtrTraits : public ScopedFreePtrTraits -{ - static void release(T* ptr) { js_delete(ptr); } -}; -SCOPED_TEMPLATE(ScopedJSDeletePtr, ScopedDeletePtrTraits) - -template -struct ScopedReleasePtrTraits : public ScopedFreePtrTraits -{ - static void release(T* ptr) { if (ptr) ptr->release(); } -}; -SCOPED_TEMPLATE(ScopedReleasePtr, ScopedReleasePtrTraits) - -} /* namespace js */ - -namespace JS { - -template -struct DeletePolicy -{ - constexpr DeletePolicy() {} - - template - MOZ_IMPLICIT DeletePolicy(DeletePolicy other, - typename mozilla::EnableIf::value, - int>::Type dummy = 0) - {} - - void operator()(const T* ptr) { - js_delete(const_cast(ptr)); - } -}; - -struct FreePolicy -{ - void operator()(const void* ptr) { - js_free(const_cast(ptr)); - } -}; - -typedef mozilla::UniquePtr UniqueChars; -typedef mozilla::UniquePtr UniqueTwoByteChars; - -} // namespace JS - -namespace js { - -/* Integral types for all hash functions. */ -typedef uint32_t HashNumber; -const unsigned HashNumberSizeBits = 32; - -namespace detail { - -/* - * Given a raw hash code, h, return a number that can be used to select a hash - * bucket. - * - * This function aims to produce as uniform an output distribution as possible, - * especially in the most significant (leftmost) bits, even though the input - * distribution may be highly nonrandom, given the constraints that this must - * be deterministic and quick to compute. - * - * Since the leftmost bits of the result are best, the hash bucket index is - * computed by doing ScrambleHashCode(h) / (2^32/N) or the equivalent - * right-shift, not ScrambleHashCode(h) % N or the equivalent bit-mask. - * - * FIXME: OrderedHashTable uses a bit-mask; see bug 775896. - */ -inline HashNumber -ScrambleHashCode(HashNumber h) -{ - /* - * Simply returning h would not cause any hash tables to produce wrong - * answers. But it can produce pathologically bad performance: The caller - * right-shifts the result, keeping only the highest bits. The high bits of - * hash codes are very often completely entropy-free. (So are the lowest - * bits.) - * - * So we use Fibonacci hashing, as described in Knuth, The Art of Computer - * Programming, 6.4. This mixes all the bits of the input hash code h. - * - * The value of goldenRatio is taken from the hex - * expansion of the golden ratio, which starts 1.9E3779B9.... - * This value is especially good if values with consecutive hash codes - * are stored in a hash table; see Knuth for details. - */ - static const HashNumber goldenRatio = 0x9E3779B9U; - return h * goldenRatio; -} - -} /* namespace detail */ - -} /* namespace js */ - -/* sixgill annotation defines */ -#ifndef HAVE_STATIC_ANNOTATIONS -# define HAVE_STATIC_ANNOTATIONS -# ifdef XGILL_PLUGIN -# define STATIC_PRECONDITION(COND) __attribute__((precondition(#COND))) -# define STATIC_PRECONDITION_ASSUME(COND) __attribute__((precondition_assume(#COND))) -# define STATIC_POSTCONDITION(COND) __attribute__((postcondition(#COND))) -# define STATIC_POSTCONDITION_ASSUME(COND) __attribute__((postcondition_assume(#COND))) -# define STATIC_INVARIANT(COND) __attribute__((invariant(#COND))) -# define STATIC_INVARIANT_ASSUME(COND) __attribute__((invariant_assume(#COND))) -# define STATIC_ASSUME(COND) \ - JS_BEGIN_MACRO \ - __attribute__((assume_static(#COND), unused)) \ - int STATIC_PASTE1(assume_static_, __COUNTER__); \ - JS_END_MACRO -# else /* XGILL_PLUGIN */ -# define STATIC_PRECONDITION(COND) /* nothing */ -# define STATIC_PRECONDITION_ASSUME(COND) /* nothing */ -# define STATIC_POSTCONDITION(COND) /* nothing */ -# define STATIC_POSTCONDITION_ASSUME(COND) /* nothing */ -# define STATIC_INVARIANT(COND) /* nothing */ -# define STATIC_INVARIANT_ASSUME(COND) /* nothing */ -# define STATIC_ASSUME(COND) JS_BEGIN_MACRO /* nothing */ JS_END_MACRO -# endif /* XGILL_PLUGIN */ -# define STATIC_SKIP_INFERENCE STATIC_INVARIANT(skip_inference()) -#endif /* HAVE_STATIC_ANNOTATIONS */ - -#endif /* js_Utility_h */ diff --git a/ios/include/spidermonkey/js/Value.h b/ios/include/spidermonkey/js/Value.h deleted file mode 100644 index 00fdad58..00000000 --- a/ios/include/spidermonkey/js/Value.h +++ /dev/null @@ -1,1509 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JS::Value implementation. */ - -#ifndef js_Value_h -#define js_Value_h - -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/Likely.h" - -#include /* for std::numeric_limits */ - -#include "js-config.h" -#include "jstypes.h" - -#include "js/GCAPI.h" -#include "js/RootingAPI.h" -#include "js/Utility.h" - -namespace JS { class Value; } - -/* JS::Value can store a full int32_t. */ -#define JSVAL_INT_BITS 32 -#define JSVAL_INT_MIN ((int32_t)0x80000000) -#define JSVAL_INT_MAX ((int32_t)0x7fffffff) - -#if defined(JS_PUNBOX64) -# define JSVAL_TAG_SHIFT 47 -#endif - -// Use enums so that printing a JS::Value in the debugger shows nice -// symbolic type tags. - -#if defined(_MSC_VER) -# define JS_ENUM_HEADER(id, type) enum id : type -# define JS_ENUM_FOOTER(id) -#else -# define JS_ENUM_HEADER(id, type) enum id -# define JS_ENUM_FOOTER(id) __attribute__((packed)) -#endif - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueType, uint8_t) -{ - JSVAL_TYPE_DOUBLE = 0x00, - JSVAL_TYPE_INT32 = 0x01, - JSVAL_TYPE_UNDEFINED = 0x02, - JSVAL_TYPE_BOOLEAN = 0x03, - JSVAL_TYPE_MAGIC = 0x04, - JSVAL_TYPE_STRING = 0x05, - JSVAL_TYPE_SYMBOL = 0x06, - JSVAL_TYPE_PRIVATE_GCTHING = 0x07, - JSVAL_TYPE_NULL = 0x08, - JSVAL_TYPE_OBJECT = 0x0c, - - /* These never appear in a jsval; they are only provided as an out-of-band value. */ - JSVAL_TYPE_UNKNOWN = 0x20, - JSVAL_TYPE_MISSING = 0x21 -} JS_ENUM_FOOTER(JSValueType); - -static_assert(sizeof(JSValueType) == 1, - "compiler typed enum support is apparently buggy"); - -#if defined(JS_NUNBOX32) - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueTag, uint32_t) -{ - JSVAL_TAG_CLEAR = 0xFFFFFF80, - JSVAL_TAG_INT32 = JSVAL_TAG_CLEAR | JSVAL_TYPE_INT32, - JSVAL_TAG_UNDEFINED = JSVAL_TAG_CLEAR | JSVAL_TYPE_UNDEFINED, - JSVAL_TAG_STRING = JSVAL_TAG_CLEAR | JSVAL_TYPE_STRING, - JSVAL_TAG_SYMBOL = JSVAL_TAG_CLEAR | JSVAL_TYPE_SYMBOL, - JSVAL_TAG_BOOLEAN = JSVAL_TAG_CLEAR | JSVAL_TYPE_BOOLEAN, - JSVAL_TAG_MAGIC = JSVAL_TAG_CLEAR | JSVAL_TYPE_MAGIC, - JSVAL_TAG_NULL = JSVAL_TAG_CLEAR | JSVAL_TYPE_NULL, - JSVAL_TAG_OBJECT = JSVAL_TAG_CLEAR | JSVAL_TYPE_OBJECT, - JSVAL_TAG_PRIVATE_GCTHING = JSVAL_TAG_CLEAR | JSVAL_TYPE_PRIVATE_GCTHING -} JS_ENUM_FOOTER(JSValueTag); - -static_assert(sizeof(JSValueTag) == sizeof(uint32_t), - "compiler typed enum support is apparently buggy"); - -#elif defined(JS_PUNBOX64) - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueTag, uint32_t) -{ - JSVAL_TAG_MAX_DOUBLE = 0x1FFF0, - JSVAL_TAG_INT32 = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_INT32, - JSVAL_TAG_UNDEFINED = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_UNDEFINED, - JSVAL_TAG_STRING = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_STRING, - JSVAL_TAG_SYMBOL = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_SYMBOL, - JSVAL_TAG_BOOLEAN = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_BOOLEAN, - JSVAL_TAG_MAGIC = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_MAGIC, - JSVAL_TAG_NULL = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_NULL, - JSVAL_TAG_OBJECT = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_OBJECT, - JSVAL_TAG_PRIVATE_GCTHING = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_PRIVATE_GCTHING -} JS_ENUM_FOOTER(JSValueTag); - -static_assert(sizeof(JSValueTag) == sizeof(uint32_t), - "compiler typed enum support is apparently buggy"); - -JS_ENUM_HEADER(JSValueShiftedTag, uint64_t) -{ - JSVAL_SHIFTED_TAG_MAX_DOUBLE = ((((uint64_t)JSVAL_TAG_MAX_DOUBLE) << JSVAL_TAG_SHIFT) | 0xFFFFFFFF), - JSVAL_SHIFTED_TAG_INT32 = (((uint64_t)JSVAL_TAG_INT32) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_UNDEFINED = (((uint64_t)JSVAL_TAG_UNDEFINED) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_STRING = (((uint64_t)JSVAL_TAG_STRING) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_SYMBOL = (((uint64_t)JSVAL_TAG_SYMBOL) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_BOOLEAN = (((uint64_t)JSVAL_TAG_BOOLEAN) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_MAGIC = (((uint64_t)JSVAL_TAG_MAGIC) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_NULL = (((uint64_t)JSVAL_TAG_NULL) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_OBJECT = (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_PRIVATE_GCTHING = (((uint64_t)JSVAL_TAG_PRIVATE_GCTHING) << JSVAL_TAG_SHIFT) -} JS_ENUM_FOOTER(JSValueShiftedTag); - -static_assert(sizeof(JSValueShiftedTag) == sizeof(uint64_t), - "compiler typed enum support is apparently buggy"); - -#endif - -/* - * All our supported compilers implement C++11 |enum Foo : T| syntax, so don't - * expose these macros. (This macro exists *only* because gcc bug 51242 - * makes bit-fields of - * typed enums trigger a warning that can't be turned off. Don't expose it - * beyond this file!) - */ -#undef JS_ENUM_HEADER -#undef JS_ENUM_FOOTER - -#if defined(JS_NUNBOX32) - -#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_CLEAR | (type))) - -#define JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET JSVAL_TAG_NULL -#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT -#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32 -#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING - -#elif defined(JS_PUNBOX64) - -#define JSVAL_PAYLOAD_MASK 0x00007FFFFFFFFFFFLL -#define JSVAL_TAG_MASK 0xFFFF800000000000LL -#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_MAX_DOUBLE | (type))) -#define JSVAL_TYPE_TO_SHIFTED_TAG(type) (((uint64_t)JSVAL_TYPE_TO_TAG(type)) << JSVAL_TAG_SHIFT) - -#define JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET JSVAL_TAG_NULL -#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT -#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32 -#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING - -#define JSVAL_LOWER_INCL_SHIFTED_TAG_OF_OBJ_OR_NULL_SET JSVAL_SHIFTED_TAG_NULL -#define JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET JSVAL_SHIFTED_TAG_OBJECT -#define JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET JSVAL_SHIFTED_TAG_UNDEFINED -#define JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET JSVAL_SHIFTED_TAG_STRING - -#endif /* JS_PUNBOX64 */ - -typedef enum JSWhyMagic -{ - /** a hole in a native object's elements */ - JS_ELEMENTS_HOLE, - - /** there is not a pending iterator value */ - JS_NO_ITER_VALUE, - - /** exception value thrown when closing a generator */ - JS_GENERATOR_CLOSING, - - /** compiler sentinel value */ - JS_NO_CONSTANT, - - /** used in debug builds to catch tracing errors */ - JS_THIS_POISON, - - /** used in debug builds to catch tracing errors */ - JS_ARG_POISON, - - /** an empty subnode in the AST serializer */ - JS_SERIALIZE_NO_NODE, - - /** lazy arguments value on the stack */ - JS_LAZY_ARGUMENTS, - - /** optimized-away 'arguments' value */ - JS_OPTIMIZED_ARGUMENTS, - - /** magic value passed to natives to indicate construction */ - JS_IS_CONSTRUCTING, - - /** value of static block object slot */ - JS_BLOCK_NEEDS_CLONE, - - /** see class js::HashableValue */ - JS_HASH_KEY_EMPTY, - - /** error while running Ion code */ - JS_ION_ERROR, - - /** missing recover instruction result */ - JS_ION_BAILOUT, - - /** optimized out slot */ - JS_OPTIMIZED_OUT, - - /** uninitialized lexical bindings that produce ReferenceError on touch. */ - JS_UNINITIALIZED_LEXICAL, - - /** for local use */ - JS_GENERIC_MAGIC, - - JS_WHY_MAGIC_COUNT -} JSWhyMagic; - -namespace JS { - -static inline constexpr JS::Value UndefinedValue(); -static inline JS::Value PoisonedObjectValue(JSObject* obj); - -namespace detail { - -constexpr int CanonicalizedNaNSignBit = 0; -constexpr uint64_t CanonicalizedNaNSignificand = 0x8000000000000ULL; - -constexpr uint64_t CanonicalizedNaNBits = - mozilla::SpecificNaNBits::value; - -} // namespace detail - -/** - * Returns a generic quiet NaN value, with all payload bits set to zero. - * - * Among other properties, this NaN's bit pattern conforms to JS::Value's - * bit pattern restrictions. - */ -static MOZ_ALWAYS_INLINE double -GenericNaN() -{ - return mozilla::SpecificNaN(detail::CanonicalizedNaNSignBit, - detail::CanonicalizedNaNSignificand); -} - -/* MSVC with PGO miscompiles this function. */ -#if defined(_MSC_VER) -# pragma optimize("g", off) -#endif -static inline double -CanonicalizeNaN(double d) -{ - if (MOZ_UNLIKELY(mozilla::IsNaN(d))) - return GenericNaN(); - return d; -} -#if defined(_MSC_VER) -# pragma optimize("", on) -#endif - -/** - * JS::Value is the interface for a single JavaScript Engine value. A few - * general notes on JS::Value: - * - * - JS::Value has setX() and isX() members for X in - * - * { Int32, Double, String, Symbol, Boolean, Undefined, Null, Object, Magic } - * - * JS::Value also contains toX() for each of the non-singleton types. - * - * - Magic is a singleton type whose payload contains either a JSWhyMagic "reason" for - * the magic value or a uint32_t value. By providing JSWhyMagic values when - * creating and checking for magic values, it is possible to assert, at - * runtime, that only magic values with the expected reason flow through a - * particular value. For example, if cx->exception has a magic value, the - * reason must be JS_GENERATOR_CLOSING. - * - * - The JS::Value operations are preferred. The JSVAL_* operations remain for - * compatibility; they may be removed at some point. These operations mostly - * provide similar functionality. But there are a few key differences. One - * is that JS::Value gives null a separate type. - * Also, to help prevent mistakenly boxing a nullable JSObject* as an object, - * Value::setObject takes a JSObject&. (Conversely, Value::toObject returns a - * JSObject&.) A convenience member Value::setObjectOrNull is provided. - * - * - JSVAL_VOID is the same as the singleton value of the Undefined type. - * - * - Note that JS::Value is 8 bytes on 32 and 64-bit architectures. Thus, on - * 32-bit user code should avoid copying jsval/JS::Value as much as possible, - * preferring to pass by const Value&. - */ -class MOZ_NON_PARAM alignas(8) Value -{ - public: -#if defined(JS_NUNBOX32) - using PayloadType = uint32_t; -#elif defined(JS_PUNBOX64) - using PayloadType = uint64_t; -#endif - - /* - * N.B. the default constructor leaves Value unitialized. Adding a default - * constructor prevents Value from being stored in a union. - */ - Value() = default; - Value(const Value& v) = default; - - /** - * Returns false if creating a NumberValue containing the given type would - * be lossy, true otherwise. - */ - template - static bool isNumberRepresentable(const T t) { - return T(double(t)) == t; - } - - /*** Mutators ***/ - - void setNull() { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_NULL, 0); - } - - void setUndefined() { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_UNDEFINED, 0); - } - - void setInt32(int32_t i) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_INT32, uint32_t(i)); - } - - int32_t& getInt32Ref() { - MOZ_ASSERT(isInt32()); - return data.s.payload.i32; - } - - void setDouble(double d) { - // Don't assign to data.asDouble to fix a miscompilation with - // GCC 5.2.1 and 5.3.1. See bug 1312488. - data = layout(d); - MOZ_ASSERT(isDouble()); - } - - void setNaN() { - setDouble(GenericNaN()); - } - - double& getDoubleRef() { - MOZ_ASSERT(isDouble()); - return data.asDouble; - } - - void setString(JSString* str) { - MOZ_ASSERT(uintptr_t(str) > 0x1000); - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_STRING, PayloadType(str)); - } - - void setSymbol(JS::Symbol* sym) { - MOZ_ASSERT(uintptr_t(sym) > 0x1000); - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_SYMBOL, PayloadType(sym)); - } - - void setObject(JSObject& obj) { - MOZ_ASSERT(uintptr_t(&obj) > 0x1000 || uintptr_t(&obj) == 0x48); -#if defined(JS_PUNBOX64) - // VisualStudio cannot contain parenthesized C++ style cast and shift - // inside decltype in template parameter: - // AssertionConditionType> 1))> - // It throws syntax error. - MOZ_ASSERT((((uintptr_t)&obj) >> JSVAL_TAG_SHIFT) == 0); -#endif - setObjectNoCheck(&obj); - } - - private: - void setObjectNoCheck(JSObject* obj) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_OBJECT, PayloadType(obj)); - } - - friend inline Value PoisonedObjectValue(JSObject* obj); - - public: - void setBoolean(bool b) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_BOOLEAN, uint32_t(b)); - } - - void setMagic(JSWhyMagic why) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_MAGIC, uint32_t(why)); - } - - void setMagicUint32(uint32_t payload) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_MAGIC, payload); - } - - bool setNumber(uint32_t ui) { - if (ui > JSVAL_INT_MAX) { - setDouble((double)ui); - return false; - } else { - setInt32((int32_t)ui); - return true; - } - } - - bool setNumber(double d) { - int32_t i; - if (mozilla::NumberIsInt32(d, &i)) { - setInt32(i); - return true; - } - - setDouble(d); - return false; - } - - void setObjectOrNull(JSObject* arg) { - if (arg) - setObject(*arg); - else - setNull(); - } - - void swap(Value& rhs) { - uint64_t tmp = rhs.data.asBits; - rhs.data.asBits = data.asBits; - data.asBits = tmp; - } - - private: - JSValueTag toTag() const { -#if defined(JS_NUNBOX32) - return data.s.tag; -#elif defined(JS_PUNBOX64) - return JSValueTag(data.asBits >> JSVAL_TAG_SHIFT); -#endif - } - - public: - /*** JIT-only interfaces to interact with and create raw Values ***/ -#if defined(JS_NUNBOX32) - PayloadType toNunboxPayload() const { - return data.s.payload.i32; - } - - JSValueTag toNunboxTag() const { - return data.s.tag; - } -#elif defined(JS_PUNBOX64) - const void* bitsAsPunboxPointer() const { - return reinterpret_cast(data.asBits); - } -#endif - - /*** Value type queries ***/ - - /* - * N.B. GCC, in some but not all cases, chooses to emit signed comparison - * of JSValueTag even though its underlying type has been forced to be - * uint32_t. Thus, all comparisons should explicitly cast operands to - * uint32_t. - */ - - bool isUndefined() const { -#if defined(JS_NUNBOX32) - return toTag() == JSVAL_TAG_UNDEFINED; -#elif defined(JS_PUNBOX64) - return data.asBits == JSVAL_SHIFTED_TAG_UNDEFINED; -#endif - } - - bool isNull() const { -#if defined(JS_NUNBOX32) - return toTag() == JSVAL_TAG_NULL; -#elif defined(JS_PUNBOX64) - return data.asBits == JSVAL_SHIFTED_TAG_NULL; -#endif - } - - bool isNullOrUndefined() const { - return isNull() || isUndefined(); - } - - bool isInt32() const { - return toTag() == JSVAL_TAG_INT32; - } - - bool isInt32(int32_t i32) const { - return data.asBits == bitsFromTagAndPayload(JSVAL_TAG_INT32, uint32_t(i32)); - } - - bool isDouble() const { -#if defined(JS_NUNBOX32) - return uint32_t(toTag()) <= uint32_t(JSVAL_TAG_CLEAR); -#elif defined(JS_PUNBOX64) - return (data.asBits | mozilla::DoubleTypeTraits::kSignBit) <= JSVAL_SHIFTED_TAG_MAX_DOUBLE; -#endif - } - - bool isNumber() const { -#if defined(JS_NUNBOX32) - MOZ_ASSERT(toTag() != JSVAL_TAG_CLEAR); - return uint32_t(toTag()) <= uint32_t(JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET); -#elif defined(JS_PUNBOX64) - return data.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET; -#endif - } - - bool isString() const { - return toTag() == JSVAL_TAG_STRING; - } - - bool isSymbol() const { - return toTag() == JSVAL_TAG_SYMBOL; - } - - bool isObject() const { -#if defined(JS_NUNBOX32) - return toTag() == JSVAL_TAG_OBJECT; -#elif defined(JS_PUNBOX64) - MOZ_ASSERT((data.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_TAG_OBJECT); - return data.asBits >= JSVAL_SHIFTED_TAG_OBJECT; -#endif - } - - bool isPrimitive() const { -#if defined(JS_NUNBOX32) - return uint32_t(toTag()) < uint32_t(JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET); -#elif defined(JS_PUNBOX64) - return data.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET; -#endif - } - - bool isObjectOrNull() const { - MOZ_ASSERT(uint32_t(toTag()) <= uint32_t(JSVAL_TAG_OBJECT)); -#if defined(JS_NUNBOX32) - return uint32_t(toTag()) >= uint32_t(JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET); -#elif defined(JS_PUNBOX64) - return data.asBits >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_OBJ_OR_NULL_SET; -#endif - } - - bool isGCThing() const { -#if defined(JS_NUNBOX32) - /* gcc sometimes generates signed < without explicit casts. */ - return uint32_t(toTag()) >= uint32_t(JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET); -#elif defined(JS_PUNBOX64) - return data.asBits >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET; -#endif - } - - bool isBoolean() const { - return toTag() == JSVAL_TAG_BOOLEAN; - } - - bool isTrue() const { - return data.asBits == bitsFromTagAndPayload(JSVAL_TAG_BOOLEAN, uint32_t(true)); - } - - bool isFalse() const { - return data.asBits == bitsFromTagAndPayload(JSVAL_TAG_BOOLEAN, uint32_t(false)); - } - - bool isMagic() const { - return toTag() == JSVAL_TAG_MAGIC; - } - - bool isMagic(JSWhyMagic why) const { - MOZ_ASSERT_IF(isMagic(), data.s.payload.why == why); - return isMagic(); - } - - bool isMarkable() const { - return isGCThing() && !isNull(); - } - - JS::TraceKind traceKind() const { - MOZ_ASSERT(isMarkable()); - static_assert((JSVAL_TAG_STRING & 0x03) == size_t(JS::TraceKind::String), - "Value type tags must correspond with JS::TraceKinds."); - static_assert((JSVAL_TAG_SYMBOL & 0x03) == size_t(JS::TraceKind::Symbol), - "Value type tags must correspond with JS::TraceKinds."); - static_assert((JSVAL_TAG_OBJECT & 0x03) == size_t(JS::TraceKind::Object), - "Value type tags must correspond with JS::TraceKinds."); - if (MOZ_UNLIKELY(isPrivateGCThing())) - return JS::GCThingTraceKind(toGCThing()); - return JS::TraceKind(toTag() & 0x03); - } - - JSWhyMagic whyMagic() const { - MOZ_ASSERT(isMagic()); - return data.s.payload.why; - } - - uint32_t magicUint32() const { - MOZ_ASSERT(isMagic()); - return data.s.payload.u32; - } - - /*** Comparison ***/ - - bool operator==(const Value& rhs) const { - return data.asBits == rhs.data.asBits; - } - - bool operator!=(const Value& rhs) const { - return data.asBits != rhs.data.asBits; - } - - friend inline bool SameType(const Value& lhs, const Value& rhs); - - /*** Extract the value's typed payload ***/ - - int32_t toInt32() const { - MOZ_ASSERT(isInt32()); -#if defined(JS_NUNBOX32) - return data.s.payload.i32; -#elif defined(JS_PUNBOX64) - return int32_t(data.asBits); -#endif - } - - double toDouble() const { - MOZ_ASSERT(isDouble()); - return data.asDouble; - } - - double toNumber() const { - MOZ_ASSERT(isNumber()); - return isDouble() ? toDouble() : double(toInt32()); - } - - JSString* toString() const { - MOZ_ASSERT(isString()); -#if defined(JS_NUNBOX32) - return data.s.payload.str; -#elif defined(JS_PUNBOX64) - return reinterpret_cast(data.asBits & JSVAL_PAYLOAD_MASK); -#endif - } - - JS::Symbol* toSymbol() const { - MOZ_ASSERT(isSymbol()); -#if defined(JS_NUNBOX32) - return data.s.payload.sym; -#elif defined(JS_PUNBOX64) - return reinterpret_cast(data.asBits & JSVAL_PAYLOAD_MASK); -#endif - } - - JSObject& toObject() const { - MOZ_ASSERT(isObject()); -#if defined(JS_NUNBOX32) - return *data.s.payload.obj; -#elif defined(JS_PUNBOX64) - return *toObjectOrNull(); -#endif - } - - JSObject* toObjectOrNull() const { - MOZ_ASSERT(isObjectOrNull()); -#if defined(JS_NUNBOX32) - return data.s.payload.obj; -#elif defined(JS_PUNBOX64) - uint64_t ptrBits = data.asBits & JSVAL_PAYLOAD_MASK; - MOZ_ASSERT((ptrBits & 0x7) == 0); - return reinterpret_cast(ptrBits); -#endif - } - - js::gc::Cell* toGCThing() const { - MOZ_ASSERT(isGCThing()); -#if defined(JS_NUNBOX32) - return data.s.payload.cell; -#elif defined(JS_PUNBOX64) - uint64_t ptrBits = data.asBits & JSVAL_PAYLOAD_MASK; - MOZ_ASSERT((ptrBits & 0x7) == 0); - return reinterpret_cast(ptrBits); -#endif - } - - js::gc::Cell* toMarkablePointer() const { - MOZ_ASSERT(isMarkable()); - return toGCThing(); - } - - GCCellPtr toGCCellPtr() const { - return GCCellPtr(toGCThing(), traceKind()); - } - - bool toBoolean() const { - MOZ_ASSERT(isBoolean()); -#if defined(JS_NUNBOX32) - return bool(data.s.payload.boo); -#elif defined(JS_PUNBOX64) - return bool(data.asBits & JSVAL_PAYLOAD_MASK); -#endif - } - - uint32_t payloadAsRawUint32() const { - MOZ_ASSERT(!isDouble()); - return data.s.payload.u32; - } - - uint64_t asRawBits() const { - return data.asBits; - } - - JSValueType extractNonDoubleType() const { - uint32_t type = toTag() & 0xF; - MOZ_ASSERT(type > JSVAL_TYPE_DOUBLE); - return JSValueType(type); - } - - /* - * Private API - * - * Private setters/getters allow the caller to read/write arbitrary types - * that fit in the 64-bit payload. It is the caller's responsibility, after - * storing to a value with setPrivateX to read only using getPrivateX. - * Privates values are given a type which ensures they are not marked. - */ - - void setPrivate(void* ptr) { - MOZ_ASSERT((uintptr_t(ptr) & 1) == 0); -#if defined(JS_NUNBOX32) - data.s.tag = JSValueTag(0); - data.s.payload.ptr = ptr; -#elif defined(JS_PUNBOX64) - data.asBits = uintptr_t(ptr) >> 1; -#endif - MOZ_ASSERT(isDouble()); - } - - void* toPrivate() const { - MOZ_ASSERT(isDouble()); -#if defined(JS_NUNBOX32) - return data.s.payload.ptr; -#elif defined(JS_PUNBOX64) - MOZ_ASSERT((data.asBits & 0x8000000000000000ULL) == 0); - return reinterpret_cast(data.asBits << 1); -#endif - } - - void setPrivateUint32(uint32_t ui) { - MOZ_ASSERT(uint32_t(int32_t(ui)) == ui); - setInt32(int32_t(ui)); - } - - uint32_t toPrivateUint32() const { - return uint32_t(toInt32()); - } - - /* - * Private GC Thing API - * - * Non-JSObject, JSString, and JS::Symbol cells may be put into the 64-bit - * payload as private GC things. Such Values are considered isMarkable() - * and isGCThing(), and as such, automatically marked. Their traceKind() - * is gotten via their cells. - */ - - void setPrivateGCThing(js::gc::Cell* cell) { - MOZ_ASSERT(JS::GCThingTraceKind(cell) != JS::TraceKind::String, - "Private GC thing Values must not be strings. Make a StringValue instead."); - MOZ_ASSERT(JS::GCThingTraceKind(cell) != JS::TraceKind::Symbol, - "Private GC thing Values must not be symbols. Make a SymbolValue instead."); - MOZ_ASSERT(JS::GCThingTraceKind(cell) != JS::TraceKind::Object, - "Private GC thing Values must not be objects. Make an ObjectValue instead."); - - MOZ_ASSERT(uintptr_t(cell) > 0x1000); -#if defined(JS_PUNBOX64) - // VisualStudio cannot contain parenthesized C++ style cast and shift - // inside decltype in template parameter: - // AssertionConditionType> 1))> - // It throws syntax error. - MOZ_ASSERT((((uintptr_t)cell) >> JSVAL_TAG_SHIFT) == 0); -#endif - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_PRIVATE_GCTHING, PayloadType(cell)); - } - - bool isPrivateGCThing() const { - return toTag() == JSVAL_TAG_PRIVATE_GCTHING; - } - - const size_t* payloadWord() const { -#if defined(JS_NUNBOX32) - return &data.s.payload.word; -#elif defined(JS_PUNBOX64) - return &data.asWord; -#endif - } - - const uintptr_t* payloadUIntPtr() const { -#if defined(JS_NUNBOX32) - return &data.s.payload.uintptr; -#elif defined(JS_PUNBOX64) - return &data.asUIntPtr; -#endif - } - -#if !defined(_MSC_VER) && !defined(__sparc) - // Value must be POD so that MSVC will pass it by value and not in memory - // (bug 689101); the same is true for SPARC as well (bug 737344). More - // precisely, we don't want Value return values compiled as out params. - private: -#endif - -#if MOZ_LITTLE_ENDIAN -# if defined(JS_NUNBOX32) - union layout { - uint64_t asBits; - struct { - union { - int32_t i32; - uint32_t u32; - uint32_t boo; // Don't use |bool| -- it must be four bytes. - JSString* str; - JS::Symbol* sym; - JSObject* obj; - js::gc::Cell* cell; - void* ptr; - JSWhyMagic why; - size_t word; - uintptr_t uintptr; - } payload; - JSValueTag tag; - } s; - double asDouble; - void* asPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# elif defined(JS_PUNBOX64) - union layout { - uint64_t asBits; -#if !defined(_WIN64) - /* MSVC does not pack these correctly :-( */ - struct { - uint64_t payload47 : 47; - JSValueTag tag : 17; - } debugView; -#endif - struct { - union { - int32_t i32; - uint32_t u32; - JSWhyMagic why; - } payload; - } s; - double asDouble; - void* asPtr; - size_t asWord; - uintptr_t asUIntPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# endif /* JS_PUNBOX64 */ -#else /* MOZ_LITTLE_ENDIAN */ -# if defined(JS_NUNBOX32) - union layout { - uint64_t asBits; - struct { - JSValueTag tag; - union { - int32_t i32; - uint32_t u32; - uint32_t boo; // Don't use |bool| -- it must be four bytes. - JSString* str; - JS::Symbol* sym; - JSObject* obj; - js::gc::Cell* cell; - void* ptr; - JSWhyMagic why; - size_t word; - uintptr_t uintptr; - } payload; - } s; - double asDouble; - void* asPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# elif defined(JS_PUNBOX64) - union layout { - uint64_t asBits; - struct { - JSValueTag tag : 17; - uint64_t payload47 : 47; - } debugView; - struct { - uint32_t padding; - union { - int32_t i32; - uint32_t u32; - JSWhyMagic why; - } payload; - } s; - double asDouble; - void* asPtr; - size_t asWord; - uintptr_t asUIntPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# endif /* JS_PUNBOX64 */ -#endif /* MOZ_LITTLE_ENDIAN */ - - private: - explicit constexpr Value(uint64_t asBits) : data(asBits) {} - explicit constexpr Value(double d) : data(d) {} - - void staticAssertions() { - JS_STATIC_ASSERT(sizeof(JSValueType) == 1); - JS_STATIC_ASSERT(sizeof(JSValueTag) == 4); - JS_STATIC_ASSERT(sizeof(JSWhyMagic) <= 4); - JS_STATIC_ASSERT(sizeof(Value) == 8); - } - - friend constexpr Value JS::UndefinedValue(); - - public: - static constexpr uint64_t - bitsFromTagAndPayload(JSValueTag tag, PayloadType payload) - { -#if defined(JS_NUNBOX32) - return (uint64_t(uint32_t(tag)) << 32) | payload; -#elif defined(JS_PUNBOX64) - return (uint64_t(uint32_t(tag)) << JSVAL_TAG_SHIFT) | payload; -#endif - } - - static constexpr Value - fromTagAndPayload(JSValueTag tag, PayloadType payload) - { - return fromRawBits(bitsFromTagAndPayload(tag, payload)); - } - - static constexpr Value - fromRawBits(uint64_t asBits) { - return Value(asBits); - } - - static constexpr Value - fromInt32(int32_t i) { - return fromTagAndPayload(JSVAL_TAG_INT32, uint32_t(i)); - } - - static constexpr Value - fromDouble(double d) { - return Value(d); - } -} JS_HAZ_GC_POINTER; - -static_assert(sizeof(Value) == 8, "Value size must leave three tag bits, be a binary power, and is ubiquitously depended upon everywhere"); - -inline bool -IsOptimizedPlaceholderMagicValue(const Value& v) -{ - if (v.isMagic()) { - MOZ_ASSERT(v.whyMagic() == JS_OPTIMIZED_ARGUMENTS || v.whyMagic() == JS_OPTIMIZED_OUT); - return true; - } - return false; -} - -static MOZ_ALWAYS_INLINE void -ExposeValueToActiveJS(const Value& v) -{ - if (v.isMarkable()) - js::gc::ExposeGCThingToActiveJS(GCCellPtr(v)); -} - -/************************************************************************/ - -static inline Value -NullValue() -{ - Value v; - v.setNull(); - return v; -} - -static inline constexpr Value -UndefinedValue() -{ - return Value::fromTagAndPayload(JSVAL_TAG_UNDEFINED, 0); -} - -static inline constexpr Value -Int32Value(int32_t i32) -{ - return Value::fromInt32(i32); -} - -static inline Value -DoubleValue(double dbl) -{ - Value v; - v.setDouble(dbl); - return v; -} - -static inline Value -CanonicalizedDoubleValue(double d) -{ - return MOZ_UNLIKELY(mozilla::IsNaN(d)) - ? Value::fromRawBits(detail::CanonicalizedNaNBits) - : Value::fromDouble(d); -} - -static inline bool -IsCanonicalized(double d) -{ - if (mozilla::IsInfinite(d) || mozilla::IsFinite(d)) - return true; - - uint64_t bits; - mozilla::BitwiseCast(d, &bits); - return (bits & ~mozilla::DoubleTypeTraits::kSignBit) == detail::CanonicalizedNaNBits; -} - -static inline Value -DoubleNaNValue() -{ - Value v; - v.setNaN(); - return v; -} - -static inline Value -Float32Value(float f) -{ - Value v; - v.setDouble(f); - return v; -} - -static inline Value -StringValue(JSString* str) -{ - Value v; - v.setString(str); - return v; -} - -static inline Value -SymbolValue(JS::Symbol* sym) -{ - Value v; - v.setSymbol(sym); - return v; -} - -static inline Value -BooleanValue(bool boo) -{ - Value v; - v.setBoolean(boo); - return v; -} - -static inline Value -TrueValue() -{ - Value v; - v.setBoolean(true); - return v; -} - -static inline Value -FalseValue() -{ - Value v; - v.setBoolean(false); - return v; -} - -static inline Value -ObjectValue(JSObject& obj) -{ - Value v; - v.setObject(obj); - return v; -} - -static inline Value -ObjectValueCrashOnTouch() -{ - Value v; - v.setObject(*reinterpret_cast(0x48)); - return v; -} - -static inline Value -MagicValue(JSWhyMagic why) -{ - Value v; - v.setMagic(why); - return v; -} - -static inline Value -MagicValueUint32(uint32_t payload) -{ - Value v; - v.setMagicUint32(payload); - return v; -} - -static inline Value -NumberValue(float f) -{ - Value v; - v.setNumber(f); - return v; -} - -static inline Value -NumberValue(double dbl) -{ - Value v; - v.setNumber(dbl); - return v; -} - -static inline Value -NumberValue(int8_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(uint8_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(int16_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(uint16_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(int32_t i) -{ - return Int32Value(i); -} - -static inline constexpr Value -NumberValue(uint32_t i) -{ - return i <= JSVAL_INT_MAX - ? Int32Value(int32_t(i)) - : Value::fromDouble(double(i)); -} - -namespace detail { - -template -class MakeNumberValue -{ - public: - template - static inline Value create(const T t) - { - Value v; - if (JSVAL_INT_MIN <= t && t <= JSVAL_INT_MAX) - v.setInt32(int32_t(t)); - else - v.setDouble(double(t)); - return v; - } -}; - -template <> -class MakeNumberValue -{ - public: - template - static inline Value create(const T t) - { - Value v; - if (t <= JSVAL_INT_MAX) - v.setInt32(int32_t(t)); - else - v.setDouble(double(t)); - return v; - } -}; - -} // namespace detail - -template -static inline Value -NumberValue(const T t) -{ - MOZ_ASSERT(Value::isNumberRepresentable(t), "value creation would be lossy"); - return detail::MakeNumberValue::is_signed>::create(t); -} - -static inline Value -ObjectOrNullValue(JSObject* obj) -{ - Value v; - v.setObjectOrNull(obj); - return v; -} - -static inline Value -PrivateValue(void* ptr) -{ - Value v; - v.setPrivate(ptr); - return v; -} - -static inline Value -PrivateUint32Value(uint32_t ui) -{ - Value v; - v.setPrivateUint32(ui); - return v; -} - -static inline Value -PrivateGCThingValue(js::gc::Cell* cell) -{ - Value v; - v.setPrivateGCThing(cell); - return v; -} - -static inline Value -PoisonedObjectValue(JSObject* obj) -{ - Value v; - v.setObjectNoCheck(obj); - return v; -} - -inline bool -SameType(const Value& lhs, const Value& rhs) -{ -#if defined(JS_NUNBOX32) - JSValueTag ltag = lhs.toTag(), rtag = rhs.toTag(); - return ltag == rtag || (ltag < JSVAL_TAG_CLEAR && rtag < JSVAL_TAG_CLEAR); -#elif defined(JS_PUNBOX64) - return (lhs.isDouble() && rhs.isDouble()) || - (((lhs.data.asBits ^ rhs.data.asBits) & 0xFFFF800000000000ULL) == 0); -#endif -} - -} // namespace JS - -/************************************************************************/ - -namespace JS { -JS_PUBLIC_API(void) HeapValuePostBarrier(Value* valuep, const Value& prev, const Value& next); - -template <> -struct GCPolicy -{ - static Value initial() { return UndefinedValue(); } - static void trace(JSTracer* trc, Value* v, const char* name) { - js::UnsafeTraceManuallyBarrieredEdge(trc, v, name); - } - static bool isTenured(const Value& thing) { - return !thing.isGCThing() || !IsInsideNursery(thing.toGCThing()); - } -}; - -} // namespace JS - -namespace js { - -template <> -struct BarrierMethods -{ - static gc::Cell* asGCThingOrNull(const JS::Value& v) { - return v.isMarkable() ? v.toGCThing() : nullptr; - } - static void postBarrier(JS::Value* v, const JS::Value& prev, const JS::Value& next) { - JS::HeapValuePostBarrier(v, prev, next); - } - static void exposeToJS(const JS::Value& v) { - JS::ExposeValueToActiveJS(v); - } -}; - -template class MutableValueOperations; - -/** - * A class designed for CRTP use in implementing the non-mutating parts of the - * Value interface in Value-like classes. Outer must be a class inheriting - * ValueOperations with a visible get() method returning a const - * reference to the Value abstracted by Outer. - */ -template -class ValueOperations -{ - friend class MutableValueOperations; - - const JS::Value& value() const { return static_cast(this)->get(); } - - public: - bool isUndefined() const { return value().isUndefined(); } - bool isNull() const { return value().isNull(); } - bool isBoolean() const { return value().isBoolean(); } - bool isTrue() const { return value().isTrue(); } - bool isFalse() const { return value().isFalse(); } - bool isNumber() const { return value().isNumber(); } - bool isInt32() const { return value().isInt32(); } - bool isInt32(int32_t i32) const { return value().isInt32(i32); } - bool isDouble() const { return value().isDouble(); } - bool isString() const { return value().isString(); } - bool isSymbol() const { return value().isSymbol(); } - bool isObject() const { return value().isObject(); } - bool isMagic() const { return value().isMagic(); } - bool isMagic(JSWhyMagic why) const { return value().isMagic(why); } - bool isMarkable() const { return value().isMarkable(); } - bool isPrimitive() const { return value().isPrimitive(); } - bool isGCThing() const { return value().isGCThing(); } - - bool isNullOrUndefined() const { return value().isNullOrUndefined(); } - bool isObjectOrNull() const { return value().isObjectOrNull(); } - - bool toBoolean() const { return value().toBoolean(); } - double toNumber() const { return value().toNumber(); } - int32_t toInt32() const { return value().toInt32(); } - double toDouble() const { return value().toDouble(); } - JSString* toString() const { return value().toString(); } - JS::Symbol* toSymbol() const { return value().toSymbol(); } - JSObject& toObject() const { return value().toObject(); } - JSObject* toObjectOrNull() const { return value().toObjectOrNull(); } - gc::Cell* toGCThing() const { return value().toGCThing(); } - JS::TraceKind traceKind() const { return value().traceKind(); } - void* toPrivate() const { return value().toPrivate(); } - uint32_t toPrivateUint32() const { return value().toPrivateUint32(); } - - uint64_t asRawBits() const { return value().asRawBits(); } - JSValueType extractNonDoubleType() const { return value().extractNonDoubleType(); } - - JSWhyMagic whyMagic() const { return value().whyMagic(); } - uint32_t magicUint32() const { return value().magicUint32(); } -}; - -/** - * A class designed for CRTP use in implementing all the mutating parts of the - * Value interface in Value-like classes. Outer must be a class inheriting - * MutableValueOperations with visible get() methods returning const and - * non-const references to the Value abstracted by Outer. - */ -template -class MutableValueOperations : public ValueOperations -{ - JS::Value& value() { return static_cast(this)->get(); } - - public: - void setNull() { value().setNull(); } - void setUndefined() { value().setUndefined(); } - void setInt32(int32_t i) { value().setInt32(i); } - void setDouble(double d) { value().setDouble(d); } - void setNaN() { setDouble(JS::GenericNaN()); } - void setBoolean(bool b) { value().setBoolean(b); } - void setMagic(JSWhyMagic why) { value().setMagic(why); } - bool setNumber(uint32_t ui) { return value().setNumber(ui); } - bool setNumber(double d) { return value().setNumber(d); } - void setString(JSString* str) { this->value().setString(str); } - void setSymbol(JS::Symbol* sym) { this->value().setSymbol(sym); } - void setObject(JSObject& obj) { this->value().setObject(obj); } - void setObjectOrNull(JSObject* arg) { this->value().setObjectOrNull(arg); } - void setPrivate(void* ptr) { this->value().setPrivate(ptr); } - void setPrivateUint32(uint32_t ui) { this->value().setPrivateUint32(ui); } - void setPrivateGCThing(js::gc::Cell* cell) { this->value().setPrivateGCThing(cell); } -}; - -/* - * Augment the generic Heap interface when T = Value with - * type-querying, value-extracting, and mutating operations. - */ -template <> -class HeapBase : public ValueOperations > -{ - typedef JS::Heap Outer; - - friend class ValueOperations; - - void setBarriered(const JS::Value& v) { - *static_cast*>(this) = v; - } - - public: - void setNull() { setBarriered(JS::NullValue()); } - void setUndefined() { setBarriered(JS::UndefinedValue()); } - void setInt32(int32_t i) { setBarriered(JS::Int32Value(i)); } - void setDouble(double d) { setBarriered(JS::DoubleValue(d)); } - void setNaN() { setDouble(JS::GenericNaN()); } - void setBoolean(bool b) { setBarriered(JS::BooleanValue(b)); } - void setMagic(JSWhyMagic why) { setBarriered(JS::MagicValue(why)); } - void setString(JSString* str) { setBarriered(JS::StringValue(str)); } - void setSymbol(JS::Symbol* sym) { setBarriered(JS::SymbolValue(sym)); } - void setObject(JSObject& obj) { setBarriered(JS::ObjectValue(obj)); } - void setPrivateGCThing(js::gc::Cell* cell) { setBarriered(JS::PrivateGCThingValue(cell)); } - - bool setNumber(uint32_t ui) { - if (ui > JSVAL_INT_MAX) { - setDouble((double)ui); - return false; - } else { - setInt32((int32_t)ui); - return true; - } - } - - bool setNumber(double d) { - int32_t i; - if (mozilla::NumberIsInt32(d, &i)) { - setInt32(i); - return true; - } - - setDouble(d); - return false; - } - - void setObjectOrNull(JSObject* arg) { - if (arg) - setObject(*arg); - else - setNull(); - } -}; - -template <> -class HandleBase : public ValueOperations > -{}; - -template <> -class MutableHandleBase : public MutableValueOperations > -{}; - -template <> -class RootedBase : public MutableValueOperations > -{}; - -template <> -class PersistentRootedBase : public MutableValueOperations> -{}; - -/* - * If the Value is a GC pointer type, convert to that type and call |f| with - * the pointer. If the Value is not a GC type, calls F::defaultValue. - */ -template -auto -DispatchTyped(F f, const JS::Value& val, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - if (val.isString()) - return f(val.toString(), mozilla::Forward(args)...); - if (val.isObject()) - return f(&val.toObject(), mozilla::Forward(args)...); - if (val.isSymbol()) - return f(val.toSymbol(), mozilla::Forward(args)...); - if (MOZ_UNLIKELY(val.isPrivateGCThing())) - return DispatchTyped(f, val.toGCCellPtr(), mozilla::Forward(args)...); - MOZ_ASSERT(!val.isMarkable()); - return F::defaultValue(val); -} - -template struct VoidDefaultAdaptor { static void defaultValue(const S&) {} }; -template struct IdentityDefaultAdaptor { static S defaultValue(const S& v) {return v;} }; -template struct BoolDefaultAdaptor { static bool defaultValue(const S&) { return v; } }; - -} // namespace js - -/************************************************************************/ - -namespace JS { - -extern JS_PUBLIC_DATA(const HandleValue) NullHandleValue; -extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; -extern JS_PUBLIC_DATA(const HandleValue) TrueHandleValue; -extern JS_PUBLIC_DATA(const HandleValue) FalseHandleValue; - -} // namespace JS - -#endif /* js_Value_h */ diff --git a/ios/include/spidermonkey/js/Vector.h b/ios/include/spidermonkey/js/Vector.h deleted file mode 100644 index 6fa63e93..00000000 --- a/ios/include/spidermonkey/js/Vector.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Vector_h -#define js_Vector_h - -#include "mozilla/Vector.h" - -/* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4345) -#endif - -namespace js { - -class TempAllocPolicy; - -namespace detail { - -template -struct TypeIsGCThing : mozilla::FalseType -{}; - -// Uncomment this once we actually can assert it: -//template <> -//struct TypeIsGCThing : mozilla::TrueType -//{}; - -} // namespace detail - -template ::value>::Type - > -using Vector = mozilla::Vector; - -} // namespace js - -#endif /* js_Vector_h */ diff --git a/ios/include/spidermonkey/js/WeakMapPtr.h b/ios/include/spidermonkey/js/WeakMapPtr.h deleted file mode 100644 index 41860551..00000000 --- a/ios/include/spidermonkey/js/WeakMapPtr.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_WeakMapPtr_h -#define js_WeakMapPtr_h - -#include "jspubtd.h" - -#include "js/TypeDecls.h" - -namespace JS { - -// A wrapper around the internal C++ representation of SpiderMonkey WeakMaps, -// usable outside the engine. -// -// The supported template specializations are enumerated in WeakMapPtr.cpp. If -// you want to use this class for a different key/value combination, add it to -// the list and the compiler will generate the relevant machinery. -template -class JS_PUBLIC_API(WeakMapPtr) -{ - public: - WeakMapPtr() : ptr(nullptr) {} - bool init(JSContext* cx); - bool initialized() { return ptr != nullptr; } - void destroy(); - virtual ~WeakMapPtr() { MOZ_ASSERT(!initialized()); } - void trace(JSTracer* tracer); - - V lookup(const K& key); - bool put(JSContext* cx, const K& key, const V& value); - - private: - void* ptr; - - // WeakMapPtr is neither copyable nor assignable. - WeakMapPtr(const WeakMapPtr& wmp) = delete; - WeakMapPtr& operator=(const WeakMapPtr& wmp) = delete; -}; - -} /* namespace JS */ - -#endif /* js_WeakMapPtr_h */ diff --git a/ios/include/spidermonkey/jsalloc.h b/ios/include/spidermonkey/jsalloc.h deleted file mode 100644 index 6660b71d..00000000 --- a/ios/include/spidermonkey/jsalloc.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * JS allocation policies. - * - * The allocators here are for system memory with lifetimes which are not - * managed by the GC. See the comment at the top of vm/MallocProvider.h. - */ - -#ifndef jsalloc_h -#define jsalloc_h - -#include "js/TypeDecls.h" -#include "js/Utility.h" - -namespace js { - -enum class AllocFunction { - Malloc, - Calloc, - Realloc -}; - -struct ContextFriendFields; - -/* Policy for using system memory functions and doing no error reporting. */ -class SystemAllocPolicy -{ - public: - template T* maybe_pod_malloc(size_t numElems) { return js_pod_malloc(numElems); } - template T* maybe_pod_calloc(size_t numElems) { return js_pod_calloc(numElems); } - template T* maybe_pod_realloc(T* p, size_t oldSize, size_t newSize) { - return js_pod_realloc(p, oldSize, newSize); - } - template T* pod_malloc(size_t numElems) { return maybe_pod_malloc(numElems); } - template T* pod_calloc(size_t numElems) { return maybe_pod_calloc(numElems); } - template T* pod_realloc(T* p, size_t oldSize, size_t newSize) { - return maybe_pod_realloc(p, oldSize, newSize); - } - void free_(void* p) { js_free(p); } - void reportAllocOverflow() const {} - bool checkSimulatedOOM() const { - return !js::oom::ShouldFailWithOOM(); - } -}; - -class ExclusiveContext; -JS_PUBLIC_API(void) ReportOutOfMemory(ExclusiveContext* cxArg); - -/* - * Allocation policy that calls the system memory functions and reports errors - * to the context. Since the JSContext given on construction is stored for - * the lifetime of the container, this policy may only be used for containers - * whose lifetime is a shorter than the given JSContext. - * - * FIXME bug 647103 - rewrite this in terms of temporary allocation functions, - * not the system ones. - */ -class TempAllocPolicy -{ - ContextFriendFields* const cx_; - - /* - * Non-inline helper to call JSRuntime::onOutOfMemory with minimal - * code bloat. - */ - JS_FRIEND_API(void*) onOutOfMemory(AllocFunction allocFunc, size_t nbytes, - void* reallocPtr = nullptr); - - template - T* onOutOfMemoryTyped(AllocFunction allocFunc, size_t numElems, void* reallocPtr = nullptr) { - size_t bytes; - if (MOZ_UNLIKELY(!CalculateAllocSize(numElems, &bytes))) - return nullptr; - return static_cast(onOutOfMemory(allocFunc, bytes, reallocPtr)); - } - - public: - MOZ_IMPLICIT TempAllocPolicy(JSContext* cx) : cx_((ContextFriendFields*) cx) {} // :( - MOZ_IMPLICIT TempAllocPolicy(ContextFriendFields* cx) : cx_(cx) {} - - template - T* maybe_pod_malloc(size_t numElems) { - return js_pod_malloc(numElems); - } - - template - T* maybe_pod_calloc(size_t numElems) { - return js_pod_calloc(numElems); - } - - template - T* maybe_pod_realloc(T* prior, size_t oldSize, size_t newSize) { - return js_pod_realloc(prior, oldSize, newSize); - } - - template - T* pod_malloc(size_t numElems) { - T* p = maybe_pod_malloc(numElems); - if (MOZ_UNLIKELY(!p)) - p = onOutOfMemoryTyped(AllocFunction::Malloc, numElems); - return p; - } - - template - T* pod_calloc(size_t numElems) { - T* p = maybe_pod_calloc(numElems); - if (MOZ_UNLIKELY(!p)) - p = onOutOfMemoryTyped(AllocFunction::Calloc, numElems); - return p; - } - - template - T* pod_realloc(T* prior, size_t oldSize, size_t newSize) { - T* p2 = maybe_pod_realloc(prior, oldSize, newSize); - if (MOZ_UNLIKELY(!p2)) - p2 = onOutOfMemoryTyped(AllocFunction::Realloc, newSize, prior); - return p2; - } - - void free_(void* p) { - js_free(p); - } - - JS_FRIEND_API(void) reportAllocOverflow() const; - - bool checkSimulatedOOM() const { - if (js::oom::ShouldFailWithOOM()) { - js::ReportOutOfMemory(reinterpret_cast(cx_)); - return false; - } - - return true; - } -}; - -} /* namespace js */ - -#endif /* jsalloc_h */ diff --git a/ios/include/spidermonkey/jsapi.h b/ios/include/spidermonkey/jsapi.h deleted file mode 100644 index 84d639a0..00000000 --- a/ios/include/spidermonkey/jsapi.h +++ /dev/null @@ -1,6630 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JavaScript API. */ - -#ifndef jsapi_h -#define jsapi_h - -#include "mozilla/AlreadyAddRefed.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Range.h" -#include "mozilla/RangedPtr.h" -#include "mozilla/RefCounted.h" -#include "mozilla/RefPtr.h" -#include "mozilla/Variant.h" - -#include -#include -#include -#include - -#include "jsalloc.h" -#include "jspubtd.h" - -#include "js/CallArgs.h" -#include "js/CharacterEncoding.h" -#include "js/Class.h" -#include "js/GCVector.h" -#include "js/HashTable.h" -#include "js/Id.h" -#include "js/Principals.h" -#include "js/Realm.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" -#include "js/Utility.h" -#include "js/Value.h" -#include "js/Vector.h" - -/************************************************************************/ - -namespace JS { - -class TwoByteChars; - -#ifdef JS_DEBUG - -class JS_PUBLIC_API(AutoCheckRequestDepth) -{ - JSContext* cx; - public: - explicit AutoCheckRequestDepth(JSContext* cx); - explicit AutoCheckRequestDepth(js::ContextFriendFields* cx); - ~AutoCheckRequestDepth(); -}; - -# define CHECK_REQUEST(cx) \ - JS::AutoCheckRequestDepth _autoCheckRequestDepth(cx) - -#else - -# define CHECK_REQUEST(cx) \ - ((void) 0) - -#endif /* JS_DEBUG */ - -/** AutoValueArray roots an internal fixed-size array of Values. */ -template -class MOZ_RAII AutoValueArray : public AutoGCRooter -{ - const size_t length_; - Value elements_[N]; - - public: - explicit AutoValueArray(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, VALARRAY), length_(N) - { - /* Always initialize in case we GC before assignment. */ - mozilla::PodArrayZero(elements_); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - unsigned length() const { return length_; } - const Value* begin() const { return elements_; } - Value* begin() { return elements_; } - - HandleValue operator[](unsigned i) const { - MOZ_ASSERT(i < N); - return HandleValue::fromMarkedLocation(&elements_[i]); - } - MutableHandleValue operator[](unsigned i) { - MOZ_ASSERT(i < N); - return MutableHandleValue::fromMarkedLocation(&elements_[i]); - } - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -template -class MOZ_RAII AutoVectorRooterBase : protected AutoGCRooter -{ - typedef js::Vector VectorImpl; - VectorImpl vector; - - public: - explicit AutoVectorRooterBase(JSContext* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), vector(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit AutoVectorRooterBase(js::ContextFriendFields* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), vector(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - typedef T ElementType; - typedef typename VectorImpl::Range Range; - - size_t length() const { return vector.length(); } - bool empty() const { return vector.empty(); } - - MOZ_MUST_USE bool append(const T& v) { return vector.append(v); } - MOZ_MUST_USE bool appendN(const T& v, size_t len) { return vector.appendN(v, len); } - MOZ_MUST_USE bool append(const T* ptr, size_t len) { return vector.append(ptr, len); } - MOZ_MUST_USE bool appendAll(const AutoVectorRooterBase& other) { - return vector.appendAll(other.vector); - } - - MOZ_MUST_USE bool insert(T* p, const T& val) { return vector.insert(p, val); } - - /* For use when space has already been reserved. */ - void infallibleAppend(const T& v) { vector.infallibleAppend(v); } - - void popBack() { vector.popBack(); } - T popCopy() { return vector.popCopy(); } - - MOZ_MUST_USE bool growBy(size_t inc) { - size_t oldLength = vector.length(); - if (!vector.growByUninitialized(inc)) - return false; - makeRangeGCSafe(oldLength); - return true; - } - - MOZ_MUST_USE bool resize(size_t newLength) { - size_t oldLength = vector.length(); - if (newLength <= oldLength) { - vector.shrinkBy(oldLength - newLength); - return true; - } - if (!vector.growByUninitialized(newLength - oldLength)) - return false; - makeRangeGCSafe(oldLength); - return true; - } - - void clear() { vector.clear(); } - - MOZ_MUST_USE bool reserve(size_t newLength) { - return vector.reserve(newLength); - } - - JS::MutableHandle operator[](size_t i) { - return JS::MutableHandle::fromMarkedLocation(&vector[i]); - } - JS::Handle operator[](size_t i) const { - return JS::Handle::fromMarkedLocation(&vector[i]); - } - - const T* begin() const { return vector.begin(); } - T* begin() { return vector.begin(); } - - const T* end() const { return vector.end(); } - T* end() { return vector.end(); } - - Range all() { return vector.all(); } - - const T& back() const { return vector.back(); } - - friend void AutoGCRooter::trace(JSTracer* trc); - - private: - void makeRangeGCSafe(size_t oldLength) { - T* t = vector.begin() + oldLength; - for (size_t i = oldLength; i < vector.length(); ++i, ++t) - memset(t, 0, sizeof(T)); - } - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -template -class MOZ_RAII AutoVectorRooter : public AutoVectorRooterBase -{ - public: - explicit AutoVectorRooter(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoVectorRooterBase(cx, this->GetTag(T())) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit AutoVectorRooter(js::ContextFriendFields* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoVectorRooterBase(cx, this->GetTag(T())) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -class AutoValueVector : public Rooted> { - using Vec = GCVector; - using Base = Rooted; - public: - explicit AutoValueVector(JSContext* cx) : Base(cx, Vec(cx)) {} - explicit AutoValueVector(js::ContextFriendFields* cx) : Base(cx, Vec(cx)) {} -}; - -class AutoIdVector : public Rooted> { - using Vec = GCVector; - using Base = Rooted; - public: - explicit AutoIdVector(JSContext* cx) : Base(cx, Vec(cx)) {} - explicit AutoIdVector(js::ContextFriendFields* cx) : Base(cx, Vec(cx)) {} - - bool appendAll(const AutoIdVector& other) { return this->Base::appendAll(other.get()); } -}; - -class AutoObjectVector : public Rooted> { - using Vec = GCVector; - using Base = Rooted; - public: - explicit AutoObjectVector(JSContext* cx) : Base(cx, Vec(cx)) {} - explicit AutoObjectVector(js::ContextFriendFields* cx) : Base(cx, Vec(cx)) {} -}; - -using ValueVector = JS::GCVector; -using IdVector = JS::GCVector; -using ScriptVector = JS::GCVector; -using StringVector = JS::GCVector; - -template -class MOZ_RAII AutoHashMapRooter : protected AutoGCRooter -{ - private: - typedef js::HashMap HashMapImpl; - - public: - explicit AutoHashMapRooter(JSContext* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), map(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - typedef Key KeyType; - typedef Value ValueType; - typedef typename HashMapImpl::Entry Entry; - typedef typename HashMapImpl::Lookup Lookup; - typedef typename HashMapImpl::Ptr Ptr; - typedef typename HashMapImpl::AddPtr AddPtr; - - bool init(uint32_t len = 16) { - return map.init(len); - } - bool initialized() const { - return map.initialized(); - } - Ptr lookup(const Lookup& l) const { - return map.lookup(l); - } - void remove(Ptr p) { - map.remove(p); - } - AddPtr lookupForAdd(const Lookup& l) const { - return map.lookupForAdd(l); - } - - template - bool add(AddPtr& p, const KeyInput& k, const ValueInput& v) { - return map.add(p, k, v); - } - - bool add(AddPtr& p, const Key& k) { - return map.add(p, k); - } - - template - bool relookupOrAdd(AddPtr& p, const KeyInput& k, const ValueInput& v) { - return map.relookupOrAdd(p, k, v); - } - - typedef typename HashMapImpl::Range Range; - Range all() const { - return map.all(); - } - - typedef typename HashMapImpl::Enum Enum; - - void clear() { - map.clear(); - } - - void finish() { - map.finish(); - } - - bool empty() const { - return map.empty(); - } - - uint32_t count() const { - return map.count(); - } - - size_t capacity() const { - return map.capacity(); - } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return map.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return map.sizeOfIncludingThis(mallocSizeOf); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return map.has(l); - } - - template - bool put(const KeyInput& k, const ValueInput& v) { - return map.put(k, v); - } - - template - bool putNew(const KeyInput& k, const ValueInput& v) { - return map.putNew(k, v); - } - - Ptr lookupWithDefault(const Key& k, const Value& defaultValue) { - return map.lookupWithDefault(k, defaultValue); - } - - void remove(const Lookup& l) { - map.remove(l); - } - - friend void AutoGCRooter::trace(JSTracer* trc); - - private: - AutoHashMapRooter(const AutoHashMapRooter& hmr) = delete; - AutoHashMapRooter& operator=(const AutoHashMapRooter& hmr) = delete; - - HashMapImpl map; - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -template -class MOZ_RAII AutoHashSetRooter : protected AutoGCRooter -{ - private: - typedef js::HashSet HashSetImpl; - - public: - explicit AutoHashSetRooter(JSContext* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), set(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - typedef typename HashSetImpl::Lookup Lookup; - typedef typename HashSetImpl::Ptr Ptr; - typedef typename HashSetImpl::AddPtr AddPtr; - - bool init(uint32_t len = 16) { - return set.init(len); - } - bool initialized() const { - return set.initialized(); - } - Ptr lookup(const Lookup& l) const { - return set.lookup(l); - } - void remove(Ptr p) { - set.remove(p); - } - AddPtr lookupForAdd(const Lookup& l) const { - return set.lookupForAdd(l); - } - - bool add(AddPtr& p, const T& t) { - return set.add(p, t); - } - - bool relookupOrAdd(AddPtr& p, const Lookup& l, const T& t) { - return set.relookupOrAdd(p, l, t); - } - - typedef typename HashSetImpl::Range Range; - Range all() const { - return set.all(); - } - - typedef typename HashSetImpl::Enum Enum; - - void clear() { - set.clear(); - } - - void finish() { - set.finish(); - } - - bool empty() const { - return set.empty(); - } - - uint32_t count() const { - return set.count(); - } - - size_t capacity() const { - return set.capacity(); - } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return set.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return set.sizeOfIncludingThis(mallocSizeOf); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return set.has(l); - } - - bool put(const T& t) { - return set.put(t); - } - - bool putNew(const T& t) { - return set.putNew(t); - } - - void remove(const Lookup& l) { - set.remove(l); - } - - friend void AutoGCRooter::trace(JSTracer* trc); - - private: - AutoHashSetRooter(const AutoHashSetRooter& hmr) = delete; - AutoHashSetRooter& operator=(const AutoHashSetRooter& hmr) = delete; - - HashSetImpl set; - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/** - * Custom rooting behavior for internal and external clients. - */ -class MOZ_RAII JS_PUBLIC_API(CustomAutoRooter) : private AutoGCRooter -{ - public: - template - explicit CustomAutoRooter(const CX& cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, CUSTOM) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - friend void AutoGCRooter::trace(JSTracer* trc); - - protected: - virtual ~CustomAutoRooter() {} - - /** Supplied by derived class to trace roots. */ - virtual void trace(JSTracer* trc) = 0; - - private: - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/** A handle to an array of rooted values. */ -class HandleValueArray -{ - const size_t length_; - const Value * const elements_; - - HandleValueArray(size_t len, const Value* elements) : length_(len), elements_(elements) {} - - public: - explicit HandleValueArray(const RootedValue& value) : length_(1), elements_(value.address()) {} - - MOZ_IMPLICIT HandleValueArray(const AutoValueVector& values) - : length_(values.length()), elements_(values.begin()) {} - - template - MOZ_IMPLICIT HandleValueArray(const AutoValueArray& values) : length_(N), elements_(values.begin()) {} - - /** CallArgs must already be rooted somewhere up the stack. */ - MOZ_IMPLICIT HandleValueArray(const JS::CallArgs& args) : length_(args.length()), elements_(args.array()) {} - - /** Use with care! Only call this if the data is guaranteed to be marked. */ - static HandleValueArray fromMarkedLocation(size_t len, const Value* elements) { - return HandleValueArray(len, elements); - } - - static HandleValueArray subarray(const HandleValueArray& values, size_t startIndex, size_t len) { - MOZ_ASSERT(startIndex + len <= values.length()); - return HandleValueArray(len, values.begin() + startIndex); - } - - static HandleValueArray empty() { - return HandleValueArray(0, nullptr); - } - - size_t length() const { return length_; } - const Value* begin() const { return elements_; } - - HandleValue operator[](size_t i) const { - MOZ_ASSERT(i < length_); - return HandleValue::fromMarkedLocation(&elements_[i]); - } -}; - -} /* namespace JS */ - -/************************************************************************/ - -struct JSFreeOp { - protected: - JSRuntime* runtime_; - - explicit JSFreeOp(JSRuntime* rt) - : runtime_(rt) { } - - public: - JSRuntime* runtime() const { - MOZ_ASSERT(runtime_); - return runtime_; - } -}; - -/* Callbacks and their arguments. */ - -/************************************************************************/ - -typedef enum JSGCStatus { - JSGC_BEGIN, - JSGC_END -} JSGCStatus; - -typedef void -(* JSGCCallback)(JSContext* cx, JSGCStatus status, void* data); - -typedef void -(* JSObjectsTenuredCallback)(JSContext* cx, void* data); - -typedef enum JSFinalizeStatus { - /** - * Called when preparing to sweep a group of zones, before anything has been - * swept. The collector will not yield to the mutator before calling the - * callback with JSFINALIZE_GROUP_END status. - */ - JSFINALIZE_GROUP_START, - - /** - * Called when preparing to sweep a group of zones. Weak references to - * unmarked things have been removed and things that are not swept - * incrementally have been finalized at this point. The collector may yield - * to the mutator after this point. - */ - JSFINALIZE_GROUP_END, - - /** - * Called at the end of collection when everything has been swept. - */ - JSFINALIZE_COLLECTION_END -} JSFinalizeStatus; - -typedef void -(* JSFinalizeCallback)(JSFreeOp* fop, JSFinalizeStatus status, bool isZoneGC, void* data); - -typedef void -(* JSWeakPointerZoneGroupCallback)(JSContext* cx, void* data); - -typedef void -(* JSWeakPointerCompartmentCallback)(JSContext* cx, JSCompartment* comp, void* data); - -typedef bool -(* JSInterruptCallback)(JSContext* cx); - -typedef JSObject* -(* JSGetIncumbentGlobalCallback)(JSContext* cx); - -typedef bool -(* JSEnqueuePromiseJobCallback)(JSContext* cx, JS::HandleObject job, - JS::HandleObject allocationSite, JS::HandleObject incumbentGlobal, - void* data); - -enum class PromiseRejectionHandlingState { - Unhandled, - Handled -}; - -typedef void -(* JSPromiseRejectionTrackerCallback)(JSContext* cx, JS::HandleObject promise, - PromiseRejectionHandlingState state, void* data); - -typedef void -(* JSProcessPromiseCallback)(JSContext* cx, JS::HandleObject promise); - -/** - * Possible exception types. These types are part of a JSErrorFormatString - * structure. They define which error to throw in case of a runtime error. - * - * JSEXN_WARN is used for warnings in js.msg files (for instance because we - * don't want to prepend 'Error:' to warning messages). This value can go away - * if we ever decide to use an entirely separate mechanism for warnings. - */ -typedef enum JSExnType { - JSEXN_ERR, - JSEXN_FIRST = JSEXN_ERR, - JSEXN_INTERNALERR, - JSEXN_EVALERR, - JSEXN_RANGEERR, - JSEXN_REFERENCEERR, - JSEXN_SYNTAXERR, - JSEXN_TYPEERR, - JSEXN_URIERR, - JSEXN_DEBUGGEEWOULDRUN, - JSEXN_WASMCOMPILEERROR, - JSEXN_WASMRUNTIMEERROR, - JSEXN_WARN, - JSEXN_LIMIT -} JSExnType; - -typedef struct JSErrorFormatString { - /** The error message name in ASCII. */ - const char* name; - - /** The error format string in ASCII. */ - const char* format; - - /** The number of arguments to expand in the formatted error message. */ - uint16_t argCount; - - /** One of the JSExnType constants above. */ - int16_t exnType; -} JSErrorFormatString; - -typedef const JSErrorFormatString* -(* JSErrorCallback)(void* userRef, const unsigned errorNumber); - -typedef bool -(* JSLocaleToUpperCase)(JSContext* cx, JS::HandleString src, JS::MutableHandleValue rval); - -typedef bool -(* JSLocaleToLowerCase)(JSContext* cx, JS::HandleString src, JS::MutableHandleValue rval); - -typedef bool -(* JSLocaleCompare)(JSContext* cx, JS::HandleString src1, JS::HandleString src2, - JS::MutableHandleValue rval); - -typedef bool -(* JSLocaleToUnicode)(JSContext* cx, const char* src, JS::MutableHandleValue rval); - -/** - * Callback used to ask the embedding for the cross compartment wrapper handler - * that implements the desired prolicy for this kind of object in the - * destination compartment. |obj| is the object to be wrapped. If |existing| is - * non-nullptr, it will point to an existing wrapper object that should be - * re-used if possible. |existing| is guaranteed to be a cross-compartment - * wrapper with a lazily-defined prototype and the correct global. It is - * guaranteed not to wrap a function. - */ -typedef JSObject* -(* JSWrapObjectCallback)(JSContext* cx, JS::HandleObject existing, JS::HandleObject obj); - -/** - * Callback used by the wrap hook to ask the embedding to prepare an object - * for wrapping in a context. This might include unwrapping other wrappers - * or even finding a more suitable object for the new compartment. - */ -typedef void -(* JSPreWrapCallback)(JSContext* cx, JS::HandleObject scope, JS::HandleObject obj, - JS::HandleObject objectPassedToWrap, - JS::MutableHandleObject retObj); - -struct JSWrapObjectCallbacks -{ - JSWrapObjectCallback wrap; - JSPreWrapCallback preWrap; -}; - -typedef void -(* JSDestroyCompartmentCallback)(JSFreeOp* fop, JSCompartment* compartment); - -typedef size_t -(* JSSizeOfIncludingThisCompartmentCallback)(mozilla::MallocSizeOf mallocSizeOf, - JSCompartment* compartment); - -typedef void -(* JSZoneCallback)(JS::Zone* zone); - -typedef void -(* JSCompartmentNameCallback)(JSContext* cx, JSCompartment* compartment, - char* buf, size_t bufsize); - -/************************************************************************/ - -static MOZ_ALWAYS_INLINE JS::Value -JS_NumberValue(double d) -{ - int32_t i; - d = JS::CanonicalizeNaN(d); - if (mozilla::NumberIsInt32(d, &i)) - return JS::Int32Value(i); - return JS::DoubleValue(d); -} - -/************************************************************************/ - -JS_PUBLIC_API(bool) -JS_StringHasBeenPinned(JSContext* cx, JSString* str); - -namespace JS { - -/** - * Container class for passing in script source buffers to the JS engine. This - * not only groups the buffer and length values, it also provides a way to - * optionally pass ownership of the buffer to the JS engine without copying. - * Rules for use: - * - * 1) The data array must be allocated with js_malloc() or js_realloc() if - * ownership is being granted to the SourceBufferHolder. - * 2) If ownership is not given to the SourceBufferHolder, then the memory - * must be kept alive until the JS compilation is complete. - * 3) Any code calling SourceBufferHolder::take() must guarantee to keep the - * memory alive until JS compilation completes. Normally only the JS - * engine should be calling take(). - * - * Example use: - * - * size_t length = 512; - * char16_t* chars = static_cast(js_malloc(sizeof(char16_t) * length)); - * JS::SourceBufferHolder srcBuf(chars, length, JS::SourceBufferHolder::GiveOwnership); - * JS::Compile(cx, options, srcBuf); - */ -class MOZ_STACK_CLASS SourceBufferHolder final -{ - public: - enum Ownership { - NoOwnership, - GiveOwnership - }; - - SourceBufferHolder(const char16_t* data, size_t dataLength, Ownership ownership) - : data_(data), - length_(dataLength), - ownsChars_(ownership == GiveOwnership) - { - // Ensure that null buffers properly return an unowned, empty, - // null-terminated string. - static const char16_t NullChar_ = 0; - if (!get()) { - data_ = &NullChar_; - length_ = 0; - ownsChars_ = false; - } - } - - SourceBufferHolder(SourceBufferHolder&& other) - : data_(other.data_), - length_(other.length_), - ownsChars_(other.ownsChars_) - { - other.data_ = nullptr; - other.length_ = 0; - other.ownsChars_ = false; - } - - ~SourceBufferHolder() { - if (ownsChars_) - js_free(const_cast(data_)); - } - - // Access the underlying source buffer without affecting ownership. - const char16_t* get() const { return data_; } - - // Length of the source buffer in char16_t code units (not bytes) - size_t length() const { return length_; } - - // Returns true if the SourceBufferHolder owns the buffer and will free - // it upon destruction. If true, it is legal to call take(). - bool ownsChars() const { return ownsChars_; } - - // Retrieve and take ownership of the underlying data buffer. The caller - // is now responsible for calling js_free() on the returned value, *but only - // after JS script compilation has completed*. - // - // After the buffer has been taken the SourceBufferHolder functions as if - // it had been constructed on an unowned buffer; get() and length() still - // work. In order for this to be safe the taken buffer must be kept alive - // until after JS script compilation completes as noted above. - // - // Note, it's the caller's responsibility to check ownsChars() before taking - // the buffer. Taking and then free'ing an unowned buffer will have dire - // consequences. - char16_t* take() { - MOZ_ASSERT(ownsChars_); - ownsChars_ = false; - return const_cast(data_); - } - - private: - SourceBufferHolder(SourceBufferHolder&) = delete; - SourceBufferHolder& operator=(SourceBufferHolder&) = delete; - - const char16_t* data_; - size_t length_; - bool ownsChars_; -}; - -} /* namespace JS */ - -/************************************************************************/ - -/* Property attributes, set in JSPropertySpec and passed to API functions. - * - * NB: The data structure in which some of these values are stored only uses - * a uint8_t to store the relevant information. Proceed with caution if - * trying to reorder or change the the first byte worth of flags. - */ -#define JSPROP_ENUMERATE 0x01 /* property is visible to for/in loop */ -#define JSPROP_READONLY 0x02 /* not settable: assignment is no-op. - This flag is only valid when neither - JSPROP_GETTER nor JSPROP_SETTER is - set. */ -#define JSPROP_PERMANENT 0x04 /* property cannot be deleted */ -#define JSPROP_PROPOP_ACCESSORS 0x08 /* Passed to JS_Define(UC)Property* and - JS_DefineElement if getters/setters - are JSGetterOp/JSSetterOp */ -#define JSPROP_GETTER 0x10 /* property holds getter function */ -#define JSPROP_SETTER 0x20 /* property holds setter function */ -#define JSPROP_SHARED 0x40 /* don't allocate a value slot for this - property; don't copy the property on - set of the same-named property in an - object that delegates to a prototype - containing this property */ -#define JSPROP_INTERNAL_USE_BIT 0x80 /* internal JS engine use only */ -#define JSFUN_STUB_GSOPS 0x200 /* use JS_PropertyStub getter/setter - instead of defaulting to class gsops - for property holding function */ - -#define JSFUN_CONSTRUCTOR 0x400 /* native that can be called as a ctor */ - -// 0x800 /* Unused */ - -#define JSFUN_HAS_REST 0x1000 /* function has ...rest parameter. */ - -#define JSFUN_FLAGS_MASK 0x1e00 /* | of all the JSFUN_* flags */ - -/* - * If set, will allow redefining a non-configurable property, but only on a - * non-DOM global. This is a temporary hack that will need to go away in bug - * 1105518. - */ -#define JSPROP_REDEFINE_NONCONFIGURABLE 0x1000 - -/* - * Resolve hooks and enumerate hooks must pass this flag when calling - * JS_Define* APIs to reify lazily-defined properties. - * - * JSPROP_RESOLVING is used only with property-defining APIs. It tells the - * engine to skip the resolve hook when performing the lookup at the beginning - * of property definition. This keeps the resolve hook from accidentally - * triggering itself: unchecked recursion. - * - * For enumerate hooks, triggering the resolve hook would be merely silly, not - * fatal, except in some cases involving non-configurable properties. - */ -#define JSPROP_RESOLVING 0x2000 - -#define JSPROP_IGNORE_ENUMERATE 0x4000 /* ignore the value in JSPROP_ENUMERATE. - This flag only valid when defining over - an existing property. */ -#define JSPROP_IGNORE_READONLY 0x8000 /* ignore the value in JSPROP_READONLY. - This flag only valid when defining over - an existing property. */ -#define JSPROP_IGNORE_PERMANENT 0x10000 /* ignore the value in JSPROP_PERMANENT. - This flag only valid when defining over - an existing property. */ -#define JSPROP_IGNORE_VALUE 0x20000 /* ignore the Value in the descriptor. Nothing was - specified when passed to Object.defineProperty - from script. */ - -/** Microseconds since the epoch, midnight, January 1, 1970 UTC. */ -extern JS_PUBLIC_API(int64_t) -JS_Now(void); - -/** Don't want to export data, so provide accessors for non-inline Values. */ -extern JS_PUBLIC_API(JS::Value) -JS_GetNaNValue(JSContext* cx); - -extern JS_PUBLIC_API(JS::Value) -JS_GetNegativeInfinityValue(JSContext* cx); - -extern JS_PUBLIC_API(JS::Value) -JS_GetPositiveInfinityValue(JSContext* cx); - -extern JS_PUBLIC_API(JS::Value) -JS_GetEmptyStringValue(JSContext* cx); - -extern JS_PUBLIC_API(JSString*) -JS_GetEmptyString(JSContext* cx); - -extern JS_PUBLIC_API(bool) -JS_ValueToObject(JSContext* cx, JS::HandleValue v, JS::MutableHandleObject objp); - -extern JS_PUBLIC_API(JSFunction*) -JS_ValueToFunction(JSContext* cx, JS::HandleValue v); - -extern JS_PUBLIC_API(JSFunction*) -JS_ValueToConstructor(JSContext* cx, JS::HandleValue v); - -extern JS_PUBLIC_API(JSString*) -JS_ValueToSource(JSContext* cx, JS::Handle v); - -extern JS_PUBLIC_API(bool) -JS_DoubleIsInt32(double d, int32_t* ip); - -extern JS_PUBLIC_API(JSType) -JS_TypeOfValue(JSContext* cx, JS::Handle v); - -namespace JS { - -extern JS_PUBLIC_API(const char*) -InformalValueTypeName(const JS::Value& v); - -} /* namespace JS */ - -extern JS_PUBLIC_API(bool) -JS_StrictlyEqual(JSContext* cx, JS::Handle v1, JS::Handle v2, bool* equal); - -extern JS_PUBLIC_API(bool) -JS_LooselyEqual(JSContext* cx, JS::Handle v1, JS::Handle v2, bool* equal); - -extern JS_PUBLIC_API(bool) -JS_SameValue(JSContext* cx, JS::Handle v1, JS::Handle v2, bool* same); - -/** True iff fun is the global eval function. */ -extern JS_PUBLIC_API(bool) -JS_IsBuiltinEvalFunction(JSFunction* fun); - -/** True iff fun is the Function constructor. */ -extern JS_PUBLIC_API(bool) -JS_IsBuiltinFunctionConstructor(JSFunction* fun); - -/************************************************************************/ - -/* - * Locking, contexts, and memory allocation. - * - * It is important that SpiderMonkey be initialized, and the first context - * be created, in a single-threaded fashion. Otherwise the behavior of the - * library is undefined. - * See: http://developer.mozilla.org/en/docs/Category:JSAPI_Reference - */ - -extern JS_PUBLIC_API(JSContext*) -JS_NewContext(uint32_t maxbytes, - uint32_t maxNurseryBytes = JS::DefaultNurseryBytes, - JSContext* parentContext = nullptr); - -extern JS_PUBLIC_API(void) -JS_DestroyContext(JSContext* cx); - -typedef double (*JS_CurrentEmbedderTimeFunction)(); - -/** - * The embedding can specify a time function that will be used in some - * situations. The function can return the time however it likes; but - * the norm is to return times in units of milliseconds since an - * arbitrary, but consistent, epoch. If the time function is not set, - * a built-in default will be used. - */ -JS_PUBLIC_API(void) -JS_SetCurrentEmbedderTimeFunction(JS_CurrentEmbedderTimeFunction timeFn); - -/** - * Return the time as computed using the current time function, or a - * suitable default if one has not been set. - */ -JS_PUBLIC_API(double) -JS_GetCurrentEmbedderTime(); - -JS_PUBLIC_API(void*) -JS_GetContextPrivate(JSContext* cx); - -JS_PUBLIC_API(void) -JS_SetContextPrivate(JSContext* cx, void* data); - -extern JS_PUBLIC_API(JSContext*) -JS_GetParentContext(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_BeginRequest(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_EndRequest(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_SetFutexCanWait(JSContext* cx); - -namespace js { - -void -AssertHeapIsIdle(JSRuntime* rt); - -} /* namespace js */ - -class MOZ_RAII JSAutoRequest -{ - public: - explicit JSAutoRequest(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mContext(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - JS_BeginRequest(mContext); - } - ~JSAutoRequest() { - JS_EndRequest(mContext); - } - - protected: - JSContext* mContext; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - -#if 0 - private: - static void* operator new(size_t) CPP_THROW_NEW { return 0; } - static void operator delete(void*, size_t) { } -#endif -}; - -extern JS_PUBLIC_API(JSVersion) -JS_GetVersion(JSContext* cx); - -/** - * Mutate the version on the compartment. This is generally discouraged, but - * necessary to support the version mutation in the js and xpc shell command - * set. - * - * It would be nice to put this in jsfriendapi, but the linkage requirements - * of the shells make that impossible. - */ -JS_PUBLIC_API(void) -JS_SetVersionForCompartment(JSCompartment* compartment, JSVersion version); - -extern JS_PUBLIC_API(const char*) -JS_VersionToString(JSVersion version); - -extern JS_PUBLIC_API(JSVersion) -JS_StringToVersion(const char* string); - -namespace JS { - -class JS_PUBLIC_API(ContextOptions) { - public: - ContextOptions() - : baseline_(true), - ion_(true), - asmJS_(true), - wasm_(false), - wasmAlwaysBaseline_(false), - throwOnAsmJSValidationFailure_(false), - nativeRegExp_(true), - unboxedArrays_(false), - asyncStack_(true), - throwOnDebuggeeWouldRun_(true), - dumpStackOnDebuggeeWouldRun_(false), - werror_(false), - strictMode_(false), - extraWarnings_(false) - { - } - - bool baseline() const { return baseline_; } - ContextOptions& setBaseline(bool flag) { - baseline_ = flag; - return *this; - } - ContextOptions& toggleBaseline() { - baseline_ = !baseline_; - return *this; - } - - bool ion() const { return ion_; } - ContextOptions& setIon(bool flag) { - ion_ = flag; - return *this; - } - ContextOptions& toggleIon() { - ion_ = !ion_; - return *this; - } - - bool asmJS() const { return asmJS_; } - ContextOptions& setAsmJS(bool flag) { - asmJS_ = flag; - return *this; - } - ContextOptions& toggleAsmJS() { - asmJS_ = !asmJS_; - return *this; - } - - bool wasm() const { return wasm_; } - ContextOptions& setWasm(bool flag) { - wasm_ = flag; - return *this; - } - ContextOptions& toggleWasm() { - wasm_ = !wasm_; - return *this; - } - - bool wasmAlwaysBaseline() const { return wasmAlwaysBaseline_; } - ContextOptions& setWasmAlwaysBaseline(bool flag) { - wasmAlwaysBaseline_ = flag; - return *this; - } - ContextOptions& toggleWasmAlwaysBaseline() { - wasmAlwaysBaseline_ = !wasmAlwaysBaseline_; - return *this; - } - - bool throwOnAsmJSValidationFailure() const { return throwOnAsmJSValidationFailure_; } - ContextOptions& setThrowOnAsmJSValidationFailure(bool flag) { - throwOnAsmJSValidationFailure_ = flag; - return *this; - } - ContextOptions& toggleThrowOnAsmJSValidationFailure() { - throwOnAsmJSValidationFailure_ = !throwOnAsmJSValidationFailure_; - return *this; - } - - bool nativeRegExp() const { return nativeRegExp_; } - ContextOptions& setNativeRegExp(bool flag) { - nativeRegExp_ = flag; - return *this; - } - - bool unboxedArrays() const { return unboxedArrays_; } - ContextOptions& setUnboxedArrays(bool flag) { - unboxedArrays_ = flag; - return *this; - } - - bool asyncStack() const { return asyncStack_; } - ContextOptions& setAsyncStack(bool flag) { - asyncStack_ = flag; - return *this; - } - - bool throwOnDebuggeeWouldRun() const { return throwOnDebuggeeWouldRun_; } - ContextOptions& setThrowOnDebuggeeWouldRun(bool flag) { - throwOnDebuggeeWouldRun_ = flag; - return *this; - } - - bool dumpStackOnDebuggeeWouldRun() const { return dumpStackOnDebuggeeWouldRun_; } - ContextOptions& setDumpStackOnDebuggeeWouldRun(bool flag) { - dumpStackOnDebuggeeWouldRun_ = flag; - return *this; - } - - bool werror() const { return werror_; } - ContextOptions& setWerror(bool flag) { - werror_ = flag; - return *this; - } - ContextOptions& toggleWerror() { - werror_ = !werror_; - return *this; - } - - bool strictMode() const { return strictMode_; } - ContextOptions& setStrictMode(bool flag) { - strictMode_ = flag; - return *this; - } - ContextOptions& toggleStrictMode() { - strictMode_ = !strictMode_; - return *this; - } - - bool extraWarnings() const { return extraWarnings_; } - ContextOptions& setExtraWarnings(bool flag) { - extraWarnings_ = flag; - return *this; - } - ContextOptions& toggleExtraWarnings() { - extraWarnings_ = !extraWarnings_; - return *this; - } - - private: - bool baseline_ : 1; - bool ion_ : 1; - bool asmJS_ : 1; - bool wasm_ : 1; - bool wasmAlwaysBaseline_ : 1; - bool throwOnAsmJSValidationFailure_ : 1; - bool nativeRegExp_ : 1; - bool unboxedArrays_ : 1; - bool asyncStack_ : 1; - bool throwOnDebuggeeWouldRun_ : 1; - bool dumpStackOnDebuggeeWouldRun_ : 1; - bool werror_ : 1; - bool strictMode_ : 1; - bool extraWarnings_ : 1; -}; - -JS_PUBLIC_API(ContextOptions&) -ContextOptionsRef(JSContext* cx); - -/** - * Initialize the runtime's self-hosted code. Embeddings should call this - * exactly once per runtime/context, before the first JS_NewGlobalObject - * call. - */ -JS_PUBLIC_API(bool) -InitSelfHostedCode(JSContext* cx); - -/** - * Asserts (in debug and release builds) that `obj` belongs to the current - * thread's context. - */ -JS_PUBLIC_API(void) -AssertObjectBelongsToCurrentThread(JSObject* obj); - -} /* namespace JS */ - -extern JS_PUBLIC_API(const char*) -JS_GetImplementationVersion(void); - -extern JS_PUBLIC_API(void) -JS_SetDestroyCompartmentCallback(JSContext* cx, JSDestroyCompartmentCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetSizeOfIncludingThisCompartmentCallback(JSContext* cx, - JSSizeOfIncludingThisCompartmentCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetDestroyZoneCallback(JSContext* cx, JSZoneCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetSweepZoneCallback(JSContext* cx, JSZoneCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetCompartmentNameCallback(JSContext* cx, JSCompartmentNameCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetWrapObjectCallbacks(JSContext* cx, const JSWrapObjectCallbacks* callbacks); - -extern JS_PUBLIC_API(void) -JS_SetCompartmentPrivate(JSCompartment* compartment, void* data); - -extern JS_PUBLIC_API(void*) -JS_GetCompartmentPrivate(JSCompartment* compartment); - -extern JS_PUBLIC_API(void) -JS_SetZoneUserData(JS::Zone* zone, void* data); - -extern JS_PUBLIC_API(void*) -JS_GetZoneUserData(JS::Zone* zone); - -extern JS_PUBLIC_API(bool) -JS_WrapObject(JSContext* cx, JS::MutableHandleObject objp); - -extern JS_PUBLIC_API(bool) -JS_WrapValue(JSContext* cx, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(JSObject*) -JS_TransplantObject(JSContext* cx, JS::HandleObject origobj, JS::HandleObject target); - -extern JS_PUBLIC_API(bool) -JS_RefreshCrossCompartmentWrappers(JSContext* cx, JS::Handle obj); - -/* - * At any time, a JSContext has a current (possibly-nullptr) compartment. - * Compartments are described in: - * - * developer.mozilla.org/en-US/docs/SpiderMonkey/SpiderMonkey_compartments - * - * The current compartment of a context may be changed. The preferred way to do - * this is with JSAutoCompartment: - * - * void foo(JSContext* cx, JSObject* obj) { - * // in some compartment 'c' - * { - * JSAutoCompartment ac(cx, obj); // constructor enters - * // in the compartment of 'obj' - * } // destructor leaves - * // back in compartment 'c' - * } - * - * For more complicated uses that don't neatly fit in a C++ stack frame, the - * compartment can entered and left using separate function calls: - * - * void foo(JSContext* cx, JSObject* obj) { - * // in 'oldCompartment' - * JSCompartment* oldCompartment = JS_EnterCompartment(cx, obj); - * // in the compartment of 'obj' - * JS_LeaveCompartment(cx, oldCompartment); - * // back in 'oldCompartment' - * } - * - * Note: these calls must still execute in a LIFO manner w.r.t all other - * enter/leave calls on the context. Furthermore, only the return value of a - * JS_EnterCompartment call may be passed as the 'oldCompartment' argument of - * the corresponding JS_LeaveCompartment call. - */ - -class MOZ_RAII JS_PUBLIC_API(JSAutoCompartment) -{ - JSContext* cx_; - JSCompartment* oldCompartment_; - public: - JSAutoCompartment(JSContext* cx, JSObject* target - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - JSAutoCompartment(JSContext* cx, JSScript* target - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~JSAutoCompartment(); - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -class MOZ_RAII JS_PUBLIC_API(JSAutoNullableCompartment) -{ - JSContext* cx_; - JSCompartment* oldCompartment_; - public: - explicit JSAutoNullableCompartment(JSContext* cx, JSObject* targetOrNull - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~JSAutoNullableCompartment(); - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/** NB: This API is infallible; a nullptr return value does not indicate error. */ -extern JS_PUBLIC_API(JSCompartment*) -JS_EnterCompartment(JSContext* cx, JSObject* target); - -extern JS_PUBLIC_API(void) -JS_LeaveCompartment(JSContext* cx, JSCompartment* oldCompartment); - -typedef void (*JSIterateCompartmentCallback)(JSContext* cx, void* data, JSCompartment* compartment); - -/** - * This function calls |compartmentCallback| on every compartment. Beware that - * there is no guarantee that the compartment will survive after the callback - * returns. Also, barriers are disabled via the TraceSession. - */ -extern JS_PUBLIC_API(void) -JS_IterateCompartments(JSContext* cx, void* data, - JSIterateCompartmentCallback compartmentCallback); - -/** - * Initialize standard JS class constructors, prototypes, and any top-level - * functions and constants associated with the standard classes (e.g. isNaN - * for Number). - * - * NB: This sets cx's global object to obj if it was null. - */ -extern JS_PUBLIC_API(bool) -JS_InitStandardClasses(JSContext* cx, JS::Handle obj); - -/** - * Resolve id, which must contain either a string or an int, to a standard - * class name in obj if possible, defining the class's constructor and/or - * prototype and storing true in *resolved. If id does not name a standard - * class or a top-level property induced by initializing a standard class, - * store false in *resolved and just return true. Return false on error, - * as usual for bool result-typed API entry points. - * - * This API can be called directly from a global object class's resolve op, - * to define standard classes lazily. The class's enumerate op should call - * JS_EnumerateStandardClasses(cx, obj), to define eagerly during for..in - * loops any classes not yet resolved lazily. - */ -extern JS_PUBLIC_API(bool) -JS_ResolveStandardClass(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* resolved); - -extern JS_PUBLIC_API(bool) -JS_MayResolveStandardClass(const JSAtomState& names, jsid id, JSObject* maybeObj); - -extern JS_PUBLIC_API(bool) -JS_EnumerateStandardClasses(JSContext* cx, JS::HandleObject obj); - -extern JS_PUBLIC_API(bool) -JS_GetClassObject(JSContext* cx, JSProtoKey key, JS::MutableHandle objp); - -extern JS_PUBLIC_API(bool) -JS_GetClassPrototype(JSContext* cx, JSProtoKey key, JS::MutableHandle objp); - -namespace JS { - -/* - * Determine if the given object is an instance/prototype/constructor for a standard - * class. If so, return the associated JSProtoKey. If not, return JSProto_Null. - */ - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardInstance(JSObject* obj); - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardPrototype(JSObject* obj); - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardInstanceOrPrototype(JSObject* obj); - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardConstructor(JSObject* obj); - -extern JS_PUBLIC_API(void) -ProtoKeyToId(JSContext* cx, JSProtoKey key, JS::MutableHandleId idp); - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSProtoKey) -JS_IdToProtoKey(JSContext* cx, JS::HandleId id); - -/** - * Returns the original value of |Function.prototype| from the global object in - * which |forObj| was created. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetFunctionPrototype(JSContext* cx, JS::HandleObject forObj); - -/** - * Returns the original value of |Object.prototype| from the global object in - * which |forObj| was created. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetObjectPrototype(JSContext* cx, JS::HandleObject forObj); - -/** - * Returns the original value of |Array.prototype| from the global object in - * which |forObj| was created. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetArrayPrototype(JSContext* cx, JS::HandleObject forObj); - -/** - * Returns the original value of |Error.prototype| from the global - * object of the current compartment of cx. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetErrorPrototype(JSContext* cx); - -/** - * Returns the %IteratorPrototype% object that all built-in iterator prototype - * chains go through for the global object of the current compartment of cx. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetIteratorPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -JS_GetGlobalForObject(JSContext* cx, JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_IsGlobalObject(JSObject* obj); - -extern JS_PUBLIC_API(JSObject*) -JS_GlobalLexicalEnvironment(JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_HasExtensibleLexicalEnvironment(JSObject* obj); - -extern JS_PUBLIC_API(JSObject*) -JS_ExtensibleLexicalEnvironment(JSObject* obj); - -/** - * May return nullptr, if |c| never had a global (e.g. the atoms compartment), - * or if |c|'s global has been collected. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetGlobalForCompartmentOrNull(JSContext* cx, JSCompartment* c); - -namespace JS { - -extern JS_PUBLIC_API(JSObject*) -CurrentGlobalOrNull(JSContext* cx); - -} // namespace JS - -/** - * Add 'Reflect.parse', a SpiderMonkey extension, to the Reflect object on the - * given global. - */ -extern JS_PUBLIC_API(bool) -JS_InitReflectParse(JSContext* cx, JS::HandleObject global); - -/** - * Add various profiling-related functions as properties of the given object. - * Defined in builtin/Profilers.cpp. - */ -extern JS_PUBLIC_API(bool) -JS_DefineProfilingFunctions(JSContext* cx, JS::HandleObject obj); - -/* Defined in vm/Debugger.cpp. */ -extern JS_PUBLIC_API(bool) -JS_DefineDebuggerObject(JSContext* cx, JS::HandleObject obj); - -#ifdef JS_HAS_CTYPES -/** - * Initialize the 'ctypes' object on a global variable 'obj'. The 'ctypes' - * object will be sealed. - */ -extern JS_PUBLIC_API(bool) -JS_InitCTypesClass(JSContext* cx, JS::HandleObject global); - -/** - * Convert a unicode string 'source' of length 'slen' to the platform native - * charset, returning a null-terminated string allocated with JS_malloc. On - * failure, this function should report an error. - */ -typedef char* -(* JSCTypesUnicodeToNativeFun)(JSContext* cx, const char16_t* source, size_t slen); - -/** - * Set of function pointers that ctypes can use for various internal functions. - * See JS_SetCTypesCallbacks below. Providing nullptr for a function is safe, - * and will result in the applicable ctypes functionality not being available. - */ -struct JSCTypesCallbacks { - JSCTypesUnicodeToNativeFun unicodeToNative; -}; - -typedef struct JSCTypesCallbacks JSCTypesCallbacks; - -/** - * Set the callbacks on the provided 'ctypesObj' object. 'callbacks' should be a - * pointer to static data that exists for the lifetime of 'ctypesObj', but it - * may safely be altered after calling this function and without having - * to call this function again. - */ -extern JS_PUBLIC_API(void) -JS_SetCTypesCallbacks(JSObject* ctypesObj, const JSCTypesCallbacks* callbacks); -#endif - -extern JS_PUBLIC_API(void*) -JS_malloc(JSContext* cx, size_t nbytes); - -extern JS_PUBLIC_API(void*) -JS_realloc(JSContext* cx, void* p, size_t oldBytes, size_t newBytes); - -/** - * A wrapper for js_free(p) that may delay js_free(p) invocation as a - * performance optimization. - * cx may be nullptr. - */ -extern JS_PUBLIC_API(void) -JS_free(JSContext* cx, void* p); - -/** - * A wrapper for js_free(p) that may delay js_free(p) invocation as a - * performance optimization as specified by the given JSFreeOp instance. - */ -extern JS_PUBLIC_API(void) -JS_freeop(JSFreeOp* fop, void* p); - -extern JS_PUBLIC_API(void) -JS_updateMallocCounter(JSContext* cx, size_t nbytes); - -extern JS_PUBLIC_API(char*) -JS_strdup(JSContext* cx, const char* s); - -/** - * Register externally maintained GC roots. - * - * traceOp: the trace operation. For each root the implementation should call - * JS::TraceEdge whenever the root contains a traceable thing. - * data: the data argument to pass to each invocation of traceOp. - */ -extern JS_PUBLIC_API(bool) -JS_AddExtraGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data); - -/** Undo a call to JS_AddExtraGCRootsTracer. */ -extern JS_PUBLIC_API(void) -JS_RemoveExtraGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data); - -/* - * Garbage collector API. - */ -extern JS_PUBLIC_API(void) -JS_GC(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_MaybeGC(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_SetGCCallback(JSContext* cx, JSGCCallback cb, void* data); - -extern JS_PUBLIC_API(void) -JS_SetObjectsTenuredCallback(JSContext* cx, JSObjectsTenuredCallback cb, - void* data); - -extern JS_PUBLIC_API(bool) -JS_AddFinalizeCallback(JSContext* cx, JSFinalizeCallback cb, void* data); - -extern JS_PUBLIC_API(void) -JS_RemoveFinalizeCallback(JSContext* cx, JSFinalizeCallback cb); - -/* - * Weak pointers and garbage collection - * - * Weak pointers are by their nature not marked as part of garbage collection, - * but they may need to be updated in two cases after a GC: - * - * 1) Their referent was found not to be live and is about to be finalized - * 2) Their referent has been moved by a compacting GC - * - * To handle this, any part of the system that maintain weak pointers to - * JavaScript GC things must register a callback with - * JS_(Add,Remove)WeakPointer{ZoneGroup,Compartment}Callback(). This callback - * must then call JS_UpdateWeakPointerAfterGC() on all weak pointers it knows - * about. - * - * Since sweeping is incremental, we have several callbacks to avoid repeatedly - * having to visit all embedder structures. The WeakPointerZoneGroupCallback is - * called once for each strongly connected group of zones, whereas the - * WeakPointerCompartmentCallback is called once for each compartment that is - * visited while sweeping. Structures that cannot contain references in more - * than one compartment should sweep the relevant per-compartment structures - * using the latter callback to minimizer per-slice overhead. - * - * The argument to JS_UpdateWeakPointerAfterGC() is an in-out param. If the - * referent is about to be finalized the pointer will be set to null. If the - * referent has been moved then the pointer will be updated to point to the new - * location. - * - * Callers of this method are responsible for updating any state that is - * dependent on the object's address. For example, if the object's address is - * used as a key in a hashtable, then the object must be removed and - * re-inserted with the correct hash. - */ - -extern JS_PUBLIC_API(bool) -JS_AddWeakPointerZoneGroupCallback(JSContext* cx, JSWeakPointerZoneGroupCallback cb, void* data); - -extern JS_PUBLIC_API(void) -JS_RemoveWeakPointerZoneGroupCallback(JSContext* cx, JSWeakPointerZoneGroupCallback cb); - -extern JS_PUBLIC_API(bool) -JS_AddWeakPointerCompartmentCallback(JSContext* cx, JSWeakPointerCompartmentCallback cb, - void* data); - -extern JS_PUBLIC_API(void) -JS_RemoveWeakPointerCompartmentCallback(JSContext* cx, JSWeakPointerCompartmentCallback cb); - -extern JS_PUBLIC_API(void) -JS_UpdateWeakPointerAfterGC(JS::Heap* objp); - -extern JS_PUBLIC_API(void) -JS_UpdateWeakPointerAfterGCUnbarriered(JSObject** objp); - -typedef enum JSGCParamKey { - /** Maximum nominal heap before last ditch GC. */ - JSGC_MAX_BYTES = 0, - - /** Number of JS_malloc bytes before last ditch GC. */ - JSGC_MAX_MALLOC_BYTES = 1, - - /** Amount of bytes allocated by the GC. */ - JSGC_BYTES = 3, - - /** Number of times GC has been invoked. Includes both major and minor GC. */ - JSGC_NUMBER = 4, - - /** Select GC mode. */ - JSGC_MODE = 6, - - /** Number of cached empty GC chunks. */ - JSGC_UNUSED_CHUNKS = 7, - - /** Total number of allocated GC chunks. */ - JSGC_TOTAL_CHUNKS = 8, - - /** Max milliseconds to spend in an incremental GC slice. */ - JSGC_SLICE_TIME_BUDGET = 9, - - /** Maximum size the GC mark stack can grow to. */ - JSGC_MARK_STACK_LIMIT = 10, - - /** - * GCs less than this far apart in time will be considered 'high-frequency GCs'. - * See setGCLastBytes in jsgc.cpp. - */ - JSGC_HIGH_FREQUENCY_TIME_LIMIT = 11, - - /** Start of dynamic heap growth. */ - JSGC_HIGH_FREQUENCY_LOW_LIMIT = 12, - - /** End of dynamic heap growth. */ - JSGC_HIGH_FREQUENCY_HIGH_LIMIT = 13, - - /** Upper bound of heap growth. */ - JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX = 14, - - /** Lower bound of heap growth. */ - JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN = 15, - - /** Heap growth for low frequency GCs. */ - JSGC_LOW_FREQUENCY_HEAP_GROWTH = 16, - - /** - * If false, the heap growth factor is fixed at 3. If true, it is determined - * based on whether GCs are high- or low- frequency. - */ - JSGC_DYNAMIC_HEAP_GROWTH = 17, - - /** If true, high-frequency GCs will use a longer mark slice. */ - JSGC_DYNAMIC_MARK_SLICE = 18, - - /** Lower limit after which we limit the heap growth. */ - JSGC_ALLOCATION_THRESHOLD = 19, - - /** - * We try to keep at least this many unused chunks in the free chunk pool at - * all times, even after a shrinking GC. - */ - JSGC_MIN_EMPTY_CHUNK_COUNT = 21, - - /** We never keep more than this many unused chunks in the free chunk pool. */ - JSGC_MAX_EMPTY_CHUNK_COUNT = 22, - - /** Whether compacting GC is enabled. */ - JSGC_COMPACTING_ENABLED = 23, - - /** If true, painting can trigger IGC slices. */ - JSGC_REFRESH_FRAME_SLICES_ENABLED = 24, -} JSGCParamKey; - -extern JS_PUBLIC_API(void) -JS_SetGCParameter(JSContext* cx, JSGCParamKey key, uint32_t value); - -extern JS_PUBLIC_API(uint32_t) -JS_GetGCParameter(JSContext* cx, JSGCParamKey key); - -extern JS_PUBLIC_API(void) -JS_SetGCParametersBasedOnAvailableMemory(JSContext* cx, uint32_t availMem); - -/** - * Create a new JSString whose chars member refers to external memory, i.e., - * memory requiring application-specific finalization. - */ -extern JS_PUBLIC_API(JSString*) -JS_NewExternalString(JSContext* cx, const char16_t* chars, size_t length, - const JSStringFinalizer* fin); - -/** - * Return whether 'str' was created with JS_NewExternalString or - * JS_NewExternalStringWithClosure. - */ -extern JS_PUBLIC_API(bool) -JS_IsExternalString(JSString* str); - -/** - * Return the 'fin' arg passed to JS_NewExternalString. - */ -extern JS_PUBLIC_API(const JSStringFinalizer*) -JS_GetExternalStringFinalizer(JSString* str); - -/** - * Set the size of the native stack that should not be exceed. To disable - * stack size checking pass 0. - * - * SpiderMonkey allows for a distinction between system code (such as GCs, which - * may incidentally be triggered by script but are not strictly performed on - * behalf of such script), trusted script (as determined by JS_SetTrustedPrincipals), - * and untrusted script. Each kind of code may have a different stack quota, - * allowing embedders to keep higher-priority machinery running in the face of - * scripted stack exhaustion by something else. - * - * The stack quotas for each kind of code should be monotonically descending, - * and may be specified with this function. If 0 is passed for a given kind - * of code, it defaults to the value of the next-highest-priority kind. - * - * This function may only be called immediately after the runtime is initialized - * and before any code is executed and/or interrupts requested. - */ -extern JS_PUBLIC_API(void) -JS_SetNativeStackQuota(JSContext* cx, size_t systemCodeStackSize, - size_t trustedScriptStackSize = 0, - size_t untrustedScriptStackSize = 0); - -/************************************************************************/ - -extern JS_PUBLIC_API(bool) -JS_ValueToId(JSContext* cx, JS::HandleValue v, JS::MutableHandleId idp); - -extern JS_PUBLIC_API(bool) -JS_StringToId(JSContext* cx, JS::HandleString s, JS::MutableHandleId idp); - -extern JS_PUBLIC_API(bool) -JS_IdToValue(JSContext* cx, jsid id, JS::MutableHandle vp); - -namespace JS { - -/** - * Convert obj to a primitive value. On success, store the result in vp and - * return true. - * - * The hint argument must be JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_VOID (no - * hint). - * - * Implements: ES6 7.1.1 ToPrimitive(input, [PreferredType]). - */ -extern JS_PUBLIC_API(bool) -ToPrimitive(JSContext* cx, JS::HandleObject obj, JSType hint, JS::MutableHandleValue vp); - -/** - * If args.get(0) is one of the strings "string", "number", or "default", set - * *result to JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_VOID accordingly and - * return true. Otherwise, return false with a TypeError pending. - * - * This can be useful in implementing a @@toPrimitive method. - */ -extern JS_PUBLIC_API(bool) -GetFirstArgumentAsTypeHint(JSContext* cx, CallArgs args, JSType *result); - -} /* namespace JS */ - -extern JS_PUBLIC_API(bool) -JS_PropertyStub(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_StrictPropertyStub(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp, JS::ObjectOpResult& result); - -template -struct JSConstScalarSpec { - const char* name; - T val; -}; - -typedef JSConstScalarSpec JSConstDoubleSpec; -typedef JSConstScalarSpec JSConstIntegerSpec; - -struct JSJitInfo; - -/** - * Wrapper to relace JSNative for JSPropertySpecs and JSFunctionSpecs. This will - * allow us to pass one JSJitInfo per function with the property/function spec, - * without additional field overhead. - */ -typedef struct JSNativeWrapper { - JSNative op; - const JSJitInfo* info; -} JSNativeWrapper; - -/* - * Macro static initializers which make it easy to pass no JSJitInfo as part of a - * JSPropertySpec or JSFunctionSpec. - */ -#define JSNATIVE_WRAPPER(native) { {native, nullptr} } - -/** - * Description of a property. JS_DefineProperties and JS_InitClass take arrays - * of these and define many properties at once. JS_PSG, JS_PSGS and JS_PS_END - * are helper macros for defining such arrays. - */ -struct JSPropertySpec { - struct SelfHostedWrapper { - void* unused; - const char* funname; - }; - - struct ValueWrapper { - uintptr_t type; - union { - const char* string; - int32_t int32; - }; - }; - - const char* name; - uint8_t flags; - union { - struct { - union { - JSNativeWrapper native; - SelfHostedWrapper selfHosted; - } getter; - union { - JSNativeWrapper native; - SelfHostedWrapper selfHosted; - } setter; - } accessors; - ValueWrapper value; - }; - - bool isAccessor() const { - return !(flags & JSPROP_INTERNAL_USE_BIT); - } - bool getValue(JSContext* cx, JS::MutableHandleValue value) const; - - bool isSelfHosted() const { - MOZ_ASSERT(isAccessor()); - -#ifdef DEBUG - // Verify that our accessors match our JSPROP_GETTER flag. - if (flags & JSPROP_GETTER) - checkAccessorsAreSelfHosted(); - else - checkAccessorsAreNative(); -#endif - return (flags & JSPROP_GETTER); - } - - static_assert(sizeof(SelfHostedWrapper) == sizeof(JSNativeWrapper), - "JSPropertySpec::getter/setter must be compact"); - static_assert(offsetof(SelfHostedWrapper, funname) == offsetof(JSNativeWrapper, info), - "JS_SELF_HOSTED* macros below require that " - "SelfHostedWrapper::funname overlay " - "JSNativeWrapper::info"); -private: - void checkAccessorsAreNative() const { - MOZ_ASSERT(accessors.getter.native.op); - // We may not have a setter at all. So all we can assert here, for the - // native case is that if we have a jitinfo for the setter then we have - // a setter op too. This is good enough to make sure we don't have a - // SelfHostedWrapper for the setter. - MOZ_ASSERT_IF(accessors.setter.native.info, accessors.setter.native.op); - } - - void checkAccessorsAreSelfHosted() const { - MOZ_ASSERT(!accessors.getter.selfHosted.unused); - MOZ_ASSERT(!accessors.setter.selfHosted.unused); - } -}; - -namespace JS { -namespace detail { - -/* NEVER DEFINED, DON'T USE. For use by JS_CAST_NATIVE_TO only. */ -inline int CheckIsNative(JSNative native); - -/* NEVER DEFINED, DON'T USE. For use by JS_CAST_STRING_TO only. */ -template -inline int -CheckIsCharacterLiteral(const char (&arr)[N]); - -/* NEVER DEFINED, DON'T USE. For use by JS_CAST_INT32_TO only. */ -inline int CheckIsInt32(int32_t value); - -/* NEVER DEFINED, DON'T USE. For use by JS_PROPERTYOP_GETTER only. */ -inline int CheckIsGetterOp(JSGetterOp op); - -/* NEVER DEFINED, DON'T USE. For use by JS_PROPERTYOP_SETTER only. */ -inline int CheckIsSetterOp(JSSetterOp op); - -} // namespace detail -} // namespace JS - -#define JS_CAST_NATIVE_TO(v, To) \ - (static_cast(sizeof(JS::detail::CheckIsNative(v))), \ - reinterpret_cast(v)) - -#define JS_CAST_STRING_TO(s, To) \ - (static_cast(sizeof(JS::detail::CheckIsCharacterLiteral(s))), \ - reinterpret_cast(s)) - -#define JS_CAST_INT32_TO(s, To) \ - (static_cast(sizeof(JS::detail::CheckIsInt32(s))), \ - reinterpret_cast(s)) - -#define JS_CHECK_ACCESSOR_FLAGS(flags) \ - (static_cast::Type>(0), \ - (flags)) - -#define JS_PROPERTYOP_GETTER(v) \ - (static_cast(sizeof(JS::detail::CheckIsGetterOp(v))), \ - reinterpret_cast(v)) - -#define JS_PROPERTYOP_SETTER(v) \ - (static_cast(sizeof(JS::detail::CheckIsSetterOp(v))), \ - reinterpret_cast(v)) - -#define JS_STUBGETTER JS_PROPERTYOP_GETTER(JS_PropertyStub) - -#define JS_STUBSETTER JS_PROPERTYOP_SETTER(JS_StrictPropertyStub) - -#define JS_PS_ACCESSOR_SPEC(name, getter, setter, flags, extraFlags) \ - { name, uint8_t(JS_CHECK_ACCESSOR_FLAGS(flags) | extraFlags), \ - { { getter, setter } } } -#define JS_PS_VALUE_SPEC(name, value, flags) \ - { name, uint8_t(flags | JSPROP_INTERNAL_USE_BIT), \ - { { value, JSNATIVE_WRAPPER(nullptr) } } } - -#define SELFHOSTED_WRAPPER(name) \ - { { nullptr, JS_CAST_STRING_TO(name, const JSJitInfo*) } } -#define STRINGVALUE_WRAPPER(value) \ - { { reinterpret_cast(JSVAL_TYPE_STRING), JS_CAST_STRING_TO(value, const JSJitInfo*) } } -#define INT32VALUE_WRAPPER(value) \ - { { reinterpret_cast(JSVAL_TYPE_INT32), JS_CAST_INT32_TO(value, const JSJitInfo*) } } - -/* - * JSPropertySpec uses JSNativeWrapper. These macros encapsulate the definition - * of JSNative-backed JSPropertySpecs, by defining the JSNativeWrappers for - * them. - */ -#define JS_PSG(name, getter, flags) \ - JS_PS_ACCESSOR_SPEC(name, JSNATIVE_WRAPPER(getter), JSNATIVE_WRAPPER(nullptr), flags, \ - JSPROP_SHARED) -#define JS_PSGS(name, getter, setter, flags) \ - JS_PS_ACCESSOR_SPEC(name, JSNATIVE_WRAPPER(getter), JSNATIVE_WRAPPER(setter), flags, \ - JSPROP_SHARED) -#define JS_SELF_HOSTED_GET(name, getterName, flags) \ - JS_PS_ACCESSOR_SPEC(name, SELFHOSTED_WRAPPER(getterName), JSNATIVE_WRAPPER(nullptr), flags, \ - JSPROP_SHARED | JSPROP_GETTER) -#define JS_SELF_HOSTED_GETSET(name, getterName, setterName, flags) \ - JS_PS_ACCESSOR_SPEC(name, SELFHOSTED_WRAPPER(getterName), SELFHOSTED_WRAPPER(setterName), \ - flags, JSPROP_SHARED | JSPROP_GETTER | JSPROP_SETTER) -#define JS_SELF_HOSTED_SYM_GET(symbol, getterName, flags) \ - JS_PS_ACCESSOR_SPEC(reinterpret_cast(uint32_t(::JS::SymbolCode::symbol) + 1), \ - SELFHOSTED_WRAPPER(getterName), JSNATIVE_WRAPPER(nullptr), flags, \ - JSPROP_SHARED | JSPROP_GETTER) -#define JS_STRING_PS(name, string, flags) \ - JS_PS_VALUE_SPEC(name, STRINGVALUE_WRAPPER(string), flags) -#define JS_STRING_SYM_PS(symbol, string, flags) \ - JS_PS_VALUE_SPEC(reinterpret_cast(uint32_t(::JS::SymbolCode::symbol) + 1), \ - STRINGVALUE_WRAPPER(string), flags) -#define JS_INT32_PS(name, value, flags) \ - JS_PS_VALUE_SPEC(name, INT32VALUE_WRAPPER(value), flags) -#define JS_PS_END \ - JS_PS_ACCESSOR_SPEC(nullptr, JSNATIVE_WRAPPER(nullptr), JSNATIVE_WRAPPER(nullptr), 0, 0) - -/** - * To define a native function, set call to a JSNativeWrapper. To define a - * self-hosted function, set selfHostedName to the name of a function - * compiled during JSRuntime::initSelfHosting. - */ -struct JSFunctionSpec { - const char* name; - JSNativeWrapper call; - uint16_t nargs; - uint16_t flags; - const char* selfHostedName; -}; - -/* - * Terminating sentinel initializer to put at the end of a JSFunctionSpec array - * that's passed to JS_DefineFunctions or JS_InitClass. - */ -#define JS_FS_END JS_FS(nullptr,nullptr,0,0) - -/* - * Initializer macros for a JSFunctionSpec array element. JS_FN (whose name pays - * homage to the old JSNative/JSFastNative split) simply adds the flag - * JSFUN_STUB_GSOPS. JS_FNINFO allows the simple adding of - * JSJitInfos. JS_SELF_HOSTED_FN declares a self-hosted function. - * JS_INLINABLE_FN allows specifying an InlinableNative enum value for natives - * inlined or specialized by the JIT. Finally JS_FNSPEC has slots for all the - * fields. - * - * The _SYM variants allow defining a function with a symbol key rather than a - * string key. For example, use JS_SYM_FN(iterator, ...) to define an - * @@iterator method. - */ -#define JS_FS(name,call,nargs,flags) \ - JS_FNSPEC(name, call, nullptr, nargs, flags, nullptr) -#define JS_FN(name,call,nargs,flags) \ - JS_FNSPEC(name, call, nullptr, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr) -#define JS_INLINABLE_FN(name,call,nargs,flags,native) \ - JS_FNSPEC(name, call, &js::jit::JitInfo_##native, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr) -#define JS_SYM_FN(symbol,call,nargs,flags) \ - JS_SYM_FNSPEC(symbol, call, nullptr, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr) -#define JS_FNINFO(name,call,info,nargs,flags) \ - JS_FNSPEC(name, call, info, nargs, flags, nullptr) -#define JS_SELF_HOSTED_FN(name,selfHostedName,nargs,flags) \ - JS_FNSPEC(name, nullptr, nullptr, nargs, flags, selfHostedName) -#define JS_SELF_HOSTED_SYM_FN(symbol, selfHostedName, nargs, flags) \ - JS_SYM_FNSPEC(symbol, nullptr, nullptr, nargs, flags, selfHostedName) -#define JS_SYM_FNSPEC(symbol, call, info, nargs, flags, selfHostedName) \ - JS_FNSPEC(reinterpret_cast( \ - uint32_t(::JS::SymbolCode::symbol) + 1), \ - call, info, nargs, flags, selfHostedName) -#define JS_FNSPEC(name,call,info,nargs,flags,selfHostedName) \ - {name, {call, info}, nargs, flags, selfHostedName} - -extern JS_PUBLIC_API(JSObject*) -JS_InitClass(JSContext* cx, JS::HandleObject obj, JS::HandleObject parent_proto, - const JSClass* clasp, JSNative constructor, unsigned nargs, - const JSPropertySpec* ps, const JSFunctionSpec* fs, - const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs); - -/** - * Set up ctor.prototype = proto and proto.constructor = ctor with the - * right property flags. - */ -extern JS_PUBLIC_API(bool) -JS_LinkConstructorAndPrototype(JSContext* cx, JS::Handle ctor, - JS::Handle proto); - -extern JS_PUBLIC_API(const JSClass*) -JS_GetClass(JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_InstanceOf(JSContext* cx, JS::Handle obj, const JSClass* clasp, JS::CallArgs* args); - -extern JS_PUBLIC_API(bool) -JS_HasInstance(JSContext* cx, JS::Handle obj, JS::Handle v, bool* bp); - -namespace JS { - -// Implementation of -// http://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance. If -// you're looking for the equivalent of "instanceof", you want JS_HasInstance, -// not this function. -extern JS_PUBLIC_API(bool) -OrdinaryHasInstance(JSContext* cx, HandleObject objArg, HandleValue v, bool* bp); - -} // namespace JS - -extern JS_PUBLIC_API(void*) -JS_GetPrivate(JSObject* obj); - -extern JS_PUBLIC_API(void) -JS_SetPrivate(JSObject* obj, void* data); - -extern JS_PUBLIC_API(void*) -JS_GetInstancePrivate(JSContext* cx, JS::Handle obj, const JSClass* clasp, - JS::CallArgs* args); - -extern JS_PUBLIC_API(JSObject*) -JS_GetConstructor(JSContext* cx, JS::Handle proto); - -namespace JS { - -enum ZoneSpecifier { - FreshZone = 0, - SystemZone = 1 -}; - -/** - * CompartmentCreationOptions specifies options relevant to creating a new - * compartment, that are either immutable characteristics of that compartment - * or that are discarded after the compartment has been created. - * - * Access to these options on an existing compartment is read-only: if you - * need particular selections, make them before you create the compartment. - */ -class JS_PUBLIC_API(CompartmentCreationOptions) -{ - public: - CompartmentCreationOptions() - : addonId_(nullptr), - traceGlobal_(nullptr), - invisibleToDebugger_(false), - mergeable_(false), - preserveJitCode_(false), - cloneSingletons_(false), - sharedMemoryAndAtomics_(false), - secureContext_(false) - { - zone_.spec = JS::FreshZone; - } - - // A null add-on ID means that the compartment is not associated with an - // add-on. - JSAddonId* addonIdOrNull() const { return addonId_; } - CompartmentCreationOptions& setAddonId(JSAddonId* id) { - addonId_ = id; - return *this; - } - - JSTraceOp getTrace() const { - return traceGlobal_; - } - CompartmentCreationOptions& setTrace(JSTraceOp op) { - traceGlobal_ = op; - return *this; - } - - void* zonePointer() const { - MOZ_ASSERT(uintptr_t(zone_.pointer) > uintptr_t(JS::SystemZone)); - return zone_.pointer; - } - ZoneSpecifier zoneSpecifier() const { return zone_.spec; } - CompartmentCreationOptions& setZone(ZoneSpecifier spec); - CompartmentCreationOptions& setSameZoneAs(JSObject* obj); - - // Certain scopes (i.e. XBL compilation scopes) are implementation details - // of the embedding, and references to them should never leak out to script. - // This flag causes the this compartment to skip firing onNewGlobalObject - // and makes addDebuggee a no-op for this global. - bool invisibleToDebugger() const { return invisibleToDebugger_; } - CompartmentCreationOptions& setInvisibleToDebugger(bool flag) { - invisibleToDebugger_ = flag; - return *this; - } - - // Compartments used for off-thread compilation have their contents merged - // into a target compartment when the compilation is finished. This is only - // allowed if this flag is set. The invisibleToDebugger flag must also be - // set for such compartments. - bool mergeable() const { return mergeable_; } - CompartmentCreationOptions& setMergeable(bool flag) { - mergeable_ = flag; - return *this; - } - - // Determines whether this compartment should preserve JIT code on - // non-shrinking GCs. - bool preserveJitCode() const { return preserveJitCode_; } - CompartmentCreationOptions& setPreserveJitCode(bool flag) { - preserveJitCode_ = flag; - return *this; - } - - bool cloneSingletons() const { return cloneSingletons_; } - CompartmentCreationOptions& setCloneSingletons(bool flag) { - cloneSingletons_ = flag; - return *this; - } - - bool getSharedMemoryAndAtomicsEnabled() const; - CompartmentCreationOptions& setSharedMemoryAndAtomicsEnabled(bool flag); - - // This flag doesn't affect JS engine behavior. It is used by Gecko to - // mark whether content windows and workers are "Secure Context"s. See - // https://w3c.github.io/webappsec-secure-contexts/ - // https://bugzilla.mozilla.org/show_bug.cgi?id=1162772#c34 - bool secureContext() const { return secureContext_; } - CompartmentCreationOptions& setSecureContext(bool flag) { - secureContext_ = flag; - return *this; - } - - private: - JSAddonId* addonId_; - JSTraceOp traceGlobal_; - union { - ZoneSpecifier spec; - void* pointer; // js::Zone* is not exposed in the API. - } zone_; - bool invisibleToDebugger_; - bool mergeable_; - bool preserveJitCode_; - bool cloneSingletons_; - bool sharedMemoryAndAtomics_; - bool secureContext_; -}; - -/** - * CompartmentBehaviors specifies behaviors of a compartment that can be - * changed after the compartment's been created. - */ -class JS_PUBLIC_API(CompartmentBehaviors) -{ - public: - class Override { - public: - Override() : mode_(Default) {} - - bool get(bool defaultValue) const { - if (mode_ == Default) - return defaultValue; - return mode_ == ForceTrue; - } - - void set(bool overrideValue) { - mode_ = overrideValue ? ForceTrue : ForceFalse; - } - - void reset() { - mode_ = Default; - } - - private: - enum Mode { - Default, - ForceTrue, - ForceFalse - }; - - Mode mode_; - }; - - CompartmentBehaviors() - : version_(JSVERSION_UNKNOWN) - , discardSource_(false) - , disableLazyParsing_(false) - , singletonsAsTemplates_(true) - { - } - - JSVersion version() const { return version_; } - CompartmentBehaviors& setVersion(JSVersion aVersion) { - MOZ_ASSERT(aVersion != JSVERSION_UNKNOWN); - version_ = aVersion; - return *this; - } - - // For certain globals, we know enough about the code that will run in them - // that we can discard script source entirely. - bool discardSource() const { return discardSource_; } - CompartmentBehaviors& setDiscardSource(bool flag) { - discardSource_ = flag; - return *this; - } - - bool disableLazyParsing() const { return disableLazyParsing_; } - CompartmentBehaviors& setDisableLazyParsing(bool flag) { - disableLazyParsing_ = flag; - return *this; - } - - bool extraWarnings(JSContext* cx) const; - Override& extraWarningsOverride() { return extraWarningsOverride_; } - - bool getSingletonsAsTemplates() const { - return singletonsAsTemplates_; - } - CompartmentBehaviors& setSingletonsAsValues() { - singletonsAsTemplates_ = false; - return *this; - } - - private: - JSVersion version_; - bool discardSource_; - bool disableLazyParsing_; - Override extraWarningsOverride_; - - // To XDR singletons, we need to ensure that all singletons are all used as - // templates, by making JSOP_OBJECT return a clone of the JSScript - // singleton, instead of returning the value which is baked in the JSScript. - bool singletonsAsTemplates_; -}; - -/** - * CompartmentOptions specifies compartment characteristics: both those that - * can't be changed on a compartment once it's been created - * (CompartmentCreationOptions), and those that can be changed on an existing - * compartment (CompartmentBehaviors). - */ -class JS_PUBLIC_API(CompartmentOptions) -{ - public: - explicit CompartmentOptions() - : creationOptions_(), - behaviors_() - {} - - CompartmentOptions(const CompartmentCreationOptions& compartmentCreation, - const CompartmentBehaviors& compartmentBehaviors) - : creationOptions_(compartmentCreation), - behaviors_(compartmentBehaviors) - {} - - // CompartmentCreationOptions specify fundamental compartment - // characteristics that must be specified when the compartment is created, - // that can't be changed after the compartment is created. - CompartmentCreationOptions& creationOptions() { - return creationOptions_; - } - const CompartmentCreationOptions& creationOptions() const { - return creationOptions_; - } - - // CompartmentBehaviors specify compartment characteristics that can be - // changed after the compartment is created. - CompartmentBehaviors& behaviors() { - return behaviors_; - } - const CompartmentBehaviors& behaviors() const { - return behaviors_; - } - - private: - CompartmentCreationOptions creationOptions_; - CompartmentBehaviors behaviors_; -}; - -JS_PUBLIC_API(const CompartmentCreationOptions&) -CompartmentCreationOptionsRef(JSCompartment* compartment); - -JS_PUBLIC_API(const CompartmentCreationOptions&) -CompartmentCreationOptionsRef(JSObject* obj); - -JS_PUBLIC_API(const CompartmentCreationOptions&) -CompartmentCreationOptionsRef(JSContext* cx); - -JS_PUBLIC_API(CompartmentBehaviors&) -CompartmentBehaviorsRef(JSCompartment* compartment); - -JS_PUBLIC_API(CompartmentBehaviors&) -CompartmentBehaviorsRef(JSObject* obj); - -JS_PUBLIC_API(CompartmentBehaviors&) -CompartmentBehaviorsRef(JSContext* cx); - -/** - * During global creation, we fire notifications to callbacks registered - * via the Debugger API. These callbacks are arbitrary script, and can touch - * the global in arbitrary ways. When that happens, the global should not be - * in a half-baked state. But this creates a problem for consumers that need - * to set slots on the global to put it in a consistent state. - * - * This API provides a way for consumers to set slots atomically (immediately - * after the global is created), before any debugger hooks are fired. It's - * unfortunately on the clunky side, but that's the way the cookie crumbles. - * - * If callers have no additional state on the global to set up, they may pass - * |FireOnNewGlobalHook| to JS_NewGlobalObject, which causes that function to - * fire the hook as its final act before returning. Otherwise, callers should - * pass |DontFireOnNewGlobalHook|, which means that they are responsible for - * invoking JS_FireOnNewGlobalObject upon successfully creating the global. If - * an error occurs and the operation aborts, callers should skip firing the - * hook. But otherwise, callers must take care to fire the hook exactly once - * before compiling any script in the global's scope (we have assertions in - * place to enforce this). This lets us be sure that debugger clients never miss - * breakpoints. - */ -enum OnNewGlobalHookOption { - FireOnNewGlobalHook, - DontFireOnNewGlobalHook -}; - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSObject*) -JS_NewGlobalObject(JSContext* cx, const JSClass* clasp, JSPrincipals* principals, - JS::OnNewGlobalHookOption hookOption, - const JS::CompartmentOptions& options); -/** - * Spidermonkey does not have a good way of keeping track of what compartments should be marked on - * their own. We can mark the roots unconditionally, but marking GC things only relevant in live - * compartments is hard. To mitigate this, we create a static trace hook, installed on each global - * object, from which we can be sure the compartment is relevant, and mark it. - * - * It is still possible to specify custom trace hooks for global object classes. They can be - * provided via the CompartmentOptions passed to JS_NewGlobalObject. - */ -extern JS_PUBLIC_API(void) -JS_GlobalObjectTraceHook(JSTracer* trc, JSObject* global); - -extern JS_PUBLIC_API(void) -JS_FireOnNewGlobalObject(JSContext* cx, JS::HandleObject global); - -extern JS_PUBLIC_API(JSObject*) -JS_NewObject(JSContext* cx, const JSClass* clasp); - -extern JS_PUBLIC_API(bool) -JS_IsNative(JSObject* obj); - -/** - * Unlike JS_NewObject, JS_NewObjectWithGivenProto does not compute a default - * proto. If proto is nullptr, the JS object will have `null` as [[Prototype]]. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewObjectWithGivenProto(JSContext* cx, const JSClass* clasp, JS::Handle proto); - -/** Creates a new plain object, like `new Object()`, with Object.prototype as [[Prototype]]. */ -extern JS_PUBLIC_API(JSObject*) -JS_NewPlainObject(JSContext* cx); - -/** - * Freeze obj, and all objects it refers to, recursively. This will not recurse - * through non-extensible objects, on the assumption that those are already - * deep-frozen. - */ -extern JS_PUBLIC_API(bool) -JS_DeepFreezeObject(JSContext* cx, JS::Handle obj); - -/** - * Freezes an object; see ES5's Object.freeze(obj) method. - */ -extern JS_PUBLIC_API(bool) -JS_FreezeObject(JSContext* cx, JS::Handle obj); - - -/*** Property descriptors ************************************************************************/ - -namespace JS { - -struct JS_PUBLIC_API(PropertyDescriptor) { - JSObject* obj; - unsigned attrs; - JSGetterOp getter; - JSSetterOp setter; - JS::Value value; - - PropertyDescriptor() - : obj(nullptr), attrs(0), getter(nullptr), setter(nullptr), value(JS::UndefinedValue()) - {} - - static void trace(PropertyDescriptor* self, JSTracer* trc) { self->trace(trc); } - void trace(JSTracer* trc); -}; - -template -class PropertyDescriptorOperations -{ - const PropertyDescriptor& desc() const { return static_cast(this)->get(); } - - bool has(unsigned bit) const { - MOZ_ASSERT(bit != 0); - MOZ_ASSERT((bit & (bit - 1)) == 0); // only a single bit - return (desc().attrs & bit) != 0; - } - - bool hasAny(unsigned bits) const { - return (desc().attrs & bits) != 0; - } - - bool hasAll(unsigned bits) const { - return (desc().attrs & bits) == bits; - } - - // Non-API attributes bit used internally for arguments objects. - enum { SHADOWABLE = JSPROP_INTERNAL_USE_BIT }; - - public: - // Descriptors with JSGetterOp/JSSetterOp are considered data - // descriptors. It's complicated. - bool isAccessorDescriptor() const { return hasAny(JSPROP_GETTER | JSPROP_SETTER); } - bool isGenericDescriptor() const { - return (desc().attrs& - (JSPROP_GETTER | JSPROP_SETTER | JSPROP_IGNORE_READONLY | JSPROP_IGNORE_VALUE)) == - (JSPROP_IGNORE_READONLY | JSPROP_IGNORE_VALUE); - } - bool isDataDescriptor() const { return !isAccessorDescriptor() && !isGenericDescriptor(); } - - bool hasConfigurable() const { return !has(JSPROP_IGNORE_PERMANENT); } - bool configurable() const { MOZ_ASSERT(hasConfigurable()); return !has(JSPROP_PERMANENT); } - - bool hasEnumerable() const { return !has(JSPROP_IGNORE_ENUMERATE); } - bool enumerable() const { MOZ_ASSERT(hasEnumerable()); return has(JSPROP_ENUMERATE); } - - bool hasValue() const { return !isAccessorDescriptor() && !has(JSPROP_IGNORE_VALUE); } - JS::HandleValue value() const { - return JS::HandleValue::fromMarkedLocation(&desc().value); - } - - bool hasWritable() const { return !isAccessorDescriptor() && !has(JSPROP_IGNORE_READONLY); } - bool writable() const { MOZ_ASSERT(hasWritable()); return !has(JSPROP_READONLY); } - - bool hasGetterObject() const { return has(JSPROP_GETTER); } - JS::HandleObject getterObject() const { - MOZ_ASSERT(hasGetterObject()); - return JS::HandleObject::fromMarkedLocation( - reinterpret_cast(&desc().getter)); - } - bool hasSetterObject() const { return has(JSPROP_SETTER); } - JS::HandleObject setterObject() const { - MOZ_ASSERT(hasSetterObject()); - return JS::HandleObject::fromMarkedLocation( - reinterpret_cast(&desc().setter)); - } - - bool hasGetterOrSetter() const { return desc().getter || desc().setter; } - bool isShared() const { return has(JSPROP_SHARED); } - - JS::HandleObject object() const { - return JS::HandleObject::fromMarkedLocation(&desc().obj); - } - unsigned attributes() const { return desc().attrs; } - JSGetterOp getter() const { return desc().getter; } - JSSetterOp setter() const { return desc().setter; } - - void assertValid() const { -#ifdef DEBUG - MOZ_ASSERT((attributes() & ~(JSPROP_ENUMERATE | JSPROP_IGNORE_ENUMERATE | - JSPROP_PERMANENT | JSPROP_IGNORE_PERMANENT | - JSPROP_READONLY | JSPROP_IGNORE_READONLY | - JSPROP_IGNORE_VALUE | - JSPROP_GETTER | - JSPROP_SETTER | - JSPROP_SHARED | - JSPROP_REDEFINE_NONCONFIGURABLE | - JSPROP_RESOLVING | - SHADOWABLE)) == 0); - MOZ_ASSERT(!hasAll(JSPROP_IGNORE_ENUMERATE | JSPROP_ENUMERATE)); - MOZ_ASSERT(!hasAll(JSPROP_IGNORE_PERMANENT | JSPROP_PERMANENT)); - if (isAccessorDescriptor()) { - MOZ_ASSERT(has(JSPROP_SHARED)); - MOZ_ASSERT(!has(JSPROP_READONLY)); - MOZ_ASSERT(!has(JSPROP_IGNORE_READONLY)); - MOZ_ASSERT(!has(JSPROP_IGNORE_VALUE)); - MOZ_ASSERT(!has(SHADOWABLE)); - MOZ_ASSERT(value().isUndefined()); - MOZ_ASSERT_IF(!has(JSPROP_GETTER), !getter()); - MOZ_ASSERT_IF(!has(JSPROP_SETTER), !setter()); - } else { - MOZ_ASSERT(!hasAll(JSPROP_IGNORE_READONLY | JSPROP_READONLY)); - MOZ_ASSERT_IF(has(JSPROP_IGNORE_VALUE), value().isUndefined()); - } - MOZ_ASSERT(getter() != JS_PropertyStub); - MOZ_ASSERT(setter() != JS_StrictPropertyStub); - - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_ENUMERATE)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_PERMANENT)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_READONLY)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_VALUE)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_REDEFINE_NONCONFIGURABLE)); -#endif - } - - void assertComplete() const { -#ifdef DEBUG - assertValid(); - MOZ_ASSERT((attributes() & ~(JSPROP_ENUMERATE | - JSPROP_PERMANENT | - JSPROP_READONLY | - JSPROP_GETTER | - JSPROP_SETTER | - JSPROP_SHARED | - JSPROP_REDEFINE_NONCONFIGURABLE | - JSPROP_RESOLVING | - SHADOWABLE)) == 0); - MOZ_ASSERT_IF(isAccessorDescriptor(), has(JSPROP_GETTER) && has(JSPROP_SETTER)); -#endif - } - - void assertCompleteIfFound() const { -#ifdef DEBUG - if (object()) - assertComplete(); -#endif - } -}; - -template -class MutablePropertyDescriptorOperations : public PropertyDescriptorOperations -{ - PropertyDescriptor& desc() { return static_cast(this)->get(); } - - public: - void clear() { - object().set(nullptr); - setAttributes(0); - setGetter(nullptr); - setSetter(nullptr); - value().setUndefined(); - } - - void initFields(HandleObject obj, HandleValue v, unsigned attrs, - JSGetterOp getterOp, JSSetterOp setterOp) { - MOZ_ASSERT(getterOp != JS_PropertyStub); - MOZ_ASSERT(setterOp != JS_StrictPropertyStub); - - object().set(obj); - value().set(v); - setAttributes(attrs); - setGetter(getterOp); - setSetter(setterOp); - } - - void assign(PropertyDescriptor& other) { - object().set(other.obj); - setAttributes(other.attrs); - setGetter(other.getter); - setSetter(other.setter); - value().set(other.value); - } - - void setDataDescriptor(HandleValue v, unsigned attrs) { - MOZ_ASSERT((attrs & ~(JSPROP_ENUMERATE | - JSPROP_PERMANENT | - JSPROP_READONLY | - JSPROP_IGNORE_ENUMERATE | - JSPROP_IGNORE_PERMANENT | - JSPROP_IGNORE_READONLY)) == 0); - object().set(nullptr); - setAttributes(attrs); - setGetter(nullptr); - setSetter(nullptr); - value().set(v); - } - - JS::MutableHandleObject object() { - return JS::MutableHandleObject::fromMarkedLocation(&desc().obj); - } - unsigned& attributesRef() { return desc().attrs; } - JSGetterOp& getter() { return desc().getter; } - JSSetterOp& setter() { return desc().setter; } - JS::MutableHandleValue value() { - return JS::MutableHandleValue::fromMarkedLocation(&desc().value); - } - void setValue(JS::HandleValue v) { - MOZ_ASSERT(!(desc().attrs & (JSPROP_GETTER | JSPROP_SETTER))); - attributesRef() &= ~JSPROP_IGNORE_VALUE; - value().set(v); - } - - void setConfigurable(bool configurable) { - setAttributes((desc().attrs & ~(JSPROP_IGNORE_PERMANENT | JSPROP_PERMANENT)) | - (configurable ? 0 : JSPROP_PERMANENT)); - } - void setEnumerable(bool enumerable) { - setAttributes((desc().attrs & ~(JSPROP_IGNORE_ENUMERATE | JSPROP_ENUMERATE)) | - (enumerable ? JSPROP_ENUMERATE : 0)); - } - void setWritable(bool writable) { - MOZ_ASSERT(!(desc().attrs & (JSPROP_GETTER | JSPROP_SETTER))); - setAttributes((desc().attrs & ~(JSPROP_IGNORE_READONLY | JSPROP_READONLY)) | - (writable ? 0 : JSPROP_READONLY)); - } - void setAttributes(unsigned attrs) { desc().attrs = attrs; } - - void setGetter(JSGetterOp op) { - MOZ_ASSERT(op != JS_PropertyStub); - desc().getter = op; - } - void setSetter(JSSetterOp op) { - MOZ_ASSERT(op != JS_StrictPropertyStub); - desc().setter = op; - } - void setGetterObject(JSObject* obj) { - desc().getter = reinterpret_cast(obj); - desc().attrs &= ~(JSPROP_IGNORE_VALUE | JSPROP_IGNORE_READONLY | JSPROP_READONLY); - desc().attrs |= JSPROP_GETTER | JSPROP_SHARED; - } - void setSetterObject(JSObject* obj) { - desc().setter = reinterpret_cast(obj); - desc().attrs &= ~(JSPROP_IGNORE_VALUE | JSPROP_IGNORE_READONLY | JSPROP_READONLY); - desc().attrs |= JSPROP_SETTER | JSPROP_SHARED; - } - - JS::MutableHandleObject getterObject() { - MOZ_ASSERT(this->hasGetterObject()); - return JS::MutableHandleObject::fromMarkedLocation( - reinterpret_cast(&desc().getter)); - } - JS::MutableHandleObject setterObject() { - MOZ_ASSERT(this->hasSetterObject()); - return JS::MutableHandleObject::fromMarkedLocation( - reinterpret_cast(&desc().setter)); - } -}; - -} /* namespace JS */ - -namespace js { - -template <> -class RootedBase - : public JS::MutablePropertyDescriptorOperations> -{}; - -template <> -class HandleBase - : public JS::PropertyDescriptorOperations> -{}; - -template <> -class MutableHandleBase - : public JS::MutablePropertyDescriptorOperations> -{}; - -} /* namespace js */ - -namespace JS { - -extern JS_PUBLIC_API(bool) -ObjectToCompletePropertyDescriptor(JSContext* cx, - JS::HandleObject obj, - JS::HandleValue descriptor, - JS::MutableHandle desc); - -/* - * ES6 draft rev 32 (2015 Feb 2) 6.2.4.4 FromPropertyDescriptor(Desc). - * - * If desc.object() is null, then vp is set to undefined. - */ -extern JS_PUBLIC_API(bool) -FromPropertyDescriptor(JSContext* cx, - JS::Handle desc, - JS::MutableHandleValue vp); - -} // namespace JS - - -/*** Standard internal methods ******************************************************************** - * - * The functions below are the fundamental operations on objects. - * - * ES6 specifies 14 internal methods that define how objects behave. The - * standard is actually quite good on this topic, though you may have to read - * it a few times. See ES6 sections 6.1.7.2 and 6.1.7.3. - * - * When 'obj' is an ordinary object, these functions have boring standard - * behavior as specified by ES6 section 9.1; see the section about internal - * methods in js/src/vm/NativeObject.h. - * - * Proxies override the behavior of internal methods. So when 'obj' is a proxy, - * any one of the functions below could do just about anything. See - * js/public/Proxy.h. - */ - -/** - * Get the prototype of obj, storing it in result. - * - * Implements: ES6 [[GetPrototypeOf]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_GetPrototype(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject result); - -/** - * If |obj| (underneath any functionally-transparent wrapper proxies) has as - * its [[GetPrototypeOf]] trap the ordinary [[GetPrototypeOf]] behavior defined - * for ordinary objects, set |*isOrdinary = true| and store |obj|'s prototype - * in |result|. Otherwise set |*isOrdinary = false|. In case of error, both - * outparams have unspecified value. - */ -extern JS_PUBLIC_API(bool) -JS_GetPrototypeIfOrdinary(JSContext* cx, JS::HandleObject obj, bool* isOrdinary, - JS::MutableHandleObject result); - -/** - * Change the prototype of obj. - * - * Implements: ES6 [[SetPrototypeOf]] internal method. - * - * In cases where ES6 [[SetPrototypeOf]] returns false without an exception, - * JS_SetPrototype throws a TypeError and returns false. - * - * Performance warning: JS_SetPrototype is very bad for performance. It may - * cause compiled jit-code to be invalidated. It also causes not only obj but - * all other objects in the same "group" as obj to be permanently deoptimized. - * It's better to create the object with the right prototype from the start. - */ -extern JS_PUBLIC_API(bool) -JS_SetPrototype(JSContext* cx, JS::HandleObject obj, JS::HandleObject proto); - -/** - * Determine whether obj is extensible. Extensible objects can have new - * properties defined on them. Inextensible objects can't, and their - * [[Prototype]] slot is fixed as well. - * - * Implements: ES6 [[IsExtensible]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_IsExtensible(JSContext* cx, JS::HandleObject obj, bool* extensible); - -/** - * Attempt to make |obj| non-extensible. - * - * Not all failures are treated as errors. See the comment on - * JS::ObjectOpResult in js/public/Class.h. - * - * Implements: ES6 [[PreventExtensions]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_PreventExtensions(JSContext* cx, JS::HandleObject obj, JS::ObjectOpResult& result); - -/** - * Attempt to make the [[Prototype]] of |obj| immutable, such that any attempt - * to modify it will fail. If an error occurs during the attempt, return false - * (with a pending exception set, depending upon the nature of the error). If - * no error occurs, return true with |*succeeded| set to indicate whether the - * attempt successfully made the [[Prototype]] immutable. - * - * This is a nonstandard internal method. - */ -extern JS_PUBLIC_API(bool) -JS_SetImmutablePrototype(JSContext* cx, JS::HandleObject obj, bool* succeeded); - -/** - * Get a description of one of obj's own properties. If no such property exists - * on obj, return true with desc.object() set to null. - * - * Implements: ES6 [[GetOwnProperty]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_GetOwnPropertyDescriptorById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); - -extern JS_PUBLIC_API(bool) -JS_GetOwnPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char* name, - JS::MutableHandle desc); - -extern JS_PUBLIC_API(bool) -JS_GetOwnUCPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char16_t* name, - JS::MutableHandle desc); - -/** - * Like JS_GetOwnPropertyDescriptorById, but also searches the prototype chain - * if no own property is found directly on obj. The object on which the - * property is found is returned in desc.object(). If the property is not found - * on the prototype chain, this returns true with desc.object() set to null. - */ -extern JS_PUBLIC_API(bool) -JS_GetPropertyDescriptorById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); - -extern JS_PUBLIC_API(bool) -JS_GetPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char* name, - JS::MutableHandle desc); - -/** - * Define a property on obj. - * - * This function uses JS::ObjectOpResult to indicate conditions that ES6 - * specifies as non-error failures. This is inconvenient at best, so use this - * function only if you are implementing a proxy handler's defineProperty() - * method. For all other purposes, use one of the many DefineProperty functions - * below that throw an exception in all failure cases. - * - * Implements: ES6 [[DefineOwnProperty]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc, - JS::ObjectOpResult& result); - -/** - * Define a property on obj, throwing a TypeError if the attempt fails. - * This is the C++ equivalent of `Object.defineProperty(obj, id, desc)`. - */ -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleString value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, int32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, uint32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, double value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleValue value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleObject value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleString value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, int32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, uint32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, double value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::Handle desc, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::Handle desc); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleValue value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleObject value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleString value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - int32_t value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - uint32_t value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - double value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleValue value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleObject value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleString value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, int32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, uint32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, double value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -/** - * Compute the expression `id in obj`. - * - * If obj has an own or inherited property obj[id], set *foundp = true and - * return true. If not, set *foundp = false and return true. On error, return - * false with an exception pending. - * - * Implements: ES6 [[Has]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_HasPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_HasProperty(JSContext* cx, JS::HandleObject obj, const char* name, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_HasUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - bool* vp); - -extern JS_PUBLIC_API(bool) -JS_HasElement(JSContext* cx, JS::HandleObject obj, uint32_t index, bool* foundp); - -/** - * Determine whether obj has an own property with the key `id`. - * - * Implements: ES6 7.3.11 HasOwnProperty(O, P). - */ -extern JS_PUBLIC_API(bool) -JS_HasOwnPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_HasOwnProperty(JSContext* cx, JS::HandleObject obj, const char* name, bool* foundp); - -/** - * Get the value of the property `obj[id]`, or undefined if no such property - * exists. This is the C++ equivalent of `vp = Reflect.get(obj, id, receiver)`. - * - * Most callers don't need the `receiver` argument. Consider using - * JS_GetProperty instead. (But if you're implementing a proxy handler's set() - * method, it's often correct to call this function and pass the receiver - * through.) - * - * Implements: ES6 [[Get]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_ForwardGetPropertyTo(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::HandleValue receiver, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_ForwardGetElementTo(JSContext* cx, JS::HandleObject obj, uint32_t index, - JS::HandleObject receiver, JS::MutableHandleValue vp); - -/** - * Get the value of the property `obj[id]`, or undefined if no such property - * exists. The result is stored in vp. - * - * Implements: ES6 7.3.1 Get(O, P). - */ -extern JS_PUBLIC_API(bool) -JS_GetPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_GetProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_GetUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_GetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::MutableHandleValue vp); - -/** - * Perform the same property assignment as `Reflect.set(obj, id, v, receiver)`. - * - * This function has a `receiver` argument that most callers don't need. - * Consider using JS_SetProperty instead. - * - * Implements: ES6 [[Set]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_ForwardSetPropertyTo(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v, - JS::HandleValue receiver, JS::ObjectOpResult& result); - -/** - * Perform the assignment `obj[id] = v`. - * - * This function performs non-strict assignment, so if the property is - * read-only, nothing happens and no error is thrown. - */ -extern JS_PUBLIC_API(bool) -JS_SetPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleObject v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleString v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, int32_t v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, uint32_t v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, double v); - -/** - * Delete a property. This is the C++ equivalent of - * `result = Reflect.deleteProperty(obj, id)`. - * - * This function has a `result` out parameter that most callers don't need. - * Unless you can pass through an ObjectOpResult provided by your caller, it's - * probably best to use the JS_DeletePropertyById signature with just 3 - * arguments. - * - * Implements: ES6 [[Delete]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_DeletePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DeleteProperty(JSContext* cx, JS::HandleObject obj, const char* name, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DeleteUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DeleteElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::ObjectOpResult& result); - -/** - * Delete a property, ignoring strict failures. This is the C++ equivalent of - * the JS `delete obj[id]` in non-strict mode code. - */ -extern JS_PUBLIC_API(bool) -JS_DeletePropertyById(JSContext* cx, JS::HandleObject obj, jsid id); - -extern JS_PUBLIC_API(bool) -JS_DeleteProperty(JSContext* cx, JS::HandleObject obj, const char* name); - -extern JS_PUBLIC_API(bool) -JS_DeleteElement(JSContext* cx, JS::HandleObject obj, uint32_t index); - -/** - * Get an array of the non-symbol enumerable properties of obj. - * This function is roughly equivalent to: - * - * var result = []; - * for (key in obj) - * result.push(key); - * return result; - * - * This is the closest thing we currently have to the ES6 [[Enumerate]] - * internal method. - * - * The array of ids returned by JS_Enumerate must be rooted to protect its - * contents from garbage collection. Use JS::Rooted. - */ -extern JS_PUBLIC_API(bool) -JS_Enumerate(JSContext* cx, JS::HandleObject obj, JS::MutableHandle props); - -/* - * API for determining callability and constructability. [[Call]] and - * [[Construct]] are internal methods that aren't present on all objects, so it - * is useful to ask if they are there or not. The standard itself asks these - * questions routinely. - */ -namespace JS { - -/** - * Return true if the given object is callable. In ES6 terms, an object is - * callable if it has a [[Call]] internal method. - * - * Implements: ES6 7.2.3 IsCallable(argument). - * - * Functions are callable. A scripted proxy or wrapper is callable if its - * target is callable. Most other objects aren't callable. - */ -extern JS_PUBLIC_API(bool) -IsCallable(JSObject* obj); - -/** - * Return true if the given object is a constructor. In ES6 terms, an object is - * a constructor if it has a [[Construct]] internal method. The expression - * `new obj()` throws a TypeError if obj is not a constructor. - * - * Implements: ES6 7.2.4 IsConstructor(argument). - * - * JS functions and classes are constructors. Arrow functions and most builtin - * functions are not. A scripted proxy or wrapper is a constructor if its - * target is a constructor. - */ -extern JS_PUBLIC_API(bool) -IsConstructor(JSObject* obj); - -} /* namespace JS */ - -/** - * Call a function, passing a this-value and arguments. This is the C++ - * equivalent of `rval = Reflect.apply(fun, obj, args)`. - * - * Implements: ES6 7.3.12 Call(F, V, [argumentsList]). - * Use this function to invoke the [[Call]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_CallFunctionValue(JSContext* cx, JS::HandleObject obj, JS::HandleValue fval, - const JS::HandleValueArray& args, JS::MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -JS_CallFunction(JSContext* cx, JS::HandleObject obj, JS::HandleFunction fun, - const JS::HandleValueArray& args, JS::MutableHandleValue rval); - -/** - * Perform the method call `rval = obj[name](args)`. - */ -extern JS_PUBLIC_API(bool) -JS_CallFunctionName(JSContext* cx, JS::HandleObject obj, const char* name, - const JS::HandleValueArray& args, JS::MutableHandleValue rval); - -namespace JS { - -static inline bool -Call(JSContext* cx, JS::HandleObject thisObj, JS::HandleFunction fun, - const JS::HandleValueArray& args, MutableHandleValue rval) -{ - return !!JS_CallFunction(cx, thisObj, fun, args, rval); -} - -static inline bool -Call(JSContext* cx, JS::HandleObject thisObj, JS::HandleValue fun, const JS::HandleValueArray& args, - MutableHandleValue rval) -{ - return !!JS_CallFunctionValue(cx, thisObj, fun, args, rval); -} - -static inline bool -Call(JSContext* cx, JS::HandleObject thisObj, const char* name, const JS::HandleValueArray& args, - MutableHandleValue rval) -{ - return !!JS_CallFunctionName(cx, thisObj, name, args, rval); -} - -extern JS_PUBLIC_API(bool) -Call(JSContext* cx, JS::HandleValue thisv, JS::HandleValue fun, const JS::HandleValueArray& args, - MutableHandleValue rval); - -static inline bool -Call(JSContext* cx, JS::HandleValue thisv, JS::HandleObject funObj, const JS::HandleValueArray& args, - MutableHandleValue rval) -{ - MOZ_ASSERT(funObj); - JS::RootedValue fun(cx, JS::ObjectValue(*funObj)); - return Call(cx, thisv, fun, args, rval); -} - -/** - * Invoke a constructor. This is the C++ equivalent of - * `rval = Reflect.construct(fun, args, newTarget)`. - * - * JS::Construct() takes a `newTarget` argument that most callers don't need. - * Consider using the four-argument Construct signature instead. (But if you're - * implementing a subclass or a proxy handler's construct() method, this is the - * right function to call.) - * - * Implements: ES6 7.3.13 Construct(F, [argumentsList], [newTarget]). - * Use this function to invoke the [[Construct]] internal method. - */ -extern JS_PUBLIC_API(bool) -Construct(JSContext* cx, JS::HandleValue fun, HandleObject newTarget, - const JS::HandleValueArray &args, MutableHandleObject objp); - -/** - * Invoke a constructor. This is the C++ equivalent of - * `rval = new fun(...args)`. - * - * Implements: ES6 7.3.13 Construct(F, [argumentsList], [newTarget]), when - * newTarget is omitted. - */ -extern JS_PUBLIC_API(bool) -Construct(JSContext* cx, JS::HandleValue fun, const JS::HandleValueArray& args, - MutableHandleObject objp); - -} /* namespace JS */ - -/** - * Invoke a constructor, like the JS expression `new ctor(...args)`. Returns - * the new object, or null on error. - */ -extern JS_PUBLIC_API(JSObject*) -JS_New(JSContext* cx, JS::HandleObject ctor, const JS::HandleValueArray& args); - - -/*** Other property-defining functions ***********************************************************/ - -extern JS_PUBLIC_API(JSObject*) -JS_DefineObject(JSContext* cx, JS::HandleObject obj, const char* name, - const JSClass* clasp = nullptr, unsigned attrs = 0); - -extern JS_PUBLIC_API(bool) -JS_DefineConstDoubles(JSContext* cx, JS::HandleObject obj, const JSConstDoubleSpec* cds); - -extern JS_PUBLIC_API(bool) -JS_DefineConstIntegers(JSContext* cx, JS::HandleObject obj, const JSConstIntegerSpec* cis); - -extern JS_PUBLIC_API(bool) -JS_DefineProperties(JSContext* cx, JS::HandleObject obj, const JSPropertySpec* ps); - - -/* * */ - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnProperty(JSContext* cx, JS::HandleObject obj, const char* name, - bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, - size_t namelen, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnElement(JSContext* cx, JS::HandleObject obj, uint32_t index, bool* foundp); - -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayObject(JSContext* cx, const JS::HandleValueArray& contents); - -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayObject(JSContext* cx, size_t length); - -/** - * Returns true and sets |*isArray| indicating whether |value| is an Array - * object or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isArray == false| when passed a proxy whose - * target is an Array, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_IsArrayObject(JSContext* cx, JS::HandleValue value, bool* isArray); - -/** - * Returns true and sets |*isArray| indicating whether |obj| is an Array object - * or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isArray == false| when passed a proxy whose - * target is an Array, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_IsArrayObject(JSContext* cx, JS::HandleObject obj, bool* isArray); - -extern JS_PUBLIC_API(bool) -JS_GetArrayLength(JSContext* cx, JS::Handle obj, uint32_t* lengthp); - -extern JS_PUBLIC_API(bool) -JS_SetArrayLength(JSContext* cx, JS::Handle obj, uint32_t length); - -namespace JS { - -/** - * Returns true and sets |*isMap| indicating whether |obj| is an Map object - * or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isMap == false| when passed a proxy whose - * target is an Map, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -IsMapObject(JSContext* cx, JS::HandleObject obj, bool* isMap); - -/** - * Returns true and sets |*isSet| indicating whether |obj| is an Set object - * or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isSet == false| when passed a proxy whose - * target is an Set, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -IsSetObject(JSContext* cx, JS::HandleObject obj, bool* isSet); - -} /* namespace JS */ - -/** - * Assign 'undefined' to all of the object's non-reserved slots. Note: this is - * done for all slots, regardless of the associated property descriptor. - */ -JS_PUBLIC_API(void) -JS_SetAllNonReservedSlotsToUndefined(JSContext* cx, JSObject* objArg); - -/** - * Create a new array buffer with the given contents. It must be legal to pass - * these contents to free(). On success, the ownership is transferred to the - * new array buffer. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayBufferWithContents(JSContext* cx, size_t nbytes, void* contents); - -/** - * Create a new array buffer with the given contents. The array buffer does not take ownership of - * contents, and JS_DetachArrayBuffer must be called before the contents are disposed of. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayBufferWithExternalContents(JSContext* cx, size_t nbytes, void* contents); - -/** - * Steal the contents of the given array buffer. The array buffer has its - * length set to 0 and its contents array cleared. The caller takes ownership - * of the return value and must free it or transfer ownership via - * JS_NewArrayBufferWithContents when done using it. - */ -extern JS_PUBLIC_API(void*) -JS_StealArrayBufferContents(JSContext* cx, JS::HandleObject obj); - -/** - * Returns a pointer to the ArrayBuffer |obj|'s data. |obj| and its views will store and expose - * the data in the returned pointer: assigning into the returned pointer will affect values exposed - * by views of |obj| and vice versa. - * - * The caller must ultimately deallocate the returned pointer to avoid leaking. The memory is - * *not* garbage-collected with |obj|. These steps must be followed to deallocate: - * - * 1. The ArrayBuffer |obj| must be detached using JS_DetachArrayBuffer. - * 2. The returned pointer must be freed using JS_free. - * - * To perform step 1, callers *must* hold a reference to |obj| until they finish using the returned - * pointer. They *must not* attempt to let |obj| be GC'd, then JS_free the pointer. - * - * If |obj| isn't an ArrayBuffer, this function returns null and reports an error. - */ -extern JS_PUBLIC_API(void*) -JS_ExternalizeArrayBufferContents(JSContext* cx, JS::HandleObject obj); - -/** - * Create a new mapped array buffer with the given memory mapped contents. It - * must be legal to free the contents pointer by unmapping it. On success, - * ownership is transferred to the new mapped array buffer. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewMappedArrayBufferWithContents(JSContext* cx, size_t nbytes, void* contents); - -/** - * Create memory mapped array buffer contents. - * Caller must take care of closing fd after calling this function. - */ -extern JS_PUBLIC_API(void*) -JS_CreateMappedArrayBufferContents(int fd, size_t offset, size_t length); - -/** - * Release the allocated resource of mapped array buffer contents before the - * object is created. - * If a new object has been created by JS_NewMappedArrayBufferWithContents() - * with this content, then JS_DetachArrayBuffer() should be used instead to - * release the resource used by the object. - */ -extern JS_PUBLIC_API(void) -JS_ReleaseMappedArrayBufferContents(void* contents, size_t length); - -extern JS_PUBLIC_API(JS::Value) -JS_GetReservedSlot(JSObject* obj, uint32_t index); - -extern JS_PUBLIC_API(void) -JS_SetReservedSlot(JSObject* obj, uint32_t index, const JS::Value& v); - - -/************************************************************************/ - -/* - * Functions and scripts. - */ -extern JS_PUBLIC_API(JSFunction*) -JS_NewFunction(JSContext* cx, JSNative call, unsigned nargs, unsigned flags, - const char* name); - -namespace JS { - -extern JS_PUBLIC_API(JSFunction*) -GetSelfHostedFunction(JSContext* cx, const char* selfHostedName, HandleId id, - unsigned nargs); - -/** - * Create a new function based on the given JSFunctionSpec, *fs. - * id is the result of a successful call to - * `PropertySpecNameToPermanentId(cx, fs->name, &id)`. - * - * Unlike JS_DefineFunctions, this does not treat fs as an array. - * *fs must not be JS_FS_END. - */ -extern JS_PUBLIC_API(JSFunction*) -NewFunctionFromSpec(JSContext* cx, const JSFunctionSpec* fs, HandleId id); - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSObject*) -JS_GetFunctionObject(JSFunction* fun); - -/** - * Return the function's identifier as a JSString, or null if fun is unnamed. - * The returned string lives as long as fun, so you don't need to root a saved - * reference to it if fun is well-connected or rooted, and provided you bound - * the use of the saved reference by fun's lifetime. - */ -extern JS_PUBLIC_API(JSString*) -JS_GetFunctionId(JSFunction* fun); - -/** - * Return a function's display name. This is the defined name if one was given - * where the function was defined, or it could be an inferred name by the JS - * engine in the case that the function was defined to be anonymous. This can - * still return nullptr if a useful display name could not be inferred. The - * same restrictions on rooting as those in JS_GetFunctionId apply. - */ -extern JS_PUBLIC_API(JSString*) -JS_GetFunctionDisplayId(JSFunction* fun); - -/* - * Return the arity (length) of fun. - */ -extern JS_PUBLIC_API(uint16_t) -JS_GetFunctionArity(JSFunction* fun); - -/** - * Infallible predicate to test whether obj is a function object (faster than - * comparing obj's class name to "Function", but equivalent unless someone has - * overwritten the "Function" identifier with a different constructor and then - * created instances using that constructor that might be passed in as obj). - */ -extern JS_PUBLIC_API(bool) -JS_ObjectIsFunction(JSContext* cx, JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_IsNativeFunction(JSObject* funobj, JSNative call); - -/** Return whether the given function is a valid constructor. */ -extern JS_PUBLIC_API(bool) -JS_IsConstructor(JSFunction* fun); - -extern JS_PUBLIC_API(bool) -JS_DefineFunctions(JSContext* cx, JS::Handle obj, const JSFunctionSpec* fs); - -extern JS_PUBLIC_API(JSFunction*) -JS_DefineFunction(JSContext* cx, JS::Handle obj, const char* name, JSNative call, - unsigned nargs, unsigned attrs); - -extern JS_PUBLIC_API(JSFunction*) -JS_DefineUCFunction(JSContext* cx, JS::Handle obj, - const char16_t* name, size_t namelen, JSNative call, - unsigned nargs, unsigned attrs); - -extern JS_PUBLIC_API(JSFunction*) -JS_DefineFunctionById(JSContext* cx, JS::Handle obj, JS::Handle id, JSNative call, - unsigned nargs, unsigned attrs); - -extern JS_PUBLIC_API(bool) -JS_IsFunctionBound(JSFunction* fun); - -extern JS_PUBLIC_API(JSObject*) -JS_GetBoundFunctionTarget(JSFunction* fun); - -namespace JS { - -/** - * Clone a top-level function into cx's global. This function will dynamically - * fail if funobj was lexically nested inside some other function. - */ -extern JS_PUBLIC_API(JSObject*) -CloneFunctionObject(JSContext* cx, HandleObject funobj); - -/** - * As above, but providing an explicit scope chain. scopeChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the clone's scope chain. - */ -extern JS_PUBLIC_API(JSObject*) -CloneFunctionObject(JSContext* cx, HandleObject funobj, AutoObjectVector& scopeChain); - -} // namespace JS - -/** - * Given a buffer, return false if the buffer might become a valid - * javascript statement with the addition of more lines. Otherwise return - * true. The intent is to support interactive compilation - accumulate - * lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to - * the compiler. - */ -extern JS_PUBLIC_API(bool) -JS_BufferIsCompilableUnit(JSContext* cx, JS::Handle obj, const char* utf8, - size_t length); - -/** - * |script| will always be set. On failure, it will be set to nullptr. - */ -extern JS_PUBLIC_API(bool) -JS_CompileScript(JSContext* cx, const char* ascii, size_t length, - const JS::CompileOptions& options, - JS::MutableHandleScript script); - -/** - * |script| will always be set. On failure, it will be set to nullptr. - */ -extern JS_PUBLIC_API(bool) -JS_CompileUCScript(JSContext* cx, const char16_t* chars, size_t length, - const JS::CompileOptions& options, - JS::MutableHandleScript script); - -extern JS_PUBLIC_API(JSObject*) -JS_GetGlobalFromScript(JSScript* script); - -extern JS_PUBLIC_API(const char*) -JS_GetScriptFilename(JSScript* script); - -extern JS_PUBLIC_API(unsigned) -JS_GetScriptBaseLineNumber(JSContext* cx, JSScript* script); - -extern JS_PUBLIC_API(JSScript*) -JS_GetFunctionScript(JSContext* cx, JS::HandleFunction fun); - -namespace JS { - -/* Options for JavaScript compilation. */ - -/* - * In the most common use case, a CompileOptions instance is allocated on the - * stack, and holds non-owning references to non-POD option values: strings; - * principals; objects; and so on. The code declaring the instance guarantees - * that such option values will outlive the CompileOptions itself: objects are - * otherwise rooted; principals have had their reference counts bumped; strings - * will not be freed until the CompileOptions goes out of scope. In this - * situation, CompileOptions only refers to things others own, so it can be - * lightweight. - * - * In some cases, however, we need to hold compilation options with a - * non-stack-like lifetime. For example, JS::CompileOffThread needs to save - * compilation options where a worker thread can find them, and then return - * immediately. The worker thread will come along at some later point, and use - * the options. - * - * The compiler itself just needs to be able to access a collection of options; - * it doesn't care who owns them, or what's keeping them alive. It does its own - * addrefs/copies/tracing/etc. - * - * Furthermore, in some cases compile options are propagated from one entity to - * another (e.g. from a scriipt to a function defined in that script). This - * involves copying over some, but not all, of the options. - * - * So, we have a class hierarchy that reflects these four use cases: - * - * - TransitiveCompileOptions is the common base class, representing options - * that should get propagated from a script to functions defined in that - * script. This is never instantiated directly. - * - * - ReadOnlyCompileOptions is the only subclass of TransitiveCompileOptions, - * representing a full set of compile options. It can be used by code that - * simply needs to access options set elsewhere, like the compiler. This, - * again, is never instantiated directly. - * - * - The usual CompileOptions class must be stack-allocated, and holds - * non-owning references to the filename, element, and so on. It's derived - * from ReadOnlyCompileOptions, so the compiler can use it. - * - * - OwningCompileOptions roots / copies / reference counts of all its values, - * and unroots / frees / releases them when it is destructed. It too is - * derived from ReadOnlyCompileOptions, so the compiler accepts it. - */ - -enum class AsmJSOption : uint8_t { Enabled, Disabled, DisabledByDebugger }; - -/** - * The common base class for the CompileOptions hierarchy. - * - * Use this in code that needs to propagate compile options from one compilation - * unit to another. - */ -class JS_FRIEND_API(TransitiveCompileOptions) -{ - protected: - // The Web Platform allows scripts to be loaded from arbitrary cross-origin - // sources. This allows an attack by which a malicious website loads a - // sensitive file (say, a bank statement) cross-origin (using the user's - // cookies), and sniffs the generated syntax errors (via a window.onerror - // handler) for juicy morsels of its contents. - // - // To counter this attack, HTML5 specifies that script errors should be - // sanitized ("muted") when the script is not same-origin with the global - // for which it is loaded. Callers should set this flag for cross-origin - // scripts, and it will be propagated appropriately to child scripts and - // passed back in JSErrorReports. - bool mutedErrors_; - const char* filename_; - const char* introducerFilename_; - const char16_t* sourceMapURL_; - - // This constructor leaves 'version' set to JSVERSION_UNKNOWN. The structure - // is unusable until that's set to something more specific; the derived - // classes' constructors take care of that, in ways appropriate to their - // purpose. - TransitiveCompileOptions() - : mutedErrors_(false), - filename_(nullptr), - introducerFilename_(nullptr), - sourceMapURL_(nullptr), - version(JSVERSION_UNKNOWN), - versionSet(false), - utf8(false), - selfHostingMode(false), - canLazilyParse(true), - strictOption(false), - extraWarningsOption(false), - werrorOption(false), - asmJSOption(AsmJSOption::Disabled), - throwOnAsmJSValidationFailureOption(false), - forceAsync(false), - installedFile(false), - sourceIsLazy(false), - introductionType(nullptr), - introductionLineno(0), - introductionOffset(0), - hasIntroductionInfo(false) - { } - - // Set all POD options (those not requiring reference counts, copies, - // rooting, or other hand-holding) to their values in |rhs|. - void copyPODTransitiveOptions(const TransitiveCompileOptions& rhs); - - public: - // Read-only accessors for non-POD options. The proper way to set these - // depends on the derived type. - bool mutedErrors() const { return mutedErrors_; } - const char* filename() const { return filename_; } - const char* introducerFilename() const { return introducerFilename_; } - const char16_t* sourceMapURL() const { return sourceMapURL_; } - virtual JSObject* element() const = 0; - virtual JSString* elementAttributeName() const = 0; - virtual JSScript* introductionScript() const = 0; - - // POD options. - JSVersion version; - bool versionSet; - bool utf8; - bool selfHostingMode; - bool canLazilyParse; - bool strictOption; - bool extraWarningsOption; - bool werrorOption; - AsmJSOption asmJSOption; - bool throwOnAsmJSValidationFailureOption; - bool forceAsync; - bool installedFile; // 'true' iff pre-compiling js file in packaged app - bool sourceIsLazy; - - // |introductionType| is a statically allocated C string: - // one of "eval", "Function", or "GeneratorFunction". - const char* introductionType; - unsigned introductionLineno; - uint32_t introductionOffset; - bool hasIntroductionInfo; - - private: - void operator=(const TransitiveCompileOptions&) = delete; -}; - -/** - * The class representing a full set of compile options. - * - * Use this in code that only needs to access compilation options created - * elsewhere, like the compiler. Don't instantiate this class (the constructor - * is protected anyway); instead, create instances only of the derived classes: - * CompileOptions and OwningCompileOptions. - */ -class JS_FRIEND_API(ReadOnlyCompileOptions) : public TransitiveCompileOptions -{ - friend class CompileOptions; - - protected: - ReadOnlyCompileOptions() - : TransitiveCompileOptions(), - lineno(1), - column(0), - isRunOnce(false), - noScriptRval(false) - { } - - // Set all POD options (those not requiring reference counts, copies, - // rooting, or other hand-holding) to their values in |rhs|. - void copyPODOptions(const ReadOnlyCompileOptions& rhs); - - public: - // Read-only accessors for non-POD options. The proper way to set these - // depends on the derived type. - bool mutedErrors() const { return mutedErrors_; } - const char* filename() const { return filename_; } - const char* introducerFilename() const { return introducerFilename_; } - const char16_t* sourceMapURL() const { return sourceMapURL_; } - virtual JSObject* element() const = 0; - virtual JSString* elementAttributeName() const = 0; - virtual JSScript* introductionScript() const = 0; - - // POD options. - unsigned lineno; - unsigned column; - // isRunOnce only applies to non-function scripts. - bool isRunOnce; - bool noScriptRval; - - private: - void operator=(const ReadOnlyCompileOptions&) = delete; -}; - -/** - * Compilation options, with dynamic lifetime. An instance of this type - * makes a copy of / holds / roots all dynamically allocated resources - * (principals; elements; strings) that it refers to. Its destructor frees - * / drops / unroots them. This is heavier than CompileOptions, below, but - * unlike CompileOptions, it can outlive any given stack frame. - * - * Note that this *roots* any JS values it refers to - they're live - * unconditionally. Thus, instances of this type can't be owned, directly - * or indirectly, by a JavaScript object: if any value that this roots ever - * comes to refer to the object that owns this, then the whole cycle, and - * anything else it entrains, will never be freed. - */ -class JS_FRIEND_API(OwningCompileOptions) : public ReadOnlyCompileOptions -{ - PersistentRootedObject elementRoot; - PersistentRootedString elementAttributeNameRoot; - PersistentRootedScript introductionScriptRoot; - - public: - // A minimal constructor, for use with OwningCompileOptions::copy. This - // leaves |this.version| set to JSVERSION_UNKNOWN; the instance - // shouldn't be used until we've set that to something real (as |copy| - // will). - explicit OwningCompileOptions(JSContext* cx); - ~OwningCompileOptions(); - - JSObject* element() const override { return elementRoot; } - JSString* elementAttributeName() const override { return elementAttributeNameRoot; } - JSScript* introductionScript() const override { return introductionScriptRoot; } - - // Set this to a copy of |rhs|. Return false on OOM. - bool copy(JSContext* cx, const ReadOnlyCompileOptions& rhs); - - /* These setters make copies of their string arguments, and are fallible. */ - bool setFile(JSContext* cx, const char* f); - bool setFileAndLine(JSContext* cx, const char* f, unsigned l); - bool setSourceMapURL(JSContext* cx, const char16_t* s); - bool setIntroducerFilename(JSContext* cx, const char* s); - - /* These setters are infallible, and can be chained. */ - OwningCompileOptions& setLine(unsigned l) { lineno = l; return *this; } - OwningCompileOptions& setElement(JSObject* e) { - elementRoot = e; - return *this; - } - OwningCompileOptions& setElementAttributeName(JSString* p) { - elementAttributeNameRoot = p; - return *this; - } - OwningCompileOptions& setIntroductionScript(JSScript* s) { - introductionScriptRoot = s; - return *this; - } - OwningCompileOptions& setMutedErrors(bool mute) { - mutedErrors_ = mute; - return *this; - } - OwningCompileOptions& setVersion(JSVersion v) { - version = v; - versionSet = true; - return *this; - } - OwningCompileOptions& setUTF8(bool u) { utf8 = u; return *this; } - OwningCompileOptions& setColumn(unsigned c) { column = c; return *this; } - OwningCompileOptions& setIsRunOnce(bool once) { isRunOnce = once; return *this; } - OwningCompileOptions& setNoScriptRval(bool nsr) { noScriptRval = nsr; return *this; } - OwningCompileOptions& setSelfHostingMode(bool shm) { selfHostingMode = shm; return *this; } - OwningCompileOptions& setCanLazilyParse(bool clp) { canLazilyParse = clp; return *this; } - OwningCompileOptions& setSourceIsLazy(bool l) { sourceIsLazy = l; return *this; } - OwningCompileOptions& setIntroductionType(const char* t) { introductionType = t; return *this; } - bool setIntroductionInfo(JSContext* cx, const char* introducerFn, const char* intro, - unsigned line, JSScript* script, uint32_t offset) - { - if (!setIntroducerFilename(cx, introducerFn)) - return false; - introductionType = intro; - introductionLineno = line; - introductionScriptRoot = script; - introductionOffset = offset; - hasIntroductionInfo = true; - return true; - } - - private: - void operator=(const CompileOptions& rhs) = delete; -}; - -/** - * Compilation options stored on the stack. An instance of this type - * simply holds references to dynamically allocated resources (element; - * filename; source map URL) that are owned by something else. If you - * create an instance of this type, it's up to you to guarantee that - * everything you store in it will outlive it. - */ -class MOZ_STACK_CLASS JS_FRIEND_API(CompileOptions) final : public ReadOnlyCompileOptions -{ - RootedObject elementRoot; - RootedString elementAttributeNameRoot; - RootedScript introductionScriptRoot; - - public: - explicit CompileOptions(JSContext* cx, JSVersion version = JSVERSION_UNKNOWN); - CompileOptions(js::ContextFriendFields* cx, const ReadOnlyCompileOptions& rhs) - : ReadOnlyCompileOptions(), elementRoot(cx), elementAttributeNameRoot(cx), - introductionScriptRoot(cx) - { - copyPODOptions(rhs); - - filename_ = rhs.filename(); - introducerFilename_ = rhs.introducerFilename(); - sourceMapURL_ = rhs.sourceMapURL(); - elementRoot = rhs.element(); - elementAttributeNameRoot = rhs.elementAttributeName(); - introductionScriptRoot = rhs.introductionScript(); - } - - CompileOptions(js::ContextFriendFields* cx, const TransitiveCompileOptions& rhs) - : ReadOnlyCompileOptions(), elementRoot(cx), elementAttributeNameRoot(cx), - introductionScriptRoot(cx) - { - copyPODTransitiveOptions(rhs); - - filename_ = rhs.filename(); - introducerFilename_ = rhs.introducerFilename(); - sourceMapURL_ = rhs.sourceMapURL(); - elementRoot = rhs.element(); - elementAttributeNameRoot = rhs.elementAttributeName(); - introductionScriptRoot = rhs.introductionScript(); - } - - JSObject* element() const override { return elementRoot; } - JSString* elementAttributeName() const override { return elementAttributeNameRoot; } - JSScript* introductionScript() const override { return introductionScriptRoot; } - - CompileOptions& setFile(const char* f) { filename_ = f; return *this; } - CompileOptions& setLine(unsigned l) { lineno = l; return *this; } - CompileOptions& setFileAndLine(const char* f, unsigned l) { - filename_ = f; lineno = l; return *this; - } - CompileOptions& setSourceMapURL(const char16_t* s) { sourceMapURL_ = s; return *this; } - CompileOptions& setElement(JSObject* e) { elementRoot = e; return *this; } - CompileOptions& setElementAttributeName(JSString* p) { - elementAttributeNameRoot = p; - return *this; - } - CompileOptions& setIntroductionScript(JSScript* s) { - introductionScriptRoot = s; - return *this; - } - CompileOptions& setMutedErrors(bool mute) { - mutedErrors_ = mute; - return *this; - } - CompileOptions& setVersion(JSVersion v) { - version = v; - versionSet = true; - return *this; - } - CompileOptions& setUTF8(bool u) { utf8 = u; return *this; } - CompileOptions& setColumn(unsigned c) { column = c; return *this; } - CompileOptions& setIsRunOnce(bool once) { isRunOnce = once; return *this; } - CompileOptions& setNoScriptRval(bool nsr) { noScriptRval = nsr; return *this; } - CompileOptions& setSelfHostingMode(bool shm) { selfHostingMode = shm; return *this; } - CompileOptions& setCanLazilyParse(bool clp) { canLazilyParse = clp; return *this; } - CompileOptions& setSourceIsLazy(bool l) { sourceIsLazy = l; return *this; } - CompileOptions& setIntroductionType(const char* t) { introductionType = t; return *this; } - CompileOptions& setIntroductionInfo(const char* introducerFn, const char* intro, - unsigned line, JSScript* script, uint32_t offset) - { - introducerFilename_ = introducerFn; - introductionType = intro; - introductionLineno = line; - introductionScriptRoot = script; - introductionOffset = offset; - hasIntroductionInfo = true; - return *this; - } - CompileOptions& maybeMakeStrictMode(bool strict) { - strictOption = strictOption || strict; - return *this; - } - - private: - void operator=(const CompileOptions& rhs) = delete; -}; - -/** - * |script| will always be set. On failure, it will be set to nullptr. - */ -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* bytes, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - FILE* file, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* filename, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* bytes, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - FILE* file, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* filename, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CanCompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options, size_t length); - -/* - * Off thread compilation control flow. - * - * After successfully triggering an off thread compile of a script, the - * callback will eventually be invoked with the specified data and a token - * for the compilation. The callback will be invoked while off the main thread, - * so must ensure that its operations are thread safe. Afterwards, one of the - * following functions must be invoked on the main thread: - * - * - FinishOffThreadScript, to get the result script (or nullptr on failure). - * - CancelOffThreadScript, to free the resources without creating a script. - * - * The characters passed in to CompileOffThread must remain live until the - * callback is invoked, and the resulting script will be rooted until the call - * to FinishOffThreadScript. - */ - -extern JS_PUBLIC_API(bool) -CompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, - OffThreadCompileCallback callback, void* callbackData); - -extern JS_PUBLIC_API(JSScript*) -FinishOffThreadScript(JSContext* cx, void* token); - -extern JS_PUBLIC_API(void) -CancelOffThreadScript(JSContext* cx, void* token); - -extern JS_PUBLIC_API(bool) -CompileOffThreadModule(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, - OffThreadCompileCallback callback, void* callbackData); - -extern JS_PUBLIC_API(JSObject*) -FinishOffThreadModule(JSContext* cx, void* token); - -extern JS_PUBLIC_API(void) -CancelOffThreadModule(JSContext* cx, void* token); - -/** - * Compile a function with envChain plus the global as its scope chain. - * envChain must contain objects in the current compartment of cx. The actual - * scope chain used for the function will consist of With wrappers for those - * objects, followed by the current global of the compartment cx is in. This - * global must not be explicitly included in the scope chain. - */ -extern JS_PUBLIC_API(bool) -CompileFunction(JSContext* cx, AutoObjectVector& envChain, - const ReadOnlyCompileOptions& options, - const char* name, unsigned nargs, const char* const* argnames, - const char16_t* chars, size_t length, JS::MutableHandleFunction fun); - -/** - * Same as above, but taking a SourceBufferHolder for the function body. - */ -extern JS_PUBLIC_API(bool) -CompileFunction(JSContext* cx, AutoObjectVector& envChain, - const ReadOnlyCompileOptions& options, - const char* name, unsigned nargs, const char* const* argnames, - SourceBufferHolder& srcBuf, JS::MutableHandleFunction fun); - -/** - * Same as above, but taking a const char * for the function body. - */ -extern JS_PUBLIC_API(bool) -CompileFunction(JSContext* cx, AutoObjectVector& envChain, - const ReadOnlyCompileOptions& options, - const char* name, unsigned nargs, const char* const* argnames, - const char* bytes, size_t length, JS::MutableHandleFunction fun); - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSString*) -JS_DecompileScript(JSContext* cx, JS::Handle script, const char* name, unsigned indent); - -/* - * API extension: OR this into indent to avoid pretty-printing the decompiled - * source resulting from JS_DecompileFunction. - */ -#define JS_DONT_PRETTY_PRINT ((unsigned)0x8000) - -extern JS_PUBLIC_API(JSString*) -JS_DecompileFunction(JSContext* cx, JS::Handle fun, unsigned indent); - - -/* - * NB: JS_ExecuteScript and the JS::Evaluate APIs come in two flavors: either - * they use the global as the scope, or they take an AutoObjectVector of objects - * to use as the scope chain. In the former case, the global is also used as - * the "this" keyword value and the variables object (ECMA parlance for where - * 'var' and 'function' bind names) of the execution context for script. In the - * latter case, the first object in the provided list is used, unless the list - * is empty, in which case the global is used. - * - * Why a runtime option? The alternative is to add APIs duplicating those - * for the other value of flags, and that doesn't seem worth the code bloat - * cost. Such new entry points would probably have less obvious names, too, so - * would not tend to be used. The ContextOptionsRef adjustment, OTOH, can be - * more easily hacked into existing code that does not depend on the bug; such - * code can continue to use the familiar JS::Evaluate, etc., entry points. - */ - -/** - * Evaluate a script in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::HandleScript script, JS::MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::HandleScript script); - -/** - * As above, but providing an explicit scope chain. envChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the script's scope chain. - */ -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::AutoObjectVector& envChain, - JS::HandleScript script, JS::MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::AutoObjectVector& envChain, JS::HandleScript script); - -namespace JS { - -/** - * Like the above, but handles a cross-compartment script. If the script is - * cross-compartment, it is cloned into the current compartment before executing. - */ -extern JS_PUBLIC_API(bool) -CloneAndExecuteScript(JSContext* cx, JS::Handle script, - JS::MutableHandleValue rval); - -} /* namespace JS */ - -namespace JS { - -/** - * Evaluate the given source buffer in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleValue rval); - -/** - * As above, but providing an explicit scope chain. envChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the script's scope chain. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, AutoObjectVector& envChain, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleValue rval); - -/** - * Evaluate the given character buffer in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleValue rval); - -/** - * As above, but providing an explicit scope chain. envChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the script's scope chain. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, AutoObjectVector& envChain, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleValue rval); - -/** - * Evaluate the given byte buffer in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* bytes, size_t length, JS::MutableHandleValue rval); - -/** - * Evaluate the given file in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* filename, JS::MutableHandleValue rval); - -/** - * Get the HostResolveImportedModule hook for a global. - */ -extern JS_PUBLIC_API(JSFunction*) -GetModuleResolveHook(JSContext* cx); - -/** - * Set the HostResolveImportedModule hook for a global to the given function. - */ -extern JS_PUBLIC_API(void) -SetModuleResolveHook(JSContext* cx, JS::HandleFunction func); - -/** - * Parse the given source buffer as a module in the scope of the current global - * of cx and return a source text module record. - */ -extern JS_PUBLIC_API(bool) -CompileModule(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleObject moduleRecord); - -/** - * Set the [[HostDefined]] field of a source text module record to the given - * value. - */ -extern JS_PUBLIC_API(void) -SetModuleHostDefinedField(JSObject* module, const JS::Value& value); - -/** - * Get the [[HostDefined]] field of a source text module record. - */ -extern JS_PUBLIC_API(JS::Value) -GetModuleHostDefinedField(JSObject* module); - -/* - * Perform the ModuleDeclarationInstantiation operation on on the give source - * text module record. - * - * This transitively resolves all module dependencies (calling the - * HostResolveImportedModule hook) and initializes the environment record for - * the module. - */ -extern JS_PUBLIC_API(bool) -ModuleDeclarationInstantiation(JSContext* cx, JS::HandleObject moduleRecord); - -/* - * Perform the ModuleEvaluation operation on on the give source text module - * record. - * - * This does nothing if this module has already been evaluated. Otherwise, it - * transitively evaluates all dependences of this module and then evaluates this - * module. - * - * ModuleDeclarationInstantiation must have completed prior to calling this. - */ -extern JS_PUBLIC_API(bool) -ModuleEvaluation(JSContext* cx, JS::HandleObject moduleRecord); - -/* - * Get a list of the module specifiers used by a source text module - * record to request importation of modules. - * - * The result is a JavaScript array of string values. To extract the individual - * values use only JS_GetArrayLength and JS_GetElement with indices 0 to - * length - 1. - */ -extern JS_PUBLIC_API(JSObject*) -GetRequestedModules(JSContext* cx, JS::HandleObject moduleRecord); - -/* - * Get the script associated with a module. - */ -extern JS_PUBLIC_API(JSScript*) -GetModuleScript(JSContext* cx, JS::HandleObject moduleRecord); - -} /* namespace JS */ - -extern JS_PUBLIC_API(bool) -JS_CheckForInterrupt(JSContext* cx); - -/* - * These functions allow setting an interrupt callback that will be called - * from the JS thread some time after any thread triggered the callback using - * JS_RequestInterruptCallback(cx). - * - * To schedule the GC and for other activities the engine internally triggers - * interrupt callbacks. The embedding should thus not rely on callbacks being - * triggered through the external API only. - * - * Important note: Additional callbacks can occur inside the callback handler - * if it re-enters the JS engine. The embedding must ensure that the callback - * is disconnected before attempting such re-entry. - */ -extern JS_PUBLIC_API(bool) -JS_AddInterruptCallback(JSContext* cx, JSInterruptCallback callback); - -extern JS_PUBLIC_API(bool) -JS_DisableInterruptCallback(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_ResetInterruptCallback(JSContext* cx, bool enable); - -extern JS_PUBLIC_API(void) -JS_RequestInterruptCallback(JSContext* cx); - -namespace JS { - -/** - * Sets the callback that's invoked whenever an incumbent global is required. - * - * SpiderMonkey doesn't itself have a notion of incumbent globals as defined - * by the html spec, so we need the embedding to provide this. - * See dom/base/ScriptSettings.h for details. - */ -extern JS_PUBLIC_API(void) -SetGetIncumbentGlobalCallback(JSContext* cx, JSGetIncumbentGlobalCallback callback); - -/** - * Sets the callback that's invoked whenever a Promise job should be enqeued. - * - * SpiderMonkey doesn't schedule Promise resolution jobs itself; instead, - * using this function the embedding can provide a callback to do that - * scheduling. The provided `callback` is invoked with the promise job, - * the corresponding Promise's allocation stack, and the `data` pointer - * passed here as arguments. - */ -extern JS_PUBLIC_API(void) -SetEnqueuePromiseJobCallback(JSContext* cx, JSEnqueuePromiseJobCallback callback, - void* data = nullptr); - -/** - * Sets the callback that's invoked whenever a Promise is rejected without - * a rejection handler, and when a Promise that was previously rejected - * without a handler gets a handler attached. - */ -extern JS_PUBLIC_API(void) -SetPromiseRejectionTrackerCallback(JSContext* cx, JSPromiseRejectionTrackerCallback callback, - void* data = nullptr); - -/** - * Returns a new instance of the Promise builtin class in the current - * compartment, with the right slot layout. If a `proto` is passed, that gets - * set as the instance's [[Prototype]] instead of the original value of - * `Promise.prototype`. - */ -extern JS_PUBLIC_API(JSObject*) -NewPromiseObject(JSContext* cx, JS::HandleObject executor, JS::HandleObject proto = nullptr); - -/** - * Returns true if the given object is an unwrapped PromiseObject, false - * otherwise. - */ -extern JS_PUBLIC_API(bool) -IsPromiseObject(JS::HandleObject obj); - -/** - * Returns the current compartment's original Promise constructor. - */ -extern JS_PUBLIC_API(JSObject*) -GetPromiseConstructor(JSContext* cx); - -/** - * Returns the current compartment's original Promise.prototype. - */ -extern JS_PUBLIC_API(JSObject*) -GetPromisePrototype(JSContext* cx); - -// Keep this in sync with the PROMISE_STATE defines in SelfHostingDefines.h. -enum class PromiseState { - Pending, - Fulfilled, - Rejected -}; - -/** - * Returns the given Promise's state as a JS::PromiseState enum value. - */ -extern JS_PUBLIC_API(PromiseState) -GetPromiseState(JS::HandleObject promise); - -/** - * Returns the given Promise's process-unique ID. - */ -JS_PUBLIC_API(uint64_t) -GetPromiseID(JS::HandleObject promise); - -/** - * Returns the given Promise's result: either the resolution value for - * fulfilled promises, or the rejection reason for rejected ones. - */ -extern JS_PUBLIC_API(JS::Value) -GetPromiseResult(JS::HandleObject promise); - -/** - * Returns a js::SavedFrame linked list of the stack that lead to the given - * Promise's allocation. - */ -extern JS_PUBLIC_API(JSObject*) -GetPromiseAllocationSite(JS::HandleObject promise); - -extern JS_PUBLIC_API(JSObject*) -GetPromiseResolutionSite(JS::HandleObject promise); - -#ifdef DEBUG -extern JS_PUBLIC_API(void) -DumpPromiseAllocationSite(JSContext* cx, JS::HandleObject promise); - -extern JS_PUBLIC_API(void) -DumpPromiseResolutionSite(JSContext* cx, JS::HandleObject promise); -#endif - -/** - * Calls the current compartment's original Promise.resolve on the original - * Promise constructor, with `resolutionValue` passed as an argument. - */ -extern JS_PUBLIC_API(JSObject*) -CallOriginalPromiseResolve(JSContext* cx, JS::HandleValue resolutionValue); - -/** - * Calls the current compartment's original Promise.reject on the original - * Promise constructor, with `resolutionValue` passed as an argument. - */ -extern JS_PUBLIC_API(JSObject*) -CallOriginalPromiseReject(JSContext* cx, JS::HandleValue rejectionValue); - -/** - * Resolves the given Promise with the given `resolutionValue`. - * - * Calls the `resolve` function that was passed to the executor function when - * the Promise was created. - */ -extern JS_PUBLIC_API(bool) -ResolvePromise(JSContext* cx, JS::HandleObject promise, JS::HandleValue resolutionValue); - -/** - * Rejects the given `promise` with the given `rejectionValue`. - * - * Calls the `reject` function that was passed to the executor function when - * the Promise was created. - */ -extern JS_PUBLIC_API(bool) -RejectPromise(JSContext* cx, JS::HandleObject promise, JS::HandleValue rejectionValue); - -/** - * Calls the current compartment's original Promise.prototype.then on the - * given `promise`, with `onResolve` and `onReject` passed as arguments. - * - * Asserts if the passed-in `promise` object isn't an unwrapped instance of - * `Promise` or a subclass or `onResolve` and `onReject` aren't both either - * `nullptr` or callable objects. - */ -extern JS_PUBLIC_API(JSObject*) -CallOriginalPromiseThen(JSContext* cx, JS::HandleObject promise, - JS::HandleObject onResolve, JS::HandleObject onReject); - -/** - * Unforgeable, optimized version of the JS builtin Promise.prototype.then. - * - * Takes a Promise instance and `onResolve`, `onReject` callables to enqueue - * as reactions for that promise. In difference to Promise.prototype.then, - * this doesn't create and return a new Promise instance. - * - * Asserts if the passed-in `promise` object isn't an unwrapped instance of - * `Promise` or a subclass or `onResolve` and `onReject` aren't both callable - * objects. - */ -extern JS_PUBLIC_API(bool) -AddPromiseReactions(JSContext* cx, JS::HandleObject promise, - JS::HandleObject onResolve, JS::HandleObject onReject); - -/** - * Unforgeable version of the JS builtin Promise.all. - * - * Takes an AutoObjectVector of Promise objects and returns a promise that's - * resolved with an array of resolution values when all those promises ahve - * been resolved, or rejected with the rejection value of the first rejected - * promise. - * - * Asserts if the array isn't dense or one of the entries isn't an unwrapped - * instance of Promise or a subclass. - */ -extern JS_PUBLIC_API(JSObject*) -GetWaitForAllPromise(JSContext* cx, const JS::AutoObjectVector& promises); - -/** - * An AsyncTask represents a SpiderMonkey-internal operation that starts on a - * JSContext's owner thread, possibly executes on other threads, completes, and - * then needs to be scheduled to run again on the JSContext's owner thread. The - * embedding provides for this final dispatch back to the JSContext's owner - * thread by calling methods on this interface when requested. - */ -struct JS_PUBLIC_API(AsyncTask) -{ - AsyncTask() : user(nullptr) {} - virtual ~AsyncTask() {} - - /** - * After the FinishAsyncTaskCallback is called and succeeds, one of these - * two functions will be called on the original JSContext's owner thread. - */ - virtual void finish(JSContext* cx) = 0; - virtual void cancel(JSContext* cx) = 0; - - /* The embedding may use this field to attach arbitrary data to a task. */ - void* user; -}; - -/** - * A new AsyncTask object, created inside SpiderMonkey on the JSContext's owner - * thread, will be passed to the StartAsyncTaskCallback before it is dispatched - * to another thread. The embedding may use the AsyncTask::user field to attach - * additional task state. - * - * If this function succeeds, SpiderMonkey will call the FinishAsyncTaskCallback - * at some point in the future. Otherwise, FinishAsyncTaskCallback will *not* - * be called. SpiderMonkey assumes that, if StartAsyncTaskCallback fails, it is - * because the JSContext is being shut down. - */ -typedef bool -(*StartAsyncTaskCallback)(JSContext* cx, AsyncTask* task); - -/** - * The FinishAsyncTaskCallback may be called from any thread and will only be - * passed AsyncTasks that have already been started via StartAsyncTaskCallback. - * If the embedding returns 'true', indicating success, the embedding must call - * either task->finish() or task->cancel() on the JSContext's owner thread at - * some point in the future. - */ -typedef bool -(*FinishAsyncTaskCallback)(AsyncTask* task); - -/** - * Set the above callbacks for the given context. - */ -extern JS_PUBLIC_API(void) -SetAsyncTaskCallbacks(JSContext* cx, StartAsyncTaskCallback start, FinishAsyncTaskCallback finish); - -} // namespace JS - -extern JS_PUBLIC_API(bool) -JS_IsRunning(JSContext* cx); - -namespace JS { - -/** - * This class can be used to store a pointer to the youngest frame of a saved - * stack in the specified JSContext. This reference will be picked up by any new - * calls performed until the class is destroyed, with the specified asyncCause, - * that must not be empty. - * - * Any stack capture initiated during these new calls will go through the async - * stack instead of the current stack. - * - * Capturing the stack before a new call is performed will not be affected. - * - * The provided chain of SavedFrame objects can live in any compartment, - * although it will be copied to the compartment where the stack is captured. - * - * See also `js/src/doc/SavedFrame/SavedFrame.md` for documentation on async - * stack frames. - */ -class MOZ_STACK_CLASS JS_PUBLIC_API(AutoSetAsyncStackForNewCalls) -{ - JSContext* cx; - RootedObject oldAsyncStack; - const char* oldAsyncCause; - bool oldAsyncCallIsExplicit; - - public: - enum class AsyncCallKind { - // The ordinary kind of call, where we may apply an async - // parent if there is no ordinary parent. - IMPLICIT, - // An explicit async parent, e.g., callFunctionWithAsyncStack, - // where we always want to override any ordinary parent. - EXPLICIT - }; - - // The stack parameter cannot be null by design, because it would be - // ambiguous whether that would clear any scheduled async stack and make the - // normal stack reappear in the new call, or just keep the async stack - // already scheduled for the new call, if any. - // - // asyncCause is owned by the caller and its lifetime must outlive the - // lifetime of the AutoSetAsyncStackForNewCalls object. It is strongly - // encouraged that asyncCause be a string constant or similar statically - // allocated string. - AutoSetAsyncStackForNewCalls(JSContext* cx, HandleObject stack, - const char* asyncCause, - AsyncCallKind kind = AsyncCallKind::IMPLICIT); - ~AutoSetAsyncStackForNewCalls(); -}; - -} // namespace JS - -/************************************************************************/ - -/* - * Strings. - * - * NB: JS_NewUCString takes ownership of bytes on success, avoiding a copy; - * but on error (signified by null return), it leaves chars owned by the - * caller. So the caller must free bytes in the error case, if it has no use - * for them. In contrast, all the JS_New*StringCopy* functions do not take - * ownership of the character memory passed to them -- they copy it. - */ -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyN(JSContext* cx, const char* s, size_t n); - -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyZ(JSContext* cx, const char* s); - -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyUTF8Z(JSContext* cx, const JS::ConstUTF8CharsZ s); - -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyUTF8N(JSContext* cx, const JS::UTF8Chars s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinJSString(JSContext* cx, JS::HandleString str); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeStringN(JSContext* cx, const char* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeString(JSContext* cx, const char* s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinStringN(JSContext* cx, const char* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinString(JSContext* cx, const char* s); - -extern JS_PUBLIC_API(JSString*) -JS_NewUCString(JSContext* cx, char16_t* chars, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_NewUCStringCopyN(JSContext* cx, const char16_t* s, size_t n); - -extern JS_PUBLIC_API(JSString*) -JS_NewUCStringCopyZ(JSContext* cx, const char16_t* s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeUCStringN(JSContext* cx, const char16_t* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeUCString(JSContext* cx, const char16_t* s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinUCStringN(JSContext* cx, const char16_t* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinUCString(JSContext* cx, const char16_t* s); - -extern JS_PUBLIC_API(bool) -JS_CompareStrings(JSContext* cx, JSString* str1, JSString* str2, int32_t* result); - -extern JS_PUBLIC_API(bool) -JS_StringEqualsAscii(JSContext* cx, JSString* str, const char* asciiBytes, bool* match); - -extern JS_PUBLIC_API(size_t) -JS_PutEscapedString(JSContext* cx, char* buffer, size_t size, JSString* str, char quote); - -extern JS_PUBLIC_API(bool) -JS_FileEscapedString(FILE* fp, JSString* str, char quote); - -/* - * Extracting string characters and length. - * - * While getting the length of a string is infallible, getting the chars can - * fail. As indicated by the lack of a JSContext parameter, there are two - * special cases where getting the chars is infallible: - * - * The first case is for strings that have been atomized, e.g. directly by - * JS_AtomizeAndPinString or implicitly because it is stored in a jsid. - * - * The second case is "flat" strings that have been explicitly prepared in a - * fallible context by JS_FlattenString. To catch errors, a separate opaque - * JSFlatString type is returned by JS_FlattenString and expected by - * JS_GetFlatStringChars. Note, though, that this is purely a syntactic - * distinction: the input and output of JS_FlattenString are the same actual - * GC-thing. If a JSString is known to be flat, JS_ASSERT_STRING_IS_FLAT can be - * used to make a debug-checked cast. Example: - * - * // in a fallible context - * JSFlatString* fstr = JS_FlattenString(cx, str); - * if (!fstr) - * return false; - * MOZ_ASSERT(fstr == JS_ASSERT_STRING_IS_FLAT(str)); - * - * // in an infallible context, for the same 'str' - * AutoCheckCannotGC nogc; - * const char16_t* chars = JS_GetTwoByteFlatStringChars(nogc, fstr) - * MOZ_ASSERT(chars); - * - * Flat strings and interned strings are always null-terminated, so - * JS_FlattenString can be used to get a null-terminated string. - * - * Additionally, string characters are stored as either Latin1Char (8-bit) - * or char16_t (16-bit). Clients can use JS_StringHasLatin1Chars and can then - * call either the Latin1* or TwoByte* functions. Some functions like - * JS_CopyStringChars and JS_GetStringCharAt accept both Latin1 and TwoByte - * strings. - */ - -extern JS_PUBLIC_API(size_t) -JS_GetStringLength(JSString* str); - -extern JS_PUBLIC_API(bool) -JS_StringIsFlat(JSString* str); - -/** Returns true iff the string's characters are stored as Latin1. */ -extern JS_PUBLIC_API(bool) -JS_StringHasLatin1Chars(JSString* str); - -extern JS_PUBLIC_API(const JS::Latin1Char*) -JS_GetLatin1StringCharsAndLength(JSContext* cx, const JS::AutoCheckCannotGC& nogc, JSString* str, - size_t* length); - -extern JS_PUBLIC_API(const char16_t*) -JS_GetTwoByteStringCharsAndLength(JSContext* cx, const JS::AutoCheckCannotGC& nogc, JSString* str, - size_t* length); - -extern JS_PUBLIC_API(bool) -JS_GetStringCharAt(JSContext* cx, JSString* str, size_t index, char16_t* res); - -extern JS_PUBLIC_API(char16_t) -JS_GetFlatStringCharAt(JSFlatString* str, size_t index); - -extern JS_PUBLIC_API(const char16_t*) -JS_GetTwoByteExternalStringChars(JSString* str); - -extern JS_PUBLIC_API(bool) -JS_CopyStringChars(JSContext* cx, mozilla::Range dest, JSString* str); - -extern JS_PUBLIC_API(JSFlatString*) -JS_FlattenString(JSContext* cx, JSString* str); - -extern JS_PUBLIC_API(const JS::Latin1Char*) -JS_GetLatin1FlatStringChars(const JS::AutoCheckCannotGC& nogc, JSFlatString* str); - -extern JS_PUBLIC_API(const char16_t*) -JS_GetTwoByteFlatStringChars(const JS::AutoCheckCannotGC& nogc, JSFlatString* str); - -static MOZ_ALWAYS_INLINE JSFlatString* -JSID_TO_FLAT_STRING(jsid id) -{ - MOZ_ASSERT(JSID_IS_STRING(id)); - return (JSFlatString*)(JSID_BITS(id)); -} - -static MOZ_ALWAYS_INLINE JSFlatString* -JS_ASSERT_STRING_IS_FLAT(JSString* str) -{ - MOZ_ASSERT(JS_StringIsFlat(str)); - return (JSFlatString*)str; -} - -static MOZ_ALWAYS_INLINE JSString* -JS_FORGET_STRING_FLATNESS(JSFlatString* fstr) -{ - return (JSString*)fstr; -} - -/* - * Additional APIs that avoid fallibility when given a flat string. - */ - -extern JS_PUBLIC_API(bool) -JS_FlatStringEqualsAscii(JSFlatString* str, const char* asciiBytes); - -extern JS_PUBLIC_API(size_t) -JS_PutEscapedFlatString(char* buffer, size_t size, JSFlatString* str, char quote); - -/** - * Create a dependent string, i.e., a string that owns no character storage, - * but that refers to a slice of another string's chars. Dependent strings - * are mutable by definition, so the thread safety comments above apply. - */ -extern JS_PUBLIC_API(JSString*) -JS_NewDependentString(JSContext* cx, JS::HandleString str, size_t start, - size_t length); - -/** - * Concatenate two strings, possibly resulting in a rope. - * See above for thread safety comments. - */ -extern JS_PUBLIC_API(JSString*) -JS_ConcatStrings(JSContext* cx, JS::HandleString left, JS::HandleString right); - -/** - * For JS_DecodeBytes, set *dstlenp to the size of the destination buffer before - * the call; on return, *dstlenp contains the number of characters actually - * stored. To determine the necessary destination buffer size, make a sizing - * call that passes nullptr for dst. - * - * On errors, the functions report the error. In that case, *dstlenp contains - * the number of characters or bytes transferred so far. If cx is nullptr, no - * error is reported on failure, and the functions simply return false. - * - * NB: This function does not store an additional zero byte or char16_t after the - * transcoded string. - */ -JS_PUBLIC_API(bool) -JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen, char16_t* dst, - size_t* dstlenp); - -/** - * A variation on JS_EncodeCharacters where a null terminated string is - * returned that you are expected to call JS_free on when done. - */ -JS_PUBLIC_API(char*) -JS_EncodeString(JSContext* cx, JSString* str); - -/** - * Same behavior as JS_EncodeString(), but encode into UTF-8 string - */ -JS_PUBLIC_API(char*) -JS_EncodeStringToUTF8(JSContext* cx, JS::HandleString str); - -/** - * Get number of bytes in the string encoding (without accounting for a - * terminating zero bytes. The function returns (size_t) -1 if the string - * can not be encoded into bytes and reports an error using cx accordingly. - */ -JS_PUBLIC_API(size_t) -JS_GetStringEncodingLength(JSContext* cx, JSString* str); - -/** - * Encode string into a buffer. The function does not stores an additional - * zero byte. The function returns (size_t) -1 if the string can not be - * encoded into bytes with no error reported. Otherwise it returns the number - * of bytes that are necessary to encode the string. If that exceeds the - * length parameter, the string will be cut and only length bytes will be - * written into the buffer. - */ -JS_PUBLIC_API(size_t) -JS_EncodeStringToBuffer(JSContext* cx, JSString* str, char* buffer, size_t length); - -class MOZ_RAII JSAutoByteString -{ - public: - JSAutoByteString(JSContext* cx, JSString* str - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mBytes(JS_EncodeString(cx, str)) - { - MOZ_ASSERT(cx); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit JSAutoByteString(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) - : mBytes(nullptr) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - ~JSAutoByteString() { - JS_free(nullptr, mBytes); - } - - /* Take ownership of the given byte array. */ - void initBytes(char* bytes) { - MOZ_ASSERT(!mBytes); - mBytes = bytes; - } - - char* encodeLatin1(JSContext* cx, JSString* str) { - MOZ_ASSERT(!mBytes); - MOZ_ASSERT(cx); - mBytes = JS_EncodeString(cx, str); - return mBytes; - } - - char* encodeLatin1(js::ExclusiveContext* cx, JSString* str); - - char* encodeUtf8(JSContext* cx, JS::HandleString str) { - MOZ_ASSERT(!mBytes); - MOZ_ASSERT(cx); - mBytes = JS_EncodeStringToUTF8(cx, str); - return mBytes; - } - - void clear() { - js_free(mBytes); - mBytes = nullptr; - } - - char* ptr() const { - return mBytes; - } - - bool operator!() const { - return !mBytes; - } - - size_t length() const { - if (!mBytes) - return 0; - return strlen(mBytes); - } - - private: - char* mBytes; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - - /* Copy and assignment are not supported. */ - JSAutoByteString(const JSAutoByteString& another); - JSAutoByteString& operator=(const JSAutoByteString& another); -}; - -namespace JS { - -extern JS_PUBLIC_API(JSAddonId*) -NewAddonId(JSContext* cx, JS::HandleString str); - -extern JS_PUBLIC_API(JSString*) -StringOfAddonId(JSAddonId* id); - -extern JS_PUBLIC_API(JSAddonId*) -AddonIdOfObject(JSObject* obj); - -} // namespace JS - -/************************************************************************/ -/* - * Symbols - */ - -namespace JS { - -/** - * Create a new Symbol with the given description. This function never returns - * a Symbol that is in the Runtime-wide symbol registry. - * - * If description is null, the new Symbol's [[Description]] attribute is - * undefined. - */ -JS_PUBLIC_API(Symbol*) -NewSymbol(JSContext* cx, HandleString description); - -/** - * Symbol.for as specified in ES6. - * - * Get a Symbol with the description 'key' from the Runtime-wide symbol registry. - * If there is not already a Symbol with that description in the registry, a new - * Symbol is created and registered. 'key' must not be null. - */ -JS_PUBLIC_API(Symbol*) -GetSymbolFor(JSContext* cx, HandleString key); - -/** - * Get the [[Description]] attribute of the given symbol. - * - * This function is infallible. If it returns null, that means the symbol's - * [[Description]] is undefined. - */ -JS_PUBLIC_API(JSString*) -GetSymbolDescription(HandleSymbol symbol); - -/* Well-known symbols. */ -#define JS_FOR_EACH_WELL_KNOWN_SYMBOL(macro) \ - macro(isConcatSpreadable) \ - macro(iterator) \ - macro(match) \ - macro(replace) \ - macro(search) \ - macro(species) \ - macro(hasInstance) \ - macro(split) \ - macro(toPrimitive) \ - macro(toStringTag) \ - macro(unscopables) - -enum class SymbolCode : uint32_t { - // There is one SymbolCode for each well-known symbol. -#define JS_DEFINE_SYMBOL_ENUM(name) name, - JS_FOR_EACH_WELL_KNOWN_SYMBOL(JS_DEFINE_SYMBOL_ENUM) // SymbolCode::iterator, etc. -#undef JS_DEFINE_SYMBOL_ENUM - Limit, - InSymbolRegistry = 0xfffffffe, // created by Symbol.for() or JS::GetSymbolFor() - UniqueSymbol = 0xffffffff // created by Symbol() or JS::NewSymbol() -}; - -/* For use in loops that iterate over the well-known symbols. */ -const size_t WellKnownSymbolLimit = size_t(SymbolCode::Limit); - -/** - * Return the SymbolCode telling what sort of symbol `symbol` is. - * - * A symbol's SymbolCode never changes once it is created. - */ -JS_PUBLIC_API(SymbolCode) -GetSymbolCode(Handle symbol); - -/** - * Get one of the well-known symbols defined by ES6. A single set of well-known - * symbols is shared by all compartments in a JSRuntime. - * - * `which` must be in the range [0, WellKnownSymbolLimit). - */ -JS_PUBLIC_API(Symbol*) -GetWellKnownSymbol(JSContext* cx, SymbolCode which); - -/** - * Return true if the given JSPropertySpec::name or JSFunctionSpec::name value - * is actually a symbol code and not a string. See JS_SYM_FN. - */ -inline bool -PropertySpecNameIsSymbol(const char* name) -{ - uintptr_t u = reinterpret_cast(name); - return u != 0 && u - 1 < WellKnownSymbolLimit; -} - -JS_PUBLIC_API(bool) -PropertySpecNameEqualsId(const char* name, HandleId id); - -/** - * Create a jsid that does not need to be marked for GC. - * - * 'name' is a JSPropertySpec::name or JSFunctionSpec::name value. The - * resulting jsid, on success, is either an interned string or a well-known - * symbol; either way it is immune to GC so there is no need to visit *idp - * during GC marking. - */ -JS_PUBLIC_API(bool) -PropertySpecNameToPermanentId(JSContext* cx, const char* name, jsid* idp); - -} /* namespace JS */ - -/************************************************************************/ -/* - * JSON functions - */ -typedef bool (* JSONWriteCallback)(const char16_t* buf, uint32_t len, void* data); - -/** - * JSON.stringify as specified by ES5. - */ -JS_PUBLIC_API(bool) -JS_Stringify(JSContext* cx, JS::MutableHandleValue value, JS::HandleObject replacer, - JS::HandleValue space, JSONWriteCallback callback, void* data); - -namespace JS { - -/** - * An API akin to JS_Stringify but with the goal of not having observable - * side-effects when the stringification is performed. This means it does not - * allow a replacer or a custom space, and has the following constraints on its - * input: - * - * 1) The input must be a plain object or array, not an abitrary value. - * 2) Every value in the graph reached by the algorithm starting with this - * object must be one of the following: null, undefined, a string (NOT a - * string object!), a boolean, a finite number (i.e. no NaN or Infinity or - * -Infinity), a plain object with no accessor properties, or an Array with - * no holes. - * - * The actual behavior differs from JS_Stringify only in asserting the above and - * NOT attempting to get the "toJSON" property from things, since that could - * clearly have side-effects. - */ -JS_PUBLIC_API(bool) -ToJSONMaybeSafely(JSContext* cx, JS::HandleObject input, - JSONWriteCallback callback, void* data); - -} /* namespace JS */ - -/** - * JSON.parse as specified by ES5. - */ -JS_PUBLIC_API(bool) -JS_ParseJSON(JSContext* cx, const char16_t* chars, uint32_t len, JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_ParseJSON(JSContext* cx, JS::HandleString str, JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_ParseJSONWithReviver(JSContext* cx, const char16_t* chars, uint32_t len, JS::HandleValue reviver, - JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_ParseJSONWithReviver(JSContext* cx, JS::HandleString str, JS::HandleValue reviver, - JS::MutableHandleValue vp); - -/************************************************************************/ - -/** - * The default locale for the ECMAScript Internationalization API - * (Intl.Collator, Intl.NumberFormat, Intl.DateTimeFormat). - * Note that the Internationalization API encourages clients to - * specify their own locales. - * The locale string remains owned by the caller. - */ -extern JS_PUBLIC_API(bool) -JS_SetDefaultLocale(JSContext* cx, const char* locale); - -/** - * Look up the default locale for the ECMAScript Internationalization API. - */ -extern JS_PUBLIC_API(JS::UniqueChars) -JS_GetDefaultLocale(JSContext* cx); - -/** - * Reset the default locale to OS defaults. - */ -extern JS_PUBLIC_API(void) -JS_ResetDefaultLocale(JSContext* cx); - -/** - * Locale specific string conversion and error message callbacks. - */ -struct JSLocaleCallbacks { - JSLocaleToUpperCase localeToUpperCase; - JSLocaleToLowerCase localeToLowerCase; - JSLocaleCompare localeCompare; // not used #if EXPOSE_INTL_API - JSLocaleToUnicode localeToUnicode; -}; - -/** - * Establish locale callbacks. The pointer must persist as long as the - * JSContext. Passing nullptr restores the default behaviour. - */ -extern JS_PUBLIC_API(void) -JS_SetLocaleCallbacks(JSContext* cx, const JSLocaleCallbacks* callbacks); - -/** - * Return the address of the current locale callbacks struct, which may - * be nullptr. - */ -extern JS_PUBLIC_API(const JSLocaleCallbacks*) -JS_GetLocaleCallbacks(JSContext* cx); - -/************************************************************************/ - -/* - * Error reporting. - */ - -namespace JS { -const uint16_t MaxNumErrorArguments = 10; -}; - -/** - * Report an exception represented by the sprintf-like conversion of format - * and its arguments. - */ -extern JS_PUBLIC_API(void) -JS_ReportErrorASCII(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(void) -JS_ReportErrorLatin1(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(void) -JS_ReportErrorUTF8(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -/* - * Use an errorNumber to retrieve the format string, args are char* - */ -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberASCII(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberASCIIVA(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, va_list ap); - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberLatin1(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -#ifdef va_start -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberLatin1VA(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, va_list ap); -#endif - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUTF8(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -#ifdef va_start -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUTF8VA(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, va_list ap); -#endif - -/* - * Use an errorNumber to retrieve the format string, args are char16_t* - */ -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUC(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUCArray(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, - const char16_t** args); - -/** - * As above, but report a warning instead (JSREPORT_IS_WARNING(report.flags)). - * Return true if there was no error trying to issue the warning, and if the - * warning was not converted into an error due to the JSOPTION_WERROR option - * being set, false otherwise. - */ -extern JS_PUBLIC_API(bool) -JS_ReportWarningASCII(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(bool) -JS_ReportWarningLatin1(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(bool) -JS_ReportWarningUTF8(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberASCII(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberLatin1(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberUTF8(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberUC(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -/** - * Complain when out of memory. - */ -extern JS_PUBLIC_API(void) -JS_ReportOutOfMemory(JSContext* cx); - -/** - * Complain when an allocation size overflows the maximum supported limit. - */ -extern JS_PUBLIC_API(void) -JS_ReportAllocationOverflow(JSContext* cx); - -class JSErrorReport -{ - // The (default) error message. - // If ownsMessage_ is true, the it is freed in destructor. - JS::ConstUTF8CharsZ message_; - - // Offending source line without final '\n'. - // If ownsLinebuf__ is true, the buffer is freed in destructor. - const char16_t* linebuf_; - - // Number of chars in linebuf_. Does not include trailing '\0'. - size_t linebufLength_; - - // The 0-based offset of error token in linebuf_. - size_t tokenOffset_; - - public: - JSErrorReport() - : linebuf_(nullptr), linebufLength_(0), tokenOffset_(0), - filename(nullptr), lineno(0), column(0), - flags(0), errorNumber(0), - exnType(0), isMuted(false), - ownsLinebuf_(false), ownsMessage_(false) - {} - - ~JSErrorReport() { - freeLinebuf(); - freeMessage(); - } - - const char* filename; /* source file name, URL, etc., or null */ - unsigned lineno; /* source line number */ - unsigned column; /* zero-based column index in line */ - unsigned flags; /* error/warning, etc. */ - unsigned errorNumber; /* the error number, e.g. see js.msg */ - int16_t exnType; /* One of the JSExnType constants */ - bool isMuted : 1; /* See the comment in ReadOnlyCompileOptions. */ - - private: - bool ownsLinebuf_ : 1; - bool ownsMessage_ : 1; - - public: - const char16_t* linebuf() const { - return linebuf_; - } - size_t linebufLength() const { - return linebufLength_; - } - size_t tokenOffset() const { - return tokenOffset_; - } - void initOwnedLinebuf(const char16_t* linebufArg, size_t linebufLengthArg, size_t tokenOffsetArg) { - initBorrowedLinebuf(linebufArg, linebufLengthArg, tokenOffsetArg); - ownsLinebuf_ = true; - } - void initBorrowedLinebuf(const char16_t* linebufArg, size_t linebufLengthArg, size_t tokenOffsetArg); - void freeLinebuf(); - - const JS::ConstUTF8CharsZ message() const { - return message_; - } - - void initOwnedMessage(const char* messageArg) { - initBorrowedMessage(messageArg); - ownsMessage_ = true; - } - void initBorrowedMessage(const char* messageArg) { - MOZ_ASSERT(!message_); - message_ = JS::ConstUTF8CharsZ(messageArg, strlen(messageArg)); - } - - JSString* newMessageString(JSContext* cx); - - void freeMessage(); -}; - -/* - * JSErrorReport flag values. These may be freely composed. - */ -#define JSREPORT_ERROR 0x0 /* pseudo-flag for default case */ -#define JSREPORT_WARNING 0x1 /* reported via JS_ReportWarning */ -#define JSREPORT_EXCEPTION 0x2 /* exception was thrown */ -#define JSREPORT_STRICT 0x4 /* error or warning due to strict option */ - -#define JSREPORT_USER_1 0x8 /* user-defined flag */ - -/* - * If JSREPORT_EXCEPTION is set, then a JavaScript-catchable exception - * has been thrown for this runtime error, and the host should ignore it. - * Exception-aware hosts should also check for JS_IsExceptionPending if - * JS_ExecuteScript returns failure, and signal or propagate the exception, as - * appropriate. - */ -#define JSREPORT_IS_WARNING(flags) (((flags) & JSREPORT_WARNING) != 0) -#define JSREPORT_IS_EXCEPTION(flags) (((flags) & JSREPORT_EXCEPTION) != 0) -#define JSREPORT_IS_STRICT(flags) (((flags) & JSREPORT_STRICT) != 0) - -namespace JS { - -using WarningReporter = void (*)(JSContext* cx, JSErrorReport* report); - -extern JS_PUBLIC_API(WarningReporter) -SetWarningReporter(JSContext* cx, WarningReporter reporter); - -extern JS_PUBLIC_API(WarningReporter) -GetWarningReporter(JSContext* cx); - -extern JS_PUBLIC_API(bool) -CreateError(JSContext* cx, JSExnType type, HandleObject stack, - HandleString fileName, uint32_t lineNumber, uint32_t columnNumber, - JSErrorReport* report, HandleString message, MutableHandleValue rval); - -/************************************************************************/ - -/* - * Weak Maps. - */ - -extern JS_PUBLIC_API(JSObject*) -NewWeakMapObject(JSContext* cx); - -extern JS_PUBLIC_API(bool) -IsWeakMapObject(JSObject* obj); - -extern JS_PUBLIC_API(bool) -GetWeakMapEntry(JSContext* cx, JS::HandleObject mapObj, JS::HandleObject key, - JS::MutableHandleValue val); - -extern JS_PUBLIC_API(bool) -SetWeakMapEntry(JSContext* cx, JS::HandleObject mapObj, JS::HandleObject key, - JS::HandleValue val); - -/* - * Map - */ -extern JS_PUBLIC_API(JSObject*) -NewMapObject(JSContext* cx); - -extern JS_PUBLIC_API(uint32_t) -MapSize(JSContext* cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -MapGet(JSContext* cx, HandleObject obj, - HandleValue key, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapHas(JSContext* cx, HandleObject obj, HandleValue key, bool* rval); - -extern JS_PUBLIC_API(bool) -MapSet(JSContext* cx, HandleObject obj, HandleValue key, HandleValue val); - -extern JS_PUBLIC_API(bool) -MapDelete(JSContext *cx, HandleObject obj, HandleValue key, bool *rval); - -extern JS_PUBLIC_API(bool) -MapClear(JSContext* cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -MapKeys(JSContext* cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapValues(JSContext* cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapEntries(JSContext* cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapForEach(JSContext *cx, HandleObject obj, HandleValue callbackFn, HandleValue thisVal); - -/* - * Set - */ -extern JS_PUBLIC_API(JSObject *) -NewSetObject(JSContext *cx); - -extern JS_PUBLIC_API(uint32_t) -SetSize(JSContext *cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -SetHas(JSContext *cx, HandleObject obj, HandleValue key, bool *rval); - -extern JS_PUBLIC_API(bool) -SetDelete(JSContext *cx, HandleObject obj, HandleValue key, bool *rval); - -extern JS_PUBLIC_API(bool) -SetAdd(JSContext *cx, HandleObject obj, HandleValue key); - -extern JS_PUBLIC_API(bool) -SetClear(JSContext *cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -SetKeys(JSContext *cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -SetValues(JSContext *cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -SetEntries(JSContext *cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -SetForEach(JSContext *cx, HandleObject obj, HandleValue callbackFn, HandleValue thisVal); - -} /* namespace JS */ - -/* - * Dates. - */ - -extern JS_PUBLIC_API(JSObject*) -JS_NewDateObject(JSContext* cx, int year, int mon, int mday, int hour, int min, int sec); - -/** - * Returns true and sets |*isDate| indicating whether |obj| is a Date object or - * a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isDate == false| when passed a proxy whose - * target is a Date, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_ObjectIsDate(JSContext* cx, JS::HandleObject obj, bool* isDate); - -/************************************************************************/ - -/* - * Regular Expressions. - */ -#define JSREG_FOLD 0x01u /* fold uppercase to lowercase */ -#define JSREG_GLOB 0x02u /* global exec, creates array of matches */ -#define JSREG_MULTILINE 0x04u /* treat ^ and $ as begin and end of line */ -#define JSREG_STICKY 0x08u /* only match starting at lastIndex */ -#define JSREG_UNICODE 0x10u /* unicode */ - -extern JS_PUBLIC_API(JSObject*) -JS_NewRegExpObject(JSContext* cx, const char* bytes, size_t length, unsigned flags); - -extern JS_PUBLIC_API(JSObject*) -JS_NewUCRegExpObject(JSContext* cx, const char16_t* chars, size_t length, unsigned flags); - -extern JS_PUBLIC_API(bool) -JS_SetRegExpInput(JSContext* cx, JS::HandleObject obj, JS::HandleString input); - -extern JS_PUBLIC_API(bool) -JS_ClearRegExpStatics(JSContext* cx, JS::HandleObject obj); - -extern JS_PUBLIC_API(bool) -JS_ExecuteRegExp(JSContext* cx, JS::HandleObject obj, JS::HandleObject reobj, - char16_t* chars, size_t length, size_t* indexp, bool test, - JS::MutableHandleValue rval); - -/* RegExp interface for clients without a global object. */ - -extern JS_PUBLIC_API(bool) -JS_ExecuteRegExpNoStatics(JSContext* cx, JS::HandleObject reobj, char16_t* chars, size_t length, - size_t* indexp, bool test, JS::MutableHandleValue rval); - -/** - * Returns true and sets |*isRegExp| indicating whether |obj| is a RegExp - * object or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isRegExp == false| when passed a proxy whose - * target is a RegExp, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_ObjectIsRegExp(JSContext* cx, JS::HandleObject obj, bool* isRegExp); - -extern JS_PUBLIC_API(unsigned) -JS_GetRegExpFlags(JSContext* cx, JS::HandleObject obj); - -extern JS_PUBLIC_API(JSString*) -JS_GetRegExpSource(JSContext* cx, JS::HandleObject obj); - -/************************************************************************/ - -extern JS_PUBLIC_API(bool) -JS_IsExceptionPending(JSContext* cx); - -extern JS_PUBLIC_API(bool) -JS_GetPendingException(JSContext* cx, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(void) -JS_SetPendingException(JSContext* cx, JS::HandleValue v); - -extern JS_PUBLIC_API(void) -JS_ClearPendingException(JSContext* cx); - -namespace JS { - -/** - * Save and later restore the current exception state of a given JSContext. - * This is useful for implementing behavior in C++ that's like try/catch - * or try/finally in JS. - * - * Typical usage: - * - * bool ok = JS::Evaluate(cx, ...); - * AutoSaveExceptionState savedExc(cx); - * ... cleanup that might re-enter JS ... - * return ok; - */ -class JS_PUBLIC_API(AutoSaveExceptionState) -{ - private: - JSContext* context; - bool wasPropagatingForcedReturn; - bool wasOverRecursed; - bool wasThrowing; - RootedValue exceptionValue; - - public: - /* - * Take a snapshot of cx's current exception state. Then clear any current - * pending exception in cx. - */ - explicit AutoSaveExceptionState(JSContext* cx); - - /* - * If neither drop() nor restore() was called, restore the exception - * state only if no exception is currently pending on cx. - */ - ~AutoSaveExceptionState(); - - /* - * Discard any stored exception state. - * If this is called, the destructor is a no-op. - */ - void drop() { - wasPropagatingForcedReturn = false; - wasOverRecursed = false; - wasThrowing = false; - exceptionValue.setUndefined(); - } - - /* - * Replace cx's exception state with the stored exception state. Then - * discard the stored exception state. If this is called, the - * destructor is a no-op. - */ - void restore(); -}; - -} /* namespace JS */ - -/* Deprecated API. Use AutoSaveExceptionState instead. */ -extern JS_PUBLIC_API(JSExceptionState*) -JS_SaveExceptionState(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_RestoreExceptionState(JSContext* cx, JSExceptionState* state); - -extern JS_PUBLIC_API(void) -JS_DropExceptionState(JSContext* cx, JSExceptionState* state); - -/** - * If the given object is an exception object, the exception will have (or be - * able to lazily create) an error report struct, and this function will return - * the address of that struct. Otherwise, it returns nullptr. The lifetime - * of the error report struct that might be returned is the same as the - * lifetime of the exception object. - */ -extern JS_PUBLIC_API(JSErrorReport*) -JS_ErrorFromException(JSContext* cx, JS::HandleObject obj); - -/** - * If the given object is an exception object (or an unwrappable - * cross-compartment wrapper for one), return the stack for that exception, if - * any. Will return null if the given object is not an exception object - * (including if it's null or a security wrapper that can't be unwrapped) or if - * the exception has no stack. - */ -extern JS_PUBLIC_API(JSObject*) -ExceptionStackOrNull(JS::HandleObject obj); - -/* - * Throws a StopIteration exception on cx. - */ -extern JS_PUBLIC_API(bool) -JS_ThrowStopIteration(JSContext* cx); - -extern JS_PUBLIC_API(bool) -JS_IsStopIteration(const JS::Value& v); - -/** - * A JS context always has an "owner thread". The owner thread is set when the - * context is created (to the current thread) and practically all entry points - * into the JS engine check that a context (or anything contained in the - * context: runtime, compartment, object, etc) is only touched by its owner - * thread. Embeddings may check this invariant outside the JS engine by calling - * JS_AbortIfWrongThread (which will abort if not on the owner thread, even for - * non-debug builds). - */ - -extern JS_PUBLIC_API(void) -JS_AbortIfWrongThread(JSContext* cx); - -/************************************************************************/ - -/** - * A constructor can request that the JS engine create a default new 'this' - * object of the given class, using the callee to determine parentage and - * [[Prototype]]. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewObjectForConstructor(JSContext* cx, const JSClass* clasp, const JS::CallArgs& args); - -/************************************************************************/ - -#ifdef JS_GC_ZEAL -#define JS_DEFAULT_ZEAL_FREQ 100 - -extern JS_PUBLIC_API(void) -JS_GetGCZealBits(JSContext* cx, uint32_t* zealBits, uint32_t* frequency, uint32_t* nextScheduled); - -extern JS_PUBLIC_API(void) -JS_SetGCZeal(JSContext* cx, uint8_t zeal, uint32_t frequency); - -extern JS_PUBLIC_API(void) -JS_ScheduleGC(JSContext* cx, uint32_t count); -#endif - -extern JS_PUBLIC_API(void) -JS_SetParallelParsingEnabled(JSContext* cx, bool enabled); - -extern JS_PUBLIC_API(void) -JS_SetOffthreadIonCompilationEnabled(JSContext* cx, bool enabled); - -#define JIT_COMPILER_OPTIONS(Register) \ - Register(BASELINE_WARMUP_TRIGGER, "baseline.warmup.trigger") \ - Register(ION_WARMUP_TRIGGER, "ion.warmup.trigger") \ - Register(ION_GVN_ENABLE, "ion.gvn.enable") \ - Register(ION_FORCE_IC, "ion.forceinlineCaches") \ - Register(ION_ENABLE, "ion.enable") \ - Register(ION_INTERRUPT_WITHOUT_SIGNAL, "ion.interrupt-without-signals") \ - Register(ION_CHECK_RANGE_ANALYSIS, "ion.check-range-analysis") \ - Register(BASELINE_ENABLE, "baseline.enable") \ - Register(OFFTHREAD_COMPILATION_ENABLE, "offthread-compilation.enable") \ - Register(JUMP_THRESHOLD, "jump-threshold") \ - Register(ASMJS_ATOMICS_ENABLE, "asmjs.atomics.enable") \ - Register(WASM_TEST_MODE, "wasm.test-mode") \ - Register(WASM_FOLD_OFFSETS, "wasm.fold-offsets") - -typedef enum JSJitCompilerOption { -#define JIT_COMPILER_DECLARE(key, str) \ - JSJITCOMPILER_ ## key, - - JIT_COMPILER_OPTIONS(JIT_COMPILER_DECLARE) -#undef JIT_COMPILER_DECLARE - - JSJITCOMPILER_NOT_AN_OPTION -} JSJitCompilerOption; - -extern JS_PUBLIC_API(void) -JS_SetGlobalJitCompilerOption(JSContext* cx, JSJitCompilerOption opt, uint32_t value); -extern JS_PUBLIC_API(bool) -JS_GetGlobalJitCompilerOption(JSContext* cx, JSJitCompilerOption opt, uint32_t* valueOut); - -/** - * Convert a uint32_t index into a jsid. - */ -extern JS_PUBLIC_API(bool) -JS_IndexToId(JSContext* cx, uint32_t index, JS::MutableHandleId); - -/** - * Convert chars into a jsid. - * - * |chars| may not be an index. - */ -extern JS_PUBLIC_API(bool) -JS_CharsToId(JSContext* cx, JS::TwoByteChars chars, JS::MutableHandleId); - -/** - * Test if the given string is a valid ECMAScript identifier - */ -extern JS_PUBLIC_API(bool) -JS_IsIdentifier(JSContext* cx, JS::HandleString str, bool* isIdentifier); - -/** - * Test whether the given chars + length are a valid ECMAScript identifier. - * This version is infallible, so just returns whether the chars are an - * identifier. - */ -extern JS_PUBLIC_API(bool) -JS_IsIdentifier(const char16_t* chars, size_t length); - -namespace js { -class ScriptSource; -} // namespace js - -namespace JS { - -class MOZ_RAII JS_PUBLIC_API(AutoFilename) -{ - private: - js::ScriptSource* ss_; - mozilla::Variant filename_; - - AutoFilename(const AutoFilename&) = delete; - AutoFilename& operator=(const AutoFilename&) = delete; - - public: - AutoFilename() - : ss_(nullptr), - filename_(mozilla::AsVariant(nullptr)) - {} - - ~AutoFilename() { - reset(); - } - - void reset(); - - void setOwned(UniqueChars&& filename); - void setUnowned(const char* filename); - void setScriptSource(js::ScriptSource* ss); - - const char* get() const; -}; - -/** - * Return the current filename, line number and column number of the most - * currently running frame. Returns true if a scripted frame was found, false - * otherwise. - * - * If a the embedding has hidden the scripted caller for the topmost activation - * record, this will also return false. - */ -extern JS_PUBLIC_API(bool) -DescribeScriptedCaller(JSContext* cx, AutoFilename* filename = nullptr, - unsigned* lineno = nullptr, unsigned* column = nullptr); - -extern JS_PUBLIC_API(JSObject*) -GetScriptedCallerGlobal(JSContext* cx); - -/** - * Informs the JS engine that the scripted caller should be hidden. This can be - * used by the embedding to maintain an override of the scripted caller in its - * calculations, by hiding the scripted caller in the JS engine and pushing data - * onto a separate stack, which it inspects when DescribeScriptedCaller returns - * null. - * - * We maintain a counter on each activation record. Add() increments the counter - * of the topmost activation, and Remove() decrements it. The count may never - * drop below zero, and must always be exactly zero when the activation is - * popped from the stack. - */ -extern JS_PUBLIC_API(void) -HideScriptedCaller(JSContext* cx); - -extern JS_PUBLIC_API(void) -UnhideScriptedCaller(JSContext* cx); - -class MOZ_RAII AutoHideScriptedCaller -{ - public: - explicit AutoHideScriptedCaller(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mContext(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - HideScriptedCaller(mContext); - } - ~AutoHideScriptedCaller() { - UnhideScriptedCaller(mContext); - } - - protected: - JSContext* mContext; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/* - * Encode/Decode interpreted scripts and functions to/from memory. - */ - -typedef mozilla::Vector TranscodeBuffer; - -enum TranscodeResult -{ - // Successful encoding / decoding. - TranscodeResult_Ok = 0, - - // A warning message, is set to the message out-param. - TranscodeResult_Failure = 0x100, - TranscodeResult_Failure_BadBuildId = TranscodeResult_Failure | 0x1, - TranscodeResult_Failure_RunOnceNotSupported = TranscodeResult_Failure | 0x2, - TranscodeResult_Failure_AsmJSNotSupported = TranscodeResult_Failure | 0x3, - TranscodeResult_Failure_UnknownClassKind = TranscodeResult_Failure | 0x4, - - // A error, the JSContext has a pending exception. - TranscodeResult_Throw = 0x200 -}; - -extern JS_PUBLIC_API(TranscodeResult) -EncodeScript(JSContext* cx, TranscodeBuffer& buffer, JS::HandleScript script); - -extern JS_PUBLIC_API(TranscodeResult) -EncodeInterpretedFunction(JSContext* cx, TranscodeBuffer& buffer, JS::HandleObject funobj); - -extern JS_PUBLIC_API(TranscodeResult) -DecodeScript(JSContext* cx, TranscodeBuffer& buffer, JS::MutableHandleScript scriptp, - size_t cursorIndex = 0); - -extern JS_PUBLIC_API(TranscodeResult) -DecodeInterpretedFunction(JSContext* cx, TranscodeBuffer& buffer, JS::MutableHandleFunction funp, - size_t cursorIndex = 0); - -} /* namespace JS */ - -namespace js { - -enum class StackFormat { SpiderMonkey, V8, Default }; - -/* - * Sets the format used for stringifying Error stacks. - * - * The default format is StackFormat::SpiderMonkey. Use StackFormat::V8 - * in order to emulate V8's stack formatting. StackFormat::Default can't be - * used here. - */ -extern JS_PUBLIC_API(void) -SetStackFormat(JSContext* cx, StackFormat format); - -extern JS_PUBLIC_API(StackFormat) -GetStackFormat(JSContext* cx); - -} - -namespace JS { - -/* - * This callback represents a request by the JS engine to open for reading the - * existing cache entry for the given global and char range that may contain a - * module. If a cache entry exists, the callback shall return 'true' and return - * the size, base address and an opaque file handle as outparams. If the - * callback returns 'true', the JS engine guarantees a call to - * CloseAsmJSCacheEntryForReadOp, passing the same base address, size and - * handle. - */ -typedef bool -(* OpenAsmJSCacheEntryForReadOp)(HandleObject global, const char16_t* begin, const char16_t* limit, - size_t* size, const uint8_t** memory, intptr_t* handle); -typedef void -(* CloseAsmJSCacheEntryForReadOp)(size_t size, const uint8_t* memory, intptr_t handle); - -/** The list of reasons why an asm.js module may not be stored in the cache. */ -enum AsmJSCacheResult -{ - AsmJSCache_Success, - AsmJSCache_MIN = AsmJSCache_Success, - AsmJSCache_ModuleTooSmall, - AsmJSCache_SynchronousScript, - AsmJSCache_QuotaExceeded, - AsmJSCache_StorageInitFailure, - AsmJSCache_Disabled_Internal, - AsmJSCache_Disabled_ShellFlags, - AsmJSCache_Disabled_JitInspector, - AsmJSCache_InternalError, - AsmJSCache_Disabled_PrivateBrowsing, - AsmJSCache_LIMIT -}; - -/* - * This callback represents a request by the JS engine to open for writing a - * cache entry of the given size for the given global and char range containing - * the just-compiled module. If cache entry space is available, the callback - * shall return 'true' and return the base address and an opaque file handle as - * outparams. If the callback returns 'true', the JS engine guarantees a call - * to CloseAsmJSCacheEntryForWriteOp passing the same base address, size and - * handle. - * - * If 'installed' is true, then the cache entry is associated with a permanently - * installed JS file (e.g., in a packaged webapp). This information allows the - * embedding to store the cache entry in a installed location associated with - * the principal of 'global' where it will not be evicted until the associated - * installed JS file is removed. - */ -typedef AsmJSCacheResult -(* OpenAsmJSCacheEntryForWriteOp)(HandleObject global, bool installed, - const char16_t* begin, const char16_t* end, - size_t size, uint8_t** memory, intptr_t* handle); -typedef void -(* CloseAsmJSCacheEntryForWriteOp)(size_t size, uint8_t* memory, intptr_t handle); - -struct AsmJSCacheOps -{ - OpenAsmJSCacheEntryForReadOp openEntryForRead; - CloseAsmJSCacheEntryForReadOp closeEntryForRead; - OpenAsmJSCacheEntryForWriteOp openEntryForWrite; - CloseAsmJSCacheEntryForWriteOp closeEntryForWrite; -}; - -extern JS_PUBLIC_API(void) -SetAsmJSCacheOps(JSContext* cx, const AsmJSCacheOps* callbacks); - -/** - * Return the buildId (represented as a sequence of characters) associated with - * the currently-executing build. If the JS engine is embedded such that a - * single cache entry can be observed by different compiled versions of the JS - * engine, it is critical that the buildId shall change for each new build of - * the JS engine. - */ -typedef js::Vector BuildIdCharVector; - -typedef bool -(* BuildIdOp)(BuildIdCharVector* buildId); - -extern JS_PUBLIC_API(void) -SetBuildIdOp(JSContext* cx, BuildIdOp buildIdOp); - -/** - * The WasmModule interface allows the embedding to hold a reference to the - * underying C++ implementation of a JS WebAssembly.Module object for purposes - * of (de)serialization off the object's JSRuntime's thread. - * - * - Serialization starts when WebAssembly.Module is passed to the - * structured-clone algorithm. JS::GetWasmModule is called on the JSRuntime - * thread that initiated the structured clone to get the JS::WasmModule. - * This interface is then taken to a background thread where serializedSize() - * and serialize() are called to write the object to two files: a bytecode file - * that always allows successful deserialization and a compiled-code file keyed - * on cpu- and build-id that may become invalid if either of these change between - * serialization and deserialization. After serialization, the reference is - * dropped from the background thread. - * - * - Deserialization starts when the structured clone algorithm encounters a - * serialized WebAssembly.Module. On a background thread, the compiled-code file - * is opened and CompiledWasmModuleAssumptionsMatch is called to see if it is - * still valid (as described above). DeserializeWasmModule is then called to - * construct a JS::WasmModule (also on the background thread), passing the - * bytecode file descriptor and, if valid, the compiled-code file descriptor. - * The JS::WasmObject is then transported to the JSRuntime thread (which - * originated the request) and the wrapping WebAssembly.Module object is created - * by calling createObject(). - */ - -struct WasmModule : mozilla::external::AtomicRefCounted -{ - MOZ_DECLARE_REFCOUNTED_TYPENAME(WasmModule) - virtual ~WasmModule() {} - - virtual void serializedSize(size_t* maybeBytecodeSize, size_t* maybeCompiledSize) const = 0; - virtual void serialize(uint8_t* maybeBytecodeBegin, size_t maybeBytecodeSize, - uint8_t* maybeCompiledBegin, size_t maybeCompiledSize) const = 0; - - virtual JSObject* createObject(JSContext* cx) = 0; -}; - -extern JS_PUBLIC_API(bool) -IsWasmModuleObject(HandleObject obj); - -extern JS_PUBLIC_API(RefPtr) -GetWasmModule(HandleObject obj); - -extern JS_PUBLIC_API(bool) -CompiledWasmModuleAssumptionsMatch(PRFileDesc* compiled, BuildIdCharVector&& buildId); - -extern JS_PUBLIC_API(RefPtr) -DeserializeWasmModule(PRFileDesc* bytecode, PRFileDesc* maybeCompiled, BuildIdCharVector&& buildId, - JS::UniqueChars filename, unsigned line, unsigned column); - -/** - * Convenience class for imitating a JS level for-of loop. Typical usage: - * - * ForOfIterator it(cx); - * if (!it.init(iterable)) - * return false; - * RootedValue val(cx); - * while (true) { - * bool done; - * if (!it.next(&val, &done)) - * return false; - * if (done) - * break; - * if (!DoStuff(cx, val)) - * return false; - * } - */ -class MOZ_STACK_CLASS JS_PUBLIC_API(ForOfIterator) { - protected: - JSContext* cx_; - /* - * Use the ForOfPIC on the global object (see vm/GlobalObject.h) to try - * to optimize iteration across arrays. - * - * Case 1: Regular Iteration - * iterator - pointer to the iterator object. - * index - fixed to NOT_ARRAY (== UINT32_MAX) - * - * Case 2: Optimized Array Iteration - * iterator - pointer to the array object. - * index - current position in array. - * - * The cases are distinguished by whether or not |index| is equal to NOT_ARRAY. - */ - JS::RootedObject iterator; - uint32_t index; - - static const uint32_t NOT_ARRAY = UINT32_MAX; - - ForOfIterator(const ForOfIterator&) = delete; - ForOfIterator& operator=(const ForOfIterator&) = delete; - - public: - explicit ForOfIterator(JSContext* cx) : cx_(cx), iterator(cx_), index(NOT_ARRAY) { } - - enum NonIterableBehavior { - ThrowOnNonIterable, - AllowNonIterable - }; - - /** - * Initialize the iterator. If AllowNonIterable is passed then if getting - * the @@iterator property from iterable returns undefined init() will just - * return true instead of throwing. Callers must then check - * valueIsIterable() before continuing with the iteration. - */ - bool init(JS::HandleValue iterable, - NonIterableBehavior nonIterableBehavior = ThrowOnNonIterable); - - /** - * Get the next value from the iterator. If false *done is true - * after this call, do not examine val. - */ - bool next(JS::MutableHandleValue val, bool* done); - - /** - * If initialized with throwOnNonCallable = false, check whether - * the value is iterable. - */ - bool valueIsIterable() const { - return iterator; - } - - private: - inline bool nextFromOptimizedArray(MutableHandleValue val, bool* done); - bool materializeArrayIterator(); -}; - - -/** - * If a large allocation fails when calling pod_{calloc,realloc}CanGC, the JS - * engine may call the large-allocation- failure callback, if set, to allow the - * embedding to flush caches, possibly perform shrinking GCs, etc. to make some - * room. The allocation will then be retried (and may still fail.) - */ - -typedef void -(* LargeAllocationFailureCallback)(void* data); - -extern JS_PUBLIC_API(void) -SetLargeAllocationFailureCallback(JSContext* cx, LargeAllocationFailureCallback afc, void* data); - -/** - * Unlike the error reporter, which is only called if the exception for an OOM - * bubbles up and is not caught, the OutOfMemoryCallback is called immediately - * at the OOM site to allow the embedding to capture the current state of heap - * allocation before anything is freed. If the large-allocation-failure callback - * is called at all (not all allocation sites call the large-allocation-failure - * callback on failure), it is called before the out-of-memory callback; the - * out-of-memory callback is only called if the allocation still fails after the - * large-allocation-failure callback has returned. - */ - -typedef void -(* OutOfMemoryCallback)(JSContext* cx, void* data); - -extern JS_PUBLIC_API(void) -SetOutOfMemoryCallback(JSContext* cx, OutOfMemoryCallback cb, void* data); - -/** - * Capture all frames. - */ -struct AllFrames { }; - -/** - * Capture at most this many frames. - */ -struct MaxFrames -{ - uint32_t maxFrames; - - explicit MaxFrames(uint32_t max) - : maxFrames(max) - { - MOZ_ASSERT(max > 0); - } -}; - -/** - * Capture the first frame with the given principals. By default, do not - * consider self-hosted frames with the given principals as satisfying the stack - * capture. - */ -struct FirstSubsumedFrame -{ - JSContext* cx; - JSPrincipals* principals; - bool ignoreSelfHosted; - - /** - * Use the cx's current compartment's principals. - */ - explicit FirstSubsumedFrame(JSContext* cx, bool ignoreSelfHostedFrames = true); - - explicit FirstSubsumedFrame(JSContext* ctx, JSPrincipals* p, bool ignoreSelfHostedFrames = true) - : cx(ctx) - , principals(p) - , ignoreSelfHosted(ignoreSelfHostedFrames) - { - if (principals) - JS_HoldPrincipals(principals); - } - - // No copying because we want to avoid holding and dropping principals - // unnecessarily. - FirstSubsumedFrame(const FirstSubsumedFrame&) = delete; - FirstSubsumedFrame& operator=(const FirstSubsumedFrame&) = delete; - - FirstSubsumedFrame(FirstSubsumedFrame&& rhs) - : principals(rhs.principals) - , ignoreSelfHosted(rhs.ignoreSelfHosted) - { - MOZ_ASSERT(this != &rhs, "self move disallowed"); - rhs.principals = nullptr; - } - - FirstSubsumedFrame& operator=(FirstSubsumedFrame&& rhs) { - new (this) FirstSubsumedFrame(mozilla::Move(rhs)); - return *this; - } - - ~FirstSubsumedFrame() { - if (principals) - JS_DropPrincipals(cx, principals); - } -}; - -using StackCapture = mozilla::Variant; - -/** - * Capture the current call stack as a chain of SavedFrame JSObjects, and set - * |stackp| to the SavedFrame for the youngest stack frame, or nullptr if there - * are no JS frames on the stack. - * - * The |capture| parameter describes the portion of the JS stack to capture: - * - * * |JS::AllFrames|: Capture all frames on the stack. - * - * * |JS::MaxFrames|: Capture no more than |JS::MaxFrames::maxFrames| from the - * stack. - * - * * |JS::FirstSubsumedFrame|: Capture the first frame whose principals are - * subsumed by |JS::FirstSubsumedFrame::principals|. By default, do not - * consider self-hosted frames; this can be controlled via the - * |JS::FirstSubsumedFrame::ignoreSelfHosted| flag. Do not capture any async - * stack. - */ -extern JS_PUBLIC_API(bool) -CaptureCurrentStack(JSContext* cx, MutableHandleObject stackp, - StackCapture&& capture = StackCapture(AllFrames())); - -/* - * This is a utility function for preparing an async stack to be used - * by some other object. This may be used when you need to treat a - * given stack trace as an async parent. If you just need to capture - * the current stack, async parents and all, use CaptureCurrentStack - * instead. - * - * Here |asyncStack| is the async stack to prepare. It is copied into - * |cx|'s current compartment, and the newest frame is given - * |asyncCause| as its asynchronous cause. If |maxFrameCount| is - * non-zero, capture at most the youngest |maxFrameCount| frames. The - * new stack object is written to |stackp|. Returns true on success, - * or sets an exception and returns |false| on error. - */ -extern JS_PUBLIC_API(bool) -CopyAsyncStack(JSContext* cx, HandleObject asyncStack, - HandleString asyncCause, MutableHandleObject stackp, - unsigned maxFrameCount); - -/* - * Accessors for working with SavedFrame JSObjects - * - * Each of these functions assert that if their `HandleObject savedFrame` - * argument is non-null, its JSClass is the SavedFrame class (or it is a - * cross-compartment or Xray wrapper around an object with the SavedFrame class) - * and the object is not the SavedFrame.prototype object. - * - * Each of these functions will find the first SavedFrame object in the chain - * whose underlying stack frame principals are subsumed by the cx's current - * compartment's principals, and operate on that SavedFrame object. This - * prevents leaking information about privileged frames to un-privileged - * callers. As a result, the SavedFrame in parameters do _NOT_ need to be in the - * same compartment as the cx, and the various out parameters are _NOT_ - * guaranteed to be in the same compartment as cx. - * - * You may consider or skip over self-hosted frames by passing - * `SavedFrameSelfHosted::Include` or `SavedFrameSelfHosted::Exclude` - * respectively. - * - * Additionally, it may be the case that there is no such SavedFrame object - * whose captured frame's principals are subsumed by the caller's compartment's - * principals! If the `HandleObject savedFrame` argument is null, or the - * caller's principals do not subsume any of the chained SavedFrame object's - * principals, `SavedFrameResult::AccessDenied` is returned and a (hopefully) - * sane default value is chosen for the out param. - * - * See also `js/src/doc/SavedFrame/SavedFrame.md`. - */ - -enum class SavedFrameResult { - Ok, - AccessDenied -}; - -enum class SavedFrameSelfHosted { - Include, - Exclude -}; - -/** - * Given a SavedFrame JSObject, get its source property. Defaults to the empty - * string. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameSource(JSContext* cx, HandleObject savedFrame, MutableHandleString sourcep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its line property. Defaults to 0. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameLine(JSContext* cx, HandleObject savedFrame, uint32_t* linep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its column property. Defaults to 0. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameColumn(JSContext* cx, HandleObject savedFrame, uint32_t* columnp, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its functionDisplayName string, or nullptr - * if SpiderMonkey was unable to infer a name for the captured frame's - * function. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameFunctionDisplayName(JSContext* cx, HandleObject savedFrame, MutableHandleString namep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its asyncCause string. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameAsyncCause(JSContext* cx, HandleObject savedFrame, MutableHandleString asyncCausep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its asyncParent SavedFrame object or nullptr - * if there is no asyncParent. The `asyncParentp` out parameter is _NOT_ - * guaranteed to be in the cx's compartment. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameAsyncParent(JSContext* cx, HandleObject savedFrame, MutableHandleObject asyncParentp, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its parent SavedFrame object or nullptr if - * it is the oldest frame in the stack. The `parentp` out parameter is _NOT_ - * guaranteed to be in the cx's compartment. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameParent(JSContext* cx, HandleObject savedFrame, MutableHandleObject parentp, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject stack, stringify it in the same format as - * Error.prototype.stack. The stringified stack out parameter is placed in the - * cx's compartment. Defaults to the empty string. - * - * The same notes above about SavedFrame accessors applies here as well: cx - * doesn't need to be in stack's compartment, and stack can be null, a - * SavedFrame object, or a wrapper (CCW or Xray) around a SavedFrame object. - * - * Optional indent parameter specifies the number of white spaces to indent - * each line. - */ -extern JS_PUBLIC_API(bool) -BuildStackString(JSContext* cx, HandleObject stack, MutableHandleString stringp, - size_t indent = 0, js::StackFormat stackFormat = js::StackFormat::Default); - -/** - * Return true iff the given object is either a SavedFrame object or wrapper - * around a SavedFrame object, and it is not the SavedFrame.prototype object. - */ -extern JS_PUBLIC_API(bool) -IsSavedFrame(JSObject* obj); - -} /* namespace JS */ - - -/* Stopwatch-based performance monitoring. */ - -namespace js { - -class AutoStopwatch; - -/** - * Abstract base class for a representation of the performance of a - * component. Embeddings interested in performance monitoring should - * provide a concrete implementation of this class, as well as the - * relevant callbacks (see below). - */ -struct PerformanceGroup { - PerformanceGroup(); - - // The current iteration of the event loop. - uint64_t iteration() const; - - // `true` if an instance of `AutoStopwatch` is already monitoring - // the performance of this performance group for this iteration - // of the event loop, `false` otherwise. - bool isAcquired(uint64_t it) const; - - // `true` if a specific instance of `AutoStopwatch` is already monitoring - // the performance of this performance group for this iteration - // of the event loop, `false` otherwise. - bool isAcquired(uint64_t it, const AutoStopwatch* owner) const; - - // Mark that an instance of `AutoStopwatch` is monitoring - // the performance of this group for a given iteration. - void acquire(uint64_t it, const AutoStopwatch* owner); - - // Mark that no `AutoStopwatch` is monitoring the - // performance of this group for the iteration. - void release(uint64_t it, const AutoStopwatch* owner); - - // The number of cycles spent in this group during this iteration - // of the event loop. Note that cycles are not a reliable measure, - // especially over short intervals. See Stopwatch.* for a more - // complete discussion on the imprecision of cycle measurement. - uint64_t recentCycles(uint64_t iteration) const; - void addRecentCycles(uint64_t iteration, uint64_t cycles); - - // The number of times this group has been activated during this - // iteration of the event loop. - uint64_t recentTicks(uint64_t iteration) const; - void addRecentTicks(uint64_t iteration, uint64_t ticks); - - // The number of microseconds spent doing CPOW during this - // iteration of the event loop. - uint64_t recentCPOW(uint64_t iteration) const; - void addRecentCPOW(uint64_t iteration, uint64_t CPOW); - - // Get rid of any data that pretends to be recent. - void resetRecentData(); - - // `true` if new measures should be added to this group, `false` - // otherwise. - bool isActive() const; - void setIsActive(bool); - - // `true` if this group has been used in the current iteration, - // `false` otherwise. - bool isUsedInThisIteration() const; - void setIsUsedInThisIteration(bool); - protected: - // An implementation of `delete` for this object. Must be provided - // by the embedding. - virtual void Delete() = 0; - - private: - // The number of cycles spent in this group during this iteration - // of the event loop. Note that cycles are not a reliable measure, - // especially over short intervals. See Runtime.cpp for a more - // complete discussion on the imprecision of cycle measurement. - uint64_t recentCycles_; - - // The number of times this group has been activated during this - // iteration of the event loop. - uint64_t recentTicks_; - - // The number of microseconds spent doing CPOW during this - // iteration of the event loop. - uint64_t recentCPOW_; - - // The current iteration of the event loop. If necessary, - // may safely overflow. - uint64_t iteration_; - - // `true` if new measures should be added to this group, `false` - // otherwise. - bool isActive_; - - // `true` if this group has been used in the current iteration, - // `false` otherwise. - bool isUsedInThisIteration_; - - // The stopwatch currently monitoring the group, - // or `nullptr` if none. Used ony for comparison. - const AutoStopwatch* owner_; - - public: - // Compatibility with RefPtr<> - void AddRef(); - void Release(); - uint64_t refCount_; -}; - -using PerformanceGroupVector = mozilla::Vector, 0, SystemAllocPolicy>; - -/** - * Commit any Performance Monitoring data. - * - * Until `FlushMonitoring` has been called, all PerformanceMonitoring data is invisible - * to the outside world and can cancelled with a call to `ResetMonitoring`. - */ -extern JS_PUBLIC_API(bool) -FlushPerformanceMonitoring(JSContext*); - -/** - * Cancel any measurement that hasn't been committed. - */ -extern JS_PUBLIC_API(void) -ResetPerformanceMonitoring(JSContext*); - -/** - * Cleanup any memory used by performance monitoring. - */ -extern JS_PUBLIC_API(void) -DisposePerformanceMonitoring(JSContext*); - -/** - * Turn on/off stopwatch-based CPU monitoring. - * - * `SetStopwatchIsMonitoringCPOW` or `SetStopwatchIsMonitoringJank` - * may return `false` if monitoring could not be activated, which may - * happen if we are out of memory. - */ -extern JS_PUBLIC_API(bool) -SetStopwatchIsMonitoringCPOW(JSContext*, bool); -extern JS_PUBLIC_API(bool) -GetStopwatchIsMonitoringCPOW(JSContext*); -extern JS_PUBLIC_API(bool) -SetStopwatchIsMonitoringJank(JSContext*, bool); -extern JS_PUBLIC_API(bool) -GetStopwatchIsMonitoringJank(JSContext*); - -// Extract the CPU rescheduling data. -extern JS_PUBLIC_API(void) -GetPerfMonitoringTestCpuRescheduling(JSContext*, uint64_t* stayed, uint64_t* moved); - - -/** - * Add a number of microseconds to the time spent waiting on CPOWs - * since process start. - */ -extern JS_PUBLIC_API(void) -AddCPOWPerformanceDelta(JSContext*, uint64_t delta); - -typedef bool -(*StopwatchStartCallback)(uint64_t, void*); -extern JS_PUBLIC_API(bool) -SetStopwatchStartCallback(JSContext*, StopwatchStartCallback, void*); - -typedef bool -(*StopwatchCommitCallback)(uint64_t, PerformanceGroupVector&, void*); -extern JS_PUBLIC_API(bool) -SetStopwatchCommitCallback(JSContext*, StopwatchCommitCallback, void*); - -typedef bool -(*GetGroupsCallback)(JSContext*, PerformanceGroupVector&, void*); -extern JS_PUBLIC_API(bool) -SetGetPerformanceGroupsCallback(JSContext*, GetGroupsCallback, void*); - -} /* namespace js */ - - -#endif /* jsapi_h */ diff --git a/ios/include/spidermonkey/jsbytecode.h b/ios/include/spidermonkey/jsbytecode.h deleted file mode 100644 index 8e4f4cf9..00000000 --- a/ios/include/spidermonkey/jsbytecode.h +++ /dev/null @@ -1,14 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsbytecode_h -#define jsbytecode_h - -#include - -typedef uint8_t jsbytecode; - -#endif /* jsbytecode_h */ diff --git a/ios/include/spidermonkey/jsclist.h b/ios/include/spidermonkey/jsclist.h deleted file mode 100644 index b8455152..00000000 --- a/ios/include/spidermonkey/jsclist.h +++ /dev/null @@ -1,107 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsclist_h -#define jsclist_h - -#include "jstypes.h" - -/* -** Circular linked list -*/ -typedef struct JSCListStr { - struct JSCListStr* next; - struct JSCListStr* prev; -} JSCList; - -/* -** Insert element "_e" into the list, before "_l". -*/ -#define JS_INSERT_BEFORE(_e,_l) \ - JS_BEGIN_MACRO \ - (_e)->next = (_l); \ - (_e)->prev = (_l)->prev; \ - (_l)->prev->next = (_e); \ - (_l)->prev = (_e); \ - JS_END_MACRO - -/* -** Insert element "_e" into the list, after "_l". -*/ -#define JS_INSERT_AFTER(_e,_l) \ - JS_BEGIN_MACRO \ - (_e)->next = (_l)->next; \ - (_e)->prev = (_l); \ - (_l)->next->prev = (_e); \ - (_l)->next = (_e); \ - JS_END_MACRO - -/* -** Return the element following element "_e" -*/ -#define JS_NEXT_LINK(_e) \ - ((_e)->next) -/* -** Return the element preceding element "_e" -*/ -#define JS_PREV_LINK(_e) \ - ((_e)->prev) - -/* -** Append an element "_e" to the end of the list "_l" -*/ -#define JS_APPEND_LINK(_e,_l) JS_INSERT_BEFORE(_e,_l) - -/* -** Insert an element "_e" at the head of the list "_l" -*/ -#define JS_INSERT_LINK(_e,_l) JS_INSERT_AFTER(_e,_l) - -/* Return the head/tail of the list */ -#define JS_LIST_HEAD(_l) (_l)->next -#define JS_LIST_TAIL(_l) (_l)->prev - -/* -** Remove the element "_e" from it's circular list. -*/ -#define JS_REMOVE_LINK(_e) \ - JS_BEGIN_MACRO \ - (_e)->prev->next = (_e)->next; \ - (_e)->next->prev = (_e)->prev; \ - JS_END_MACRO - -/* -** Remove the element "_e" from it's circular list. Also initializes the -** linkage. -*/ -#define JS_REMOVE_AND_INIT_LINK(_e) \ - JS_BEGIN_MACRO \ - (_e)->prev->next = (_e)->next; \ - (_e)->next->prev = (_e)->prev; \ - (_e)->next = (_e); \ - (_e)->prev = (_e); \ - JS_END_MACRO - -/* -** Return non-zero if the given circular list "_l" is empty, zero if the -** circular list is not empty -*/ -#define JS_CLIST_IS_EMPTY(_l) \ - bool((_l)->next == (_l)) - -/* -** Initialize a circular list -*/ -#define JS_INIT_CLIST(_l) \ - JS_BEGIN_MACRO \ - (_l)->next = (_l); \ - (_l)->prev = (_l); \ - JS_END_MACRO - -#define JS_INIT_STATIC_CLIST(_l) \ - {(_l), (_l)} - -#endif /* jsclist_h */ diff --git a/ios/include/spidermonkey/jscpucfg.h b/ios/include/spidermonkey/jscpucfg.h deleted file mode 100644 index 80fdf6bb..00000000 --- a/ios/include/spidermonkey/jscpucfg.h +++ /dev/null @@ -1,20 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jscpucfg_h -#define jscpucfg_h - -#include "mozilla/EndianUtils.h" - -#ifndef JS_STACK_GROWTH_DIRECTION -# ifdef __hppa -# define JS_STACK_GROWTH_DIRECTION (1) -# else -# define JS_STACK_GROWTH_DIRECTION (-1) -# endif -#endif - -#endif /* jscpucfg_h */ diff --git a/ios/include/spidermonkey/jsfriendapi.h b/ios/include/spidermonkey/jsfriendapi.h deleted file mode 100644 index d6463d3d..00000000 --- a/ios/include/spidermonkey/jsfriendapi.h +++ /dev/null @@ -1,3067 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsfriendapi_h -#define jsfriendapi_h - -#include "mozilla/Atomics.h" -#include "mozilla/Casting.h" -#include "mozilla/Maybe.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/UniquePtr.h" - -#include "jsapi.h" // For JSAutoByteString. See bug 1033916. -#include "jsbytecode.h" -#include "jspubtd.h" - -#include "js/CallArgs.h" -#include "js/CallNonGenericMethod.h" -#include "js/Class.h" -#include "js/Utility.h" - -#if JS_STACK_GROWTH_DIRECTION > 0 -# define JS_CHECK_STACK_SIZE(limit, sp) (MOZ_LIKELY((uintptr_t)(sp) < (limit))) -#else -# define JS_CHECK_STACK_SIZE(limit, sp) (MOZ_LIKELY((uintptr_t)(sp) > (limit))) -#endif - -class JSAtom; -struct JSErrorFormatString; -class JSLinearString; -struct JSJitInfo; -class JSErrorReport; - -namespace JS { -template -class Heap; -} /* namespace JS */ - -namespace js { -class JS_FRIEND_API(BaseProxyHandler); -class InterpreterFrame; -} /* namespace js */ - -extern JS_FRIEND_API(void) -JS_SetGrayGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data); - -extern JS_FRIEND_API(JSObject*) -JS_FindCompilationScope(JSContext* cx, JS::HandleObject obj); - -extern JS_FRIEND_API(JSFunction*) -JS_GetObjectFunction(JSObject* obj); - -extern JS_FRIEND_API(bool) -JS_SplicePrototype(JSContext* cx, JS::HandleObject obj, JS::HandleObject proto); - -extern JS_FRIEND_API(JSObject*) -JS_NewObjectWithUniqueType(JSContext* cx, const JSClass* clasp, JS::HandleObject proto); - -/** - * Allocate an object in exactly the same way as JS_NewObjectWithGivenProto, but - * without invoking the metadata callback on it. This allows creation of - * internal bookkeeping objects that are guaranteed to not have metadata - * attached to them. - */ -extern JS_FRIEND_API(JSObject*) -JS_NewObjectWithoutMetadata(JSContext* cx, const JSClass* clasp, JS::Handle proto); - -extern JS_FRIEND_API(uint32_t) -JS_ObjectCountDynamicSlots(JS::HandleObject obj); - -extern JS_FRIEND_API(size_t) -JS_SetProtoCalled(JSContext* cx); - -extern JS_FRIEND_API(size_t) -JS_GetCustomIteratorCount(JSContext* cx); - -extern JS_FRIEND_API(bool) -JS_NondeterministicGetWeakMapKeys(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject ret); - -extern JS_FRIEND_API(bool) -JS_NondeterministicGetWeakSetKeys(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject ret); - -// Raw JSScript* because this needs to be callable from a signal handler. -extern JS_FRIEND_API(unsigned) -JS_PCToLineNumber(JSScript* script, jsbytecode* pc, unsigned* columnp = nullptr); - -/** - * Determine whether the given object is backed by a DeadObjectProxy. - * - * Such objects hold no other objects (they have no outgoing reference edges) - * and will throw if you touch them (e.g. by reading/writing a property). - */ -extern JS_FRIEND_API(bool) -JS_IsDeadWrapper(JSObject* obj); - -/* - * Used by the cycle collector to trace through a shape or object group and - * all cycle-participating data it reaches, using bounded stack space. - */ -extern JS_FRIEND_API(void) -JS_TraceShapeCycleCollectorChildren(JS::CallbackTracer* trc, JS::GCCellPtr shape); -extern JS_FRIEND_API(void) -JS_TraceObjectGroupCycleCollectorChildren(JS::CallbackTracer* trc, JS::GCCellPtr group); - -enum { - JS_TELEMETRY_GC_REASON, - JS_TELEMETRY_GC_IS_ZONE_GC, - JS_TELEMETRY_GC_MS, - JS_TELEMETRY_GC_BUDGET_MS, - JS_TELEMETRY_GC_ANIMATION_MS, - JS_TELEMETRY_GC_MAX_PAUSE_MS, - JS_TELEMETRY_GC_MARK_MS, - JS_TELEMETRY_GC_SWEEP_MS, - JS_TELEMETRY_GC_COMPACT_MS, - JS_TELEMETRY_GC_MARK_ROOTS_MS, - JS_TELEMETRY_GC_MARK_GRAY_MS, - JS_TELEMETRY_GC_SLICE_MS, - JS_TELEMETRY_GC_SLOW_PHASE, - JS_TELEMETRY_GC_MMU_50, - JS_TELEMETRY_GC_RESET, - JS_TELEMETRY_GC_RESET_REASON, - JS_TELEMETRY_GC_INCREMENTAL_DISABLED, - JS_TELEMETRY_GC_NON_INCREMENTAL, - JS_TELEMETRY_GC_NON_INCREMENTAL_REASON, - JS_TELEMETRY_GC_SCC_SWEEP_TOTAL_MS, - JS_TELEMETRY_GC_SCC_SWEEP_MAX_PAUSE_MS, - JS_TELEMETRY_GC_MINOR_REASON, - JS_TELEMETRY_GC_MINOR_REASON_LONG, - JS_TELEMETRY_GC_MINOR_US, - JS_TELEMETRY_GC_NURSERY_BYTES, - JS_TELEMETRY_GC_PRETENURE_COUNT, - JS_TELEMETRY_DEPRECATED_LANGUAGE_EXTENSIONS_IN_CONTENT, - JS_TELEMETRY_DEPRECATED_LANGUAGE_EXTENSIONS_IN_ADDONS, - JS_TELEMETRY_ADDON_EXCEPTIONS, - JS_TELEMETRY_AOT_USAGE, - JS_TELEMETRY_END -}; - -typedef void -(*JSAccumulateTelemetryDataCallback)(int id, uint32_t sample, const char* key); - -extern JS_FRIEND_API(void) -JS_SetAccumulateTelemetryCallback(JSContext* cx, JSAccumulateTelemetryDataCallback callback); - -extern JS_FRIEND_API(bool) -JS_GetIsSecureContext(JSCompartment* compartment); - -extern JS_FRIEND_API(JSPrincipals*) -JS_GetCompartmentPrincipals(JSCompartment* compartment); - -extern JS_FRIEND_API(void) -JS_SetCompartmentPrincipals(JSCompartment* compartment, JSPrincipals* principals); - -extern JS_FRIEND_API(JSPrincipals*) -JS_GetScriptPrincipals(JSScript* script); - -extern JS_FRIEND_API(bool) -JS_ScriptHasMutedErrors(JSScript* script); - -extern JS_FRIEND_API(JSObject*) -JS_CloneObject(JSContext* cx, JS::HandleObject obj, JS::HandleObject proto); - -/** - * Copy the own properties of src to dst in a fast way. src and dst must both - * be native and must be in the compartment of cx. They must have the same - * class, the same parent, and the same prototype. Class reserved slots will - * NOT be copied. - * - * dst must not have any properties on it before this function is called. - * - * src must have been allocated via JS_NewObjectWithoutMetadata so that we can - * be sure it has no metadata that needs copying to dst. This also means that - * dst needs to have the compartment global as its parent. This function will - * preserve the existing metadata on dst, if any. - */ -extern JS_FRIEND_API(bool) -JS_InitializePropertiesFromCompatibleNativeObject(JSContext* cx, - JS::HandleObject dst, - JS::HandleObject src); - -extern JS_FRIEND_API(JSString*) -JS_BasicObjectToString(JSContext* cx, JS::HandleObject obj); - -namespace js { - -JS_FRIEND_API(bool) -GetBuiltinClass(JSContext* cx, JS::HandleObject obj, ESClass* cls); - -JS_FRIEND_API(const char*) -ObjectClassName(JSContext* cx, JS::HandleObject obj); - -JS_FRIEND_API(void) -ReportOverRecursed(JSContext* maybecx); - -JS_FRIEND_API(bool) -AddRawValueRoot(JSContext* cx, JS::Value* vp, const char* name); - -JS_FRIEND_API(void) -RemoveRawValueRoot(JSContext* cx, JS::Value* vp); - -JS_FRIEND_API(JSAtom*) -GetPropertyNameFromPC(JSScript* script, jsbytecode* pc); - -#ifdef JS_DEBUG - -/* - * Routines to print out values during debugging. These are FRIEND_API to help - * the debugger find them and to support temporarily hacking js::Dump* calls - * into other code. Note that there are overloads that do not require the FILE* - * parameter, which will default to stderr. - */ - -extern JS_FRIEND_API(void) -DumpString(JSString* str, FILE* fp); - -extern JS_FRIEND_API(void) -DumpAtom(JSAtom* atom, FILE* fp); - -extern JS_FRIEND_API(void) -DumpObject(JSObject* obj, FILE* fp); - -extern JS_FRIEND_API(void) -DumpChars(const char16_t* s, size_t n, FILE* fp); - -extern JS_FRIEND_API(void) -DumpValue(const JS::Value& val, FILE* fp); - -extern JS_FRIEND_API(void) -DumpId(jsid id, FILE* fp); - -extern JS_FRIEND_API(void) -DumpInterpreterFrame(JSContext* cx, FILE* fp, InterpreterFrame* start = nullptr); - -extern JS_FRIEND_API(bool) -DumpPC(JSContext* cx, FILE* fp); - -extern JS_FRIEND_API(bool) -DumpScript(JSContext* cx, JSScript* scriptArg, FILE* fp); - -// Versions for use directly in a debugger (default parameters are not handled -// well in gdb; built-in handles like stderr are not handled well in lldb.) -extern JS_FRIEND_API(void) DumpString(JSString* str); -extern JS_FRIEND_API(void) DumpAtom(JSAtom* atom); -extern JS_FRIEND_API(void) DumpObject(JSObject* obj); -extern JS_FRIEND_API(void) DumpChars(const char16_t* s, size_t n); -extern JS_FRIEND_API(void) DumpValue(const JS::Value& val); -extern JS_FRIEND_API(void) DumpId(jsid id); -extern JS_FRIEND_API(void) DumpInterpreterFrame(JSContext* cx, InterpreterFrame* start = nullptr); -extern JS_FRIEND_API(bool) DumpPC(JSContext* cx); -extern JS_FRIEND_API(bool) DumpScript(JSContext* cx, JSScript* scriptArg); - -#endif - -extern JS_FRIEND_API(void) -DumpBacktrace(JSContext* cx, FILE* fp); - -extern JS_FRIEND_API(void) -DumpBacktrace(JSContext* cx); - -} // namespace js - -namespace JS { - -/** Exposed for DumpJSStack */ -extern JS_FRIEND_API(char*) -FormatStackDump(JSContext* cx, char* buf, bool showArgs, bool showLocals, bool showThisProps); - -/** - * Set all of the uninitialized lexicals on an object to undefined. Return - * true if any lexicals were initialized and false otherwise. - * */ -extern JS_FRIEND_API(bool) -ForceLexicalInitialization(JSContext *cx, HandleObject obj); - -} // namespace JS - -/** - * Copies all own properties from |obj| to |target|. |obj| must be a "native" - * object (that is to say, normal-ish - not an Array or a Proxy). - * - * This function immediately enters a compartment, and does not impose any - * restrictions on the compartment of |cx|. - */ -extern JS_FRIEND_API(bool) -JS_CopyPropertiesFrom(JSContext* cx, JS::HandleObject target, JS::HandleObject obj); - -/* - * Single-property version of the above. This function asserts that an |own| - * property of the given name exists on |obj|. - * - * On entry, |cx| must be same-compartment with |obj|. - * - * The copyBehavior argument controls what happens with - * non-configurable properties. - */ -typedef enum { - MakeNonConfigurableIntoConfigurable, - CopyNonConfigurableAsIs -} PropertyCopyBehavior; - -extern JS_FRIEND_API(bool) -JS_CopyPropertyFrom(JSContext* cx, JS::HandleId id, JS::HandleObject target, - JS::HandleObject obj, - PropertyCopyBehavior copyBehavior = CopyNonConfigurableAsIs); - -extern JS_FRIEND_API(bool) -JS_WrapPropertyDescriptor(JSContext* cx, JS::MutableHandle desc); - -struct JSFunctionSpecWithHelp { - const char* name; - JSNative call; - uint16_t nargs; - uint16_t flags; - const JSJitInfo* jitInfo; - const char* usage; - const char* help; -}; - -#define JS_FN_HELP(name,call,nargs,flags,usage,help) \ - {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, nullptr, usage, help} -#define JS_INLINABLE_FN_HELP(name,call,nargs,flags,native,usage,help) \ - {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, &js::jit::JitInfo_##native,\ - usage, help} -#define JS_FS_HELP_END \ - {nullptr, nullptr, 0, 0, nullptr, nullptr} - -extern JS_FRIEND_API(bool) -JS_DefineFunctionsWithHelp(JSContext* cx, JS::HandleObject obj, const JSFunctionSpecWithHelp* fs); - -namespace js { - -extern JS_FRIEND_DATA(const js::ClassOps) ProxyClassOps; -extern JS_FRIEND_DATA(const js::ClassExtension) ProxyClassExtension; -extern JS_FRIEND_DATA(const js::ObjectOps) ProxyObjectOps; - -/* - * Helper Macros for creating JSClasses that function as proxies. - * - * NB: The macro invocation must be surrounded by braces, so as to - * allow for potential JSClass extensions. - */ -#define PROXY_MAKE_EXT(objectMoved) \ - { \ - js::proxy_WeakmapKeyDelegate, \ - objectMoved \ - } - -#define PROXY_CLASS_WITH_EXT(name, flags, extPtr) \ - { \ - name, \ - js::Class::NON_NATIVE | \ - JSCLASS_IS_PROXY | \ - JSCLASS_DELAY_METADATA_BUILDER | \ - flags, \ - &js::ProxyClassOps, \ - JS_NULL_CLASS_SPEC, \ - extPtr, \ - &js::ProxyObjectOps \ - } - -#define PROXY_CLASS_DEF(name, flags) \ - PROXY_CLASS_WITH_EXT(name, flags, &js::ProxyClassExtension) - -/* - * Proxy stubs, similar to JS_*Stub, for embedder proxy class definitions. - * - * NB: Should not be called directly. - */ - -extern JS_FRIEND_API(bool) -proxy_LookupProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleObject objp, - JS::MutableHandle propp); -extern JS_FRIEND_API(bool) -proxy_DefineProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc, - JS::ObjectOpResult& result); -extern JS_FRIEND_API(bool) -proxy_HasProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); -extern JS_FRIEND_API(bool) -proxy_GetProperty(JSContext* cx, JS::HandleObject obj, JS::HandleValue receiver, JS::HandleId id, - JS::MutableHandleValue vp); -extern JS_FRIEND_API(bool) -proxy_SetProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue bp, - JS::HandleValue receiver, JS::ObjectOpResult& result); -extern JS_FRIEND_API(bool) -proxy_GetOwnPropertyDescriptor(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); -extern JS_FRIEND_API(bool) -proxy_DeleteProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -extern JS_FRIEND_API(void) -proxy_Trace(JSTracer* trc, JSObject* obj); -extern JS_FRIEND_API(JSObject*) -proxy_WeakmapKeyDelegate(JSObject* obj); -extern JS_FRIEND_API(bool) -proxy_Convert(JSContext* cx, JS::HandleObject proxy, JSType hint, JS::MutableHandleValue vp); -extern JS_FRIEND_API(void) -proxy_Finalize(FreeOp* fop, JSObject* obj); -extern JS_FRIEND_API(void) -proxy_ObjectMoved(JSObject* obj, const JSObject* old); -extern JS_FRIEND_API(bool) -proxy_HasInstance(JSContext* cx, JS::HandleObject proxy, JS::MutableHandleValue v, bool* bp); -extern JS_FRIEND_API(bool) -proxy_Call(JSContext* cx, unsigned argc, JS::Value* vp); -extern JS_FRIEND_API(bool) -proxy_Construct(JSContext* cx, unsigned argc, JS::Value* vp); -extern JS_FRIEND_API(JSObject*) -proxy_innerObject(JSObject* obj); -extern JS_FRIEND_API(bool) -proxy_Watch(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); -extern JS_FRIEND_API(bool) -proxy_Unwatch(JSContext* cx, JS::HandleObject obj, JS::HandleId id); -extern JS_FRIEND_API(bool) -proxy_GetElements(JSContext* cx, JS::HandleObject proxy, uint32_t begin, uint32_t end, - ElementAdder* adder); -extern JS_FRIEND_API(JSString*) -proxy_FunToString(JSContext* cx, JS::HandleObject proxy, unsigned indent); - -/** - * A class of objects that return source code on demand. - * - * When code is compiled with setSourceIsLazy(true), SpiderMonkey doesn't - * retain the source code (and doesn't do lazy bytecode generation). If we ever - * need the source code, say, in response to a call to Function.prototype. - * toSource or Debugger.Source.prototype.text, then we call the 'load' member - * function of the instance of this class that has hopefully been registered - * with the runtime, passing the code's URL, and hope that it will be able to - * find the source. - */ -class SourceHook { - public: - virtual ~SourceHook() { } - - /** - * Set |*src| and |*length| to refer to the source code for |filename|. - * On success, the caller owns the buffer to which |*src| points, and - * should use JS_free to free it. - */ - virtual bool load(JSContext* cx, const char* filename, char16_t** src, size_t* length) = 0; -}; - -/** - * Have |cx| use |hook| to retrieve lazily-retrieved source code. See the - * comments for SourceHook. The context takes ownership of the hook, and - * will delete it when the context itself is deleted, or when a new hook is - * set. - */ -extern JS_FRIEND_API(void) -SetSourceHook(JSContext* cx, mozilla::UniquePtr hook); - -/** Remove |cx|'s source hook, and return it. The caller now owns the hook. */ -extern JS_FRIEND_API(mozilla::UniquePtr) -ForgetSourceHook(JSContext* cx); - -extern JS_FRIEND_API(JS::Zone*) -GetCompartmentZone(JSCompartment* comp); - -typedef bool -(* PreserveWrapperCallback)(JSContext* cx, JSObject* obj); - -typedef enum { - CollectNurseryBeforeDump, - IgnoreNurseryObjects -} DumpHeapNurseryBehaviour; - - /** - * Dump the complete object graph of heap-allocated things. - * fp is the file for the dump output. - */ -extern JS_FRIEND_API(void) -DumpHeap(JSContext* cx, FILE* fp, DumpHeapNurseryBehaviour nurseryBehaviour); - -#ifdef JS_OLD_GETTER_SETTER_METHODS -JS_FRIEND_API(bool) obj_defineGetter(JSContext* cx, unsigned argc, JS::Value* vp); -JS_FRIEND_API(bool) obj_defineSetter(JSContext* cx, unsigned argc, JS::Value* vp); -#endif - -extern JS_FRIEND_API(bool) -IsSystemCompartment(JSCompartment* comp); - -extern JS_FRIEND_API(bool) -IsSystemZone(JS::Zone* zone); - -extern JS_FRIEND_API(bool) -IsAtomsCompartment(JSCompartment* comp); - -extern JS_FRIEND_API(bool) -IsAtomsZone(JS::Zone* zone); - -struct WeakMapTracer -{ - JSContext* context; - - explicit WeakMapTracer(JSContext* cx) : context(cx) {} - - // Weak map tracer callback, called once for every binding of every - // weak map that was live at the time of the last garbage collection. - // - // m will be nullptr if the weak map is not contained in a JS Object. - // - // The callback should not GC (and will assert in a debug build if it does so.) - virtual void trace(JSObject* m, JS::GCCellPtr key, JS::GCCellPtr value) = 0; -}; - -extern JS_FRIEND_API(void) -TraceWeakMaps(WeakMapTracer* trc); - -extern JS_FRIEND_API(bool) -AreGCGrayBitsValid(JSContext* cx); - -extern JS_FRIEND_API(bool) -ZoneGlobalsAreAllGray(JS::Zone* zone); - -typedef void -(*GCThingCallback)(void* closure, JS::GCCellPtr thing); - -extern JS_FRIEND_API(void) -VisitGrayWrapperTargets(JS::Zone* zone, GCThingCallback callback, void* closure); - -extern JS_FRIEND_API(JSObject*) -GetWeakmapKeyDelegate(JSObject* key); - -/** - * Invoke cellCallback on every gray JSObject in the given zone. - */ -extern JS_FRIEND_API(void) -IterateGrayObjects(JS::Zone* zone, GCThingCallback cellCallback, void* data); - -/** - * Invoke cellCallback on every gray JSObject in the given zone while cycle - * collection is in progress. - */ -extern JS_FRIEND_API(void) -IterateGrayObjectsUnderCC(JS::Zone* zone, GCThingCallback cellCallback, void* data); - -#ifdef JS_HAS_CTYPES -extern JS_FRIEND_API(size_t) -SizeOfDataIfCDataObject(mozilla::MallocSizeOf mallocSizeOf, JSObject* obj); -#endif - -extern JS_FRIEND_API(JSCompartment*) -GetAnyCompartmentInZone(JS::Zone* zone); - -/* - * Shadow declarations of JS internal structures, for access by inline access - * functions below. Do not use these structures in any other way. When adding - * new fields for access by inline methods, make sure to add static asserts to - * the original header file to ensure that offsets are consistent. - */ -namespace shadow { - -struct ObjectGroup { - const Class* clasp; - JSObject* proto; - JSCompartment* compartment; -}; - -struct BaseShape { - const js::Class* clasp_; - JSObject* parent; -}; - -class Shape { -public: - shadow::BaseShape* base; - jsid _1; - uint32_t slotInfo; - - static const uint32_t FIXED_SLOTS_SHIFT = 27; -}; - -/** - * This layout is shared by all native objects. For non-native objects, the - * group may always be accessed safely, and other members may be as well, - * depending on the object's specific layout. - */ -struct Object { - shadow::ObjectGroup* group; - shadow::Shape* shape; - JS::Value* slots; - void* _1; - - size_t numFixedSlots() const { return shape->slotInfo >> Shape::FIXED_SLOTS_SHIFT; } - JS::Value* fixedSlots() const { - return (JS::Value*)(uintptr_t(this) + sizeof(shadow::Object)); - } - - JS::Value& slotRef(size_t slot) const { - size_t nfixed = numFixedSlots(); - if (slot < nfixed) - return fixedSlots()[slot]; - return slots[slot - nfixed]; - } -}; - -struct Function { - Object base; - uint16_t nargs; - uint16_t flags; - /* Used only for natives */ - JSNative native; - const JSJitInfo* jitinfo; - void* _1; -}; - -struct String -{ - static const uint32_t INLINE_CHARS_BIT = JS_BIT(2); - static const uint32_t LATIN1_CHARS_BIT = JS_BIT(6); - static const uint32_t ROPE_FLAGS = 0; - static const uint32_t TYPE_FLAGS_MASK = JS_BIT(6) - 1; - uint32_t flags; - uint32_t length; - union { - const JS::Latin1Char* nonInlineCharsLatin1; - const char16_t* nonInlineCharsTwoByte; - JS::Latin1Char inlineStorageLatin1[1]; - char16_t inlineStorageTwoByte[1]; - }; -}; - -} /* namespace shadow */ - -// This is equal to |&JSObject::class_|. Use it in places where you don't want -// to #include jsobj.h. -extern JS_FRIEND_DATA(const js::Class* const) ObjectClassPtr; - -inline const js::Class* -GetObjectClass(const JSObject* obj) -{ - return reinterpret_cast(obj)->group->clasp; -} - -inline const JSClass* -GetObjectJSClass(JSObject* obj) -{ - return js::Jsvalify(GetObjectClass(obj)); -} - -JS_FRIEND_API(const Class*) -ProtoKeyToClass(JSProtoKey key); - -// Returns the key for the class inherited by a given standard class (that -// is to say, the prototype of this standard class's prototype). -// -// You must be sure that this corresponds to a standard class with a cached -// JSProtoKey before calling this function. In general |key| will match the -// cached proto key, except in cases where multiple JSProtoKeys share a -// JSClass. -inline JSProtoKey -InheritanceProtoKeyForStandardClass(JSProtoKey key) -{ - // [Object] has nothing to inherit from. - if (key == JSProto_Object) - return JSProto_Null; - - // If we're ClassSpec defined return the proto key from that - if (ProtoKeyToClass(key)->specDefined()) - return ProtoKeyToClass(key)->specInheritanceProtoKey(); - - // Otherwise, we inherit [Object]. - return JSProto_Object; -} - -JS_FRIEND_API(bool) -IsFunctionObject(JSObject* obj); - -static MOZ_ALWAYS_INLINE JSCompartment* -GetObjectCompartment(JSObject* obj) -{ - return reinterpret_cast(obj)->group->compartment; -} - -JS_FRIEND_API(JSObject*) -GetGlobalForObjectCrossCompartment(JSObject* obj); - -JS_FRIEND_API(JSObject*) -GetPrototypeNoProxy(JSObject* obj); - -JS_FRIEND_API(void) -AssertSameCompartment(JSContext* cx, JSObject* obj); - -#ifdef JS_DEBUG -JS_FRIEND_API(void) -AssertSameCompartment(JSObject* objA, JSObject* objB); -#else -inline void AssertSameCompartment(JSObject* objA, JSObject* objB) {} -#endif - -JS_FRIEND_API(void) -NotifyAnimationActivity(JSObject* obj); - -/** - * Return the outermost enclosing function (script) of the scripted caller. - * This function returns nullptr in several cases: - * - no script is running on the context - * - the caller is in global or eval code - * In particular, this function will "stop" its outermost search at eval() and - * thus it will really return the outermost enclosing function *since the - * innermost eval*. - */ -JS_FRIEND_API(JSFunction*) -GetOutermostEnclosingFunctionOfScriptedCaller(JSContext* cx); - -JS_FRIEND_API(JSFunction*) -DefineFunctionWithReserved(JSContext* cx, JSObject* obj, const char* name, JSNative call, - unsigned nargs, unsigned attrs); - -JS_FRIEND_API(JSFunction*) -NewFunctionWithReserved(JSContext* cx, JSNative call, unsigned nargs, unsigned flags, - const char* name); - -JS_FRIEND_API(JSFunction*) -NewFunctionByIdWithReserved(JSContext* cx, JSNative native, unsigned nargs, unsigned flags, - jsid id); - -JS_FRIEND_API(const JS::Value&) -GetFunctionNativeReserved(JSObject* fun, size_t which); - -JS_FRIEND_API(void) -SetFunctionNativeReserved(JSObject* fun, size_t which, const JS::Value& val); - -JS_FRIEND_API(bool) -FunctionHasNativeReserved(JSObject* fun); - -JS_FRIEND_API(bool) -GetObjectProto(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject proto); - -extern JS_FRIEND_API(JSObject*) -GetStaticPrototype(JSObject* obj); - -JS_FRIEND_API(bool) -GetOriginalEval(JSContext* cx, JS::HandleObject scope, - JS::MutableHandleObject eval); - -inline void* -GetObjectPrivate(JSObject* obj) -{ - MOZ_ASSERT(GetObjectClass(obj)->flags & JSCLASS_HAS_PRIVATE); - const shadow::Object* nobj = reinterpret_cast(obj); - void** addr = reinterpret_cast(&nobj->fixedSlots()[nobj->numFixedSlots()]); - return *addr; -} - -inline const JS::Value& -GetReservedSlot(JSObject* obj, size_t slot) -{ - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); - return reinterpret_cast(obj)->slotRef(slot); -} - -JS_FRIEND_API(void) -SetReservedOrProxyPrivateSlotWithBarrier(JSObject* obj, size_t slot, const JS::Value& value); - -inline void -SetReservedSlot(JSObject* obj, size_t slot, const JS::Value& value) -{ - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); - shadow::Object* sobj = reinterpret_cast(obj); - if (sobj->slotRef(slot).isMarkable() || value.isMarkable()) - SetReservedOrProxyPrivateSlotWithBarrier(obj, slot, value); - else - sobj->slotRef(slot) = value; -} - -JS_FRIEND_API(uint32_t) -GetObjectSlotSpan(JSObject* obj); - -inline const JS::Value& -GetObjectSlot(JSObject* obj, size_t slot) -{ - MOZ_ASSERT(slot < GetObjectSlotSpan(obj)); - return reinterpret_cast(obj)->slotRef(slot); -} - -MOZ_ALWAYS_INLINE size_t -GetAtomLength(JSAtom* atom) -{ - return reinterpret_cast(atom)->length; -} - -static const uint32_t MaxStringLength = (1 << 28) - 1; - -MOZ_ALWAYS_INLINE size_t -GetStringLength(JSString* s) -{ - return reinterpret_cast(s)->length; -} - -MOZ_ALWAYS_INLINE size_t -GetFlatStringLength(JSFlatString* s) -{ - return reinterpret_cast(s)->length; -} - -MOZ_ALWAYS_INLINE size_t -GetLinearStringLength(JSLinearString* s) -{ - return reinterpret_cast(s)->length; -} - -MOZ_ALWAYS_INLINE bool -LinearStringHasLatin1Chars(JSLinearString* s) -{ - return reinterpret_cast(s)->flags & shadow::String::LATIN1_CHARS_BIT; -} - -MOZ_ALWAYS_INLINE bool -AtomHasLatin1Chars(JSAtom* atom) -{ - return reinterpret_cast(atom)->flags & shadow::String::LATIN1_CHARS_BIT; -} - -MOZ_ALWAYS_INLINE bool -StringHasLatin1Chars(JSString* s) -{ - return reinterpret_cast(s)->flags & shadow::String::LATIN1_CHARS_BIT; -} - -MOZ_ALWAYS_INLINE const JS::Latin1Char* -GetLatin1LinearStringChars(const JS::AutoCheckCannotGC& nogc, JSLinearString* linear) -{ - MOZ_ASSERT(LinearStringHasLatin1Chars(linear)); - - using shadow::String; - String* s = reinterpret_cast(linear); - if (s->flags & String::INLINE_CHARS_BIT) - return s->inlineStorageLatin1; - return s->nonInlineCharsLatin1; -} - -MOZ_ALWAYS_INLINE const char16_t* -GetTwoByteLinearStringChars(const JS::AutoCheckCannotGC& nogc, JSLinearString* linear) -{ - MOZ_ASSERT(!LinearStringHasLatin1Chars(linear)); - - using shadow::String; - String* s = reinterpret_cast(linear); - if (s->flags & String::INLINE_CHARS_BIT) - return s->inlineStorageTwoByte; - return s->nonInlineCharsTwoByte; -} - -MOZ_ALWAYS_INLINE JSLinearString* -AtomToLinearString(JSAtom* atom) -{ - return reinterpret_cast(atom); -} - -MOZ_ALWAYS_INLINE JSFlatString* -AtomToFlatString(JSAtom* atom) -{ - return reinterpret_cast(atom); -} - -MOZ_ALWAYS_INLINE JSLinearString* -FlatStringToLinearString(JSFlatString* s) -{ - return reinterpret_cast(s); -} - -MOZ_ALWAYS_INLINE const JS::Latin1Char* -GetLatin1AtomChars(const JS::AutoCheckCannotGC& nogc, JSAtom* atom) -{ - return GetLatin1LinearStringChars(nogc, AtomToLinearString(atom)); -} - -MOZ_ALWAYS_INLINE const char16_t* -GetTwoByteAtomChars(const JS::AutoCheckCannotGC& nogc, JSAtom* atom) -{ - return GetTwoByteLinearStringChars(nogc, AtomToLinearString(atom)); -} - -JS_FRIEND_API(JSLinearString*) -StringToLinearStringSlow(JSContext* cx, JSString* str); - -MOZ_ALWAYS_INLINE JSLinearString* -StringToLinearString(JSContext* cx, JSString* str) -{ - using shadow::String; - String* s = reinterpret_cast(str); - if (MOZ_UNLIKELY((s->flags & String::TYPE_FLAGS_MASK) == String::ROPE_FLAGS)) - return StringToLinearStringSlow(cx, str); - return reinterpret_cast(str); -} - -template -MOZ_ALWAYS_INLINE void -CopyLinearStringChars(CharType* dest, JSLinearString* s, size_t len, size_t start = 0); - -MOZ_ALWAYS_INLINE void -CopyLinearStringChars(char16_t* dest, JSLinearString* s, size_t len, size_t start = 0) -{ - MOZ_ASSERT(start + len <= GetLinearStringLength(s)); - JS::AutoCheckCannotGC nogc; - if (LinearStringHasLatin1Chars(s)) { - const JS::Latin1Char* src = GetLatin1LinearStringChars(nogc, s); - for (size_t i = 0; i < len; i++) - dest[i] = src[start + i]; - } else { - const char16_t* src = GetTwoByteLinearStringChars(nogc, s); - mozilla::PodCopy(dest, src + start, len); - } -} - -MOZ_ALWAYS_INLINE void -CopyLinearStringChars(char* dest, JSLinearString* s, size_t len, size_t start = 0) -{ - MOZ_ASSERT(start + len <= GetLinearStringLength(s)); - JS::AutoCheckCannotGC nogc; - if (LinearStringHasLatin1Chars(s)) { - const JS::Latin1Char* src = GetLatin1LinearStringChars(nogc, s); - for (size_t i = 0; i < len; i++) - dest[i] = char(src[start + i]); - } else { - const char16_t* src = GetTwoByteLinearStringChars(nogc, s); - for (size_t i = 0; i < len; i++) - dest[i] = char(src[start + i]); - } -} - -template -inline bool -CopyStringChars(JSContext* cx, CharType* dest, JSString* s, size_t len, size_t start = 0) -{ - JSLinearString* linear = StringToLinearString(cx, s); - if (!linear) - return false; - - CopyLinearStringChars(dest, linear, len, start); - return true; -} - -inline void -CopyFlatStringChars(char16_t* dest, JSFlatString* s, size_t len) -{ - CopyLinearStringChars(dest, FlatStringToLinearString(s), len); -} - -/** - * Add some or all property keys of obj to the id vector *props. - * - * The flags parameter controls which property keys are added. Pass a - * combination of the following bits: - * - * JSITER_OWNONLY - Don't also search the prototype chain; only consider - * obj's own properties. - * - * JSITER_HIDDEN - Include nonenumerable properties. - * - * JSITER_SYMBOLS - Include property keys that are symbols. The default - * behavior is to filter out symbols. - * - * JSITER_SYMBOLSONLY - Exclude non-symbol property keys. - * - * This is the closest C++ API we have to `Reflect.ownKeys(obj)`, or - * equivalently, the ES6 [[OwnPropertyKeys]] internal method. Pass - * `JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS` as flags to get - * results that match the output of Reflect.ownKeys. - */ -JS_FRIEND_API(bool) -GetPropertyKeys(JSContext* cx, JS::HandleObject obj, unsigned flags, JS::AutoIdVector* props); - -JS_FRIEND_API(bool) -AppendUnique(JSContext* cx, JS::AutoIdVector& base, JS::AutoIdVector& others); - -JS_FRIEND_API(bool) -StringIsArrayIndex(JSLinearString* str, uint32_t* indexp); - -JS_FRIEND_API(void) -SetPreserveWrapperCallback(JSContext* cx, PreserveWrapperCallback callback); - -JS_FRIEND_API(bool) -IsObjectInContextCompartment(JSObject* obj, const JSContext* cx); - -/* - * NB: keep these in sync with the copy in builtin/SelfHostingDefines.h. - * The first three are omitted because they shouldn't be used in new code. - */ -#define JSITER_ENUMERATE 0x1 /* for-in compatible hidden default iterator */ -#define JSITER_FOREACH 0x2 /* get obj[key] for each property */ -#define JSITER_KEYVALUE 0x4 /* obsolete destructuring for-in wants [key, value] */ -#define JSITER_OWNONLY 0x8 /* iterate over obj's own properties only */ -#define JSITER_HIDDEN 0x10 /* also enumerate non-enumerable properties */ -#define JSITER_SYMBOLS 0x20 /* also include symbol property keys */ -#define JSITER_SYMBOLSONLY 0x40 /* exclude string property keys */ - -JS_FRIEND_API(bool) -RunningWithTrustedPrincipals(JSContext* cx); - -inline uintptr_t -GetNativeStackLimit(JSContext* cx, StackKind kind, int extraAllowance = 0) -{ - uintptr_t limit = ContextFriendFields::get(cx)->nativeStackLimit[kind]; -#if JS_STACK_GROWTH_DIRECTION > 0 - limit += extraAllowance; -#else - limit -= extraAllowance; -#endif - return limit; -} - -inline uintptr_t -GetNativeStackLimit(JSContext* cx, int extraAllowance = 0) -{ - StackKind kind = RunningWithTrustedPrincipals(cx) ? StackForTrustedScript - : StackForUntrustedScript; - return GetNativeStackLimit(cx, kind, extraAllowance); -} - -/* - * These macros report a stack overflow and run |onerror| if we are close to - * using up the C stack. The JS_CHECK_CHROME_RECURSION variant gives us a - * little extra space so that we can ensure that crucial code is able to run. - * JS_CHECK_RECURSION_CONSERVATIVE allows less space than any other check, - * including a safety buffer (as in, it uses the untrusted limit and subtracts - * a little more from it). - */ - -#define JS_CHECK_RECURSION_LIMIT(cx, limit, onerror) \ - JS_BEGIN_MACRO \ - int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(limit, &stackDummy_)) { \ - js::ReportOverRecursed(cx); \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_RECURSION(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT(cx, js::GetNativeStackLimit(cx), onerror) - -#define JS_CHECK_RECURSION_LIMIT_DONT_REPORT(cx, limit, onerror) \ - JS_BEGIN_MACRO \ - int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(limit, &stackDummy_)) { \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_RECURSION_DONT_REPORT(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT_DONT_REPORT(cx, js::GetNativeStackLimit(cx), onerror) - -#define JS_CHECK_RECURSION_WITH_SP_DONT_REPORT(cx, sp, onerror) \ - JS_BEGIN_MACRO \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_RECURSION_WITH_SP(cx, sp, onerror) \ - JS_BEGIN_MACRO \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ - js::ReportOverRecursed(cx); \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_SYSTEM_RECURSION(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT(cx, js::GetNativeStackLimit(cx, js::StackForSystemCode), onerror) - -#define JS_CHECK_RECURSION_CONSERVATIVE(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT(cx, \ - js::GetNativeStackLimit(cx, js::StackForUntrustedScript, -1024 * int(sizeof(size_t))), \ - onerror) - -#define JS_CHECK_RECURSION_CONSERVATIVE_DONT_REPORT(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT_DONT_REPORT(cx, \ - js::GetNativeStackLimit(cx, js::StackForUntrustedScript, -1024 * int(sizeof(size_t))), \ - onerror) - -JS_FRIEND_API(void) -StartPCCountProfiling(JSContext* cx); - -JS_FRIEND_API(void) -StopPCCountProfiling(JSContext* cx); - -JS_FRIEND_API(void) -PurgePCCounts(JSContext* cx); - -JS_FRIEND_API(size_t) -GetPCCountScriptCount(JSContext* cx); - -JS_FRIEND_API(JSString*) -GetPCCountScriptSummary(JSContext* cx, size_t script); - -JS_FRIEND_API(JSString*) -GetPCCountScriptContents(JSContext* cx, size_t script); - -/** - * Generate lcov trace file content for the current compartment, and allocate a - * new buffer and return the content in it, the size of the newly allocated - * content within the buffer would be set to the length out-param. - * - * In case of out-of-memory, this function returns nullptr and does not set any - * value to the length out-param. - */ -JS_FRIEND_API(char*) -GetCodeCoverageSummary(JSContext* cx, size_t* length); - -typedef void -(* ActivityCallback)(void* arg, bool active); - -/** - * Sets a callback that is run whenever the runtime goes idle - the - * last active request ceases - and begins activity - when it was - * idle and a request begins. - */ -JS_FRIEND_API(void) -SetActivityCallback(JSContext* cx, ActivityCallback cb, void* arg); - -typedef bool -(* DOMInstanceClassHasProtoAtDepth)(const Class* instanceClass, - uint32_t protoID, uint32_t depth); -struct JSDOMCallbacks { - DOMInstanceClassHasProtoAtDepth instanceClassMatchesProto; -}; -typedef struct JSDOMCallbacks DOMCallbacks; - -extern JS_FRIEND_API(void) -SetDOMCallbacks(JSContext* cx, const DOMCallbacks* callbacks); - -extern JS_FRIEND_API(const DOMCallbacks*) -GetDOMCallbacks(JSContext* cx); - -extern JS_FRIEND_API(JSObject*) -GetTestingFunctions(JSContext* cx); - -/** - * Helper to convert FreeOp to JSFreeOp when the definition of FreeOp is not - * available and the compiler does not know that FreeOp inherits from - * JSFreeOp. - */ -inline JSFreeOp* -CastToJSFreeOp(FreeOp* fop) -{ - return reinterpret_cast(fop); -} - -/* Implemented in jsexn.cpp. */ - -/** - * Get an error type name from a JSExnType constant. - * Returns nullptr for invalid arguments and JSEXN_INTERNALERR - */ -extern JS_FRIEND_API(JSFlatString*) -GetErrorTypeName(JSContext* cx, int16_t exnType); - -#ifdef JS_DEBUG -extern JS_FRIEND_API(unsigned) -GetEnterCompartmentDepth(JSContext* cx); -#endif - -class RegExpGuard; -extern JS_FRIEND_API(bool) -RegExpToSharedNonInline(JSContext* cx, JS::HandleObject regexp, RegExpGuard* shared); - -/* Implemented in jswrapper.cpp. */ -typedef enum NukeReferencesToWindow { - NukeWindowReferences, - DontNukeWindowReferences -} NukeReferencesToWindow; - -/* - * These filters are designed to be ephemeral stack classes, and thus don't - * do any rooting or holding of their members. - */ -struct CompartmentFilter { - virtual bool match(JSCompartment* c) const = 0; -}; - -struct AllCompartments : public CompartmentFilter { - virtual bool match(JSCompartment* c) const override { return true; } -}; - -struct ContentCompartmentsOnly : public CompartmentFilter { - virtual bool match(JSCompartment* c) const override { - return !IsSystemCompartment(c); - } -}; - -struct ChromeCompartmentsOnly : public CompartmentFilter { - virtual bool match(JSCompartment* c) const override { - return IsSystemCompartment(c); - } -}; - -struct SingleCompartment : public CompartmentFilter { - JSCompartment* ours; - explicit SingleCompartment(JSCompartment* c) : ours(c) {} - virtual bool match(JSCompartment* c) const override { return c == ours; } -}; - -struct CompartmentsWithPrincipals : public CompartmentFilter { - JSPrincipals* principals; - explicit CompartmentsWithPrincipals(JSPrincipals* p) : principals(p) {} - virtual bool match(JSCompartment* c) const override { - return JS_GetCompartmentPrincipals(c) == principals; - } -}; - -extern JS_FRIEND_API(bool) -NukeCrossCompartmentWrappers(JSContext* cx, - const CompartmentFilter& sourceFilter, - const CompartmentFilter& targetFilter, - NukeReferencesToWindow nukeReferencesToWindow); - -/* Specify information about DOMProxy proxies in the DOM, for use by ICs. */ - -/* - * The DOMProxyShadowsCheck function will be called to check if the property for - * id should be gotten from the prototype, or if there is an own property that - * shadows it. - * * If ShadowsViaDirectExpando is returned, then the slot at - * listBaseExpandoSlot contains an expando object which has the property in - * question. - * * If ShadowsViaIndirectExpando is returned, then the slot at - * listBaseExpandoSlot contains a private pointer to an ExpandoAndGeneration - * and the expando object in the ExpandoAndGeneration has the property in - * question. - * * If DoesntShadow is returned then the slot at listBaseExpandoSlot should - * either be undefined or point to an expando object that would contain the - * own property. - * * If DoesntShadowUnique is returned then the slot at listBaseExpandoSlot - * should contain a private pointer to a ExpandoAndGeneration, which contains - * a JS::Value that should either be undefined or point to an expando object, - * and a uint64 value. If that value changes then the IC for getting a - * property will be invalidated. - * * If Shadows is returned, that means the property is an own property of the - * proxy but doesn't live on the expando object. - */ - -struct ExpandoAndGeneration { - ExpandoAndGeneration() - : expando(JS::UndefinedValue()), - generation(0) - {} - - void OwnerUnlinked() - { - ++generation; - } - - static size_t offsetOfExpando() - { - return offsetof(ExpandoAndGeneration, expando); - } - - static size_t offsetOfGeneration() - { - return offsetof(ExpandoAndGeneration, generation); - } - - JS::Heap expando; - uint64_t generation; -}; - -typedef enum DOMProxyShadowsResult { - ShadowCheckFailed, - Shadows, - DoesntShadow, - DoesntShadowUnique, - ShadowsViaDirectExpando, - ShadowsViaIndirectExpando -} DOMProxyShadowsResult; -typedef DOMProxyShadowsResult -(* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); -JS_FRIEND_API(void) -SetDOMProxyInformation(const void* domProxyHandlerFamily, uint32_t domProxyExpandoSlot, - DOMProxyShadowsCheck domProxyShadowsCheck); - -const void* GetDOMProxyHandlerFamily(); -uint32_t GetDOMProxyExpandoSlot(); -DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); -inline bool DOMProxyIsShadowing(DOMProxyShadowsResult result) { - return result == Shadows || - result == ShadowsViaDirectExpando || - result == ShadowsViaIndirectExpando; -} - -/* Implemented in jsdate.cpp. */ - -/** Detect whether the internal date value is NaN. */ -extern JS_FRIEND_API(bool) -DateIsValid(JSContext* cx, JS::HandleObject obj, bool* isValid); - -extern JS_FRIEND_API(bool) -DateGetMsecSinceEpoch(JSContext* cx, JS::HandleObject obj, double* msecSinceEpoch); - -} /* namespace js */ - -/* Implemented in jscntxt.cpp. */ - -/** - * Report an exception, which is currently realized as a printf-style format - * string and its arguments. - */ -typedef enum JSErrNum { -#define MSG_DEF(name, count, exception, format) \ - name, -#include "js.msg" -#undef MSG_DEF - JSErr_Limit -} JSErrNum; - -namespace js { - -extern JS_FRIEND_API(const JSErrorFormatString*) -GetErrorMessage(void* userRef, const unsigned errorNumber); - -// AutoStableStringChars is here so we can use it in ErrorReport. It -// should get moved out of here if we can manage it. See bug 1040316. - -/** - * This class provides safe access to a string's chars across a GC. Once - * we allocate strings and chars in the nursery (bug 903519), this class - * will have to make a copy of the string's chars if they are allocated - * in the nursery, so it's best to avoid using this class unless you really - * need it. It's usually more efficient to use the latin1Chars/twoByteChars - * JSString methods and often the code can be rewritten so that only indexes - * instead of char pointers are used in parts of the code that can GC. - */ -class MOZ_STACK_CLASS AutoStableStringChars -{ - /* - * When copying string char, use this many bytes of inline storage. This is - * chosen to allow the inline string types to be copied without allocating. - * This is asserted in AutoStableStringChars::allocOwnChars. - */ - static const size_t InlineCapacity = 24; - - /* Ensure the string is kept alive while we're using its chars. */ - JS::RootedString s_; - union { - const char16_t* twoByteChars_; - const JS::Latin1Char* latin1Chars_; - }; - mozilla::Maybe> ownChars_; - enum State { Uninitialized, Latin1, TwoByte }; - State state_; - - public: - explicit AutoStableStringChars(JSContext* cx) - : s_(cx), state_(Uninitialized) - {} - - MOZ_MUST_USE - bool init(JSContext* cx, JSString* s); - - /* Like init(), but Latin1 chars are inflated to TwoByte. */ - MOZ_MUST_USE - bool initTwoByte(JSContext* cx, JSString* s); - - bool isLatin1() const { return state_ == Latin1; } - bool isTwoByte() const { return state_ == TwoByte; } - - const char16_t* twoByteChars() const { - MOZ_ASSERT(state_ == TwoByte); - return twoByteChars_; - } - - mozilla::Range latin1Range() const { - MOZ_ASSERT(state_ == Latin1); - return mozilla::Range(latin1Chars_, - GetStringLength(s_)); - } - - mozilla::Range twoByteRange() const { - MOZ_ASSERT(state_ == TwoByte); - return mozilla::Range(twoByteChars_, - GetStringLength(s_)); - } - - /* If we own the chars, transfer ownership to the caller. */ - bool maybeGiveOwnershipToCaller() { - MOZ_ASSERT(state_ != Uninitialized); - if (!ownChars_.isSome() || !ownChars_->extractRawBuffer()) - return false; - state_ = Uninitialized; - ownChars_.reset(); - return true; - } - - private: - AutoStableStringChars(const AutoStableStringChars& other) = delete; - void operator=(const AutoStableStringChars& other) = delete; - - bool baseIsInline(JS::Handle linearString); - template T* allocOwnChars(JSContext* cx, size_t count); - bool copyLatin1Chars(JSContext* cx, JS::Handle linearString); - bool copyTwoByteChars(JSContext* cx, JS::Handle linearString); - bool copyAndInflateLatin1Chars(JSContext*, JS::Handle linearString); -}; - -struct MOZ_STACK_CLASS JS_FRIEND_API(ErrorReport) -{ - explicit ErrorReport(JSContext* cx); - ~ErrorReport(); - - enum SniffingBehavior { - WithSideEffects, - NoSideEffects - }; - - /** - * Generate a JSErrorReport from the provided thrown value. - * - * If the value is a (possibly wrapped) Error object, the JSErrorReport will - * be exactly initialized from the Error object's information, without - * observable side effects. (The Error object's JSErrorReport is reused, if - * it has one.) - * - * Otherwise various attempts are made to derive JSErrorReport information - * from |exn| and from the current execution state. This process is - * *definitely* inconsistent with any standard, and particulars of the - * behavior implemented here generally shouldn't be relied upon. - * - * If the value of |sniffingBehavior| is |WithSideEffects|, some of these - * attempts *may* invoke user-configurable behavior when |exn| is an object: - * converting |exn| to a string, detecting and getting properties on |exn|, - * accessing |exn|'s prototype chain, and others are possible. Users *must* - * tolerate |ErrorReport::init| potentially having arbitrary effects. Any - * exceptions thrown by these operations will be caught and silently - * ignored, and "default" values will be substituted into the JSErrorReport. - * - * But if the value of |sniffingBehavior| is |NoSideEffects|, these attempts - * *will not* invoke any observable side effects. The JSErrorReport will - * simply contain fewer, less precise details. - * - * Unlike some functions involved in error handling, this function adheres - * to the usual JSAPI return value error behavior. - */ - bool init(JSContext* cx, JS::HandleValue exn, - SniffingBehavior sniffingBehavior); - - JSErrorReport* report() - { - return reportp; - } - - const JS::ConstUTF8CharsZ toStringResult() - { - return toStringResult_; - } - - private: - // More or less an equivalent of JS_ReportErrorNumber/js::ReportErrorNumberVA - // but fills in an ErrorReport instead of reporting it. Uses varargs to - // make it simpler to call js::ExpandErrorArgumentsVA. - // - // Returns false if we fail to actually populate the ErrorReport - // for some reason (probably out of memory). - bool populateUncaughtExceptionReportUTF8(JSContext* cx, ...); - bool populateUncaughtExceptionReportUTF8VA(JSContext* cx, va_list ap); - - // Reports exceptions from add-on scopes to telementry. - void ReportAddonExceptionToTelementry(JSContext* cx); - - // We may have a provided JSErrorReport, so need a way to represent that. - JSErrorReport* reportp; - - // Or we may need to synthesize a JSErrorReport one of our own. - JSErrorReport ownedReport; - - // And we have a string to maybe keep alive that has pointers into - // it from ownedReport. - JS::RootedString str; - - // And keep its chars alive too. - AutoStableStringChars strChars; - - // And we need to root our exception value. - JS::RootedObject exnObject; - - // And for our filename. - JSAutoByteString filename; - - // We may have a result of error.toString(). - // FIXME: We should not call error.toString(), since it could have side - // effect (see bug 633623). - JS::ConstUTF8CharsZ toStringResult_; - JSAutoByteString toStringResultBytesStorage; -}; - -/* Implemented in vm/StructuredClone.cpp. */ -extern JS_FRIEND_API(uint64_t) -GetSCOffset(JSStructuredCloneWriter* writer); - -namespace Scalar { - -/** - * Scalar types that can appear in typed arrays and typed objects. The enum - * values must to be kept in sync with the JS_SCALARTYPEREPR_ constants, as - * well as the TypedArrayObject::classes and TypedArrayObject::protoClasses - * definitions. - */ -enum Type { - Int8 = 0, - Uint8, - Int16, - Uint16, - Int32, - Uint32, - Float32, - Float64, - - /** - * Special type that is a uint8_t, but assignments are clamped to [0, 256). - * Treat the raw data type as a uint8_t. - */ - Uint8Clamped, - - /** - * Types that don't have their own TypedArray equivalent, for now. - */ - MaxTypedArrayViewType, - - Int64, - Float32x4, - Int8x16, - Int16x8, - Int32x4 -}; - -static inline size_t -byteSize(Type atype) -{ - switch (atype) { - case Int8: - case Uint8: - case Uint8Clamped: - return 1; - case Int16: - case Uint16: - return 2; - case Int32: - case Uint32: - case Float32: - return 4; - case Int64: - case Float64: - return 8; - case Int8x16: - case Int16x8: - case Int32x4: - case Float32x4: - return 16; - default: - MOZ_CRASH("invalid scalar type"); - } -} - -static inline bool -isSignedIntType(Type atype) { - switch (atype) { - case Int8: - case Int16: - case Int32: - case Int64: - case Int8x16: - case Int16x8: - case Int32x4: - return true; - case Uint8: - case Uint8Clamped: - case Uint16: - case Uint32: - case Float32: - case Float64: - case Float32x4: - return false; - default: - MOZ_CRASH("invalid scalar type"); - } -} - -static inline bool -isSimdType(Type atype) { - switch (atype) { - case Int8: - case Uint8: - case Uint8Clamped: - case Int16: - case Uint16: - case Int32: - case Uint32: - case Int64: - case Float32: - case Float64: - return false; - case Int8x16: - case Int16x8: - case Int32x4: - case Float32x4: - return true; - case MaxTypedArrayViewType: - break; - } - MOZ_CRASH("invalid scalar type"); -} - -static inline size_t -scalarByteSize(Type atype) { - switch (atype) { - case Int8x16: - return 1; - case Int16x8: - return 2; - case Int32x4: - case Float32x4: - return 4; - case Int8: - case Uint8: - case Uint8Clamped: - case Int16: - case Uint16: - case Int32: - case Uint32: - case Int64: - case Float32: - case Float64: - case MaxTypedArrayViewType: - break; - } - MOZ_CRASH("invalid simd type"); -} - -} /* namespace Scalar */ -} /* namespace js */ - -/* - * Create a new typed array with nelements elements. - * - * These functions (except the WithBuffer variants) fill in the array with zeros. - */ - -extern JS_FRIEND_API(JSObject*) -JS_NewInt8Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ClampedArray(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewInt16Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint16Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewInt32Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint32Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat32Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat64Array(JSContext* cx, uint32_t nelements); - -/* - * Create a new typed array and copy in values from the given object. The - * object is used as if it were an array; that is, the new array (if - * successfully created) will have length given by array.length, and its - * elements will be those specified by array[0], array[1], and so on, after - * conversion to the typed array element type. - */ - -extern JS_FRIEND_API(JSObject*) -JS_NewInt8ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ClampedArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewInt16ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint16ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewInt32ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint32ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat32ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat64ArrayFromArray(JSContext* cx, JS::HandleObject array); - -/* - * Create a new typed array using the given ArrayBuffer or - * SharedArrayBuffer for storage. The length value is optional; if -1 - * is passed, enough elements to use up the remainder of the byte - * array is used as the default value. - */ - -extern JS_FRIEND_API(JSObject*) -JS_NewInt8ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ClampedArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewInt16ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint16ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewInt32ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint32ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat32ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat64ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); - -/** - * Create a new SharedArrayBuffer with the given byte length. This - * may only be called if - * JS::CompartmentCreationOptionsRef(cx).getSharedMemoryAndAtomicsEnabled() is - * true. - */ -extern JS_FRIEND_API(JSObject*) -JS_NewSharedArrayBuffer(JSContext* cx, uint32_t nbytes); - -/** - * Create a new ArrayBuffer with the given byte length. - */ -extern JS_FRIEND_API(JSObject*) -JS_NewArrayBuffer(JSContext* cx, uint32_t nbytes); - -/** - * Check whether obj supports JS_GetTypedArray* APIs. Note that this may return - * false if a security wrapper is encountered that denies the unwrapping. If - * this test or one of the JS_Is*Array tests succeeds, then it is safe to call - * the various accessor JSAPI calls defined below. - */ -extern JS_FRIEND_API(bool) -JS_IsTypedArrayObject(JSObject* obj); - -/** - * Check whether obj supports JS_GetArrayBufferView* APIs. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. If this test or one of the more specific tests succeeds, then it - * is safe to call the various ArrayBufferView accessor JSAPI calls defined - * below. - */ -extern JS_FRIEND_API(bool) -JS_IsArrayBufferViewObject(JSObject* obj); - -/* - * Test for specific typed array types (ArrayBufferView subtypes) - */ - -extern JS_FRIEND_API(bool) -JS_IsInt8Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint8Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint8ClampedArray(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsInt16Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint16Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsInt32Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint32Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsFloat32Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsFloat64Array(JSObject* obj); - -/** - * Return the isShared flag of a typed array, which denotes whether - * the underlying buffer is a SharedArrayBuffer. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(bool) -JS_GetTypedArraySharedness(JSObject* obj); - -/* - * Test for specific typed array types (ArrayBufferView subtypes) and return - * the unwrapped object if so, else nullptr. Never throws. - */ - -namespace js { - -extern JS_FRIEND_API(JSObject*) -UnwrapInt8Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint8Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint8ClampedArray(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapInt16Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint16Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapInt32Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint32Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapFloat32Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapFloat64Array(JSObject* obj); - -extern JS_FRIEND_API(JSObject*) -UnwrapArrayBuffer(JSObject* obj); - -extern JS_FRIEND_API(JSObject*) -UnwrapArrayBufferView(JSObject* obj); - -extern JS_FRIEND_API(JSObject*) -UnwrapSharedArrayBuffer(JSObject* obj); - - -namespace detail { - -extern JS_FRIEND_DATA(const Class* const) Int8ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint8ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint8ClampedArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Int16ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint16ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Int32ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint32ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Float32ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Float64ArrayClassPtr; - -const size_t TypedArrayLengthSlot = 1; - -} // namespace detail - -#define JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Type, type) \ -inline void \ -Get ## Type ## ArrayLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, type** data) \ -{ \ - MOZ_ASSERT(GetObjectClass(obj) == detail::Type ## ArrayClassPtr); \ - const JS::Value& lenSlot = GetReservedSlot(obj, detail::TypedArrayLengthSlot); \ - *length = mozilla::AssertedCast(lenSlot.toInt32()); \ - *isSharedMemory = JS_GetTypedArraySharedness(obj); \ - *data = static_cast(GetObjectPrivate(obj)); \ -} - -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Int8, int8_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint8, uint8_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint8Clamped, uint8_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Int16, int16_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint16, uint16_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Int32, int32_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint32, uint32_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Float32, float) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Float64, double) - -#undef JS_DEFINE_DATA_AND_LENGTH_ACCESSOR - -// This one isn't inlined because it's rather tricky (by dint of having to deal -// with a dozen-plus classes and varying slot layouts. -extern JS_FRIEND_API(void) -GetArrayBufferViewLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -// This one isn't inlined because there are a bunch of different ArrayBuffer -// classes that would have to be individually handled here. -// -// There is an isShared out argument for API consistency (eases use from DOM). -// It will always be set to false. -extern JS_FRIEND_API(void) -GetArrayBufferLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -// Ditto for SharedArrayBuffer. -// -// There is an isShared out argument for API consistency (eases use from DOM). -// It will always be set to true. -extern JS_FRIEND_API(void) -GetSharedArrayBufferLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -} // namespace js - -JS_FRIEND_API(uint8_t*) -JS_GetSharedArrayBufferData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/* - * Unwrap Typed arrays all at once. Return nullptr without throwing if the - * object cannot be viewed as the correct typed array, or the typed array - * object on success, filling both outparameters. - */ -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsInt8Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, int8_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint8Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint8ClampedArray(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsInt16Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, int16_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint16Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint16_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsInt32Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, int32_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint32Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint32_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsFloat32Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, float** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsFloat64Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, double** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsArrayBufferView(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -/* - * Unwrap an ArrayBuffer, return nullptr if it's a different type. - */ -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsArrayBuffer(JSObject* obj, uint32_t* length, uint8_t** data); - -/* - * Get the type of elements in a typed array, or MaxTypedArrayViewType if a DataView. - * - * |obj| must have passed a JS_IsArrayBufferView/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is an ArrayBufferView or a - * wrapper of an ArrayBufferView, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(js::Scalar::Type) -JS_GetArrayBufferViewType(JSObject* obj); - -extern JS_FRIEND_API(js::Scalar::Type) -JS_GetSharedArrayBufferViewType(JSObject* obj); - -/* - * Check whether obj supports the JS_GetArrayBuffer* APIs. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. If this test succeeds, then it is safe to call the various - * accessor JSAPI calls defined below. - */ -extern JS_FRIEND_API(bool) -JS_IsArrayBufferObject(JSObject* obj); - -extern JS_FRIEND_API(bool) -JS_IsSharedArrayBufferObject(JSObject* obj); - -/** - * Return the available byte length of an array buffer. - * - * |obj| must have passed a JS_IsArrayBufferObject test, or somehow be known - * that it would pass such a test: it is an ArrayBuffer or a wrapper of an - * ArrayBuffer, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetArrayBufferByteLength(JSObject* obj); - -extern JS_FRIEND_API(uint32_t) -JS_GetSharedArrayBufferByteLength(JSObject* obj); - -/** - * Return true if the arrayBuffer contains any data. This will return false for - * ArrayBuffer.prototype and detached ArrayBuffers. - * - * |obj| must have passed a JS_IsArrayBufferObject test, or somehow be known - * that it would pass such a test: it is an ArrayBuffer or a wrapper of an - * ArrayBuffer, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(bool) -JS_ArrayBufferHasData(JSObject* obj); - -/** - * Return a pointer to the start of the data referenced by a typed array. The - * data is still owned by the typed array, and should not be modified on - * another thread. Furthermore, the pointer can become invalid on GC (if the - * data is small and fits inside the array's GC header), so callers must take - * care not to hold on across anything that could GC. - * - * |obj| must have passed a JS_IsArrayBufferObject test, or somehow be known - * that it would pass such a test: it is an ArrayBuffer or a wrapper of an - * ArrayBuffer, and the unwrapping will succeed. - * - * *isSharedMemory will be set to false, the argument is present to simplify - * its use from code that also interacts with SharedArrayBuffer. - */ -extern JS_FRIEND_API(uint8_t*) -JS_GetArrayBufferData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/** - * Check whether the obj is ArrayBufferObject and memory mapped. Note that this - * may return false if a security wrapper is encountered that denies the - * unwrapping. - */ -extern JS_FRIEND_API(bool) -JS_IsMappedArrayBufferObject(JSObject* obj); - -/** - * Return the number of elements in a typed array. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetTypedArrayLength(JSObject* obj); - -/** - * Return the byte offset from the start of an array buffer to the start of a - * typed array view. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetTypedArrayByteOffset(JSObject* obj); - -/** - * Return the byte length of a typed array. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetTypedArrayByteLength(JSObject* obj); - -/** - * Check whether obj supports JS_ArrayBufferView* APIs. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. - */ -extern JS_FRIEND_API(bool) -JS_IsArrayBufferViewObject(JSObject* obj); - -/** - * More generic name for JS_GetTypedArrayByteLength to cover DataViews as well - */ -extern JS_FRIEND_API(uint32_t) -JS_GetArrayBufferViewByteLength(JSObject* obj); - -/* - * Return a pointer to the start of the data referenced by a typed array. The - * data is still owned by the typed array, and should not be modified on - * another thread. Furthermore, the pointer can become invalid on GC (if the - * data is small and fits inside the array's GC header), so callers must take - * care not to hold on across anything that could GC. - * - * |obj| must have passed a JS_Is*Array test, or somehow be known that it would - * pass such a test: it is a typed array or a wrapper of a typed array, and the - * unwrapping will succeed. - * - * *isSharedMemory will be set to true if the typed array maps a - * SharedArrayBuffer, otherwise to false. - */ - -extern JS_FRIEND_API(int8_t*) -JS_GetInt8ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint8_t*) -JS_GetUint8ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint8_t*) -JS_GetUint8ClampedArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(int16_t*) -JS_GetInt16ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint16_t*) -JS_GetUint16ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(int32_t*) -JS_GetInt32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint32_t*) -JS_GetUint32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(float*) -JS_GetFloat32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(double*) -JS_GetFloat64ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/** - * Same as above, but for any kind of ArrayBufferView. Prefer the type-specific - * versions when possible. - */ -extern JS_FRIEND_API(void*) -JS_GetArrayBufferViewData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/** - * Return the ArrayBuffer or SharedArrayBuffer underlying an ArrayBufferView. - * This may return a detached buffer. |obj| must be an object that would - * return true for JS_IsArrayBufferViewObject(). - */ -extern JS_FRIEND_API(JSObject*) -JS_GetArrayBufferViewBuffer(JSContext* cx, JS::HandleObject obj, bool* isSharedMemory); - -/** - * Detach an ArrayBuffer, causing all associated views to no longer refer to - * the ArrayBuffer's original attached memory. - * - * The |changeData| argument is obsolete and ignored. - */ -extern JS_FRIEND_API(bool) -JS_DetachArrayBuffer(JSContext* cx, JS::HandleObject obj); - -/** - * Check whether the obj is a detached ArrayBufferObject. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. - */ -extern JS_FRIEND_API(bool) -JS_IsDetachedArrayBufferObject(JSObject* obj); - -/** - * Check whether obj supports JS_GetDataView* APIs. - */ -JS_FRIEND_API(bool) -JS_IsDataViewObject(JSObject* obj); - -/** - * Create a new DataView using the given ArrayBuffer for storage. The given - * buffer must be an ArrayBuffer (or a cross-compartment wrapper of an - * ArrayBuffer), and the offset and length must fit within the bounds of the - * arrayBuffer. Currently, nullptr will be returned and an exception will be - * thrown if these conditions do not hold, but do not depend on that behavior. - */ -JS_FRIEND_API(JSObject*) -JS_NewDataView(JSContext* cx, JS::HandleObject arrayBuffer, uint32_t byteOffset, int32_t byteLength); - -/** - * Return the byte offset of a data view into its array buffer. |obj| must be a - * DataView. - * - * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that - * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. - */ -JS_FRIEND_API(uint32_t) -JS_GetDataViewByteOffset(JSObject* obj); - -/** - * Return the byte length of a data view. - * - * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that - * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be - * unable to assert when unwrapping should be disallowed. - */ -JS_FRIEND_API(uint32_t) -JS_GetDataViewByteLength(JSObject* obj); - -/** - * Return a pointer to the beginning of the data referenced by a DataView. - * - * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that - * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be - * unable to assert when unwrapping should be disallowed. - */ -JS_FRIEND_API(void*) -JS_GetDataViewData(JSObject* obj, const JS::AutoCheckCannotGC&); - -namespace js { - -/** - * Add a watchpoint -- in the Object.prototype.watch sense -- to |obj| for the - * property |id|, using the callable object |callable| as the function to be - * called for notifications. - * - * This is an internal function exposed -- temporarily -- only so that DOM - * proxies can be watchable. Don't use it! We'll soon kill off the - * Object.prototype.{,un}watch functions, at which point this will go too. - */ -extern JS_FRIEND_API(bool) -WatchGuts(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); - -/** - * Remove a watchpoint -- in the Object.prototype.watch sense -- from |obj| for - * the property |id|. - * - * This is an internal function exposed -- temporarily -- only so that DOM - * proxies can be watchable. Don't use it! We'll soon kill off the - * Object.prototype.{,un}watch functions, at which point this will go too. - */ -extern JS_FRIEND_API(bool) -UnwatchGuts(JSContext* cx, JS::HandleObject obj, JS::HandleId id); - -namespace jit { - -enum class InlinableNative : uint16_t; - -} // namespace jit - -} // namespace js - -/** - * A class, expected to be passed by value, which represents the CallArgs for a - * JSJitGetterOp. - */ -class JSJitGetterCallArgs : protected JS::MutableHandleValue -{ - public: - explicit JSJitGetterCallArgs(const JS::CallArgs& args) - : JS::MutableHandleValue(args.rval()) - {} - - explicit JSJitGetterCallArgs(JS::RootedValue* rooted) - : JS::MutableHandleValue(rooted) - {} - - JS::MutableHandleValue rval() { - return *this; - } -}; - -/** - * A class, expected to be passed by value, which represents the CallArgs for a - * JSJitSetterOp. - */ -class JSJitSetterCallArgs : protected JS::MutableHandleValue -{ - public: - explicit JSJitSetterCallArgs(const JS::CallArgs& args) - : JS::MutableHandleValue(args[0]) - {} - - JS::MutableHandleValue operator[](unsigned i) { - MOZ_ASSERT(i == 0); - return *this; - } - - unsigned length() const { return 1; } - - // Add get() or maybe hasDefined() as needed -}; - -struct JSJitMethodCallArgsTraits; - -/** - * A class, expected to be passed by reference, which represents the CallArgs - * for a JSJitMethodOp. - */ -class JSJitMethodCallArgs : protected JS::detail::CallArgsBase -{ - private: - typedef JS::detail::CallArgsBase Base; - friend struct JSJitMethodCallArgsTraits; - - public: - explicit JSJitMethodCallArgs(const JS::CallArgs& args) { - argv_ = args.array(); - argc_ = args.length(); - } - - JS::MutableHandleValue rval() const { - return Base::rval(); - } - - unsigned length() const { return Base::length(); } - - JS::MutableHandleValue operator[](unsigned i) const { - return Base::operator[](i); - } - - bool hasDefined(unsigned i) const { - return Base::hasDefined(i); - } - - JSObject& callee() const { - // We can't use Base::callee() because that will try to poke at - // this->usedRval_, which we don't have. - return argv_[-2].toObject(); - } - - JS::HandleValue get(unsigned i) const { - return Base::get(i); - } -}; - -struct JSJitMethodCallArgsTraits -{ - static const size_t offsetOfArgv = offsetof(JSJitMethodCallArgs, argv_); - static const size_t offsetOfArgc = offsetof(JSJitMethodCallArgs, argc_); -}; - -typedef bool -(* JSJitGetterOp)(JSContext* cx, JS::HandleObject thisObj, - void* specializedThis, JSJitGetterCallArgs args); -typedef bool -(* JSJitSetterOp)(JSContext* cx, JS::HandleObject thisObj, - void* specializedThis, JSJitSetterCallArgs args); -typedef bool -(* JSJitMethodOp)(JSContext* cx, JS::HandleObject thisObj, - void* specializedThis, const JSJitMethodCallArgs& args); - -/** - * This struct contains metadata passed from the DOM to the JS Engine for JIT - * optimizations on DOM property accessors. Eventually, this should be made - * available to general JSAPI users, but we are not currently ready to do so. - */ -struct JSJitInfo { - enum OpType { - Getter, - Setter, - Method, - StaticMethod, - InlinableNative, - // Must be last - OpTypeCount - }; - - enum ArgType { - // Basic types - String = (1 << 0), - Integer = (1 << 1), // Only 32-bit or less - Double = (1 << 2), // Maybe we want to add Float sometime too - Boolean = (1 << 3), - Object = (1 << 4), - Null = (1 << 5), - - // And derived types - Numeric = Integer | Double, - // Should "Primitive" use the WebIDL definition, which - // excludes string and null, or the typical JS one that includes them? - Primitive = Numeric | Boolean | Null | String, - ObjectOrNull = Object | Null, - Any = ObjectOrNull | Primitive, - - // Our sentinel value. - ArgTypeListEnd = (1 << 31) - }; - - static_assert(Any & String, "Any must include String."); - static_assert(Any & Integer, "Any must include Integer."); - static_assert(Any & Double, "Any must include Double."); - static_assert(Any & Boolean, "Any must include Boolean."); - static_assert(Any & Object, "Any must include Object."); - static_assert(Any & Null, "Any must include Null."); - - /** - * An enum that describes what this getter/setter/method aliases. This - * determines what things can be hoisted past this call, and if this - * call is movable what it can be hoisted past. - */ - enum AliasSet { - /** - * Alias nothing: a constant value, getting it can't affect any other - * values, nothing can affect it. - */ - AliasNone, - - /** - * Alias things that can modify the DOM but nothing else. Doing the - * call can't affect the behavior of any other function. - */ - AliasDOMSets, - - /** - * Alias the world. Calling this can change arbitrary values anywhere - * in the system. Most things fall in this bucket. - */ - AliasEverything, - - /** Must be last. */ - AliasSetCount - }; - - bool needsOuterizedThisObject() const - { - return type() != Getter && type() != Setter; - } - - bool isTypedMethodJitInfo() const - { - return isTypedMethod; - } - - OpType type() const - { - return OpType(type_); - } - - AliasSet aliasSet() const - { - return AliasSet(aliasSet_); - } - - JSValueType returnType() const - { - return JSValueType(returnType_); - } - - union { - JSJitGetterOp getter; - JSJitSetterOp setter; - JSJitMethodOp method; - /** A DOM static method, used for Promise wrappers */ - JSNative staticMethod; - }; - - union { - uint16_t protoID; - js::jit::InlinableNative inlinableNative; - }; - - union { - uint16_t depth; - - // Additional opcode for some InlinableNative functions. - uint16_t nativeOp; - }; - - // These fields are carefully packed to take up 4 bytes. If you need more - // bits for whatever reason, please see if you can steal bits from existing - // fields before adding more members to this structure. - -#define JITINFO_OP_TYPE_BITS 4 -#define JITINFO_ALIAS_SET_BITS 4 -#define JITINFO_RETURN_TYPE_BITS 8 -#define JITINFO_SLOT_INDEX_BITS 10 - - /** The OpType that says what sort of function we are. */ - uint32_t type_ : JITINFO_OP_TYPE_BITS; - - /** - * The alias set for this op. This is a _minimal_ alias set; in - * particular for a method it does not include whatever argument - * conversions might do. That's covered by argTypes and runtime - * analysis of the actual argument types being passed in. - */ - uint32_t aliasSet_ : JITINFO_ALIAS_SET_BITS; - - /** The return type tag. Might be JSVAL_TYPE_UNKNOWN. */ - uint32_t returnType_ : JITINFO_RETURN_TYPE_BITS; - - static_assert(OpTypeCount <= (1 << JITINFO_OP_TYPE_BITS), - "Not enough space for OpType"); - static_assert(AliasSetCount <= (1 << JITINFO_ALIAS_SET_BITS), - "Not enough space for AliasSet"); - static_assert((sizeof(JSValueType) * 8) <= JITINFO_RETURN_TYPE_BITS, - "Not enough space for JSValueType"); - -#undef JITINFO_RETURN_TYPE_BITS -#undef JITINFO_ALIAS_SET_BITS -#undef JITINFO_OP_TYPE_BITS - - /** Is op fallible? False in setters. */ - uint32_t isInfallible : 1; - - /** - * Is op movable? To be movable the op must - * not AliasEverything, but even that might - * not be enough (e.g. in cases when it can - * throw or is explicitly not movable). - */ - uint32_t isMovable : 1; - - /** - * Can op be dead-code eliminated? Again, this - * depends on whether the op can throw, in - * addition to the alias set. - */ - uint32_t isEliminatable : 1; - - // XXXbz should we have a JSValueType for the type of the member? - /** - * True if this is a getter that can always - * get the value from a slot of the "this" object. - */ - uint32_t isAlwaysInSlot : 1; - - /** - * True if this is a getter that can sometimes (if the slot doesn't contain - * UndefinedValue()) get the value from a slot of the "this" object. - */ - uint32_t isLazilyCachedInSlot : 1; - - /** True if this is an instance of JSTypedMethodJitInfo. */ - uint32_t isTypedMethod : 1; - - /** - * If isAlwaysInSlot or isSometimesInSlot is true, - * the index of the slot to get the value from. - * Otherwise 0. - */ - uint32_t slotIndex : JITINFO_SLOT_INDEX_BITS; - - static const size_t maxSlotIndex = (1 << JITINFO_SLOT_INDEX_BITS) - 1; - -#undef JITINFO_SLOT_INDEX_BITS -}; - -static_assert(sizeof(JSJitInfo) == (sizeof(void*) + 2 * sizeof(uint32_t)), - "There are several thousand instances of JSJitInfo stored in " - "a binary. Please don't increase its space requirements without " - "verifying that there is no other way forward (better packing, " - "smaller datatypes for fields, subclassing, etc.)."); - -struct JSTypedMethodJitInfo -{ - // We use C-style inheritance here, rather than C++ style inheritance - // because not all compilers support brace-initialization for non-aggregate - // classes. Using C++ style inheritance and constructors instead of - // brace-initialization would also force the creation of static - // constructors (on some compilers) when JSJitInfo and JSTypedMethodJitInfo - // structures are declared. Since there can be several thousand of these - // structures present and we want to have roughly equivalent performance - // across a range of compilers, we do things manually. - JSJitInfo base; - - const JSJitInfo::ArgType* const argTypes; /* For a method, a list of sets of - types that the function - expects. This can be used, - for example, to figure out - when argument coercions can - have side-effects. */ -}; - -namespace js { - -static MOZ_ALWAYS_INLINE shadow::Function* -FunctionObjectToShadowFunction(JSObject* fun) -{ - MOZ_ASSERT(GetObjectClass(fun) == FunctionClassPtr); - return reinterpret_cast(fun); -} - -/* Statically asserted in jsfun.h. */ -static const unsigned JS_FUNCTION_INTERPRETED_BITS = 0x0201; - -// Return whether the given function object is native. -static MOZ_ALWAYS_INLINE bool -FunctionObjectIsNative(JSObject* fun) -{ - return !(FunctionObjectToShadowFunction(fun)->flags & JS_FUNCTION_INTERPRETED_BITS); -} - -static MOZ_ALWAYS_INLINE JSNative -GetFunctionObjectNative(JSObject* fun) -{ - MOZ_ASSERT(FunctionObjectIsNative(fun)); - return FunctionObjectToShadowFunction(fun)->native; -} - -} // namespace js - -static MOZ_ALWAYS_INLINE const JSJitInfo* -FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) -{ - MOZ_ASSERT(js::FunctionObjectIsNative(&v.toObject())); - return js::FunctionObjectToShadowFunction(&v.toObject())->jitinfo; -} - -static MOZ_ALWAYS_INLINE void -SET_JITINFO(JSFunction * func, const JSJitInfo* info) -{ - js::shadow::Function* fun = reinterpret_cast(func); - MOZ_ASSERT(!(fun->flags & js::JS_FUNCTION_INTERPRETED_BITS)); - fun->jitinfo = info; -} - -/* - * Engine-internal extensions of jsid. This code is here only until we - * eliminate Gecko's dependencies on it! - */ - -static MOZ_ALWAYS_INLINE jsid -JSID_FROM_BITS(size_t bits) -{ - jsid id; - JSID_BITS(id) = bits; - return id; -} - -namespace js { -namespace detail { -bool IdMatchesAtom(jsid id, JSAtom* atom); -} // namespace detail -} // namespace js - -/** - * Must not be used on atoms that are representable as integer jsids. - * Prefer NameToId or AtomToId over this function: - * - * A PropertyName is an atom that does not contain an integer in the range - * [0, UINT32_MAX]. However, jsid can only hold an integer in the range - * [0, JSID_INT_MAX] (where JSID_INT_MAX == 2^31-1). Thus, for the range of - * integers (JSID_INT_MAX, UINT32_MAX], to represent as a jsid 'id', it must be - * the case JSID_IS_ATOM(id) and !JSID_TO_ATOM(id)->isPropertyName(). In most - * cases when creating a jsid, code does not have to care about this corner - * case because: - * - * - When given an arbitrary JSAtom*, AtomToId must be used, which checks for - * integer atoms representable as integer jsids, and does this conversion. - * - * - When given a PropertyName*, NameToId can be used which which does not need - * to do any dynamic checks. - * - * Thus, it is only the rare third case which needs this function, which - * handles any JSAtom* that is known not to be representable with an int jsid. - */ -static MOZ_ALWAYS_INLINE jsid -NON_INTEGER_ATOM_TO_JSID(JSAtom* atom) -{ - MOZ_ASSERT(((size_t)atom & 0x7) == 0); - jsid id = JSID_FROM_BITS((size_t)atom); - MOZ_ASSERT(js::detail::IdMatchesAtom(id, atom)); - return id; -} - -/* All strings stored in jsids are atomized, but are not necessarily property names. */ -static MOZ_ALWAYS_INLINE bool -JSID_IS_ATOM(jsid id) -{ - return JSID_IS_STRING(id); -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_ATOM(jsid id, JSAtom* atom) -{ - return id == JSID_FROM_BITS((size_t)atom); -} - -static MOZ_ALWAYS_INLINE JSAtom* -JSID_TO_ATOM(jsid id) -{ - return (JSAtom*)JSID_TO_STRING(id); -} - -JS_STATIC_ASSERT(sizeof(jsid) == sizeof(void*)); - -namespace js { - -static MOZ_ALWAYS_INLINE JS::Value -IdToValue(jsid id) -{ - if (JSID_IS_STRING(id)) - return JS::StringValue(JSID_TO_STRING(id)); - if (JSID_IS_INT(id)) - return JS::Int32Value(JSID_TO_INT(id)); - if (JSID_IS_SYMBOL(id)) - return JS::SymbolValue(JSID_TO_SYMBOL(id)); - MOZ_ASSERT(JSID_IS_VOID(id)); - return JS::UndefinedValue(); -} - -/** - * If the embedder has registered a ScriptEnvironmentPreparer, - * PrepareScriptEnvironmentAndInvoke will call the preparer's 'invoke' method - * with the given |closure|, with the assumption that the preparer will set up - * any state necessary to run script in |scope|, invoke |closure| with a valid - * JSContext*, report any exceptions thrown from the closure, and return. - * - * If no preparer is registered, PrepareScriptEnvironmentAndInvoke will assert - * that |rt| has exactly one JSContext associated with it, enter the compartment - * of |scope| on that context, and invoke |closure|. - * - * In both cases, PrepareScriptEnvironmentAndInvoke will report any exceptions - * that are thrown by the closure. Consumers who want to propagate back - * whether the closure succeeded should do so via members of the closure - * itself. - */ - -struct ScriptEnvironmentPreparer { - struct Closure { - virtual bool operator()(JSContext* cx) = 0; - }; - - virtual void invoke(JS::HandleObject scope, Closure& closure) = 0; -}; - -extern JS_FRIEND_API(void) -PrepareScriptEnvironmentAndInvoke(JSContext* cx, JS::HandleObject scope, - ScriptEnvironmentPreparer::Closure& closure); - -JS_FRIEND_API(void) -SetScriptEnvironmentPreparer(JSContext* cx, ScriptEnvironmentPreparer* preparer); - -enum CTypesActivityType { - CTYPES_CALL_BEGIN, - CTYPES_CALL_END, - CTYPES_CALLBACK_BEGIN, - CTYPES_CALLBACK_END -}; - -typedef void -(* CTypesActivityCallback)(JSContext* cx, CTypesActivityType type); - -/** - * Sets a callback that is run whenever js-ctypes is about to be used when - * calling into C. - */ -JS_FRIEND_API(void) -SetCTypesActivityCallback(JSContext* cx, CTypesActivityCallback cb); - -class MOZ_RAII JS_FRIEND_API(AutoCTypesActivityCallback) { - private: - JSContext* cx; - CTypesActivityCallback callback; - CTypesActivityType endType; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - - public: - AutoCTypesActivityCallback(JSContext* cx, CTypesActivityType beginType, - CTypesActivityType endType - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~AutoCTypesActivityCallback() { - DoEndCallback(); - } - void DoEndCallback() { - if (callback) { - callback(cx, endType); - callback = nullptr; - } - } -}; - -// Abstract base class for objects that build allocation metadata for JavaScript -// values. -struct AllocationMetadataBuilder { - AllocationMetadataBuilder() { } - - // Return a metadata object for the newly constructed object |obj|, or - // nullptr if there's no metadata to attach. - // - // Implementations should treat all errors as fatal; there is no way to - // report errors from this callback. In particular, the caller provides an - // oomUnsafe for overriding implementations to use. - virtual JSObject* build(JSContext* cx, JS::HandleObject obj, - AutoEnterOOMUnsafeRegion& oomUnsafe) const - { - return nullptr; - } -}; - -/** - * Specify a callback to invoke when creating each JS object in the current - * compartment, which may return a metadata object to associate with the - * object. - */ -JS_FRIEND_API(void) -SetAllocationMetadataBuilder(JSContext* cx, const AllocationMetadataBuilder *callback); - -/** Get the metadata associated with an object. */ -JS_FRIEND_API(JSObject*) -GetAllocationMetadata(JSObject* obj); - -JS_FRIEND_API(bool) -GetElementsWithAdder(JSContext* cx, JS::HandleObject obj, JS::HandleObject receiver, - uint32_t begin, uint32_t end, js::ElementAdder* adder); - -JS_FRIEND_API(bool) -ForwardToNative(JSContext* cx, JSNative native, const JS::CallArgs& args); - -/** - * Helper function for HTMLDocument and HTMLFormElement. - * - * These are the only two interfaces that have [OverrideBuiltins], a named - * getter, and no named setter. They're implemented as proxies with a custom - * getOwnPropertyDescriptor() method. Unfortunately, overriding - * getOwnPropertyDescriptor() automatically affects the behavior of set(), - * which normally is just common sense but is *not* desired for these two - * interfaces. - * - * The fix is for these two interfaces to override set() to ignore the - * getOwnPropertyDescriptor() override. - * - * SetPropertyIgnoringNamedGetter is exposed to make it easier to override - * set() in this way. It carries out all the steps of BaseProxyHandler::set() - * except the initial getOwnPropertyDescriptor() call. The caller must supply - * that descriptor as the 'ownDesc' parameter. - * - * Implemented in proxy/BaseProxyHandler.cpp. - */ -JS_FRIEND_API(bool) -SetPropertyIgnoringNamedGetter(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::HandleValue v, JS::HandleValue receiver, - JS::Handle ownDesc, - JS::ObjectOpResult& result); - -JS_FRIEND_API(void) -ReportASCIIErrorWithId(JSContext* cx, const char* msg, JS::HandleId id); - -// This function is for one specific use case, please don't use this for anything else! -extern JS_FRIEND_API(bool) -ExecuteInGlobalAndReturnScope(JSContext* cx, JS::HandleObject obj, JS::HandleScript script, - JS::MutableHandleObject scope); - -#if defined(XP_WIN) && defined(_WIN64) -// Parameters use void* types to avoid #including windows.h. The return value of -// this function is returned from the exception handler. -typedef long -(*JitExceptionHandler)(void* exceptionRecord, // PEXECTION_RECORD - void* context); // PCONTEXT - -/** - * Windows uses "structured exception handling" to handle faults. When a fault - * occurs, the stack is searched for a handler (similar to C++ exception - * handling). If the search does not find a handler, the "unhandled exception - * filter" is called. Breakpad uses the unhandled exception filter to do crash - * reporting. Unfortunately, on Win64, JIT code on the stack completely throws - * off this unwinding process and prevents the unhandled exception filter from - * being called. The reason is that Win64 requires unwind information be - * registered for all code regions and JIT code has none. While it is possible - * to register full unwind information for JIT code, this is a lot of work (one - * has to be able to recover the frame pointer at any PC) so instead we register - * a handler for all JIT code that simply calls breakpad's unhandled exception - * filter (which will perform crash reporting and then terminate the process). - * This would be wrong if there was an outer __try block that expected to handle - * the fault, but this is not generally allowed. - * - * Gecko must call SetJitExceptionFilter before any JIT code is compiled and - * only once per process. - */ -extern JS_FRIEND_API(void) -SetJitExceptionHandler(JitExceptionHandler handler); -#endif - -/** - * Get the nearest enclosing with environment object for a given function. If - * the function is not scripted or is not enclosed by a with scope, returns - * the global. - */ -extern JS_FRIEND_API(JSObject*) -GetNearestEnclosingWithEnvironmentObjectForFunction(JSFunction* fun); - -/** - * Get the first SavedFrame object in this SavedFrame stack whose principals are - * subsumed by the cx's principals. If there is no such frame, return nullptr. - * - * Do NOT pass a non-SavedFrame object here. - * - * The savedFrame and cx do not need to be in the same compartment. - */ -extern JS_FRIEND_API(JSObject*) -GetFirstSubsumedSavedFrame(JSContext* cx, JS::HandleObject savedFrame, JS::SavedFrameSelfHosted selfHosted); - -extern JS_FRIEND_API(bool) -ReportIsNotFunction(JSContext* cx, JS::HandleValue v); - -extern JS_FRIEND_API(JSObject*) -ConvertArgsToArray(JSContext* cx, const JS::CallArgs& args); - -/** - * Window and WindowProxy - * - * The functions below have to do with Windows and WindowProxies. There's an - * invariant that actual Window objects (the global objects of web pages) are - * never directly exposed to script. Instead we often substitute a WindowProxy. - * - * The environment chain, on the other hand, contains the Window and never its - * WindowProxy. - * - * As a result, we have calls to these "substitute-this-object-for-that-object" - * functions sprinkled at apparently arbitrary (but actually *very* carefully - * and nervously selected) places throughout the engine and indeed the - * universe. - */ - -/** - * Tell the JS engine which Class is used for WindowProxy objects. Used by the - * functions below. - */ -extern JS_FRIEND_API(void) -SetWindowProxyClass(JSContext* cx, const Class* clasp); - -/** - * Associates a WindowProxy with a Window (global object). `windowProxy` must - * have the Class set by SetWindowProxyClass. - */ -extern JS_FRIEND_API(void) -SetWindowProxy(JSContext* cx, JS::HandleObject global, JS::HandleObject windowProxy); - -namespace detail { - -JS_FRIEND_API(bool) -IsWindowSlow(JSObject* obj); - -} // namespace detail - -/** - * Returns true iff `obj` is a global object with an associated WindowProxy, - * see SetWindowProxy. - */ -inline bool -IsWindow(JSObject* obj) -{ - if (GetObjectClass(obj)->flags & JSCLASS_IS_GLOBAL) - return detail::IsWindowSlow(obj); - return false; -} - -/** - * Returns true iff `obj` has the WindowProxy Class (see SetWindowProxyClass). - */ -JS_FRIEND_API(bool) -IsWindowProxy(JSObject* obj); - -/** - * If `obj` is a Window, get its associated WindowProxy (or a CCW or dead - * wrapper if the page was navigated away from), else return `obj`. This - * function is infallible and never returns nullptr. - */ -extern JS_FRIEND_API(JSObject*) -ToWindowProxyIfWindow(JSObject* obj); - -/** - * If `obj` is a WindowProxy, get its associated Window (the compartment's - * global), else return `obj`. This function is infallible and never returns - * nullptr. - */ -extern JS_FRIEND_API(JSObject*) -ToWindowIfWindowProxy(JSObject* obj); - -} /* namespace js */ - -class NativeProfiler -{ - public: - virtual ~NativeProfiler() {}; - virtual void sampleNative(void* addr, uint32_t size) = 0; - virtual void removeNative(void* addr) = 0; - virtual void reset() = 0; -}; - -class GCHeapProfiler -{ - public: - virtual ~GCHeapProfiler() {}; - virtual void sampleTenured(void* addr, uint32_t size) = 0; - virtual void sampleNursery(void* addr, uint32_t size) = 0; - virtual void markTenuredStart() = 0; - virtual void markTenured(void* addr) = 0; - virtual void sweepTenured() = 0; - virtual void sweepNursery() = 0; - virtual void moveNurseryToTenured(void* addrOld, void* addrNew) = 0; - virtual void reset() = 0; -}; - -class MemProfiler -{ - static mozilla::Atomic sActiveProfilerCount; - static NativeProfiler* sNativeProfiler; - - static GCHeapProfiler* GetGCHeapProfiler(void* addr); - static GCHeapProfiler* GetGCHeapProfiler(JSRuntime* runtime); - - static NativeProfiler* GetNativeProfiler() { - return sNativeProfiler; - } - - GCHeapProfiler* mGCHeapProfiler; - JSRuntime* mRuntime; - - public: - explicit MemProfiler(JSRuntime* aRuntime) : mGCHeapProfiler(nullptr), mRuntime(aRuntime) {} - - void start(GCHeapProfiler* aGCHeapProfiler); - void stop(); - - GCHeapProfiler* getGCHeapProfiler() const { - return mGCHeapProfiler; - } - - static MOZ_ALWAYS_INLINE bool enabled() { - return sActiveProfilerCount > 0; - } - - static MemProfiler* GetMemProfiler(JSContext* context); - - static void SetNativeProfiler(NativeProfiler* aProfiler) { - sNativeProfiler = aProfiler; - } - - static MOZ_ALWAYS_INLINE void SampleNative(void* addr, uint32_t size) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - NativeProfiler* profiler = GetNativeProfiler(); - if (profiler) - profiler->sampleNative(addr, size); - } - - static MOZ_ALWAYS_INLINE void SampleTenured(void* addr, uint32_t size) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addr); - if (profiler) - profiler->sampleTenured(addr, size); - } - - static MOZ_ALWAYS_INLINE void SampleNursery(void* addr, uint32_t size) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addr); - if (profiler) - profiler->sampleNursery(addr, size); - } - - static MOZ_ALWAYS_INLINE void RemoveNative(void* addr) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - NativeProfiler* profiler = GetNativeProfiler(); - if (profiler) - profiler->removeNative(addr); - } - - static MOZ_ALWAYS_INLINE void MarkTenuredStart(JSRuntime* runtime) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(runtime); - if (profiler) - profiler->markTenuredStart(); - } - - static MOZ_ALWAYS_INLINE void MarkTenured(void* addr) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addr); - if (profiler) - profiler->markTenured(addr); - } - - static MOZ_ALWAYS_INLINE void SweepTenured(JSRuntime* runtime) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(runtime); - if (profiler) - profiler->sweepTenured(); - } - - static MOZ_ALWAYS_INLINE void SweepNursery(JSRuntime* runtime) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(runtime); - if (profiler) - profiler->sweepNursery(); - } - - static MOZ_ALWAYS_INLINE void MoveNurseryToTenured(void* addrOld, void* addrNew) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addrOld); - if (profiler) - profiler->moveNurseryToTenured(addrOld, addrNew); - } -}; - -#endif /* jsfriendapi_h */ diff --git a/ios/include/spidermonkey/jsperf.h b/ios/include/spidermonkey/jsperf.h deleted file mode 100644 index b8f2909a..00000000 --- a/ios/include/spidermonkey/jsperf.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef perf_jsperf_h -#define perf_jsperf_h - -#include "jstypes.h" - -#include "js/TypeDecls.h" -#include "js/Utility.h" - -namespace JS { - -/* - * JS::PerfMeasurement is a generic way to access detailed performance - * measurement APIs provided by your operating system. The details of - * exactly how this works and what can be measured are highly - * system-specific, but this interface is (one hopes) implementable - * on top of all of them. - * - * To use this API, create a PerfMeasurement object, passing its - * constructor a bitmask indicating which events you are interested - * in. Thereafter, Start() zeroes all counters and starts timing; - * Stop() stops timing again; and the counters for the events you - * requested are available as data values after calling Stop(). The - * object may be reused for many measurements. - */ -class JS_FRIEND_API(PerfMeasurement) -{ - protected: - // Implementation-specific data, if any. - void* impl; - - public: - /* - * Events that may be measured. Taken directly from the list of - * "generalized hardware performance event types" in the Linux - * perf_event API, plus some of the "software events". - */ - enum EventMask { - CPU_CYCLES = 0x00000001, - INSTRUCTIONS = 0x00000002, - CACHE_REFERENCES = 0x00000004, - CACHE_MISSES = 0x00000008, - BRANCH_INSTRUCTIONS = 0x00000010, - BRANCH_MISSES = 0x00000020, - BUS_CYCLES = 0x00000040, - PAGE_FAULTS = 0x00000080, - MAJOR_PAGE_FAULTS = 0x00000100, - CONTEXT_SWITCHES = 0x00000200, - CPU_MIGRATIONS = 0x00000400, - - ALL = 0x000007ff, - NUM_MEASURABLE_EVENTS = 11 - }; - - /* - * Bitmask of events that will be measured when this object is - * active (between Start() and Stop()). This may differ from the - * bitmask passed to the constructor if the platform does not - * support measuring all of the requested events. - */ - const EventMask eventsMeasured; - - /* - * Counters for each measurable event. - * Immediately after one of these objects is created, all of the - * counters for enabled events will be zero, and all of the - * counters for disabled events will be uint64_t(-1). - */ - uint64_t cpu_cycles; - uint64_t instructions; - uint64_t cache_references; - uint64_t cache_misses; - uint64_t branch_instructions; - uint64_t branch_misses; - uint64_t bus_cycles; - uint64_t page_faults; - uint64_t major_page_faults; - uint64_t context_switches; - uint64_t cpu_migrations; - - /* - * Prepare to measure the indicated set of events. If not all of - * the requested events can be measured on the current platform, - * then the eventsMeasured bitmask will only include the subset of - * |toMeasure| corresponding to the events that can be measured. - */ - explicit PerfMeasurement(EventMask toMeasure); - - /* Done with this set of measurements, tear down OS-level state. */ - ~PerfMeasurement(); - - /* Start a measurement cycle. */ - void start(); - - /* - * End a measurement cycle, and for each enabled counter, add the - * number of measured events of that type to the appropriate - * visible variable. - */ - void stop(); - - /* Reset all enabled counters to zero. */ - void reset(); - - /* - * True if this platform supports measuring _something_, i.e. it's - * not using the stub implementation. - */ - static bool canMeasureSomething(); -}; - -/* Inject a Javascript wrapper around the above C++ class into the - * Javascript object passed as an argument (this will normally be a - * global object). The JS-visible API is identical to the C++ API. - */ -extern JS_FRIEND_API(JSObject*) - RegisterPerfMeasurement(JSContext* cx, JS::HandleObject global); - -/* - * Given a Value which contains an instance of the aforementioned - * wrapper class, extract the C++ object. Returns nullptr if the - * Value is not an instance of the wrapper. - */ -extern JS_FRIEND_API(PerfMeasurement*) - ExtractPerfMeasurement(const Value& wrapper); - -} // namespace JS - -#endif /* perf_jsperf_h */ diff --git a/ios/include/spidermonkey/jsprf.h b/ios/include/spidermonkey/jsprf.h deleted file mode 100644 index b84b5a5c..00000000 --- a/ios/include/spidermonkey/jsprf.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsprf_h -#define jsprf_h - -/* -** API for PR printf like routines. Supports the following formats -** %d - decimal -** %u - unsigned decimal -** %x - unsigned hex -** %X - unsigned uppercase hex -** %o - unsigned octal -** %hd, %hu, %hx, %hX, %ho - "short" versions of above -** %ld, %lu, %lx, %lX, %lo - "long" versions of above -** %lld, %llu, %llx, %llX, %llo - "long long" versions of above -** %zd, %zo, %zu, %zx, %zX - size_t versions of above -** %Id, %Io, %Iu, %Ix, %IX - size_t versions of above (for Windows compat) -** You should use PRI*SIZE macros instead -** %s - string -** %c - character -** %p - pointer (deals with machine dependent pointer size) -** %f - float -** %g - float -*/ - -#include "mozilla/IntegerPrintfMacros.h" -#include "mozilla/SizePrintfMacros.h" - -#include - -#include "jstypes.h" - -/* -** sprintf into a malloc'd buffer. Return a pointer to the malloc'd -** buffer on success, nullptr on failure. Call "JS_smprintf_free" to release -** the memory returned. -*/ -extern JS_PUBLIC_API(char*) JS_smprintf(const char* fmt, ...) - MOZ_FORMAT_PRINTF(1, 2); - -/* -** Free the memory allocated, for the caller, by JS_smprintf -*/ -extern JS_PUBLIC_API(void) JS_smprintf_free(char* mem); - -/* -** "append" sprintf into a malloc'd buffer. "last" is the last value of -** the malloc'd buffer. sprintf will append data to the end of last, -** growing it as necessary using realloc. If last is nullptr, JS_sprintf_append -** will allocate the initial string. The return value is the new value of -** last for subsequent calls, or nullptr if there is a malloc failure. -*/ -extern JS_PUBLIC_API(char*) JS_sprintf_append(char* last, const char* fmt, ...) - MOZ_FORMAT_PRINTF(2, 3); - -/* -** va_list forms of the above. -*/ -extern JS_PUBLIC_API(char*) JS_vsmprintf(const char* fmt, va_list ap); -extern JS_PUBLIC_API(char*) JS_vsprintf_append(char* last, const char* fmt, va_list ap); - -#endif /* jsprf_h */ diff --git a/ios/include/spidermonkey/jsprototypes.h b/ios/include/spidermonkey/jsprototypes.h deleted file mode 100644 index f409dce9..00000000 --- a/ios/include/spidermonkey/jsprototypes.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsprototypes_h -#define jsprototypes_h - -/* A higher-order macro for enumerating all JSProtoKey values. */ -/* - * Consumers define macros as follows: - * macro(name, code, init, clasp) - * name: The canonical name of the class. - * code: The enumerator code. There are part of the XDR API, and must not change. - * init: Initialization function. These are |extern "C";|, and clients should use - * |extern "C" {}| as appropriate when using this macro. - * clasp: The JSClass for this object, or "dummy" if it doesn't exist. - * - * - * Consumers wishing to iterate over all the JSProtoKey values, can use - * JS_FOR_EACH_PROTOTYPE. However, there are certain values that don't correspond - * to real constructors, like Null or constructors that are disabled via - * preprocessor directives. We still need to include these in the JSProtoKey list - * in order to maintain binary XDR compatibility, but we need to provide a tool - * to handle them differently. JS_FOR_PROTOTYPES fills this niche. - * - * Consumers pass two macros to JS_FOR_PROTOTYPES - |real| and |imaginary|. The - * former is invoked for entries that have real client-exposed constructors, and - * the latter is called for the rest. Consumers that don't care about this - * distinction can simply pass the same macro to both, which is exactly what - * JS_FOR_EACH_PROTOTYPE does. - */ - -#define CLASP(name) (&name##Class) -#define OCLASP(name) (&name##Object::class_) -#define TYPED_ARRAY_CLASP(type) (&TypedArrayObject::classes[Scalar::type]) -#define ERROR_CLASP(type) (&ErrorObject::classes[type]) - -#ifdef EXPOSE_INTL_API -#define IF_INTL(real,imaginary) real -#else -#define IF_INTL(real,imaginary) imaginary -#endif - -#ifdef ENABLE_BINARYDATA -#define IF_BDATA(real,imaginary) real -#else -#define IF_BDATA(real,imaginary) imaginary -#endif - -#ifdef ENABLE_SIMD -# define IF_SIMD(real,imaginary) real -#else -# define IF_SIMD(real,imaginary) imaginary -#endif - -#ifdef ENABLE_SHARED_ARRAY_BUFFER -#define IF_SAB(real,imaginary) real -#else -#define IF_SAB(real,imaginary) imaginary -#endif - -#ifdef SPIDERMONKEY_PROMISE -#define IF_PROMISE(real,imaginary) real -#else -#define IF_PROMISE(real,imaginary) imaginary -#endif - -#define JS_FOR_PROTOTYPES(real,imaginary) \ - imaginary(Null, 0, InitNullClass, dummy) \ - real(Object, 1, InitViaClassSpec, OCLASP(Plain)) \ - real(Function, 2, InitViaClassSpec, &JSFunction::class_) \ - real(Array, 3, InitViaClassSpec, OCLASP(Array)) \ - real(Boolean, 4, InitBooleanClass, OCLASP(Boolean)) \ - real(JSON, 5, InitJSONClass, CLASP(JSON)) \ - real(Date, 6, InitViaClassSpec, OCLASP(Date)) \ - real(Math, 7, InitMathClass, CLASP(Math)) \ - real(Number, 8, InitNumberClass, OCLASP(Number)) \ - real(String, 9, InitStringClass, OCLASP(String)) \ - real(RegExp, 10, InitViaClassSpec, OCLASP(RegExp)) \ - real(Error, 11, InitViaClassSpec, ERROR_CLASP(JSEXN_ERR)) \ - real(InternalError, 12, InitViaClassSpec, ERROR_CLASP(JSEXN_INTERNALERR)) \ - real(EvalError, 13, InitViaClassSpec, ERROR_CLASP(JSEXN_EVALERR)) \ - real(RangeError, 14, InitViaClassSpec, ERROR_CLASP(JSEXN_RANGEERR)) \ - real(ReferenceError, 15, InitViaClassSpec, ERROR_CLASP(JSEXN_REFERENCEERR)) \ - real(SyntaxError, 16, InitViaClassSpec, ERROR_CLASP(JSEXN_SYNTAXERR)) \ - real(TypeError, 17, InitViaClassSpec, ERROR_CLASP(JSEXN_TYPEERR)) \ - real(URIError, 18, InitViaClassSpec, ERROR_CLASP(JSEXN_URIERR)) \ - real(DebuggeeWouldRun, 19, InitViaClassSpec, ERROR_CLASP(JSEXN_DEBUGGEEWOULDRUN)) \ - real(CompileError, 20, InitViaClassSpec, ERROR_CLASP(JSEXN_WASMCOMPILEERROR)) \ - real(RuntimeError, 21, InitViaClassSpec, ERROR_CLASP(JSEXN_WASMRUNTIMEERROR)) \ - real(Iterator, 22, InitLegacyIteratorClass,OCLASP(PropertyIterator)) \ - real(StopIteration, 23, InitStopIterationClass, OCLASP(StopIteration)) \ - real(ArrayBuffer, 24, InitViaClassSpec, OCLASP(ArrayBuffer)) \ - real(Int8Array, 25, InitViaClassSpec, TYPED_ARRAY_CLASP(Int8)) \ - real(Uint8Array, 26, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint8)) \ - real(Int16Array, 27, InitViaClassSpec, TYPED_ARRAY_CLASP(Int16)) \ - real(Uint16Array, 28, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint16)) \ - real(Int32Array, 29, InitViaClassSpec, TYPED_ARRAY_CLASP(Int32)) \ - real(Uint32Array, 30, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint32)) \ - real(Float32Array, 31, InitViaClassSpec, TYPED_ARRAY_CLASP(Float32)) \ - real(Float64Array, 32, InitViaClassSpec, TYPED_ARRAY_CLASP(Float64)) \ - real(Uint8ClampedArray, 33, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint8Clamped)) \ - real(Proxy, 34, InitProxyClass, js::ProxyClassPtr) \ - real(WeakMap, 35, InitWeakMapClass, OCLASP(WeakMap)) \ - real(Map, 36, InitMapClass, OCLASP(Map)) \ - real(Set, 37, InitSetClass, OCLASP(Set)) \ - real(DataView, 38, InitDataViewClass, OCLASP(DataView)) \ - real(Symbol, 39, InitSymbolClass, OCLASP(Symbol)) \ -IF_SAB(real,imaginary)(SharedArrayBuffer, 40, InitViaClassSpec, OCLASP(SharedArrayBuffer)) \ -IF_INTL(real,imaginary) (Intl, 41, InitIntlClass, CLASP(Intl)) \ -IF_BDATA(real,imaginary)(TypedObject, 42, InitTypedObjectModuleObject, OCLASP(TypedObjectModule)) \ - real(Reflect, 43, InitReflect, nullptr) \ -IF_SIMD(real,imaginary)(SIMD, 44, InitSimdClass, OCLASP(Simd)) \ - real(WeakSet, 45, InitWeakSetClass, OCLASP(WeakSet)) \ - real(TypedArray, 46, InitViaClassSpec, &js::TypedArrayObject::sharedTypedArrayPrototypeClass) \ -IF_SAB(real,imaginary)(Atomics, 47, InitAtomicsClass, OCLASP(Atomics)) \ - real(SavedFrame, 48, InitViaClassSpec, &js::SavedFrame::class_) \ - real(WebAssembly, 49, InitWebAssemblyClass, CLASP(WebAssembly)) \ - imaginary(WasmModule, 50, dummy, dummy) \ - imaginary(WasmInstance, 51, dummy, dummy) \ - imaginary(WasmMemory, 52, dummy, dummy) \ - imaginary(WasmTable, 53, dummy, dummy) \ -IF_PROMISE(real,imaginary)(Promise, 54, InitViaClassSpec, OCLASP(Promise)) \ - -#define JS_FOR_EACH_PROTOTYPE(macro) JS_FOR_PROTOTYPES(macro,macro) - -#endif /* jsprototypes_h */ diff --git a/ios/include/spidermonkey/jspubtd.h b/ios/include/spidermonkey/jspubtd.h deleted file mode 100644 index 309b9d74..00000000 --- a/ios/include/spidermonkey/jspubtd.h +++ /dev/null @@ -1,476 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jspubtd_h -#define jspubtd_h - -/* - * JS public API typedefs. - */ - -#include "mozilla/Assertions.h" -#include "mozilla/EnumeratedArray.h" -#include "mozilla/LinkedList.h" -#include "mozilla/PodOperations.h" - -#include "jsprototypes.h" -#include "jstypes.h" - -#include "js/TraceKind.h" -#include "js/TypeDecls.h" - -#if defined(JS_GC_ZEAL) || defined(DEBUG) -# define JSGC_HASH_TABLE_CHECKS -#endif - -namespace JS { - -class AutoIdVector; -class CallArgs; - -template -class Rooted; - -class JS_FRIEND_API(CompileOptions); -class JS_FRIEND_API(ReadOnlyCompileOptions); -class JS_FRIEND_API(OwningCompileOptions); -class JS_FRIEND_API(TransitiveCompileOptions); -class JS_PUBLIC_API(CompartmentOptions); - -struct RootingContext; -class Value; -struct Zone; - -namespace shadow { -struct Runtime; -} // namespace shadow - -} // namespace JS - -namespace js { -class RootLists; -} // namespace js - -/* - * Run-time version enumeration. For compile-time version checking, please use - * the JS_HAS_* macros in jsversion.h, or use MOZJS_MAJOR_VERSION, - * MOZJS_MINOR_VERSION, MOZJS_PATCH_VERSION, and MOZJS_ALPHA definitions. - */ -enum JSVersion { - JSVERSION_ECMA_3 = 148, - JSVERSION_1_6 = 160, - JSVERSION_1_7 = 170, - JSVERSION_1_8 = 180, - JSVERSION_ECMA_5 = 185, - JSVERSION_DEFAULT = 0, - JSVERSION_UNKNOWN = -1, - JSVERSION_LATEST = JSVERSION_ECMA_5 -}; - -/* Result of typeof operator enumeration. */ -enum JSType { - JSTYPE_VOID, /* undefined */ - JSTYPE_OBJECT, /* object */ - JSTYPE_FUNCTION, /* function */ - JSTYPE_STRING, /* string */ - JSTYPE_NUMBER, /* number */ - JSTYPE_BOOLEAN, /* boolean */ - JSTYPE_NULL, /* null */ - JSTYPE_SYMBOL, /* symbol */ - JSTYPE_LIMIT -}; - -/* Dense index into cached prototypes and class atoms for standard objects. */ -enum JSProtoKey { -#define PROTOKEY_AND_INITIALIZER(name,code,init,clasp) JSProto_##name = code, - JS_FOR_EACH_PROTOTYPE(PROTOKEY_AND_INITIALIZER) -#undef PROTOKEY_AND_INITIALIZER - JSProto_LIMIT -}; - -/* Struct forward declarations. */ -struct JSClass; -struct JSCompartment; -struct JSCrossCompartmentCall; -class JSErrorReport; -struct JSExceptionState; -struct JSFunctionSpec; -struct JSLocaleCallbacks; -struct JSObjectMap; -struct JSPrincipals; -struct JSPropertyName; -struct JSPropertySpec; -struct JSRuntime; -struct JSSecurityCallbacks; -struct JSStructuredCloneCallbacks; -struct JSStructuredCloneReader; -struct JSStructuredCloneWriter; -class JS_PUBLIC_API(JSTracer); - -class JSFlatString; - -typedef bool (*JSInitCallback)(void); - -template struct JSConstScalarSpec; -typedef JSConstScalarSpec JSConstDoubleSpec; -typedef JSConstScalarSpec JSConstIntegerSpec; - -/* - * Generic trace operation that calls JS::TraceEdge on each traceable thing's - * location reachable from data. - */ -typedef void -(* JSTraceDataOp)(JSTracer* trc, void* data); - -namespace js { -namespace gc { -class AutoTraceSession; -class StoreBuffer; -} // namespace gc - -// Whether the current thread is permitted access to any part of the specified -// runtime or zone. -JS_FRIEND_API(bool) -CurrentThreadCanAccessRuntime(const JSRuntime* rt); - -#ifdef DEBUG -JS_FRIEND_API(bool) -CurrentThreadIsPerformingGC(); -#endif - -} // namespace js - -namespace JS { - -class JS_PUBLIC_API(AutoEnterCycleCollection); -class JS_PUBLIC_API(AutoAssertOnBarrier); -struct JS_PUBLIC_API(PropertyDescriptor); - -typedef void (*OffThreadCompileCallback)(void* token, void* callbackData); - -enum class HeapState { - Idle, // doing nothing with the GC heap - Tracing, // tracing the GC heap without collecting, e.g. IterateCompartments() - MajorCollecting, // doing a GC of the major heap - MinorCollecting, // doing a GC of the minor heap (nursery) - CycleCollecting // in the "Unlink" phase of cycle collection -}; - -namespace shadow { - -struct Runtime -{ - private: - JS::HeapState heapState_; - - protected: - void setHeapState(JS::HeapState newState) { - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(asRuntime())); - MOZ_ASSERT(heapState_ != newState); - heapState_ = newState; - } - - JS::HeapState heapState() const { - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(asRuntime()) || - js::CurrentThreadIsPerformingGC()); - return heapState_; - } - - // In some cases, invoking GC barriers (incremental or otherwise) will break - // things. These barriers assert if this flag is set. - bool allowGCBarriers_; - friend class JS::AutoAssertOnBarrier; - - js::gc::StoreBuffer* gcStoreBufferPtr_; - - // The gray bits can become invalid if UnmarkGray overflows the stack. A - // full GC will reset this bit, since it fills in all the gray bits. - bool gcGrayBitsValid_; - - public: - Runtime() - : heapState_(JS::HeapState::Idle) - , allowGCBarriers_(true) - , gcStoreBufferPtr_(nullptr) - , gcGrayBitsValid_(false) - {} - - bool isHeapBusy() const { return heapState() != JS::HeapState::Idle; } - bool isHeapTracing() const { return heapState() == JS::HeapState::Tracing; } - bool isHeapMajorCollecting() const { return heapState() == JS::HeapState::MajorCollecting; } - bool isHeapMinorCollecting() const { return heapState() == JS::HeapState::MinorCollecting; } - bool isHeapCollecting() const { return isHeapMinorCollecting() || isHeapMajorCollecting(); } - bool isCycleCollecting() const { - return heapState() == JS::HeapState::CycleCollecting; - } - - bool allowGCBarriers() const { return allowGCBarriers_; } - - js::gc::StoreBuffer* gcStoreBufferPtr() { return gcStoreBufferPtr_; } - - bool areGCGrayBitsValid() const { return gcGrayBitsValid_; } - void setGCGrayBitsValid(bool valid) { gcGrayBitsValid_ = valid; } - - const JSRuntime* asRuntime() const { - return reinterpret_cast(this); - } - - static JS::shadow::Runtime* asShadowRuntime(JSRuntime* rt) { - return reinterpret_cast(rt); - } - - protected: - void setGCStoreBufferPtr(js::gc::StoreBuffer* storeBuffer) { - gcStoreBufferPtr_ = storeBuffer; - } -}; - -} /* namespace shadow */ - -// Decorates the Unlinking phase of CycleCollection so that accidental use -// of barriered accessors results in assertions instead of leaks. -class MOZ_STACK_CLASS JS_PUBLIC_API(AutoEnterCycleCollection) -{ -#ifdef DEBUG - JSRuntime* runtime; - - public: - explicit AutoEnterCycleCollection(JSContext* cx); - ~AutoEnterCycleCollection(); -#else - public: - explicit AutoEnterCycleCollection(JSContext* cx) {} - ~AutoEnterCycleCollection() {} -#endif -}; - -class JS_PUBLIC_API(AutoGCRooter) -{ - public: - AutoGCRooter(JSContext* cx, ptrdiff_t tag); - AutoGCRooter(JS::RootingContext* cx, ptrdiff_t tag); - - ~AutoGCRooter() { - MOZ_ASSERT(this == *stackTop); - *stackTop = down; - } - - /* Implemented in gc/RootMarking.cpp. */ - inline void trace(JSTracer* trc); - static void traceAll(JSTracer* trc); - static void traceAllWrappers(JSTracer* trc); - - protected: - AutoGCRooter * const down; - - /* - * Discriminates actual subclass of this being used. If non-negative, the - * subclass roots an array of values of the length stored in this field. - * If negative, meaning is indicated by the corresponding value in the enum - * below. Any other negative value indicates some deeper problem such as - * memory corruption. - */ - ptrdiff_t tag_; - - enum { - VALARRAY = -2, /* js::AutoValueArray */ - PARSER = -3, /* js::frontend::Parser */ - VALVECTOR = -10, /* js::AutoValueVector */ - IDVECTOR = -11, /* js::AutoIdVector */ - OBJVECTOR = -14, /* js::AutoObjectVector */ - IONMASM = -19, /* js::jit::MacroAssembler */ - WRAPVECTOR = -20, /* js::AutoWrapperVector */ - WRAPPER = -21, /* js::AutoWrapperRooter */ - CUSTOM = -26 /* js::CustomAutoRooter */ - }; - - static ptrdiff_t GetTag(const Value& value) { return VALVECTOR; } - static ptrdiff_t GetTag(const jsid& id) { return IDVECTOR; } - static ptrdiff_t GetTag(JSObject* obj) { return OBJVECTOR; } - - private: - AutoGCRooter ** const stackTop; - - /* No copy or assignment semantics. */ - AutoGCRooter(AutoGCRooter& ida) = delete; - void operator=(AutoGCRooter& ida) = delete; -}; - -// Our instantiations of Rooted and PersistentRooted require an -// instantiation of MapTypeToRootKind. -template <> -struct MapTypeToRootKind { - static const RootKind kind = RootKind::Traceable; -}; - -} /* namespace JS */ - -namespace js { - -class ExclusiveContext; - -/* - * This list enumerates the different types of conceptual stacks we have in - * SpiderMonkey. In reality, they all share the C stack, but we allow different - * stack limits depending on the type of code running. - */ -enum StackKind -{ - StackForSystemCode, // C++, such as the GC, running on behalf of the VM. - StackForTrustedScript, // Script running with trusted principals. - StackForUntrustedScript, // Script running with untrusted principals. - StackKindCount -}; - -using RootedListHeads = mozilla::EnumeratedArray*>; - -// Abstracts JS rooting mechanisms so they can be shared between the JSContext -// and JSRuntime. -class RootLists -{ - // Stack GC roots for Rooted GC heap pointers. - RootedListHeads stackRoots_; - template friend class JS::Rooted; - - // Stack GC roots for AutoFooRooter classes. - JS::AutoGCRooter* autoGCRooters_; - friend class JS::AutoGCRooter; - - // Heap GC roots for PersistentRooted pointers. - mozilla::EnumeratedArray>> heapRoots_; - template friend class JS::PersistentRooted; - - public: - RootLists() : autoGCRooters_(nullptr) { - for (auto& stackRootPtr : stackRoots_) - stackRootPtr = nullptr; - } - - ~RootLists() { - // The semantics of PersistentRooted containing pointers and tagged - // pointers are somewhat different from those of PersistentRooted - // containing a structure with a trace method. PersistentRooted - // containing pointers are allowed to outlive the owning RootLists, - // whereas those containing a traceable structure are not. - // - // The purpose of this feature is to support lazy initialization of - // global references for the several places in Gecko that do not have - // access to a tighter context, but that still need to refer to GC - // pointers. For such pointers, FinishPersistentRootedChains ensures - // that the contained references are nulled out when the owning - // RootLists dies to prevent UAF errors. - // - // However, for RootKind::Traceable, we do not know the concrete type - // of the held thing, so we simply cannot do this without accruing - // extra overhead and complexity for all users for a case that is - // unlikely to ever be used in practice. For this reason, the following - // assertion disallows usage of PersistentRooted that - // outlives the RootLists. - MOZ_ASSERT(heapRoots_[JS::RootKind::Traceable].isEmpty()); - } - - void traceStackRoots(JSTracer* trc); - void checkNoGCRooters(); - - void tracePersistentRoots(JSTracer* trc); - void finishPersistentRoots(); -}; - -} // namespace js - -namespace JS { - -/* - * JS::RootingContext is a base class of ContextFriendFields and JSContext. - * This class can be used to let code construct a Rooted<> or PersistentRooted<> - * instance, without giving it full access to the JSContext. - */ -struct RootingContext -{ - js::RootLists roots; - -#ifdef DEBUG - // Whether the derived class is a JSContext or an ExclusiveContext. - bool isJSContext; -#endif - - explicit RootingContext(bool isJSContextArg) -#ifdef DEBUG - : isJSContext(isJSContextArg) -#endif - {} - - static RootingContext* get(JSContext* cx) { - return reinterpret_cast(cx); - } -}; - -} // namespace JS - -namespace js { - -struct ContextFriendFields : public JS::RootingContext -{ - protected: - /* The current compartment. */ - JSCompartment* compartment_; - - /* The current zone. */ - JS::Zone* zone_; - - public: - /* Limit pointer for checking native stack consumption. */ - uintptr_t nativeStackLimit[js::StackKindCount]; - - explicit ContextFriendFields(bool isJSContext); - - static const ContextFriendFields* get(const JSContext* cx) { - return reinterpret_cast(cx); - } - - static ContextFriendFields* get(JSContext* cx) { - return reinterpret_cast(cx); - } - - friend JSCompartment* GetContextCompartment(const JSContext* cx); - friend JS::Zone* GetContextZone(const JSContext* cx); - template friend class JS::Rooted; -}; - -/* - * Inlinable accessors for JSContext. - * - * - These must not be available on the more restricted superclasses of - * JSContext, so we can't simply define them on ContextFriendFields. - * - * - They're perfectly ordinary JSContext functionality, so ought to be - * usable without resorting to jsfriendapi.h, and when JSContext is an - * incomplete type. - */ -inline JSCompartment* -GetContextCompartment(const JSContext* cx) -{ - return ContextFriendFields::get(cx)->compartment_; -} - -inline JS::Zone* -GetContextZone(const JSContext* cx) -{ - return ContextFriendFields::get(cx)->zone_; -} - -} /* namespace js */ - -MOZ_BEGIN_EXTERN_C - -// Defined in NSPR prio.h. -typedef struct PRFileDesc PRFileDesc; - -MOZ_END_EXTERN_C - -#endif /* jspubtd_h */ diff --git a/ios/include/spidermonkey/jstypes.h b/ios/include/spidermonkey/jstypes.h deleted file mode 100644 index 914674ab..00000000 --- a/ios/include/spidermonkey/jstypes.h +++ /dev/null @@ -1,219 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: jstypes.h -** Description: Definitions of NSPR's basic types -** -** Prototypes and macros used to make up for deficiencies in ANSI environments -** that we have found. -** -** Since we do not wrap and all the other standard headers, authors -** of portable code will not know in general that they need these definitions. -** Instead of requiring these authors to find the dependent uses in their code -** and take the following steps only in those C files, we take steps once here -** for all C files. -**/ - -#ifndef jstypes_h -#define jstypes_h - -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/Types.h" - -// jstypes.h is (or should be!) included by every file in SpiderMonkey. -// js-config.h and jsversion.h also should be included by every file. -// So include them here. -// XXX: including them in js/RequiredDefines.h should be a better option, since -// that is by definition the header file that should be included in all -// SpiderMonkey code. However, Gecko doesn't do this! See bug 909576. -#include "js-config.h" -#include "jsversion.h" - -/*********************************************************************** -** MACROS: JS_EXTERN_API -** JS_EXPORT_API -** DESCRIPTION: -** These are only for externally visible routines and globals. For -** internal routines, just use "extern" for type checking and that -** will not export internal cross-file or forward-declared symbols. -** Define a macro for declaring procedures return types. We use this to -** deal with windoze specific type hackery for DLL definitions. Use -** JS_EXTERN_API when the prototype for the method is declared. Use -** JS_EXPORT_API for the implementation of the method. -** -** Example: -** in dowhim.h -** JS_EXTERN_API( void ) DoWhatIMean( void ); -** in dowhim.c -** JS_EXPORT_API( void ) DoWhatIMean( void ) { return; } -** -** -***********************************************************************/ - -#define JS_EXTERN_API(type) extern MOZ_EXPORT type -#define JS_EXPORT_API(type) MOZ_EXPORT type -#define JS_EXPORT_DATA(type) MOZ_EXPORT type -#define JS_IMPORT_API(type) MOZ_IMPORT_API type -#define JS_IMPORT_DATA(type) MOZ_IMPORT_DATA type - -/* - * The linkage of JS API functions differs depending on whether the file is - * used within the JS library or not. Any source file within the JS - * interpreter should define EXPORT_JS_API whereas any client of the library - * should not. STATIC_JS_API is used to build JS as a static library. - */ -#if defined(STATIC_JS_API) -# define JS_PUBLIC_API(t) t -# define JS_PUBLIC_DATA(t) t -# define JS_FRIEND_API(t) t -# define JS_FRIEND_DATA(t) t -#elif defined(EXPORT_JS_API) || defined(STATIC_EXPORTABLE_JS_API) -# define JS_PUBLIC_API(t) MOZ_EXPORT t -# define JS_PUBLIC_DATA(t) MOZ_EXPORT t -# define JS_FRIEND_API(t) MOZ_EXPORT t -# define JS_FRIEND_DATA(t) MOZ_EXPORT t -#else -# define JS_PUBLIC_API(t) MOZ_IMPORT_API t -# define JS_PUBLIC_DATA(t) MOZ_IMPORT_DATA t -# define JS_FRIEND_API(t) MOZ_IMPORT_API t -# define JS_FRIEND_DATA(t) MOZ_IMPORT_DATA t -#endif - -#if defined(_MSC_VER) && defined(_M_IX86) -#define JS_FASTCALL __fastcall -#elif defined(__GNUC__) && defined(__i386__) -#define JS_FASTCALL __attribute__((fastcall)) -#else -#define JS_FASTCALL -#define JS_NO_FASTCALL -#endif - -/*********************************************************************** -** MACROS: JS_BEGIN_MACRO -** JS_END_MACRO -** DESCRIPTION: -** Macro body brackets so that macros with compound statement definitions -** behave syntactically more like functions when called. -***********************************************************************/ -#define JS_BEGIN_MACRO do { - -#if defined(_MSC_VER) -# define JS_END_MACRO \ - } __pragma(warning(push)) __pragma(warning(disable:4127)) \ - while (0) __pragma(warning(pop)) -#else -# define JS_END_MACRO } while (0) -#endif - -/*********************************************************************** -** MACROS: JS_BIT -** JS_BITMASK -** DESCRIPTION: -** Bit masking macros. XXX n must be <= 31 to be portable -***********************************************************************/ -#define JS_BIT(n) ((uint32_t)1 << (n)) -#define JS_BITMASK(n) (JS_BIT(n) - 1) - -/*********************************************************************** -** MACROS: JS_HOWMANY -** JS_ROUNDUP -** DESCRIPTION: -** Commonly used macros for operations on compatible types. -***********************************************************************/ -#define JS_HOWMANY(x,y) (((x)+(y)-1)/(y)) -#define JS_ROUNDUP(x,y) (JS_HOWMANY(x,y)*(y)) - -#include "jscpucfg.h" - -/* - * Define JS_64BIT iff we are building in an environment with 64-bit - * addresses. - */ -#ifdef _MSC_VER -# if defined(_M_X64) || defined(_M_AMD64) -# define JS_64BIT -# endif -#elif defined(__GNUC__) -/* Additional GCC defines are when running on Solaris, AIX, and HPUX */ -# if defined(__x86_64__) || defined(__sparcv9) || \ - defined(__64BIT__) || defined(__LP64__) -# define JS_64BIT -# endif -#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Sun Studio C/C++ */ -# if defined(__x86_64) || defined(__sparcv9) -# define JS_64BIT -# endif -#elif defined(__xlc__) || defined(__xlC__) /* IBM XL C/C++ */ -# if defined(__64BIT__) -# define JS_64BIT -# endif -#elif defined(__HP_cc) || defined(__HP_aCC) /* HP-UX cc/aCC */ -# if defined(__LP64__) -# define JS_64BIT -# endif -#else -# error "Implement me" -#endif - -/*********************************************************************** -** MACROS: JS_ARRAY_LENGTH -** JS_ARRAY_END -** DESCRIPTION: -** Macros to get the number of elements and the pointer to one past the -** last element of a C array. Use them like this: -** -** char16_t buf[10]; -** JSString* str; -** ... -** for (char16_t* s = buf; s != JS_ARRAY_END(buf); ++s) *s = ...; -** ... -** str = JS_NewStringCopyN(cx, buf, JS_ARRAY_LENGTH(buf)); -** ... -** -***********************************************************************/ - -#define JS_ARRAY_LENGTH(array) (sizeof (array) / sizeof (array)[0]) -#define JS_ARRAY_END(array) ((array) + JS_ARRAY_LENGTH(array)) - -#define JS_BITS_PER_BYTE 8 -#define JS_BITS_PER_BYTE_LOG2 3 - -#if defined(JS_64BIT) -# define JS_BITS_PER_WORD 64 -#else -# define JS_BITS_PER_WORD 32 -#endif - -/*********************************************************************** -** MACROS: JS_FUNC_TO_DATA_PTR -** JS_DATA_TO_FUNC_PTR -** DESCRIPTION: -** Macros to convert between function and data pointers of the same -** size. Use them like this: -** -** JSGetterOp nativeGetter; -** JSObject* scriptedGetter; -** ... -** scriptedGetter = JS_FUNC_TO_DATA_PTR(JSObject*, nativeGetter); -** ... -** nativeGetter = JS_DATA_TO_FUNC_PTR(JSGetterOp, scriptedGetter); -** -***********************************************************************/ - -#define JS_FUNC_TO_DATA_PTR(type, fun) (mozilla::BitwiseCast(fun)) -#define JS_DATA_TO_FUNC_PTR(type, ptr) (mozilla::BitwiseCast(ptr)) - -#ifdef __GNUC__ -# define JS_EXTENSION __extension__ -# define JS_EXTENSION_(s) __extension__ ({ s; }) -#else -# define JS_EXTENSION -# define JS_EXTENSION_(s) s -#endif - -#endif /* jstypes_h */ diff --git a/ios/include/spidermonkey/jsversion.h b/ios/include/spidermonkey/jsversion.h deleted file mode 100644 index 8bdfe47b..00000000 --- a/ios/include/spidermonkey/jsversion.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsversion_h -#define jsversion_h - -/* - * JS Capability Macros. - */ -#define JS_HAS_STR_HTML_HELPERS 1 /* (no longer used) */ -#define JS_HAS_OBJ_PROTO_PROP 1 /* has o.__proto__ etc. */ -#define JS_HAS_OBJ_WATCHPOINT 1 /* has o.watch and o.unwatch */ -#define JS_HAS_TOSOURCE 1 /* has Object/Array toSource method */ -#define JS_HAS_CATCH_GUARD 1 /* has exception handling catch guard */ -#define JS_HAS_UNEVAL 1 /* has uneval() top-level function */ -#define JS_HAS_CONST 1 /* (no longer used) */ -#define JS_HAS_FUN_EXPR_STMT 1 /* (no longer used) */ -#define JS_HAS_FOR_EACH_IN 1 /* has for each (lhs in iterable) */ -#define JS_HAS_GENERATORS 1 /* (no longer used) */ -#define JS_HAS_BLOCK_SCOPE 1 /* (no longer used) */ -#define JS_HAS_DESTRUCTURING 2 /* (no longer used) */ -#define JS_HAS_GENERATOR_EXPRS 1 /* (no longer used) */ -#define JS_HAS_EXPR_CLOSURES 1 /* has function (formals) listexpr */ - -/* (no longer used) */ -#define JS_HAS_NEW_GLOBAL_OBJECT 1 - -/* (no longer used) */ -#define JS_HAS_DESTRUCTURING_SHORTHAND (JS_HAS_DESTRUCTURING == 2) - -/* - * Feature for Object.prototype.__{define,lookup}{G,S}etter__ legacy support; - * support likely to be made opt-in at some future time. - */ -#define JS_OLD_GETTER_SETTER_METHODS 1 - -#endif /* jsversion_h */ diff --git a/ios/include/spidermonkey/jswrapper.h b/ios/include/spidermonkey/jswrapper.h deleted file mode 100644 index 9b14c59e..00000000 --- a/ios/include/spidermonkey/jswrapper.h +++ /dev/null @@ -1,382 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jswrapper_h -#define jswrapper_h - -#include "mozilla/Attributes.h" - -#include "js/Proxy.h" - -namespace js { - -/* - * Helper for Wrapper::New default options. - * - * Callers of Wrapper::New() who wish to specify a prototype for the created - * Wrapper, *MUST* construct a WrapperOptions with a JSContext. - */ -class MOZ_STACK_CLASS WrapperOptions : public ProxyOptions { - public: - WrapperOptions() : ProxyOptions(false), - proto_() - {} - - explicit WrapperOptions(JSContext* cx) : ProxyOptions(false), - proto_() - { - proto_.emplace(cx); - } - - inline JSObject* proto() const; - WrapperOptions& setProto(JSObject* protoArg) { - MOZ_ASSERT(proto_); - *proto_ = protoArg; - return *this; - } - - private: - mozilla::Maybe proto_; -}; - -/* - * A wrapper is a proxy with a target object to which it generally forwards - * operations, but may restrict access to certain operations or augment those - * operations in various ways. - * - * A wrapper can be "unwrapped" in C++, exposing the underlying object. - * Callers should be careful to avoid unwrapping security wrappers in the wrong - * context. - * - * Important: If you add a method implementation here, you probably also need - * to add an override in CrossCompartmentWrapper. If you don't, you risk - * compartment mismatches. See bug 945826 comment 0. - */ -class JS_FRIEND_API(Wrapper) : public BaseProxyHandler -{ - unsigned mFlags; - - public: - explicit constexpr Wrapper(unsigned aFlags, bool aHasPrototype = false, - bool aHasSecurityPolicy = false) - : BaseProxyHandler(&family, aHasPrototype, aHasSecurityPolicy), - mFlags(aFlags) - { } - - virtual bool finalizeInBackground(const Value& priv) const override; - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const override; - virtual bool defineProperty(JSContext* cx, HandleObject proxy, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const override; - virtual bool delete_(JSContext* cx, HandleObject proxy, HandleId id, - ObjectOpResult& result) const override; - virtual bool enumerate(JSContext* cx, HandleObject proxy, - MutableHandleObject objp) const override; - virtual bool getPrototype(JSContext* cx, HandleObject proxy, - MutableHandleObject protop) const override; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const override; - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, - MutableHandleObject protop) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, - bool* succeeded) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject proxy, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject proxy, bool* extensible) const override; - virtual bool has(JSContext* cx, HandleObject proxy, HandleId id, - bool* bp) const override; - virtual bool get(JSContext* cx, HandleObject proxy, HandleValue receiver, - HandleId id, MutableHandleValue vp) const override; - virtual bool set(JSContext* cx, HandleObject proxy, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const override; - virtual bool call(JSContext* cx, HandleObject proxy, const CallArgs& args) const override; - virtual bool construct(JSContext* cx, HandleObject proxy, const CallArgs& args) const override; - - /* SpiderMonkey extensions. */ - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const override; - virtual bool hasOwn(JSContext* cx, HandleObject proxy, HandleId id, - bool* bp) const override; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const override; - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const override; - virtual bool hasInstance(JSContext* cx, HandleObject proxy, MutableHandleValue v, - bool* bp) const override; - virtual bool getBuiltinClass(JSContext* cx, HandleObject proxy, ESClass* cls) const override; - virtual bool isArray(JSContext* cx, HandleObject proxy, - JS::IsArrayAnswer* answer) const override; - virtual const char* className(JSContext* cx, HandleObject proxy) const override; - virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, - unsigned indent) const override; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, - RegExpGuard* g) const override; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, - MutableHandleValue vp) const override; - virtual bool isCallable(JSObject* obj) const override; - virtual bool isConstructor(JSObject* obj) const override; - virtual JSObject* weakmapKeyDelegate(JSObject* proxy) const override; - - public: - using BaseProxyHandler::Action; - - enum Flags { - CROSS_COMPARTMENT = 1 << 0, - LAST_USED_FLAG = CROSS_COMPARTMENT - }; - - static JSObject* New(JSContext* cx, JSObject* obj, const Wrapper* handler, - const WrapperOptions& options = WrapperOptions()); - - static JSObject* Renew(JSContext* cx, JSObject* existing, JSObject* obj, const Wrapper* handler); - - static const Wrapper* wrapperHandler(JSObject* wrapper); - - static JSObject* wrappedObject(JSObject* wrapper); - - unsigned flags() const { - return mFlags; - } - - static const char family; - static const Wrapper singleton; - static const Wrapper singletonWithPrototype; - - static JSObject* defaultProto; -}; - -inline JSObject* -WrapperOptions::proto() const -{ - return proto_ ? *proto_ : Wrapper::defaultProto; -} - -/* Base class for all cross compartment wrapper handlers. */ -class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper -{ - public: - explicit constexpr CrossCompartmentWrapper(unsigned aFlags, bool aHasPrototype = false, - bool aHasSecurityPolicy = false) - : Wrapper(CROSS_COMPARTMENT | aFlags, aHasPrototype, aHasSecurityPolicy) - { } - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool delete_(JSContext* cx, HandleObject wrapper, HandleId id, - ObjectOpResult& result) const override; - virtual bool enumerate(JSContext* cx, HandleObject wrapper, MutableHandleObject objp) const override; - virtual bool getPrototype(JSContext* cx, HandleObject proxy, - MutableHandleObject protop) const override; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const override; - - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, - MutableHandleObject protop) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, - bool* succeeded) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; - virtual bool has(JSContext* cx, HandleObject wrapper, HandleId id, bool* bp) const override; - virtual bool get(JSContext* cx, HandleObject wrapper, HandleValue receiver, - HandleId id, MutableHandleValue vp) const override; - virtual bool set(JSContext* cx, HandleObject wrapper, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const override; - virtual bool call(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - virtual bool construct(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - - /* SpiderMonkey extensions. */ - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool hasOwn(JSContext* cx, HandleObject wrapper, HandleId id, bool* bp) const override; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const override; - virtual bool hasInstance(JSContext* cx, HandleObject wrapper, MutableHandleValue v, - bool* bp) const override; - virtual const char* className(JSContext* cx, HandleObject proxy) const override; - virtual JSString* fun_toString(JSContext* cx, HandleObject wrapper, - unsigned indent) const override; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const override; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const override; - - // Allocate CrossCompartmentWrappers in the nursery. - virtual bool canNurseryAllocate() const override { return true; } - - static const CrossCompartmentWrapper singleton; - static const CrossCompartmentWrapper singletonWithPrototype; -}; - -class JS_FRIEND_API(OpaqueCrossCompartmentWrapper) : public CrossCompartmentWrapper -{ - public: - explicit constexpr OpaqueCrossCompartmentWrapper() : CrossCompartmentWrapper(0) - { } - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool delete_(JSContext* cx, HandleObject wrapper, HandleId id, - ObjectOpResult& result) const override; - virtual bool enumerate(JSContext* cx, HandleObject wrapper, - MutableHandleObject objp) const override; - virtual bool getPrototype(JSContext* cx, HandleObject wrapper, - MutableHandleObject protop) const override; - virtual bool setPrototype(JSContext* cx, HandleObject wrapper, HandleObject proto, - ObjectOpResult& result) const override; - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject wrapper, bool* isOrdinary, - MutableHandleObject protop) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject wrapper, - bool* succeeded) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; - virtual bool has(JSContext* cx, HandleObject wrapper, HandleId id, - bool* bp) const override; - virtual bool get(JSContext* cx, HandleObject wrapper, HandleValue receiver, - HandleId id, MutableHandleValue vp) const override; - virtual bool set(JSContext* cx, HandleObject wrapper, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const override; - virtual bool call(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - virtual bool construct(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - - /* SpiderMonkey extensions. */ - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool hasOwn(JSContext* cx, HandleObject wrapper, HandleId id, - bool* bp) const override; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool getBuiltinClass(JSContext* cx, HandleObject wrapper, ESClass* cls) const override; - virtual bool isArray(JSContext* cx, HandleObject obj, - JS::IsArrayAnswer* answer) const override; - virtual const char* className(JSContext* cx, HandleObject wrapper) const override; - virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, unsigned indent) const override; - - static const OpaqueCrossCompartmentWrapper singleton; -}; - -/* - * Base class for security wrappers. A security wrapper is potentially hiding - * all or part of some wrapped object thus SecurityWrapper defaults to denying - * access to the wrappee. This is the opposite of Wrapper which tries to be - * completely transparent. - * - * NB: Currently, only a few ProxyHandler operations are overridden to deny - * access, relying on derived SecurityWrapper to block access when necessary. - */ -template -class JS_FRIEND_API(SecurityWrapper) : public Base -{ - public: - explicit constexpr SecurityWrapper(unsigned flags, bool hasPrototype = false) - : Base(flags, hasPrototype, /* hasSecurityPolicy = */ true) - { } - - virtual bool enter(JSContext* cx, HandleObject wrapper, HandleId id, Wrapper::Action act, - bool* bp) const override; - - virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, - ObjectOpResult& result) const override; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, bool* succeeded) const override; - - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const override; - virtual bool getBuiltinClass(JSContext* cx, HandleObject wrapper, ESClass* cls) const override; - virtual bool isArray(JSContext* cx, HandleObject wrapper, JS::IsArrayAnswer* answer) const override; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const override; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const override; - - // Allow isCallable and isConstructor. They used to be class-level, and so could not be guarded - // against. - - virtual bool watch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, - JS::HandleObject callable) const override; - virtual bool unwatch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id) const override; - - /* - * Allow our subclasses to select the superclass behavior they want without - * needing to specify an exact superclass. - */ - typedef Base Permissive; - typedef SecurityWrapper Restrictive; -}; - -typedef SecurityWrapper CrossCompartmentSecurityWrapper; - -extern JSObject* -TransparentObjectWrapper(JSContext* cx, HandleObject existing, HandleObject obj); - -inline bool -IsWrapper(JSObject* obj) -{ - return IsProxy(obj) && GetProxyHandler(obj)->family() == &Wrapper::family; -} - -// Given a JSObject, returns that object stripped of wrappers. If -// stopAtWindowProxy is true, then this returns the WindowProxy if it was -// previously wrapped. Otherwise, this returns the first object for -// which JSObject::isWrapper returns false. -JS_FRIEND_API(JSObject*) -UncheckedUnwrap(JSObject* obj, bool stopAtWindowProxy = true, unsigned* flagsp = nullptr); - -// Given a JSObject, returns that object stripped of wrappers. At each stage, -// the security wrapper has the opportunity to veto the unwrap. If -// stopAtWindowProxy is true, then this returns the WindowProxy if it was -// previously wrapped. -JS_FRIEND_API(JSObject*) -CheckedUnwrap(JSObject* obj, bool stopAtWindowProxy = true); - -// Unwrap only the outermost security wrapper, with the same semantics as -// above. This is the checked version of Wrapper::wrappedObject. -JS_FRIEND_API(JSObject*) -UnwrapOneChecked(JSObject* obj, bool stopAtWindowProxy = true); - -JS_FRIEND_API(bool) -IsCrossCompartmentWrapper(JSObject* obj); - -void -NukeCrossCompartmentWrapper(JSContext* cx, JSObject* wrapper); - -void -RemapWrapper(JSContext* cx, JSObject* wobj, JSObject* newTarget); - -JS_FRIEND_API(bool) -RemapAllWrappersForObject(JSContext* cx, JSObject* oldTarget, - JSObject* newTarget); - -// API to recompute all cross-compartment wrappers whose source and target -// match the given filters. -JS_FRIEND_API(bool) -RecomputeWrappers(JSContext* cx, const CompartmentFilter& sourceFilter, - const CompartmentFilter& targetFilter); - -} /* namespace js */ - -#endif /* jswrapper_h */ diff --git a/ios/include/spidermonkey/mozilla/Alignment.h b/ios/include/spidermonkey/mozilla/Alignment.h deleted file mode 100644 index 4fcda4f3..00000000 --- a/ios/include/spidermonkey/mozilla/Alignment.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Functionality related to memory alignment. */ - -#ifndef mozilla_Alignment_h -#define mozilla_Alignment_h - -#include "mozilla/Attributes.h" -#include -#include - -namespace mozilla { - -/* - * This class, and the corresponding macro MOZ_ALIGNOF, figures out how many - * bytes of alignment a given type needs. - */ -template -class AlignmentFinder -{ - struct Aligner - { - char mChar; - T mT; - }; - -public: - static const size_t alignment = sizeof(Aligner) - sizeof(T); -}; - -#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment - -/* - * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. - * - * For instance, - * - * MOZ_ALIGNED_DECL(char arr[2], 8); - * - * will declare a two-character array |arr| aligned to 8 bytes. - */ - -#if defined(__GNUC__) -# define MOZ_ALIGNED_DECL(_type, _align) \ - _type __attribute__((aligned(_align))) -#elif defined(_MSC_VER) -# define MOZ_ALIGNED_DECL(_type, _align) \ - __declspec(align(_align)) _type -#else -# warning "We don't know how to align variables on this compiler." -# define MOZ_ALIGNED_DECL(_type, _align) _type -#endif - -/* - * AlignedElem is a structure whose alignment is guaranteed to be at least N - * bytes. - * - * We support 1, 2, 4, 8, and 16-bit alignment. - */ -template -struct AlignedElem; - -/* - * We have to specialize this template because GCC doesn't like - * __attribute__((aligned(foo))) where foo is a template parameter. - */ - -template<> -struct AlignedElem<1> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 1); -}; - -template<> -struct AlignedElem<2> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 2); -}; - -template<> -struct AlignedElem<4> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 4); -}; - -template<> -struct AlignedElem<8> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 8); -}; - -template<> -struct AlignedElem<16> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 16); -}; - -/* - * This utility pales in comparison to Boost's aligned_storage. The utility - * simply assumes that uint64_t is enough alignment for anyone. This may need - * to be extended one day... - * - * As an important side effect, pulling the storage into this template is - * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving - * false negatives when we cast from the char buffer to whatever type we've - * constructed using the bytes. - */ -template -struct AlignedStorage -{ - union U - { - char mBytes[Nbytes]; - uint64_t mDummy; - } u; - - const void* addr() const { return u.mBytes; } - void* addr() { return u.mBytes; } - - AlignedStorage() = default; - - // AlignedStorage is non-copyable: the default copy constructor violates - // strict aliasing rules, per bug 1269319. - AlignedStorage(const AlignedStorage&) = delete; - void operator=(const AlignedStorage&) = delete; -}; - -template -struct MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS AlignedStorage2 -{ - union U - { - char mBytes[sizeof(T)]; - uint64_t mDummy; - } u; - - const T* addr() const { return reinterpret_cast(u.mBytes); } - T* addr() { return static_cast(static_cast(u.mBytes)); } - - AlignedStorage2() = default; - - // AlignedStorage2 is non-copyable: the default copy constructor violates - // strict aliasing rules, per bug 1269319. - AlignedStorage2(const AlignedStorage2&) = delete; - void operator=(const AlignedStorage2&) = delete; -}; - -} /* namespace mozilla */ - -#endif /* mozilla_Alignment_h */ diff --git a/ios/include/spidermonkey/mozilla/AllocPolicy.h b/ios/include/spidermonkey/mozilla/AllocPolicy.h deleted file mode 100644 index 81f62b03..00000000 --- a/ios/include/spidermonkey/mozilla/AllocPolicy.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * An allocation policy concept, usable for structures and algorithms to - * control how memory is allocated and how failures are handled. - */ - -#ifndef mozilla_AllocPolicy_h -#define mozilla_AllocPolicy_h - -#include "mozilla/Attributes.h" -#include "mozilla/TemplateLib.h" - -#include -#include - -namespace mozilla { - -/* - * Allocation policies are used to implement the standard allocation behaviors - * in a customizable way. Additionally, custom behaviors may be added to these - * behaviors, such as additionally reporting an error through an out-of-band - * mechanism when OOM occurs. The concept modeled here is as follows: - * - * - public copy constructor, assignment, destructor - * - template T* maybe_pod_malloc(size_t) - * Fallible, but doesn't report an error on OOM. - * - template T* maybe_pod_calloc(size_t) - * Fallible, but doesn't report an error on OOM. - * - template T* maybe_pod_realloc(T*, size_t, size_t) - * Fallible, but doesn't report an error on OOM. The old allocation - * size is passed in, in addition to the new allocation size requested. - * - template T* pod_malloc(size_t) - * Responsible for OOM reporting when null is returned. - * - template T* pod_calloc(size_t) - * Responsible for OOM reporting when null is returned. - * - template T* pod_realloc(T*, size_t, size_t) - * Responsible for OOM reporting when null is returned. The old allocation - * size is passed in, in addition to the new allocation size requested. - * - void free_(void*) - * - void reportAllocOverflow() const - * Called on allocation overflow (that is, an allocation implicitly tried - * to allocate more than the available memory space -- think allocating an - * array of large-size objects, where N * size overflows) before null is - * returned. - * - bool checkSimulatedOOM() const - * Some clients generally allocate memory yet in some circumstances won't - * need to do so. For example, appending to a vector with a small amount of - * inline storage generally allocates memory, but no allocation occurs - * unless appending exceeds inline storage. But for testing purposes, it - * can be useful to treat *every* operation as allocating. - * Clients (such as this hypothetical append method implementation) should - * call this method in situations that don't allocate, but could generally, - * to support this. The default behavior should return true; more - * complicated behavior might be to return false only after a certain - * number of allocations-or-check-simulated-OOMs (coordinating with the - * other AllocPolicy methods) have occurred. - * - * mfbt provides (and typically uses by default) only MallocAllocPolicy, which - * does nothing more than delegate to the malloc/alloc/free functions. - */ - -/* - * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no - * extra behaviors. - */ -class MallocAllocPolicy -{ -public: - template - T* maybe_pod_malloc(size_t aNumElems) - { - if (aNumElems & mozilla::tl::MulOverflowMask::value) { - return nullptr; - } - return static_cast(malloc(aNumElems * sizeof(T))); - } - - template - T* maybe_pod_calloc(size_t aNumElems) - { - return static_cast(calloc(aNumElems, sizeof(T))); - } - - template - T* maybe_pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - if (aNewSize & mozilla::tl::MulOverflowMask::value) { - return nullptr; - } - return static_cast(realloc(aPtr, aNewSize * sizeof(T))); - } - - template - T* pod_malloc(size_t aNumElems) - { - return maybe_pod_malloc(aNumElems); - } - - template - T* pod_calloc(size_t aNumElems) - { - return maybe_pod_calloc(aNumElems); - } - - template - T* pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - return maybe_pod_realloc(aPtr, aOldSize, aNewSize); - } - - void free_(void* aPtr) - { - free(aPtr); - } - - void reportAllocOverflow() const - { - } - - MOZ_MUST_USE bool checkSimulatedOOM() const - { - return true; - } -}; - -} // namespace mozilla - -#endif /* mozilla_AllocPolicy_h */ diff --git a/ios/include/spidermonkey/mozilla/AlreadyAddRefed.h b/ios/include/spidermonkey/mozilla/AlreadyAddRefed.h deleted file mode 100644 index 0d7b0cae..00000000 --- a/ios/include/spidermonkey/mozilla/AlreadyAddRefed.h +++ /dev/null @@ -1,147 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Typed temporary pointers for reference-counted smart pointers. */ - -#ifndef AlreadyAddRefed_h -#define AlreadyAddRefed_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" - -namespace mozilla { - -struct unused_t; - -} // namespace mozilla - -/** - * already_AddRefed cooperates with reference counting smart pointers to enable - * you to assign in a pointer _without_ |AddRef|ing it. You might want to use - * this as a return type from a function that returns an already |AddRef|ed - * pointer. - * - * TODO Move already_AddRefed to namespace mozilla. This has not yet been done - * because of the sheer number of usages of already_AddRefed. - */ -template -struct MOZ_MUST_USE_TYPE MOZ_NON_AUTOABLE already_AddRefed -{ - /* - * We want to allow returning nullptr from functions returning - * already_AddRefed, for simplicity. But we also don't want to allow - * returning raw T*, instead preferring creation of already_AddRefed from - * a reference counting smart pointer. - * - * We address the latter requirement by making the (T*) constructor explicit. - * But |return nullptr| won't consider an explicit constructor, so we need - * another constructor to handle it. Plain old (decltype(nullptr)) doesn't - * cut it, because if nullptr is emulated as __null (with type int or long), - * passing nullptr to an int/long parameter triggers compiler warnings. We - * need a type that no one can pass accidentally; a pointer-to-member-function - * (where no such function exists) does the trick nicely. - * - * That handles the return-value case. What about for locals, argument types, - * and so on? |already_AddRefed(nullptr)| considers both overloads (and - * the (already_AddRefed&&) overload as well!), so there's an ambiguity. - * We can target true nullptr using decltype(nullptr), but we can't target - * emulated nullptr the same way, because passing __null to an int/long - * parameter triggers compiler warnings. So just give up on this, and provide - * this behavior through the default constructor. - * - * We can revert to simply explicit (T*) and implicit (decltype(nullptr)) when - * nullptr no longer needs to be emulated to support the ancient b2g compiler. - * (The () overload could also be removed, if desired, if we changed callers.) - */ - already_AddRefed() : mRawPtr(nullptr) {} - - // The return and argument types here are arbitrarily selected so no - // corresponding member function exists. - typedef void (already_AddRefed::* MatchNullptr)(double, float); - MOZ_IMPLICIT already_AddRefed(MatchNullptr aRawPtr) : mRawPtr(nullptr) {} - - explicit already_AddRefed(T* aRawPtr) : mRawPtr(aRawPtr) {} - - // Disallow copy constructor and copy assignment operator: move semantics used instead. - already_AddRefed(const already_AddRefed& aOther) = delete; - already_AddRefed& operator=(const already_AddRefed& aOther) = delete; - - already_AddRefed(already_AddRefed&& aOther) : mRawPtr(aOther.take()) {} - - already_AddRefed& operator=(already_AddRefed&& aOther) - { - mRawPtr = aOther.take(); - return *this; - } - - /** - * This helper is useful in cases like - * - * already_AddRefed - * Foo() - * { - * RefPtr x = ...; - * return x.forget(); - * } - * - * The autoconversion allows one to omit the idiom - * - * RefPtr y = x.forget(); - * return y.forget(); - * - * Note that nsRefPtr is the XPCOM reference counting smart pointer class. - */ - template - MOZ_IMPLICIT already_AddRefed(already_AddRefed&& aOther) : mRawPtr(aOther.take()) {} - - ~already_AddRefed() { MOZ_ASSERT(!mRawPtr); } - - // Specialize the unused operator<< for already_AddRefed, to allow - // nsCOMPtr foo; - // Unused << foo.forget(); - // Note that nsCOMPtr is the XPCOM reference counting smart pointer class. - friend void operator<<(const mozilla::unused_t& aUnused, - const already_AddRefed& aRhs) - { - auto mutableAlreadyAddRefed = const_cast*>(&aRhs); - aUnused << mutableAlreadyAddRefed->take(); - } - - MOZ_MUST_USE T* take() - { - T* rawPtr = mRawPtr; - mRawPtr = nullptr; - return rawPtr; - } - - /** - * This helper provides a static_cast replacement for already_AddRefed, so - * if you have - * - * already_AddRefed F(); - * - * you can write - * - * already_AddRefed - * G() - * { - * return F().downcast(); - * } - */ - template - already_AddRefed downcast() - { - U* tmp = static_cast(mRawPtr); - mRawPtr = nullptr; - return already_AddRefed(tmp); - } - -private: - T* MOZ_OWNING_REF mRawPtr; -}; - -#endif // AlreadyAddRefed_h diff --git a/ios/include/spidermonkey/mozilla/Array.h b/ios/include/spidermonkey/mozilla/Array.h deleted file mode 100644 index 72b89ede..00000000 --- a/ios/include/spidermonkey/mozilla/Array.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A compile-time constant-length array with bounds-checking assertions. */ - -#ifndef mozilla_Array_h -#define mozilla_Array_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/ReverseIterator.h" - -#include - -namespace mozilla { - -template -class Array -{ - T mArr[Length]; - -public: - Array() {} - - template - MOZ_IMPLICIT Array(Args&&... aArgs) - : mArr{mozilla::Forward(aArgs)...} - { - static_assert(sizeof...(aArgs) == Length, - "The number of arguments should be equal to the template parameter Length"); - } - - T& operator[](size_t aIndex) - { - MOZ_ASSERT(aIndex < Length); - return mArr[aIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(aIndex < Length); - return mArr[aIndex]; - } - - typedef T* iterator; - typedef const T* const_iterator; - typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; - - // Methods for range-based for loops. - iterator begin() { return mArr; } - const_iterator begin() const { return mArr; } - const_iterator cbegin() const { return begin(); } - iterator end() { return mArr + Length; } - const_iterator end() const { return mArr + Length; } - const_iterator cend() const { return end(); } - - // Methods for reverse iterating. - reverse_iterator rbegin() { return reverse_iterator(end()); } - const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() { return reverse_iterator(begin()); } - const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } - const_reverse_iterator crend() const { return rend(); } -}; - -template -class Array -{ -public: - T& operator[](size_t aIndex) - { - MOZ_CRASH("indexing into zero-length array"); - } - - const T& operator[](size_t aIndex) const - { - MOZ_CRASH("indexing into zero-length array"); - } -}; - -} /* namespace mozilla */ - -#endif /* mozilla_Array_h */ diff --git a/ios/include/spidermonkey/mozilla/ArrayUtils.h b/ios/include/spidermonkey/mozilla/ArrayUtils.h deleted file mode 100644 index 50236ccb..00000000 --- a/ios/include/spidermonkey/mozilla/ArrayUtils.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements various helper functions related to arrays. - */ - -#ifndef mozilla_ArrayUtils_h -#define mozilla_ArrayUtils_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#include - -#ifdef __cplusplus - -#include "mozilla/Alignment.h" -#include "mozilla/Array.h" -#include "mozilla/EnumeratedArray.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/* - * Safely subtract two pointers when it is known that aEnd >= aBegin, yielding a - * size_t result. - * - * Ordinary pointer subtraction yields a ptrdiff_t result, which, being signed, - * has insufficient range to express the distance between pointers at opposite - * ends of the address space. Furthermore, most compilers use ptrdiff_t to - * represent the intermediate byte address distance, before dividing by - * sizeof(T); if that intermediate result overflows, they'll produce results - * with the wrong sign even when the correct scaled distance would fit in a - * ptrdiff_t. - */ -template -MOZ_ALWAYS_INLINE size_t -PointerRangeSize(T* aBegin, T* aEnd) -{ - MOZ_ASSERT(aEnd >= aBegin); - return (size_t(aEnd) - size_t(aBegin)) / sizeof(T); -} - -/* - * Compute the length of an array with constant length. (Use of this method - * with a non-array pointer will not compile.) - * - * Beware of the implicit trailing '\0' when using this with string constants. - */ -template -constexpr size_t -ArrayLength(T (&aArr)[N]) -{ - return N; -} - -template -constexpr size_t -ArrayLength(const Array& aArr) -{ - return N; -} - -template -constexpr size_t -ArrayLength(const EnumeratedArray& aArr) -{ - return size_t(N); -} - -/* - * Compute the address one past the last element of a constant-length array. - * - * Beware of the implicit trailing '\0' when using this with string constants. - */ -template -constexpr T* -ArrayEnd(T (&aArr)[N]) -{ - return aArr + ArrayLength(aArr); -} - -template -constexpr T* -ArrayEnd(Array& aArr) -{ - return &aArr[0] + ArrayLength(aArr); -} - -template -constexpr const T* -ArrayEnd(const Array& aArr) -{ - return &aArr[0] + ArrayLength(aArr); -} - -namespace detail { - -template::value>> -struct AlignedChecker -{ - static void - test(const Pointee* aPtr) - { - MOZ_ASSERT((uintptr_t(aPtr) % MOZ_ALIGNOF(AlignType)) == 0, - "performing a range-check with a misaligned pointer"); - } -}; - -template -struct AlignedChecker -{ - static void - test(const Pointee* aPtr) - { - } -}; - -} // namespace detail - -/** - * Determines whether |aPtr| points at an object in the range [aBegin, aEnd). - * - * |aPtr| must have the same alignment as |aBegin| and |aEnd|. This usually - * should be achieved by ensuring |aPtr| points at a |U|, not just that it - * points at a |T|. - * - * It is a usage error for any argument to be misaligned. - * - * It's okay for T* to be void*, and if so U* may also be void*. In the latter - * case no argument is required to be aligned (obviously, as void* implies no - * particular alignment). - */ -template -inline typename EnableIf::value || - IsBaseOf::value || - IsVoid::value, - bool>::Type -IsInRange(const T* aPtr, const U* aBegin, const U* aEnd) -{ - MOZ_ASSERT(aBegin <= aEnd); - detail::AlignedChecker::test(aPtr); - detail::AlignedChecker::test(aBegin); - detail::AlignedChecker::test(aEnd); - return aBegin <= reinterpret_cast(aPtr) && - reinterpret_cast(aPtr) < aEnd; -} - -/** - * Convenience version of the above method when the valid range is specified as - * uintptr_t values. As above, |aPtr| must be aligned, and |aBegin| and |aEnd| - * must be aligned with respect to |T|. - */ -template -inline bool -IsInRange(const T* aPtr, uintptr_t aBegin, uintptr_t aEnd) -{ - return IsInRange(aPtr, - reinterpret_cast(aBegin), - reinterpret_cast(aEnd)); -} - -namespace detail { - -/* - * Helper for the MOZ_ARRAY_LENGTH() macro to make the length a typesafe - * compile-time constant even on compilers lacking constexpr support. - */ -template -char (&ArrayLengthHelper(T (&array)[N]))[N]; - -} /* namespace detail */ - -} /* namespace mozilla */ - -#endif /* __cplusplus */ - -/* - * MOZ_ARRAY_LENGTH() is an alternative to mozilla::ArrayLength() for C files - * that can't use C++ template functions and for static_assert() calls that - * can't call ArrayLength() when it is not a C++11 constexpr function. - */ -#ifdef __cplusplus -# define MOZ_ARRAY_LENGTH(array) sizeof(mozilla::detail::ArrayLengthHelper(array)) -#else -# define MOZ_ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0])) -#endif - -#endif /* mozilla_ArrayUtils_h */ diff --git a/ios/include/spidermonkey/mozilla/Assertions.h b/ios/include/spidermonkey/mozilla/Assertions.h deleted file mode 100644 index e978af3d..00000000 --- a/ios/include/spidermonkey/mozilla/Assertions.h +++ /dev/null @@ -1,585 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implementations of runtime and static assertion macros for C and C++. */ - -#ifndef mozilla_Assertions_h -#define mozilla_Assertions_h - -#if defined(MOZILLA_INTERNAL_API) && defined(__cplusplus) -#define MOZ_DUMP_ASSERTION_STACK -#endif - -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/Likely.h" -#include "mozilla/MacroArgs.h" -#include "mozilla/StaticAnalysisFunctions.h" -#include "mozilla/Types.h" -#ifdef MOZ_DUMP_ASSERTION_STACK -#include "nsTraceRefcnt.h" -#endif - -#if defined(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API) -/* - * The crash reason set by MOZ_CRASH_ANNOTATE is consumed by the crash reporter - * if present. It is declared here (and defined in Assertions.cpp) to make it - * available to all code, even libraries that don't link with the crash reporter - * directly. - */ -MOZ_BEGIN_EXTERN_C -extern MFBT_DATA const char* gMozCrashReason; -MOZ_END_EXTERN_C - -static inline void -AnnotateMozCrashReason(const char* reason) -{ - gMozCrashReason = reason; -} -# define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__) -#else -# define MOZ_CRASH_ANNOTATE(...) do { /* nothing */ } while (0) -#endif - -#include -#include -#include -#ifdef WIN32 - /* - * TerminateProcess and GetCurrentProcess are defined in , which - * further depends on . We hardcode these few definitions manually - * because those headers clutter the global namespace with a significant - * number of undesired macros and symbols. - */ -# ifdef __cplusplus -extern "C" { -# endif -__declspec(dllimport) int __stdcall -TerminateProcess(void* hProcess, unsigned int uExitCode); -__declspec(dllimport) void* __stdcall GetCurrentProcess(void); -# ifdef __cplusplus -} -# endif -#else -# include -#endif -#ifdef ANDROID -# include -#endif - -/* - * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C. - * In C++11, static_assert is provided by the compiler to the same effect. - * This can be useful when you make certain assumptions about what must hold for - * optimal, or even correct, behavior. For example, you might assert that the - * size of a struct is a multiple of the target architecture's word size: - * - * struct S { ... }; - * // C - * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0, - * "S should be a multiple of word size for efficiency"); - * // C++11 - * static_assert(sizeof(S) % sizeof(size_t) == 0, - * "S should be a multiple of word size for efficiency"); - * - * This macro can be used in any location where both an extern declaration and a - * typedef could be used. - */ -#ifndef __cplusplus - /* - * Some of the definitions below create an otherwise-unused typedef. This - * triggers compiler warnings with some versions of gcc, so mark the typedefs - * as permissibly-unused to disable the warnings. - */ -# if defined(__GNUC__) -# define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused)) -# else -# define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */ -# endif -# define MOZ_STATIC_ASSERT_GLUE1(x, y) x##y -# define MOZ_STATIC_ASSERT_GLUE(x, y) MOZ_STATIC_ASSERT_GLUE1(x, y) -# if defined(__SUNPRO_CC) - /* - * The Sun Studio C++ compiler is buggy when declaring, inside a function, - * another extern'd function with an array argument whose length contains a - * sizeof, triggering the error message "sizeof expression not accepted as - * size of array parameter". This bug (6688515, not public yet) would hit - * defining moz_static_assert as a function, so we always define an extern - * array for Sun Studio. - * - * We include the line number in the symbol name in a best-effort attempt - * to avoid conflicts (see below). - */ -# define MOZ_STATIC_ASSERT(cond, reason) \ - extern char MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)[(cond) ? 1 : -1] -# elif defined(__COUNTER__) - /* - * If there was no preferred alternative, use a compiler-agnostic version. - * - * Note that the non-__COUNTER__ version has a bug in C++: it can't be used - * in both |extern "C"| and normal C++ in the same translation unit. (Alas - * |extern "C"| isn't allowed in a function.) The only affected compiler - * we really care about is gcc 4.2. For that compiler and others like it, - * we include the line number in the function name to do the best we can to - * avoid conflicts. These should be rare: a conflict would require use of - * MOZ_STATIC_ASSERT on the same line in separate files in the same - * translation unit, *and* the uses would have to be in code with - * different linkage, *and* the first observed use must be in C++-linkage - * code. - */ -# define MOZ_STATIC_ASSERT(cond, reason) \ - typedef int MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __COUNTER__)[(cond) ? 1 : -1] MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE -# else -# define MOZ_STATIC_ASSERT(cond, reason) \ - extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE -# endif - -#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason) -#else -#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Prints |aStr| as an assertion failure (using aFilename and aLine as the - * location of the assertion) to the standard debug-output channel. - * - * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This - * method is primarily for internal use in this header, and only secondarily - * for use in implementing release-build assertions. - */ -static MOZ_COLD MOZ_ALWAYS_INLINE void -MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename, int aLine) - MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS -{ -#ifdef ANDROID - __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert", - "Assertion failure: %s, at %s:%d\n", - aStr, aFilename, aLine); -#else - fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine); -#if defined (MOZ_DUMP_ASSERTION_STACK) - nsTraceRefcnt::WalkTheStack(stderr); -#endif - fflush(stderr); -#endif -} - -static MOZ_COLD MOZ_ALWAYS_INLINE void -MOZ_ReportCrash(const char* aStr, const char* aFilename, int aLine) - MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS -{ -#ifdef ANDROID - __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH", - "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine); -#else - fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine); -#if defined(MOZ_DUMP_ASSERTION_STACK) - nsTraceRefcnt::WalkTheStack(stderr); -#endif - fflush(stderr); -#endif -} - -/** - * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should - * call MOZ_CRASH instead. - */ -#if defined(_MSC_VER) - /* - * On MSVC use the __debugbreak compiler intrinsic, which produces an inline - * (not nested in a system function) breakpoint. This distinctively invokes - * Breakpad without requiring system library symbols on all stack-processing - * machines, as a nested breakpoint would require. - * - * We use TerminateProcess with the exit code aborting would generate - * because we don't want to invoke atexit handlers, destructors, library - * unload handlers, and so on when our process might be in a compromised - * state. - * - * We don't use abort() because it'd cause Windows to annoyingly pop up the - * process error dialog multiple times. See bug 345118 and bug 426163. - * - * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the - * compiler doesn't hassle us to provide a return statement after a - * MOZ_REALLY_CRASH() call. - * - * (Technically these are Windows requirements, not MSVC requirements. But - * practically you need MSVC for debugging, and we only ship builds created - * by MSVC, so doing it this way reduces complexity.) - */ - -__declspec(noreturn) __inline void MOZ_NoReturn() {} - -# ifdef __cplusplus -# define MOZ_REALLY_CRASH() \ - do { \ - ::__debugbreak(); \ - *((volatile int*) NULL) = __LINE__; \ - ::TerminateProcess(::GetCurrentProcess(), 3); \ - ::MOZ_NoReturn(); \ - } while (0) -# else -# define MOZ_REALLY_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = __LINE__; \ - TerminateProcess(GetCurrentProcess(), 3); \ - MOZ_NoReturn(); \ - } while (0) -# endif -#else -# ifdef __cplusplus -# define MOZ_REALLY_CRASH() \ - do { \ - *((volatile int*) NULL) = __LINE__; \ - ::abort(); \ - } while (0) -# else -# define MOZ_REALLY_CRASH() \ - do { \ - *((volatile int*) NULL) = __LINE__; \ - abort(); \ - } while (0) -# endif -#endif - -/* - * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a - * Breakpad-compatible way, in both debug and release builds. - * - * MOZ_CRASH is a good solution for "handling" failure cases when you're - * unwilling or unable to handle them more cleanly -- for OOM, for likely memory - * corruption, and so on. It's also a good solution if you need safe behavior - * in release builds as well as debug builds. But if the failure is one that - * should be debugged and fixed, MOZ_ASSERT is generally preferable. - * - * The optional explanation-string, if provided, must be a string literal - * explaining why we're crashing. This argument is intended for use with - * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's - * obvious why we're crashing. - * - * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an - * explanation-string, we print the string to stderr. Otherwise, we don't - * print anything; this is because we want MOZ_CRASH to be 100% safe in release - * builds, and it's hard to print to stderr safely when memory might have been - * corrupted. - */ -#ifndef DEBUG -# define MOZ_CRASH(...) \ - do { \ - MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \ - MOZ_REALLY_CRASH(); \ - } while (0) -#else -# define MOZ_CRASH(...) \ - do { \ - MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \ - MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \ - MOZ_REALLY_CRASH(); \ - } while (0) -#endif - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -/* - * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in - * debug builds. If it is, execution continues. Otherwise, an error message - * including the expression and the explanation-string (if provided) is printed, - * an attempt is made to invoke any existing debugger, and execution halts. - * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition - * which can correctly be falsy. - * - * The optional explanation-string, if provided, must be a string literal - * explaining the assertion. It is intended for use with assertions whose - * correctness or rationale is non-obvious, and for assertions where the "real" - * condition being tested is best described prosaically. Don't provide an - * explanation if it's not actually helpful. - * - * // No explanation needed: pointer arguments often must not be NULL. - * MOZ_ASSERT(arg); - * - * // An explanation can be helpful to explain exactly how we know an - * // assertion is valid. - * MOZ_ASSERT(state == WAITING_FOR_RESPONSE, - * "given that and , we must have..."); - * - * // Or it might disambiguate multiple identical (save for their location) - * // assertions of the same expression. - * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(), - * "we already set [[PrimitiveThis]] for this Boolean object"); - * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(), - * "we already set [[PrimitiveThis]] for this String object"); - * - * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs - * *only* during debugging, not "in the field". If you want the latter, use - * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well. - * - * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and - * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare - * enough to require real user testing to hit, but is not security-sensitive. - * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT - * is firing, it should promptly be converted to a MOZ_ASSERT while the failure - * is being investigated, rather than letting users suffer. - */ - -/* - * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against - * accidentally passing something unintended in lieu of an assertion condition. - */ - -#ifdef __cplusplus -# include "mozilla/TypeTraits.h" -namespace mozilla { -namespace detail { - -template -struct AssertionConditionType -{ - typedef typename RemoveReference::Type ValueT; - static_assert(!IsArray::value, - "Expected boolean assertion condition, got an array or a " - "string!"); - static_assert(!IsFunction::value, - "Expected boolean assertion condition, got a function! Did " - "you intend to call that function?"); - static_assert(!IsFloatingPoint::value, - "It's often a bad idea to assert that a floating-point number " - "is nonzero, because such assertions tend to intermittently " - "fail. Shouldn't your code gracefully handle this case instead " - "of asserting? Anyway, if you really want to do that, write an " - "explicit boolean condition, like !!x or x!=0."); - - static const bool isValid = true; -}; - -} // namespace detail -} // namespace mozilla -# define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \ - static_assert(mozilla::detail::AssertionConditionType::isValid, \ - "invalid assertion condition") -#else -# define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) -#endif - -/* First the single-argument form. */ -#define MOZ_ASSERT_HELPER1(expr) \ - do { \ - MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \ - if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \ - MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \ - MOZ_CRASH_ANNOTATE("MOZ_RELEASE_ASSERT(" #expr ")"); \ - MOZ_REALLY_CRASH(); \ - } \ - } while (0) -/* Now the two-argument form. */ -#define MOZ_ASSERT_HELPER2(expr, explain) \ - do { \ - MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \ - if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \ - MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \ - MOZ_CRASH_ANNOTATE("MOZ_RELEASE_ASSERT(" #expr ") (" explain ")"); \ - MOZ_REALLY_CRASH(); \ - } \ - } while (0) - -#define MOZ_RELEASE_ASSERT_GLUE(a, b) a b -#define MOZ_RELEASE_ASSERT(...) \ - MOZ_RELEASE_ASSERT_GLUE( \ - MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \ - (__VA_ARGS__)) - -#ifdef DEBUG -# define MOZ_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__) -#else -# define MOZ_ASSERT(...) do { } while (0) -#endif /* DEBUG */ - -#ifdef RELEASE_OR_BETA -# define MOZ_DIAGNOSTIC_ASSERT MOZ_ASSERT -#else -# define MOZ_DIAGNOSTIC_ASSERT MOZ_RELEASE_ASSERT -#endif - -/* - * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is - * true. - * - * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num)); - * - * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is - * designed to catch bugs during debugging, not "in the field". - */ -#ifdef DEBUG -# define MOZ_ASSERT_IF(cond, expr) \ - do { \ - if (cond) { \ - MOZ_ASSERT(expr); \ - } \ - } while (0) -#else -# define MOZ_ASSERT_IF(cond, expr) do { } while (0) -#endif - -/* - * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that - * it is undefined behavior for execution to reach this point. No guarantees - * are made about what will happen if this is reached at runtime. Most code - * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra - * asserts. - */ -#if defined(__clang__) || defined(__GNUC__) -# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() -#elif defined(_MSC_VER) -# define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0) -#else -# ifdef __cplusplus -# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() -# else -# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() -# endif -#endif - -/* - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it - * can assume that the macro call cannot be reached during execution. This lets - * the compiler generate better-optimized code under some circumstances, at the - * expense of the program's behavior being undefined if control reaches the - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE. - * - * In Gecko, you probably should not use this macro outside of performance- or - * size-critical code, because it's unsafe. If you don't care about code size - * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH. - * - * SpiderMonkey is a different beast, and there it's acceptable to use - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely. - * - * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid - * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE - * call. - * - * Example usage: - * - * enum ValueType { - * VALUE_STRING, - * VALUE_INT, - * VALUE_FLOAT - * }; - * - * int ptrToInt(ValueType type, void* value) { - * { - * // We know for sure that type is either INT or FLOAT, and we want this - * // code to run as quickly as possible. - * switch (type) { - * case VALUE_INT: - * return *(int*) value; - * case VALUE_FLOAT: - * return (int) *(float*) value; - * default: - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType"); - * } - * } - */ - -/* - * Unconditional assert in debug builds for (assumed) unreachable code paths - * that have a safe return without crashing in release builds. - */ -#define MOZ_ASSERT_UNREACHABLE(reason) \ - MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason) - -#define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \ - do { \ - MOZ_ASSERT_UNREACHABLE(reason); \ - MOZ_ASSUME_UNREACHABLE_MARKER(); \ - } while (0) - -/** - * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about - * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in - * debug builds, but intentionally fall through in release builds to handle - * unexpected values. - * - * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to MOZ_FALLTHROUGH? In - * release builds, the MOZ_ASSERT(false) will expand to `do { } while (0)`, - * requiring a MOZ_FALLTHROUGH annotation to suppress a -Wimplicit-fallthrough - * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like - * `if (true) { MOZ_CRASH(); }` and the MOZ_FALLTHROUGH annotation will cause - * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this - * warning stalemate. - * - * // Example before MOZ_FALLTHROUGH_ASSERT: - * switch (foo) { - * default: - * // This case wants to assert in debug builds, fall through in release. - * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds! - * MOZ_FALLTHROUGH; // but -Wunreachable-code warning in debug builds! - * case 5: - * return 5; - * } - * - * // Example with MOZ_FALLTHROUGH_ASSERT: - * switch (foo) { - * default: - * // This case asserts in debug builds, falls through in release. - * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!"); - * case 5: - * return 5; - * } - */ -#ifdef DEBUG -# define MOZ_FALLTHROUGH_ASSERT(reason) MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " reason) -#else -# define MOZ_FALLTHROUGH_ASSERT(...) MOZ_FALLTHROUGH -#endif - -/* - * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided - * expression, in debug builds and in release builds both. Then, in debug - * builds only, the value of the expression is asserted either true or false - * using MOZ_ASSERT. - */ -#ifdef DEBUG -# define MOZ_ALWAYS_TRUE(expr) \ - do { \ - if ((expr)) { \ - /* Do nothing. */ \ - } else { \ - MOZ_ASSERT(false, #expr); \ - } \ - } while (0) -# define MOZ_ALWAYS_FALSE(expr) \ - do { \ - if ((expr)) { \ - MOZ_ASSERT(false, #expr); \ - } else { \ - /* Do nothing. */ \ - } \ - } while (0) -#else -# define MOZ_ALWAYS_TRUE(expr) \ - do { \ - if ((expr)) { \ - /* Silence MOZ_MUST_USE. */ \ - } \ - } while (0) -# define MOZ_ALWAYS_FALSE(expr) \ - do { \ - if ((expr)) { \ - /* Silence MOZ_MUST_USE. */ \ - } \ - } while (0) -#endif - -#undef MOZ_DUMP_ASSERTION_STACK -#undef MOZ_CRASH_CRASHREPORT - -#endif /* mozilla_Assertions_h */ diff --git a/ios/include/spidermonkey/mozilla/Atomics.h b/ios/include/spidermonkey/mozilla/Atomics.h deleted file mode 100644 index 213d1b9f..00000000 --- a/ios/include/spidermonkey/mozilla/Atomics.h +++ /dev/null @@ -1,800 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements (almost always) lock-free atomic operations. The operations here - * are a subset of that which can be found in C++11's header, with a - * different API to enforce consistent memory ordering constraints. - * - * Anyone caught using |volatile| for inter-thread memory safety needs to be - * sent a copy of this header and the C++11 standard. - */ - -#ifndef mozilla_Atomics_h -#define mozilla_Atomics_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/TypeTraits.h" - -#include - -/* - * Our minimum deployment target on clang/OS X is OS X 10.6, whose SDK - * does not have . So be sure to check for support - * along with C++0x support. - */ -#if defined(_MSC_VER) -# define MOZ_HAVE_CXX11_ATOMICS -#elif defined(__clang__) || defined(__GNUC__) - /* - * Clang doesn't like from libstdc++ before 4.7 due to the - * loose typing of the atomic builtins. GCC 4.5 and 4.6 lacks inline - * definitions for unspecialized std::atomic and causes linking errors. - * Therefore, we require at least 4.7.0 for using libstdc++. - * - * libc++ is only functional with clang. - */ -# if MOZ_USING_LIBSTDCXX && MOZ_LIBSTDCXX_VERSION_AT_LEAST(4, 7, 0) -# define MOZ_HAVE_CXX11_ATOMICS -# elif MOZ_USING_LIBCXX && defined(__clang__) -# define MOZ_HAVE_CXX11_ATOMICS -# endif -#endif - -namespace mozilla { - -/** - * An enum of memory ordering possibilities for atomics. - * - * Memory ordering is the observable state of distinct values in memory. - * (It's a separate concept from atomicity, which concerns whether an - * operation can ever be observed in an intermediate state. Don't - * conflate the two!) Given a sequence of operations in source code on - * memory, it is *not* always the case that, at all times and on all - * cores, those operations will appear to have occurred in that exact - * sequence. First, the compiler might reorder that sequence, if it - * thinks another ordering will be more efficient. Second, the CPU may - * not expose so consistent a view of memory. CPUs will often perform - * their own instruction reordering, above and beyond that performed by - * the compiler. And each core has its own memory caches, and accesses - * (reads and writes both) to "memory" may only resolve to out-of-date - * cache entries -- not to the "most recently" performed operation in - * some global sense. Any access to a value that may be used by - * multiple threads, potentially across multiple cores, must therefore - * have a memory ordering imposed on it, for all code on all - * threads/cores to have a sufficiently coherent worldview. - * - * http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync and - * http://en.cppreference.com/w/cpp/atomic/memory_order go into more - * detail on all this, including examples of how each mode works. - * - * Note that for simplicity and practicality, not all of the modes in - * C++11 are supported. The missing C++11 modes are either subsumed by - * the modes we provide below, or not relevant for the CPUs we support - * in Gecko. These three modes are confusing enough as it is! - */ -enum MemoryOrdering { - /* - * Relaxed ordering is the simplest memory ordering: none at all. - * When the result of a write is observed, nothing may be inferred - * about other memory. Writes ostensibly performed "before" on the - * writing thread may not yet be visible. Writes performed "after" on - * the writing thread may already be visible, if the compiler or CPU - * reordered them. (The latter can happen if reads and/or writes get - * held up in per-processor caches.) Relaxed ordering means - * operations can always use cached values (as long as the actual - * updates to atomic values actually occur, correctly, eventually), so - * it's usually the fastest sort of atomic access. For this reason, - * *it's also the most dangerous kind of access*. - * - * Relaxed ordering is good for things like process-wide statistics - * counters that don't need to be consistent with anything else, so - * long as updates themselves are atomic. (And so long as any - * observations of that value can tolerate being out-of-date -- if you - * need some sort of up-to-date value, you need some sort of other - * synchronizing operation.) It's *not* good for locks, mutexes, - * reference counts, etc. that mediate access to other memory, or must - * be observably consistent with other memory. - * - * x86 architectures don't take advantage of the optimization - * opportunities that relaxed ordering permits. Thus it's possible - * that using relaxed ordering will "work" on x86 but fail elsewhere - * (ARM, say, which *does* implement non-sequentially-consistent - * relaxed ordering semantics). Be extra-careful using relaxed - * ordering if you can't easily test non-x86 architectures! - */ - Relaxed, - - /* - * When an atomic value is updated with ReleaseAcquire ordering, and - * that new value is observed with ReleaseAcquire ordering, prior - * writes (atomic or not) are also observable. What ReleaseAcquire - * *doesn't* give you is any observable ordering guarantees for - * ReleaseAcquire-ordered operations on different objects. For - * example, if there are two cores that each perform ReleaseAcquire - * operations on separate objects, each core may or may not observe - * the operations made by the other core. The only way the cores can - * be synchronized with ReleaseAcquire is if they both - * ReleaseAcquire-access the same object. This implies that you can't - * necessarily describe some global total ordering of ReleaseAcquire - * operations. - * - * ReleaseAcquire ordering is good for (as the name implies) atomic - * operations on values controlling ownership of things: reference - * counts, mutexes, and the like. However, if you are thinking about - * using these to implement your own locks or mutexes, you should take - * a good, hard look at actual lock or mutex primitives first. - */ - ReleaseAcquire, - - /* - * When an atomic value is updated with SequentiallyConsistent - * ordering, all writes observable when the update is observed, just - * as with ReleaseAcquire ordering. But, furthermore, a global total - * ordering of SequentiallyConsistent operations *can* be described. - * For example, if two cores perform SequentiallyConsistent operations - * on separate objects, one core will observably perform its update - * (and all previous operations will have completed), then the other - * core will observably perform its update (and all previous - * operations will have completed). (Although those previous - * operations aren't themselves ordered -- they could be intermixed, - * or ordered if they occur on atomic values with ordering - * requirements.) SequentiallyConsistent is the *simplest and safest* - * ordering of atomic operations -- it's always as if one operation - * happens, then another, then another, in some order -- and every - * core observes updates to happen in that single order. Because it - * has the most synchronization requirements, operations ordered this - * way also tend to be slowest. - * - * SequentiallyConsistent ordering can be desirable when multiple - * threads observe objects, and they all have to agree on the - * observable order of changes to them. People expect - * SequentiallyConsistent ordering, even if they shouldn't, when - * writing code, atomic or otherwise. SequentiallyConsistent is also - * the ordering of choice when designing lockless data structures. If - * you don't know what order to use, use this one. - */ - SequentiallyConsistent, -}; - -} // namespace mozilla - -// Build up the underlying intrinsics. -#ifdef MOZ_HAVE_CXX11_ATOMICS - -# include - -namespace mozilla { -namespace detail { - -/* - * We provide CompareExchangeFailureOrder to work around a bug in some - * versions of GCC's header. See bug 898491. - */ -template struct AtomicOrderConstraints; - -template<> -struct AtomicOrderConstraints -{ - static const std::memory_order AtomicRMWOrder = std::memory_order_relaxed; - static const std::memory_order LoadOrder = std::memory_order_relaxed; - static const std::memory_order StoreOrder = std::memory_order_relaxed; - static const std::memory_order CompareExchangeFailureOrder = - std::memory_order_relaxed; -}; - -template<> -struct AtomicOrderConstraints -{ - static const std::memory_order AtomicRMWOrder = std::memory_order_acq_rel; - static const std::memory_order LoadOrder = std::memory_order_acquire; - static const std::memory_order StoreOrder = std::memory_order_release; - static const std::memory_order CompareExchangeFailureOrder = - std::memory_order_acquire; -}; - -template<> -struct AtomicOrderConstraints -{ - static const std::memory_order AtomicRMWOrder = std::memory_order_seq_cst; - static const std::memory_order LoadOrder = std::memory_order_seq_cst; - static const std::memory_order StoreOrder = std::memory_order_seq_cst; - static const std::memory_order CompareExchangeFailureOrder = - std::memory_order_seq_cst; -}; - -template -struct IntrinsicBase -{ - typedef std::atomic ValueType; - typedef AtomicOrderConstraints OrderedOp; -}; - -template -struct IntrinsicMemoryOps : public IntrinsicBase -{ - typedef IntrinsicBase Base; - - static T load(const typename Base::ValueType& aPtr) - { - return aPtr.load(Base::OrderedOp::LoadOrder); - } - - static void store(typename Base::ValueType& aPtr, T aVal) - { - aPtr.store(aVal, Base::OrderedOp::StoreOrder); - } - - static T exchange(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.exchange(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static bool compareExchange(typename Base::ValueType& aPtr, - T aOldVal, T aNewVal) - { - return aPtr.compare_exchange_strong(aOldVal, aNewVal, - Base::OrderedOp::AtomicRMWOrder, - Base::OrderedOp::CompareExchangeFailureOrder); - } -}; - -template -struct IntrinsicAddSub : public IntrinsicBase -{ - typedef IntrinsicBase Base; - - static T add(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_add(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T sub(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_sub(aVal, Base::OrderedOp::AtomicRMWOrder); - } -}; - -template -struct IntrinsicAddSub : public IntrinsicBase -{ - typedef IntrinsicBase Base; - - static T* add(typename Base::ValueType& aPtr, ptrdiff_t aVal) - { - return aPtr.fetch_add(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T* sub(typename Base::ValueType& aPtr, ptrdiff_t aVal) - { - return aPtr.fetch_sub(aVal, Base::OrderedOp::AtomicRMWOrder); - } -}; - -template -struct IntrinsicIncDec : public IntrinsicAddSub -{ - typedef IntrinsicBase Base; - - static T inc(typename Base::ValueType& aPtr) - { - return IntrinsicAddSub::add(aPtr, 1); - } - - static T dec(typename Base::ValueType& aPtr) - { - return IntrinsicAddSub::sub(aPtr, 1); - } -}; - -template -struct AtomicIntrinsics : public IntrinsicMemoryOps, - public IntrinsicIncDec -{ - typedef IntrinsicBase Base; - - static T or_(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_or(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T xor_(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_xor(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T and_(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_and(aVal, Base::OrderedOp::AtomicRMWOrder); - } -}; - -template -struct AtomicIntrinsics - : public IntrinsicMemoryOps, public IntrinsicIncDec -{ -}; - -template -struct ToStorageTypeArgument -{ - static constexpr T convert (T aT) { return aT; } -}; - -} // namespace detail -} // namespace mozilla - -#elif defined(__GNUC__) - -namespace mozilla { -namespace detail { - -/* - * The __sync_* family of intrinsics is documented here: - * - * http://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Atomic-Builtins.html - * - * While these intrinsics are deprecated in favor of the newer __atomic_* - * family of intrincs: - * - * http://gcc.gnu.org/onlinedocs/gcc-4.7.3/gcc/_005f_005fatomic-Builtins.html - * - * any GCC version that supports the __atomic_* intrinsics will also support - * the header and so will be handled above. We provide a version of - * atomics using the __sync_* intrinsics to support older versions of GCC. - * - * All __sync_* intrinsics that we use below act as full memory barriers, for - * both compiler and hardware reordering, except for __sync_lock_test_and_set, - * which is a only an acquire barrier. When we call __sync_lock_test_and_set, - * we add a barrier above it as appropriate. - */ - -template struct Barrier; - -/* - * Some processors (in particular, x86) don't require quite so many calls to - * __sync_sychronize as our specializations of Barrier produce. If - * performance turns out to be an issue, defining these specializations - * on a per-processor basis would be a good first tuning step. - */ - -template<> -struct Barrier -{ - static void beforeLoad() {} - static void afterLoad() {} - static void beforeStore() {} - static void afterStore() {} -}; - -template<> -struct Barrier -{ - static void beforeLoad() {} - static void afterLoad() { __sync_synchronize(); } - static void beforeStore() { __sync_synchronize(); } - static void afterStore() {} -}; - -template<> -struct Barrier -{ - static void beforeLoad() { __sync_synchronize(); } - static void afterLoad() { __sync_synchronize(); } - static void beforeStore() { __sync_synchronize(); } - static void afterStore() { __sync_synchronize(); } -}; - -template::value> -struct AtomicStorageType -{ - // For non-enums, just use the type directly. - typedef T Type; -}; - -template -struct AtomicStorageType - : Conditional -{ - static_assert(sizeof(T) == 4 || sizeof(T) == 8, - "wrong type computed in conditional above"); -}; - -template -struct IntrinsicMemoryOps -{ - typedef typename AtomicStorageType::Type ValueType; - - static T load(const ValueType& aPtr) - { - Barrier::beforeLoad(); - T val = T(aPtr); - Barrier::afterLoad(); - return val; - } - - static void store(ValueType& aPtr, T aVal) - { - Barrier::beforeStore(); - aPtr = ValueType(aVal); - Barrier::afterStore(); - } - - static T exchange(ValueType& aPtr, T aVal) - { - // __sync_lock_test_and_set is only an acquire barrier; loads and stores - // can't be moved up from after to before it, but they can be moved down - // from before to after it. We may want a stricter ordering, so we need - // an explicit barrier. - Barrier::beforeStore(); - return T(__sync_lock_test_and_set(&aPtr, ValueType(aVal))); - } - - static bool compareExchange(ValueType& aPtr, T aOldVal, T aNewVal) - { - return __sync_bool_compare_and_swap(&aPtr, ValueType(aOldVal), ValueType(aNewVal)); - } -}; - -template -struct IntrinsicAddSub - : public IntrinsicMemoryOps -{ - typedef IntrinsicMemoryOps Base; - typedef typename Base::ValueType ValueType; - - static T add(ValueType& aPtr, T aVal) - { - return T(__sync_fetch_and_add(&aPtr, ValueType(aVal))); - } - - static T sub(ValueType& aPtr, T aVal) - { - return T(__sync_fetch_and_sub(&aPtr, ValueType(aVal))); - } -}; - -template -struct IntrinsicAddSub - : public IntrinsicMemoryOps -{ - typedef IntrinsicMemoryOps Base; - typedef typename Base::ValueType ValueType; - - /* - * The reinterpret_casts are needed so that - * __sync_fetch_and_{add,sub} will properly type-check. - * - * Also, these functions do not provide standard semantics for - * pointer types, so we need to adjust the addend. - */ - static ValueType add(ValueType& aPtr, ptrdiff_t aVal) - { - ValueType amount = reinterpret_cast(aVal * sizeof(T)); - return __sync_fetch_and_add(&aPtr, amount); - } - - static ValueType sub(ValueType& aPtr, ptrdiff_t aVal) - { - ValueType amount = reinterpret_cast(aVal * sizeof(T)); - return __sync_fetch_and_sub(&aPtr, amount); - } -}; - -template -struct IntrinsicIncDec : public IntrinsicAddSub -{ - typedef IntrinsicAddSub Base; - typedef typename Base::ValueType ValueType; - - static T inc(ValueType& aPtr) { return Base::add(aPtr, 1); } - static T dec(ValueType& aPtr) { return Base::sub(aPtr, 1); } -}; - -template -struct AtomicIntrinsics : public IntrinsicIncDec -{ - static T or_( T& aPtr, T aVal) { return __sync_fetch_and_or(&aPtr, aVal); } - static T xor_(T& aPtr, T aVal) { return __sync_fetch_and_xor(&aPtr, aVal); } - static T and_(T& aPtr, T aVal) { return __sync_fetch_and_and(&aPtr, aVal); } -}; - -template -struct AtomicIntrinsics : public IntrinsicIncDec -{ -}; - -template::value> -struct ToStorageTypeArgument -{ - typedef typename AtomicStorageType::Type ResultType; - - static constexpr ResultType convert (T aT) { return ResultType(aT); } -}; - -template -struct ToStorageTypeArgument -{ - static constexpr T convert (T aT) { return aT; } -}; - -} // namespace detail -} // namespace mozilla - -#else -# error "Atomic compiler intrinsics are not supported on your platform" -#endif - -namespace mozilla { - -namespace detail { - -template -class AtomicBase -{ - static_assert(sizeof(T) == 4 || sizeof(T) == 8, - "mozilla/Atomics.h only supports 32-bit and 64-bit types"); - -protected: - typedef typename detail::AtomicIntrinsics Intrinsics; - typedef typename Intrinsics::ValueType ValueType; - ValueType mValue; - -public: - constexpr AtomicBase() : mValue() {} - explicit constexpr AtomicBase(T aInit) - : mValue(ToStorageTypeArgument::convert(aInit)) - {} - - // Note: we can't provide operator T() here because Atomic inherits - // from AtomcBase with T=uint32_t and not T=bool. If we implemented - // operator T() here, it would cause errors when comparing Atomic with - // a regular bool. - - T operator=(T aVal) - { - Intrinsics::store(mValue, aVal); - return aVal; - } - - /** - * Performs an atomic swap operation. aVal is stored and the previous - * value of this variable is returned. - */ - T exchange(T aVal) - { - return Intrinsics::exchange(mValue, aVal); - } - - /** - * Performs an atomic compare-and-swap operation and returns true if it - * succeeded. This is equivalent to atomically doing - * - * if (mValue == aOldValue) { - * mValue = aNewValue; - * return true; - * } else { - * return false; - * } - */ - bool compareExchange(T aOldValue, T aNewValue) - { - return Intrinsics::compareExchange(mValue, aOldValue, aNewValue); - } - -private: - template - AtomicBase(const AtomicBase& aCopy) = delete; -}; - -template -class AtomicBaseIncDec : public AtomicBase -{ - typedef typename detail::AtomicBase Base; - -public: - constexpr AtomicBaseIncDec() : Base() {} - explicit constexpr AtomicBaseIncDec(T aInit) : Base(aInit) {} - - using Base::operator=; - - operator T() const { return Base::Intrinsics::load(Base::mValue); } - T operator++(int) { return Base::Intrinsics::inc(Base::mValue); } - T operator--(int) { return Base::Intrinsics::dec(Base::mValue); } - T operator++() { return Base::Intrinsics::inc(Base::mValue) + 1; } - T operator--() { return Base::Intrinsics::dec(Base::mValue) - 1; } - -private: - template - AtomicBaseIncDec(const AtomicBaseIncDec& aCopy) = delete; -}; - -} // namespace detail - -/** - * A wrapper for a type that enforces that all memory accesses are atomic. - * - * In general, where a variable |T foo| exists, |Atomic foo| can be used in - * its place. Implementations for integral and pointer types are provided - * below. - * - * Atomic accesses are sequentially consistent by default. You should - * use the default unless you are tall enough to ride the - * memory-ordering roller coaster (if you're not sure, you aren't) and - * you have a compelling reason to do otherwise. - * - * There is one exception to the case of atomic memory accesses: providing an - * initial value of the atomic value is not guaranteed to be atomic. This is a - * deliberate design choice that enables static atomic variables to be declared - * without introducing extra static constructors. - */ -template -class Atomic; - -/** - * Atomic implementation for integral types. - * - * In addition to atomic store and load operations, compound assignment and - * increment/decrement operators are implemented which perform the - * corresponding read-modify-write operation atomically. Finally, an atomic - * swap method is provided. - */ -template -class Atomic::value && - !IsSame::value>::Type> - : public detail::AtomicBaseIncDec -{ - typedef typename detail::AtomicBaseIncDec Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(T aInit) : Base(aInit) {} - - using Base::operator=; - - T operator+=(T aDelta) - { - return Base::Intrinsics::add(Base::mValue, aDelta) + aDelta; - } - - T operator-=(T aDelta) - { - return Base::Intrinsics::sub(Base::mValue, aDelta) - aDelta; - } - - T operator|=(T aVal) - { - return Base::Intrinsics::or_(Base::mValue, aVal) | aVal; - } - - T operator^=(T aVal) - { - return Base::Intrinsics::xor_(Base::mValue, aVal) ^ aVal; - } - - T operator&=(T aVal) - { - return Base::Intrinsics::and_(Base::mValue, aVal) & aVal; - } - -private: - Atomic(Atomic& aOther) = delete; -}; - -/** - * Atomic implementation for pointer types. - * - * An atomic compare-and-swap primitive for pointer variables is provided, as - * are atomic increment and decement operators. Also provided are the compound - * assignment operators for addition and subtraction. Atomic swap (via - * exchange()) is included as well. - */ -template -class Atomic : public detail::AtomicBaseIncDec -{ - typedef typename detail::AtomicBaseIncDec Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(T* aInit) : Base(aInit) {} - - using Base::operator=; - - T* operator+=(ptrdiff_t aDelta) - { - return Base::Intrinsics::add(Base::mValue, aDelta) + aDelta; - } - - T* operator-=(ptrdiff_t aDelta) - { - return Base::Intrinsics::sub(Base::mValue, aDelta) - aDelta; - } - -private: - Atomic(Atomic& aOther) = delete; -}; - -/** - * Atomic implementation for enum types. - * - * The atomic store and load operations and the atomic swap method is provided. - */ -template -class Atomic::value>::Type> - : public detail::AtomicBase -{ - typedef typename detail::AtomicBase Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(T aInit) : Base(aInit) {} - - operator T() const { return T(Base::Intrinsics::load(Base::mValue)); } - - using Base::operator=; - -private: - Atomic(Atomic& aOther) = delete; -}; - -/** - * Atomic implementation for boolean types. - * - * The atomic store and load operations and the atomic swap method is provided. - * - * Note: - * - * - sizeof(Atomic) != sizeof(bool) for some implementations of - * bool and/or some implementations of std::atomic. This is allowed in - * [atomic.types.generic]p9. - * - * - It's not obvious whether the 8-bit atomic functions on Windows are always - * inlined or not. If they are not inlined, the corresponding functions in the - * runtime library are not available on Windows XP. This is why we implement - * Atomic with an underlying type of uint32_t. - */ -template -class Atomic - : protected detail::AtomicBase -{ - typedef typename detail::AtomicBase Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(bool aInit) : Base(aInit) {} - - // We provide boolean wrappers for the underlying AtomicBase methods. - MOZ_IMPLICIT operator bool() const - { - return Base::Intrinsics::load(Base::mValue); - } - - bool operator=(bool aVal) - { - return Base::operator=(aVal); - } - - bool exchange(bool aVal) - { - return Base::exchange(aVal); - } - - bool compareExchange(bool aOldValue, bool aNewValue) - { - return Base::compareExchange(aOldValue, aNewValue); - } - -private: - Atomic(Atomic& aOther) = delete; -}; - -} // namespace mozilla - -#endif /* mozilla_Atomics_h */ diff --git a/ios/include/spidermonkey/mozilla/Attributes.h b/ios/include/spidermonkey/mozilla/Attributes.h deleted file mode 100644 index df6172f3..00000000 --- a/ios/include/spidermonkey/mozilla/Attributes.h +++ /dev/null @@ -1,604 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implementations of various class and method modifier attributes. */ - -#ifndef mozilla_Attributes_h -#define mozilla_Attributes_h - -#include "mozilla/Compiler.h" - -/* - * MOZ_ALWAYS_INLINE is a macro which expands to tell the compiler that the - * method decorated with it must be inlined, even if the compiler thinks - * otherwise. This is only a (much) stronger version of the inline hint: - * compilers are not guaranteed to respect it (although they're much more likely - * to do so). - * - * The MOZ_ALWAYS_INLINE_EVEN_DEBUG macro is yet stronger. It tells the - * compiler to inline even in DEBUG builds. It should be used very rarely. - */ -#if defined(_MSC_VER) -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __forceinline -#elif defined(__GNUC__) -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) inline -#else -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG inline -#endif - -#if !defined(DEBUG) -# define MOZ_ALWAYS_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG -#elif defined(_MSC_VER) && !defined(__cplusplus) -# define MOZ_ALWAYS_INLINE __inline -#else -# define MOZ_ALWAYS_INLINE inline -#endif - -#if defined(_MSC_VER) -/* - * g++ requires -std=c++0x or -std=gnu++0x to support C++11 functionality - * without warnings (functionality used by the macros below). These modes are - * detectable by checking whether __GXX_EXPERIMENTAL_CXX0X__ is defined or, more - * standardly, by checking whether __cplusplus has a C++11 or greater value. - * Current versions of g++ do not correctly set __cplusplus, so we check both - * for forward compatibility. - */ -# define MOZ_HAVE_NEVER_INLINE __declspec(noinline) -# define MOZ_HAVE_NORETURN __declspec(noreturn) -#elif defined(__clang__) - /* - * Per Clang documentation, "Note that marketing version numbers should not - * be used to check for language features, as different vendors use different - * numbering schemes. Instead, use the feature checking macros." - */ -# ifndef __has_extension -# define __has_extension __has_feature /* compatibility, for older versions of clang */ -# endif -# if __has_attribute(noinline) -# define MOZ_HAVE_NEVER_INLINE __attribute__((noinline)) -# endif -# if __has_attribute(noreturn) -# define MOZ_HAVE_NORETURN __attribute__((noreturn)) -# endif -#elif defined(__GNUC__) -# define MOZ_HAVE_NEVER_INLINE __attribute__((noinline)) -# define MOZ_HAVE_NORETURN __attribute__((noreturn)) -#endif - -/* - * When built with clang analyzer (a.k.a scan-build), define MOZ_HAVE_NORETURN - * to mark some false positives - */ -#ifdef __clang_analyzer__ -# if __has_extension(attribute_analyzer_noreturn) -# define MOZ_HAVE_ANALYZER_NORETURN __attribute__((analyzer_noreturn)) -# endif -#endif - -/* - * MOZ_NEVER_INLINE is a macro which expands to tell the compiler that the - * method decorated with it must never be inlined, even if the compiler would - * otherwise choose to inline the method. Compilers aren't absolutely - * guaranteed to support this, but most do. - */ -#if defined(MOZ_HAVE_NEVER_INLINE) -# define MOZ_NEVER_INLINE MOZ_HAVE_NEVER_INLINE -#else -# define MOZ_NEVER_INLINE /* no support */ -#endif - -/* - * MOZ_NORETURN, specified at the start of a function declaration, indicates - * that the given function does not return. (The function definition does not - * need to be annotated.) - * - * MOZ_NORETURN void abort(const char* msg); - * - * This modifier permits the compiler to optimize code assuming a call to such a - * function will never return. It also enables the compiler to avoid spurious - * warnings about not initializing variables, or about any other seemingly-dodgy - * operations performed after the function returns. - * - * This modifier does not affect the corresponding function's linking behavior. - */ -#if defined(MOZ_HAVE_NORETURN) -# define MOZ_NORETURN MOZ_HAVE_NORETURN -#else -# define MOZ_NORETURN /* no support */ -#endif - -/** - * MOZ_COLD tells the compiler that a function is "cold", meaning infrequently - * executed. This may lead it to optimize for size more aggressively than speed, - * or to allocate the body of the function in a distant part of the text segment - * to help keep it from taking up unnecessary icache when it isn't in use. - * - * Place this attribute at the very beginning of a function definition. For - * example, write - * - * MOZ_COLD int foo(); - * - * or - * - * MOZ_COLD int foo() { return 42; } - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_COLD __attribute__ ((cold)) -#else -# define MOZ_COLD -#endif - -/** - * MOZ_NONNULL tells the compiler that some of the arguments to a function are - * known to be non-null. The arguments are a list of 1-based argument indexes - * identifying arguments which are known to be non-null. - * - * Place this attribute at the very beginning of a function definition. For - * example, write - * - * MOZ_NONNULL(1, 2) int foo(char *p, char *q); - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_NONNULL(...) __attribute__ ((nonnull(__VA_ARGS__))) -#else -# define MOZ_NONNULL(...) -#endif - -/* - * MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS, specified at the end of a function - * declaration, indicates that for the purposes of static analysis, this - * function does not return. (The function definition does not need to be - * annotated.) - * - * MOZ_ReportCrash(const char* s, const char* file, int ln) - * MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS - * - * Some static analyzers, like scan-build from clang, can use this information - * to eliminate false positives. From the upstream documentation of scan-build: - * "This attribute is useful for annotating assertion handlers that actually - * can return, but for the purpose of using the analyzer we want to pretend - * that such functions do not return." - * - */ -#if defined(MOZ_HAVE_ANALYZER_NORETURN) -# define MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS MOZ_HAVE_ANALYZER_NORETURN -#else -# define MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS /* no support */ -#endif - -/* - * MOZ_ASAN_BLACKLIST is a macro to tell AddressSanitizer (a compile-time - * instrumentation shipped with Clang and GCC) to not instrument the annotated - * function. Furthermore, it will prevent the compiler from inlining the - * function because inlining currently breaks the blacklisting mechanism of - * AddressSanitizer. - */ -#if defined(__has_feature) -# if __has_feature(address_sanitizer) -# define MOZ_HAVE_ASAN_BLACKLIST -# endif -#elif defined(__GNUC__) -# if defined(__SANITIZE_ADDRESS__) -# define MOZ_HAVE_ASAN_BLACKLIST -# endif -#endif - -#if defined(MOZ_HAVE_ASAN_BLACKLIST) -# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_address)) -#else -# define MOZ_ASAN_BLACKLIST /* nothing */ -#endif - -/* - * MOZ_TSAN_BLACKLIST is a macro to tell ThreadSanitizer (a compile-time - * instrumentation shipped with Clang) to not instrument the annotated function. - * Furthermore, it will prevent the compiler from inlining the function because - * inlining currently breaks the blacklisting mechanism of ThreadSanitizer. - */ -#if defined(__has_feature) -# if __has_feature(thread_sanitizer) -# define MOZ_TSAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_thread)) -# else -# define MOZ_TSAN_BLACKLIST /* nothing */ -# endif -#else -# define MOZ_TSAN_BLACKLIST /* nothing */ -#endif - -/** - * MOZ_ALLOCATOR tells the compiler that the function it marks returns either a - * "fresh", "pointer-free" block of memory, or nullptr. "Fresh" means that the - * block is not pointed to by any other reachable pointer in the program. - * "Pointer-free" means that the block contains no pointers to any valid object - * in the program. It may be initialized with other (non-pointer) values. - * - * Placing this attribute on appropriate functions helps GCC analyze pointer - * aliasing more accurately in their callers. - * - * GCC warns if a caller ignores the value returned by a function marked with - * MOZ_ALLOCATOR: it is hard to imagine cases where dropping the value returned - * by a function that meets the criteria above would be intentional. - * - * Place this attribute after the argument list and 'this' qualifiers of a - * function definition. For example, write - * - * void *my_allocator(size_t) MOZ_ALLOCATOR; - * - * or - * - * void *my_allocator(size_t bytes) MOZ_ALLOCATOR { ... } - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_ALLOCATOR __attribute__ ((malloc, warn_unused_result)) -#else -# define MOZ_ALLOCATOR -#endif - -/** - * MOZ_MUST_USE tells the compiler to emit a warning if a function's - * return value is not used by the caller. - * - * Place this attribute at the very beginning of a function declaration. For - * example, write - * - * MOZ_MUST_USE int foo(); - * - * or - * - * MOZ_MUST_USE int foo() { return 42; } - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_MUST_USE __attribute__ ((warn_unused_result)) -#else -# define MOZ_MUST_USE -#endif - -/** - * MOZ_FALLTHROUGH is an annotation to suppress compiler warnings about switch - * cases that fall through without a break or return statement. MOZ_FALLTHROUGH - * is only needed on cases that have code. - * - * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about - * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in - * debug builds, but intentionally fall through in release builds. See comment - * in Assertions.h for more details. - * - * switch (foo) { - * case 1: // These cases have no code. No fallthrough annotations are needed. - * case 2: - * case 3: // This case has code, so a fallthrough annotation is needed! - * foo++; - * MOZ_FALLTHROUGH; - * case 4: - * return foo; - * - * default: - * // This case asserts in debug builds, falls through in release. - * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!"); - * case 5: - * return 5; - * } - */ -#if defined(__clang__) && __cplusplus >= 201103L - /* clang's fallthrough annotations are only available starting in C++11. */ -# define MOZ_FALLTHROUGH [[clang::fallthrough]] -#elif defined(_MSC_VER) - /* - * MSVC's __fallthrough annotations are checked by /analyze (Code Analysis): - * https://msdn.microsoft.com/en-us/library/ms235402%28VS.80%29.aspx - */ -# include -# define MOZ_FALLTHROUGH __fallthrough -#else -# define MOZ_FALLTHROUGH /* FALLTHROUGH */ -#endif - -#ifdef __cplusplus - -/* - * The following macros are attributes that support the static analysis plugin - * included with Mozilla, and will be implemented (when such support is enabled) - * as C++11 attributes. Since such attributes are legal pretty much everywhere - * and have subtly different semantics depending on their placement, the - * following is a guide on where to place the attributes. - * - * Attributes that apply to a struct or class precede the name of the class: - * (Note that this is different from the placement of final for classes!) - * - * class MOZ_CLASS_ATTRIBUTE SomeClass {}; - * - * Attributes that apply to functions follow the parentheses and const - * qualifiers but precede final, override and the function body: - * - * void DeclaredFunction() MOZ_FUNCTION_ATTRIBUTE; - * void SomeFunction() MOZ_FUNCTION_ATTRIBUTE {} - * void PureFunction() const MOZ_FUNCTION_ATTRIBUTE = 0; - * void OverriddenFunction() MOZ_FUNCTION_ATTIRBUTE override; - * - * Attributes that apply to variables or parameters follow the variable's name: - * - * int variable MOZ_VARIABLE_ATTRIBUTE; - * - * Attributes that apply to types follow the type name: - * - * typedef int MOZ_TYPE_ATTRIBUTE MagicInt; - * int MOZ_TYPE_ATTRIBUTE someVariable; - * int* MOZ_TYPE_ATTRIBUTE magicPtrInt; - * int MOZ_TYPE_ATTRIBUTE* ptrToMagicInt; - * - * Attributes that apply to statements precede the statement: - * - * MOZ_IF_ATTRIBUTE if (x == 0) - * MOZ_DO_ATTRIBUTE do { } while (0); - * - * Attributes that apply to labels precede the label: - * - * MOZ_LABEL_ATTRIBUTE target: - * goto target; - * MOZ_CASE_ATTRIBUTE case 5: - * MOZ_DEFAULT_ATTRIBUTE default: - * - * The static analyses that are performed by the plugin are as follows: - * - * MOZ_MUST_OVERRIDE: Applies to all C++ member functions. All immediate - * subclasses must provide an exact override of this method; if a subclass - * does not override this method, the compiler will emit an error. This - * attribute is not limited to virtual methods, so if it is applied to a - * nonvirtual method and the subclass does not provide an equivalent - * definition, the compiler will emit an error. - * MOZ_STACK_CLASS: Applies to all classes. Any class with this annotation is - * expected to live on the stack, so it is a compile-time error to use it, or - * an array of such objects, as a global or static variable, or as the type of - * a new expression (unless placement new is being used). If a member of - * another class uses this class, or if another class inherits from this - * class, then it is considered to be a stack class as well, although this - * attribute need not be provided in such cases. - * MOZ_NONHEAP_CLASS: Applies to all classes. Any class with this annotation is - * expected to live on the stack or in static storage, so it is a compile-time - * error to use it, or an array of such objects, as the type of a new - * expression. If a member of another class uses this class, or if another - * class inherits from this class, then it is considered to be a non-heap class - * as well, although this attribute need not be provided in such cases. - * MOZ_HEAP_CLASS: Applies to all classes. Any class with this annotation is - * expected to live on the heap, so it is a compile-time error to use it, or - * an array of such objects, as the type of a variable declaration, or as a - * temporary object. If a member of another class uses this class, or if - * another class inherits from this class, then it is considered to be a heap - * class as well, although this attribute need not be provided in such cases. - * MOZ_NON_TEMPORARY_CLASS: Applies to all classes. Any class with this - * annotation is expected not to live in a temporary. If a member of another - * class uses this class or if another class inherits from this class, then it - * is considered to be a non-temporary class as well, although this attribute - * need not be provided in such cases. - * MOZ_RAII: Applies to all classes. Any class with this annotation is assumed - * to be a RAII guard, which is expected to live on the stack in an automatic - * allocation. It is prohibited from being allocated in a temporary, static - * storage, or on the heap. This is a combination of MOZ_STACK_CLASS and - * MOZ_NON_TEMPORARY_CLASS. - * MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS: Applies to all classes that are - * intended to prevent introducing static initializers. This attribute - * currently makes it a compile-time error to instantiate these classes - * anywhere other than at the global scope, or as a static member of a class. - * In non-debug mode, it also prohibits non-trivial constructors and - * destructors. - * MOZ_TRIVIAL_CTOR_DTOR: Applies to all classes that must have both a trivial - * or constexpr constructor and a trivial destructor. Setting this attribute - * on a class makes it a compile-time error for that class to get a - * non-trivial constructor or destructor for any reason. - * MOZ_HEAP_ALLOCATOR: Applies to any function. This indicates that the return - * value is allocated on the heap, and will as a result check such allocations - * during MOZ_STACK_CLASS and MOZ_NONHEAP_CLASS annotation checking. - * MOZ_IMPLICIT: Applies to constructors. Implicit conversion constructors - * are disallowed by default unless they are marked as MOZ_IMPLICIT. This - * attribute must be used for constructors which intend to provide implicit - * conversions. - * MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT: Applies to functions. Makes it a compile - * time error to pass arithmetic expressions on variables to the function. - * MOZ_OWNING_REF: Applies to declarations of pointers to reference counted - * types. This attribute tells the compiler that the raw pointer is a strong - * reference, where ownership through methods such as AddRef and Release is - * managed manually. This can make the compiler ignore these pointers when - * validating the usage of pointers otherwise. - * - * Example uses include owned pointers inside of unions, and pointers stored - * in POD types where a using a smart pointer class would make the object - * non-POD. - * MOZ_NON_OWNING_REF: Applies to declarations of pointers to reference counted - * types. This attribute tells the compiler that the raw pointer is a weak - * reference, which is ensured to be valid by a guarantee that the reference - * will be nulled before the pointer becomes invalid. This can make the compiler - * ignore these pointers when validating the usage of pointers otherwise. - * - * Examples include an mOwner pointer, which is nulled by the owning class's - * destructor, and is null-checked before dereferencing. - * MOZ_UNSAFE_REF: Applies to declarations of pointers to reference counted types. - * Occasionally there are non-owning references which are valid, but do not take - * the form of a MOZ_NON_OWNING_REF. Their safety may be dependent on the behaviour - * of API consumers. The string argument passed to this macro documents the safety - * conditions. This can make the compiler ignore these pointers when validating - * the usage of pointers elsewhere. - * - * Examples include an nsIAtom* member which is known at compile time to point to a - * static atom which is valid throughout the lifetime of the program, or an API which - * stores a pointer, but doesn't take ownership over it, instead requiring the API - * consumer to correctly null the value before it becomes invalid. - * - * Use of this annotation is discouraged when a strong reference or one of the above - * two annotations can be used instead. - * MOZ_NO_ADDREF_RELEASE_ON_RETURN: Applies to function declarations. Makes it - * a compile time error to call AddRef or Release on the return value of a - * function. This is intended to be used with operator->() of our smart - * pointer classes to ensure that the refcount of an object wrapped in a - * smart pointer is not manipulated directly. - * MOZ_MUST_USE_TYPE: Applies to type declarations. Makes it a compile time - * error to not use the return value of a function which has this type. This - * is intended to be used with types which it is an error to not use. - * MOZ_NEEDS_NO_VTABLE_TYPE: Applies to template class declarations. Makes it - * a compile time error to instantiate this template with a type parameter which - * has a VTable. - * MOZ_NON_MEMMOVABLE: Applies to class declarations for types that are not safe - * to be moved in memory using memmove(). - * MOZ_NEEDS_MEMMOVABLE_TYPE: Applies to template class declarations where the - * template arguments are required to be safe to move in memory using - * memmove(). Passing MOZ_NON_MEMMOVABLE types to these templates is a - * compile time error. - * MOZ_NEEDS_MEMMOVABLE_MEMBERS: Applies to class declarations where each member - * must be safe to move in memory using memmove(). MOZ_NON_MEMMOVABLE types - * used in members of these classes are compile time errors. - * MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS: Applies to template class - * declarations where an instance of the template should be considered, for - * static analysis purposes, to inherit any type annotations (such as - * MOZ_MUST_USE_TYPE and MOZ_STACK_CLASS) from its template arguments. - * MOZ_INIT_OUTSIDE_CTOR: Applies to class member declarations. Occasionally - * there are class members that are not initialized in the constructor, - * but logic elsewhere in the class ensures they are initialized prior to use. - * Using this attribute on a member disables the check that this member must be - * initialized in constructors via list-initialization, in the constructor body, - * or via functions called from the constructor body. - * MOZ_IS_CLASS_INIT: Applies to class method declarations. Occasionally the - * constructor doesn't initialize all of the member variables and another function - * is used to initialize the rest. This marker is used to make the static analysis - * tool aware that the marked function is part of the initialization process - * and to include the marked function in the scan mechanism that determines witch - * member variables still remain uninitialized. - * MOZ_NON_PARAM: Applies to types. Makes it compile time error to use the type - * in parameter without pointer or reference. - * MOZ_NON_AUTOABLE: Applies to class declarations. Makes it a compile time error to - * use `auto` in place of this type in variable declarations. This is intended to - * be used with types which are intended to be implicitly constructed into other - * other types before being assigned to variables. - * MOZ_REQUIRED_BASE_METHOD: Applies to virtual class method declarations. - * Sometimes derived classes override methods that need to be called by their - * overridden counterparts. This marker indicates that the marked method must - * be called by the method that it overrides. - */ -#ifdef MOZ_CLANG_PLUGIN -# define MOZ_MUST_OVERRIDE __attribute__((annotate("moz_must_override"))) -# define MOZ_STACK_CLASS __attribute__((annotate("moz_stack_class"))) -# define MOZ_NONHEAP_CLASS __attribute__((annotate("moz_nonheap_class"))) -# define MOZ_HEAP_CLASS __attribute__((annotate("moz_heap_class"))) -# define MOZ_NON_TEMPORARY_CLASS __attribute__((annotate("moz_non_temporary_class"))) -# define MOZ_TRIVIAL_CTOR_DTOR __attribute__((annotate("moz_trivial_ctor_dtor"))) -# ifdef DEBUG - /* in debug builds, these classes do have non-trivial constructors. */ -# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS __attribute__((annotate("moz_global_class"))) -# else -# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS __attribute__((annotate("moz_global_class"))) \ - MOZ_TRIVIAL_CTOR_DTOR -# endif -# define MOZ_IMPLICIT __attribute__((annotate("moz_implicit"))) -# define MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT __attribute__((annotate("moz_no_arith_expr_in_arg"))) -# define MOZ_OWNING_REF __attribute__((annotate("moz_strong_ref"))) -# define MOZ_NON_OWNING_REF __attribute__((annotate("moz_weak_ref"))) -# define MOZ_UNSAFE_REF(reason) __attribute__((annotate("moz_weak_ref"))) -# define MOZ_NO_ADDREF_RELEASE_ON_RETURN __attribute__((annotate("moz_no_addref_release_on_return"))) -# define MOZ_MUST_USE_TYPE __attribute__((annotate("moz_must_use_type"))) -# define MOZ_NEEDS_NO_VTABLE_TYPE __attribute__((annotate("moz_needs_no_vtable_type"))) -# define MOZ_NON_MEMMOVABLE __attribute__((annotate("moz_non_memmovable"))) -# define MOZ_NEEDS_MEMMOVABLE_TYPE __attribute__((annotate("moz_needs_memmovable_type"))) -# define MOZ_NEEDS_MEMMOVABLE_MEMBERS __attribute__((annotate("moz_needs_memmovable_members"))) -# define MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS \ - __attribute__((annotate("moz_inherit_type_annotations_from_template_args"))) -# define MOZ_NON_AUTOABLE __attribute__((annotate("moz_non_autoable"))) -# define MOZ_INIT_OUTSIDE_CTOR \ - __attribute__((annotate("moz_ignore_ctor_initialization"))) -# define MOZ_IS_CLASS_INIT \ - __attribute__((annotate("moz_is_class_init"))) -# define MOZ_NON_PARAM \ - __attribute__((annotate("moz_non_param"))) -# define MOZ_REQUIRED_BASE_METHOD \ - __attribute__((annotate("moz_required_base_method"))) -/* - * It turns out that clang doesn't like void func() __attribute__ {} without a - * warning, so use pragmas to disable the warning. This code won't work on GCC - * anyways, so the warning is safe to ignore. - */ -# define MOZ_HEAP_ALLOCATOR \ - _Pragma("clang diagnostic push") \ - _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ - __attribute__((annotate("moz_heap_allocator"))) \ - _Pragma("clang diagnostic pop") -#else -# define MOZ_MUST_OVERRIDE /* nothing */ -# define MOZ_STACK_CLASS /* nothing */ -# define MOZ_NONHEAP_CLASS /* nothing */ -# define MOZ_HEAP_CLASS /* nothing */ -# define MOZ_NON_TEMPORARY_CLASS /* nothing */ -# define MOZ_TRIVIAL_CTOR_DTOR /* nothing */ -# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS /* nothing */ -# define MOZ_IMPLICIT /* nothing */ -# define MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT /* nothing */ -# define MOZ_HEAP_ALLOCATOR /* nothing */ -# define MOZ_OWNING_REF /* nothing */ -# define MOZ_NON_OWNING_REF /* nothing */ -# define MOZ_UNSAFE_REF(reason) /* nothing */ -# define MOZ_NO_ADDREF_RELEASE_ON_RETURN /* nothing */ -# define MOZ_MUST_USE_TYPE /* nothing */ -# define MOZ_NEEDS_NO_VTABLE_TYPE /* nothing */ -# define MOZ_NON_MEMMOVABLE /* nothing */ -# define MOZ_NEEDS_MEMMOVABLE_TYPE /* nothing */ -# define MOZ_NEEDS_MEMMOVABLE_MEMBERS /* nothing */ -# define MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS /* nothing */ -# define MOZ_INIT_OUTSIDE_CTOR /* nothing */ -# define MOZ_IS_CLASS_INIT /* nothing */ -# define MOZ_NON_PARAM /* nothing */ -# define MOZ_NON_AUTOABLE /* nothing */ -# define MOZ_REQUIRED_BASE_METHOD /* nothing */ -#endif /* MOZ_CLANG_PLUGIN */ - -#define MOZ_RAII MOZ_NON_TEMPORARY_CLASS MOZ_STACK_CLASS - -/* - * MOZ_HAVE_REF_QUALIFIERS is defined for compilers that support C++11's rvalue - * qualifier, "&&". - */ -#if defined(_MSC_VER) && _MSC_VER >= 1900 -# define MOZ_HAVE_REF_QUALIFIERS -#elif defined(__clang__) -// All supported Clang versions -# define MOZ_HAVE_REF_QUALIFIERS -#elif defined(__GNUC__) -# include "mozilla/Compiler.h" -# if MOZ_GCC_VERSION_AT_LEAST(4, 8, 1) -# define MOZ_HAVE_REF_QUALIFIERS -# endif -#endif - -#endif /* __cplusplus */ - -/** - * Printf style formats. MOZ_FORMAT_PRINTF can be used to annotate a - * function or method that is "printf-like"; this will let (some) - * compilers check that the arguments match the template string. - * - * This macro takes two arguments. The first argument is the argument - * number of the template string. The second argument is the argument - * number of the '...' argument holding the arguments. - * - * Argument numbers start at 1. Note that the implicit "this" - * argument of a non-static member function counts as an argument. - * - * So, for a simple case like: - * void print_something (int whatever, const char *fmt, ...); - * The corresponding annotation would be - * MOZ_FORMAT_PRINTF(2, 3) - * However, if "print_something" were a non-static member function, - * then the annotation would be: - * MOZ_FORMAT_PRINTF(3, 4) - * - * Note that the checking is limited to standards-conforming - * printf-likes, and in particular this should not be used for - * PR_snprintf and friends, which are "printf-like" but which assign - * different meanings to the various formats. - */ -#ifdef __GNUC__ -#define MOZ_FORMAT_PRINTF(stringIndex, firstToCheck) \ - __attribute__ ((format (printf, stringIndex, firstToCheck))) -#else -#define MOZ_FORMAT_PRINTF(stringIndex, firstToCheck) -#endif - -#endif /* mozilla_Attributes_h */ diff --git a/ios/include/spidermonkey/mozilla/BinarySearch.h b/ios/include/spidermonkey/mozilla/BinarySearch.h deleted file mode 100644 index 1bbe0566..00000000 --- a/ios/include/spidermonkey/mozilla/BinarySearch.h +++ /dev/null @@ -1,139 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_BinarySearch_h -#define mozilla_BinarySearch_h - -#include "mozilla/Assertions.h" - -#include - -namespace mozilla { - -/* - * The BinarySearch() algorithm searches the given container |aContainer| over - * the sorted index range [aBegin, aEnd) for an index |i| where - * |aContainer[i] == aTarget|. - * If such an index |i| is found, BinarySearch returns |true| and the index is - * returned via the outparam |aMatchOrInsertionPoint|. If no index is found, - * BinarySearch returns |false| and the outparam returns the first index in - * [aBegin, aEnd] where |aTarget| can be inserted to maintain sorted order. - * - * Example: - * - * Vector sortedInts = ... - * - * size_t match; - * if (BinarySearch(sortedInts, 0, sortedInts.length(), 13, &match)) { - * printf("found 13 at %lu\n", match); - * } - * - * The BinarySearchIf() version behaves similarly, but takes |aComparator|, a - * functor to compare the values with, instead of a value to find. - * That functor should take one argument - the value to compare - and return an - * |int| with the comparison result: - * - * * 0, if the argument is equal to, - * * less than 0, if the argument is greater than, - * * greater than 0, if the argument is less than - * - * the value. - * - * Example: - * - * struct Comparator { - * int operator()(int aVal) const { - * if (mTarget < aVal) { return -1; } - * if (mTarget > aVal) { return 1; } - * return 0; - * } - * explicit Comparator(int aTarget) : mTarget(aTarget) {} - * const int mTarget; - * }; - * - * Vector sortedInts = ... - * - * size_t match; - * if (BinarySearchIf(sortedInts, 0, sortedInts.length(), Comparator(13), &match)) { - * printf("found 13 at %lu\n", match); - * } - * - */ - -template -bool -BinarySearchIf(const Container& aContainer, size_t aBegin, size_t aEnd, - const Comparator& aCompare, size_t* aMatchOrInsertionPoint) -{ - MOZ_ASSERT(aBegin <= aEnd); - - size_t low = aBegin; - size_t high = aEnd; - while (high != low) { - size_t middle = low + (high - low) / 2; - - // Allow any intermediate type so long as it provides a suitable ordering - // relation. - const int result = aCompare(aContainer[middle]); - - if (result == 0) { - *aMatchOrInsertionPoint = middle; - return true; - } - - if (result < 0) { - high = middle; - } else { - low = middle + 1; - } - } - - *aMatchOrInsertionPoint = low; - return false; -} - -namespace detail { - -template -class BinarySearchDefaultComparator -{ -public: - explicit BinarySearchDefaultComparator(const T& aTarget) - : mTarget(aTarget) - {} - - template - int operator()(const U& aVal) const { - if (mTarget == aVal) { - return 0; - } - - if (mTarget < aVal) { - return -1; - } - - return 1; - } - -private: - const T& mTarget; -}; - -} // namespace detail - -template -bool -BinarySearch(const Container& aContainer, size_t aBegin, size_t aEnd, - T aTarget, size_t* aMatchOrInsertionPoint) -{ - return BinarySearchIf(aContainer, aBegin, aEnd, - detail::BinarySearchDefaultComparator(aTarget), - aMatchOrInsertionPoint); -} - -} // namespace mozilla - -#endif // mozilla_BinarySearch_h diff --git a/ios/include/spidermonkey/mozilla/BloomFilter.h b/ios/include/spidermonkey/mozilla/BloomFilter.h deleted file mode 100644 index 6757e411..00000000 --- a/ios/include/spidermonkey/mozilla/BloomFilter.h +++ /dev/null @@ -1,256 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * A counting Bloom filter implementation. This allows consumers to - * do fast probabilistic "is item X in set Y?" testing which will - * never answer "no" when the correct answer is "yes" (but might - * incorrectly answer "yes" when the correct answer is "no"). - */ - -#ifndef mozilla_BloomFilter_h -#define mozilla_BloomFilter_h - -#include "mozilla/Assertions.h" -#include "mozilla/Likely.h" - -#include -#include - -namespace mozilla { - -/* - * This class implements a counting Bloom filter as described at - * , with - * 8-bit counters. This allows quick probabilistic answers to the - * question "is object X in set Y?" where the contents of Y might not - * be time-invariant. The probabilistic nature of the test means that - * sometimes the answer will be "yes" when it should be "no". If the - * answer is "no", then X is guaranteed not to be in Y. - * - * The filter is parametrized on KeySize, which is the size of the key - * generated by each of hash functions used by the filter, in bits, - * and the type of object T being added and removed. T must implement - * a |uint32_t hash() const| method which returns a uint32_t hash key - * that will be used to generate the two separate hash functions for - * the Bloom filter. This hash key MUST be well-distributed for good - * results! KeySize is not allowed to be larger than 16. - * - * The filter uses exactly 2**KeySize bytes of memory. From now on we - * will refer to the memory used by the filter as M. - * - * The expected rate of incorrect "yes" answers depends on M and on - * the number N of objects in set Y. As long as N is small compared - * to M, the rate of such answers is expected to be approximately - * 4*(N/M)**2 for this filter. In practice, if Y has a few hundred - * elements then using a KeySize of 12 gives a reasonably low - * incorrect answer rate. A KeySize of 12 has the additional benefit - * of using exactly one page for the filter in typical hardware - * configurations. - */ - -template -class BloomFilter -{ - /* - * A counting Bloom filter with 8-bit counters. For now we assume - * that having two hash functions is enough, but we may revisit that - * decision later. - * - * The filter uses an array with 2**KeySize entries. - * - * Assuming a well-distributed hash function, a Bloom filter with - * array size M containing N elements and - * using k hash function has expected false positive rate exactly - * - * $ (1 - (1 - 1/M)^{kN})^k $ - * - * because each array slot has a - * - * $ (1 - 1/M)^{kN} $ - * - * chance of being 0, and the expected false positive rate is the - * probability that all of the k hash functions will hit a nonzero - * slot. - * - * For reasonable assumptions (M large, kN large, which should both - * hold if we're worried about false positives) about M and kN this - * becomes approximately - * - * $$ (1 - \exp(-kN/M))^k $$ - * - * For our special case of k == 2, that's $(1 - \exp(-2N/M))^2$, - * or in other words - * - * $$ N/M = -0.5 * \ln(1 - \sqrt(r)) $$ - * - * where r is the false positive rate. This can be used to compute - * the desired KeySize for a given load N and false positive rate r. - * - * If N/M is assumed small, then the false positive rate can - * further be approximated as 4*N^2/M^2. So increasing KeySize by - * 1, which doubles M, reduces the false positive rate by about a - * factor of 4, and a false positive rate of 1% corresponds to - * about M/N == 20. - * - * What this means in practice is that for a few hundred keys using a - * KeySize of 12 gives false positive rates on the order of 0.25-4%. - * - * Similarly, using a KeySize of 10 would lead to a 4% false - * positive rate for N == 100 and to quite bad false positive - * rates for larger N. - */ -public: - BloomFilter() - { - static_assert(KeySize <= kKeyShift, "KeySize too big"); - - // Should we have a custom operator new using calloc instead and - // require that we're allocated via the operator? - clear(); - } - - /* - * Clear the filter. This should be done before reusing it, because - * just removing all items doesn't clear counters that hit the upper - * bound. - */ - void clear(); - - /* - * Add an item to the filter. - */ - void add(const T* aValue); - - /* - * Remove an item from the filter. - */ - void remove(const T* aValue); - - /* - * Check whether the filter might contain an item. This can - * sometimes return true even if the item is not in the filter, - * but will never return false for items that are actually in the - * filter. - */ - bool mightContain(const T* aValue) const; - - /* - * Methods for add/remove/contain when we already have a hash computed - */ - void add(uint32_t aHash); - void remove(uint32_t aHash); - bool mightContain(uint32_t aHash) const; - -private: - static const size_t kArraySize = (1 << KeySize); - static const uint32_t kKeyMask = (1 << KeySize) - 1; - static const uint32_t kKeyShift = 16; - - static uint32_t hash1(uint32_t aHash) - { - return aHash & kKeyMask; - } - static uint32_t hash2(uint32_t aHash) - { - return (aHash >> kKeyShift) & kKeyMask; - } - - uint8_t& firstSlot(uint32_t aHash) - { - return mCounters[hash1(aHash)]; - } - uint8_t& secondSlot(uint32_t aHash) - { - return mCounters[hash2(aHash)]; - } - - const uint8_t& firstSlot(uint32_t aHash) const - { - return mCounters[hash1(aHash)]; - } - const uint8_t& secondSlot(uint32_t aHash) const - { - return mCounters[hash2(aHash)]; - } - - static bool full(const uint8_t& aSlot) { return aSlot == UINT8_MAX; } - - uint8_t mCounters[kArraySize]; -}; - -template -inline void -BloomFilter::clear() -{ - memset(mCounters, 0, kArraySize); -} - -template -inline void -BloomFilter::add(uint32_t aHash) -{ - uint8_t& slot1 = firstSlot(aHash); - if (MOZ_LIKELY(!full(slot1))) { - ++slot1; - } - uint8_t& slot2 = secondSlot(aHash); - if (MOZ_LIKELY(!full(slot2))) { - ++slot2; - } -} - -template -MOZ_ALWAYS_INLINE void -BloomFilter::add(const T* aValue) -{ - uint32_t hash = aValue->hash(); - return add(hash); -} - -template -inline void -BloomFilter::remove(uint32_t aHash) -{ - // If the slots are full, we don't know whether we bumped them to be - // there when we added or not, so just leave them full. - uint8_t& slot1 = firstSlot(aHash); - if (MOZ_LIKELY(!full(slot1))) { - --slot1; - } - uint8_t& slot2 = secondSlot(aHash); - if (MOZ_LIKELY(!full(slot2))) { - --slot2; - } -} - -template -MOZ_ALWAYS_INLINE void -BloomFilter::remove(const T* aValue) -{ - uint32_t hash = aValue->hash(); - remove(hash); -} - -template -MOZ_ALWAYS_INLINE bool -BloomFilter::mightContain(uint32_t aHash) const -{ - // Check that all the slots for this hash contain something - return firstSlot(aHash) && secondSlot(aHash); -} - -template -MOZ_ALWAYS_INLINE bool -BloomFilter::mightContain(const T* aValue) const -{ - uint32_t hash = aValue->hash(); - return mightContain(hash); -} - -} // namespace mozilla - -#endif /* mozilla_BloomFilter_h */ diff --git a/ios/include/spidermonkey/mozilla/BufferList.h b/ios/include/spidermonkey/mozilla/BufferList.h deleted file mode 100644 index 42aea12d..00000000 --- a/ios/include/spidermonkey/mozilla/BufferList.h +++ /dev/null @@ -1,517 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_BufferList_h -#define mozilla_BufferList_h - -#include -#include "mozilla/AllocPolicy.h" -#include "mozilla/Move.h" -#include "mozilla/ScopeExit.h" -#include "mozilla/Types.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Vector.h" -#include - -// BufferList represents a sequence of buffers of data. A BufferList can choose -// to own its buffers or not. The class handles writing to the buffers, -// iterating over them, and reading data out. Unlike SegmentedVector, the -// buffers may be of unequal size. Like SegmentedVector, BufferList is a nice -// way to avoid large contiguous allocations (which can trigger OOMs). - -namespace mozilla { - -template -class BufferList : private AllocPolicy -{ - // Each buffer in a BufferList has a size and a capacity. The first mSize - // bytes are initialized and the remaining |mCapacity - mSize| bytes are free. - struct Segment - { - char* mData; - size_t mSize; - size_t mCapacity; - - Segment(char* aData, size_t aSize, size_t aCapacity) - : mData(aData), - mSize(aSize), - mCapacity(aCapacity) - { - } - - Segment(const Segment&) = delete; - Segment& operator=(const Segment&) = delete; - - Segment(Segment&&) = default; - Segment& operator=(Segment&&) = default; - - char* Start() const { return mData; } - char* End() const { return mData + mSize; } - }; - - template - friend class BufferList; - - public: - // For the convenience of callers, all segments are required to be a multiple - // of 8 bytes in capacity. Also, every buffer except the last one is required - // to be full (i.e., size == capacity). Therefore, a byte at offset N within - // the BufferList and stored in memory at an address A will satisfy - // (N % Align == A % Align) if Align == 2, 4, or 8. - static const size_t kSegmentAlignment = 8; - - // Allocate a BufferList. The BufferList will free all its buffers when it is - // destroyed. An initial buffer of size aInitialSize and capacity - // aInitialCapacity is allocated automatically. This data will be contiguous - // an can be accessed via |Start()|. Subsequent buffers will be allocated with - // capacity aStandardCapacity. - BufferList(size_t aInitialSize, - size_t aInitialCapacity, - size_t aStandardCapacity, - AllocPolicy aAP = AllocPolicy()) - : AllocPolicy(aAP), - mOwning(true), - mSegments(aAP), - mSize(0), - mStandardCapacity(aStandardCapacity) - { - MOZ_ASSERT(aInitialCapacity % kSegmentAlignment == 0); - MOZ_ASSERT(aStandardCapacity % kSegmentAlignment == 0); - - if (aInitialCapacity) { - AllocateSegment(aInitialSize, aInitialCapacity); - } - } - - BufferList(const BufferList& aOther) = delete; - - BufferList(BufferList&& aOther) - : mOwning(aOther.mOwning), - mSegments(Move(aOther.mSegments)), - mSize(aOther.mSize), - mStandardCapacity(aOther.mStandardCapacity) - { - aOther.mSegments.clear(); - aOther.mSize = 0; - } - - BufferList& operator=(const BufferList& aOther) = delete; - - BufferList& operator=(BufferList&& aOther) - { - Clear(); - - mOwning = aOther.mOwning; - mSegments = Move(aOther.mSegments); - mSize = aOther.mSize; - aOther.mSegments.clear(); - aOther.mSize = 0; - return *this; - } - - ~BufferList() { Clear(); } - - // Returns the sum of the sizes of all the buffers. - size_t Size() const { return mSize; } - - void Clear() - { - if (mOwning) { - for (Segment& segment : mSegments) { - this->free_(segment.mData); - } - } - mSegments.clear(); - - mSize = 0; - } - - // Iterates over bytes in the segments. You can advance it by as many bytes as - // you choose. - class IterImpl - { - // Invariants: - // (0) mSegment <= bufferList.mSegments.size() - // (1) mData <= mDataEnd - // (2) If mSegment is not the last segment, mData < mDataEnd - uintptr_t mSegment; - char* mData; - char* mDataEnd; - - friend class BufferList; - - public: - explicit IterImpl(const BufferList& aBuffers) - : mSegment(0), - mData(nullptr), - mDataEnd(nullptr) - { - if (!aBuffers.mSegments.empty()) { - mData = aBuffers.mSegments[0].Start(); - mDataEnd = aBuffers.mSegments[0].End(); - } - } - - // Returns a pointer to the raw data. It is valid to access up to - // RemainingInSegment bytes of this buffer. - char* Data() const - { - MOZ_RELEASE_ASSERT(!Done()); - return mData; - } - - // Returns true if the memory in the range [Data(), Data() + aBytes) is all - // part of one contiguous buffer. - bool HasRoomFor(size_t aBytes) const - { - MOZ_RELEASE_ASSERT(mData <= mDataEnd); - return size_t(mDataEnd - mData) >= aBytes; - } - - // Returns the maximum value aBytes for which HasRoomFor(aBytes) will be - // true. - size_t RemainingInSegment() const - { - MOZ_RELEASE_ASSERT(mData <= mDataEnd); - return mDataEnd - mData; - } - - // Advances the iterator by aBytes bytes. aBytes must be less than - // RemainingInSegment(). If advancing by aBytes takes the iterator to the - // end of a buffer, it will be moved to the beginning of the next buffer - // unless it is the last buffer. - void Advance(const BufferList& aBuffers, size_t aBytes) - { - const Segment& segment = aBuffers.mSegments[mSegment]; - MOZ_RELEASE_ASSERT(segment.Start() <= mData); - MOZ_RELEASE_ASSERT(mData <= mDataEnd); - MOZ_RELEASE_ASSERT(mDataEnd == segment.End()); - - MOZ_RELEASE_ASSERT(HasRoomFor(aBytes)); - mData += aBytes; - - if (mData == mDataEnd && mSegment + 1 < aBuffers.mSegments.length()) { - mSegment++; - const Segment& nextSegment = aBuffers.mSegments[mSegment]; - mData = nextSegment.Start(); - mDataEnd = nextSegment.End(); - MOZ_RELEASE_ASSERT(mData < mDataEnd); - } - } - - // Advance the iterator by aBytes, possibly crossing segments. This function - // returns false if it runs out of buffers to advance through. Otherwise it - // returns true. - bool AdvanceAcrossSegments(const BufferList& aBuffers, size_t aBytes) - { - size_t bytes = aBytes; - while (bytes) { - size_t toAdvance = std::min(bytes, RemainingInSegment()); - if (!toAdvance) { - return false; - } - Advance(aBuffers, toAdvance); - bytes -= toAdvance; - } - return true; - } - - // Returns true when the iterator reaches the end of the BufferList. - bool Done() const - { - return mData == mDataEnd; - } - - private: - - // Count the bytes we would need to advance in order to reach aTarget. - size_t BytesUntil(const BufferList& aBuffers, const IterImpl& aTarget) const { - size_t offset = 0; - - MOZ_ASSERT(aTarget.IsIn(aBuffers)); - - char* data = mData; - for (uintptr_t segment = mSegment; segment < aTarget.mSegment; segment++) { - offset += aBuffers.mSegments[segment].End() - data; - data = aBuffers.mSegments[segment].mData; - } - - MOZ_RELEASE_ASSERT(IsIn(aBuffers)); - MOZ_RELEASE_ASSERT(aTarget.mData >= data); - - offset += aTarget.mData - data; - return offset; - } - - bool IsIn(const BufferList& aBuffers) const { - return mSegment < aBuffers.mSegments.length() && - mData >= aBuffers.mSegments[mSegment].mData && - mData < aBuffers.mSegments[mSegment].End(); - } - }; - - // Special convenience method that returns Iter().Data(). - char* Start() { return mSegments[0].mData; } - const char* Start() const { return mSegments[0].mData; } - - IterImpl Iter() const { return IterImpl(*this); } - - // Copies aSize bytes from aData into the BufferList. The storage for these - // bytes may be split across multiple buffers. Size() is increased by aSize. - inline bool WriteBytes(const char* aData, size_t aSize); - - // Copies possibly non-contiguous byte range starting at aIter into - // aData. aIter is advanced by aSize bytes. Returns false if it runs out of - // data before aSize. - inline bool ReadBytes(IterImpl& aIter, char* aData, size_t aSize) const; - - // Return a new BufferList that shares storage with this BufferList. The new - // BufferList is read-only. It allows iteration over aSize bytes starting at - // aIter. Borrow can fail, in which case *aSuccess will be false upon - // return. The borrowed BufferList can use a different AllocPolicy than the - // original one. However, it is not responsible for freeing buffers, so the - // AllocPolicy is only used for the buffer vector. - template - BufferList Borrow(IterImpl& aIter, size_t aSize, bool* aSuccess, - BorrowingAllocPolicy aAP = BorrowingAllocPolicy()) const; - - // Return a new BufferList and move storage from this BufferList to it. The - // new BufferList owns the buffers. Move can fail, in which case *aSuccess - // will be false upon return. The new BufferList can use a different - // AllocPolicy than the original one. The new OtherAllocPolicy is responsible - // for freeing buffers, so the OtherAllocPolicy must use freeing method - // compatible to the original one. - template - BufferList MoveFallible(bool* aSuccess, OtherAllocPolicy aAP = OtherAllocPolicy()); - - // Return a new BufferList that adopts the byte range starting at Iter so that - // range [aIter, aIter + aSize) is transplanted to the returned BufferList. - // Contents of the buffer before aIter + aSize is left undefined. - // Extract can fail, in which case *aSuccess will be false upon return. The - // moved buffers are erased from the original BufferList. In case of extract - // fails, the original BufferList is intact. All other iterators except aIter - // are invalidated. - // This method requires aIter and aSize to be 8-byte aligned. - BufferList Extract(IterImpl& aIter, size_t aSize, bool* aSuccess); - - // Return the number of bytes from 'start' to 'end', two iterators within - // this BufferList. - size_t RangeLength(const IterImpl& start, const IterImpl& end) const { - MOZ_ASSERT(start.IsIn(*this) && end.IsIn(*this)); - return start.BytesUntil(*this, end); - } - -private: - explicit BufferList(AllocPolicy aAP) - : AllocPolicy(aAP), - mOwning(false), - mSize(0), - mStandardCapacity(0) - { - } - - void* AllocateSegment(size_t aSize, size_t aCapacity) - { - MOZ_RELEASE_ASSERT(mOwning); - - char* data = this->template pod_malloc(aCapacity); - if (!data) { - return nullptr; - } - if (!mSegments.append(Segment(data, aSize, aCapacity))) { - this->free_(data); - return nullptr; - } - mSize += aSize; - return data; - } - - bool mOwning; - Vector mSegments; - size_t mSize; - size_t mStandardCapacity; -}; - -template -bool -BufferList::WriteBytes(const char* aData, size_t aSize) -{ - MOZ_RELEASE_ASSERT(mOwning); - MOZ_RELEASE_ASSERT(mStandardCapacity); - - size_t copied = 0; - size_t remaining = aSize; - - if (!mSegments.empty()) { - Segment& lastSegment = mSegments.back(); - - size_t toCopy = std::min(aSize, lastSegment.mCapacity - lastSegment.mSize); - memcpy(lastSegment.mData + lastSegment.mSize, aData, toCopy); - lastSegment.mSize += toCopy; - mSize += toCopy; - - copied += toCopy; - remaining -= toCopy; - } - - while (remaining) { - size_t toCopy = std::min(remaining, mStandardCapacity); - - void* data = AllocateSegment(toCopy, mStandardCapacity); - if (!data) { - return false; - } - memcpy(data, aData + copied, toCopy); - - copied += toCopy; - remaining -= toCopy; - } - - return true; -} - -template -bool -BufferList::ReadBytes(IterImpl& aIter, char* aData, size_t aSize) const -{ - size_t copied = 0; - size_t remaining = aSize; - while (remaining) { - size_t toCopy = std::min(aIter.RemainingInSegment(), remaining); - if (!toCopy) { - // We've run out of data in the last segment. - return false; - } - memcpy(aData + copied, aIter.Data(), toCopy); - copied += toCopy; - remaining -= toCopy; - - aIter.Advance(*this, toCopy); - } - - return true; -} - -template template -BufferList -BufferList::Borrow(IterImpl& aIter, size_t aSize, bool* aSuccess, - BorrowingAllocPolicy aAP) const -{ - BufferList result(aAP); - - size_t size = aSize; - while (size) { - size_t toAdvance = std::min(size, aIter.RemainingInSegment()); - - if (!toAdvance || !result.mSegments.append(typename BufferList::Segment(aIter.mData, toAdvance, toAdvance))) { - *aSuccess = false; - return result; - } - aIter.Advance(*this, toAdvance); - size -= toAdvance; - } - - result.mSize = aSize; - *aSuccess = true; - return result; -} - -template template -BufferList -BufferList::MoveFallible(bool* aSuccess, OtherAllocPolicy aAP) -{ - BufferList result(0, 0, mStandardCapacity, aAP); - - IterImpl iter = Iter(); - while (!iter.Done()) { - size_t toAdvance = iter.RemainingInSegment(); - - if (!toAdvance || !result.mSegments.append(typename BufferList::Segment(iter.mData, toAdvance, toAdvance))) { - *aSuccess = false; - result.mSegments.clear(); - return result; - } - iter.Advance(*this, toAdvance); - } - - result.mSize = mSize; - mSegments.clear(); - mSize = 0; - *aSuccess = true; - return result; -} - -template -BufferList -BufferList::Extract(IterImpl& aIter, size_t aSize, bool* aSuccess) -{ - MOZ_RELEASE_ASSERT(aSize); - MOZ_RELEASE_ASSERT(mOwning); - MOZ_ASSERT(aSize % kSegmentAlignment == 0); - MOZ_ASSERT(intptr_t(aIter.mData) % kSegmentAlignment == 0); - - IterImpl iter = aIter; - size_t size = aSize; - size_t toCopy = std::min(size, aIter.RemainingInSegment()); - MOZ_ASSERT(toCopy % kSegmentAlignment == 0); - - BufferList result(0, toCopy, mStandardCapacity); - BufferList error(0, 0, mStandardCapacity); - - // Copy the head - if (!result.WriteBytes(aIter.mData, toCopy)) { - *aSuccess = false; - return error; - } - iter.Advance(*this, toCopy); - size -= toCopy; - - // Move segments to result - auto resultGuard = MakeScopeExit([&] { - *aSuccess = false; - result.mSegments.erase(result.mSegments.begin()+1, result.mSegments.end()); - }); - - size_t movedSize = 0; - uintptr_t toRemoveStart = iter.mSegment; - uintptr_t toRemoveEnd = iter.mSegment; - while (!iter.Done() && - !iter.HasRoomFor(size)) { - if (!result.mSegments.append(Segment(mSegments[iter.mSegment].mData, - mSegments[iter.mSegment].mSize, - mSegments[iter.mSegment].mCapacity))) { - return error; - } - movedSize += iter.RemainingInSegment(); - size -= iter.RemainingInSegment(); - toRemoveEnd++; - iter.Advance(*this, iter.RemainingInSegment()); - } - - if (size) { - if (!iter.HasRoomFor(size) || - !result.WriteBytes(iter.Data(), size)) { - return error; - } - iter.Advance(*this, size); - } - - mSegments.erase(mSegments.begin() + toRemoveStart, mSegments.begin() + toRemoveEnd); - mSize -= movedSize; - aIter.mSegment = iter.mSegment - (toRemoveEnd - toRemoveStart); - aIter.mData = iter.mData; - aIter.mDataEnd = iter.mDataEnd; - MOZ_ASSERT(aIter.mDataEnd == mSegments[aIter.mSegment].End()); - result.mSize = aSize; - - resultGuard.release(); - *aSuccess = true; - return result; -} - -} // namespace mozilla - -#endif /* mozilla_BufferList_h */ diff --git a/ios/include/spidermonkey/mozilla/Casting.h b/ios/include/spidermonkey/mozilla/Casting.h deleted file mode 100644 index a7d0fb50..00000000 --- a/ios/include/spidermonkey/mozilla/Casting.h +++ /dev/null @@ -1,243 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Cast operations to supplement the built-in casting operations. */ - -#ifndef mozilla_Casting_h -#define mozilla_Casting_h - -#include "mozilla/Assertions.h" -#include "mozilla/TypeTraits.h" - -#include - -namespace mozilla { - -/** - * Sets the outparam value of type |To| with the same underlying bit pattern of - * |aFrom|. - * - * |To| and |From| must be types of the same size; be careful of cross-platform - * size differences, or this might fail to compile on some but not all - * platforms. - * - * There is also a variant that returns the value directly. In most cases, the - * two variants should be identical. However, in the specific case of x86 - * chips, the behavior differs: returning floating-point values directly is done - * through the x87 stack, and x87 loads and stores turn signaling NaNs into - * quiet NaNs... silently. Returning floating-point values via outparam, - * however, is done entirely within the SSE registers when SSE2 floating-point - * is enabled in the compiler, which has semantics-preserving behavior you would - * expect. - * - * If preserving the distinction between signaling NaNs and quiet NaNs is - * important to you, you should use the outparam version. In all other cases, - * you should use the direct return version. - */ -template -inline void -BitwiseCast(const From aFrom, To* aResult) -{ - static_assert(sizeof(From) == sizeof(To), - "To and From must have the same size"); - union - { - From mFrom; - To mTo; - } u; - u.mFrom = aFrom; - *aResult = u.mTo; -} - -template -inline To -BitwiseCast(const From aFrom) -{ - To temp; - BitwiseCast(aFrom, &temp); - return temp; -} - -namespace detail { - -enum ToSignedness { ToIsSigned, ToIsUnsigned }; -enum FromSignedness { FromIsSigned, FromIsUnsigned }; - -template::value ? FromIsSigned : FromIsUnsigned, - ToSignedness = IsSigned::value ? ToIsSigned : ToIsUnsigned> -struct BoundsCheckImpl; - -// Implicit conversions on operands to binary operations make this all a bit -// hard to verify. Attempt to ease the pain below by *only* comparing values -// that are obviously the same type (and will undergo no further conversions), -// even when it's not strictly necessary, for explicitness. - -enum UUComparison { FromIsBigger, FromIsNotBigger }; - -// Unsigned-to-unsigned range check - -template sizeof(To)) - ? FromIsBigger - : FromIsNotBigger> -struct UnsignedUnsignedCheck; - -template -struct UnsignedUnsignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - return aFrom <= From(To(-1)); - } -}; - -template -struct UnsignedUnsignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - return true; - } -}; - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - return UnsignedUnsignedCheck::checkBounds(aFrom); - } -}; - -// Signed-to-unsigned range check - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - if (aFrom < 0) { - return false; - } - if (sizeof(To) >= sizeof(From)) { - return true; - } - return aFrom <= From(To(-1)); - } -}; - -// Unsigned-to-signed range check - -enum USComparison { FromIsSmaller, FromIsNotSmaller }; - -template -struct UnsignedSignedCheck; - -template -struct UnsignedSignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - return true; - } -}; - -template -struct UnsignedSignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); - return aFrom <= From(MaxValue); - } -}; - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - return UnsignedSignedCheck::checkBounds(aFrom); - } -}; - -// Signed-to-signed range check - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - if (sizeof(From) <= sizeof(To)) { - return true; - } - const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); - const To MinValue = -MaxValue - To(1); - return From(MinValue) <= aFrom && - From(aFrom) <= From(MaxValue); - } -}; - -template::value && - IsIntegral::value> -class BoundsChecker; - -template -class BoundsChecker -{ -public: - static bool checkBounds(const From aFrom) { return true; } -}; - -template -class BoundsChecker -{ -public: - static bool checkBounds(const From aFrom) - { - return BoundsCheckImpl::checkBounds(aFrom); - } -}; - -template -inline bool -IsInBounds(const From aFrom) -{ - return BoundsChecker::checkBounds(aFrom); -} - -} // namespace detail - -/** - * Cast a value of integral type |From| to a value of integral type |To|, - * asserting that the cast will be a safe cast per C++ (that is, that |to| is in - * the range of values permitted for the type |From|). - */ -template -inline To -AssertedCast(const From aFrom) -{ - MOZ_ASSERT((detail::IsInBounds(aFrom))); - return static_cast(aFrom); -} - -} // namespace mozilla - -#endif /* mozilla_Casting_h */ diff --git a/ios/include/spidermonkey/mozilla/ChaosMode.h b/ios/include/spidermonkey/mozilla/ChaosMode.h deleted file mode 100644 index 94833c39..00000000 --- a/ios/include/spidermonkey/mozilla/ChaosMode.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_ChaosMode_h -#define mozilla_ChaosMode_h - -#include "mozilla/Atomics.h" -#include "mozilla/EnumSet.h" - -#include -#include - -namespace mozilla { - -enum ChaosFeature { - None = 0x0, - // Altering thread scheduling. - ThreadScheduling = 0x1, - // Altering network request scheduling. - NetworkScheduling = 0x2, - // Altering timer scheduling. - TimerScheduling = 0x4, - // Read and write less-than-requested amounts. - IOAmounts = 0x8, - // Iterate over hash tables in random order. - HashTableIteration = 0x10, - // Randomly refuse to use cached version of image (when allowed by spec). - ImageCache = 0x20, - Any = 0xffffffff, -}; - -namespace detail { -extern MFBT_DATA Atomic gChaosModeCounter; -extern MFBT_DATA ChaosFeature gChaosFeatures; -} // namespace detail - -/** - * When "chaos mode" is activated, code that makes implicitly nondeterministic - * choices is encouraged to make random and extreme choices, to test more - * code paths and uncover bugs. - */ -class ChaosMode -{ -public: - static void SetChaosFeature(ChaosFeature aChaosFeature) - { - detail::gChaosFeatures = aChaosFeature; - } - - static bool isActive(ChaosFeature aFeature) - { - if (detail::gChaosModeCounter > 0) { - return true; - } - return detail::gChaosFeatures & aFeature; - } - - /** - * Increase the chaos mode activation level. An equivalent number of - * calls to leaveChaosMode must be made in order to restore the original - * chaos mode state. If the activation level is nonzero all chaos mode - * features are activated. - */ - static void enterChaosMode() - { - detail::gChaosModeCounter++; - } - - /** - * Decrease the chaos mode activation level. See enterChaosMode(). - */ - static void leaveChaosMode() - { - MOZ_ASSERT(detail::gChaosModeCounter > 0); - detail::gChaosModeCounter--; - } - - /** - * Returns a somewhat (but not uniformly) random uint32_t < aBound. - * Not to be used for anything except ChaosMode, since it's not very random. - */ - static uint32_t randomUint32LessThan(uint32_t aBound) - { - MOZ_ASSERT(aBound != 0); - return uint32_t(rand()) % aBound; - } -}; - -} /* namespace mozilla */ - -#endif /* mozilla_ChaosMode_h */ diff --git a/ios/include/spidermonkey/mozilla/Char16.h b/ios/include/spidermonkey/mozilla/Char16.h deleted file mode 100644 index 3c2f254a..00000000 --- a/ios/include/spidermonkey/mozilla/Char16.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements a UTF-16 character type. */ - -#ifndef mozilla_Char16_h -#define mozilla_Char16_h - -#ifdef __cplusplus - -/* - * C++11 introduces a char16_t type and support for UTF-16 string and character - * literals. C++11's char16_t is a distinct builtin type. Technically, char16_t - * is a 16-bit code unit of a Unicode code point, not a "character". - */ - -#ifdef WIN32 -# define MOZ_USE_CHAR16_WRAPPER -# include - /** - * Win32 API extensively uses wchar_t, which is represented by a separated - * builtin type than char16_t per spec. It's not the case for MSVC prior to - * MSVC 2015, but other compilers follow the spec. We want to mix wchar_t and - * char16_t on Windows builds. This class is supposed to make it easier. It - * stores char16_t const pointer, but provides implicit casts for wchar_t as - * well. On other platforms, we simply use - * |typedef const char16_t* char16ptr_t|. Here, we want to make the class as - * similar to this typedef, including providing some casts that are allowed - * by the typedef. - */ -class char16ptr_t -{ -private: - const char16_t* mPtr; - static_assert(sizeof(char16_t) == sizeof(wchar_t), - "char16_t and wchar_t sizes differ"); - -public: - char16ptr_t(const char16_t* aPtr) : mPtr(aPtr) {} - char16ptr_t(const wchar_t* aPtr) : - mPtr(reinterpret_cast(aPtr)) - {} - - /* Without this, nullptr assignment would be ambiguous. */ - constexpr char16ptr_t(decltype(nullptr)) : mPtr(nullptr) {} - - operator const char16_t*() const - { - return mPtr; - } - operator const wchar_t*() const - { - return reinterpret_cast(mPtr); - } - operator const void*() const - { - return mPtr; - } - operator bool() const - { - return mPtr != nullptr; - } - - /* Explicit cast operators to allow things like (char16_t*)str. */ - explicit operator char16_t*() const - { - return const_cast(mPtr); - } - explicit operator wchar_t*() const - { - return const_cast(static_cast(*this)); - } - explicit operator int() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned int() const - { - return reinterpret_cast(mPtr); - } - explicit operator long() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned long() const - { - return reinterpret_cast(mPtr); - } - explicit operator long long() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned long long() const - { - return reinterpret_cast(mPtr); - } - - /** - * Some Windows API calls accept BYTE* but require that data actually be - * WCHAR*. Supporting this requires explicit operators to support the - * requisite explicit casts. - */ - explicit operator const char*() const - { - return reinterpret_cast(mPtr); - } - explicit operator const unsigned char*() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned char*() const - { - return - const_cast(reinterpret_cast(mPtr)); - } - explicit operator void*() const - { - return const_cast(mPtr); - } - - /* Some operators used on pointers. */ - char16_t operator[](size_t aIndex) const - { - return mPtr[aIndex]; - } - bool operator==(const char16ptr_t& aOther) const - { - return mPtr == aOther.mPtr; - } - bool operator==(decltype(nullptr)) const - { - return mPtr == nullptr; - } - bool operator!=(const char16ptr_t& aOther) const - { - return mPtr != aOther.mPtr; - } - bool operator!=(decltype(nullptr)) const - { - return mPtr != nullptr; - } - char16ptr_t operator+(int aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(unsigned int aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(unsigned long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(long long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(unsigned long long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - ptrdiff_t operator-(const char16ptr_t& aOther) const - { - return mPtr - aOther.mPtr; - } -}; - -inline decltype((char*)0-(char*)0) -operator-(const char16_t* aX, const char16ptr_t aY) -{ - return aX - static_cast(aY); -} - -#else - -typedef const char16_t* char16ptr_t; - -#endif - -static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); -static_assert(char16_t(-1) > char16_t(0), "Is char16_t type unsigned?"); -static_assert(sizeof(u'A') == 2, "Is unicode char literal 16 bits?"); -static_assert(sizeof(u""[0]) == 2, "Is unicode string char 16 bits?"); - -#endif - -#endif /* mozilla_Char16_h */ diff --git a/ios/include/spidermonkey/mozilla/CheckedInt.h b/ios/include/spidermonkey/mozilla/CheckedInt.h deleted file mode 100644 index 02ef8d5b..00000000 --- a/ios/include/spidermonkey/mozilla/CheckedInt.h +++ /dev/null @@ -1,791 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Provides checked integers, detecting integer overflow and divide-by-0. */ - -#ifndef mozilla_CheckedInt_h -#define mozilla_CheckedInt_h - -#include -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/IntegerTypeTraits.h" - -namespace mozilla { - -template class CheckedInt; - -namespace detail { - -/* - * Step 1: manually record supported types - * - * What's nontrivial here is that there are different families of integer - * types: basic integer types and stdint types. It is merrily undefined which - * types from one family may be just typedefs for a type from another family. - * - * For example, on GCC 4.6, aside from the basic integer types, the only other - * type that isn't just a typedef for some of them, is int8_t. - */ - -struct UnsupportedType {}; - -template -struct IsSupportedPass2 -{ - static const bool value = false; -}; - -template -struct IsSupported -{ - static const bool value = IsSupportedPass2::value; -}; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -/* - * Step 2: Implement the actual validity checks. - * - * Ideas taken from IntegerLib, code different. - */ - -template -struct TwiceBiggerType -{ - typedef typename detail::StdintTypeForSizeAndSignedness< - sizeof(IntegerType) * 2, - IsSigned::value - >::Type Type; -}; - -template -struct TwiceBiggerType -{ - typedef UnsupportedType Type; -}; - -template -inline bool -HasSignBit(T aX) -{ - // In C++, right bit shifts on negative values is undefined by the standard. - // Notice that signed-to-unsigned conversions are always well-defined in the - // standard, as the value congruent modulo 2**n as expected. By contrast, - // unsigned-to-signed is only well-defined if the value is representable. - return bool(typename MakeUnsigned::Type(aX) >> - PositionOfSignBit::value); -} - -// Bitwise ops may return a larger type, so it's good to use this inline -// helper guaranteeing that the result is really of type T. -template -inline T -BinaryComplement(T aX) -{ - return ~aX; -} - -template::value, - bool IsUSigned = IsSigned::value> -struct DoesRangeContainRange -{ -}; - -template -struct DoesRangeContainRange -{ - static const bool value = sizeof(T) >= sizeof(U); -}; - -template -struct DoesRangeContainRange -{ - static const bool value = sizeof(T) > sizeof(U); -}; - -template -struct DoesRangeContainRange -{ - static const bool value = false; -}; - -template::value, - bool IsUSigned = IsSigned::value, - bool DoesTRangeContainURange = DoesRangeContainRange::value> -struct IsInRangeImpl {}; - -template -struct IsInRangeImpl -{ - static bool run(U) - { - return true; - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return aX <= MaxValue::value && aX >= MinValue::value; - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return aX <= MaxValue::value; - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return sizeof(T) > sizeof(U) || aX <= U(MaxValue::value); - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return sizeof(T) >= sizeof(U) - ? aX >= 0 - : aX >= 0 && aX <= U(MaxValue::value); - } -}; - -template -inline bool -IsInRange(U aX) -{ - return IsInRangeImpl::run(aX); -} - -template -inline bool -IsAddValid(T aX, T aY) -{ - // Addition is valid if the sign of aX+aY is equal to either that of aX or - // that of aY. Since the value of aX+aY is undefined if we have a signed - // type, we compute it using the unsigned type of the same size. Beware! - // These bitwise operations can return a larger integer type, if T was a - // small type like int8_t, so we explicitly cast to T. - - typename MakeUnsigned::Type ux = aX; - typename MakeUnsigned::Type uy = aY; - typename MakeUnsigned::Type result = ux + uy; - return IsSigned::value - ? HasSignBit(BinaryComplement(T((result ^ aX) & (result ^ aY)))) - : BinaryComplement(aX) >= aY; -} - -template -inline bool -IsSubValid(T aX, T aY) -{ - // Subtraction is valid if either aX and aY have same sign, or aX-aY and aX - // have same sign. Since the value of aX-aY is undefined if we have a signed - // type, we compute it using the unsigned type of the same size. - typename MakeUnsigned::Type ux = aX; - typename MakeUnsigned::Type uy = aY; - typename MakeUnsigned::Type result = ux - uy; - - return IsSigned::value - ? HasSignBit(BinaryComplement(T((result ^ aX) & (aX ^ aY)))) - : aX >= aY; -} - -template::value, - bool TwiceBiggerTypeIsSupported = - IsSupported::Type>::value> -struct IsMulValidImpl {}; - -template -struct IsMulValidImpl -{ - static bool run(T aX, T aY) - { - typedef typename TwiceBiggerType::Type TwiceBiggerType; - TwiceBiggerType product = TwiceBiggerType(aX) * TwiceBiggerType(aY); - return IsInRange(product); - } -}; - -template -struct IsMulValidImpl -{ - static bool run(T aX, T aY) - { - const T max = MaxValue::value; - const T min = MinValue::value; - - if (aX == 0 || aY == 0) { - return true; - } - if (aX > 0) { - return aY > 0 - ? aX <= max / aY - : aY >= min / aX; - } - - // If we reach this point, we know that aX < 0. - return aY > 0 - ? aX >= min / aY - : aY >= max / aX; - } -}; - -template -struct IsMulValidImpl -{ - static bool run(T aX, T aY) - { - return aY == 0 || aX <= MaxValue::value / aY; - } -}; - -template -inline bool -IsMulValid(T aX, T aY) -{ - return IsMulValidImpl::run(aX, aY); -} - -template -inline bool -IsDivValid(T aX, T aY) -{ - // Keep in mind that in the signed case, min/-1 is invalid because - // abs(min)>max. - return aY != 0 && - !(IsSigned::value && aX == MinValue::value && aY == T(-1)); -} - -template::value> -struct IsModValidImpl; - -template -inline bool -IsModValid(T aX, T aY) -{ - return IsModValidImpl::run(aX, aY); -} - -/* - * Mod is pretty simple. - * For now, let's just use the ANSI C definition: - * If aX or aY are negative, the results are implementation defined. - * Consider these invalid. - * Undefined for aY=0. - * The result will never exceed either aX or aY. - * - * Checking that aX>=0 is a warning when T is unsigned. - */ - -template -struct IsModValidImpl -{ - static inline bool run(T aX, T aY) - { - return aY >= 1; - } -}; - -template -struct IsModValidImpl -{ - static inline bool run(T aX, T aY) - { - if (aX < 0) { - return false; - } - return aY >= 1; - } -}; - -template::value> -struct NegateImpl; - -template -struct NegateImpl -{ - static CheckedInt negate(const CheckedInt& aVal) - { - // Handle negation separately for signed/unsigned, for simpler code and to - // avoid an MSVC warning negating an unsigned value. - return CheckedInt(0, aVal.isValid() && aVal.mValue == 0); - } -}; - -template -struct NegateImpl -{ - static CheckedInt negate(const CheckedInt& aVal) - { - // Watch out for the min-value, which (with twos-complement) can't be - // negated as -min-value is then (max-value + 1). - if (!aVal.isValid() || aVal.mValue == MinValue::value) { - return CheckedInt(aVal.mValue, false); - } - return CheckedInt(-aVal.mValue, true); - } -}; - -} // namespace detail - - -/* - * Step 3: Now define the CheckedInt class. - */ - -/** - * @class CheckedInt - * @brief Integer wrapper class checking for integer overflow and other errors - * @param T the integer type to wrap. Can be any type among the following: - * - any basic integer type such as |int| - * - any stdint type such as |int8_t| - * - * This class implements guarded integer arithmetic. Do a computation, check - * that isValid() returns true, you then have a guarantee that no problem, such - * as integer overflow, happened during this computation, and you can call - * value() to get the plain integer value. - * - * The arithmetic operators in this class are guaranteed not to raise a signal - * (e.g. in case of a division by zero). - * - * For example, suppose that you want to implement a function that computes - * (aX+aY)/aZ, that doesn't crash if aZ==0, and that reports on error (divide by - * zero or integer overflow). You could code it as follows: - @code - bool computeXPlusYOverZ(int aX, int aY, int aZ, int* aResult) - { - CheckedInt checkedResult = (CheckedInt(aX) + aY) / aZ; - if (checkedResult.isValid()) { - *aResult = checkedResult.value(); - return true; - } else { - return false; - } - } - @endcode - * - * Implicit conversion from plain integers to checked integers is allowed. The - * plain integer is checked to be in range before being casted to the - * destination type. This means that the following lines all compile, and the - * resulting CheckedInts are correctly detected as valid or invalid: - * @code - // 1 is of type int, is found to be in range for uint8_t, x is valid - CheckedInt x(1); - // -1 is of type int, is found not to be in range for uint8_t, x is invalid - CheckedInt x(-1); - // -1 is of type int, is found to be in range for int8_t, x is valid - CheckedInt x(-1); - // 1000 is of type int16_t, is found not to be in range for int8_t, - // x is invalid - CheckedInt x(int16_t(1000)); - // 3123456789 is of type uint32_t, is found not to be in range for int32_t, - // x is invalid - CheckedInt x(uint32_t(3123456789)); - * @endcode - * Implicit conversion from - * checked integers to plain integers is not allowed. As shown in the - * above example, to get the value of a checked integer as a normal integer, - * call value(). - * - * Arithmetic operations between checked and plain integers is allowed; the - * result type is the type of the checked integer. - * - * Checked integers of different types cannot be used in the same arithmetic - * expression. - * - * There are convenience typedefs for all stdint types, of the following form - * (these are just 2 examples): - @code - typedef CheckedInt CheckedInt32; - typedef CheckedInt CheckedUint16; - @endcode - */ -template -class CheckedInt -{ -protected: - T mValue; - bool mIsValid; - - template - CheckedInt(U aValue, bool aIsValid) : mValue(aValue), mIsValid(aIsValid) - { - static_assert(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); - } - - friend struct detail::NegateImpl; - -public: - /** - * Constructs a checked integer with given @a value. The checked integer is - * initialized as valid or invalid depending on whether the @a value - * is in range. - * - * This constructor is not explicit. Instead, the type of its argument is a - * separate template parameter, ensuring that no conversion is performed - * before this constructor is actually called. As explained in the above - * documentation for class CheckedInt, this constructor checks that its - * argument is valid. - */ - template - MOZ_IMPLICIT CheckedInt(U aValue) MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT - : mValue(T(aValue)), - mIsValid(detail::IsInRange(aValue)) - { - static_assert(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); - } - - template - friend class CheckedInt; - - template - CheckedInt toChecked() const - { - CheckedInt ret(mValue); - ret.mIsValid = ret.mIsValid && mIsValid; - return ret; - } - - /** Constructs a valid checked integer with initial value 0 */ - CheckedInt() : mValue(0), mIsValid(true) - { - static_assert(detail::IsSupported::value, - "This type is not supported by CheckedInt"); - } - - /** @returns the actual value */ - T value() const - { - MOZ_ASSERT(mIsValid, "Invalid checked integer (division by zero or integer overflow)"); - return mValue; - } - - /** - * @returns true if the checked integer is valid, i.e. is not the result - * of an invalid operation or of an operation involving an invalid checked - * integer - */ - bool isValid() const - { - return mIsValid; - } - - template - friend CheckedInt operator +(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator +=(U aRhs); - CheckedInt& operator +=(const CheckedInt& aRhs); - - template - friend CheckedInt operator -(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator -=(U aRhs); - CheckedInt& operator -=(const CheckedInt& aRhs); - - template - friend CheckedInt operator *(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator *=(U aRhs); - CheckedInt& operator *=(const CheckedInt& aRhs); - - template - friend CheckedInt operator /(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator /=(U aRhs); - CheckedInt& operator /=(const CheckedInt& aRhs); - - template - friend CheckedInt operator %(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator %=(U aRhs); - CheckedInt& operator %=(const CheckedInt& aRhs); - - CheckedInt operator -() const - { - return detail::NegateImpl::negate(*this); - } - - /** - * @returns true if the left and right hand sides are valid - * and have the same value. - * - * Note that these semantics are the reason why we don't offer - * a operator!=. Indeed, we'd want to have a!=b be equivalent to !(a==b) - * but that would mean that whenever a or b is invalid, a!=b - * is always true, which would be very confusing. - * - * For similar reasons, operators <, >, <=, >= would be very tricky to - * specify, so we just avoid offering them. - * - * Notice that these == semantics are made more reasonable by these facts: - * 1. a==b implies equality at the raw data level - * (the converse is false, as a==b is never true among invalids) - * 2. This is similar to the behavior of IEEE floats, where a==b - * means that a and b have the same value *and* neither is NaN. - */ - bool operator ==(const CheckedInt& aOther) const - { - return mIsValid && aOther.mIsValid && mValue == aOther.mValue; - } - - /** prefix ++ */ - CheckedInt& operator++() - { - *this += 1; - return *this; - } - - /** postfix ++ */ - CheckedInt operator++(int) - { - CheckedInt tmp = *this; - *this += 1; - return tmp; - } - - /** prefix -- */ - CheckedInt& operator--() - { - *this -= 1; - return *this; - } - - /** postfix -- */ - CheckedInt operator--(int) - { - CheckedInt tmp = *this; - *this -= 1; - return tmp; - } - -private: - /** - * The !=, <, <=, >, >= operators are disabled: - * see the comment on operator==. - */ - template bool operator !=(U aOther) const = delete; - template bool operator < (U aOther) const = delete; - template bool operator <=(U aOther) const = delete; - template bool operator > (U aOther) const = delete; - template bool operator >=(U aOther) const = delete; -}; - -#define MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(NAME, OP) \ - template \ - inline CheckedInt \ - operator OP(const CheckedInt& aLhs, const CheckedInt& aRhs) \ - { \ - if (!detail::Is##NAME##Valid(aLhs.mValue, aRhs.mValue)) { \ - return CheckedInt(0, false); \ - } \ - return CheckedInt(aLhs.mValue OP aRhs.mValue, \ - aLhs.mIsValid && aRhs.mIsValid); \ - } - -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Add, +) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Sub, -) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mul, *) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Div, /) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mod, %) - -#undef MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR - -// Implement castToCheckedInt(x), making sure that -// - it allows x to be either a CheckedInt or any integer type -// that can be casted to T -// - if x is already a CheckedInt, we just return a reference to it, -// instead of copying it (optimization) - -namespace detail { - -template -struct CastToCheckedIntImpl -{ - typedef CheckedInt ReturnType; - static CheckedInt run(U aU) { return aU; } -}; - -template -struct CastToCheckedIntImpl > -{ - typedef const CheckedInt& ReturnType; - static const CheckedInt& run(const CheckedInt& aU) { return aU; } -}; - -} // namespace detail - -template -inline typename detail::CastToCheckedIntImpl::ReturnType -castToCheckedInt(U aU) -{ - static_assert(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); - return detail::CastToCheckedIntImpl::run(aU); -} - -#define MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(OP, COMPOUND_OP) \ - template \ - template \ - CheckedInt& CheckedInt::operator COMPOUND_OP(U aRhs) \ - { \ - *this = *this OP castToCheckedInt(aRhs); \ - return *this; \ - } \ - template \ - CheckedInt& CheckedInt::operator COMPOUND_OP(const CheckedInt& aRhs) \ - { \ - *this = *this OP aRhs; \ - return *this; \ - } \ - template \ - inline CheckedInt operator OP(const CheckedInt& aLhs, U aRhs) \ - { \ - return aLhs OP castToCheckedInt(aRhs); \ - } \ - template \ - inline CheckedInt operator OP(U aLhs, const CheckedInt& aRhs) \ - { \ - return castToCheckedInt(aLhs) OP aRhs; \ - } - -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(+, +=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(*, *=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(-, -=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(/, /=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(%, %=) - -#undef MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS - -template -inline bool -operator ==(const CheckedInt& aLhs, U aRhs) -{ - return aLhs == castToCheckedInt(aRhs); -} - -template -inline bool -operator ==(U aLhs, const CheckedInt& aRhs) -{ - return castToCheckedInt(aLhs) == aRhs; -} - -// Convenience typedefs. -typedef CheckedInt CheckedInt8; -typedef CheckedInt CheckedUint8; -typedef CheckedInt CheckedInt16; -typedef CheckedInt CheckedUint16; -typedef CheckedInt CheckedInt32; -typedef CheckedInt CheckedUint32; -typedef CheckedInt CheckedInt64; -typedef CheckedInt CheckedUint64; - -} // namespace mozilla - -#endif /* mozilla_CheckedInt_h */ diff --git a/ios/include/spidermonkey/mozilla/Compiler.h b/ios/include/spidermonkey/mozilla/Compiler.h deleted file mode 100644 index 1bd34d32..00000000 --- a/ios/include/spidermonkey/mozilla/Compiler.h +++ /dev/null @@ -1,113 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Various compiler checks. */ - -#ifndef mozilla_Compiler_h -#define mozilla_Compiler_h - -#define MOZ_IS_GCC 0 -#define MOZ_IS_MSVC 0 - -#if !defined(__clang__) && defined(__GNUC__) - -# undef MOZ_IS_GCC -# define MOZ_IS_GCC 1 - /* - * These macros should simplify gcc version checking. For example, to check - * for gcc 4.7.1 or later, check `#if MOZ_GCC_VERSION_AT_LEAST(4, 7, 1)`. - */ -# define MOZ_GCC_VERSION_AT_LEAST(major, minor, patchlevel) \ - ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \ - >= ((major) * 10000 + (minor) * 100 + (patchlevel))) -# define MOZ_GCC_VERSION_AT_MOST(major, minor, patchlevel) \ - ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \ - <= ((major) * 10000 + (minor) * 100 + (patchlevel))) -# if !MOZ_GCC_VERSION_AT_LEAST(4, 8, 0) -# error "mfbt (and Gecko) require at least gcc 4.8 to build." -# endif - -#elif defined(_MSC_VER) - -# undef MOZ_IS_MSVC -# define MOZ_IS_MSVC 1 - -#endif - -/* - * The situation with standard libraries is a lot worse than with compilers, - * particularly as clang and gcc could end up using one of three or so standard - * libraries, and they may not be up-to-snuff with newer C++11 versions. To - * detect the library, we're going to include cstddef (which is a small header - * which will be transitively included by everybody else at some point) to grab - * the version macros and deduce macros from there. - */ -#ifdef __cplusplus -# include -# ifdef _STLPORT_MAJOR -# define MOZ_USING_STLPORT 1 -# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) \ - (_STLPORT_VERSION >= ((major) << 8 | (minor) << 4 | (patch))) -# elif defined(_LIBCPP_VERSION) - /* - * libc++, unfortunately, doesn't appear to have useful versioning macros. - * Hopefully, the recommendations of N3694 with respect to standard libraries - * will get applied instead and we won't need to worry about version numbers - * here. - */ -# define MOZ_USING_LIBCXX 1 -# elif defined(__GLIBCXX__) -# define MOZ_USING_LIBSTDCXX 1 - /* - * libstdc++ is also annoying and doesn't give us useful versioning macros - * for the library. If we're using gcc, then assume that libstdc++ matches - * the compiler version. If we're using clang, we're going to have to fake - * major/minor combinations by looking for newly-defined config macros. - */ -# if MOZ_IS_GCC -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - MOZ_GCC_VERSION_AT_LEAST(major, minor, patch) -# elif defined(_GLIBCXX_THROW_OR_ABORT) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 8)) -# elif defined(_GLIBCXX_NOEXCEPT) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 7)) -# elif defined(_GLIBCXX_USE_DEPRECATED) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 6)) -# elif defined(_GLIBCXX_PSEUDO_VISIBILITY) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 5)) -# elif defined(_GLIBCXX_BEGIN_EXTERN_C) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 4)) -# elif defined(_GLIBCXX_VISIBILITY_ATTR) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 3)) -# elif defined(_GLIBCXX_VISIBILITY) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 2)) -# else -# error "Your version of libstdc++ is unknown to us and is likely too old." -# endif -# endif - - // Flesh out the defines for everyone else -# ifndef MOZ_USING_STLPORT -# define MOZ_USING_STLPORT 0 -# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) 0 -# endif -# ifndef MOZ_USING_LIBCXX -# define MOZ_USING_LIBCXX 0 -# endif -# ifndef MOZ_USING_LIBSTDCXX -# define MOZ_USING_LIBSTDCXX 0 -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) 0 -# endif -#endif /* __cplusplus */ - -#endif /* mozilla_Compiler_h */ diff --git a/ios/include/spidermonkey/mozilla/Compression.h b/ios/include/spidermonkey/mozilla/Compression.h deleted file mode 100644 index aa50211b..00000000 --- a/ios/include/spidermonkey/mozilla/Compression.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Various simple compression/decompression functions. */ - -#ifndef mozilla_Compression_h_ -#define mozilla_Compression_h_ - -#include "mozilla/Assertions.h" -#include "mozilla/Types.h" - -namespace mozilla { -namespace Compression { - -/** - * LZ4 is a very fast byte-wise compression algorithm. - * - * Compared to Google's Snappy it is faster to compress and decompress and - * generally produces output of about the same size. - * - * Compared to zlib it compresses at about 10x the speed, decompresses at about - * 4x the speed and produces output of about 1.5x the size. - */ - -class LZ4 -{ -public: - /** - * Compresses |aInputSize| bytes from |aSource| into |aDest|. Destination - * buffer must be already allocated, and must be sized to handle worst cases - * situations (input data not compressible). Worst case size evaluation is - * provided by function maxCompressedSize() - * - * @param aInputSize is the input size. Max supported value is ~1.9GB - * @return the number of bytes written in buffer |aDest| - */ - static MFBT_API size_t - compress(const char* aSource, size_t aInputSize, char* aDest); - - /** - * Compress |aInputSize| bytes from |aSource| into an output buffer - * |aDest| of maximum size |aMaxOutputSize|. If it cannot achieve it, - * compression will stop, and result of the function will be zero, - * |aDest| will still be written to, but since the number of input - * bytes consumed is not returned the result is not usable. - * - * This function never writes outside of provided output buffer. - * - * @param aInputSize is the input size. Max supported value is ~1.9GB - * @param aMaxOutputSize is the size of the destination buffer (which must - * be already allocated) - * @return the number of bytes written in buffer |aDest| or 0 if the - * compression fails - */ - static MFBT_API size_t - compressLimitedOutput(const char* aSource, size_t aInputSize, char* aDest, - size_t aMaxOutputSize); - - /** - * If the source stream is malformed, the function will stop decoding - * and return false. - * - * This function never writes outside of provided buffers, and never - * modifies input buffer. - * - * Note: destination buffer must be already allocated, and its size must be a - * minimum of |aOutputSize| bytes. - * - * @param aOutputSize is the output size, therefore the original size - * @return true on success, false on failure - */ - static MFBT_API MOZ_MUST_USE bool - decompress(const char* aSource, char* aDest, size_t aOutputSize); - - /** - * If the source stream is malformed, the function will stop decoding - * and return false. - * - * This function never writes beyond aDest + aMaxOutputSize, and is - * therefore protected against malicious data packets. - * - * Note: Destination buffer must be already allocated. This version is - * slightly slower than the decompress without the aMaxOutputSize. - * - * @param aInputSize is the length of the input compressed data - * @param aMaxOutputSize is the size of the destination buffer (which must be - * already allocated) - * @param aOutputSize the actual number of bytes decoded in the destination - * buffer (necessarily <= aMaxOutputSize) - * @return true on success, false on failure - */ - static MFBT_API MOZ_MUST_USE bool - decompress(const char* aSource, size_t aInputSize, char* aDest, - size_t aMaxOutputSize, size_t* aOutputSize); - - /* - * Provides the maximum size that LZ4 may output in a "worst case" - * scenario (input data not compressible) primarily useful for memory - * allocation of output buffer. - * note : this function is limited by "int" range (2^31-1) - * - * @param aInputSize is the input size. Max supported value is ~1.9GB - * @return maximum output size in a "worst case" scenario - */ - static inline size_t maxCompressedSize(size_t aInputSize) - { - size_t max = (aInputSize + (aInputSize / 255) + 16); - MOZ_ASSERT(max > aInputSize); - return max; - } -}; - -} /* namespace Compression */ -} /* namespace mozilla */ - -#endif /* mozilla_Compression_h_ */ diff --git a/ios/include/spidermonkey/mozilla/DebugOnly.h b/ios/include/spidermonkey/mozilla/DebugOnly.h deleted file mode 100644 index a1a669db..00000000 --- a/ios/include/spidermonkey/mozilla/DebugOnly.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Provides DebugOnly, a type for variables used only in debug builds (i.e. by - * assertions). - */ - -#ifndef mozilla_DebugOnly_h -#define mozilla_DebugOnly_h - -#include "mozilla/Attributes.h" - -namespace mozilla { - -/** - * DebugOnly contains a value of type T, but only in debug builds. In release - * builds, it does not contain a value. This helper is intended to be used with - * MOZ_ASSERT()-style macros, allowing one to write: - * - * DebugOnly check = func(); - * MOZ_ASSERT(check); - * - * more concisely than declaring |check| conditional on #ifdef DEBUG. - * - * DebugOnly instances can only be coerced to T in debug builds. In release - * builds they don't have a value, so type coercion is not well defined. - * - * NOTE: DebugOnly instances still take up one byte of space, plus padding, even - * in optimized, non-DEBUG builds (see bug 1253094 comment 37 for more info). - * For this reason the class is MOZ_STACK_CLASS to prevent consumers using - * DebugOnly for struct/class members and unwittingly inflating the size of - * their objects in release builds. - */ -template -class MOZ_STACK_CLASS DebugOnly -{ -public: -#ifdef DEBUG - T value; - - DebugOnly() { } - MOZ_IMPLICIT DebugOnly(const T& aOther) : value(aOther) { } - DebugOnly(const DebugOnly& aOther) : value(aOther.value) { } - DebugOnly& operator=(const T& aRhs) { - value = aRhs; - return *this; - } - - void operator++(int) { value++; } - void operator--(int) { value--; } - - // Do not define operator+=(), etc. here. These will coerce via the - // implicit cast and built-in operators. Defining explicit methods here - // will create ambiguity the compiler can't deal with. - - T* operator&() { return &value; } - - operator T&() { return value; } - operator const T&() const { return value; } - - T& operator->() { return value; } - const T& operator->() const { return value; } - -#else - DebugOnly() { } - MOZ_IMPLICIT DebugOnly(const T&) { } - DebugOnly(const DebugOnly&) { } - DebugOnly& operator=(const T&) { return *this; } - void operator++(int) { } - void operator--(int) { } - DebugOnly& operator+=(const T&) { return *this; } - DebugOnly& operator-=(const T&) { return *this; } - DebugOnly& operator&=(const T&) { return *this; } - DebugOnly& operator|=(const T&) { return *this; } - DebugOnly& operator^=(const T&) { return *this; } -#endif - - /* - * DebugOnly must always have a destructor or else it will - * generate "unused variable" warnings, exactly what it's intended - * to avoid! - */ - ~DebugOnly() {} -}; - -} // namespace mozilla - -#endif /* mozilla_DebugOnly_h */ diff --git a/ios/include/spidermonkey/mozilla/Decimal.h b/ios/include/spidermonkey/mozilla/Decimal.h deleted file mode 100644 index 10d0e2c7..00000000 --- a/ios/include/spidermonkey/mozilla/Decimal.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * Imported from: - * https://chromium.googlesource.com/chromium/src.git/+/master/third_party/WebKit/Source/platform/Decimal.h - * Check UPSTREAM-GIT-SHA for the commit ID of the last update from Blink core. - */ - -#ifndef Decimal_h -#define Decimal_h - -#include "mozilla/Assertions.h" -#include -#include "mozilla/Types.h" - -#include - -#ifndef ASSERT -#define DEFINED_ASSERT_FOR_DECIMAL_H 1 -#define ASSERT MOZ_ASSERT -#endif - -#define PLATFORM_EXPORT - -// To use USING_FAST_MALLOC we'd need: -// https://chromium.googlesource.com/chromium/src.git/+/master/third_party/WebKit/Source/wtf/Allocator.h -// Since we don't allocate Decimal objects, no need. -#define USING_FAST_MALLOC(type) \ - void ignore_this_dummy_method() = delete - -#define DISALLOW_NEW() \ - private: \ - void* operator new(size_t) = delete; \ - void* operator new(size_t, void*) = delete; \ - public: - -namespace blink { - -namespace DecimalPrivate { -class SpecialValueHandler; -} - -// This class represents decimal base floating point number. -// -// FIXME: Once all C++ compiler support decimal type, we should replace this -// class to compiler supported one. See below URI for current status of decimal -// type for C++: // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1977.html -class PLATFORM_EXPORT Decimal { - USING_FAST_MALLOC(Decimal); -public: - enum Sign { - Positive, - Negative, - }; - - // You should not use EncodedData other than unit testing. - class EncodedData { - DISALLOW_NEW(); - // For accessing FormatClass. - friend class Decimal; - friend class DecimalPrivate::SpecialValueHandler; - public: - EncodedData(Sign, int exponent, uint64_t coefficient); - - bool operator==(const EncodedData&) const; - bool operator!=(const EncodedData& another) const { return !operator==(another); } - - uint64_t coefficient() const { return m_coefficient; } - int countDigits() const; - int exponent() const { return m_exponent; } - bool isFinite() const { return !isSpecial(); } - bool isInfinity() const { return m_formatClass == ClassInfinity; } - bool isNaN() const { return m_formatClass == ClassNaN; } - bool isSpecial() const { return m_formatClass == ClassInfinity || m_formatClass == ClassNaN; } - bool isZero() const { return m_formatClass == ClassZero; } - Sign sign() const { return m_sign; } - void setSign(Sign sign) { m_sign = sign; } - - private: - enum FormatClass { - ClassInfinity, - ClassNormal, - ClassNaN, - ClassZero, - }; - - EncodedData(Sign, FormatClass); - FormatClass formatClass() const { return m_formatClass; } - - uint64_t m_coefficient; - int16_t m_exponent; - FormatClass m_formatClass; - Sign m_sign; - }; - - MFBT_API explicit Decimal(int32_t = 0); - MFBT_API Decimal(Sign, int exponent, uint64_t coefficient); - MFBT_API Decimal(const Decimal&); - - MFBT_API Decimal& operator=(const Decimal&); - MFBT_API Decimal& operator+=(const Decimal&); - MFBT_API Decimal& operator-=(const Decimal&); - MFBT_API Decimal& operator*=(const Decimal&); - MFBT_API Decimal& operator/=(const Decimal&); - - MFBT_API Decimal operator-() const; - - MFBT_API bool operator==(const Decimal&) const; - MFBT_API bool operator!=(const Decimal&) const; - MFBT_API bool operator<(const Decimal&) const; - MFBT_API bool operator<=(const Decimal&) const; - MFBT_API bool operator>(const Decimal&) const; - MFBT_API bool operator>=(const Decimal&) const; - - MFBT_API Decimal operator+(const Decimal&) const; - MFBT_API Decimal operator-(const Decimal&) const; - MFBT_API Decimal operator*(const Decimal&) const; - MFBT_API Decimal operator/(const Decimal&) const; - - int exponent() const - { - ASSERT(isFinite()); - return m_data.exponent(); - } - - bool isFinite() const { return m_data.isFinite(); } - bool isInfinity() const { return m_data.isInfinity(); } - bool isNaN() const { return m_data.isNaN(); } - bool isNegative() const { return sign() == Negative; } - bool isPositive() const { return sign() == Positive; } - bool isSpecial() const { return m_data.isSpecial(); } - bool isZero() const { return m_data.isZero(); } - - MFBT_API Decimal abs() const; - MFBT_API Decimal ceil() const; - MFBT_API Decimal floor() const; - MFBT_API Decimal remainder(const Decimal&) const; - MFBT_API Decimal round() const; - - MFBT_API double toDouble() const; - // Note: toString method supports infinity and nan but fromString not. - MFBT_API std::string toString() const; - MFBT_API bool toString(char* strBuf, size_t bufLength) const; - - static MFBT_API Decimal fromDouble(double); - // fromString supports following syntax EBNF: - // number ::= sign? digit+ ('.' digit*) (exponent-marker sign? digit+)? - // | sign? '.' digit+ (exponent-marker sign? digit+)? - // sign ::= '+' | '-' - // exponent-marker ::= 'e' | 'E' - // digit ::= '0' | '1' | ... | '9' - // Note: fromString doesn't support "infinity" and "nan". - static MFBT_API Decimal fromString(const std::string& aValue); - static MFBT_API Decimal infinity(Sign); - static MFBT_API Decimal nan(); - static MFBT_API Decimal zero(Sign); - - // You should not use below methods. We expose them for unit testing. - MFBT_API explicit Decimal(const EncodedData&); - const EncodedData& value() const { return m_data; } - -private: - struct AlignedOperands { - uint64_t lhsCoefficient; - uint64_t rhsCoefficient; - int exponent; - }; - - MFBT_API explicit Decimal(double); - MFBT_API Decimal compareTo(const Decimal&) const; - - static MFBT_API AlignedOperands alignOperands(const Decimal& lhs, const Decimal& rhs); - static inline Sign invertSign(Sign sign) { return sign == Negative ? Positive : Negative; } - - Sign sign() const { return m_data.sign(); } - - EncodedData m_data; -}; - -} // namespace blink - -namespace mozilla { -typedef blink::Decimal Decimal; -} // namespace mozilla - -#undef USING_FAST_MALLOC - -#ifdef DEFINED_ASSERT_FOR_DECIMAL_H -#undef DEFINED_ASSERT_FOR_DECIMAL_H -#undef ASSERT -#endif - -#endif // Decimal_h diff --git a/ios/include/spidermonkey/mozilla/EndianUtils.h b/ios/include/spidermonkey/mozilla/EndianUtils.h deleted file mode 100644 index 00815580..00000000 --- a/ios/include/spidermonkey/mozilla/EndianUtils.h +++ /dev/null @@ -1,695 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Functions for reading and writing integers in various endiannesses. */ - -/* - * The classes LittleEndian and BigEndian expose static methods for - * reading and writing 16-, 32-, and 64-bit signed and unsigned integers - * in their respective endianness. The naming scheme is: - * - * {Little,Big}Endian::{read,write}{Uint,Int} - * - * For instance, LittleEndian::readInt32 will read a 32-bit signed - * integer from memory in little endian format. Similarly, - * BigEndian::writeUint16 will write a 16-bit unsigned integer to memory - * in big-endian format. - * - * The class NativeEndian exposes methods for conversion of existing - * data to and from the native endianness. These methods are intended - * for cases where data needs to be transferred, serialized, etc. - * swap{To,From}{Little,Big}Endian byteswap a single value if necessary. - * Bulk conversion functions are also provided which optimize the - * no-conversion-needed case: - * - * - copyAndSwap{To,From}{Little,Big}Endian; - * - swap{To,From}{Little,Big}EndianInPlace. - * - * The *From* variants are intended to be used for reading data and the - * *To* variants for writing data. - * - * Methods on NativeEndian work with integer data of any type. - * Floating-point data is not supported. - * - * For clarity in networking code, "Network" may be used as a synonym - * for "Big" in any of the above methods or class names. - * - * As an example, reading a file format header whose fields are stored - * in big-endian format might look like: - * - * class ExampleHeader - * { - * private: - * uint32_t mMagic; - * uint32_t mLength; - * uint32_t mTotalRecords; - * uint64_t mChecksum; - * - * public: - * ExampleHeader(const void* data) - * { - * const uint8_t* ptr = static_cast(data); - * mMagic = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t); - * mLength = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t); - * mTotalRecords = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t); - * mChecksum = BigEndian::readUint64(ptr); - * } - * ... - * }; - */ - -#ifndef mozilla_EndianUtils_h -#define mozilla_EndianUtils_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/DebugOnly.h" -#include "mozilla/TypeTraits.h" - -#include -#include - -#if defined(_MSC_VER) -# include -# pragma intrinsic(_byteswap_ushort) -# pragma intrinsic(_byteswap_ulong) -# pragma intrinsic(_byteswap_uint64) -#endif - -#if defined(_WIN64) -# if defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_) -# define MOZ_LITTLE_ENDIAN 1 -# else -# error "CPU type is unknown" -# endif -#elif defined(_WIN32) -# if defined(_M_IX86) -# define MOZ_LITTLE_ENDIAN 1 -# elif defined(_M_ARM) -# define MOZ_LITTLE_ENDIAN 1 -# else -# error "CPU type is unknown" -# endif -#elif defined(__APPLE__) || defined(__powerpc__) || defined(__ppc__) -# if __LITTLE_ENDIAN__ -# define MOZ_LITTLE_ENDIAN 1 -# elif __BIG_ENDIAN__ -# define MOZ_BIG_ENDIAN 1 -# endif -#elif defined(__GNUC__) && \ - defined(__BYTE_ORDER__) && \ - defined(__ORDER_LITTLE_ENDIAN__) && \ - defined(__ORDER_BIG_ENDIAN__) - /* - * Some versions of GCC provide architecture-independent macros for - * this. Yes, there are more than two values for __BYTE_ORDER__. - */ -# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -# define MOZ_LITTLE_ENDIAN 1 -# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -# define MOZ_BIG_ENDIAN 1 -# else -# error "Can't handle mixed-endian architectures" -# endif -/* - * We can't include useful headers like or - * here because they're not present on all platforms. Instead we have - * this big conditional that ideally will catch all the interesting - * cases. - */ -#elif defined(__sparc) || defined(__sparc__) || \ - defined(_POWER) || defined(__hppa) || \ - defined(_MIPSEB) || defined(__ARMEB__) || \ - defined(__s390__) || defined(__AARCH64EB__) || \ - (defined(__sh__) && defined(__LITTLE_ENDIAN__)) || \ - (defined(__ia64) && defined(__BIG_ENDIAN__)) -# define MOZ_BIG_ENDIAN 1 -#elif defined(__i386) || defined(__i386__) || \ - defined(__x86_64) || defined(__x86_64__) || \ - defined(_MIPSEL) || defined(__ARMEL__) || \ - defined(__alpha__) || defined(__AARCH64EL__) || \ - (defined(__sh__) && defined(__BIG_ENDIAN__)) || \ - (defined(__ia64) && !defined(__BIG_ENDIAN__)) -# define MOZ_LITTLE_ENDIAN 1 -#endif - -#if MOZ_BIG_ENDIAN -# define MOZ_LITTLE_ENDIAN 0 -#elif MOZ_LITTLE_ENDIAN -# define MOZ_BIG_ENDIAN 0 -#else -# error "Cannot determine endianness" -#endif - -#if defined(__clang__) -# if __has_builtin(__builtin_bswap16) -# define MOZ_HAVE_BUILTIN_BYTESWAP16 __builtin_bswap16 -# endif -#elif defined(__GNUC__) -# define MOZ_HAVE_BUILTIN_BYTESWAP16 __builtin_bswap16 -#elif defined(_MSC_VER) -# define MOZ_HAVE_BUILTIN_BYTESWAP16 _byteswap_ushort -#endif - -namespace mozilla { - -namespace detail { - -/* - * We need wrappers here because free functions with default template - * arguments and/or partial specialization of function templates are not - * supported by all the compilers we use. - */ -template -struct Swapper; - -template -struct Swapper -{ - static T swap(T aValue) - { -#if defined(MOZ_HAVE_BUILTIN_BYTESWAP16) - return MOZ_HAVE_BUILTIN_BYTESWAP16(aValue); -#else - return T(((aValue & 0x00ff) << 8) | ((aValue & 0xff00) >> 8)); -#endif - } -}; - -template -struct Swapper -{ - static T swap(T aValue) - { -#if defined(__clang__) || defined(__GNUC__) - return T(__builtin_bswap32(aValue)); -#elif defined(_MSC_VER) - return T(_byteswap_ulong(aValue)); -#else - return T(((aValue & 0x000000ffU) << 24) | - ((aValue & 0x0000ff00U) << 8) | - ((aValue & 0x00ff0000U) >> 8) | - ((aValue & 0xff000000U) >> 24)); -#endif - } -}; - -template -struct Swapper -{ - static inline T swap(T aValue) - { -#if defined(__clang__) || defined(__GNUC__) - return T(__builtin_bswap64(aValue)); -#elif defined(_MSC_VER) - return T(_byteswap_uint64(aValue)); -#else - return T(((aValue & 0x00000000000000ffULL) << 56) | - ((aValue & 0x000000000000ff00ULL) << 40) | - ((aValue & 0x0000000000ff0000ULL) << 24) | - ((aValue & 0x00000000ff000000ULL) << 8) | - ((aValue & 0x000000ff00000000ULL) >> 8) | - ((aValue & 0x0000ff0000000000ULL) >> 24) | - ((aValue & 0x00ff000000000000ULL) >> 40) | - ((aValue & 0xff00000000000000ULL) >> 56)); -#endif - } -}; - -enum Endianness { Little, Big }; - -#if MOZ_BIG_ENDIAN -# define MOZ_NATIVE_ENDIANNESS detail::Big -#else -# define MOZ_NATIVE_ENDIANNESS detail::Little -#endif - -class EndianUtils -{ - /** - * Assert that the memory regions [aDest, aDest+aCount) and - * [aSrc, aSrc+aCount] do not overlap. aCount is given in bytes. - */ - static void assertNoOverlap(const void* aDest, const void* aSrc, - size_t aCount) - { - DebugOnly byteDestPtr = static_cast(aDest); - DebugOnly byteSrcPtr = static_cast(aSrc); - MOZ_ASSERT((byteDestPtr <= byteSrcPtr && - byteDestPtr + aCount <= byteSrcPtr) || - (byteSrcPtr <= byteDestPtr && - byteSrcPtr + aCount <= byteDestPtr)); - } - - template - static void assertAligned(T* aPtr) - { - MOZ_ASSERT((uintptr_t(aPtr) % sizeof(T)) == 0, "Unaligned pointer!"); - } - -protected: - /** - * Return |aValue| converted from SourceEndian encoding to DestEndian - * encoding. - */ - template - static inline T maybeSwap(T aValue) - { - if (SourceEndian == DestEndian) { - return aValue; - } - return Swapper::swap(aValue); - } - - /** - * Convert |aCount| elements at |aPtr| from SourceEndian encoding to - * DestEndian encoding. - */ - template - static inline void maybeSwapInPlace(T* aPtr, size_t aCount) - { - assertAligned(aPtr); - - if (SourceEndian == DestEndian) { - return; - } - for (size_t i = 0; i < aCount; i++) { - aPtr[i] = Swapper::swap(aPtr[i]); - } - } - - /** - * Write |aCount| elements to the unaligned address |aDest| in DestEndian - * format, using elements found at |aSrc| in SourceEndian format. - */ - template - static void copyAndSwapTo(void* aDest, const T* aSrc, size_t aCount) - { - assertNoOverlap(aDest, aSrc, aCount * sizeof(T)); - assertAligned(aSrc); - - if (SourceEndian == DestEndian) { - memcpy(aDest, aSrc, aCount * sizeof(T)); - return; - } - - uint8_t* byteDestPtr = static_cast(aDest); - for (size_t i = 0; i < aCount; ++i) { - union - { - T mVal; - uint8_t mBuffer[sizeof(T)]; - } u; - u.mVal = maybeSwap(aSrc[i]); - memcpy(byteDestPtr, u.mBuffer, sizeof(T)); - byteDestPtr += sizeof(T); - } - } - - /** - * Write |aCount| elements to |aDest| in DestEndian format, using elements - * found at the unaligned address |aSrc| in SourceEndian format. - */ - template - static void copyAndSwapFrom(T* aDest, const void* aSrc, size_t aCount) - { - assertNoOverlap(aDest, aSrc, aCount * sizeof(T)); - assertAligned(aDest); - - if (SourceEndian == DestEndian) { - memcpy(aDest, aSrc, aCount * sizeof(T)); - return; - } - - const uint8_t* byteSrcPtr = static_cast(aSrc); - for (size_t i = 0; i < aCount; ++i) { - union - { - T mVal; - uint8_t mBuffer[sizeof(T)]; - } u; - memcpy(u.mBuffer, byteSrcPtr, sizeof(T)); - aDest[i] = maybeSwap(u.mVal); - byteSrcPtr += sizeof(T); - } - } -}; - -template -class Endian : private EndianUtils -{ -protected: - /** Read a uint16_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE uint16_t readUint16(const void* aPtr) - { - return read(aPtr); - } - - /** Read a uint32_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE uint32_t readUint32(const void* aPtr) - { - return read(aPtr); - } - - /** Read a uint64_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE uint64_t readUint64(const void* aPtr) - { - return read(aPtr); - } - - /** Read an int16_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE int16_t readInt16(const void* aPtr) - { - return read(aPtr); - } - - /** Read an int32_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE int32_t readInt32(const void* aPtr) - { - return read(aPtr); - } - - /** Read an int64_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE int64_t readInt64(const void* aPtr) - { - return read(aPtr); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeUint16(void* aPtr, uint16_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeUint32(void* aPtr, uint32_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeUint64(void* aPtr, uint64_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeInt16(void* aPtr, int16_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeInt32(void* aPtr, int32_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeInt64(void* aPtr, int64_t aValue) - { - write(aPtr, aValue); - } - - /* - * Converts a value of type T to little-endian format. - * - * This function is intended for cases where you have data in your - * native-endian format and you need it to appear in little-endian - * format for transmission. - */ - template - MOZ_MUST_USE static T swapToLittleEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to little-endian format if ThisEndian is Big. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapToLittleEndian(void* aDest, const T* aSrc, - size_t aCount) - { - copyAndSwapTo(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapToLittleEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Converts a value of type T to big-endian format. - */ - template - MOZ_MUST_USE static T swapToBigEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to big-endian format if ThisEndian is Little. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapToBigEndian(void* aDest, const T* aSrc, - size_t aCount) - { - copyAndSwapTo(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapToBigEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Synonyms for the big-endian functions, for better readability - * in network code. - */ - - template - MOZ_MUST_USE static T swapToNetworkOrder(T aValue) - { - return swapToBigEndian(aValue); - } - - template - static void - copyAndSwapToNetworkOrder(void* aDest, const T* aSrc, size_t aCount) - { - copyAndSwapToBigEndian(aDest, aSrc, aCount); - } - - template - static void - swapToNetworkOrderInPlace(T* aPtr, size_t aCount) - { - swapToBigEndianInPlace(aPtr, aCount); - } - - /* - * Converts a value of type T from little-endian format. - */ - template - MOZ_MUST_USE static T swapFromLittleEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to little-endian format if ThisEndian is Big. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapFromLittleEndian(T* aDest, const void* aSrc, - size_t aCount) - { - copyAndSwapFrom(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapFromLittleEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Converts a value of type T from big-endian format. - */ - template - MOZ_MUST_USE static T swapFromBigEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to big-endian format if ThisEndian is Little. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapFromBigEndian(T* aDest, const void* aSrc, - size_t aCount) - { - copyAndSwapFrom(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapFromBigEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Synonyms for the big-endian functions, for better readability - * in network code. - */ - template - MOZ_MUST_USE static T swapFromNetworkOrder(T aValue) - { - return swapFromBigEndian(aValue); - } - - template - static void copyAndSwapFromNetworkOrder(T* aDest, const void* aSrc, - size_t aCount) - { - copyAndSwapFromBigEndian(aDest, aSrc, aCount); - } - - template - static void swapFromNetworkOrderInPlace(T* aPtr, size_t aCount) - { - swapFromBigEndianInPlace(aPtr, aCount); - } - -private: - /** - * Read a value of type T, encoded in endianness ThisEndian from |aPtr|. - * Return that value encoded in native endianness. - */ - template - static T read(const void* aPtr) - { - union - { - T mVal; - uint8_t mBuffer[sizeof(T)]; - } u; - memcpy(u.mBuffer, aPtr, sizeof(T)); - return maybeSwap(u.mVal); - } - - /** - * Write a value of type T, in native endianness, to |aPtr|, in ThisEndian - * endianness. - */ - template - static void write(void* aPtr, T aValue) - { - T tmp = maybeSwap(aValue); - memcpy(aPtr, &tmp, sizeof(T)); - } - - Endian() = delete; - Endian(const Endian& aTther) = delete; - void operator=(const Endian& aOther) = delete; -}; - -template -class EndianReadWrite : public Endian -{ -private: - typedef Endian super; - -public: - using super::readUint16; - using super::readUint32; - using super::readUint64; - using super::readInt16; - using super::readInt32; - using super::readInt64; - using super::writeUint16; - using super::writeUint32; - using super::writeUint64; - using super::writeInt16; - using super::writeInt32; - using super::writeInt64; -}; - -} /* namespace detail */ - -class LittleEndian final : public detail::EndianReadWrite -{}; - -class BigEndian final : public detail::EndianReadWrite -{}; - -typedef BigEndian NetworkEndian; - -class NativeEndian final : public detail::Endian -{ -private: - typedef detail::Endian super; - -public: - /* - * These functions are intended for cases where you have data in your - * native-endian format and you need the data to appear in the appropriate - * endianness for transmission, serialization, etc. - */ - using super::swapToLittleEndian; - using super::copyAndSwapToLittleEndian; - using super::swapToLittleEndianInPlace; - using super::swapToBigEndian; - using super::copyAndSwapToBigEndian; - using super::swapToBigEndianInPlace; - using super::swapToNetworkOrder; - using super::copyAndSwapToNetworkOrder; - using super::swapToNetworkOrderInPlace; - - /* - * These functions are intended for cases where you have data in the - * given endianness (e.g. reading from disk or a file-format) and you - * need the data to appear in native-endian format for processing. - */ - using super::swapFromLittleEndian; - using super::copyAndSwapFromLittleEndian; - using super::swapFromLittleEndianInPlace; - using super::swapFromBigEndian; - using super::copyAndSwapFromBigEndian; - using super::swapFromBigEndianInPlace; - using super::swapFromNetworkOrder; - using super::copyAndSwapFromNetworkOrder; - using super::swapFromNetworkOrderInPlace; -}; - -#undef MOZ_NATIVE_ENDIANNESS - -} /* namespace mozilla */ - -#endif /* mozilla_EndianUtils_h */ diff --git a/ios/include/spidermonkey/mozilla/EnumSet.h b/ios/include/spidermonkey/mozilla/EnumSet.h deleted file mode 100644 index 5282ab30..00000000 --- a/ios/include/spidermonkey/mozilla/EnumSet.h +++ /dev/null @@ -1,344 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A set abstraction for enumeration values. */ - -#ifndef mozilla_EnumSet_h -#define mozilla_EnumSet_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#include - -#include - -namespace mozilla { - -/** - * EnumSet is a set of values defined by an enumeration. It is implemented - * using a 32 bit mask for each value so it will only work for enums with an int - * representation less than 32. It works both for enum and enum class types. - */ -template -class EnumSet -{ -public: - EnumSet() - : mBitField(0) - { - initVersion(); - } - - MOZ_IMPLICIT EnumSet(T aEnum) - : mBitField(bitFor(aEnum)) - { } - - EnumSet(T aEnum1, T aEnum2) - : mBitField(bitFor(aEnum1) | - bitFor(aEnum2)) - { - initVersion(); - } - - EnumSet(T aEnum1, T aEnum2, T aEnum3) - : mBitField(bitFor(aEnum1) | - bitFor(aEnum2) | - bitFor(aEnum3)) - { - initVersion(); - } - - EnumSet(T aEnum1, T aEnum2, T aEnum3, T aEnum4) - : mBitField(bitFor(aEnum1) | - bitFor(aEnum2) | - bitFor(aEnum3) | - bitFor(aEnum4)) - { - initVersion(); - } - - MOZ_IMPLICIT EnumSet(std::initializer_list list) - : mBitField(0) - { - for (auto value : list) { - (*this) += value; - } - initVersion(); - } - - EnumSet(const EnumSet& aEnumSet) - : mBitField(aEnumSet.mBitField) - { - initVersion(); - } - - /** - * Add an element - */ - void operator+=(T aEnum) - { - incVersion(); - mBitField |= bitFor(aEnum); - } - - /** - * Add an element - */ - EnumSet operator+(T aEnum) const - { - EnumSet result(*this); - result += aEnum; - return result; - } - - /** - * Union - */ - void operator+=(const EnumSet aEnumSet) - { - incVersion(); - mBitField |= aEnumSet.mBitField; - } - - /** - * Union - */ - EnumSet operator+(const EnumSet aEnumSet) const - { - EnumSet result(*this); - result += aEnumSet; - return result; - } - - /** - * Remove an element - */ - void operator-=(T aEnum) - { - incVersion(); - mBitField &= ~(bitFor(aEnum)); - } - - /** - * Remove an element - */ - EnumSet operator-(T aEnum) const - { - EnumSet result(*this); - result -= aEnum; - return result; - } - - /** - * Remove a set of elements - */ - void operator-=(const EnumSet aEnumSet) - { - incVersion(); - mBitField &= ~(aEnumSet.mBitField); - } - - /** - * Remove a set of elements - */ - EnumSet operator-(const EnumSet aEnumSet) const - { - EnumSet result(*this); - result -= aEnumSet; - return result; - } - - /** - * Clear - */ - void clear() - { - incVersion(); - mBitField = 0; - } - - /** - * Intersection - */ - void operator&=(const EnumSet aEnumSet) - { - incVersion(); - mBitField &= aEnumSet.mBitField; - } - - /** - * Intersection - */ - EnumSet operator&(const EnumSet aEnumSet) const - { - EnumSet result(*this); - result &= aEnumSet; - return result; - } - - /** - * Equality - */ - bool operator==(const EnumSet aEnumSet) const - { - return mBitField == aEnumSet.mBitField; - } - - /** - * Test is an element is contained in the set. - */ - bool contains(T aEnum) const - { - return mBitField & bitFor(aEnum); - } - - /** - * Return the number of elements in the set. - */ - uint8_t size() const - { - uint8_t count = 0; - for (uint32_t bitField = mBitField; bitField; bitField >>= 1) { - if (bitField & 1) { - count++; - } - } - return count; - } - - bool isEmpty() const - { - return mBitField == 0; - } - - uint32_t serialize() const - { - return mBitField; - } - - void deserialize(uint32_t aValue) - { - incVersion(); - mBitField = aValue; - } - - class ConstIterator - { - const EnumSet* mSet; - uint32_t mPos; -#ifdef DEBUG - uint64_t mVersion; -#endif - - void checkVersion() { - // Check that the set has not been modified while being iterated. - MOZ_ASSERT_IF(mSet, mSet->mVersion == mVersion); - } - - public: - ConstIterator(const EnumSet& aSet, uint32_t aPos) - : mSet(&aSet), mPos(aPos) - { -#ifdef DEBUG - mVersion = mSet->mVersion; -#endif - MOZ_ASSERT(aPos <= kMaxBits); - if (aPos != kMaxBits && !mSet->contains(T(mPos))) - ++*this; - } - - ConstIterator(const ConstIterator& aOther) - : mSet(aOther.mSet), mPos(aOther.mPos) - { -#ifdef DEBUG - mVersion = aOther.mVersion; - checkVersion(); -#endif - } - - ConstIterator(ConstIterator&& aOther) - : mSet(aOther.mSet), mPos(aOther.mPos) - { -#ifdef DEBUG - mVersion = aOther.mVersion; - checkVersion(); -#endif - aOther.mSet = nullptr; - } - - ~ConstIterator() { - checkVersion(); - } - - bool operator==(const ConstIterator& other) { - MOZ_ASSERT(mSet == other.mSet); - checkVersion(); - return mPos == other.mPos; - } - - bool operator!=(const ConstIterator& other) { - return !(*this == other); - } - - T operator*() { - MOZ_ASSERT(mSet); - MOZ_ASSERT(mPos < kMaxBits); - MOZ_ASSERT(mSet->contains(T(mPos))); - checkVersion(); - return T(mPos); - } - - ConstIterator& operator++() { - MOZ_ASSERT(mSet); - MOZ_ASSERT(mPos < kMaxBits); - checkVersion(); - do { - mPos++; - } while (mPos < kMaxBits && !mSet->contains(T(mPos))); - return *this; - } - }; - - ConstIterator begin() const { - return ConstIterator(*this, 0); - } - - ConstIterator end() const { - return ConstIterator(*this, kMaxBits); - } - -private: - static uint32_t bitFor(T aEnum) - { - uint32_t bitNumber = (uint32_t)aEnum; - MOZ_ASSERT(bitNumber < kMaxBits); - return 1U << bitNumber; - } - - void initVersion() { -#ifdef DEBUG - mVersion = 0; -#endif - } - - void incVersion() { -#ifdef DEBUG - mVersion++; -#endif - } - - static const size_t kMaxBits = 32; - uint32_t mBitField; - -#ifdef DEBUG - uint64_t mVersion; -#endif -}; - -} // namespace mozilla - -#endif /* mozilla_EnumSet_h_*/ diff --git a/ios/include/spidermonkey/mozilla/EnumTypeTraits.h b/ios/include/spidermonkey/mozilla/EnumTypeTraits.h deleted file mode 100644 index 223eaf8c..00000000 --- a/ios/include/spidermonkey/mozilla/EnumTypeTraits.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Type traits for enums. */ - -#ifndef mozilla_EnumTypeTraits_h -#define mozilla_EnumTypeTraits_h - -#include - -namespace mozilla { - -namespace detail { - -template -struct EnumFitsWithinHelper; - -// Signed enum, signed storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -// Signed enum, unsigned storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -// Unsigned enum, signed storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -// Unsigned enum, unsigned storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -} // namespace detail - -/* - * Type trait that determines whether the enum type T can fit within the - * integral type Storage without data loss. This trait should be used with - * caution with an enum type whose underlying type has not been explicitly - * specified: for such enums, the C++ implementation is free to choose a type - * no smaller than int whose range encompasses all possible values of the enum. - * So for an enum with only small non-negative values, the underlying type may - * be either int or unsigned int, depending on the whims of the implementation. - */ -template -struct EnumTypeFitsWithin - : public detail::EnumFitsWithinHelper< - sizeof(T), - std::is_signed::type>::value, - sizeof(Storage), - std::is_signed::value - > -{ - static_assert(std::is_enum::value, "must provide an enum type"); - static_assert(std::is_integral::value, "must provide an integral type"); -}; - -} // namespace mozilla - -#endif /* mozilla_EnumTypeTraits_h */ diff --git a/ios/include/spidermonkey/mozilla/EnumeratedArray.h b/ios/include/spidermonkey/mozilla/EnumeratedArray.h deleted file mode 100644 index 9e74b772..00000000 --- a/ios/include/spidermonkey/mozilla/EnumeratedArray.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* EnumeratedArray is like Array, but indexed by a typed enum. */ - -#ifndef mozilla_EnumeratedArray_h -#define mozilla_EnumeratedArray_h - -#include "mozilla/Array.h" -#include "mozilla/Move.h" - -namespace mozilla { - -/** - * EnumeratedArray is a fixed-size array container for use when an - * array is indexed by a specific enum class. - * - * This provides type safety by guarding at compile time against accidentally - * indexing such arrays with unrelated values. This also removes the need - * for manual casting when using a typed enum value to index arrays. - * - * Aside from the typing of indices, EnumeratedArray is similar to Array. - * - * Example: - * - * enum class AnimalSpecies { - * Cow, - * Sheep, - * Count - * }; - * - * EnumeratedArray headCount; - * - * headCount[AnimalSpecies::Cow] = 17; - * headCount[AnimalSpecies::Sheep] = 30; - * - */ -template -class EnumeratedArray -{ -public: - static const size_t kSize = size_t(SizeAsEnumValue); - -private: - typedef Array ArrayType; - - ArrayType mArray; - -public: - EnumeratedArray() {} - - template - MOZ_IMPLICIT EnumeratedArray(Args&&... aArgs) - : mArray{mozilla::Forward(aArgs)...} - {} - - explicit EnumeratedArray(const EnumeratedArray& aOther) - { - for (size_t i = 0; i < kSize; i++) { - mArray[i] = aOther.mArray[i]; - } - } - - EnumeratedArray(EnumeratedArray&& aOther) - { - for (size_t i = 0; i < kSize; i++) { - mArray[i] = Move(aOther.mArray[i]); - } - } - - ValueType& operator[](IndexType aIndex) - { - return mArray[size_t(aIndex)]; - } - - const ValueType& operator[](IndexType aIndex) const - { - return mArray[size_t(aIndex)]; - } - - typedef typename ArrayType::iterator iterator; - typedef typename ArrayType::const_iterator const_iterator; - typedef typename ArrayType::reverse_iterator reverse_iterator; - typedef typename ArrayType::const_reverse_iterator const_reverse_iterator; - - // Methods for range-based for loops. - iterator begin() { return mArray.begin(); } - const_iterator begin() const { return mArray.begin(); } - const_iterator cbegin() const { return mArray.cbegin(); } - iterator end() { return mArray.end(); } - const_iterator end() const { return mArray.end(); } - const_iterator cend() const { return mArray.cend(); } - - // Methods for reverse iterating. - reverse_iterator rbegin() { return mArray.rbegin(); } - const_reverse_iterator rbegin() const { return mArray.rbegin(); } - const_reverse_iterator crbegin() const { return mArray.crbegin(); } - reverse_iterator rend() { return mArray.rend(); } - const_reverse_iterator rend() const { return mArray.rend(); } - const_reverse_iterator crend() const { return mArray.crend(); } -}; - -} // namespace mozilla - -#endif // mozilla_EnumeratedArray_h diff --git a/ios/include/spidermonkey/mozilla/EnumeratedRange.h b/ios/include/spidermonkey/mozilla/EnumeratedRange.h deleted file mode 100644 index b158f8a3..00000000 --- a/ios/include/spidermonkey/mozilla/EnumeratedRange.h +++ /dev/null @@ -1,201 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Iterator over contiguous enum values */ - -/* - * Implements generator functions that create a range to iterate over the values - * of a scoped or unscoped enum. Unlike IntegerRange, which can only function on - * the underlying integral type, the elements of the generated sequence will - * have the type of the enum in question. - * - * Note that the enum values should be contiguous in the iterated range; - * unfortunately there exists no way for EnumeratedRange to enforce this - * either dynamically or at compile time. - */ - -#ifndef mozilla_EnumeratedRange_h -#define mozilla_EnumeratedRange_h - -#include - -#include "mozilla/ReverseIterator.h" - -namespace mozilla { - -namespace detail { - -template -class EnumeratedIterator -{ -public: - typedef typename std::underlying_type::type IntTypeT; - - template - explicit EnumeratedIterator(EnumType aCurrent) - : mCurrent(aCurrent) { } - - template - explicit EnumeratedIterator(const EnumeratedIterator& aOther) - : mCurrent(aOther.mCurrent) { } - - EnumTypeT operator*() const { return mCurrent; } - - /* Increment and decrement operators */ - - EnumeratedIterator& operator++() - { - mCurrent = EnumTypeT(IntTypeT(mCurrent) + IntTypeT(1)); - return *this; - } - EnumeratedIterator& operator--() - { - mCurrent = EnumTypeT(IntTypeT(mCurrent) - IntTypeT(1)); - return *this; - } - EnumeratedIterator operator++(int) - { - auto ret = *this; - mCurrent = EnumTypeT(IntTypeT(mCurrent) + IntTypeT(1)); - return ret; - } - EnumeratedIterator operator--(int) - { - auto ret = *this; - mCurrent = EnumTypeT(IntTypeT(mCurrent) - IntTypeT(1)); - return ret; - } - - /* Comparison operators */ - - template - friend bool operator==(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator!=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator<(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator<=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator>(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator>=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - -private: - EnumTypeT mCurrent; -}; - -template -bool operator==(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent == aIter2.mCurrent; -} - -template -bool operator!=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent != aIter2.mCurrent; -} - -template -bool operator<(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent < aIter2.mCurrent; -} - -template -bool operator<=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent <= aIter2.mCurrent; -} - -template -bool operator>(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent > aIter2.mCurrent; -} - -template -bool operator>=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent >= aIter2.mCurrent; -} - -template -class EnumeratedRange -{ -public: - typedef EnumeratedIterator iterator; - typedef EnumeratedIterator const_iterator; - typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; - - template - EnumeratedRange(EnumType aBegin, EnumType aEnd) - : mBegin(aBegin), mEnd(aEnd) { } - - iterator begin() const { return iterator(mBegin); } - const_iterator cbegin() const { return begin(); } - iterator end() const { return iterator(mEnd); } - const_iterator cend() const { return end(); } - reverse_iterator rbegin() const { return reverse_iterator(mEnd); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() const { return reverse_iterator(mBegin); } - const_reverse_iterator crend() const { return rend(); } - -private: - EnumTypeT mBegin; - EnumTypeT mEnd; -}; - -} // namespace detail - -#ifdef __GNUC__ -// Enums can have an unsigned underlying type, which makes some of the -// comparisons below always true or always false. Temporarily disable -// -Wtype-limits to avoid breaking -Werror builds. -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wtype-limits" -#endif - -// Create a range to iterate from aBegin to aEnd, exclusive. -template -inline detail::EnumeratedRange -MakeEnumeratedRange(EnumType aBegin, EnumType aEnd) -{ - MOZ_ASSERT(aBegin <= aEnd, "Cannot generate invalid, unbounded range!"); - return detail::EnumeratedRange(aBegin, aEnd); -} - -// Create a range to iterate from EnumType(0) to aEnd, exclusive. EnumType(0) -// should exist, but note that there is no way for us to ensure that it does! -template -inline detail::EnumeratedRange -MakeEnumeratedRange(EnumType aEnd) -{ - return MakeEnumeratedRange(EnumType(0), aEnd); -} - -#ifdef __GNUC__ -# pragma GCC diagnostic pop -#endif - -} // namespace mozilla - -#endif // mozilla_EnumeratedRange_h - diff --git a/ios/include/spidermonkey/mozilla/FastBernoulliTrial.h b/ios/include/spidermonkey/mozilla/FastBernoulliTrial.h deleted file mode 100644 index 7e38b70a..00000000 --- a/ios/include/spidermonkey/mozilla/FastBernoulliTrial.h +++ /dev/null @@ -1,379 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_FastBernoulliTrial_h -#define mozilla_FastBernoulliTrial_h - -#include "mozilla/Assertions.h" -#include "mozilla/XorShift128PlusRNG.h" - -#include -#include - -namespace mozilla { - -/** - * class FastBernoulliTrial: Efficient sampling with uniform probability - * - * When gathering statistics about a program's behavior, we may be observing - * events that occur very frequently (e.g., function calls or memory - * allocations) and we may be gathering information that is somewhat expensive - * to produce (e.g., call stacks). Sampling all the events could have a - * significant impact on the program's performance. - * - * Why not just sample every N'th event? This technique is called "systematic - * sampling"; it's simple and efficient, and it's fine if we imagine a - * patternless stream of events. But what if we're sampling allocations, and the - * program happens to have a loop where each iteration does exactly N - * allocations? You would end up sampling the same allocation every time through - * the loop; the entire rest of the loop becomes invisible to your measurements! - * More generally, if each iteration does M allocations, and M and N have any - * common divisor at all, most allocation sites will never be sampled. If - * they're both even, say, the odd-numbered allocations disappear from your - * results. - * - * Ideally, we'd like each event to have some probability P of being sampled, - * independent of its neighbors and of its position in the sequence. This is - * called "Bernoulli sampling", and it doesn't suffer from any of the problems - * mentioned above. - * - * One disadvantage of Bernoulli sampling is that you can't be sure exactly how - * many samples you'll get: technically, it's possible that you might sample - * none of them, or all of them. But if the number of events N is large, these - * aren't likely outcomes; you can generally expect somewhere around P * N - * events to be sampled. - * - * The other disadvantage of Bernoulli sampling is that you have to generate a - * random number for every event, which can be slow. - * - * [significant pause] - * - * BUT NOT WITH THIS CLASS! FastBernoulliTrial lets you do true Bernoulli - * sampling, while generating a fresh random number only when we do decide to - * sample an event, not on every trial. When it decides not to sample, a call to - * |FastBernoulliTrial::trial| is nothing but decrementing a counter and - * comparing it to zero. So the lower your sampling probability is, the less - * overhead FastBernoulliTrial imposes. - * - * Probabilities of 0 and 1 are handled efficiently. (In neither case need we - * ever generate a random number at all.) - * - * The essential API: - * - * - FastBernoulliTrial(double P) - * Construct an instance that selects events with probability P. - * - * - FastBernoulliTrial::trial() - * Return true with probability P. Call this each time an event occurs, to - * decide whether to sample it or not. - * - * - FastBernoulliTrial::trial(size_t n) - * Equivalent to calling trial() |n| times, and returning true if any of those - * calls do. However, like trial, this runs in fast constant time. - * - * What is this good for? In some applications, some events are "bigger" than - * others. For example, large allocations are more significant than small - * allocations. Perhaps we'd like to imagine that we're drawing allocations - * from a stream of bytes, and performing a separate Bernoulli trial on every - * byte from the stream. We can accomplish this by calling |t.trial(S)| for - * the number of bytes S, and sampling the event if that returns true. - * - * Of course, this style of sampling needs to be paired with analysis and - * presentation that makes the size of the event apparent, lest trials with - * large values for |n| appear to be indistinguishable from those with small - * values for |n|. - */ -class FastBernoulliTrial { - /* - * This comment should just read, "Generate skip counts with a geometric - * distribution", and leave everyone to go look that up and see why it's the - * right thing to do, if they don't know already. - * - * BUT IF YOU'RE CURIOUS, COMMENTS ARE FREE... - * - * Instead of generating a fresh random number for every trial, we can - * randomly generate a count of how many times we should return false before - * the next time we return true. We call this a "skip count". Once we've - * returned true, we generate a fresh skip count, and begin counting down - * again. - * - * Here's an awesome fact: by exercising a little care in the way we generate - * skip counts, we can produce results indistinguishable from those we would - * get "rolling the dice" afresh for every trial. - * - * In short, skip counts in Bernoulli trials of probability P obey a geometric - * distribution. If a random variable X is uniformly distributed from [0..1), - * then std::floor(std::log(X) / std::log(1-P)) has the appropriate geometric - * distribution for the skip counts. - * - * Why that formula? - * - * Suppose we're to return |true| with some probability P, say, 0.3. Spread - * all possible futures along a line segment of length 1. In portion P of - * those cases, we'll return true on the next call to |trial|; the skip count - * is 0. For the remaining portion 1-P of cases, the skip count is 1 or more. - * - * skip: 0 1 or more - * |------------------^-----------------------------------------| - * portion: 0.3 0.7 - * P 1-P - * - * But the "1 or more" section of the line is subdivided the same way: *within - * that section*, in portion P the second call to |trial()| returns true, and in - * portion 1-P it returns false a second time; the skip count is two or more. - * So we return true on the second call in proportion 0.7 * 0.3, and skip at - * least the first two in proportion 0.7 * 0.7. - * - * skip: 0 1 2 or more - * |------------------^------------^----------------------------| - * portion: 0.3 0.7 * 0.3 0.7 * 0.7 - * P (1-P)*P (1-P)^2 - * - * We can continue to subdivide: - * - * skip >= 0: |------------------------------------------------- (1-P)^0 --| - * skip >= 1: | ------------------------------- (1-P)^1 --| - * skip >= 2: | ------------------ (1-P)^2 --| - * skip >= 3: | ^ ---------- (1-P)^3 --| - * skip >= 4: | . --- (1-P)^4 --| - * . - * ^X, see below - * - * In other words, the likelihood of the next n calls to |trial| returning - * false is (1-P)^n. The longer a run we require, the more the likelihood - * drops. Further calls may return false too, but this is the probability - * we'll skip at least n. - * - * This is interesting, because we can pick a point along this line segment - * and see which skip count's range it falls within; the point X above, for - * example, is within the ">= 2" range, but not within the ">= 3" range, so it - * designates a skip count of 2. So if we pick points on the line at random - * and use the skip counts they fall under, that will be indistinguishable - * from generating a fresh random number between 0 and 1 for each trial and - * comparing it to P. - * - * So to find the skip count for a point X, we must ask: To what whole power - * must we raise 1-P such that we include X, but the next power would exclude - * it? This is exactly std::floor(std::log(X) / std::log(1-P)). - * - * Our algorithm is then, simply: When constructed, compute an initial skip - * count. Return false from |trial| that many times, and then compute a new skip - * count. - * - * For a call to |trial(n)|, if the skip count is greater than n, return false - * and subtract n from the skip count. If the skip count is less than n, - * return true and compute a new skip count. Since each trial is independent, - * it doesn't matter by how much n overshoots the skip count; we can actually - * compute a new skip count at *any* time without affecting the distribution. - * This is really beautiful. - */ - public: - /** - * Construct a fast Bernoulli trial generator. Calls to |trial()| return true - * with probability |aProbability|. Use |aState0| and |aState1| to seed the - * random number generator; both may not be zero. - */ - FastBernoulliTrial(double aProbability, uint64_t aState0, uint64_t aState1) - : mProbability(0) - , mInvLogNotProbability(0) - , mGenerator(aState0, aState1) - , mSkipCount(0) - { - setProbability(aProbability); - } - - /** - * Return true with probability |mProbability|. Call this each time an event - * occurs, to decide whether to sample it or not. The lower |mProbability| is, - * the faster this function runs. - */ - bool trial() { - if (mSkipCount) { - mSkipCount--; - return false; - } - - return chooseSkipCount(); - } - - /** - * Equivalent to calling trial() |n| times, and returning true if any of those - * calls do. However, like trial, this runs in fast constant time. - * - * What is this good for? In some applications, some events are "bigger" than - * others. For example, large allocations are more significant than small - * allocations. Perhaps we'd like to imagine that we're drawing allocations - * from a stream of bytes, and performing a separate Bernoulli trial on every - * byte from the stream. We can accomplish this by calling |t.trial(S)| for - * the number of bytes S, and sampling the event if that returns true. - * - * Of course, this style of sampling needs to be paired with analysis and - * presentation that makes the "size" of the event apparent, lest trials with - * large values for |n| appear to be indistinguishable from those with small - * values for |n|, despite being potentially much more likely to be sampled. - */ - bool trial(size_t aCount) { - if (mSkipCount > aCount) { - mSkipCount -= aCount; - return false; - } - - return chooseSkipCount(); - } - - void setRandomState(uint64_t aState0, uint64_t aState1) { - mGenerator.setState(aState0, aState1); - } - - void setProbability(double aProbability) { - MOZ_ASSERT(0 <= aProbability && aProbability <= 1); - mProbability = aProbability; - if (0 < mProbability && mProbability < 1) { - /* - * Let's look carefully at how this calculation plays out in floating- - * point arithmetic. We'll assume IEEE, but the final C++ code we arrive - * at would still be fine if our numbers were mathematically perfect. So, - * while we've considered IEEE's edge cases, we haven't done anything that - * should be actively bad when using other representations. - * - * (In the below, read comparisons as exact mathematical comparisons: when - * we say something "equals 1", that means it's exactly equal to 1. We - * treat approximation using intervals with open boundaries: saying a - * value is in (0,1) doesn't specify how close to 0 or 1 the value gets. - * When we use closed boundaries like [2**-53, 1], we're careful to ensure - * the boundary values are actually representable.) - * - * - After the comparison above, we know mProbability is in (0,1). - * - * - The gaps below 1 are 2**-53, so that interval is (0, 1-2**-53]. - * - * - Because the floating-point gaps near 1 are wider than those near - * zero, there are many small positive doubles ε such that 1-ε rounds to - * exactly 1. However, 2**-53 can be represented exactly. So - * 1-mProbability is in [2**-53, 1]. - * - * - log(1 - mProbability) is thus in (-37, 0]. - * - * That range includes zero, but when we use mInvLogNotProbability, it - * would be helpful if we could trust that it's negative. So when log(1 - * - mProbability) is 0, we'll just set mProbability to 0, so that - * mInvLogNotProbability is not used in chooseSkipCount. - * - * - How much of the range of mProbability does this cause us to ignore? - * The only value for which log returns 0 is exactly 1; the slope of log - * at 1 is 1, so for small ε such that 1 - ε != 1, log(1 - ε) is -ε, - * never 0. The gaps near one are larger than the gaps near zero, so if - * 1 - ε wasn't 1, then -ε is representable. So if log(1 - mProbability) - * isn't 0, then 1 - mProbability isn't 1, which means that mProbability - * is at least 2**-53, as discussed earlier. This is a sampling - * likelihood of roughly one in ten trillion, which is unlikely to be - * distinguishable from zero in practice. - * - * So by forbidding zero, we've tightened our range to (-37, -2**-53]. - * - * - Finally, 1 / log(1 - mProbability) is in [-2**53, -1/37). This all - * falls readily within the range of an IEEE double. - * - * ALL THAT HAVING BEEN SAID: here are the five lines of actual code: - */ - double logNotProbability = std::log(1 - mProbability); - if (logNotProbability == 0.0) - mProbability = 0.0; - else - mInvLogNotProbability = 1 / logNotProbability; - } - - chooseSkipCount(); - } - - private: - /* The likelihood that any given call to |trial| should return true. */ - double mProbability; - - /* - * The value of 1/std::log(1 - mProbability), cached for repeated use. - * - * If mProbability is exactly 0 or exactly 1, we don't use this value. - * Otherwise, we guarantee this value is in the range [-2**53, -1/37), i.e. - * definitely negative, as required by chooseSkipCount. See setProbability for - * the details. - */ - double mInvLogNotProbability; - - /* Our random number generator. */ - non_crypto::XorShift128PlusRNG mGenerator; - - /* The number of times |trial| should return false before next returning true. */ - size_t mSkipCount; - - /* - * Choose the next skip count. This also returns the value that |trial| should - * return, since we have to check for the extreme values for mProbability - * anyway, and |trial| should never return true at all when mProbability is 0. - */ - bool chooseSkipCount() { - /* - * If the probability is 1.0, every call to |trial| returns true. Make sure - * mSkipCount is 0. - */ - if (mProbability == 1.0) { - mSkipCount = 0; - return true; - } - - /* - * If the probabilility is zero, |trial| never returns true. Don't bother us - * for a while. - */ - if (mProbability == 0.0) { - mSkipCount = SIZE_MAX; - return false; - } - - /* - * What sorts of values can this call to std::floor produce? - * - * Since mGenerator.nextDouble returns a value in [0, 1-2**-53], std::log - * returns a value in the range [-infinity, -2**-53], all negative. Since - * mInvLogNotProbability is negative (see its comments), the product is - * positive and possibly infinite. std::floor returns +infinity unchanged. - * So the result will always be positive. - * - * Converting a double to an integer that is out of range for that integer - * is undefined behavior, so we must clamp our result to SIZE_MAX, to ensure - * we get an acceptable value for mSkipCount. - * - * The clamp is written carefully. Note that if we had said: - * - * if (skipCount > SIZE_MAX) - * skipCount = SIZE_MAX; - * - * that leads to undefined behavior 64-bit machines: SIZE_MAX coerced to - * double is 2^64, not 2^64-1, so this doesn't actually set skipCount to a - * value that can be safely assigned to mSkipCount. - * - * Jakub Oleson cleverly suggested flipping the sense of the comparison: if - * we require that skipCount < SIZE_MAX, then because of the gaps (2048) - * between doubles at that magnitude, the highest double less than 2^64 is - * 2^64 - 2048, which is fine to store in a size_t. - * - * (On 32-bit machines, all size_t values can be represented exactly in - * double, so all is well.) - */ - double skipCount = std::floor(std::log(mGenerator.nextDouble()) - * mInvLogNotProbability); - if (skipCount < SIZE_MAX) - mSkipCount = skipCount; - else - mSkipCount = SIZE_MAX; - - return true; - } -}; - -} /* namespace mozilla */ - -#endif /* mozilla_FastBernoulliTrial_h */ diff --git a/ios/include/spidermonkey/mozilla/FloatingPoint.h b/ios/include/spidermonkey/mozilla/FloatingPoint.h deleted file mode 100644 index 59afccd1..00000000 --- a/ios/include/spidermonkey/mozilla/FloatingPoint.h +++ /dev/null @@ -1,479 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Various predicates and operations on IEEE-754 floating point types. */ - -#ifndef mozilla_FloatingPoint_h -#define mozilla_FloatingPoint_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/MathAlgorithms.h" -#include "mozilla/Types.h" - -#include - -namespace mozilla { - -/* - * It's reasonable to ask why we have this header at all. Don't isnan, - * copysign, the built-in comparison operators, and the like solve these - * problems? Unfortunately, they don't. We've found that various compilers - * (MSVC, MSVC when compiling with PGO, and GCC on OS X, at least) miscompile - * the standard methods in various situations, so we can't use them. Some of - * these compilers even have problems compiling seemingly reasonable bitwise - * algorithms! But with some care we've found algorithms that seem to not - * trigger those compiler bugs. - * - * For the aforementioned reasons, be very wary of making changes to any of - * these algorithms. If you must make changes, keep a careful eye out for - * compiler bustage, particularly PGO-specific bustage. - */ - -struct FloatTypeTraits -{ - typedef uint32_t Bits; - - static const unsigned kExponentBias = 127; - static const unsigned kExponentShift = 23; - - static const Bits kSignBit = 0x80000000UL; - static const Bits kExponentBits = 0x7F800000UL; - static const Bits kSignificandBits = 0x007FFFFFUL; -}; - -struct DoubleTypeTraits -{ - typedef uint64_t Bits; - - static const unsigned kExponentBias = 1023; - static const unsigned kExponentShift = 52; - - static const Bits kSignBit = 0x8000000000000000ULL; - static const Bits kExponentBits = 0x7ff0000000000000ULL; - static const Bits kSignificandBits = 0x000fffffffffffffULL; -}; - -template struct SelectTrait; -template<> struct SelectTrait : public FloatTypeTraits {}; -template<> struct SelectTrait : public DoubleTypeTraits {}; - -/* - * This struct contains details regarding the encoding of floating-point - * numbers that can be useful for direct bit manipulation. As of now, the - * template parameter has to be float or double. - * - * The nested typedef |Bits| is the unsigned integral type with the same size - * as T: uint32_t for float and uint64_t for double (static assertions - * double-check these assumptions). - * - * kExponentBias is the offset that is subtracted from the exponent when - * computing the value, i.e. one plus the opposite of the mininum possible - * exponent. - * kExponentShift is the shift that one needs to apply to retrieve the - * exponent component of the value. - * - * kSignBit contains a bits mask. Bit-and-ing with this mask will result in - * obtaining the sign bit. - * kExponentBits contains the mask needed for obtaining the exponent bits and - * kSignificandBits contains the mask needed for obtaining the significand - * bits. - * - * Full details of how floating point number formats are encoded are beyond - * the scope of this comment. For more information, see - * http://en.wikipedia.org/wiki/IEEE_floating_point - * http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers - */ -template -struct FloatingPoint : public SelectTrait -{ - typedef SelectTrait Base; - typedef typename Base::Bits Bits; - - static_assert((Base::kSignBit & Base::kExponentBits) == 0, - "sign bit shouldn't overlap exponent bits"); - static_assert((Base::kSignBit & Base::kSignificandBits) == 0, - "sign bit shouldn't overlap significand bits"); - static_assert((Base::kExponentBits & Base::kSignificandBits) == 0, - "exponent bits shouldn't overlap significand bits"); - - static_assert((Base::kSignBit | Base::kExponentBits | Base::kSignificandBits) == - ~Bits(0), - "all bits accounted for"); - - /* - * These implementations assume float/double are 32/64-bit single/double - * format number types compatible with the IEEE-754 standard. C++ don't - * require this to be the case. But we required this in implementations of - * these algorithms that preceded this header, so we shouldn't break anything - * if we keep doing so. - */ - static_assert(sizeof(T) == sizeof(Bits), "Bits must be same size as T"); -}; - -/** Determines whether a float/double is NaN. */ -template -static MOZ_ALWAYS_INLINE bool -IsNaN(T aValue) -{ - /* - * A float/double is NaN if all exponent bits are 1 and the significand - * contains at least one non-zero bit. - */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - return (BitwiseCast(aValue) & Traits::kExponentBits) == Traits::kExponentBits && - (BitwiseCast(aValue) & Traits::kSignificandBits) != 0; -} - -/** Determines whether a float/double is +Infinity or -Infinity. */ -template -static MOZ_ALWAYS_INLINE bool -IsInfinite(T aValue) -{ - /* Infinities have all exponent bits set to 1 and an all-0 significand. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return (bits & ~Traits::kSignBit) == Traits::kExponentBits; -} - -/** Determines whether a float/double is not NaN or infinite. */ -template -static MOZ_ALWAYS_INLINE bool -IsFinite(T aValue) -{ - /* - * NaN and Infinities are the only non-finite floats/doubles, and both have - * all exponent bits set to 1. - */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return (bits & Traits::kExponentBits) != Traits::kExponentBits; -} - -/** - * Determines whether a float/double is negative or -0. It is an error - * to call this method on a float/double which is NaN. - */ -template -static MOZ_ALWAYS_INLINE bool -IsNegative(T aValue) -{ - MOZ_ASSERT(!IsNaN(aValue), "NaN does not have a sign"); - - /* The sign bit is set if the double is negative. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return (bits & Traits::kSignBit) != 0; -} - -/** Determines whether a float/double represents -0. */ -template -static MOZ_ALWAYS_INLINE bool -IsNegativeZero(T aValue) -{ - /* Only the sign bit is set if the value is -0. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return bits == Traits::kSignBit; -} - -/** Determines wether a float/double represents +0. */ -template -static MOZ_ALWAYS_INLINE bool -IsPositiveZero(T aValue) -{ - /* All bits are zero if the value is +0. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return bits == 0; -} - -/** - * Returns 0 if a float/double is NaN or infinite; - * otherwise, the float/double is returned. - */ -template -static MOZ_ALWAYS_INLINE T -ToZeroIfNonfinite(T aValue) -{ - return IsFinite(aValue) ? aValue : 0; -} - -/** - * Returns the exponent portion of the float/double. - * - * Zero is not special-cased, so ExponentComponent(0.0) is - * -int_fast16_t(Traits::kExponentBias). - */ -template -static MOZ_ALWAYS_INLINE int_fast16_t -ExponentComponent(T aValue) -{ - /* - * The exponent component of a float/double is an unsigned number, biased - * from its actual value. Subtract the bias to retrieve the actual exponent. - */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return int_fast16_t((bits & Traits::kExponentBits) >> Traits::kExponentShift) - - int_fast16_t(Traits::kExponentBias); -} - -/** Returns +Infinity. */ -template -static MOZ_ALWAYS_INLINE T -PositiveInfinity() -{ - /* - * Positive infinity has all exponent bits set, sign bit set to 0, and no - * significand. - */ - typedef FloatingPoint Traits; - return BitwiseCast(Traits::kExponentBits); -} - -/** Returns -Infinity. */ -template -static MOZ_ALWAYS_INLINE T -NegativeInfinity() -{ - /* - * Negative infinity has all exponent bits set, sign bit set to 1, and no - * significand. - */ - typedef FloatingPoint Traits; - return BitwiseCast(Traits::kSignBit | Traits::kExponentBits); -} - -/** - * Computes the bit pattern for a NaN with the specified sign bit and - * significand bits. - */ -template::Bits Significand> -struct SpecificNaNBits -{ - using Traits = FloatingPoint; - - static_assert(SignBit == 0 || SignBit == 1, "bad sign bit"); - static_assert((Significand & ~Traits::kSignificandBits) == 0, - "significand must only have significand bits set"); - static_assert(Significand & Traits::kSignificandBits, - "significand must be nonzero"); - - static constexpr typename Traits::Bits value = - (SignBit * Traits::kSignBit) | Traits::kExponentBits | Significand; -}; - -/** - * Constructs a NaN value with the specified sign bit and significand bits. - * - * There is also a variant that returns the value directly. In most cases, the - * two variants should be identical. However, in the specific case of x86 - * chips, the behavior differs: returning floating-point values directly is done - * through the x87 stack, and x87 loads and stores turn signaling NaNs into - * quiet NaNs... silently. Returning floating-point values via outparam, - * however, is done entirely within the SSE registers when SSE2 floating-point - * is enabled in the compiler, which has semantics-preserving behavior you would - * expect. - * - * If preserving the distinction between signaling NaNs and quiet NaNs is - * important to you, you should use the outparam version. In all other cases, - * you should use the direct return version. - */ -template -static MOZ_ALWAYS_INLINE void -SpecificNaN(int signbit, typename FloatingPoint::Bits significand, T* result) -{ - typedef FloatingPoint Traits; - MOZ_ASSERT(signbit == 0 || signbit == 1); - MOZ_ASSERT((significand & ~Traits::kSignificandBits) == 0); - MOZ_ASSERT(significand & Traits::kSignificandBits); - - BitwiseCast((signbit ? Traits::kSignBit : 0) | - Traits::kExponentBits | - significand, - result); - MOZ_ASSERT(IsNaN(*result)); -} - -template -static MOZ_ALWAYS_INLINE T -SpecificNaN(int signbit, typename FloatingPoint::Bits significand) -{ - T t; - SpecificNaN(signbit, significand, &t); - return t; -} - -/** Computes the smallest non-zero positive float/double value. */ -template -static MOZ_ALWAYS_INLINE T -MinNumberValue() -{ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - return BitwiseCast(Bits(1)); -} - -/** - * If aValue is equal to some int32_t value, set *aInt32 to that value and - * return true; otherwise return false. - * - * Note that negative zero is "equal" to zero here. To test whether a value can - * be losslessly converted to int32_t and back, use NumberIsInt32 instead. - */ -template -static MOZ_ALWAYS_INLINE bool -NumberEqualsInt32(T aValue, int32_t* aInt32) -{ - /* - * XXX Casting a floating-point value that doesn't truncate to int32_t, to - * int32_t, induces undefined behavior. We should definitely fix this - * (bug 744965), but as apparently it "works" in practice, it's not a - * pressing concern now. - */ - return aValue == (*aInt32 = int32_t(aValue)); -} - -/** - * If d can be converted to int32_t and back to an identical double value, - * set *aInt32 to that value and return true; otherwise return false. - * - * The difference between this and NumberEqualsInt32 is that this method returns - * false for negative zero. - */ -template -static MOZ_ALWAYS_INLINE bool -NumberIsInt32(T aValue, int32_t* aInt32) -{ - return !IsNegativeZero(aValue) && NumberEqualsInt32(aValue, aInt32); -} - -/** - * Computes a NaN value. Do not use this method if you depend upon a particular - * NaN value being returned. - */ -template -static MOZ_ALWAYS_INLINE T -UnspecifiedNaN() -{ - /* - * If we can use any quiet NaN, we might as well use the all-ones NaN, - * since it's cheap to materialize on common platforms (such as x64, where - * this value can be represented in a 32-bit signed immediate field, allowing - * it to be stored to memory in a single instruction). - */ - typedef FloatingPoint Traits; - return SpecificNaN(1, Traits::kSignificandBits); -} - -/** - * Compare two doubles for equality, *without* equating -0 to +0, and equating - * any NaN value to any other NaN value. (The normal equality operators equate - * -0 with +0, and they equate NaN to no other value.) - */ -template -static inline bool -NumbersAreIdentical(T aValue1, T aValue2) -{ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - if (IsNaN(aValue1)) { - return IsNaN(aValue2); - } - return BitwiseCast(aValue1) == BitwiseCast(aValue2); -} - -namespace detail { - -template -struct FuzzyEqualsEpsilon; - -template<> -struct FuzzyEqualsEpsilon -{ - // A number near 1e-5 that is exactly representable in a float. - static float value() { return 1.0f / (1 << 17); } -}; - -template<> -struct FuzzyEqualsEpsilon -{ - // A number near 1e-12 that is exactly representable in a double. - static double value() { return 1.0 / (1LL << 40); } -}; - -} // namespace detail - -/** - * Compare two floating point values for equality, modulo rounding error. That - * is, the two values are considered equal if they are both not NaN and if they - * are less than or equal to aEpsilon apart. The default value of aEpsilon is - * near 1e-5. - * - * For most scenarios you will want to use FuzzyEqualsMultiplicative instead, - * as it is more reasonable over the entire range of floating point numbers. - * This additive version should only be used if you know the range of the - * numbers you are dealing with is bounded and stays around the same order of - * magnitude. - */ -template -static MOZ_ALWAYS_INLINE bool -FuzzyEqualsAdditive(T aValue1, T aValue2, - T aEpsilon = detail::FuzzyEqualsEpsilon::value()) -{ - static_assert(IsFloatingPoint::value, "floating point type required"); - return Abs(aValue1 - aValue2) <= aEpsilon; -} - -/** - * Compare two floating point values for equality, allowing for rounding error - * relative to the magnitude of the values. That is, the two values are - * considered equal if they are both not NaN and they are less than or equal to - * some aEpsilon apart, where the aEpsilon is scaled by the smaller of the two - * argument values. - * - * In most cases you will want to use this rather than FuzzyEqualsAdditive, as - * this function effectively masks out differences in the bottom few bits of - * the floating point numbers being compared, regardless of what order of - * magnitude those numbers are at. - */ -template -static MOZ_ALWAYS_INLINE bool -FuzzyEqualsMultiplicative(T aValue1, T aValue2, - T aEpsilon = detail::FuzzyEqualsEpsilon::value()) -{ - static_assert(IsFloatingPoint::value, "floating point type required"); - // can't use std::min because of bug 965340 - T smaller = Abs(aValue1) < Abs(aValue2) ? Abs(aValue1) : Abs(aValue2); - return Abs(aValue1 - aValue2) <= aEpsilon * smaller; -} - -/** - * Returns true if the given value can be losslessly represented as an IEEE-754 - * single format number, false otherwise. All NaN values are considered - * representable (notwithstanding that the exact bit pattern of a double format - * NaN value can't be exactly represented in single format). - * - * This function isn't inlined to avoid buggy optimizations by MSVC. - */ -MOZ_MUST_USE -extern MFBT_API bool -IsFloat32Representable(double aFloat32); - -} /* namespace mozilla */ - -#endif /* mozilla_FloatingPoint_h */ diff --git a/ios/include/spidermonkey/mozilla/Function.h b/ios/include/spidermonkey/mozilla/Function.h deleted file mode 100644 index d6de9c83..00000000 --- a/ios/include/spidermonkey/mozilla/Function.h +++ /dev/null @@ -1,223 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A type-erased callable wrapper. */ - -#ifndef mozilla_Function_h -#define mozilla_Function_h - -#include "mozilla/Attributes.h" // for MOZ_IMPLICIT -#include "mozilla/Move.h" -#include "mozilla/RefCounted.h" -#include "mozilla/RefPtr.h" - -// |function| is a wrapper that can hold any type of callable -// object that can be invoked in a way that's compatible with |Signature|. -// The standard "type erasure" technique is used to avoid the type of the -// wrapper depending on the concrete type of the wrapped callable. -// -// Supported callable types include non-member functions, static member -// functions, and function objects (that is to say, objects with an overloaded -// call operator; this includes C++11 lambdas). Member functions aren't -// directly supported; they first need to be wrapped into a function object -// using |std::mem_fn()| or an equivalent. -// -// |Signature| is a type of the form |ReturnType(Arguments...)|. Syntactically, -// this is a function type; it's not used in any way other than serving as a -// vehicle to encode the return and argument types into a single type. -// -// |function| is default-constructible. A default-constructed instance is -// considered "empty". Invoking an empty instance is undefined behaviour. -// An empty instance can be populated with a callable by assigning to it. -// -// This class is intended to provide functionality similar to the C++11 -// standard library class |std::function|. - -namespace mozilla { - -namespace detail { - -template -class FunctionImplBase : public mozilla::RefCounted> -{ -public: - MOZ_DECLARE_REFCOUNTED_TYPENAME(FunctionImplBase) - - virtual ~FunctionImplBase() {} - virtual ReturnType call(Arguments... aArguments) = 0; -}; - -// Normal Callable Object. -template -class FunctionImpl : public FunctionImplBase -{ - public: - explicit FunctionImpl(const Callable& aCallable) - : mCallable(aCallable) {} - - ReturnType call(Arguments... aArguments) override - { - return mCallable(Forward(aArguments)...); - } - private: - Callable mCallable; -}; - -// Base class for passing pointer to member function. -template -class MemberFunctionImplBase : public FunctionImplBase -{ -public: - explicit MemberFunctionImplBase(const Callable& aCallable) - : mCallable(aCallable) {} - - ReturnType call(Arguments... aArguments) override - { - return callInternal(Forward(aArguments)...); - } -private: - template - ReturnType callInternal(ThisType* aThis, Args&&... aArguments) - { - return (aThis->*mCallable)(Forward(aArguments)...); - } - - template - ReturnType callInternal(ThisType&& aThis, Args&&... aArguments) - { - return (aThis.*mCallable)(Forward(aArguments)...); - } - Callable mCallable; -}; - -// For non-const member function specialization of FunctionImpl. -template -class FunctionImpl - : public MemberFunctionImplBase -{ -public: - explicit FunctionImpl(ReturnType(ThisType::*aMemberFunc)(Args...)) - : MemberFunctionImplBase(aMemberFunc) - {} -}; - -// For const member function specialization of FunctionImpl. -template -class FunctionImpl - : public MemberFunctionImplBase -{ -public: - explicit FunctionImpl(ReturnType(ThisType::*aConstMemberFunc)(Args...) const) - : MemberFunctionImplBase(aConstMemberFunc) - {} -}; - -} // namespace detail - -// The primary template is never defined. As |Signature| is required to be -// of the form |ReturnType(Arguments...)|, we only define a partial -// specialization that matches this form. This allows us to use |ReturnType| -// and |Arguments| in the definition of the specialization without having to -// introspect |Signature|. -template -class function; - -template -class function -{ -public: - function() {} - - // This constructor is implicit to match the interface of |std::function|. - template - MOZ_IMPLICIT function(const Callable& aCallable) - : mImpl(new detail::FunctionImpl(aCallable)) - {} - MOZ_IMPLICIT function(const function& aFunction) - : mImpl(aFunction.mImpl) - {} - MOZ_IMPLICIT function(decltype(nullptr)) - {} - - // Move constructor and move assingment operator. - // These should be generated automatically, but MSVC doesn't do that yet. - function(function&& aOther) : mImpl(Move(aOther.mImpl)) {} - function& operator=(function&& aOther) { - mImpl = Move(aOther.mImpl); - return *this; - } - - template - function& operator=(const Callable& aCallable) - { - mImpl = new detail::FunctionImpl(aCallable); - return *this; - } - function& operator=(const function& aFunction) - { - mImpl = aFunction.mImpl; - return *this; - } - function& operator=(decltype(nullptr)) - { - mImpl = nullptr; - return *this; - } - - template - ReturnType operator()(Args&&... aArguments) const - { - MOZ_ASSERT(mImpl); - return mImpl->call(Forward(aArguments)...); - } - - explicit operator bool() const - { - return bool(mImpl); - } - -private: - // TODO: Consider implementing a small object optimization. - RefPtr> mImpl; -}; - -template -bool -operator==(const function& aX, decltype(nullptr)) -{ - return !aX; -} - -template -bool -operator==(decltype(nullptr), const function& aX) -{ - return !aX; -} - -template -bool -operator!=(const function& aX, decltype(nullptr)) -{ - return bool(aX); -} - -template -bool -operator!=(decltype(nullptr), const function& aX) -{ - return bool(aX); -} - -} // namespace mozilla - -#endif /* mozilla_Function_h */ diff --git a/ios/include/spidermonkey/mozilla/GuardObjects.h b/ios/include/spidermonkey/mozilla/GuardObjects.h deleted file mode 100644 index 9440c71c..00000000 --- a/ios/include/spidermonkey/mozilla/GuardObjects.h +++ /dev/null @@ -1,167 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implementation of macros to ensure correct use of RAII Auto* objects. */ - -#ifndef mozilla_GuardObjects_h -#define mozilla_GuardObjects_h - -#include "mozilla/Assertions.h" -#include "mozilla/Move.h" -#include "mozilla/Types.h" - -#ifdef __cplusplus - -#ifdef DEBUG - -/** - * A custom define is used rather than |mozPoisonValue()| due to cascading - * build failures relating to how mfbt is linked on different operating - * systems. See bug 1160253. - */ -#define MOZ_POISON uintptr_t(-1) - -namespace mozilla { -namespace detail { - -/* - * The following classes are designed to cause assertions to detect - * inadvertent use of guard objects as temporaries. In other words, - * when we have a guard object whose only purpose is its constructor and - * destructor (and is never otherwise referenced), the intended use - * might be: - * - * AutoRestore savePainting(mIsPainting); - * - * but is is easy to accidentally write: - * - * AutoRestore(mIsPainting); - * - * which compiles just fine, but runs the destructor well before the - * intended time. - * - * They work by adding (#ifdef DEBUG) an additional parameter to the - * guard object's constructor, with a default value, so that users of - * the guard object's API do not need to do anything. The default value - * of this parameter is a temporary object. C++ (ISO/IEC 14882:1998), - * section 12.2 [class.temporary], clauses 4 and 5 seem to assume a - * guarantee that temporaries are destroyed in the reverse of their - * construction order, but I actually can't find a statement that that - * is true in the general case (beyond the two specific cases mentioned - * there). However, it seems to be true. - * - * These classes are intended to be used only via the macros immediately - * below them: - * - * MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER declares (ifdef DEBUG) a member - * variable, and should be put where a declaration of a private - * member variable would be placed. - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM should be placed at the end of the - * parameters to each constructor of the guard object; it declares - * (ifdef DEBUG) an additional parameter. (But use the *_ONLY_PARAM - * variant for constructors that take no other parameters.) - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL should likewise be used in - * the implementation of such constructors when they are not inline. - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT should be used in - * the implementation of such constructors to pass the parameter to - * a base class that also uses these macros - * MOZ_GUARD_OBJECT_NOTIFIER_INIT is a statement that belongs in each - * constructor. It uses the parameter declared by - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM. - * - * For more details, and examples of using these macros, see - * https://developer.mozilla.org/en/Using_RAII_classes_in_Mozilla - */ -class GuardObjectNotifier -{ -private: - bool* mStatementDone; - -public: - GuardObjectNotifier() - : mStatementDone(reinterpret_cast(MOZ_POISON)) - { - } - - ~GuardObjectNotifier() - { - // Assert that the GuardObjectNotifier has been properly initialized by - // using the |MOZ_GUARD_OBJECT_NOTIFIER_INIT| macro. A poison value is - // used rather than a null check to appease static analyzers that were - // (incorrectly) detecting null pointer dereferences. - MOZ_ASSERT(mStatementDone != reinterpret_cast(MOZ_POISON)); - *mStatementDone = true; - } - - void setStatementDone(bool* aStatementIsDone) - { - mStatementDone = aStatementIsDone; - } -}; - -class GuardObjectNotificationReceiver -{ -private: - bool mStatementDone; - -public: - GuardObjectNotificationReceiver() : mStatementDone(false) { } - - ~GuardObjectNotificationReceiver() { - /* - * Assert that the guard object was not used as a temporary. (Note that - * this assert might also fire if init is not called because the guard - * object's implementation is not using the above macros correctly.) - */ - MOZ_ASSERT(mStatementDone); - } - - void init(GuardObjectNotifier& aNotifier) - { - aNotifier.setStatementDone(&mStatementDone); - } -}; - -} /* namespace detail */ -} /* namespace mozilla */ - -#undef MOZ_POISON - -#endif /* DEBUG */ - -#ifdef DEBUG -# define MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER \ - mozilla::detail::GuardObjectNotificationReceiver _mCheckNotUsedAsTemporary; -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM \ - , mozilla::detail::GuardObjectNotifier&& _notifier = \ - mozilla::detail::GuardObjectNotifier() -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM \ - mozilla::detail::GuardObjectNotifier&& _notifier = \ - mozilla::detail::GuardObjectNotifier() -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL \ - , mozilla::detail::GuardObjectNotifier&& _notifier -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_IN_IMPL \ - mozilla::detail::GuardObjectNotifier&& _notifier -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT \ - , mozilla::Move(_notifier) -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT \ - mozilla::Move(_notifier) -# define MOZ_GUARD_OBJECT_NOTIFIER_INIT \ - do { _mCheckNotUsedAsTemporary.init(_notifier); } while (0) -#else -# define MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_IN_IMPL -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT -# define MOZ_GUARD_OBJECT_NOTIFIER_INIT do { } while (0) -#endif - -#endif /* __cplusplus */ - -#endif /* mozilla_GuardObjects_h */ diff --git a/ios/include/spidermonkey/mozilla/HashFunctions.h b/ios/include/spidermonkey/mozilla/HashFunctions.h deleted file mode 100644 index eeb192c3..00000000 --- a/ios/include/spidermonkey/mozilla/HashFunctions.h +++ /dev/null @@ -1,389 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Utilities for hashing. */ - -/* - * This file exports functions for hashing data down to a 32-bit value, - * including: - * - * - HashString Hash a char* or char16_t/wchar_t* of known or unknown - * length. - * - * - HashBytes Hash a byte array of known length. - * - * - HashGeneric Hash one or more values. Currently, we support uint32_t, - * types which can be implicitly cast to uint32_t, data - * pointers, and function pointers. - * - * - AddToHash Add one or more values to the given hash. This supports the - * same list of types as HashGeneric. - * - * - * You can chain these functions together to hash complex objects. For example: - * - * class ComplexObject - * { - * char* mStr; - * uint32_t mUint1, mUint2; - * void (*mCallbackFn)(); - * - * public: - * uint32_t hash() - * { - * uint32_t hash = HashString(mStr); - * hash = AddToHash(hash, mUint1, mUint2); - * return AddToHash(hash, mCallbackFn); - * } - * }; - * - * If you want to hash an nsAString or nsACString, use the HashString functions - * in nsHashKeys.h. - */ - -#ifndef mozilla_HashFunctions_h -#define mozilla_HashFunctions_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Char16.h" -#include "mozilla/MathAlgorithms.h" -#include "mozilla/Types.h" - -#include - -#ifdef __cplusplus -namespace mozilla { - -/** - * The golden ratio as a 32-bit fixed-point value. - */ -static const uint32_t kGoldenRatioU32 = 0x9E3779B9U; - -inline uint32_t -RotateBitsLeft32(uint32_t aValue, uint8_t aBits) -{ - MOZ_ASSERT(aBits < 32); - return (aValue << aBits) | (aValue >> (32 - aBits)); -} - -namespace detail { - -inline uint32_t -AddU32ToHash(uint32_t aHash, uint32_t aValue) -{ - /* - * This is the meat of all our hash routines. This hash function is not - * particularly sophisticated, but it seems to work well for our mostly - * plain-text inputs. Implementation notes follow. - * - * Our use of the golden ratio here is arbitrary; we could pick almost any - * number which: - * - * * is odd (because otherwise, all our hash values will be even) - * - * * has a reasonably-even mix of 1's and 0's (consider the extreme case - * where we multiply by 0x3 or 0xeffffff -- this will not produce good - * mixing across all bits of the hash). - * - * The rotation length of 5 is also arbitrary, although an odd number is again - * preferable so our hash explores the whole universe of possible rotations. - * - * Finally, we multiply by the golden ratio *after* xor'ing, not before. - * Otherwise, if |aHash| is 0 (as it often is for the beginning of a - * message), the expression - * - * (kGoldenRatioU32 * RotateBitsLeft(aHash, 5)) |xor| aValue - * - * evaluates to |aValue|. - * - * (Number-theoretic aside: Because any odd number |m| is relatively prime to - * our modulus (2^32), the list - * - * [x * m (mod 2^32) for 0 <= x < 2^32] - * - * has no duplicate elements. This means that multiplying by |m| does not - * cause us to skip any possible hash values. - * - * It's also nice if |m| has large-ish order mod 2^32 -- that is, if the - * smallest k such that m^k == 1 (mod 2^32) is large -- so we can safely - * multiply our hash value by |m| a few times without negating the - * multiplicative effect. Our golden ratio constant has order 2^29, which is - * more than enough for our purposes.) - */ - return kGoldenRatioU32 * (RotateBitsLeft32(aHash, 5) ^ aValue); -} - -/** - * AddUintptrToHash takes sizeof(uintptr_t) as a template parameter. - */ -template -inline uint32_t -AddUintptrToHash(uint32_t aHash, uintptr_t aValue); - -template<> -inline uint32_t -AddUintptrToHash<4>(uint32_t aHash, uintptr_t aValue) -{ - return AddU32ToHash(aHash, static_cast(aValue)); -} - -template<> -inline uint32_t -AddUintptrToHash<8>(uint32_t aHash, uintptr_t aValue) -{ - /* - * The static cast to uint64_t below is necessary because this function - * sometimes gets compiled on 32-bit platforms (yes, even though it's a - * template and we never call this particular override in a 32-bit build). If - * we do aValue >> 32 on a 32-bit machine, we're shifting a 32-bit uintptr_t - * right 32 bits, and the compiler throws an error. - */ - uint32_t v1 = static_cast(aValue); - uint32_t v2 = static_cast(static_cast(aValue) >> 32); - return AddU32ToHash(AddU32ToHash(aHash, v1), v2); -} - -} /* namespace detail */ - -/** - * AddToHash takes a hash and some values and returns a new hash based on the - * inputs. - * - * Currently, we support hashing uint32_t's, values which we can implicitly - * convert to uint32_t, data pointers, and function pointers. - */ -template -MOZ_MUST_USE inline uint32_t -AddToHash(uint32_t aHash, A aA) -{ - /* - * Try to convert |A| to uint32_t implicitly. If this works, great. If not, - * we'll error out. - */ - return detail::AddU32ToHash(aHash, aA); -} - -template -MOZ_MUST_USE inline uint32_t -AddToHash(uint32_t aHash, A* aA) -{ - /* - * You might think this function should just take a void*. But then we'd only - * catch data pointers and couldn't handle function pointers. - */ - - static_assert(sizeof(aA) == sizeof(uintptr_t), "Strange pointer!"); - - return detail::AddUintptrToHash(aHash, uintptr_t(aA)); -} - -template<> -MOZ_MUST_USE inline uint32_t -AddToHash(uint32_t aHash, uintptr_t aA) -{ - return detail::AddUintptrToHash(aHash, aA); -} - -template -MOZ_MUST_USE uint32_t -AddToHash(uint32_t aHash, A aArg, Args... aArgs) -{ - return AddToHash(AddToHash(aHash, aArg), aArgs...); -} - -/** - * The HashGeneric class of functions let you hash one or more values. - * - * If you want to hash together two values x and y, calling HashGeneric(x, y) is - * much better than calling AddToHash(x, y), because AddToHash(x, y) assumes - * that x has already been hashed. - */ -template -MOZ_MUST_USE inline uint32_t -HashGeneric(Args... aArgs) -{ - return AddToHash(0, aArgs...); -} - -namespace detail { - -template -uint32_t -HashUntilZero(const T* aStr) -{ - uint32_t hash = 0; - for (T c; (c = *aStr); aStr++) { - hash = AddToHash(hash, c); - } - return hash; -} - -template -uint32_t -HashKnownLength(const T* aStr, size_t aLength) -{ - uint32_t hash = 0; - for (size_t i = 0; i < aLength; i++) { - hash = AddToHash(hash, aStr[i]); - } - return hash; -} - -} /* namespace detail */ - -/** - * The HashString overloads below do just what you'd expect. - * - * If you have the string's length, you might as well call the overload which - * includes the length. It may be marginally faster. - */ -MOZ_MUST_USE inline uint32_t -HashString(const char* aStr) -{ - return detail::HashUntilZero(reinterpret_cast(aStr)); -} - -MOZ_MUST_USE inline uint32_t -HashString(const char* aStr, size_t aLength) -{ - return detail::HashKnownLength(reinterpret_cast(aStr), aLength); -} - -MOZ_MUST_USE -inline uint32_t -HashString(const unsigned char* aStr, size_t aLength) -{ - return detail::HashKnownLength(aStr, aLength); -} - -MOZ_MUST_USE inline uint32_t -HashString(const char16_t* aStr) -{ - return detail::HashUntilZero(aStr); -} - -MOZ_MUST_USE inline uint32_t -HashString(const char16_t* aStr, size_t aLength) -{ - return detail::HashKnownLength(aStr, aLength); -} - -/* - * On Windows, wchar_t is not the same as char16_t, even though it's - * the same width! - */ -#ifdef WIN32 -MOZ_MUST_USE inline uint32_t -HashString(const wchar_t* aStr) -{ - return detail::HashUntilZero(aStr); -} - -MOZ_MUST_USE inline uint32_t -HashString(const wchar_t* aStr, size_t aLength) -{ - return detail::HashKnownLength(aStr, aLength); -} -#endif - -/** - * Hash some number of bytes. - * - * This hash walks word-by-word, rather than byte-by-byte, so you won't get the - * same result out of HashBytes as you would out of HashString. - */ -MOZ_MUST_USE extern MFBT_API uint32_t -HashBytes(const void* bytes, size_t aLength); - -/** - * A pseudorandom function mapping 32-bit integers to 32-bit integers. - * - * This is for when you're feeding private data (like pointer values or credit - * card numbers) to a non-crypto hash function (like HashBytes) and then using - * the hash code for something that untrusted parties could observe (like a JS - * Map). Plug in a HashCodeScrambler before that last step to avoid leaking the - * private data. - * - * By itself, this does not prevent hash-flooding DoS attacks, because an - * attacker can still generate many values with exactly equal hash codes by - * attacking the non-crypto hash function alone. Equal hash codes will, of - * course, still be equal however much you scramble them. - * - * The algorithm is SipHash-1-3. See . - */ -class HashCodeScrambler -{ - struct SipHasher; - - uint64_t mK0, mK1; - -public: - /** Creates a new scrambler with the given 128-bit key. */ - constexpr HashCodeScrambler(uint64_t aK0, uint64_t aK1) : mK0(aK0), mK1(aK1) {} - - /** - * Scramble a hash code. Always produces the same result for the same - * combination of key and hash code. - */ - uint32_t scramble(uint32_t aHashCode) const - { - SipHasher hasher(mK0, mK1); - return uint32_t(hasher.sipHash(aHashCode)); - } - -private: - struct SipHasher - { - SipHasher(uint64_t aK0, uint64_t aK1) - { - // 1. Initialization. - mV0 = aK0 ^ UINT64_C(0x736f6d6570736575); - mV1 = aK1 ^ UINT64_C(0x646f72616e646f6d); - mV2 = aK0 ^ UINT64_C(0x6c7967656e657261); - mV3 = aK1 ^ UINT64_C(0x7465646279746573); - } - - uint64_t sipHash(uint64_t aM) - { - // 2. Compression. - mV3 ^= aM; - sipRound(); - mV0 ^= aM; - - // 3. Finalization. - mV2 ^= 0xff; - for (int i = 0; i < 3; i++) - sipRound(); - return mV0 ^ mV1 ^ mV2 ^ mV3; - } - - void sipRound() - { - mV0 += mV1; - mV1 = RotateLeft(mV1, 13); - mV1 ^= mV0; - mV0 = RotateLeft(mV0, 32); - mV2 += mV3; - mV3 = RotateLeft(mV3, 16); - mV3 ^= mV2; - mV0 += mV3; - mV3 = RotateLeft(mV3, 21); - mV3 ^= mV0; - mV2 += mV1; - mV1 = RotateLeft(mV1, 17); - mV1 ^= mV2; - mV2 = RotateLeft(mV2, 32); - } - - uint64_t mV0, mV1, mV2, mV3; - }; -}; - -} /* namespace mozilla */ -#endif /* __cplusplus */ - -#endif /* mozilla_HashFunctions_h */ diff --git a/ios/include/spidermonkey/mozilla/IndexSequence.h b/ios/include/spidermonkey/mozilla/IndexSequence.h deleted file mode 100644 index 1ccace02..00000000 --- a/ios/include/spidermonkey/mozilla/IndexSequence.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A utility for expanding a tuple into a variadic argument list. - * Based on std::index_sequence. */ - -/** - * Example usage: - * - * Problem: - * - * You have a variadic function Foo: - * - * template void Foo(Args...); - * - * And a variadic function Bar, which contains a tuple: - * - * template - * void Bar() { - * // ... - * Tuple t; - * } - * - * And inside Bar, you want to call Foo with the elements of the tuple as - * arguments to Foo. - * - * You want to write: - * - * Foo(Get<0>(t), Get<1>(t), ..., Get(t)) - * - * but you can't literally write that, because N is different for different - * instantiations of Bar. - * - * Solution: - * - * Write a helper function which takes the tuple, and an index sequence - * containing indices corresponding to the tuple indices. - * - * template - * void Helper(const Tuple& t, IndexSequence) - * { - * Foo(Get(t)...); - * } - * - * Assuming 'Indices...' are 0, 1, ..., N - 1, where N is the size of the - * tuple, pack expansion will expand the pack 'Get(t)...' to - * 'Get<0>(t), Get<1>(t), ..., Get(t)'. - * - * Finally, call the helper, creating the index sequence to pass in like so: - * - * template - * void Bar() { - * // ... - * Tuple t; - * Helper(t, typename IndexSequenceFor::Type()); - * } - */ - -#ifndef mozilla_IndexSequence_h -#define mozilla_IndexSequence_h - -#include "mozilla/Attributes.h" - -#include - -namespace mozilla { - -/** - * Represents a compile-time sequence of integer indices. - */ -template -struct IndexSequence -{ - static constexpr size_t Size() { return sizeof...(Indices); } -}; - -namespace detail { - -// Helpers used by MakeIndexSequence. - -template -struct IndexTuple -{ - typedef IndexTuple Next; -}; - -// Builds IndexTuple<0, 1, ..., N - 1>. -template -struct BuildIndexTuple -{ - typedef typename BuildIndexTuple::Type::Next Type; -}; - -template<> -struct BuildIndexTuple<0> -{ - typedef IndexTuple<> Type; -}; - -template -struct MakeIndexSequenceImpl; - -template -struct MakeIndexSequenceImpl> -{ - typedef IndexSequence Type; -}; - -} // namespace detail - -/** - * A utility for building an IndexSequence of consecutive indices. - * MakeIndexSequence::Type evaluates to IndexSequence<0, 1, .., N - 1>. - * Note: unlike std::make_index_sequence, this is not an alias template - * to work around bugs in MSVC 2013. - */ -template -struct MakeIndexSequence -{ - typedef typename detail::MakeIndexSequenceImpl::Type>::Type Type; -}; - -/** - * A utility for building an IndexSequence of consecutive indices - * corresponding to a variadic argument list. - * IndexSequenceFor evaluates to IndexSequence<0, 1, ..., N - 1> - * where N is the number of types in Types. - * Note: unlike std::index_sequence_for, this is not an alias template - * to work around bugs in MSVC 2013. - */ -template -struct IndexSequenceFor -{ - typedef typename MakeIndexSequence::Type Type; -}; - -} // namespace mozilla - -#endif /* mozilla_IndexSequence_h */ diff --git a/ios/include/spidermonkey/mozilla/IntegerPrintfMacros.h b/ios/include/spidermonkey/mozilla/IntegerPrintfMacros.h deleted file mode 100644 index c534a0ba..00000000 --- a/ios/include/spidermonkey/mozilla/IntegerPrintfMacros.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements the C99 interface. */ - -#ifndef mozilla_IntegerPrintfMacros_h_ -#define mozilla_IntegerPrintfMacros_h_ - -/* - * These macros should not be used with the NSPR printf-like functions or their - * users, e.g. mozilla/Logging.h. If you need to use NSPR's facilities, see the - * comment on supported formats at the top of nsprpub/pr/include/prprf.h. - */ - -/* - * scanf is a footgun: if the input number exceeds the bounds of the target - * type, behavior is undefined (in the compiler sense: that is, this code - * could overwrite your hard drive with zeroes): - * - * uint8_t u; - * sscanf("256", "%" SCNu8, &u); // BAD - * - * For this reason, *never* use the SCN* macros provided by this header! - */ - -#include - -/* - * Fix up Android's broken [u]intptr_t inttype macros. Android's PRI*PTR - * macros are defined as "ld", but sizeof(long) is 8 and sizeof(intptr_t) - * is 4 on 32-bit Android. TestTypeTraits.cpp asserts that these new macro - * definitions match the actual type sizes seen at compile time. - */ -#if defined(ANDROID) && !defined(__LP64__) -# undef PRIdPTR /* intptr_t */ -# define PRIdPTR "d" /* intptr_t */ -# undef PRIiPTR /* intptr_t */ -# define PRIiPTR "i" /* intptr_t */ -# undef PRIoPTR /* uintptr_t */ -# define PRIoPTR "o" /* uintptr_t */ -# undef PRIuPTR /* uintptr_t */ -# define PRIuPTR "u" /* uintptr_t */ -# undef PRIxPTR /* uintptr_t */ -# define PRIxPTR "x" /* uintptr_t */ -# undef PRIXPTR /* uintptr_t */ -# define PRIXPTR "X" /* uintptr_t */ -#endif - -#endif /* mozilla_IntegerPrintfMacros_h_ */ diff --git a/ios/include/spidermonkey/mozilla/IntegerRange.h b/ios/include/spidermonkey/mozilla/IntegerRange.h deleted file mode 100644 index 8d5d2e4d..00000000 --- a/ios/include/spidermonkey/mozilla/IntegerRange.h +++ /dev/null @@ -1,181 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Iterator over ranges of integers */ - -#ifndef mozilla_IntegerRange_h -#define mozilla_IntegerRange_h - -#include "mozilla/Assertions.h" -#include "mozilla/ReverseIterator.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -namespace detail { - -template -class IntegerIterator -{ -public: - template - explicit IntegerIterator(IntType aCurrent) - : mCurrent(aCurrent) { } - - template - explicit IntegerIterator(const IntegerIterator& aOther) - : mCurrent(aOther.mCurrent) { } - - IntTypeT operator*() const { return mCurrent; } - - /* Increment and decrement operators */ - - IntegerIterator& operator++() { ++mCurrent; return *this; } - IntegerIterator& operator--() { --mCurrent; return *this; } - IntegerIterator operator++(int) { auto ret = *this; ++mCurrent; return ret; } - IntegerIterator operator--(int) { auto ret = *this; --mCurrent; return ret; } - - /* Comparison operators */ - - template - friend bool operator==(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator!=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator<(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator<=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator>(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator>=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - -private: - IntTypeT mCurrent; -}; - -template -bool operator==(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent == aIter2.mCurrent; -} - -template -bool operator!=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent != aIter2.mCurrent; -} - -template -bool operator<(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent < aIter2.mCurrent; -} - -template -bool operator<=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent <= aIter2.mCurrent; -} - -template -bool operator>(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent > aIter2.mCurrent; -} - -template -bool operator>=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent >= aIter2.mCurrent; -} - -template -class IntegerRange -{ -public: - typedef IntegerIterator iterator; - typedef IntegerIterator const_iterator; - typedef ReverseIterator> reverse_iterator; - typedef ReverseIterator> const_reverse_iterator; - - template - explicit IntegerRange(IntType aEnd) - : mBegin(0), mEnd(aEnd) { } - - template - IntegerRange(IntType1 aBegin, IntType2 aEnd) - : mBegin(aBegin), mEnd(aEnd) { } - - iterator begin() const { return iterator(mBegin); } - const_iterator cbegin() const { return begin(); } - iterator end() const { return iterator(mEnd); } - const_iterator cend() const { return end(); } - reverse_iterator rbegin() const { return reverse_iterator(mEnd); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() const { return reverse_iterator(mBegin); } - const_reverse_iterator crend() const { return rend(); } - -private: - IntTypeT mBegin; - IntTypeT mEnd; -}; - -template::value> -struct GeqZero -{ - static bool check(T t) { - return t >= 0; - } -}; - -template -struct GeqZero -{ - static bool check(T t) { - return true; - } -}; - -} // namespace detail - -template -detail::IntegerRange -MakeRange(IntType aEnd) -{ - static_assert(IsIntegral::value, "value must be integral"); - MOZ_ASSERT(detail::GeqZero::check(aEnd), - "Should never have negative value here"); - return detail::IntegerRange(aEnd); -} - -template -detail::IntegerRange -MakeRange(IntType1 aBegin, IntType2 aEnd) -{ - static_assert(IsIntegral::value && IsIntegral::value, - "values must both be integral"); - static_assert(IsSigned::value == IsSigned::value, - "signed/unsigned mismatch"); - MOZ_ASSERT(aEnd >= aBegin, "End value should be larger than begin value"); - return detail::IntegerRange(aBegin, aEnd); -} - -} // namespace mozilla - -#endif // mozilla_IntegerRange_h diff --git a/ios/include/spidermonkey/mozilla/IntegerTypeTraits.h b/ios/include/spidermonkey/mozilla/IntegerTypeTraits.h deleted file mode 100644 index 6144d208..00000000 --- a/ios/include/spidermonkey/mozilla/IntegerTypeTraits.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Helpers to manipulate integer types that don't fit in TypeTraits.h */ - -#ifndef mozilla_IntegerTypeTraits_h -#define mozilla_IntegerTypeTraits_h - -#include "mozilla/TypeTraits.h" -#include - -namespace mozilla { - -namespace detail { - -/** - * StdintTypeForSizeAndSignedness returns the stdint integer type - * of given size (can be 1, 2, 4 or 8) and given signedness - * (false means unsigned, true means signed). - */ -template -struct StdintTypeForSizeAndSignedness; - -template<> -struct StdintTypeForSizeAndSignedness<1, true> -{ - typedef int8_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<1, false> -{ - typedef uint8_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<2, true> -{ - typedef int16_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<2, false> -{ - typedef uint16_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<4, true> -{ - typedef int32_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<4, false> -{ - typedef uint32_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<8, true> -{ - typedef int64_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<8, false> -{ - typedef uint64_t Type; -}; - -} // namespace detail - -template -struct UnsignedStdintTypeForSize - : detail::StdintTypeForSizeAndSignedness -{}; - -template -struct SignedStdintTypeForSize - : detail::StdintTypeForSizeAndSignedness -{}; - -template -struct PositionOfSignBit -{ - static_assert(IsIntegral::value, - "PositionOfSignBit is only for integral types"); - // 8 here should be CHAR_BIT from limits.h, but the world has moved on. - static const size_t value = 8 * sizeof(IntegerType) - 1; -}; - -/** - * MinValue returns the minimum value of the given integer type as a - * compile-time constant, which std::numeric_limits::min() - * cannot do in c++98. - */ -template -struct MinValue -{ -private: - static_assert(IsIntegral::value, - "MinValue is only for integral types"); - - typedef typename MakeUnsigned::Type UnsignedIntegerType; - static const size_t PosOfSignBit = PositionOfSignBit::value; - -public: - // Bitwise ops may return a larger type, that's why we cast explicitly. - // In C++, left bit shifts on signed values is undefined by the standard - // unless the shifted value is representable. - // Notice that signed-to-unsigned conversions are always well-defined in - // the standard as the value congruent to 2**n, as expected. By contrast, - // unsigned-to-signed is only well-defined if the value is representable. - static const IntegerType value = - IsSigned::value - ? IntegerType(UnsignedIntegerType(1) << PosOfSignBit) - : IntegerType(0); -}; - -/** - * MaxValue returns the maximum value of the given integer type as a - * compile-time constant, which std::numeric_limits::max() - * cannot do in c++98. - */ -template -struct MaxValue -{ - static_assert(IsIntegral::value, - "MaxValue is only for integral types"); - - // Tricksy, but covered by the CheckedInt unit test. - // Relies on the type of MinValue::value - // being IntegerType. - static const IntegerType value = ~MinValue::value; -}; - -} // namespace mozilla - -#endif // mozilla_IntegerTypeTraits_h diff --git a/ios/include/spidermonkey/mozilla/JSONWriter.h b/ios/include/spidermonkey/mozilla/JSONWriter.h deleted file mode 100644 index 7d44dc7f..00000000 --- a/ios/include/spidermonkey/mozilla/JSONWriter.h +++ /dev/null @@ -1,460 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A JSON pretty-printer class. */ - -// A typical JSON-writing library requires you to first build up a data -// structure that represents a JSON object and then serialize it (to file, or -// somewhere else). This approach makes for a clean API, but building the data -// structure takes up memory. Sometimes that isn't desirable, such as when the -// JSON data is produced for memory reporting. -// -// The JSONWriter class instead allows JSON data to be written out -// incrementally without building up large data structures. -// -// The API is slightly uglier than you would see in a typical JSON-writing -// library, but still fairly easy to use. It's possible to generate invalid -// JSON with JSONWriter, but typically the most basic testing will identify any -// such problems. -// -// Similarly, there are no RAII facilities for automatically closing objects -// and arrays. These would be nice if you are generating all your code within -// nested functions, but in other cases you'd have to maintain an explicit -// stack of RAII objects and manually unwind it, which is no better than just -// calling "end" functions. Furthermore, the consequences of forgetting to -// close an object or array are obvious and, again, will be identified via -// basic testing, unlike other cases where RAII is typically used (e.g. smart -// pointers) and the consequences of defects are more subtle. -// -// Importantly, the class does solve the two hard problems of JSON -// pretty-printing, which are (a) correctly escaping strings, and (b) adding -// appropriate indentation and commas between items. -// -// By default, every property is placed on its own line. However, it is -// possible to request that objects and arrays be placed entirely on a single -// line, which can reduce output size significantly in some cases. -// -// Strings used (for property names and string property values) are |const -// char*| throughout, and can be ASCII or UTF-8. -// -// EXAMPLE -// ------- -// Assume that |MyWriteFunc| is a class that implements |JSONWriteFunc|. The -// following code: -// -// JSONWriter w(MakeUnique()); -// w.Start(); -// { -// w.NullProperty("null"); -// w.BoolProperty("bool", true); -// w.IntProperty("int", 1); -// w.StartArrayProperty("array"); -// { -// w.StringElement("string"); -// w.StartObjectElement(); -// { -// w.DoubleProperty("double", 3.4); -// w.StartArrayProperty("single-line array", w.SingleLineStyle); -// { -// w.IntElement(1); -// w.StartObjectElement(); // SingleLineStyle is inherited from -// w.EndObjectElement(); // above for this collection -// } -// w.EndArray(); -// } -// w.EndObjectElement(); -// } -// w.EndArrayProperty(); -// } -// w.End(); -// -// will produce pretty-printed output for the following JSON object: -// -// { -// "null": null, -// "bool": true, -// "int": 1, -// "array": [ -// "string", -// { -// "double": 3.4, -// "single-line array": [1, {}] -// } -// ] -// } -// -// The nesting in the example code is obviously optional, but can aid -// readability. - -#ifndef mozilla_JSONWriter_h -#define mozilla_JSONWriter_h - -#include "mozilla/double-conversion.h" -#include "mozilla/IntegerPrintfMacros.h" -#include "mozilla/PodOperations.h" -#include "mozilla/Sprintf.h" -#include "mozilla/UniquePtr.h" -#include "mozilla/Vector.h" - -#include - -namespace mozilla { - -// A quasi-functor for JSONWriter. We don't use a true functor because that -// requires templatizing JSONWriter, and the templatization seeps to lots of -// places we don't want it to. -class JSONWriteFunc -{ -public: - virtual void Write(const char* aStr) = 0; - virtual ~JSONWriteFunc() {} -}; - -// Ideally this would be within |EscapedString| but when compiling with GCC -// on Linux that caused link errors, whereas this formulation didn't. -namespace detail { -extern MFBT_DATA const char gTwoCharEscapes[256]; -} // namespace detail - -class JSONWriter -{ - // From http://www.ietf.org/rfc/rfc4627.txt: - // - // "All Unicode characters may be placed within the quotation marks except - // for the characters that must be escaped: quotation mark, reverse - // solidus, and the control characters (U+0000 through U+001F)." - // - // This implementation uses two-char escape sequences where possible, namely: - // - // \", \\, \b, \f, \n, \r, \t - // - // All control characters not in the above list are represented with a - // six-char escape sequence, e.g. '\u000b' (a.k.a. '\v'). - // - class EscapedString - { - // Only one of |mUnownedStr| and |mOwnedStr| are ever non-null. |mIsOwned| - // indicates which one is in use. They're not within a union because that - // wouldn't work with UniquePtr. - bool mIsOwned; - const char* mUnownedStr; - UniquePtr mOwnedStr; - - void SanityCheck() const - { - MOZ_ASSERT_IF( mIsOwned, mOwnedStr.get() && !mUnownedStr); - MOZ_ASSERT_IF(!mIsOwned, !mOwnedStr.get() && mUnownedStr); - } - - static char hexDigitToAsciiChar(uint8_t u) - { - u = u & 0xf; - return u < 10 ? '0' + u : 'a' + (u - 10); - } - - public: - explicit EscapedString(const char* aStr) - : mUnownedStr(nullptr) - , mOwnedStr(nullptr) - { - const char* p; - - // First, see if we need to modify the string. - size_t nExtra = 0; - p = aStr; - while (true) { - uint8_t u = *p; // ensure it can't be interpreted as negative - if (u == 0) { - break; - } - if (detail::gTwoCharEscapes[u]) { - nExtra += 1; - } else if (u <= 0x1f) { - nExtra += 5; - } - p++; - } - - if (nExtra == 0) { - // No escapes needed. Easy. - mIsOwned = false; - mUnownedStr = aStr; - return; - } - - // Escapes are needed. We'll create a new string. - mIsOwned = true; - size_t len = (p - aStr) + nExtra; - mOwnedStr = MakeUnique(len + 1); - - p = aStr; - size_t i = 0; - - while (true) { - uint8_t u = *p; // ensure it can't be interpreted as negative - if (u == 0) { - mOwnedStr[i] = 0; - break; - } - if (detail::gTwoCharEscapes[u]) { - mOwnedStr[i++] = '\\'; - mOwnedStr[i++] = detail::gTwoCharEscapes[u]; - } else if (u <= 0x1f) { - mOwnedStr[i++] = '\\'; - mOwnedStr[i++] = 'u'; - mOwnedStr[i++] = '0'; - mOwnedStr[i++] = '0'; - mOwnedStr[i++] = hexDigitToAsciiChar((u & 0x00f0) >> 4); - mOwnedStr[i++] = hexDigitToAsciiChar(u & 0x000f); - } else { - mOwnedStr[i++] = u; - } - p++; - } - } - - ~EscapedString() - { - SanityCheck(); - } - - const char* get() const - { - SanityCheck(); - return mIsOwned ? mOwnedStr.get() : mUnownedStr; - } - }; - -public: - // Collections (objects and arrays) are printed in a multi-line style by - // default. This can be changed to a single-line style if SingleLineStyle is - // specified. If a collection is printed in single-line style, every nested - // collection within it is also printed in single-line style, even if - // multi-line style is requested. - enum CollectionStyle { - MultiLineStyle, // the default - SingleLineStyle - }; - -protected: - const UniquePtr mWriter; - Vector mNeedComma; // do we need a comma at depth N? - Vector mNeedNewlines; // do we need newlines at depth N? - size_t mDepth; // the current nesting depth - - void Indent() - { - for (size_t i = 0; i < mDepth; i++) { - mWriter->Write(" "); - } - } - - // Adds whatever is necessary (maybe a comma, and then a newline and - // whitespace) to separate an item (property or element) from what's come - // before. - void Separator() - { - if (mNeedComma[mDepth]) { - mWriter->Write(","); - } - if (mDepth > 0 && mNeedNewlines[mDepth]) { - mWriter->Write("\n"); - Indent(); - } else if (mNeedComma[mDepth]) { - mWriter->Write(" "); - } - } - - void PropertyNameAndColon(const char* aName) - { - EscapedString escapedName(aName); - mWriter->Write("\""); - mWriter->Write(escapedName.get()); - mWriter->Write("\": "); - } - - void Scalar(const char* aMaybePropertyName, const char* aStringValue) - { - Separator(); - if (aMaybePropertyName) { - PropertyNameAndColon(aMaybePropertyName); - } - mWriter->Write(aStringValue); - mNeedComma[mDepth] = true; - } - - void QuotedScalar(const char* aMaybePropertyName, const char* aStringValue) - { - Separator(); - if (aMaybePropertyName) { - PropertyNameAndColon(aMaybePropertyName); - } - mWriter->Write("\""); - mWriter->Write(aStringValue); - mWriter->Write("\""); - mNeedComma[mDepth] = true; - } - - void NewVectorEntries() - { - // If these tiny allocations OOM we might as well just crash because we - // must be in serious memory trouble. - MOZ_RELEASE_ASSERT(mNeedComma.resizeUninitialized(mDepth + 1)); - MOZ_RELEASE_ASSERT(mNeedNewlines.resizeUninitialized(mDepth + 1)); - mNeedComma[mDepth] = false; - mNeedNewlines[mDepth] = true; - } - - void StartCollection(const char* aMaybePropertyName, const char* aStartChar, - CollectionStyle aStyle = MultiLineStyle) - { - Separator(); - if (aMaybePropertyName) { - mWriter->Write("\""); - mWriter->Write(aMaybePropertyName); - mWriter->Write("\": "); - } - mWriter->Write(aStartChar); - mNeedComma[mDepth] = true; - mDepth++; - NewVectorEntries(); - mNeedNewlines[mDepth] = - mNeedNewlines[mDepth - 1] && aStyle == MultiLineStyle; - } - - // Adds the whitespace and closing char necessary to end a collection. - void EndCollection(const char* aEndChar) - { - if (mNeedNewlines[mDepth]) { - mWriter->Write("\n"); - mDepth--; - Indent(); - } else { - mDepth--; - } - mWriter->Write(aEndChar); - } - -public: - explicit JSONWriter(UniquePtr aWriter) - : mWriter(Move(aWriter)) - , mNeedComma() - , mNeedNewlines() - , mDepth(0) - { - NewVectorEntries(); - } - - // Returns the JSONWriteFunc passed in at creation, for temporary use. The - // JSONWriter object still owns the JSONWriteFunc. - JSONWriteFunc* WriteFunc() const { return mWriter.get(); } - - // For all the following functions, the "Prints:" comment indicates what the - // basic output looks like. However, it doesn't indicate the whitespace and - // trailing commas, which are automatically added as required. - // - // All property names and string properties are escaped as necessary. - - // Prints: { - void Start(CollectionStyle aStyle = MultiLineStyle) - { - StartCollection(nullptr, "{", aStyle); - } - - // Prints: } - void End() { EndCollection("}\n"); } - - // Prints: "": null - void NullProperty(const char* aName) - { - Scalar(aName, "null"); - } - - // Prints: null - void NullElement() { NullProperty(nullptr); } - - // Prints: "": - void BoolProperty(const char* aName, bool aBool) - { - Scalar(aName, aBool ? "true" : "false"); - } - - // Prints: - void BoolElement(bool aBool) { BoolProperty(nullptr, aBool); } - - // Prints: "": - void IntProperty(const char* aName, int64_t aInt) - { - char buf[64]; - SprintfLiteral(buf, "%" PRId64, aInt); - Scalar(aName, buf); - } - - // Prints: - void IntElement(int64_t aInt) { IntProperty(nullptr, aInt); } - - // Prints: "": - void DoubleProperty(const char* aName, double aDouble) - { - static const size_t buflen = 64; - char buf[buflen]; - const double_conversion::DoubleToStringConverter &converter = - double_conversion::DoubleToStringConverter::EcmaScriptConverter(); - double_conversion::StringBuilder builder(buf, buflen); - converter.ToShortest(aDouble, &builder); - Scalar(aName, builder.Finalize()); - } - - // Prints: - void DoubleElement(double aDouble) { DoubleProperty(nullptr, aDouble); } - - // Prints: "": "" - void StringProperty(const char* aName, const char* aStr) - { - EscapedString escapedStr(aStr); - QuotedScalar(aName, escapedStr.get()); - } - - // Prints: "" - void StringElement(const char* aStr) { StringProperty(nullptr, aStr); } - - // Prints: "": [ - void StartArrayProperty(const char* aName, - CollectionStyle aStyle = MultiLineStyle) - { - StartCollection(aName, "[", aStyle); - } - - // Prints: [ - void StartArrayElement(CollectionStyle aStyle = MultiLineStyle) - { - StartArrayProperty(nullptr, aStyle); - } - - // Prints: ] - void EndArray() { EndCollection("]"); } - - // Prints: "": { - void StartObjectProperty(const char* aName, - CollectionStyle aStyle = MultiLineStyle) - { - StartCollection(aName, "{", aStyle); - } - - // Prints: { - void StartObjectElement(CollectionStyle aStyle = MultiLineStyle) - { - StartObjectProperty(nullptr, aStyle); - } - - // Prints: } - void EndObject() { EndCollection("}"); } -}; - -} // namespace mozilla - -#endif /* mozilla_JSONWriter_h */ - diff --git a/ios/include/spidermonkey/mozilla/Likely.h b/ios/include/spidermonkey/mozilla/Likely.h deleted file mode 100644 index 4f216092..00000000 --- a/ios/include/spidermonkey/mozilla/Likely.h +++ /dev/null @@ -1,23 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * MOZ_LIKELY and MOZ_UNLIKELY macros to hint to the compiler how a - * boolean predicate should be branch-predicted. - */ - -#ifndef mozilla_Likely_h -#define mozilla_Likely_h - -#if defined(__clang__) || defined(__GNUC__) -# define MOZ_LIKELY(x) (__builtin_expect(!!(x), 1)) -# define MOZ_UNLIKELY(x) (__builtin_expect(!!(x), 0)) -#else -# define MOZ_LIKELY(x) (!!(x)) -# define MOZ_UNLIKELY(x) (!!(x)) -#endif - -#endif /* mozilla_Likely_h */ diff --git a/ios/include/spidermonkey/mozilla/LinkedList.h b/ios/include/spidermonkey/mozilla/LinkedList.h deleted file mode 100644 index 6e14aa16..00000000 --- a/ios/include/spidermonkey/mozilla/LinkedList.h +++ /dev/null @@ -1,659 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A type-safe doubly-linked list class. */ - -/* - * The classes LinkedList and LinkedListElement together form a - * convenient, type-safe doubly-linked list implementation. - * - * The class T which will be inserted into the linked list must inherit from - * LinkedListElement. A given object may be in only one linked list at a - * time. - * - * A LinkedListElement automatically removes itself from the list upon - * destruction, and a LinkedList will fatally assert in debug builds if it's - * non-empty when it's destructed. - * - * For example, you might use LinkedList in a simple observer list class as - * follows. - * - * class Observer : public LinkedListElement - * { - * public: - * void observe(char* aTopic) { ... } - * }; - * - * class ObserverContainer - * { - * private: - * LinkedList list; - * - * public: - * void addObserver(Observer* aObserver) - * { - * // Will assert if |aObserver| is part of another list. - * list.insertBack(aObserver); - * } - * - * void removeObserver(Observer* aObserver) - * { - * // Will assert if |aObserver| is not part of some list. - * aObserver.remove(); - * // Or, will assert if |aObserver| is not part of |list| specifically. - * // aObserver.removeFrom(list); - * } - * - * void notifyObservers(char* aTopic) - * { - * for (Observer* o = list.getFirst(); o != nullptr; o = o->getNext()) { - * o->observe(aTopic); - * } - * } - * }; - * - * Additionally, the class AutoCleanLinkedList is a LinkedList that will - * remove and delete each element still within itself upon destruction. Note - * that because each element is deleted, elements must have been allocated - * using |new|. - */ - -#ifndef mozilla_LinkedList_h -#define mozilla_LinkedList_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/RefPtr.h" - -#ifdef __cplusplus - -namespace mozilla { - -template -class LinkedListElement; - -namespace detail { - -/** - * LinkedList supports refcounted elements using this adapter class. Clients - * using LinkedList> will get a data structure that holds a strong - * reference to T as long as T is in the list. - */ -template -struct LinkedListElementTraits -{ - typedef T* RawType; - typedef const T* ConstRawType; - typedef T* ClientType; - typedef const T* ConstClientType; - - // These static methods are called when an element is added to or removed from - // a linked list. It can be used to keep track ownership in lists that are - // supposed to own their elements. If elements are transferred from one list - // to another, no enter or exit calls happen since the elements still belong - // to a list. - static void enterList(LinkedListElement* elt) {} - static void exitList(LinkedListElement* elt) {} -}; - -template -struct LinkedListElementTraits> -{ - typedef T* RawType; - typedef const T* ConstRawType; - typedef RefPtr ClientType; - typedef RefPtr ConstClientType; - - static void enterList(LinkedListElement>* elt) { elt->asT()->AddRef(); } - static void exitList(LinkedListElement>* elt) { elt->asT()->Release(); } -}; - -} /* namespace detail */ - -template -class LinkedList; - -template -class LinkedListElement -{ - typedef typename detail::LinkedListElementTraits Traits; - typedef typename Traits::RawType RawType; - typedef typename Traits::ConstRawType ConstRawType; - typedef typename Traits::ClientType ClientType; - typedef typename Traits::ConstClientType ConstClientType; - - /* - * It's convenient that we return nullptr when getNext() or getPrevious() - * hits the end of the list, but doing so costs an extra word of storage in - * each linked list node (to keep track of whether |this| is the sentinel - * node) and a branch on this value in getNext/getPrevious. - * - * We could get rid of the extra word of storage by shoving the "is - * sentinel" bit into one of the pointers, although this would, of course, - * have performance implications of its own. - * - * But the goal here isn't to win an award for the fastest or slimmest - * linked list; rather, we want a *convenient* linked list. So we won't - * waste time guessing which micro-optimization strategy is best. - * - * - * Speaking of unnecessary work, it's worth addressing here why we wrote - * mozilla::LinkedList in the first place, instead of using stl::list. - * - * The key difference between mozilla::LinkedList and stl::list is that - * mozilla::LinkedList stores the mPrev/mNext pointers in the object itself, - * while stl::list stores the mPrev/mNext pointers in a list element which - * itself points to the object being stored. - * - * mozilla::LinkedList's approach makes it harder to store an object in more - * than one list. But the upside is that you can call next() / prev() / - * remove() directly on the object. With stl::list, you'd need to store a - * pointer to its iterator in the object in order to accomplish this. Not - * only would this waste space, but you'd have to remember to update that - * pointer every time you added or removed the object from a list. - * - * In-place, constant-time removal is a killer feature of doubly-linked - * lists, and supporting this painlessly was a key design criterion. - */ - -private: - LinkedListElement* mNext; - LinkedListElement* mPrev; - const bool mIsSentinel; - -public: - LinkedListElement() - : mNext(this), - mPrev(this), - mIsSentinel(false) - { } - - /* - * Moves |aOther| into |*this|. If |aOther| is already in a list, then - * |aOther| is removed from the list and replaced by |*this|. - */ - LinkedListElement(LinkedListElement&& aOther) - : mIsSentinel(aOther.mIsSentinel) - { - adjustLinkForMove(Move(aOther)); - } - - LinkedListElement& operator=(LinkedListElement&& aOther) - { - MOZ_ASSERT(mIsSentinel == aOther.mIsSentinel, "Mismatch NodeKind!"); - MOZ_ASSERT(!isInList(), - "Assigning to an element in a list messes up that list!"); - adjustLinkForMove(Move(aOther)); - return *this; - } - - ~LinkedListElement() - { - if (!mIsSentinel && isInList()) { - remove(); - } - } - - /* - * Get the next element in the list, or nullptr if this is the last element - * in the list. - */ - RawType getNext() { return mNext->asT(); } - ConstRawType getNext() const { return mNext->asT(); } - - /* - * Get the previous element in the list, or nullptr if this is the first - * element in the list. - */ - RawType getPrevious() { return mPrev->asT(); } - ConstRawType getPrevious() const { return mPrev->asT(); } - - /* - * Insert aElem after this element in the list. |this| must be part of a - * linked list when you call setNext(); otherwise, this method will assert. - */ - void setNext(RawType aElem) - { - MOZ_ASSERT(isInList()); - setNextUnsafe(aElem); - } - - /* - * Insert aElem before this element in the list. |this| must be part of a - * linked list when you call setPrevious(); otherwise, this method will - * assert. - */ - void setPrevious(RawType aElem) - { - MOZ_ASSERT(isInList()); - setPreviousUnsafe(aElem); - } - - /* - * Remove this element from the list which contains it. If this element is - * not currently part of a linked list, this method asserts. - */ - void remove() - { - MOZ_ASSERT(isInList()); - - mPrev->mNext = mNext; - mNext->mPrev = mPrev; - mNext = this; - mPrev = this; - - Traits::exitList(this); - } - - /* - * Remove this element from the list containing it. Returns a pointer to the - * element that follows this element (before it was removed). This method - * asserts if the element does not belong to a list. - */ - ClientType removeAndGetNext() - { - ClientType r = getNext(); - remove(); - return r; - } - - /* - * Remove this element from the list containing it. Returns a pointer to the - * previous element in the containing list (before the removal). This method - * asserts if the element does not belong to a list. - */ - ClientType removeAndGetPrevious() - { - ClientType r = getPrevious(); - remove(); - return r; - } - - /* - * Identical to remove(), but also asserts in debug builds that this element - * is in aList. - */ - void removeFrom(const LinkedList& aList) - { - aList.assertContains(asT()); - remove(); - } - - /* - * Return true if |this| part is of a linked list, and false otherwise. - */ - bool isInList() const - { - MOZ_ASSERT((mNext == this) == (mPrev == this)); - return mNext != this; - } - -private: - friend class LinkedList; - friend struct detail::LinkedListElementTraits; - - enum class NodeKind { - Normal, - Sentinel - }; - - explicit LinkedListElement(NodeKind nodeKind) - : mNext(this), - mPrev(this), - mIsSentinel(nodeKind == NodeKind::Sentinel) - { } - - /* - * Return |this| cast to T* if we're a normal node, or return nullptr if - * we're a sentinel node. - */ - RawType asT() - { - return mIsSentinel ? nullptr : static_cast(this); - } - ConstRawType asT() const - { - return mIsSentinel ? nullptr : static_cast(this); - } - - /* - * Insert aElem after this element, but don't check that this element is in - * the list. This is called by LinkedList::insertFront(). - */ - void setNextUnsafe(RawType aElem) - { - LinkedListElement *listElem = static_cast(aElem); - MOZ_ASSERT(!listElem->isInList()); - - listElem->mNext = this->mNext; - listElem->mPrev = this; - this->mNext->mPrev = listElem; - this->mNext = listElem; - - Traits::enterList(aElem); - } - - /* - * Insert aElem before this element, but don't check that this element is in - * the list. This is called by LinkedList::insertBack(). - */ - void setPreviousUnsafe(RawType aElem) - { - LinkedListElement* listElem = static_cast*>(aElem); - MOZ_ASSERT(!listElem->isInList()); - - listElem->mNext = this; - listElem->mPrev = this->mPrev; - this->mPrev->mNext = listElem; - this->mPrev = listElem; - - Traits::enterList(aElem); - } - - /* - * Adjust mNext and mPrev for implementing move constructor and move - * assignment. - */ - void adjustLinkForMove(LinkedListElement&& aOther) - { - if (!aOther.isInList()) { - mNext = this; - mPrev = this; - return; - } - - if (!mIsSentinel) { - Traits::enterList(this); - } - - MOZ_ASSERT(aOther.mNext->mPrev == &aOther); - MOZ_ASSERT(aOther.mPrev->mNext == &aOther); - - /* - * Initialize |this| with |aOther|'s mPrev/mNext pointers, and adjust those - * element to point to this one. - */ - mNext = aOther.mNext; - mPrev = aOther.mPrev; - - mNext->mPrev = this; - mPrev->mNext = this; - - /* - * Adjust |aOther| so it doesn't think it's in a list. This makes it - * safely destructable. - */ - aOther.mNext = &aOther; - aOther.mPrev = &aOther; - - if (!mIsSentinel) { - Traits::exitList(&aOther); - } - } - - LinkedListElement& operator=(const LinkedListElement& aOther) = delete; - LinkedListElement(const LinkedListElement& aOther) = delete; -}; - -template -class LinkedList -{ -private: - typedef typename detail::LinkedListElementTraits Traits; - typedef typename Traits::RawType RawType; - typedef typename Traits::ConstRawType ConstRawType; - typedef typename Traits::ClientType ClientType; - typedef typename Traits::ConstClientType ConstClientType; - - LinkedListElement sentinel; - -public: - class Iterator { - RawType mCurrent; - - public: - explicit Iterator(RawType aCurrent) : mCurrent(aCurrent) {} - - RawType operator *() const { - return mCurrent; - } - - const Iterator& operator++() { - mCurrent = mCurrent->getNext(); - return *this; - } - - bool operator!=(Iterator& aOther) const { - return mCurrent != aOther.mCurrent; - } - }; - - LinkedList() : sentinel(LinkedListElement::NodeKind::Sentinel) { } - - LinkedList(LinkedList&& aOther) - : sentinel(mozilla::Move(aOther.sentinel)) - { } - - LinkedList& operator=(LinkedList&& aOther) - { - MOZ_ASSERT(isEmpty(), "Assigning to a non-empty list leaks elements in that list!"); - sentinel = mozilla::Move(aOther.sentinel); - return *this; - } - - ~LinkedList() { - MOZ_ASSERT(isEmpty(), - "failing this assertion means this LinkedList's creator is " - "buggy: it should have removed all this list's elements before " - "the list's destruction"); - } - - /* - * Add aElem to the front of the list. - */ - void insertFront(RawType aElem) - { - /* Bypass setNext()'s this->isInList() assertion. */ - sentinel.setNextUnsafe(aElem); - } - - /* - * Add aElem to the back of the list. - */ - void insertBack(RawType aElem) - { - sentinel.setPreviousUnsafe(aElem); - } - - /* - * Get the first element of the list, or nullptr if the list is empty. - */ - RawType getFirst() { return sentinel.getNext(); } - ConstRawType getFirst() const { return sentinel.getNext(); } - - /* - * Get the last element of the list, or nullptr if the list is empty. - */ - RawType getLast() { return sentinel.getPrevious(); } - ConstRawType getLast() const { return sentinel.getPrevious(); } - - /* - * Get and remove the first element of the list. If the list is empty, - * return nullptr. - */ - ClientType popFirst() - { - ClientType ret = sentinel.getNext(); - if (ret) { - static_cast*>(RawType(ret))->remove(); - } - return ret; - } - - /* - * Get and remove the last element of the list. If the list is empty, - * return nullptr. - */ - ClientType popLast() - { - ClientType ret = sentinel.getPrevious(); - if (ret) { - static_cast*>(RawType(ret))->remove(); - } - return ret; - } - - /* - * Return true if the list is empty, or false otherwise. - */ - bool isEmpty() const - { - return !sentinel.isInList(); - } - - /* - * Remove all the elements from the list. - * - * This runs in time linear to the list's length, because we have to mark - * each element as not in the list. - */ - void clear() - { - while (popFirst()) { - continue; - } - } - - /* - * Allow range-based iteration: - * - * for (MyElementType* elt : myList) { ... } - */ - Iterator begin() { - return Iterator(getFirst()); - } - Iterator end() { - return Iterator(nullptr); - } - - /* - * Measures the memory consumption of the list excluding |this|. Note that - * it only measures the list elements themselves. If the list elements - * contain pointers to other memory blocks, those blocks must be measured - * separately during a subsequent iteration over the list. - */ - size_t sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const - { - size_t n = 0; - for (const T* t = getFirst(); t; t = t->getNext()) { - n += aMallocSizeOf(t); - } - return n; - } - - /* - * Like sizeOfExcludingThis(), but measures |this| as well. - */ - size_t sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const - { - return aMallocSizeOf(this) + sizeOfExcludingThis(aMallocSizeOf); - } - - /* - * In a debug build, make sure that the list is sane (no cycles, consistent - * mNext/mPrev pointers, only one sentinel). Has no effect in release builds. - */ - void debugAssertIsSane() const - { -#ifdef DEBUG - const LinkedListElement* slow; - const LinkedListElement* fast1; - const LinkedListElement* fast2; - - /* - * Check for cycles in the forward singly-linked list using the - * tortoise/hare algorithm. - */ - for (slow = sentinel.mNext, - fast1 = sentinel.mNext->mNext, - fast2 = sentinel.mNext->mNext->mNext; - slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; - slow = slow->mNext, fast1 = fast2->mNext, fast2 = fast1->mNext) { - MOZ_ASSERT(slow != fast1); - MOZ_ASSERT(slow != fast2); - } - - /* Check for cycles in the backward singly-linked list. */ - for (slow = sentinel.mPrev, - fast1 = sentinel.mPrev->mPrev, - fast2 = sentinel.mPrev->mPrev->mPrev; - slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; - slow = slow->mPrev, fast1 = fast2->mPrev, fast2 = fast1->mPrev) { - MOZ_ASSERT(slow != fast1); - MOZ_ASSERT(slow != fast2); - } - - /* - * Check that |sentinel| is the only node in the list with - * mIsSentinel == true. - */ - for (const LinkedListElement* elem = sentinel.mNext; - elem != &sentinel; - elem = elem->mNext) { - MOZ_ASSERT(!elem->mIsSentinel); - } - - /* Check that the mNext/mPrev pointers match up. */ - const LinkedListElement* prev = &sentinel; - const LinkedListElement* cur = sentinel.mNext; - do { - MOZ_ASSERT(cur->mPrev == prev); - MOZ_ASSERT(prev->mNext == cur); - - prev = cur; - cur = cur->mNext; - } while (cur != &sentinel); -#endif /* ifdef DEBUG */ - } - -private: - friend class LinkedListElement; - - void assertContains(const RawType aValue) const - { -#ifdef DEBUG - for (ConstRawType elem = getFirst(); elem; elem = elem->getNext()) { - if (elem == aValue) { - return; - } - } - MOZ_CRASH("element wasn't found in this list!"); -#endif - } - - LinkedList& operator=(const LinkedList& aOther) = delete; - LinkedList(const LinkedList& aOther) = delete; -}; - -template -class AutoCleanLinkedList : public LinkedList -{ -public: - ~AutoCleanLinkedList() - { - while (T* element = this->popFirst()) { - delete element; - } - } -}; - -} /* namespace mozilla */ - -#endif /* __cplusplus */ - -#endif /* mozilla_LinkedList_h */ diff --git a/ios/include/spidermonkey/mozilla/MacroArgs.h b/ios/include/spidermonkey/mozilla/MacroArgs.h deleted file mode 100644 index 52ed1e82..00000000 --- a/ios/include/spidermonkey/mozilla/MacroArgs.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements various macros meant to ease the use of variadic macros. - */ - -#ifndef mozilla_MacroArgs_h -#define mozilla_MacroArgs_h - -// Concatenates pre-processor tokens in a way that can be used with __LINE__. -#define MOZ_CONCAT2(x, y) x ## y -#define MOZ_CONCAT(x, y) MOZ_CONCAT2(x, y) - -/* - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(aPrefix, ...) counts the number of variadic - * arguments and prefixes it with |aPrefix|. For example: - * - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(, foo, 42) expands to 2 - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(A, foo, 42, bar) expands to A3 - * - * You must pass in between 1 and 50 (inclusive) variadic arguments, past - * |aPrefix|. It is not legal to do - * - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(prefix) - * - * (that is, pass in 0 variadic arguments). To ensure that a compile-time - * error occurs when these constraints are violated, use the - * MOZ_STATIC_ASSERT_VALID_ARG_COUNT macro with the same variaidc arguments - * wherever this macro is used. - * - * Passing (__VA_ARGS__, ) rather than simply calling - * MOZ_MACROARGS_ARG_COUNT_HELPER2(__VA_ARGS__, ) very - * carefully tiptoes around a MSVC bug where it improperly expands __VA_ARGS__ - * as a single token in argument lists. For details, see: - * - * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement - * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644 - */ -#define MOZ_PASTE_PREFIX_AND_ARG_COUNT(aPrefix, ...) \ - MOZ_MACROARGS_ARG_COUNT_HELPER((__VA_ARGS__, \ - aPrefix##50, aPrefix##49, aPrefix##48, aPrefix##47, aPrefix##46, \ - aPrefix##45, aPrefix##44, aPrefix##43, aPrefix##42, aPrefix##41, \ - aPrefix##40, aPrefix##39, aPrefix##38, aPrefix##37, aPrefix##36, \ - aPrefix##35, aPrefix##34, aPrefix##33, aPrefix##32, aPrefix##31, \ - aPrefix##30, aPrefix##29, aPrefix##28, aPrefix##27, aPrefix##26, \ - aPrefix##25, aPrefix##24, aPrefix##23, aPrefix##22, aPrefix##21, \ - aPrefix##20, aPrefix##19, aPrefix##18, aPrefix##17, aPrefix##16, \ - aPrefix##15, aPrefix##14, aPrefix##13, aPrefix##12, aPrefix##11, \ - aPrefix##10, aPrefix##9, aPrefix##8, aPrefix##7, aPrefix##6, \ - aPrefix##5, aPrefix##4, aPrefix##3, aPrefix##2, aPrefix##1, aPrefix##0)) - -#define MOZ_MACROARGS_ARG_COUNT_HELPER(aArgs) \ - MOZ_MACROARGS_ARG_COUNT_HELPER2 aArgs - -#define MOZ_MACROARGS_ARG_COUNT_HELPER2( \ - a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, \ - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, \ - a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, \ - a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, \ - a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, \ - a51, ...) a51 - -/* - * MOZ_STATIC_ASSERT_VALID_ARG_COUNT ensures that a compile-time error occurs - * when the argument count constraints of MOZ_PASTE_PREFIX_AND_ARG_COUNT are - * violated. Use this macro wherever MOZ_PASTE_PREFIX_AND_ARG_COUNT is used - * and pass it the same variadic arguments. - * - * This macro employs a few dirty tricks to function. To detect the zero - * argument case, |(__VA_ARGS__)| is stringified, sizeof-ed, and compared to - * what it should be in the absence of arguments. - * - * Detecting too many arguments is a little trickier. With a valid argument - * count and a prefix of 1, MOZ_PASTE_PREFIX_AND_ARG_COUNT expands to e.g. 14. - * With a prefix of 0.0, it expands to e.g. 0.04. If there are too many - * arguments, it expands to the first argument over the limit. If this - * exceeding argument is a number, the assertion will fail as there is no - * number than can simultaneously be both > 10 and == 0. If the exceeding - * argument is not a number, a compile-time error should still occur due to - * the operations performed on it. - */ -#define MOZ_MACROARGS_STRINGIFY_HELPER(x) #x -#define MOZ_STATIC_ASSERT_VALID_ARG_COUNT(...) \ - static_assert( \ - sizeof(MOZ_MACROARGS_STRINGIFY_HELPER((__VA_ARGS__))) != sizeof("()") && \ - (MOZ_PASTE_PREFIX_AND_ARG_COUNT(1, __VA_ARGS__)) > 10 && \ - (int)(MOZ_PASTE_PREFIX_AND_ARG_COUNT(0.0, __VA_ARGS__)) == 0, \ - "MOZ_STATIC_ASSERT_VALID_ARG_COUNT requires 1 to 50 arguments") /* ; */ - -/* - * MOZ_ARGS_AFTER_N expands to its arguments excluding the first |N| - * arguments. For example: - * - * MOZ_ARGS_AFTER_2(a, b, c, d) expands to: c, d - */ -#define MOZ_ARGS_AFTER_1(a1, ...) __VA_ARGS__ -#define MOZ_ARGS_AFTER_2(a1, a2, ...) __VA_ARGS__ - -/* - * MOZ_ARG_N expands to its |N|th argument. - */ -#define MOZ_ARG_1(a1, ...) a1 -#define MOZ_ARG_2(a1, a2, ...) a2 - -#endif /* mozilla_MacroArgs_h */ diff --git a/ios/include/spidermonkey/mozilla/MacroForEach.h b/ios/include/spidermonkey/mozilla/MacroForEach.h deleted file mode 100644 index 7c0e3cfb..00000000 --- a/ios/include/spidermonkey/mozilla/MacroForEach.h +++ /dev/null @@ -1,158 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements a higher-order macro for iteratively calling another macro with - * fixed leading arguments, plus a trailing element picked from a second list - * of arguments. - */ - -#ifndef mozilla_MacroForEach_h -#define mozilla_MacroForEach_h - -#include "mozilla/MacroArgs.h" - -/* - * MOZ_FOR_EACH(aMacro, aFixedArgs, aArgs) expands to N calls to the macro - * |aMacro| where N is equal the number of items in the list |aArgs|. The - * arguments for each |aMacro| call are composed of *all* arguments in the list - * |aFixedArgs| as well as a single argument in the list |aArgs|. For example: - * - * #define MACRO_A(x) x + - * int a = MOZ_FOR_EACH(MACRO_A, (), (1, 2, 3)) 0; - * // Expands to: MACRO_A(1) MACRO_A(2) MACRO_A(3) 0; - * // And further to: 1 + 2 + 3 + 0; - * - * #define MACRO_B(k, x) (k + x) + - * int b = MOZ_FOR_EACH(MACRO_B, (5,), (1, 2)) 0; - * // Expands to: MACRO_B(5, 1) MACRO_B(5, 2) 0; - * - * #define MACRO_C(k1, k2, x) (k1 + k2 + x) + - * int c = MOZ_FOR_EACH(MACRO_C, (5, 8,), (1, 2)) 0; - * // Expands to: MACRO_B(5, 8, 1) MACRO_B(5, 8, 2) 0; - * - * If the |aFixedArgs| list is not empty, a trailing comma must be included. - * - * The |aArgs| list must be not be empty and may be up to 50 items long. Use - * MOZ_STATIC_ASSERT_VALID_ARG_COUNT to ensure that violating this constraint - * results in a compile-time error. - */ -#define MOZ_FOR_EACH_EXPAND_HELPER(...) __VA_ARGS__ -#define MOZ_FOR_EACH_GLUE(a, b) a b -#define MOZ_FOR_EACH(aMacro, aFixedArgs, aArgs) \ - MOZ_FOR_EACH_GLUE( \ - MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_FOR_EACH_, \ - MOZ_FOR_EACH_EXPAND_HELPER aArgs), \ - (aMacro, aFixedArgs, aArgs)) - -#define MOZ_FOR_EACH_HELPER_GLUE(a, b) a b -#define MOZ_FOR_EACH_HELPER(aMacro, aFixedArgs, aArgs) \ - MOZ_FOR_EACH_HELPER_GLUE( \ - aMacro, \ - (MOZ_FOR_EACH_EXPAND_HELPER aFixedArgs MOZ_ARG_1 aArgs)) - -#define MOZ_FOR_EACH_1(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) -#define MOZ_FOR_EACH_2(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_1(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_3(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_2(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_4(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_3(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_5(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_4(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_6(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_5(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_7(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_6(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_8(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_7(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_9(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_8(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_10(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_9(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_11(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_10(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_12(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_11(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_13(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_12(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_14(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_13(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_15(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_14(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_16(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_15(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_17(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_16(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_18(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_17(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_19(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_18(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_20(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_19(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_21(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_20(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_22(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_21(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_23(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_22(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_24(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_23(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_25(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_24(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_26(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_25(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_27(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_26(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_28(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_27(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_29(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_28(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_30(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_29(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_31(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_30(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_32(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_31(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_33(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_32(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_34(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_33(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_35(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_34(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_36(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_35(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_37(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_36(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_38(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_37(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_39(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_38(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_40(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_39(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_41(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_40(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_42(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_41(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_43(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_42(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_44(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_43(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_45(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_44(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_46(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_45(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_47(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_46(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_48(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_47(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_49(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_48(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_50(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_49(m, fa, (MOZ_ARGS_AFTER_1 a)) - -#endif /* mozilla_MacroForEach_h */ diff --git a/ios/include/spidermonkey/mozilla/MathAlgorithms.h b/ios/include/spidermonkey/mozilla/MathAlgorithms.h deleted file mode 100644 index 4db6de49..00000000 --- a/ios/include/spidermonkey/mozilla/MathAlgorithms.h +++ /dev/null @@ -1,547 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* mfbt maths algorithms. */ - -#ifndef mozilla_MathAlgorithms_h -#define mozilla_MathAlgorithms_h - -#include "mozilla/Assertions.h" -#include "mozilla/TypeTraits.h" - -#include -#include -#include - -namespace mozilla { - -// Greatest Common Divisor -template -MOZ_ALWAYS_INLINE IntegerType -EuclidGCD(IntegerType aA, IntegerType aB) -{ - // Euclid's algorithm; O(N) in the worst case. (There are better - // ways, but we don't need them for the current use of this algo.) - MOZ_ASSERT(aA > IntegerType(0)); - MOZ_ASSERT(aB > IntegerType(0)); - - while (aA != aB) { - if (aA > aB) { - aA = aA - aB; - } else { - aB = aB - aA; - } - } - - return aA; -} - -// Least Common Multiple -template -MOZ_ALWAYS_INLINE IntegerType -EuclidLCM(IntegerType aA, IntegerType aB) -{ - // Divide first to reduce overflow risk. - return (aA / EuclidGCD(aA, aB)) * aB; -} - -namespace detail { - -template -struct AllowDeprecatedAbsFixed : FalseType {}; - -template<> struct AllowDeprecatedAbsFixed : TrueType {}; -template<> struct AllowDeprecatedAbsFixed : TrueType {}; - -template -struct AllowDeprecatedAbs : AllowDeprecatedAbsFixed {}; - -template<> struct AllowDeprecatedAbs : TrueType {}; -template<> struct AllowDeprecatedAbs : TrueType {}; - -} // namespace detail - -// DO NOT USE DeprecatedAbs. It exists only until its callers can be converted -// to Abs below, and it will be removed when all callers have been changed. -template -inline typename mozilla::EnableIf::value, T>::Type -DeprecatedAbs(const T aValue) -{ - // The absolute value of the smallest possible value of a signed-integer type - // won't fit in that type (on twos-complement systems -- and we're blithely - // assuming we're on such systems, for the non- types listed above), - // so assert that the input isn't that value. - // - // This is the case if: the value is non-negative; or if adding one (giving a - // value in the range [-maxvalue, 0]), then negating (giving a value in the - // range [0, maxvalue]), doesn't produce maxvalue (because in twos-complement, - // (minvalue + 1) == -maxvalue). - MOZ_ASSERT(aValue >= 0 || - -(aValue + 1) != T((1ULL << (CHAR_BIT * sizeof(T) - 1)) - 1), - "You can't negate the smallest possible negative integer!"); - return aValue >= 0 ? aValue : -aValue; -} - -namespace detail { - -// For now mozilla::Abs only takes intN_T, the signed natural types, and -// float/double/long double. Feel free to add overloads for other standard, -// signed types if you need them. - -template -struct AbsReturnTypeFixed; - -template<> struct AbsReturnTypeFixed { typedef uint8_t Type; }; -template<> struct AbsReturnTypeFixed { typedef uint16_t Type; }; -template<> struct AbsReturnTypeFixed { typedef uint32_t Type; }; -template<> struct AbsReturnTypeFixed { typedef uint64_t Type; }; - -template -struct AbsReturnType : AbsReturnTypeFixed {}; - -template<> struct AbsReturnType : - EnableIf {}; -template<> struct AbsReturnType { typedef unsigned char Type; }; -template<> struct AbsReturnType { typedef unsigned short Type; }; -template<> struct AbsReturnType { typedef unsigned int Type; }; -template<> struct AbsReturnType { typedef unsigned long Type; }; -template<> struct AbsReturnType { typedef unsigned long long Type; }; -template<> struct AbsReturnType { typedef float Type; }; -template<> struct AbsReturnType { typedef double Type; }; -template<> struct AbsReturnType { typedef long double Type; }; - -} // namespace detail - -template -inline typename detail::AbsReturnType::Type -Abs(const T aValue) -{ - typedef typename detail::AbsReturnType::Type ReturnType; - return aValue >= 0 ? ReturnType(aValue) : ~ReturnType(aValue) + 1; -} - -template<> -inline float -Abs(const float aFloat) -{ - return std::fabs(aFloat); -} - -template<> -inline double -Abs(const double aDouble) -{ - return std::fabs(aDouble); -} - -template<> -inline long double -Abs(const long double aLongDouble) -{ - return std::fabs(aLongDouble); -} - -} // namespace mozilla - -#if defined(_MSC_VER) && \ - (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) -# define MOZ_BITSCAN_WINDOWS - -# include -# pragma intrinsic(_BitScanForward, _BitScanReverse) - -# if defined(_M_AMD64) || defined(_M_X64) -# define MOZ_BITSCAN_WINDOWS64 -# pragma intrinsic(_BitScanForward64, _BitScanReverse64) -# endif - -#endif - -namespace mozilla { - -namespace detail { - -#if defined(MOZ_BITSCAN_WINDOWS) - -inline uint_fast8_t -CountLeadingZeroes32(uint32_t aValue) -{ - unsigned long index; - if (!_BitScanReverse(&index, static_cast(aValue))) - return 32; - return uint_fast8_t(31 - index); -} - - -inline uint_fast8_t -CountTrailingZeroes32(uint32_t aValue) -{ - unsigned long index; - if (!_BitScanForward(&index, static_cast(aValue))) - return 32; - return uint_fast8_t(index); -} - -inline uint_fast8_t -CountPopulation32(uint32_t aValue) -{ - uint32_t x = aValue - ((aValue >> 1) & 0x55555555); - x = (x & 0x33333333) + ((x >> 2) & 0x33333333); - return (((x + (x >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24; -} -inline uint_fast8_t -CountPopulation64(uint64_t aValue) -{ - return uint_fast8_t(CountPopulation32(aValue & 0xffffffff) + - CountPopulation32(aValue >> 32)); -} - -inline uint_fast8_t -CountLeadingZeroes64(uint64_t aValue) -{ -#if defined(MOZ_BITSCAN_WINDOWS64) - unsigned long index; - if (!_BitScanReverse64(&index, static_cast(aValue))) - return 64; - return uint_fast8_t(63 - index); -#else - uint32_t hi = uint32_t(aValue >> 32); - if (hi != 0) { - return CountLeadingZeroes32(hi); - } - return 32u + CountLeadingZeroes32(uint32_t(aValue)); -#endif -} - -inline uint_fast8_t -CountTrailingZeroes64(uint64_t aValue) -{ -#if defined(MOZ_BITSCAN_WINDOWS64) - unsigned long index; - if (!_BitScanForward64(&index, static_cast(aValue))) - return 64; - return uint_fast8_t(index); -#else - uint32_t lo = uint32_t(aValue); - if (lo != 0) { - return CountTrailingZeroes32(lo); - } - return 32u + CountTrailingZeroes32(uint32_t(aValue >> 32)); -#endif -} - -# ifdef MOZ_HAVE_BITSCAN64 -# undef MOZ_HAVE_BITSCAN64 -# endif - -#elif defined(__clang__) || defined(__GNUC__) - -# if defined(__clang__) -# if !__has_builtin(__builtin_ctz) || !__has_builtin(__builtin_clz) -# error "A clang providing __builtin_c[lt]z is required to build" -# endif -# else - // gcc has had __builtin_clz and friends since 3.4: no need to check. -# endif - -inline uint_fast8_t -CountLeadingZeroes32(uint32_t aValue) -{ - return __builtin_clz(aValue); -} - -inline uint_fast8_t -CountTrailingZeroes32(uint32_t aValue) -{ - return __builtin_ctz(aValue); -} - -inline uint_fast8_t -CountPopulation32(uint32_t aValue) -{ - return __builtin_popcount(aValue); -} - -inline uint_fast8_t -CountPopulation64(uint64_t aValue) -{ - return __builtin_popcountll(aValue); -} - -inline uint_fast8_t -CountLeadingZeroes64(uint64_t aValue) -{ - return __builtin_clzll(aValue); -} - -inline uint_fast8_t -CountTrailingZeroes64(uint64_t aValue) -{ - return __builtin_ctzll(aValue); -} - -#else -# error "Implement these!" -inline uint_fast8_t CountLeadingZeroes32(uint32_t aValue) = delete; -inline uint_fast8_t CountTrailingZeroes32(uint32_t aValue) = delete; -inline uint_fast8_t CountPopulation32(uint32_t aValue) = delete; -inline uint_fast8_t CountPopulation64(uint64_t aValue) = delete; -inline uint_fast8_t CountLeadingZeroes64(uint64_t aValue) = delete; -inline uint_fast8_t CountTrailingZeroes64(uint64_t aValue) = delete; -#endif - -} // namespace detail - -/** - * Compute the number of high-order zero bits in the NON-ZERO number |aValue|. - * That is, looking at the bitwise representation of the number, with the - * highest- valued bits at the start, return the number of zeroes before the - * first one is observed. - * - * CountLeadingZeroes32(0xF0FF1000) is 0; - * CountLeadingZeroes32(0x7F8F0001) is 1; - * CountLeadingZeroes32(0x3FFF0100) is 2; - * CountLeadingZeroes32(0x1FF50010) is 3; and so on. - */ -inline uint_fast8_t -CountLeadingZeroes32(uint32_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountLeadingZeroes32(aValue); -} - -/** - * Compute the number of low-order zero bits in the NON-ZERO number |aValue|. - * That is, looking at the bitwise representation of the number, with the - * lowest- valued bits at the start, return the number of zeroes before the - * first one is observed. - * - * CountTrailingZeroes32(0x0100FFFF) is 0; - * CountTrailingZeroes32(0x7000FFFE) is 1; - * CountTrailingZeroes32(0x0080FFFC) is 2; - * CountTrailingZeroes32(0x0080FFF8) is 3; and so on. - */ -inline uint_fast8_t -CountTrailingZeroes32(uint32_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountTrailingZeroes32(aValue); -} - -/** - * Compute the number of one bits in the number |aValue|, - */ -inline uint_fast8_t -CountPopulation32(uint32_t aValue) -{ - return detail::CountPopulation32(aValue); -} - -/** Analogous to CountPopulation32, but for 64-bit numbers */ -inline uint_fast8_t -CountPopulation64(uint64_t aValue) -{ - return detail::CountPopulation64(aValue); -} - -/** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ -inline uint_fast8_t -CountLeadingZeroes64(uint64_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountLeadingZeroes64(aValue); -} - -/** Analogous to CountTrailingZeroes32, but for 64-bit numbers. */ -inline uint_fast8_t -CountTrailingZeroes64(uint64_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountTrailingZeroes64(aValue); -} - -namespace detail { - -template -class CeilingLog2; - -template -class CeilingLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - // Check for <= 1 to avoid the == 0 undefined case. - return aValue <= 1 ? 0u : 32u - CountLeadingZeroes32(aValue - 1); - } -}; - -template -class CeilingLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - // Check for <= 1 to avoid the == 0 undefined case. - return aValue <= 1 ? 0u : 64u - CountLeadingZeroes64(aValue - 1); - } -}; - -} // namespace detail - -/** - * Compute the log of the least power of 2 greater than or equal to |aValue|. - * - * CeilingLog2(0..1) is 0; - * CeilingLog2(2) is 1; - * CeilingLog2(3..4) is 2; - * CeilingLog2(5..8) is 3; - * CeilingLog2(9..16) is 4; and so on. - */ -template -inline uint_fast8_t -CeilingLog2(const T aValue) -{ - return detail::CeilingLog2::compute(aValue); -} - -/** A CeilingLog2 variant that accepts only size_t. */ -inline uint_fast8_t -CeilingLog2Size(size_t aValue) -{ - return CeilingLog2(aValue); -} - -namespace detail { - -template -class FloorLog2; - -template -class FloorLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - return 31u - CountLeadingZeroes32(aValue | 1); - } -}; - -template -class FloorLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - return 63u - CountLeadingZeroes64(aValue | 1); - } -}; - -} // namespace detail - -/** - * Compute the log of the greatest power of 2 less than or equal to |aValue|. - * - * FloorLog2(0..1) is 0; - * FloorLog2(2..3) is 1; - * FloorLog2(4..7) is 2; - * FloorLog2(8..15) is 3; and so on. - */ -template -inline uint_fast8_t -FloorLog2(const T aValue) -{ - return detail::FloorLog2::compute(aValue); -} - -/** A FloorLog2 variant that accepts only size_t. */ -inline uint_fast8_t -FloorLog2Size(size_t aValue) -{ - return FloorLog2(aValue); -} - -/* - * Compute the smallest power of 2 greater than or equal to |x|. |x| must not - * be so great that the computed value would overflow |size_t|. - */ -inline size_t -RoundUpPow2(size_t aValue) -{ - MOZ_ASSERT(aValue <= (size_t(1) << (sizeof(size_t) * CHAR_BIT - 1)), - "can't round up -- will overflow!"); - return size_t(1) << CeilingLog2(aValue); -} - -/** - * Rotates the bits of the given value left by the amount of the shift width. - */ -template -inline T -RotateLeft(const T aValue, uint_fast8_t aShift) -{ - MOZ_ASSERT(aShift < sizeof(T) * CHAR_BIT, "Shift value is too large!"); - MOZ_ASSERT(aShift > 0, - "Rotation by value length is undefined behavior, but compilers " - "do not currently fold a test into the rotate instruction. " - "Please remove this restriction when compilers optimize the " - "zero case (http://blog.regehr.org/archives/1063)."); - static_assert(IsUnsigned::value, "Rotates require unsigned values"); - return (aValue << aShift) | (aValue >> (sizeof(T) * CHAR_BIT - aShift)); -} - -/** - * Rotates the bits of the given value right by the amount of the shift width. - */ -template -inline T -RotateRight(const T aValue, uint_fast8_t aShift) -{ - MOZ_ASSERT(aShift < sizeof(T) * CHAR_BIT, "Shift value is too large!"); - MOZ_ASSERT(aShift > 0, - "Rotation by value length is undefined behavior, but compilers " - "do not currently fold a test into the rotate instruction. " - "Please remove this restriction when compilers optimize the " - "zero case (http://blog.regehr.org/archives/1063)."); - static_assert(IsUnsigned::value, "Rotates require unsigned values"); - return (aValue >> aShift) | (aValue << (sizeof(T) * CHAR_BIT - aShift)); -} - -/** - * Returns true if |x| is a power of two. - * Zero is not an integer power of two. (-Inf is not an integer) - */ -template -constexpr bool -IsPowerOfTwo(T x) -{ - static_assert(IsUnsigned::value, - "IsPowerOfTwo requires unsigned values"); - return x && (x & (x - 1)) == 0; -} - -template -inline T -Clamp(const T aValue, const T aMin, const T aMax) -{ - static_assert(IsIntegral::value, - "Clamp accepts only integral types, so that it doesn't have" - " to distinguish differently-signed zeroes (which users may" - " or may not care to distinguish, likely at a perf cost) or" - " to decide how to clamp NaN or a range with a NaN" - " endpoint."); - MOZ_ASSERT(aMin <= aMax); - - if (aValue <= aMin) - return aMin; - if (aValue >= aMax) - return aMax; - return aValue; -} - -} /* namespace mozilla */ - -#endif /* mozilla_MathAlgorithms_h */ diff --git a/ios/include/spidermonkey/mozilla/Maybe.h b/ios/include/spidermonkey/mozilla/Maybe.h deleted file mode 100644 index 2a601ac4..00000000 --- a/ios/include/spidermonkey/mozilla/Maybe.h +++ /dev/null @@ -1,551 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A class for optional values and in-place lazy construction. */ - -#ifndef mozilla_Maybe_h -#define mozilla_Maybe_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include // for placement new -#include - -namespace mozilla { - -struct Nothing { }; - -/* - * Maybe is a container class which contains either zero or one elements. It - * serves two roles. It can represent values which are *semantically* optional, - * augmenting a type with an explicit 'Nothing' value. In this role, it provides - * methods that make it easy to work with values that may be missing, along with - * equality and comparison operators so that Maybe values can be stored in - * containers. Maybe values can be constructed conveniently in expressions using - * type inference, as follows: - * - * void doSomething(Maybe aFoo) { - * if (aFoo) // Make sure that aFoo contains a value... - * aFoo->takeAction(); // and then use |aFoo->| to access it. - * } // |*aFoo| also works! - * - * doSomething(Nothing()); // Passes a Maybe containing no value. - * doSomething(Some(Foo(100))); // Passes a Maybe containing |Foo(100)|. - * - * You'll note that it's important to check whether a Maybe contains a value - * before using it, using conversion to bool, |isSome()|, or |isNothing()|. You - * can avoid these checks, and sometimes write more readable code, using - * |valueOr()|, |ptrOr()|, and |refOr()|, which allow you to retrieve the value - * in the Maybe and provide a default for the 'Nothing' case. You can also use - * |apply()| to call a function only if the Maybe holds a value, and |map()| to - * transform the value in the Maybe, returning another Maybe with a possibly - * different type. - * - * Maybe's other role is to support lazily constructing objects without using - * dynamic storage. A Maybe directly contains storage for a value, but it's - * empty by default. |emplace()|, as mentioned above, can be used to construct a - * value in Maybe's storage. The value a Maybe contains can be destroyed by - * calling |reset()|; this will happen automatically if a Maybe is destroyed - * while holding a value. - * - * It's a common idiom in C++ to use a pointer as a 'Maybe' type, with a null - * value meaning 'Nothing' and any other value meaning 'Some'. You can convert - * from such a pointer to a Maybe value using 'ToMaybe()'. - * - * Maybe is inspired by similar types in the standard library of many other - * languages (e.g. Haskell's Maybe and Rust's Option). In the C++ world it's - * very similar to std::optional, which was proposed for C++14 and originated in - * Boost. The most important differences between Maybe and std::optional are: - * - * - std::optional may be compared with T. We deliberately forbid that. - * - std::optional allows in-place construction without a separate call to - * |emplace()| by using a dummy |in_place_t| value to tag the appropriate - * constructor. - * - std::optional has |valueOr()|, equivalent to Maybe's |valueOr()|, but - * lacks corresponding methods for |refOr()| and |ptrOr()|. - * - std::optional lacks |map()| and |apply()|, making it less suitable for - * functional-style code. - * - std::optional lacks many convenience functions that Maybe has. Most - * unfortunately, it lacks equivalents of the type-inferred constructor - * functions |Some()| and |Nothing()|. - * - * N.B. GCC has missed optimizations with Maybe in the past and may generate - * extra branches/loads/stores. Use with caution on hot paths; it's not known - * whether or not this is still a problem. - */ -template -class Maybe -{ - bool mIsSome; - AlignedStorage2 mStorage; - -public: - typedef T ValueType; - - Maybe() : mIsSome(false) { } - ~Maybe() { reset(); } - - MOZ_IMPLICIT Maybe(Nothing) : mIsSome(false) { } - - Maybe(const Maybe& aOther) - : mIsSome(false) - { - if (aOther.mIsSome) { - emplace(*aOther); - } - } - - /** - * Maybe can be copy-constructed from a Maybe if U* and T* are - * compatible, or from Maybe. - */ - template::value && - (std::is_same::value || - (std::is_pointer::value && - std::is_base_of::type, - typename std::remove_pointer::type>::value))>::type> - MOZ_IMPLICIT - Maybe(const Maybe& aOther) - : mIsSome(false) - { - if (aOther.isSome()) { - emplace(*aOther); - } - } - - Maybe(Maybe&& aOther) - : mIsSome(false) - { - if (aOther.mIsSome) { - emplace(Move(*aOther)); - aOther.reset(); - } - } - - /** - * Maybe can be move-constructed from a Maybe if U* and T* are - * compatible, or from Maybe. - */ - template::value && - (std::is_same::value || - (std::is_pointer::value && - std::is_base_of::type, - typename std::remove_pointer::type>::value))>::type> - MOZ_IMPLICIT - Maybe(Maybe&& aOther) - : mIsSome(false) - { - if (aOther.isSome()) { - emplace(Move(*aOther)); - aOther.reset(); - } - } - - Maybe& operator=(const Maybe& aOther) - { - if (&aOther != this) { - if (aOther.mIsSome) { - if (mIsSome) { - // XXX(seth): The correct code for this branch, below, can't be used - // due to a bug in Visual Studio 2010. See bug 1052940. - /* - ref() = aOther.ref(); - */ - reset(); - emplace(*aOther); - } else { - emplace(*aOther); - } - } else { - reset(); - } - } - return *this; - } - - Maybe& operator=(Maybe&& aOther) - { - MOZ_ASSERT(this != &aOther, "Self-moves are prohibited"); - - if (aOther.mIsSome) { - if (mIsSome) { - ref() = Move(aOther.ref()); - } else { - emplace(Move(*aOther)); - } - aOther.reset(); - } else { - reset(); - } - - return *this; - } - - /* Methods that check whether this Maybe contains a value */ - explicit operator bool() const { return isSome(); } - bool isSome() const { return mIsSome; } - bool isNothing() const { return !mIsSome; } - - /* Returns the contents of this Maybe by value. Unsafe unless |isSome()|. */ - T value() const - { - MOZ_ASSERT(mIsSome); - return ref(); - } - - /* - * Returns the contents of this Maybe by value. If |isNothing()|, returns - * the default value provided. - */ - template - T valueOr(V&& aDefault) const - { - if (isSome()) { - return ref(); - } - return Forward(aDefault); - } - - /* - * Returns the contents of this Maybe by value. If |isNothing()|, returns - * the value returned from the function or functor provided. - */ - template - T valueOrFrom(F&& aFunc) const - { - if (isSome()) { - return ref(); - } - return aFunc(); - } - - /* Returns the contents of this Maybe by pointer. Unsafe unless |isSome()|. */ - T* ptr() - { - MOZ_ASSERT(mIsSome); - return &ref(); - } - - const T* ptr() const - { - MOZ_ASSERT(mIsSome); - return &ref(); - } - - /* - * Returns the contents of this Maybe by pointer. If |isNothing()|, - * returns the default value provided. - */ - T* ptrOr(T* aDefault) - { - if (isSome()) { - return ptr(); - } - return aDefault; - } - - const T* ptrOr(const T* aDefault) const - { - if (isSome()) { - return ptr(); - } - return aDefault; - } - - /* - * Returns the contents of this Maybe by pointer. If |isNothing()|, - * returns the value returned from the function or functor provided. - */ - template - T* ptrOrFrom(F&& aFunc) - { - if (isSome()) { - return ptr(); - } - return aFunc(); - } - - template - const T* ptrOrFrom(F&& aFunc) const - { - if (isSome()) { - return ptr(); - } - return aFunc(); - } - - T* operator->() - { - MOZ_ASSERT(mIsSome); - return ptr(); - } - - const T* operator->() const - { - MOZ_ASSERT(mIsSome); - return ptr(); - } - - /* Returns the contents of this Maybe by ref. Unsafe unless |isSome()|. */ - T& ref() - { - MOZ_ASSERT(mIsSome); - return *mStorage.addr(); - } - - const T& ref() const - { - MOZ_ASSERT(mIsSome); - return *mStorage.addr(); - } - - /* - * Returns the contents of this Maybe by ref. If |isNothing()|, returns - * the default value provided. - */ - T& refOr(T& aDefault) - { - if (isSome()) { - return ref(); - } - return aDefault; - } - - const T& refOr(const T& aDefault) const - { - if (isSome()) { - return ref(); - } - return aDefault; - } - - /* - * Returns the contents of this Maybe by ref. If |isNothing()|, returns the - * value returned from the function or functor provided. - */ - template - T& refOrFrom(F&& aFunc) - { - if (isSome()) { - return ref(); - } - return aFunc(); - } - - template - const T& refOrFrom(F&& aFunc) const - { - if (isSome()) { - return ref(); - } - return aFunc(); - } - - T& operator*() - { - MOZ_ASSERT(mIsSome); - return ref(); - } - - const T& operator*() const - { - MOZ_ASSERT(mIsSome); - return ref(); - } - - /* If |isSome()|, runs the provided function or functor on the contents of - * this Maybe. */ - template - Maybe& apply(Func aFunc) - { - if (isSome()) { - aFunc(ref()); - } - return *this; - } - - template - const Maybe& apply(Func aFunc) const - { - if (isSome()) { - aFunc(ref()); - } - return *this; - } - - /* - * If |isSome()|, runs the provided function and returns the result wrapped - * in a Maybe. If |isNothing()|, returns an empty Maybe value. - */ - template - auto map(Func aFunc) -> Maybe>().ref()))> - { - using ReturnType = decltype(aFunc(ref())); - if (isSome()) { - Maybe val; - val.emplace(aFunc(ref())); - return val; - } - return Maybe(); - } - - template - auto map(Func aFunc) const -> Maybe>().ref()))> - { - using ReturnType = decltype(aFunc(ref())); - if (isSome()) { - Maybe val; - val.emplace(aFunc(ref())); - return val; - } - return Maybe(); - } - - /* If |isSome()|, empties this Maybe and destroys its contents. */ - void reset() - { - if (isSome()) { - ref().T::~T(); - mIsSome = false; - } - } - - /* - * Constructs a T value in-place in this empty Maybe's storage. The - * arguments to |emplace()| are the parameters to T's constructor. - */ - template - void emplace(Args&&... aArgs) - { - MOZ_ASSERT(!mIsSome); - ::new (mStorage.addr()) T(Forward(aArgs)...); - mIsSome = true; - } -}; - -/* - * Some() creates a Maybe value containing the provided T value. If T has a - * move constructor, it's used to make this as efficient as possible. - * - * Some() selects the type of Maybe it returns by removing any const, volatile, - * or reference qualifiers from the type of the value you pass to it. This gives - * it more intuitive behavior when used in expressions, but it also means that - * if you need to construct a Maybe value that holds a const, volatile, or - * reference value, you need to use emplace() instead. - */ -template -Maybe::Type>::Type> -Some(T&& aValue) -{ - typedef typename RemoveCV::Type>::Type U; - Maybe value; - value.emplace(Forward(aValue)); - return value; -} - -template -Maybe::Type>::Type> -ToMaybe(T* aPtr) -{ - if (aPtr) { - return Some(*aPtr); - } - return Nothing(); -} - -/* - * Two Maybe values are equal if - * - both are Nothing, or - * - both are Some, and the values they contain are equal. - */ -template bool -operator==(const Maybe& aLHS, const Maybe& aRHS) -{ - if (aLHS.isNothing() != aRHS.isNothing()) { - return false; - } - return aLHS.isNothing() || *aLHS == *aRHS; -} - -template bool -operator!=(const Maybe& aLHS, const Maybe& aRHS) -{ - return !(aLHS == aRHS); -} - -/* - * We support comparison to Nothing to allow reasonable expressions like: - * if (maybeValue == Nothing()) { ... } - */ -template bool -operator==(const Maybe& aLHS, const Nothing& aRHS) -{ - return aLHS.isNothing(); -} - -template bool -operator!=(const Maybe& aLHS, const Nothing& aRHS) -{ - return !(aLHS == aRHS); -} - -template bool -operator==(const Nothing& aLHS, const Maybe& aRHS) -{ - return aRHS.isNothing(); -} - -template bool -operator!=(const Nothing& aLHS, const Maybe& aRHS) -{ - return !(aLHS == aRHS); -} - -/* - * Maybe values are ordered in the same way T values are ordered, except that - * Nothing comes before anything else. - */ -template bool -operator<(const Maybe& aLHS, const Maybe& aRHS) -{ - if (aLHS.isNothing()) { - return aRHS.isSome(); - } - if (aRHS.isNothing()) { - return false; - } - return *aLHS < *aRHS; -} - -template bool -operator>(const Maybe& aLHS, const Maybe& aRHS) -{ - return !(aLHS < aRHS || aLHS == aRHS); -} - -template bool -operator<=(const Maybe& aLHS, const Maybe& aRHS) -{ - return aLHS < aRHS || aLHS == aRHS; -} - -template bool -operator>=(const Maybe& aLHS, const Maybe& aRHS) -{ - return !(aLHS < aRHS); -} - -} // namespace mozilla - -#endif /* mozilla_Maybe_h */ diff --git a/ios/include/spidermonkey/mozilla/MaybeOneOf.h b/ios/include/spidermonkey/mozilla/MaybeOneOf.h deleted file mode 100644 index 9c38ff8b..00000000 --- a/ios/include/spidermonkey/mozilla/MaybeOneOf.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_MaybeOneOf_h -#define mozilla_MaybeOneOf_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Move.h" -#include "mozilla/TemplateLib.h" - -#include // For placement new - -namespace mozilla { - -/* - * MaybeOneOf is like Maybe, but it supports constructing either T1 - * or T2. When a MaybeOneOf is constructed, it is |empty()|, i.e., - * no value has been constructed and no destructor will be called when the - * MaybeOneOf is destroyed. Upon calling |construct()| or - * |construct()|, a T1 or T2 object will be constructed with the given - * arguments and that object will be destroyed when the owning MaybeOneOf is - * destroyed. - */ -template -class MaybeOneOf -{ - AlignedStorage::value> storage; - - enum State { None, SomeT1, SomeT2 } state; - template struct Type2State {}; - - template - T& as() - { - MOZ_ASSERT(state == Type2State::result); - return *(T*)storage.addr(); - } - - template - const T& as() const - { - MOZ_ASSERT(state == Type2State::result); - return *(T*)storage.addr(); - } - -public: - MaybeOneOf() : state(None) {} - ~MaybeOneOf() { destroyIfConstructed(); } - - MaybeOneOf(MaybeOneOf&& rhs) - : state(None) - { - if (!rhs.empty()) { - if (rhs.constructed()) { - construct(Move(rhs.as())); - rhs.as().~T1(); - } else { - construct(Move(rhs.as())); - rhs.as().~T2(); - } - rhs.state = None; - } - } - - MaybeOneOf &operator=(MaybeOneOf&& rhs) - { - MOZ_ASSERT(this != &rhs, "Self-move is prohibited"); - this->~MaybeOneOf(); - new(this) MaybeOneOf(Move(rhs)); - return *this; - } - - bool empty() const { return state == None; } - - template - bool constructed() const { return state == Type2State::result; } - - template - void construct(Args&&... aArgs) - { - MOZ_ASSERT(state == None); - state = Type2State::result; - ::new (storage.addr()) T(Forward(aArgs)...); - } - - template - T& ref() - { - return as(); - } - - template - const T& ref() const - { - return as(); - } - - void destroy() - { - MOZ_ASSERT(state == SomeT1 || state == SomeT2); - if (state == SomeT1) { - as().~T1(); - } else if (state == SomeT2) { - as().~T2(); - } - state = None; - } - - void destroyIfConstructed() - { - if (!empty()) { - destroy(); - } - } - -private: - MaybeOneOf(const MaybeOneOf& aOther) = delete; - const MaybeOneOf& operator=(const MaybeOneOf& aOther) = delete; -}; - -template -template -struct MaybeOneOf::Type2State -{ - typedef MaybeOneOf Enclosing; - static const typename Enclosing::State result = Enclosing::SomeT1; -}; - -template -template -struct MaybeOneOf::Type2State -{ - typedef MaybeOneOf Enclosing; - static const typename Enclosing::State result = Enclosing::SomeT2; -}; - -} // namespace mozilla - -#endif /* mozilla_MaybeOneOf_h */ diff --git a/ios/include/spidermonkey/mozilla/MemoryChecking.h b/ios/include/spidermonkey/mozilla/MemoryChecking.h deleted file mode 100644 index ff42d7f1..00000000 --- a/ios/include/spidermonkey/mozilla/MemoryChecking.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Provides a common interface to the ASan (AddressSanitizer) and Valgrind - * functions used to mark memory in certain ways. In detail, the following - * three macros are provided: - * - * MOZ_MAKE_MEM_NOACCESS - Mark memory as unsafe to access (e.g. freed) - * MOZ_MAKE_MEM_UNDEFINED - Mark memory as accessible, with content undefined - * MOZ_MAKE_MEM_DEFINED - Mark memory as accessible, with content defined - * - * With Valgrind in use, these directly map to the three respective Valgrind - * macros. With ASan in use, the NOACCESS macro maps to poisoning the memory, - * while the UNDEFINED/DEFINED macros unpoison memory. - * - * With no memory checker available, all macros expand to the empty statement. - */ - -#ifndef mozilla_MemoryChecking_h -#define mozilla_MemoryChecking_h - -#if defined(MOZ_VALGRIND) -#include "valgrind/memcheck.h" -#endif - -#if defined(MOZ_ASAN) || defined(MOZ_VALGRIND) -#define MOZ_HAVE_MEM_CHECKS 1 -#endif - -#if defined(MOZ_ASAN) -#include - -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" - -#ifdef _MSC_VER -// In clang-cl based ASAN, we link against the memory poisoning functions -// statically. -#define MOZ_ASAN_VISIBILITY -#else -#define MOZ_ASAN_VISIBILITY MOZ_EXPORT -#endif - -extern "C" { -/* These definitions are usually provided through the - * sanitizer/asan_interface.h header installed by ASan. - */ -void MOZ_ASAN_VISIBILITY -__asan_poison_memory_region(void const volatile *addr, size_t size); -void MOZ_ASAN_VISIBILITY -__asan_unpoison_memory_region(void const volatile *addr, size_t size); - -#define MOZ_MAKE_MEM_NOACCESS(addr, size) \ - __asan_poison_memory_region((addr), (size)) - -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \ - __asan_unpoison_memory_region((addr), (size)) - -#define MOZ_MAKE_MEM_DEFINED(addr, size) \ - __asan_unpoison_memory_region((addr), (size)) - -/* - * These definitions are usually provided through the - * sanitizer/lsan_interface.h header installed by LSan. - */ -void MOZ_EXPORT -__lsan_ignore_object(const void *p); - -} -#elif defined(MOZ_MSAN) -#include - -#include "mozilla/Types.h" - -extern "C" { -/* These definitions are usually provided through the - * sanitizer/msan_interface.h header installed by MSan. - */ -void MOZ_EXPORT -__msan_poison(void const volatile *addr, size_t size); -void MOZ_EXPORT -__msan_unpoison(void const volatile *addr, size_t size); - -#define MOZ_MAKE_MEM_NOACCESS(addr, size) \ - __msan_poison((addr), (size)) - -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \ - __msan_poison((addr), (size)) - -#define MOZ_MAKE_MEM_DEFINED(addr, size) \ - __msan_unpoison((addr), (size)) -} -#elif defined(MOZ_VALGRIND) -#define MOZ_MAKE_MEM_NOACCESS(addr, size) \ - VALGRIND_MAKE_MEM_NOACCESS((addr), (size)) - -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \ - VALGRIND_MAKE_MEM_UNDEFINED((addr), (size)) - -#define MOZ_MAKE_MEM_DEFINED(addr, size) \ - VALGRIND_MAKE_MEM_DEFINED((addr), (size)) -#else - -#define MOZ_MAKE_MEM_NOACCESS(addr, size) do {} while (0) -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) do {} while (0) -#define MOZ_MAKE_MEM_DEFINED(addr, size) do {} while (0) - -#endif - -/* - * MOZ_LSAN_INTENTIONAL_LEAK(X) is a macro to tell LeakSanitizer that X - * points to a value that will intentionally never be deallocated during - * the execution of the process. - * - * Additional uses of this macro should be reviewed by people - * conversant in leak-checking and/or MFBT peers. - */ -#if defined(MOZ_ASAN) -# define MOZ_LSAN_INTENTIONALLY_LEAK_OBJECT(X) __lsan_ignore_object(X) -#else -# define MOZ_LSAN_INTENTIONALLY_LEAK_OBJECT(X) /* nothing */ -#endif // defined(MOZ_ASAN) - - -#endif /* mozilla_MemoryChecking_h */ diff --git a/ios/include/spidermonkey/mozilla/MemoryReporting.h b/ios/include/spidermonkey/mozilla/MemoryReporting.h deleted file mode 100644 index d2340ecf..00000000 --- a/ios/include/spidermonkey/mozilla/MemoryReporting.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Memory reporting infrastructure. */ - -#ifndef mozilla_MemoryReporting_h -#define mozilla_MemoryReporting_h - -#include - -#ifdef __cplusplus - -namespace mozilla { - -/* - * This is for functions that are like malloc_usable_size. Such functions are - * used for measuring the size of data structures. - */ -typedef size_t (*MallocSizeOf)(const void* p); - -} /* namespace mozilla */ - -#endif /* __cplusplus */ - -typedef size_t (*MozMallocSizeOf)(const void* p); - -#endif /* mozilla_MemoryReporting_h */ diff --git a/ios/include/spidermonkey/mozilla/Move.h b/ios/include/spidermonkey/mozilla/Move.h deleted file mode 100644 index f6d0bfc1..00000000 --- a/ios/include/spidermonkey/mozilla/Move.h +++ /dev/null @@ -1,238 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* C++11-style, but C++98-usable, "move references" implementation. */ - -#ifndef mozilla_Move_h -#define mozilla_Move_h - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/* - * "Move" References - * - * Some types can be copied much more efficiently if we know the original's - * value need not be preserved --- that is, if we are doing a "move", not a - * "copy". For example, if we have: - * - * Vector u; - * Vector v(u); - * - * the constructor for v must apply a copy constructor to each element of u --- - * taking time linear in the length of u. However, if we know we will not need u - * any more once v has been initialized, then we could initialize v very - * efficiently simply by stealing u's dynamically allocated buffer and giving it - * to v --- a constant-time operation, regardless of the size of u. - * - * Moves often appear in container implementations. For example, when we append - * to a vector, we may need to resize its buffer. This entails moving each of - * its extant elements from the old, smaller buffer to the new, larger buffer. - * But once the elements have been migrated, we're just going to throw away the - * old buffer; we don't care if they still have their values. So if the vector's - * element type can implement "move" more efficiently than "copy", the vector - * resizing should by all means use a "move" operation. Hash tables should also - * use moves when resizing their internal array as entries are added and - * removed. - * - * The details of the optimization, and whether it's worth applying, vary - * from one type to the next: copying an 'int' is as cheap as moving it, so - * there's no benefit in distinguishing 'int' moves from copies. And while - * some constructor calls for complex types are moves, many really have to - * be copies, and can't be optimized this way. So we need: - * - * 1) a way for a type (like Vector) to announce that it can be moved more - * efficiently than it can be copied, and provide an implementation of that - * move operation; and - * - * 2) a way for a particular invocation of a copy constructor to say that it's - * really a move, not a copy, and that the value of the original isn't - * important afterwards (although it must still be safe to destroy). - * - * If a constructor has a single argument of type 'T&&' (an 'rvalue reference - * to T'), that indicates that it is a 'move constructor'. That's 1). It should - * move, not copy, its argument into the object being constructed. It may leave - * the original in any safely-destructible state. - * - * If a constructor's argument is an rvalue, as in 'C(f(x))' or 'C(x + y)', as - * opposed to an lvalue, as in 'C(x)', then overload resolution will prefer the - * move constructor, if there is one. The 'mozilla::Move' function, defined in - * this file, is an identity function you can use in a constructor invocation to - * make any argument into an rvalue, like this: C(Move(x)). That's 2). (You - * could use any function that works, but 'Move' indicates your intention - * clearly.) - * - * Where we might define a copy constructor for a class C like this: - * - * C(const C& rhs) { ... copy rhs to this ... } - * - * we would declare a move constructor like this: - * - * C(C&& rhs) { .. move rhs to this ... } - * - * And where we might perform a copy like this: - * - * C c2(c1); - * - * we would perform a move like this: - * - * C c2(Move(c1)); - * - * Note that 'T&&' implicitly converts to 'T&'. So you can pass a 'T&&' to an - * ordinary copy constructor for a type that doesn't support a special move - * constructor, and you'll just get a copy. This means that templates can use - * Move whenever they know they won't use the original value any more, even if - * they're not sure whether the type at hand has a specialized move constructor. - * If it doesn't, the 'T&&' will just convert to a 'T&', and the ordinary copy - * constructor will apply. - * - * A class with a move constructor can also provide a move assignment operator. - * A generic definition would run this's destructor, and then apply the move - * constructor to *this's memory. A typical definition: - * - * C& operator=(C&& rhs) { - * MOZ_ASSERT(&rhs != this, "self-moves are prohibited"); - * this->~C(); - * new(this) C(Move(rhs)); - * return *this; - * } - * - * With that in place, one can write move assignments like this: - * - * c2 = Move(c1); - * - * This destroys c2, moves c1's value to c2, and leaves c1 in an undefined but - * destructible state. - * - * As we say, a move must leave the original in a "destructible" state. The - * original's destructor will still be called, so if a move doesn't - * actually steal all its resources, that's fine. We require only that the - * move destination must take on the original's value; and that destructing - * the original must not break the move destination. - * - * (Opinions differ on whether move assignment operators should deal with move - * assignment of an object onto itself. It seems wise to either handle that - * case, or assert that it does not occur.) - * - * Forwarding: - * - * Sometimes we want copy construction or assignment if we're passed an ordinary - * value, but move construction if passed an rvalue reference. For example, if - * our constructor takes two arguments and either could usefully be a move, it - * seems silly to write out all four combinations: - * - * C::C(X& x, Y& y) : x(x), y(y) { } - * C::C(X& x, Y&& y) : x(x), y(Move(y)) { } - * C::C(X&& x, Y& y) : x(Move(x)), y(y) { } - * C::C(X&& x, Y&& y) : x(Move(x)), y(Move(y)) { } - * - * To avoid this, C++11 has tweaks to make it possible to write what you mean. - * The four constructor overloads above can be written as one constructor - * template like so[0]: - * - * template - * C::C(XArg&& x, YArg&& y) : x(Forward(x)), y(Forward(y)) { } - * - * ("'Don't Repeat Yourself'? What's that?") - * - * This takes advantage of two new rules in C++11: - * - * - First, when a function template takes an argument that is an rvalue - * reference to a template argument (like 'XArg&& x' and 'YArg&& y' above), - * then when the argument is applied to an lvalue, the template argument - * resolves to 'T&'; and when it is applied to an rvalue, the template - * argument resolves to 'T'. Thus, in a call to C::C like: - * - * X foo(int); - * Y yy; - * - * C(foo(5), yy) - * - * XArg would resolve to 'X', and YArg would resolve to 'Y&'. - * - * - Second, Whereas C++ used to forbid references to references, C++11 defines - * 'collapsing rules': 'T& &', 'T&& &', and 'T& &&' (that is, any combination - * involving an lvalue reference) now collapse to simply 'T&'; and 'T&& &&' - * collapses to 'T&&'. - * - * Thus, in the call above, 'XArg&&' is 'X&&'; and 'YArg&&' is 'Y& &&', which - * collapses to 'Y&'. Because the arguments are declared as rvalue references - * to template arguments, the lvalue-ness "shines through" where present. - * - * Then, the 'Forward' function --- you must invoke 'Forward' with its type - * argument --- returns an lvalue reference or an rvalue reference to its - * argument, depending on what T is. In our unified constructor definition, that - * means that we'll invoke either the copy or move constructors for x and y, - * depending on what we gave C's constructor. In our call, we'll move 'foo()' - * into 'x', but copy 'yy' into 'y'. - * - * This header file defines Move and Forward in the mozilla namespace. It's up - * to individual containers to annotate moves as such, by calling Move; and it's - * up to individual types to define move constructors and assignment operators - * when valuable. - * - * (C++11 says that the header file should define 'std::move' and - * 'std::forward', which are just like our 'Move' and 'Forward'; but those - * definitions aren't available in that header on all our platforms, so we - * define them ourselves here.) - * - * 0. This pattern is known as "perfect forwarding". Interestingly, it is not - * actually perfect, and it can't forward all possible argument expressions! - * There is a C++11 issue: you can't form a reference to a bit-field. As a - * workaround, assign the bit-field to a local variable and use that: - * - * // C is as above - * struct S { int x : 1; } s; - * C(s.x, 0); // BAD: s.x is a reference to a bit-field, can't form those - * int tmp = s.x; - * C(tmp, 0); // OK: tmp not a bit-field - */ - -/** - * Identical to std::Move(); this is necessary until our stlport supports - * std::move(). - */ -template -inline typename RemoveReference::Type&& -Move(T&& aX) -{ - return static_cast::Type&&>(aX); -} - -/** - * These two overloads are identical to std::forward(); they are necessary until - * our stlport supports std::forward(). - */ -template -inline T&& -Forward(typename RemoveReference::Type& aX) -{ - return static_cast(aX); -} - -template -inline T&& -Forward(typename RemoveReference::Type&& aX) -{ - static_assert(!IsLvalueReference::value, - "misuse of Forward detected! try the other overload"); - return static_cast(aX); -} - -/** Swap |aX| and |aY| using move-construction if possible. */ -template -inline void -Swap(T& aX, T& aY) -{ - T tmp(Move(aX)); - aX = Move(aY); - aY = Move(tmp); -} - -} // namespace mozilla - -#endif /* mozilla_Move_h */ diff --git a/ios/include/spidermonkey/mozilla/NotNull.h b/ios/include/spidermonkey/mozilla/NotNull.h deleted file mode 100644 index 0c3c333e..00000000 --- a/ios/include/spidermonkey/mozilla/NotNull.h +++ /dev/null @@ -1,209 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_NotNull_h -#define mozilla_NotNull_h - -// It's often unclear if a particular pointer, be it raw (T*) or smart -// (RefPtr, nsCOMPtr, etc.) can be null. This leads to missing null -// checks (which can cause crashes) and unnecessary null checks (which clutter -// the code). -// -// C++ has a built-in alternative that avoids these problems: references. This -// module defines another alternative, NotNull, which can be used in cases -// where references are not suitable. -// -// In the comments below we use the word "handle" to cover all varieties of -// pointers and references. -// -// References -// ---------- -// References are always non-null. (You can do |T& r = *p;| where |p| is null, -// but that's undefined behaviour. C++ doesn't provide any built-in, ironclad -// guarantee of non-nullness.) -// -// A reference works well when you need a temporary handle to an existing -// single object, e.g. for passing a handle to a function, or as a local handle -// within another object. (In Rust parlance, this is a "borrow".) -// -// A reference is less appropriate in the following cases. -// -// - As a primary handle to an object. E.g. code such as this is possible but -// strange: |T& t = *new T(); ...; delete &t;| -// -// - As a handle to an array. It's common for |T*| to refer to either a single -// |T| or an array of |T|, but |T&| cannot refer to an array of |T| because -// you can't index off a reference (at least, not without first converting it -// to a pointer). -// -// - When the handle identity is meaningful, e.g. if you have a hashtable of -// handles, because you have to use |&| on the reference to convert it to a -// pointer. -// -// - Some people don't like using non-const references as function parameters, -// because it is not clear at the call site that the argument might be -// modified. -// -// - When you need "smart" behaviour. E.g. we lack reference equivalents to -// RefPtr and nsCOMPtr. -// -// - When interfacing with code that uses pointers a lot, sometimes using a -// reference just feels like an odd fit. -// -// Furthermore, a reference is impossible in the following cases. -// -// - When the handle is rebound to another object. References don't allow this. -// -// - When the handle has type |void|. |void&| is not allowed. -// -// NotNull is an alternative that can be used in any of the above cases except -// for the last one, where the handle type is |void|. See below. - -#include "mozilla/Assertions.h" - -namespace mozilla { - -// NotNull can be used to wrap a "base" pointer (raw or smart) to indicate it -// is not null. Some examples: -// -// - NotNull -// - NotNull> -// - NotNull> -// -// NotNull has the following notable properties. -// -// - It has zero space overhead. -// -// - It must be initialized explicitly. There is no default initialization. -// -// - It auto-converts to the base pointer type. -// -// - It does not auto-convert from a base pointer. Implicit conversion from a -// less-constrained type (e.g. T*) to a more-constrained type (e.g. -// NotNull) is dangerous. Creation and assignment from a base pointer can -// only be done with WrapNotNull(), which makes them impossible to overlook, -// both when writing and reading code. -// -// - When initialized (or assigned) it is checked, and if it is null we abort. -// This guarantees that it cannot be null. -// -// - |operator bool()| is deleted. This means you cannot check a NotNull in a -// boolean context, which eliminates the possibility of unnecessary null -// checks. -// -// NotNull currently doesn't work with UniquePtr. See -// https://github.com/Microsoft/GSL/issues/89 for some discussion. -// -template -class NotNull -{ - template friend NotNull WrapNotNull(U aBasePtr); - - T mBasePtr; - - // This constructor is only used by WrapNotNull(). - template - explicit NotNull(U aBasePtr) : mBasePtr(aBasePtr) {} - -public: - // Disallow default construction. - NotNull() = delete; - - // Construct/assign from another NotNull with a compatible base pointer type. - template - MOZ_IMPLICIT NotNull(const NotNull& aOther) : mBasePtr(aOther.get()) {} - - // Default copy/move construction and assignment. - NotNull(const NotNull&) = default; - NotNull& operator=(const NotNull&) = default; - NotNull(NotNull&&) = default; - NotNull& operator=(NotNull&&) = default; - - // Disallow null checks, which are unnecessary for this type. - explicit operator bool() const = delete; - - // Explicit conversion to a base pointer. Use only to resolve ambiguity or to - // get a castable pointer. - const T& get() const { return mBasePtr; } - - // Implicit conversion to a base pointer. Preferable to get(). - operator const T&() const { return get(); } - - // Dereference operators. - const T& operator->() const { return get(); } - decltype(*mBasePtr) operator*() const { return *mBasePtr; } -}; - -template -NotNull -WrapNotNull(const T aBasePtr) -{ - NotNull notNull(aBasePtr); - MOZ_RELEASE_ASSERT(aBasePtr); - return notNull; -} - -// Compare two NotNulls. -template -inline bool -operator==(const NotNull& aLhs, const NotNull& aRhs) -{ - return aLhs.get() == aRhs.get(); -} -template -inline bool -operator!=(const NotNull& aLhs, const NotNull& aRhs) -{ - return aLhs.get() != aRhs.get(); -} - -// Compare a NotNull to a base pointer. -template -inline bool -operator==(const NotNull& aLhs, const U& aRhs) -{ - return aLhs.get() == aRhs; -} -template -inline bool -operator!=(const NotNull& aLhs, const U& aRhs) -{ - return aLhs.get() != aRhs; -} - -// Compare a base pointer to a NotNull. -template -inline bool -operator==(const T& aLhs, const NotNull& aRhs) -{ - return aLhs == aRhs.get(); -} -template -inline bool -operator!=(const T& aLhs, const NotNull& aRhs) -{ - return aLhs != aRhs.get(); -} - -// Disallow comparing a NotNull to a nullptr. -template -bool -operator==(const NotNull&, decltype(nullptr)) = delete; -template -bool -operator!=(const NotNull&, decltype(nullptr)) = delete; - -// Disallow comparing a nullptr to a NotNull. -template -bool -operator==(decltype(nullptr), const NotNull&) = delete; -template -bool -operator!=(decltype(nullptr), const NotNull&) = delete; - -} // namespace mozilla - -#endif /* mozilla_NotNull_h */ diff --git a/ios/include/spidermonkey/mozilla/NullPtr.h b/ios/include/spidermonkey/mozilla/NullPtr.h deleted file mode 100644 index d2248f4b..00000000 --- a/ios/include/spidermonkey/mozilla/NullPtr.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements a mozilla::IsNullPointer type trait. */ - -#ifndef mozilla_NullPtr_h -#define mozilla_NullPtr_h - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/** - * IsNullPointer::value is true iff T is decltype(nullptr). - * - * Ideally this would be in TypeTraits.h, but C++11 omitted std::is_null_pointer - * (fixed in C++14), so in the interests of easing a switch to , - * this trait lives elsewhere. - */ -template -struct IsNullPointer : FalseType {}; - -template<> -struct IsNullPointer : TrueType {}; - -} // namespace mozilla - -#endif /* mozilla_NullPtr_h */ diff --git a/ios/include/spidermonkey/mozilla/Opaque.h b/ios/include/spidermonkey/mozilla/Opaque.h deleted file mode 100644 index d7239ee7..00000000 --- a/ios/include/spidermonkey/mozilla/Opaque.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* An opaque integral type supporting only comparison operators. */ - -#ifndef mozilla_Opaque_h -#define mozilla_Opaque_h - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/** - * Opaque is a replacement for integral T in cases where only comparisons - * must be supported, and it's desirable to prevent accidental dependency on - * exact values. - */ -template -class Opaque final -{ - static_assert(mozilla::IsIntegral::value, - "mozilla::Opaque only supports integral types"); - - T mValue; - -public: - Opaque() {} - explicit Opaque(T aValue) : mValue(aValue) {} - - bool operator==(const Opaque& aOther) const { - return mValue == aOther.mValue; - } - - bool operator!=(const Opaque& aOther) const { - return !(*this == aOther); - } -}; - -} // namespace mozilla - -#endif /* mozilla_Opaque_h */ diff --git a/ios/include/spidermonkey/mozilla/OperatorNewExtensions.h b/ios/include/spidermonkey/mozilla/OperatorNewExtensions.h deleted file mode 100644 index 52fd88a6..00000000 --- a/ios/include/spidermonkey/mozilla/OperatorNewExtensions.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A version of |operator new| that eschews mandatory null-checks. */ - -#ifndef mozilla_OperatorNewExtensions_h -#define mozilla_OperatorNewExtensions_h - -#include "mozilla/Assertions.h" - -// Credit goes to WebKit for this implementation, cf. -// https://bugs.webkit.org/show_bug.cgi?id=74676 -namespace mozilla { -enum NotNullTag { - KnownNotNull, -}; -} // namespace mozilla - -/* - * The logic here is a little subtle. [expr.new] states that if the allocation - * function being called returns null, then object initialization must not be - * done, and the entirety of the new expression must return null. Non-throwing - * (noexcept) functions are defined to return null to indicate failure. The - * standard placement operator new is defined in such a way, and so it requires - * a null check, even when that null check would be extraneous. Functions - * declared without such a specification are defined to throw std::bad_alloc if - * they fail, and return a non-null pointer otherwise. We compile without - * exceptions, so any placement new overload we define that doesn't declare - * itself as noexcept must therefore avoid generating a null check. Below is - * just such an overload. - * - * You might think that MOZ_NONNULL might perform the same function, but - * MOZ_NONNULL isn't supported on all of our compilers, and even when it is - * supported, doesn't work on all the versions we support. And even keeping - * those limitations in mind, we can't put MOZ_NONNULL on the global, - * standardized placement new function in any event. - * - * We deliberately don't add MOZ_NONNULL(3) to tag |p| as non-null, to benefit - * hypothetical static analyzers. Doing so makes |MOZ_ASSERT(p)|'s internal - * test vacuous, and some compilers warn about such vacuous tests. - */ -inline void* -operator new(size_t, mozilla::NotNullTag, void* p) -{ - MOZ_ASSERT(p); - return p; -} - -#endif // mozilla_OperatorNewExtensions_h diff --git a/ios/include/spidermonkey/mozilla/Pair.h b/ios/include/spidermonkey/mozilla/Pair.h deleted file mode 100644 index ad7b86a2..00000000 --- a/ios/include/spidermonkey/mozilla/Pair.h +++ /dev/null @@ -1,219 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A class holding a pair of objects that tries to conserve storage space. */ - -#ifndef mozilla_Pair_h -#define mozilla_Pair_h - -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -namespace detail { - -enum StorageType { AsBase, AsMember }; - -// Optimize storage using the Empty Base Optimization -- that empty base classes -// don't take up space -- to optimize size when one or the other class is -// stateless and can be used as a base class. -// -// The extra conditions on storage for B are necessary so that PairHelper won't -// ambiguously inherit from either A or B, such that one or the other base class -// would be inaccessible. -template::value ? detail::AsBase : detail::AsMember, - detail::StorageType = - IsEmpty::value && !IsBaseOf::value && !IsBaseOf::value - ? detail::AsBase - : detail::AsMember> -struct PairHelper; - -template -struct PairHelper -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : mFirstA(Forward(aA)), - mSecondB(Forward(aB)) - {} - - A& first() { return mFirstA; } - const A& first() const { return mFirstA; } - B& second() { return mSecondB; } - const B& second() const { return mSecondB; } - - void swap(PairHelper& aOther) - { - Swap(mFirstA, aOther.mFirstA); - Swap(mSecondB, aOther.mSecondB); - } - -private: - A mFirstA; - B mSecondB; -}; - -template -struct PairHelper : private B -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : B(Forward(aB)), - mFirstA(Forward(aA)) - {} - - A& first() { return mFirstA; } - const A& first() const { return mFirstA; } - B& second() { return *this; } - const B& second() const { return *this; } - - void swap(PairHelper& aOther) - { - Swap(mFirstA, aOther.mFirstA); - Swap(static_cast(*this), static_cast(aOther)); - } - -private: - A mFirstA; -}; - -template -struct PairHelper : private A -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : A(Forward(aA)), - mSecondB(Forward(aB)) - {} - - A& first() { return *this; } - const A& first() const { return *this; } - B& second() { return mSecondB; } - const B& second() const { return mSecondB; } - - void swap(PairHelper& aOther) - { - Swap(static_cast(*this), static_cast(aOther)); - Swap(mSecondB, aOther.mSecondB); - } - -private: - B mSecondB; -}; - -template -struct PairHelper : private A, private B -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : A(Forward(aA)), - B(Forward(aB)) - {} - - A& first() { return static_cast(*this); } - const A& first() const { return static_cast(*this); } - B& second() { return static_cast(*this); } - const B& second() const { return static_cast(*this); } - - void swap(PairHelper& aOther) - { - Swap(static_cast(*this), static_cast(aOther)); - Swap(static_cast(*this), static_cast(aOther)); - } -}; - -} // namespace detail - -/** - * Pair is the logical concatenation of an instance of A with an instance B. - * Space is conserved when possible. Neither A nor B may be a final class. - * - * It's typically clearer to have individual A and B member fields. Except if - * you want the space-conserving qualities of Pair, you're probably better off - * not using this! - * - * No guarantees are provided about the memory layout of A and B, the order of - * initialization or destruction of A and B, and so on. (This is approximately - * required to optimize space usage.) The first/second names are merely - * conceptual! - */ -template -struct Pair - : private detail::PairHelper -{ - typedef typename detail::PairHelper Base; - -public: - template - Pair(AArg&& aA, BArg&& aB) - : Base(Forward(aA), Forward(aB)) - {} - - Pair(Pair&& aOther) - : Base(Move(aOther.first()), Move(aOther.second())) - { } - - Pair(const Pair& aOther) = default; - - Pair& operator=(Pair&& aOther) - { - MOZ_ASSERT(this != &aOther, "Self-moves are prohibited"); - - first() = Move(aOther.first()); - second() = Move(aOther.second()); - - return *this; - } - - Pair& operator=(const Pair& aOther) = default; - - /** The A instance. */ - using Base::first; - /** The B instance. */ - using Base::second; - - /** Swap this pair with another pair. */ - void swap(Pair& aOther) { Base::swap(aOther); } -}; - -template -void -Swap(Pair& aX, Pair& aY) -{ - aX.swap(aY); -} - -/** - * MakePair allows you to construct a Pair instance using type inference. A call - * like this: - * - * MakePair(Foo(), Bar()) - * - * will return a Pair. - */ -template -Pair::Type>::Type, - typename RemoveCV::Type>::Type> -MakePair(A&& aA, B&& aB) -{ - return - Pair::Type>::Type, - typename RemoveCV::Type>::Type>( - Forward(aA), - Forward(aB)); -} - -} // namespace mozilla - -#endif /* mozilla_Pair_h */ diff --git a/ios/include/spidermonkey/mozilla/PodOperations.h b/ios/include/spidermonkey/mozilla/PodOperations.h deleted file mode 100644 index e6f4df21..00000000 --- a/ios/include/spidermonkey/mozilla/PodOperations.h +++ /dev/null @@ -1,196 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Operations for zeroing POD types, arrays, and so on. - * - * These operations are preferable to memset, memcmp, and the like because they - * don't require remembering to multiply by sizeof(T), array lengths, and so on - * everywhere. - */ - -#ifndef mozilla_PodOperations_h -#define mozilla_PodOperations_h - -#include "mozilla/Array.h" -#include "mozilla/ArrayUtils.h" -#include "mozilla/Attributes.h" - -#include -#include - -namespace mozilla { - -/** Set the contents of |aT| to 0. */ -template -static MOZ_ALWAYS_INLINE void -PodZero(T* aT) -{ - memset(aT, 0, sizeof(T)); -} - -/** Set the contents of |aNElem| elements starting at |aT| to 0. */ -template -static MOZ_ALWAYS_INLINE void -PodZero(T* aT, size_t aNElem) -{ - /* - * This function is often called with 'aNElem' small; we use an inline loop - * instead of calling 'memset' with a non-constant length. The compiler - * should inline the memset call with constant size, though. - */ - for (T* end = aT + aNElem; aT < end; aT++) { - memset(aT, 0, sizeof(T)); - } -} - -/* - * Arrays implicitly convert to pointers to their first element, which is - * dangerous when combined with the above PodZero definitions. Adding an - * overload for arrays is ambiguous, so we need another identifier. The - * ambiguous overload is left to catch mistaken uses of PodZero; if you get a - * compile error involving PodZero and array types, use PodArrayZero instead. - */ -template -static void PodZero(T (&aT)[N]) = delete; -template -static void PodZero(T (&aT)[N], size_t aNElem) = delete; - -/** Set the contents of the array |aT| to zero. */ -template -static MOZ_ALWAYS_INLINE void -PodArrayZero(T (&aT)[N]) -{ - memset(aT, 0, N * sizeof(T)); -} - -template -static MOZ_ALWAYS_INLINE void -PodArrayZero(Array& aArr) -{ - memset(&aArr[0], 0, N * sizeof(T)); -} - -/** - * Assign |*aSrc| to |*aDst|. The locations must not be the same and must not - * overlap. - */ -template -static MOZ_ALWAYS_INLINE void -PodAssign(T* aDst, const T* aSrc) -{ - MOZ_ASSERT(aDst + 1 <= aSrc || aSrc + 1 <= aDst, - "destination and source must not overlap"); - memcpy(reinterpret_cast(aDst), reinterpret_cast(aSrc), - sizeof(T)); -} - -/** - * Copy |aNElem| T elements from |aSrc| to |aDst|. The two memory ranges must - * not overlap! - */ -template -static MOZ_ALWAYS_INLINE void -PodCopy(T* aDst, const T* aSrc, size_t aNElem) -{ - MOZ_ASSERT(aDst + aNElem <= aSrc || aSrc + aNElem <= aDst, - "destination and source must not overlap"); - if (aNElem < 128) { - /* - * Avoid using operator= in this loop, as it may have been - * intentionally deleted by the POD type. - */ - for (const T* srcend = aSrc + aNElem; aSrc < srcend; aSrc++, aDst++) { - PodAssign(aDst, aSrc); - } - } else { - memcpy(aDst, aSrc, aNElem * sizeof(T)); - } -} - -template -static MOZ_ALWAYS_INLINE void -PodCopy(volatile T* aDst, const volatile T* aSrc, size_t aNElem) -{ - MOZ_ASSERT(aDst + aNElem <= aSrc || aSrc + aNElem <= aDst, - "destination and source must not overlap"); - - /* - * Volatile |aDst| requires extra work, because it's undefined behavior to - * modify volatile objects using the mem* functions. Just write out the - * loops manually, using operator= rather than memcpy for the same reason, - * and let the compiler optimize to the extent it can. - */ - for (const volatile T* srcend = aSrc + aNElem; - aSrc < srcend; - aSrc++, aDst++) { - *aDst = *aSrc; - } -} - -/* - * Copy the contents of the array |aSrc| into the array |aDst|, both of size N. - * The arrays must not overlap! - */ -template -static MOZ_ALWAYS_INLINE void -PodArrayCopy(T (&aDst)[N], const T (&aSrc)[N]) -{ - PodCopy(aDst, aSrc, N); -} - -/** - * Copy the memory for |aNElem| T elements from |aSrc| to |aDst|. If the two - * memory ranges overlap, then the effect is as if the |aNElem| elements are - * first copied from |aSrc| to a temporary array, and then from the temporary - * array to |aDst|. - */ -template -static MOZ_ALWAYS_INLINE void -PodMove(T* aDst, const T* aSrc, size_t aNElem) -{ - MOZ_ASSERT(aNElem <= SIZE_MAX / sizeof(T), - "trying to move an impossible number of elements"); - memmove(aDst, aSrc, aNElem * sizeof(T)); -} - -/** - * Determine whether the |len| elements at |one| are memory-identical to the - * |len| elements at |two|. - */ -template -static MOZ_ALWAYS_INLINE bool -PodEqual(const T* one, const T* two, size_t len) -{ - if (len < 128) { - const T* p1end = one + len; - const T* p1 = one; - const T* p2 = two; - for (; p1 < p1end; p1++, p2++) { - if (*p1 != *p2) { - return false; - } - } - return true; - } - - return !memcmp(one, two, len * sizeof(T)); -} - -/* - * Determine whether the |N| elements at |one| are memory-identical to the - * |N| elements at |two|. - */ -template -static MOZ_ALWAYS_INLINE bool -PodEqual(const T (&one)[N], const T (&two)[N]) -{ - return PodEqual(one, two, N); -} - -} // namespace mozilla - -#endif /* mozilla_PodOperations_h */ diff --git a/ios/include/spidermonkey/mozilla/Poison.h b/ios/include/spidermonkey/mozilla/Poison.h deleted file mode 100644 index aae56765..00000000 --- a/ios/include/spidermonkey/mozilla/Poison.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * A poison value that can be used to fill a memory space with - * an address that leads to a safe crash when dereferenced. - */ - -#ifndef mozilla_Poison_h -#define mozilla_Poison_h - -#include "mozilla/Assertions.h" -#include "mozilla/Types.h" - -#include - -MOZ_BEGIN_EXTERN_C - -extern MFBT_DATA uintptr_t gMozillaPoisonValue; - -/** - * @return the poison value. - */ -inline uintptr_t mozPoisonValue() -{ - return gMozillaPoisonValue; -} - -/** - * Overwrite the memory block of aSize bytes at aPtr with the poison value. - * aPtr MUST be aligned at a sizeof(uintptr_t) boundary. - * Only an even number of sizeof(uintptr_t) bytes are overwritten, the last - * few bytes (if any) is not overwritten. - */ -inline void mozWritePoison(void* aPtr, size_t aSize) -{ - const uintptr_t POISON = mozPoisonValue(); - char* p = (char*)aPtr; - char* limit = p + aSize; - MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); - MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); - for (; p < limit; p += sizeof(uintptr_t)) { - *((uintptr_t*)p) = POISON; - } -} - -/** - * Initialize the poison value. - * This should only be called once. - */ -extern MFBT_API void mozPoisonValueInit(); - -/* Values annotated by CrashReporter */ -extern MFBT_DATA uintptr_t gMozillaPoisonBase; -extern MFBT_DATA uintptr_t gMozillaPoisonSize; - -MOZ_END_EXTERN_C - -#if defined(__cplusplus) - -namespace mozilla { - -/** - * This class is designed to cause crashes when various kinds of memory - * corruption are observed. For instance, let's say we have a class C where we - * suspect out-of-bounds writes to some members. We can insert a member of type - * Poison near the members we suspect are being corrupted by out-of-bounds - * writes. Or perhaps we have a class K we suspect is subject to use-after-free - * violations, in which case it doesn't particularly matter where in the class - * we add the member of type Poison. - * - * In either case, we then insert calls to Check() throughout the code. Doing - * so enables us to narrow down the location where the corruption is occurring. - * A pleasant side-effect of these additional Check() calls is that crash - * signatures may become more regular, as crashes will ideally occur - * consolidated at the point of a Check(), rather than scattered about at - * various uses of the corrupted memory. - */ -class CorruptionCanary { -public: - CorruptionCanary() { - mValue = kCanarySet; - } - - ~CorruptionCanary() { - Check(); - mValue = mozPoisonValue(); - } - - void Check() const { - if (mValue != kCanarySet) { - MOZ_CRASH("Canary check failed, check lifetime"); - } - } - -private: - static const uintptr_t kCanarySet = 0x0f0b0f0b; - uintptr_t mValue; -}; - -} // mozilla - -#endif - -#endif /* mozilla_Poison_h */ diff --git a/ios/include/spidermonkey/mozilla/Range.h b/ios/include/spidermonkey/mozilla/Range.h deleted file mode 100644 index 47d91bb0..00000000 --- a/ios/include/spidermonkey/mozilla/Range.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_Range_h -#define mozilla_Range_h - -#include "mozilla/RangedPtr.h" -#include "mozilla/TypeTraits.h" - -#include - -namespace mozilla { - -// Range is a tuple containing a pointer and a length. -template -class Range -{ - const RangedPtr mStart; - const RangedPtr mEnd; - -public: - Range() : mStart(nullptr, 0), mEnd(nullptr, 0) {} - Range(T* aPtr, size_t aLength) - : mStart(aPtr, aPtr, aPtr + aLength), - mEnd(aPtr + aLength, aPtr, aPtr + aLength) - {} - Range(const RangedPtr& aStart, const RangedPtr& aEnd) - : mStart(aStart.get(), aStart.get(), aEnd.get()), - mEnd(aEnd.get(), aStart.get(), aEnd.get()) - { - // Only accept two RangedPtrs within the same range. - aStart.checkIdenticalRange(aEnd); - MOZ_ASSERT(aStart <= aEnd); - } - - template::value, - int>::Type> - MOZ_IMPLICIT Range(const Range& aOther) - : mStart(aOther.mStart), - mEnd(aOther.mEnd) - {} - - RangedPtr begin() const { return mStart; } - RangedPtr end() const { return mEnd; } - size_t length() const { return mEnd - mStart; } - - T& operator[](size_t aOffset) const { return mStart[aOffset]; } - - explicit operator bool() const { return mStart != nullptr; } -}; - -} // namespace mozilla - -#endif /* mozilla_Range_h */ diff --git a/ios/include/spidermonkey/mozilla/RangedArray.h b/ios/include/spidermonkey/mozilla/RangedArray.h deleted file mode 100644 index afe6267f..00000000 --- a/ios/include/spidermonkey/mozilla/RangedArray.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * A compile-time constant-length array, with bounds-checking assertions -- but - * unlike mozilla::Array, with indexes biased by a constant. - * - * Thus where mozilla::Array is a three-element array indexed by [0, 3), - * mozilla::RangedArray is a three-element array indexed by [8, 11). - */ - -#ifndef mozilla_RangedArray_h -#define mozilla_RangedArray_h - -#include "mozilla/Array.h" - -namespace mozilla { - -template -class RangedArray -{ -private: - typedef Array ArrayType; - ArrayType mArr; - -public: - T& operator[](size_t aIndex) - { - MOZ_ASSERT(aIndex == MinIndex || aIndex > MinIndex); - return mArr[aIndex - MinIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(aIndex == MinIndex || aIndex > MinIndex); - return mArr[aIndex - MinIndex]; - } - - typedef typename ArrayType::iterator iterator; - typedef typename ArrayType::const_iterator const_iterator; - typedef typename ArrayType::reverse_iterator reverse_iterator; - typedef typename ArrayType::const_reverse_iterator const_reverse_iterator; - - // Methods for range-based for loops. - iterator begin() { return mArr.begin(); } - const_iterator begin() const { return mArr.begin(); } - const_iterator cbegin() const { return mArr.cbegin(); } - iterator end() { return mArr.end(); } - const_iterator end() const { return mArr.end(); } - const_iterator cend() const { return mArr.cend(); } - - // Methods for reverse iterating. - reverse_iterator rbegin() { return mArr.rbegin(); } - const_reverse_iterator rbegin() const { return mArr.rbegin(); } - const_reverse_iterator crbegin() const { return mArr.crbegin(); } - reverse_iterator rend() { return mArr.rend(); } - const_reverse_iterator rend() const { return mArr.rend(); } - const_reverse_iterator crend() const { return mArr.crend(); } -}; - -} // namespace mozilla - -#endif // mozilla_RangedArray_h diff --git a/ios/include/spidermonkey/mozilla/RangedPtr.h b/ios/include/spidermonkey/mozilla/RangedPtr.h deleted file mode 100644 index a07c1f4f..00000000 --- a/ios/include/spidermonkey/mozilla/RangedPtr.h +++ /dev/null @@ -1,292 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements a smart pointer asserted to remain within a range specified at - * construction. - */ - -#ifndef mozilla_RangedPtr_h -#define mozilla_RangedPtr_h - -#include "mozilla/ArrayUtils.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#include - -namespace mozilla { - -/* - * RangedPtr is a smart pointer restricted to an address range specified at - * creation. The pointer (and any smart pointers derived from it) must remain - * within the range [start, end] (inclusive of end to facilitate use as - * sentinels). Dereferencing or indexing into the pointer (or pointers derived - * from it) must remain within the range [start, end). All the standard pointer - * operators are defined on it; in debug builds these operations assert that the - * range specified at construction is respected. - * - * In theory passing a smart pointer instance as an argument can be slightly - * slower than passing a T* (due to ABI requirements for passing structs versus - * passing pointers), if the method being called isn't inlined. If you are in - * extremely performance-critical code, you may want to be careful using this - * smart pointer as an argument type. - * - * RangedPtr intentionally does not implicitly convert to T*. Use get() to - * explicitly convert to T*. Keep in mind that the raw pointer of course won't - * implement bounds checking in debug builds. - */ -template -class RangedPtr -{ - T* mPtr; - -#ifdef DEBUG - T* const mRangeStart; - T* const mRangeEnd; -#endif - - void checkSanity() - { - MOZ_ASSERT(mRangeStart <= mPtr); - MOZ_ASSERT(mPtr <= mRangeEnd); - } - - /* Creates a new pointer for |aPtr|, restricted to this pointer's range. */ - RangedPtr create(T* aPtr) const - { -#ifdef DEBUG - return RangedPtr(aPtr, mRangeStart, mRangeEnd); -#else - return RangedPtr(aPtr, nullptr, size_t(0)); -#endif - } - - uintptr_t asUintptr() const { return reinterpret_cast(mPtr); } - -public: - RangedPtr(T* aPtr, T* aStart, T* aEnd) - : mPtr(aPtr) -#ifdef DEBUG - , mRangeStart(aStart), mRangeEnd(aEnd) -#endif - { - MOZ_ASSERT(mRangeStart <= mRangeEnd); - checkSanity(); - } - RangedPtr(T* aPtr, T* aStart, size_t aLength) - : mPtr(aPtr) -#ifdef DEBUG - , mRangeStart(aStart), mRangeEnd(aStart + aLength) -#endif - { - MOZ_ASSERT(aLength <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(reinterpret_cast(mRangeStart) + aLength * sizeof(T) >= - reinterpret_cast(mRangeStart)); - checkSanity(); - } - - /* Equivalent to RangedPtr(aPtr, aPtr, aLength). */ - RangedPtr(T* aPtr, size_t aLength) - : mPtr(aPtr) -#ifdef DEBUG - , mRangeStart(aPtr), mRangeEnd(aPtr + aLength) -#endif - { - MOZ_ASSERT(aLength <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(reinterpret_cast(mRangeStart) + aLength * sizeof(T) >= - reinterpret_cast(mRangeStart)); - checkSanity(); - } - - /* Equivalent to RangedPtr(aArr, aArr, N). */ - template - explicit RangedPtr(T (&aArr)[N]) - : mPtr(aArr) -#ifdef DEBUG - , mRangeStart(aArr), mRangeEnd(aArr + N) -#endif - { - checkSanity(); - } - - T* get() const { return mPtr; } - - explicit operator bool() const { return mPtr != nullptr; } - - void checkIdenticalRange(const RangedPtr& aOther) const - { - MOZ_ASSERT(mRangeStart == aOther.mRangeStart); - MOZ_ASSERT(mRangeEnd == aOther.mRangeEnd); - } - - /* - * You can only assign one RangedPtr into another if the two pointers have - * the same valid range: - * - * char arr1[] = "hi"; - * char arr2[] = "bye"; - * RangedPtr p1(arr1, 2); - * p1 = RangedPtr(arr1 + 1, arr1, arr1 + 2); // works - * p1 = RangedPtr(arr2, 3); // asserts - */ - RangedPtr& operator=(const RangedPtr& aOther) - { - checkIdenticalRange(aOther); - mPtr = aOther.mPtr; - checkSanity(); - return *this; - } - - RangedPtr operator+(size_t aInc) const - { - MOZ_ASSERT(aInc <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(asUintptr() + aInc * sizeof(T) >= asUintptr()); - return create(mPtr + aInc); - } - - RangedPtr operator-(size_t aDec) const - { - MOZ_ASSERT(aDec <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(asUintptr() - aDec * sizeof(T) <= asUintptr()); - return create(mPtr - aDec); - } - - /* - * You can assign a raw pointer into a RangedPtr if the raw pointer is - * within the range specified at creation. - */ - template - RangedPtr& operator=(U* aPtr) - { - *this = create(aPtr); - return *this; - } - - template - RangedPtr& operator=(const RangedPtr& aPtr) - { - MOZ_ASSERT(mRangeStart <= aPtr.mPtr); - MOZ_ASSERT(aPtr.mPtr <= mRangeEnd); - mPtr = aPtr.mPtr; - checkSanity(); - return *this; - } - - RangedPtr& operator++() - { - return (*this += 1); - } - - RangedPtr operator++(int) - { - RangedPtr rcp = *this; - ++*this; - return rcp; - } - - RangedPtr& operator--() - { - return (*this -= 1); - } - - RangedPtr operator--(int) - { - RangedPtr rcp = *this; - --*this; - return rcp; - } - - RangedPtr& operator+=(size_t aInc) - { - *this = *this + aInc; - return *this; - } - - RangedPtr& operator-=(size_t aDec) - { - *this = *this - aDec; - return *this; - } - - T& operator[](int aIndex) const - { - MOZ_ASSERT(size_t(aIndex > 0 ? aIndex : -aIndex) <= size_t(-1) / sizeof(T)); - return *create(mPtr + aIndex); - } - - T& operator*() const - { - MOZ_ASSERT(mPtr >= mRangeStart); - MOZ_ASSERT(mPtr < mRangeEnd); - return *mPtr; - } - - T* operator->() const - { - MOZ_ASSERT(mPtr >= mRangeStart); - MOZ_ASSERT(mPtr < mRangeEnd); - return mPtr; - } - - template - bool operator==(const RangedPtr& aOther) const - { - return mPtr == aOther.mPtr; - } - template - bool operator!=(const RangedPtr& aOther) const - { - return !(*this == aOther); - } - - template - bool operator==(const U* u) const - { - return mPtr == u; - } - template - bool operator!=(const U* u) const - { - return !(*this == u); - } - - template - bool operator<(const RangedPtr& aOther) const - { - return mPtr < aOther.mPtr; - } - template - bool operator<=(const RangedPtr& aOther) const - { - return mPtr <= aOther.mPtr; - } - - template - bool operator>(const RangedPtr& aOther) const - { - return mPtr > aOther.mPtr; - } - template - bool operator>=(const RangedPtr& aOther) const - { - return mPtr >= aOther.mPtr; - } - - size_t operator-(const RangedPtr& aOther) const - { - MOZ_ASSERT(mPtr >= aOther.mPtr); - return PointerRangeSize(aOther.mPtr, mPtr); - } - -private: - RangedPtr() = delete; - T* operator&() = delete; -}; - -} /* namespace mozilla */ - -#endif /* mozilla_RangedPtr_h */ diff --git a/ios/include/spidermonkey/mozilla/ReentrancyGuard.h b/ios/include/spidermonkey/mozilla/ReentrancyGuard.h deleted file mode 100644 index 9963974e..00000000 --- a/ios/include/spidermonkey/mozilla/ReentrancyGuard.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Small helper class for asserting uses of a class are non-reentrant. */ - -#ifndef mozilla_ReentrancyGuard_h -#define mozilla_ReentrancyGuard_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/GuardObjects.h" - -namespace mozilla { - -/* Useful for implementing containers that assert non-reentrancy */ -class MOZ_RAII ReentrancyGuard -{ - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -#ifdef DEBUG - bool& mEntered; -#endif - -public: - template -#ifdef DEBUG - explicit ReentrancyGuard(T& aObj - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mEntered(aObj.mEntered) -#else - explicit ReentrancyGuard(T& - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) -#endif - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; -#ifdef DEBUG - MOZ_ASSERT(!mEntered); - mEntered = true; -#endif - } - ~ReentrancyGuard() - { -#ifdef DEBUG - mEntered = false; -#endif - } - -private: - ReentrancyGuard(const ReentrancyGuard&) = delete; - void operator=(const ReentrancyGuard&) = delete; -}; - -} // namespace mozilla - -#endif /* mozilla_ReentrancyGuard_h */ diff --git a/ios/include/spidermonkey/mozilla/RefCountType.h b/ios/include/spidermonkey/mozilla/RefCountType.h deleted file mode 100644 index e95a22a0..00000000 --- a/ios/include/spidermonkey/mozilla/RefCountType.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_RefCountType_h -#define mozilla_RefCountType_h - -#include - -/** - * MozRefCountType is Mozilla's reference count type. - * - * We use the same type to represent the refcount of RefCounted objects - * as well, in order to be able to use the leak detection facilities - * that are implemented by XPCOM. - * - * Note that this type is not in the mozilla namespace so that it is - * usable for both C and C++ code. - */ -typedef uintptr_t MozRefCountType; - -/* - * This is the return type for AddRef() and Release() in nsISupports. - * IUnknown of COM returns an unsigned long from equivalent functions. - * - * The following ifdef exists to maintain binary compatibility with - * IUnknown, the base interface in Microsoft COM. - */ -#ifdef XP_WIN -typedef unsigned long MozExternalRefCountType; -#else -typedef uint32_t MozExternalRefCountType; -#endif - -#endif diff --git a/ios/include/spidermonkey/mozilla/RefCounted.h b/ios/include/spidermonkey/mozilla/RefCounted.h deleted file mode 100644 index ae05f1e0..00000000 --- a/ios/include/spidermonkey/mozilla/RefCounted.h +++ /dev/null @@ -1,210 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* CRTP refcounting templates. Do not use unless you are an Expert. */ - -#ifndef mozilla_RefCounted_h -#define mozilla_RefCounted_h - -#include "mozilla/AlreadyAddRefed.h" -#include "mozilla/Assertions.h" -#include "mozilla/Atomics.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/RefCountType.h" -#include "mozilla/TypeTraits.h" - -#if defined(MOZILLA_INTERNAL_API) -#include "nsXPCOM.h" -#endif - -#if defined(MOZILLA_INTERNAL_API) && \ - (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING)) -#define MOZ_REFCOUNTED_LEAK_CHECKING -#endif - -namespace mozilla { - -/** - * RefCounted is a sort of a "mixin" for a class T. RefCounted - * manages, well, refcounting for T, and because RefCounted is - * parameterized on T, RefCounted can call T's destructor directly. - * This means T doesn't need to have a virtual dtor and so doesn't - * need a vtable. - * - * RefCounted is created with refcount == 0. Newly-allocated - * RefCounted must immediately be assigned to a RefPtr to make the - * refcount > 0. It's an error to allocate and free a bare - * RefCounted, i.e. outside of the RefPtr machinery. Attempts to - * do so will abort DEBUG builds. - * - * Live RefCounted have refcount > 0. The lifetime (refcounts) of - * live RefCounted are controlled by RefPtr and - * RefPtr. Upon a transition from refcounted==1 - * to 0, the RefCounted "dies" and is destroyed. The "destroyed" - * state is represented in DEBUG builds by refcount==0xffffdead. This - * state distinguishes use-before-ref (refcount==0) from - * use-after-destroy (refcount==0xffffdead). - * - * Note that when deriving from RefCounted or AtomicRefCounted, you - * should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public - * section of your class, where ClassName is the name of your class. - */ -namespace detail { -const MozRefCountType DEAD = 0xffffdead; - -// When building code that gets compiled into Gecko, try to use the -// trace-refcount leak logging facilities. -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING -class RefCountLogger -{ -public: - static void logAddRef(const void* aPointer, MozRefCountType aRefCount, - const char* aTypeName, uint32_t aInstanceSize) - { - MOZ_ASSERT(aRefCount != DEAD); - NS_LogAddRef(const_cast(aPointer), aRefCount, aTypeName, - aInstanceSize); - } - - static void logRelease(const void* aPointer, MozRefCountType aRefCount, - const char* aTypeName) - { - MOZ_ASSERT(aRefCount != DEAD); - NS_LogRelease(const_cast(aPointer), aRefCount, aTypeName); - } -}; -#endif - -// This is used WeakPtr.h as well as this file. -enum RefCountAtomicity -{ - AtomicRefCount, - NonAtomicRefCount -}; - -template -class RefCounted -{ -protected: - RefCounted() : mRefCnt(0) {} - ~RefCounted() { MOZ_ASSERT(mRefCnt == detail::DEAD); } - -public: - // Compatibility with nsRefPtr. - void AddRef() const - { - // Note: this method must be thread safe for AtomicRefCounted. - MOZ_ASSERT(int32_t(mRefCnt) >= 0); -#ifndef MOZ_REFCOUNTED_LEAK_CHECKING - ++mRefCnt; -#else - const char* type = static_cast(this)->typeName(); - uint32_t size = static_cast(this)->typeSize(); - const void* ptr = static_cast(this); - MozRefCountType cnt = ++mRefCnt; - detail::RefCountLogger::logAddRef(ptr, cnt, type, size); -#endif - } - - void Release() const - { - // Note: this method must be thread safe for AtomicRefCounted. - MOZ_ASSERT(int32_t(mRefCnt) > 0); -#ifndef MOZ_REFCOUNTED_LEAK_CHECKING - MozRefCountType cnt = --mRefCnt; -#else - const char* type = static_cast(this)->typeName(); - const void* ptr = static_cast(this); - MozRefCountType cnt = --mRefCnt; - // Note: it's not safe to touch |this| after decrementing the refcount, - // except for below. - detail::RefCountLogger::logRelease(ptr, cnt, type); -#endif - if (0 == cnt) { - // Because we have atomically decremented the refcount above, only - // one thread can get a 0 count here, so as long as we can assume that - // everything else in the system is accessing this object through - // RefPtrs, it's safe to access |this| here. -#ifdef DEBUG - mRefCnt = detail::DEAD; -#endif - delete static_cast(this); - } - } - - // Compatibility with wtf::RefPtr. - void ref() { AddRef(); } - void deref() { Release(); } - MozRefCountType refCount() const { return mRefCnt; } - bool hasOneRef() const - { - MOZ_ASSERT(mRefCnt > 0); - return mRefCnt == 1; - } - -private: - mutable typename Conditional, - MozRefCountType>::Type mRefCnt; -}; - -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING -// Passing override for the optional argument marks the typeName and -// typeSize functions defined by this macro as overrides. -#define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \ - virtual const char* typeName() const __VA_ARGS__ { return #T; } \ - virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); } -#else -#define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) -#endif - -// Note that this macro is expanded unconditionally because it declares only -// two small inline functions which will hopefully get eliminated by the linker -// in non-leak-checking builds. -#define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \ - const char* typeName() const { return #T; } \ - size_t typeSize() const { return sizeof(*this); } - -} // namespace detail - -template -class RefCounted : public detail::RefCounted -{ -public: - ~RefCounted() - { - static_assert(IsBaseOf::value, - "T must derive from RefCounted"); - } -}; - -namespace external { - -/** - * AtomicRefCounted is like RefCounted, with an atomically updated - * reference counter. - * - * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING - * instead. - */ -template -class AtomicRefCounted : - public mozilla::detail::RefCounted -{ -public: - ~AtomicRefCounted() - { - static_assert(IsBaseOf::value, - "T must derive from AtomicRefCounted"); - } -}; - -} // namespace external - -} // namespace mozilla - -#endif // mozilla_RefCounted_h diff --git a/ios/include/spidermonkey/mozilla/RefPtr.h b/ios/include/spidermonkey/mozilla/RefPtr.h deleted file mode 100644 index bfa8f6e0..00000000 --- a/ios/include/spidermonkey/mozilla/RefPtr.h +++ /dev/null @@ -1,656 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_RefPtr_h -#define mozilla_RefPtr_h - -#include "mozilla/AlreadyAddRefed.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -/*****************************************************************************/ - -// template class RefPtrGetterAddRefs; - -class nsCOMPtr_helper; - -namespace mozilla { -template class OwningNonNull; -template class StaticRefPtr; - -// Traditionally, RefPtr supports automatic refcounting of any pointer type -// with AddRef() and Release() methods that follow the traditional semantics. -// -// This traits class can be specialized to operate on other pointer types. For -// example, we specialize this trait for opaque FFI types that represent -// refcounted objects in Rust. -// -// Given the use of ConstRemovingRefPtrTraits below, U should not be a const- -// qualified type. -template -struct RefPtrTraits -{ - static void AddRef(U* aPtr) { - aPtr->AddRef(); - } - static void Release(U* aPtr) { - aPtr->Release(); - } -}; - -} // namespace mozilla - -template -class RefPtr -{ -private: - void - assign_with_AddRef(T* aRawPtr) - { - if (aRawPtr) { - ConstRemovingRefPtrTraits::AddRef(aRawPtr); - } - assign_assuming_AddRef(aRawPtr); - } - - void - assign_assuming_AddRef(T* aNewPtr) - { - T* oldPtr = mRawPtr; - mRawPtr = aNewPtr; - if (oldPtr) { - ConstRemovingRefPtrTraits::Release(oldPtr); - } - } - -private: - T* MOZ_OWNING_REF mRawPtr; - -public: - typedef T element_type; - - ~RefPtr() - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::Release(mRawPtr); - } - } - - // Constructors - - RefPtr() - : mRawPtr(nullptr) - // default constructor - { - } - - RefPtr(const RefPtr& aSmartPtr) - : mRawPtr(aSmartPtr.mRawPtr) - // copy-constructor - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::AddRef(mRawPtr); - } - } - - RefPtr(RefPtr&& aRefPtr) - : mRawPtr(aRefPtr.mRawPtr) - { - aRefPtr.mRawPtr = nullptr; - } - - // construct from a raw pointer (of the right type) - - MOZ_IMPLICIT RefPtr(T* aRawPtr) - : mRawPtr(aRawPtr) - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::AddRef(mRawPtr); - } - } - - MOZ_IMPLICIT RefPtr(decltype(nullptr)) - : mRawPtr(nullptr) - { - } - - template - MOZ_IMPLICIT RefPtr(already_AddRefed& aSmartPtr) - : mRawPtr(aSmartPtr.take()) - // construct from |already_AddRefed| - { - } - - template - MOZ_IMPLICIT RefPtr(already_AddRefed&& aSmartPtr) - : mRawPtr(aSmartPtr.take()) - // construct from |otherRefPtr.forget()| - { - } - - template - MOZ_IMPLICIT RefPtr(const RefPtr& aSmartPtr) - : mRawPtr(aSmartPtr.get()) - // copy-construct from a smart pointer with a related pointer type - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::AddRef(mRawPtr); - } - } - - template - MOZ_IMPLICIT RefPtr(RefPtr&& aSmartPtr) - : mRawPtr(aSmartPtr.forget().take()) - // construct from |Move(RefPtr)|. - { - } - - MOZ_IMPLICIT RefPtr(const nsCOMPtr_helper& aHelper); - - // Defined in OwningNonNull.h - template - MOZ_IMPLICIT RefPtr(const mozilla::OwningNonNull& aOther); - - // Defined in StaticPtr.h - template - MOZ_IMPLICIT RefPtr(const mozilla::StaticRefPtr& aOther); - - // Assignment operators - - RefPtr& - operator=(decltype(nullptr)) - { - assign_assuming_AddRef(nullptr); - return *this; - } - - RefPtr& - operator=(const RefPtr& aRhs) - // copy assignment operator - { - assign_with_AddRef(aRhs.mRawPtr); - return *this; - } - - template - RefPtr& - operator=(const RefPtr& aRhs) - // assign from an RefPtr of a related pointer type - { - assign_with_AddRef(aRhs.get()); - return *this; - } - - RefPtr& - operator=(T* aRhs) - // assign from a raw pointer (of the right type) - { - assign_with_AddRef(aRhs); - return *this; - } - - template - RefPtr& - operator=(already_AddRefed& aRhs) - // assign from |already_AddRefed| - { - assign_assuming_AddRef(aRhs.take()); - return *this; - } - - template - RefPtr& - operator=(already_AddRefed && aRhs) - // assign from |otherRefPtr.forget()| - { - assign_assuming_AddRef(aRhs.take()); - return *this; - } - - RefPtr& operator=(const nsCOMPtr_helper& aHelper); - - RefPtr& - operator=(RefPtr && aRefPtr) - { - assign_assuming_AddRef(aRefPtr.mRawPtr); - aRefPtr.mRawPtr = nullptr; - return *this; - } - - // Defined in OwningNonNull.h - template - RefPtr& - operator=(const mozilla::OwningNonNull& aOther); - - // Defined in StaticPtr.h - template - RefPtr& - operator=(const mozilla::StaticRefPtr& aOther); - - // Other pointer operators - - void - swap(RefPtr& aRhs) - // ...exchange ownership with |aRhs|; can save a pair of refcount operations - { - T* temp = aRhs.mRawPtr; - aRhs.mRawPtr = mRawPtr; - mRawPtr = temp; - } - - void - swap(T*& aRhs) - // ...exchange ownership with |aRhs|; can save a pair of refcount operations - { - T* temp = aRhs; - aRhs = mRawPtr; - mRawPtr = temp; - } - - already_AddRefed - forget() - // return the value of mRawPtr and null out mRawPtr. Useful for - // already_AddRefed return values. - { - T* temp = nullptr; - swap(temp); - return already_AddRefed(temp); - } - - template - void - forget(I** aRhs) - // Set the target of aRhs to the value of mRawPtr and null out mRawPtr. - // Useful to avoid unnecessary AddRef/Release pairs with "out" - // parameters where aRhs bay be a T** or an I** where I is a base class - // of T. - { - MOZ_ASSERT(aRhs, "Null pointer passed to forget!"); - *aRhs = mRawPtr; - mRawPtr = nullptr; - } - - T* - get() const - /* - Prefer the implicit conversion provided automatically by |operator T*() const|. - Use |get()| to resolve ambiguity or to get a castable pointer. - */ - { - return const_cast(mRawPtr); - } - - operator T*() const -#ifdef MOZ_HAVE_REF_QUALIFIERS - & -#endif - /* - ...makes an |RefPtr| act like its underlying raw pointer type whenever it - is used in a context where a raw pointer is expected. It is this operator - that makes an |RefPtr| substitutable for a raw pointer. - - Prefer the implicit use of this operator to calling |get()|, except where - necessary to resolve ambiguity. - */ - { - return get(); - } - -#ifdef MOZ_HAVE_REF_QUALIFIERS - // Don't allow implicit conversion of temporary RefPtr to raw pointer, - // because the refcount might be one and the pointer will immediately become - // invalid. - operator T*() const && = delete; - - // These are needed to avoid the deleted operator above. XXX Why is operator! - // needed separately? Shouldn't the compiler prefer using the non-deleted - // operator bool instead of the deleted operator T*? - explicit operator bool() const { return !!mRawPtr; } - bool operator!() const { return !mRawPtr; } -#endif - - T* - operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN - { - MOZ_ASSERT(mRawPtr != nullptr, - "You can't dereference a NULL RefPtr with operator->()."); - return get(); - } - - template - class Proxy - { - typedef R (T::*member_function)(Args...); - T* mRawPtr; - member_function mFunction; - public: - Proxy(T* aRawPtr, member_function aFunction) - : mRawPtr(aRawPtr), - mFunction(aFunction) - { - } - template - R operator()(ActualArgs&&... aArgs) - { - return ((*mRawPtr).*mFunction)(mozilla::Forward(aArgs)...); - } - }; - - template - Proxy operator->*(R (T::*aFptr)(Args...)) const - { - MOZ_ASSERT(mRawPtr != nullptr, - "You can't dereference a NULL RefPtr with operator->*()."); - return Proxy(get(), aFptr); - } - - RefPtr* - get_address() - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } - - const RefPtr* - get_address() const - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } - -public: - T& - operator*() const - { - MOZ_ASSERT(mRawPtr != nullptr, - "You can't dereference a NULL RefPtr with operator*()."); - return *get(); - } - - T** - StartAssignment() - { - assign_assuming_AddRef(nullptr); - return reinterpret_cast(&mRawPtr); - } -private: - // This helper class makes |RefPtr| possible by casting away - // the constness from the pointer when calling AddRef() and Release(). - // - // This is necessary because AddRef() and Release() implementations can't - // generally expected to be const themselves (without heavy use of |mutable| - // and |const_cast| in their own implementations). - // - // This should be sound because while |RefPtr| provides a - // const view of an object, the object itself should not be const (it - // would have to be allocated as |new const T| or similar to be const). - template - struct ConstRemovingRefPtrTraits - { - static void AddRef(U* aPtr) { - mozilla::RefPtrTraits::AddRef(aPtr); - } - static void Release(U* aPtr) { - mozilla::RefPtrTraits::Release(aPtr); - } - }; - template - struct ConstRemovingRefPtrTraits - { - static void AddRef(const U* aPtr) { - mozilla::RefPtrTraits::AddRef(const_cast(aPtr)); - } - static void Release(const U* aPtr) { - mozilla::RefPtrTraits::Release(const_cast(aPtr)); - } - }; -}; - -class nsCycleCollectionTraversalCallback; -template -void -CycleCollectionNoteChild(nsCycleCollectionTraversalCallback& aCallback, - T* aChild, const char* aName, uint32_t aFlags); - -template -inline void -ImplCycleCollectionUnlink(RefPtr& aField) -{ - aField = nullptr; -} - -template -inline void -ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback, - RefPtr& aField, - const char* aName, - uint32_t aFlags = 0) -{ - CycleCollectionNoteChild(aCallback, aField.get(), aName, aFlags); -} - -template -inline RefPtr* -address_of(RefPtr& aPtr) -{ - return aPtr.get_address(); -} - -template -inline const RefPtr* -address_of(const RefPtr& aPtr) -{ - return aPtr.get_address(); -} - -template -class RefPtrGetterAddRefs -/* - ... - - This class is designed to be used for anonymous temporary objects in the - argument list of calls that return COM interface pointers, e.g., - - RefPtr fooP; - ...->GetAddRefedPointer(getter_AddRefs(fooP)) - - DO NOT USE THIS TYPE DIRECTLY IN YOUR CODE. Use |getter_AddRefs()| instead. - - When initialized with a |RefPtr|, as in the example above, it returns - a |void**|, a |T**|, or an |nsISupports**| as needed, that the - outer call (|GetAddRefedPointer| in this case) can fill in. - - This type should be a nested class inside |RefPtr|. -*/ -{ -public: - explicit - RefPtrGetterAddRefs(RefPtr& aSmartPtr) - : mTargetSmartPtr(aSmartPtr) - { - // nothing else to do - } - - operator void**() - { - return reinterpret_cast(mTargetSmartPtr.StartAssignment()); - } - - operator T**() - { - return mTargetSmartPtr.StartAssignment(); - } - - T*& - operator*() - { - return *(mTargetSmartPtr.StartAssignment()); - } - -private: - RefPtr& mTargetSmartPtr; -}; - -template -inline RefPtrGetterAddRefs -getter_AddRefs(RefPtr& aSmartPtr) -/* - Used around a |RefPtr| when - ...makes the class |RefPtrGetterAddRefs| invisible. -*/ -{ - return RefPtrGetterAddRefs(aSmartPtr); -} - - -// Comparing two |RefPtr|s - -template -inline bool -operator==(const RefPtr& aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs.get()) == static_cast(aRhs.get()); -} - - -template -inline bool -operator!=(const RefPtr& aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs.get()) != static_cast(aRhs.get()); -} - - -// Comparing an |RefPtr| to a raw pointer - -template -inline bool -operator==(const RefPtr& aLhs, const U* aRhs) -{ - return static_cast(aLhs.get()) == static_cast(aRhs); -} - -template -inline bool -operator==(const U* aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs) == static_cast(aRhs.get()); -} - -template -inline bool -operator!=(const RefPtr& aLhs, const U* aRhs) -{ - return static_cast(aLhs.get()) != static_cast(aRhs); -} - -template -inline bool -operator!=(const U* aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs) != static_cast(aRhs.get()); -} - -template -inline bool -operator==(const RefPtr& aLhs, U* aRhs) -{ - return static_cast(aLhs.get()) == const_cast(aRhs); -} - -template -inline bool -operator==(U* aLhs, const RefPtr& aRhs) -{ - return const_cast(aLhs) == static_cast(aRhs.get()); -} - -template -inline bool -operator!=(const RefPtr& aLhs, U* aRhs) -{ - return static_cast(aLhs.get()) != const_cast(aRhs); -} - -template -inline bool -operator!=(U* aLhs, const RefPtr& aRhs) -{ - return const_cast(aLhs) != static_cast(aRhs.get()); -} - -// Comparing an |RefPtr| to |nullptr| - -template -inline bool -operator==(const RefPtr& aLhs, decltype(nullptr)) -{ - return aLhs.get() == nullptr; -} - -template -inline bool -operator==(decltype(nullptr), const RefPtr& aRhs) -{ - return nullptr == aRhs.get(); -} - -template -inline bool -operator!=(const RefPtr& aLhs, decltype(nullptr)) -{ - return aLhs.get() != nullptr; -} - -template -inline bool -operator!=(decltype(nullptr), const RefPtr& aRhs) -{ - return nullptr != aRhs.get(); -} - -/*****************************************************************************/ - -template -inline already_AddRefed -do_AddRef(T* aObj) -{ - RefPtr ref(aObj); - return ref.forget(); -} - -template -inline already_AddRefed -do_AddRef(const RefPtr& aObj) -{ - RefPtr ref(aObj); - return ref.forget(); -} - -namespace mozilla { - -/** - * Helper function to be able to conveniently write things like: - * - * already_AddRefed - * f(...) - * { - * return MakeAndAddRef(...); - * } - */ -template -already_AddRefed -MakeAndAddRef(Args&&... aArgs) -{ - RefPtr p(new T(Forward(aArgs)...)); - return p.forget(); -} - -} // namespace mozilla - -#endif /* mozilla_RefPtr_h */ diff --git a/ios/include/spidermonkey/mozilla/ReverseIterator.h b/ios/include/spidermonkey/mozilla/ReverseIterator.h deleted file mode 100644 index 49c2e279..00000000 --- a/ios/include/spidermonkey/mozilla/ReverseIterator.h +++ /dev/null @@ -1,168 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* An iterator that acts like another iterator, but iterating in - * the negative direction. (Note that not all iterators can iterate - * in the negative direction.) */ - -#ifndef mozilla_ReverseIterator_h -#define mozilla_ReverseIterator_h - -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -template -class ReverseIterator -{ -public: - template - explicit ReverseIterator(Iterator aIter) - : mCurrent(aIter) { } - - template - MOZ_IMPLICIT ReverseIterator(const ReverseIterator& aOther) - : mCurrent(aOther.mCurrent) { } - - decltype(*DeclVal()) operator*() const - { - IteratorT tmp = mCurrent; - return *--tmp; - } - - /* Increments and decrements operators */ - - ReverseIterator& operator++() { --mCurrent; return *this; } - ReverseIterator& operator--() { ++mCurrent; return *this; } - ReverseIterator operator++(int) { auto ret = *this; mCurrent--; return ret; } - ReverseIterator operator--(int) { auto ret = *this; mCurrent++; return ret; } - - /* Comparison operators */ - - template - friend bool operator==(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator!=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator<(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator<=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator>(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator>=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - -private: - IteratorT mCurrent; -}; - -template -bool -operator==(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent == aIter2.mCurrent; -} - -template -bool -operator!=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent != aIter2.mCurrent; -} - -template -bool -operator<(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent > aIter2.mCurrent; -} - -template -bool -operator<=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent >= aIter2.mCurrent; -} - -template -bool -operator>(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent < aIter2.mCurrent; -} - -template -bool -operator>=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent <= aIter2.mCurrent; -} - -namespace detail { - -template -class IteratorRange -{ -public: - typedef IteratorT iterator; - typedef IteratorT const_iterator; - typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; - - template - MOZ_IMPLICIT IteratorRange(Iterator1 aIterBegin, Iterator2 aIterEnd) - : mIterBegin(aIterBegin), mIterEnd(aIterEnd) { } - - template - MOZ_IMPLICIT IteratorRange(const IteratorRange& aOther) - : mIterBegin(aOther.mIterBegin), mIterEnd(aOther.mIterEnd) { } - - iterator begin() const { return mIterBegin; } - const_iterator cbegin() const { return begin(); } - iterator end() const { return mIterEnd; } - const_iterator cend() const { return end(); } - reverse_iterator rbegin() const { return reverse_iterator(mIterEnd); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() const { return reverse_iterator(mIterBegin); } - const_reverse_iterator crend() const { return rend(); } - -private: - IteratorT mIterBegin; - IteratorT mIterEnd; -}; - -} // namespace detail - -template -detail::IteratorRange -Reversed(Range& aRange) -{ - return {aRange.rbegin(), aRange.rend()}; -} - -template -detail::IteratorRange -Reversed(const Range& aRange) -{ - return {aRange.rbegin(), aRange.rend()}; -} - -} // namespace mozilla - -#endif // mozilla_ReverseIterator_h diff --git a/ios/include/spidermonkey/mozilla/RollingMean.h b/ios/include/spidermonkey/mozilla/RollingMean.h deleted file mode 100644 index 8cc3148e..00000000 --- a/ios/include/spidermonkey/mozilla/RollingMean.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A set abstraction for enumeration values. */ - -#ifndef mozilla_RollingMean_h_ -#define mozilla_RollingMean_h_ - -#include "mozilla/Assertions.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Vector.h" - -#include - -namespace mozilla { - -/** - * RollingMean calculates a rolling mean of the values it is given. It - * accumulates the total as values are added and removed. The second type - * argument S specifies the type of the total. This may need to be a bigger - * type in order to maintain that the sum of all values in the average doesn't - * exceed the maximum input value. - * - * WARNING: Float types are not supported due to rounding errors. - */ -template -class RollingMean -{ -private: - size_t mInsertIndex; - size_t mMaxValues; - Vector mValues; - S mTotal; - -public: - static_assert(!IsFloatingPoint::value, - "floating-point types are unsupported due to rounding " - "errors"); - - explicit RollingMean(size_t aMaxValues) - : mInsertIndex(0), - mMaxValues(aMaxValues), - mTotal(0) - { - MOZ_ASSERT(aMaxValues > 0); - } - - RollingMean& operator=(RollingMean&& aOther) - { - MOZ_ASSERT(this != &aOther, "self-assignment is forbidden"); - this->~RollingMean(); - new(this) RollingMean(aOther.mMaxValues); - mInsertIndex = aOther.mInsertIndex; - mTotal = aOther.mTotal; - mValues.swap(aOther.mValues); - return *this; - } - - /** - * Insert a value into the rolling mean. - */ - bool insert(T aValue) - { - MOZ_ASSERT(mValues.length() <= mMaxValues); - - if (mValues.length() == mMaxValues) { - mTotal = mTotal - mValues[mInsertIndex] + aValue; - mValues[mInsertIndex] = aValue; - } else { - if (!mValues.append(aValue)) { - return false; - } - mTotal = mTotal + aValue; - } - - mInsertIndex = (mInsertIndex + 1) % mMaxValues; - return true; - } - - /** - * Calculate the rolling mean. - */ - T mean() - { - MOZ_ASSERT(!empty()); - return T(mTotal / int64_t(mValues.length())); - } - - bool empty() - { - return mValues.empty(); - } - - /** - * Remove all values from the rolling mean. - */ - void clear() - { - mValues.clear(); - mInsertIndex = 0; - mTotal = T(0); - } - - size_t maxValues() - { - return mMaxValues; - } -}; - -} // namespace mozilla - -#endif // mozilla_RollingMean_h_ diff --git a/ios/include/spidermonkey/mozilla/SHA1.h b/ios/include/spidermonkey/mozilla/SHA1.h deleted file mode 100644 index ddccaa67..00000000 --- a/ios/include/spidermonkey/mozilla/SHA1.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Simple class for computing SHA1. */ - -#ifndef mozilla_SHA1_h -#define mozilla_SHA1_h - -#include "mozilla/Types.h" - -#include -#include - -namespace mozilla { - -/** - * This class computes the SHA1 hash of a byte sequence, or of the concatenation - * of multiple sequences. For example, computing the SHA1 of two sequences of - * bytes could be done as follows: - * - * void SHA1(const uint8_t* buf1, uint32_t size1, - * const uint8_t* buf2, uint32_t size2, - * SHA1Sum::Hash& hash) - * { - * SHA1Sum s; - * s.update(buf1, size1); - * s.update(buf2, size2); - * s.finish(hash); - * } - * - * The finish method may only be called once and cannot be followed by calls - * to update. - */ -class SHA1Sum -{ - union - { - uint32_t mW[16]; /* input buffer */ - uint8_t mB[64]; - } mU; - uint64_t mSize; /* count of hashed bytes. */ - unsigned mH[22]; /* 5 state variables, 16 tmp values, 1 extra */ - bool mDone; - -public: - MFBT_API SHA1Sum(); - - static const size_t kHashSize = 20; - typedef uint8_t Hash[kHashSize]; - - /* Add len bytes of dataIn to the data sequence being hashed. */ - MFBT_API void update(const void* aData, uint32_t aLength); - - /* Compute the final hash of all data into hashOut. */ - MFBT_API void finish(SHA1Sum::Hash& aHashOut); -}; - -} /* namespace mozilla */ - -#endif /* mozilla_SHA1_h */ diff --git a/ios/include/spidermonkey/mozilla/Saturate.h b/ios/include/spidermonkey/mozilla/Saturate.h deleted file mode 100644 index b79364d2..00000000 --- a/ios/include/spidermonkey/mozilla/Saturate.h +++ /dev/null @@ -1,288 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Provides saturation arithmetics for scalar types. */ - -#ifndef mozilla_Saturate_h -#define mozilla_Saturate_h - -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include - -namespace mozilla { -namespace detail { - -/** - * |SaturateOp| wraps scalar values for saturation arithmetics. Usage: - * - * uint32_t value = 1; - * - * ++SaturateOp(value); // value is 2 - * --SaturateOp(value); // value is 1 - * --SaturateOp(value); // value is 0 - * --SaturateOp(value); // value is still 0 - * - * Please add new operators when required. - * - * |SaturateOp| will saturate at the minimum and maximum values of - * type T. If you need other bounds, implement a clamped-type class and - * specialize the type traits accordingly. - */ -template -class SaturateOp -{ -public: - explicit SaturateOp(T& aValue) - : mValue(aValue) - { - // We should actually check for |std::is_scalar::value| to be - // true, but this type trait is not available everywhere. Relax - // this assertion if you want to use floating point values as well. - static_assert(IsIntegral::value, - "Integral type required in instantiation"); - } - - // Add and subtract operators - - T operator+(const T& aRhs) const - { - return T(mValue) += aRhs; - } - - T operator-(const T& aRhs) const - { - return T(mValue) -= aRhs; - } - - // Compound operators - - const T& operator+=(const T& aRhs) const - { - const T min = std::numeric_limits::min(); - const T max = std::numeric_limits::max(); - - if (aRhs > static_cast(0)) { - mValue = (max - aRhs) < mValue ? max : mValue + aRhs; - } else { - mValue = (min - aRhs) > mValue ? min : mValue + aRhs; - } - return mValue; - } - - const T& operator-=(const T& aRhs) const - { - const T min = std::numeric_limits::min(); - const T max = std::numeric_limits::max(); - - if (aRhs > static_cast(0)) { - mValue = (min + aRhs) > mValue ? min : mValue - aRhs; - } else { - mValue = (max + aRhs) < mValue ? max : mValue - aRhs; - } - return mValue; - } - - // Increment and decrement operators - - const T& operator++() const // prefix - { - return operator+=(static_cast(1)); - } - - T operator++(int) const // postfix - { - const T value(mValue); - operator++(); - return value; - } - - const T& operator--() const // prefix - { - return operator-=(static_cast(1)); - } - - T operator--(int) const // postfix - { - const T value(mValue); - operator--(); - return value; - } - -private: - SaturateOp(const SaturateOp&) = delete; - SaturateOp(SaturateOp&&) = delete; - SaturateOp& operator=(const SaturateOp&) = delete; - SaturateOp& operator=(SaturateOp&&) = delete; - - T& mValue; -}; - -/** - * |Saturate| is a value type for saturation arithmetics. It's - * build on top of |SaturateOp|. - */ -template -class Saturate -{ -public: - Saturate() = default; - MOZ_IMPLICIT Saturate(const Saturate&) = default; - - MOZ_IMPLICIT Saturate(Saturate&& aValue) - { - mValue = Move(aValue.mValue); - } - - explicit Saturate(const T& aValue) - : mValue(aValue) - { } - - const T& value() const - { - return mValue; - } - - // Compare operators - - bool operator==(const Saturate& aRhs) const - { - return mValue == aRhs.mValue; - } - - bool operator!=(const Saturate& aRhs) const - { - return !operator==(aRhs); - } - - bool operator==(const T& aRhs) const - { - return mValue == aRhs; - } - - bool operator!=(const T& aRhs) const - { - return !operator==(aRhs); - } - - // Assignment operators - - Saturate& operator=(const Saturate&) = default; - - Saturate& operator=(Saturate&& aRhs) - { - mValue = Move(aRhs.mValue); - return *this; - } - - // Add and subtract operators - - Saturate operator+(const Saturate& aRhs) const - { - Saturate lhs(mValue); - return lhs += aRhs.mValue; - } - - Saturate operator+(const T& aRhs) const - { - Saturate lhs(mValue); - return lhs += aRhs; - } - - Saturate operator-(const Saturate& aRhs) const - { - Saturate lhs(mValue); - return lhs -= aRhs.mValue; - } - - Saturate operator-(const T& aRhs) const - { - Saturate lhs(mValue); - return lhs -= aRhs; - } - - // Compound operators - - Saturate& operator+=(const Saturate& aRhs) - { - SaturateOp(mValue) += aRhs.mValue; - return *this; - } - - Saturate& operator+=(const T& aRhs) - { - SaturateOp(mValue) += aRhs; - return *this; - } - - Saturate& operator-=(const Saturate& aRhs) - { - SaturateOp(mValue) -= aRhs.mValue; - return *this; - } - - Saturate& operator-=(const T& aRhs) - { - SaturateOp(mValue) -= aRhs; - return *this; - } - - // Increment and decrement operators - - Saturate& operator++() // prefix - { - ++SaturateOp(mValue); - return *this; - } - - Saturate operator++(int) // postfix - { - return Saturate(SaturateOp(mValue)++); - } - - Saturate& operator--() // prefix - { - --SaturateOp(mValue); - return *this; - } - - Saturate operator--(int) // postfix - { - return Saturate(SaturateOp(mValue)--); - } - -private: - T mValue; -}; - -} // namespace detail - -typedef detail::Saturate SaturateInt8; -typedef detail::Saturate SaturateInt16; -typedef detail::Saturate SaturateInt32; -typedef detail::Saturate SaturateUint8; -typedef detail::Saturate SaturateUint16; -typedef detail::Saturate SaturateUint32; - -} // namespace mozilla - -template -bool -operator==(LhsT aLhs, const mozilla::detail::Saturate& aRhs) -{ - return aRhs.operator==(static_cast(aLhs)); -} - -template -bool -operator!=(LhsT aLhs, const mozilla::detail::Saturate& aRhs) -{ - return !(aLhs == aRhs); -} - -#endif // mozilla_Saturate_h diff --git a/ios/include/spidermonkey/mozilla/ScopeExit.h b/ios/include/spidermonkey/mozilla/ScopeExit.h deleted file mode 100644 index 7aff82d8..00000000 --- a/ios/include/spidermonkey/mozilla/ScopeExit.h +++ /dev/null @@ -1,135 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* RAII class for executing arbitrary actions at scope end. */ - -#ifndef mozilla_ScopeExit_h -#define mozilla_ScopeExit_h - -/* - * See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189.pdf for a - * standards-track version of this. - * - * Error handling can be complex when various actions need to be performed that - * need to be undone if an error occurs midway. This can be handled with a - * collection of boolean state variables and gotos, which can get clunky and - * error-prone: - * - * { - * if (!a.setup()) - * goto fail; - * isASetup = true; - * - * if (!b.setup()) - * goto fail; - * isBSetup = true; - * - * ... - * return true; - * - * fail: - * if (isASetup) - * a.teardown(); - * if (isBSetup) - * b.teardown(); - * return false; - * } - * - * ScopeExit is a mechanism to simplify this pattern by keeping an RAII guard - * class that will perform the teardown on destruction, unless released. So the - * above would become: - * - * { - * if (!a.setup()) { - * return false; - * } - * auto guardA = MakeScopeExit([&] { - * a.teardown(); - * }); - * - * if (!b.setup()) { - * return false; - * } - * auto guardB = MakeScopeExit([&] { - * b.teardown(); - * }); - * - * ... - * guardA.release(); - * guardB.release(); - * return true; - * } - * - * This header provides: - * - * - |ScopeExit| - a container for a cleanup call, automically called at the - * end of the scope; - * - |MakeScopeExit| - a convenience function for constructing a |ScopeExit| - * with a given cleanup routine, commonly used with a lambda function. - * - * Note that the RAII classes defined in this header do _not_ perform any form - * of reference-counting or garbage-collection. These classes have exactly two - * behaviors: - * - * - if |release()| has not been called, the cleanup is always performed at - * the end of the scope; - * - if |release()| has been called, nothing will happen at the end of the - * scope. - */ - -#include "mozilla/GuardObjects.h" -#include "mozilla/Move.h" - -namespace mozilla { - -template -class MOZ_STACK_CLASS ScopeExit { - ExitFunction mExitFunction; - bool mExecuteOnDestruction; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - -public: - explicit ScopeExit(ExitFunction&& cleanup - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mExitFunction(cleanup) - , mExecuteOnDestruction(true) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - ScopeExit(ScopeExit&& rhs) - : mExitFunction(mozilla::Move(rhs.mExitFunction)) - , mExecuteOnDestruction(rhs.mExecuteOnDestruction) - { - rhs.release(); - } - - ~ScopeExit() { - if (mExecuteOnDestruction) { - mExitFunction(); - } - } - - void release() { - mExecuteOnDestruction = false; - } - -private: - explicit ScopeExit(const ScopeExit&) = delete; - ScopeExit& operator=(const ScopeExit&) = delete; - ScopeExit& operator=(ScopeExit&&) = delete; -}; - -template -ScopeExit -MakeScopeExit(ExitFunction&& exitFunction) -{ - return ScopeExit(mozilla::Move(exitFunction)); -} - -} /* namespace mozilla */ - -#endif /* mozilla_ScopeExit_h */ diff --git a/ios/include/spidermonkey/mozilla/Scoped.h b/ios/include/spidermonkey/mozilla/Scoped.h deleted file mode 100644 index c935434a..00000000 --- a/ios/include/spidermonkey/mozilla/Scoped.h +++ /dev/null @@ -1,255 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* DEPRECATED: Use UniquePtr.h instead. */ - -#ifndef mozilla_Scoped_h -#define mozilla_Scoped_h - -/* - * DEPRECATED: Use UniquePtr.h instead. - * - * Resource Acquisition Is Initialization is a programming idiom used - * to write robust code that is able to deallocate resources properly, - * even in presence of execution errors or exceptions that need to be - * propagated. The Scoped* classes defined via the |SCOPED_TEMPLATE| - * and |MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLTE| macros perform the - * deallocation of the resource they hold once program execution - * reaches the end of the scope for which they have been defined. - * These macros have been used to automatically close file - * descriptors/file handles when reaching the end of the scope, - * graphics contexts, etc. - * - * The general scenario for RAII classes created by the above macros - * is the following: - * - * ScopedClass foo(create_value()); - * // ... In this scope, |foo| is defined. Use |foo.get()| or |foo.rwget()| - * to access the value. - * // ... In case of |return| or |throw|, |foo| is deallocated automatically. - * // ... If |foo| needs to be returned or stored, use |foo.forget()| - * - * Note that the RAII classes defined in this header do _not_ perform any form - * of reference-counting or garbage-collection. These classes have exactly two - * behaviors: - * - * - if |forget()| has not been called, the resource is always deallocated at - * the end of the scope; - * - if |forget()| has been called, any control on the resource is unbound - * and the resource is not deallocated by the class. - */ - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/GuardObjects.h" -#include "mozilla/Move.h" - -namespace mozilla { - -/* - * Scoped is a helper to create RAII wrappers - * Type argument |Traits| is expected to have the following structure: - * - * struct Traits - * { - * // Define the type of the value stored in the wrapper - * typedef value_type type; - * // Returns the value corresponding to the uninitialized or freed state - * const static type empty(); - * // Release resources corresponding to the wrapped value - * // This function is responsible for not releasing an |empty| value - * const static void release(type); - * } - */ -template -class MOZ_NON_TEMPORARY_CLASS Scoped -{ -public: - typedef typename Traits::type Resource; - - explicit Scoped(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) - : mValue(Traits::empty()) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit Scoped(const Resource& aValue - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mValue(aValue) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - /* Move constructor. */ - Scoped(Scoped&& aOther - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mValue(Move(aOther.mValue)) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - aOther.mValue = Traits::empty(); - } - - ~Scoped() { Traits::release(mValue); } - - // Constant getter - operator const Resource&() const { return mValue; } - const Resource& operator->() const { return mValue; } - const Resource& get() const { return mValue; } - // Non-constant getter. - Resource& rwget() { return mValue; } - - /* - * Forget the resource. - * - * Once |forget| has been called, the |Scoped| is neutralized, i.e. it will - * have no effect at destruction (unless it is reset to another resource by - * |operator=|). - * - * @return The original resource. - */ - Resource forget() - { - Resource tmp = mValue; - mValue = Traits::empty(); - return tmp; - } - - /* - * Perform immediate clean-up of this |Scoped|. - * - * If this |Scoped| is currently empty, this method has no effect. - */ - void dispose() - { - Traits::release(mValue); - mValue = Traits::empty(); - } - - bool operator==(const Resource& aOther) const { return mValue == aOther; } - - /* - * Replace the resource with another resource. - * - * Calling |operator=| has the side-effect of triggering clean-up. If you do - * not want to trigger clean-up, you should first invoke |forget|. - * - * @return this - */ - Scoped& operator=(const Resource& aOther) { return reset(aOther); } - - Scoped& reset(const Resource& aOther) - { - Traits::release(mValue); - mValue = aOther; - return *this; - } - - /* Move assignment operator. */ - Scoped& operator=(Scoped&& aRhs) - { - MOZ_ASSERT(&aRhs != this, "self-move-assignment not allowed"); - this->~Scoped(); - new(this) Scoped(Move(aRhs)); - return *this; - } - -private: - explicit Scoped(const Scoped& aValue) = delete; - Scoped& operator=(const Scoped& aValue) = delete; - -private: - Resource mValue; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/* - * SCOPED_TEMPLATE defines a templated class derived from Scoped - * This allows to implement templates such as ScopedFreePtr. - * - * @param name The name of the class to define. - * @param Traits A struct implementing clean-up. See the implementations - * for more details. - */ -#define SCOPED_TEMPLATE(name, Traits) \ -template \ -struct MOZ_NON_TEMPORARY_CLASS name : public mozilla::Scoped > \ -{ \ - typedef mozilla::Scoped > Super; \ - typedef typename Super::Resource Resource; \ - name& operator=(Resource aRhs) \ - { \ - Super::operator=(aRhs); \ - return *this; \ - } \ - name& operator=(name&& aRhs) \ - { \ - Super::operator=(Move(aRhs)); \ - return *this; \ - } \ - explicit name(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) \ - : Super(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT) \ - {} \ - explicit name(Resource aRhs \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) \ - : Super(aRhs \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT) \ - {} \ - name(name&& aRhs \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) \ - : Super(Move(aRhs) \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT) \ - {} \ -private: \ - explicit name(name&) = delete; \ - name& operator=(name&) = delete; \ -}; - -/* - * MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE makes it easy to create scoped - * pointers for types with custom deleters; just overload - * TypeSpecificDelete(T*) in the same namespace as T to call the deleter for - * type T. - * - * @param name The name of the class to define. - * @param Type A struct implementing clean-up. See the implementations - * for more details. - * *param Deleter The function that is used to delete/destroy/free a - * non-null value of Type*. - * - * Example: - * - * MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPRFileDesc, PRFileDesc, \ - * PR_Close) - * ... - * { - * ScopedPRFileDesc file(PR_OpenFile(...)); - * ... - * } // file is closed with PR_Close here - */ -#define MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(name, Type, Deleter) \ -template <> inline void TypeSpecificDelete(Type* aValue) { Deleter(aValue); } \ -typedef ::mozilla::TypeSpecificScopedPointer name; - -template void TypeSpecificDelete(T* aValue); - -template -struct TypeSpecificScopedPointerTraits -{ - typedef T* type; - static type empty() { return nullptr; } - static void release(type aValue) - { - if (aValue) { - TypeSpecificDelete(aValue); - } - } -}; - -SCOPED_TEMPLATE(TypeSpecificScopedPointer, TypeSpecificScopedPointerTraits) - -} /* namespace mozilla */ - -#endif /* mozilla_Scoped_h */ diff --git a/ios/include/spidermonkey/mozilla/SegmentedVector.h b/ios/include/spidermonkey/mozilla/SegmentedVector.h deleted file mode 100644 index 1bf60e46..00000000 --- a/ios/include/spidermonkey/mozilla/SegmentedVector.h +++ /dev/null @@ -1,339 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// A simple segmented vector class. -// -// This class should be used in preference to mozilla::Vector or nsTArray when -// you are simply gathering items in order to later iterate over them. -// -// - In the case where you don't know the final size in advance, using -// SegmentedVector avoids the need to repeatedly allocate increasingly large -// buffers and copy the data into them. -// -// - In the case where you know the final size in advance and so can set the -// capacity appropriately, using SegmentedVector still avoids the need for -// large allocations (which can trigger OOMs). - -#ifndef mozilla_SegmentedVector_h -#define mozilla_SegmentedVector_h - -#include "mozilla/Alignment.h" -#include "mozilla/AllocPolicy.h" -#include "mozilla/Array.h" -#include "mozilla/LinkedList.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include // for placement new - -namespace mozilla { - -// |IdealSegmentSize| specifies how big each segment will be in bytes (or as -// close as is possible). Use the following guidelines to choose a size. -// -// - It should be a power-of-two, to avoid slop. -// -// - It should not be too small, so that segment allocations are infrequent, -// and so that per-segment bookkeeping overhead is low. Typically each -// segment should be able to hold hundreds of elements, at least. -// -// - It should not be too large, so that OOMs are unlikely when allocating -// segments, and so that not too much space is wasted when the final segment -// is not full. -// -// The ideal size depends on how the SegmentedVector is used and the size of -// |T|, but reasonable sizes include 1024, 4096 (the default), 8192, and 16384. -// -template -class SegmentedVector : private AllocPolicy -{ - template - struct SegmentImpl - : public mozilla::LinkedListElement> - { - SegmentImpl() : mLength(0) {} - - ~SegmentImpl() - { - for (uint32_t i = 0; i < mLength; i++) { - (*this)[i].~T(); - } - } - - uint32_t Length() const { return mLength; } - - T* Elems() { return reinterpret_cast(&mStorage.mBuf); } - - T& operator[](size_t aIndex) - { - MOZ_ASSERT(aIndex < mLength); - return Elems()[aIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(aIndex < mLength); - return Elems()[aIndex]; - } - - template - void Append(U&& aU) - { - MOZ_ASSERT(mLength < SegmentCapacity); - // Pre-increment mLength so that the bounds-check in operator[] passes. - mLength++; - T* elem = &(*this)[mLength - 1]; - new (elem) T(mozilla::Forward(aU)); - } - - void PopLast() - { - MOZ_ASSERT(mLength > 0); - (*this)[mLength - 1].~T(); - mLength--; - } - - uint32_t mLength; - - // The union ensures that the elements are appropriately aligned. - union Storage - { - char mBuf[sizeof(T) * SegmentCapacity]; - mozilla::AlignedElem mAlign; - } mStorage; - - static_assert(MOZ_ALIGNOF(T) == MOZ_ALIGNOF(Storage), - "SegmentedVector provides incorrect alignment"); - }; - - // See how many we elements we can fit in a segment of IdealSegmentSize. If - // IdealSegmentSize is too small, it'll be just one. The +1 is because - // kSingleElementSegmentSize already accounts for one element. - static const size_t kSingleElementSegmentSize = sizeof(SegmentImpl<1>); - static const size_t kSegmentCapacity = - kSingleElementSegmentSize <= IdealSegmentSize - ? (IdealSegmentSize - kSingleElementSegmentSize) / sizeof(T) + 1 - : 1; - - typedef SegmentImpl Segment; - -public: - // The |aIdealSegmentSize| is only for sanity checking. If it's specified, we - // check that the actual segment size is as close as possible to it. This - // serves as a sanity check for SegmentedVectorCapacity's capacity - // computation. - explicit SegmentedVector(size_t aIdealSegmentSize = 0) - { - // The difference between the actual segment size and the ideal segment - // size should be less than the size of a single element... unless the - // ideal size was too small, in which case the capacity should be one. - MOZ_ASSERT_IF( - aIdealSegmentSize != 0, - (sizeof(Segment) > aIdealSegmentSize && kSegmentCapacity == 1) || - aIdealSegmentSize - sizeof(Segment) < sizeof(T)); - } - - ~SegmentedVector() { Clear(); } - - bool IsEmpty() const { return !mSegments.getFirst(); } - - // Note that this is O(n) rather than O(1), but the constant factor is very - // small because it only has to do one addition per segment. - size_t Length() const - { - size_t n = 0; - for (auto segment = mSegments.getFirst(); - segment; - segment = segment->getNext()) { - n += segment->Length(); - } - return n; - } - - // Returns false if the allocation failed. (If you are using an infallible - // allocation policy, use InfallibleAppend() instead.) - template - MOZ_MUST_USE bool Append(U&& aU) - { - Segment* last = mSegments.getLast(); - if (!last || last->Length() == kSegmentCapacity) { - last = this->template pod_malloc(1); - if (!last) { - return false; - } - new (last) Segment(); - mSegments.insertBack(last); - } - last->Append(mozilla::Forward(aU)); - return true; - } - - // You should probably only use this instead of Append() if you are using an - // infallible allocation policy. It will crash if the allocation fails. - template - void InfallibleAppend(U&& aU) - { - bool ok = Append(mozilla::Forward(aU)); - MOZ_RELEASE_ASSERT(ok); - } - - void Clear() - { - Segment* segment; - while ((segment = mSegments.popFirst())) { - segment->~Segment(); - this->free_(segment); - } - } - - T& GetLast() - { - MOZ_ASSERT(!IsEmpty()); - Segment* last = mSegments.getLast(); - return (*last)[last->Length() - 1]; - } - - const T& GetLast() const - { - MOZ_ASSERT(!IsEmpty()); - Segment* last = mSegments.getLast(); - return (*last)[last->Length() - 1]; - } - - void PopLast() - { - MOZ_ASSERT(!IsEmpty()); - Segment* last = mSegments.getLast(); - last->PopLast(); - if (!last->Length()) { - mSegments.popLast(); - last->~Segment(); - this->free_(last); - } - } - - // Equivalent to calling |PopLast| |aNumElements| times, but potentially - // more efficient. - void PopLastN(uint32_t aNumElements) - { - MOZ_ASSERT(aNumElements <= Length()); - - Segment* last; - - // Pop full segments for as long as we can. Note that this loop - // cleanly handles the case when the initial last segment is not - // full and we are popping more elements than said segment contains. - do { - last = mSegments.getLast(); - - // The list is empty. We're all done. - if (!last) { - return; - } - - // Check to see if the list contains too many elements. Handle - // that in the epilogue. - uint32_t segmentLen = last->Length(); - if (segmentLen > aNumElements) { - break; - } - - // Destroying the segment destroys all elements contained therein. - mSegments.popLast(); - last->~Segment(); - this->free_(last); - - MOZ_ASSERT(aNumElements >= segmentLen); - aNumElements -= segmentLen; - if (aNumElements == 0) { - return; - } - } while (true); - - // Handle the case where the last segment contains more elements - // than we want to pop. - MOZ_ASSERT(last); - MOZ_ASSERT(last == mSegments.getLast()); - MOZ_ASSERT(aNumElements != 0); - MOZ_ASSERT(aNumElements < last->Length()); - for (uint32_t i = 0; i < aNumElements; ++i) { - last->PopLast(); - } - MOZ_ASSERT(last->Length() != 0); - } - - // Use this class to iterate over a SegmentedVector, like so: - // - // for (auto iter = v.Iter(); !iter.Done(); iter.Next()) { - // MyElem& elem = iter.Get(); - // f(elem); - // } - // - class IterImpl - { - friend class SegmentedVector; - - Segment* mSegment; - size_t mIndex; - - explicit IterImpl(SegmentedVector* aVector) - : mSegment(aVector->mSegments.getFirst()) - , mIndex(0) - {} - - public: - bool Done() const { return !mSegment; } - - T& Get() - { - MOZ_ASSERT(!Done()); - return (*mSegment)[mIndex]; - } - - const T& Get() const - { - MOZ_ASSERT(!Done()); - return (*mSegment)[mIndex]; - } - - void Next() - { - MOZ_ASSERT(!Done()); - mIndex++; - if (mIndex == mSegment->Length()) { - mSegment = mSegment->getNext(); - mIndex = 0; - } - } - }; - - IterImpl Iter() { return IterImpl(this); } - - // Measure the memory consumption of the vector excluding |this|. Note that - // it only measures the vector itself. If the vector elements contain - // pointers to other memory blocks, those blocks must be measured separately - // during a subsequent iteration over the vector. - size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const - { - return mSegments.sizeOfExcludingThis(aMallocSizeOf); - } - - // Like sizeOfExcludingThis(), but measures |this| as well. - size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const - { - return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf); - } - -private: - mozilla::LinkedList mSegments; -}; - -} // namespace mozilla - -#endif /* mozilla_SegmentedVector_h */ diff --git a/ios/include/spidermonkey/mozilla/SizePrintfMacros.h b/ios/include/spidermonkey/mozilla/SizePrintfMacros.h deleted file mode 100644 index ec55c62c..00000000 --- a/ios/include/spidermonkey/mozilla/SizePrintfMacros.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements (nonstandard) PRI{ouxX}SIZE format macros for size_t types. */ - -#ifndef mozilla_SizePrintfMacros_h_ -#define mozilla_SizePrintfMacros_h_ - -/* - * MSVC's libc does not support C99's %z format length modifier for size_t - * types. Instead, we use Microsoft's nonstandard %I modifier for size_t, which - * is unsigned __int32 on 32-bit platforms and unsigned __int64 on 64-bit - * platforms: - * - * http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx - */ - -#if defined(XP_WIN) -# define PRIoSIZE "Io" -# define PRIuSIZE "Iu" -# define PRIxSIZE "Ix" -# define PRIXSIZE "IX" -#else -# define PRIoSIZE "zo" -# define PRIuSIZE "zu" -# define PRIxSIZE "zx" -# define PRIXSIZE "zX" -#endif - -#endif /* mozilla_SizePrintfMacros_h_ */ diff --git a/ios/include/spidermonkey/mozilla/SplayTree.h b/ios/include/spidermonkey/mozilla/SplayTree.h deleted file mode 100644 index 2b3b838b..00000000 --- a/ios/include/spidermonkey/mozilla/SplayTree.h +++ /dev/null @@ -1,330 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/** - * A sorted tree with optimal access times, where recently-accessed elements - * are faster to access again. - */ - -#ifndef mozilla_SplayTree_h -#define mozilla_SplayTree_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -namespace mozilla { - -template -class SplayTree; - -template -class SplayTreeNode -{ -public: - template - friend class SplayTree; - - SplayTreeNode() - : mLeft(nullptr) - , mRight(nullptr) - , mParent(nullptr) - {} - -private: - T* mLeft; - T* mRight; - T* mParent; -}; - - -/** - * Class which represents a splay tree. - * Splay trees are balanced binary search trees for which search, insert and - * remove are all amortized O(log n), but where accessing a node makes it - * faster to access that node in the future. - * - * T indicates the type of tree elements, Comparator must have a static - * compare(const T&, const T&) method ordering the elements. The compare - * method must be free from side effects. - */ -template -class SplayTree -{ - T* mRoot; - -public: - constexpr SplayTree() - : mRoot(nullptr) - {} - - bool empty() const - { - return !mRoot; - } - - T* find(const T& aValue) - { - if (empty()) { - return nullptr; - } - - T* last = lookup(aValue); - splay(last); - return Comparator::compare(aValue, *last) == 0 ? last : nullptr; - } - - void insert(T* aValue) - { - MOZ_ASSERT(!find(*aValue), "Duplicate elements are not allowed."); - - if (!mRoot) { - mRoot = aValue; - return; - } - T* last = lookup(*aValue); - int cmp = Comparator::compare(*aValue, *last); - - finishInsertion(last, cmp, aValue); - return; - } - - T* findOrInsert(const T& aValue); - - T* remove(const T& aValue) - { - T* last = lookup(aValue); - MOZ_ASSERT(last, "This tree must contain the element being removed."); - MOZ_ASSERT(Comparator::compare(aValue, *last) == 0); - - // Splay the tree so that the item to remove is the root. - splay(last); - MOZ_ASSERT(last == mRoot); - - // Find another node which can be swapped in for the root: either the - // rightmost child of the root's left, or the leftmost child of the - // root's right. - T* swap; - T* swapChild; - if (mRoot->mLeft) { - swap = mRoot->mLeft; - while (swap->mRight) { - swap = swap->mRight; - } - swapChild = swap->mLeft; - } else if (mRoot->mRight) { - swap = mRoot->mRight; - while (swap->mLeft) { - swap = swap->mLeft; - } - swapChild = swap->mRight; - } else { - T* result = mRoot; - mRoot = nullptr; - return result; - } - - // The selected node has at most one child, in swapChild. Detach it - // from the subtree by replacing it with that child. - if (swap == swap->mParent->mLeft) { - swap->mParent->mLeft = swapChild; - } else { - swap->mParent->mRight = swapChild; - } - if (swapChild) { - swapChild->mParent = swap->mParent; - } - - // Make the selected node the new root. - mRoot = swap; - mRoot->mParent = nullptr; - mRoot->mLeft = last->mLeft; - mRoot->mRight = last->mRight; - if (mRoot->mLeft) { - mRoot->mLeft->mParent = mRoot; - } - if (mRoot->mRight) { - mRoot->mRight->mParent = mRoot; - } - - return last; - } - - T* removeMin() - { - MOZ_ASSERT(mRoot, "No min to remove!"); - - T* min = mRoot; - while (min->mLeft) { - min = min->mLeft; - } - return remove(*min); - } - - // For testing purposes only. - void checkCoherency() - { - checkCoherency(mRoot, nullptr); - } - -private: - /** - * Returns the node in this comparing equal to |aValue|, or a node just - * greater or just less than |aValue| if there is no such node. - */ - T* lookup(const T& aValue) - { - MOZ_ASSERT(!empty()); - - T* node = mRoot; - T* parent; - do { - parent = node; - int c = Comparator::compare(aValue, *node); - if (c == 0) { - return node; - } else if (c < 0) { - node = node->mLeft; - } else { - node = node->mRight; - } - } while (node); - return parent; - } - - void finishInsertion(T* aLast, int32_t aCmp, T* aNew) - { - MOZ_ASSERT(aCmp, "Nodes shouldn't be equal!"); - - T** parentPointer = (aCmp < 0) ? &aLast->mLeft : &aLast->mRight; - MOZ_ASSERT(!*parentPointer); - *parentPointer = aNew; - aNew->mParent = aLast; - - splay(aNew); - } - - /** - * Rotate the tree until |node| is at the root of the tree. Performing - * the rotations in this fashion preserves the amortized balancing of - * the tree. - */ - void splay(T* aNode) - { - MOZ_ASSERT(aNode); - - while (aNode != mRoot) { - T* parent = aNode->mParent; - if (parent == mRoot) { - // Zig rotation. - rotate(aNode); - MOZ_ASSERT(aNode == mRoot); - return; - } - T* grandparent = parent->mParent; - if ((parent->mLeft == aNode) == (grandparent->mLeft == parent)) { - // Zig-zig rotation. - rotate(parent); - rotate(aNode); - } else { - // Zig-zag rotation. - rotate(aNode); - rotate(aNode); - } - } - } - - void rotate(T* aNode) - { - // Rearrange nodes so that aNode becomes the parent of its current - // parent, while preserving the sortedness of the tree. - T* parent = aNode->mParent; - if (parent->mLeft == aNode) { - // x y - // y c ==> a x - // a b b c - parent->mLeft = aNode->mRight; - if (aNode->mRight) { - aNode->mRight->mParent = parent; - } - aNode->mRight = parent; - } else { - MOZ_ASSERT(parent->mRight == aNode); - // x y - // a y ==> x c - // b c a b - parent->mRight = aNode->mLeft; - if (aNode->mLeft) { - aNode->mLeft->mParent = parent; - } - aNode->mLeft = parent; - } - aNode->mParent = parent->mParent; - parent->mParent = aNode; - if (T* grandparent = aNode->mParent) { - if (grandparent->mLeft == parent) { - grandparent->mLeft = aNode; - } else { - grandparent->mRight = aNode; - } - } else { - mRoot = aNode; - } - } - - T* checkCoherency(T* aNode, T* aMinimum) - { - if (mRoot) { - MOZ_RELEASE_ASSERT(!mRoot->mParent); - } - if (!aNode) { - MOZ_RELEASE_ASSERT(!mRoot); - return nullptr; - } - if (!aNode->mParent) { - MOZ_RELEASE_ASSERT(aNode == mRoot); - } - if (aMinimum) { - MOZ_RELEASE_ASSERT(Comparator::compare(*aMinimum, *aNode) < 0); - } - if (aNode->mLeft) { - MOZ_RELEASE_ASSERT(aNode->mLeft->mParent == aNode); - T* leftMaximum = checkCoherency(aNode->mLeft, aMinimum); - MOZ_RELEASE_ASSERT(Comparator::compare(*leftMaximum, *aNode) < 0); - } - if (aNode->mRight) { - MOZ_RELEASE_ASSERT(aNode->mRight->mParent == aNode); - return checkCoherency(aNode->mRight, aNode); - } - return aNode; - } - - SplayTree(const SplayTree&) = delete; - void operator=(const SplayTree&) = delete; -}; - -template -T* -SplayTree::findOrInsert(const T& aValue) -{ - if (!mRoot) { - mRoot = new T(aValue); - return mRoot; - } - - T* last = lookup(aValue); - int cmp = Comparator::compare(aValue, *last); - if (!cmp) { - return last; - } - - T* t = new T(aValue); - finishInsertion(last, cmp, t); - return t; -} - -} /* namespace mozilla */ - -#endif /* mozilla_SplayTree_h */ diff --git a/ios/include/spidermonkey/mozilla/Sprintf.h b/ios/include/spidermonkey/mozilla/Sprintf.h deleted file mode 100644 index e0be271e..00000000 --- a/ios/include/spidermonkey/mozilla/Sprintf.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Provides a safer sprintf for printing to fixed-size character arrays. */ - -#ifndef mozilla_Sprintf_h_ -#define mozilla_Sprintf_h_ - -#include -#include - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#ifdef __cplusplus - -template -int VsprintfLiteral(char (&buffer)[N], const char* format, va_list args) -{ - MOZ_ASSERT(format != buffer); - int result = vsnprintf(buffer, N, format, args); - buffer[N - 1] = '\0'; - return result; -} - -template -MOZ_FORMAT_PRINTF(2, 3) -int SprintfLiteral(char (&buffer)[N], const char* format, ...) -{ - va_list args; - va_start(args, format); - int result = VsprintfLiteral(buffer, format, args); - va_end(args); - return result; -} - -#endif -#endif /* mozilla_Sprintf_h_ */ diff --git a/ios/include/spidermonkey/mozilla/StackWalk.h b/ios/include/spidermonkey/mozilla/StackWalk.h deleted file mode 100644 index 534c0bd8..00000000 --- a/ios/include/spidermonkey/mozilla/StackWalk.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* API for getting a stack trace of the C/C++ stack on the current thread */ - -#ifndef mozilla_StackWalk_h -#define mozilla_StackWalk_h - -/* WARNING: This file is intended to be included from C or C++ files. */ - -#include "mozilla/Types.h" -#include - -/** - * The callback for MozStackWalk. - * - * @param aFrameNumber The frame number (starts at 1, not 0). - * @param aPC The program counter value. - * @param aSP The best approximation possible of what the stack - * pointer will be pointing to when the execution returns - * to executing that at aPC. If no approximation can - * be made it will be nullptr. - * @param aClosure Extra data passed in via MozStackWalk(). - */ -typedef void -(*MozWalkStackCallback)(uint32_t aFrameNumber, void* aPC, void* aSP, - void* aClosure); - -/** - * Call aCallback for the C/C++ stack frames on the current thread, from - * the caller of MozStackWalk to main (or above). - * - * @param aCallback Callback function, called once per frame. - * @param aSkipFrames Number of initial frames to skip. 0 means that - * the first callback will be for the caller of - * MozStackWalk. - * @param aMaxFrames Maximum number of frames to trace. 0 means no limit. - * @param aClosure Caller-supplied data passed through to aCallback. - * @param aThread The thread for which the stack is to be retrieved. - * Passing null causes us to walk the stack of the - * current thread. On Windows, this is a thread HANDLE. - * It is currently not supported on any other platform. - * @param aPlatformData Platform specific data that can help in walking the - * stack, this should be nullptr unless you really know - * what you're doing! This needs to be a pointer to a - * CONTEXT on Windows and should not be passed on other - * platforms. - * - * May skip some stack frames due to compiler optimizations or code - * generation. - * - */ -MFBT_API bool -MozStackWalk(MozWalkStackCallback aCallback, uint32_t aSkipFrames, - uint32_t aMaxFrames, void* aClosure, uintptr_t aThread, - void* aPlatformData); - -typedef struct -{ - /* - * The name of the shared library or executable containing an - * address and the address's offset within that library, or empty - * string and zero if unknown. - */ - char library[256]; - ptrdiff_t loffset; - /* - * The name of the file name and line number of the code - * corresponding to the address, or empty string and zero if - * unknown. - */ - char filename[256]; - unsigned long lineno; - /* - * The name of the function containing an address and the address's - * offset within that function, or empty string and zero if unknown. - */ - char function[256]; - ptrdiff_t foffset; -} MozCodeAddressDetails; - -/** - * For a given pointer to code, fill in the pieces of information used - * when printing a stack trace. - * - * @param aPC The code address. - * @param aDetails A structure to be filled in with the result. - */ -MFBT_API bool -MozDescribeCodeAddress(void* aPC, MozCodeAddressDetails* aDetails); - -/** - * Format the information about a code address in a format suitable for - * stack traces on the current platform. When available, this string - * should contain the function name, source file, and line number. When - * these are not available, library and offset should be reported, if - * possible. - * - * Note that this output is parsed by several scripts including the fix*.py and - * make-tree.pl scripts in tools/rb/. It should only be change with care, and - * in conjunction with those scripts. - * - * @param aBuffer A string to be filled in with the description. - * The string will always be null-terminated. - * @param aBufferSize The size, in bytes, of aBuffer, including - * room for the terminating null. If the information - * to be printed would be larger than aBuffer, it - * will be truncated so that aBuffer[aBufferSize-1] - * is the terminating null. - * @param aFrameNumber The frame number. - * @param aPC The code address. - * @param aFunction The function name. Possibly null or the empty string. - * @param aLibrary The library name. Possibly null or the empty string. - * @param aLOffset The library offset. - * @param aFileName The filename. Possibly null or the empty string. - * @param aLineNo The line number. Possibly zero. - */ -MFBT_API void -MozFormatCodeAddress(char* aBuffer, uint32_t aBufferSize, uint32_t aFrameNumber, - const void* aPC, const char* aFunction, - const char* aLibrary, ptrdiff_t aLOffset, - const char* aFileName, uint32_t aLineNo); - -/** - * Format the information about a code address in the same fashion as - * MozFormatCodeAddress. - * - * @param aBuffer A string to be filled in with the description. - * The string will always be null-terminated. - * @param aBufferSize The size, in bytes, of aBuffer, including - * room for the terminating null. If the information - * to be printed would be larger than aBuffer, it - * will be truncated so that aBuffer[aBufferSize-1] - * is the terminating null. - * @param aFrameNumber The frame number. - * @param aPC The code address. - * @param aDetails The value filled in by MozDescribeCodeAddress(aPC). - */ -MFBT_API void -MozFormatCodeAddressDetails(char* aBuffer, uint32_t aBufferSize, - uint32_t aFrameNumber, void* aPC, - const MozCodeAddressDetails* aDetails); - -namespace mozilla { - -MFBT_API bool -FramePointerStackWalk(MozWalkStackCallback aCallback, uint32_t aSkipFrames, - uint32_t aMaxFrames, void* aClosure, void** aBp, - void* aStackEnd); - -} // namespace mozilla - -/** - * Initialize the critical sections for this platform so that we can - * abort stack walks when needed. - */ -MFBT_API void -StackWalkInitCriticalAddress(void); - -#endif diff --git a/ios/include/spidermonkey/mozilla/StaticAnalysisFunctions.h b/ios/include/spidermonkey/mozilla/StaticAnalysisFunctions.h deleted file mode 100644 index a06809dc..00000000 --- a/ios/include/spidermonkey/mozilla/StaticAnalysisFunctions.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_StaticAnalysisFunctions_h -#define mozilla_StaticAnalysisFunctions_h - -#ifndef __cplusplus -#ifndef bool -#include -#endif -#endif -/* - * Functions that are used as markers in Gecko code for static analysis. Their - * purpose is to have different AST nodes generated during compile time and to - * match them based on different checkers implemented in build/clang-plugin - */ - -#ifdef MOZ_CLANG_PLUGIN - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * MOZ_AssertAssignmentTest - used in MOZ_ASSERT in order to test the possible - * presence of assignment instead of logical comparisons. - * - * Example: - * MOZ_ASSERT(retVal = true); - */ -static MOZ_ALWAYS_INLINE bool MOZ_AssertAssignmentTest(bool exprResult) { - return exprResult; -} - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#define MOZ_CHECK_ASSERT_ASSIGNMENT(expr) MOZ_AssertAssignmentTest(!!(expr)) - -#else - -#define MOZ_CHECK_ASSERT_ASSIGNMENT(expr) (!!(expr)) - -#endif /* MOZ_CLANG_PLUGIN */ -#endif /* StaticAnalysisFunctions_h */ \ No newline at end of file diff --git a/ios/include/spidermonkey/mozilla/TaggedAnonymousMemory.h b/ios/include/spidermonkey/mozilla/TaggedAnonymousMemory.h deleted file mode 100644 index d26b06df..00000000 --- a/ios/include/spidermonkey/mozilla/TaggedAnonymousMemory.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// Some Linux kernels -- specifically, newer versions of Android and -// some B2G devices -- have a feature for assigning names to ranges of -// anonymous memory (i.e., memory that doesn't have a "name" in the -// form of an underlying mapped file). These names are reported in -// /proc//smaps alongside system-level memory usage information -// such as Proportional Set Size (memory usage adjusted for sharing -// between processes), which allows reporting this information at a -// finer granularity than would otherwise be possible (e.g., -// separating malloc() heap from JS heap). -// -// Existing memory can be tagged with MozTagAnonymousMemory(); it will -// tag the range of complete pages containing the given interval, so -// the results may be inexact if the range isn't page-aligned. -// MozTaggedAnonymousMmap() can be used like mmap() with an extra -// parameter, and will tag the returned memory if the mapping was -// successful (and if it was in fact anonymous). -// -// NOTE: The pointer given as the "tag" argument MUST remain valid as -// long as the mapping exists. The referenced string is read when -// /proc//smaps or /proc//maps is read, not when the tag is -// established, so freeing it or changing its contents will have -// unexpected results. Using a static string is probably best. -// -// Also note that this header can be used by both C and C++ code. - -#ifndef mozilla_TaggedAnonymousMemory_h -#define mozilla_TaggedAnonymousMemory_h - -#ifndef XP_WIN - -#include -#include - -#include "mozilla/Types.h" - -#ifdef ANDROID - -#ifdef __cplusplus -extern "C" { -#endif - -MFBT_API void -MozTagAnonymousMemory(const void* aPtr, size_t aLength, const char* aTag); - -MFBT_API void* -MozTaggedAnonymousMmap(void* aAddr, size_t aLength, int aProt, int aFlags, - int aFd, off_t aOffset, const char* aTag); - -MFBT_API int -MozTaggedMemoryIsSupported(void); - -#ifdef __cplusplus -} // extern "C" -#endif - -#else // ANDROID - -static inline void -MozTagAnonymousMemory(const void* aPtr, size_t aLength, const char* aTag) -{ -} - -static inline void* -MozTaggedAnonymousMmap(void* aAddr, size_t aLength, int aProt, int aFlags, - int aFd, off_t aOffset, const char* aTag) -{ - return mmap(aAddr, aLength, aProt, aFlags, aFd, aOffset); -} - -static inline int -MozTaggedMemoryIsSupported(void) -{ - return 0; -} - -#endif // ANDROID - -#endif // !XP_WIN - -#endif // mozilla_TaggedAnonymousMemory_h diff --git a/ios/include/spidermonkey/mozilla/TemplateLib.h b/ios/include/spidermonkey/mozilla/TemplateLib.h deleted file mode 100644 index 6286452d..00000000 --- a/ios/include/spidermonkey/mozilla/TemplateLib.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Reusable template meta-functions on types and compile-time values. Meta- - * functions are placed inside the 'tl' namespace to avoid conflict with non- - * meta functions of the same name (e.g., mozilla::tl::FloorLog2 vs. - * mozilla::FloorLog2). - * - * When constexpr support becomes universal, we should probably use that instead - * of some of these templates, for simplicity. - */ - -#ifndef mozilla_TemplateLib_h -#define mozilla_TemplateLib_h - -#include -#include - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -namespace tl { - -/** Compute min/max. */ -template -struct Min -{ - static const size_t value = I < J ? I : J; -}; -template -struct Max -{ - static const size_t value = I > J ? I : J; -}; - -/** Compute floor(log2(i)). */ -template -struct FloorLog2 -{ - static const size_t value = 1 + FloorLog2::value; -}; -template<> struct FloorLog2<0> { /* Error */ }; -template<> struct FloorLog2<1> { static const size_t value = 0; }; - -/** Compute ceiling(log2(i)). */ -template -struct CeilingLog2 -{ - static const size_t value = FloorLog2<2 * I - 1>::value; -}; - -/** Round up to the nearest power of 2. */ -template -struct RoundUpPow2 -{ - static const size_t value = size_t(1) << CeilingLog2::value; -}; -template<> -struct RoundUpPow2<0> -{ - static const size_t value = 1; -}; - -/** Compute the number of bits in the given unsigned type. */ -template -struct BitSize -{ - static const size_t value = sizeof(T) * CHAR_BIT; -}; - -/** - * Produce an N-bit mask, where N <= BitSize::value. Handle the - * language-undefined edge case when N = BitSize::value. - */ -template -struct NBitMask -{ - // Assert the precondition. On success this evaluates to 0. Otherwise it - // triggers divide-by-zero at compile time: a guaranteed compile error in - // C++11, and usually one in C++98. Add this value to |value| to assure - // its computation. - static const size_t checkPrecondition = - 0 / size_t(N < BitSize::value); - static const size_t value = (size_t(1) << N) - 1 + checkPrecondition; -}; -template<> -struct NBitMask::value> -{ - static const size_t value = size_t(-1); -}; - -/** - * For the unsigned integral type size_t, compute a mask M for N such that - * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) - */ -template -struct MulOverflowMask -{ - static const size_t value = - ~NBitMask::value - CeilingLog2::value>::value; -}; -template<> struct MulOverflowMask<0> { /* Error */ }; -template<> struct MulOverflowMask<1> { static const size_t value = 0; }; - -/** - * And computes the logical 'and' of its argument booleans. - * - * Examples: - * mozilla::t1::And::value is true. - * mozilla::t1::And::value is false. - * mozilla::t1::And<>::value is true. - */ - -template -struct And; - -template<> -struct And<> : public TrueType { }; - -template -struct And - : public Conditional, FalseType>::Type { }; - -} // namespace tl - -} // namespace mozilla - -#endif /* mozilla_TemplateLib_h */ diff --git a/ios/include/spidermonkey/mozilla/ThreadLocal.h b/ios/include/spidermonkey/mozilla/ThreadLocal.h deleted file mode 100644 index 880e6773..00000000 --- a/ios/include/spidermonkey/mozilla/ThreadLocal.h +++ /dev/null @@ -1,222 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Cross-platform lightweight thread local data wrappers. */ - -#ifndef mozilla_ThreadLocal_h -#define mozilla_ThreadLocal_h - -#if defined(XP_WIN) -// This file will get included in any file that wants to add a profiler mark. -// In order to not bring together we could include windef.h and -// winbase.h which are sufficient to get the prototypes for the Tls* functions. -// # include -// # include -// Unfortunately, even including these headers causes us to add a bunch of ugly -// stuff to our namespace e.g #define CreateEvent CreateEventW -extern "C" { -__declspec(dllimport) void* __stdcall TlsGetValue(unsigned long); -__declspec(dllimport) int __stdcall TlsSetValue(unsigned long, void*); -__declspec(dllimport) unsigned long __stdcall TlsAlloc(); -} -#else -# include -# include -#endif - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -// sig_safe_t denotes an atomic type which can be read or stored in a single -// instruction. This means that data of this type is safe to be manipulated -// from a signal handler, or other similar asynchronous execution contexts. -#if defined(XP_WIN) -typedef unsigned long sig_safe_t; -#else -typedef sig_atomic_t sig_safe_t; -#endif - -namespace detail { - -#if defined(HAVE_THREAD_TLS_KEYWORD) -#define MOZ_HAS_THREAD_LOCAL -#endif - -/* - * Thread Local Storage helpers. - * - * Usage: - * - * Do not directly instantiate this class. Instead, use the - * MOZ_THREAD_LOCAL macro to declare or define instances. The macro - * takes a type name as its argument. - * - * Declare like this: - * extern MOZ_THREAD_LOCAL(int) tlsInt; - * Define like this: - * MOZ_THREAD_LOCAL(int) tlsInt; - * or: - * static MOZ_THREAD_LOCAL(int) tlsInt; - * - * Only static-storage-duration (e.g. global variables, or static class members) - * objects of this class should be instantiated. This class relies on - * zero-initialization, which is implicit for static-storage-duration objects. - * It doesn't have a custom default constructor, to avoid static initializers. - * - * API usage: - * - * // Create a TLS item. - * // - * // Note that init() should be invoked before the first use of set() - * // or get(). It is ok to call it multiple times. This must be - * // called in a way that avoids possible races with other threads. - * MOZ_THREAD_LOCAL(int) tlsKey; - * if (!tlsKey.init()) { - * // deal with the error - * } - * - * // Set the TLS value - * tlsKey.set(123); - * - * // Get the TLS value - * int value = tlsKey.get(); - */ -template -class ThreadLocal -{ -#ifndef MOZ_HAS_THREAD_LOCAL -#if defined(XP_WIN) - typedef unsigned long key_t; -#else - typedef pthread_key_t key_t; -#endif - - // Integral types narrower than void* must be extended to avoid - // warnings from valgrind on some platforms. This helper type - // achieves that without penalizing the common case of ThreadLocals - // instantiated using a pointer type. - template - struct Helper - { - typedef uintptr_t Type; - }; - - template - struct Helper - { - typedef S *Type; - }; -#endif - - bool initialized() const { -#ifdef MOZ_HAS_THREAD_LOCAL - return true; -#else - return mInited; -#endif - } - -public: - // __thread does not allow non-trivial constructors, but we can - // instead rely on zero-initialization. -#ifndef MOZ_HAS_THREAD_LOCAL - ThreadLocal() - : mKey(0), mInited(false) - {} -#endif - - MOZ_MUST_USE inline bool init(); - - inline T get() const; - - inline void set(const T aValue); - -private: -#ifdef MOZ_HAS_THREAD_LOCAL - T mValue; -#else - key_t mKey; - bool mInited; -#endif -}; - -template -inline bool -ThreadLocal::init() -{ - static_assert(mozilla::IsPointer::value || mozilla::IsIntegral::value, - "mozilla::ThreadLocal must be used with a pointer or " - "integral type"); - static_assert(sizeof(T) <= sizeof(void*), - "mozilla::ThreadLocal can't be used for types larger than " - "a pointer"); - -#ifdef MOZ_HAS_THREAD_LOCAL - return true; -#else - if (!initialized()) { -#ifdef XP_WIN - mKey = TlsAlloc(); - mInited = mKey != 0xFFFFFFFFUL; // TLS_OUT_OF_INDEXES -#else - mInited = !pthread_key_create(&mKey, nullptr); -#endif - } - return mInited; -#endif -} - -template -inline T -ThreadLocal::get() const -{ -#ifdef MOZ_HAS_THREAD_LOCAL - return mValue; -#else - MOZ_ASSERT(initialized()); - void* h; -#ifdef XP_WIN - h = TlsGetValue(mKey); -#else - h = pthread_getspecific(mKey); -#endif - return static_cast(reinterpret_cast::Type>(h)); -#endif -} - -template -inline void -ThreadLocal::set(const T aValue) -{ -#ifdef MOZ_HAS_THREAD_LOCAL - mValue = aValue; -#else - MOZ_ASSERT(initialized()); - void* h = reinterpret_cast(static_cast::Type>(aValue)); -#ifdef XP_WIN - bool succeeded = TlsSetValue(mKey, h); -#else - bool succeeded = !pthread_setspecific(mKey, h); -#endif - if (!succeeded) { - MOZ_CRASH(); - } -#endif -} - -#ifdef MOZ_HAS_THREAD_LOCAL -#define MOZ_THREAD_LOCAL(TYPE) __thread mozilla::detail::ThreadLocal -#else -#define MOZ_THREAD_LOCAL(TYPE) mozilla::detail::ThreadLocal -#endif - -} // namespace detail -} // namespace mozilla - -#endif /* mozilla_ThreadLocal_h */ diff --git a/ios/include/spidermonkey/mozilla/TimeStamp.h b/ios/include/spidermonkey/mozilla/TimeStamp.h deleted file mode 100644 index a1a0eb36..00000000 --- a/ios/include/spidermonkey/mozilla/TimeStamp.h +++ /dev/null @@ -1,609 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_TimeStamp_h -#define mozilla_TimeStamp_h - -#include -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Types.h" - -namespace IPC { -template struct ParamTraits; -} // namespace IPC - -#ifdef XP_WIN -// defines TimeStampValue as a complex value keeping both -// GetTickCount and QueryPerformanceCounter values -#include "TimeStamp_windows.h" -#endif - -namespace mozilla { - -#ifndef XP_WIN -typedef uint64_t TimeStampValue; -#endif - -class TimeStamp; - -/** - * Platform-specific implementation details of BaseTimeDuration. - */ -class BaseTimeDurationPlatformUtils -{ -public: - static MFBT_API double ToSeconds(int64_t aTicks); - static MFBT_API double ToSecondsSigDigits(int64_t aTicks); - static MFBT_API int64_t TicksFromMilliseconds(double aMilliseconds); - static MFBT_API int64_t ResolutionInTicks(); -}; - -/** - * Instances of this class represent the length of an interval of time. - * Negative durations are allowed, meaning the end is before the start. - * - * Internally the duration is stored as a int64_t in units of - * PR_TicksPerSecond() when building with NSPR interval timers, or a - * system-dependent unit when building with system clocks. The - * system-dependent unit must be constant, otherwise the semantics of - * this class would be broken. - * - * The ValueCalculator template parameter determines how arithmetic - * operations are performed on the integer count of ticks (mValue). - */ -template -class BaseTimeDuration -{ -public: - // The default duration is 0. - constexpr BaseTimeDuration() : mValue(0) {} - // Allow construction using '0' as the initial value, for readability, - // but no other numbers (so we don't have any implicit unit conversions). - struct _SomethingVeryRandomHere; - MOZ_IMPLICIT BaseTimeDuration(_SomethingVeryRandomHere* aZero) : mValue(0) - { - MOZ_ASSERT(!aZero, "Who's playing funny games here?"); - } - // Default copy-constructor and assignment are OK - - // Converting copy-constructor and assignment operator - template - explicit BaseTimeDuration(const BaseTimeDuration& aOther) - : mValue(aOther.mValue) - { } - - template - BaseTimeDuration& operator=(const BaseTimeDuration& aOther) - { - mValue = aOther.mValue; - return *this; - } - - double ToSeconds() const - { - if (mValue == INT64_MAX) { - return PositiveInfinity(); - } - if (mValue == INT64_MIN) { - return NegativeInfinity(); - } - return BaseTimeDurationPlatformUtils::ToSeconds(mValue); - } - // Return a duration value that includes digits of time we think to - // be significant. This method should be used when displaying a - // time to humans. - double ToSecondsSigDigits() const - { - if (mValue == INT64_MAX) { - return PositiveInfinity(); - } - if (mValue == INT64_MIN) { - return NegativeInfinity(); - } - return BaseTimeDurationPlatformUtils::ToSecondsSigDigits(mValue); - } - double ToMilliseconds() const { return ToSeconds() * 1000.0; } - double ToMicroseconds() const { return ToMilliseconds() * 1000.0; } - - // Using a double here is safe enough; with 53 bits we can represent - // durations up to over 280,000 years exactly. If the units of - // mValue do not allow us to represent durations of that length, - // long durations are clamped to the max/min representable value - // instead of overflowing. - static inline BaseTimeDuration FromSeconds(double aSeconds) - { - return FromMilliseconds(aSeconds * 1000.0); - } - static BaseTimeDuration FromMilliseconds(double aMilliseconds) - { - if (aMilliseconds == PositiveInfinity()) { - return Forever(); - } - if (aMilliseconds == NegativeInfinity()) { - return FromTicks(INT64_MIN); - } - return FromTicks( - BaseTimeDurationPlatformUtils::TicksFromMilliseconds(aMilliseconds)); - } - static inline BaseTimeDuration FromMicroseconds(double aMicroseconds) - { - return FromMilliseconds(aMicroseconds / 1000.0); - } - - static BaseTimeDuration Forever() - { - return FromTicks(INT64_MAX); - } - - BaseTimeDuration operator+(const BaseTimeDuration& aOther) const - { - return FromTicks(ValueCalculator::Add(mValue, aOther.mValue)); - } - BaseTimeDuration operator-(const BaseTimeDuration& aOther) const - { - return FromTicks(ValueCalculator::Subtract(mValue, aOther.mValue)); - } - BaseTimeDuration& operator+=(const BaseTimeDuration& aOther) - { - mValue = ValueCalculator::Add(mValue, aOther.mValue); - return *this; - } - BaseTimeDuration& operator-=(const BaseTimeDuration& aOther) - { - mValue = ValueCalculator::Subtract(mValue, aOther.mValue); - return *this; - } - BaseTimeDuration operator-() const - { - // We don't just use FromTicks(ValueCalculator::Subtract(0, mValue)) - // since that won't give the correct result for -TimeDuration::Forever(). - int64_t ticks; - if (mValue == INT64_MAX) { - ticks = INT64_MIN; - } else if (mValue == INT64_MIN) { - ticks = INT64_MAX; - } else { - ticks = -mValue; - } - - return FromTicks(ticks); - } - -private: - // Block double multiplier (slower, imprecise if long duration) - Bug 853398. - // If required, use MultDouble explicitly and with care. - BaseTimeDuration operator*(const double aMultiplier) const = delete; - - // Block double divisor (for the same reason, and because dividing by - // fractional values would otherwise invoke the int64_t variant, and rounding - // the passed argument can then cause divide-by-zero) - Bug 1147491. - BaseTimeDuration operator/(const double aDivisor) const = delete; - -public: - BaseTimeDuration MultDouble(double aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const int32_t aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const uint32_t aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const int64_t aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const uint64_t aMultiplier) const - { - if (aMultiplier > INT64_MAX) { - return Forever(); - } - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator/(const int64_t aDivisor) const - { - MOZ_ASSERT(aDivisor != 0, "Division by zero"); - return FromTicks(ValueCalculator::Divide(mValue, aDivisor)); - } - double operator/(const BaseTimeDuration& aOther) const - { -#ifndef MOZ_B2G - // Bug 1066388 - This fails on B2G ICS Emulator - MOZ_ASSERT(aOther.mValue != 0, "Division by zero"); -#endif - return ValueCalculator::DivideDouble(mValue, aOther.mValue); - } - BaseTimeDuration operator%(const BaseTimeDuration& aOther) const - { - MOZ_ASSERT(aOther.mValue != 0, "Division by zero"); - return FromTicks(ValueCalculator::Modulo(mValue, aOther.mValue)); - } - - template - bool operator<(const BaseTimeDuration& aOther) const - { - return mValue < aOther.mValue; - } - template - bool operator<=(const BaseTimeDuration& aOther) const - { - return mValue <= aOther.mValue; - } - template - bool operator>=(const BaseTimeDuration& aOther) const - { - return mValue >= aOther.mValue; - } - template - bool operator>(const BaseTimeDuration& aOther) const - { - return mValue > aOther.mValue; - } - template - bool operator==(const BaseTimeDuration& aOther) const - { - return mValue == aOther.mValue; - } - template - bool operator!=(const BaseTimeDuration& aOther) const - { - return mValue != aOther.mValue; - } - bool IsZero() const - { - return mValue == 0; - } - explicit operator bool() const - { - return mValue != 0; - } - - // Return a best guess at the system's current timing resolution, - // which might be variable. BaseTimeDurations below this order of - // magnitude are meaningless, and those at the same order of - // magnitude or just above are suspect. - static BaseTimeDuration Resolution() { - return FromTicks(BaseTimeDurationPlatformUtils::ResolutionInTicks()); - } - - // We could define additional operators here: - // -- convert to/from other time units - // -- scale duration by a float - // but let's do that on demand. - // Comparing durations for equality will only lead to bugs on - // platforms with high-resolution timers. - -private: - friend class TimeStamp; - friend struct IPC::ParamTraits>; - template - friend class BaseTimeDuration; - - static BaseTimeDuration FromTicks(int64_t aTicks) - { - BaseTimeDuration t; - t.mValue = aTicks; - return t; - } - - static BaseTimeDuration FromTicks(double aTicks) - { - // NOTE: this MUST be a >= test, because int64_t(double(INT64_MAX)) - // overflows and gives INT64_MIN. - if (aTicks >= double(INT64_MAX)) { - return FromTicks(INT64_MAX); - } - - // This MUST be a <= test. - if (aTicks <= double(INT64_MIN)) { - return FromTicks(INT64_MIN); - } - - return FromTicks(int64_t(aTicks)); - } - - // Duration, result is implementation-specific difference of two TimeStamps - int64_t mValue; -}; - -/** - * Perform arithmetic operations on the value of a BaseTimeDuration without - * doing strict checks on the range of values. - */ -class TimeDurationValueCalculator -{ -public: - static int64_t Add(int64_t aA, int64_t aB) { return aA + aB; } - static int64_t Subtract(int64_t aA, int64_t aB) { return aA - aB; } - - template - static int64_t Multiply(int64_t aA, T aB) - { - static_assert(IsIntegral::value, - "Using integer multiplication routine with non-integer type." - " Further specialization required"); - return aA * static_cast(aB); - } - - static int64_t Divide(int64_t aA, int64_t aB) { return aA / aB; } - static double DivideDouble(int64_t aA, int64_t aB) - { - return static_cast(aA) / aB; - } - static int64_t Modulo(int64_t aA, int64_t aB) { return aA % aB; } -}; - -template <> -inline int64_t -TimeDurationValueCalculator::Multiply(int64_t aA, double aB) -{ - return static_cast(aA * aB); -} - -/** - * Specialization of BaseTimeDuration that uses TimeDurationValueCalculator for - * arithmetic on the mValue member. - * - * Use this class for time durations that are *not* expected to hold values of - * Forever (or the negative equivalent) or when such time duration are *not* - * expected to be used in arithmetic operations. - */ -typedef BaseTimeDuration TimeDuration; - -/** - * Instances of this class represent moments in time, or a special - * "null" moment. We do not use the non-monotonic system clock or - * local time, since they can be reset, causing apparent backward - * travel in time, which can confuse algorithms. Instead we measure - * elapsed time according to the system. This time can never go - * backwards (i.e. it never wraps around, at least not in less than - * five million years of system elapsed time). It might not advance - * while the system is sleeping. If TimeStamp::SetNow() is not called - * at all for hours or days, we might not notice the passage of some - * of that time. - * - * We deliberately do not expose a way to convert TimeStamps to some - * particular unit. All you can do is compute a difference between two - * TimeStamps to get a TimeDuration. You can also add a TimeDuration - * to a TimeStamp to get a new TimeStamp. You can't do something - * meaningless like add two TimeStamps. - * - * Internally this is implemented as either a wrapper around - * - high-resolution, monotonic, system clocks if they exist on this - * platform - * - PRIntervalTime otherwise. We detect wraparounds of - * PRIntervalTime and work around them. - * - * This class is similar to C++11's time_point, however it is - * explicitly nullable and provides an IsNull() method. time_point - * is initialized to the clock's epoch and provides a - * time_since_epoch() method that functions similiarly. i.e. - * t.IsNull() is equivalent to t.time_since_epoch() == decltype(t)::duration::zero(); - */ -class TimeStamp -{ -public: - /** - * Initialize to the "null" moment - */ - constexpr TimeStamp() : mValue(0) {} - // Default copy-constructor and assignment are OK - - /** - * The system timestamps are the same as the TimeStamp - * retrieved by mozilla::TimeStamp. Since we need this for - * vsync timestamps, we enable the creation of mozilla::TimeStamps - * on platforms that support vsync aligned refresh drivers / compositors - * Verified true as of Jan 31, 2015: B2G and OS X - * False on Windows 7 - * UNTESTED ON OTHER PLATFORMS - */ -#if defined(MOZ_WIDGET_GONK) || defined(XP_DARWIN) - static TimeStamp FromSystemTime(int64_t aSystemTime) - { - static_assert(sizeof(aSystemTime) == sizeof(TimeStampValue), - "System timestamp should be same units as TimeStampValue"); - return TimeStamp(aSystemTime); - } -#endif - - /** - * Return true if this is the "null" moment - */ - bool IsNull() const { return mValue == 0; } - - /** - * Return true if this is not the "null" moment, may be used in tests, e.g.: - * |if (timestamp) { ... }| - */ - explicit operator bool() const - { - return mValue != 0; - } - - /** - * Return a timestamp reflecting the current elapsed system time. This - * is monotonically increasing (i.e., does not decrease) over the - * lifetime of this process' XPCOM session. - * - * Now() is trying to ensure the best possible precision on each platform, - * at least one millisecond. - * - * NowLoRes() has been introduced to workaround performance problems of - * QueryPerformanceCounter on the Windows platform. NowLoRes() is giving - * lower precision, usually 15.6 ms, but with very good performance benefit. - * Use it for measurements of longer times, like >200ms timeouts. - */ - static TimeStamp Now() { return Now(true); } - static TimeStamp NowLoRes() { return Now(false); } - - /** - * Return a timestamp representing the time when the current process was - * created which will be comparable with other timestamps taken with this - * class. If the actual process creation time is detected to be inconsistent - * the @a aIsInconsistent parameter will be set to true, the returned - * timestamp however will still be valid though inaccurate. - * - * @param aIsInconsistent Set to true if an inconsistency was detected in the - * process creation time - * @returns A timestamp representing the time when the process was created, - * this timestamp is always valid even when errors are reported - */ - static MFBT_API TimeStamp ProcessCreation(bool& aIsInconsistent); - - /** - * Records a process restart. After this call ProcessCreation() will return - * the time when the browser was restarted instead of the actual time when - * the process was created. - */ - static MFBT_API void RecordProcessRestart(); - - /** - * Compute the difference between two timestamps. Both must be non-null. - */ - TimeDuration operator-(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - static_assert(-INT64_MAX > INT64_MIN, "int64_t sanity check"); - int64_t ticks = int64_t(mValue - aOther.mValue); - // Check for overflow. - if (mValue > aOther.mValue) { - if (ticks < 0) { - ticks = INT64_MAX; - } - } else { - if (ticks > 0) { - ticks = INT64_MIN; - } - } - return TimeDuration::FromTicks(ticks); - } - - TimeStamp operator+(const TimeDuration& aOther) const - { - TimeStamp result = *this; - result += aOther; - return result; - } - TimeStamp operator-(const TimeDuration& aOther) const - { - TimeStamp result = *this; - result -= aOther; - return result; - } - TimeStamp& operator+=(const TimeDuration& aOther) - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - TimeStampValue value = mValue + aOther.mValue; - // Check for underflow. - // (We don't check for overflow because it's not obvious what the error - // behavior should be in that case.) - if (aOther.mValue < 0 && value > mValue) { - value = 0; - } - mValue = value; - return *this; - } - TimeStamp& operator-=(const TimeDuration& aOther) - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - TimeStampValue value = mValue - aOther.mValue; - // Check for underflow. - // (We don't check for overflow because it's not obvious what the error - // behavior should be in that case.) - if (aOther.mValue > 0 && value > mValue) { - value = 0; - } - mValue = value; - return *this; - } - - bool operator<(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue < aOther.mValue; - } - bool operator<=(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue <= aOther.mValue; - } - bool operator>=(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue >= aOther.mValue; - } - bool operator>(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue > aOther.mValue; - } - bool operator==(const TimeStamp& aOther) const - { - return IsNull() - ? aOther.IsNull() - : !aOther.IsNull() && mValue == aOther.mValue; - } - bool operator!=(const TimeStamp& aOther) const - { - return !(*this == aOther); - } - - // Comparing TimeStamps for equality should be discouraged. Adding - // two TimeStamps, or scaling TimeStamps, is nonsense and must never - // be allowed. - - static MFBT_API void Startup(); - static MFBT_API void Shutdown(); - -private: - friend struct IPC::ParamTraits; - friend void StartupTimelineRecordExternal(int, uint64_t); - - MOZ_IMPLICIT TimeStamp(TimeStampValue aValue) : mValue(aValue) {} - - static MFBT_API TimeStamp Now(bool aHighResolution); - - /** - * Computes the uptime of the current process in microseconds. The result - * is platform-dependent and needs to be checked against existing timestamps - * for consistency. - * - * @returns The number of microseconds since the calling process was started - * or 0 if an error was encountered while computing the uptime - */ - static MFBT_API uint64_t ComputeProcessUptime(); - - /** - * When built with PRIntervalTime, a value of 0 means this instance - * is "null". Otherwise, the low 32 bits represent a PRIntervalTime, - * and the high 32 bits represent a counter of the number of - * rollovers of PRIntervalTime that we've seen. This counter starts - * at 1 to avoid a real time colliding with the "null" value. - * - * PR_INTERVAL_MAX is set at 100,000 ticks per second. So the minimum - * time to wrap around is about 2^64/100000 seconds, i.e. about - * 5,849,424 years. - * - * When using a system clock, a value is system dependent. - */ - TimeStampValue mValue; -}; - -} // namespace mozilla - -#endif /* mozilla_TimeStamp_h */ diff --git a/ios/include/spidermonkey/mozilla/ToString.h b/ios/include/spidermonkey/mozilla/ToString.h deleted file mode 100644 index f11cad5c..00000000 --- a/ios/include/spidermonkey/mozilla/ToString.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Utilities for converting an object to a string representation. */ - -#ifndef mozilla_ToString_h -#define mozilla_ToString_h - -#include -#include - -namespace mozilla { - -/** - * A convenience function for converting an object to a string representation. - * Supports any object which can be streamed to an std::ostream. - */ -template -std::string -ToString(const T& aValue) -{ - std::ostringstream stream; - stream << aValue; - return stream.str(); -} - -} // namespace mozilla - -#endif /* mozilla_ToString_h */ diff --git a/ios/include/spidermonkey/mozilla/Tuple.h b/ios/include/spidermonkey/mozilla/Tuple.h deleted file mode 100644 index a7f9bee6..00000000 --- a/ios/include/spidermonkey/mozilla/Tuple.h +++ /dev/null @@ -1,461 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A variadic tuple class. */ - -#ifndef mozilla_Tuple_h -#define mozilla_Tuple_h - -#include "mozilla/Move.h" -#include "mozilla/Pair.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/TypeTraits.h" - -#include -#include - -namespace mozilla { - -namespace detail { - -/* - * A helper class that allows passing around multiple variadic argument lists - * by grouping them. - */ -template -struct Group; - -/* - * CheckConvertibility checks whether each type in a source pack of types - * is convertible to the corresponding type in a target pack of types. - * - * It is intended to be invoked like this: - * CheckConvertibility, Group> - * 'Group' is used to separate types in the two packs (otherwise if we just - * wrote 'CheckConvertibility -struct CheckConvertibilityImpl; - -template -struct CheckConvertibilityImpl - : FalseType {}; - -template -struct CheckConvertibilityImpl, Group, true> - : IntegralConstant::value...>::value> { }; - -template -struct CheckConvertibility; - -template -struct CheckConvertibility, Group> - : CheckConvertibilityImpl, Group, - sizeof...(SourceTypes) == sizeof...(TargetTypes)> { }; - -/* - * TupleImpl is a helper class used to implement mozilla::Tuple. - * It represents one node in a recursive inheritance hierarchy. - * 'Index' is the 0-based index of the tuple element stored in this node; - * 'Elements...' are the types of the elements stored in this node and its - * base classes. - * - * Example: - * Tuple inherits from - * TupleImpl<0, int, float, char>, which stores the 'int' and inherits from - * TupleImpl<1, float, char>, which stores the 'float' and inherits from - * TupleImpl<2, char>, which stores the 'char' and inherits from - * TupleImpl<3>, which stores nothing and terminates the recursion. - * - * The purpose of the 'Index' parameter is to allow efficient index-based - * access to a tuple element: given a tuple, and an index 'I' that we wish to - * access, we can cast the tuple to the base which stores the I'th element - * by performing template argument deduction against 'TupleImpl', - * where 'I' is specified explicitly and 'E...' is deduced (this is what the - * non-member 'Get(t)' function does). - * - * This implementation strategy is borrowed from libstdc++'s std::tuple - * implementation. - */ -template -struct TupleImpl; - -/* - * The base case of the inheritance recursion (and also the implementation - * of an empty tuple). - */ -template -struct TupleImpl { - bool operator==(const TupleImpl& aOther) const - { - return true; - } -}; - -/* - * One node of the recursive inheritance hierarchy. It stores the element at - * index 'Index' of a tuple, of type 'HeadT', and inherits from the nodes - * that store the remaining elements, of types 'TailT...'. - */ -template -struct TupleImpl - : public TupleImpl -{ - typedef TupleImpl Base; - - // Accessors for the head and the tail. - // These are static, because the intended usage is for the caller to, - // given a tuple, obtain the type B of the base class which stores the - // element of interest, and then call B::Head(tuple) to access it. - // (Tail() is mostly for internal use, but is exposed for consistency.) - static HeadT& Head(TupleImpl& aTuple) { return aTuple.mHead; } - static const HeadT& Head(const TupleImpl& aTuple) { return aTuple.mHead; } - static Base& Tail(TupleImpl& aTuple) { return aTuple; } - static const Base& Tail(const TupleImpl& aTuple) { return aTuple; } - - TupleImpl() : Base(), mHead() { } - - // Construct from const references to the elements. - explicit TupleImpl(const HeadT& aHead, const TailT&... aTail) - : Base(aTail...), mHead(aHead) { } - - // Construct from objects that are convertible to the elements. - // This constructor is enabled only when the argument types are actually - // convertible to the element types, otherwise it could become a better - // match for certain invocations than the copy constructor. - template , - Group>::value>::Type> - explicit TupleImpl(OtherHeadT&& aHead, OtherTailT&&... aTail) - : Base(Forward(aTail)...), mHead(Forward(aHead)) { } - - // Copy and move constructors. - // We'd like to use '= default' to implement these, but MSVC 2013's support - // for '= default' is incomplete and this doesn't work. - TupleImpl(const TupleImpl& aOther) - : Base(Tail(aOther)) - , mHead(Head(aOther)) {} - TupleImpl(TupleImpl&& aOther) - : Base(Move(Tail(aOther))) - , mHead(Forward(Head(aOther))) {} - - // Assign from a tuple whose elements are convertible to the elements - // of this tuple. - template ::Type> - TupleImpl& operator=(const TupleImpl& aOther) - { - typedef TupleImpl OtherT; - Head(*this) = OtherT::Head(aOther); - Tail(*this) = OtherT::Tail(aOther); - return *this; - } - template ::Type> - TupleImpl& operator=(TupleImpl&& aOther) - { - typedef TupleImpl OtherT; - Head(*this) = Move(OtherT::Head(aOther)); - Tail(*this) = Move(OtherT::Tail(aOther)); - return *this; - } - - // Copy and move assignment operators. - TupleImpl& operator=(const TupleImpl& aOther) - { - Head(*this) = Head(aOther); - Tail(*this) = Tail(aOther); - return *this; - } - TupleImpl& operator=(TupleImpl&& aOther) - { - Head(*this) = Move(Head(aOther)); - Tail(*this) = Move(Tail(aOther)); - return *this; - } - bool operator==(const TupleImpl& aOther) const - { - return Head(*this) == Head(aOther) && Tail(*this) == Tail(aOther); - } -private: - HeadT mHead; // The element stored at this index in the tuple. -}; - -} // namespace detail - -/** - * Tuple is a class that stores zero or more objects, whose types are specified - * as template parameters. It can be thought of as a generalization of Pair, - * (which can be thought of as a 2-tuple). - * - * Tuple allows index-based access to its elements (with the index having to be - * known at compile time) via the non-member function 'Get(tuple)'. - */ -template -class Tuple : public detail::TupleImpl<0, Elements...> -{ - typedef detail::TupleImpl<0, Elements...> Impl; -public: - // The constructors and assignment operators here are simple wrappers - // around those in TupleImpl. - - Tuple() : Impl() { } - explicit Tuple(const Elements&... aElements) : Impl(aElements...) { } - // Here, we can't just use 'typename... OtherElements' because MSVC will give - // a warning "C4520: multiple default constructors specified" (even if no one - // actually instantiates the constructor with an empty parameter pack - - // that's probably a bug) and we compile with warnings-as-errors. - template , - detail::Group>::value>::Type> - explicit Tuple(OtherHead&& aHead, OtherTail&&... aTail) - : Impl(Forward(aHead), Forward(aTail)...) { } - Tuple(const Tuple& aOther) : Impl(aOther) { } - Tuple(Tuple&& aOther) : Impl(Move(aOther)) { } - - template ::Type> - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - template ::Type> - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - bool operator==(const Tuple& aOther) const - { - return static_cast(*this) == static_cast(aOther); - } -}; - -/** - * Specialization of Tuple for two elements. - * This is created to support construction and assignment from a Pair or std::pair. - */ -template -class Tuple : public detail::TupleImpl<0, A, B> -{ - typedef detail::TupleImpl<0, A, B> Impl; - -public: - // The constructors and assignment operators here are simple wrappers - // around those in TupleImpl. - - Tuple() : Impl() { } - explicit Tuple(const A& aA, const B& aB) : Impl(aA, aB) { } - template , - detail::Group>::value>::Type> - explicit Tuple(AArg&& aA, BArg&& aB) - : Impl(Forward(aA), Forward(aB)) { } - Tuple(const Tuple& aOther) : Impl(aOther) { } - Tuple(Tuple&& aOther) : Impl(Move(aOther)) { } - explicit Tuple(const Pair& aOther) - : Impl(aOther.first(), aOther.second()) { } - explicit Tuple(Pair&& aOther) : Impl(Forward(aOther.first()), - Forward(aOther.second())) { } - explicit Tuple(const std::pair& aOther) - : Impl(aOther.first, aOther.second) { } - explicit Tuple(std::pair&& aOther) : Impl(Forward(aOther.first), - Forward(aOther.second)) { } - - template - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - template - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - template - Tuple& operator=(const Pair& aOther) - { - Impl::Head(*this) = aOther.first(); - Impl::Tail(*this).Head(*this) = aOther.second(); - return *this; - } - template - Tuple& operator=(Pair&& aOther) - { - Impl::Head(*this) = Forward(aOther.first()); - Impl::Tail(*this).Head(*this) = Forward(aOther.second()); - return *this; - } - template - Tuple& operator=(const std::pair& aOther) - { - Impl::Head(*this) = aOther.first; - Impl::Tail(*this).Head(*this) = aOther.second; - return *this; - } - template - Tuple& operator=(std::pair&& aOther) - { - Impl::Head(*this) = Forward(aOther.first); - Impl::Tail(*this).Head(*this) = Forward(aOther.second); - return *this; - } -}; - -/** - * Specialization of Tuple for zero arguments. - * This is necessary because if the primary template were instantiated with - * an empty parameter pack, the 'Tuple(Elements...)' constructors would - * become illegal overloads of the default constructor. - */ -template <> -class Tuple<> {}; - -namespace detail { - -/* - * Helper functions for implementing Get(tuple). - * These functions take a TupleImpl, with Index being - * explicitly specified, and Elements being deduced. By passing a Tuple - * object as argument, template argument deduction will do its magic and - * cast the tuple to the base class which stores the element at Index. - */ - -// Const reference version. -template -auto TupleGetHelper(TupleImpl& aTuple) - -> decltype(TupleImpl::Head(aTuple)) -{ - return TupleImpl::Head(aTuple); -} - -// Non-const reference version. -template -auto TupleGetHelper(const TupleImpl& aTuple) - -> decltype(TupleImpl::Head(aTuple)) -{ - return TupleImpl::Head(aTuple); -} - -} // namespace detail - -/** - * Index-based access to an element of a tuple. - * The syntax is Get(tuple). The index is zero-based. - * - * Example: - * - * Tuple t; - * ... - * float f = Get<1>(t); - */ - -// Non-const reference version. -template -auto Get(Tuple& aTuple) - -> decltype(detail::TupleGetHelper(aTuple)) -{ - return detail::TupleGetHelper(aTuple); -} - -// Const reference version. -template -auto Get(const Tuple& aTuple) - -> decltype(detail::TupleGetHelper(aTuple)) -{ - return detail::TupleGetHelper(aTuple); -} - -// Rvalue reference version. -template -auto Get(Tuple&& aTuple) - -> decltype(Move(mozilla::Get(aTuple))) -{ - // We need a 'mozilla::' qualification here to avoid - // name lookup only finding the current function. - return Move(mozilla::Get(aTuple)); -} - -/** - * A convenience function for constructing a tuple out of a sequence of - * values without specifying the type of the tuple. - * The type of the tuple is deduced from the types of its elements. - * - * Example: - * - * auto tuple = MakeTuple(42, 0.5f, 'c'); // has type Tuple - */ -template -inline Tuple::Type...> -MakeTuple(Elements&&... aElements) -{ - return Tuple::Type...>(Forward(aElements)...); -} - -/** - * A convenience function for constructing a tuple of references to a - * sequence of variables. Since assignments to the elements of the tuple - * "go through" to the referenced variables, this can be used to "unpack" - * a tuple into individual variables. - * - * Example: - * - * int i; - * float f; - * char c; - * Tie(i, f, c) = FunctionThatReturnsATuple(); - */ -template -inline Tuple -Tie(Elements&... aVariables) -{ - return Tuple(aVariables...); -} - -} // namespace mozilla - -#endif /* mozilla_Tuple_h */ diff --git a/ios/include/spidermonkey/mozilla/TypeTraits.h b/ios/include/spidermonkey/mozilla/TypeTraits.h deleted file mode 100644 index 084f608c..00000000 --- a/ios/include/spidermonkey/mozilla/TypeTraits.h +++ /dev/null @@ -1,1262 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Template-based metaprogramming and type-testing facilities. */ - -#ifndef mozilla_TypeTraits_h -#define mozilla_TypeTraits_h - -#include "mozilla/Types.h" - -/* - * These traits are approximate copies of the traits and semantics from C++11's - * header. Don't add traits not in that header! When all - * platforms provide that header, we can convert all users and remove this one. - */ - -#include - -namespace mozilla { - -/* Forward declarations. */ - -template struct RemoveCV; -template struct AddRvalueReference; - -/* 20.2.4 Function template declval [declval] */ - -/** - * DeclVal simplifies the definition of expressions which occur as unevaluated - * operands. It converts T to a reference type, making it possible to use in - * decltype expressions even if T does not have a default constructor, e.g.: - * decltype(DeclVal().foo()) - */ -template -typename AddRvalueReference::Type DeclVal(); - -/* 20.9.3 Helper classes [meta.help] */ - -/** - * Helper class used as a base for various type traits, exposed publicly - * because exposes it as well. - */ -template -struct IntegralConstant -{ - static const T value = Value; - typedef T ValueType; - typedef IntegralConstant Type; -}; - -/** Convenient aliases. */ -typedef IntegralConstant TrueType; -typedef IntegralConstant FalseType; - -/* 20.9.4 Unary type traits [meta.unary] */ - -/* 20.9.4.1 Primary type categories [meta.unary.cat] */ - -namespace detail { - -template -struct IsVoidHelper : FalseType {}; - -template<> -struct IsVoidHelper : TrueType {}; - -} // namespace detail - -/** - * IsVoid determines whether a type is void. - * - * mozilla::IsVoid::value is false; - * mozilla::IsVoid::value is true; - * mozilla::IsVoid::value is false; - * mozilla::IsVoid::value is true. - */ -template -struct IsVoid : detail::IsVoidHelper::Type> {}; - -namespace detail { - -template -struct IsIntegralHelper : FalseType {}; - -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; - -} /* namespace detail */ - -/** - * IsIntegral determines whether a type is an integral type. - * - * mozilla::IsIntegral::value is true; - * mozilla::IsIntegral::value is true; - * mozilla::IsIntegral::value is true; - * mozilla::IsIntegral::value is false; - * mozilla::IsIntegral::value is false; - */ -template -struct IsIntegral : detail::IsIntegralHelper::Type> -{}; - -template -struct IsSame; - -namespace detail { - -template -struct IsFloatingPointHelper - : IntegralConstant::value || - IsSame::value || - IsSame::value> -{}; - -} // namespace detail - -/** - * IsFloatingPoint determines whether a type is a floating point type (float, - * double, long double). - * - * mozilla::IsFloatingPoint::value is false; - * mozilla::IsFloatingPoint::value is true; - * mozilla::IsFloatingPoint::value is true; - * mozilla::IsFloatingPoint::value is false. - */ -template -struct IsFloatingPoint - : detail::IsFloatingPointHelper::Type> -{}; - -namespace detail { - -template -struct IsArrayHelper : FalseType {}; - -template -struct IsArrayHelper : TrueType {}; - -template -struct IsArrayHelper : TrueType {}; - -} // namespace detail - -/** - * IsArray determines whether a type is an array type, of known or unknown - * length. - * - * mozilla::IsArray::value is false; - * mozilla::IsArray::value is true; - * mozilla::IsArray::value is true. - */ -template -struct IsArray : detail::IsArrayHelper::Type> -{}; - -namespace detail { - -template -struct IsFunPtr; - -template -struct IsFunPtr - : public FalseType -{}; - -template -struct IsFunPtr - : public TrueType -{}; - -}; // namespace detail - -/** - * IsFunction determines whether a type is a function type. Function pointers - * don't qualify here--only the type of an actual function symbol. We do not - * correctly handle varags function types because of a bug in MSVC. - * - * Given the function: - * void f(int) {} - * - * mozilla::IsFunction is true; - * mozilla::IsFunction is false; - * mozilla::IsFunction is true. - */ -template -struct IsFunction - : public detail::IsFunPtr::Type *> -{}; - -namespace detail { - -template -struct IsPointerHelper : FalseType {}; - -template -struct IsPointerHelper : TrueType {}; - -} // namespace detail - -/** - * IsPointer determines whether a type is a possibly-CV-qualified pointer type - * (but not a pointer-to-member type). - * - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is false; - * mozilla::IsPointer::value is false. - * mozilla::IsPointer::value is false - */ -template -struct IsPointer : detail::IsPointerHelper::Type> -{}; - -/** - * IsLvalueReference determines whether a type is an lvalue reference. - * - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is true; - * mozilla::IsLvalueReference::value is false. - */ -template -struct IsLvalueReference : FalseType {}; - -template -struct IsLvalueReference : TrueType {}; - -/** - * IsRvalueReference determines whether a type is an rvalue reference. - * - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is true. - */ -template -struct IsRvalueReference : FalseType {}; - -template -struct IsRvalueReference : TrueType {}; - -namespace detail { - -// __is_enum is a supported extension across all of our supported compilers. -template -struct IsEnumHelper - : IntegralConstant -{}; - -} // namespace detail - -/** - * IsEnum determines whether a type is an enum type. - * - * mozilla::IsEnum::value is true; - * mozilla::IsEnum::value is false; - * mozilla::IsEnum::value is false; - */ -template -struct IsEnum - : detail::IsEnumHelper::Type> -{}; - -namespace detail { - -// __is_class is a supported extension across all of our supported compilers: -// http://llvm.org/releases/3.0/docs/ClangReleaseNotes.html -// http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Type-Traits.html#Type-Traits -// http://msdn.microsoft.com/en-us/library/ms177194%28v=vs.100%29.aspx -template -struct IsClassHelper - : IntegralConstant -{}; - -} // namespace detail - -/** - * IsClass determines whether a type is a class type (but not a union). - * - * struct S {}; - * union U {}; - * mozilla::IsClass::value is false; - * mozilla::IsClass::value is true; - * mozilla::IsClass::value is false; - */ -template -struct IsClass - : detail::IsClassHelper::Type> -{}; - -/* 20.9.4.2 Composite type traits [meta.unary.comp] */ - -/** - * IsReference determines whether a type is an lvalue or rvalue reference. - * - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is true. - */ -template -struct IsReference - : IntegralConstant::value || IsRvalueReference::value> -{}; - -/** - * IsArithmetic determines whether a type is arithmetic. A type is arithmetic - * iff it is an integral type or a floating point type. - * - * mozilla::IsArithmetic::value is true; - * mozilla::IsArithmetic::value is true; - * mozilla::IsArithmetic::value is false. - */ -template -struct IsArithmetic - : IntegralConstant::value || IsFloatingPoint::value> -{}; - -namespace detail { - -template -struct IsMemberPointerHelper : FalseType {}; - -template -struct IsMemberPointerHelper : TrueType {}; - -} // namespace detail - -/** - * IsMemberPointer determines whether a type is pointer to non-static member - * object or a pointer to non-static member function. - * - * mozilla::IsMemberPointer::value is true - * mozilla::IsMemberPointer::value is false - */ -template -struct IsMemberPointer - : detail::IsMemberPointerHelper::Type> -{}; - -/** - * IsScalar determines whether a type is a scalar type. - * - * mozilla::IsScalar::value is true - * mozilla::IsScalar::value is true - * mozilla::IsScalar::value is false - */ -template -struct IsScalar - : IntegralConstant::value || IsEnum::value || - IsPointer::value || IsMemberPointer::value> -{}; - -/* 20.9.4.3 Type properties [meta.unary.prop] */ - -/** - * IsConst determines whether a type is const or not. - * - * mozilla::IsConst::value is false; - * mozilla::IsConst::value is true; - * mozilla::IsConst::value is false. - */ -template -struct IsConst : FalseType {}; - -template -struct IsConst : TrueType {}; - -/** - * IsVolatile determines whether a type is volatile or not. - * - * mozilla::IsVolatile::value is false; - * mozilla::IsVolatile::value is true; - * mozilla::IsVolatile::value is false. - */ -template -struct IsVolatile : FalseType {}; - -template -struct IsVolatile : TrueType {}; - -/** - * Traits class for identifying POD types. Until C++11 there's no automatic - * way to detect PODs, so for the moment this is done manually. Users may - * define specializations of this class that inherit from mozilla::TrueType and - * mozilla::FalseType (or equivalently mozilla::IntegralConstant, or conveniently from mozilla::IsPod for composite types) as needed to - * ensure correct IsPod behavior. - */ -template -struct IsPod : public FalseType {}; - -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template struct IsPod : TrueType {}; - -namespace detail { - -// __is_empty is a supported extension across all of our supported compilers: -// http://llvm.org/releases/3.0/docs/ClangReleaseNotes.html -// http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Type-Traits.html#Type-Traits -// http://msdn.microsoft.com/en-us/library/ms177194%28v=vs.100%29.aspx -template -struct IsEmptyHelper - : IntegralConstant::value && __is_empty(T)> -{}; - -} // namespace detail - -/** - * IsEmpty determines whether a type is a class (but not a union) that is empty. - * - * A class is empty iff it and all its base classes have no non-static data - * members (except bit-fields of length 0) and no virtual member functions, and - * no base class is empty or a virtual base class. - * - * Intuitively, empty classes don't have any data that has to be stored in - * instances of those classes. (The size of the class must still be non-zero, - * because distinct array elements of any type must have different addresses. - * However, if the Empty Base Optimization is implemented by the compiler [most - * compilers implement it, and in certain cases C++11 requires it], the size of - * a class inheriting from an empty |Base| class need not be inflated by - * |sizeof(Base)|.) And intuitively, non-empty classes have data members and/or - * vtable pointers that must be stored in each instance for proper behavior. - * - * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); - * union U1 { int x; }; - * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); - * struct E1 {}; - * struct E2 { int : 0 }; - * struct E3 : E1 {}; - * struct E4 : E2 {}; - * static_assert(mozilla::IsEmpty::value && - * mozilla::IsEmpty::value && - * mozilla::IsEmpty::value && - * mozilla::IsEmpty::value, - * "all empty"); - * union U2 { E1 e1; }; - * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); - * struct NE1 { int x; }; - * struct NE2 : virtual E1 {}; - * struct NE3 : E2 { virtual ~NE3() {} }; - * struct NE4 { virtual void f() {} }; - * static_assert(!mozilla::IsEmpty::value && - * !mozilla::IsEmpty::value && - * !mozilla::IsEmpty::value && - * !mozilla::IsEmpty::value, - * "all empty"); - */ -template -struct IsEmpty : detail::IsEmptyHelper::Type> -{}; - - -namespace detail { - -template::value, - bool = IsIntegral::value, - typename NoCV = typename RemoveCV::Type> -struct IsSignedHelper; - -// Floating point is signed. -template -struct IsSignedHelper : TrueType {}; - -// Integral is conditionally signed. -template -struct IsSignedHelper - : IntegralConstant -{}; - -// Non-floating point, non-integral is not signed. -template -struct IsSignedHelper : FalseType {}; - -} // namespace detail - -/** - * IsSigned determines whether a type is a signed arithmetic type. |char| is - * considered a signed type if it has the same representation as |signed char|. - * - * mozilla::IsSigned::value is true; - * mozilla::IsSigned::value is false; - * mozilla::IsSigned::value is false; - * mozilla::IsSigned::value is true. - */ -template -struct IsSigned : detail::IsSignedHelper {}; - -namespace detail { - -template::value, - bool = IsIntegral::value, - typename NoCV = typename RemoveCV::Type> -struct IsUnsignedHelper; - -// Floating point is not unsigned. -template -struct IsUnsignedHelper : FalseType {}; - -// Integral is conditionally unsigned. -template -struct IsUnsignedHelper - : IntegralConstant::value || bool(NoCV(1) < NoCV(-1)))> -{}; - -// Non-floating point, non-integral is not unsigned. -template -struct IsUnsignedHelper : FalseType {}; - -} // namespace detail - -/** - * IsUnsigned determines whether a type is an unsigned arithmetic type. - * - * mozilla::IsUnsigned::value is false; - * mozilla::IsUnsigned::value is true; - * mozilla::IsUnsigned::value is true; - * mozilla::IsUnsigned::value is false. - */ -template -struct IsUnsigned : detail::IsUnsignedHelper {}; - -namespace detail { - -struct DoIsDestructibleImpl -{ - template().~T())> - static TrueType test(int); - template - static FalseType test(...); -}; - -template -struct IsDestructibleImpl : public DoIsDestructibleImpl -{ - typedef decltype(test(0)) Type; -}; - -} // namespace detail - -template -struct IsDestructible : public detail::IsDestructibleImpl::Type {}; - -/* 20.9.5 Type property queries [meta.unary.prop.query] */ - -/* 20.9.6 Relationships between types [meta.rel] */ - -/** - * IsSame tests whether two types are the same type. - * - * mozilla::IsSame::value is true; - * mozilla::IsSame::value is true; - * mozilla::IsSame::value is false; - * mozilla::IsSame::value is true; - * mozilla::IsSame::value is false; - * mozilla::IsSame::value is true. - */ -template -struct IsSame : FalseType {}; - -template -struct IsSame : TrueType {}; - -namespace detail { - -#if defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) - -template -struct BaseOfTester : IntegralConstant {}; - -#else - -// The trickery used to implement IsBaseOf here makes it possible to use it for -// the cases of private and multiple inheritance. This code was inspired by the -// sample code here: -// -// http://stackoverflow.com/questions/2910979/how-is-base-of-works -template -struct BaseOfHelper -{ -public: - operator Base*() const; - operator Derived*(); -}; - -template -struct BaseOfTester -{ -private: - template - static char test(Derived*, T); - static int test(Base*, int); - -public: - static const bool value = - sizeof(test(BaseOfHelper(), int())) == sizeof(char); -}; - -template -struct BaseOfTester -{ -private: - template - static char test(Derived*, T); - static int test(Base*, int); - -public: - static const bool value = - sizeof(test(BaseOfHelper(), int())) == sizeof(char); -}; - -template -struct BaseOfTester : FalseType {}; - -template -struct BaseOfTester : TrueType {}; - -template -struct BaseOfTester : TrueType {}; - -#endif - -} /* namespace detail */ - -/* - * IsBaseOf allows to know whether a given class is derived from another. - * - * Consider the following class definitions: - * - * class A {}; - * class B : public A {}; - * class C {}; - * - * mozilla::IsBaseOf::value is true; - * mozilla::IsBaseOf::value is false; - */ -template -struct IsBaseOf - : IntegralConstant::value> -{}; - -namespace detail { - -template -struct ConvertibleTester -{ -private: - template - static char test_helper(To1); - - template - static decltype(test_helper(DeclVal())) test(int); - - template - static int test(...); - -public: - static const bool value = - sizeof(test(0)) == sizeof(char); -}; - -} // namespace detail - -/** - * IsConvertible determines whether a value of type From will implicitly convert - * to a value of type To. For example: - * - * struct A {}; - * struct B : public A {}; - * struct C {}; - * - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is false; - * mozilla::IsConvertible::value is false; - * mozilla::IsConvertible::value is false; - * mozilla::IsConvertible::value is false. - * - * For obscure reasons, you can't use IsConvertible when the types being tested - * are related through private inheritance, and you'll get a compile error if - * you try. Just don't do it! - * - * Note - we need special handling for void, which ConvertibleTester doesn't - * handle. The void handling here doesn't handle const/volatile void correctly, - * which could be easily fixed if the need arises. - */ -template -struct IsConvertible - : IntegralConstant::value> -{}; - -template -struct IsConvertible - : IntegralConstant::value> -{}; - -template -struct IsConvertible - : IntegralConstant::value> -{}; - -template<> -struct IsConvertible - : TrueType -{}; - -/* 20.9.7 Transformations between types [meta.trans] */ - -/* 20.9.7.1 Const-volatile modifications [meta.trans.cv] */ - -/** - * RemoveConst removes top-level const qualifications on a type. - * - * mozilla::RemoveConst::Type is int; - * mozilla::RemoveConst::Type is int; - * mozilla::RemoveConst::Type is const int*; - * mozilla::RemoveConst::Type is int*. - */ -template -struct RemoveConst -{ - typedef T Type; -}; - -template -struct RemoveConst -{ - typedef T Type; -}; - -/** - * RemoveVolatile removes top-level volatile qualifications on a type. - * - * mozilla::RemoveVolatile::Type is int; - * mozilla::RemoveVolatile::Type is int; - * mozilla::RemoveVolatile::Type is volatile int*; - * mozilla::RemoveVolatile::Type is int*. - */ -template -struct RemoveVolatile -{ - typedef T Type; -}; - -template -struct RemoveVolatile -{ - typedef T Type; -}; - -/** - * RemoveCV removes top-level const and volatile qualifications on a type. - * - * mozilla::RemoveCV::Type is int; - * mozilla::RemoveCV::Type is int; - * mozilla::RemoveCV::Type is int; - * mozilla::RemoveCV::Type is int*. - */ -template -struct RemoveCV -{ - typedef typename RemoveConst::Type>::Type Type; -}; - -/* 20.9.7.2 Reference modifications [meta.trans.ref] */ - -/** - * Converts reference types to the underlying types. - * - * mozilla::RemoveReference::Type is T; - * mozilla::RemoveReference::Type is T; - * mozilla::RemoveReference::Type is T; - */ - -template -struct RemoveReference -{ - typedef T Type; -}; - -template -struct RemoveReference -{ - typedef T Type; -}; - -template -struct RemoveReference -{ - typedef T Type; -}; - -template -struct Conditional; - -namespace detail { - -enum Voidness { TIsVoid, TIsNotVoid }; - -template::value ? TIsVoid : TIsNotVoid> -struct AddLvalueReferenceHelper; - -template -struct AddLvalueReferenceHelper -{ - typedef void Type; -}; - -template -struct AddLvalueReferenceHelper -{ - typedef T& Type; -}; - -} // namespace detail - -/** - * AddLvalueReference adds an lvalue & reference to T if one isn't already - * present. (Note: adding an lvalue reference to an rvalue && reference in - * essence replaces the && with a &&, per C+11 reference collapsing rules. For - * example, int&& would become int&.) - * - * The final computed type will only *not* be an lvalue reference if T is void. - * - * mozilla::AddLvalueReference::Type is int&; - * mozilla::AddLvalueRference::Type is volatile int&; - * mozilla::AddLvalueReference::Type is void*&; - * mozilla::AddLvalueReference::Type is void; - * mozilla::AddLvalueReference::Type is struct S&. - */ -template -struct AddLvalueReference - : detail::AddLvalueReferenceHelper -{}; - -namespace detail { - -template::value ? TIsVoid : TIsNotVoid> -struct AddRvalueReferenceHelper; - -template -struct AddRvalueReferenceHelper -{ - typedef void Type; -}; - -template -struct AddRvalueReferenceHelper -{ - typedef T&& Type; -}; - -} // namespace detail - -/** - * AddRvalueReference adds an rvalue && reference to T if one isn't already - * present. (Note: adding an rvalue reference to an lvalue & reference in - * essence keeps the &, per C+11 reference collapsing rules. For example, - * int& would remain int&.) - * - * The final computed type will only *not* be a reference if T is void. - * - * mozilla::AddRvalueReference::Type is int&&; - * mozilla::AddRvalueRference::Type is volatile int&; - * mozilla::AddRvalueRference::Type is const int&&; - * mozilla::AddRvalueReference::Type is void*&&; - * mozilla::AddRvalueReference::Type is void; - * mozilla::AddRvalueReference::Type is struct S&. - */ -template -struct AddRvalueReference - : detail::AddRvalueReferenceHelper -{}; - -/* 20.9.7.3 Sign modifications [meta.trans.sign] */ - -template -struct EnableIf; - -namespace detail { - -template -struct WithC : Conditional -{}; - -template -struct WithV : Conditional -{}; - - -template -struct WithCV : WithC::Type> -{}; - -template -struct CorrespondingSigned; - -template<> -struct CorrespondingSigned { typedef signed char Type; }; -template<> -struct CorrespondingSigned { typedef signed char Type; }; -template<> -struct CorrespondingSigned { typedef short Type; }; -template<> -struct CorrespondingSigned { typedef int Type; }; -template<> -struct CorrespondingSigned { typedef long Type; }; -template<> -struct CorrespondingSigned { typedef long long Type; }; - -template::Type, - bool IsSignedIntegerType = IsSigned::value && - !IsSame::value> -struct MakeSigned; - -template -struct MakeSigned -{ - typedef T Type; -}; - -template -struct MakeSigned - : WithCV::value, IsVolatile::value, - typename CorrespondingSigned::Type> -{}; - -} // namespace detail - -/** - * MakeSigned produces the corresponding signed integer type for a given - * integral type T, with the const/volatile qualifiers of T. T must be a - * possibly-const/volatile-qualified integral type that isn't bool. - * - * If T is already a signed integer type (not including char!), then T is - * produced. - * - * Otherwise, if T is an unsigned integer type, the signed variety of T, with - * T's const/volatile qualifiers, is produced. - * - * Otherwise, the integral type of the same size as T, with the lowest rank, - * with T's const/volatile qualifiers, is produced. (This basically only acts - * to produce signed char when T = char.) - * - * mozilla::MakeSigned::Type is signed long; - * mozilla::MakeSigned::Type is volatile int; - * mozilla::MakeSigned::Type is const signed short; - * mozilla::MakeSigned::Type is const signed char; - * mozilla::MakeSigned is an error; - * mozilla::MakeSigned is an error. - */ -template -struct MakeSigned - : EnableIf::value && - !IsSame::Type>::value, - typename detail::MakeSigned - >::Type -{}; - -namespace detail { - -template -struct CorrespondingUnsigned; - -template<> -struct CorrespondingUnsigned { typedef unsigned char Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned char Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned short Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned int Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned long Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned long long Type; }; - - -template::Type, - bool IsUnsignedIntegerType = IsUnsigned::value && - !IsSame::value> -struct MakeUnsigned; - -template -struct MakeUnsigned -{ - typedef T Type; -}; - -template -struct MakeUnsigned - : WithCV::value, IsVolatile::value, - typename CorrespondingUnsigned::Type> -{}; - -} // namespace detail - -/** - * MakeUnsigned produces the corresponding unsigned integer type for a given - * integral type T, with the const/volatile qualifiers of T. T must be a - * possibly-const/volatile-qualified integral type that isn't bool. - * - * If T is already an unsigned integer type (not including char!), then T is - * produced. - * - * Otherwise, if T is an signed integer type, the unsigned variety of T, with - * T's const/volatile qualifiers, is produced. - * - * Otherwise, the unsigned integral type of the same size as T, with the lowest - * rank, with T's const/volatile qualifiers, is produced. (This basically only - * acts to produce unsigned char when T = char.) - * - * mozilla::MakeUnsigned::Type is unsigned long; - * mozilla::MakeUnsigned::Type is volatile unsigned int; - * mozilla::MakeUnsigned::Type is const unsigned short; - * mozilla::MakeUnsigned::Type is const unsigned char; - * mozilla::MakeUnsigned is an error; - * mozilla::MakeUnsigned is an error. - */ -template -struct MakeUnsigned - : EnableIf::value && - !IsSame::Type>::value, - typename detail::MakeUnsigned - >::Type -{}; - -/* 20.9.7.4 Array modifications [meta.trans.arr] */ - -/** - * RemoveExtent produces either the type of the elements of the array T, or T - * itself. - * - * mozilla::RemoveExtent::Type is int; - * mozilla::RemoveExtent::Type is const int; - * mozilla::RemoveExtent::Type is volatile int; - * mozilla::RemoveExtent::Type is long[17]. - */ -template -struct RemoveExtent -{ - typedef T Type; -}; - -template -struct RemoveExtent -{ - typedef T Type; -}; - -template -struct RemoveExtent -{ - typedef T Type; -}; - -/* 20.9.7.5 Pointer modifications [meta.trans.ptr] */ - -namespace detail { - -template -struct RemovePointerHelper -{ - typedef T Type; -}; - -template -struct RemovePointerHelper -{ - typedef Pointee Type; -}; - -} // namespace detail - -/** - * Produces the pointed-to type if a pointer is provided, else returns the input - * type. Note that this does not dereference pointer-to-member pointers. - * - * struct S { bool m; void f(); }; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is const long; - * mozilla::RemovePointer::Type is void; - * mozilla::RemovePointer::Type is void (S::*)(); - * mozilla::RemovePointer::Type is void(); - * mozilla::RemovePointer::Type is bool S::*. - */ -template -struct RemovePointer - : detail::RemovePointerHelper::Type> -{}; - -/** - * Converts T& to T*. Otherwise returns T* given T. Note that C++17 wants - * std::add_pointer to work differently for function types. We don't implement - * that behavior here. - * - * mozilla::AddPointer is int*; - * mozilla::AddPointer is int**; - * mozilla::AddPointer is int*; - * mozilla::AddPointer is int** const. - */ -template -struct AddPointer -{ - typedef typename RemoveReference::Type* Type; -}; - -/* 20.9.7.6 Other transformations [meta.trans.other] */ - -/** - * EnableIf is a struct containing a typedef of T if and only if B is true. - * - * mozilla::EnableIf::Type is int; - * mozilla::EnableIf::Type is a compile-time error. - * - * Use this template to implement SFINAE-style (Substitution Failure Is not An - * Error) requirements. For example, you might use it to impose a restriction - * on a template parameter: - * - * template - * class PodVector // vector optimized to store POD (memcpy-able) types - * { - * EnableIf::value, T>::Type* vector; - * size_t length; - * ... - * }; - */ -template -struct EnableIf -{}; - -template -struct EnableIf -{ - typedef T Type; -}; - -/** - * Conditional selects a class between two, depending on a given boolean value. - * - * mozilla::Conditional::Type is A; - * mozilla::Conditional::Type is B; - */ -template -struct Conditional -{ - typedef A Type; -}; - -template -struct Conditional -{ - typedef B Type; -}; - -namespace detail { - -template::value, - bool IsFunction = IsFunction::value> -struct DecaySelector; - -template -struct DecaySelector -{ - typedef typename RemoveCV::Type Type; -}; - -template -struct DecaySelector -{ - typedef typename RemoveExtent::Type* Type; -}; - -template -struct DecaySelector -{ - typedef typename AddPointer::Type Type; -}; - -}; // namespace detail - -/** - * Strips const/volatile off a type and decays it from an lvalue to an - * rvalue. So function types are converted to function pointers, arrays to - * pointers, and references are removed. - * - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int* - * mozilla::Decay::Type is int(*)(int) - */ -template -class Decay - : public detail::DecaySelector::Type> -{ -}; - -} /* namespace mozilla */ - -#endif /* mozilla_TypeTraits_h */ diff --git a/ios/include/spidermonkey/mozilla/TypedEnumBits.h b/ios/include/spidermonkey/mozilla/TypedEnumBits.h deleted file mode 100644 index 5ee6315c..00000000 --- a/ios/include/spidermonkey/mozilla/TypedEnumBits.h +++ /dev/null @@ -1,156 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS allows using a typed enum as bit flags. - */ - -#ifndef mozilla_TypedEnumBits_h -#define mozilla_TypedEnumBits_h - -#include "mozilla/Attributes.h" -#include "mozilla/IntegerTypeTraits.h" - -namespace mozilla { - -/* - * The problem that CastableTypedEnumResult aims to solve is that - * typed enums are not convertible to bool, and there is no way to make them - * be, yet user code wants to be able to write - * - * if (myFlags & Flags::SOME_PARTICULAR_FLAG) (1) - * - * There are different approaches to solving this. Most of them require - * adapting user code. For example, we could implement operator! and have - * the user write - * - * if (!!(myFlags & Flags::SOME_PARTICULAR_FLAG)) (2) - * - * Or we could supply a IsNonZero() or Any() function returning whether - * an enum value is nonzero, and have the user write - * - * if (Any(Flags & Flags::SOME_PARTICULAR_FLAG)) (3) - * - * But instead, we choose to preserve the original user syntax (1) as it - * is inherently more readable, and to ease porting existing code to typed - * enums. We achieve this by having operator& and other binary bitwise - * operators have as return type a class, CastableTypedEnumResult, - * that wraps a typed enum but adds bool convertibility. - */ -template -class CastableTypedEnumResult -{ -private: - const E mValue; - -public: - explicit constexpr CastableTypedEnumResult(E aValue) - : mValue(aValue) - {} - - constexpr operator E() const { return mValue; } - - template - explicit constexpr - operator DestinationType() const { return DestinationType(mValue); } - - constexpr bool operator !() const { return !bool(mValue); } -}; - -#define MOZ_CASTABLETYPEDENUMRESULT_BINOP(Op, OtherType, ReturnType) \ -template \ -constexpr ReturnType \ -operator Op(const OtherType& aE, const CastableTypedEnumResult& aR) \ -{ \ - return ReturnType(aE Op OtherType(aR)); \ -} \ -template \ -constexpr ReturnType \ -operator Op(const CastableTypedEnumResult& aR, const OtherType& aE) \ -{ \ - return ReturnType(OtherType(aR) Op aE); \ -} \ -template \ -constexpr ReturnType \ -operator Op(const CastableTypedEnumResult& aR1, \ - const CastableTypedEnumResult& aR2) \ -{ \ - return ReturnType(OtherType(aR1) Op OtherType(aR2)); \ -} - -MOZ_CASTABLETYPEDENUMRESULT_BINOP(|, E, CastableTypedEnumResult) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(&, E, CastableTypedEnumResult) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(^, E, CastableTypedEnumResult) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(==, E, bool) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(!=, E, bool) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(||, bool, bool) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(&&, bool, bool) - -template -constexpr CastableTypedEnumResult -operator ~(const CastableTypedEnumResult& aR) -{ - return CastableTypedEnumResult(~(E(aR))); -} - -#define MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(Op) \ -template \ -E& \ -operator Op(E& aR1, \ - const CastableTypedEnumResult& aR2) \ -{ \ - return aR1 Op E(aR2); \ -} - -MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(&=) -MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(|=) -MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(^=) - -#undef MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP - -#undef MOZ_CASTABLETYPEDENUMRESULT_BINOP - -namespace detail { -template -struct UnsignedIntegerTypeForEnum - : UnsignedStdintTypeForSize -{}; -} // namespace detail - -} // namespace mozilla - -#define MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, Op) \ - inline constexpr mozilla::CastableTypedEnumResult \ - operator Op(Name a, Name b) \ - { \ - typedef mozilla::CastableTypedEnumResult Result; \ - typedef mozilla::detail::UnsignedIntegerTypeForEnum::Type U; \ - return Result(Name(U(a) Op U(b))); \ - } \ - \ - inline Name& \ - operator Op##=(Name& a, Name b) \ - { \ - return a = a Op b; \ - } - -/** - * MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS generates standard bitwise operators - * for the given enum type. Use this to enable using an enum type as bit-field. - */ -#define MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Name) \ - MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, |) \ - MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, &) \ - MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, ^) \ - inline constexpr mozilla::CastableTypedEnumResult \ - operator~(Name a) \ - { \ - typedef mozilla::CastableTypedEnumResult Result; \ - typedef mozilla::detail::UnsignedIntegerTypeForEnum::Type U; \ - return Result(Name(~(U(a)))); \ - } - -#endif // mozilla_TypedEnumBits_h diff --git a/ios/include/spidermonkey/mozilla/Types.h b/ios/include/spidermonkey/mozilla/Types.h deleted file mode 100644 index e7e18abb..00000000 --- a/ios/include/spidermonkey/mozilla/Types.h +++ /dev/null @@ -1,134 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* mfbt foundational types and macros. */ - -#ifndef mozilla_Types_h -#define mozilla_Types_h - -/* - * This header must be valid C and C++, includable by code embedding either - * SpiderMonkey or Gecko. - */ - -/* Expose all types and size_t. */ -#include -#include - -/* Implement compiler and linker macros needed for APIs. */ - -/* - * MOZ_EXPORT is used to declare and define a symbol or type which is externally - * visible to users of the current library. It encapsulates various decorations - * needed to properly export the method's symbol. - * - * api.h: - * extern MOZ_EXPORT int MeaningOfLife(void); - * extern MOZ_EXPORT int LuggageCombination; - * - * api.c: - * int MeaningOfLife(void) { return 42; } - * int LuggageCombination = 12345; - * - * If you are merely sharing a method across files, just use plain |extern|. - * These macros are designed for use by library interfaces -- not for normal - * methods or data used cross-file. - */ -#if defined(WIN32) -# define MOZ_EXPORT __declspec(dllexport) -#else /* Unix */ -# ifdef HAVE_VISIBILITY_ATTRIBUTE -# define MOZ_EXPORT __attribute__((visibility("default"))) -# elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) -# define MOZ_EXPORT __global -# else -# define MOZ_EXPORT /* nothing */ -# endif -#endif - - -/* - * Whereas implementers use MOZ_EXPORT to declare and define library symbols, - * users use MOZ_IMPORT_API and MOZ_IMPORT_DATA to access them. Most often the - * implementer of the library will expose an API macro which expands to either - * the export or import version of the macro, depending upon the compilation - * mode. - */ -#ifdef _WIN32 -# if defined(__MWERKS__) -# define MOZ_IMPORT_API /* nothing */ -# else -# define MOZ_IMPORT_API __declspec(dllimport) -# endif -#else -# define MOZ_IMPORT_API MOZ_EXPORT -#endif - -#if defined(_WIN32) && !defined(__MWERKS__) -# define MOZ_IMPORT_DATA __declspec(dllimport) -#else -# define MOZ_IMPORT_DATA MOZ_EXPORT -#endif - -/* - * Consistent with the above comment, the MFBT_API and MFBT_DATA macros expose - * export mfbt declarations when building mfbt, and they expose import mfbt - * declarations when using mfbt. - */ -#if defined(IMPL_MFBT) -# define MFBT_API MOZ_EXPORT -# define MFBT_DATA MOZ_EXPORT -#else - /* - * On linux mozglue is linked in the program and we link libxul.so with - * -z,defs. Normally that causes the linker to reject undefined references in - * libxul.so, but as a loophole it allows undefined references to weak - * symbols. We add the weak attribute to the import version of the MFBT API - * macros to exploit this. - */ -# if defined(MOZ_GLUE_IN_PROGRAM) -# define MFBT_API __attribute__((weak)) MOZ_IMPORT_API -# define MFBT_DATA __attribute__((weak)) MOZ_IMPORT_DATA -# else -# define MFBT_API MOZ_IMPORT_API -# define MFBT_DATA MOZ_IMPORT_DATA -# endif -#endif - -/* - * C symbols in C++ code must be declared immediately within |extern "C"| - * blocks. However, in C code, they need not be declared specially. This - * difference is abstracted behind the MOZ_BEGIN_EXTERN_C and MOZ_END_EXTERN_C - * macros, so that the user need not know whether he is being used in C or C++ - * code. - * - * MOZ_BEGIN_EXTERN_C - * - * extern MOZ_EXPORT int MostRandomNumber(void); - * ...other declarations... - * - * MOZ_END_EXTERN_C - * - * This said, it is preferable to just use |extern "C"| in C++ header files for - * its greater clarity. - */ -#ifdef __cplusplus -# define MOZ_BEGIN_EXTERN_C extern "C" { -# define MOZ_END_EXTERN_C } -#else -# define MOZ_BEGIN_EXTERN_C -# define MOZ_END_EXTERN_C -#endif - -/* - * GCC's typeof is available when decltype is not. - */ -#if defined(__GNUC__) && defined(__cplusplus) && \ - !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L -# define decltype __typeof__ -#endif - -#endif /* mozilla_Types_h */ diff --git a/ios/include/spidermonkey/mozilla/UniquePtr.h b/ios/include/spidermonkey/mozilla/UniquePtr.h deleted file mode 100644 index 7e1035bc..00000000 --- a/ios/include/spidermonkey/mozilla/UniquePtr.h +++ /dev/null @@ -1,697 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Smart pointer managing sole ownership of a resource. */ - -#ifndef mozilla_UniquePtr_h -#define mozilla_UniquePtr_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/Move.h" -#include "mozilla/Pair.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -template class DefaultDelete; -template> class UniquePtr; - -} // namespace mozilla - -namespace mozilla { - -namespace detail { - -struct HasPointerTypeHelper -{ - template static double Test(...); - template static char Test(typename U::pointer* = 0); -}; - -template -class HasPointerType : public IntegralConstant(0)) == 1> -{ -}; - -template ::value> -struct PointerTypeImpl -{ - typedef typename D::pointer Type; -}; - -template -struct PointerTypeImpl -{ - typedef T* Type; -}; - -template -struct PointerType -{ - typedef typename PointerTypeImpl::Type>::Type Type; -}; - -} // namespace detail - -/** - * UniquePtr is a smart pointer that wholly owns a resource. Ownership may be - * transferred out of a UniquePtr through explicit action, but otherwise the - * resource is destroyed when the UniquePtr is destroyed. - * - * UniquePtr is similar to C++98's std::auto_ptr, but it improves upon auto_ptr - * in one crucial way: it's impossible to copy a UniquePtr. Copying an auto_ptr - * obviously *can't* copy ownership of its singly-owned resource. So what - * happens if you try to copy one? Bizarrely, ownership is implicitly - * *transferred*, preserving single ownership but breaking code that assumes a - * copy of an object is identical to the original. (This is why auto_ptr is - * prohibited in STL containers.) - * - * UniquePtr solves this problem by being *movable* rather than copyable. - * Instead of passing a |UniquePtr u| directly to the constructor or assignment - * operator, you pass |Move(u)|. In doing so you indicate that you're *moving* - * ownership out of |u|, into the target of the construction/assignment. After - * the transfer completes, |u| contains |nullptr| and may be safely destroyed. - * This preserves single ownership but also allows UniquePtr to be moved by - * algorithms that have been made move-safe. (Note: if |u| is instead a - * temporary expression, don't use |Move()|: just pass the expression, because - * it's already move-ready. For more information see Move.h.) - * - * UniquePtr is also better than std::auto_ptr in that the deletion operation is - * customizable. An optional second template parameter specifies a class that - * (through its operator()(T*)) implements the desired deletion policy. If no - * policy is specified, mozilla::DefaultDelete is used -- which will either - * |delete| or |delete[]| the resource, depending whether the resource is an - * array. Custom deletion policies ideally should be empty classes (no member - * fields, no member fields in base classes, no virtual methods/inheritance), - * because then UniquePtr can be just as efficient as a raw pointer. - * - * Use of UniquePtr proceeds like so: - * - * UniquePtr g1; // initializes to nullptr - * g1.reset(new int); // switch resources using reset() - * g1 = nullptr; // clears g1, deletes the int - * - * UniquePtr g2(new int); // owns that int - * int* p = g2.release(); // g2 leaks its int -- still requires deletion - * delete p; // now freed - * - * struct S { int x; S(int x) : x(x) {} }; - * UniquePtr g3, g4(new S(5)); - * g3 = Move(g4); // g3 owns the S, g4 cleared - * S* p = g3.get(); // g3 still owns |p| - * assert(g3->x == 5); // operator-> works (if .get() != nullptr) - * assert((*g3).x == 5); // also operator* (again, if not cleared) - * Swap(g3, g4); // g4 now owns the S, g3 cleared - * g3.swap(g4); // g3 now owns the S, g4 cleared - * UniquePtr g5(Move(g3)); // g5 owns the S, g3 cleared - * g5.reset(); // deletes the S, g5 cleared - * - * struct FreePolicy { void operator()(void* p) { free(p); } }; - * UniquePtr g6(static_cast(malloc(sizeof(int)))); - * int* ptr = g6.get(); - * g6 = nullptr; // calls free(ptr) - * - * Now, carefully note a few things you *can't* do: - * - * UniquePtr b1; - * b1 = new int; // BAD: can only assign another UniquePtr - * int* ptr = b1; // BAD: no auto-conversion to pointer, use get() - * - * UniquePtr b2(b1); // BAD: can't copy a UniquePtr - * UniquePtr b3 = b1; // BAD: can't copy-assign a UniquePtr - * - * (Note that changing a UniquePtr to store a direct |new| expression is - * permitted, but usually you should use MakeUnique, defined at the end of this - * header.) - * - * A few miscellaneous notes: - * - * UniquePtr, when not instantiated for an array type, can be move-constructed - * and move-assigned, not only from itself but from "derived" UniquePtr - * instantiations where U converts to T and E converts to D. If you want to use - * this, you're going to have to specify a deletion policy for both UniquePtr - * instantations, and T pretty much has to have a virtual destructor. In other - * words, this doesn't work: - * - * struct Base { virtual ~Base() {} }; - * struct Derived : Base {}; - * - * UniquePtr b1; - * // BAD: DefaultDelete and DefaultDelete don't interconvert - * UniquePtr d1(Move(b)); - * - * UniquePtr b2; - * UniquePtr> d2(Move(b2)); // okay - * - * UniquePtr is specialized for array types. Specializing with an array type - * creates a smart-pointer version of that array -- not a pointer to such an - * array. - * - * UniquePtr arr(new int[5]); - * arr[0] = 4; - * - * What else is different? Deletion of course uses |delete[]|. An operator[] - * is provided. Functionality that doesn't make sense for arrays is removed. - * The constructors and mutating methods only accept array pointers (not T*, U* - * that converts to T*, or UniquePtr or UniquePtr) or |nullptr|. - * - * It's perfectly okay for a function to return a UniquePtr. This transfers - * the UniquePtr's sole ownership of the data, to the fresh UniquePtr created - * in the calling function, that will then solely own that data. Such functions - * can return a local variable UniquePtr, |nullptr|, |UniquePtr(ptr)| where - * |ptr| is a |T*|, or a UniquePtr |Move()|'d from elsewhere. - * - * UniquePtr will commonly be a member of a class, with lifetime equivalent to - * that of that class. If you want to expose the related resource, you could - * expose a raw pointer via |get()|, but ownership of a raw pointer is - * inherently unclear. So it's better to expose a |const UniquePtr&| instead. - * This prohibits mutation but still allows use of |get()| when needed (but - * operator-> is preferred). Of course, you can only use this smart pointer as - * long as the enclosing class instance remains live -- no different than if you - * exposed the |get()| raw pointer. - * - * To pass a UniquePtr-managed resource as a pointer, use a |const UniquePtr&| - * argument. To specify an inout parameter (where the method may or may not - * take ownership of the resource, or reset it), or to specify an out parameter - * (where simply returning a |UniquePtr| isn't possible), use a |UniquePtr&| - * argument. To unconditionally transfer ownership of a UniquePtr - * into a method, use a |UniquePtr| argument. To conditionally transfer - * ownership of a resource into a method, should the method want it, use a - * |UniquePtr&&| argument. - */ -template -class UniquePtr -{ -public: - typedef T ElementType; - typedef D DeleterType; - typedef typename detail::PointerType::Type Pointer; - -private: - Pair mTuple; - - Pointer& ptr() { return mTuple.first(); } - const Pointer& ptr() const { return mTuple.first(); } - - DeleterType& del() { return mTuple.second(); } - const DeleterType& del() const { return mTuple.second(); } - -public: - /** - * Construct a UniquePtr containing |nullptr|. - */ - constexpr UniquePtr() - : mTuple(static_cast(nullptr), DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - /** - * Construct a UniquePtr containing |aPtr|. - */ - explicit UniquePtr(Pointer aPtr) - : mTuple(aPtr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - UniquePtr(Pointer aPtr, - typename Conditional::value, - D, - const D&>::Type aD1) - : mTuple(aPtr, aD1) - {} - - // If you encounter an error with MSVC10 about RemoveReference below, along - // the lines that "more than one partial specialization matches the template - // argument list": don't use UniquePtr! Ideally - // you should make deletion use the same function every time, using a - // deleter policy: - // - // // BAD, won't compile with MSVC10, deleter doesn't need to be a - // // variable at all - // typedef void (&FreeSignature)(void*); - // UniquePtr ptr((int*) malloc(sizeof(int)), free); - // - // // GOOD, compiles with MSVC10, deletion behavior statically known and - // // optimizable - // struct DeleteByFreeing - // { - // void operator()(void* aPtr) { free(aPtr); } - // }; - // - // If deletion really, truly, must be a variable: you might be able to work - // around this with a deleter class that contains the function reference. - // But this workaround is untried and untested, because variable deletion - // behavior really isn't something you should use. - UniquePtr(Pointer aPtr, - typename RemoveReference::Type&& aD2) - : mTuple(aPtr, Move(aD2)) - { - static_assert(!IsReference::value, - "rvalue deleter can't be stored by reference"); - } - - UniquePtr(UniquePtr&& aOther) - : mTuple(aOther.release(), Forward(aOther.get_deleter())) - {} - - MOZ_IMPLICIT - UniquePtr(decltype(nullptr)) - : mTuple(nullptr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - template - MOZ_IMPLICIT - UniquePtr(UniquePtr&& aOther, - typename EnableIf::Pointer, - Pointer>::value && - !IsArray::value && - (IsReference::value - ? IsSame::value - : IsConvertible::value), - int>::Type aDummy = 0) - : mTuple(aOther.release(), Forward(aOther.get_deleter())) - { - } - - ~UniquePtr() { reset(nullptr); } - - UniquePtr& operator=(UniquePtr&& aOther) - { - reset(aOther.release()); - get_deleter() = Forward(aOther.get_deleter()); - return *this; - } - - template - UniquePtr& operator=(UniquePtr&& aOther) - { - static_assert(IsConvertible::Pointer, - Pointer>::value, - "incompatible UniquePtr pointees"); - static_assert(!IsArray::value, - "can't assign from UniquePtr holding an array"); - - reset(aOther.release()); - get_deleter() = Forward(aOther.get_deleter()); - return *this; - } - - UniquePtr& operator=(decltype(nullptr)) - { - reset(nullptr); - return *this; - } - - T& operator*() const { return *get(); } - Pointer operator->() const - { - MOZ_ASSERT(get(), "dereferencing a UniquePtr containing nullptr"); - return get(); - } - - explicit operator bool() const { return get() != nullptr; } - - Pointer get() const { return ptr(); } - - DeleterType& get_deleter() { return del(); } - const DeleterType& get_deleter() const { return del(); } - - MOZ_MUST_USE Pointer release() - { - Pointer p = ptr(); - ptr() = nullptr; - return p; - } - - void reset(Pointer aPtr = Pointer()) - { - Pointer old = ptr(); - ptr() = aPtr; - if (old != nullptr) { - get_deleter()(old); - } - } - - void swap(UniquePtr& aOther) - { - mTuple.swap(aOther.mTuple); - } - - UniquePtr(const UniquePtr& aOther) = delete; // construct using Move()! - void operator=(const UniquePtr& aOther) = delete; // assign using Move()! -}; - -// In case you didn't read the comment by the main definition (you should!): the -// UniquePtr specialization exists to manage array pointers. It deletes -// such pointers using delete[], it will reject construction and modification -// attempts using U* or U[]. Otherwise it works like the normal UniquePtr. -template -class UniquePtr -{ -public: - typedef T* Pointer; - typedef T ElementType; - typedef D DeleterType; - -private: - Pair mTuple; - -public: - /** - * Construct a UniquePtr containing nullptr. - */ - constexpr UniquePtr() - : mTuple(static_cast(nullptr), DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - /** - * Construct a UniquePtr containing |aPtr|. - */ - explicit UniquePtr(Pointer aPtr) - : mTuple(aPtr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - // delete[] knows how to handle *only* an array of a single class type. For - // delete[] to work correctly, it must know the size of each element, the - // fields and base classes of each element requiring destruction, and so on. - // So forbid all overloads which would end up invoking delete[] on a pointer - // of the wrong type. - template - UniquePtr(U&& aU, - typename EnableIf::value && - IsConvertible::value, - int>::Type aDummy = 0) - = delete; - - UniquePtr(Pointer aPtr, - typename Conditional::value, - D, - const D&>::Type aD1) - : mTuple(aPtr, aD1) - {} - - // If you encounter an error with MSVC10 about RemoveReference below, along - // the lines that "more than one partial specialization matches the template - // argument list": don't use UniquePtr! See the - // comment by this constructor in the non-T[] specialization above. - UniquePtr(Pointer aPtr, - typename RemoveReference::Type&& aD2) - : mTuple(aPtr, Move(aD2)) - { - static_assert(!IsReference::value, - "rvalue deleter can't be stored by reference"); - } - - // Forbidden for the same reasons as stated above. - template - UniquePtr(U&& aU, V&& aV, - typename EnableIf::value && - IsConvertible::value, - int>::Type aDummy = 0) - = delete; - - UniquePtr(UniquePtr&& aOther) - : mTuple(aOther.release(), Forward(aOther.get_deleter())) - {} - - MOZ_IMPLICIT - UniquePtr(decltype(nullptr)) - : mTuple(nullptr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - ~UniquePtr() { reset(nullptr); } - - UniquePtr& operator=(UniquePtr&& aOther) - { - reset(aOther.release()); - get_deleter() = Forward(aOther.get_deleter()); - return *this; - } - - UniquePtr& operator=(decltype(nullptr)) - { - reset(); - return *this; - } - - explicit operator bool() const { return get() != nullptr; } - - T& operator[](decltype(sizeof(int)) aIndex) const { return get()[aIndex]; } - Pointer get() const { return mTuple.first(); } - - DeleterType& get_deleter() { return mTuple.second(); } - const DeleterType& get_deleter() const { return mTuple.second(); } - - MOZ_MUST_USE Pointer release() - { - Pointer p = mTuple.first(); - mTuple.first() = nullptr; - return p; - } - - void reset(Pointer aPtr = Pointer()) - { - Pointer old = mTuple.first(); - mTuple.first() = aPtr; - if (old != nullptr) { - mTuple.second()(old); - } - } - - void reset(decltype(nullptr)) - { - Pointer old = mTuple.first(); - mTuple.first() = nullptr; - if (old != nullptr) { - mTuple.second()(old); - } - } - - template - void reset(U) = delete; - - void swap(UniquePtr& aOther) { mTuple.swap(aOther.mTuple); } - - UniquePtr(const UniquePtr& aOther) = delete; // construct using Move()! - void operator=(const UniquePtr& aOther) = delete; // assign using Move()! -}; - -/** - * A default deletion policy using plain old operator delete. - * - * Note that this type can be specialized, but authors should beware of the risk - * that the specialization may at some point cease to match (either because it - * gets moved to a different compilation unit or the signature changes). If the - * non-specialized (|delete|-based) version compiles for that type but does the - * wrong thing, bad things could happen. - * - * This is a non-issue for types which are always incomplete (i.e. opaque handle - * types), since |delete|-ing such a type will always trigger a compilation - * error. - */ -template -class DefaultDelete -{ -public: - constexpr DefaultDelete() {} - - template - MOZ_IMPLICIT DefaultDelete(const DefaultDelete& aOther, - typename EnableIf::value, - int>::Type aDummy = 0) - {} - - void operator()(T* aPtr) const - { - static_assert(sizeof(T) > 0, "T must be complete"); - delete aPtr; - } -}; - -/** A default deletion policy using operator delete[]. */ -template -class DefaultDelete -{ -public: - constexpr DefaultDelete() {} - - void operator()(T* aPtr) const - { - static_assert(sizeof(T) > 0, "T must be complete"); - delete[] aPtr; - } - - template - void operator()(U* aPtr) const = delete; -}; - -template -void -Swap(UniquePtr& aX, UniquePtr& aY) -{ - aX.swap(aY); -} - -template -bool -operator==(const UniquePtr& aX, const UniquePtr& aY) -{ - return aX.get() == aY.get(); -} - -template -bool -operator!=(const UniquePtr& aX, const UniquePtr& aY) -{ - return aX.get() != aY.get(); -} - -template -bool -operator==(const UniquePtr& aX, decltype(nullptr)) -{ - return !aX; -} - -template -bool -operator==(decltype(nullptr), const UniquePtr& aX) -{ - return !aX; -} - -template -bool -operator!=(const UniquePtr& aX, decltype(nullptr)) -{ - return bool(aX); -} - -template -bool -operator!=(decltype(nullptr), const UniquePtr& aX) -{ - return bool(aX); -} - -// No operator<, operator>, operator<=, operator>= for now because simplicity. - -namespace detail { - -template -struct UniqueSelector -{ - typedef UniquePtr SingleObject; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr UnknownBound; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr KnownBound; -}; - -} // namespace detail - -/** - * MakeUnique is a helper function for allocating new'd objects and arrays, - * returning a UniquePtr containing the resulting pointer. The semantics of - * MakeUnique(...) are as follows. - * - * If Type is an array T[n]: - * Disallowed, deleted, no overload for you! - * If Type is an array T[]: - * MakeUnique(size_t) is the only valid overload. The pointer returned - * is as if by |new T[n]()|, which value-initializes each element. (If T - * isn't a class type, this will zero each element. If T is a class type, - * then roughly speaking, each element will be constructed using its default - * constructor. See C++11 [dcl.init]p7 for the full gory details.) - * If Type is non-array T: - * The arguments passed to MakeUnique(...) are forwarded into a - * |new T(...)| call, initializing the T as would happen if executing - * |T(...)|. - * - * There are various benefits to using MakeUnique instead of |new| expressions. - * - * First, MakeUnique eliminates use of |new| from code entirely. If objects are - * only created through UniquePtr, then (assuming all explicit release() calls - * are safe, including transitively, and no type-safety casting funniness) - * correctly maintained ownership of the UniquePtr guarantees no leaks are - * possible. (This pays off best if a class is only ever created through a - * factory method on the class, using a private constructor.) - * - * Second, initializing a UniquePtr using a |new| expression requires repeating - * the name of the new'd type, whereas MakeUnique in concert with the |auto| - * keyword names it only once: - * - * UniquePtr ptr1(new char()); // repetitive - * auto ptr2 = MakeUnique(); // shorter - * - * Of course this assumes the reader understands the operation MakeUnique - * performs. In the long run this is probably a reasonable assumption. In the - * short run you'll have to use your judgment about what readers can be expected - * to know, or to quickly look up. - * - * Third, a call to MakeUnique can be assigned directly to a UniquePtr. In - * contrast you can't assign a pointer into a UniquePtr without using the - * cumbersome reset(). - * - * UniquePtr p; - * p = new char; // ERROR - * p.reset(new char); // works, but fugly - * p = MakeUnique(); // preferred - * - * (And third, although not relevant to Mozilla: MakeUnique is exception-safe. - * An exception thrown after |new T| succeeds will leak that memory, unless the - * pointer is assigned to an object that will manage its ownership. UniquePtr - * ably serves this function.) - */ - -template -typename detail::UniqueSelector::SingleObject -MakeUnique(Args&&... aArgs) -{ - return UniquePtr(new T(Forward(aArgs)...)); -} - -template -typename detail::UniqueSelector::UnknownBound -MakeUnique(decltype(sizeof(int)) aN) -{ - typedef typename RemoveExtent::Type ArrayType; - return UniquePtr(new ArrayType[aN]()); -} - -template -typename detail::UniqueSelector::KnownBound -MakeUnique(Args&&... aArgs) = delete; - -} // namespace mozilla - -#endif /* mozilla_UniquePtr_h */ diff --git a/ios/include/spidermonkey/mozilla/UniquePtrExtensions.h b/ios/include/spidermonkey/mozilla/UniquePtrExtensions.h deleted file mode 100644 index d94f33ee..00000000 --- a/ios/include/spidermonkey/mozilla/UniquePtrExtensions.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Useful extensions to UniquePtr. */ - -#ifndef mozilla_UniquePtrExtensions_h -#define mozilla_UniquePtrExtensions_h - -#include "mozilla/fallible.h" -#include "mozilla/UniquePtr.h" - -namespace mozilla { - -/** - * MakeUniqueFallible works exactly like MakeUnique, except that the memory - * allocation performed is done fallibly, i.e. it can return nullptr. - */ -template -typename detail::UniqueSelector::SingleObject -MakeUniqueFallible(Args&&... aArgs) -{ - return UniquePtr(new (fallible) T(Forward(aArgs)...)); -} - -template -typename detail::UniqueSelector::UnknownBound -MakeUniqueFallible(decltype(sizeof(int)) aN) -{ - typedef typename RemoveExtent::Type ArrayType; - return UniquePtr(new (fallible) ArrayType[aN]()); -} - -template -typename detail::UniqueSelector::KnownBound -MakeUniqueFallible(Args&&... aArgs) = delete; - -namespace detail { - -template -struct FreePolicy -{ - void operator()(const void* ptr) { - free(const_cast(ptr)); - } -}; - -} // namespace detail - -template -using UniqueFreePtr = UniquePtr>; - -} // namespace mozilla - -#endif // mozilla_UniquePtrExtensions_h diff --git a/ios/include/spidermonkey/mozilla/Unused.h b/ios/include/spidermonkey/mozilla/Unused.h deleted file mode 100644 index e693e32a..00000000 --- a/ios/include/spidermonkey/mozilla/Unused.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_unused_h -#define mozilla_unused_h - -#include "mozilla/Types.h" - -#ifdef __cplusplus - -namespace mozilla { - -// -// Suppress GCC warnings about unused return values with -// Unused << SomeFuncDeclaredWarnUnusedReturnValue(); -// -struct unused_t -{ - template - inline void - operator<<(const T& /*unused*/) const {} -}; - -extern MFBT_DATA const unused_t Unused; - -} // namespace mozilla - -#endif // __cplusplus - -// An alternative to mozilla::Unused for use in (a) C code and (b) code where -// linking with unused.o is difficult. -#define MOZ_UNUSED(expr) \ - do { if (expr) { (void)0; } } while (0) - -#endif // mozilla_unused_h diff --git a/ios/include/spidermonkey/mozilla/Variant.h b/ios/include/spidermonkey/mozilla/Variant.h deleted file mode 100644 index 8a33286e..00000000 --- a/ios/include/spidermonkey/mozilla/Variant.h +++ /dev/null @@ -1,625 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A template class for tagged unions. */ - -#include -#include - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#ifndef mozilla_Variant_h -#define mozilla_Variant_h - -namespace mozilla { - -template -class Variant; - -namespace detail { - -// MaxSizeOf computes the maximum sizeof(T) for each T in Ts. - -template -struct MaxSizeOf -{ - static const size_t size = sizeof(T) > MaxSizeOf::size - ? sizeof(T) - : MaxSizeOf::size; -}; - -template -struct MaxSizeOf -{ - static const size_t size = sizeof(T); -}; - -// The `IsVariant` helper is used in conjunction with static_assert and -// `mozilla::EnableIf` to catch passing non-variant types to `Variant::is()` -// and friends at compile time, rather than at runtime. It ensures that the -// given type `Needle` is one of the types in the set of types `Haystack`. - -template -struct IsVariant; - -template -struct IsVariant -{ - static const bool value = false; -}; - -template -struct IsVariant -{ - static const bool value = true; -}; - -template -struct IsVariant : public IsVariant { }; - -/// SelectVariantTypeHelper is used in the implementation of SelectVariantType. -template -struct SelectVariantTypeHelper; - -template -struct SelectVariantTypeHelper -{ }; - -template -struct SelectVariantTypeHelper -{ - typedef T Type; -}; - -template -struct SelectVariantTypeHelper -{ - typedef const T Type; -}; - -template -struct SelectVariantTypeHelper -{ - typedef const T& Type; -}; - -template -struct SelectVariantTypeHelper -{ - typedef T&& Type; -}; - -template -struct SelectVariantTypeHelper - : public SelectVariantTypeHelper -{ }; - -/** - * SelectVariantType takes a type T and a list of variant types Variants and - * yields a type Type, selected from Variants, that can store a value of type T - * or a reference to type T. If no such type was found, Type is not defined. - */ -template -struct SelectVariantType - : public SelectVariantTypeHelper::Type>::Type, - Variants...> -{ }; - -// Compute a fast, compact type that can be used to hold integral values that -// distinctly map to every type in Ts. -template -struct VariantTag -{ -private: - static const size_t TypeCount = sizeof...(Ts); - -public: - using Type = - typename Conditional::Type - >::Type; -}; - -// TagHelper gets the given sentinel tag value for the given type T. This has to -// be split out from VariantImplementation because you can't nest a partial -// template specialization within a template class. - -template -struct TagHelper; - -// In the case where T != U, we continue recursion. -template -struct TagHelper -{ - static Tag tag() { return Next::template tag(); } -}; - -// In the case where T == U, return the tag number. -template -struct TagHelper -{ - static Tag tag() { return Tag(N); } -}; - -// The VariantImplementation template provides the guts of mozilla::Variant. We -// create a VariantImplementation for each T in Ts... which handles -// construction, destruction, etc for when the Variant's type is T. If the -// Variant's type isn't T, it punts the request on to the next -// VariantImplementation. - -template -struct VariantImplementation; - -// The singly typed Variant / recursion base case. -template -struct VariantImplementation -{ - template - static Tag tag() { - static_assert(mozilla::IsSame::value, - "mozilla::Variant: tag: bad type!"); - return Tag(N); - } - - template - static void copyConstruct(void* aLhs, const Variant& aRhs) { - new (aLhs) T(aRhs.template as()); - } - - template - static void moveConstruct(void* aLhs, Variant&& aRhs) { - new (aLhs) T(aRhs.template extract()); - } - - template - static void destroy(Variant& aV) { - aV.template as().~T(); - } - - template - static bool - equal(const Variant& aLhs, const Variant& aRhs) { - return aLhs.template as() == aRhs.template as(); - } - - template - static auto - match(Matcher&& aMatcher, ConcreteVariant& aV) - -> decltype(aMatcher.match(aV.template as())) - { - return aMatcher.match(aV.template as()); - } -}; - -// VariantImplementation for some variant type T. -template -struct VariantImplementation -{ - // The next recursive VariantImplementation. - using Next = VariantImplementation; - - template - static Tag tag() { - return TagHelper::value>::tag(); - } - - template - static void copyConstruct(void* aLhs, const Variant& aRhs) { - if (aRhs.template is()) { - new (aLhs) T(aRhs.template as()); - } else { - Next::copyConstruct(aLhs, aRhs); - } - } - - template - static void moveConstruct(void* aLhs, Variant&& aRhs) { - if (aRhs.template is()) { - new (aLhs) T(aRhs.template extract()); - } else { - Next::moveConstruct(aLhs, aRhs); - } - } - - template - static void destroy(Variant& aV) { - if (aV.template is()) { - aV.template as().~T(); - } else { - Next::destroy(aV); - } - } - - template - static bool equal(const Variant& aLhs, const Variant& aRhs) { - if (aLhs.template is()) { - MOZ_ASSERT(aRhs.template is()); - return aLhs.template as() == aRhs.template as(); - } else { - return Next::equal(aLhs, aRhs); - } - } - - template - static auto - match(Matcher&& aMatcher, ConcreteVariant& aV) - -> decltype(aMatcher.match(aV.template as())) - { - if (aV.template is()) { - return aMatcher.match(aV.template as()); - } else { - // If you're seeing compilation errors here like "no matching - // function for call to 'match'" then that means that the - // Matcher doesn't exhaust all variant types. There must exist a - // Matcher::match(T&) for every variant type T. - // - // If you're seeing compilation errors here like "cannot - // initialize return object of type <...> with an rvalue of type - // <...>" then that means that the Matcher::match(T&) overloads - // are returning different types. They must all return the same - // Matcher::ReturnType type. - return Next::match(aMatcher, aV); - } - } -}; - -/** - * AsVariantTemporary stores a value of type T to allow construction of a - * Variant value via type inference. Because T is copied and there's no - * guarantee that the copy can be elided, AsVariantTemporary is best used with - * primitive or very small types. - */ -template -struct AsVariantTemporary -{ - explicit AsVariantTemporary(const T& aValue) - : mValue(aValue) - {} - - template - explicit AsVariantTemporary(U&& aValue) - : mValue(Forward(aValue)) - {} - - AsVariantTemporary(const AsVariantTemporary& aOther) - : mValue(aOther.mValue) - {} - - AsVariantTemporary(AsVariantTemporary&& aOther) - : mValue(Move(aOther.mValue)) - {} - - AsVariantTemporary() = delete; - void operator=(const AsVariantTemporary&) = delete; - void operator=(AsVariantTemporary&&) = delete; - - typename RemoveConst::Type>::Type mValue; -}; - -} // namespace detail - -/** - * # mozilla::Variant - * - * A variant / tagged union / heterogenous disjoint union / sum-type template - * class. Similar in concept to (but not derived from) `boost::variant`. - * - * Sometimes, you may wish to use a C union with non-POD types. However, this is - * forbidden in C++ because it is not clear which type in the union should have - * its constructor and destructor run on creation and deletion - * respectively. This is the problem that `mozilla::Variant` solves. - * - * ## Usage - * - * A `mozilla::Variant` instance is constructed (via move or copy) from one of - * its variant types (ignoring const and references). It does *not* support - * construction from subclasses of variant types or types that coerce to one of - * the variant types. - * - * Variant v1('a'); - * Variant, B, C> v2(MakeUnique()); - * - * Because specifying the full type of a Variant value is often verbose, - * AsVariant() can be used to construct a Variant value using type inference in - * contexts such as expressions or when returning values from functions. Because - * AsVariant() must copy or move the value into a temporary and this cannot - * necessarily be elided by the compiler, it's mostly appropriate only for use - * with primitive or very small types. - * - * - * Variant Foo() { return AsVariant('x'); } - * // ... - * Variant v1 = Foo(); // v1 holds char('x'). - * - * All access to the contained value goes through type-safe accessors. - * - * void - * Foo(Variant v) - * { - * if (v.is()) { - * A& ref = v.as(); - * ... - * } else { - * ... - * } - * } - * - * Attempting to use the contained value as type `T1` when the `Variant` - * instance contains a value of type `T2` causes an assertion failure. - * - * A a; - * Variant v(a); - * v.as(); // <--- Assertion failure! - * - * Trying to use a `Variant` instance as some type `U` that is not a - * member of the set of `Ts...` is a compiler error. - * - * A a; - * Variant v(a); - * v.as(); // <--- Compiler error! - * - * Additionally, you can turn a `Variant` that `is` into a `T` by moving it - * out of the containing `Variant` instance with the `extract` method: - * - * Variant, B, C> v(MakeUnique()); - * auto ptr = v.extract>(); - * - * Finally, you can exhaustively match on the contained variant and branch into - * different code paths depending which type is contained. This is preferred to - * manually checking every variant type T with is() because it provides - * compile-time checking that you handled every type, rather than runtime - * assertion failures. - * - * // Bad! - * char* foo(Variant& v) { - * if (v.is()) { - * return ...; - * } else if (v.is()) { - * return ...; - * } else { - * return doSomething(v.as()); // Forgot about case D! - * } - * } - * - * // Good! - * struct FooMatcher - * { - * // The return type of all matchers must be identical. - * char* match(A& a) { ... } - * char* match(B& b) { ... } - * char* match(C& c) { ... } - * char* match(D& d) { ... } // Compile-time error to forget D! - * } - * char* foo(Variant& v) { - * return v.match(FooMatcher()); - * } - * - * ## Examples - * - * A tree is either an empty leaf, or a node with a value and two children: - * - * struct Leaf { }; - * - * template - * struct Node - * { - * T value; - * Tree* left; - * Tree* right; - * }; - * - * template - * using Tree = Variant>; - * - * A copy-on-write string is either a non-owning reference to some existing - * string, or an owning reference to our copy: - * - * class CopyOnWriteString - * { - * Variant> string; - * - * ... - * }; - */ -template -class MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS Variant -{ - using Tag = typename detail::VariantTag::Type; - using Impl = detail::VariantImplementation; - using RawData = AlignedStorage::size>; - - // Raw storage for the contained variant value. - RawData raw; - - // Each type is given a unique tag value that lets us keep track of the - // contained variant value's type. - Tag tag; - - void* ptr() { - return reinterpret_cast(&raw); - } - -public: - /** Perfect forwarding construction for some variant type T. */ - template::Type> - explicit Variant(RefT&& aT) - : tag(Impl::template tag()) - { - new (ptr()) T(Forward(aT)); - } - - /** - * Constructs this Variant from an AsVariantTemporary such that T can be - * stored in one of the types allowable in this Variant. This is used in the - * implementation of AsVariant(). - */ - template::Type> - MOZ_IMPLICIT Variant(detail::AsVariantTemporary&& aValue) - : tag(Impl::template tag()) - { - new (ptr()) T(Move(aValue.mValue)); - } - - /** Copy construction. */ - Variant(const Variant& aRhs) - : tag(aRhs.tag) - { - Impl::copyConstruct(ptr(), aRhs); - } - - /** Move construction. */ - Variant(Variant&& aRhs) - : tag(aRhs.tag) - { - Impl::moveConstruct(ptr(), Move(aRhs)); - } - - /** Copy assignment. */ - Variant& operator=(const Variant& aRhs) { - MOZ_ASSERT(&aRhs != this, "self-assign disallowed"); - this->~Variant(); - new (this) Variant(aRhs); - return *this; - } - - /** Move assignment. */ - Variant& operator=(Variant&& aRhs) { - MOZ_ASSERT(&aRhs != this, "self-assign disallowed"); - this->~Variant(); - new (this) Variant(Move(aRhs)); - return *this; - } - - /** Move assignment from AsVariant(). */ - template - Variant& operator=(detail::AsVariantTemporary&& aValue) - { - this->~Variant(); - new (this) Variant(Move(aValue)); - return *this; - } - - ~Variant() - { - Impl::destroy(*this); - } - - /** Check which variant type is currently contained. */ - template - bool is() const { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - return Impl::template tag() == tag; - } - - /** - * Operator == overload that defers to the variant type's operator== - * implementation if the rhs is tagged as the same type as this one. - */ - bool operator==(const Variant& aRhs) const { - return tag == aRhs.tag && Impl::equal(*this, aRhs); - } - - /** - * Operator != overload that defers to the negation of the variant type's - * operator== implementation if the rhs is tagged as the same type as this - * one. - */ - bool operator!=(const Variant& aRhs) const { - return !(*this == aRhs); - } - - // Accessors for working with the contained variant value. - - /** Mutable reference. */ - template - T& as() { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - MOZ_ASSERT(is()); - return *reinterpret_cast(&raw); - } - - /** Immutable const reference. */ - template - const T& as() const { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - MOZ_ASSERT(is()); - return *reinterpret_cast(&raw); - } - - /** - * Extract the contained variant value from this container into a temporary - * value. On completion, the value in the variant will be in a - * safely-destructible state, as determined by the behavior of T's move - * constructor when provided the variant's internal value. - */ - template - T extract() { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - MOZ_ASSERT(is()); - return T(Move(as())); - } - - // Exhaustive matching of all variant types on the contained value. - - /** Match on an immutable const reference. */ - template - auto - match(Matcher&& aMatcher) const - -> decltype(Impl::match(aMatcher, *this)) - { - return Impl::match(aMatcher, *this); - } - - /** Match on a mutable non-const reference. */ - template - auto - match(Matcher&& aMatcher) - -> decltype(Impl::match(aMatcher, *this)) - { - return Impl::match(aMatcher, *this); - } -}; - -/* - * AsVariant() is used to construct a Variant value containing the - * provided T value using type inference. It can be used to construct Variant - * values in expressions or return them from functions without specifying the - * entire Variant type. - * - * Because AsVariant() must copy or move the value into a temporary and this - * cannot necessarily be elided by the compiler, it's mostly appropriate only - * for use with primitive or very small types. - * - * AsVariant() returns a AsVariantTemporary value which is implicitly - * convertible to any Variant that can hold a value of type T. - */ -template -detail::AsVariantTemporary -AsVariant(T&& aValue) -{ - return detail::AsVariantTemporary(Forward(aValue)); -} - -} // namespace mozilla - -#endif /* mozilla_Variant_h */ diff --git a/ios/include/spidermonkey/mozilla/Vector.h b/ios/include/spidermonkey/mozilla/Vector.h deleted file mode 100644 index fc43afcf..00000000 --- a/ios/include/spidermonkey/mozilla/Vector.h +++ /dev/null @@ -1,1491 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A type/length-parametrized vector class. */ - -#ifndef mozilla_Vector_h -#define mozilla_Vector_h - -#include "mozilla/Alignment.h" -#include "mozilla/AllocPolicy.h" -#include "mozilla/ArrayUtils.h" // for PointerRangeSize -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/MathAlgorithms.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/OperatorNewExtensions.h" -#include "mozilla/ReentrancyGuard.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/TypeTraits.h" - -#include // for placement new - -/* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4345) -#endif - -namespace mozilla { - -template -class Vector; - -namespace detail { - -/* - * Check that the given capacity wastes the minimal amount of space if - * allocated on the heap. This means that aCapacity*sizeof(T) is as close to a - * power-of-two as possible. growStorageBy() is responsible for ensuring this. - */ -template -static bool CapacityHasExcessSpace(size_t aCapacity) -{ - size_t size = aCapacity * sizeof(T); - return RoundUpPow2(size) - size >= sizeof(T); -} - -/* - * This template class provides a default implementation for vector operations - * when the element type is not known to be a POD, as judged by IsPod. - */ -template -struct VectorImpl -{ - /* - * Constructs an object in the uninitialized memory at *aDst with aArgs. - */ - template - MOZ_NONNULL(1) - static inline void new_(T* aDst, Args&&... aArgs) - { - new(KnownNotNull, aDst) T(Forward(aArgs)...); - } - - /* Destroys constructed objects in the range [aBegin, aEnd). */ - static inline void destroy(T* aBegin, T* aEnd) - { - MOZ_ASSERT(aBegin <= aEnd); - for (T* p = aBegin; p < aEnd; ++p) { - p->~T(); - } - } - - /* Constructs objects in the uninitialized range [aBegin, aEnd). */ - static inline void initialize(T* aBegin, T* aEnd) - { - MOZ_ASSERT(aBegin <= aEnd); - for (T* p = aBegin; p < aEnd; ++p) { - new_(p); - } - } - - /* - * Copy-constructs objects in the uninitialized range - * [aDst, aDst+(aSrcEnd-aSrcStart)) from the range [aSrcStart, aSrcEnd). - */ - template - static inline void copyConstruct(T* aDst, - const U* aSrcStart, const U* aSrcEnd) - { - MOZ_ASSERT(aSrcStart <= aSrcEnd); - for (const U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) { - new_(aDst, *p); - } - } - - /* - * Move-constructs objects in the uninitialized range - * [aDst, aDst+(aSrcEnd-aSrcStart)) from the range [aSrcStart, aSrcEnd). - */ - template - static inline void moveConstruct(T* aDst, U* aSrcStart, U* aSrcEnd) - { - MOZ_ASSERT(aSrcStart <= aSrcEnd); - for (U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) { - new_(aDst, Move(*p)); - } - } - - /* - * Copy-constructs objects in the uninitialized range [aDst, aDst+aN) from - * the same object aU. - */ - template - static inline void copyConstructN(T* aDst, size_t aN, const U& aU) - { - for (T* end = aDst + aN; aDst < end; ++aDst) { - new_(aDst, aU); - } - } - - /* - * Grows the given buffer to have capacity aNewCap, preserving the objects - * constructed in the range [begin, end) and updating aV. Assumes that (1) - * aNewCap has not overflowed, and (2) multiplying aNewCap by sizeof(T) will - * not overflow. - */ - static inline MOZ_MUST_USE bool - growTo(Vector& aV, size_t aNewCap) - { - MOZ_ASSERT(!aV.usingInlineStorage()); - MOZ_ASSERT(!CapacityHasExcessSpace(aNewCap)); - T* newbuf = aV.template pod_malloc(aNewCap); - if (MOZ_UNLIKELY(!newbuf)) { - return false; - } - T* dst = newbuf; - T* src = aV.beginNoCheck(); - for (; src < aV.endNoCheck(); ++dst, ++src) { - new_(dst, Move(*src)); - } - VectorImpl::destroy(aV.beginNoCheck(), aV.endNoCheck()); - aV.free_(aV.mBegin); - aV.mBegin = newbuf; - /* aV.mLength is unchanged. */ - aV.mCapacity = aNewCap; - return true; - } -}; - -/* - * This partial template specialization provides a default implementation for - * vector operations when the element type is known to be a POD, as judged by - * IsPod. - */ -template -struct VectorImpl -{ - template - MOZ_NONNULL(1) - static inline void new_(T* aDst, Args&&... aArgs) - { - // Explicitly construct a local object instead of using a temporary since - // T(args...) will be treated like a C-style cast in the unary case and - // allow unsafe conversions. Both forms should be equivalent to an - // optimizing compiler. - T temp(Forward(aArgs)...); - *aDst = temp; - } - - static inline void destroy(T*, T*) {} - - static inline void initialize(T* aBegin, T* aEnd) - { - /* - * You would think that memset would be a big win (or even break even) - * when we know T is a POD. But currently it's not. This is probably - * because |append| tends to be given small ranges and memset requires - * a function call that doesn't get inlined. - * - * memset(aBegin, 0, sizeof(T) * (aEnd - aBegin)); - */ - MOZ_ASSERT(aBegin <= aEnd); - for (T* p = aBegin; p < aEnd; ++p) { - new_(p); - } - } - - template - static inline void copyConstruct(T* aDst, - const U* aSrcStart, const U* aSrcEnd) - { - /* - * See above memset comment. Also, notice that copyConstruct is - * currently templated (T != U), so memcpy won't work without - * requiring T == U. - * - * memcpy(aDst, aSrcStart, sizeof(T) * (aSrcEnd - aSrcStart)); - */ - MOZ_ASSERT(aSrcStart <= aSrcEnd); - for (const U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) { - new_(aDst, *p); - } - } - - template - static inline void moveConstruct(T* aDst, - const U* aSrcStart, const U* aSrcEnd) - { - copyConstruct(aDst, aSrcStart, aSrcEnd); - } - - static inline void copyConstructN(T* aDst, size_t aN, const T& aT) - { - for (T* end = aDst + aN; aDst < end; ++aDst) { - new_(aDst, aT); - } - } - - static inline MOZ_MUST_USE bool - growTo(Vector& aV, size_t aNewCap) - { - MOZ_ASSERT(!aV.usingInlineStorage()); - MOZ_ASSERT(!CapacityHasExcessSpace(aNewCap)); - T* newbuf = aV.template pod_realloc(aV.mBegin, aV.mCapacity, aNewCap); - if (MOZ_UNLIKELY(!newbuf)) { - return false; - } - aV.mBegin = newbuf; - /* aV.mLength is unchanged. */ - aV.mCapacity = aNewCap; - return true; - } - - static inline void - podResizeToFit(Vector& aV) - { - if (aV.usingInlineStorage() || aV.mLength == aV.mCapacity) { - return; - } - T* newbuf = aV.template pod_realloc(aV.mBegin, aV.mCapacity, aV.mLength); - if (MOZ_UNLIKELY(!newbuf)) { - return; - } - aV.mBegin = newbuf; - aV.mCapacity = aV.mLength; - } -}; - -// A struct for TestVector.cpp to access private internal fields. -// DO NOT DEFINE IN YOUR OWN CODE. -struct VectorTesting; - -} // namespace detail - -/* - * STL-like container providing a short-lived, dynamic buffer. Vector calls the - * constructors/destructors of all elements stored in its internal buffer, so - * non-PODs may be safely used. Additionally, Vector will store the first N - * elements in-place before resorting to dynamic allocation. - * - * T requirements: - * - default and copy constructible, assignable, destructible - * - operations do not throw - * MinInlineCapacity requirements: - * - any value, however, MinInlineCapacity is clamped to min/max values - * AllocPolicy: - * - see "Allocation policies" in AllocPolicy.h (defaults to - * mozilla::MallocAllocPolicy) - * - * Vector is not reentrant: T member functions called during Vector member - * functions must not call back into the same object! - */ -template -class Vector final : private AllocPolicy -{ - /* utilities */ - - static const bool kElemIsPod = IsPod::value; - typedef detail::VectorImpl Impl; - friend struct detail::VectorImpl; - - friend struct detail::VectorTesting; - - MOZ_MUST_USE bool growStorageBy(size_t aIncr); - MOZ_MUST_USE bool convertToHeapStorage(size_t aNewCap); - MOZ_MUST_USE bool maybeCheckSimulatedOOM(size_t aRequestedSize); - - /* magic constants */ - - static const int kMaxInlineBytes = 1024; - - /* compute constants */ - - /* - * Consider element size to be 1 for buffer sizing if there are 0 inline - * elements. This allows us to compile when the definition of the element - * type is not visible here. - * - * Explicit specialization is only allowed at namespace scope, so in order - * to keep everything here, we use a dummy template parameter with partial - * specialization. - */ - template - struct ElemSize - { - static const size_t value = sizeof(T); - }; - template - struct ElemSize<0, Dummy> - { - static const size_t value = 1; - }; - - static const size_t kInlineCapacity = - tl::Min::value>::value; - - /* Calculate inline buffer size; avoid 0-sized array. */ - static const size_t kInlineBytes = - tl::Max<1, kInlineCapacity * ElemSize::value>::value; - - /* member data */ - - /* - * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, - * mBegin + mLength) hold valid constructed T objects. The range [mBegin + - * mLength, mBegin + mCapacity) holds uninitialized memory. The range - * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory - * previously allocated by a call to reserve(). - */ - T* mBegin; - - /* Number of elements in the vector. */ - size_t mLength; - - /* Max number of elements storable in the vector without resizing. */ - size_t mCapacity; - -#ifdef DEBUG - /* Max elements of reserved or used space in this vector. */ - size_t mReserved; -#endif - - /* Memory used for inline storage. */ - AlignedStorage mStorage; - -#ifdef DEBUG - friend class ReentrancyGuard; - bool mEntered; -#endif - - /* private accessors */ - - bool usingInlineStorage() const - { - return mBegin == const_cast(this)->inlineStorage(); - } - - T* inlineStorage() - { - return static_cast(mStorage.addr()); - } - - T* beginNoCheck() const - { - return mBegin; - } - - T* endNoCheck() - { - return mBegin + mLength; - } - - const T* endNoCheck() const - { - return mBegin + mLength; - } - -#ifdef DEBUG - /** - * The amount of explicitly allocated space in this vector that is immediately - * available to be filled by appending additional elements. This value is - * always greater than or equal to |length()| -- the vector's actual elements - * are implicitly reserved. This value is always less than or equal to - * |capacity()|. It may be explicitly increased using the |reserve()| method. - */ - size_t reserved() const - { - MOZ_ASSERT(mLength <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - return mReserved; - } -#endif - - /* Append operations guaranteed to succeed due to pre-reserved space. */ - template void internalAppend(U&& aU); - template - void internalAppendAll(const Vector& aU); - void internalAppendN(const T& aT, size_t aN); - template void internalAppend(const U* aBegin, size_t aLength); - -public: - static const size_t sMaxInlineStorage = MinInlineCapacity; - - typedef T ElementType; - - explicit Vector(AllocPolicy = AllocPolicy()); - Vector(Vector&&); /* Move constructor. */ - Vector& operator=(Vector&&); /* Move assignment. */ - ~Vector(); - - /* accessors */ - - const AllocPolicy& allocPolicy() const { return *this; } - - AllocPolicy& allocPolicy() { return *this; } - - enum { InlineLength = MinInlineCapacity }; - - size_t length() const { return mLength; } - - bool empty() const { return mLength == 0; } - - size_t capacity() const { return mCapacity; } - - T* begin() - { - MOZ_ASSERT(!mEntered); - return mBegin; - } - - const T* begin() const - { - MOZ_ASSERT(!mEntered); - return mBegin; - } - - T* end() - { - MOZ_ASSERT(!mEntered); - return mBegin + mLength; - } - - const T* end() const - { - MOZ_ASSERT(!mEntered); - return mBegin + mLength; - } - - T& operator[](size_t aIndex) - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(aIndex < mLength); - return begin()[aIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(aIndex < mLength); - return begin()[aIndex]; - } - - T& back() - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(!empty()); - return *(end() - 1); - } - - const T& back() const - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(!empty()); - return *(end() - 1); - } - - class Range - { - friend class Vector; - T* mCur; - T* mEnd; - Range(T* aCur, T* aEnd) - : mCur(aCur) - , mEnd(aEnd) - { - MOZ_ASSERT(aCur <= aEnd); - } - - public: - bool empty() const { return mCur == mEnd; } - size_t remain() const { return PointerRangeSize(mCur, mEnd); } - T& front() const { MOZ_ASSERT(!empty()); return *mCur; } - void popFront() { MOZ_ASSERT(!empty()); ++mCur; } - T popCopyFront() { MOZ_ASSERT(!empty()); return *mCur++; } - }; - - class ConstRange - { - friend class Vector; - const T* mCur; - const T* mEnd; - ConstRange(const T* aCur, const T* aEnd) - : mCur(aCur) - , mEnd(aEnd) - { - MOZ_ASSERT(aCur <= aEnd); - } - - public: - bool empty() const { return mCur == mEnd; } - size_t remain() const { return PointerRangeSize(mCur, mEnd); } - const T& front() const { MOZ_ASSERT(!empty()); return *mCur; } - void popFront() { MOZ_ASSERT(!empty()); ++mCur; } - T popCopyFront() { MOZ_ASSERT(!empty()); return *mCur++; } - }; - - Range all() { return Range(begin(), end()); } - ConstRange all() const { return ConstRange(begin(), end()); } - - /* mutators */ - - /** - * Reverse the order of the elements in the vector in place. - */ - void reverse(); - - /** - * Given that the vector is empty, grow the internal capacity to |aRequest|, - * keeping the length 0. - */ - MOZ_MUST_USE bool initCapacity(size_t aRequest); - - /** - * Given that the vector is empty, grow the internal capacity and length to - * |aRequest| leaving the elements' memory completely uninitialized (with all - * the associated hazards and caveats). This avoids the usual allocation-size - * rounding that happens in resize and overhead of initialization for elements - * that are about to be overwritten. - */ - MOZ_MUST_USE bool initLengthUninitialized(size_t aRequest); - - /** - * If reserve(aRequest) succeeds and |aRequest >= length()|, then appending - * |aRequest - length()| elements, in any sequence of append/appendAll calls, - * is guaranteed to succeed. - * - * A request to reserve an amount less than the current length does not affect - * reserved space. - */ - MOZ_MUST_USE bool reserve(size_t aRequest); - - /** - * Destroy elements in the range [end() - aIncr, end()). Does not deallocate - * or unreserve storage for those elements. - */ - void shrinkBy(size_t aIncr); - - /** - * Destroy elements in the range [aNewLength, end()). Does not deallocate - * or unreserve storage for those elements. - */ - void shrinkTo(size_t aNewLength); - - /** Grow the vector by aIncr elements. */ - MOZ_MUST_USE bool growBy(size_t aIncr); - - /** Call shrinkBy or growBy based on whether newSize > length(). */ - MOZ_MUST_USE bool resize(size_t aNewLength); - - /** - * Increase the length of the vector, but don't initialize the new elements - * -- leave them as uninitialized memory. - */ - MOZ_MUST_USE bool growByUninitialized(size_t aIncr); - void infallibleGrowByUninitialized(size_t aIncr); - MOZ_MUST_USE bool resizeUninitialized(size_t aNewLength); - - /** Shorthand for shrinkBy(length()). */ - void clear(); - - /** Clears and releases any heap-allocated storage. */ - void clearAndFree(); - - /** - * Calls the AllocPolicy's pod_realloc to release excess capacity. Since - * realloc is only safe on PODs, this method fails to compile if IsPod - * is false. - */ - void podResizeToFit(); - - /** - * If true, appending |aNeeded| elements won't reallocate elements storage. - * This *doesn't* mean that infallibleAppend may be used! You still must - * reserve the extra space, even if this method indicates that appends won't - * need to reallocate elements storage. - */ - bool canAppendWithoutRealloc(size_t aNeeded) const; - - /** Potentially fallible append operations. */ - - /** - * This can take either a T& or a T&&. Given a T&&, it moves |aU| into the - * vector, instead of copying it. If it fails, |aU| is left unmoved. ("We are - * not amused.") - */ - template MOZ_MUST_USE bool append(U&& aU); - - /** - * Construct a T in-place as a new entry at the end of this vector. - */ - template - MOZ_MUST_USE bool emplaceBack(Args&&... aArgs) - { - if (!growByUninitialized(1)) - return false; - Impl::new_(&back(), Forward(aArgs)...); - return true; - } - - template - MOZ_MUST_USE bool appendAll(const Vector& aU); - MOZ_MUST_USE bool appendN(const T& aT, size_t aN); - template MOZ_MUST_USE bool append(const U* aBegin, const U* aEnd); - template MOZ_MUST_USE bool append(const U* aBegin, size_t aLength); - - /* - * Guaranteed-infallible append operations for use upon vectors whose - * memory has been pre-reserved. Don't use this if you haven't reserved the - * memory! - */ - template void infallibleAppend(U&& aU) - { - internalAppend(Forward(aU)); - } - void infallibleAppendN(const T& aT, size_t aN) - { - internalAppendN(aT, aN); - } - template void infallibleAppend(const U* aBegin, const U* aEnd) - { - internalAppend(aBegin, PointerRangeSize(aBegin, aEnd)); - } - template void infallibleAppend(const U* aBegin, size_t aLength) - { - internalAppend(aBegin, aLength); - } - template - void infallibleEmplaceBack(Args&&... aArgs) - { - infallibleGrowByUninitialized(1); - Impl::new_(&back(), Forward(aArgs)...); - } - - void popBack(); - - T popCopy(); - - /** - * If elements are stored in-place, return nullptr and leave this vector - * unmodified. - * - * Otherwise return this vector's elements buffer, and clear this vector as if - * by clearAndFree(). The caller now owns the buffer and is responsible for - * deallocating it consistent with this vector's AllocPolicy. - * - * N.B. Although a T*, only the range [0, length()) is constructed. - */ - MOZ_MUST_USE T* extractRawBuffer(); - - /** - * If elements are stored in-place, allocate a new buffer, move this vector's - * elements into it, and return that buffer. - * - * Otherwise return this vector's elements buffer. The caller now owns the - * buffer and is responsible for deallocating it consistent with this vector's - * AllocPolicy. - * - * This vector is cleared, as if by clearAndFree(), when this method - * succeeds. This method fails and returns nullptr only if new elements buffer - * allocation fails. - * - * N.B. Only the range [0, length()) of the returned buffer is constructed. - * If any of these elements are uninitialized (as growByUninitialized - * enables), behavior is undefined. - */ - MOZ_MUST_USE T* extractOrCopyRawBuffer(); - - /** - * Transfer ownership of an array of objects into the vector. The caller - * must have allocated the array in accordance with this vector's - * AllocPolicy. - * - * N.B. This call assumes that there are no uninitialized elements in the - * passed array. - */ - void replaceRawBuffer(T* aP, size_t aLength); - - /** - * Places |aVal| at position |aP|, shifting existing elements from |aP| onward - * one position higher. On success, |aP| should not be reused because it'll - * be a dangling pointer if reallocation of the vector storage occurred; the - * return value should be used instead. On failure, nullptr is returned. - * - * Example usage: - * - * if (!(p = vec.insert(p, val))) { - * - * } - * - * - * This is inherently a linear-time operation. Be careful! - */ - template - MOZ_MUST_USE T* insert(T* aP, U&& aVal); - - /** - * Removes the element |aT|, which must fall in the bounds [begin, end), - * shifting existing elements from |aT + 1| onward one position lower. - */ - void erase(T* aT); - - /** - * Removes the elements [|aBegin|, |aEnd|), which must fall in the bounds - * [begin, end), shifting existing elements from |aEnd + 1| onward to aBegin's - * old position. - */ - void erase(T* aBegin, T* aEnd); - - /** - * Measure the size of the vector's heap-allocated storage. - */ - size_t sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const; - - /** - * Like sizeOfExcludingThis, but also measures the size of the vector - * object (which must be heap-allocated) itself. - */ - size_t sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const; - - void swap(Vector& aOther); - -private: - Vector(const Vector&) = delete; - void operator=(const Vector&) = delete; -}; - -/* This does the re-entrancy check plus several other sanity checks. */ -#define MOZ_REENTRANCY_GUARD_ET_AL \ - ReentrancyGuard g(*this); \ - MOZ_ASSERT_IF(usingInlineStorage(), mCapacity == kInlineCapacity); \ - MOZ_ASSERT(reserved() <= mCapacity); \ - MOZ_ASSERT(mLength <= reserved()); \ - MOZ_ASSERT(mLength <= mCapacity) - -/* Vector Implementation */ - -template -MOZ_ALWAYS_INLINE -Vector::Vector(AP aAP) - : AP(aAP) - , mLength(0) - , mCapacity(kInlineCapacity) -#ifdef DEBUG - , mReserved(0) - , mEntered(false) -#endif -{ - mBegin = static_cast(mStorage.addr()); -} - -/* Move constructor. */ -template -MOZ_ALWAYS_INLINE -Vector::Vector(Vector&& aRhs) - : AllocPolicy(Move(aRhs)) -#ifdef DEBUG - , mEntered(false) -#endif -{ - mLength = aRhs.mLength; - mCapacity = aRhs.mCapacity; -#ifdef DEBUG - mReserved = aRhs.mReserved; -#endif - - if (aRhs.usingInlineStorage()) { - /* We can't move the buffer over in this case, so copy elements. */ - mBegin = static_cast(mStorage.addr()); - Impl::moveConstruct(mBegin, aRhs.beginNoCheck(), aRhs.endNoCheck()); - /* - * Leave aRhs's mLength, mBegin, mCapacity, and mReserved as they are. - * The elements in its in-line storage still need to be destroyed. - */ - } else { - /* - * Take src's buffer, and turn src into an empty vector using - * in-line storage. - */ - mBegin = aRhs.mBegin; - aRhs.mBegin = static_cast(aRhs.mStorage.addr()); - aRhs.mCapacity = kInlineCapacity; - aRhs.mLength = 0; -#ifdef DEBUG - aRhs.mReserved = 0; -#endif - } -} - -/* Move assignment. */ -template -MOZ_ALWAYS_INLINE Vector& -Vector::operator=(Vector&& aRhs) -{ - MOZ_ASSERT(this != &aRhs, "self-move assignment is prohibited"); - this->~Vector(); - new(KnownNotNull, this) Vector(Move(aRhs)); - return *this; -} - -template -MOZ_ALWAYS_INLINE -Vector::~Vector() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) { - this->free_(beginNoCheck()); - } -} - -template -MOZ_ALWAYS_INLINE void -Vector::reverse() { - MOZ_REENTRANCY_GUARD_ET_AL; - T* elems = mBegin; - size_t len = mLength; - size_t mid = len / 2; - for (size_t i = 0; i < mid; i++) { - Swap(elems[i], elems[len - i - 1]); - } -} - -/* - * This function will create a new heap buffer with capacity aNewCap, - * move all elements in the inline buffer to this new buffer, - * and fail on OOM. - */ -template -inline bool -Vector::convertToHeapStorage(size_t aNewCap) -{ - MOZ_ASSERT(usingInlineStorage()); - - /* Allocate buffer. */ - MOZ_ASSERT(!detail::CapacityHasExcessSpace(aNewCap)); - T* newBuf = this->template pod_malloc(aNewCap); - if (MOZ_UNLIKELY(!newBuf)) { - return false; - } - - /* Copy inline elements into heap buffer. */ - Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - - /* Switch in heap buffer. */ - mBegin = newBuf; - /* mLength is unchanged. */ - mCapacity = aNewCap; - return true; -} - -template -MOZ_NEVER_INLINE bool -Vector::growStorageBy(size_t aIncr) -{ - MOZ_ASSERT(mLength + aIncr > mCapacity); - - /* - * When choosing a new capacity, its size should is as close to 2**N bytes - * as possible. 2**N-sized requests are best because they are unlikely to - * be rounded up by the allocator. Asking for a 2**N number of elements - * isn't as good, because if sizeof(T) is not a power-of-two that would - * result in a non-2**N request size. - */ - - size_t newCap; - - if (aIncr == 1) { - if (usingInlineStorage()) { - /* This case occurs in ~70--80% of the calls to this function. */ - size_t newSize = - tl::RoundUpPow2<(kInlineCapacity + 1) * sizeof(T)>::value; - newCap = newSize / sizeof(T); - goto convert; - } - - if (mLength == 0) { - /* This case occurs in ~0--10% of the calls to this function. */ - newCap = 1; - goto grow; - } - - /* This case occurs in ~15--20% of the calls to this function. */ - - /* - * Will mLength * 4 *sizeof(T) overflow? This condition limits a vector - * to 1GB of memory on a 32-bit system, which is a reasonable limit. It - * also ensures that - * - * static_cast(end()) - static_cast(begin()) - * - * doesn't overflow ptrdiff_t (see bug 510319). - */ - if (MOZ_UNLIKELY(mLength & tl::MulOverflowMask<4 * sizeof(T)>::value)) { - this->reportAllocOverflow(); - return false; - } - - /* - * If we reach here, the existing capacity will have a size that is already - * as close to 2^N as sizeof(T) will allow. Just double the capacity, and - * then there might be space for one more element. - */ - newCap = mLength * 2; - if (detail::CapacityHasExcessSpace(newCap)) { - newCap += 1; - } - } else { - /* This case occurs in ~2% of the calls to this function. */ - size_t newMinCap = mLength + aIncr; - - /* Did mLength + aIncr overflow? Will newCap * sizeof(T) overflow? */ - if (MOZ_UNLIKELY(newMinCap < mLength || - newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::value)) - { - this->reportAllocOverflow(); - return false; - } - - size_t newMinSize = newMinCap * sizeof(T); - size_t newSize = RoundUpPow2(newMinSize); - newCap = newSize / sizeof(T); - } - - if (usingInlineStorage()) { -convert: - return convertToHeapStorage(newCap); - } - -grow: - return Impl::growTo(*this, newCap); -} - -template -inline bool -Vector::initCapacity(size_t aRequest) -{ - MOZ_ASSERT(empty()); - MOZ_ASSERT(usingInlineStorage()); - if (aRequest == 0) { - return true; - } - T* newbuf = this->template pod_malloc(aRequest); - if (MOZ_UNLIKELY(!newbuf)) { - return false; - } - mBegin = newbuf; - mCapacity = aRequest; -#ifdef DEBUG - mReserved = aRequest; -#endif - return true; -} - -template -inline bool -Vector::initLengthUninitialized(size_t aRequest) -{ - if (!initCapacity(aRequest)) { - return false; - } - infallibleGrowByUninitialized(aRequest); - return true; -} - -template -inline bool -Vector::maybeCheckSimulatedOOM(size_t aRequestedSize) -{ - if (aRequestedSize <= N) { - return true; - } - -#ifdef DEBUG - if (aRequestedSize <= mReserved) { - return true; - } -#endif - - return allocPolicy().checkSimulatedOOM(); -} - -template -inline bool -Vector::reserve(size_t aRequest) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (aRequest > mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(aRequest - mLength))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(aRequest)) { - return false; - } -#ifdef DEBUG - if (aRequest > mReserved) { - mReserved = aRequest; - } - MOZ_ASSERT(mLength <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); -#endif - return true; -} - -template -inline void -Vector::shrinkBy(size_t aIncr) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - MOZ_ASSERT(aIncr <= mLength); - Impl::destroy(endNoCheck() - aIncr, endNoCheck()); - mLength -= aIncr; -} - -template -MOZ_ALWAYS_INLINE void -Vector::shrinkTo(size_t aNewLength) -{ - MOZ_ASSERT(aNewLength <= mLength); - shrinkBy(mLength - aNewLength); -} - -template -MOZ_ALWAYS_INLINE bool -Vector::growBy(size_t aIncr) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (aIncr > mCapacity - mLength) { - if (MOZ_UNLIKELY(!growStorageBy(aIncr))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aIncr)) { - return false; - } - MOZ_ASSERT(mLength + aIncr <= mCapacity); - T* newend = endNoCheck() + aIncr; - Impl::initialize(endNoCheck(), newend); - mLength += aIncr; -#ifdef DEBUG - if (mLength > mReserved) { - mReserved = mLength; - } -#endif - return true; -} - -template -MOZ_ALWAYS_INLINE bool -Vector::growByUninitialized(size_t aIncr) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (aIncr > mCapacity - mLength) { - if (MOZ_UNLIKELY(!growStorageBy(aIncr))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aIncr)) { - return false; - } -#ifdef DEBUG - if (mLength + aIncr > mReserved) { - mReserved = mLength + aIncr; - } -#endif - infallibleGrowByUninitialized(aIncr); - return true; -} - -template -MOZ_ALWAYS_INLINE void -Vector::infallibleGrowByUninitialized(size_t aIncr) -{ - MOZ_ASSERT(mLength + aIncr <= reserved()); - mLength += aIncr; -} - -template -inline bool -Vector::resize(size_t aNewLength) -{ - size_t curLength = mLength; - if (aNewLength > curLength) { - return growBy(aNewLength - curLength); - } - shrinkBy(curLength - aNewLength); - return true; -} - -template -MOZ_ALWAYS_INLINE bool -Vector::resizeUninitialized(size_t aNewLength) -{ - size_t curLength = mLength; - if (aNewLength > curLength) { - return growByUninitialized(aNewLength - curLength); - } - shrinkBy(curLength - aNewLength); - return true; -} - -template -inline void -Vector::clear() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - mLength = 0; -} - -template -inline void -Vector::clearAndFree() -{ - clear(); - - if (usingInlineStorage()) { - return; - } - this->free_(beginNoCheck()); - mBegin = static_cast(mStorage.addr()); - mCapacity = kInlineCapacity; -#ifdef DEBUG - mReserved = 0; -#endif -} - -template -inline void -Vector::podResizeToFit() -{ - // This function is only defined if IsPod is true and will fail to compile - // otherwise. - Impl::podResizeToFit(*this); -} - -template -inline bool -Vector::canAppendWithoutRealloc(size_t aNeeded) const -{ - return mLength + aNeeded <= mCapacity; -} - -template -template -MOZ_ALWAYS_INLINE void -Vector::internalAppendAll(const Vector& aOther) -{ - internalAppend(aOther.begin(), aOther.length()); -} - -template -template -MOZ_ALWAYS_INLINE void -Vector::internalAppend(U&& aU) -{ - MOZ_ASSERT(mLength + 1 <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - Impl::new_(endNoCheck(), Forward(aU)); - ++mLength; -} - -template -MOZ_ALWAYS_INLINE bool -Vector::appendN(const T& aT, size_t aNeeded) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (mLength + aNeeded > mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(aNeeded))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aNeeded)) { - return false; - } -#ifdef DEBUG - if (mLength + aNeeded > mReserved) { - mReserved = mLength + aNeeded; - } -#endif - internalAppendN(aT, aNeeded); - return true; -} - -template -MOZ_ALWAYS_INLINE void -Vector::internalAppendN(const T& aT, size_t aNeeded) -{ - MOZ_ASSERT(mLength + aNeeded <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - Impl::copyConstructN(endNoCheck(), aNeeded, aT); - mLength += aNeeded; -} - -template -template -inline T* -Vector::insert(T* aP, U&& aVal) -{ - MOZ_ASSERT(begin() <= aP); - MOZ_ASSERT(aP <= end()); - size_t pos = aP - begin(); - MOZ_ASSERT(pos <= mLength); - size_t oldLength = mLength; - if (pos == oldLength) { - if (!append(Forward(aVal))) { - return nullptr; - } - } else { - T oldBack = Move(back()); - if (!append(Move(oldBack))) { /* Dup the last element. */ - return nullptr; - } - for (size_t i = oldLength; i > pos; --i) { - (*this)[i] = Move((*this)[i - 1]); - } - (*this)[pos] = Forward(aVal); - } - return begin() + pos; -} - -template -inline void -Vector::erase(T* aIt) -{ - MOZ_ASSERT(begin() <= aIt); - MOZ_ASSERT(aIt < end()); - while (aIt + 1 < end()) { - *aIt = Move(*(aIt + 1)); - ++aIt; - } - popBack(); -} - -template -inline void -Vector::erase(T* aBegin, T* aEnd) -{ - MOZ_ASSERT(begin() <= aBegin); - MOZ_ASSERT(aBegin <= aEnd); - MOZ_ASSERT(aEnd <= end()); - while (aEnd < end()) { - *aBegin++ = Move(*aEnd++); - } - shrinkBy(aEnd - aBegin); -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::append(const U* aInsBegin, const U* aInsEnd) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - size_t aNeeded = PointerRangeSize(aInsBegin, aInsEnd); - if (mLength + aNeeded > mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(aNeeded))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aNeeded)) { - return false; - } -#ifdef DEBUG - if (mLength + aNeeded > mReserved) { - mReserved = mLength + aNeeded; - } -#endif - internalAppend(aInsBegin, aNeeded); - return true; -} - -template -template -MOZ_ALWAYS_INLINE void -Vector::internalAppend(const U* aInsBegin, size_t aInsLength) -{ - MOZ_ASSERT(mLength + aInsLength <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - Impl::copyConstruct(endNoCheck(), aInsBegin, aInsBegin + aInsLength); - mLength += aInsLength; -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::append(U&& aU) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (mLength == mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(1))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + 1)) { - return false; - } -#ifdef DEBUG - if (mLength + 1 > mReserved) { - mReserved = mLength + 1; - } -#endif - internalAppend(Forward(aU)); - return true; -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::appendAll(const Vector& aOther) -{ - return append(aOther.begin(), aOther.length()); -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::append(const U* aInsBegin, size_t aInsLength) -{ - return append(aInsBegin, aInsBegin + aInsLength); -} - -template -MOZ_ALWAYS_INLINE void -Vector::popBack() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - MOZ_ASSERT(!empty()); - --mLength; - endNoCheck()->~T(); -} - -template -MOZ_ALWAYS_INLINE T -Vector::popCopy() -{ - T ret = back(); - popBack(); - return ret; -} - -template -inline T* -Vector::extractRawBuffer() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - - if (usingInlineStorage()) { - return nullptr; - } - - T* ret = mBegin; - mBegin = static_cast(mStorage.addr()); - mLength = 0; - mCapacity = kInlineCapacity; -#ifdef DEBUG - mReserved = 0; -#endif - return ret; -} - -template -inline T* -Vector::extractOrCopyRawBuffer() -{ - if (T* ret = extractRawBuffer()) { - return ret; - } - - MOZ_REENTRANCY_GUARD_ET_AL; - - T* copy = this->template pod_malloc(mLength); - if (!copy) { - return nullptr; - } - - Impl::moveConstruct(copy, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - mBegin = static_cast(mStorage.addr()); - mLength = 0; - mCapacity = kInlineCapacity; -#ifdef DEBUG - mReserved = 0; -#endif - return copy; -} - -template -inline void -Vector::replaceRawBuffer(T* aP, size_t aLength) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - - /* Destroy what we have. */ - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) { - this->free_(beginNoCheck()); - } - - /* Take in the new buffer. */ - if (aLength <= kInlineCapacity) { - /* - * We convert to inline storage if possible, even though aP might - * otherwise be acceptable. Maybe this behaviour should be - * specifiable with an argument to this function. - */ - mBegin = static_cast(mStorage.addr()); - mLength = aLength; - mCapacity = kInlineCapacity; - Impl::moveConstruct(mBegin, aP, aP + aLength); - Impl::destroy(aP, aP + aLength); - this->free_(aP); - } else { - mBegin = aP; - mLength = aLength; - mCapacity = aLength; - } -#ifdef DEBUG - mReserved = aLength; -#endif -} - -template -inline size_t -Vector::sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const -{ - return usingInlineStorage() ? 0 : aMallocSizeOf(beginNoCheck()); -} - -template -inline size_t -Vector::sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const -{ - return aMallocSizeOf(this) + sizeOfExcludingThis(aMallocSizeOf); -} - -template -inline void -Vector::swap(Vector& aOther) -{ - static_assert(N == 0, - "still need to implement this for N != 0"); - - // This only works when inline storage is always empty. - if (!usingInlineStorage() && aOther.usingInlineStorage()) { - aOther.mBegin = mBegin; - mBegin = inlineStorage(); - } else if (usingInlineStorage() && !aOther.usingInlineStorage()) { - mBegin = aOther.mBegin; - aOther.mBegin = aOther.inlineStorage(); - } else if (!usingInlineStorage() && !aOther.usingInlineStorage()) { - Swap(mBegin, aOther.mBegin); - } else { - // This case is a no-op, since we'd set both to use their inline storage. - } - - Swap(mLength, aOther.mLength); - Swap(mCapacity, aOther.mCapacity); -#ifdef DEBUG - Swap(mReserved, aOther.mReserved); -#endif -} - -} // namespace mozilla - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif /* mozilla_Vector_h */ diff --git a/ios/include/spidermonkey/mozilla/WeakPtr.h b/ios/include/spidermonkey/mozilla/WeakPtr.h deleted file mode 100644 index ef0c19f4..00000000 --- a/ios/include/spidermonkey/mozilla/WeakPtr.h +++ /dev/null @@ -1,283 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Weak pointer functionality, implemented as a mixin for use with any class. */ - -/** - * SupportsWeakPtr lets you have a pointer to an object 'Foo' without affecting - * its lifetime. It works by creating a single shared reference counted object - * (WeakReference) that each WeakPtr will access 'Foo' through. This lets 'Foo' - * clear the pointer in the WeakReference without having to know about all of - * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime - * of 'Foo'. - * - * PLEASE NOTE: This weak pointer implementation is not thread-safe. - * - * Note that when deriving from SupportsWeakPtr you should add - * MOZ_DECLARE_WEAKREFERENCE_TYPENAME(ClassName) to the public section of your - * class, where ClassName is the name of your class. - * - * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional - * dereference, and an additional heap allocated pointer sized object shared - * between all of the WeakPtrs. - * - * Example of usage: - * - * // To have a class C support weak pointers, inherit from - * // SupportsWeakPtr. - * class C : public SupportsWeakPtr - * { - * public: - * MOZ_DECLARE_WEAKREFERENCE_TYPENAME(C) - * int mNum; - * void act(); - * }; - * - * C* ptr = new C(); - * - * // Get weak pointers to ptr. The first time a weak pointer - * // is obtained, a reference counted WeakReference object is created that - * // can live beyond the lifetime of 'ptr'. The WeakReference - * // object will be notified of 'ptr's destruction. - * WeakPtr weak = ptr; - * WeakPtr other = ptr; - * - * // Test a weak pointer for validity before using it. - * if (weak) { - * weak->mNum = 17; - * weak->act(); - * } - * - * // Destroying the underlying object clears weak pointers to it. - * delete ptr; - * - * MOZ_ASSERT(!weak, "Deleting |ptr| clears weak pointers to it."); - * MOZ_ASSERT(!other, "Deleting |ptr| clears all weak pointers to it."); - * - * WeakPtr is typesafe and may be used with any class. It is not required that - * the class be reference-counted or allocated in any particular way. - * - * The API was loosely inspired by Chromium's weak_ptr.h: - * http://src.chromium.org/svn/trunk/src/base/memory/weak_ptr.h - */ - -#ifndef mozilla_WeakPtr_h -#define mozilla_WeakPtr_h - -#include "mozilla/ArrayUtils.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/RefCounted.h" -#include "mozilla/RefPtr.h" -#include "mozilla/TypeTraits.h" - -#include - -// Weak referencing is not implemeted as thread safe. When a WeakPtr -// is created or dereferenced on thread A but the real object is just -// being Released() on thread B, there is a possibility of a race -// when the proxy object (detail::WeakReference) is notified about -// the real object destruction just between when thread A is storing -// the object pointer locally and is about to add a reference to it. -// -// Hence, a non-null weak proxy object is considered to have a single -// "owning thread". It means that each query for a weak reference, -// its dereference, and destruction of the real object must all happen -// on a single thread. The following macros implement assertions for -// checking these conditions. -// -// We disable this on MinGW. MinGW has two threading models: win32 -// API based, which disables std::thread; and POSIX based which -// enables it but requires an emulation library (winpthreads). -// Rather than attempting to switch to pthread emulation at this point, -// we are disabling the std::thread based assertion checking. -// -// In the future, to enable it we could -// a. have libgcc/stdc++ support win32 threads natively -// b. switch to POSIX-based threading in MinGW with pthread emulation -// c. refactor it to not use std::thread - -#if !defined(__MINGW32__) && (defined(DEBUG) || (defined(NIGHTLY_BUILD) && !defined(MOZ_PROFILING))) - -#include -#define MOZ_WEAKPTR_DECLARE_THREAD_SAFETY_CHECK \ - std::thread::id _owningThread; \ - bool _empty; // If it was initialized as a placeholder with mPtr = nullptr. -#define MOZ_WEAKPTR_INIT_THREAD_SAFETY_CHECK() \ - do { \ - _owningThread = std::this_thread::get_id(); \ - _empty = !p; \ - } while (false) -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY() \ - MOZ_DIAGNOSTIC_ASSERT(_empty || _owningThread == std::this_thread::get_id(), \ - "WeakPtr used on multiple threads") -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(that) \ - (that)->AssertThreadSafety(); - -#define MOZ_WEAKPTR_THREAD_SAFETY_CHECKING 1 - -#else - -#define MOZ_WEAKPTR_DECLARE_THREAD_SAFETY_CHECK -#define MOZ_WEAKPTR_INIT_THREAD_SAFETY_CHECK() do { } while (false) -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY() do { } while (false) -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(that) do { } while (false) - -#endif - -namespace mozilla { - -template class WeakPtr; -template class SupportsWeakPtr; - -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING -#define MOZ_DECLARE_WEAKREFERENCE_TYPENAME(T) \ - static const char* weakReferenceTypeName() { return "WeakReference<" #T ">"; } -#else -#define MOZ_DECLARE_WEAKREFERENCE_TYPENAME(T) -#endif - -namespace detail { - -// This can live beyond the lifetime of the class derived from -// SupportsWeakPtr. -template -class WeakReference : public ::mozilla::RefCounted > -{ -public: - explicit WeakReference(T* p) : mPtr(p) - { - MOZ_WEAKPTR_INIT_THREAD_SAFETY_CHECK(); - } - - T* get() const { - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY(); - return mPtr; - } - -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING - const char* typeName() const - { - // The first time this is called mPtr is null, so don't - // invoke any methods on mPtr. - return T::weakReferenceTypeName(); - } - size_t typeSize() const { return sizeof(*this); } -#endif - -#ifdef MOZ_WEAKPTR_THREAD_SAFETY_CHECKING - void AssertThreadSafety() { MOZ_WEAKPTR_ASSERT_THREAD_SAFETY(); } -#endif - -private: - friend class mozilla::SupportsWeakPtr; - - void detach() { - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY(); - mPtr = nullptr; - } - - T* MOZ_NON_OWNING_REF mPtr; - MOZ_WEAKPTR_DECLARE_THREAD_SAFETY_CHECK -}; - -} // namespace detail - -template -class SupportsWeakPtr -{ -protected: - ~SupportsWeakPtr() - { - static_assert(IsBaseOf, T>::value, - "T must derive from SupportsWeakPtr"); - if (mSelfReferencingWeakPtr) { - mSelfReferencingWeakPtr.mRef->detach(); - } - } - -private: - const WeakPtr& SelfReferencingWeakPtr() - { - if (!mSelfReferencingWeakPtr) { - mSelfReferencingWeakPtr.mRef = new detail::WeakReference(static_cast(this)); - } else { - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(mSelfReferencingWeakPtr.mRef); - } - return mSelfReferencingWeakPtr; - } - - const WeakPtr& SelfReferencingWeakPtr() const - { - const WeakPtr& p = const_cast(this)->SelfReferencingWeakPtr(); - return reinterpret_cast&>(p); - } - - friend class WeakPtr; - friend class WeakPtr; - - WeakPtr mSelfReferencingWeakPtr; -}; - -template -class WeakPtr -{ - typedef detail::WeakReference WeakReference; - -public: - WeakPtr& operator=(const WeakPtr& aOther) - { - mRef = aOther.mRef; - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(mRef); - return *this; - } - - WeakPtr(const WeakPtr& aOther) - { - // The thread safety check is performed inside of the operator= method. - *this = aOther; - } - - WeakPtr& operator=(T* aOther) - { - if (aOther) { - *this = aOther->SelfReferencingWeakPtr(); - } else if (!mRef || mRef->get()) { - // Ensure that mRef is dereferenceable in the uninitialized state. - mRef = new WeakReference(nullptr); - } - // The thread safety check happens inside SelfReferencingWeakPtr - // or is initialized in the WeakReference constructor. - return *this; - } - - MOZ_IMPLICIT WeakPtr(T* aOther) - { - *this = aOther; - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(mRef); - } - - // Ensure that mRef is dereferenceable in the uninitialized state. - WeakPtr() : mRef(new WeakReference(nullptr)) {} - - operator T*() const { return mRef->get(); } - T& operator*() const { return *mRef->get(); } - - T* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN { return mRef->get(); } - - T* get() const { return mRef->get(); } - -private: - friend class SupportsWeakPtr; - - explicit WeakPtr(const RefPtr& aOther) : mRef(aOther) {} - - RefPtr mRef; -}; - -} // namespace mozilla - -#endif /* mozilla_WeakPtr_h */ diff --git a/ios/include/spidermonkey/mozilla/XorShift128PlusRNG.h b/ios/include/spidermonkey/mozilla/XorShift128PlusRNG.h deleted file mode 100644 index 2f182f0f..00000000 --- a/ios/include/spidermonkey/mozilla/XorShift128PlusRNG.h +++ /dev/null @@ -1,121 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* The xorshift128+ pseudo-random number generator. */ - -#ifndef mozilla_XorShift128Plus_h -#define mozilla_XorShift128Plus_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/FloatingPoint.h" - -#include - -namespace mozilla { -namespace non_crypto { - -/* - * A stream of pseudo-random numbers generated using the xorshift+ technique - * described here: - * - * Vigna, Sebastiano (2014). "Further scramblings of Marsaglia's xorshift - * generators". arXiv:1404.0390 (http://arxiv.org/abs/1404.0390) - * - * That paper says: - * - * In particular, we propose a tightly coded xorshift128+ generator that - * does not fail systematically any test from the BigCrush suite of TestU01 - * (even reversed) and generates 64 pseudorandom bits in 1.10 ns on an - * Intel(R) Core(TM) i7-4770 CPU @3.40GHz (Haswell). It is the fastest - * generator we are aware of with such empirical statistical properties. - * - * The stream of numbers produced by this method repeats every 2**128 - 1 calls - * (i.e. never, for all practical purposes). Zero appears 2**64 - 1 times in - * this period; all other numbers appear 2**64 times. Additionally, each *bit* - * in the produced numbers repeats every 2**128 - 1 calls. - * - * This generator is not suitable as a cryptographically secure random number - * generator. - */ -class XorShift128PlusRNG { - uint64_t mState[2]; - - public: - /* - * Construct a xorshift128+ pseudo-random number stream using |aInitial0| and - * |aInitial1| as the initial state. These MUST NOT both be zero. - * - * If the initial states contain many zeros, for a few iterations you'll see - * many zeroes in the generated numbers. It's suggested to seed a SplitMix64 - * generator and use its first two - * outputs to seed xorshift128+. - */ - XorShift128PlusRNG(uint64_t aInitial0, uint64_t aInitial1) { - setState(aInitial0, aInitial1); - } - - /** - * Return a pseudo-random 64-bit number. - */ - uint64_t next() { - /* - * The offsetOfState*() methods below are provided so that exceedingly-rare - * callers that want to observe or poke at RNG state in C++ type-system- - * ignoring means can do so. Don't change the next() or nextDouble() - * algorithms without altering code that uses offsetOfState*()! - */ - uint64_t s1 = mState[0]; - const uint64_t s0 = mState[1]; - mState[0] = s0; - s1 ^= s1 << 23; - mState[1] = s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26); - return mState[1] + s0; - } - - /* - * Return a pseudo-random floating-point value in the range [0, 1). More - * precisely, choose an integer in the range [0, 2**53) and divide it by - * 2**53. Given the 2**128 - 1 period noted above, the produced doubles are - * all but uniformly distributed in this range. - */ - double nextDouble() { - /* - * Because the IEEE 64-bit floating point format stores the leading '1' bit - * of the mantissa implicitly, it effectively represents a mantissa in the - * range [0, 2**53) in only 52 bits. FloatingPoint::kExponentShift - * is the width of the bitfield in the in-memory format, so we must add one - * to get the mantissa's range. - */ - static constexpr int kMantissaBits = - mozilla::FloatingPoint::kExponentShift + 1; - uint64_t mantissa = next() & ((UINT64_C(1) << kMantissaBits) - 1); - return double(mantissa) / (UINT64_C(1) << kMantissaBits); - } - - /* - * Set the stream's current state to |aState0| and |aState1|. These must not - * both be zero; ideally, they should have an almost even mix of zero and one - * bits. - */ - void setState(uint64_t aState0, uint64_t aState1) { - MOZ_ASSERT(aState0 || aState1); - mState[0] = aState0; - mState[1] = aState1; - } - - static size_t offsetOfState0() { - return offsetof(XorShift128PlusRNG, mState[0]); - } - static size_t offsetOfState1() { - return offsetof(XorShift128PlusRNG, mState[1]); - } -}; - -} // namespace non_crypto -} // namespace mozilla - -#endif // mozilla_XorShift128Plus_h diff --git a/ios/include/spidermonkey/mozilla/double-conversion.h b/ios/include/spidermonkey/mozilla/double-conversion.h deleted file mode 100644 index 957575cf..00000000 --- a/ios/include/spidermonkey/mozilla/double-conversion.h +++ /dev/null @@ -1,538 +0,0 @@ -// Copyright 2012 the V8 project authors. All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following -// disclaimer in the documentation and/or other materials provided -// with the distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ -#define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ - -#include "mozilla/Types.h" -#include "utils.h" - -namespace double_conversion { - -class DoubleToStringConverter { - public: - // When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint - // or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the - // function returns false. - static const int kMaxFixedDigitsBeforePoint = 60; - static const int kMaxFixedDigitsAfterPoint = 60; - - // When calling ToExponential with a requested_digits - // parameter > kMaxExponentialDigits then the function returns false. - static const int kMaxExponentialDigits = 120; - - // When calling ToPrecision with a requested_digits - // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits - // then the function returns false. - static const int kMinPrecisionDigits = 1; - static const int kMaxPrecisionDigits = 120; - - enum Flags { - NO_FLAGS = 0, - EMIT_POSITIVE_EXPONENT_SIGN = 1, - EMIT_TRAILING_DECIMAL_POINT = 2, - EMIT_TRAILING_ZERO_AFTER_POINT = 4, - UNIQUE_ZERO = 8 - }; - - // Flags should be a bit-or combination of the possible Flags-enum. - // - NO_FLAGS: no special flags. - // - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent - // form, emits a '+' for positive exponents. Example: 1.2e+2. - // - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is - // converted into decimal format then a trailing decimal point is appended. - // Example: 2345.0 is converted to "2345.". - // - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point - // emits a trailing '0'-character. This flag requires the - // EXMIT_TRAILING_DECIMAL_POINT flag. - // Example: 2345.0 is converted to "2345.0". - // - UNIQUE_ZERO: "-0.0" is converted to "0.0". - // - // Infinity symbol and nan_symbol provide the string representation for these - // special values. If the string is NULL and the special value is encountered - // then the conversion functions return false. - // - // The exponent_character is used in exponential representations. It is - // usually 'e' or 'E'. - // - // When converting to the shortest representation the converter will - // represent input numbers in decimal format if they are in the interval - // [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[ - // (lower boundary included, greater boundary excluded). - // Example: with decimal_in_shortest_low = -6 and - // decimal_in_shortest_high = 21: - // ToShortest(0.000001) -> "0.000001" - // ToShortest(0.0000001) -> "1e-7" - // ToShortest(111111111111111111111.0) -> "111111111111111110000" - // ToShortest(100000000000000000000.0) -> "100000000000000000000" - // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21" - // - // When converting to precision mode the converter may add - // max_leading_padding_zeroes before returning the number in exponential - // format. - // Example with max_leading_padding_zeroes_in_precision_mode = 6. - // ToPrecision(0.0000012345, 2) -> "0.0000012" - // ToPrecision(0.00000012345, 2) -> "1.2e-7" - // Similarily the converter may add up to - // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid - // returning an exponential representation. A zero added by the - // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit. - // Examples for max_trailing_padding_zeroes_in_precision_mode = 1: - // ToPrecision(230.0, 2) -> "230" - // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT. - // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT. - DoubleToStringConverter(int flags, - const char* infinity_symbol, - const char* nan_symbol, - char exponent_character, - int decimal_in_shortest_low, - int decimal_in_shortest_high, - int max_leading_padding_zeroes_in_precision_mode, - int max_trailing_padding_zeroes_in_precision_mode) - : flags_(flags), - infinity_symbol_(infinity_symbol), - nan_symbol_(nan_symbol), - exponent_character_(exponent_character), - decimal_in_shortest_low_(decimal_in_shortest_low), - decimal_in_shortest_high_(decimal_in_shortest_high), - max_leading_padding_zeroes_in_precision_mode_( - max_leading_padding_zeroes_in_precision_mode), - max_trailing_padding_zeroes_in_precision_mode_( - max_trailing_padding_zeroes_in_precision_mode) { - // When 'trailing zero after the point' is set, then 'trailing point' - // must be set too. - ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) || - !((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0)); - } - - // Returns a converter following the EcmaScript specification. - static MFBT_API const DoubleToStringConverter& EcmaScriptConverter(); - - // Computes the shortest string of digits that correctly represent the input - // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high - // (see constructor) it then either returns a decimal representation, or an - // exponential representation. - // Example with decimal_in_shortest_low = -6, - // decimal_in_shortest_high = 21, - // EMIT_POSITIVE_EXPONENT_SIGN activated, and - // EMIT_TRAILING_DECIMAL_POINT deactived: - // ToShortest(0.000001) -> "0.000001" - // ToShortest(0.0000001) -> "1e-7" - // ToShortest(111111111111111111111.0) -> "111111111111111110000" - // ToShortest(100000000000000000000.0) -> "100000000000000000000" - // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21" - // - // Note: the conversion may round the output if the returned string - // is accurate enough to uniquely identify the input-number. - // For example the most precise representation of the double 9e59 equals - // "899999999999999918767229449717619953810131273674690656206848", but - // the converter will return the shorter (but still correct) "9e59". - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except when the input value is special and no infinity_symbol or - // nan_symbol has been given to the constructor. - bool ToShortest(double value, StringBuilder* result_builder) const { - return ToShortestIeeeNumber(value, result_builder, SHORTEST); - } - - // Same as ToShortest, but for single-precision floats. - bool ToShortestSingle(float value, StringBuilder* result_builder) const { - return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE); - } - - - // Computes a decimal representation with a fixed number of digits after the - // decimal point. The last emitted digit is rounded. - // - // Examples: - // ToFixed(3.12, 1) -> "3.1" - // ToFixed(3.1415, 3) -> "3.142" - // ToFixed(1234.56789, 4) -> "1234.5679" - // ToFixed(1.23, 5) -> "1.23000" - // ToFixed(0.1, 4) -> "0.1000" - // ToFixed(1e30, 2) -> "1000000000000000019884624838656.00" - // ToFixed(0.1, 30) -> "0.100000000000000005551115123126" - // ToFixed(0.1, 17) -> "0.10000000000000001" - // - // If requested_digits equals 0, then the tail of the result depends on - // the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT. - // Examples, for requested_digits == 0, - // let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be - // - false and false: then 123.45 -> 123 - // 0.678 -> 1 - // - true and false: then 123.45 -> 123. - // 0.678 -> 1. - // - true and true: then 123.45 -> 123.0 - // 0.678 -> 1.0 - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except for the following cases: - // - the input value is special and no infinity_symbol or nan_symbol has - // been provided to the constructor, - // - 'value' > 10^kMaxFixedDigitsBeforePoint, or - // - 'requested_digits' > kMaxFixedDigitsAfterPoint. - // The last two conditions imply that the result will never contain more than - // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters - // (one additional character for the sign, and one for the decimal point). - MFBT_API bool ToFixed(double value, - int requested_digits, - StringBuilder* result_builder) const; - - // Computes a representation in exponential format with requested_digits - // after the decimal point. The last emitted digit is rounded. - // If requested_digits equals -1, then the shortest exponential representation - // is computed. - // - // Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and - // exponent_character set to 'e'. - // ToExponential(3.12, 1) -> "3.1e0" - // ToExponential(5.0, 3) -> "5.000e0" - // ToExponential(0.001, 2) -> "1.00e-3" - // ToExponential(3.1415, -1) -> "3.1415e0" - // ToExponential(3.1415, 4) -> "3.1415e0" - // ToExponential(3.1415, 3) -> "3.142e0" - // ToExponential(123456789000000, 3) -> "1.235e14" - // ToExponential(1000000000000000019884624838656.0, -1) -> "1e30" - // ToExponential(1000000000000000019884624838656.0, 32) -> - // "1.00000000000000001988462483865600e30" - // ToExponential(1234, 0) -> "1e3" - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except for the following cases: - // - the input value is special and no infinity_symbol or nan_symbol has - // been provided to the constructor, - // - 'requested_digits' > kMaxExponentialDigits. - // The last condition implies that the result will never contain more than - // kMaxExponentialDigits + 8 characters (the sign, the digit before the - // decimal point, the decimal point, the exponent character, the - // exponent's sign, and at most 3 exponent digits). - MFBT_API bool ToExponential(double value, - int requested_digits, - StringBuilder* result_builder) const; - - // Computes 'precision' leading digits of the given 'value' and returns them - // either in exponential or decimal format, depending on - // max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the - // constructor). - // The last computed digit is rounded. - // - // Example with max_leading_padding_zeroes_in_precision_mode = 6. - // ToPrecision(0.0000012345, 2) -> "0.0000012" - // ToPrecision(0.00000012345, 2) -> "1.2e-7" - // Similarily the converter may add up to - // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid - // returning an exponential representation. A zero added by the - // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit. - // Examples for max_trailing_padding_zeroes_in_precision_mode = 1: - // ToPrecision(230.0, 2) -> "230" - // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT. - // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT. - // Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no - // EMIT_TRAILING_ZERO_AFTER_POINT: - // ToPrecision(123450.0, 6) -> "123450" - // ToPrecision(123450.0, 5) -> "123450" - // ToPrecision(123450.0, 4) -> "123500" - // ToPrecision(123450.0, 3) -> "123000" - // ToPrecision(123450.0, 2) -> "1.2e5" - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except for the following cases: - // - the input value is special and no infinity_symbol or nan_symbol has - // been provided to the constructor, - // - precision < kMinPericisionDigits - // - precision > kMaxPrecisionDigits - // The last condition implies that the result will never contain more than - // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the - // exponent character, the exponent's sign, and at most 3 exponent digits). - MFBT_API bool ToPrecision(double value, - int precision, - bool* used_exponential_notation, - StringBuilder* result_builder) const; - - enum DtoaMode { - // Produce the shortest correct representation. - // For example the output of 0.299999999999999988897 is (the less accurate - // but correct) 0.3. - SHORTEST, - // Same as SHORTEST, but for single-precision floats. - SHORTEST_SINGLE, - // Produce a fixed number of digits after the decimal point. - // For instance fixed(0.1, 4) becomes 0.1000 - // If the input number is big, the output will be big. - FIXED, - // Fixed number of digits (independent of the decimal point). - PRECISION - }; - - // The maximal number of digits that are needed to emit a double in base 10. - // A higher precision can be achieved by using more digits, but the shortest - // accurate representation of any double will never use more digits than - // kBase10MaximalLength. - // Note that DoubleToAscii null-terminates its input. So the given buffer - // should be at least kBase10MaximalLength + 1 characters long. - static const MFBT_DATA int kBase10MaximalLength = 17; - - // Converts the given double 'v' to ascii. 'v' must not be NaN, +Infinity, or - // -Infinity. In SHORTEST_SINGLE-mode this restriction also applies to 'v' - // after it has been casted to a single-precision float. That is, in this - // mode static_cast(v) must not be NaN, +Infinity or -Infinity. - // - // The result should be interpreted as buffer * 10^(point-length). - // - // The output depends on the given mode: - // - SHORTEST: produce the least amount of digits for which the internal - // identity requirement is still satisfied. If the digits are printed - // (together with the correct exponent) then reading this number will give - // 'v' again. The buffer will choose the representation that is closest to - // 'v'. If there are two at the same distance, than the one farther away - // from 0 is chosen (halfway cases - ending with 5 - are rounded up). - // In this mode the 'requested_digits' parameter is ignored. - // - SHORTEST_SINGLE: same as SHORTEST but with single-precision. - // - FIXED: produces digits necessary to print a given number with - // 'requested_digits' digits after the decimal point. The produced digits - // might be too short in which case the caller has to fill the remainder - // with '0's. - // Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2. - // Halfway cases are rounded towards +/-Infinity (away from 0). The call - // toFixed(0.15, 2) thus returns buffer="2", point=0. - // The returned buffer may contain digits that would be truncated from the - // shortest representation of the input. - // - PRECISION: produces 'requested_digits' where the first digit is not '0'. - // Even though the length of produced digits usually equals - // 'requested_digits', the function is allowed to return fewer digits, in - // which case the caller has to fill the missing digits with '0's. - // Halfway cases are again rounded away from 0. - // DoubleToAscii expects the given buffer to be big enough to hold all - // digits and a terminating null-character. In SHORTEST-mode it expects a - // buffer of at least kBase10MaximalLength + 1. In all other modes the - // requested_digits parameter and the padding-zeroes limit the size of the - // output. Don't forget the decimal point, the exponent character and the - // terminating null-character when computing the maximal output size. - // The given length is only used in debug mode to ensure the buffer is big - // enough. - static MFBT_API void DoubleToAscii(double v, - DtoaMode mode, - int requested_digits, - char* buffer, - int buffer_length, - bool* sign, - int* length, - int* point); - - private: - // Implementation for ToShortest and ToShortestSingle. - MFBT_API bool ToShortestIeeeNumber(double value, - StringBuilder* result_builder, - DtoaMode mode) const; - - // If the value is a special value (NaN or Infinity) constructs the - // corresponding string using the configured infinity/nan-symbol. - // If either of them is NULL or the value is not special then the - // function returns false. - MFBT_API bool HandleSpecialValues(double value, StringBuilder* result_builder) const; - // Constructs an exponential representation (i.e. 1.234e56). - // The given exponent assumes a decimal point after the first decimal digit. - MFBT_API void CreateExponentialRepresentation(const char* decimal_digits, - int length, - int exponent, - StringBuilder* result_builder) const; - // Creates a decimal representation (i.e 1234.5678). - MFBT_API void CreateDecimalRepresentation(const char* decimal_digits, - int length, - int decimal_point, - int digits_after_point, - StringBuilder* result_builder) const; - - const int flags_; - const char* const infinity_symbol_; - const char* const nan_symbol_; - const char exponent_character_; - const int decimal_in_shortest_low_; - const int decimal_in_shortest_high_; - const int max_leading_padding_zeroes_in_precision_mode_; - const int max_trailing_padding_zeroes_in_precision_mode_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter); -}; - - -class StringToDoubleConverter { - public: - // Enumeration for allowing octals and ignoring junk when converting - // strings to numbers. - enum Flags { - NO_FLAGS = 0, - ALLOW_HEX = 1, - ALLOW_OCTALS = 2, - ALLOW_TRAILING_JUNK = 4, - ALLOW_LEADING_SPACES = 8, - ALLOW_TRAILING_SPACES = 16, - ALLOW_SPACES_AFTER_SIGN = 32 - }; - - // Flags should be a bit-or combination of the possible Flags-enum. - // - NO_FLAGS: no special flags. - // - ALLOW_HEX: recognizes the prefix "0x". Hex numbers may only be integers. - // Ex: StringToDouble("0x1234") -> 4660.0 - // In StringToDouble("0x1234.56") the characters ".56" are trailing - // junk. The result of the call is hence dependent on - // the ALLOW_TRAILING_JUNK flag and/or the junk value. - // With this flag "0x" is a junk-string. Even with ALLOW_TRAILING_JUNK, - // the string will not be parsed as "0" followed by junk. - // - // - ALLOW_OCTALS: recognizes the prefix "0" for octals: - // If a sequence of octal digits starts with '0', then the number is - // read as octal integer. Octal numbers may only be integers. - // Ex: StringToDouble("01234") -> 668.0 - // StringToDouble("012349") -> 12349.0 // Not a sequence of octal - // // digits. - // In StringToDouble("01234.56") the characters ".56" are trailing - // junk. The result of the call is hence dependent on - // the ALLOW_TRAILING_JUNK flag and/or the junk value. - // In StringToDouble("01234e56") the characters "e56" are trailing - // junk, too. - // - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of - // a double literal. - // - ALLOW_LEADING_SPACES: skip over leading spaces. - // - ALLOW_TRAILING_SPACES: ignore trailing spaces. - // - ALLOW_SPACES_AFTER_SIGN: ignore spaces after the sign. - // Ex: StringToDouble("- 123.2") -> -123.2. - // StringToDouble("+ 123.2") -> 123.2 - // - // empty_string_value is returned when an empty string is given as input. - // If ALLOW_LEADING_SPACES or ALLOW_TRAILING_SPACES are set, then a string - // containing only spaces is converted to the 'empty_string_value', too. - // - // junk_string_value is returned when - // a) ALLOW_TRAILING_JUNK is not set, and a junk character (a character not - // part of a double-literal) is found. - // b) ALLOW_TRAILING_JUNK is set, but the string does not start with a - // double literal. - // - // infinity_symbol and nan_symbol are strings that are used to detect - // inputs that represent infinity and NaN. They can be null, in which case - // they are ignored. - // The conversion routine first reads any possible signs. Then it compares the - // following character of the input-string with the first character of - // the infinity, and nan-symbol. If either matches, the function assumes, that - // a match has been found, and expects the following input characters to match - // the remaining characters of the special-value symbol. - // This means that the following restrictions apply to special-value symbols: - // - they must not start with signs ('+', or '-'), - // - they must not have the same first character. - // - they must not start with digits. - // - // Examples: - // flags = ALLOW_HEX | ALLOW_TRAILING_JUNK, - // empty_string_value = 0.0, - // junk_string_value = NaN, - // infinity_symbol = "infinity", - // nan_symbol = "nan": - // StringToDouble("0x1234") -> 4660.0. - // StringToDouble("0x1234K") -> 4660.0. - // StringToDouble("") -> 0.0 // empty_string_value. - // StringToDouble(" ") -> NaN // junk_string_value. - // StringToDouble(" 1") -> NaN // junk_string_value. - // StringToDouble("0x") -> NaN // junk_string_value. - // StringToDouble("-123.45") -> -123.45. - // StringToDouble("--123.45") -> NaN // junk_string_value. - // StringToDouble("123e45") -> 123e45. - // StringToDouble("123E45") -> 123e45. - // StringToDouble("123e+45") -> 123e45. - // StringToDouble("123E-45") -> 123e-45. - // StringToDouble("123e") -> 123.0 // trailing junk ignored. - // StringToDouble("123e-") -> 123.0 // trailing junk ignored. - // StringToDouble("+NaN") -> NaN // NaN string literal. - // StringToDouble("-infinity") -> -inf. // infinity literal. - // StringToDouble("Infinity") -> NaN // junk_string_value. - // - // flags = ALLOW_OCTAL | ALLOW_LEADING_SPACES, - // empty_string_value = 0.0, - // junk_string_value = NaN, - // infinity_symbol = NULL, - // nan_symbol = NULL: - // StringToDouble("0x1234") -> NaN // junk_string_value. - // StringToDouble("01234") -> 668.0. - // StringToDouble("") -> 0.0 // empty_string_value. - // StringToDouble(" ") -> 0.0 // empty_string_value. - // StringToDouble(" 1") -> 1.0 - // StringToDouble("0x") -> NaN // junk_string_value. - // StringToDouble("0123e45") -> NaN // junk_string_value. - // StringToDouble("01239E45") -> 1239e45. - // StringToDouble("-infinity") -> NaN // junk_string_value. - // StringToDouble("NaN") -> NaN // junk_string_value. - StringToDoubleConverter(int flags, - double empty_string_value, - double junk_string_value, - const char* infinity_symbol, - const char* nan_symbol) - : flags_(flags), - empty_string_value_(empty_string_value), - junk_string_value_(junk_string_value), - infinity_symbol_(infinity_symbol), - nan_symbol_(nan_symbol) { - } - - // Performs the conversion. - // The output parameter 'processed_characters_count' is set to the number - // of characters that have been processed to read the number. - // Spaces than are processed with ALLOW_{LEADING|TRAILING}_SPACES are included - // in the 'processed_characters_count'. Trailing junk is never included. - double StringToDouble(const char* buffer, - int length, - int* processed_characters_count) const { - return StringToIeee(buffer, length, processed_characters_count, true); - } - - // Same as StringToDouble but reads a float. - // Note that this is not equivalent to static_cast(StringToDouble(...)) - // due to potential double-rounding. - float StringToFloat(const char* buffer, - int length, - int* processed_characters_count) const { - return static_cast(StringToIeee(buffer, length, - processed_characters_count, false)); - } - - private: - const int flags_; - const double empty_string_value_; - const double junk_string_value_; - const char* const infinity_symbol_; - const char* const nan_symbol_; - - double StringToIeee(const char* buffer, - int length, - int* processed_characters_count, - bool read_as_double) const; - - DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter); -}; - -} // namespace double_conversion - -#endif // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ diff --git a/ios/include/spidermonkey/mozilla/fallible.h b/ios/include/spidermonkey/mozilla/fallible.h deleted file mode 100644 index c028360b..00000000 --- a/ios/include/spidermonkey/mozilla/fallible.h +++ /dev/null @@ -1,68 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_fallible_h -#define mozilla_fallible_h - -#if defined(__cplusplus) - -/* Explicit fallible allocation - * - * Memory allocation (normally) defaults to abort in case of failed - * allocation. That is, it never returns NULL, and crashes instead. - * - * Code can explicitely request for fallible memory allocation thanks - * to the declarations below. - * - * The typical use of the mozilla::fallible const is with placement new, - * like the following: - * - * foo = new (mozilla::fallible) Foo(); - * - * The following forms, or derivatives, are also possible but deprecated: - * - * foo = new ((mozilla::fallible_t())) Foo(); - * - * const mozilla::fallible_t fallible = mozilla::fallible_t(); - * bar = new (f) Bar(); - * - * It is also possible to declare method overloads with fallible allocation - * alternatives, like so: - * - * class Foo { - * public: - * void Method(void *); - * void Method(void *, const mozilla::fallible_t&); - * }; - * - * Foo foo; - * foo.Method(nullptr, mozilla::fallible); - * - * If that last method call is in a method that itself takes a const - * fallible_t& argument, it is recommended to propagate that argument - * instead of using mozilla::fallible: - * - * void Func(Foo &foo, const mozilla::fallible_t& aFallible) { - * foo.Method(nullptr, aFallible); - * } - * - */ -namespace mozilla { - -struct fallible_t { }; - -/* This symbol is kept unexported, such that in corner cases where the - * compiler can't remove its use (essentially, cross compilation-unit - * calls), the smallest machine code is used. - * Depending how the linker packs symbols, it will consume between 1 and - * 8 bytes of read-only data in each executable or shared library, but - * only in those where it's actually not optimized out by the compiler. - */ -extern const fallible_t fallible; - -} // namespace mozilla - -#endif - -#endif // mozilla_fallible_h diff --git a/ios/include/spidermonkey/mozilla/mozalloc.h b/ios/include/spidermonkey/mozilla/mozalloc.h deleted file mode 100644 index f7ddb7e6..00000000 --- a/ios/include/spidermonkey/mozilla/mozalloc.h +++ /dev/null @@ -1,361 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: sw=4 ts=4 et : - */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_mozalloc_h -#define mozilla_mozalloc_h - -/* - * https://bugzilla.mozilla.org/show_bug.cgi?id=427099 - */ - -#if defined(__cplusplus) -# include -// Since libstdc++ 6, including the C headers (e.g. stdlib.h) instead of the -// corresponding C++ header (e.g. cstdlib) can cause confusion in C++ code -// using things defined there. Specifically, with stdlib.h, the use of abs() -// in gfx/graphite2/src/inc/UtfCodec.h somehow ends up picking the wrong abs() -# include -# include -#else -# include -# include -#endif - -#if defined(__cplusplus) -#include "mozilla/fallible.h" -#include "mozilla/mozalloc_abort.h" -#include "mozilla/TemplateLib.h" -#endif -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" - -#define MOZALLOC_HAVE_XMALLOC - -#if defined(MOZ_ALWAYS_INLINE_EVEN_DEBUG) -# define MOZALLOC_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG -#elif defined(HAVE_FORCEINLINE) -# define MOZALLOC_INLINE __forceinline -#else -# define MOZALLOC_INLINE inline -#endif - -/* Workaround build problem with Sun Studio 12 */ -#if defined(__SUNPRO_C) || defined(__SUNPRO_CC) -# undef MOZ_MUST_USE -# define MOZ_MUST_USE -# undef MOZ_ALLOCATOR -# define MOZ_ALLOCATOR -#endif - -#if defined(__cplusplus) -extern "C" { -#endif /* ifdef __cplusplus */ - -/* - * We need to use malloc_impl and free_impl in this file when they are - * defined, because of how mozglue.dll is linked on Windows, where using - * malloc/free would end up using the symbols from the MSVCRT instead of - * ours. - */ -#ifndef free_impl -#define free_impl free -#define free_impl_ -#endif -#ifndef malloc_impl -#define malloc_impl malloc -#define malloc_impl_ -#endif - -/* - * Each declaration below is analogous to a "standard" allocation - * function, except that the out-of-memory handling is made explicit. - * The |moz_x| versions will never return a NULL pointer; if memory - * is exhausted, they abort. The |moz_| versions may return NULL - * pointers if memory is exhausted: their return value must be checked. - * - * All these allocation functions are *guaranteed* to return a pointer - * to memory allocated in such a way that that memory can be freed by - * passing that pointer to |free()|. - */ - -MFBT_API void* moz_xmalloc(size_t size) - MOZ_ALLOCATOR; - -MFBT_API void* moz_xcalloc(size_t nmemb, size_t size) - MOZ_ALLOCATOR; - -MFBT_API void* moz_xrealloc(void* ptr, size_t size) - MOZ_ALLOCATOR; - -MFBT_API char* moz_xstrdup(const char* str) - MOZ_ALLOCATOR; - -MFBT_API size_t moz_malloc_usable_size(void *ptr); - -MFBT_API size_t moz_malloc_size_of(const void *ptr); - -#if defined(HAVE_STRNDUP) -MFBT_API char* moz_xstrndup(const char* str, size_t strsize) - MOZ_ALLOCATOR; -#endif /* if defined(HAVE_STRNDUP) */ - - -#if defined(HAVE_POSIX_MEMALIGN) -MFBT_API MOZ_MUST_USE -int moz_xposix_memalign(void **ptr, size_t alignment, size_t size); - -MFBT_API MOZ_MUST_USE -int moz_posix_memalign(void **ptr, size_t alignment, size_t size); -#endif /* if defined(HAVE_POSIX_MEMALIGN) */ - - -#if defined(HAVE_MEMALIGN) -MFBT_API void* moz_xmemalign(size_t boundary, size_t size) - MOZ_ALLOCATOR; -#endif /* if defined(HAVE_MEMALIGN) */ - - -#if defined(HAVE_VALLOC) -MFBT_API void* moz_xvalloc(size_t size) - MOZ_ALLOCATOR; -#endif /* if defined(HAVE_VALLOC) */ - - -#ifdef __cplusplus -} /* extern "C" */ -#endif /* ifdef __cplusplus */ - - -#ifdef __cplusplus - -/* - * We implement the default operators new/delete as part of - * libmozalloc, replacing their definitions in libstdc++. The - * operator new* definitions in libmozalloc will never return a NULL - * pointer. - * - * Each operator new immediately below returns a pointer to memory - * that can be delete'd by any of - * - * (1) the matching infallible operator delete immediately below - * (2) the matching "fallible" operator delete further below - * (3) the matching system |operator delete(void*, std::nothrow)| - * (4) the matching system |operator delete(void*) throw(std::bad_alloc)| - * - * NB: these are declared |throw(std::bad_alloc)|, though they will never - * throw that exception. This declaration is consistent with the rule - * that |::operator new() throw(std::bad_alloc)| will never return NULL. - */ - -/* NB: This is defined just to silence vacuous warnings about symbol - * visibility on OS X/gcc. These symbols are force-inline and not - * exported. */ -#if defined(XP_MACOSX) -# define MOZALLOC_EXPORT_NEW MFBT_API -#else -# define MOZALLOC_EXPORT_NEW -#endif - -#if defined(ANDROID) -/* - * It's important to always specify 'throw()' in GCC because it's used to tell - * GCC that 'new' may return null. That makes GCC null-check the result before - * potentially initializing the memory to zero. - * Also, the Android minimalistic headers don't include std::bad_alloc. - */ -#define MOZALLOC_THROW_IF_HAS_EXCEPTIONS throw() -#define MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS -#elif defined(_MSC_VER) -/* - * Suppress build warning spam (bug 578546). - */ -#define MOZALLOC_THROW_IF_HAS_EXCEPTIONS -#define MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS -#else -#define MOZALLOC_THROW_IF_HAS_EXCEPTIONS throw() -#define MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS throw(std::bad_alloc) -#endif - -#define MOZALLOC_THROW_BAD_ALLOC MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS - -MOZALLOC_EXPORT_NEW -#if defined(__GNUC__) && !defined(__clang__) && defined(__SANITIZE_ADDRESS__) -/* gcc's asan somehow doesn't like always_inline on this function. */ -__attribute__((gnu_inline)) inline -#else -MOZALLOC_INLINE -#endif -void* operator new(size_t size) MOZALLOC_THROW_BAD_ALLOC -{ - return moz_xmalloc(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void* operator new(size_t size, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void* operator new[](size_t size) MOZALLOC_THROW_BAD_ALLOC -{ - return moz_xmalloc(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void* operator new[](size_t size, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete(void* ptr) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete(void* ptr, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete[](void* ptr) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete[](void* ptr, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - - -/* - * We also add a new allocator variant: "fallible operator new." - * Unlike libmozalloc's implementations of the standard nofail - * allocators, this allocator is allowed to return NULL. It can be used - * as follows - * - * Foo* f = new (mozilla::fallible) Foo(...); - * - * operator delete(fallible) is defined for completeness only. - * - * Each operator new below returns a pointer to memory that can be - * delete'd by any of - * - * (1) the matching "fallible" operator delete below - * (2) the matching infallible operator delete above - * (3) the matching system |operator delete(void*, std::nothrow)| - * (4) the matching system |operator delete(void*) throw(std::bad_alloc)| - */ - -MOZALLOC_INLINE -void* operator new(size_t size, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_INLINE -void* operator new[](size_t size, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_INLINE -void operator delete(void* ptr, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - free_impl(ptr); -} - -MOZALLOC_INLINE -void operator delete[](void* ptr, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - free_impl(ptr); -} - - -/* - * This policy is identical to MallocAllocPolicy, except it uses - * moz_xmalloc/moz_xcalloc/moz_xrealloc instead of - * malloc/calloc/realloc. - */ -class InfallibleAllocPolicy -{ -public: - template - T* maybe_pod_malloc(size_t aNumElems) - { - return pod_malloc(aNumElems); - } - - template - T* maybe_pod_calloc(size_t aNumElems) - { - return pod_calloc(aNumElems); - } - - template - T* maybe_pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - return pod_realloc(aPtr, aOldSize, aNewSize); - } - - template - T* pod_malloc(size_t aNumElems) - { - if (aNumElems & mozilla::tl::MulOverflowMask::value) { - reportAllocOverflow(); - } - return static_cast(moz_xmalloc(aNumElems * sizeof(T))); - } - - template - T* pod_calloc(size_t aNumElems) - { - return static_cast(moz_xcalloc(aNumElems, sizeof(T))); - } - - template - T* pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - if (aNewSize & mozilla::tl::MulOverflowMask::value) { - reportAllocOverflow(); - } - return static_cast(moz_xrealloc(aPtr, aNewSize * sizeof(T))); - } - - void free_(void* aPtr) - { - free_impl(aPtr); - } - - void reportAllocOverflow() const - { - mozalloc_abort("alloc overflow"); - } - - bool checkSimulatedOOM() const - { - return true; - } -}; - -#endif /* ifdef __cplusplus */ - -#ifdef malloc_impl_ -#undef malloc_impl_ -#undef malloc_impl -#endif -#ifdef free_impl_ -#undef free_impl_ -#undef free_impl -#endif - -#endif /* ifndef mozilla_mozalloc_h */ diff --git a/ios/include/spidermonkey/mozilla/mozalloc_abort.h b/ios/include/spidermonkey/mozilla/mozalloc_abort.h deleted file mode 100644 index 065cebcb..00000000 --- a/ios/include/spidermonkey/mozilla/mozalloc_abort.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: sw=4 ts=4 et : - */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_mozalloc_abort_h -#define mozilla_mozalloc_abort_h - -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" - -/** - * Terminate this process in such a way that breakpad is triggered, if - * at all possible. - * - * Note: MOZ_NORETURN seems to break crash stacks on ARM, so we don't - * use that annotation there. - */ -MFBT_API -#if !defined(__arm__) - MOZ_NORETURN -#endif - void mozalloc_abort(const char* const msg); - - -#endif /* ifndef mozilla_mozalloc_abort_h */ diff --git a/ios/include/spidermonkey/mozilla/mozalloc_oom.h b/ios/include/spidermonkey/mozilla/mozalloc_oom.h deleted file mode 100644 index 35bb9acc..00000000 --- a/ios/include/spidermonkey/mozilla/mozalloc_oom.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: sw=4 ts=4 et : - */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_mozalloc_oom_h -#define mozilla_mozalloc_oom_h - -#include "mozalloc.h" - -/** - * Called when memory is critically low. Returns iff it was able to - * remedy the critical memory situation; if not, it will abort(). - */ -MFBT_API void mozalloc_handle_oom(size_t requestedSize); - -/** - * Called by embedders (specifically Mozilla breakpad) which wants to be - * notified of an intentional abort, to annotate any crash report with - * the size of the allocation on which we aborted. - */ -typedef void (*mozalloc_oom_abort_handler)(size_t size); -MFBT_API void mozalloc_set_oom_abort_handler(mozalloc_oom_abort_handler handler); - -/* TODO: functions to query system memory usage and register - * critical-memory handlers. */ - - -#endif /* ifndef mozilla_mozalloc_oom_h */ diff --git a/ios/include/spidermonkey/mozilla/utils.h b/ios/include/spidermonkey/mozilla/utils.h deleted file mode 100644 index 15dd4bfb..00000000 --- a/ios/include/spidermonkey/mozilla/utils.h +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright 2010 the V8 project authors. All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following -// disclaimer in the documentation and/or other materials provided -// with the distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef DOUBLE_CONVERSION_UTILS_H_ -#define DOUBLE_CONVERSION_UTILS_H_ - -#include -#include - -#include "mozilla/Assertions.h" -#ifndef ASSERT -#define ASSERT(condition) MOZ_ASSERT(condition) -#endif -#ifndef UNIMPLEMENTED -#define UNIMPLEMENTED() MOZ_CRASH() -#endif -#ifndef UNREACHABLE -#define UNREACHABLE() MOZ_CRASH() -#endif - -// Double operations detection based on target architecture. -// Linux uses a 80bit wide floating point stack on x86. This induces double -// rounding, which in turn leads to wrong results. -// An easy way to test if the floating-point operations are correct is to -// evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then -// the result is equal to 89255e-22. -// The best way to test this, is to create a division-function and to compare -// the output of the division with the expected result. (Inlining must be -// disabled.) -// On Linux,x86 89255e-22 != Div_double(89255.0/1e22) -#if defined(_M_X64) || defined(__x86_64__) || \ - defined(__ARMEL__) || defined(__avr32__) || \ - defined(__hppa__) || defined(__ia64__) || \ - defined(__mips__) || \ - defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \ - defined(__sparc__) || defined(__sparc) || defined(__s390__) || \ - defined(__SH4__) || defined(__alpha__) || \ - defined(_MIPS_ARCH_MIPS32R2) || \ - defined(__AARCH64EL__) || defined(__aarch64__) -#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 -#elif defined(_M_IX86) || defined(__i386__) || defined(__i386) -#if defined(_WIN32) -// Windows uses a 64bit wide floating point stack. -#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 -#else -#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS -#endif // _WIN32 -#else -#error Target architecture was not detected as supported by Double-Conversion. -#endif - - -#include - -// The following macro works on both 32 and 64-bit platforms. -// Usage: instead of writing 0x1234567890123456 -// write UINT64_2PART_C(0x12345678,90123456); -#define UINT64_2PART_C(a, b) (((static_cast(a) << 32) + 0x##b##u)) - - -// The expression ARRAY_SIZE(a) is a compile-time constant of type -// size_t which represents the number of elements of the given -// array. You should only use ARRAY_SIZE on statically allocated -// arrays. -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(a) \ - ((sizeof(a) / sizeof(*(a))) / \ - static_cast(!(sizeof(a) % sizeof(*(a))))) -#endif - -// A macro to disallow the evil copy constructor and operator= functions -// This should be used in the private: declarations for a class -#ifndef DISALLOW_COPY_AND_ASSIGN -#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&); \ - void operator=(const TypeName&) -#endif - -// A macro to disallow all the implicit constructors, namely the -// default constructor, copy constructor and operator= functions. -// -// This should be used in the private: declarations for a class -// that wants to prevent anyone from instantiating it. This is -// especially useful for classes containing only static methods. -#ifndef DISALLOW_IMPLICIT_CONSTRUCTORS -#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ - TypeName(); \ - DISALLOW_COPY_AND_ASSIGN(TypeName) -#endif - -namespace double_conversion { - -static const int kCharSize = sizeof(char); - -// Returns the maximum of the two parameters. -template -static T Max(T a, T b) { - return a < b ? b : a; -} - - -// Returns the minimum of the two parameters. -template -static T Min(T a, T b) { - return a < b ? a : b; -} - - -inline int StrLength(const char* string) { - size_t length = strlen(string); - ASSERT(length == static_cast(static_cast(length))); - return static_cast(length); -} - -// This is a simplified version of V8's Vector class. -template -class Vector { - public: - Vector() : start_(NULL), length_(0) {} - Vector(T* data, int len) : start_(data), length_(len) { - ASSERT(len == 0 || (len > 0 && data != NULL)); - } - - // Returns a vector using the same backing storage as this one, - // spanning from and including 'from', to but not including 'to'. - Vector SubVector(int from, int to) { - ASSERT(to <= length_); - ASSERT(from < to); - ASSERT(0 <= from); - return Vector(start() + from, to - from); - } - - // Returns the length of the vector. - int length() const { return length_; } - - // Returns whether or not the vector is empty. - bool is_empty() const { return length_ == 0; } - - // Returns the pointer to the start of the data in the vector. - T* start() const { return start_; } - - // Access individual vector elements - checks bounds in debug mode. - T& operator[](int index) const { - ASSERT(0 <= index && index < length_); - return start_[index]; - } - - T& first() { return start_[0]; } - - T& last() { return start_[length_ - 1]; } - - private: - T* start_; - int length_; -}; - - -// Helper class for building result strings in a character buffer. The -// purpose of the class is to use safe operations that checks the -// buffer bounds on all operations in debug mode. -class StringBuilder { - public: - StringBuilder(char* buffer, int buffer_size) - : buffer_(buffer, buffer_size), position_(0) { } - - ~StringBuilder() { if (!is_finalized()) Finalize(); } - - int size() const { return buffer_.length(); } - - // Get the current position in the builder. - int position() const { - ASSERT(!is_finalized()); - return position_; - } - - // Reset the position. - void Reset() { position_ = 0; } - - // Add a single character to the builder. It is not allowed to add - // 0-characters; use the Finalize() method to terminate the string - // instead. - void AddCharacter(char c) { - ASSERT(c != '\0'); - ASSERT(!is_finalized() && position_ < buffer_.length()); - buffer_[position_++] = c; - } - - // Add an entire string to the builder. Uses strlen() internally to - // compute the length of the input string. - void AddString(const char* s) { - AddSubstring(s, StrLength(s)); - } - - // Add the first 'n' characters of the given string 's' to the - // builder. The input string must have enough characters. - void AddSubstring(const char* s, int n) { - ASSERT(!is_finalized() && position_ + n < buffer_.length()); - ASSERT(static_cast(n) <= strlen(s)); - memmove(&buffer_[position_], s, n * kCharSize); - position_ += n; - } - - - // Add character padding to the builder. If count is non-positive, - // nothing is added to the builder. - void AddPadding(char c, int count) { - for (int i = 0; i < count; i++) { - AddCharacter(c); - } - } - - // Finalize the string by 0-terminating it and returning the buffer. - char* Finalize() { - ASSERT(!is_finalized() && position_ < buffer_.length()); - buffer_[position_] = '\0'; - // Make sure nobody managed to add a 0-character to the - // buffer while building the string. - ASSERT(strlen(buffer_.start()) == static_cast(position_)); - position_ = -1; - ASSERT(is_finalized()); - return buffer_.start(); - } - - private: - Vector buffer_; - int position_; - - bool is_finalized() const { return position_ < 0; } - - DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder); -}; - -// The type-based aliasing rule allows the compiler to assume that pointers of -// different types (for some definition of different) never alias each other. -// Thus the following code does not work: -// -// float f = foo(); -// int fbits = *(int*)(&f); -// -// The compiler 'knows' that the int pointer can't refer to f since the types -// don't match, so the compiler may cache f in a register, leaving random data -// in fbits. Using C++ style casts makes no difference, however a pointer to -// char data is assumed to alias any other pointer. This is the 'memcpy -// exception'. -// -// Bit_cast uses the memcpy exception to move the bits from a variable of one -// type of a variable of another type. Of course the end result is likely to -// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005) -// will completely optimize BitCast away. -// -// There is an additional use for BitCast. -// Recent gccs will warn when they see casts that may result in breakage due to -// the type-based aliasing rule. If you have checked that there is no breakage -// you can use BitCast to cast one pointer type to another. This confuses gcc -// enough that it can no longer see that you have cast one pointer type to -// another thus avoiding the warning. -template -inline Dest BitCast(const Source& source) { - static_assert(sizeof(Dest) == sizeof(Source), - "BitCast's source and destination types must be the same size"); - - Dest dest; - memmove(&dest, &source, sizeof(dest)); - return dest; -} - -template -inline Dest BitCast(Source* source) { - return BitCast(reinterpret_cast(source)); -} - -} // namespace double_conversion - -#endif // DOUBLE_CONVERSION_UTILS_H_ diff --git a/ios/include/spidermonkey/mozmemory.h b/ios/include/spidermonkey/mozmemory.h deleted file mode 100644 index 84007fff..00000000 --- a/ios/include/spidermonkey/mozmemory.h +++ /dev/null @@ -1,91 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozmemory_h -#define mozmemory_h - -/* - * This header is meant to be used when the following functions are - * necessary: - * - malloc_good_size (used to be called je_malloc_usable_in_advance) - * - jemalloc_stats - * - jemalloc_purge_freed_pages - * - jemalloc_free_dirty_pages - */ - -#ifndef MOZ_MEMORY -# error Should not include mozmemory.h when MOZ_MEMORY is not set -#endif - -#include "mozmemory_wrap.h" -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" -#include "jemalloc_types.h" - -MOZ_BEGIN_EXTERN_C - -/* - * On OSX, malloc/malloc.h contains the declaration for malloc_good_size, - * which will call back in jemalloc, through the zone allocator so just use it. - */ -#ifdef XP_DARWIN -# include -#else -MOZ_MEMORY_API size_t malloc_good_size_impl(size_t size); - -/* Note: the MOZ_GLUE_IN_PROGRAM ifdef below is there to avoid -Werror turning - * the protective if into errors. MOZ_GLUE_IN_PROGRAM is what triggers MFBT_API - * to use weak imports. */ - -static inline size_t _malloc_good_size(size_t size) { -# if defined(MOZ_GLUE_IN_PROGRAM) && !defined(IMPL_MFBT) - if (!malloc_good_size) - return size; -# endif - return malloc_good_size_impl(size); -} - -# define malloc_good_size _malloc_good_size -#endif - -MOZ_JEMALLOC_API void jemalloc_stats(jemalloc_stats_t *stats); - -/* - * On some operating systems (Mac), we use madvise(MADV_FREE) to hand pages - * back to the operating system. On Mac, the operating system doesn't take - * this memory back immediately; instead, the OS takes it back only when the - * machine is running out of physical memory. - * - * This is great from the standpoint of efficiency, but it makes measuring our - * actual RSS difficult, because pages which we've MADV_FREE'd shouldn't count - * against our RSS. - * - * This function explicitly purges any MADV_FREE'd pages from physical memory, - * causing our reported RSS match the amount of memory we're actually using. - * - * Note that this call is expensive in two ways. First, it may be slow to - * execute, because it may make a number of slow syscalls to free memory. This - * function holds the big jemalloc locks, so basically all threads are blocked - * while this function runs. - * - * This function is also expensive in that the next time we go to access a page - * which we've just explicitly decommitted, the operating system has to attach - * to it a physical page! If we hadn't run this function, the OS would have - * less work to do. - * - * If MALLOC_DOUBLE_PURGE is not defined, this function does nothing. - */ -MOZ_JEMALLOC_API void jemalloc_purge_freed_pages(); - -/* - * Free all unused dirty pages in all arenas. Calling this function will slow - * down subsequent allocations so it is recommended to use it only when - * memory needs to be reclaimed at all costs (see bug 805855). This function - * provides functionality similar to mallctl("arenas.purge") in jemalloc 3. - */ -MOZ_JEMALLOC_API void jemalloc_free_dirty_pages(); - -MOZ_END_EXTERN_C - -#endif /* mozmemory_h */ diff --git a/ios/include/spidermonkey/mozmemory_wrap.h b/ios/include/spidermonkey/mozmemory_wrap.h deleted file mode 100644 index 066d5778..00000000 --- a/ios/include/spidermonkey/mozmemory_wrap.h +++ /dev/null @@ -1,219 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozmemory_wrap_h -#define mozmemory_wrap_h - -/* - * This header contains #defines which tweak the names of various memory - * allocation functions. - * - * There are several types of functions related to memory allocation - * that are meant to be used publicly by the Gecko codebase: - * - * - malloc implementation functions: - * - malloc - * - posix_memalign - * - aligned_alloc - * - calloc - * - realloc - * - free - * - memalign - * - valloc - * - malloc_usable_size - * - malloc_good_size - * Some of these functions are specific to some systems, but for - * convenience, they are treated as being cross-platform, and available - * as such. - * - * - duplication functions: - * - strndup - * - strdup - * - wcsdup (Windows only) - * - * - jemalloc specific functions: - * - jemalloc_stats - * - jemalloc_purge_freed_pages - * - jemalloc_free_dirty_pages - * (these functions are native to mozjemalloc, and have compatibility - * implementations for jemalloc3) - * - * These functions are all exported as part of libmozglue (see - * $(topsrcdir)/mozglue/build/Makefile.in), with a few implementation - * peculiarities: - * - * - On Windows, the malloc implementation functions are all prefixed with - * "je_", the duplication functions are prefixed with "wrap_", and jemalloc - * specific functions are left unprefixed. All these functions are however - * aliased when exporting them, such that the resulting mozglue.dll exports - * them unprefixed (see $(topsrcdir)/mozglue/build/mozglue.def.in). The - * prefixed malloc implementation and duplication functions are not - * exported. - * - * - On MacOSX, the system libc has a zone allocator, which allows us to - * hook custom malloc implementation functions without exporting them. - * The malloc implementation functions are all prefixed with "je_" and used - * this way from the custom zone allocator. They are not exported. - * Duplication functions are not included, since they will call the custom - * zone allocator anyways. Jemalloc-specific functions are also left - * unprefixed. - * - * - On Android and Gonk, all functions are left unprefixed. Additionally, - * C++ allocation functions (operator new/delete) are also exported and - * unprefixed. - * - * - On other systems (mostly Linux), all functions are left unprefixed. - * - * Only Android and Gonk add C++ allocation functions. - * - * Proper exporting of the various functions is done with the MOZ_MEMORY_API - * and MOZ_JEMALLOC_API macros. MOZ_MEMORY_API is meant to be used for malloc - * implementation and duplication functions, while MOZ_JEMALLOC_API is - * dedicated to jemalloc specific functions. - * - * - * All these functions are meant to be called with no prefix from Gecko code. - * In most cases, this is because that's how they are available at runtime. - * However, on Android, this relies on faulty.lib (the custom dynamic linker) - * resolving mozglue symbols before libc symbols, which is guaranteed by the - * way faulty.lib works (it respects the DT_NEEDED order, and libc always - * appears after mozglue ; which we double check when building anyways) - * - * - * Within libmozglue (when MOZ_MEMORY_IMPL is defined), all the functions - * should be suffixed with "_impl" both for declarations and use. - * That is, the implementation declaration for e.g. strdup would look like: - * char* strdup_impl(const char *) - * That implementation would call malloc by using "malloc_impl". - * - * While mozjemalloc uses these "_impl" suffixed helpers, jemalloc3, being - * third-party code, doesn't, but instead has an elaborate way to mangle - * individual functions. See under "Run jemalloc configure script" in - * $(topsrcdir)/configure.in. - * - * - * When building with replace-malloc support, the above still holds, but - * the malloc implementation and jemalloc specific functions are the - * replace-malloc functions from replace_malloc.c. - * - * The actual jemalloc/mozjemalloc implementation is prefixed with "je_". - * - * Thus, when MOZ_REPLACE_MALLOC is defined, the "_impl" suffixed macros - * expand to "je_" prefixed function when building mozjemalloc or - * jemalloc3/mozjemalloc_compat, where MOZ_JEMALLOC_IMPL is defined. - * - * In other cases, the "_impl" suffixed macros follow the original scheme, - * except on Windows and MacOSX, where they would expand to "je_" prefixed - * functions. Instead, they are left unmodified (malloc_impl expands to - * malloc_impl). - */ - -#ifndef MOZ_MEMORY -# error Should only include mozmemory_wrap.h when MOZ_MEMORY is set. -#endif - -#if defined(MOZ_JEMALLOC_IMPL) && !defined(MOZ_MEMORY_IMPL) -# define MOZ_MEMORY_IMPL -#endif -#if defined(MOZ_MEMORY_IMPL) && !defined(IMPL_MFBT) -# ifdef MFBT_API /* mozilla/Types.h was already included */ -# error mozmemory_wrap.h has to be included before mozilla/Types.h when MOZ_MEMORY_IMPL is set and IMPL_MFBT is not. -# endif -# define IMPL_MFBT -#endif - -#include "mozilla/Types.h" - -#if !defined(MOZ_SYSTEM_JEMALLOC) -# ifdef MOZ_MEMORY_IMPL -# if defined(MOZ_JEMALLOC_IMPL) && defined(MOZ_REPLACE_MALLOC) && !defined(MOZ_REPLACE_JEMALLOC) -# define mozmem_malloc_impl(a) je_ ## a -# define mozmem_jemalloc_impl(a) je_ ## a -# else -# define MOZ_JEMALLOC_API MFBT_API -# ifdef MOZ_REPLACE_JEMALLOC -# define MOZ_MEMORY_API MFBT_API -# define mozmem_malloc_impl(a) replace_ ## a -# define mozmem_jemalloc_impl(a) replace_ ## a -# elif (defined(XP_WIN) || defined(XP_DARWIN)) -# if defined(MOZ_REPLACE_MALLOC) -# define mozmem_malloc_impl(a) a ## _impl -# else -# define mozmem_malloc_impl(a) je_ ## a -# endif -# else -# define MOZ_MEMORY_API MFBT_API -# if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK) -# define MOZ_WRAP_NEW_DELETE -# endif -# endif -# endif -# ifdef XP_WIN -# define mozmem_dup_impl(a) wrap_ ## a -# endif -# endif - -/* All other jemalloc3 functions are prefixed with "je_", except when - * building against an unprefixed system jemalloc library */ -# define je_(a) je_ ## a -#else /* defined(MOZ_SYSTEM_JEMALLOC) */ -# define je_(a) a -#endif - -#if !defined(MOZ_MEMORY_IMPL) || defined(MOZ_SYSTEM_JEMALLOC) -# define MOZ_MEMORY_API MFBT_API -# define MOZ_JEMALLOC_API MFBT_API -#endif - -#ifndef MOZ_MEMORY_API -# define MOZ_MEMORY_API -#endif -#ifndef MOZ_JEMALLOC_API -# define MOZ_JEMALLOC_API -#endif - -#ifndef mozmem_malloc_impl -# define mozmem_malloc_impl(a) a -#endif -#ifndef mozmem_dup_impl -# define mozmem_dup_impl(a) a -#endif -#ifndef mozmem_jemalloc_impl -# define mozmem_jemalloc_impl(a) a -#endif - -/* Malloc implementation functions */ -#define malloc_impl mozmem_malloc_impl(malloc) -#define posix_memalign_impl mozmem_malloc_impl(posix_memalign) -#define aligned_alloc_impl mozmem_malloc_impl(aligned_alloc) -#define calloc_impl mozmem_malloc_impl(calloc) -#define realloc_impl mozmem_malloc_impl(realloc) -#define free_impl mozmem_malloc_impl(free) -#define memalign_impl mozmem_malloc_impl(memalign) -#define valloc_impl mozmem_malloc_impl(valloc) -#define malloc_usable_size_impl mozmem_malloc_impl(malloc_usable_size) -#define malloc_good_size_impl mozmem_malloc_impl(malloc_good_size) - -/* Duplication functions */ -#define strndup_impl mozmem_dup_impl(strndup) -#define strdup_impl mozmem_dup_impl(strdup) -#ifdef XP_WIN -# define wcsdup_impl mozmem_dup_impl(wcsdup) -#endif - -/* String functions */ -#ifdef ANDROID -/* Bug 801571 and Bug 879668, libstagefright uses vasprintf, causing malloc()/ - * free() to be mismatched between bionic and mozglue implementation. - */ -#define vasprintf_impl mozmem_dup_impl(vasprintf) -#define asprintf_impl mozmem_dup_impl(asprintf) -#endif - -/* Jemalloc specific function */ -#define jemalloc_stats_impl mozmem_jemalloc_impl(jemalloc_stats) -#define jemalloc_purge_freed_pages_impl mozmem_jemalloc_impl(jemalloc_purge_freed_pages) -#define jemalloc_free_dirty_pages_impl mozmem_jemalloc_impl(jemalloc_free_dirty_pages) - -#endif /* mozmemory_wrap_h */ diff --git a/ios/libs/libjs_static.a b/ios/libs/libjs_static.a deleted file mode 100644 index ad4eca10..00000000 Binary files a/ios/libs/libjs_static.a and /dev/null differ diff --git a/ios/libs/libmozglue.a b/ios/libs/libmozglue.a deleted file mode 100644 index 68a4fa13..00000000 Binary files a/ios/libs/libmozglue.a and /dev/null differ diff --git a/mac/CMakeLists.txt b/mac/CMakeLists.txt index d2e4a706..aa8329b8 100644 --- a/mac/CMakeLists.txt +++ b/mac/CMakeLists.txt @@ -84,6 +84,16 @@ set_target_properties(mozglue PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_LIST_DIR}/libs/libmozglue.a ) +add_library(EGL SHARED IMPORTED GLOBAL) +set_target_properties(EGL PROPERTIES + IMPORTED_LOCATION ${CMAKE_CURRENT_LIST_DIR}/libs/libEGL.dylib +) + +add_library(GLESv2 SHARED IMPORTED GLOBAL) +set_target_properties(GLESv2 PROPERTIES + IMPORTED_LOCATION ${CMAKE_CURRENT_LIST_DIR}/libs/libGLESv2.dylib +) + set(se_libs_name) if(USE_SE_V8) @@ -123,7 +133,8 @@ endif() list(APPEND CC_EXTERNAL_LIBS freetype - glfw3 + EGL + GLESv2 jpeg png webp diff --git a/mac/include/glfw3/glfw3.h b/mac/include/glfw3/glfw3.h deleted file mode 100644 index 5a0c4508..00000000 --- a/mac/include/glfw3/glfw3.h +++ /dev/null @@ -1,4235 +0,0 @@ -/************************************************************************* - * GLFW 3.2 - www.glfw.org - * A library for OpenGL, window and input - *------------------------------------------------------------------------ - * Copyright (c) 2002-2006 Marcus Geelnard - * Copyright (c) 2006-2016 Camilla Berglund - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would - * be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and must not - * be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - *************************************************************************/ - -#ifndef _glfw3_h_ -#define _glfw3_h_ - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************************************************* - * Doxygen documentation - *************************************************************************/ - -/*! @file glfw3.h - * @brief The header of the GLFW 3 API. - * - * This is the header file of the GLFW 3 API. It defines all its types and - * declares all its functions. - * - * For more information about how to use this file, see @ref build_include. - */ -/*! @defgroup context Context reference - * - * This is the reference documentation for OpenGL and OpenGL ES context related - * functions. For more task-oriented information, see the @ref context_guide. - */ -/*! @defgroup vulkan Vulkan reference - * - * This is the reference documentation for Vulkan related functions and types. - * For more task-oriented information, see the @ref vulkan_guide. - */ -/*! @defgroup init Initialization, version and error reference - * - * This is the reference documentation for initialization and termination of - * the library, version management and error handling. For more task-oriented - * information, see the @ref intro_guide. - */ -/*! @defgroup input Input reference - * - * This is the reference documentation for input related functions and types. - * For more task-oriented information, see the @ref input_guide. - */ -/*! @defgroup monitor Monitor reference - * - * This is the reference documentation for monitor related functions and types. - * For more task-oriented information, see the @ref monitor_guide. - */ -/*! @defgroup window Window reference - * - * This is the reference documentation for window related functions and types, - * including creation, deletion and event polling. For more task-oriented - * information, see the @ref window_guide. - */ - - -/************************************************************************* - * Compiler- and platform-specific preprocessor work - *************************************************************************/ - -/* If we are we on Windows, we want a single define for it. - */ -#if !defined(_WIN32) && (defined(__WIN32__) || defined(WIN32) || defined(__MINGW32__)) - #define _WIN32 -#endif /* _WIN32 */ - -/* It is customary to use APIENTRY for OpenGL function pointer declarations on - * all platforms. Additionally, the Windows OpenGL header needs APIENTRY. - */ -#ifndef APIENTRY - #ifdef _WIN32 - #define APIENTRY __stdcall - #else - #define APIENTRY - #endif -#endif /* APIENTRY */ - -/* Some Windows OpenGL headers need this. - */ -#if !defined(WINGDIAPI) && defined(_WIN32) - #define WINGDIAPI __declspec(dllimport) - #define GLFW_WINGDIAPI_DEFINED -#endif /* WINGDIAPI */ - -/* Some Windows GLU headers need this. - */ -#if !defined(CALLBACK) && defined(_WIN32) - #define CALLBACK __stdcall - #define GLFW_CALLBACK_DEFINED -#endif /* CALLBACK */ - -/* Most Windows GLU headers need wchar_t. - * The OS X OpenGL header blocks the definition of ptrdiff_t by glext.h. - * Include it unconditionally to avoid surprising side-effects. - */ -#include -#include - -/* Include the chosen client API headers. - */ -#if defined(__APPLE__) - #if defined(GLFW_INCLUDE_GLCOREARB) - #include - #if defined(GLFW_INCLUDE_GLEXT) - #include - #endif - #elif !defined(GLFW_INCLUDE_NONE) - #if !defined(GLFW_INCLUDE_GLEXT) - #define GL_GLEXT_LEGACY - #endif - #include - #endif - #if defined(GLFW_INCLUDE_GLU) - #include - #endif -#else - #if defined(GLFW_INCLUDE_GLCOREARB) - #include - #elif defined(GLFW_INCLUDE_ES1) - #include - #if defined(GLFW_INCLUDE_GLEXT) - #include - #endif - #elif defined(GLFW_INCLUDE_ES2) - #include - #if defined(GLFW_INCLUDE_GLEXT) - #include - #endif - #elif defined(GLFW_INCLUDE_ES3) - #include - #if defined(GLFW_INCLUDE_GLEXT) - #include - #endif - #elif defined(GLFW_INCLUDE_ES31) - #include - #if defined(GLFW_INCLUDE_GLEXT) - #include - #endif - #elif defined(GLFW_INCLUDE_VULKAN) - #include - #elif !defined(GLFW_INCLUDE_NONE) - #include - #if defined(GLFW_INCLUDE_GLEXT) - #include - #endif - #endif - #if defined(GLFW_INCLUDE_GLU) - #include - #endif -#endif - -#if defined(GLFW_DLL) && defined(_GLFW_BUILD_DLL) - /* GLFW_DLL must be defined by applications that are linking against the DLL - * version of the GLFW library. _GLFW_BUILD_DLL is defined by the GLFW - * configuration header when compiling the DLL version of the library. - */ - #error "You must not have both GLFW_DLL and _GLFW_BUILD_DLL defined" -#endif - -/* GLFWAPI is used to declare public API functions for export - * from the DLL / shared library / dynamic library. - */ -#if defined(_WIN32) && defined(_GLFW_BUILD_DLL) - /* We are building GLFW as a Win32 DLL */ - #define GLFWAPI __declspec(dllexport) -#elif defined(_WIN32) && defined(GLFW_DLL) - /* We are calling GLFW as a Win32 DLL */ - #define GLFWAPI __declspec(dllimport) -#elif defined(__GNUC__) && defined(_GLFW_BUILD_DLL) - /* We are building GLFW as a shared / dynamic library */ - #define GLFWAPI __attribute__((visibility("default"))) -#else - /* We are building or calling GLFW as a static library */ - #define GLFWAPI -#endif - - -/************************************************************************* - * GLFW API tokens - *************************************************************************/ - -/*! @name GLFW version macros - * @{ */ -/*! @brief The major version number of the GLFW library. - * - * This is incremented when the API is changed in non-compatible ways. - * @ingroup init - */ -#define GLFW_VERSION_MAJOR 3 -/*! @brief The minor version number of the GLFW library. - * - * This is incremented when features are added to the API but it remains - * backward-compatible. - * @ingroup init - */ -#define GLFW_VERSION_MINOR 2 -/*! @brief The revision number of the GLFW library. - * - * This is incremented when a bug fix release is made that does not contain any - * API changes. - * @ingroup init - */ -#define GLFW_VERSION_REVISION 0 -/*! @} */ - -/*! @name Boolean values - * @{ */ -/*! @brief One. - * - * One. Seriously. You don't _need_ to use this symbol in your code. It's - * just semantic sugar for the number 1. You can use `1` or `true` or `_True` - * or `GL_TRUE` or whatever you want. - */ -#define GLFW_TRUE 1 -/*! @brief Zero. - * - * Zero. Seriously. You don't _need_ to use this symbol in your code. It's - * just just semantic sugar for the number 0. You can use `0` or `false` or - * `_False` or `GL_FALSE` or whatever you want. - */ -#define GLFW_FALSE 0 -/*! @} */ - -/*! @name Key and button actions - * @{ */ -/*! @brief The key or mouse button was released. - * - * The key or mouse button was released. - * - * @ingroup input - */ -#define GLFW_RELEASE 0 -/*! @brief The key or mouse button was pressed. - * - * The key or mouse button was pressed. - * - * @ingroup input - */ -#define GLFW_PRESS 1 -/*! @brief The key was held down until it repeated. - * - * The key was held down until it repeated. - * - * @ingroup input - */ -#define GLFW_REPEAT 2 -/*! @} */ - -/*! @defgroup keys Keyboard keys - * - * See [key input](@ref input_key) for how these are used. - * - * These key codes are inspired by the _USB HID Usage Tables v1.12_ (p. 53-60), - * but re-arranged to map to 7-bit ASCII for printable keys (function keys are - * put in the 256+ range). - * - * The naming of the key codes follow these rules: - * - The US keyboard layout is used - * - Names of printable alpha-numeric characters are used (e.g. "A", "R", - * "3", etc.) - * - For non-alphanumeric characters, Unicode:ish names are used (e.g. - * "COMMA", "LEFT_SQUARE_BRACKET", etc.). Note that some names do not - * correspond to the Unicode standard (usually for brevity) - * - Keys that lack a clear US mapping are named "WORLD_x" - * - For non-printable keys, custom names are used (e.g. "F4", - * "BACKSPACE", etc.) - * - * @ingroup input - * @{ - */ - -/* The unknown key */ -#define GLFW_KEY_UNKNOWN -1 - -/* Printable keys */ -#define GLFW_KEY_SPACE 32 -#define GLFW_KEY_APOSTROPHE 39 /* ' */ -#define GLFW_KEY_COMMA 44 /* , */ -#define GLFW_KEY_MINUS 45 /* - */ -#define GLFW_KEY_PERIOD 46 /* . */ -#define GLFW_KEY_SLASH 47 /* / */ -#define GLFW_KEY_0 48 -#define GLFW_KEY_1 49 -#define GLFW_KEY_2 50 -#define GLFW_KEY_3 51 -#define GLFW_KEY_4 52 -#define GLFW_KEY_5 53 -#define GLFW_KEY_6 54 -#define GLFW_KEY_7 55 -#define GLFW_KEY_8 56 -#define GLFW_KEY_9 57 -#define GLFW_KEY_SEMICOLON 59 /* ; */ -#define GLFW_KEY_EQUAL 61 /* = */ -#define GLFW_KEY_A 65 -#define GLFW_KEY_B 66 -#define GLFW_KEY_C 67 -#define GLFW_KEY_D 68 -#define GLFW_KEY_E 69 -#define GLFW_KEY_F 70 -#define GLFW_KEY_G 71 -#define GLFW_KEY_H 72 -#define GLFW_KEY_I 73 -#define GLFW_KEY_J 74 -#define GLFW_KEY_K 75 -#define GLFW_KEY_L 76 -#define GLFW_KEY_M 77 -#define GLFW_KEY_N 78 -#define GLFW_KEY_O 79 -#define GLFW_KEY_P 80 -#define GLFW_KEY_Q 81 -#define GLFW_KEY_R 82 -#define GLFW_KEY_S 83 -#define GLFW_KEY_T 84 -#define GLFW_KEY_U 85 -#define GLFW_KEY_V 86 -#define GLFW_KEY_W 87 -#define GLFW_KEY_X 88 -#define GLFW_KEY_Y 89 -#define GLFW_KEY_Z 90 -#define GLFW_KEY_LEFT_BRACKET 91 /* [ */ -#define GLFW_KEY_BACKSLASH 92 /* \ */ -#define GLFW_KEY_RIGHT_BRACKET 93 /* ] */ -#define GLFW_KEY_GRAVE_ACCENT 96 /* ` */ -#define GLFW_KEY_WORLD_1 161 /* non-US #1 */ -#define GLFW_KEY_WORLD_2 162 /* non-US #2 */ - -/* Function keys */ -#define GLFW_KEY_ESCAPE 256 -#define GLFW_KEY_ENTER 257 -#define GLFW_KEY_TAB 258 -#define GLFW_KEY_BACKSPACE 259 -#define GLFW_KEY_INSERT 260 -#define GLFW_KEY_DELETE 261 -#define GLFW_KEY_RIGHT 262 -#define GLFW_KEY_LEFT 263 -#define GLFW_KEY_DOWN 264 -#define GLFW_KEY_UP 265 -#define GLFW_KEY_PAGE_UP 266 -#define GLFW_KEY_PAGE_DOWN 267 -#define GLFW_KEY_HOME 268 -#define GLFW_KEY_END 269 -#define GLFW_KEY_CAPS_LOCK 280 -#define GLFW_KEY_SCROLL_LOCK 281 -#define GLFW_KEY_NUM_LOCK 282 -#define GLFW_KEY_PRINT_SCREEN 283 -#define GLFW_KEY_PAUSE 284 -#define GLFW_KEY_F1 290 -#define GLFW_KEY_F2 291 -#define GLFW_KEY_F3 292 -#define GLFW_KEY_F4 293 -#define GLFW_KEY_F5 294 -#define GLFW_KEY_F6 295 -#define GLFW_KEY_F7 296 -#define GLFW_KEY_F8 297 -#define GLFW_KEY_F9 298 -#define GLFW_KEY_F10 299 -#define GLFW_KEY_F11 300 -#define GLFW_KEY_F12 301 -#define GLFW_KEY_F13 302 -#define GLFW_KEY_F14 303 -#define GLFW_KEY_F15 304 -#define GLFW_KEY_F16 305 -#define GLFW_KEY_F17 306 -#define GLFW_KEY_F18 307 -#define GLFW_KEY_F19 308 -#define GLFW_KEY_F20 309 -#define GLFW_KEY_F21 310 -#define GLFW_KEY_F22 311 -#define GLFW_KEY_F23 312 -#define GLFW_KEY_F24 313 -#define GLFW_KEY_F25 314 -#define GLFW_KEY_KP_0 320 -#define GLFW_KEY_KP_1 321 -#define GLFW_KEY_KP_2 322 -#define GLFW_KEY_KP_3 323 -#define GLFW_KEY_KP_4 324 -#define GLFW_KEY_KP_5 325 -#define GLFW_KEY_KP_6 326 -#define GLFW_KEY_KP_7 327 -#define GLFW_KEY_KP_8 328 -#define GLFW_KEY_KP_9 329 -#define GLFW_KEY_KP_DECIMAL 330 -#define GLFW_KEY_KP_DIVIDE 331 -#define GLFW_KEY_KP_MULTIPLY 332 -#define GLFW_KEY_KP_SUBTRACT 333 -#define GLFW_KEY_KP_ADD 334 -#define GLFW_KEY_KP_ENTER 335 -#define GLFW_KEY_KP_EQUAL 336 -#define GLFW_KEY_LEFT_SHIFT 340 -#define GLFW_KEY_LEFT_CONTROL 341 -#define GLFW_KEY_LEFT_ALT 342 -#define GLFW_KEY_LEFT_SUPER 343 -#define GLFW_KEY_RIGHT_SHIFT 344 -#define GLFW_KEY_RIGHT_CONTROL 345 -#define GLFW_KEY_RIGHT_ALT 346 -#define GLFW_KEY_RIGHT_SUPER 347 -#define GLFW_KEY_MENU 348 - -#define GLFW_KEY_LAST GLFW_KEY_MENU - -/*! @} */ - -/*! @defgroup mods Modifier key flags - * - * See [key input](@ref input_key) for how these are used. - * - * @ingroup input - * @{ */ - -/*! @brief If this bit is set one or more Shift keys were held down. - */ -#define GLFW_MOD_SHIFT 0x0001 -/*! @brief If this bit is set one or more Control keys were held down. - */ -#define GLFW_MOD_CONTROL 0x0002 -/*! @brief If this bit is set one or more Alt keys were held down. - */ -#define GLFW_MOD_ALT 0x0004 -/*! @brief If this bit is set one or more Super keys were held down. - */ -#define GLFW_MOD_SUPER 0x0008 - -/*! @} */ - -/*! @defgroup buttons Mouse buttons - * - * See [mouse button input](@ref input_mouse_button) for how these are used. - * - * @ingroup input - * @{ */ -#define GLFW_MOUSE_BUTTON_1 0 -#define GLFW_MOUSE_BUTTON_2 1 -#define GLFW_MOUSE_BUTTON_3 2 -#define GLFW_MOUSE_BUTTON_4 3 -#define GLFW_MOUSE_BUTTON_5 4 -#define GLFW_MOUSE_BUTTON_6 5 -#define GLFW_MOUSE_BUTTON_7 6 -#define GLFW_MOUSE_BUTTON_8 7 -#define GLFW_MOUSE_BUTTON_LAST GLFW_MOUSE_BUTTON_8 -#define GLFW_MOUSE_BUTTON_LEFT GLFW_MOUSE_BUTTON_1 -#define GLFW_MOUSE_BUTTON_RIGHT GLFW_MOUSE_BUTTON_2 -#define GLFW_MOUSE_BUTTON_MIDDLE GLFW_MOUSE_BUTTON_3 -/*! @} */ - -/*! @defgroup joysticks Joysticks - * - * See [joystick input](@ref joystick) for how these are used. - * - * @ingroup input - * @{ */ -#define GLFW_JOYSTICK_1 0 -#define GLFW_JOYSTICK_2 1 -#define GLFW_JOYSTICK_3 2 -#define GLFW_JOYSTICK_4 3 -#define GLFW_JOYSTICK_5 4 -#define GLFW_JOYSTICK_6 5 -#define GLFW_JOYSTICK_7 6 -#define GLFW_JOYSTICK_8 7 -#define GLFW_JOYSTICK_9 8 -#define GLFW_JOYSTICK_10 9 -#define GLFW_JOYSTICK_11 10 -#define GLFW_JOYSTICK_12 11 -#define GLFW_JOYSTICK_13 12 -#define GLFW_JOYSTICK_14 13 -#define GLFW_JOYSTICK_15 14 -#define GLFW_JOYSTICK_16 15 -#define GLFW_JOYSTICK_LAST GLFW_JOYSTICK_16 -/*! @} */ - -/*! @defgroup errors Error codes - * - * See [error handling](@ref error_handling) for how these are used. - * - * @ingroup init - * @{ */ -/*! @brief GLFW has not been initialized. - * - * This occurs if a GLFW function was called that must not be called unless the - * library is [initialized](@ref intro_init). - * - * @analysis Application programmer error. Initialize GLFW before calling any - * function that requires initialization. - */ -#define GLFW_NOT_INITIALIZED 0x00010001 -/*! @brief No context is current for this thread. - * - * This occurs if a GLFW function was called that needs and operates on the - * current OpenGL or OpenGL ES context but no context is current on the calling - * thread. One such function is @ref glfwSwapInterval. - * - * @analysis Application programmer error. Ensure a context is current before - * calling functions that require a current context. - */ -#define GLFW_NO_CURRENT_CONTEXT 0x00010002 -/*! @brief One of the arguments to the function was an invalid enum value. - * - * One of the arguments to the function was an invalid enum value, for example - * requesting [GLFW_RED_BITS](@ref window_hints_fb) with @ref - * glfwGetWindowAttrib. - * - * @analysis Application programmer error. Fix the offending call. - */ -#define GLFW_INVALID_ENUM 0x00010003 -/*! @brief One of the arguments to the function was an invalid value. - * - * One of the arguments to the function was an invalid value, for example - * requesting a non-existent OpenGL or OpenGL ES version like 2.7. - * - * Requesting a valid but unavailable OpenGL or OpenGL ES version will instead - * result in a @ref GLFW_VERSION_UNAVAILABLE error. - * - * @analysis Application programmer error. Fix the offending call. - */ -#define GLFW_INVALID_VALUE 0x00010004 -/*! @brief A memory allocation failed. - * - * A memory allocation failed. - * - * @analysis A bug in GLFW or the underlying operating system. Report the bug - * to our [issue tracker](https://github.com/glfw/glfw/issues). - */ -#define GLFW_OUT_OF_MEMORY 0x00010005 -/*! @brief GLFW could not find support for the requested API on the system. - * - * GLFW could not find support for the requested API on the system. - * - * @analysis The installed graphics driver does not support the requested - * API, or does not support it via the chosen context creation backend. - * Below are a few examples. - * - * @par - * Some pre-installed Windows graphics drivers do not support OpenGL. AMD only - * supports OpenGL ES via EGL, while Nvidia and Intel only support it via - * a WGL or GLX extension. OS X does not provide OpenGL ES at all. The Mesa - * EGL, OpenGL and OpenGL ES libraries do not interface with the Nvidia binary - * driver. Older graphics drivers do not support Vulkan. - */ -#define GLFW_API_UNAVAILABLE 0x00010006 -/*! @brief The requested OpenGL or OpenGL ES version is not available. - * - * The requested OpenGL or OpenGL ES version (including any requested context - * or framebuffer hints) is not available on this machine. - * - * @analysis The machine does not support your requirements. If your - * application is sufficiently flexible, downgrade your requirements and try - * again. Otherwise, inform the user that their machine does not match your - * requirements. - * - * @par - * Future invalid OpenGL and OpenGL ES versions, for example OpenGL 4.8 if 5.0 - * comes out before the 4.x series gets that far, also fail with this error and - * not @ref GLFW_INVALID_VALUE, because GLFW cannot know what future versions - * will exist. - */ -#define GLFW_VERSION_UNAVAILABLE 0x00010007 -/*! @brief A platform-specific error occurred that does not match any of the - * more specific categories. - * - * A platform-specific error occurred that does not match any of the more - * specific categories. - * - * @analysis A bug or configuration error in GLFW, the underlying operating - * system or its drivers, or a lack of required resources. Report the issue to - * our [issue tracker](https://github.com/glfw/glfw/issues). - */ -#define GLFW_PLATFORM_ERROR 0x00010008 -/*! @brief The requested format is not supported or available. - * - * If emitted during window creation, the requested pixel format is not - * supported. - * - * If emitted when querying the clipboard, the contents of the clipboard could - * not be converted to the requested format. - * - * @analysis If emitted during window creation, one or more - * [hard constraints](@ref window_hints_hard) did not match any of the - * available pixel formats. If your application is sufficiently flexible, - * downgrade your requirements and try again. Otherwise, inform the user that - * their machine does not match your requirements. - * - * @par - * If emitted when querying the clipboard, ignore the error or report it to - * the user, as appropriate. - */ -#define GLFW_FORMAT_UNAVAILABLE 0x00010009 -/*! @brief The specified window does not have an OpenGL or OpenGL ES context. - * - * A window that does not have an OpenGL or OpenGL ES context was passed to - * a function that requires it to have one. - * - * @analysis Application programmer error. Fix the offending call. - */ -#define GLFW_NO_WINDOW_CONTEXT 0x0001000A -/*! @} */ - -#define GLFW_FOCUSED 0x00020001 -#define GLFW_ICONIFIED 0x00020002 -#define GLFW_RESIZABLE 0x00020003 -#define GLFW_VISIBLE 0x00020004 -#define GLFW_DECORATED 0x00020005 -#define GLFW_AUTO_ICONIFY 0x00020006 -#define GLFW_FLOATING 0x00020007 -#define GLFW_MAXIMIZED 0x00020008 - -#define GLFW_RED_BITS 0x00021001 -#define GLFW_GREEN_BITS 0x00021002 -#define GLFW_BLUE_BITS 0x00021003 -#define GLFW_ALPHA_BITS 0x00021004 -#define GLFW_DEPTH_BITS 0x00021005 -#define GLFW_STENCIL_BITS 0x00021006 -#define GLFW_ACCUM_RED_BITS 0x00021007 -#define GLFW_ACCUM_GREEN_BITS 0x00021008 -#define GLFW_ACCUM_BLUE_BITS 0x00021009 -#define GLFW_ACCUM_ALPHA_BITS 0x0002100A -#define GLFW_AUX_BUFFERS 0x0002100B -#define GLFW_STEREO 0x0002100C -#define GLFW_SAMPLES 0x0002100D -#define GLFW_SRGB_CAPABLE 0x0002100E -#define GLFW_REFRESH_RATE 0x0002100F -#define GLFW_DOUBLEBUFFER 0x00021010 - -#define GLFW_CLIENT_API 0x00022001 -#define GLFW_CONTEXT_VERSION_MAJOR 0x00022002 -#define GLFW_CONTEXT_VERSION_MINOR 0x00022003 -#define GLFW_CONTEXT_REVISION 0x00022004 -#define GLFW_CONTEXT_ROBUSTNESS 0x00022005 -#define GLFW_OPENGL_FORWARD_COMPAT 0x00022006 -#define GLFW_OPENGL_DEBUG_CONTEXT 0x00022007 -#define GLFW_OPENGL_PROFILE 0x00022008 -#define GLFW_CONTEXT_RELEASE_BEHAVIOR 0x00022009 -#define GLFW_CONTEXT_NO_ERROR 0x0002200A -#define GLFW_CONTEXT_CREATION_API 0x0002200B - -#define GLFW_NO_API 0 -#define GLFW_OPENGL_API 0x00030001 -#define GLFW_OPENGL_ES_API 0x00030002 - -#define GLFW_NO_ROBUSTNESS 0 -#define GLFW_NO_RESET_NOTIFICATION 0x00031001 -#define GLFW_LOSE_CONTEXT_ON_RESET 0x00031002 - -#define GLFW_OPENGL_ANY_PROFILE 0 -#define GLFW_OPENGL_CORE_PROFILE 0x00032001 -#define GLFW_OPENGL_COMPAT_PROFILE 0x00032002 - -#define GLFW_CURSOR 0x00033001 -#define GLFW_STICKY_KEYS 0x00033002 -#define GLFW_STICKY_MOUSE_BUTTONS 0x00033003 - -#define GLFW_CURSOR_NORMAL 0x00034001 -#define GLFW_CURSOR_HIDDEN 0x00034002 -#define GLFW_CURSOR_DISABLED 0x00034003 - -#define GLFW_ANY_RELEASE_BEHAVIOR 0 -#define GLFW_RELEASE_BEHAVIOR_FLUSH 0x00035001 -#define GLFW_RELEASE_BEHAVIOR_NONE 0x00035002 - -#define GLFW_NATIVE_CONTEXT_API 0x00036001 -#define GLFW_EGL_CONTEXT_API 0x00036002 - -/*! @defgroup shapes Standard cursor shapes - * - * See [standard cursor creation](@ref cursor_standard) for how these are used. - * - * @ingroup input - * @{ */ - -/*! @brief The regular arrow cursor shape. - * - * The regular arrow cursor. - */ -#define GLFW_ARROW_CURSOR 0x00036001 -/*! @brief The text input I-beam cursor shape. - * - * The text input I-beam cursor shape. - */ -#define GLFW_IBEAM_CURSOR 0x00036002 -/*! @brief The crosshair shape. - * - * The crosshair shape. - */ -#define GLFW_CROSSHAIR_CURSOR 0x00036003 -/*! @brief The hand shape. - * - * The hand shape. - */ -#define GLFW_HAND_CURSOR 0x00036004 -/*! @brief The horizontal resize arrow shape. - * - * The horizontal resize arrow shape. - */ -#define GLFW_HRESIZE_CURSOR 0x00036005 -/*! @brief The vertical resize arrow shape. - * - * The vertical resize arrow shape. - */ -#define GLFW_VRESIZE_CURSOR 0x00036006 -/*! @} */ - -#define GLFW_CONNECTED 0x00040001 -#define GLFW_DISCONNECTED 0x00040002 - -#define GLFW_DONT_CARE -1 - - -/************************************************************************* - * GLFW API types - *************************************************************************/ - -/*! @brief Client API function pointer type. - * - * Generic function pointer used for returning client API function pointers - * without forcing a cast from a regular pointer. - * - * @sa @ref context_glext - * @sa glfwGetProcAddress - * - * @since Added in version 3.0. - - * @ingroup context - */ -typedef void (*GLFWglproc)(void); - -/*! @brief Vulkan API function pointer type. - * - * Generic function pointer used for returning Vulkan API function pointers - * without forcing a cast from a regular pointer. - * - * @sa @ref vulkan_proc - * @sa glfwGetInstanceProcAddress - * - * @since Added in version 3.2. - * - * @ingroup vulkan - */ -typedef void (*GLFWvkproc)(void); - -/*! @brief Opaque monitor object. - * - * Opaque monitor object. - * - * @see @ref monitor_object - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -typedef struct GLFWmonitor GLFWmonitor; - -/*! @brief Opaque window object. - * - * Opaque window object. - * - * @see @ref window_object - * - * @since Added in version 3.0. - * - * @ingroup window - */ -typedef struct GLFWwindow GLFWwindow; - -/*! @brief Opaque cursor object. - * - * Opaque cursor object. - * - * @see @ref cursor_object - * - * @since Added in version 3.1. - * - * @ingroup cursor - */ -typedef struct GLFWcursor GLFWcursor; - -/*! @brief The function signature for error callbacks. - * - * This is the function signature for error callback functions. - * - * @param[in] error An [error code](@ref errors). - * @param[in] description A UTF-8 encoded string describing the error. - * - * @sa @ref error_handling - * @sa glfwSetErrorCallback - * - * @since Added in version 3.0. - * - * @ingroup init - */ -typedef void (* GLFWerrorfun)(int,const char*); - -/*! @brief The function signature for window position callbacks. - * - * This is the function signature for window position callback functions. - * - * @param[in] window The window that was moved. - * @param[in] xpos The new x-coordinate, in screen coordinates, of the - * upper-left corner of the client area of the window. - * @param[in] ypos The new y-coordinate, in screen coordinates, of the - * upper-left corner of the client area of the window. - * - * @sa @ref window_pos - * @sa glfwSetWindowPosCallback - * - * @since Added in version 3.0. - * - * @ingroup window - */ -typedef void (* GLFWwindowposfun)(GLFWwindow*,int,int); - -/*! @brief The function signature for window resize callbacks. - * - * This is the function signature for window size callback functions. - * - * @param[in] window The window that was resized. - * @param[in] width The new width, in screen coordinates, of the window. - * @param[in] height The new height, in screen coordinates, of the window. - * - * @sa @ref window_size - * @sa glfwSetWindowSizeCallback - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -typedef void (* GLFWwindowsizefun)(GLFWwindow*,int,int); - -/*! @brief The function signature for window close callbacks. - * - * This is the function signature for window close callback functions. - * - * @param[in] window The window that the user attempted to close. - * - * @sa @ref window_close - * @sa glfwSetWindowCloseCallback - * - * @since Added in version 2.5. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -typedef void (* GLFWwindowclosefun)(GLFWwindow*); - -/*! @brief The function signature for window content refresh callbacks. - * - * This is the function signature for window refresh callback functions. - * - * @param[in] window The window whose content needs to be refreshed. - * - * @sa @ref window_refresh - * @sa glfwSetWindowRefreshCallback - * - * @since Added in version 2.5. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -typedef void (* GLFWwindowrefreshfun)(GLFWwindow*); - -/*! @brief The function signature for window focus/defocus callbacks. - * - * This is the function signature for window focus callback functions. - * - * @param[in] window The window that gained or lost input focus. - * @param[in] focused `GLFW_TRUE` if the window was given input focus, or - * `GLFW_FALSE` if it lost it. - * - * @sa @ref window_focus - * @sa glfwSetWindowFocusCallback - * - * @since Added in version 3.0. - * - * @ingroup window - */ -typedef void (* GLFWwindowfocusfun)(GLFWwindow*,int); - -/*! @brief The function signature for window iconify/restore callbacks. - * - * This is the function signature for window iconify/restore callback - * functions. - * - * @param[in] window The window that was iconified or restored. - * @param[in] iconified `GLFW_TRUE` if the window was iconified, or - * `GLFW_FALSE` if it was restored. - * - * @sa @ref window_iconify - * @sa glfwSetWindowIconifyCallback - * - * @since Added in version 3.0. - * - * @ingroup window - */ -typedef void (* GLFWwindowiconifyfun)(GLFWwindow*,int); - -/*! @brief The function signature for framebuffer resize callbacks. - * - * This is the function signature for framebuffer resize callback - * functions. - * - * @param[in] window The window whose framebuffer was resized. - * @param[in] width The new width, in pixels, of the framebuffer. - * @param[in] height The new height, in pixels, of the framebuffer. - * - * @sa @ref window_fbsize - * @sa glfwSetFramebufferSizeCallback - * - * @since Added in version 3.0. - * - * @ingroup window - */ -typedef void (* GLFWframebuffersizefun)(GLFWwindow*,int,int); - -/*! @brief The function signature for mouse button callbacks. - * - * This is the function signature for mouse button callback functions. - * - * @param[in] window The window that received the event. - * @param[in] button The [mouse button](@ref buttons) that was pressed or - * released. - * @param[in] action One of `GLFW_PRESS` or `GLFW_RELEASE`. - * @param[in] mods Bit field describing which [modifier keys](@ref mods) were - * held down. - * - * @sa @ref input_mouse_button - * @sa glfwSetMouseButtonCallback - * - * @since Added in version 1.0. - * @glfw3 Added window handle and modifier mask parameters. - * - * @ingroup input - */ -typedef void (* GLFWmousebuttonfun)(GLFWwindow*,int,int,int); - -/*! @brief The function signature for cursor position callbacks. - * - * This is the function signature for cursor position callback functions. - * - * @param[in] window The window that received the event. - * @param[in] xpos The new cursor x-coordinate, relative to the left edge of - * the client area. - * @param[in] ypos The new cursor y-coordinate, relative to the top edge of the - * client area. - * - * @sa @ref cursor_pos - * @sa glfwSetCursorPosCallback - * - * @since Added in version 3.0. Replaces `GLFWmouseposfun`. - * - * @ingroup input - */ -typedef void (* GLFWcursorposfun)(GLFWwindow*,double,double); - -/*! @brief The function signature for cursor enter/leave callbacks. - * - * This is the function signature for cursor enter/leave callback functions. - * - * @param[in] window The window that received the event. - * @param[in] entered `GLFW_TRUE` if the cursor entered the window's client - * area, or `GLFW_FALSE` if it left it. - * - * @sa @ref cursor_enter - * @sa glfwSetCursorEnterCallback - * - * @since Added in version 3.0. - * - * @ingroup input - */ -typedef void (* GLFWcursorenterfun)(GLFWwindow*,int); - -/*! @brief The function signature for scroll callbacks. - * - * This is the function signature for scroll callback functions. - * - * @param[in] window The window that received the event. - * @param[in] xoffset The scroll offset along the x-axis. - * @param[in] yoffset The scroll offset along the y-axis. - * - * @sa @ref scrolling - * @sa glfwSetScrollCallback - * - * @since Added in version 3.0. Replaces `GLFWmousewheelfun`. - * - * @ingroup input - */ -typedef void (* GLFWscrollfun)(GLFWwindow*,double,double); - -/*! @brief The function signature for keyboard key callbacks. - * - * This is the function signature for keyboard key callback functions. - * - * @param[in] window The window that received the event. - * @param[in] key The [keyboard key](@ref keys) that was pressed or released. - * @param[in] scancode The system-specific scancode of the key. - * @param[in] action `GLFW_PRESS`, `GLFW_RELEASE` or `GLFW_REPEAT`. - * @param[in] mods Bit field describing which [modifier keys](@ref mods) were - * held down. - * - * @sa @ref input_key - * @sa glfwSetKeyCallback - * - * @since Added in version 1.0. - * @glfw3 Added window handle, scancode and modifier mask parameters. - * - * @ingroup input - */ -typedef void (* GLFWkeyfun)(GLFWwindow*,int,int,int,int); - -/*! @brief The function signature for Unicode character callbacks. - * - * This is the function signature for Unicode character callback functions. - * - * @param[in] window The window that received the event. - * @param[in] codepoint The Unicode code point of the character. - * - * @sa @ref input_char - * @sa glfwSetCharCallback - * - * @since Added in version 2.4. - * @glfw3 Added window handle parameter. - * - * @ingroup input - */ -typedef void (* GLFWcharfun)(GLFWwindow*,unsigned int); - -/*! @brief The function signature for Unicode character with modifiers - * callbacks. - * - * This is the function signature for Unicode character with modifiers callback - * functions. It is called for each input character, regardless of what - * modifier keys are held down. - * - * @param[in] window The window that received the event. - * @param[in] codepoint The Unicode code point of the character. - * @param[in] mods Bit field describing which [modifier keys](@ref mods) were - * held down. - * - * @sa @ref input_char - * @sa glfwSetCharModsCallback - * - * @since Added in version 3.1. - * - * @ingroup input - */ -typedef void (* GLFWcharmodsfun)(GLFWwindow*,unsigned int,int); - -/*! @brief The function signature for file drop callbacks. - * - * This is the function signature for file drop callbacks. - * - * @param[in] window The window that received the event. - * @param[in] count The number of dropped files. - * @param[in] paths The UTF-8 encoded file and/or directory path names. - * - * @sa @ref path_drop - * @sa glfwSetDropCallback - * - * @since Added in version 3.1. - * - * @ingroup input - */ -typedef void (* GLFWdropfun)(GLFWwindow*,int,const char**); - -/*! @brief The function signature for monitor configuration callbacks. - * - * This is the function signature for monitor configuration callback functions. - * - * @param[in] monitor The monitor that was connected or disconnected. - * @param[in] event One of `GLFW_CONNECTED` or `GLFW_DISCONNECTED`. - * - * @sa @ref monitor_event - * @sa glfwSetMonitorCallback - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -typedef void (* GLFWmonitorfun)(GLFWmonitor*,int); - -/*! @brief The function signature for joystick configuration callbacks. - * - * This is the function signature for joystick configuration callback - * functions. - * - * @param[in] joy The joystick that was connected or disconnected. - * @param[in] event One of `GLFW_CONNECTED` or `GLFW_DISCONNECTED`. - * - * @sa @ref joystick_event - * @sa glfwSetJoystickCallback - * - * @since Added in version 3.2. - * - * @ingroup input - */ -typedef void (* GLFWjoystickfun)(int,int); - -/*! @brief Video mode type. - * - * This describes a single video mode. - * - * @sa @ref monitor_modes - * @sa glfwGetVideoMode glfwGetVideoModes - * - * @since Added in version 1.0. - * @glfw3 Added refresh rate member. - * - * @ingroup monitor - */ -typedef struct GLFWvidmode -{ - /*! The width, in screen coordinates, of the video mode. - */ - int width; - /*! The height, in screen coordinates, of the video mode. - */ - int height; - /*! The bit depth of the red channel of the video mode. - */ - int redBits; - /*! The bit depth of the green channel of the video mode. - */ - int greenBits; - /*! The bit depth of the blue channel of the video mode. - */ - int blueBits; - /*! The refresh rate, in Hz, of the video mode. - */ - int refreshRate; -} GLFWvidmode; - -/*! @brief Gamma ramp. - * - * This describes the gamma ramp for a monitor. - * - * @sa @ref monitor_gamma - * @sa glfwGetGammaRamp glfwSetGammaRamp - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -typedef struct GLFWgammaramp -{ - /*! An array of value describing the response of the red channel. - */ - unsigned short* red; - /*! An array of value describing the response of the green channel. - */ - unsigned short* green; - /*! An array of value describing the response of the blue channel. - */ - unsigned short* blue; - /*! The number of elements in each array. - */ - unsigned int size; -} GLFWgammaramp; - -/*! @brief Image data. - * - * @sa @ref cursor_custom - * - * @since Added in version 2.1. - * @glfw3 Removed format and bytes-per-pixel members. - */ -typedef struct GLFWimage -{ - /*! The width, in pixels, of this image. - */ - int width; - /*! The height, in pixels, of this image. - */ - int height; - /*! The pixel data of this image, arranged left-to-right, top-to-bottom. - */ - unsigned char* pixels; -} GLFWimage; - - -/************************************************************************* - * GLFW API functions - *************************************************************************/ - -/*! @brief Initializes the GLFW library. - * - * This function initializes the GLFW library. Before most GLFW functions can - * be used, GLFW must be initialized, and before an application terminates GLFW - * should be terminated in order to free any resources allocated during or - * after initialization. - * - * If this function fails, it calls @ref glfwTerminate before returning. If it - * succeeds, you should call @ref glfwTerminate before the application exits. - * - * Additional calls to this function after successful initialization but before - * termination will return `GLFW_TRUE` immediately. - * - * @return `GLFW_TRUE` if successful, or `GLFW_FALSE` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_PLATFORM_ERROR. - * - * @remark @osx This function will change the current directory of the - * application to the `Contents/Resources` subdirectory of the application's - * bundle, if present. This can be disabled with a - * [compile-time option](@ref compile_options_osx). - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref intro_init - * @sa glfwTerminate - * - * @since Added in version 1.0. - * - * @ingroup init - */ -GLFWAPI int glfwInit(void); - -/*! @brief Terminates the GLFW library. - * - * This function destroys all remaining windows and cursors, restores any - * modified gamma ramps and frees any other allocated resources. Once this - * function is called, you must again call @ref glfwInit successfully before - * you will be able to use most GLFW functions. - * - * If GLFW has been successfully initialized, this function should be called - * before the application exits. If initialization fails, there is no need to - * call this function, as it is called by @ref glfwInit before it returns - * failure. - * - * @errors Possible errors include @ref GLFW_PLATFORM_ERROR. - * - * @remark This function may be called before @ref glfwInit. - * - * @warning The contexts of any remaining windows must not be current on any - * other thread when this function is called. - * - * @reentrancy This function must not be called from a callback. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref intro_init - * @sa glfwInit - * - * @since Added in version 1.0. - * - * @ingroup init - */ -GLFWAPI void glfwTerminate(void); - -/*! @brief Retrieves the version of the GLFW library. - * - * This function retrieves the major, minor and revision numbers of the GLFW - * library. It is intended for when you are using GLFW as a shared library and - * want to ensure that you are using the minimum required version. - * - * Any or all of the version arguments may be `NULL`. - * - * @param[out] major Where to store the major version number, or `NULL`. - * @param[out] minor Where to store the minor version number, or `NULL`. - * @param[out] rev Where to store the revision number, or `NULL`. - * - * @errors None. - * - * @remark This function may be called before @ref glfwInit. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref intro_version - * @sa glfwGetVersionString - * - * @since Added in version 1.0. - * - * @ingroup init - */ -GLFWAPI void glfwGetVersion(int* major, int* minor, int* rev); - -/*! @brief Returns a string describing the compile-time configuration. - * - * This function returns the compile-time generated - * [version string](@ref intro_version_string) of the GLFW library binary. It - * describes the version, platform, compiler and any platform-specific - * compile-time options. It should not be confused with the OpenGL or OpenGL - * ES version string, queried with `glGetString`. - * - * __Do not use the version string__ to parse the GLFW library version. The - * @ref glfwGetVersion function provides the version of the running library - * binary in numerical format. - * - * @return The ASCII encoded GLFW version string. - * - * @errors None. - * - * @remark This function may be called before @ref glfwInit. - * - * @pointer_lifetime The returned string is static and compile-time generated. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref intro_version - * @sa glfwGetVersion - * - * @since Added in version 3.0. - * - * @ingroup init - */ -GLFWAPI const char* glfwGetVersionString(void); - -/*! @brief Sets the error callback. - * - * This function sets the error callback, which is called with an error code - * and a human-readable description each time a GLFW error occurs. - * - * The error callback is called on the thread where the error occurred. If you - * are using GLFW from multiple threads, your error callback needs to be - * written accordingly. - * - * Because the description string may have been generated specifically for that - * error, it is not guaranteed to be valid after the callback has returned. If - * you wish to use it after the callback returns, you need to make a copy. - * - * Once set, the error callback remains set even after the library has been - * terminated. - * - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set. - * - * @errors None. - * - * @remark This function may be called before @ref glfwInit. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref error_handling - * - * @since Added in version 3.0. - * - * @ingroup init - */ -GLFWAPI GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun); - -/*! @brief Returns the currently connected monitors. - * - * This function returns an array of handles for all currently connected - * monitors. The primary monitor is always first in the returned array. If no - * monitors were found, this function returns `NULL`. - * - * @param[out] count Where to store the number of monitors in the returned - * array. This is set to zero if an error occurred. - * @return An array of monitor handles, or `NULL` if no monitors were found or - * if an [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @pointer_lifetime The returned array is allocated and freed by GLFW. You - * should not free it yourself. It is guaranteed to be valid only until the - * monitor configuration changes or the library is terminated. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref monitor_monitors - * @sa @ref monitor_event - * @sa glfwGetPrimaryMonitor - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -GLFWAPI GLFWmonitor** glfwGetMonitors(int* count); - -/*! @brief Returns the primary monitor. - * - * This function returns the primary monitor. This is usually the monitor - * where elements like the task bar or global menu bar are located. - * - * @return The primary monitor, or `NULL` if no monitors were found or if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @remark The primary monitor is always first in the array returned by @ref - * glfwGetMonitors. - * - * @sa @ref monitor_monitors - * @sa glfwGetMonitors - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -GLFWAPI GLFWmonitor* glfwGetPrimaryMonitor(void); - -/*! @brief Returns the position of the monitor's viewport on the virtual screen. - * - * This function returns the position, in screen coordinates, of the upper-left - * corner of the specified monitor. - * - * Any or all of the position arguments may be `NULL`. If an error occurs, all - * non-`NULL` position arguments will be set to zero. - * - * @param[in] monitor The monitor to query. - * @param[out] xpos Where to store the monitor x-coordinate, or `NULL`. - * @param[out] ypos Where to store the monitor y-coordinate, or `NULL`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref monitor_properties - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -GLFWAPI void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos); - -/*! @brief Returns the physical size of the monitor. - * - * This function returns the size, in millimetres, of the display area of the - * specified monitor. - * - * Some systems do not provide accurate monitor size information, either - * because the monitor - * [EDID](https://en.wikipedia.org/wiki/Extended_display_identification_data) - * data is incorrect or because the driver does not report it accurately. - * - * Any or all of the size arguments may be `NULL`. If an error occurs, all - * non-`NULL` size arguments will be set to zero. - * - * @param[in] monitor The monitor to query. - * @param[out] widthMM Where to store the width, in millimetres, of the - * monitor's display area, or `NULL`. - * @param[out] heightMM Where to store the height, in millimetres, of the - * monitor's display area, or `NULL`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @remark @win32 calculates the returned physical size from the - * current resolution and system DPI instead of querying the monitor EDID data. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref monitor_properties - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -GLFWAPI void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* widthMM, int* heightMM); - -/*! @brief Returns the name of the specified monitor. - * - * This function returns a human-readable name, encoded as UTF-8, of the - * specified monitor. The name typically reflects the make and model of the - * monitor and is not guaranteed to be unique among the connected monitors. - * - * @param[in] monitor The monitor to query. - * @return The UTF-8 encoded name of the monitor, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @pointer_lifetime The returned string is allocated and freed by GLFW. You - * should not free it yourself. It is valid until the specified monitor is - * disconnected or the library is terminated. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref monitor_properties - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -GLFWAPI const char* glfwGetMonitorName(GLFWmonitor* monitor); - -/*! @brief Sets the monitor configuration callback. - * - * This function sets the monitor configuration callback, or removes the - * currently set callback. This is called when a monitor is connected to or - * disconnected from the system. - * - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref monitor_event - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -GLFWAPI GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun); - -/*! @brief Returns the available video modes for the specified monitor. - * - * This function returns an array of all video modes supported by the specified - * monitor. The returned array is sorted in ascending order, first by color - * bit depth (the sum of all channel depths) and then by resolution area (the - * product of width and height). - * - * @param[in] monitor The monitor to query. - * @param[out] count Where to store the number of video modes in the returned - * array. This is set to zero if an error occurred. - * @return An array of video modes, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The returned array is allocated and freed by GLFW. You - * should not free it yourself. It is valid until the specified monitor is - * disconnected, this function is called again for that monitor or the library - * is terminated. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref monitor_modes - * @sa glfwGetVideoMode - * - * @since Added in version 1.0. - * @glfw3 Changed to return an array of modes for a specific monitor. - * - * @ingroup monitor - */ -GLFWAPI const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count); - -/*! @brief Returns the current mode of the specified monitor. - * - * This function returns the current video mode of the specified monitor. If - * you have created a full screen window for that monitor, the return value - * will depend on whether that window is iconified. - * - * @param[in] monitor The monitor to query. - * @return The current mode of the monitor, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The returned array is allocated and freed by GLFW. You - * should not free it yourself. It is valid until the specified monitor is - * disconnected or the library is terminated. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref monitor_modes - * @sa glfwGetVideoModes - * - * @since Added in version 3.0. Replaces `glfwGetDesktopMode`. - * - * @ingroup monitor - */ -GLFWAPI const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor); - -/*! @brief Generates a gamma ramp and sets it for the specified monitor. - * - * This function generates a 256-element gamma ramp from the specified exponent - * and then calls @ref glfwSetGammaRamp with it. The value must be a finite - * number greater than zero. - * - * @param[in] monitor The monitor whose gamma ramp to set. - * @param[in] gamma The desired exponent. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_VALUE and @ref GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref monitor_gamma - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -GLFWAPI void glfwSetGamma(GLFWmonitor* monitor, float gamma); - -/*! @brief Returns the current gamma ramp for the specified monitor. - * - * This function returns the current gamma ramp of the specified monitor. - * - * @param[in] monitor The monitor to query. - * @return The current gamma ramp, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The returned structure and its arrays are allocated and - * freed by GLFW. You should not free them yourself. They are valid until the - * specified monitor is disconnected, this function is called again for that - * monitor or the library is terminated. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref monitor_gamma - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -GLFWAPI const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor); - -/*! @brief Sets the current gamma ramp for the specified monitor. - * - * This function sets the current gamma ramp for the specified monitor. The - * original gamma ramp for that monitor is saved by GLFW the first time this - * function is called and is restored by @ref glfwTerminate. - * - * @param[in] monitor The monitor whose gamma ramp to set. - * @param[in] ramp The gamma ramp to use. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @remark Gamma ramp sizes other than 256 are not supported by all platforms - * or graphics hardware. - * - * @remark @win32 The gamma ramp size must be 256. - * - * @pointer_lifetime The specified gamma ramp is copied before this function - * returns. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref monitor_gamma - * - * @since Added in version 3.0. - * - * @ingroup monitor - */ -GLFWAPI void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); - -/*! @brief Resets all window hints to their default values. - * - * This function resets all window hints to their - * [default values](@ref window_hints_values). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_hints - * @sa glfwWindowHint - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI void glfwDefaultWindowHints(void); - -/*! @brief Sets the specified window hint to the desired value. - * - * This function sets hints for the next call to @ref glfwCreateWindow. The - * hints, once set, retain their values until changed by a call to @ref - * glfwWindowHint or @ref glfwDefaultWindowHints, or until the library is - * terminated. - * - * This function does not check whether the specified hint values are valid. - * If you set hints to invalid values this will instead be reported by the next - * call to @ref glfwCreateWindow. - * - * @param[in] hint The [window hint](@ref window_hints) to set. - * @param[in] value The new value of the window hint. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_INVALID_ENUM. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_hints - * @sa glfwDefaultWindowHints - * - * @since Added in version 3.0. Replaces `glfwOpenWindowHint`. - * - * @ingroup window - */ -GLFWAPI void glfwWindowHint(int hint, int value); - -/*! @brief Creates a window and its associated context. - * - * This function creates a window and its associated OpenGL or OpenGL ES - * context. Most of the options controlling how the window and its context - * should be created are specified with [window hints](@ref window_hints). - * - * Successful creation does not change which context is current. Before you - * can use the newly created context, you need to - * [make it current](@ref context_current). For information about the `share` - * parameter, see @ref context_sharing. - * - * The created window, framebuffer and context may differ from what you - * requested, as not all parameters and hints are - * [hard constraints](@ref window_hints_hard). This includes the size of the - * window, especially for full screen windows. To query the actual attributes - * of the created window, framebuffer and context, see @ref - * glfwGetWindowAttrib, @ref glfwGetWindowSize and @ref glfwGetFramebufferSize. - * - * To create a full screen window, you need to specify the monitor the window - * will cover. If no monitor is specified, the window will be windowed mode. - * Unless you have a way for the user to choose a specific monitor, it is - * recommended that you pick the primary monitor. For more information on how - * to query connected monitors, see @ref monitor_monitors. - * - * For full screen windows, the specified size becomes the resolution of the - * window's _desired video mode_. As long as a full screen window is not - * iconified, the supported video mode most closely matching the desired video - * mode is set for the specified monitor. For more information about full - * screen windows, including the creation of so called _windowed full screen_ - * or _borderless full screen_ windows, see @ref window_windowed_full_screen. - * - * By default, newly created windows use the placement recommended by the - * window system. To create the window at a specific position, make it - * initially invisible using the [GLFW_VISIBLE](@ref window_hints_wnd) window - * hint, set its [position](@ref window_pos) and then [show](@ref window_hide) - * it. - * - * As long as at least one full screen window is not iconified, the screensaver - * is prohibited from starting. - * - * Window systems put limits on window sizes. Very large or very small window - * dimensions may be overridden by the window system on creation. Check the - * actual [size](@ref window_size) after creation. - * - * The [swap interval](@ref buffer_swap) is not set during window creation and - * the initial value may vary depending on driver settings and defaults. - * - * @param[in] width The desired width, in screen coordinates, of the window. - * This must be greater than zero. - * @param[in] height The desired height, in screen coordinates, of the window. - * This must be greater than zero. - * @param[in] title The initial, UTF-8 encoded window title. - * @param[in] monitor The monitor to use for full screen mode, or `NULL` for - * windowed mode. - * @param[in] share The window whose context to share resources with, or `NULL` - * to not share resources. - * @return The handle of the created window, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_ENUM, @ref GLFW_INVALID_VALUE, @ref GLFW_API_UNAVAILABLE, @ref - * GLFW_VERSION_UNAVAILABLE, @ref GLFW_FORMAT_UNAVAILABLE and @ref - * GLFW_PLATFORM_ERROR. - * - * @remark @win32 Window creation will fail if the Microsoft GDI software - * OpenGL implementation is the only one available. - * - * @remark @win32 If the executable has an icon resource named `GLFW_ICON,` it - * will be set as the initial icon for the window. If no such icon is present, - * the `IDI_WINLOGO` icon will be used instead. To set a different icon, see - * @ref glfwSetWindowIcon. - * - * @remark @win32 The context to share resources with must not be current on - * any other thread. - * - * @remark @osx The GLFW window has no icon, as it is not a document - * window, but the dock icon will be the same as the application bundle's icon. - * For more information on bundles, see the - * [Bundle Programming Guide](https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/) - * in the Mac Developer Library. - * - * @remark @osx The first time a window is created the menu bar is populated - * with common commands like Hide, Quit and About. The About entry opens - * a minimal about dialog with information from the application's bundle. The - * menu bar can be disabled with a - * [compile-time option](@ref compile_options_osx). - * - * @remark @osx On OS X 10.10 and later the window frame will not be rendered - * at full resolution on Retina displays unless the `NSHighResolutionCapable` - * key is enabled in the application bundle's `Info.plist`. For more - * information, see - * [High Resolution Guidelines for OS X](https://developer.apple.com/library/mac/documentation/GraphicsAnimation/Conceptual/HighResolutionOSX/Explained/Explained.html) - * in the Mac Developer Library. The GLFW test and example programs use - * a custom `Info.plist` template for this, which can be found as - * `CMake/MacOSXBundleInfo.plist.in` in the source tree. - * - * @remark @x11 Some window managers will not respect the placement of - * initially hidden windows. - * - * @remark @x11 Due to the asynchronous nature of X11, it may take a moment for - * a window to reach its requested state. This means you may not be able to - * query the final size, position or other attributes directly after window - * creation. - * - * @reentrancy This function must not be called from a callback. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_creation - * @sa glfwDestroyWindow - * - * @since Added in version 3.0. Replaces `glfwOpenWindow`. - * - * @ingroup window - */ -GLFWAPI GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share); - -/*! @brief Destroys the specified window and its context. - * - * This function destroys the specified window and its context. On calling - * this function, no further callbacks will be called for that window. - * - * If the context of the specified window is current on the main thread, it is - * detached before being destroyed. - * - * @param[in] window The window to destroy. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @note The context of the specified window must not be current on any other - * thread when this function is called. - * - * @reentrancy This function must not be called from a callback. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_creation - * @sa glfwCreateWindow - * - * @since Added in version 3.0. Replaces `glfwCloseWindow`. - * - * @ingroup window - */ -GLFWAPI void glfwDestroyWindow(GLFWwindow* window); - -/*! @brief Checks the close flag of the specified window. - * - * This function returns the value of the close flag of the specified window. - * - * @param[in] window The window to query. - * @return The value of the close flag. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @sa @ref window_close - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI int glfwWindowShouldClose(GLFWwindow* window); - -/*! @brief Sets the close flag of the specified window. - * - * This function sets the value of the close flag of the specified window. - * This can be used to override the user's attempt to close the window, or - * to signal that it should be closed. - * - * @param[in] window The window whose flag to change. - * @param[in] value The new value. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @sa @ref window_close - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowShouldClose(GLFWwindow* window, int value); - -/*! @brief Sets the title of the specified window. - * - * This function sets the window title, encoded as UTF-8, of the specified - * window. - * - * @param[in] window The window whose title to change. - * @param[in] title The UTF-8 encoded window title. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @remark @osx The window title will not be updated until the next time you - * process events. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_title - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowTitle(GLFWwindow* window, const char* title); - -/*! @brief Sets the icon for the specified window. - * - * This function sets the icon of the specified window. If passed an array of - * candidate images, those of or closest to the sizes desired by the system are - * selected. If no images are specified, the window reverts to its default - * icon. - * - * The desired image sizes varies depending on platform and system settings. - * The selected images will be rescaled as needed. Good sizes include 16x16, - * 32x32 and 48x48. - * - * @param[in] window The window whose icon to set. - * @param[in] count The number of images in the specified array, or zero to - * revert to the default window icon. - * @param[in] images The images to create the icon from. This is ignored if - * count is zero. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The specified image data is copied before this function - * returns. - * - * @remark @osx The GLFW window has no icon, as it is not a document - * window, so this function does nothing. The dock icon will be the same as - * the application bundle's icon. For more information on bundles, see the - * [Bundle Programming Guide](https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/) - * in the Mac Developer Library. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_icon - * - * @since Added in version 3.2. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowIcon(GLFWwindow* window, int count, const GLFWimage* images); - -/*! @brief Retrieves the position of the client area of the specified window. - * - * This function retrieves the position, in screen coordinates, of the - * upper-left corner of the client area of the specified window. - * - * Any or all of the position arguments may be `NULL`. If an error occurs, all - * non-`NULL` position arguments will be set to zero. - * - * @param[in] window The window to query. - * @param[out] xpos Where to store the x-coordinate of the upper-left corner of - * the client area, or `NULL`. - * @param[out] ypos Where to store the y-coordinate of the upper-left corner of - * the client area, or `NULL`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_pos - * @sa glfwSetWindowPos - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); - -/*! @brief Sets the position of the client area of the specified window. - * - * This function sets the position, in screen coordinates, of the upper-left - * corner of the client area of the specified windowed mode window. If the - * window is a full screen window, this function does nothing. - * - * __Do not use this function__ to move an already visible window unless you - * have very good reasons for doing so, as it will confuse and annoy the user. - * - * The window manager may put limits on what positions are allowed. GLFW - * cannot and should not override these limits. - * - * @param[in] window The window to query. - * @param[in] xpos The x-coordinate of the upper-left corner of the client area. - * @param[in] ypos The y-coordinate of the upper-left corner of the client area. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_pos - * @sa glfwGetWindowPos - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos); - -/*! @brief Retrieves the size of the client area of the specified window. - * - * This function retrieves the size, in screen coordinates, of the client area - * of the specified window. If you wish to retrieve the size of the - * framebuffer of the window in pixels, see @ref glfwGetFramebufferSize. - * - * Any or all of the size arguments may be `NULL`. If an error occurs, all - * non-`NULL` size arguments will be set to zero. - * - * @param[in] window The window whose size to retrieve. - * @param[out] width Where to store the width, in screen coordinates, of the - * client area, or `NULL`. - * @param[out] height Where to store the height, in screen coordinates, of the - * client area, or `NULL`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_size - * @sa glfwSetWindowSize - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -GLFWAPI void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); - -/*! @brief Sets the size limits of the specified window. - * - * This function sets the size limits of the client area of the specified - * window. If the window is full screen, the size limits only take effect - * once it is made windowed. If the window is not resizable, this function - * does nothing. - * - * The size limits are applied immediately to a windowed mode window and may - * cause it to be resized. - * - * The maximum dimensions must be greater than or equal to the minimum - * dimensions and all must be greater than or equal to zero. - * - * @param[in] window The window to set limits for. - * @param[in] minwidth The minimum width, in screen coordinates, of the client - * area, or `GLFW_DONT_CARE`. - * @param[in] minheight The minimum height, in screen coordinates, of the - * client area, or `GLFW_DONT_CARE`. - * @param[in] maxwidth The maximum width, in screen coordinates, of the client - * area, or `GLFW_DONT_CARE`. - * @param[in] maxheight The maximum height, in screen coordinates, of the - * client area, or `GLFW_DONT_CARE`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_VALUE and @ref GLFW_PLATFORM_ERROR. - * - * @remark If you set size limits and an aspect ratio that conflict, the - * results are undefined. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_sizelimits - * @sa glfwSetWindowAspectRatio - * - * @since Added in version 3.2. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowSizeLimits(GLFWwindow* window, int minwidth, int minheight, int maxwidth, int maxheight); - -/*! @brief Sets the aspect ratio of the specified window. - * - * This function sets the required aspect ratio of the client area of the - * specified window. If the window is full screen, the aspect ratio only takes - * effect once it is made windowed. If the window is not resizable, this - * function does nothing. - * - * The aspect ratio is specified as a numerator and a denominator and both - * values must be greater than zero. For example, the common 16:9 aspect ratio - * is specified as 16 and 9, respectively. - * - * If the numerator and denominator is set to `GLFW_DONT_CARE` then the aspect - * ratio limit is disabled. - * - * The aspect ratio is applied immediately to a windowed mode window and may - * cause it to be resized. - * - * @param[in] window The window to set limits for. - * @param[in] numer The numerator of the desired aspect ratio, or - * `GLFW_DONT_CARE`. - * @param[in] denom The denominator of the desired aspect ratio, or - * `GLFW_DONT_CARE`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_VALUE and @ref GLFW_PLATFORM_ERROR. - * - * @remark If you set size limits and an aspect ratio that conflict, the - * results are undefined. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_sizelimits - * @sa glfwSetWindowSizeLimits - * - * @since Added in version 3.2. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowAspectRatio(GLFWwindow* window, int numer, int denom); - -/*! @brief Sets the size of the client area of the specified window. - * - * This function sets the size, in screen coordinates, of the client area of - * the specified window. - * - * For full screen windows, this function updates the resolution of its desired - * video mode and switches to the video mode closest to it, without affecting - * the window's context. As the context is unaffected, the bit depths of the - * framebuffer remain unchanged. - * - * If you wish to update the refresh rate of the desired video mode in addition - * to its resolution, see @ref glfwSetWindowMonitor. - * - * The window manager may put limits on what sizes are allowed. GLFW cannot - * and should not override these limits. - * - * @param[in] window The window to resize. - * @param[in] width The desired width, in screen coordinates, of the window - * client area. - * @param[in] height The desired height, in screen coordinates, of the window - * client area. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_size - * @sa glfwGetWindowSize - * @sa glfwSetWindowMonitor - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowSize(GLFWwindow* window, int width, int height); - -/*! @brief Retrieves the size of the framebuffer of the specified window. - * - * This function retrieves the size, in pixels, of the framebuffer of the - * specified window. If you wish to retrieve the size of the window in screen - * coordinates, see @ref glfwGetWindowSize. - * - * Any or all of the size arguments may be `NULL`. If an error occurs, all - * non-`NULL` size arguments will be set to zero. - * - * @param[in] window The window whose framebuffer to query. - * @param[out] width Where to store the width, in pixels, of the framebuffer, - * or `NULL`. - * @param[out] height Where to store the height, in pixels, of the framebuffer, - * or `NULL`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_fbsize - * @sa glfwSetFramebufferSizeCallback - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height); - -/*! @brief Retrieves the size of the frame of the window. - * - * This function retrieves the size, in screen coordinates, of each edge of the - * frame of the specified window. This size includes the title bar, if the - * window has one. The size of the frame may vary depending on the - * [window-related hints](@ref window_hints_wnd) used to create it. - * - * Because this function retrieves the size of each window frame edge and not - * the offset along a particular coordinate axis, the retrieved values will - * always be zero or positive. - * - * Any or all of the size arguments may be `NULL`. If an error occurs, all - * non-`NULL` size arguments will be set to zero. - * - * @param[in] window The window whose frame size to query. - * @param[out] left Where to store the size, in screen coordinates, of the left - * edge of the window frame, or `NULL`. - * @param[out] top Where to store the size, in screen coordinates, of the top - * edge of the window frame, or `NULL`. - * @param[out] right Where to store the size, in screen coordinates, of the - * right edge of the window frame, or `NULL`. - * @param[out] bottom Where to store the size, in screen coordinates, of the - * bottom edge of the window frame, or `NULL`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_size - * - * @since Added in version 3.1. - * - * @ingroup window - */ -GLFWAPI void glfwGetWindowFrameSize(GLFWwindow* window, int* left, int* top, int* right, int* bottom); - -/*! @brief Iconifies the specified window. - * - * This function iconifies (minimizes) the specified window if it was - * previously restored. If the window is already iconified, this function does - * nothing. - * - * If the specified window is a full screen window, the original monitor - * resolution is restored until the window is restored. - * - * @param[in] window The window to iconify. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_iconify - * @sa glfwRestoreWindow - * @sa glfwMaximizeWindow - * - * @since Added in version 2.1. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -GLFWAPI void glfwIconifyWindow(GLFWwindow* window); - -/*! @brief Restores the specified window. - * - * This function restores the specified window if it was previously iconified - * (minimized) or maximized. If the window is already restored, this function - * does nothing. - * - * If the specified window is a full screen window, the resolution chosen for - * the window is restored on the selected monitor. - * - * @param[in] window The window to restore. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_iconify - * @sa glfwIconifyWindow - * @sa glfwMaximizeWindow - * - * @since Added in version 2.1. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -GLFWAPI void glfwRestoreWindow(GLFWwindow* window); - -/*! @brief Maximizes the specified window. - * - * This function maximizes the specified window if it was previously not - * maximized. If the window is already maximized, this function does nothing. - * - * If the specified window is a full screen window, this function does nothing. - * - * @param[in] window The window to maximize. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @par Thread Safety - * This function may only be called from the main thread. - * - * @sa @ref window_iconify - * @sa glfwIconifyWindow - * @sa glfwRestoreWindow - * - * @since Added in GLFW 3.2. - * - * @ingroup window - */ -GLFWAPI void glfwMaximizeWindow(GLFWwindow* window); - -/*! @brief Makes the specified window visible. - * - * This function makes the specified window visible if it was previously - * hidden. If the window is already visible or is in full screen mode, this - * function does nothing. - * - * @param[in] window The window to make visible. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_hide - * @sa glfwHideWindow - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI void glfwShowWindow(GLFWwindow* window); - -/*! @brief Hides the specified window. - * - * This function hides the specified window if it was previously visible. If - * the window is already hidden or is in full screen mode, this function does - * nothing. - * - * @param[in] window The window to hide. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_hide - * @sa glfwShowWindow - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI void glfwHideWindow(GLFWwindow* window); - -/*! @brief Brings the specified window to front and sets input focus. - * - * This function brings the specified window to front and sets input focus. - * The window should already be visible and not iconified. - * - * By default, both windowed and full screen mode windows are focused when - * initially created. Set the [GLFW_FOCUSED](@ref window_hints_wnd) to disable - * this behavior. - * - * __Do not use this function__ to steal focus from other applications unless - * you are certain that is what the user wants. Focus stealing can be - * extremely disruptive. - * - * @param[in] window The window to give input focus. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_focus - * - * @since Added in version 3.2. - * - * @ingroup window - */ -GLFWAPI void glfwFocusWindow(GLFWwindow* window); - -/*! @brief Returns the monitor that the window uses for full screen mode. - * - * This function returns the handle of the monitor that the specified window is - * in full screen on. - * - * @param[in] window The window to query. - * @return The monitor, or `NULL` if the window is in windowed mode or an error - * occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_monitor - * @sa glfwSetWindowMonitor - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window); - -/*! @brief Sets the mode, monitor, video mode and placement of a window. - * - * This function sets the monitor that the window uses for full screen mode or, - * if the monitor is `NULL`, makes it windowed mode. - * - * When setting a monitor, this function updates the width, height and refresh - * rate of the desired video mode and switches to the video mode closest to it. - * The window position is ignored when setting a monitor. - * - * When the monitor is `NULL`, the position, width and height are used to - * place the window client area. The refresh rate is ignored when no monitor - * is specified. - * - * If you only wish to update the resolution of a full screen window or the - * size of a windowed mode window, see @ref glfwSetWindowSize. - * - * When a window transitions from full screen to windowed mode, this function - * restores any previous window settings such as whether it is decorated, - * floating, resizable, has size or aspect ratio limits, etc.. - * - * @param[in] window The window whose monitor, size or video mode to set. - * @param[in] monitor The desired monitor, or `NULL` to set windowed mode. - * @param[in] xpos The desired x-coordinate of the upper-left corner of the - * client area. - * @param[in] ypos The desired y-coordinate of the upper-left corner of the - * client area. - * @param[in] width The desired with, in screen coordinates, of the client area - * or video mode. - * @param[in] height The desired height, in screen coordinates, of the client - * area or video mode. - * @param[in] refreshRate The desired refresh rate, in Hz, of the video mode, - * or `GLFW_DONT_CARE`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_monitor - * @sa @ref window_full_screen - * @sa glfwGetWindowMonitor - * @sa glfwSetWindowSize - * - * @since Added in version 3.2. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowMonitor(GLFWwindow* window, GLFWmonitor* monitor, int xpos, int ypos, int width, int height, int refreshRate); - -/*! @brief Returns an attribute of the specified window. - * - * This function returns the value of an attribute of the specified window or - * its OpenGL or OpenGL ES context. - * - * @param[in] window The window to query. - * @param[in] attrib The [window attribute](@ref window_attribs) whose value to - * return. - * @return The value of the attribute, or zero if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_ENUM and @ref GLFW_PLATFORM_ERROR. - * - * @remark Framebuffer related hints are not window attributes. See @ref - * window_attribs_fb for more information. - * - * @remark Zero is a valid value for many window and context related - * attributes so you cannot use a return value of zero as an indication of - * errors. However, this function should not fail as long as it is passed - * valid arguments and the library has been [initialized](@ref intro_init). - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_attribs - * - * @since Added in version 3.0. Replaces `glfwGetWindowParam` and - * `glfwGetGLVersion`. - * - * @ingroup window - */ -GLFWAPI int glfwGetWindowAttrib(GLFWwindow* window, int attrib); - -/*! @brief Sets the user pointer of the specified window. - * - * This function sets the user-defined pointer of the specified window. The - * current value is retained until the window is destroyed. The initial value - * is `NULL`. - * - * @param[in] window The window whose pointer to set. - * @param[in] pointer The new value. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @sa @ref window_userptr - * @sa glfwGetWindowUserPointer - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer); - -/*! @brief Returns the user pointer of the specified window. - * - * This function returns the current value of the user-defined pointer of the - * specified window. The initial value is `NULL`. - * - * @param[in] window The window whose pointer to return. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @sa @ref window_userptr - * @sa glfwSetWindowUserPointer - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI void* glfwGetWindowUserPointer(GLFWwindow* window); - -/*! @brief Sets the position callback for the specified window. - * - * This function sets the position callback of the specified window, which is - * called when the window is moved. The callback is provided with the screen - * position of the upper-left corner of the client area of the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_pos - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun); - -/*! @brief Sets the size callback for the specified window. - * - * This function sets the size callback of the specified window, which is - * called when the window is resized. The callback is provided with the size, - * in screen coordinates, of the client area of the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_size - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter and return value. - * - * @ingroup window - */ -GLFWAPI GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun); - -/*! @brief Sets the close callback for the specified window. - * - * This function sets the close callback of the specified window, which is - * called when the user attempts to close the window, for example by clicking - * the close widget in the title bar. - * - * The close flag is set before this callback is called, but you can modify it - * at any time with @ref glfwSetWindowShouldClose. - * - * The close callback is not triggered by @ref glfwDestroyWindow. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @remark @osx Selecting Quit from the application menu will trigger the close - * callback for all windows. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_close - * - * @since Added in version 2.5. - * @glfw3 Added window handle parameter and return value. - * - * @ingroup window - */ -GLFWAPI GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun); - -/*! @brief Sets the refresh callback for the specified window. - * - * This function sets the refresh callback of the specified window, which is - * called when the client area of the window needs to be redrawn, for example - * if the window has been exposed after having been covered by another window. - * - * On compositing window systems such as Aero, Compiz or Aqua, where the window - * contents are saved off-screen, this callback may be called only very - * infrequently or never at all. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_refresh - * - * @since Added in version 2.5. - * @glfw3 Added window handle parameter and return value. - * - * @ingroup window - */ -GLFWAPI GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, GLFWwindowrefreshfun cbfun); - -/*! @brief Sets the focus callback for the specified window. - * - * This function sets the focus callback of the specified window, which is - * called when the window gains or loses input focus. - * - * After the focus callback is called for a window that lost input focus, - * synthetic key and mouse button release events will be generated for all such - * that had been pressed. For more information, see @ref glfwSetKeyCallback - * and @ref glfwSetMouseButtonCallback. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_focus - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun); - -/*! @brief Sets the iconify callback for the specified window. - * - * This function sets the iconification callback of the specified window, which - * is called when the window is iconified or restored. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_iconify - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun); - -/*! @brief Sets the framebuffer resize callback for the specified window. - * - * This function sets the framebuffer resize callback of the specified window, - * which is called when the framebuffer of the specified window is resized. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref window_fbsize - * - * @since Added in version 3.0. - * - * @ingroup window - */ -GLFWAPI GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun); - -/*! @brief Processes all pending events. - * - * This function processes only those events that are already in the event - * queue and then returns immediately. Processing events will cause the window - * and input callbacks associated with those events to be called. - * - * On some platforms, a window move, resize or menu operation will cause event - * processing to block. This is due to how event processing is designed on - * those platforms. You can use the - * [window refresh callback](@ref window_refresh) to redraw the contents of - * your window when necessary during such operations. - * - * On some platforms, certain events are sent directly to the application - * without going through the event queue, causing callbacks to be called - * outside of a call to one of the event processing functions. - * - * Event processing is not required for joystick input to work. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @reentrancy This function must not be called from a callback. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref events - * @sa glfwWaitEvents - * @sa glfwWaitEventsTimeout - * - * @since Added in version 1.0. - * - * @ingroup window - */ -GLFWAPI void glfwPollEvents(void); - -/*! @brief Waits until events are queued and processes them. - * - * This function puts the calling thread to sleep until at least one event is - * available in the event queue. Once one or more events are available, - * it behaves exactly like @ref glfwPollEvents, i.e. the events in the queue - * are processed and the function then returns immediately. Processing events - * will cause the window and input callbacks associated with those events to be - * called. - * - * Since not all events are associated with callbacks, this function may return - * without a callback having been called even if you are monitoring all - * callbacks. - * - * On some platforms, a window move, resize or menu operation will cause event - * processing to block. This is due to how event processing is designed on - * those platforms. You can use the - * [window refresh callback](@ref window_refresh) to redraw the contents of - * your window when necessary during such operations. - * - * On some platforms, certain callbacks may be called outside of a call to one - * of the event processing functions. - * - * If no windows exist, this function returns immediately. For synchronization - * of threads in applications that do not create windows, use your threading - * library of choice. - * - * Event processing is not required for joystick input to work. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @reentrancy This function must not be called from a callback. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref events - * @sa glfwPollEvents - * @sa glfwWaitEventsTimeout - * - * @since Added in version 2.5. - * - * @ingroup window - */ -GLFWAPI void glfwWaitEvents(void); - -/*! @brief Waits with timeout until events are queued and processes them. - * - * This function puts the calling thread to sleep until at least one event is - * available in the event queue, or until the specified timeout is reached. If - * one or more events are available, it behaves exactly like @ref - * glfwPollEvents, i.e. the events in the queue are processed and the function - * then returns immediately. Processing events will cause the window and input - * callbacks associated with those events to be called. - * - * The timeout value must be a positive finite number. - * - * Since not all events are associated with callbacks, this function may return - * without a callback having been called even if you are monitoring all - * callbacks. - * - * On some platforms, a window move, resize or menu operation will cause event - * processing to block. This is due to how event processing is designed on - * those platforms. You can use the - * [window refresh callback](@ref window_refresh) to redraw the contents of - * your window when necessary during such operations. - * - * On some platforms, certain callbacks may be called outside of a call to one - * of the event processing functions. - * - * If no windows exist, this function returns immediately. For synchronization - * of threads in applications that do not create windows, use your threading - * library of choice. - * - * Event processing is not required for joystick input to work. - * - * @param[in] timeout The maximum amount of time, in seconds, to wait. - * - * @reentrancy This function must not be called from a callback. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref events - * @sa glfwPollEvents - * @sa glfwWaitEvents - * - * @since Added in version 3.2. - * - * @ingroup window - */ -GLFWAPI void glfwWaitEventsTimeout(double timeout); - -/*! @brief Posts an empty event to the event queue. - * - * This function posts an empty event from the current thread to the event - * queue, causing @ref glfwWaitEvents to return. - * - * If no windows exist, this function returns immediately. For synchronization - * of threads in applications that do not create windows, use your threading - * library of choice. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref events - * @sa glfwWaitEvents - * - * @since Added in version 3.1. - * - * @ingroup window - */ -GLFWAPI void glfwPostEmptyEvent(void); - -/*! @brief Returns the value of an input option for the specified window. - * - * This function returns the value of an input option for the specified window. - * The mode must be one of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or - * `GLFW_STICKY_MOUSE_BUTTONS`. - * - * @param[in] window The window to query. - * @param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or - * `GLFW_STICKY_MOUSE_BUTTONS`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_INVALID_ENUM. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa glfwSetInputMode - * - * @since Added in version 3.0. - * - * @ingroup input - */ -GLFWAPI int glfwGetInputMode(GLFWwindow* window, int mode); - -/*! @brief Sets an input option for the specified window. - * - * This function sets an input mode option for the specified window. The mode - * must be one of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or - * `GLFW_STICKY_MOUSE_BUTTONS`. - * - * If the mode is `GLFW_CURSOR`, the value must be one of the following cursor - * modes: - * - `GLFW_CURSOR_NORMAL` makes the cursor visible and behaving normally. - * - `GLFW_CURSOR_HIDDEN` makes the cursor invisible when it is over the client - * area of the window but does not restrict the cursor from leaving. - * - `GLFW_CURSOR_DISABLED` hides and grabs the cursor, providing virtual - * and unlimited cursor movement. This is useful for implementing for - * example 3D camera controls. - * - * If the mode is `GLFW_STICKY_KEYS`, the value must be either `GLFW_TRUE` to - * enable sticky keys, or `GLFW_FALSE` to disable it. If sticky keys are - * enabled, a key press will ensure that @ref glfwGetKey returns `GLFW_PRESS` - * the next time it is called even if the key had been released before the - * call. This is useful when you are only interested in whether keys have been - * pressed but not when or in which order. - * - * If the mode is `GLFW_STICKY_MOUSE_BUTTONS`, the value must be either - * `GLFW_TRUE` to enable sticky mouse buttons, or `GLFW_FALSE` to disable it. - * If sticky mouse buttons are enabled, a mouse button press will ensure that - * @ref glfwGetMouseButton returns `GLFW_PRESS` the next time it is called even - * if the mouse button had been released before the call. This is useful when - * you are only interested in whether mouse buttons have been pressed but not - * when or in which order. - * - * @param[in] window The window whose input mode to set. - * @param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or - * `GLFW_STICKY_MOUSE_BUTTONS`. - * @param[in] value The new value of the specified input mode. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_ENUM and @ref GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa glfwGetInputMode - * - * @since Added in version 3.0. Replaces `glfwEnable` and `glfwDisable`. - * - * @ingroup input - */ -GLFWAPI void glfwSetInputMode(GLFWwindow* window, int mode, int value); - -/*! @brief Returns the localized name of the specified printable key. - * - * This function returns the localized name of the specified printable key. - * This is intended for displaying key bindings to the user. - * - * If the key is `GLFW_KEY_UNKNOWN`, the scancode is used instead, otherwise - * the scancode is ignored. If a non-printable key or (if the key is - * `GLFW_KEY_UNKNOWN`) a scancode that maps to a non-printable key is - * specified, this function returns `NULL`. - * - * This behavior allows you to pass in the arguments passed to the - * [key callback](@ref input_key) without modification. - * - * The printable keys are: - * - `GLFW_KEY_APOSTROPHE` - * - `GLFW_KEY_COMMA` - * - `GLFW_KEY_MINUS` - * - `GLFW_KEY_PERIOD` - * - `GLFW_KEY_SLASH` - * - `GLFW_KEY_SEMICOLON` - * - `GLFW_KEY_EQUAL` - * - `GLFW_KEY_LEFT_BRACKET` - * - `GLFW_KEY_RIGHT_BRACKET` - * - `GLFW_KEY_BACKSLASH` - * - `GLFW_KEY_WORLD_1` - * - `GLFW_KEY_WORLD_2` - * - `GLFW_KEY_0` to `GLFW_KEY_9` - * - `GLFW_KEY_A` to `GLFW_KEY_Z` - * - `GLFW_KEY_KP_0` to `GLFW_KEY_KP_9` - * - `GLFW_KEY_KP_DECIMAL` - * - `GLFW_KEY_KP_DIVIDE` - * - `GLFW_KEY_KP_MULTIPLY` - * - `GLFW_KEY_KP_SUBTRACT` - * - `GLFW_KEY_KP_ADD` - * - `GLFW_KEY_KP_EQUAL` - * - * @param[in] key The key to query, or `GLFW_KEY_UNKNOWN`. - * @param[in] scancode The scancode of the key to query. - * @return The localized name of the key, or `NULL`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The returned string is allocated and freed by GLFW. You - * should not free it yourself. It is valid until the next call to @ref - * glfwGetKeyName, or until the library is terminated. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref input_key_name - * - * @since Added in version 3.2. - * - * @ingroup input - */ -GLFWAPI const char* glfwGetKeyName(int key, int scancode); - -/*! @brief Returns the last reported state of a keyboard key for the specified - * window. - * - * This function returns the last state reported for the specified key to the - * specified window. The returned state is one of `GLFW_PRESS` or - * `GLFW_RELEASE`. The higher-level action `GLFW_REPEAT` is only reported to - * the key callback. - * - * If the `GLFW_STICKY_KEYS` input mode is enabled, this function returns - * `GLFW_PRESS` the first time you call it for a key that was pressed, even if - * that key has already been released. - * - * The key functions deal with physical keys, with [key tokens](@ref keys) - * named after their use on the standard US keyboard layout. If you want to - * input text, use the Unicode character callback instead. - * - * The [modifier key bit masks](@ref mods) are not key tokens and cannot be - * used with this function. - * - * __Do not use this function__ to implement [text input](@ref input_char). - * - * @param[in] window The desired window. - * @param[in] key The desired [keyboard key](@ref keys). `GLFW_KEY_UNKNOWN` is - * not a valid key for this function. - * @return One of `GLFW_PRESS` or `GLFW_RELEASE`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_INVALID_ENUM. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref input_key - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter. - * - * @ingroup input - */ -GLFWAPI int glfwGetKey(GLFWwindow* window, int key); - -/*! @brief Returns the last reported state of a mouse button for the specified - * window. - * - * This function returns the last state reported for the specified mouse button - * to the specified window. The returned state is one of `GLFW_PRESS` or - * `GLFW_RELEASE`. - * - * If the `GLFW_STICKY_MOUSE_BUTTONS` input mode is enabled, this function - * `GLFW_PRESS` the first time you call it for a mouse button that was pressed, - * even if that mouse button has already been released. - * - * @param[in] window The desired window. - * @param[in] button The desired [mouse button](@ref buttons). - * @return One of `GLFW_PRESS` or `GLFW_RELEASE`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_INVALID_ENUM. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref input_mouse_button - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter. - * - * @ingroup input - */ -GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); - -/*! @brief Retrieves the position of the cursor relative to the client area of - * the window. - * - * This function returns the position of the cursor, in screen coordinates, - * relative to the upper-left corner of the client area of the specified - * window. - * - * If the cursor is disabled (with `GLFW_CURSOR_DISABLED`) then the cursor - * position is unbounded and limited only by the minimum and maximum values of - * a `double`. - * - * The coordinate can be converted to their integer equivalents with the - * `floor` function. Casting directly to an integer type works for positive - * coordinates, but fails for negative ones. - * - * Any or all of the position arguments may be `NULL`. If an error occurs, all - * non-`NULL` position arguments will be set to zero. - * - * @param[in] window The desired window. - * @param[out] xpos Where to store the cursor x-coordinate, relative to the - * left edge of the client area, or `NULL`. - * @param[out] ypos Where to store the cursor y-coordinate, relative to the to - * top edge of the client area, or `NULL`. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref cursor_pos - * @sa glfwSetCursorPos - * - * @since Added in version 3.0. Replaces `glfwGetMousePos`. - * - * @ingroup input - */ -GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); - -/*! @brief Sets the position of the cursor, relative to the client area of the - * window. - * - * This function sets the position, in screen coordinates, of the cursor - * relative to the upper-left corner of the client area of the specified - * window. The window must have input focus. If the window does not have - * input focus when this function is called, it fails silently. - * - * __Do not use this function__ to implement things like camera controls. GLFW - * already provides the `GLFW_CURSOR_DISABLED` cursor mode that hides the - * cursor, transparently re-centers it and provides unconstrained cursor - * motion. See @ref glfwSetInputMode for more information. - * - * If the cursor mode is `GLFW_CURSOR_DISABLED` then the cursor position is - * unconstrained and limited only by the minimum and maximum values of - * a `double`. - * - * @param[in] window The desired window. - * @param[in] xpos The desired x-coordinate, relative to the left edge of the - * client area. - * @param[in] ypos The desired y-coordinate, relative to the top edge of the - * client area. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref cursor_pos - * @sa glfwGetCursorPos - * - * @since Added in version 3.0. Replaces `glfwSetMousePos`. - * - * @ingroup input - */ -GLFWAPI void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos); - -/*! @brief Creates a custom cursor. - * - * Creates a new custom cursor image that can be set for a window with @ref - * glfwSetCursor. The cursor can be destroyed with @ref glfwDestroyCursor. - * Any remaining cursors are destroyed by @ref glfwTerminate. - * - * The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight - * bits per channel. They are arranged canonically as packed sequential rows, - * starting from the top-left corner. - * - * The cursor hotspot is specified in pixels, relative to the upper-left corner - * of the cursor image. Like all other coordinate systems in GLFW, the X-axis - * points to the right and the Y-axis points down. - * - * @param[in] image The desired cursor image. - * @param[in] xhot The desired x-coordinate, in pixels, of the cursor hotspot. - * @param[in] yhot The desired y-coordinate, in pixels, of the cursor hotspot. - * @return The handle of the created cursor, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The specified image data is copied before this function - * returns. - * - * @reentrancy This function must not be called from a callback. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref cursor_object - * @sa glfwDestroyCursor - * @sa glfwCreateStandardCursor - * - * @since Added in version 3.1. - * - * @ingroup input - */ -GLFWAPI GLFWcursor* glfwCreateCursor(const GLFWimage* image, int xhot, int yhot); - -/*! @brief Creates a cursor with a standard shape. - * - * Returns a cursor with a [standard shape](@ref shapes), that can be set for - * a window with @ref glfwSetCursor. - * - * @param[in] shape One of the [standard shapes](@ref shapes). - * @return A new cursor ready to use or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_ENUM and @ref GLFW_PLATFORM_ERROR. - * - * @reentrancy This function must not be called from a callback. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref cursor_object - * @sa glfwCreateCursor - * - * @since Added in version 3.1. - * - * @ingroup input - */ -GLFWAPI GLFWcursor* glfwCreateStandardCursor(int shape); - -/*! @brief Destroys a cursor. - * - * This function destroys a cursor previously created with @ref - * glfwCreateCursor. Any remaining cursors will be destroyed by @ref - * glfwTerminate. - * - * @param[in] cursor The cursor object to destroy. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @reentrancy This function must not be called from a callback. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref cursor_object - * @sa glfwCreateCursor - * - * @since Added in version 3.1. - * - * @ingroup input - */ -GLFWAPI void glfwDestroyCursor(GLFWcursor* cursor); - -/*! @brief Sets the cursor for the window. - * - * This function sets the cursor image to be used when the cursor is over the - * client area of the specified window. The set cursor will only be visible - * when the [cursor mode](@ref cursor_mode) of the window is - * `GLFW_CURSOR_NORMAL`. - * - * On some platforms, the set cursor may not be visible unless the window also - * has input focus. - * - * @param[in] window The window to set the cursor for. - * @param[in] cursor The cursor to set, or `NULL` to switch back to the default - * arrow cursor. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref cursor_object - * - * @since Added in version 3.1. - * - * @ingroup input - */ -GLFWAPI void glfwSetCursor(GLFWwindow* window, GLFWcursor* cursor); - -/*! @brief Sets the key callback. - * - * This function sets the key callback of the specified window, which is called - * when a key is pressed, repeated or released. - * - * The key functions deal with physical keys, with layout independent - * [key tokens](@ref keys) named after their values in the standard US keyboard - * layout. If you want to input text, use the - * [character callback](@ref glfwSetCharCallback) instead. - * - * When a window loses input focus, it will generate synthetic key release - * events for all pressed keys. You can tell these events from user-generated - * events by the fact that the synthetic ones are generated after the focus - * loss event has been processed, i.e. after the - * [window focus callback](@ref glfwSetWindowFocusCallback) has been called. - * - * The scancode of a key is specific to that platform or sometimes even to that - * machine. Scancodes are intended to allow users to bind keys that don't have - * a GLFW key token. Such keys have `key` set to `GLFW_KEY_UNKNOWN`, their - * state is not saved and so it cannot be queried with @ref glfwGetKey. - * - * Sometimes GLFW needs to generate synthetic key events, in which case the - * scancode may be zero. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new key callback, or `NULL` to remove the currently - * set callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref input_key - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter and return value. - * - * @ingroup input - */ -GLFWAPI GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun); - -/*! @brief Sets the Unicode character callback. - * - * This function sets the character callback of the specified window, which is - * called when a Unicode character is input. - * - * The character callback is intended for Unicode text input. As it deals with - * characters, it is keyboard layout dependent, whereas the - * [key callback](@ref glfwSetKeyCallback) is not. Characters do not map 1:1 - * to physical keys, as a key may produce zero, one or more characters. If you - * want to know whether a specific physical key was pressed or released, see - * the key callback instead. - * - * The character callback behaves as system text input normally does and will - * not be called if modifier keys are held down that would prevent normal text - * input on that platform, for example a Super (Command) key on OS X or Alt key - * on Windows. There is a - * [character with modifiers callback](@ref glfwSetCharModsCallback) that - * receives these events. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref input_char - * - * @since Added in version 2.4. - * @glfw3 Added window handle parameter and return value. - * - * @ingroup input - */ -GLFWAPI GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun); - -/*! @brief Sets the Unicode character with modifiers callback. - * - * This function sets the character with modifiers callback of the specified - * window, which is called when a Unicode character is input regardless of what - * modifier keys are used. - * - * The character with modifiers callback is intended for implementing custom - * Unicode character input. For regular Unicode text input, see the - * [character callback](@ref glfwSetCharCallback). Like the character - * callback, the character with modifiers callback deals with characters and is - * keyboard layout dependent. Characters do not map 1:1 to physical keys, as - * a key may produce zero, one or more characters. If you want to know whether - * a specific physical key was pressed or released, see the - * [key callback](@ref glfwSetKeyCallback) instead. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref input_char - * - * @since Added in version 3.1. - * - * @ingroup input - */ -GLFWAPI GLFWcharmodsfun glfwSetCharModsCallback(GLFWwindow* window, GLFWcharmodsfun cbfun); - -/*! @brief Sets the mouse button callback. - * - * This function sets the mouse button callback of the specified window, which - * is called when a mouse button is pressed or released. - * - * When a window loses input focus, it will generate synthetic mouse button - * release events for all pressed mouse buttons. You can tell these events - * from user-generated events by the fact that the synthetic ones are generated - * after the focus loss event has been processed, i.e. after the - * [window focus callback](@ref glfwSetWindowFocusCallback) has been called. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref input_mouse_button - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter and return value. - * - * @ingroup input - */ -GLFWAPI GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun); - -/*! @brief Sets the cursor position callback. - * - * This function sets the cursor position callback of the specified window, - * which is called when the cursor is moved. The callback is provided with the - * position, in screen coordinates, relative to the upper-left corner of the - * client area of the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref cursor_pos - * - * @since Added in version 3.0. Replaces `glfwSetMousePosCallback`. - * - * @ingroup input - */ -GLFWAPI GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun); - -/*! @brief Sets the cursor enter/exit callback. - * - * This function sets the cursor boundary crossing callback of the specified - * window, which is called when the cursor enters or leaves the client area of - * the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref cursor_enter - * - * @since Added in version 3.0. - * - * @ingroup input - */ -GLFWAPI GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun cbfun); - -/*! @brief Sets the scroll callback. - * - * This function sets the scroll callback of the specified window, which is - * called when a scrolling device is used, such as a mouse wheel or scrolling - * area of a touchpad. - * - * The scroll callback receives all scrolling input, like that from a mouse - * wheel or a touchpad scrolling area. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new scroll callback, or `NULL` to remove the currently - * set callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref scrolling - * - * @since Added in version 3.0. Replaces `glfwSetMouseWheelCallback`. - * - * @ingroup input - */ -GLFWAPI GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun); - -/*! @brief Sets the file drop callback. - * - * This function sets the file drop callback of the specified window, which is - * called when one or more dragged files are dropped on the window. - * - * Because the path array and its strings may have been generated specifically - * for that event, they are not guaranteed to be valid after the callback has - * returned. If you wish to use them after the callback returns, you need to - * make a deep copy. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new file drop callback, or `NULL` to remove the - * currently set callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref path_drop - * - * @since Added in version 3.1. - * - * @ingroup input - */ -GLFWAPI GLFWdropfun glfwSetDropCallback(GLFWwindow* window, GLFWdropfun cbfun); - -/*! @brief Returns whether the specified joystick is present. - * - * This function returns whether the specified joystick is present. - * - * @param[in] joy The [joystick](@ref joysticks) to query. - * @return `GLFW_TRUE` if the joystick is present, or `GLFW_FALSE` otherwise. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_ENUM and @ref GLFW_PLATFORM_ERROR. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref joystick - * - * @since Added in version 3.0. Replaces `glfwGetJoystickParam`. - * - * @ingroup input - */ -GLFWAPI int glfwJoystickPresent(int joy); - -/*! @brief Returns the values of all axes of the specified joystick. - * - * This function returns the values of all axes of the specified joystick. - * Each element in the array is a value between -1.0 and 1.0. - * - * Querying a joystick slot with no device present is not an error, but will - * cause this function to return `NULL`. Call @ref glfwJoystickPresent to - * check device presence. - * - * @param[in] joy The [joystick](@ref joysticks) to query. - * @param[out] count Where to store the number of axis values in the returned - * array. This is set to zero if an error occurred. - * @return An array of axis values, or `NULL` if the joystick is not present. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_ENUM and @ref GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The returned array is allocated and freed by GLFW. You - * should not free it yourself. It is valid until the specified joystick is - * disconnected, this function is called again for that joystick or the library - * is terminated. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref joystick_axis - * - * @since Added in version 3.0. Replaces `glfwGetJoystickPos`. - * - * @ingroup input - */ -GLFWAPI const float* glfwGetJoystickAxes(int joy, int* count); - -/*! @brief Returns the state of all buttons of the specified joystick. - * - * This function returns the state of all buttons of the specified joystick. - * Each element in the array is either `GLFW_PRESS` or `GLFW_RELEASE`. - * - * Querying a joystick slot with no device present is not an error, but will - * cause this function to return `NULL`. Call @ref glfwJoystickPresent to - * check device presence. - * - * @param[in] joy The [joystick](@ref joysticks) to query. - * @param[out] count Where to store the number of button states in the returned - * array. This is set to zero if an error occurred. - * @return An array of button states, or `NULL` if the joystick is not present. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_ENUM and @ref GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The returned array is allocated and freed by GLFW. You - * should not free it yourself. It is valid until the specified joystick is - * disconnected, this function is called again for that joystick or the library - * is terminated. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref joystick_button - * - * @since Added in version 2.2. - * @glfw3 Changed to return a dynamic array. - * - * @ingroup input - */ -GLFWAPI const unsigned char* glfwGetJoystickButtons(int joy, int* count); - -/*! @brief Returns the name of the specified joystick. - * - * This function returns the name, encoded as UTF-8, of the specified joystick. - * The returned string is allocated and freed by GLFW. You should not free it - * yourself. - * - * Querying a joystick slot with no device present is not an error, but will - * cause this function to return `NULL`. Call @ref glfwJoystickPresent to - * check device presence. - * - * @param[in] joy The [joystick](@ref joysticks) to query. - * @return The UTF-8 encoded name of the joystick, or `NULL` if the joystick - * is not present. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_ENUM and @ref GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The returned string is allocated and freed by GLFW. You - * should not free it yourself. It is valid until the specified joystick is - * disconnected, this function is called again for that joystick or the library - * is terminated. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref joystick_name - * - * @since Added in version 3.0. - * - * @ingroup input - */ -GLFWAPI const char* glfwGetJoystickName(int joy); - -/*! @brief Sets the joystick configuration callback. - * - * This function sets the joystick configuration callback, or removes the - * currently set callback. This is called when a joystick is connected to or - * disconnected from the system. - * - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or the - * library had not been [initialized](@ref intro_init). - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref joystick_event - * - * @since Added in version 3.2. - * - * @ingroup input - */ -GLFWAPI GLFWjoystickfun glfwSetJoystickCallback(GLFWjoystickfun cbfun); - -/*! @brief Sets the clipboard to the specified string. - * - * This function sets the system clipboard to the specified, UTF-8 encoded - * string. - * - * @param[in] window The window that will own the clipboard contents. - * @param[in] string A UTF-8 encoded string. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The specified string is copied before this function - * returns. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref clipboard - * @sa glfwGetClipboardString - * - * @since Added in version 3.0. - * - * @ingroup input - */ -GLFWAPI void glfwSetClipboardString(GLFWwindow* window, const char* string); - -/*! @brief Returns the contents of the clipboard as a string. - * - * This function returns the contents of the system clipboard, if it contains - * or is convertible to a UTF-8 encoded string. If the clipboard is empty or - * if its contents cannot be converted, `NULL` is returned and a @ref - * GLFW_FORMAT_UNAVAILABLE error is generated. - * - * @param[in] window The window that will request the clipboard contents. - * @return The contents of the clipboard as a UTF-8 encoded string, or `NULL` - * if an [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. - * - * @pointer_lifetime The returned string is allocated and freed by GLFW. You - * should not free it yourself. It is valid until the next call to @ref - * glfwGetClipboardString or @ref glfwSetClipboardString, or until the library - * is terminated. - * - * @thread_safety This function must only be called from the main thread. - * - * @sa @ref clipboard - * @sa glfwSetClipboardString - * - * @since Added in version 3.0. - * - * @ingroup input - */ -GLFWAPI const char* glfwGetClipboardString(GLFWwindow* window); - -/*! @brief Returns the value of the GLFW timer. - * - * This function returns the value of the GLFW timer. Unless the timer has - * been set using @ref glfwSetTime, the timer measures time elapsed since GLFW - * was initialized. - * - * The resolution of the timer is system dependent, but is usually on the order - * of a few micro- or nanoseconds. It uses the highest-resolution monotonic - * time source on each supported platform. - * - * @return The current value, in seconds, or zero if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function may be called from any thread. Reading and - * writing of the internal timer offset is not atomic, so it needs to be - * externally synchronized with calls to @ref glfwSetTime. - * - * @sa @ref time - * - * @since Added in version 1.0. - * - * @ingroup input - */ -GLFWAPI double glfwGetTime(void); - -/*! @brief Sets the GLFW timer. - * - * This function sets the value of the GLFW timer. It then continues to count - * up from that value. The value must be a positive finite number less than - * or equal to 18446744073.0, which is approximately 584.5 years. - * - * @param[in] time The new value, in seconds. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_INVALID_VALUE. - * - * @remark The upper limit of the timer is calculated as - * floor((264 - 1) / 109) and is due to implementations - * storing nanoseconds in 64 bits. The limit may be increased in the future. - * - * @thread_safety This function may be called from any thread. Reading and - * writing of the internal timer offset is not atomic, so it needs to be - * externally synchronized with calls to @ref glfwGetTime. - * - * @sa @ref time - * - * @since Added in version 2.2. - * - * @ingroup input - */ -GLFWAPI void glfwSetTime(double time); - -/*! @brief Returns the current value of the raw timer. - * - * This function returns the current value of the raw timer, measured in - * 1 / frequency seconds. To get the frequency, call @ref - * glfwGetTimerFrequency. - * - * @return The value of the timer, or zero if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref time - * @sa glfwGetTimerFrequency - * - * @since Added in version 3.2. - * - * @ingroup input - */ -GLFWAPI uint64_t glfwGetTimerValue(void); - -/*! @brief Returns the frequency, in Hz, of the raw timer. - * - * This function returns the frequency, in Hz, of the raw timer. - * - * @return The frequency of the timer, in Hz, or zero if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref time - * @sa glfwGetTimerValue - * - * @since Added in version 3.2. - * - * @ingroup input - */ -GLFWAPI uint64_t glfwGetTimerFrequency(void); - -/*! @brief Makes the context of the specified window current for the calling - * thread. - * - * This function makes the OpenGL or OpenGL ES context of the specified window - * current on the calling thread. A context can only be made current on - * a single thread at a time and each thread can have only a single current - * context at a time. - * - * By default, making a context non-current implicitly forces a pipeline flush. - * On machines that support `GL_KHR_context_flush_control`, you can control - * whether a context performs this flush by setting the - * [GLFW_CONTEXT_RELEASE_BEHAVIOR](@ref window_hints_ctx) window hint. - * - * The specified window must have an OpenGL or OpenGL ES context. Specifying - * a window without a context will generate a @ref GLFW_NO_WINDOW_CONTEXT - * error. - * - * @param[in] window The window whose context to make current, or `NULL` to - * detach the current context. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_NO_WINDOW_CONTEXT and @ref GLFW_PLATFORM_ERROR. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref context_current - * @sa glfwGetCurrentContext - * - * @since Added in version 3.0. - * - * @ingroup context - */ -GLFWAPI void glfwMakeContextCurrent(GLFWwindow* window); - -/*! @brief Returns the window whose context is current on the calling thread. - * - * This function returns the window whose OpenGL or OpenGL ES context is - * current on the calling thread. - * - * @return The window whose context is current, or `NULL` if no window's - * context is current. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref context_current - * @sa glfwMakeContextCurrent - * - * @since Added in version 3.0. - * - * @ingroup context - */ -GLFWAPI GLFWwindow* glfwGetCurrentContext(void); - -/*! @brief Swaps the front and back buffers of the specified window. - * - * This function swaps the front and back buffers of the specified window when - * rendering with OpenGL or OpenGL ES. If the swap interval is greater than - * zero, the GPU driver waits the specified number of screen updates before - * swapping the buffers. - * - * The specified window must have an OpenGL or OpenGL ES context. Specifying - * a window without a context will generate a @ref GLFW_NO_WINDOW_CONTEXT - * error. - * - * This function does not apply to Vulkan. If you are rendering with Vulkan, - * see `vkQueuePresentKHR` instead. - * - * @param[in] window The window whose buffers to swap. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_NO_WINDOW_CONTEXT and @ref GLFW_PLATFORM_ERROR. - * - * @remark __EGL:__ The context of the specified window must be current on the - * calling thread. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref buffer_swap - * @sa glfwSwapInterval - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -GLFWAPI void glfwSwapBuffers(GLFWwindow* window); - -/*! @brief Sets the swap interval for the current context. - * - * This function sets the swap interval for the current OpenGL or OpenGL ES - * context, i.e. the number of screen updates to wait from the time @ref - * glfwSwapBuffers was called before swapping the buffers and returning. This - * is sometimes called _vertical synchronization_, _vertical retrace - * synchronization_ or just _vsync_. - * - * Contexts that support either of the `WGL_EXT_swap_control_tear` and - * `GLX_EXT_swap_control_tear` extensions also accept negative swap intervals, - * which allow the driver to swap even if a frame arrives a little bit late. - * You can check for the presence of these extensions using @ref - * glfwExtensionSupported. For more information about swap tearing, see the - * extension specifications. - * - * A context must be current on the calling thread. Calling this function - * without a current context will cause a @ref GLFW_NO_CURRENT_CONTEXT error. - * - * This function does not apply to Vulkan. If you are rendering with Vulkan, - * see the present mode of your swapchain instead. - * - * @param[in] interval The minimum number of screen updates to wait for - * until the buffers are swapped by @ref glfwSwapBuffers. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_NO_CURRENT_CONTEXT and @ref GLFW_PLATFORM_ERROR. - * - * @remark This function is not called during context creation, leaving the - * swap interval set to whatever is the default on that platform. This is done - * because some swap interval extensions used by GLFW do not allow the swap - * interval to be reset to zero once it has been set to a non-zero value. - * - * @remark Some GPU drivers do not honor the requested swap interval, either - * because of a user setting that overrides the application's request or due to - * bugs in the driver. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref buffer_swap - * @sa glfwSwapBuffers - * - * @since Added in version 1.0. - * - * @ingroup context - */ -GLFWAPI void glfwSwapInterval(int interval); - -/*! @brief Returns whether the specified extension is available. - * - * This function returns whether the specified - * [API extension](@ref context_glext) is supported by the current OpenGL or - * OpenGL ES context. It searches both for client API extension and context - * creation API extensions. - * - * A context must be current on the calling thread. Calling this function - * without a current context will cause a @ref GLFW_NO_CURRENT_CONTEXT error. - * - * As this functions retrieves and searches one or more extension strings each - * call, it is recommended that you cache its results if it is going to be used - * frequently. The extension strings will not change during the lifetime of - * a context, so there is no danger in doing this. - * - * This function does not apply to Vulkan. If you are using Vulkan, see @ref - * glfwGetRequiredInstanceExtensions, `vkEnumerateInstanceExtensionProperties` - * and `vkEnumerateDeviceExtensionProperties` instead. - * - * @param[in] extension The ASCII encoded name of the extension. - * @return `GLFW_TRUE` if the extension is available, or `GLFW_FALSE` - * otherwise. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_NO_CURRENT_CONTEXT, @ref GLFW_INVALID_VALUE and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref context_glext - * @sa glfwGetProcAddress - * - * @since Added in version 1.0. - * - * @ingroup context - */ -GLFWAPI int glfwExtensionSupported(const char* extension); - -/*! @brief Returns the address of the specified function for the current - * context. - * - * This function returns the address of the specified OpenGL or OpenGL ES - * [core or extension function](@ref context_glext), if it is supported - * by the current context. - * - * A context must be current on the calling thread. Calling this function - * without a current context will cause a @ref GLFW_NO_CURRENT_CONTEXT error. - * - * This function does not apply to Vulkan. If you are rendering with Vulkan, - * see @ref glfwGetInstanceProcAddress, `vkGetInstanceProcAddr` and - * `vkGetDeviceProcAddr` instead. - * - * @param[in] procname The ASCII encoded name of the function. - * @return The address of the function, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_NO_CURRENT_CONTEXT and @ref GLFW_PLATFORM_ERROR. - * - * @remark The address of a given function is not guaranteed to be the same - * between contexts. - * - * @remark This function may return a non-`NULL` address despite the - * associated version or extension not being available. Always check the - * context version or extension string first. - * - * @pointer_lifetime The returned function pointer is valid until the context - * is destroyed or the library is terminated. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref context_glext - * @sa glfwExtensionSupported - * - * @since Added in version 1.0. - * - * @ingroup context - */ -GLFWAPI GLFWglproc glfwGetProcAddress(const char* procname); - -/*! @brief Returns whether the Vulkan loader has been found. - * - * This function returns whether the Vulkan loader has been found. This check - * is performed by @ref glfwInit. - * - * The availability of a Vulkan loader does not by itself guarantee that window - * surface creation or even device creation is possible. Call @ref - * glfwGetRequiredInstanceExtensions to check whether the extensions necessary - * for Vulkan surface creation are available and @ref - * glfwGetPhysicalDevicePresentationSupport to check whether a queue family of - * a physical device supports image presentation. - * - * @return `GLFW_TRUE` if Vulkan is available, or `GLFW_FALSE` otherwise. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref vulkan_support - * - * @since Added in version 3.2. - * - * @ingroup vulkan - */ -GLFWAPI int glfwVulkanSupported(void); - -/*! @brief Returns the Vulkan instance extensions required by GLFW. - * - * This function returns an array of names of Vulkan instance extensions required - * by GLFW for creating Vulkan surfaces for GLFW windows. If successful, the - * list will always contains `VK_KHR_surface`, so if you don't require any - * additional extensions you can pass this list directly to the - * `VkInstanceCreateInfo` struct. - * - * If Vulkan is not available on the machine, this function returns `NULL` and - * generates a @ref GLFW_API_UNAVAILABLE error. Call @ref glfwVulkanSupported - * to check whether Vulkan is available. - * - * If Vulkan is available but no set of extensions allowing window surface - * creation was found, this function returns `NULL`. You may still use Vulkan - * for off-screen rendering and compute work. - * - * @param[out] count Where to store the number of extensions in the returned - * array. This is set to zero if an error occurred. - * @return An array of ASCII encoded extension names, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_API_UNAVAILABLE. - * - * @remarks Additional extensions may be required by future versions of GLFW. - * You should check if any extensions you wish to enable are already in the - * returned array, as it is an error to specify an extension more than once in - * the `VkInstanceCreateInfo` struct. - * - * @pointer_lifetime The returned array is allocated and freed by GLFW. You - * should not free it yourself. It is guaranteed to be valid only until the - * library is terminated. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref vulkan_ext - * @sa glfwCreateWindowSurface - * - * @since Added in version 3.2. - * - * @ingroup vulkan - */ -GLFWAPI const char** glfwGetRequiredInstanceExtensions(uint32_t* count); - -#if defined(VK_VERSION_1_0) - -/*! @brief Returns the address of the specified Vulkan instance function. - * - * This function returns the address of the specified Vulkan core or extension - * function for the specified instance. If instance is set to `NULL` it can - * return any function exported from the Vulkan loader, including at least the - * following functions: - * - * - `vkEnumerateInstanceExtensionProperties` - * - `vkEnumerateInstanceLayerProperties` - * - `vkCreateInstance` - * - `vkGetInstanceProcAddr` - * - * If Vulkan is not available on the machine, this function returns `NULL` and - * generates a @ref GLFW_API_UNAVAILABLE error. Call @ref glfwVulkanSupported - * to check whether Vulkan is available. - * - * This function is equivalent to calling `vkGetInstanceProcAddr` with - * a platform-specific query of the Vulkan loader as a fallback. - * - * @param[in] instance The Vulkan instance to query, or `NULL` to retrieve - * functions related to instance creation. - * @param[in] procname The ASCII encoded name of the function. - * @return The address of the function, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_API_UNAVAILABLE. - * - * @pointer_lifetime The returned function pointer is valid until the library - * is terminated. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref vulkan_proc - * - * @since Added in version 3.2. - * - * @ingroup vulkan - */ -GLFWAPI GLFWvkproc glfwGetInstanceProcAddress(VkInstance instance, const char* procname); - -/*! @brief Returns whether the specified queue family can present images. - * - * This function returns whether the specified queue family of the specified - * physical device supports presentation to the platform GLFW was built for. - * - * If Vulkan or the required window surface creation instance extensions are - * not available on the machine, or if the specified instance was not created - * with the required extensions, this function returns `GLFW_FALSE` and - * generates a @ref GLFW_API_UNAVAILABLE error. Call @ref glfwVulkanSupported - * to check whether Vulkan is available and @ref - * glfwGetRequiredInstanceExtensions to check what instance extensions are - * required. - * - * @param[in] instance The instance that the physical device belongs to. - * @param[in] device The physical device that the queue family belongs to. - * @param[in] queuefamily The index of the queue family to query. - * @return `GLFW_TRUE` if the queue family supports presentation, or - * `GLFW_FALSE` otherwise. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_API_UNAVAILABLE and @ref GLFW_PLATFORM_ERROR. - * - * @thread_safety This function may be called from any thread. For - * synchronization details of Vulkan objects, see the Vulkan specification. - * - * @sa @ref vulkan_present - * - * @since Added in version 3.2. - * - * @ingroup vulkan - */ -GLFWAPI int glfwGetPhysicalDevicePresentationSupport(VkInstance instance, VkPhysicalDevice device, uint32_t queuefamily); - -/*! @brief Creates a Vulkan surface for the specified window. - * - * This function creates a Vulkan surface for the specified window. - * - * If the Vulkan loader was not found at initialization, this function returns - * `VK_ERROR_INITIALIZATION_FAILED` and generates a @ref GLFW_API_UNAVAILABLE - * error. Call @ref glfwVulkanSupported to check whether the Vulkan loader was - * found. - * - * If the required window surface creation instance extensions are not - * available or if the specified instance was not created with these extensions - * enabled, this function returns `VK_ERROR_EXTENSION_NOT_PRESENT` and - * generates a @ref GLFW_API_UNAVAILABLE error. Call @ref - * glfwGetRequiredInstanceExtensions to check what instance extensions are - * required. - * - * The window surface must be destroyed before the specified Vulkan instance. - * It is the responsibility of the caller to destroy the window surface. GLFW - * does not destroy it for you. Call `vkDestroySurfaceKHR` to destroy the - * surface. - * - * @param[in] instance The Vulkan instance to create the surface in. - * @param[in] window The window to create the surface for. - * @param[in] allocator The allocator to use, or `NULL` to use the default - * allocator. - * @param[out] surface Where to store the handle of the surface. This is set - * to `VK_NULL_HANDLE` if an error occurred. - * @return `VK_SUCCESS` if successful, or a Vulkan error code if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_API_UNAVAILABLE and @ref GLFW_PLATFORM_ERROR. - * - * @remarks If an error occurs before the creation call is made, GLFW returns - * the Vulkan error code most appropriate for the error. Appropriate use of - * @ref glfwVulkanSupported and @ref glfwGetRequiredInstanceExtensions should - * eliminate almost all occurrences of these errors. - * - * @thread_safety This function may be called from any thread. For - * synchronization details of Vulkan objects, see the Vulkan specification. - * - * @sa @ref vulkan_surface - * @sa glfwGetRequiredInstanceExtensions - * - * @since Added in version 3.2. - * - * @ingroup vulkan - */ -GLFWAPI VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface); - -#endif /*VK_VERSION_1_0*/ - - -/************************************************************************* - * Global definition cleanup - *************************************************************************/ - -/* ------------------- BEGIN SYSTEM/COMPILER SPECIFIC -------------------- */ - -#ifdef GLFW_WINGDIAPI_DEFINED - #undef WINGDIAPI - #undef GLFW_WINGDIAPI_DEFINED -#endif - -#ifdef GLFW_CALLBACK_DEFINED - #undef CALLBACK - #undef GLFW_CALLBACK_DEFINED -#endif - -/* -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- */ - - -#ifdef __cplusplus -} -#endif - -#endif /* _glfw3_h_ */ - diff --git a/mac/include/glfw3/glfw3native.h b/mac/include/glfw3/glfw3native.h deleted file mode 100644 index 90ef43bf..00000000 --- a/mac/include/glfw3/glfw3native.h +++ /dev/null @@ -1,456 +0,0 @@ -/************************************************************************* - * GLFW 3.2 - www.glfw.org - * A library for OpenGL, window and input - *------------------------------------------------------------------------ - * Copyright (c) 2002-2006 Marcus Geelnard - * Copyright (c) 2006-2016 Camilla Berglund - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would - * be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and must not - * be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - *************************************************************************/ - -#ifndef _glfw3_native_h_ -#define _glfw3_native_h_ - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************************************************* - * Doxygen documentation - *************************************************************************/ - -/*! @file glfw3native.h - * @brief The header of the native access functions. - * - * This is the header file of the native access functions. See @ref native for - * more information. - */ -/*! @defgroup native Native access - * - * **By using the native access functions you assert that you know what you're - * doing and how to fix problems caused by using them. If you don't, you - * shouldn't be using them.** - * - * Before the inclusion of @ref glfw3native.h, you may define exactly one - * window system API macro and zero or more context creation API macros. - * - * The chosen backends must match those the library was compiled for. Failure - * to do this will cause a link-time error. - * - * The available window API macros are: - * * `GLFW_EXPOSE_NATIVE_WIN32` - * * `GLFW_EXPOSE_NATIVE_COCOA` - * * `GLFW_EXPOSE_NATIVE_X11` - * * `GLFW_EXPOSE_NATIVE_WAYLAND` - * * `GLFW_EXPOSE_NATIVE_MIR` - * - * The available context API macros are: - * * `GLFW_EXPOSE_NATIVE_WGL` - * * `GLFW_EXPOSE_NATIVE_NSGL` - * * `GLFW_EXPOSE_NATIVE_GLX` - * * `GLFW_EXPOSE_NATIVE_EGL` - * - * These macros select which of the native access functions that are declared - * and which platform-specific headers to include. It is then up your (by - * definition platform-specific) code to handle which of these should be - * defined. - */ - - -/************************************************************************* - * System headers and types - *************************************************************************/ - -#if defined(GLFW_EXPOSE_NATIVE_WIN32) - // This is a workaround for the fact that glfw3.h needs to export APIENTRY (for - // example to allow applications to correctly declare a GL_ARB_debug_output - // callback) but windows.h assumes no one will define APIENTRY before it does - #undef APIENTRY - #include -#elif defined(GLFW_EXPOSE_NATIVE_COCOA) -// #include - #if defined(__OBJC__) - #import - #else - typedef void* id; - #endif -#elif defined(GLFW_EXPOSE_NATIVE_X11) - #include - #include -#elif defined(GLFW_EXPOSE_NATIVE_WAYLAND) - #include -#elif defined(GLFW_EXPOSE_NATIVE_MIR) - #include -#endif - -#if defined(GLFW_EXPOSE_NATIVE_WGL) - /* WGL is declared by windows.h */ -#endif -#if defined(GLFW_EXPOSE_NATIVE_NSGL) - /* NSGL is declared by Cocoa.h */ -#endif -#if defined(GLFW_EXPOSE_NATIVE_GLX) - #include -#endif -#if defined(GLFW_EXPOSE_NATIVE_EGL) - #include -#endif - - -/************************************************************************* - * Functions - *************************************************************************/ - -#if defined(GLFW_EXPOSE_NATIVE_WIN32) -/*! @brief Returns the adapter device name of the specified monitor. - * - * @return The UTF-8 encoded adapter device name (for example `\\.\DISPLAY1`) - * of the specified monitor, or `NULL` if an [error](@ref error_handling) - * occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.1. - * - * @ingroup native - */ -GLFWAPI const char* glfwGetWin32Adapter(GLFWmonitor* monitor); - -/*! @brief Returns the display device name of the specified monitor. - * - * @return The UTF-8 encoded display device name (for example - * `\\.\DISPLAY1\Monitor0`) of the specified monitor, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.1. - * - * @ingroup native - */ -GLFWAPI const char* glfwGetWin32Monitor(GLFWmonitor* monitor); - -/*! @brief Returns the `HWND` of the specified window. - * - * @return The `HWND` of the specified window, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.0. - * - * @ingroup native - */ -GLFWAPI HWND glfwGetWin32Window(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_WGL) -/*! @brief Returns the `HGLRC` of the specified window. - * - * @return The `HGLRC` of the specified window, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.0. - * - * @ingroup native - */ -GLFWAPI HGLRC glfwGetWGLContext(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_COCOA) -/*! @brief Returns the `CGDirectDisplayID` of the specified monitor. - * - * @return The `CGDirectDisplayID` of the specified monitor, or - * `kCGNullDirectDisplay` if an [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.1. - * - * @ingroup native - */ -//GLFWAPI CGDirectDisplayID glfwGetCocoaMonitor(GLFWmonitor* monitor); - -/*! @brief Returns the `NSWindow` of the specified window. - * - * @return The `NSWindow` of the specified window, or `nil` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.0. - * - * @ingroup native - */ -GLFWAPI id glfwGetCocoaWindow(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_NSGL) -/*! @brief Returns the `NSOpenGLContext` of the specified window. - * - * @return The `NSOpenGLContext` of the specified window, or `nil` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.0. - * - * @ingroup native - */ -GLFWAPI id glfwGetNSGLContext(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_X11) -/*! @brief Returns the `Display` used by GLFW. - * - * @return The `Display` used by GLFW, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.0. - * - * @ingroup native - */ -GLFWAPI Display* glfwGetX11Display(void); - -/*! @brief Returns the `RRCrtc` of the specified monitor. - * - * @return The `RRCrtc` of the specified monitor, or `None` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.1. - * - * @ingroup native - */ -GLFWAPI RRCrtc glfwGetX11Adapter(GLFWmonitor* monitor); - -/*! @brief Returns the `RROutput` of the specified monitor. - * - * @return The `RROutput` of the specified monitor, or `None` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.1. - * - * @ingroup native - */ -GLFWAPI RROutput glfwGetX11Monitor(GLFWmonitor* monitor); - -/*! @brief Returns the `Window` of the specified window. - * - * @return The `Window` of the specified window, or `None` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.0. - * - * @ingroup native - */ -GLFWAPI Window glfwGetX11Window(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_GLX) -/*! @brief Returns the `GLXContext` of the specified window. - * - * @return The `GLXContext` of the specified window, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.0. - * - * @ingroup native - */ -GLFWAPI GLXContext glfwGetGLXContext(GLFWwindow* window); - -/*! @brief Returns the `GLXWindow` of the specified window. - * - * @return The `GLXWindow` of the specified window, or `None` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.2. - * - * @ingroup native - */ -GLFWAPI GLXWindow glfwGetGLXWindow(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_WAYLAND) -/*! @brief Returns the `struct wl_display*` used by GLFW. - * - * @return The `struct wl_display*` used by GLFW, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.2. - * - * @ingroup native - */ -GLFWAPI struct wl_display* glfwGetWaylandDisplay(void); - -/*! @brief Returns the `struct wl_output*` of the specified monitor. - * - * @return The `struct wl_output*` of the specified monitor, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.2. - * - * @ingroup native - */ -GLFWAPI struct wl_output* glfwGetWaylandMonitor(GLFWmonitor* monitor); - -/*! @brief Returns the main `struct wl_surface*` of the specified window. - * - * @return The main `struct wl_surface*` of the specified window, or `NULL` if - * an [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.2. - * - * @ingroup native - */ -GLFWAPI struct wl_surface* glfwGetWaylandWindow(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_MIR) -/*! @brief Returns the `MirConnection*` used by GLFW. - * - * @return The `MirConnection*` used by GLFW, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.2. - * - * @ingroup native - */ -GLFWAPI MirConnection* glfwGetMirDisplay(void); - -/*! @brief Returns the Mir output ID of the specified monitor. - * - * @return The Mir output ID of the specified monitor, or zero if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.2. - * - * @ingroup native - */ -GLFWAPI int glfwGetMirMonitor(GLFWmonitor* monitor); - -/*! @brief Returns the `MirSurface*` of the specified window. - * - * @return The `MirSurface*` of the specified window, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.2. - * - * @ingroup native - */ -GLFWAPI MirSurface* glfwGetMirWindow(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_EGL) -/*! @brief Returns the `EGLDisplay` used by GLFW. - * - * @return The `EGLDisplay` used by GLFW, or `EGL_NO_DISPLAY` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.0. - * - * @ingroup native - */ -GLFWAPI EGLDisplay glfwGetEGLDisplay(void); - -/*! @brief Returns the `EGLContext` of the specified window. - * - * @return The `EGLContext` of the specified window, or `EGL_NO_CONTEXT` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.0. - * - * @ingroup native - */ -GLFWAPI EGLContext glfwGetEGLContext(GLFWwindow* window); - -/*! @brief Returns the `EGLSurface` of the specified window. - * - * @return The `EGLSurface` of the specified window, or `EGL_NO_SURFACE` if an - * [error](@ref error_handling) occurred. - * - * @thread_safety This function may be called from any thread. Access is not - * synchronized. - * - * @since Added in version 3.0. - * - * @ingroup native - */ -GLFWAPI EGLSurface glfwGetEGLSurface(GLFWwindow* window); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* _glfw3_native_h_ */ - diff --git a/mac/include/jpeg/jmorecfg.h b/mac/include/jpeg/jmorecfg.h index 2407edbe..b7a5038e 100644 --- a/mac/include/jpeg/jmorecfg.h +++ b/mac/include/jpeg/jmorecfg.h @@ -264,6 +264,7 @@ typedef enum { FALSE = 0, TRUE = 1 } boolean; #endif + /* * The remaining options affect code selection within the JPEG library, * but they don't need to be visible to most applications using the library. diff --git a/mac/include/spidermonkey/fdlibm.h b/mac/include/spidermonkey/fdlibm.h deleted file mode 100644 index 0ad21591..00000000 --- a/mac/include/spidermonkey/fdlibm.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ==================================================== - * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. - * - * Developed at SunPro, a Sun Microsystems, Inc. business. - * Permission to use, copy, modify, and distribute this - * software is freely granted, provided that this notice - * is preserved. - * ==================================================== - */ - -/* - * from: @(#)fdlibm.h 5.1 93/09/24 - * $FreeBSD$ - */ - -#ifndef mozilla_imported_fdlibm_h -#define mozilla_imported_fdlibm_h - -namespace fdlibm { - -double acos(double); -double asin(double); -double atan(double); -double atan2(double, double); - -double cosh(double); -double sinh(double); -double tanh(double); - -double exp(double); -double log(double); -double log10(double); - -double pow(double, double); -double sqrt(double); -double fabs(double); - -double floor(double); -double trunc(double); -double ceil(double); - -double acosh(double); -double asinh(double); -double atanh(double); -double cbrt(double); -double expm1(double); -double hypot(double, double); -double log1p(double); -double log2(double); -double rint(double); -double copysign(double, double); -double nearbyint(double); -double scalbn(double, int); - -float ceilf(float); -float floorf(float); - -float nearbyintf(float); -float rintf(float); -float truncf(float); - -} /* namespace fdlibm */ - -#endif /* mozilla_imported_fdlibm_h */ diff --git a/mac/include/spidermonkey/jemalloc_types.h b/mac/include/spidermonkey/jemalloc_types.h deleted file mode 100644 index ae8dc441..00000000 --- a/mac/include/spidermonkey/jemalloc_types.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -*- Mode: C; tab-width: 8; c-basic-offset: 8 -*- */ -/* vim:set softtabstop=8 shiftwidth=8: */ -/*- - * Copyright (C) 2006-2008 Jason Evans . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice(s), this list of conditions and the following disclaimer as - * the first lines of this file unmodified other than the possible - * addition of one or more copyright notices. - * 2. Redistributions in binary form must reproduce the above copyright - * notice(s), this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR - * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _JEMALLOC_TYPES_H_ -#define _JEMALLOC_TYPES_H_ - -/* grab size_t */ -#ifdef _MSC_VER -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef unsigned char jemalloc_bool; - -/* - * jemalloc_stats() is not a stable interface. When using jemalloc_stats_t, be - * sure that the compiled results of jemalloc.c are in sync with this header - * file. - */ -typedef struct { - /* - * Run-time configuration settings. - */ - jemalloc_bool opt_abort; /* abort(3) on error? */ - jemalloc_bool opt_junk; /* Fill allocated memory with 0xe4? */ - jemalloc_bool opt_poison; /* Fill free memory with 0xe5? */ - jemalloc_bool opt_utrace; /* Trace all allocation events? */ - jemalloc_bool opt_sysv; /* SysV semantics? */ - jemalloc_bool opt_xmalloc; /* abort(3) on OOM? */ - jemalloc_bool opt_zero; /* Fill allocated memory with 0x0? */ - size_t narenas; /* Number of arenas. */ - size_t balance_threshold; /* Arena contention rebalance threshold. */ - size_t quantum; /* Allocation quantum. */ - size_t small_max; /* Max quantum-spaced allocation size. */ - size_t large_max; /* Max sub-chunksize allocation size. */ - size_t chunksize; /* Size of each virtual memory mapping. */ - size_t dirty_max; /* Max dirty pages per arena. */ - - /* - * Current memory usage statistics. - */ - size_t mapped; /* Bytes mapped (not necessarily committed). */ - size_t allocated; /* Bytes allocated (committed, in use by application). */ - size_t waste; /* Bytes committed, not in use by the - application, and not intentionally left - unused (i.e., not dirty). */ - size_t page_cache; /* Committed, unused pages kept around as a - cache. (jemalloc calls these "dirty".) */ - size_t bookkeeping; /* Committed bytes used internally by the - allocator. */ - size_t bin_unused; /* Bytes committed to a bin but currently unused. */ -} jemalloc_stats_t; - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* _JEMALLOC_TYPES_H_ */ diff --git a/mac/include/spidermonkey/js-config.h b/mac/include/spidermonkey/js-config.h deleted file mode 100644 index 6909f6c7..00000000 --- a/mac/include/spidermonkey/js-config.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=78: - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_config_h -#define js_config_h - -/* Definitions set at build time that affect SpiderMonkey's public API. - This header file is generated by the SpiderMonkey configure script, - and installed along with jsapi.h. */ - -/* Define to 1 if SpiderMonkey is in debug mode. */ -/* #undef JS_DEBUG */ - -/* - * NB: We have a special case for rust-bindgen, which wants to be able to - * generate both debug and release bindings on a single objdir. - */ -#ifdef JS_DEBUG -#if !defined(DEBUG) && !defined(RUST_BINDGEN) -# error "SpiderMonkey was configured with --enable-debug, so DEBUG must be defined when including this header" -# endif -#else -# if defined(DEBUG) && !defined(RUST_BINDGEN) -# error "SpiderMonkey was configured with --disable-debug, so DEBUG must be not defined when including this header" -# endif -#endif - -/* Define to 1 if SpiderMonkey should not use struct types in debug builds. */ -/* #undef JS_NO_JSVAL_JSID_STRUCT_TYPES */ - -/* Define to 1 if SpiderMonkey should support multi-threaded clients. */ -/* #undef JS_THREADSAFE */ - -/* Define to 1 if SpiderMonkey should include ctypes support. */ -/* #undef JS_HAS_CTYPES */ - -/* Define to 1 if SpiderMonkey should support the ability to perform - entirely too much GC. */ -/* #undef JS_GC_ZEAL */ - -/* Define to 1 if SpiderMonkey should use small chunks. */ -/* #undef JS_GC_SMALL_CHUNK_SIZE */ - -/* Define to 1 to perform extra assertions and heap poisoning. */ -/* #undef JS_CRASH_DIAGNOSTICS */ - -/* Define to 1 if SpiderMonkey is in NUNBOX32 mode. */ -/* #undef JS_NUNBOX32 */ - -/* Define to 1 if SpiderMonkey is in PUNBOX64 mode. */ -#define JS_PUNBOX64 1 - -/* MOZILLA JSAPI version number components */ -#define MOZJS_MAJOR_VERSION 52 -#define MOZJS_MINOR_VERSION 0 - -#endif /* js_config_h */ diff --git a/mac/include/spidermonkey/js.msg b/mac/include/spidermonkey/js.msg deleted file mode 100644 index 246e363c..00000000 --- a/mac/include/spidermonkey/js.msg +++ /dev/null @@ -1,581 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * This is the JavaScript error message file. - * - * The format for each JS error message is: - * - * MSG_DEF(, , , - * ) - * - * where ; - * is a legal C identifer that will be used in the - * JS engine source. - * - * is an integer literal specifying the total number of - * replaceable arguments in the following format string. - * - * is an exception index from the enum in jsexn.c; - * JSEXN_NONE for none. The given exception index will be raised by the - * engine when the corresponding error occurs. - * - * is a string literal, optionally containing sequences - * {X} where X is an integer representing the argument number that will - * be replaced with a string value when the error is reported. - * - * e.g. - * - * MSG_DEF(JSMSG_NOT_A_SUBSPECIES, 2, JSEXN_NONE, - * "{0} is not a member of the {1} family") - * - * can be used: - * - * JS_ReportErrorNumberASCII(JSMSG_NOT_A_SUBSPECIES, "Rhino", "Monkey"); - * - * to report: - * - * "Rhino is not a member of the Monkey family" - */ - -MSG_DEF(JSMSG_NOT_AN_ERROR, 0, JSEXN_ERR, "") -MSG_DEF(JSMSG_NOT_DEFINED, 1, JSEXN_REFERENCEERR, "{0} is not defined") -MSG_DEF(JSMSG_MORE_ARGS_NEEDED, 3, JSEXN_TYPEERR, "{0} requires more than {1} argument{2}") -MSG_DEF(JSMSG_INCOMPATIBLE_PROTO, 3, JSEXN_TYPEERR, "{0}.prototype.{1} called on incompatible {2}") -MSG_DEF(JSMSG_NO_CONSTRUCTOR, 1, JSEXN_TYPEERR, "{0} has no constructor") -MSG_DEF(JSMSG_BAD_SORT_ARG, 0, JSEXN_TYPEERR, "invalid Array.prototype.sort argument") -MSG_DEF(JSMSG_CANT_WATCH, 1, JSEXN_TYPEERR, "can't watch non-native objects of class {0}") -MSG_DEF(JSMSG_READ_ONLY, 1, JSEXN_TYPEERR, "{0} is read-only") -MSG_DEF(JSMSG_CANT_DELETE, 1, JSEXN_TYPEERR, "property {0} is non-configurable and can't be deleted") -MSG_DEF(JSMSG_CANT_TRUNCATE_ARRAY, 0, JSEXN_TYPEERR, "can't delete non-configurable array element") -MSG_DEF(JSMSG_NOT_FUNCTION, 1, JSEXN_TYPEERR, "{0} is not a function") -MSG_DEF(JSMSG_NOT_CONSTRUCTOR, 1, JSEXN_TYPEERR, "{0} is not a constructor") -MSG_DEF(JSMSG_CANT_CONVERT_TO, 2, JSEXN_TYPEERR, "can't convert {0} to {1}") -MSG_DEF(JSMSG_TOPRIMITIVE_NOT_CALLABLE, 2, JSEXN_TYPEERR, "can't convert {0} to {1}: its [Symbol.toPrimitive] property is not a function") -MSG_DEF(JSMSG_TOPRIMITIVE_RETURNED_OBJECT, 2, JSEXN_TYPEERR, "can't convert {0} to {1}: its [Symbol.toPrimitive] method returned an object") -MSG_DEF(JSMSG_NO_PROPERTIES, 1, JSEXN_TYPEERR, "{0} has no properties") -MSG_DEF(JSMSG_BAD_REGEXP_FLAG, 1, JSEXN_SYNTAXERR, "invalid regular expression flag {0}") -MSG_DEF(JSMSG_ARG_INDEX_OUT_OF_RANGE, 1, JSEXN_RANGEERR, "argument {0} accesses an index that is out of range") -MSG_DEF(JSMSG_SPREAD_TOO_LARGE, 0, JSEXN_RANGEERR, "array too large due to spread operand(s)") -MSG_DEF(JSMSG_BAD_WEAKMAP_KEY, 0, JSEXN_TYPEERR, "cannot use the given object as a weak map key") -MSG_DEF(JSMSG_BAD_GETTER_OR_SETTER, 1, JSEXN_TYPEERR, "invalid {0} usage") -MSG_DEF(JSMSG_BAD_ARRAY_LENGTH, 0, JSEXN_RANGEERR, "invalid array length") -MSG_DEF(JSMSG_REDECLARED_VAR, 2, JSEXN_SYNTAXERR, "redeclaration of {0} {1}") -MSG_DEF(JSMSG_UNDECLARED_VAR, 1, JSEXN_REFERENCEERR, "assignment to undeclared variable {0}") -MSG_DEF(JSMSG_GETTER_ONLY, 0, JSEXN_TYPEERR, "setting a property that has only a getter") -MSG_DEF(JSMSG_OVERWRITING_ACCESSOR, 1, JSEXN_TYPEERR, "can't overwrite accessor property {0}") -MSG_DEF(JSMSG_UNDEFINED_PROP, 1, JSEXN_REFERENCEERR, "reference to undefined property {0}") -MSG_DEF(JSMSG_INVALID_MAP_ITERABLE, 1, JSEXN_TYPEERR, "iterable for {0} should have array-like objects") -MSG_DEF(JSMSG_NESTING_GENERATOR, 0, JSEXN_TYPEERR, "already executing generator") -MSG_DEF(JSMSG_INCOMPATIBLE_METHOD, 3, JSEXN_TYPEERR, "{0} {1} called on incompatible {2}") -MSG_DEF(JSMSG_OBJECT_WATCH_DEPRECATED, 0, JSEXN_WARN, "Object.prototype.watch and unwatch are very slow, non-standard, and deprecated; use a getter/setter instead") -MSG_DEF(JSMSG_ARRAYBUFFER_SLICE_DEPRECATED, 0, JSEXN_WARN, "ArrayBuffer.slice is deprecated; use ArrayBuffer.prototype.slice instead") -MSG_DEF(JSMSG_BAD_SURROGATE_CHAR, 1, JSEXN_TYPEERR, "bad surrogate character {0}") -MSG_DEF(JSMSG_UTF8_CHAR_TOO_LARGE, 1, JSEXN_TYPEERR, "UTF-8 character {0} too large") -MSG_DEF(JSMSG_MALFORMED_UTF8_CHAR, 1, JSEXN_TYPEERR, "malformed UTF-8 character sequence at offset {0}") -MSG_DEF(JSMSG_BUILTIN_CTOR_NO_NEW, 1, JSEXN_TYPEERR, "calling a builtin {0} constructor without new is forbidden") -MSG_DEF(JSMSG_BAD_GENERATOR_YIELD, 1, JSEXN_TYPEERR, "yield from closing generator {0}") -MSG_DEF(JSMSG_EMPTY_ARRAY_REDUCE, 0, JSEXN_TYPEERR, "reduce of empty array with no initial value") -MSG_DEF(JSMSG_UNEXPECTED_TYPE, 2, JSEXN_TYPEERR, "{0} is {1}") -MSG_DEF(JSMSG_MISSING_FUN_ARG, 2, JSEXN_TYPEERR, "missing argument {0} when calling function {1}") -MSG_DEF(JSMSG_NOT_NONNULL_OBJECT, 1, JSEXN_TYPEERR, "{0} is not a non-null object") -MSG_DEF(JSMSG_SET_NON_OBJECT_RECEIVER, 1, JSEXN_TYPEERR, "can't assign to properties of {0}: not an object") -MSG_DEF(JSMSG_INVALID_DESCRIPTOR, 0, JSEXN_TYPEERR, "property descriptors must not specify a value or be writable when a getter or setter has been specified") -MSG_DEF(JSMSG_OBJECT_NOT_EXTENSIBLE, 1, JSEXN_TYPEERR, "{0}: Object is not extensible") -MSG_DEF(JSMSG_CANT_DEFINE_PROP_OBJECT_NOT_EXTENSIBLE, 2, JSEXN_TYPEERR, "can't define property {1}: {0} is not extensible") -MSG_DEF(JSMSG_CANT_REDEFINE_PROP, 1, JSEXN_TYPEERR, "can't redefine non-configurable property {0}") -MSG_DEF(JSMSG_CANT_REDEFINE_ARRAY_LENGTH, 0, JSEXN_TYPEERR, "can't redefine array length") -MSG_DEF(JSMSG_CANT_DEFINE_PAST_ARRAY_LENGTH, 0, JSEXN_TYPEERR, "can't define array index property past the end of an array with non-writable length") -MSG_DEF(JSMSG_BAD_GET_SET_FIELD, 1, JSEXN_TYPEERR, "property descriptor's {0} field is neither undefined nor a function") -MSG_DEF(JSMSG_THROW_TYPE_ERROR, 0, JSEXN_TYPEERR, "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them") -MSG_DEF(JSMSG_NOT_EXPECTED_TYPE, 3, JSEXN_TYPEERR, "{0}: expected {1}, got {2}") -MSG_DEF(JSMSG_NOT_ITERABLE, 1, JSEXN_TYPEERR, "{0} is not iterable") -MSG_DEF(JSMSG_NOT_ITERATOR, 1, JSEXN_TYPEERR, "{0} is not iterator") -MSG_DEF(JSMSG_ALREADY_HAS_PRAGMA, 2, JSEXN_WARN, "{0} is being assigned a {1}, but already has one") -MSG_DEF(JSMSG_GET_ITER_RETURNED_PRIMITIVE, 0, JSEXN_TYPEERR, "[Symbol.iterator]() returned a non-object value") -MSG_DEF(JSMSG_NEXT_RETURNED_PRIMITIVE, 0, JSEXN_TYPEERR, "iterator.next() returned a non-object value") -MSG_DEF(JSMSG_CANT_SET_PROTO, 0, JSEXN_TYPEERR, "can't set prototype of this object") -MSG_DEF(JSMSG_CANT_SET_PROTO_OF, 1, JSEXN_TYPEERR, "can't set prototype of {0}") -MSG_DEF(JSMSG_CANT_SET_PROTO_CYCLE, 0, JSEXN_TYPEERR, "can't set prototype: it would cause a prototype chain cycle") -MSG_DEF(JSMSG_INVALID_ARG_TYPE, 3, JSEXN_TYPEERR, "Invalid type: {0} can't be a{1} {2}") -MSG_DEF(JSMSG_TERMINATED, 1, JSEXN_ERR, "Script terminated by timeout at:\n{0}") -MSG_DEF(JSMSG_PROTO_NOT_OBJORNULL, 1, JSEXN_TYPEERR, "{0}.prototype is not an object or null") -MSG_DEF(JSMSG_CANT_CALL_CLASS_CONSTRUCTOR, 0, JSEXN_TYPEERR, "class constructors must be invoked with |new|") -MSG_DEF(JSMSG_UNINITIALIZED_THIS, 1, JSEXN_REFERENCEERR, "|this| used uninitialized in {0} class constructor") -MSG_DEF(JSMSG_UNINITIALIZED_THIS_ARROW, 0, JSEXN_REFERENCEERR, "|this| used uninitialized in arrow function in class constructor") -MSG_DEF(JSMSG_BAD_DERIVED_RETURN, 1, JSEXN_TYPEERR, "derived class constructor returned invalid value {0}") - -// JSON -MSG_DEF(JSMSG_JSON_BAD_PARSE, 3, JSEXN_SYNTAXERR, "JSON.parse: {0} at line {1} column {2} of the JSON data") -MSG_DEF(JSMSG_JSON_CYCLIC_VALUE, 0, JSEXN_TYPEERR, "cyclic object value") - -// Runtime errors -MSG_DEF(JSMSG_BAD_INSTANCEOF_RHS, 1, JSEXN_TYPEERR, "invalid 'instanceof' operand {0}") -MSG_DEF(JSMSG_BAD_LEFTSIDE_OF_ASS, 0, JSEXN_REFERENCEERR, "invalid assignment left-hand side") -MSG_DEF(JSMSG_BAD_PROTOTYPE, 1, JSEXN_TYPEERR, "'prototype' property of {0} is not an object") -MSG_DEF(JSMSG_IN_NOT_OBJECT, 1, JSEXN_TYPEERR, "invalid 'in' operand {0}") -MSG_DEF(JSMSG_TOO_MANY_CON_SPREADARGS, 0, JSEXN_RANGEERR, "too many constructor arguments") -MSG_DEF(JSMSG_TOO_MANY_FUN_SPREADARGS, 0, JSEXN_RANGEERR, "too many function arguments") -MSG_DEF(JSMSG_UNINITIALIZED_LEXICAL, 1, JSEXN_REFERENCEERR, "can't access lexical declaration `{0}' before initialization") -MSG_DEF(JSMSG_BAD_CONST_ASSIGN, 1, JSEXN_TYPEERR, "invalid assignment to const `{0}'") -MSG_DEF(JSMSG_CANT_DECLARE_GLOBAL_BINDING, 2, JSEXN_TYPEERR, "cannot declare global binding `{0}': {1}") - -// Date -MSG_DEF(JSMSG_INVALID_DATE, 0, JSEXN_RANGEERR, "invalid date") -MSG_DEF(JSMSG_BAD_TOISOSTRING_PROP, 0, JSEXN_TYPEERR, "toISOString property is not callable") - -// String -MSG_DEF(JSMSG_BAD_URI, 0, JSEXN_URIERR, "malformed URI sequence") -MSG_DEF(JSMSG_INVALID_NORMALIZE_FORM, 0, JSEXN_RANGEERR, "form must be one of 'NFC', 'NFD', 'NFKC', or 'NFKD'") -MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 0, JSEXN_RANGEERR, "repeat count must be non-negative") -MSG_DEF(JSMSG_NOT_A_CODEPOINT, 1, JSEXN_RANGEERR, "{0} is not a valid code point") -MSG_DEF(JSMSG_RESULTING_STRING_TOO_LARGE, 0, JSEXN_RANGEERR, "repeat count must be less than infinity and not overflow maximum string size") - -// Number -MSG_DEF(JSMSG_BAD_RADIX, 0, JSEXN_RANGEERR, "radix must be an integer at least 2 and no greater than 36") -MSG_DEF(JSMSG_PRECISION_RANGE, 1, JSEXN_RANGEERR, "precision {0} out of range") - -// Function -MSG_DEF(JSMSG_BAD_APPLY_ARGS, 1, JSEXN_TYPEERR, "second argument to Function.prototype.{0} must be an array") -MSG_DEF(JSMSG_BAD_FORMAL, 0, JSEXN_SYNTAXERR, "malformed formal parameter") -MSG_DEF(JSMSG_CALLER_IS_STRICT, 0, JSEXN_TYPEERR, "access to strict mode caller function is censored") -MSG_DEF(JSMSG_DEPRECATED_USAGE, 1, JSEXN_REFERENCEERR, "deprecated {0} usage") -MSG_DEF(JSMSG_NOT_SCRIPTED_FUNCTION, 1, JSEXN_TYPEERR, "{0} is not a scripted function") -MSG_DEF(JSMSG_NO_REST_NAME, 0, JSEXN_SYNTAXERR, "no parameter name after ...") -MSG_DEF(JSMSG_PARAMETER_AFTER_REST, 0, JSEXN_SYNTAXERR, "parameter after rest parameter") -MSG_DEF(JSMSG_TOO_MANY_ARGUMENTS, 0, JSEXN_RANGEERR, "too many arguments provided for a function call") - -// CSP -MSG_DEF(JSMSG_CSP_BLOCKED_EVAL, 0, JSEXN_ERR, "call to eval() blocked by CSP") -MSG_DEF(JSMSG_CSP_BLOCKED_FUNCTION, 0, JSEXN_ERR, "call to Function() blocked by CSP") - -// Wrappers -MSG_DEF(JSMSG_ACCESSOR_DEF_DENIED, 1, JSEXN_ERR, "Permission denied to define accessor property {0}") -MSG_DEF(JSMSG_DEAD_OBJECT, 0, JSEXN_TYPEERR, "can't access dead object") -MSG_DEF(JSMSG_UNWRAP_DENIED, 0, JSEXN_ERR, "permission denied to unwrap object") - -// JSAPI-only (Not thrown as JS exceptions) -MSG_DEF(JSMSG_BAD_CLONE_FUNOBJ_SCOPE, 0, JSEXN_TYPEERR, "bad cloned function scope chain") -MSG_DEF(JSMSG_CANT_CLONE_OBJECT, 0, JSEXN_TYPEERR, "can't clone object") -MSG_DEF(JSMSG_CANT_OPEN, 2, JSEXN_ERR, "can't open {0}: {1}") -MSG_DEF(JSMSG_USER_DEFINED_ERROR, 0, JSEXN_ERR, "JS_ReportError was called") - -// Internal errors -MSG_DEF(JSMSG_ALLOC_OVERFLOW, 0, JSEXN_INTERNALERR, "allocation size overflow") -MSG_DEF(JSMSG_BAD_BYTECODE, 1, JSEXN_INTERNALERR, "unimplemented JavaScript bytecode {0}") -MSG_DEF(JSMSG_BUFFER_TOO_SMALL, 0, JSEXN_INTERNALERR, "buffer too small") -MSG_DEF(JSMSG_BUILD_ID_NOT_AVAILABLE, 0, JSEXN_INTERNALERR, "build ID is not available") -MSG_DEF(JSMSG_BYTECODE_TOO_BIG, 2, JSEXN_INTERNALERR, "bytecode {0} too large (limit {1})") -MSG_DEF(JSMSG_ERR_DURING_THROW, 0, JSEXN_INTERNALERR, "an internal error occurred while throwing an exception") -MSG_DEF(JSMSG_NEED_DIET, 1, JSEXN_INTERNALERR, "{0} too large") -MSG_DEF(JSMSG_OUT_OF_MEMORY, 0, JSEXN_INTERNALERR, "out of memory") -MSG_DEF(JSMSG_OVER_RECURSED, 0, JSEXN_INTERNALERR, "too much recursion") -MSG_DEF(JSMSG_TOO_BIG_TO_ENCODE, 0, JSEXN_INTERNALERR, "data are to big to encode") -MSG_DEF(JSMSG_TOO_DEEP, 1, JSEXN_INTERNALERR, "{0} nested too deeply") -MSG_DEF(JSMSG_UNCAUGHT_EXCEPTION, 1, JSEXN_INTERNALERR, "uncaught exception: {0}") -MSG_DEF(JSMSG_UNKNOWN_FORMAT, 1, JSEXN_INTERNALERR, "unknown bytecode format {0}") - -// Frontend -MSG_DEF(JSMSG_ACCESSOR_WRONG_ARGS, 3, JSEXN_SYNTAXERR, "{0} functions must have {1} argument{2}") -MSG_DEF(JSMSG_ARRAY_COMP_LEFTSIDE, 0, JSEXN_SYNTAXERR, "invalid array comprehension left-hand side") -MSG_DEF(JSMSG_ARRAY_INIT_TOO_BIG, 0, JSEXN_INTERNALERR, "array initializer too large") -MSG_DEF(JSMSG_AS_AFTER_IMPORT_STAR, 0, JSEXN_SYNTAXERR, "missing keyword 'as' after import *") -MSG_DEF(JSMSG_AS_AFTER_RESERVED_WORD, 1, JSEXN_SYNTAXERR, "missing keyword 'as' after reserved word '{0}'") -MSG_DEF(JSMSG_ASYNC_GENERATOR, 0, JSEXN_SYNTAXERR, "generator function or method can't be async") -MSG_DEF(JSMSG_AWAIT_IN_DEFAULT, 0, JSEXN_SYNTAXERR, "await can't be used in default expression") -MSG_DEF(JSMSG_BAD_ANON_GENERATOR_RETURN, 0, JSEXN_TYPEERR, "anonymous generator function returns a value") -MSG_DEF(JSMSG_BAD_ARROW_ARGS, 0, JSEXN_SYNTAXERR, "invalid arrow-function arguments (parentheses around the arrow-function may help)") -MSG_DEF(JSMSG_BAD_BINDING, 1, JSEXN_SYNTAXERR, "redefining {0} is deprecated") -MSG_DEF(JSMSG_BAD_CONST_DECL, 0, JSEXN_SYNTAXERR, "missing = in const declaration") -MSG_DEF(JSMSG_BAD_CONTINUE, 0, JSEXN_SYNTAXERR, "continue must be inside loop") -MSG_DEF(JSMSG_BAD_DESTRUCT_ASS, 0, JSEXN_REFERENCEERR, "invalid destructuring assignment operator") -MSG_DEF(JSMSG_BAD_DESTRUCT_TARGET, 0, JSEXN_SYNTAXERR, "invalid destructuring target") -MSG_DEF(JSMSG_BAD_DESTRUCT_PARENS, 0, JSEXN_SYNTAXERR, "destructuring patterns in assignments can't be parenthesized") -MSG_DEF(JSMSG_BAD_DESTRUCT_DECL, 0, JSEXN_SYNTAXERR, "missing = in destructuring declaration") -MSG_DEF(JSMSG_BAD_DUP_ARGS, 0, JSEXN_SYNTAXERR, "duplicate argument names not allowed in this context") -MSG_DEF(JSMSG_BAD_FOR_EACH_LOOP, 0, JSEXN_SYNTAXERR, "invalid for each loop") -MSG_DEF(JSMSG_BAD_FOR_LEFTSIDE, 0, JSEXN_SYNTAXERR, "invalid for-in/of left-hand side") -MSG_DEF(JSMSG_LEXICAL_DECL_DEFINES_LET,0, JSEXN_SYNTAXERR, "a lexical declaration can't define a 'let' binding") -MSG_DEF(JSMSG_LET_STARTING_FOROF_LHS, 0, JSEXN_SYNTAXERR, "an expression X in 'for (X of Y)' must not start with 'let'") -MSG_DEF(JSMSG_BAD_GENERATOR_RETURN, 1, JSEXN_TYPEERR, "generator function {0} returns a value") -MSG_DEF(JSMSG_BAD_GENEXP_BODY, 1, JSEXN_SYNTAXERR, "illegal use of {0} in generator expression") -MSG_DEF(JSMSG_BAD_INCOP_OPERAND, 0, JSEXN_REFERENCEERR, "invalid increment/decrement operand") -MSG_DEF(JSMSG_BAD_METHOD_DEF, 0, JSEXN_SYNTAXERR, "bad method definition") -MSG_DEF(JSMSG_BAD_OCTAL, 1, JSEXN_SYNTAXERR, "{0} is not a legal ECMA-262 octal constant") -MSG_DEF(JSMSG_BAD_OPERAND, 1, JSEXN_SYNTAXERR, "invalid {0} operand") -MSG_DEF(JSMSG_BAD_POW_LEFTSIDE, 0, JSEXN_SYNTAXERR, "unparenthesized unary expression can't appear on the left-hand side of '**'") -MSG_DEF(JSMSG_BAD_PROP_ID, 0, JSEXN_SYNTAXERR, "invalid property id") -MSG_DEF(JSMSG_BAD_RETURN_OR_YIELD, 1, JSEXN_SYNTAXERR, "{0} not in function") -MSG_DEF(JSMSG_BAD_STRICT_ASSIGN, 1, JSEXN_SYNTAXERR, "'{0}' can't be defined or assigned to in strict mode code") -MSG_DEF(JSMSG_BAD_SWITCH, 0, JSEXN_SYNTAXERR, "invalid switch statement") -MSG_DEF(JSMSG_BAD_SUPER, 0, JSEXN_SYNTAXERR, "invalid use of keyword 'super'") -MSG_DEF(JSMSG_BAD_SUPERPROP, 1, JSEXN_SYNTAXERR, "use of super {0} accesses only valid within methods or eval code within methods") -MSG_DEF(JSMSG_BAD_SUPERCALL, 0, JSEXN_SYNTAXERR, "super() is only valid in derived class constructors") -MSG_DEF(JSMSG_BRACKET_AFTER_ARRAY_COMPREHENSION, 0, JSEXN_SYNTAXERR, "missing ] after array comprehension") -MSG_DEF(JSMSG_BRACKET_AFTER_LIST, 0, JSEXN_SYNTAXERR, "missing ] after element list") -MSG_DEF(JSMSG_BRACKET_IN_INDEX, 0, JSEXN_SYNTAXERR, "missing ] in index expression") -MSG_DEF(JSMSG_CATCH_AFTER_GENERAL, 0, JSEXN_SYNTAXERR, "catch after unconditional catch") -MSG_DEF(JSMSG_CATCH_IDENTIFIER, 0, JSEXN_SYNTAXERR, "missing identifier in catch") -MSG_DEF(JSMSG_CATCH_OR_FINALLY, 0, JSEXN_SYNTAXERR, "missing catch or finally after try") -MSG_DEF(JSMSG_CATCH_WITHOUT_TRY, 0, JSEXN_SYNTAXERR, "catch without try") -MSG_DEF(JSMSG_COLON_AFTER_CASE, 0, JSEXN_SYNTAXERR, "missing : after case label") -MSG_DEF(JSMSG_COLON_AFTER_ID, 0, JSEXN_SYNTAXERR, "missing : after property id") -MSG_DEF(JSMSG_COLON_IN_COND, 0, JSEXN_SYNTAXERR, "missing : in conditional expression") -MSG_DEF(JSMSG_COMP_PROP_UNTERM_EXPR, 0, JSEXN_SYNTAXERR, "missing ] in computed property name") -MSG_DEF(JSMSG_CONTRARY_NONDIRECTIVE, 1, JSEXN_SYNTAXERR, "'{0}' statement won't be enforced as a directive because it isn't in directive prologue position") -MSG_DEF(JSMSG_CURLY_AFTER_BODY, 0, JSEXN_SYNTAXERR, "missing } after function body") -MSG_DEF(JSMSG_CURLY_AFTER_CATCH, 0, JSEXN_SYNTAXERR, "missing } after catch block") -MSG_DEF(JSMSG_CURLY_AFTER_FINALLY, 0, JSEXN_SYNTAXERR, "missing } after finally block") -MSG_DEF(JSMSG_CURLY_AFTER_LIST, 0, JSEXN_SYNTAXERR, "missing } after property list") -MSG_DEF(JSMSG_CURLY_AFTER_TRY, 0, JSEXN_SYNTAXERR, "missing } after try block") -MSG_DEF(JSMSG_CURLY_BEFORE_BODY, 0, JSEXN_SYNTAXERR, "missing { before function body") -MSG_DEF(JSMSG_CURLY_BEFORE_CATCH, 0, JSEXN_SYNTAXERR, "missing { before catch block") -MSG_DEF(JSMSG_CURLY_BEFORE_CLASS, 0, JSEXN_SYNTAXERR, "missing { before class body") -MSG_DEF(JSMSG_CURLY_BEFORE_FINALLY, 0, JSEXN_SYNTAXERR, "missing { before finally block") -MSG_DEF(JSMSG_CURLY_BEFORE_SWITCH, 0, JSEXN_SYNTAXERR, "missing { before switch body") -MSG_DEF(JSMSG_CURLY_BEFORE_TRY, 0, JSEXN_SYNTAXERR, "missing { before try block") -MSG_DEF(JSMSG_CURLY_IN_COMPOUND, 0, JSEXN_SYNTAXERR, "missing } in compound statement") -MSG_DEF(JSMSG_DECLARATION_AFTER_EXPORT,0, JSEXN_SYNTAXERR, "missing declaration after 'export' keyword") -MSG_DEF(JSMSG_DECLARATION_AFTER_IMPORT,0, JSEXN_SYNTAXERR, "missing declaration after 'import' keyword") -MSG_DEF(JSMSG_DEPRECATED_DELETE_OPERAND, 0, JSEXN_SYNTAXERR, "applying the 'delete' operator to an unqualified name is deprecated") -MSG_DEF(JSMSG_DEPRECATED_EXPR_CLOSURE, 0, JSEXN_WARN, "expression closures are deprecated") -MSG_DEF(JSMSG_DEPRECATED_FOR_EACH, 0, JSEXN_WARN, "JavaScript 1.6's for-each-in loops are deprecated; consider using ES6 for-of instead") -MSG_DEF(JSMSG_DEPRECATED_OCTAL, 0, JSEXN_SYNTAXERR, "\"0\"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the \"0o\" prefix instead") -MSG_DEF(JSMSG_DEPRECATED_PRAGMA, 1, JSEXN_WARN, "Using //@ to indicate {0} pragmas is deprecated. Use //# instead") -MSG_DEF(JSMSG_DEPRECATED_BLOCK_SCOPE_FUN_REDECL, 1, JSEXN_WARN, "redeclaration of block-scoped function `{0}' is deprecated") -MSG_DEF(JSMSG_DUPLICATE_EXPORT_NAME, 1, JSEXN_SYNTAXERR, "duplicate export name '{0}'") -MSG_DEF(JSMSG_DUPLICATE_FORMAL, 1, JSEXN_SYNTAXERR, "duplicate formal argument {0}") -MSG_DEF(JSMSG_DUPLICATE_LABEL, 0, JSEXN_SYNTAXERR, "duplicate label") -MSG_DEF(JSMSG_DUPLICATE_PROPERTY, 1, JSEXN_SYNTAXERR, "property name {0} appears more than once in object literal") -MSG_DEF(JSMSG_DUPLICATE_PROTO_PROPERTY, 0, JSEXN_SYNTAXERR, "property name __proto__ appears more than once in object literal") -MSG_DEF(JSMSG_EMPTY_CONSEQUENT, 0, JSEXN_SYNTAXERR, "mistyped ; after conditional?") -MSG_DEF(JSMSG_EQUAL_AS_ASSIGN, 0, JSEXN_SYNTAXERR, "test for equality (==) mistyped as assignment (=)?") -MSG_DEF(JSMSG_EXPORT_DECL_AT_TOP_LEVEL,0, JSEXN_SYNTAXERR, "export declarations may only appear at top level of a module") -MSG_DEF(JSMSG_FINALLY_WITHOUT_TRY, 0, JSEXN_SYNTAXERR, "finally without try") -MSG_DEF(JSMSG_FORBIDDEN_AS_STATEMENT, 1, JSEXN_SYNTAXERR, "{0} can't appear in single-statement context") -MSG_DEF(JSMSG_FROM_AFTER_IMPORT_CLAUSE, 0, JSEXN_SYNTAXERR, "missing keyword 'from' after import clause") -MSG_DEF(JSMSG_FROM_AFTER_EXPORT_STAR, 0, JSEXN_SYNTAXERR, "missing keyword 'from' after export *") -MSG_DEF(JSMSG_GARBAGE_AFTER_INPUT, 2, JSEXN_SYNTAXERR, "unexpected garbage after {0}, starting with {1}") -MSG_DEF(JSMSG_IDSTART_AFTER_NUMBER, 0, JSEXN_SYNTAXERR, "identifier starts immediately after numeric literal") -MSG_DEF(JSMSG_ILLEGAL_CHARACTER, 0, JSEXN_SYNTAXERR, "illegal character") -MSG_DEF(JSMSG_IMPORT_DECL_AT_TOP_LEVEL, 0, JSEXN_SYNTAXERR, "import declarations may only appear at top level of a module") -MSG_DEF(JSMSG_INVALID_FOR_IN_DECL_WITH_INIT,0,JSEXN_SYNTAXERR,"for-in loop head declarations may not have initializers") -MSG_DEF(JSMSG_LABEL_NOT_FOUND, 0, JSEXN_SYNTAXERR, "label not found") -MSG_DEF(JSMSG_LET_COMP_BINDING, 0, JSEXN_SYNTAXERR, "'let' is not a valid name for a comprehension variable") -MSG_DEF(JSMSG_LEXICAL_DECL_NOT_IN_BLOCK, 1, JSEXN_SYNTAXERR, "{0} declaration not directly within block") -MSG_DEF(JSMSG_LEXICAL_DECL_LABEL, 1, JSEXN_SYNTAXERR, "{0} declarations cannot be labelled") -MSG_DEF(JSMSG_GENERATOR_LABEL, 0, JSEXN_SYNTAXERR, "generator functions cannot be labelled") -MSG_DEF(JSMSG_FUNCTION_LABEL, 0, JSEXN_SYNTAXERR, "functions cannot be labelled") -MSG_DEF(JSMSG_SLOPPY_FUNCTION_LABEL, 0, JSEXN_SYNTAXERR, "functions can only be labelled inside blocks") -MSG_DEF(JSMSG_LINE_BREAK_AFTER_THROW, 0, JSEXN_SYNTAXERR, "no line break is allowed between 'throw' and its expression") -MSG_DEF(JSMSG_LINE_BREAK_BEFORE_ARROW, 0, JSEXN_SYNTAXERR, "no line break is allowed before '=>'") -MSG_DEF(JSMSG_MALFORMED_ESCAPE, 1, JSEXN_SYNTAXERR, "malformed {0} character escape sequence") -MSG_DEF(JSMSG_MISSING_BINARY_DIGITS, 0, JSEXN_SYNTAXERR, "missing binary digits after '0b'") -MSG_DEF(JSMSG_MISSING_EXPONENT, 0, JSEXN_SYNTAXERR, "missing exponent") -MSG_DEF(JSMSG_MISSING_EXPR_AFTER_THROW,0, JSEXN_SYNTAXERR, "throw statement is missing an expression") -MSG_DEF(JSMSG_MISSING_FORMAL, 0, JSEXN_SYNTAXERR, "missing formal parameter") -MSG_DEF(JSMSG_MISSING_HEXDIGITS, 0, JSEXN_SYNTAXERR, "missing hexadecimal digits after '0x'") -MSG_DEF(JSMSG_MISSING_OCTAL_DIGITS, 0, JSEXN_SYNTAXERR, "missing octal digits after '0o'") -MSG_DEF(JSMSG_MODULE_SPEC_AFTER_FROM, 0, JSEXN_SYNTAXERR, "missing module specifier after 'from' keyword") -MSG_DEF(JSMSG_NAME_AFTER_DOT, 0, JSEXN_SYNTAXERR, "missing name after . operator") -MSG_DEF(JSMSG_NAMED_IMPORTS_OR_NAMESPACE_IMPORT, 0, JSEXN_SYNTAXERR, "expected named imports or namespace import after comma") -MSG_DEF(JSMSG_NO_BINDING_NAME, 0, JSEXN_SYNTAXERR, "missing binding name") -MSG_DEF(JSMSG_NO_EXPORT_NAME, 0, JSEXN_SYNTAXERR, "missing export name") -MSG_DEF(JSMSG_NO_IMPORT_NAME, 0, JSEXN_SYNTAXERR, "missing import name") -MSG_DEF(JSMSG_NO_VARIABLE_NAME, 0, JSEXN_SYNTAXERR, "missing variable name") -MSG_DEF(JSMSG_OF_AFTER_FOR_NAME, 0, JSEXN_SYNTAXERR, "missing 'of' after for") -MSG_DEF(JSMSG_PAREN_AFTER_ARGS, 0, JSEXN_SYNTAXERR, "missing ) after argument list") -MSG_DEF(JSMSG_PAREN_AFTER_CATCH, 0, JSEXN_SYNTAXERR, "missing ) after catch") -MSG_DEF(JSMSG_PAREN_AFTER_COND, 0, JSEXN_SYNTAXERR, "missing ) after condition") -MSG_DEF(JSMSG_PAREN_AFTER_FOR, 0, JSEXN_SYNTAXERR, "missing ( after for") -MSG_DEF(JSMSG_PAREN_AFTER_FORMAL, 0, JSEXN_SYNTAXERR, "missing ) after formal parameters") -MSG_DEF(JSMSG_PAREN_AFTER_FOR_CTRL, 0, JSEXN_SYNTAXERR, "missing ) after for-loop control") -MSG_DEF(JSMSG_PAREN_AFTER_FOR_OF_ITERABLE, 0, JSEXN_SYNTAXERR, "missing ) after for-of iterable") -MSG_DEF(JSMSG_PAREN_AFTER_SWITCH, 0, JSEXN_SYNTAXERR, "missing ) after switch expression") -MSG_DEF(JSMSG_PAREN_AFTER_WITH, 0, JSEXN_SYNTAXERR, "missing ) after with-statement object") -MSG_DEF(JSMSG_PAREN_BEFORE_CATCH, 0, JSEXN_SYNTAXERR, "missing ( before catch") -MSG_DEF(JSMSG_PAREN_BEFORE_COND, 0, JSEXN_SYNTAXERR, "missing ( before condition") -MSG_DEF(JSMSG_PAREN_BEFORE_FORMAL, 0, JSEXN_SYNTAXERR, "missing ( before formal parameters") -MSG_DEF(JSMSG_PAREN_BEFORE_SWITCH, 0, JSEXN_SYNTAXERR, "missing ( before switch expression") -MSG_DEF(JSMSG_PAREN_BEFORE_WITH, 0, JSEXN_SYNTAXERR, "missing ( before with-statement object") -MSG_DEF(JSMSG_PAREN_IN_PAREN, 0, JSEXN_SYNTAXERR, "missing ) in parenthetical") -MSG_DEF(JSMSG_RC_AFTER_EXPORT_SPEC_LIST, 0, JSEXN_SYNTAXERR, "missing '}' after export specifier list") -MSG_DEF(JSMSG_RC_AFTER_IMPORT_SPEC_LIST, 0, JSEXN_SYNTAXERR, "missing '}' after module specifier list") -MSG_DEF(JSMSG_REDECLARED_CATCH_IDENTIFIER, 1, JSEXN_SYNTAXERR, "redeclaration of identifier '{0}' in catch") -MSG_DEF(JSMSG_RESERVED_ID, 1, JSEXN_SYNTAXERR, "{0} is a reserved identifier") -MSG_DEF(JSMSG_REST_WITH_COMMA, 0, JSEXN_SYNTAXERR, "rest element may not have a trailing comma") -MSG_DEF(JSMSG_REST_WITH_DEFAULT, 0, JSEXN_SYNTAXERR, "rest parameter may not have a default") -MSG_DEF(JSMSG_SELFHOSTED_TOP_LEVEL_LEXICAL, 1, JSEXN_SYNTAXERR, "self-hosted code cannot contain top-level {0} declarations") -MSG_DEF(JSMSG_SELFHOSTED_METHOD_CALL, 0, JSEXN_SYNTAXERR, "self-hosted code may not contain direct method calls. Use callFunction() or callContentFunction()") -MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") -MSG_DEF(JSMSG_SEMI_AFTER_FOR_COND, 0, JSEXN_SYNTAXERR, "missing ; after for-loop condition") -MSG_DEF(JSMSG_SEMI_AFTER_FOR_INIT, 0, JSEXN_SYNTAXERR, "missing ; after for-loop initializer") -MSG_DEF(JSMSG_SEMI_BEFORE_STMNT, 0, JSEXN_SYNTAXERR, "missing ; before statement") -MSG_DEF(JSMSG_SOURCE_TOO_LONG, 0, JSEXN_RANGEERR, "source is too long") -MSG_DEF(JSMSG_STMT_AFTER_RETURN, 0, JSEXN_WARN, "unreachable code after return statement") -MSG_DEF(JSMSG_STRICT_CODE_WITH, 0, JSEXN_SYNTAXERR, "strict mode code may not contain 'with' statements") -MSG_DEF(JSMSG_STRICT_NON_SIMPLE_PARAMS, 1, JSEXN_SYNTAXERR, "\"use strict\" not allowed in function with {0} parameter") -MSG_DEF(JSMSG_TEMPLSTR_UNTERM_EXPR, 0, JSEXN_SYNTAXERR, "missing } in template string") -MSG_DEF(JSMSG_SIMD_NOT_A_VECTOR, 2, JSEXN_TYPEERR, "expecting a SIMD {0} object as argument {1}") -MSG_DEF(JSMSG_TOO_MANY_CASES, 0, JSEXN_INTERNALERR, "too many switch cases") -MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 0, JSEXN_SYNTAXERR, "too many catch variables") -MSG_DEF(JSMSG_TOO_MANY_CON_ARGS, 0, JSEXN_SYNTAXERR, "too many constructor arguments") -MSG_DEF(JSMSG_TOO_MANY_DEFAULTS, 0, JSEXN_SYNTAXERR, "more than one switch default") -MSG_DEF(JSMSG_TOO_MANY_FUN_ARGS, 0, JSEXN_SYNTAXERR, "too many function arguments") -MSG_DEF(JSMSG_TOO_MANY_LOCALS, 0, JSEXN_SYNTAXERR, "too many local variables") -MSG_DEF(JSMSG_TOO_MANY_YIELDS, 0, JSEXN_SYNTAXERR, "too many yield expressions") -MSG_DEF(JSMSG_TOUGH_BREAK, 0, JSEXN_SYNTAXERR, "unlabeled break must be inside loop or switch") -MSG_DEF(JSMSG_UNEXPECTED_TOKEN, 2, JSEXN_SYNTAXERR, "expected {0}, got {1}") -MSG_DEF(JSMSG_UNNAMED_CLASS_STMT, 0, JSEXN_SYNTAXERR, "class statement requires a name") -MSG_DEF(JSMSG_UNNAMED_FUNCTION_STMT, 0, JSEXN_SYNTAXERR, "function statement requires a name") -MSG_DEF(JSMSG_UNTERMINATED_COMMENT, 0, JSEXN_SYNTAXERR, "unterminated comment") -MSG_DEF(JSMSG_UNTERMINATED_REGEXP, 0, JSEXN_SYNTAXERR, "unterminated regular expression literal") -MSG_DEF(JSMSG_UNTERMINATED_STRING, 0, JSEXN_SYNTAXERR, "unterminated string literal") -MSG_DEF(JSMSG_USELESS_EXPR, 0, JSEXN_TYPEERR, "useless expression") -MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 0, JSEXN_SYNTAXERR, "\"use asm\" is only meaningful in the Directive Prologue of a function body") -MSG_DEF(JSMSG_VAR_HIDES_ARG, 1, JSEXN_TYPEERR, "variable {0} redeclares argument") -MSG_DEF(JSMSG_WHILE_AFTER_DO, 0, JSEXN_SYNTAXERR, "missing while after do-loop body") -MSG_DEF(JSMSG_YIELD_IN_ARROW, 0, JSEXN_SYNTAXERR, "arrow function may not contain yield") -MSG_DEF(JSMSG_YIELD_IN_DEFAULT, 0, JSEXN_SYNTAXERR, "yield in default expression") -MSG_DEF(JSMSG_YIELD_IN_METHOD, 0, JSEXN_SYNTAXERR, "non-generator method definitions may not contain yield") -MSG_DEF(JSMSG_BAD_COLUMN_NUMBER, 0, JSEXN_RANGEERR, "column number out of range") -MSG_DEF(JSMSG_COMPUTED_NAME_IN_PATTERN,0, JSEXN_SYNTAXERR, "computed property names aren't supported in this destructuring declaration") -MSG_DEF(JSMSG_DEFAULT_IN_PATTERN, 0, JSEXN_SYNTAXERR, "destructuring defaults aren't supported in this destructuring declaration") -MSG_DEF(JSMSG_BAD_NEWTARGET, 0, JSEXN_SYNTAXERR, "new.target only allowed within functions") -MSG_DEF(JSMSG_ESCAPED_KEYWORD, 0, JSEXN_SYNTAXERR, "keywords must be written literally, without embedded escapes") - -// asm.js -MSG_DEF(JSMSG_USE_ASM_TYPE_FAIL, 1, JSEXN_TYPEERR, "asm.js type error: {0}") -MSG_DEF(JSMSG_USE_ASM_LINK_FAIL, 1, JSEXN_TYPEERR, "asm.js link error: {0}") -MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 1, JSEXN_WARN, "Successfully compiled asm.js code ({0})") - -// wasm -MSG_DEF(JSMSG_WASM_COMPILE_ERROR, 1, JSEXN_WASMCOMPILEERROR, "{0}") -MSG_DEF(JSMSG_WASM_IND_CALL_TO_NULL, 0, JSEXN_WASMRUNTIMEERROR, "indirect call to null") -MSG_DEF(JSMSG_WASM_IND_CALL_BAD_SIG, 0, JSEXN_WASMRUNTIMEERROR, "indirect call signature mismatch") -MSG_DEF(JSMSG_WASM_UNREACHABLE, 0, JSEXN_WASMRUNTIMEERROR, "unreachable executed") -MSG_DEF(JSMSG_WASM_INTEGER_OVERFLOW, 0, JSEXN_WASMRUNTIMEERROR, "integer overflow") -MSG_DEF(JSMSG_WASM_INVALID_CONVERSION, 0, JSEXN_WASMRUNTIMEERROR, "invalid conversion to integer") -MSG_DEF(JSMSG_WASM_INT_DIVIDE_BY_ZERO, 0, JSEXN_WASMRUNTIMEERROR, "integer divide by zero") -MSG_DEF(JSMSG_WASM_OUT_OF_BOUNDS, 0, JSEXN_WASMRUNTIMEERROR, "index out of bounds") -MSG_DEF(JSMSG_WASM_UNALIGNED_ACCESS, 0, JSEXN_WASMRUNTIMEERROR, "unaligned memory access") -MSG_DEF(JSMSG_WASM_BAD_UINT32, 2, JSEXN_RANGEERR, "bad {0} {1}") -MSG_DEF(JSMSG_WASM_BAD_GROW, 1, JSEXN_RANGEERR, "failed to grow {0}") -MSG_DEF(JSMSG_WASM_BAD_FIT, 2, JSEXN_RANGEERR, "{0} segment does not fit in {1}") -MSG_DEF(JSMSG_WASM_BAD_BUF_ARG, 0, JSEXN_TYPEERR, "first argument must be an ArrayBuffer or typed array object") -MSG_DEF(JSMSG_WASM_BAD_MOD_ARG, 0, JSEXN_TYPEERR, "first argument must be a WebAssembly.Module") -MSG_DEF(JSMSG_WASM_BAD_BUF_MOD_ARG, 0, JSEXN_TYPEERR, "first argument must be a WebAssembly.Module, ArrayBuffer or typed array object") -MSG_DEF(JSMSG_WASM_BAD_DESC_ARG, 1, JSEXN_TYPEERR, "first argument must be a {0} descriptor") -MSG_DEF(JSMSG_WASM_BAD_IMP_SIZE, 1, JSEXN_TYPEERR, "imported {0} with incompatible size") -MSG_DEF(JSMSG_WASM_BAD_IMP_MAX, 1, JSEXN_TYPEERR, "imported {0} with incompatible maximum size") -MSG_DEF(JSMSG_WASM_BAD_ELEMENT, 0, JSEXN_TYPEERR, "\"element\" property of table descriptor must be \"anyfunc\"") -MSG_DEF(JSMSG_WASM_BAD_IMPORT_ARG, 0, JSEXN_TYPEERR, "second argument must be an object") -MSG_DEF(JSMSG_WASM_BAD_IMPORT_FIELD, 2, JSEXN_TYPEERR, "import object field '{0}' is not {1}") -MSG_DEF(JSMSG_WASM_BAD_IMPORT_SIG, 0, JSEXN_TYPEERR, "imported function signature mismatch") -MSG_DEF(JSMSG_WASM_BAD_TABLE_VALUE, 0, JSEXN_TYPEERR, "can only assign WebAssembly exported functions to Table") -MSG_DEF(JSMSG_WASM_BAD_I64, 0, JSEXN_TYPEERR, "cannot pass i64 to or from JS") -MSG_DEF(JSMSG_WASM_NO_TRANSFER, 0, JSEXN_TYPEERR, "cannot transfer WebAssembly/asm.js ArrayBuffer") -MSG_DEF(JSMSG_WASM_TEXT_FAIL, 1, JSEXN_SYNTAXERR, "wasm text error: {0}") - -// Proxy -MSG_DEF(JSMSG_BAD_TRAP_RETURN_VALUE, 2, JSEXN_TYPEERR,"trap {1} for {0} returned a primitive value") -MSG_DEF(JSMSG_BAD_GETPROTOTYPEOF_TRAP_RETURN,0,JSEXN_TYPEERR,"proxy getPrototypeOf handler returned a non-object, non-null value") -MSG_DEF(JSMSG_INCONSISTENT_GETPROTOTYPEOF_TRAP,0,JSEXN_TYPEERR,"proxy getPrototypeOf handler didn't return the target object's prototype") -MSG_DEF(JSMSG_PROXY_SETPROTOTYPEOF_RETURNED_FALSE, 0, JSEXN_TYPEERR, "proxy setPrototypeOf handler returned false") -MSG_DEF(JSMSG_PROXY_ISEXTENSIBLE_RETURNED_FALSE,0,JSEXN_TYPEERR,"proxy isExtensible handler must return the same extensibility as target") -MSG_DEF(JSMSG_INCONSISTENT_SETPROTOTYPEOF_TRAP,0,JSEXN_TYPEERR,"proxy setPrototypeOf handler returned true, even though the target's prototype is immutable because the target is non-extensible") -MSG_DEF(JSMSG_CANT_CHANGE_EXTENSIBILITY, 0, JSEXN_TYPEERR, "can't change object's extensibility") -MSG_DEF(JSMSG_CANT_DEFINE_INVALID, 0, JSEXN_TYPEERR, "proxy can't define an incompatible property descriptor") -MSG_DEF(JSMSG_CANT_DEFINE_NEW, 0, JSEXN_TYPEERR, "proxy can't define a new property on a non-extensible object") -MSG_DEF(JSMSG_CANT_DEFINE_NE_AS_NC, 0, JSEXN_TYPEERR, "proxy can't define a non-existent property as non-configurable") -MSG_DEF(JSMSG_PROXY_DEFINE_RETURNED_FALSE, 1, JSEXN_TYPEERR, "proxy defineProperty handler returned false for property '{0}'") -MSG_DEF(JSMSG_PROXY_DELETE_RETURNED_FALSE, 1, JSEXN_TYPEERR, "can't delete property '{0}': proxy deleteProperty handler returned false") -MSG_DEF(JSMSG_PROXY_PREVENTEXTENSIONS_RETURNED_FALSE, 0, JSEXN_TYPEERR, "proxy preventExtensions handler returned false") -MSG_DEF(JSMSG_PROXY_SET_RETURNED_FALSE, 1, JSEXN_TYPEERR, "proxy set handler returned false for property '{0}'") -MSG_DEF(JSMSG_CANT_REPORT_AS_NON_EXTENSIBLE, 0, JSEXN_TYPEERR, "proxy can't report an extensible object as non-extensible") -MSG_DEF(JSMSG_CANT_REPORT_C_AS_NC, 0, JSEXN_TYPEERR, "proxy can't report existing configurable property as non-configurable") -MSG_DEF(JSMSG_CANT_REPORT_E_AS_NE, 0, JSEXN_TYPEERR, "proxy can't report an existing own property as non-existent on a non-extensible object") -MSG_DEF(JSMSG_CANT_REPORT_INVALID, 0, JSEXN_TYPEERR, "proxy can't report an incompatible property descriptor") -MSG_DEF(JSMSG_CANT_REPORT_NC_AS_NE, 0, JSEXN_TYPEERR, "proxy can't report a non-configurable own property as non-existent") -MSG_DEF(JSMSG_CANT_REPORT_NEW, 0, JSEXN_TYPEERR, "proxy can't report a new property on a non-extensible object") -MSG_DEF(JSMSG_CANT_REPORT_NE_AS_NC, 0, JSEXN_TYPEERR, "proxy can't report a non-existent property as non-configurable") -MSG_DEF(JSMSG_CANT_SET_NW_NC, 0, JSEXN_TYPEERR, "proxy can't successfully set a non-writable, non-configurable property") -MSG_DEF(JSMSG_CANT_SET_WO_SETTER, 0, JSEXN_TYPEERR, "proxy can't succesfully set an accessor property without a setter") -MSG_DEF(JSMSG_CANT_SKIP_NC, 0, JSEXN_TYPEERR, "proxy can't skip a non-configurable property") -MSG_DEF(JSMSG_ONWKEYS_STR_SYM, 0, JSEXN_TYPEERR, "proxy [[OwnPropertyKeys]] must return an array with only string and symbol elements") -MSG_DEF(JSMSG_MUST_REPORT_SAME_VALUE, 0, JSEXN_TYPEERR, "proxy must report the same value for a non-writable, non-configurable property") -MSG_DEF(JSMSG_MUST_REPORT_UNDEFINED, 0, JSEXN_TYPEERR, "proxy must report undefined for a non-configurable accessor property without a getter") -MSG_DEF(JSMSG_OBJECT_ACCESS_DENIED, 0, JSEXN_ERR, "Permission denied to access object") -MSG_DEF(JSMSG_PROPERTY_ACCESS_DENIED, 1, JSEXN_ERR, "Permission denied to access property {0}") -MSG_DEF(JSMSG_PROXY_CONSTRUCT_OBJECT, 0, JSEXN_TYPEERR, "proxy [[Construct]] must return an object") -MSG_DEF(JSMSG_PROXY_EXTENSIBILITY, 0, JSEXN_TYPEERR, "proxy must report same extensiblitity as target") -MSG_DEF(JSMSG_PROXY_GETOWN_OBJORUNDEF, 0, JSEXN_TYPEERR, "proxy [[GetOwnProperty]] must return an object or undefined") -MSG_DEF(JSMSG_PROXY_REVOKED, 0, JSEXN_TYPEERR, "illegal operation attempted on a revoked proxy") -MSG_DEF(JSMSG_PROXY_ARG_REVOKED, 1, JSEXN_TYPEERR, "argument {0} cannot be a revoked proxy") -MSG_DEF(JSMSG_BAD_TRAP, 1, JSEXN_TYPEERR, "proxy handler's {0} trap wasn't undefined, null, or callable") - -// Structured cloning -MSG_DEF(JSMSG_SC_BAD_CLONE_VERSION, 0, JSEXN_ERR, "unsupported structured clone version") -MSG_DEF(JSMSG_SC_BAD_SERIALIZED_DATA, 1, JSEXN_INTERNALERR, "bad serialized structured data ({0})") -MSG_DEF(JSMSG_SC_DUP_TRANSFERABLE, 0, JSEXN_TYPEERR, "duplicate transferable for structured clone") -MSG_DEF(JSMSG_SC_NOT_TRANSFERABLE, 0, JSEXN_TYPEERR, "invalid transferable array for structured clone") -MSG_DEF(JSMSG_SC_UNSUPPORTED_TYPE, 0, JSEXN_TYPEERR, "unsupported type for structured data") -MSG_DEF(JSMSG_SC_NOT_CLONABLE, 1, JSEXN_TYPEERR, "{0} cannot be cloned in this context") -MSG_DEF(JSMSG_SC_SAB_TRANSFER, 0, JSEXN_WARN, "SharedArrayBuffer must not be in the transfer list") -MSG_DEF(JSMSG_SC_SAB_DISABLED, 0, JSEXN_TYPEERR, "SharedArrayBuffer not cloned - shared memory disabled in receiver") - -// Debugger -MSG_DEF(JSMSG_ASSIGN_FUNCTION_OR_NULL, 1, JSEXN_TYPEERR, "value assigned to {0} must be a function or null") -MSG_DEF(JSMSG_DEBUG_BAD_AWAIT, 0, JSEXN_TYPEERR, "await expression received invalid value") -MSG_DEF(JSMSG_DEBUG_BAD_LINE, 0, JSEXN_TYPEERR, "invalid line number") -MSG_DEF(JSMSG_DEBUG_BAD_OFFSET, 0, JSEXN_TYPEERR, "invalid script offset") -MSG_DEF(JSMSG_DEBUG_BAD_REFERENT, 2, JSEXN_TYPEERR, "{0} does not refer to {1}") -MSG_DEF(JSMSG_DEBUG_BAD_RESUMPTION, 0, JSEXN_TYPEERR, "debugger resumption value must be undefined, {throw: val}, {return: val}, or null") -MSG_DEF(JSMSG_DEBUG_BAD_YIELD, 0, JSEXN_TYPEERR, "generator yielded invalid value") -MSG_DEF(JSMSG_DEBUG_CANT_DEBUG_GLOBAL, 0, JSEXN_TYPEERR, "passing non-debuggable global to addDebuggee") -MSG_DEF(JSMSG_DEBUG_CCW_REQUIRED, 1, JSEXN_TYPEERR, "{0}: argument must be an object from a different compartment") -MSG_DEF(JSMSG_DEBUG_COMPARTMENT_MISMATCH, 2, JSEXN_TYPEERR, "{0}: descriptor .{1} property is an object in a different compartment than the target object") -MSG_DEF(JSMSG_DEBUG_LOOP, 0, JSEXN_TYPEERR, "cannot debug an object in same compartment as debugger or a compartment that is already debugging the debugger") -MSG_DEF(JSMSG_DEBUG_NOT_DEBUGGEE, 2, JSEXN_ERR, "{0} is not a debuggee {1}") -MSG_DEF(JSMSG_DEBUG_NOT_DEBUGGING, 0, JSEXN_ERR, "can't set breakpoint: script global is not a debuggee") -MSG_DEF(JSMSG_DEBUG_NOT_IDLE, 0, JSEXN_ERR, "can't start debugging: a debuggee script is on the stack") -MSG_DEF(JSMSG_DEBUG_NOT_LIVE, 1, JSEXN_ERR, "{0} is not live") -MSG_DEF(JSMSG_DEBUG_NO_ENV_OBJECT, 0, JSEXN_TYPEERR, "declarative Environments don't have binding objects") -MSG_DEF(JSMSG_DEBUG_PROTO, 2, JSEXN_TYPEERR, "{0}.prototype is not a valid {1} instance") -MSG_DEF(JSMSG_DEBUG_WRONG_OWNER, 1, JSEXN_TYPEERR, "{0} belongs to a different Debugger") -MSG_DEF(JSMSG_DEBUG_OPTIMIZED_OUT, 1, JSEXN_ERR, "variable `{0}' has been optimized out") -MSG_DEF(JSMSG_DEBUG_RESUMPTION_VALUE_DISALLOWED, 0, JSEXN_TYPEERR, "resumption values are disallowed in this hook") -MSG_DEF(JSMSG_DEBUG_VARIABLE_NOT_FOUND,0, JSEXN_TYPEERR, "variable not found in environment") -MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 3, JSEXN_TYPEERR, "{0} is {1}{2}a global object, but a direct reference is required") -MSG_DEF(JSMSG_DEBUGGEE_WOULD_RUN, 2, JSEXN_DEBUGGEEWOULDRUN, "debuggee `{0}:{1}' would run") -MSG_DEF(JSMSG_NOT_CALLABLE_OR_UNDEFINED, 0, JSEXN_TYPEERR, "value is not a function or undefined") -MSG_DEF(JSMSG_NOT_TRACKING_ALLOCATIONS, 1, JSEXN_ERR, "Cannot call {0} without setting trackingAllocationSites to true") -MSG_DEF(JSMSG_OBJECT_METADATA_CALLBACK_ALREADY_SET, 0, JSEXN_ERR, "Cannot track object allocation, because other tools are already doing so") -MSG_DEF(JSMSG_QUERY_INNERMOST_WITHOUT_LINE_URL, 0, JSEXN_TYPEERR, "findScripts query object with 'innermost' property must have 'line' and either 'displayURL', 'url', or 'source'") -MSG_DEF(JSMSG_QUERY_LINE_WITHOUT_URL, 0, JSEXN_TYPEERR, "findScripts query object has 'line' property, but no 'displayURL', 'url', or 'source' property") -MSG_DEF(JSMSG_DEBUG_CANT_SET_OPT_ENV, 1, JSEXN_REFERENCEERR, "can't set `{0}' in an optimized-out environment") -MSG_DEF(JSMSG_DEBUG_INVISIBLE_COMPARTMENT, 0, JSEXN_TYPEERR, "object in compartment marked as invisible to Debugger") -MSG_DEF(JSMSG_DEBUG_CENSUS_BREAKDOWN, 1, JSEXN_TYPEERR, "unrecognized 'by' value in takeCensus breakdown: {0}") -MSG_DEF(JSMSG_DEBUG_PROMISE_NOT_RESOLVED, 0, JSEXN_TYPEERR, "Promise hasn't been resolved") -MSG_DEF(JSMSG_DEBUG_PROMISE_NOT_FULFILLED, 0, JSEXN_TYPEERR, "Promise hasn't been fulfilled") -MSG_DEF(JSMSG_DEBUG_PROMISE_NOT_REJECTED, 0, JSEXN_TYPEERR, "Promise hasn't been rejected") - -// Tracelogger -MSG_DEF(JSMSG_TRACELOGGER_ENABLE_FAIL, 1, JSEXN_ERR, "enabling tracelogger failed: {0}") - -// Intl -MSG_DEF(JSMSG_DATE_NOT_FINITE, 0, JSEXN_RANGEERR, "date value is not finite in DateTimeFormat.format()") -MSG_DEF(JSMSG_INTERNAL_INTL_ERROR, 0, JSEXN_ERR, "internal error while computing Intl data") -MSG_DEF(JSMSG_INTL_OBJECT_NOT_INITED, 3, JSEXN_TYPEERR, "Intl.{0}.prototype.{1} called on value that's not an object initialized as a {2}") -MSG_DEF(JSMSG_INTL_OBJECT_REINITED, 0, JSEXN_TYPEERR, "can't initialize object twice as an object of an Intl constructor") -MSG_DEF(JSMSG_INVALID_CURRENCY_CODE, 1, JSEXN_RANGEERR, "invalid currency code in NumberFormat(): {0}") -MSG_DEF(JSMSG_INVALID_DIGITS_VALUE, 1, JSEXN_RANGEERR, "invalid digits value: {0}") -MSG_DEF(JSMSG_INVALID_LANGUAGE_TAG, 1, JSEXN_RANGEERR, "invalid language tag: {0}") -MSG_DEF(JSMSG_INVALID_LOCALES_ELEMENT, 0, JSEXN_TYPEERR, "invalid element in locales argument") -MSG_DEF(JSMSG_INVALID_LOCALE_MATCHER, 1, JSEXN_RANGEERR, "invalid locale matcher in supportedLocalesOf(): {0}") -MSG_DEF(JSMSG_INVALID_OPTION_VALUE, 2, JSEXN_RANGEERR, "invalid value {1} for option {0}") -MSG_DEF(JSMSG_INVALID_TIME_ZONE, 1, JSEXN_RANGEERR, "invalid time zone in DateTimeFormat(): {0}") -MSG_DEF(JSMSG_UNDEFINED_CURRENCY, 0, JSEXN_TYPEERR, "undefined currency in NumberFormat() with currency style") - -// RegExp -MSG_DEF(JSMSG_BACK_REF_OUT_OF_RANGE, 0, JSEXN_SYNTAXERR, "back reference out of range in regular expression") -MSG_DEF(JSMSG_BAD_CLASS_RANGE, 0, JSEXN_SYNTAXERR, "invalid range in character class") -MSG_DEF(JSMSG_ESCAPE_AT_END_OF_REGEXP, 0, JSEXN_SYNTAXERR, "\\ at end of pattern") -MSG_DEF(JSMSG_EXEC_NOT_OBJORNULL, 0, JSEXN_TYPEERR, "RegExp exec method should return object or null") -MSG_DEF(JSMSG_INVALID_DECIMAL_ESCAPE, 0, JSEXN_SYNTAXERR, "invalid decimal escape in regular expression") -MSG_DEF(JSMSG_INVALID_GROUP, 0, JSEXN_SYNTAXERR, "invalid regexp group") -MSG_DEF(JSMSG_INVALID_IDENTITY_ESCAPE, 0, JSEXN_SYNTAXERR, "invalid identity escape in regular expression") -MSG_DEF(JSMSG_INVALID_UNICODE_ESCAPE, 0, JSEXN_SYNTAXERR, "invalid unicode escape in regular expression") -MSG_DEF(JSMSG_MISSING_PAREN, 0, JSEXN_SYNTAXERR, "unterminated parenthetical") -MSG_DEF(JSMSG_NEWREGEXP_FLAGGED, 0, JSEXN_TYPEERR, "can't supply flags when constructing one RegExp from another") -MSG_DEF(JSMSG_NOTHING_TO_REPEAT, 0, JSEXN_SYNTAXERR, "nothing to repeat") -MSG_DEF(JSMSG_NUMBERS_OUT_OF_ORDER, 0, JSEXN_SYNTAXERR, "numbers out of order in {} quantifier.") -MSG_DEF(JSMSG_RANGE_WITH_CLASS_ESCAPE, 0, JSEXN_SYNTAXERR, "character class escape cannot be used in class range in regular expression") -MSG_DEF(JSMSG_RAW_BRACE_IN_REGEP, 0, JSEXN_SYNTAXERR, "raw brace is not allowed in regular expression with unicode flag") -MSG_DEF(JSMSG_RAW_BRACKET_IN_REGEP, 0, JSEXN_SYNTAXERR, "raw bracket is not allowed in regular expression with unicode flag") -MSG_DEF(JSMSG_TOO_MANY_PARENS, 0, JSEXN_INTERNALERR, "too many parentheses in regular expression") -MSG_DEF(JSMSG_UNICODE_OVERFLOW, 0, JSEXN_SYNTAXERR, "unicode codepoint should not be greater than 0x10FFFF in regular expression") -MSG_DEF(JSMSG_UNMATCHED_RIGHT_PAREN, 0, JSEXN_SYNTAXERR, "unmatched ) in regular expression") -MSG_DEF(JSMSG_UNTERM_CLASS, 0, JSEXN_SYNTAXERR, "unterminated character class") - -// Self-hosting -MSG_DEF(JSMSG_DEFAULT_LOCALE_ERROR, 0, JSEXN_ERR, "internal error getting the default locale") -MSG_DEF(JSMSG_NO_SUCH_SELF_HOSTED_PROP,1, JSEXN_ERR, "No such property on self-hosted object: {0}") - -// Typed object / SIMD -MSG_DEF(JSMSG_INVALID_PROTOTYPE, 0, JSEXN_TYPEERR, "prototype field is not an object") -MSG_DEF(JSMSG_TYPEDOBJECT_BAD_ARGS, 0, JSEXN_TYPEERR, "invalid arguments") -MSG_DEF(JSMSG_TYPEDOBJECT_BINARYARRAY_BAD_INDEX, 0, JSEXN_RANGEERR, "invalid or out-of-range index") -MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_UNATTACHED, 0, JSEXN_TYPEERR, "handle unattached") -MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_ARGS, 0, JSEXN_RANGEERR, "invalid field descriptor") -MSG_DEF(JSMSG_TYPEDOBJECT_TOO_BIG, 0, JSEXN_ERR, "Type is too large to allocate") -MSG_DEF(JSMSG_SIMD_FAILED_CONVERSION, 0, JSEXN_RANGEERR, "SIMD conversion loses precision") -MSG_DEF(JSMSG_SIMD_TO_NUMBER, 0, JSEXN_TYPEERR, "can't convert SIMD value to number") - -// Array -MSG_DEF(JSMSG_TOO_LONG_ARRAY, 0, JSEXN_TYPEERR, "Too long array") - -// Typed array -MSG_DEF(JSMSG_BAD_INDEX, 0, JSEXN_RANGEERR, "invalid or out-of-range index") -MSG_DEF(JSMSG_NON_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected ArrayBuffer, but species constructor returned non-ArrayBuffer") -MSG_DEF(JSMSG_SAME_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected different ArrayBuffer, but species constructor returned same ArrayBuffer") -MSG_DEF(JSMSG_SHORT_ARRAY_BUFFER_RETURNED, 2, JSEXN_TYPEERR, "expected ArrayBuffer with at least {0} bytes, but species constructor returns ArrayBuffer with {1} bytes") -MSG_DEF(JSMSG_TYPED_ARRAY_BAD_ARGS, 0, JSEXN_TYPEERR, "invalid arguments") -MSG_DEF(JSMSG_TYPED_ARRAY_NEGATIVE_ARG,1, JSEXN_RANGEERR, "argument {0} must be >= 0") -MSG_DEF(JSMSG_TYPED_ARRAY_DETACHED, 0, JSEXN_TYPEERR, "attempting to access detached ArrayBuffer") -MSG_DEF(JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS, 0, JSEXN_RANGEERR, "attempting to construct out-of-bounds TypedArray on ArrayBuffer") -MSG_DEF(JSMSG_TYPED_ARRAY_CALL_OR_CONSTRUCT, 1, JSEXN_TYPEERR, "cannot directly {0} builtin %TypedArray%") -MSG_DEF(JSMSG_NON_TYPED_ARRAY_RETURNED, 0, JSEXN_TYPEERR, "constructor didn't return TypedArray object") -MSG_DEF(JSMSG_SHORT_TYPED_ARRAY_RETURNED, 2, JSEXN_TYPEERR, "expected TypedArray of at least length {0}, but constructor returned TypedArray of length {1}") - -// Shared array buffer -MSG_DEF(JSMSG_SHARED_ARRAY_BAD_LENGTH, 0, JSEXN_RANGEERR, "length argument out of range") -MSG_DEF(JSMSG_NON_SHARED_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected SharedArrayBuffer, but species constructor returned non-SharedArrayBuffer") -MSG_DEF(JSMSG_SAME_SHARED_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected different SharedArrayBuffer, but species constructor returned same SharedArrayBuffer") -MSG_DEF(JSMSG_SHORT_SHARED_ARRAY_BUFFER_RETURNED, 2, JSEXN_TYPEERR, "expected SharedArrayBuffer with at least {0} bytes, but species constructor returns SharedArrayBuffer with {1} bytes") - -// Reflect -MSG_DEF(JSMSG_BAD_PARSE_NODE, 0, JSEXN_INTERNALERR, "bad parse node") - -// Symbol -MSG_DEF(JSMSG_SYMBOL_TO_STRING, 0, JSEXN_TYPEERR, "can't convert symbol to string") -MSG_DEF(JSMSG_SYMBOL_TO_NUMBER, 0, JSEXN_TYPEERR, "can't convert symbol to number") - -// Atomics and futexes -MSG_DEF(JSMSG_ATOMICS_BAD_ARRAY, 0, JSEXN_TYPEERR, "invalid array type for the operation") -MSG_DEF(JSMSG_ATOMICS_TOO_LONG, 0, JSEXN_RANGEERR, "timeout value too large") -MSG_DEF(JSMSG_ATOMICS_WAIT_NOT_ALLOWED, 0, JSEXN_ERR, "waiting is not allowed on this thread") - -// XPConnect wrappers and DOM bindings -MSG_DEF(JSMSG_CANT_SET_INTERPOSED, 1, JSEXN_TYPEERR, "unable to set interposed data property '{0}'") -MSG_DEF(JSMSG_CANT_DEFINE_WINDOW_ELEMENT, 0, JSEXN_TYPEERR, "can't define elements on a Window object") -MSG_DEF(JSMSG_CANT_DELETE_WINDOW_ELEMENT, 0, JSEXN_TYPEERR, "can't delete elements from a Window object") -MSG_DEF(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY, 1, JSEXN_TYPEERR, "can't delete property {0} from window's named properties object") -MSG_DEF(JSMSG_CANT_PREVENT_EXTENSIONS, 0, JSEXN_TYPEERR, "can't prevent extensions on this proxy object") -MSG_DEF(JSMSG_NO_NAMED_SETTER, 2, JSEXN_TYPEERR, "{0} doesn't have a named property setter for '{1}'") -MSG_DEF(JSMSG_NO_INDEXED_SETTER, 2, JSEXN_TYPEERR, "{0} doesn't have an indexed property setter for '{1}'") - -// Super -MSG_DEF(JSMSG_CANT_DELETE_SUPER, 0, JSEXN_REFERENCEERR, "invalid delete involving 'super'") -MSG_DEF(JSMSG_REINIT_THIS, 0, JSEXN_REFERENCEERR, "super() called twice in derived class constructor") - -// Modules -MSG_DEF(JSMSG_BAD_DEFAULT_EXPORT, 0, JSEXN_SYNTAXERR, "default export cannot be provided by export *") -MSG_DEF(JSMSG_MISSING_INDIRECT_EXPORT, 1, JSEXN_SYNTAXERR, "indirect export '{0}' not found") -MSG_DEF(JSMSG_AMBIGUOUS_INDIRECT_EXPORT, 1, JSEXN_SYNTAXERR, "ambiguous indirect export '{0}'") -MSG_DEF(JSMSG_MISSING_IMPORT, 1, JSEXN_SYNTAXERR, "import '{0}' not found") -MSG_DEF(JSMSG_AMBIGUOUS_IMPORT, 1, JSEXN_SYNTAXERR, "ambiguous import '{0}'") -MSG_DEF(JSMSG_MISSING_NAMESPACE_EXPORT, 0, JSEXN_SYNTAXERR, "export not found for namespace") -MSG_DEF(JSMSG_MISSING_EXPORT, 1, JSEXN_SYNTAXERR, "local binding for export '{0}' not found") -MSG_DEF(JSMSG_MODULE_INSTANTIATE_FAILED, 0, JSEXN_INTERNALERR, "attempt to re-instantiate module after failure") -MSG_DEF(JSMSG_BAD_MODULE_STATE, 0, JSEXN_INTERNALERR, "module record in unexpected state") - -// Promise -MSG_DEF(JSMSG_CANNOT_RESOLVE_PROMISE_WITH_ITSELF, 0, JSEXN_TYPEERR, "A promise cannot be resolved with itself.") -MSG_DEF(JSMSG_PROMISE_CAPABILITY_HAS_SOMETHING_ALREADY, 0, JSEXN_TYPEERR, "GetCapabilitiesExecutor function already invoked with non-undefined values.") -MSG_DEF(JSMSG_PROMISE_RESOLVE_FUNCTION_NOT_CALLABLE, 0, JSEXN_TYPEERR, "A Promise subclass passed a non-callable value as the resolve function.") -MSG_DEF(JSMSG_PROMISE_REJECT_FUNCTION_NOT_CALLABLE, 0, JSEXN_TYPEERR, "A Promise subclass passed a non-callable value as the reject function.") -MSG_DEF(JSMSG_PROMISE_ERROR_IN_WRAPPED_REJECTION_REASON,0, JSEXN_INTERNALERR, "Promise rejection value is a non-unwrappable cross-compartment wrapper.") diff --git a/mac/include/spidermonkey/js/CallArgs.h b/mac/include/spidermonkey/js/CallArgs.h deleted file mode 100644 index 1e0d909a..00000000 --- a/mac/include/spidermonkey/js/CallArgs.h +++ /dev/null @@ -1,369 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Helper classes encapsulating access to the callee, |this| value, arguments, - * and argument count for a call/construct operation. - * - * JS::CallArgs encapsulates access to a JSNative's un-abstracted - * |unsigned argc, Value* vp| arguments. The principal way to create a - * JS::CallArgs is using JS::CallArgsFromVp: - * - * // If provided no arguments or a non-numeric first argument, return zero. - * // Otherwise return |this| exactly as given, without boxing. - * static bool - * Func(JSContext* cx, unsigned argc, JS::Value* vp) - * { - * JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - * - * // Guard against no arguments or a non-numeric arg0. - * if (args.length() == 0 || !args[0].isNumber()) { - * args.rval().setInt32(0); - * return true; - * } - * - * // Access to the callee must occur before accessing/setting - * // the return value. - * JSObject& callee = args.callee(); - * args.rval().setObject(callee); - * - * // callee() and calleev() will now assert. - * - * // It's always fine to access thisv(). - * HandleValue thisv = args.thisv(); - * args.rval().set(thisv); - * - * // As the return value was last set to |this|, returns |this|. - * return true; - * } - * - * CallArgs is exposed publicly and used internally. Not all parts of its - * public interface are meant to be used by embedders! See inline comments to - * for details. - * - * It's possible (albeit deprecated) to manually index into |vp| to access the - * callee, |this|, and arguments of a function, and to set its return value. - * It's also possible to use the supported API of JS_CALLEE, JS_THIS, JS_ARGV, - * JS_RVAL, and JS_SET_RVAL to the same ends. - * - * But neither API has the error-handling or moving-GC correctness of CallArgs. - * New code should use CallArgs instead whenever possible. - * - * The eventual plan is to change JSNative to take |const CallArgs&| directly, - * for automatic assertion of correct use and to make calling functions more - * efficient. Embedders should start internally switching away from using - * |argc| and |vp| directly, except to create a |CallArgs|. Then, when an - * eventual release making that change occurs, porting efforts will require - * changing methods' signatures but won't require invasive changes to the - * methods' implementations, potentially under time pressure. - */ - -#ifndef js_CallArgs_h -#define js_CallArgs_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -#include "jstypes.h" - -#include "js/RootingAPI.h" -#include "js/Value.h" - -/* Typedef for native functions called by the JS VM. */ -typedef bool -(* JSNative)(JSContext* cx, unsigned argc, JS::Value* vp); - -namespace JS { - -extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; - -namespace detail { - -/* - * Compute |this| for the |vp| inside a JSNative, either boxing primitives or - * replacing with the global object as necessary. - */ -extern JS_PUBLIC_API(Value) -ComputeThis(JSContext* cx, JS::Value* vp); - -#ifdef JS_DEBUG -extern JS_PUBLIC_API(void) -CheckIsValidConstructible(const Value& v); -#endif - -class MOZ_STACK_CLASS IncludeUsedRval -{ - protected: -#ifdef JS_DEBUG - mutable bool usedRval_; - void setUsedRval() const { usedRval_ = true; } - void clearUsedRval() const { usedRval_ = false; } - void assertUnusedRval() const { MOZ_ASSERT(!usedRval_); } -#else - void setUsedRval() const {} - void clearUsedRval() const {} - void assertUnusedRval() const {} -#endif -}; - -class MOZ_STACK_CLASS NoUsedRval -{ - protected: - void setUsedRval() const {} - void clearUsedRval() const {} - void assertUnusedRval() const {} -}; - -template -class MOZ_STACK_CLASS CallArgsBase : public WantUsedRval -{ - static_assert(mozilla::IsSame::value || - mozilla::IsSame::value, - "WantUsedRval can only be IncludeUsedRval or NoUsedRval"); - - protected: - Value* argv_; - unsigned argc_; - bool constructing_; - - public: - // CALLEE ACCESS - - /* - * Returns the function being called, as a value. Must not be called after - * rval() has been used! - */ - HandleValue calleev() const { - this->assertUnusedRval(); - return HandleValue::fromMarkedLocation(&argv_[-2]); - } - - /* - * Returns the function being called, as an object. Must not be called - * after rval() has been used! - */ - JSObject& callee() const { - return calleev().toObject(); - } - - // CALLING/CONSTRUCTING-DIFFERENTIATIONS - - bool isConstructing() const { - if (!argv_[-1].isMagic()) - return false; - -#ifdef JS_DEBUG - if (!this->usedRval_) - CheckIsValidConstructible(calleev()); -#endif - - return true; - } - - MutableHandleValue newTarget() const { - MOZ_ASSERT(constructing_); - return MutableHandleValue::fromMarkedLocation(&this->argv_[argc_]); - } - - /* - * Returns the |this| value passed to the function. This method must not - * be called when the function is being called as a constructor via |new|. - * The value may or may not be an object: it is the individual function's - * responsibility to box the value if needed. - */ - HandleValue thisv() const { - // Some internal code uses thisv() in constructing cases, so don't do - // this yet. - // MOZ_ASSERT(!argv_[-1].isMagic(JS_IS_CONSTRUCTING)); - return HandleValue::fromMarkedLocation(&argv_[-1]); - } - - Value computeThis(JSContext* cx) const { - if (thisv().isObject()) - return thisv(); - - return ComputeThis(cx, base()); - } - - // ARGUMENTS - - /* Returns the number of arguments. */ - unsigned length() const { return argc_; } - - /* Returns the i-th zero-indexed argument. */ - MutableHandleValue operator[](unsigned i) const { - MOZ_ASSERT(i < argc_); - return MutableHandleValue::fromMarkedLocation(&this->argv_[i]); - } - - /* - * Returns the i-th zero-indexed argument, or |undefined| if there's no - * such argument. - */ - HandleValue get(unsigned i) const { - return i < length() - ? HandleValue::fromMarkedLocation(&this->argv_[i]) - : UndefinedHandleValue; - } - - /* - * Returns true if the i-th zero-indexed argument is present and is not - * |undefined|. - */ - bool hasDefined(unsigned i) const { - return i < argc_ && !this->argv_[i].isUndefined(); - } - - // RETURN VALUE - - /* - * Returns the currently-set return value. The initial contents of this - * value are unspecified. Once this method has been called, callee() and - * calleev() can no longer be used. (If you're compiling against a debug - * build of SpiderMonkey, these methods will assert to aid debugging.) - * - * If the method you're implementing succeeds by returning true, you *must* - * set this. (SpiderMonkey doesn't currently assert this, but it will do - * so eventually.) You don't need to use or change this if your method - * fails. - */ - MutableHandleValue rval() const { - this->setUsedRval(); - return MutableHandleValue::fromMarkedLocation(&argv_[-2]); - } - - public: - // These methods are publicly exposed, but they are *not* to be used when - // implementing a JSNative method and encapsulating access to |vp| within - // it. You probably don't want to use these! - - void setCallee(const Value& aCalleev) const { - this->clearUsedRval(); - argv_[-2] = aCalleev; - } - - void setThis(const Value& aThisv) const { - argv_[-1] = aThisv; - } - - MutableHandleValue mutableThisv() const { - return MutableHandleValue::fromMarkedLocation(&argv_[-1]); - } - - public: - // These methods are publicly exposed, but we're unsure of the interfaces - // (because they're hackish and drop assertions). Avoid using these if you - // can. - - Value* array() const { return argv_; } - Value* end() const { return argv_ + argc_ + constructing_; } - - public: - // These methods are only intended for internal use. Embedders shouldn't - // use them! - - Value* base() const { return argv_ - 2; } - - Value* spAfterCall() const { - this->setUsedRval(); - return argv_ - 1; - } -}; - -} // namespace detail - -class MOZ_STACK_CLASS CallArgs : public detail::CallArgsBase -{ - private: - friend CallArgs CallArgsFromVp(unsigned argc, Value* vp); - friend CallArgs CallArgsFromSp(unsigned stackSlots, Value* sp, bool constructing); - - static CallArgs create(unsigned argc, Value* argv, bool constructing) { - CallArgs args; - args.clearUsedRval(); - args.argv_ = argv; - args.argc_ = argc; - args.constructing_ = constructing; -#ifdef DEBUG - for (unsigned i = 0; i < argc; ++i) - MOZ_ASSERT_IF(argv[i].isMarkable(), !GCThingIsMarkedGray(GCCellPtr(argv[i]))); -#endif - return args; - } - - public: - /* - * Returns true if there are at least |required| arguments passed in. If - * false, it reports an error message on the context. - */ - bool requireAtLeast(JSContext* cx, const char* fnname, unsigned required) const; - -}; - -MOZ_ALWAYS_INLINE CallArgs -CallArgsFromVp(unsigned argc, Value* vp) -{ - return CallArgs::create(argc, vp + 2, vp[1].isMagic(JS_IS_CONSTRUCTING)); -} - -// This method is only intended for internal use in SpiderMonkey. We may -// eventually move it to an internal header. Embedders should use -// JS::CallArgsFromVp! -MOZ_ALWAYS_INLINE CallArgs -CallArgsFromSp(unsigned stackSlots, Value* sp, bool constructing = false) -{ - return CallArgs::create(stackSlots - constructing, sp - stackSlots, constructing); -} - -} // namespace JS - -/* - * Macros to hide interpreter stack layout details from a JSNative using its - * JS::Value* vp parameter. DO NOT USE THESE! Instead use JS::CallArgs and - * friends, above. These macros will be removed when we change JSNative to - * take a const JS::CallArgs&. - */ - -/* - * Return |this| if |this| is an object. Otherwise, return the global object - * if |this| is null or undefined, and finally return a boxed version of any - * other primitive. - * - * Note: if this method returns null, an error has occurred and must be - * propagated or caught. - */ -MOZ_ALWAYS_INLINE JS::Value -JS_THIS(JSContext* cx, JS::Value* vp) -{ - return vp[1].isPrimitive() ? JS::detail::ComputeThis(cx, vp) : vp[1]; -} - -/* - * A note on JS_THIS_OBJECT: no equivalent method is part of the CallArgs - * interface, and we're unlikely to add one (functions shouldn't be implicitly - * exposing the global object to arbitrary callers). Continue using |vp| - * directly for this case, but be aware this API will eventually be replaced - * with a function that operates directly upon |args.thisv()|. - */ -#define JS_THIS_OBJECT(cx,vp) (JS_THIS(cx,vp).toObjectOrNull()) - -/* - * |this| is passed to functions in ES5 without change. Functions themselves - * do any post-processing they desire to box |this|, compute the global object, - * &c. This macro retrieves a function's unboxed |this| value. - * - * This macro must not be used in conjunction with JS_THIS or JS_THIS_OBJECT, - * or vice versa. Either use the provided this value with this macro, or - * compute the boxed |this| value using those. JS_THIS_VALUE must not be used - * if the function is being called as a constructor. - * - * But: DO NOT USE THIS! Instead use JS::CallArgs::thisv(), above. - * - */ -#define JS_THIS_VALUE(cx,vp) ((vp)[1]) - -#endif /* js_CallArgs_h */ diff --git a/mac/include/spidermonkey/js/CallNonGenericMethod.h b/mac/include/spidermonkey/js/CallNonGenericMethod.h deleted file mode 100644 index 9a1cf010..00000000 --- a/mac/include/spidermonkey/js/CallNonGenericMethod.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_CallNonGenericMethod_h -#define js_CallNonGenericMethod_h - -#include "jstypes.h" - -#include "js/CallArgs.h" - -namespace JS { - -// Returns true if |v| is considered an acceptable this-value. -typedef bool (*IsAcceptableThis)(HandleValue v); - -// Implements the guts of a method; guaranteed to be provided an acceptable -// this-value, as determined by a corresponding IsAcceptableThis method. -typedef bool (*NativeImpl)(JSContext* cx, const CallArgs& args); - -namespace detail { - -// DON'T CALL THIS DIRECTLY. It's for use only by CallNonGenericMethod! -extern JS_PUBLIC_API(bool) -CallMethodIfWrapped(JSContext* cx, IsAcceptableThis test, NativeImpl impl, const CallArgs& args); - -} // namespace detail - -// Methods usually act upon |this| objects only from a single global object and -// compartment. Sometimes, however, a method must act upon |this| values from -// multiple global objects or compartments. In such cases the |this| value a -// method might see will be wrapped, such that various access to the object -- -// to its class, its private data, its reserved slots, and so on -- will not -// work properly without entering that object's compartment. This method -// implements a solution to this problem. -// -// To implement a method that accepts |this| values from multiple compartments, -// define two functions. The first function matches the IsAcceptableThis type -// and indicates whether the provided value is an acceptable |this| for the -// method; it must be a pure function only of its argument. -// -// static const JSClass AnswerClass = { ... }; -// -// static bool -// IsAnswerObject(const Value& v) -// { -// if (!v.isObject()) -// return false; -// return JS_GetClass(&v.toObject()) == &AnswerClass; -// } -// -// The second function implements the NativeImpl signature and defines the -// behavior of the method when it is provided an acceptable |this| value. -// Aside from some typing niceties -- see the CallArgs interface for details -- -// its interface is the same as that of JSNative. -// -// static bool -// answer_getAnswer_impl(JSContext* cx, JS::CallArgs args) -// { -// args.rval().setInt32(42); -// return true; -// } -// -// The implementation function is guaranteed to be called *only* with a |this| -// value which is considered acceptable. -// -// Now to implement the actual method, write a JSNative that calls the method -// declared below, passing the appropriate template and runtime arguments. -// -// static bool -// answer_getAnswer(JSContext* cx, unsigned argc, JS::Value* vp) -// { -// JS::CallArgs args = JS::CallArgsFromVp(argc, vp); -// return JS::CallNonGenericMethod(cx, args); -// } -// -// Note that, because they are used as template arguments, the predicate -// and implementation functions must have external linkage. (This is -// unfortunate, but GCC wasn't inlining things as one would hope when we -// passed them as function arguments.) -// -// JS::CallNonGenericMethod will test whether |args.thisv()| is acceptable. If -// it is, it will call the provided implementation function, which will return -// a value and indicate success. If it is not, it will attempt to unwrap -// |this| and call the implementation function on the unwrapped |this|. If -// that succeeds, all well and good. If it doesn't succeed, a TypeError will -// be thrown. -// -// Note: JS::CallNonGenericMethod will only work correctly if it's called in -// tail position in a JSNative. Do not call it from any other place. -// -template -MOZ_ALWAYS_INLINE bool -CallNonGenericMethod(JSContext* cx, const CallArgs& args) -{ - HandleValue thisv = args.thisv(); - if (Test(thisv)) - return Impl(cx, args); - - return detail::CallMethodIfWrapped(cx, Test, Impl, args); -} - -MOZ_ALWAYS_INLINE bool -CallNonGenericMethod(JSContext* cx, IsAcceptableThis Test, NativeImpl Impl, const CallArgs& args) -{ - HandleValue thisv = args.thisv(); - if (Test(thisv)) - return Impl(cx, args); - - return detail::CallMethodIfWrapped(cx, Test, Impl, args); -} - -} // namespace JS - -#endif /* js_CallNonGenericMethod_h */ diff --git a/mac/include/spidermonkey/js/CharacterEncoding.h b/mac/include/spidermonkey/js/CharacterEncoding.h deleted file mode 100644 index fe39a415..00000000 --- a/mac/include/spidermonkey/js/CharacterEncoding.h +++ /dev/null @@ -1,338 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_CharacterEncoding_h -#define js_CharacterEncoding_h - -#include "mozilla/Range.h" - -#include "js/TypeDecls.h" -#include "js/Utility.h" - -namespace js { -class ExclusiveContext; -} // namespace js - -class JSFlatString; - -namespace JS { - -/* - * By default, all C/C++ 1-byte-per-character strings passed into the JSAPI - * are treated as ISO/IEC 8859-1, also known as Latin-1. That is, each - * byte is treated as a 2-byte character, and there is no way to pass in a - * string containing characters beyond U+00FF. - */ -class Latin1Chars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = Latin1Char; - - Latin1Chars() : Base() {} - Latin1Chars(char* aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) {} - Latin1Chars(const Latin1Char* aBytes, size_t aLength) - : Base(const_cast(aBytes), aLength) - {} - Latin1Chars(const char* aBytes, size_t aLength) - : Base(reinterpret_cast(const_cast(aBytes)), aLength) - {} -}; - -/* - * A Latin1Chars, but with \0 termination for C compatibility. - */ -class Latin1CharsZ : public mozilla::RangedPtr -{ - typedef mozilla::RangedPtr Base; - - public: - using CharT = Latin1Char; - - Latin1CharsZ() : Base(nullptr, 0) {} - - Latin1CharsZ(char* aBytes, size_t aLength) - : Base(reinterpret_cast(aBytes), aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - Latin1CharsZ(Latin1Char* aBytes, size_t aLength) - : Base(aBytes, aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - using Base::operator=; - - char* c_str() { return reinterpret_cast(get()); } -}; - -class UTF8Chars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = unsigned char; - - UTF8Chars() : Base() {} - UTF8Chars(char* aBytes, size_t aLength) - : Base(reinterpret_cast(aBytes), aLength) - {} - UTF8Chars(const char* aBytes, size_t aLength) - : Base(reinterpret_cast(const_cast(aBytes)), aLength) - {} -}; - -/* - * SpiderMonkey also deals directly with UTF-8 encoded text in some places. - */ -class UTF8CharsZ : public mozilla::RangedPtr -{ - typedef mozilla::RangedPtr Base; - - public: - using CharT = unsigned char; - - UTF8CharsZ() : Base(nullptr, 0) {} - - UTF8CharsZ(char* aBytes, size_t aLength) - : Base(reinterpret_cast(aBytes), aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - UTF8CharsZ(unsigned char* aBytes, size_t aLength) - : Base(aBytes, aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - using Base::operator=; - - char* c_str() { return reinterpret_cast(get()); } -}; - -/* - * A wrapper for a "const char*" that is encoded using UTF-8. - * This class does not manage ownership of the data; that is left - * to others. This differs from UTF8CharsZ in that the chars are - * const and it allows assignment. - */ -class ConstUTF8CharsZ -{ - const char* data_; - - public: - using CharT = unsigned char; - - ConstUTF8CharsZ() : data_(nullptr) - {} - - ConstUTF8CharsZ(const char* aBytes, size_t aLength) - : data_(aBytes) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); -#ifdef DEBUG - validate(aLength); -#endif - } - - const void* get() const { return data_; } - - const char* c_str() const { return data_; } - - explicit operator bool() const { return data_ != nullptr; } - - private: -#ifdef DEBUG - void validate(size_t aLength); -#endif -}; - -/* - * SpiderMonkey uses a 2-byte character representation: it is a - * 2-byte-at-a-time view of a UTF-16 byte stream. This is similar to UCS-2, - * but unlike UCS-2, we do not strip UTF-16 extension bytes. This allows a - * sufficiently dedicated JavaScript program to be fully unicode-aware by - * manually interpreting UTF-16 extension characters embedded in the JS - * string. - */ -class TwoByteChars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = char16_t; - - TwoByteChars() : Base() {} - TwoByteChars(char16_t* aChars, size_t aLength) : Base(aChars, aLength) {} - TwoByteChars(const char16_t* aChars, size_t aLength) : Base(const_cast(aChars), aLength) {} -}; - -/* - * A TwoByteChars, but \0 terminated for compatibility with JSFlatString. - */ -class TwoByteCharsZ : public mozilla::RangedPtr -{ - typedef mozilla::RangedPtr Base; - - public: - using CharT = char16_t; - - TwoByteCharsZ() : Base(nullptr, 0) {} - - TwoByteCharsZ(char16_t* chars, size_t length) - : Base(chars, length) - { - MOZ_ASSERT(chars[length] == '\0'); - } - - using Base::operator=; -}; - -typedef mozilla::RangedPtr ConstCharPtr; - -/* - * Like TwoByteChars, but the chars are const. - */ -class ConstTwoByteChars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = char16_t; - - ConstTwoByteChars() : Base() {} - ConstTwoByteChars(const char16_t* aChars, size_t aLength) : Base(aChars, aLength) {} -}; - -/* - * Convert a 2-byte character sequence to "ISO-Latin-1". This works by - * truncating each 2-byte pair in the sequence to a 1-byte pair. If the source - * contains any UTF-16 extension characters, then this may give invalid Latin1 - * output. The returned string is zero terminated. The returned string or the - * returned string's |start()| must be freed with JS_free or js_free, - * respectively. If allocation fails, an OOM error will be set and the method - * will return a nullptr chars (which can be tested for with the ! operator). - * This method cannot trigger GC. - */ -extern Latin1CharsZ -LossyTwoByteCharsToNewLatin1CharsZ(js::ExclusiveContext* cx, - const mozilla::Range tbchars); - -inline Latin1CharsZ -LossyTwoByteCharsToNewLatin1CharsZ(js::ExclusiveContext* cx, const char16_t* begin, size_t length) -{ - const mozilla::Range tbchars(begin, length); - return JS::LossyTwoByteCharsToNewLatin1CharsZ(cx, tbchars); -} - -template -extern UTF8CharsZ -CharsToNewUTF8CharsZ(js::ExclusiveContext* maybeCx, const mozilla::Range chars); - -uint32_t -Utf8ToOneUcs4Char(const uint8_t* utf8Buffer, int utf8Length); - -/* - * Inflate bytes in UTF-8 encoding to char16_t. - * - On error, returns an empty TwoByteCharsZ. - * - On success, returns a malloc'd TwoByteCharsZ, and updates |outlen| to hold - * its length; the length value excludes the trailing null. - */ -extern TwoByteCharsZ -UTF8CharsToNewTwoByteCharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -/* - * Like UTF8CharsToNewTwoByteCharsZ, but for ConstUTF8CharsZ. - */ -extern TwoByteCharsZ -UTF8CharsToNewTwoByteCharsZ(JSContext* cx, const ConstUTF8CharsZ& utf8, size_t* outlen); - -/* - * The same as UTF8CharsToNewTwoByteCharsZ(), except that any malformed UTF-8 characters - * will be replaced by \uFFFD. No exception will be thrown for malformed UTF-8 - * input. - */ -extern TwoByteCharsZ -LossyUTF8CharsToNewTwoByteCharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -extern TwoByteCharsZ -LossyUTF8CharsToNewTwoByteCharsZ(JSContext* cx, const ConstUTF8CharsZ& utf8, size_t* outlen); - -/* - * Returns the length of the char buffer required to encode |s| as UTF8. - * Does not include the null-terminator. - */ -JS_PUBLIC_API(size_t) -GetDeflatedUTF8StringLength(JSFlatString* s); - -/* - * Encode |src| as UTF8. The caller must either ensure |dst| has enough space - * to encode the entire string or pass the length of the buffer as |dstlenp|, - * in which case the function will encode characters from the string until - * the buffer is exhausted. Does not write the null terminator. - * - * If |dstlenp| is provided, it will be updated to hold the number of bytes - * written to the buffer. If |numcharsp| is provided, it will be updated to hold - * the number of Unicode characters written to the buffer (which can be less - * than the length of the string, if the buffer is exhausted before the string - * is fully encoded). - */ -JS_PUBLIC_API(void) -DeflateStringToUTF8Buffer(JSFlatString* src, mozilla::RangedPtr dst, - size_t* dstlenp = nullptr, size_t* numcharsp = nullptr); - -/* - * The smallest character encoding capable of fully representing a particular - * string. - */ -enum class SmallestEncoding { - ASCII, - Latin1, - UTF16 -}; - -/* - * Returns the smallest encoding possible for the given string: if all - * codepoints are <128 then ASCII, otherwise if all codepoints are <256 - * Latin-1, else UTF16. - */ -JS_PUBLIC_API(SmallestEncoding) -FindSmallestEncoding(UTF8Chars utf8); - -/* - * Return a null-terminated Latin-1 string copied from the input string, - * storing its length (excluding null terminator) in |*outlen|. Fail and - * report an error if the string contains non-Latin-1 codepoints. Returns - * Latin1CharsZ() on failure. - */ -extern Latin1CharsZ -UTF8CharsToNewLatin1CharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -/* - * Return a null-terminated Latin-1 string copied from the input string, - * storing its length (excluding null terminator) in |*outlen|. Non-Latin-1 - * codepoints are replaced by '?'. Returns Latin1CharsZ() on failure. - */ -extern Latin1CharsZ -LossyUTF8CharsToNewLatin1CharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -/* - * Returns true if all characters in the given null-terminated string are - * ASCII, i.e. < 0x80, false otherwise. - */ -extern bool -StringIsASCII(const char* s); - -} // namespace JS - -inline void JS_free(JS::Latin1CharsZ& ptr) { js_free((void*)ptr.get()); } -inline void JS_free(JS::UTF8CharsZ& ptr) { js_free((void*)ptr.get()); } - -#endif /* js_CharacterEncoding_h */ diff --git a/mac/include/spidermonkey/js/Class.h b/mac/include/spidermonkey/js/Class.h deleted file mode 100644 index 3b502387..00000000 --- a/mac/include/spidermonkey/js/Class.h +++ /dev/null @@ -1,995 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JSClass definition and its component types, plus related interfaces. */ - -#ifndef js_Class_h -#define js_Class_h - -#include "jstypes.h" - -#include "js/CallArgs.h" -#include "js/Id.h" -#include "js/TypeDecls.h" - -/* - * A JSClass acts as a vtable for JS objects that allows JSAPI clients to - * control various aspects of the behavior of an object like property lookup. - * js::Class is an engine-private extension that allows more control over - * object behavior and, e.g., allows custom slow layout. - */ - -struct JSAtomState; -struct JSFreeOp; -struct JSFunctionSpec; - -namespace js { - -struct Class; -class FreeOp; -class Shape; - -// This is equal to JSFunction::class_. Use it in places where you don't want -// to #include jsfun.h. -extern JS_FRIEND_DATA(const js::Class* const) FunctionClassPtr; - -} // namespace js - -namespace JS { - -class AutoIdVector; - -/** - * The answer to a successful query as to whether an object is an Array per - * ES6's internal |IsArray| operation (as exposed by |Array.isArray|). - */ -enum class IsArrayAnswer -{ - Array, - NotArray, - RevokedProxy -}; - -/** - * ES6 7.2.2. - * - * Returns false on failure, otherwise returns true and sets |*isArray| - * indicating whether the object passes ECMAScript's IsArray test. This is the - * same test performed by |Array.isArray|. - * - * This is NOT the same as asking whether |obj| is an Array or a wrapper around - * one. If |obj| is a proxy created by |Proxy.revocable()| and has been - * revoked, or if |obj| is a proxy whose target (at any number of hops) is a - * revoked proxy, this method throws a TypeError and returns false. - */ -extern JS_PUBLIC_API(bool) -IsArray(JSContext* cx, HandleObject obj, bool* isArray); - -/** - * Identical to IsArray above, but the nature of the object (if successfully - * determined) is communicated via |*answer|. In particular this method - * returns true and sets |*answer = IsArrayAnswer::RevokedProxy| when called on - * a revoked proxy. - * - * Most users will want the overload above, not this one. - */ -extern JS_PUBLIC_API(bool) -IsArray(JSContext* cx, HandleObject obj, IsArrayAnswer* answer); - -/** - * Per ES6, the [[DefineOwnProperty]] internal method has three different - * possible outcomes: - * - * - It can throw an exception (which we indicate by returning false). - * - * - It can return true, indicating unvarnished success. - * - * - It can return false, indicating "strict failure". The property could - * not be defined. It's an error, but no exception was thrown. - * - * It's not just [[DefineOwnProperty]]: all the mutating internal methods have - * the same three outcomes. (The other affected internal methods are [[Set]], - * [[Delete]], [[SetPrototypeOf]], and [[PreventExtensions]].) - * - * If you think this design is awful, you're not alone. But as it's the - * standard, we must represent these boolean "success" values somehow. - * ObjectOpSuccess is the class for this. It's like a bool, but when it's false - * it also stores an error code. - * - * Typical usage: - * - * ObjectOpResult result; - * if (!DefineProperty(cx, obj, id, ..., result)) - * return false; - * if (!result) - * return result.reportError(cx, obj, id); - * - * Users don't have to call `result.report()`; another possible ending is: - * - * argv.rval().setBoolean(bool(result)); - * return true; - */ -class ObjectOpResult -{ - private: - /** - * code_ is either one of the special codes OkCode or Uninitialized, or - * an error code. For now the error codes are private to the JS engine; - * they're defined in js/src/js.msg. - * - * code_ is uintptr_t (rather than uint32_t) for the convenience of the - * JITs, which would otherwise have to deal with either padding or stack - * alignment on 64-bit platforms. - */ - uintptr_t code_; - - public: - enum SpecialCodes : uintptr_t { - OkCode = 0, - Uninitialized = uintptr_t(-1) - }; - - ObjectOpResult() : code_(Uninitialized) {} - - /* Return true if succeed() was called. */ - bool ok() const { - MOZ_ASSERT(code_ != Uninitialized); - return code_ == OkCode; - } - - explicit operator bool() const { return ok(); } - - /* Set this ObjectOpResult to true and return true. */ - bool succeed() { - code_ = OkCode; - return true; - } - - /* - * Set this ObjectOpResult to false with an error code. - * - * Always returns true, as a convenience. Typical usage will be: - * - * if (funny condition) - * return result.fail(JSMSG_CANT_DO_THE_THINGS); - * - * The true return value indicates that no exception is pending, and it - * would be OK to ignore the failure and continue. - */ - bool fail(uint32_t msg) { - MOZ_ASSERT(msg != OkCode); - code_ = msg; - return true; - } - - JS_PUBLIC_API(bool) failCantRedefineProp(); - JS_PUBLIC_API(bool) failReadOnly(); - JS_PUBLIC_API(bool) failGetterOnly(); - JS_PUBLIC_API(bool) failCantDelete(); - - JS_PUBLIC_API(bool) failCantSetInterposed(); - JS_PUBLIC_API(bool) failCantDefineWindowElement(); - JS_PUBLIC_API(bool) failCantDeleteWindowElement(); - JS_PUBLIC_API(bool) failCantDeleteWindowNamedProperty(); - JS_PUBLIC_API(bool) failCantPreventExtensions(); - JS_PUBLIC_API(bool) failCantSetProto(); - JS_PUBLIC_API(bool) failNoNamedSetter(); - JS_PUBLIC_API(bool) failNoIndexedSetter(); - - uint32_t failureCode() const { - MOZ_ASSERT(!ok()); - return uint32_t(code_); - } - - /* - * Report an error or warning if necessary; return true to proceed and - * false if an error was reported. Call this when failure should cause - * a warning if extraWarnings are enabled. - * - * The precise rules are like this: - * - * - If ok(), then we succeeded. Do nothing and return true. - * - Otherwise, if |strict| is true, or if cx has both extraWarnings and - * werrorOption enabled, throw a TypeError and return false. - * - Otherwise, if cx has extraWarnings enabled, emit a warning and - * return true. - * - Otherwise, do nothing and return true. - */ - bool checkStrictErrorOrWarning(JSContext* cx, HandleObject obj, HandleId id, bool strict) { - if (ok()) - return true; - return reportStrictErrorOrWarning(cx, obj, id, strict); - } - - /* - * The same as checkStrictErrorOrWarning(cx, id, strict), except the - * operation is not associated with a particular property id. This is - * used for [[PreventExtensions]] and [[SetPrototypeOf]]. failureCode() - * must not be an error that has "{0}" in the error message. - */ - bool checkStrictErrorOrWarning(JSContext* cx, HandleObject obj, bool strict) { - return ok() || reportStrictErrorOrWarning(cx, obj, strict); - } - - /* Throw a TypeError. Call this only if !ok(). */ - bool reportError(JSContext* cx, HandleObject obj, HandleId id) { - return reportStrictErrorOrWarning(cx, obj, id, true); - } - - /* - * The same as reportError(cx, obj, id), except the operation is not - * associated with a particular property id. - */ - bool reportError(JSContext* cx, HandleObject obj) { - return reportStrictErrorOrWarning(cx, obj, true); - } - - /* Helper function for checkStrictErrorOrWarning's slow path. */ - JS_PUBLIC_API(bool) reportStrictErrorOrWarning(JSContext* cx, HandleObject obj, HandleId id, bool strict); - JS_PUBLIC_API(bool) reportStrictErrorOrWarning(JSContext* cx, HandleObject obj, bool strict); - - /* - * Convenience method. Return true if ok() or if strict is false; otherwise - * throw a TypeError and return false. - */ - bool checkStrict(JSContext* cx, HandleObject obj, HandleId id) { - return checkStrictErrorOrWarning(cx, obj, id, true); - } - - /* - * Convenience method. The same as checkStrict(cx, id), except the - * operation is not associated with a particular property id. - */ - bool checkStrict(JSContext* cx, HandleObject obj) { - return checkStrictErrorOrWarning(cx, obj, true); - } -}; - -} // namespace JS - -// JSClass operation signatures. - -/** - * Get a property named by id in obj. Note the jsid id type -- id may - * be a string (Unicode property identifier) or an int (element index). The - * *vp out parameter, on success, is the new property value after the action. - */ -typedef bool -(* JSGetterOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp); - -/** Add a property named by id to obj. */ -typedef bool -(* JSAddPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v); - -/** - * Set a property named by id in obj, treating the assignment as strict - * mode code if strict is true. Note the jsid id type -- id may be a string - * (Unicode property identifier) or an int (element index). The *vp out - * parameter, on success, is the new property value after the - * set. - */ -typedef bool -(* JSSetterOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp, JS::ObjectOpResult& result); - -/** - * Delete a property named by id in obj. - * - * If an error occurred, return false as per normal JSAPI error practice. - * - * If no error occurred, but the deletion attempt wasn't allowed (perhaps - * because the property was non-configurable), call result.fail() and - * return true. This will cause |delete obj[id]| to evaluate to false in - * non-strict mode code, and to throw a TypeError in strict mode code. - * - * If no error occurred and the deletion wasn't disallowed (this is *not* the - * same as saying that a deletion actually occurred -- deleting a non-existent - * property, or an inherited property, is allowed -- it's just pointless), - * call result.succeed() and return true. - */ -typedef bool -(* JSDeletePropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -/** - * The type of ObjectOps::enumerate. This callback overrides a portion of - * SpiderMonkey's default [[Enumerate]] internal method. When an ordinary object - * is enumerated, that object and each object on its prototype chain is tested - * for an enumerate op, and those ops are called in order. The properties each - * op adds to the 'properties' vector are added to the set of values the for-in - * loop will iterate over. All of this is nonstandard. - * - * An object is "enumerated" when it's the target of a for-in loop or - * JS_Enumerate(). The callback's job is to populate 'properties' with the - * object's property keys. If `enumerableOnly` is true, the callback should only - * add enumerable properties. - */ -typedef bool -(* JSNewEnumerateOp)(JSContext* cx, JS::HandleObject obj, JS::AutoIdVector& properties, - bool enumerableOnly); - -/** - * The old-style JSClass.enumerate op should define all lazy properties not - * yet reflected in obj. - */ -typedef bool -(* JSEnumerateOp)(JSContext* cx, JS::HandleObject obj); - -/** - * The type of ObjectOps::funToString. This callback allows an object to - * provide a custom string to use when Function.prototype.toString is invoked on - * that object. A null return value means OOM. - */ -typedef JSString* -(* JSFunToStringOp)(JSContext* cx, JS::HandleObject obj, unsigned indent); - -/** - * Resolve a lazy property named by id in obj by defining it directly in obj. - * Lazy properties are those reflected from some peer native property space - * (e.g., the DOM attributes for a given node reflected as obj) on demand. - * - * JS looks for a property in an object, and if not found, tries to resolve - * the given id. *resolvedp should be set to true iff the property was defined - * on |obj|. - */ -typedef bool -(* JSResolveOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - bool* resolvedp); - -/** - * A class with a resolve hook can optionally have a mayResolve hook. This hook - * must have no side effects and must return true for a given id if the resolve - * hook may resolve this id. This is useful when we're doing a "pure" lookup: if - * mayResolve returns false, we know we don't have to call the effectful resolve - * hook. - * - * maybeObj, if non-null, is the object on which we're doing the lookup. This - * can be nullptr: during JIT compilation we sometimes know the Class but not - * the object. - */ -typedef bool -(* JSMayResolveOp)(const JSAtomState& names, jsid id, JSObject* maybeObj); - -/** - * Finalize obj, which the garbage collector has determined to be unreachable - * from other live objects or from GC roots. Obviously, finalizers must never - * store a reference to obj. - */ -typedef void -(* JSFinalizeOp)(JSFreeOp* fop, JSObject* obj); - -/** Finalizes external strings created by JS_NewExternalString. */ -struct JSStringFinalizer { - void (*finalize)(JS::Zone* zone, const JSStringFinalizer* fin, char16_t* chars); -}; - -/** - * Check whether v is an instance of obj. Return false on error or exception, - * true on success with true in *bp if v is an instance of obj, false in - * *bp otherwise. - */ -typedef bool -(* JSHasInstanceOp)(JSContext* cx, JS::HandleObject obj, JS::MutableHandleValue vp, - bool* bp); - -/** - * Function type for trace operation of the class called to enumerate all - * traceable things reachable from obj's private data structure. For each such - * thing, a trace implementation must call JS::TraceEdge on the thing's - * location. - * - * JSTraceOp implementation can assume that no other threads mutates object - * state. It must not change state of the object or corresponding native - * structures. The only exception for this rule is the case when the embedding - * needs a tight integration with GC. In that case the embedding can check if - * the traversal is a part of the marking phase through calling - * JS_IsGCMarkingTracer and apply a special code like emptying caches or - * marking its native structures. - */ -typedef void -(* JSTraceOp)(JSTracer* trc, JSObject* obj); - -typedef JSObject* -(* JSWeakmapKeyDelegateOp)(JSObject* obj); - -typedef void -(* JSObjectMovedOp)(JSObject* obj, const JSObject* old); - -/* js::Class operation signatures. */ - -namespace js { - -typedef bool -(* LookupPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleObject objp, JS::MutableHandle propp); -typedef bool -(* DefinePropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc, - JS::ObjectOpResult& result); -typedef bool -(* HasPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); -typedef bool -(* GetPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleValue receiver, JS::HandleId id, - JS::MutableHandleValue vp); -typedef bool -(* SetPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v, - JS::HandleValue receiver, JS::ObjectOpResult& result); -typedef bool -(* GetOwnPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); -typedef bool -(* DeletePropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -typedef bool -(* WatchOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); - -typedef bool -(* UnwatchOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id); - -class JS_FRIEND_API(ElementAdder) -{ - public: - enum GetBehavior { - // Check if the element exists before performing the Get and preserve - // holes. - CheckHasElemPreserveHoles, - - // Perform a Get operation, like obj[index] in JS. - GetElement - }; - - private: - // Only one of these is used. - JS::RootedObject resObj_; - JS::Value* vp_; - - uint32_t index_; -#ifdef DEBUG - uint32_t length_; -#endif - GetBehavior getBehavior_; - - public: - ElementAdder(JSContext* cx, JSObject* obj, uint32_t length, GetBehavior behavior) - : resObj_(cx, obj), vp_(nullptr), index_(0), -#ifdef DEBUG - length_(length), -#endif - getBehavior_(behavior) - {} - ElementAdder(JSContext* cx, JS::Value* vp, uint32_t length, GetBehavior behavior) - : resObj_(cx), vp_(vp), index_(0), -#ifdef DEBUG - length_(length), -#endif - getBehavior_(behavior) - {} - - GetBehavior getBehavior() const { return getBehavior_; } - - bool append(JSContext* cx, JS::HandleValue v); - void appendHole(); -}; - -typedef bool -(* GetElementsOp)(JSContext* cx, JS::HandleObject obj, uint32_t begin, uint32_t end, - ElementAdder* adder); - -typedef void -(* FinalizeOp)(FreeOp* fop, JSObject* obj); - -// The special treatment of |finalize| and |trace| is necessary because if we -// assign either of those hooks to a local variable and then call it -- as is -// done with the other hooks -- the GC hazard analysis gets confused. -#define JS_CLASS_MEMBERS(ClassOpsType, FreeOpType) \ - const char* name; \ - uint32_t flags; \ - const ClassOpsType* cOps; \ - \ - JSAddPropertyOp getAddProperty() const { return cOps ? cOps->addProperty : nullptr; } \ - JSDeletePropertyOp getDelProperty() const { return cOps ? cOps->delProperty : nullptr; } \ - JSGetterOp getGetProperty() const { return cOps ? cOps->getProperty : nullptr; } \ - JSSetterOp getSetProperty() const { return cOps ? cOps->setProperty : nullptr; } \ - JSEnumerateOp getEnumerate() const { return cOps ? cOps->enumerate : nullptr; } \ - JSResolveOp getResolve() const { return cOps ? cOps->resolve : nullptr; } \ - JSMayResolveOp getMayResolve() const { return cOps ? cOps->mayResolve : nullptr; } \ - JSNative getCall() const { return cOps ? cOps->call : nullptr; } \ - JSHasInstanceOp getHasInstance() const { return cOps ? cOps->hasInstance : nullptr; } \ - JSNative getConstruct() const { return cOps ? cOps->construct : nullptr; } \ - \ - bool hasFinalize() const { return cOps && cOps->finalize; } \ - bool hasTrace() const { return cOps && cOps->trace; } \ - \ - bool isTrace(JSTraceOp trace) const { return cOps && cOps->trace == trace; } \ - \ - void doFinalize(FreeOpType* fop, JSObject* obj) const { \ - MOZ_ASSERT(cOps && cOps->finalize); \ - cOps->finalize(fop, obj); \ - } \ - void doTrace(JSTracer* trc, JSObject* obj) const { \ - MOZ_ASSERT(cOps && cOps->trace); \ - cOps->trace(trc, obj); \ - } - -struct ClassOps -{ - /* Function pointer members (may be null). */ - JSAddPropertyOp addProperty; - JSDeletePropertyOp delProperty; - JSGetterOp getProperty; - JSSetterOp setProperty; - JSEnumerateOp enumerate; - JSResolveOp resolve; - JSMayResolveOp mayResolve; - FinalizeOp finalize; - JSNative call; - JSHasInstanceOp hasInstance; - JSNative construct; - JSTraceOp trace; -}; - -/** Callback for the creation of constructor and prototype objects. */ -typedef JSObject* (*ClassObjectCreationOp)(JSContext* cx, JSProtoKey key); - -/** Callback for custom post-processing after class initialization via ClassSpec. */ -typedef bool (*FinishClassInitOp)(JSContext* cx, JS::HandleObject ctor, - JS::HandleObject proto); - -const size_t JSCLASS_CACHED_PROTO_WIDTH = 6; - -struct ClassSpec -{ - // All properties except flags should be accessed through accessor. - ClassObjectCreationOp createConstructor_; - ClassObjectCreationOp createPrototype_; - const JSFunctionSpec* constructorFunctions_; - const JSPropertySpec* constructorProperties_; - const JSFunctionSpec* prototypeFunctions_; - const JSPropertySpec* prototypeProperties_; - FinishClassInitOp finishInit_; - uintptr_t flags; - - static const size_t ProtoKeyWidth = JSCLASS_CACHED_PROTO_WIDTH; - - static const uintptr_t ProtoKeyMask = (1 << ProtoKeyWidth) - 1; - static const uintptr_t DontDefineConstructor = 1 << ProtoKeyWidth; - static const uintptr_t IsDelegated = 1 << (ProtoKeyWidth + 1); - - bool defined() const { return !!createConstructor_; } - - bool delegated() const { - return (flags & IsDelegated); - } - - // The ProtoKey this class inherits from. - JSProtoKey inheritanceProtoKey() const { - MOZ_ASSERT(defined()); - static_assert(JSProto_Null == 0, "zeroed key must be null"); - - // Default: Inherit from Object. - if (!(flags & ProtoKeyMask)) - return JSProto_Object; - - return JSProtoKey(flags & ProtoKeyMask); - } - - bool shouldDefineConstructor() const { - MOZ_ASSERT(defined()); - return !(flags & DontDefineConstructor); - } - - const ClassSpec* delegatedClassSpec() const { - MOZ_ASSERT(delegated()); - return reinterpret_cast(createConstructor_); - } - - ClassObjectCreationOp createConstructorHook() const { - if (delegated()) - return delegatedClassSpec()->createConstructorHook(); - return createConstructor_; - } - ClassObjectCreationOp createPrototypeHook() const { - if (delegated()) - return delegatedClassSpec()->createPrototypeHook(); - return createPrototype_; - } - const JSFunctionSpec* constructorFunctions() const { - if (delegated()) - return delegatedClassSpec()->constructorFunctions(); - return constructorFunctions_; - } - const JSPropertySpec* constructorProperties() const { - if (delegated()) - return delegatedClassSpec()->constructorProperties(); - return constructorProperties_; - } - const JSFunctionSpec* prototypeFunctions() const { - if (delegated()) - return delegatedClassSpec()->prototypeFunctions(); - return prototypeFunctions_; - } - const JSPropertySpec* prototypeProperties() const { - if (delegated()) - return delegatedClassSpec()->prototypeProperties(); - return prototypeProperties_; - } - FinishClassInitOp finishInitHook() const { - if (delegated()) - return delegatedClassSpec()->finishInitHook(); - return finishInit_; - } -}; - -struct ClassExtension -{ - /** - * If an object is used as a key in a weakmap, it may be desirable for the - * garbage collector to keep that object around longer than it otherwise - * would. A common case is when the key is a wrapper around an object in - * another compartment, and we want to avoid collecting the wrapper (and - * removing the weakmap entry) as long as the wrapped object is alive. In - * that case, the wrapped object is returned by the wrapper's - * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap - * key, it will not be collected (and remain in the weakmap) until the - * wrapped object is collected. - */ - JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; - - /** - * Optional hook called when an object is moved by a compacting GC. - * - * There may exist weak pointers to an object that are not traced through - * when the normal trace APIs are used, for example objects in the wrapper - * cache. This hook allows these pointers to be updated. - * - * Note that this hook can be called before JS_NewObject() returns if a GC - * is triggered during construction of the object. This can happen for - * global objects for example. - */ - JSObjectMovedOp objectMovedOp; -}; - -inline ClassObjectCreationOp DELEGATED_CLASSSPEC(const ClassSpec* spec) { - return reinterpret_cast(const_cast(spec)); -} - -#define JS_NULL_CLASS_SPEC nullptr -#define JS_NULL_CLASS_EXT nullptr - -struct ObjectOps -{ - LookupPropertyOp lookupProperty; - DefinePropertyOp defineProperty; - HasPropertyOp hasProperty; - GetPropertyOp getProperty; - SetPropertyOp setProperty; - GetOwnPropertyOp getOwnPropertyDescriptor; - DeletePropertyOp deleteProperty; - WatchOp watch; - UnwatchOp unwatch; - GetElementsOp getElements; - JSNewEnumerateOp enumerate; - JSFunToStringOp funToString; -}; - -#define JS_NULL_OBJECT_OPS nullptr - -} // namespace js - -// Classes, objects, and properties. - -typedef void (*JSClassInternal)(); - -struct JSClassOps -{ - /* Function pointer members (may be null). */ - JSAddPropertyOp addProperty; - JSDeletePropertyOp delProperty; - JSGetterOp getProperty; - JSSetterOp setProperty; - JSEnumerateOp enumerate; - JSResolveOp resolve; - JSMayResolveOp mayResolve; - JSFinalizeOp finalize; - JSNative call; - JSHasInstanceOp hasInstance; - JSNative construct; - JSTraceOp trace; -}; - -#define JS_NULL_CLASS_OPS nullptr - -struct JSClass { - JS_CLASS_MEMBERS(JSClassOps, JSFreeOp); - - void* reserved[3]; -}; - -#define JSCLASS_HAS_PRIVATE (1<<0) // objects have private slot -#define JSCLASS_DELAY_METADATA_BUILDER (1<<1) // class's initialization code - // will call - // SetNewObjectMetadata itself -#define JSCLASS_IS_WRAPPED_NATIVE (1<<2) // class is an XPCWrappedNative. - // WeakMaps use this to override - // the wrapper disposal - // mechanism. -#define JSCLASS_PRIVATE_IS_NSISUPPORTS (1<<3) // private is (nsISupports*) -#define JSCLASS_IS_DOMJSCLASS (1<<4) // objects are DOM -#define JSCLASS_HAS_XRAYED_CONSTRUCTOR (1<<5) // if wrapped by an xray - // wrapper, the builtin - // class's constructor won't - // be unwrapped and invoked. - // Instead, the constructor is - // resolved in the caller's - // compartment and invoked - // with a wrapped newTarget. - // The constructor has to - // detect and handle this - // situation. - // See PromiseConstructor for - // details. -#define JSCLASS_EMULATES_UNDEFINED (1<<6) // objects of this class act - // like the value undefined, - // in some contexts -#define JSCLASS_USERBIT1 (1<<7) // Reserved for embeddings. - -// To reserve slots fetched and stored via JS_Get/SetReservedSlot, bitwise-or -// JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where -// n is a constant in [1, 255]. Reserved slots are indexed from 0 to n-1. -#define JSCLASS_RESERVED_SLOTS_SHIFT 8 // room for 8 flags below */ -#define JSCLASS_RESERVED_SLOTS_WIDTH 8 // and 16 above this field */ -#define JSCLASS_RESERVED_SLOTS_MASK JS_BITMASK(JSCLASS_RESERVED_SLOTS_WIDTH) -#define JSCLASS_HAS_RESERVED_SLOTS(n) (((n) & JSCLASS_RESERVED_SLOTS_MASK) \ - << JSCLASS_RESERVED_SLOTS_SHIFT) -#define JSCLASS_RESERVED_SLOTS(clasp) (((clasp)->flags \ - >> JSCLASS_RESERVED_SLOTS_SHIFT) \ - & JSCLASS_RESERVED_SLOTS_MASK) - -#define JSCLASS_HIGH_FLAGS_SHIFT (JSCLASS_RESERVED_SLOTS_SHIFT + \ - JSCLASS_RESERVED_SLOTS_WIDTH) - -#define JSCLASS_IS_ANONYMOUS (1<<(JSCLASS_HIGH_FLAGS_SHIFT+0)) -#define JSCLASS_IS_GLOBAL (1<<(JSCLASS_HIGH_FLAGS_SHIFT+1)) -#define JSCLASS_INTERNAL_FLAG2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+2)) -#define JSCLASS_INTERNAL_FLAG3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+3)) - -#define JSCLASS_IS_PROXY (1<<(JSCLASS_HIGH_FLAGS_SHIFT+4)) - -#define JSCLASS_SKIP_NURSERY_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+5)) - -// Reserved for embeddings. -#define JSCLASS_USERBIT2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+6)) -#define JSCLASS_USERBIT3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+7)) - -#define JSCLASS_BACKGROUND_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+8)) -#define JSCLASS_FOREGROUND_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+9)) - -// Bits 26 through 31 are reserved for the CACHED_PROTO_KEY mechanism, see -// below. - -// ECMA-262 requires that most constructors used internally create objects -// with "the original Foo.prototype value" as their [[Prototype]] (__proto__) -// member initial value. The "original ... value" verbiage is there because -// in ECMA-262, global properties naming class objects are read/write and -// deleteable, for the most part. -// -// Implementing this efficiently requires that global objects have classes -// with the following flags. Failure to use JSCLASS_GLOBAL_FLAGS was -// previously allowed, but is now an ES5 violation and thus unsupported. -// -// JSCLASS_GLOBAL_APPLICATION_SLOTS is the number of slots reserved at -// the beginning of every global object's slots for use by the -// application. -#define JSCLASS_GLOBAL_APPLICATION_SLOTS 5 -#define JSCLASS_GLOBAL_SLOT_COUNT \ - (JSCLASS_GLOBAL_APPLICATION_SLOTS + JSProto_LIMIT * 2 + 39) -#define JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(n) \ - (JSCLASS_IS_GLOBAL | JSCLASS_HAS_RESERVED_SLOTS(JSCLASS_GLOBAL_SLOT_COUNT + (n))) -#define JSCLASS_GLOBAL_FLAGS \ - JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(0) -#define JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(clasp) \ - (((clasp)->flags & JSCLASS_IS_GLOBAL) \ - && JSCLASS_RESERVED_SLOTS(clasp) >= JSCLASS_GLOBAL_SLOT_COUNT) - -// Fast access to the original value of each standard class's prototype. -#define JSCLASS_CACHED_PROTO_SHIFT (JSCLASS_HIGH_FLAGS_SHIFT + 10) -#define JSCLASS_CACHED_PROTO_MASK JS_BITMASK(js::JSCLASS_CACHED_PROTO_WIDTH) -#define JSCLASS_HAS_CACHED_PROTO(key) (uint32_t(key) << JSCLASS_CACHED_PROTO_SHIFT) -#define JSCLASS_CACHED_PROTO_KEY(clasp) ((JSProtoKey) \ - (((clasp)->flags \ - >> JSCLASS_CACHED_PROTO_SHIFT) \ - & JSCLASS_CACHED_PROTO_MASK)) - -// Initializer for unused members of statically initialized JSClass structs. -#define JSCLASS_NO_INTERNAL_MEMBERS {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} -#define JSCLASS_NO_OPTIONAL_MEMBERS 0,0,0,0,0,JSCLASS_NO_INTERNAL_MEMBERS - -namespace js { - -struct Class -{ - JS_CLASS_MEMBERS(js::ClassOps, FreeOp); - const ClassSpec* spec; - const ClassExtension* ext; - const ObjectOps* oOps; - - /* - * Objects of this class aren't native objects. They don't have Shapes that - * describe their properties and layout. Classes using this flag must - * provide their own property behavior, either by being proxy classes (do - * this) or by overriding all the ObjectOps except getElements, watch and - * unwatch (don't do this). - */ - static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; - - bool isNative() const { - return !(flags & NON_NATIVE); - } - - bool hasPrivate() const { - return !!(flags & JSCLASS_HAS_PRIVATE); - } - - bool emulatesUndefined() const { - return flags & JSCLASS_EMULATES_UNDEFINED; - } - - bool isJSFunction() const { - return this == js::FunctionClassPtr; - } - - bool nonProxyCallable() const { - MOZ_ASSERT(!isProxy()); - return isJSFunction() || getCall(); - } - - bool isProxy() const { - return flags & JSCLASS_IS_PROXY; - } - - bool isDOMClass() const { - return flags & JSCLASS_IS_DOMJSCLASS; - } - - bool shouldDelayMetadataBuilder() const { - return flags & JSCLASS_DELAY_METADATA_BUILDER; - } - - bool isWrappedNative() const { - return flags & JSCLASS_IS_WRAPPED_NATIVE; - } - - static size_t offsetOfFlags() { return offsetof(Class, flags); } - - bool specDefined() const { return spec ? spec->defined() : false; } - JSProtoKey specInheritanceProtoKey() - const { return spec ? spec->inheritanceProtoKey() : JSProto_Null; } - bool specShouldDefineConstructor() - const { return spec ? spec->shouldDefineConstructor() : true; } - ClassObjectCreationOp specCreateConstructorHook() - const { return spec ? spec->createConstructorHook() : nullptr; } - ClassObjectCreationOp specCreatePrototypeHook() - const { return spec ? spec->createPrototypeHook() : nullptr; } - const JSFunctionSpec* specConstructorFunctions() - const { return spec ? spec->constructorFunctions() : nullptr; } - const JSPropertySpec* specConstructorProperties() - const { return spec ? spec->constructorProperties() : nullptr; } - const JSFunctionSpec* specPrototypeFunctions() - const { return spec ? spec->prototypeFunctions() : nullptr; } - const JSPropertySpec* specPrototypeProperties() - const { return spec ? spec->prototypeProperties() : nullptr; } - FinishClassInitOp specFinishInitHook() - const { return spec ? spec->finishInitHook() : nullptr; } - - JSWeakmapKeyDelegateOp extWeakmapKeyDelegateOp() - const { return ext ? ext->weakmapKeyDelegateOp : nullptr; } - JSObjectMovedOp extObjectMovedOp() - const { return ext ? ext->objectMovedOp : nullptr; } - - LookupPropertyOp getOpsLookupProperty() const { return oOps ? oOps->lookupProperty : nullptr; } - DefinePropertyOp getOpsDefineProperty() const { return oOps ? oOps->defineProperty : nullptr; } - HasPropertyOp getOpsHasProperty() const { return oOps ? oOps->hasProperty : nullptr; } - GetPropertyOp getOpsGetProperty() const { return oOps ? oOps->getProperty : nullptr; } - SetPropertyOp getOpsSetProperty() const { return oOps ? oOps->setProperty : nullptr; } - GetOwnPropertyOp getOpsGetOwnPropertyDescriptor() - const { return oOps ? oOps->getOwnPropertyDescriptor - : nullptr; } - DeletePropertyOp getOpsDeleteProperty() const { return oOps ? oOps->deleteProperty : nullptr; } - WatchOp getOpsWatch() const { return oOps ? oOps->watch : nullptr; } - UnwatchOp getOpsUnwatch() const { return oOps ? oOps->unwatch : nullptr; } - GetElementsOp getOpsGetElements() const { return oOps ? oOps->getElements : nullptr; } - JSNewEnumerateOp getOpsEnumerate() const { return oOps ? oOps->enumerate : nullptr; } - JSFunToStringOp getOpsFunToString() const { return oOps ? oOps->funToString : nullptr; } -}; - -static_assert(offsetof(JSClassOps, addProperty) == offsetof(ClassOps, addProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, delProperty) == offsetof(ClassOps, delProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, getProperty) == offsetof(ClassOps, getProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, setProperty) == offsetof(ClassOps, setProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, enumerate) == offsetof(ClassOps, enumerate), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, resolve) == offsetof(ClassOps, resolve), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, mayResolve) == offsetof(ClassOps, mayResolve), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, finalize) == offsetof(ClassOps, finalize), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, call) == offsetof(ClassOps, call), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, construct) == offsetof(ClassOps, construct), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, hasInstance) == offsetof(ClassOps, hasInstance), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, trace) == offsetof(ClassOps, trace), - "ClassOps and JSClassOps must be consistent"); -static_assert(sizeof(JSClassOps) == sizeof(ClassOps), - "ClassOps and JSClassOps must be consistent"); - -static_assert(offsetof(JSClass, name) == offsetof(Class, name), - "Class and JSClass must be consistent"); -static_assert(offsetof(JSClass, flags) == offsetof(Class, flags), - "Class and JSClass must be consistent"); -static_assert(offsetof(JSClass, cOps) == offsetof(Class, cOps), - "Class and JSClass must be consistent"); -static_assert(sizeof(JSClass) == sizeof(Class), - "Class and JSClass must be consistent"); - -static MOZ_ALWAYS_INLINE const JSClass* -Jsvalify(const Class* c) -{ - return (const JSClass*)c; -} - -static MOZ_ALWAYS_INLINE const Class* -Valueify(const JSClass* c) -{ - return (const Class*)c; -} - -/** - * Enumeration describing possible values of the [[Class]] internal property - * value of objects. - */ -enum class ESClass { - Object, - Array, - Number, - String, - Boolean, - RegExp, - ArrayBuffer, - SharedArrayBuffer, - Date, - Set, - Map, - Promise, - MapIterator, - SetIterator, - Arguments, - Error, - - /** None of the above. */ - Other -}; - -/* Fills |vp| with the unboxed value for boxed types, or undefined otherwise. */ -bool -Unbox(JSContext* cx, JS::HandleObject obj, JS::MutableHandleValue vp); - -#ifdef DEBUG -JS_FRIEND_API(bool) -HasObjectMovedOp(JSObject* obj); -#endif - -} /* namespace js */ - -#endif /* js_Class_h */ diff --git a/mac/include/spidermonkey/js/Conversions.h b/mac/include/spidermonkey/js/Conversions.h deleted file mode 100644 index 1cee31c5..00000000 --- a/mac/include/spidermonkey/js/Conversions.h +++ /dev/null @@ -1,581 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* ECMAScript conversion operations. */ - -#ifndef js_Conversions_h -#define js_Conversions_h - -#include "mozilla/Casting.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/TypeTraits.h" - -#include - -#include "jspubtd.h" - -#include "js/RootingAPI.h" -#include "js/Value.h" - -struct JSContext; - -namespace js { - -/* DO NOT CALL THIS. Use JS::ToBoolean. */ -extern JS_PUBLIC_API(bool) -ToBooleanSlow(JS::HandleValue v); - -/* DO NOT CALL THIS. Use JS::ToNumber. */ -extern JS_PUBLIC_API(bool) -ToNumberSlow(JSContext* cx, JS::HandleValue v, double* dp); - -/* DO NOT CALL THIS. Use JS::ToInt8. */ -extern JS_PUBLIC_API(bool) -ToInt8Slow(JSContext *cx, JS::HandleValue v, int8_t *out); - -/* DO NOT CALL THIS. Use JS::ToUint8. */ -extern JS_PUBLIC_API(bool) -ToUint8Slow(JSContext *cx, JS::HandleValue v, uint8_t *out); - -/* DO NOT CALL THIS. Use JS::ToInt16. */ -extern JS_PUBLIC_API(bool) -ToInt16Slow(JSContext *cx, JS::HandleValue v, int16_t *out); - -/* DO NOT CALL THIS. Use JS::ToInt32. */ -extern JS_PUBLIC_API(bool) -ToInt32Slow(JSContext* cx, JS::HandleValue v, int32_t* out); - -/* DO NOT CALL THIS. Use JS::ToUint32. */ -extern JS_PUBLIC_API(bool) -ToUint32Slow(JSContext* cx, JS::HandleValue v, uint32_t* out); - -/* DO NOT CALL THIS. Use JS::ToUint16. */ -extern JS_PUBLIC_API(bool) -ToUint16Slow(JSContext* cx, JS::HandleValue v, uint16_t* out); - -/* DO NOT CALL THIS. Use JS::ToInt64. */ -extern JS_PUBLIC_API(bool) -ToInt64Slow(JSContext* cx, JS::HandleValue v, int64_t* out); - -/* DO NOT CALL THIS. Use JS::ToUint64. */ -extern JS_PUBLIC_API(bool) -ToUint64Slow(JSContext* cx, JS::HandleValue v, uint64_t* out); - -/* DO NOT CALL THIS. Use JS::ToString. */ -extern JS_PUBLIC_API(JSString*) -ToStringSlow(JSContext* cx, JS::HandleValue v); - -/* DO NOT CALL THIS. Use JS::ToObject. */ -extern JS_PUBLIC_API(JSObject*) -ToObjectSlow(JSContext* cx, JS::HandleValue v, bool reportScanStack); - -} // namespace js - -namespace JS { - -namespace detail { - -#ifdef JS_DEBUG -/** - * Assert that we're not doing GC on cx, that we're in a request as - * needed, and that the compartments for cx and v are correct. - * Also check that GC would be safe at this point. - */ -extern JS_PUBLIC_API(void) -AssertArgumentsAreSane(JSContext* cx, HandleValue v); -#else -inline void AssertArgumentsAreSane(JSContext* cx, HandleValue v) -{} -#endif /* JS_DEBUG */ - -} // namespace detail - -/** - * ES6 draft 20141224, 7.1.1, second algorithm. - * - * Most users shouldn't call this -- use JS::ToBoolean, ToNumber, or ToString - * instead. This will typically only be called from custom convert hooks that - * wish to fall back to the ES6 default conversion behavior shared by most - * objects in JS, codified as OrdinaryToPrimitive. - */ -extern JS_PUBLIC_API(bool) -OrdinaryToPrimitive(JSContext* cx, HandleObject obj, JSType type, MutableHandleValue vp); - -/* ES6 draft 20141224, 7.1.2. */ -MOZ_ALWAYS_INLINE bool -ToBoolean(HandleValue v) -{ - if (v.isBoolean()) - return v.toBoolean(); - if (v.isInt32()) - return v.toInt32() != 0; - if (v.isNullOrUndefined()) - return false; - if (v.isDouble()) { - double d = v.toDouble(); - return !mozilla::IsNaN(d) && d != 0; - } - if (v.isSymbol()) - return true; - - /* The slow path handles strings and objects. */ - return js::ToBooleanSlow(v); -} - -/* ES6 draft 20141224, 7.1.3. */ -MOZ_ALWAYS_INLINE bool -ToNumber(JSContext* cx, HandleValue v, double* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isNumber()) { - *out = v.toNumber(); - return true; - } - return js::ToNumberSlow(cx, v, out); -} - -/* ES6 draft 20141224, ToInteger (specialized for doubles). */ -inline double -ToInteger(double d) -{ - if (d == 0) - return d; - - if (!mozilla::IsFinite(d)) { - if (mozilla::IsNaN(d)) - return 0; - return d; - } - - return d < 0 ? ceil(d) : floor(d); -} - -/* ES6 draft 20141224, 7.1.5. */ -MOZ_ALWAYS_INLINE bool -ToInt32(JSContext* cx, JS::HandleValue v, int32_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = v.toInt32(); - return true; - } - return js::ToInt32Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.6. */ -MOZ_ALWAYS_INLINE bool -ToUint32(JSContext* cx, HandleValue v, uint32_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint32_t(v.toInt32()); - return true; - } - return js::ToUint32Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.7. */ -MOZ_ALWAYS_INLINE bool -ToInt16(JSContext *cx, JS::HandleValue v, int16_t *out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = int16_t(v.toInt32()); - return true; - } - return js::ToInt16Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.8. */ -MOZ_ALWAYS_INLINE bool -ToUint16(JSContext* cx, HandleValue v, uint16_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint16_t(v.toInt32()); - return true; - } - return js::ToUint16Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.9 */ -MOZ_ALWAYS_INLINE bool -ToInt8(JSContext *cx, JS::HandleValue v, int8_t *out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = int8_t(v.toInt32()); - return true; - } - return js::ToInt8Slow(cx, v, out); -} - -/* ES6 ECMA-262, 7.1.10 */ -MOZ_ALWAYS_INLINE bool -ToUint8(JSContext *cx, JS::HandleValue v, uint8_t *out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint8_t(v.toInt32()); - return true; - } - return js::ToUint8Slow(cx, v, out); -} - -/* - * Non-standard, with behavior similar to that of ToInt32, except in its - * producing an int64_t. - */ -MOZ_ALWAYS_INLINE bool -ToInt64(JSContext* cx, HandleValue v, int64_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = int64_t(v.toInt32()); - return true; - } - return js::ToInt64Slow(cx, v, out); -} - -/* - * Non-standard, with behavior similar to that of ToUint32, except in its - * producing a uint64_t. - */ -MOZ_ALWAYS_INLINE bool -ToUint64(JSContext* cx, HandleValue v, uint64_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint64_t(v.toInt32()); - return true; - } - return js::ToUint64Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.12. */ -MOZ_ALWAYS_INLINE JSString* -ToString(JSContext* cx, HandleValue v) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isString()) - return v.toString(); - return js::ToStringSlow(cx, v); -} - -/* ES6 draft 20141224, 7.1.13. */ -inline JSObject* -ToObject(JSContext* cx, HandleValue v) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isObject()) - return &v.toObject(); - return js::ToObjectSlow(cx, v, false); -} - -namespace detail { - -/* - * Convert a double value to ResultType (an unsigned integral type) using - * ECMAScript-style semantics (that is, in like manner to how ECMAScript's - * ToInt32 converts to int32_t). - * - * If d is infinite or NaN, return 0. - * Otherwise compute d2 = sign(d) * floor(abs(d)), and return the ResultType - * value congruent to d2 mod 2**(bit width of ResultType). - * - * The algorithm below is inspired by that found in - * - * but has been generalized to all integer widths. - */ -template -inline ResultType -ToUintWidth(double d) -{ - static_assert(mozilla::IsUnsigned::value, - "ResultType must be an unsigned type"); - - uint64_t bits = mozilla::BitwiseCast(d); - unsigned DoubleExponentShift = mozilla::FloatingPoint::kExponentShift; - - // Extract the exponent component. (Be careful here! It's not technically - // the exponent in NaN, infinities, and subnormals.) - int_fast16_t exp = - int_fast16_t((bits & mozilla::FloatingPoint::kExponentBits) >> DoubleExponentShift) - - int_fast16_t(mozilla::FloatingPoint::kExponentBias); - - // If the exponent's less than zero, abs(d) < 1, so the result is 0. (This - // also handles subnormals.) - if (exp < 0) - return 0; - - uint_fast16_t exponent = mozilla::AssertedCast(exp); - - // If the exponent is greater than or equal to the bits of precision of a - // double plus ResultType's width, the number is either infinite, NaN, or - // too large to have lower-order bits in the congruent value. (Example: - // 2**84 is exactly representable as a double. The next exact double is - // 2**84 + 2**32. Thus if ResultType is int32_t, an exponent >= 84 implies - // floor(abs(d)) == 0 mod 2**32.) Return 0 in all these cases. - const size_t ResultWidth = CHAR_BIT * sizeof(ResultType); - if (exponent >= DoubleExponentShift + ResultWidth) - return 0; - - // The significand contains the bits that will determine the final result. - // Shift those bits left or right, according to the exponent, to their - // locations in the unsigned binary representation of floor(abs(d)). - static_assert(sizeof(ResultType) <= sizeof(uint64_t), - "Left-shifting below would lose upper bits"); - ResultType result = (exponent > DoubleExponentShift) - ? ResultType(bits << (exponent - DoubleExponentShift)) - : ResultType(bits >> (DoubleExponentShift - exponent)); - - // Two further complications remain. First, |result| may contain bogus - // sign/exponent bits. Second, IEEE-754 numbers' significands (excluding - // subnormals, but we already handled those) have an implicit leading 1 - // which may affect the final result. - // - // It may appear that there's complexity here depending on how ResultWidth - // and DoubleExponentShift relate, but it turns out there's not. - // - // Assume ResultWidth < DoubleExponentShift: - // Only right-shifts leave bogus bits in |result|. For this to happen, - // we must right-shift by > |DoubleExponentShift - ResultWidth|, implying - // |exponent < ResultWidth|. - // The implicit leading bit only matters if it appears in the final - // result -- if |2**exponent mod 2**ResultWidth != 0|. This implies - // |exponent < ResultWidth|. - // Otherwise assume ResultWidth >= DoubleExponentShift: - // Any left-shift less than |ResultWidth - DoubleExponentShift| leaves - // bogus bits in |result|. This implies |exponent < ResultWidth|. Any - // right-shift less than |ResultWidth| does too, which implies - // |DoubleExponentShift - ResultWidth < exponent|. By assumption, then, - // |exponent| is negative, but we excluded that above. So bogus bits - // need only |exponent < ResultWidth|. - // The implicit leading bit matters identically to the other case, so - // again, |exponent < ResultWidth|. - if (exponent < ResultWidth) { - ResultType implicitOne = ResultType(1) << exponent; - result &= implicitOne - 1; // remove bogus bits - result += implicitOne; // add the implicit bit - } - - // Compute the congruent value in the signed range. - return (bits & mozilla::FloatingPoint::kSignBit) ? ~result + 1 : result; -} - -template -inline ResultType -ToIntWidth(double d) -{ - static_assert(mozilla::IsSigned::value, - "ResultType must be a signed type"); - - const ResultType MaxValue = (1ULL << (CHAR_BIT * sizeof(ResultType) - 1)) - 1; - const ResultType MinValue = -MaxValue - 1; - - typedef typename mozilla::MakeUnsigned::Type UnsignedResult; - UnsignedResult u = ToUintWidth(d); - if (u <= UnsignedResult(MaxValue)) - return static_cast(u); - return (MinValue + static_cast(u - MaxValue)) - 1; -} - -} // namespace detail - -/* ES5 9.5 ToInt32 (specialized for doubles). */ -inline int32_t -ToInt32(double d) -{ - // clang crashes compiling this when targeting arm: - // https://llvm.org/bugs/show_bug.cgi?id=22974 -#if defined (__arm__) && defined (__GNUC__) && !defined(__clang__) - int32_t i; - uint32_t tmp0; - uint32_t tmp1; - uint32_t tmp2; - asm ( - // We use a pure integer solution here. In the 'softfp' ABI, the argument - // will start in r0 and r1, and VFP can't do all of the necessary ECMA - // conversions by itself so some integer code will be required anyway. A - // hybrid solution is faster on A9, but this pure integer solution is - // notably faster for A8. - - // %0 is the result register, and may alias either of the %[QR]1 registers. - // %Q4 holds the lower part of the mantissa. - // %R4 holds the sign, exponent, and the upper part of the mantissa. - // %1, %2 and %3 are used as temporary values. - - // Extract the exponent. -" mov %1, %R4, LSR #20\n" -" bic %1, %1, #(1 << 11)\n" // Clear the sign. - - // Set the implicit top bit of the mantissa. This clobbers a bit of the - // exponent, but we have already extracted that. -" orr %R4, %R4, #(1 << 20)\n" - - // Special Cases - // We should return zero in the following special cases: - // - Exponent is 0x000 - 1023: +/-0 or subnormal. - // - Exponent is 0x7ff - 1023: +/-INFINITY or NaN - // - This case is implicitly handled by the standard code path anyway, - // as shifting the mantissa up by the exponent will result in '0'. - // - // The result is composed of the mantissa, prepended with '1' and - // bit-shifted left by the (decoded) exponent. Note that because the r1[20] - // is the bit with value '1', r1 is effectively already shifted (left) by - // 20 bits, and r0 is already shifted by 52 bits. - - // Adjust the exponent to remove the encoding offset. If the decoded - // exponent is negative, quickly bail out with '0' as such values round to - // zero anyway. This also catches +/-0 and subnormals. -" sub %1, %1, #0xff\n" -" subs %1, %1, #0x300\n" -" bmi 8f\n" - - // %1 = (decoded) exponent >= 0 - // %R4 = upper mantissa and sign - - // ---- Lower Mantissa ---- -" subs %3, %1, #52\n" // Calculate exp-52 -" bmi 1f\n" - - // Shift r0 left by exp-52. - // Ensure that we don't overflow ARM's 8-bit shift operand range. - // We need to handle anything up to an 11-bit value here as we know that - // 52 <= exp <= 1024 (0x400). Any shift beyond 31 bits results in zero - // anyway, so as long as we don't touch the bottom 5 bits, we can use - // a logical OR to push long shifts into the 32 <= (exp&0xff) <= 255 range. -" bic %2, %3, #0xff\n" -" orr %3, %3, %2, LSR #3\n" - // We can now perform a straight shift, avoiding the need for any - // conditional instructions or extra branches. -" mov %Q4, %Q4, LSL %3\n" -" b 2f\n" -"1:\n" // Shift r0 right by 52-exp. - // We know that 0 <= exp < 52, and we can shift up to 255 bits so 52-exp - // will always be a valid shift and we can sk%3 the range check for this case. -" rsb %3, %1, #52\n" -" mov %Q4, %Q4, LSR %3\n" - - // %1 = (decoded) exponent - // %R4 = upper mantissa and sign - // %Q4 = partially-converted integer - -"2:\n" - // ---- Upper Mantissa ---- - // This is much the same as the lower mantissa, with a few different - // boundary checks and some masking to hide the exponent & sign bit in the - // upper word. - // Note that the upper mantissa is pre-shifted by 20 in %R4, but we shift - // it left more to remove the sign and exponent so it is effectively - // pre-shifted by 31 bits. -" subs %3, %1, #31\n" // Calculate exp-31 -" mov %1, %R4, LSL #11\n" // Re-use %1 as a temporary register. -" bmi 3f\n" - - // Shift %R4 left by exp-31. - // Avoid overflowing the 8-bit shift range, as before. -" bic %2, %3, #0xff\n" -" orr %3, %3, %2, LSR #3\n" - // Perform the shift. -" mov %2, %1, LSL %3\n" -" b 4f\n" -"3:\n" // Shift r1 right by 31-exp. - // We know that 0 <= exp < 31, and we can shift up to 255 bits so 31-exp - // will always be a valid shift and we can skip the range check for this case. -" rsb %3, %3, #0\n" // Calculate 31-exp from -(exp-31) -" mov %2, %1, LSR %3\n" // Thumb-2 can't do "LSR %3" in "orr". - - // %Q4 = partially-converted integer (lower) - // %R4 = upper mantissa and sign - // %2 = partially-converted integer (upper) - -"4:\n" - // Combine the converted parts. -" orr %Q4, %Q4, %2\n" - // Negate the result if we have to, and move it to %0 in the process. To - // avoid conditionals, we can do this by inverting on %R4[31], then adding - // %R4[31]>>31. -" eor %Q4, %Q4, %R4, ASR #31\n" -" add %0, %Q4, %R4, LSR #31\n" -" b 9f\n" -"8:\n" - // +/-INFINITY, +/-0, subnormals, NaNs, and anything else out-of-range that - // will result in a conversion of '0'. -" mov %0, #0\n" -"9:\n" - : "=r" (i), "=&r" (tmp0), "=&r" (tmp1), "=&r" (tmp2), "=&r" (d) - : "4" (d) - : "cc" - ); - return i; -#else - return detail::ToIntWidth(d); -#endif -} - -/* ES5 9.6 (specialized for doubles). */ -inline uint32_t -ToUint32(double d) -{ - return detail::ToUintWidth(d); -} - -/* WEBIDL 4.2.4 */ -inline int8_t -ToInt8(double d) -{ - return detail::ToIntWidth(d); -} - -/* ECMA-262 7.1.10 ToUInt8() specialized for doubles. */ -inline int8_t -ToUint8(double d) -{ - return detail::ToUintWidth(d); -} - -/* WEBIDL 4.2.6 */ -inline int16_t -ToInt16(double d) -{ - return detail::ToIntWidth(d); -} - -inline uint16_t -ToUint16(double d) -{ - return detail::ToUintWidth(d); -} - -/* WEBIDL 4.2.10 */ -inline int64_t -ToInt64(double d) -{ - return detail::ToIntWidth(d); -} - -/* WEBIDL 4.2.11 */ -inline uint64_t -ToUint64(double d) -{ - return detail::ToUintWidth(d); -} - -} // namespace JS - -#endif /* js_Conversions_h */ diff --git a/mac/include/spidermonkey/js/Date.h b/mac/include/spidermonkey/js/Date.h deleted file mode 100644 index cba0ea87..00000000 --- a/mac/include/spidermonkey/js/Date.h +++ /dev/null @@ -1,170 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JavaScript date/time computation and creation functions. */ - -#ifndef js_Date_h -#define js_Date_h - -/* - * Dates in JavaScript are defined by IEEE-754 double precision numbers from - * the set: - * - * { t ∈ ℕ : -8.64e15 ≤ t ≤ +8.64e15 } ∪ { NaN } - * - * The single NaN value represents any invalid-date value. All other values - * represent idealized durations in milliseconds since the UTC epoch. (Leap - * seconds are ignored; leap days are not.) +0 is the only zero in this set. - * The limit represented by 8.64e15 milliseconds is 100 million days either - * side of 00:00 January 1, 1970 UTC. - * - * Dates in the above set are represented by the |ClippedTime| class. The - * double type is a superset of the above set, so it *may* (but need not) - * represent a date. Use ECMAScript's |TimeClip| method to produce a date from - * a double. - * - * Date *objects* are simply wrappers around |TimeClip|'d numbers, with a bunch - * of accessor methods to the various aspects of the represented date. - */ - -#include "mozilla/FloatingPoint.h" -#include "mozilla/MathAlgorithms.h" - -#include "js/Conversions.h" -#include "js/Value.h" - -struct JSContext; - -namespace JS { - -/** - * Re-query the system to determine the current time zone adjustment from UTC, - * including any component due to DST. If the time zone has changed, this will - * cause all Date object non-UTC methods and formatting functions to produce - * appropriately adjusted results. - * - * Left to its own devices, SpiderMonkey itself may occasionally call this - * method to attempt to keep up with system time changes. However, no - * particular frequency of checking is guaranteed. Embedders unable to accept - * occasional inaccuracies should call this method in response to system time - * changes, or immediately before operations requiring instantaneous - * correctness, to guarantee correct behavior. - */ -extern JS_PUBLIC_API(void) -ResetTimeZone(); - -class ClippedTime; -inline ClippedTime TimeClip(double time); - -/* - * |ClippedTime| represents the limited subset of dates/times described above. - * - * An invalid date/time may be created through the |ClippedTime::invalid| - * method. Otherwise, a |ClippedTime| may be created using the |TimeClip| - * method. - * - * In typical use, the user might wish to manipulate a timestamp. The user - * performs a series of operations on it, but the final value might not be a - * date as defined above -- it could have overflowed, acquired a fractional - * component, &c. So as a *final* step, the user passes that value through - * |TimeClip| to produce a number restricted to JavaScript's date range. - * - * APIs that accept a JavaScript date value thus accept a |ClippedTime|, not a - * double. This ensures that date/time APIs will only ever receive acceptable - * JavaScript dates. This also forces users to perform any desired clipping, - * as only the user knows what behavior is desired when clipping occurs. - */ -class ClippedTime -{ - double t; - - explicit ClippedTime(double time) : t(time) {} - friend ClippedTime TimeClip(double time); - - public: - // Create an invalid date. - ClippedTime() : t(mozilla::UnspecifiedNaN()) {} - - // Create an invalid date/time, more explicitly; prefer this to the default - // constructor. - static ClippedTime invalid() { return ClippedTime(); } - - double toDouble() const { return t; } - - bool isValid() const { return !mozilla::IsNaN(t); } -}; - -// ES6 20.3.1.15. -// -// Clip a double to JavaScript's date range (or to an invalid date) using the -// ECMAScript TimeClip algorithm. -inline ClippedTime -TimeClip(double time) -{ - // Steps 1-2. - const double MaxTimeMagnitude = 8.64e15; - if (!mozilla::IsFinite(time) || mozilla::Abs(time) > MaxTimeMagnitude) - return ClippedTime(mozilla::UnspecifiedNaN()); - - // Step 3. - return ClippedTime(ToInteger(time) + (+0.0)); -} - -// Produce a double Value from the given time. Because times may be NaN, -// prefer using this to manual canonicalization. -inline Value -TimeValue(ClippedTime time) -{ - return DoubleValue(JS::CanonicalizeNaN(time.toDouble())); -} - -// Create a new Date object whose [[DateValue]] internal slot contains the -// clipped |time|. (Users who must represent times outside that range must use -// another representation.) -extern JS_PUBLIC_API(JSObject*) -NewDateObject(JSContext* cx, ClippedTime time); - -// Year is a year, month is 0-11, day is 1-based. The return value is a number -// of milliseconds since the epoch. -// -// Consistent with the MakeDate algorithm defined in ECMAScript, this value is -// *not* clipped! Use JS::TimeClip if you need a clipped date. -JS_PUBLIC_API(double) -MakeDate(double year, unsigned month, unsigned day); - -// Takes an integer number of milliseconds since the epoch and returns the -// year. Can return NaN, and will do so if NaN is passed in. -JS_PUBLIC_API(double) -YearFromTime(double time); - -// Takes an integer number of milliseconds since the epoch and returns the -// month (0-11). Can return NaN, and will do so if NaN is passed in. -JS_PUBLIC_API(double) -MonthFromTime(double time); - -// Takes an integer number of milliseconds since the epoch and returns the -// day (1-based). Can return NaN, and will do so if NaN is passed in. -JS_PUBLIC_API(double) -DayFromTime(double time); - -// Takes an integer year and returns the number of days from epoch to the given -// year. -// NOTE: The calculation performed by this function is literally that given in -// the ECMAScript specification. Nonfinite years, years containing fractional -// components, and years outside ECMAScript's date range are not handled with -// any particular intelligence. Garbage in, garbage out. -JS_PUBLIC_API(double) -DayFromYear(double year); - -// Takes an integer number of milliseconds since the epoch and an integer year, -// returns the number of days in that year. If |time| is nonfinite, returns NaN. -// Otherwise |time| *must* correspond to a time within the valid year |year|. -// This should usually be ensured by computing |year| as |JS::DayFromYear(time)|. -JS_PUBLIC_API(double) -DayWithinYear(double time, double year); - -} // namespace JS - -#endif /* js_Date_h */ diff --git a/mac/include/spidermonkey/js/Debug.h b/mac/include/spidermonkey/js/Debug.h deleted file mode 100644 index 3e4183f0..00000000 --- a/mac/include/spidermonkey/js/Debug.h +++ /dev/null @@ -1,384 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// Interfaces by which the embedding can interact with the Debugger API. - -#ifndef js_Debug_h -#define js_Debug_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/MemoryReporting.h" - -#include "jsapi.h" -#include "jspubtd.h" - -#include "js/GCAPI.h" -#include "js/RootingAPI.h" -#include "js/TypeDecls.h" - -namespace js { -class Debugger; -} // namespace js - -namespace JS { -namespace dbg { - -// Helping embedding code build objects for Debugger -// ------------------------------------------------- -// -// Some Debugger API features lean on the embedding application to construct -// their result values. For example, Debugger.Frame.prototype.scriptEntryReason -// calls hooks provided by the embedding to construct values explaining why it -// invoked JavaScript; if F is a frame called from a mouse click event handler, -// F.scriptEntryReason would return an object of the form: -// -// { eventType: "mousedown", event: } -// -// where is a Debugger.Object whose referent is the event being -// dispatched. -// -// However, Debugger implements a trust boundary. Debuggee code may be -// considered untrusted; debugger code needs to be protected from debuggee -// getters, setters, proxies, Object.watch watchpoints, and any other feature -// that might accidentally cause debugger code to set the debuggee running. The -// Debugger API tries to make it easy to write safe debugger code by only -// offering access to debuggee objects via Debugger.Object instances, which -// ensure that only those operations whose explicit purpose is to invoke -// debuggee code do so. But this protective membrane is only helpful if we -// interpose Debugger.Object instances in all the necessary spots. -// -// SpiderMonkey's compartment system also implements a trust boundary. The -// debuggee and debugger are always in different compartments. Inter-compartment -// work requires carefully tracking which compartment each JSObject or JS::Value -// belongs to, and ensuring that is is correctly wrapped for each operation. -// -// It seems precarious to expect the embedding's hooks to implement these trust -// boundaries. Instead, the JS::dbg::Builder API segregates the code which -// constructs trusted objects from that which deals with untrusted objects. -// Trusted objects have an entirely different C++ type, so code that improperly -// mixes trusted and untrusted objects is caught at compile time. -// -// In the structure shown above, there are two trusted objects, and one -// untrusted object: -// -// - The overall object, with the 'eventType' and 'event' properties, is a -// trusted object. We're going to return it to D.F.p.scriptEntryReason's -// caller, which will handle it directly. -// -// - The Debugger.Object instance appearing as the value of the 'event' property -// is a trusted object. It belongs to the same Debugger instance as the -// Debugger.Frame instance whose scriptEntryReason accessor was called, and -// presents a safe reflection-oriented API for inspecting its referent, which -// is: -// -// - The actual event object, an untrusted object, and the referent of the -// Debugger.Object above. (Content can do things like replacing accessors on -// Event.prototype.) -// -// Using JS::dbg::Builder, all objects and values the embedding deals with -// directly are considered untrusted, and are assumed to be debuggee values. The -// only way to construct trusted objects is to use Builder's own methods, which -// return a separate Object type. The only way to set a property on a trusted -// object is through that Object type. The actual trusted object is never -// exposed to the embedding. -// -// So, for example, the embedding might use code like the following to construct -// the object shown above, given a Builder passed to it by Debugger: -// -// bool -// MyScriptEntryReason::explain(JSContext* cx, -// Builder& builder, -// Builder::Object& result) -// { -// JSObject* eventObject = ... obtain debuggee event object somehow ...; -// if (!eventObject) -// return false; -// result = builder.newObject(cx); -// return result && -// result.defineProperty(cx, "eventType", SafelyFetchType(eventObject)) && -// result.defineProperty(cx, "event", eventObject); -// } -// -// -// Object::defineProperty also accepts an Object as the value to store on the -// property. By its type, we know that the value is trusted, so we set it -// directly as the property's value, without interposing a Debugger.Object -// wrapper. This allows the embedding to builted nested structures of trusted -// objects. -// -// The Builder and Builder::Object methods take care of doing whatever -// compartment switching and wrapping are necessary to construct the trusted -// values in the Debugger's compartment. -// -// The Object type is self-rooting. Construction, assignment, and destruction -// all properly root the referent object. - -class BuilderOrigin; - -class Builder { - // The Debugger instance whose client we are building a value for. We build - // objects in this object's compartment. - PersistentRootedObject debuggerObject; - - // debuggerObject's Debugger structure, for convenience. - js::Debugger* debugger; - - // Check that |thing| is in the same compartment as our debuggerObject. Used - // for assertions when constructing BuiltThings. We can overload this as we - // add more instantiations of BuiltThing. -#if DEBUG - void assertBuilt(JSObject* obj); -#else - void assertBuilt(JSObject* obj) { } -#endif - - protected: - // A reference to a trusted object or value. At the moment, we only use it - // with JSObject*. - template - class BuiltThing { - friend class BuilderOrigin; - - protected: - // The Builder to which this trusted thing belongs. - Builder& owner; - - // A rooted reference to our value. - PersistentRooted value; - - BuiltThing(JSContext* cx, Builder& owner_, T value_ = GCPolicy::initial()) - : owner(owner_), value(cx, value_) - { - owner.assertBuilt(value_); - } - - // Forward some things from our owner, for convenience. - js::Debugger* debugger() const { return owner.debugger; } - JSObject* debuggerObject() const { return owner.debuggerObject; } - - public: - BuiltThing(const BuiltThing& rhs) : owner(rhs.owner), value(rhs.value) { } - BuiltThing& operator=(const BuiltThing& rhs) { - MOZ_ASSERT(&owner == &rhs.owner); - owner.assertBuilt(rhs.value); - value = rhs.value; - return *this; - } - - explicit operator bool() const { - // If we ever instantiate BuiltThing, this might not suffice. - return value; - } - - private: - BuiltThing() = delete; - }; - - public: - // A reference to a trusted object, possibly null. Instances of Object are - // always properly rooted. They can be copied and assigned, as if they were - // pointers. - class Object: private BuiltThing { - friend class Builder; // for construction - friend class BuilderOrigin; // for unwrapping - - typedef BuiltThing Base; - - // This is private, because only Builders can create Objects that - // actually point to something (hence the 'friend' declaration). - Object(JSContext* cx, Builder& owner_, HandleObject obj) : Base(cx, owner_, obj.get()) { } - - bool definePropertyToTrusted(JSContext* cx, const char* name, - JS::MutableHandleValue value); - - public: - Object(JSContext* cx, Builder& owner_) : Base(cx, owner_, nullptr) { } - Object(const Object& rhs) : Base(rhs) { } - - // Our automatically-generated assignment operator can see our base - // class's assignment operator, so we don't need to write one out here. - - // Set the property named |name| on this object to |value|. - // - // If |value| is a string or primitive, re-wrap it for the debugger's - // compartment. - // - // If |value| is an object, assume it is a debuggee object and make a - // Debugger.Object instance referring to it. Set that as the propery's - // value. - // - // If |value| is another trusted object, store it directly as the - // property's value. - // - // On error, report the problem on cx and return false. - bool defineProperty(JSContext* cx, const char* name, JS::HandleValue value); - bool defineProperty(JSContext* cx, const char* name, JS::HandleObject value); - bool defineProperty(JSContext* cx, const char* name, Object& value); - - using Base::operator bool; - }; - - // Build an empty object for direct use by debugger code, owned by this - // Builder. If an error occurs, report it on cx and return a false Object. - Object newObject(JSContext* cx); - - protected: - Builder(JSContext* cx, js::Debugger* debugger); -}; - -// Debugger itself instantiates this subclass of Builder, which can unwrap -// BuiltThings that belong to it. -class BuilderOrigin : public Builder { - template - T unwrapAny(const BuiltThing& thing) { - MOZ_ASSERT(&thing.owner == this); - return thing.value.get(); - } - - public: - BuilderOrigin(JSContext* cx, js::Debugger* debugger_) - : Builder(cx, debugger_) - { } - - JSObject* unwrap(Object& object) { return unwrapAny(object); } -}; - - - -// Finding the size of blocks allocated with malloc -// ------------------------------------------------ -// -// Debugger.Memory wants to be able to report how many bytes items in memory are -// consuming. To do this, it needs a function that accepts a pointer to a block, -// and returns the number of bytes allocated to that block. SpiderMonkey itself -// doesn't know which function is appropriate to use, but the embedding does. - -// Tell Debuggers in |cx| to use |mallocSizeOf| to find the size of -// malloc'd blocks. -JS_PUBLIC_API(void) -SetDebuggerMallocSizeOf(JSContext* cx, mozilla::MallocSizeOf mallocSizeOf); - -// Get the MallocSizeOf function that the given context is using to find the -// size of malloc'd blocks. -JS_PUBLIC_API(mozilla::MallocSizeOf) -GetDebuggerMallocSizeOf(JSContext* cx); - - - -// Debugger and Garbage Collection Events -// -------------------------------------- -// -// The Debugger wants to report about its debuggees' GC cycles, however entering -// JS after a GC is troublesome since SpiderMonkey will often do something like -// force a GC and then rely on the nursery being empty. If we call into some -// Debugger's hook after the GC, then JS runs and the nursery won't be -// empty. Instead, we rely on embedders to call back into SpiderMonkey after a -// GC and notify Debuggers to call their onGarbageCollection hook. - - -// For each Debugger that observed a debuggee involved in the given GC event, -// call its `onGarbageCollection` hook. -JS_PUBLIC_API(bool) -FireOnGarbageCollectionHook(JSContext* cx, GarbageCollectionEvent::Ptr&& data); - - - -// Handlers for observing Promises -// ------------------------------- -// -// The Debugger wants to observe behavior of promises, which are implemented by -// Gecko with webidl and which SpiderMonkey knows nothing about. On the other -// hand, Gecko knows nothing about which (if any) debuggers are observing a -// promise's global. The compromise is that Gecko is responsible for calling -// these handlers at the appropriate times, and SpiderMonkey will handle -// notifying any Debugger instances that are observing the given promise's -// global. - -// Notify any Debugger instances observing this promise's global that a new -// promise was allocated. -JS_PUBLIC_API(void) -onNewPromise(JSContext* cx, HandleObject promise); - -// Notify any Debugger instances observing this promise's global that the -// promise has settled (ie, it has either been fulfilled or rejected). Note that -// this is *not* equivalent to the promise resolution (ie, the promise's fate -// getting locked in) because you can resolve a promise with another pending -// promise, in which case neither promise has settled yet. -// -// It is Gecko's responsibility to ensure that this is never called on the same -// promise more than once (because a promise can only make the transition from -// unsettled to settled once). -JS_PUBLIC_API(void) -onPromiseSettled(JSContext* cx, HandleObject promise); - - - -// Return true if the given value is a Debugger object, false otherwise. -JS_PUBLIC_API(bool) -IsDebugger(JSObject& obj); - -// Append each of the debuggee global objects observed by the Debugger object -// |dbgObj| to |vector|. Returns true on success, false on failure. -JS_PUBLIC_API(bool) -GetDebuggeeGlobals(JSContext* cx, JSObject& dbgObj, AutoObjectVector& vector); - - -// Hooks for reporting where JavaScript execution began. -// -// Our performance tools would like to be able to label blocks of JavaScript -// execution with the function name and source location where execution began: -// the event handler, the callback, etc. -// -// Construct an instance of this class on the stack, providing a JSContext -// belonging to the runtime in which execution will occur. Each time we enter -// JavaScript --- specifically, each time we push a JavaScript stack frame that -// has no older JS frames younger than this AutoEntryMonitor --- we will -// call the appropriate |Entry| member function to indicate where we've begun -// execution. - -class MOZ_STACK_CLASS AutoEntryMonitor { - JSRuntime* runtime_; - AutoEntryMonitor* savedMonitor_; - - public: - explicit AutoEntryMonitor(JSContext* cx); - ~AutoEntryMonitor(); - - // SpiderMonkey reports the JavaScript entry points occuring within this - // AutoEntryMonitor's scope to the following member functions, which the - // embedding is expected to override. - // - // It is important to note that |asyncCause| is owned by the caller and its - // lifetime must outlive the lifetime of the AutoEntryMonitor object. It is - // strongly encouraged that |asyncCause| be a string constant or similar - // statically allocated string. - - // We have begun executing |function|. Note that |function| may not be the - // actual closure we are running, but only the canonical function object to - // which the script refers. - virtual void Entry(JSContext* cx, JSFunction* function, - HandleValue asyncStack, - const char* asyncCause) = 0; - - // Execution has begun at the entry point of |script|, which is not a - // function body. (This is probably being executed by 'eval' or some - // JSAPI equivalent.) - virtual void Entry(JSContext* cx, JSScript* script, - HandleValue asyncStack, - const char* asyncCause) = 0; - - // Execution of the function or script has ended. - virtual void Exit(JSContext* cx) { } -}; - - - -} // namespace dbg -} // namespace JS - - -#endif /* js_Debug_h */ diff --git a/mac/include/spidermonkey/js/GCAPI.h b/mac/include/spidermonkey/js/GCAPI.h deleted file mode 100644 index 7a6675ca..00000000 --- a/mac/include/spidermonkey/js/GCAPI.h +++ /dev/null @@ -1,723 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCAPI_h -#define js_GCAPI_h - -#include "mozilla/Vector.h" - -#include "js/GCAnnotations.h" -#include "js/HeapAPI.h" -#include "js/UniquePtr.h" - -namespace js { -namespace gc { -class GCRuntime; -} // namespace gc -namespace gcstats { -struct Statistics; -} // namespace gcstats -} // namespace js - -typedef enum JSGCMode { - /** Perform only global GCs. */ - JSGC_MODE_GLOBAL = 0, - - /** Perform per-zone GCs until too much garbage has accumulated. */ - JSGC_MODE_ZONE = 1, - - /** - * Collect in short time slices rather than all at once. Implies - * JSGC_MODE_ZONE. - */ - JSGC_MODE_INCREMENTAL = 2 -} JSGCMode; - -/** - * Kinds of js_GC invocation. - */ -typedef enum JSGCInvocationKind { - /* Normal invocation. */ - GC_NORMAL = 0, - - /* Minimize GC triggers and release empty GC chunks right away. */ - GC_SHRINK = 1 -} JSGCInvocationKind; - -namespace JS { - -#define GCREASONS(D) \ - /* Reasons internal to the JS engine */ \ - D(API) \ - D(EAGER_ALLOC_TRIGGER) \ - D(DESTROY_RUNTIME) \ - D(UNUSED0) \ - D(LAST_DITCH) \ - D(TOO_MUCH_MALLOC) \ - D(ALLOC_TRIGGER) \ - D(DEBUG_GC) \ - D(COMPARTMENT_REVIVED) \ - D(RESET) \ - D(OUT_OF_NURSERY) \ - D(EVICT_NURSERY) \ - D(FULL_STORE_BUFFER) \ - D(SHARED_MEMORY_LIMIT) \ - D(UNUSED1) \ - D(INCREMENTAL_TOO_SLOW) \ - D(ABORT_GC) \ - \ - /* These are reserved for future use. */ \ - D(RESERVED0) \ - D(RESERVED1) \ - D(RESERVED2) \ - D(RESERVED3) \ - D(RESERVED4) \ - D(RESERVED5) \ - D(RESERVED6) \ - D(RESERVED7) \ - D(RESERVED8) \ - D(RESERVED9) \ - D(RESERVED10) \ - D(RESERVED11) \ - D(RESERVED12) \ - D(RESERVED13) \ - D(RESERVED14) \ - D(RESERVED15) \ - \ - /* Reasons from Firefox */ \ - D(DOM_WINDOW_UTILS) \ - D(COMPONENT_UTILS) \ - D(MEM_PRESSURE) \ - D(CC_WAITING) \ - D(CC_FORCED) \ - D(LOAD_END) \ - D(POST_COMPARTMENT) \ - D(PAGE_HIDE) \ - D(NSJSCONTEXT_DESTROY) \ - D(SET_NEW_DOCUMENT) \ - D(SET_DOC_SHELL) \ - D(DOM_UTILS) \ - D(DOM_IPC) \ - D(DOM_WORKER) \ - D(INTER_SLICE_GC) \ - D(REFRESH_FRAME) \ - D(FULL_GC_TIMER) \ - D(SHUTDOWN_CC) \ - D(FINISH_LARGE_EVALUATE) \ - D(USER_INACTIVE) \ - D(XPCONNECT_SHUTDOWN) - -namespace gcreason { - -/* GCReasons will end up looking like JSGC_MAYBEGC */ -enum Reason { -#define MAKE_REASON(name) name, - GCREASONS(MAKE_REASON) -#undef MAKE_REASON - NO_REASON, - NUM_REASONS, - - /* - * For telemetry, we want to keep a fixed max bucket size over time so we - * don't have to switch histograms. 100 is conservative; as of this writing - * there are 52. But the cost of extra buckets seems to be low while the - * cost of switching histograms is high. - */ - NUM_TELEMETRY_REASONS = 100 -}; - -/** - * Get a statically allocated C string explaining the given GC reason. - */ -extern JS_PUBLIC_API(const char*) -ExplainReason(JS::gcreason::Reason reason); - -} /* namespace gcreason */ - -/* - * Zone GC: - * - * SpiderMonkey's GC is capable of performing a collection on an arbitrary - * subset of the zones in the system. This allows an embedding to minimize - * collection time by only collecting zones that have run code recently, - * ignoring the parts of the heap that are unlikely to have changed. - * - * When triggering a GC using one of the functions below, it is first necessary - * to select the zones to be collected. To do this, you can call - * PrepareZoneForGC on each zone, or you can call PrepareForFullGC to select - * all zones. Failing to select any zone is an error. - */ - -/** - * Schedule the given zone to be collected as part of the next GC. - */ -extern JS_PUBLIC_API(void) -PrepareZoneForGC(Zone* zone); - -/** - * Schedule all zones to be collected in the next GC. - */ -extern JS_PUBLIC_API(void) -PrepareForFullGC(JSContext* cx); - -/** - * When performing an incremental GC, the zones that were selected for the - * previous incremental slice must be selected in subsequent slices as well. - * This function selects those slices automatically. - */ -extern JS_PUBLIC_API(void) -PrepareForIncrementalGC(JSContext* cx); - -/** - * Returns true if any zone in the system has been scheduled for GC with one of - * the functions above or by the JS engine. - */ -extern JS_PUBLIC_API(bool) -IsGCScheduled(JSContext* cx); - -/** - * Undoes the effect of the Prepare methods above. The given zone will not be - * collected in the next GC. - */ -extern JS_PUBLIC_API(void) -SkipZoneForGC(Zone* zone); - -/* - * Non-Incremental GC: - * - * The following functions perform a non-incremental GC. - */ - -/** - * Performs a non-incremental collection of all selected zones. - * - * If the gckind argument is GC_NORMAL, then some objects that are unreachable - * from the program may still be alive afterwards because of internal - * references; if GC_SHRINK is passed then caches and other temporary references - * to objects will be cleared and all unreferenced objects will be removed from - * the system. - */ -extern JS_PUBLIC_API(void) -GCForReason(JSContext* cx, JSGCInvocationKind gckind, gcreason::Reason reason); - -/* - * Incremental GC: - * - * Incremental GC divides the full mark-and-sweep collection into multiple - * slices, allowing client JavaScript code to run between each slice. This - * allows interactive apps to avoid long collection pauses. Incremental GC does - * not make collection take less time, it merely spreads that time out so that - * the pauses are less noticable. - * - * For a collection to be carried out incrementally the following conditions - * must be met: - * - The collection must be run by calling JS::IncrementalGC() rather than - * JS_GC(). - * - The GC mode must have been set to JSGC_MODE_INCREMENTAL with - * JS_SetGCParameter(). - * - * Note: Even if incremental GC is enabled and working correctly, - * non-incremental collections can still happen when low on memory. - */ - -/** - * Begin an incremental collection and perform one slice worth of work. When - * this function returns, the collection may not be complete. - * IncrementalGCSlice() must be called repeatedly until - * !IsIncrementalGCInProgress(cx). - * - * Note: SpiderMonkey's GC is not realtime. Slices in practice may be longer or - * shorter than the requested interval. - */ -extern JS_PUBLIC_API(void) -StartIncrementalGC(JSContext* cx, JSGCInvocationKind gckind, gcreason::Reason reason, - int64_t millis = 0); - -/** - * Perform a slice of an ongoing incremental collection. When this function - * returns, the collection may not be complete. It must be called repeatedly - * until !IsIncrementalGCInProgress(cx). - * - * Note: SpiderMonkey's GC is not realtime. Slices in practice may be longer or - * shorter than the requested interval. - */ -extern JS_PUBLIC_API(void) -IncrementalGCSlice(JSContext* cx, gcreason::Reason reason, int64_t millis = 0); - -/** - * If IsIncrementalGCInProgress(cx), this call finishes the ongoing collection - * by performing an arbitrarily long slice. If !IsIncrementalGCInProgress(cx), - * this is equivalent to GCForReason. When this function returns, - * IsIncrementalGCInProgress(cx) will always be false. - */ -extern JS_PUBLIC_API(void) -FinishIncrementalGC(JSContext* cx, gcreason::Reason reason); - -/** - * If IsIncrementalGCInProgress(cx), this call aborts the ongoing collection and - * performs whatever work needs to be done to return the collector to its idle - * state. This may take an arbitrarily long time. When this function returns, - * IsIncrementalGCInProgress(cx) will always be false. - */ -extern JS_PUBLIC_API(void) -AbortIncrementalGC(JSContext* cx); - -namespace dbg { - -// The `JS::dbg::GarbageCollectionEvent` class is essentially a view of the -// `js::gcstats::Statistics` data without the uber implementation-specific bits. -// It should generally be palatable for web developers. -class GarbageCollectionEvent -{ - // The major GC number of the GC cycle this data pertains to. - uint64_t majorGCNumber_; - - // Reference to a non-owned, statically allocated C string. This is a very - // short reason explaining why a GC was triggered. - const char* reason; - - // Reference to a nullable, non-owned, statically allocated C string. If the - // collection was forced to be non-incremental, this is a short reason of - // why the GC could not perform an incremental collection. - const char* nonincrementalReason; - - // Represents a single slice of a possibly multi-slice incremental garbage - // collection. - struct Collection { - double startTimestamp; - double endTimestamp; - }; - - // The set of garbage collection slices that made up this GC cycle. - mozilla::Vector collections; - - GarbageCollectionEvent(const GarbageCollectionEvent& rhs) = delete; - GarbageCollectionEvent& operator=(const GarbageCollectionEvent& rhs) = delete; - - public: - explicit GarbageCollectionEvent(uint64_t majorGCNum) - : majorGCNumber_(majorGCNum) - , reason(nullptr) - , nonincrementalReason(nullptr) - , collections() - { } - - using Ptr = js::UniquePtr; - static Ptr Create(JSRuntime* rt, ::js::gcstats::Statistics& stats, uint64_t majorGCNumber); - - JSObject* toJSObject(JSContext* cx) const; - - uint64_t majorGCNumber() const { return majorGCNumber_; } -}; - -} // namespace dbg - -enum GCProgress { - /* - * During non-incremental GC, the GC is bracketed by JSGC_CYCLE_BEGIN/END - * callbacks. During an incremental GC, the sequence of callbacks is as - * follows: - * JSGC_CYCLE_BEGIN, JSGC_SLICE_END (first slice) - * JSGC_SLICE_BEGIN, JSGC_SLICE_END (second slice) - * ... - * JSGC_SLICE_BEGIN, JSGC_CYCLE_END (last slice) - */ - - GC_CYCLE_BEGIN, - GC_SLICE_BEGIN, - GC_SLICE_END, - GC_CYCLE_END -}; - -struct JS_PUBLIC_API(GCDescription) { - bool isZone_; - JSGCInvocationKind invocationKind_; - gcreason::Reason reason_; - - GCDescription(bool isZone, JSGCInvocationKind kind, gcreason::Reason reason) - : isZone_(isZone), invocationKind_(kind), reason_(reason) {} - - char16_t* formatSliceMessage(JSContext* cx) const; - char16_t* formatSummaryMessage(JSContext* cx) const; - char16_t* formatJSON(JSContext* cx, uint64_t timestamp) const; - - JS::dbg::GarbageCollectionEvent::Ptr toGCEvent(JSContext* cx) const; -}; - -typedef void -(* GCSliceCallback)(JSContext* cx, GCProgress progress, const GCDescription& desc); - -/** - * The GC slice callback is called at the beginning and end of each slice. This - * callback may be used for GC notifications as well as to perform additional - * marking. - */ -extern JS_PUBLIC_API(GCSliceCallback) -SetGCSliceCallback(JSContext* cx, GCSliceCallback callback); - -/** - * Describes the progress of an observed nursery collection. - */ -enum class GCNurseryProgress { - /** - * The nursery collection is starting. - */ - GC_NURSERY_COLLECTION_START, - /** - * The nursery collection is ending. - */ - GC_NURSERY_COLLECTION_END -}; - -/** - * A nursery collection callback receives the progress of the nursery collection - * and the reason for the collection. - */ -using GCNurseryCollectionCallback = void(*)(JSContext* cx, GCNurseryProgress progress, - gcreason::Reason reason); - -/** - * Set the nursery collection callback for the given runtime. When set, it will - * be called at the start and end of every nursery collection. - */ -extern JS_PUBLIC_API(GCNurseryCollectionCallback) -SetGCNurseryCollectionCallback(JSContext* cx, GCNurseryCollectionCallback callback); - -typedef void -(* DoCycleCollectionCallback)(JSContext* cx); - -/** - * The purge gray callback is called after any COMPARTMENT_REVIVED GC in which - * the majority of compartments have been marked gray. - */ -extern JS_PUBLIC_API(DoCycleCollectionCallback) -SetDoCycleCollectionCallback(JSContext* cx, DoCycleCollectionCallback callback); - -/** - * Incremental GC defaults to enabled, but may be disabled for testing or in - * embeddings that have not yet implemented barriers on their native classes. - * There is not currently a way to re-enable incremental GC once it has been - * disabled on the runtime. - */ -extern JS_PUBLIC_API(void) -DisableIncrementalGC(JSContext* cx); - -/** - * Returns true if incremental GC is enabled. Simply having incremental GC - * enabled is not sufficient to ensure incremental collections are happening. - * See the comment "Incremental GC" above for reasons why incremental GC may be - * suppressed. Inspection of the "nonincremental reason" field of the - * GCDescription returned by GCSliceCallback may help narrow down the cause if - * collections are not happening incrementally when expected. - */ -extern JS_PUBLIC_API(bool) -IsIncrementalGCEnabled(JSContext* cx); - -/** - * Returns true while an incremental GC is ongoing, both when actively - * collecting and between slices. - */ -extern JS_PUBLIC_API(bool) -IsIncrementalGCInProgress(JSContext* cx); - -/* - * Returns true when writes to GC things must call an incremental (pre) barrier. - * This is generally only true when running mutator code in-between GC slices. - * At other times, the barrier may be elided for performance. - */ -extern JS_PUBLIC_API(bool) -IsIncrementalBarrierNeeded(JSContext* cx); - -/* - * Notify the GC that a reference to a GC thing is about to be overwritten. - * These methods must be called if IsIncrementalBarrierNeeded. - */ -extern JS_PUBLIC_API(void) -IncrementalReferenceBarrier(GCCellPtr thing); - -extern JS_PUBLIC_API(void) -IncrementalValueBarrier(const Value& v); - -extern JS_PUBLIC_API(void) -IncrementalObjectBarrier(JSObject* obj); - -/** - * Returns true if the most recent GC ran incrementally. - */ -extern JS_PUBLIC_API(bool) -WasIncrementalGC(JSContext* cx); - -/* - * Generational GC: - * - * Note: Generational GC is not yet enabled by default. The following class - * is non-functional unless SpiderMonkey was configured with - * --enable-gcgenerational. - */ - -/** Ensure that generational GC is disabled within some scope. */ -class JS_PUBLIC_API(AutoDisableGenerationalGC) -{ - js::gc::GCRuntime* gc; - - public: - explicit AutoDisableGenerationalGC(JSRuntime* rt); - ~AutoDisableGenerationalGC(); -}; - -/** - * Returns true if generational allocation and collection is currently enabled - * on the given runtime. - */ -extern JS_PUBLIC_API(bool) -IsGenerationalGCEnabled(JSRuntime* rt); - -/** - * Returns the GC's "number". This does not correspond directly to the number - * of GCs that have been run, but is guaranteed to be monotonically increasing - * with GC activity. - */ -extern JS_PUBLIC_API(size_t) -GetGCNumber(); - -/** - * Pass a subclass of this "abstract" class to callees to require that they - * never GC. Subclasses can use assertions or the hazard analysis to ensure no - * GC happens. - */ -class JS_PUBLIC_API(AutoRequireNoGC) -{ - protected: - AutoRequireNoGC() {} - ~AutoRequireNoGC() {} -}; - -/** - * Diagnostic assert (see MOZ_DIAGNOSTIC_ASSERT) that GC cannot occur while this - * class is live. This class does not disable the static rooting hazard - * analysis. - * - * This works by entering a GC unsafe region, which is checked on allocation and - * on GC. - */ -class JS_PUBLIC_API(AutoAssertNoGC) : public AutoRequireNoGC -{ - js::gc::GCRuntime* gc; - size_t gcNumber; - - public: - AutoAssertNoGC(); - explicit AutoAssertNoGC(JSRuntime* rt); - explicit AutoAssertNoGC(JSContext* cx); - ~AutoAssertNoGC(); -}; - -/** - * Assert if an allocation of a GC thing occurs while this class is live. This - * class does not disable the static rooting hazard analysis. - */ -class JS_PUBLIC_API(AutoAssertNoAlloc) -{ -#ifdef JS_DEBUG - js::gc::GCRuntime* gc; - - public: - AutoAssertNoAlloc() : gc(nullptr) {} - explicit AutoAssertNoAlloc(JSContext* cx); - void disallowAlloc(JSRuntime* rt); - ~AutoAssertNoAlloc(); -#else - public: - AutoAssertNoAlloc() {} - explicit AutoAssertNoAlloc(JSContext* cx) {} - void disallowAlloc(JSRuntime* rt) {} -#endif -}; - -/** - * Assert if a GC barrier is invoked while this class is live. This class does - * not disable the static rooting hazard analysis. - */ -class JS_PUBLIC_API(AutoAssertOnBarrier) -{ - JSContext* context; - bool prev; - - public: - explicit AutoAssertOnBarrier(JSContext* cx); - ~AutoAssertOnBarrier(); -}; - -/** - * Disable the static rooting hazard analysis in the live region and assert if - * any allocation that could potentially trigger a GC occurs while this guard - * object is live. This is most useful to help the exact rooting hazard analysis - * in complex regions, since it cannot understand dataflow. - * - * Note: GC behavior is unpredictable even when deterministic and is generally - * non-deterministic in practice. The fact that this guard has not - * asserted is not a guarantee that a GC cannot happen in the guarded - * region. As a rule, anyone performing a GC unsafe action should - * understand the GC properties of all code in that region and ensure - * that the hazard analysis is correct for that code, rather than relying - * on this class. - */ -class JS_PUBLIC_API(AutoSuppressGCAnalysis) : public AutoAssertNoAlloc -{ - public: - AutoSuppressGCAnalysis() : AutoAssertNoAlloc() {} - explicit AutoSuppressGCAnalysis(JSContext* cx) : AutoAssertNoAlloc(cx) {} -} JS_HAZ_GC_SUPPRESSED; - -/** - * Assert that code is only ever called from a GC callback, disable the static - * rooting hazard analysis and assert if any allocation that could potentially - * trigger a GC occurs while this guard object is live. - * - * This is useful to make the static analysis ignore code that runs in GC - * callbacks. - */ -class JS_PUBLIC_API(AutoAssertGCCallback) : public AutoSuppressGCAnalysis -{ - public: - explicit AutoAssertGCCallback(JSObject* obj); -}; - -/** - * Place AutoCheckCannotGC in scopes that you believe can never GC. These - * annotations will be verified both dynamically via AutoAssertNoGC, and - * statically with the rooting hazard analysis (implemented by making the - * analysis consider AutoCheckCannotGC to be a GC pointer, and therefore - * complain if it is live across a GC call.) It is useful when dealing with - * internal pointers to GC things where the GC thing itself may not be present - * for the static analysis: e.g. acquiring inline chars from a JSString* on the - * heap. - * - * We only do the assertion checking in DEBUG builds. - */ -#ifdef DEBUG -class JS_PUBLIC_API(AutoCheckCannotGC) : public AutoAssertNoGC -{ - public: - AutoCheckCannotGC() : AutoAssertNoGC() {} - explicit AutoCheckCannotGC(JSContext* cx) : AutoAssertNoGC(cx) {} -} JS_HAZ_GC_INVALIDATED; -#else -class JS_PUBLIC_API(AutoCheckCannotGC) : public AutoRequireNoGC -{ - public: - AutoCheckCannotGC() {} - explicit AutoCheckCannotGC(JSContext* cx) {} -} JS_HAZ_GC_INVALIDATED; -#endif - -/** - * Unsets the gray bit for anything reachable from |thing|. |kind| should not be - * JS::TraceKind::Shape. |thing| should be non-null. The return value indicates - * if anything was unmarked. - */ -extern JS_FRIEND_API(bool) -UnmarkGrayGCThingRecursively(GCCellPtr thing); - -} /* namespace JS */ - -namespace js { -namespace gc { - -static MOZ_ALWAYS_INLINE void -ExposeGCThingToActiveJS(JS::GCCellPtr thing) -{ - // GC things residing in the nursery cannot be gray: they have no mark bits. - // All live objects in the nursery are moved to tenured at the beginning of - // each GC slice, so the gray marker never sees nursery things. - if (IsInsideNursery(thing.asCell())) - return; - - // There's nothing to do for permanent GC things that might be owned by - // another runtime. - if (thing.mayBeOwnedByOtherRuntime()) - return; - - JS::shadow::Runtime* rt = detail::GetCellRuntime(thing.asCell()); - MOZ_DIAGNOSTIC_ASSERT(rt->allowGCBarriers()); - - if (IsIncrementalBarrierNeededOnTenuredGCThing(rt, thing)) - JS::IncrementalReferenceBarrier(thing); - else if (!thing.mayBeOwnedByOtherRuntime() && js::gc::detail::CellIsMarkedGray(thing.asCell())) - JS::UnmarkGrayGCThingRecursively(thing); -} - -static MOZ_ALWAYS_INLINE void -MarkGCThingAsLive(JSRuntime* aRt, JS::GCCellPtr thing) -{ - // Any object in the nursery will not be freed during any GC running at that - // time. - if (IsInsideNursery(thing.asCell())) - return; - - // There's nothing to do for permanent GC things that might be owned by - // another runtime. - if (thing.mayBeOwnedByOtherRuntime()) - return; - - JS::shadow::Runtime* rt = JS::shadow::Runtime::asShadowRuntime(aRt); - MOZ_DIAGNOSTIC_ASSERT(rt->allowGCBarriers()); - - if (IsIncrementalBarrierNeededOnTenuredGCThing(rt, thing)) - JS::IncrementalReferenceBarrier(thing); -} - -} /* namespace gc */ -} /* namespace js */ - -namespace JS { - -/* - * This should be called when an object that is marked gray is exposed to the JS - * engine (by handing it to running JS code or writing it into live JS - * data). During incremental GC, since the gray bits haven't been computed yet, - * we conservatively mark the object black. - */ -static MOZ_ALWAYS_INLINE void -ExposeObjectToActiveJS(JSObject* obj) -{ - MOZ_ASSERT(obj); - js::gc::ExposeGCThingToActiveJS(GCCellPtr(obj)); -} - -static MOZ_ALWAYS_INLINE void -ExposeScriptToActiveJS(JSScript* script) -{ - js::gc::ExposeGCThingToActiveJS(GCCellPtr(script)); -} - -/* - * If a GC is currently marking, mark the string black. - */ -static MOZ_ALWAYS_INLINE void -MarkStringAsLive(Zone* zone, JSString* string) -{ - JSRuntime* rt = JS::shadow::Zone::asShadowZone(zone)->runtimeFromMainThread(); - js::gc::MarkGCThingAsLive(rt, GCCellPtr(string)); -} - -/* - * Internal to Firefox. - * - * Note: this is not related to the PokeGC in nsJSEnvironment. - */ -extern JS_FRIEND_API(void) -PokeGC(JSContext* cx); - -/* - * Internal to Firefox. - */ -extern JS_FRIEND_API(void) -NotifyDidPaint(JSContext* cx); - -} /* namespace JS */ - -#endif /* js_GCAPI_h */ diff --git a/mac/include/spidermonkey/js/GCAnnotations.h b/mac/include/spidermonkey/js/GCAnnotations.h deleted file mode 100644 index 366d787b..00000000 --- a/mac/include/spidermonkey/js/GCAnnotations.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCAnnotations_h -#define js_GCAnnotations_h - -// Set of annotations for the rooting hazard analysis, used to categorize types -// and functions. -#ifdef XGILL_PLUGIN - -// Mark a type as being a GC thing (eg js::gc::Cell has this annotation). -# define JS_HAZ_GC_THING __attribute__((tag("GC Thing"))) - -// Mark a type as holding a pointer to a GC thing (eg JS::Value has this -// annotation.) -# define JS_HAZ_GC_POINTER __attribute__((tag("GC Pointer"))) - -// Mark a type as a rooted pointer, suitable for use on the stack (eg all -// Rooted instantiations should have this.) -# define JS_HAZ_ROOTED __attribute__((tag("Rooted Pointer"))) - -// Mark a type as something that should not be held live across a GC, but which -// is not itself a GC pointer. -# define JS_HAZ_GC_INVALIDATED __attribute__((tag("Invalidated by GC"))) - -// Mark a type that would otherwise be considered a GC Pointer (eg because it -// contains a JS::Value field) as a non-GC pointer. It is handled almost the -// same in the analysis as a rooted pointer, except it will not be reported as -// an unnecessary root if used across a GC call. This should rarely be used, -// but makes sense for something like ErrorResult, which only contains a GC -// pointer when it holds an exception (and it does its own rooting, -// conditionally.) -# define JS_HAZ_NON_GC_POINTER __attribute__((tag("Suppressed GC Pointer"))) - -// Mark a function as something that runs a garbage collection, potentially -// invalidating GC pointers. -# define JS_HAZ_GC_CALL __attribute__((tag("GC Call"))) - -// Mark an RAII class as suppressing GC within its scope. -# define JS_HAZ_GC_SUPPRESSED __attribute__((tag("Suppress GC"))) - -#else - -# define JS_HAZ_GC_THING -# define JS_HAZ_GC_POINTER -# define JS_HAZ_ROOTED -# define JS_HAZ_GC_INVALIDATED -# define JS_HAZ_NON_GC_POINTER -# define JS_HAZ_GC_CALL -# define JS_HAZ_GC_SUPPRESSED - -#endif - -#endif /* js_GCAnnotations_h */ diff --git a/mac/include/spidermonkey/js/GCHashTable.h b/mac/include/spidermonkey/js/GCHashTable.h deleted file mode 100644 index d6c2ce75..00000000 --- a/mac/include/spidermonkey/js/GCHashTable.h +++ /dev/null @@ -1,399 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef GCHashTable_h -#define GCHashTable_h - -#include "js/GCPolicyAPI.h" -#include "js/HashTable.h" -#include "js/RootingAPI.h" -#include "js/SweepingAPI.h" -#include "js/TracingAPI.h" - -namespace JS { - -// Define a reasonable default GC policy for GC-aware Maps. -template -struct DefaultMapSweepPolicy { - static bool needsSweep(Key* key, Value* value) { - return GCPolicy::needsSweep(key) || GCPolicy::needsSweep(value); - } -}; - -// A GCHashMap is a GC-aware HashMap, meaning that it has additional trace and -// sweep methods that know how to visit all keys and values in the table. -// HashMaps that contain GC pointers will generally want to use this GCHashMap -// specialization instead of HashMap, because this conveniently supports tracing -// keys and values, and cleaning up weak entries. -// -// GCHashMap::trace applies GCPolicy::trace to each entry's key and value. -// Most types of GC pointers already have appropriate specializations of -// GCPolicy, so they should just work as keys and values. Any struct type with a -// default constructor and trace and sweep functions should work as well. If you -// need to define your own GCPolicy specialization, generic helpers can be found -// in js/public/TracingAPI.h. -// -// The MapSweepPolicy template parameter controls how the table drops entries -// when swept. GCHashMap::sweep applies MapSweepPolicy::needsSweep to each table -// entry; if it returns true, the entry is dropped. The default MapSweepPolicy -// drops the entry if either the key or value is about to be finalized, -// according to its GCPolicy::needsSweep method. (This default is almost -// always fine: it's hard to imagine keeping such an entry around anyway.) -// -// Note that this HashMap only knows *how* to trace and sweep, but it does not -// itself cause tracing or sweeping to be invoked. For tracing, it must be used -// with Rooted or PersistentRooted, or barriered and traced manually. For -// sweeping, currently it requires an explicit call to .sweep(). -template , - typename AllocPolicy = js::TempAllocPolicy, - typename MapSweepPolicy = DefaultMapSweepPolicy> -class GCHashMap : public js::HashMap -{ - using Base = js::HashMap; - - public: - explicit GCHashMap(AllocPolicy a = AllocPolicy()) : Base(a) {} - - static void trace(GCHashMap* map, JSTracer* trc) { map->trace(trc); } - void trace(JSTracer* trc) { - if (!this->initialized()) - return; - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - GCPolicy::trace(trc, &e.front().value(), "hashmap value"); - GCPolicy::trace(trc, &e.front().mutableKey(), "hashmap key"); - } - } - - void sweep() { - if (!this->initialized()) - return; - - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - if (MapSweepPolicy::needsSweep(&e.front().mutableKey(), &e.front().value())) - e.removeFront(); - } - } - - // GCHashMap is movable - GCHashMap(GCHashMap&& rhs) : Base(mozilla::Move(rhs)) {} - void operator=(GCHashMap&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - Base::operator=(mozilla::Move(rhs)); - } - - private: - // GCHashMap is not copyable or assignable - GCHashMap(const GCHashMap& hm) = delete; - GCHashMap& operator=(const GCHashMap& hm) = delete; -}; - -} // namespace JS - -namespace js { - -// HashMap that supports rekeying. -// -// If your keys are pointers to something like JSObject that can be tenured or -// compacted, prefer to use GCHashMap with MovableCellHasher, which takes -// advantage of the Zone's stable id table to make rekeying unnecessary. -template , - typename AllocPolicy = TempAllocPolicy, - typename MapSweepPolicy = JS::DefaultMapSweepPolicy> -class GCRekeyableHashMap : public JS::GCHashMap -{ - using Base = JS::GCHashMap; - - public: - explicit GCRekeyableHashMap(AllocPolicy a = AllocPolicy()) : Base(a) {} - - void sweep() { - if (!this->initialized()) - return; - - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - Key key(e.front().key()); - if (MapSweepPolicy::needsSweep(&key, &e.front().value())) - e.removeFront(); - else if (!HashPolicy::match(key, e.front().key())) - e.rekeyFront(key); - } - } - - // GCRekeyableHashMap is movable - GCRekeyableHashMap(GCRekeyableHashMap&& rhs) : Base(mozilla::Move(rhs)) {} - void operator=(GCRekeyableHashMap&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - Base::operator=(mozilla::Move(rhs)); - } -}; - -template -class GCHashMapOperations -{ - using Map = JS::GCHashMap; - using Lookup = typename Map::Lookup; - - const Map& map() const { return static_cast(this)->get(); } - - public: - using AddPtr = typename Map::AddPtr; - using Ptr = typename Map::Ptr; - using Range = typename Map::Range; - - bool initialized() const { return map().initialized(); } - Ptr lookup(const Lookup& l) const { return map().lookup(l); } - AddPtr lookupForAdd(const Lookup& l) const { return map().lookupForAdd(l); } - Range all() const { return map().all(); } - bool empty() const { return map().empty(); } - uint32_t count() const { return map().count(); } - size_t capacity() const { return map().capacity(); } - bool has(const Lookup& l) const { return map().lookup(l).found(); } - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return map().sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + map().sizeOfExcludingThis(mallocSizeOf); - } -}; - -template -class MutableGCHashMapOperations - : public GCHashMapOperations -{ - using Map = JS::GCHashMap; - using Lookup = typename Map::Lookup; - - Map& map() { return static_cast(this)->get(); } - - public: - using AddPtr = typename Map::AddPtr; - struct Enum : public Map::Enum { explicit Enum(Outer& o) : Map::Enum(o.map()) {} }; - using Ptr = typename Map::Ptr; - using Range = typename Map::Range; - - bool init(uint32_t len = 16) { return map().init(len); } - void clear() { map().clear(); } - void finish() { map().finish(); } - void remove(Ptr p) { map().remove(p); } - - template - bool add(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return map().add(p, mozilla::Forward(k), mozilla::Forward(v)); - } - - template - bool add(AddPtr& p, KeyInput&& k) { - return map().add(p, mozilla::Forward(k), Map::Value()); - } - - template - bool relookupOrAdd(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return map().relookupOrAdd(p, k, - mozilla::Forward(k), - mozilla::Forward(v)); - } - - template - bool put(KeyInput&& k, ValueInput&& v) { - return map().put(mozilla::Forward(k), mozilla::Forward(v)); - } - - template - bool putNew(KeyInput&& k, ValueInput&& v) { - return map().putNew(mozilla::Forward(k), mozilla::Forward(v)); - } -}; - -template -class RootedBase> - : public MutableGCHashMapOperations>, A,B,C,D,E> -{}; - -template -class MutableHandleBase> - : public MutableGCHashMapOperations>, A,B,C,D,E> -{}; - -template -class HandleBase> - : public GCHashMapOperations>, A,B,C,D,E> -{}; - -template -class WeakCacheBase> - : public MutableGCHashMapOperations>, A,B,C,D,E> -{}; - -} // namespace js - -namespace JS { - -// A GCHashSet is a HashSet with an additional trace method that knows -// be traced to be kept alive will generally want to use this GCHashSet -// specialization in lieu of HashSet. -// -// Most types of GC pointers can be traced with no extra infrastructure. For -// structs and non-gc-pointer members, ensure that there is a specialization of -// GCPolicy with an appropriate trace method available to handle the custom -// type. Generic helpers can be found in js/public/TracingAPI.h. -// -// Note that although this HashSet's trace will deal correctly with moved -// elements, it does not itself know when to barrier or trace elements. To -// function properly it must either be used with Rooted or barriered and traced -// manually. -template , - typename AllocPolicy = js::TempAllocPolicy> -class GCHashSet : public js::HashSet -{ - using Base = js::HashSet; - - public: - explicit GCHashSet(AllocPolicy a = AllocPolicy()) : Base(a) {} - - static void trace(GCHashSet* set, JSTracer* trc) { set->trace(trc); } - void trace(JSTracer* trc) { - if (!this->initialized()) - return; - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) - GCPolicy::trace(trc, &e.mutableFront(), "hashset element"); - } - - void sweep() { - if (!this->initialized()) - return; - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - if (GCPolicy::needsSweep(&e.mutableFront())) - e.removeFront(); - } - } - - // GCHashSet is movable - GCHashSet(GCHashSet&& rhs) : Base(mozilla::Move(rhs)) {} - void operator=(GCHashSet&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - Base::operator=(mozilla::Move(rhs)); - } - - private: - // GCHashSet is not copyable or assignable - GCHashSet(const GCHashSet& hs) = delete; - GCHashSet& operator=(const GCHashSet& hs) = delete; -}; - -} // namespace JS - -namespace js { - -template -class GCHashSetOperations -{ - using Set = JS::GCHashSet; - using Lookup = typename Set::Lookup; - - const Set& set() const { return static_cast(this)->get(); } - - public: - using AddPtr = typename Set::AddPtr; - using Entry = typename Set::Entry; - using Ptr = typename Set::Ptr; - using Range = typename Set::Range; - - bool initialized() const { return set().initialized(); } - Ptr lookup(const Lookup& l) const { return set().lookup(l); } - AddPtr lookupForAdd(const Lookup& l) const { return set().lookupForAdd(l); } - Range all() const { return set().all(); } - bool empty() const { return set().empty(); } - uint32_t count() const { return set().count(); } - size_t capacity() const { return set().capacity(); } - bool has(const Lookup& l) const { return set().lookup(l).found(); } - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return set().sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + set().sizeOfExcludingThis(mallocSizeOf); - } -}; - -template -class MutableGCHashSetOperations - : public GCHashSetOperations -{ - using Set = JS::GCHashSet; - using Lookup = typename Set::Lookup; - - Set& set() { return static_cast(this)->get(); } - - public: - using AddPtr = typename Set::AddPtr; - using Entry = typename Set::Entry; - struct Enum : public Set::Enum { explicit Enum(Outer& o) : Set::Enum(o.set()) {} }; - using Ptr = typename Set::Ptr; - using Range = typename Set::Range; - - bool init(uint32_t len = 16) { return set().init(len); } - void clear() { set().clear(); } - void finish() { set().finish(); } - void remove(Ptr p) { set().remove(p); } - void remove(const Lookup& l) { set().remove(l); } - - template - bool add(AddPtr& p, TInput&& t) { - return set().add(p, mozilla::Forward(t)); - } - - template - bool relookupOrAdd(AddPtr& p, const Lookup& l, TInput&& t) { - return set().relookupOrAdd(p, l, mozilla::Forward(t)); - } - - template - bool put(TInput&& t) { - return set().put(mozilla::Forward(t)); - } - - template - bool putNew(TInput&& t) { - return set().putNew(mozilla::Forward(t)); - } - - template - bool putNew(const Lookup& l, TInput&& t) { - return set().putNew(l, mozilla::Forward(t)); - } -}; - -template -class RootedBase> - : public MutableGCHashSetOperations>, T, HP, AP> -{ -}; - -template -class MutableHandleBase> - : public MutableGCHashSetOperations>, T, HP, AP> -{ -}; - -template -class HandleBase> - : public GCHashSetOperations>, T, HP, AP> -{ -}; - -template -class WeakCacheBase> - : public MutableGCHashSetOperations>, T, HP, AP> -{ -}; - -} /* namespace js */ - -#endif /* GCHashTable_h */ diff --git a/mac/include/spidermonkey/js/GCPolicyAPI.h b/mac/include/spidermonkey/js/GCPolicyAPI.h deleted file mode 100644 index 054e397a..00000000 --- a/mac/include/spidermonkey/js/GCPolicyAPI.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// GC Policy Mechanism - -// A GCPolicy controls how the GC interacts with both direct pointers to GC -// things (e.g. JSObject* or JSString*), tagged and/or optional pointers to GC -// things (e.g. Value or jsid), and C++ container types (e.g. -// JSPropertyDescriptor or GCHashMap). -// -// The GCPolicy provides at a minimum: -// -// static T initial() -// - Construct and return an empty T. -// -// static void trace(JSTracer, T* tp, const char* name) -// - Trace the edge |*tp|, calling the edge |name|. Containers like -// GCHashMap and GCHashSet use this method to trace their children. -// -// static bool needsSweep(T* tp) -// - Return true if |*tp| is about to be finalized. Otherwise, update the -// edge for moving GC, and return false. Containers like GCHashMap and -// GCHashSet use this method to decide when to remove an entry: if this -// function returns true on a key/value/member/etc, its entry is dropped -// from the container. Specializing this method is the standard way to -// get custom weak behavior from a container type. -// -// The default GCPolicy assumes that T has a default constructor and |trace| -// and |needsSweep| methods, and forwards to them. GCPolicy has appropriate -// specializations for pointers to GC things and pointer-like types like -// JS::Heap and mozilla::UniquePtr. -// -// There are some stock structs your specializations can inherit from. -// IgnoreGCPolicy does nothing. StructGCPolicy forwards the methods to the -// referent type T. - -#ifndef GCPolicyAPI_h -#define GCPolicyAPI_h - -#include "mozilla/UniquePtr.h" - -#include "js/TraceKind.h" -#include "js/TracingAPI.h" - -// Expand the given macro D for each public GC pointer. -#define FOR_EACH_PUBLIC_GC_POINTER_TYPE(D) \ - D(JS::Symbol*) \ - D(JSAtom*) \ - D(JSFunction*) \ - D(JSObject*) \ - D(JSScript*) \ - D(JSString*) - -// Expand the given macro D for each public tagged GC pointer type. -#define FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(D) \ - D(JS::Value) \ - D(jsid) - -#define FOR_EACH_PUBLIC_AGGREGATE_GC_POINTER_TYPE(D) \ - D(JSPropertyDescriptor) - -class JSAtom; -class JSFunction; -class JSObject; -class JSScript; -class JSString; -namespace JS { -class Symbol; -} - -namespace JS { - -// Defines a policy for container types with non-GC, i.e. C storage. This -// policy dispatches to the underlying struct for GC interactions. -template -struct StructGCPolicy -{ - static T initial() { - return T(); - } - - static void trace(JSTracer* trc, T* tp, const char* name) { - tp->trace(trc); - } - - static void sweep(T* tp) { - return tp->sweep(); - } - - static bool needsSweep(T* tp) { - return tp->needsSweep(); - } -}; - -// The default GC policy attempts to defer to methods on the underlying type. -// Most C++ structures that contain a default constructor, a trace function and -// a sweep function will work out of the box with Rooted, Handle, GCVector, -// and GCHash{Set,Map}. -template struct GCPolicy : public StructGCPolicy {}; - -// This policy ignores any GC interaction, e.g. for non-GC types. -template -struct IgnoreGCPolicy { - static T initial() { return T(); } - static void trace(JSTracer* trc, T* t, const char* name) {} - static bool needsSweep(T* v) { return false; } -}; -template <> struct GCPolicy : public IgnoreGCPolicy {}; -template <> struct GCPolicy : public IgnoreGCPolicy {}; - -template -struct GCPointerPolicy -{ - static T initial() { return nullptr; } - static void trace(JSTracer* trc, T* vp, const char* name) { - if (*vp) - js::UnsafeTraceManuallyBarrieredEdge(trc, vp, name); - } - static bool needsSweep(T* vp) { - if (*vp) - return js::gc::IsAboutToBeFinalizedUnbarriered(vp); - return false; - } -}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; - -template -struct GCPolicy> -{ - static void trace(JSTracer* trc, JS::Heap* thingp, const char* name) { - TraceEdge(trc, thingp, name); - } - static bool needsSweep(JS::Heap* thingp) { - return js::gc::EdgeNeedsSweep(thingp); - } -}; - -// GCPolicy> forwards the contained pointer to GCPolicy. -template -struct GCPolicy> -{ - static mozilla::UniquePtr initial() { return mozilla::UniquePtr(); } - static void trace(JSTracer* trc, mozilla::UniquePtr* tp, const char* name) { - if (tp->get()) - GCPolicy::trace(trc, tp->get(), name); - } - static bool needsSweep(mozilla::UniquePtr* tp) { - if (tp->get()) - return GCPolicy::needsSweep(tp->get()); - return false; - } -}; - -} // namespace JS - -#endif // GCPolicyAPI_h diff --git a/mac/include/spidermonkey/js/GCVariant.h b/mac/include/spidermonkey/js/GCVariant.h deleted file mode 100644 index 31ab23f5..00000000 --- a/mac/include/spidermonkey/js/GCVariant.h +++ /dev/null @@ -1,198 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCVariant_h -#define js_GCVariant_h - -#include "mozilla/Variant.h" - -#include "js/GCPolicyAPI.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" - -namespace JS { - -// These template specializations allow Variant to be used inside GC wrappers. -// -// When matching on GC wrappers around Variants, matching should be done on -// the wrapper itself. The matcher class's methods should take Handles or -// MutableHandles. For example, -// -// struct MyMatcher -// { -// using ReturnType = const char*; -// ReturnType match(HandleObject o) { return "object"; } -// ReturnType match(HandleScript s) { return "script"; } -// }; -// -// Rooted> v(cx, someScript); -// MyMatcher mm; -// v.match(mm); -// -// If you get compile errors about inability to upcast subclasses (e.g., from -// NativeObject* to JSObject*) and are inside js/src, be sure to also include -// "gc/Policy.h". - -namespace detail { - -template -struct GCVariantImplementation; - -// The base case. -template -struct GCVariantImplementation -{ - template - static void trace(JSTracer* trc, ConcreteVariant* v, const char* name) { - T& thing = v->template as(); - if (!mozilla::IsPointer::value || thing) - GCPolicy::trace(trc, &thing, name); - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, Handle v) { - const T& thing = v.get().template as(); - return matcher.match(Handle::fromMarkedLocation(&thing)); - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, MutableHandle v) { - T& thing = v.get().template as(); - return matcher.match(MutableHandle::fromMarkedLocation(&thing)); - } -}; - -// The inductive case. -template -struct GCVariantImplementation -{ - using Next = GCVariantImplementation; - - template - static void trace(JSTracer* trc, ConcreteVariant* v, const char* name) { - if (v->template is()) { - T& thing = v->template as(); - if (!mozilla::IsPointer::value || thing) - GCPolicy::trace(trc, &thing, name); - } else { - Next::trace(trc, v, name); - } - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, Handle v) { - if (v.get().template is()) { - const T& thing = v.get().template as(); - return matcher.match(Handle::fromMarkedLocation(&thing)); - } - return Next::match(matcher, v); - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, MutableHandle v) { - if (v.get().template is()) { - T& thing = v.get().template as(); - return matcher.match(MutableHandle::fromMarkedLocation(&thing)); - } - return Next::match(matcher, v); - } -}; - -} // namespace detail - -template -struct GCPolicy> -{ - using Impl = detail::GCVariantImplementation; - - // Variants do not provide initial(). They do not have a default initial - // value and one must be provided. - - static void trace(JSTracer* trc, mozilla::Variant* v, const char* name) { - Impl::trace(trc, v, name); - } -}; - -} // namespace JS - -namespace js { - -template -class GCVariantOperations -{ - using Impl = JS::detail::GCVariantImplementation; - using Variant = mozilla::Variant; - - const Variant& variant() const { return static_cast(this)->get(); } - - public: - template - bool is() const { - return variant().template is(); - } - - template - JS::Handle as() const { - return Handle::fromMarkedLocation(&variant().template as()); - } - - template - typename Matcher::ReturnType - match(Matcher& matcher) const { - return Impl::match(matcher, JS::Handle::fromMarkedLocation(&variant())); - } -}; - -template -class MutableGCVariantOperations - : public GCVariantOperations -{ - using Impl = JS::detail::GCVariantImplementation; - using Variant = mozilla::Variant; - - const Variant& variant() const { return static_cast(this)->get(); } - Variant& variant() { return static_cast(this)->get(); } - - public: - template - JS::MutableHandle as() { - return JS::MutableHandle::fromMarkedLocation(&variant().template as()); - } - - template - typename Matcher::ReturnType - match(Matcher& matcher) { - return Impl::match(matcher, JS::MutableHandle::fromMarkedLocation(&variant())); - } -}; - -template -class RootedBase> - : public MutableGCVariantOperations>, Ts...> -{ }; - -template -class MutableHandleBase> - : public MutableGCVariantOperations>, Ts...> -{ }; - -template -class HandleBase> - : public GCVariantOperations>, Ts...> -{ }; - -template -class PersistentRootedBase> - : public MutableGCVariantOperations>, Ts...> -{ }; - -} // namespace js - -#endif // js_GCVariant_h diff --git a/mac/include/spidermonkey/js/GCVector.h b/mac/include/spidermonkey/js/GCVector.h deleted file mode 100644 index 2668e65b..00000000 --- a/mac/include/spidermonkey/js/GCVector.h +++ /dev/null @@ -1,249 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCVector_h -#define js_GCVector_h - -#include "mozilla/Vector.h" - -#include "js/GCPolicyAPI.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" -#include "js/Vector.h" - -namespace JS { - -// A GCVector is a Vector with an additional trace method that knows how -// to visit all of the items stored in the Vector. For vectors that contain GC -// things, this is usually more convenient than manually iterating and marking -// the contents. -// -// Most types of GC pointers as keys and values can be traced with no extra -// infrastructure. For structs and non-gc-pointer members, ensure that there is -// a specialization of GCPolicy with an appropriate trace method available -// to handle the custom type. Generic helpers can be found in -// js/public/TracingAPI.h. -// -// Note that although this Vector's trace will deal correctly with moved items, -// it does not itself know when to barrier or trace items. To function properly -// it must either be used with Rooted, or barriered and traced manually. -template -class GCVector -{ - mozilla::Vector vector; - - public: - explicit GCVector(AllocPolicy alloc = AllocPolicy()) - : vector(alloc) - {} - - GCVector(GCVector&& vec) - : vector(mozilla::Move(vec.vector)) - {} - - GCVector& operator=(GCVector&& vec) { - vector = mozilla::Move(vec.vector); - return *this; - } - - size_t length() const { return vector.length(); } - bool empty() const { return vector.empty(); } - size_t capacity() const { return vector.capacity(); } - - T* begin() { return vector.begin(); } - const T* begin() const { return vector.begin(); } - - T* end() { return vector.end(); } - const T* end() const { return vector.end(); } - - T& operator[](size_t i) { return vector[i]; } - const T& operator[](size_t i) const { return vector[i]; } - - T& back() { return vector.back(); } - const T& back() const { return vector.back(); } - - bool initCapacity(size_t cap) { return vector.initCapacity(cap); } - bool reserve(size_t req) { return vector.reserve(req); } - void shrinkBy(size_t amount) { return vector.shrinkBy(amount); } - bool growBy(size_t amount) { return vector.growBy(amount); } - bool resize(size_t newLen) { return vector.resize(newLen); } - - void clear() { return vector.clear(); } - - template bool append(U&& item) { return vector.append(mozilla::Forward(item)); } - - template - bool - emplaceBack(Args&&... args) { - return vector.emplaceBack(mozilla::Forward(args)...); - } - - template - void infallibleAppend(U&& aU) { - return vector.infallibleAppend(mozilla::Forward(aU)); - } - void infallibleAppendN(const T& aT, size_t aN) { - return vector.infallibleAppendN(aT, aN); - } - template void - infallibleAppend(const U* aBegin, const U* aEnd) { - return vector.infallibleAppend(aBegin, aEnd); - } - template void infallibleAppend(const U* aBegin, size_t aLength) { - return vector.infallibleAppend(aBegin, aLength); - } - - template - bool appendAll(const mozilla::Vector& aU) { return vector.appendAll(aU); } - template - bool appendAll(const GCVector& aU) { return vector.append(aU.begin(), aU.length()); } - - bool appendN(const T& val, size_t count) { return vector.appendN(val, count); } - - template bool append(const U* aBegin, const U* aEnd) { - return vector.append(aBegin, aEnd); - } - template bool append(const U* aBegin, size_t aLength) { - return vector.append(aBegin, aLength); - } - - void popBack() { return vector.popBack(); } - T popCopy() { return vector.popCopy(); } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return vector.sizeOfExcludingThis(mallocSizeOf); - } - - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return vector.sizeOfIncludingThis(mallocSizeOf); - } - - static void trace(GCVector* vec, JSTracer* trc) { vec->trace(trc); } - - void trace(JSTracer* trc) { - for (auto& elem : vector) - GCPolicy::trace(trc, &elem, "vector element"); - } -}; - -} // namespace JS - -namespace js { - -template -class GCVectorOperations -{ - using Vec = JS::GCVector; - const Vec& vec() const { return static_cast(this)->get(); } - - public: - const AllocPolicy& allocPolicy() const { return vec().allocPolicy(); } - size_t length() const { return vec().length(); } - bool empty() const { return vec().empty(); } - size_t capacity() const { return vec().capacity(); } - const T* begin() const { return vec().begin(); } - const T* end() const { return vec().end(); } - const T& back() const { return vec().back(); } - - JS::Handle operator[](size_t aIndex) const { - return JS::Handle::fromMarkedLocation(&vec().operator[](aIndex)); - } -}; - -template -class MutableGCVectorOperations - : public GCVectorOperations -{ - using Vec = JS::GCVector; - const Vec& vec() const { return static_cast(this)->get(); } - Vec& vec() { return static_cast(this)->get(); } - - public: - const AllocPolicy& allocPolicy() const { return vec().allocPolicy(); } - AllocPolicy& allocPolicy() { return vec().allocPolicy(); } - const T* begin() const { return vec().begin(); } - T* begin() { return vec().begin(); } - const T* end() const { return vec().end(); } - T* end() { return vec().end(); } - const T& back() const { return vec().back(); } - T& back() { return vec().back(); } - - JS::Handle operator[](size_t aIndex) const { - return JS::Handle::fromMarkedLocation(&vec().operator[](aIndex)); - } - JS::MutableHandle operator[](size_t aIndex) { - return JS::MutableHandle::fromMarkedLocation(&vec().operator[](aIndex)); - } - - bool initCapacity(size_t aRequest) { return vec().initCapacity(aRequest); } - bool reserve(size_t aRequest) { return vec().reserve(aRequest); } - void shrinkBy(size_t aIncr) { vec().shrinkBy(aIncr); } - bool growBy(size_t aIncr) { return vec().growBy(aIncr); } - bool resize(size_t aNewLength) { return vec().resize(aNewLength); } - bool growByUninitialized(size_t aIncr) { return vec().growByUninitialized(aIncr); } - void infallibleGrowByUninitialized(size_t aIncr) { vec().infallibleGrowByUninitialized(aIncr); } - bool resizeUninitialized(size_t aNewLength) { return vec().resizeUninitialized(aNewLength); } - void clear() { vec().clear(); } - void clearAndFree() { vec().clearAndFree(); } - template bool append(U&& aU) { return vec().append(mozilla::Forward(aU)); } - template bool emplaceBack(Args&&... aArgs) { - return vec().emplaceBack(mozilla::Forward(aArgs...)); - } - template - bool appendAll(const mozilla::Vector& aU) { return vec().appendAll(aU); } - template - bool appendAll(const JS::GCVector& aU) { return vec().appendAll(aU); } - bool appendN(const T& aT, size_t aN) { return vec().appendN(aT, aN); } - template bool append(const U* aBegin, const U* aEnd) { - return vec().append(aBegin, aEnd); - } - template bool append(const U* aBegin, size_t aLength) { - return vec().append(aBegin, aLength); - } - template void infallibleAppend(U&& aU) { - vec().infallibleAppend(mozilla::Forward(aU)); - } - void infallibleAppendN(const T& aT, size_t aN) { vec().infallibleAppendN(aT, aN); } - template void infallibleAppend(const U* aBegin, const U* aEnd) { - vec().infallibleAppend(aBegin, aEnd); - } - template void infallibleAppend(const U* aBegin, size_t aLength) { - vec().infallibleAppend(aBegin, aLength); - } - void popBack() { vec().popBack(); } - T popCopy() { return vec().popCopy(); } - template T* insert(T* aP, U&& aVal) { - return vec().insert(aP, mozilla::Forward(aVal)); - } - void erase(T* aT) { vec().erase(aT); } - void erase(T* aBegin, T* aEnd) { vec().erase(aBegin, aEnd); } -}; - -template -class RootedBase> - : public MutableGCVectorOperations>, T,N,AP> -{}; - -template -class MutableHandleBase> - : public MutableGCVectorOperations>, T,N,AP> -{}; - -template -class HandleBase> - : public GCVectorOperations>, T,N,AP> -{}; - -template -class PersistentRootedBase> - : public MutableGCVectorOperations>, T,N,AP> -{}; - -} // namespace js - -#endif // js_GCVector_h diff --git a/mac/include/spidermonkey/js/HashTable.h b/mac/include/spidermonkey/js/HashTable.h deleted file mode 100644 index 5d4c0665..00000000 --- a/mac/include/spidermonkey/js/HashTable.h +++ /dev/null @@ -1,1880 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_HashTable_h -#define js_HashTable_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/HashFunctions.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/Opaque.h" -#include "mozilla/PodOperations.h" -#include "mozilla/ReentrancyGuard.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/UniquePtr.h" - -#include "js/Utility.h" - -namespace js { - -class TempAllocPolicy; -template struct DefaultHasher; -template class HashMapEntry; -namespace detail { - template class HashTableEntry; - template class HashTable; -} // namespace detail - -/*****************************************************************************/ - -// The "generation" of a hash table is an opaque value indicating the state of -// modification of the hash table through its lifetime. If the generation of -// a hash table compares equal at times T1 and T2, then lookups in the hash -// table, pointers to (or into) hash table entries, etc. at time T1 are valid -// at time T2. If the generation compares unequal, these computations are all -// invalid and must be performed again to be used. -// -// Generations are meaningfully comparable only with respect to a single hash -// table. It's always nonsensical to compare the generation of distinct hash -// tables H1 and H2. -using Generation = mozilla::Opaque; - -// A JS-friendly, STL-like container providing a hash-based map from keys to -// values. In particular, HashMap calls constructors and destructors of all -// objects added so non-PODs may be used safely. -// -// Key/Value requirements: -// - movable, destructible, assignable -// HashPolicy requirements: -// - see Hash Policy section below -// AllocPolicy: -// - see jsalloc.h -// -// Note: -// - HashMap is not reentrant: Key/Value/HashPolicy/AllocPolicy members -// called by HashMap must not call back into the same HashMap object. -// - Due to the lack of exception handling, the user must call |init()|. -template , - class AllocPolicy = TempAllocPolicy> -class HashMap -{ - typedef HashMapEntry TableEntry; - - struct MapHashPolicy : HashPolicy - { - using Base = HashPolicy; - typedef Key KeyType; - static const Key& getKey(TableEntry& e) { return e.key(); } - static void setKey(TableEntry& e, Key& k) { HashPolicy::rekey(e.mutableKey(), k); } - }; - - typedef detail::HashTable Impl; - Impl impl; - - public: - typedef typename HashPolicy::Lookup Lookup; - typedef TableEntry Entry; - - // HashMap construction is fallible (due to OOM); thus the user must call - // init after constructing a HashMap and check the return value. - explicit HashMap(AllocPolicy a = AllocPolicy()) : impl(a) {} - MOZ_MUST_USE bool init(uint32_t len = 16) { return impl.init(len); } - bool initialized() const { return impl.initialized(); } - - // Return whether the given lookup value is present in the map. E.g.: - // - // typedef HashMap HM; - // HM h; - // if (HM::Ptr p = h.lookup(3)) { - // const HM::Entry& e = *p; // p acts like a pointer to Entry - // assert(p->key == 3); // Entry contains the key - // char val = p->value; // and value - // } - // - // Also see the definition of Ptr in HashTable above (with T = Entry). - typedef typename Impl::Ptr Ptr; - Ptr lookup(const Lookup& l) const { return impl.lookup(l); } - - // Like lookup, but does not assert if two threads call lookup at the same - // time. Only use this method when none of the threads will modify the map. - Ptr readonlyThreadsafeLookup(const Lookup& l) const { return impl.readonlyThreadsafeLookup(l); } - - // Assuming |p.found()|, remove |*p|. - void remove(Ptr p) { impl.remove(p); } - - // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient - // insertion of Key |k| (where |HashPolicy::match(k,l) == true|) using - // |add(p,k,v)|. After |add(p,k,v)|, |p| points to the new Entry. E.g.: - // - // typedef HashMap HM; - // HM h; - // HM::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // if (!h.add(p, 3, 'a')) - // return false; - // } - // const HM::Entry& e = *p; // p acts like a pointer to Entry - // assert(p->key == 3); // Entry contains the key - // char val = p->value; // and value - // - // Also see the definition of AddPtr in HashTable above (with T = Entry). - // - // N.B. The caller must ensure that no mutating hash table operations - // occur between a pair of |lookupForAdd| and |add| calls. To avoid - // looking up the key a second time, the caller may use the more efficient - // relookupOrAdd method. This method reuses part of the hashing computation - // to more efficiently insert the key if it has not been added. For - // example, a mutation-handling version of the previous example: - // - // HM::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // call_that_may_mutate_h(); - // if (!h.relookupOrAdd(p, 3, 'a')) - // return false; - // } - // const HM::Entry& e = *p; - // assert(p->key == 3); - // char val = p->value; - typedef typename Impl::AddPtr AddPtr; - AddPtr lookupForAdd(const Lookup& l) const { - return impl.lookupForAdd(l); - } - - template - MOZ_MUST_USE bool add(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return impl.add(p, - mozilla::Forward(k), - mozilla::Forward(v)); - } - - template - MOZ_MUST_USE bool add(AddPtr& p, KeyInput&& k) { - return impl.add(p, mozilla::Forward(k), Value()); - } - - template - MOZ_MUST_USE bool relookupOrAdd(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return impl.relookupOrAdd(p, k, - mozilla::Forward(k), - mozilla::Forward(v)); - } - - // |all()| returns a Range containing |count()| elements. E.g.: - // - // typedef HashMap HM; - // HM h; - // for (HM::Range r = h.all(); !r.empty(); r.popFront()) - // char c = r.front().value(); - // - // Also see the definition of Range in HashTable above (with T = Entry). - typedef typename Impl::Range Range; - Range all() const { return impl.all(); } - - // Typedef for the enumeration class. An Enum may be used to examine and - // remove table entries: - // - // typedef HashMap HM; - // HM s; - // for (HM::Enum e(s); !e.empty(); e.popFront()) - // if (e.front().value() == 'l') - // e.removeFront(); - // - // Table resize may occur in Enum's destructor. Also see the definition of - // Enum in HashTable above (with T = Entry). - typedef typename Impl::Enum Enum; - - // Remove all entries. This does not shrink the table. For that consider - // using the finish() method. - void clear() { impl.clear(); } - - // Remove all the entries and release all internal buffers. The map must - // be initialized again before any use. - void finish() { impl.finish(); } - - // Does the table contain any entries? - bool empty() const { return impl.empty(); } - - // Number of live elements in the map. - uint32_t count() const { return impl.count(); } - - // Total number of allocation in the dynamic table. Note: resize will - // happen well before count() == capacity(). - size_t capacity() const { return impl.capacity(); } - - // Don't just call |impl.sizeOfExcludingThis()| because there's no - // guarantee that |impl| is the first field in HashMap. - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return impl.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); - } - - Generation generation() const { - return impl.generation(); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return impl.lookup(l).found(); - } - - // Overwrite existing value with v. Return false on oom. - template - MOZ_MUST_USE bool put(KeyInput&& k, ValueInput&& v) { - AddPtr p = lookupForAdd(k); - if (p) { - p->value() = mozilla::Forward(v); - return true; - } - return add(p, mozilla::Forward(k), mozilla::Forward(v)); - } - - // Like put, but assert that the given key is not already present. - template - MOZ_MUST_USE bool putNew(KeyInput&& k, ValueInput&& v) { - return impl.putNew(k, mozilla::Forward(k), mozilla::Forward(v)); - } - - // Only call this to populate an empty map after reserving space with init(). - template - void putNewInfallible(KeyInput&& k, ValueInput&& v) { - impl.putNewInfallible(k, mozilla::Forward(k), mozilla::Forward(v)); - } - - // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. - Ptr lookupWithDefault(const Key& k, const Value& defaultValue) { - AddPtr p = lookupForAdd(k); - if (p) - return p; - bool ok = add(p, k, defaultValue); - MOZ_ASSERT_IF(!ok, !p); // p is left false-y on oom. - (void)ok; - return p; - } - - // Remove if present. - void remove(const Lookup& l) { - if (Ptr p = lookup(l)) - remove(p); - } - - // Infallibly rekey one entry, if necessary. - // Requires template parameters Key and HashPolicy::Lookup to be the same type. - void rekeyIfMoved(const Key& old_key, const Key& new_key) { - if (old_key != new_key) - rekeyAs(old_key, new_key, new_key); - } - - // Infallibly rekey one entry if present, and return whether that happened. - bool rekeyAs(const Lookup& old_lookup, const Lookup& new_lookup, const Key& new_key) { - if (Ptr p = lookup(old_lookup)) { - impl.rekeyAndMaybeRehash(p, new_lookup, new_key); - return true; - } - return false; - } - - // HashMap is movable - HashMap(HashMap&& rhs) : impl(mozilla::Move(rhs.impl)) {} - void operator=(HashMap&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - impl = mozilla::Move(rhs.impl); - } - - private: - // HashMap is not copyable or assignable - HashMap(const HashMap& hm) = delete; - HashMap& operator=(const HashMap& hm) = delete; - - friend class Impl::Enum; -}; - -/*****************************************************************************/ - -// A JS-friendly, STL-like container providing a hash-based set of values. In -// particular, HashSet calls constructors and destructors of all objects added -// so non-PODs may be used safely. -// -// T requirements: -// - movable, destructible, assignable -// HashPolicy requirements: -// - see Hash Policy section below -// AllocPolicy: -// - see jsalloc.h -// -// Note: -// - HashSet is not reentrant: T/HashPolicy/AllocPolicy members called by -// HashSet must not call back into the same HashSet object. -// - Due to the lack of exception handling, the user must call |init()|. -template , - class AllocPolicy = TempAllocPolicy> -class HashSet -{ - struct SetOps : HashPolicy - { - using Base = HashPolicy; - typedef T KeyType; - static const KeyType& getKey(const T& t) { return t; } - static void setKey(T& t, KeyType& k) { HashPolicy::rekey(t, k); } - }; - - typedef detail::HashTable Impl; - Impl impl; - - public: - typedef typename HashPolicy::Lookup Lookup; - typedef T Entry; - - // HashSet construction is fallible (due to OOM); thus the user must call - // init after constructing a HashSet and check the return value. - explicit HashSet(AllocPolicy a = AllocPolicy()) : impl(a) {} - MOZ_MUST_USE bool init(uint32_t len = 16) { return impl.init(len); } - bool initialized() const { return impl.initialized(); } - - // Return whether the given lookup value is present in the map. E.g.: - // - // typedef HashSet HS; - // HS h; - // if (HS::Ptr p = h.lookup(3)) { - // assert(*p == 3); // p acts like a pointer to int - // } - // - // Also see the definition of Ptr in HashTable above. - typedef typename Impl::Ptr Ptr; - Ptr lookup(const Lookup& l) const { return impl.lookup(l); } - - // Like lookup, but does not assert if two threads call lookup at the same - // time. Only use this method when none of the threads will modify the map. - Ptr readonlyThreadsafeLookup(const Lookup& l) const { return impl.readonlyThreadsafeLookup(l); } - - // Assuming |p.found()|, remove |*p|. - void remove(Ptr p) { impl.remove(p); } - - // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient - // insertion of T value |t| (where |HashPolicy::match(t,l) == true|) using - // |add(p,t)|. After |add(p,t)|, |p| points to the new element. E.g.: - // - // typedef HashSet HS; - // HS h; - // HS::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // if (!h.add(p, 3)) - // return false; - // } - // assert(*p == 3); // p acts like a pointer to int - // - // Also see the definition of AddPtr in HashTable above. - // - // N.B. The caller must ensure that no mutating hash table operations - // occur between a pair of |lookupForAdd| and |add| calls. To avoid - // looking up the key a second time, the caller may use the more efficient - // relookupOrAdd method. This method reuses part of the hashing computation - // to more efficiently insert the key if it has not been added. For - // example, a mutation-handling version of the previous example: - // - // HS::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // call_that_may_mutate_h(); - // if (!h.relookupOrAdd(p, 3, 3)) - // return false; - // } - // assert(*p == 3); - // - // Note that relookupOrAdd(p,l,t) performs Lookup using |l| and adds the - // entry |t|, where the caller ensures match(l,t). - typedef typename Impl::AddPtr AddPtr; - AddPtr lookupForAdd(const Lookup& l) const { return impl.lookupForAdd(l); } - - template - MOZ_MUST_USE bool add(AddPtr& p, U&& u) { - return impl.add(p, mozilla::Forward(u)); - } - - template - MOZ_MUST_USE bool relookupOrAdd(AddPtr& p, const Lookup& l, U&& u) { - return impl.relookupOrAdd(p, l, mozilla::Forward(u)); - } - - // |all()| returns a Range containing |count()| elements: - // - // typedef HashSet HS; - // HS h; - // for (HS::Range r = h.all(); !r.empty(); r.popFront()) - // int i = r.front(); - // - // Also see the definition of Range in HashTable above. - typedef typename Impl::Range Range; - Range all() const { return impl.all(); } - - // Typedef for the enumeration class. An Enum may be used to examine and - // remove table entries: - // - // typedef HashSet HS; - // HS s; - // for (HS::Enum e(s); !e.empty(); e.popFront()) - // if (e.front() == 42) - // e.removeFront(); - // - // Table resize may occur in Enum's destructor. Also see the definition of - // Enum in HashTable above. - typedef typename Impl::Enum Enum; - - // Remove all entries. This does not shrink the table. For that consider - // using the finish() method. - void clear() { impl.clear(); } - - // Remove all the entries and release all internal buffers. The set must - // be initialized again before any use. - void finish() { impl.finish(); } - - // Does the table contain any entries? - bool empty() const { return impl.empty(); } - - // Number of live elements in the map. - uint32_t count() const { return impl.count(); } - - // Total number of allocation in the dynamic table. Note: resize will - // happen well before count() == capacity(). - size_t capacity() const { return impl.capacity(); } - - // Don't just call |impl.sizeOfExcludingThis()| because there's no - // guarantee that |impl| is the first field in HashSet. - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return impl.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); - } - - Generation generation() const { - return impl.generation(); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return impl.lookup(l).found(); - } - - // Add |u| if it is not present already. Return false on oom. - template - MOZ_MUST_USE bool put(U&& u) { - AddPtr p = lookupForAdd(u); - return p ? true : add(p, mozilla::Forward(u)); - } - - // Like put, but assert that the given key is not already present. - template - MOZ_MUST_USE bool putNew(U&& u) { - return impl.putNew(u, mozilla::Forward(u)); - } - - template - MOZ_MUST_USE bool putNew(const Lookup& l, U&& u) { - return impl.putNew(l, mozilla::Forward(u)); - } - - // Only call this to populate an empty set after reserving space with init(). - template - void putNewInfallible(const Lookup& l, U&& u) { - impl.putNewInfallible(l, mozilla::Forward(u)); - } - - void remove(const Lookup& l) { - if (Ptr p = lookup(l)) - remove(p); - } - - // Infallibly rekey one entry, if present. - // Requires template parameters T and HashPolicy::Lookup to be the same type. - void rekeyIfMoved(const Lookup& old_value, const T& new_value) { - if (old_value != new_value) - rekeyAs(old_value, new_value, new_value); - } - - // Infallibly rekey one entry if present, and return whether that happened. - bool rekeyAs(const Lookup& old_lookup, const Lookup& new_lookup, const T& new_value) { - if (Ptr p = lookup(old_lookup)) { - impl.rekeyAndMaybeRehash(p, new_lookup, new_value); - return true; - } - return false; - } - - // Infallibly replace the current key at |p| with an equivalent key. - // Specifically, both HashPolicy::hash and HashPolicy::match must return - // identical results for the new and old key when applied against all - // possible matching values. - void replaceKey(Ptr p, const T& new_value) { - MOZ_ASSERT(p.found()); - MOZ_ASSERT(*p != new_value); - MOZ_ASSERT(HashPolicy::hash(*p) == HashPolicy::hash(new_value)); - MOZ_ASSERT(HashPolicy::match(*p, new_value)); - const_cast(*p) = new_value; - } - - // HashSet is movable - HashSet(HashSet&& rhs) : impl(mozilla::Move(rhs.impl)) {} - void operator=(HashSet&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - impl = mozilla::Move(rhs.impl); - } - - private: - // HashSet is not copyable or assignable - HashSet(const HashSet& hs) = delete; - HashSet& operator=(const HashSet& hs) = delete; - - friend class Impl::Enum; -}; - -/*****************************************************************************/ - -// Hash Policy -// -// A hash policy P for a hash table with key-type Key must provide: -// - a type |P::Lookup| to use to lookup table entries; -// - a static member function |P::hash| with signature -// -// static js::HashNumber hash(Lookup) -// -// to use to hash the lookup type; and -// - a static member function |P::match| with signature -// -// static bool match(Key, Lookup) -// -// to use to test equality of key and lookup values. -// -// Normally, Lookup = Key. In general, though, different values and types of -// values can be used to lookup and store. If a Lookup value |l| is != to the -// added Key value |k|, the user must ensure that |P::match(k,l)|. E.g.: -// -// js::HashSet::AddPtr p = h.lookup(l); -// if (!p) { -// assert(P::match(k, l)); // must hold -// h.add(p, k); -// } - -// Pointer hashing policy that strips the lowest zeroBits when calculating the -// hash to improve key distribution. -template -struct PointerHasher -{ - typedef Key Lookup; - static HashNumber hash(const Lookup& l) { - size_t word = reinterpret_cast(l) >> zeroBits; - static_assert(sizeof(HashNumber) == 4, - "subsequent code assumes a four-byte hash"); -#if JS_BITS_PER_WORD == 32 - return HashNumber(word); -#else - static_assert(sizeof(word) == 8, - "unexpected word size, new hashing strategy required to " - "properly incorporate all bits"); - return HashNumber((word >> 32) ^ word); -#endif - } - static bool match(const Key& k, const Lookup& l) { - return k == l; - } - static void rekey(Key& k, const Key& newKey) { - k = newKey; - } -}; - -// Default hash policy: just use the 'lookup' value. This of course only -// works if the lookup value is integral. HashTable applies ScrambleHashCode to -// the result of the 'hash' which means that it is 'ok' if the lookup value is -// not well distributed over the HashNumber domain. -template -struct DefaultHasher -{ - typedef Key Lookup; - static HashNumber hash(const Lookup& l) { - // Hash if can implicitly cast to hash number type. - return l; - } - static bool match(const Key& k, const Lookup& l) { - // Use builtin or overloaded operator==. - return k == l; - } - static void rekey(Key& k, const Key& newKey) { - k = newKey; - } -}; - -// Specialize hashing policy for pointer types. It assumes that the type is -// at least word-aligned. For types with smaller size use PointerHasher. -template -struct DefaultHasher : PointerHasher::value> -{}; - -// Specialize hashing policy for mozilla::UniquePtr to proxy the UniquePtr's -// raw pointer to PointerHasher. -template -struct DefaultHasher> -{ - using Lookup = mozilla::UniquePtr; - using PtrHasher = PointerHasher::value>; - - static HashNumber hash(const Lookup& l) { - return PtrHasher::hash(l.get()); - } - static bool match(const mozilla::UniquePtr& k, const Lookup& l) { - return PtrHasher::match(k.get(), l.get()); - } - static void rekey(mozilla::UniquePtr& k, mozilla::UniquePtr&& newKey) { - k = mozilla::Move(newKey); - } -}; - -// For doubles, we can xor the two uint32s. -template <> -struct DefaultHasher -{ - typedef double Lookup; - static HashNumber hash(double d) { - static_assert(sizeof(HashNumber) == 4, - "subsequent code assumes a four-byte hash"); - uint64_t u = mozilla::BitwiseCast(d); - return HashNumber(u ^ (u >> 32)); - } - static bool match(double lhs, double rhs) { - return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); - } -}; - -template <> -struct DefaultHasher -{ - typedef float Lookup; - static HashNumber hash(float f) { - static_assert(sizeof(HashNumber) == 4, - "subsequent code assumes a four-byte hash"); - return HashNumber(mozilla::BitwiseCast(f)); - } - static bool match(float lhs, float rhs) { - return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); - } -}; - -// A hash policy that compares C strings. -struct CStringHasher -{ - typedef const char* Lookup; - static js::HashNumber hash(Lookup l) { - return mozilla::HashString(l); - } - static bool match(const char* key, Lookup lookup) { - return strcmp(key, lookup) == 0; - } -}; - -// Fallible hashing interface. -// -// Most of the time generating a hash code is infallible so this class provides -// default methods that always succeed. Specialize this class for your own hash -// policy to provide fallible hashing. -// -// This is used by MovableCellHasher to handle the fact that generating a unique -// ID for cell pointer may fail due to OOM. -template -struct FallibleHashMethods -{ - // Return true if a hashcode is already available for its argument. Once - // this returns true for a specific argument it must continue to do so. - template static bool hasHash(Lookup&& l) { return true; } - - // Fallible method to ensure a hashcode exists for its argument and create - // one if not. Returns false on error, e.g. out of memory. - template static bool ensureHash(Lookup&& l) { return true; } -}; - -template -static bool -HasHash(Lookup&& l) { - return FallibleHashMethods::hasHash(mozilla::Forward(l)); -} - -template -static bool -EnsureHash(Lookup&& l) { - return FallibleHashMethods::ensureHash(mozilla::Forward(l)); -} - -/*****************************************************************************/ - -// Both HashMap and HashSet are implemented by a single HashTable that is even -// more heavily parameterized than the other two. This leaves HashTable gnarly -// and extremely coupled to HashMap and HashSet; thus code should not use -// HashTable directly. - -template -class HashMapEntry -{ - Key key_; - Value value_; - - template friend class detail::HashTable; - template friend class detail::HashTableEntry; - template friend class HashMap; - - public: - template - HashMapEntry(KeyInput&& k, ValueInput&& v) - : key_(mozilla::Forward(k)), - value_(mozilla::Forward(v)) - {} - - HashMapEntry(HashMapEntry&& rhs) - : key_(mozilla::Move(rhs.key_)), - value_(mozilla::Move(rhs.value_)) - {} - - void operator=(HashMapEntry&& rhs) { - key_ = mozilla::Move(rhs.key_); - value_ = mozilla::Move(rhs.value_); - } - - typedef Key KeyType; - typedef Value ValueType; - - const Key& key() const { return key_; } - Key& mutableKey() { return key_; } - const Value& value() const { return value_; } - Value& value() { return value_; } - - private: - HashMapEntry(const HashMapEntry&) = delete; - void operator=(const HashMapEntry&) = delete; -}; - -} // namespace js - -namespace mozilla { - -template -struct IsPod > : IsPod {}; - -template -struct IsPod > - : IntegralConstant::value && IsPod::value> -{}; - -} // namespace mozilla - -namespace js { - -namespace detail { - -template -class HashTable; - -template -class HashTableEntry -{ - template friend class HashTable; - typedef typename mozilla::RemoveConst::Type NonConstT; - - HashNumber keyHash; - mozilla::AlignedStorage2 mem; - - static const HashNumber sFreeKey = 0; - static const HashNumber sRemovedKey = 1; - static const HashNumber sCollisionBit = 1; - - static bool isLiveHash(HashNumber hash) - { - return hash > sRemovedKey; - } - - HashTableEntry(const HashTableEntry&) = delete; - void operator=(const HashTableEntry&) = delete; - ~HashTableEntry() = delete; - - public: - // NB: HashTableEntry is treated as a POD: no constructor or destructor calls. - - void destroyIfLive() { - if (isLive()) - mem.addr()->~T(); - } - - void destroy() { - MOZ_ASSERT(isLive()); - mem.addr()->~T(); - } - - void swap(HashTableEntry* other) { - if (this == other) - return; - MOZ_ASSERT(isLive()); - if (other->isLive()) { - mozilla::Swap(*mem.addr(), *other->mem.addr()); - } else { - *other->mem.addr() = mozilla::Move(*mem.addr()); - destroy(); - } - mozilla::Swap(keyHash, other->keyHash); - } - - T& get() { MOZ_ASSERT(isLive()); return *mem.addr(); } - NonConstT& getMutable() { MOZ_ASSERT(isLive()); return *mem.addr(); } - - bool isFree() const { return keyHash == sFreeKey; } - void clearLive() { MOZ_ASSERT(isLive()); keyHash = sFreeKey; mem.addr()->~T(); } - void clear() { if (isLive()) mem.addr()->~T(); keyHash = sFreeKey; } - bool isRemoved() const { return keyHash == sRemovedKey; } - void removeLive() { MOZ_ASSERT(isLive()); keyHash = sRemovedKey; mem.addr()->~T(); } - bool isLive() const { return isLiveHash(keyHash); } - void setCollision() { MOZ_ASSERT(isLive()); keyHash |= sCollisionBit; } - void unsetCollision() { keyHash &= ~sCollisionBit; } - bool hasCollision() const { return keyHash & sCollisionBit; } - bool matchHash(HashNumber hn) { return (keyHash & ~sCollisionBit) == hn; } - HashNumber getKeyHash() const { return keyHash & ~sCollisionBit; } - - template - void setLive(HashNumber hn, Args&&... args) - { - MOZ_ASSERT(!isLive()); - keyHash = hn; - new(mem.addr()) T(mozilla::Forward(args)...); - MOZ_ASSERT(isLive()); - } -}; - -template -class HashTable : private AllocPolicy -{ - friend class mozilla::ReentrancyGuard; - - typedef typename mozilla::RemoveConst::Type NonConstT; - typedef typename HashPolicy::KeyType Key; - typedef typename HashPolicy::Lookup Lookup; - - public: - typedef HashTableEntry Entry; - - // A nullable pointer to a hash table element. A Ptr |p| can be tested - // either explicitly |if (p.found()) p->...| or using boolean conversion - // |if (p) p->...|. Ptr objects must not be used after any mutating hash - // table operations unless |generation()| is tested. - class Ptr - { - friend class HashTable; - - Entry* entry_; -#ifdef JS_DEBUG - const HashTable* table_; - Generation generation; -#endif - - protected: - Ptr(Entry& entry, const HashTable& tableArg) - : entry_(&entry) -#ifdef JS_DEBUG - , table_(&tableArg) - , generation(tableArg.generation()) -#endif - {} - - public: - Ptr() - : entry_(nullptr) -#ifdef JS_DEBUG - , table_(nullptr) - , generation(0) -#endif - {} - - bool isValid() const { - return !entry_; - } - - bool found() const { - if (isValid()) - return false; -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); -#endif - return entry_->isLive(); - } - - explicit operator bool() const { - return found(); - } - - bool operator==(const Ptr& rhs) const { - MOZ_ASSERT(found() && rhs.found()); - return entry_ == rhs.entry_; - } - - bool operator!=(const Ptr& rhs) const { -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); -#endif - return !(*this == rhs); - } - - T& operator*() const { -#ifdef JS_DEBUG - MOZ_ASSERT(found()); - MOZ_ASSERT(generation == table_->generation()); -#endif - return entry_->get(); - } - - T* operator->() const { -#ifdef JS_DEBUG - MOZ_ASSERT(found()); - MOZ_ASSERT(generation == table_->generation()); -#endif - return &entry_->get(); - } - }; - - // A Ptr that can be used to add a key after a failed lookup. - class AddPtr : public Ptr - { - friend class HashTable; - HashNumber keyHash; -#ifdef JS_DEBUG - uint64_t mutationCount; -#endif - - AddPtr(Entry& entry, const HashTable& tableArg, HashNumber hn) - : Ptr(entry, tableArg) - , keyHash(hn) -#ifdef JS_DEBUG - , mutationCount(tableArg.mutationCount) -#endif - {} - - public: - AddPtr() : keyHash(0) {} - }; - - // A collection of hash table entries. The collection is enumerated by - // calling |front()| followed by |popFront()| as long as |!empty()|. As - // with Ptr/AddPtr, Range objects must not be used after any mutating hash - // table operation unless the |generation()| is tested. - class Range - { - protected: - friend class HashTable; - - Range(const HashTable& tableArg, Entry* c, Entry* e) - : cur(c) - , end(e) -#ifdef JS_DEBUG - , table_(&tableArg) - , mutationCount(tableArg.mutationCount) - , generation(tableArg.generation()) - , validEntry(true) -#endif - { - while (cur < end && !cur->isLive()) - ++cur; - } - - Entry* cur; - Entry* end; -#ifdef JS_DEBUG - const HashTable* table_; - uint64_t mutationCount; - Generation generation; - bool validEntry; -#endif - - public: - Range() - : cur(nullptr) - , end(nullptr) -#ifdef JS_DEBUG - , table_(nullptr) - , mutationCount(0) - , generation(0) - , validEntry(false) -#endif - {} - - bool empty() const { -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); - MOZ_ASSERT(mutationCount == table_->mutationCount); -#endif - return cur == end; - } - - T& front() const { - MOZ_ASSERT(!empty()); -#ifdef JS_DEBUG - MOZ_ASSERT(validEntry); - MOZ_ASSERT(generation == table_->generation()); - MOZ_ASSERT(mutationCount == table_->mutationCount); -#endif - return cur->get(); - } - - void popFront() { - MOZ_ASSERT(!empty()); -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); - MOZ_ASSERT(mutationCount == table_->mutationCount); -#endif - while (++cur < end && !cur->isLive()) - continue; -#ifdef JS_DEBUG - validEntry = true; -#endif - } - }; - - // A Range whose lifetime delimits a mutating enumeration of a hash table. - // Since rehashing when elements were removed during enumeration would be - // bad, it is postponed until the Enum is destructed. Since the Enum's - // destructor touches the hash table, the user must ensure that the hash - // table is still alive when the destructor runs. - class Enum : public Range - { - friend class HashTable; - - HashTable& table_; - bool rekeyed; - bool removed; - - /* Not copyable. */ - Enum(const Enum&) = delete; - void operator=(const Enum&) = delete; - - public: - template explicit - Enum(Map& map) : Range(map.all()), table_(map.impl), rekeyed(false), removed(false) {} - - // Removes the |front()| element from the table, leaving |front()| - // invalid until the next call to |popFront()|. For example: - // - // HashSet s; - // for (HashSet::Enum e(s); !e.empty(); e.popFront()) - // if (e.front() == 42) - // e.removeFront(); - void removeFront() { - table_.remove(*this->cur); - removed = true; -#ifdef JS_DEBUG - this->validEntry = false; - this->mutationCount = table_.mutationCount; -#endif - } - - NonConstT& mutableFront() { - MOZ_ASSERT(!this->empty()); -#ifdef JS_DEBUG - MOZ_ASSERT(this->validEntry); - MOZ_ASSERT(this->generation == this->Range::table_->generation()); - MOZ_ASSERT(this->mutationCount == this->Range::table_->mutationCount); -#endif - return this->cur->getMutable(); - } - - // Removes the |front()| element and re-inserts it into the table with - // a new key at the new Lookup position. |front()| is invalid after - // this operation until the next call to |popFront()|. - void rekeyFront(const Lookup& l, const Key& k) { - MOZ_ASSERT(&k != &HashPolicy::getKey(this->cur->get())); - Ptr p(*this->cur, table_); - table_.rekeyWithoutRehash(p, l, k); - rekeyed = true; -#ifdef JS_DEBUG - this->validEntry = false; - this->mutationCount = table_.mutationCount; -#endif - } - - void rekeyFront(const Key& k) { - rekeyFront(k, k); - } - - // Potentially rehashes the table. - ~Enum() { - if (rekeyed) { - table_.gen++; - table_.checkOverRemoved(); - } - - if (removed) - table_.compactIfUnderloaded(); - } - }; - - // HashTable is movable - HashTable(HashTable&& rhs) - : AllocPolicy(rhs) - { - mozilla::PodAssign(this, &rhs); - rhs.table = nullptr; - } - void operator=(HashTable&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - if (table) - destroyTable(*this, table, capacity()); - mozilla::PodAssign(this, &rhs); - rhs.table = nullptr; - } - - private: - // HashTable is not copyable or assignable - HashTable(const HashTable&) = delete; - void operator=(const HashTable&) = delete; - - private: - static const size_t CAP_BITS = 30; - - public: - uint64_t gen:56; // entry storage generation number - uint64_t hashShift:8; // multiplicative hash shift - Entry* table; // entry storage - uint32_t entryCount; // number of entries in table - uint32_t removedCount; // removed entry sentinels in table - -#ifdef JS_DEBUG - uint64_t mutationCount; - mutable bool mEntered; - // Note that some updates to these stats are not thread-safe. See the - // comment on the three-argument overloading of HashTable::lookup(). - mutable struct Stats - { - uint32_t searches; // total number of table searches - uint32_t steps; // hash chain links traversed - uint32_t hits; // searches that found key - uint32_t misses; // searches that didn't find key - uint32_t addOverRemoved; // adds that recycled a removed entry - uint32_t removes; // calls to remove - uint32_t removeFrees; // calls to remove that freed the entry - uint32_t grows; // table expansions - uint32_t shrinks; // table contractions - uint32_t compresses; // table compressions - uint32_t rehashes; // tombstone decontaminations - } stats; -# define METER(x) x -#else -# define METER(x) -#endif - - // The default initial capacity is 32 (enough to hold 16 elements), but it - // can be as low as 4. - static const unsigned sMinCapacityLog2 = 2; - static const unsigned sMinCapacity = 1 << sMinCapacityLog2; - static const unsigned sMaxInit = JS_BIT(CAP_BITS - 1); - static const unsigned sMaxCapacity = JS_BIT(CAP_BITS); - static const unsigned sHashBits = mozilla::tl::BitSize::value; - - // Hash-table alpha is conceptually a fraction, but to avoid floating-point - // math we implement it as a ratio of integers. - static const uint8_t sAlphaDenominator = 4; - static const uint8_t sMinAlphaNumerator = 1; // min alpha: 1/4 - static const uint8_t sMaxAlphaNumerator = 3; // max alpha: 3/4 - - static const HashNumber sFreeKey = Entry::sFreeKey; - static const HashNumber sRemovedKey = Entry::sRemovedKey; - static const HashNumber sCollisionBit = Entry::sCollisionBit; - - void setTableSizeLog2(unsigned sizeLog2) - { - hashShift = sHashBits - sizeLog2; - } - - static bool isLiveHash(HashNumber hash) - { - return Entry::isLiveHash(hash); - } - - static HashNumber prepareHash(const Lookup& l) - { - HashNumber keyHash = ScrambleHashCode(HashPolicy::hash(l)); - - // Avoid reserved hash codes. - if (!isLiveHash(keyHash)) - keyHash -= (sRemovedKey + 1); - return keyHash & ~sCollisionBit; - } - - enum FailureBehavior { DontReportFailure = false, ReportFailure = true }; - - static Entry* createTable(AllocPolicy& alloc, uint32_t capacity, - FailureBehavior reportFailure = ReportFailure) - { - static_assert(sFreeKey == 0, - "newly-calloc'd tables have to be considered empty"); - if (reportFailure) - return alloc.template pod_calloc(capacity); - - return alloc.template maybe_pod_calloc(capacity); - } - - static Entry* maybeCreateTable(AllocPolicy& alloc, uint32_t capacity) - { - static_assert(sFreeKey == 0, - "newly-calloc'd tables have to be considered empty"); - return alloc.template maybe_pod_calloc(capacity); - } - - static void destroyTable(AllocPolicy& alloc, Entry* oldTable, uint32_t capacity) - { - Entry* end = oldTable + capacity; - for (Entry* e = oldTable; e < end; ++e) - e->destroyIfLive(); - alloc.free_(oldTable); - } - - public: - explicit HashTable(AllocPolicy ap) - : AllocPolicy(ap) - , gen(0) - , hashShift(sHashBits) - , table(nullptr) - , entryCount(0) - , removedCount(0) -#ifdef JS_DEBUG - , mutationCount(0) - , mEntered(false) -#endif - {} - - MOZ_MUST_USE bool init(uint32_t length) - { - MOZ_ASSERT(!initialized()); - - // Reject all lengths whose initial computed capacity would exceed - // sMaxCapacity. Round that maximum length down to the nearest power - // of two for speedier code. - if (MOZ_UNLIKELY(length > sMaxInit)) { - this->reportAllocOverflow(); - return false; - } - - static_assert((sMaxInit * sAlphaDenominator) / sAlphaDenominator == sMaxInit, - "multiplication in numerator below could overflow"); - static_assert(sMaxInit * sAlphaDenominator <= UINT32_MAX - sMaxAlphaNumerator, - "numerator calculation below could potentially overflow"); - - // Compute the smallest capacity allowing |length| elements to be - // inserted without rehashing: ceil(length / max-alpha). (Ceiling - // integral division: .) - uint32_t newCapacity = - (length * sAlphaDenominator + sMaxAlphaNumerator - 1) / sMaxAlphaNumerator; - if (newCapacity < sMinCapacity) - newCapacity = sMinCapacity; - - // FIXME: use JS_CEILING_LOG2 when PGO stops crashing (bug 543034). - uint32_t roundUp = sMinCapacity, roundUpLog2 = sMinCapacityLog2; - while (roundUp < newCapacity) { - roundUp <<= 1; - ++roundUpLog2; - } - - newCapacity = roundUp; - MOZ_ASSERT(newCapacity >= length); - MOZ_ASSERT(newCapacity <= sMaxCapacity); - - table = createTable(*this, newCapacity); - if (!table) - return false; - - setTableSizeLog2(roundUpLog2); - METER(memset(&stats, 0, sizeof(stats))); - return true; - } - - bool initialized() const - { - return !!table; - } - - ~HashTable() - { - if (table) - destroyTable(*this, table, capacity()); - } - - private: - HashNumber hash1(HashNumber hash0) const - { - return hash0 >> hashShift; - } - - struct DoubleHash - { - HashNumber h2; - HashNumber sizeMask; - }; - - DoubleHash hash2(HashNumber curKeyHash) const - { - unsigned sizeLog2 = sHashBits - hashShift; - DoubleHash dh = { - ((curKeyHash << sizeLog2) >> hashShift) | 1, - (HashNumber(1) << sizeLog2) - 1 - }; - return dh; - } - - static HashNumber applyDoubleHash(HashNumber h1, const DoubleHash& dh) - { - return (h1 - dh.h2) & dh.sizeMask; - } - - bool overloaded() - { - static_assert(sMaxCapacity <= UINT32_MAX / sMaxAlphaNumerator, - "multiplication below could overflow"); - return entryCount + removedCount >= - capacity() * sMaxAlphaNumerator / sAlphaDenominator; - } - - // Would the table be underloaded if it had the given capacity and entryCount? - static bool wouldBeUnderloaded(uint32_t capacity, uint32_t entryCount) - { - static_assert(sMaxCapacity <= UINT32_MAX / sMinAlphaNumerator, - "multiplication below could overflow"); - return capacity > sMinCapacity && - entryCount <= capacity * sMinAlphaNumerator / sAlphaDenominator; - } - - bool underloaded() - { - return wouldBeUnderloaded(capacity(), entryCount); - } - - static bool match(Entry& e, const Lookup& l) - { - return HashPolicy::match(HashPolicy::getKey(e.get()), l); - } - - // Warning: in order for readonlyThreadsafeLookup() to be safe this - // function must not modify the table in any way when |collisionBit| is 0. - // (The use of the METER() macro to increment stats violates this - // restriction but we will live with that for now because it's enabled so - // rarely.) - Entry& lookup(const Lookup& l, HashNumber keyHash, unsigned collisionBit) const - { - MOZ_ASSERT(isLiveHash(keyHash)); - MOZ_ASSERT(!(keyHash & sCollisionBit)); - MOZ_ASSERT(collisionBit == 0 || collisionBit == sCollisionBit); - MOZ_ASSERT(table); - METER(stats.searches++); - - // Compute the primary hash address. - HashNumber h1 = hash1(keyHash); - Entry* entry = &table[h1]; - - // Miss: return space for a new entry. - if (entry->isFree()) { - METER(stats.misses++); - return *entry; - } - - // Hit: return entry. - if (entry->matchHash(keyHash) && match(*entry, l)) { - METER(stats.hits++); - return *entry; - } - - // Collision: double hash. - DoubleHash dh = hash2(keyHash); - - // Save the first removed entry pointer so we can recycle later. - Entry* firstRemoved = nullptr; - - while (true) { - if (MOZ_UNLIKELY(entry->isRemoved())) { - if (!firstRemoved) - firstRemoved = entry; - } else { - if (collisionBit == sCollisionBit) - entry->setCollision(); - } - - METER(stats.steps++); - h1 = applyDoubleHash(h1, dh); - - entry = &table[h1]; - if (entry->isFree()) { - METER(stats.misses++); - return firstRemoved ? *firstRemoved : *entry; - } - - if (entry->matchHash(keyHash) && match(*entry, l)) { - METER(stats.hits++); - return *entry; - } - } - } - - // This is a copy of lookup hardcoded to the assumptions: - // 1. the lookup is a lookupForAdd - // 2. the key, whose |keyHash| has been passed is not in the table, - // 3. no entries have been removed from the table. - // This specialized search avoids the need for recovering lookup values - // from entries, which allows more flexible Lookup/Key types. - Entry& findFreeEntry(HashNumber keyHash) - { - MOZ_ASSERT(!(keyHash & sCollisionBit)); - MOZ_ASSERT(table); - METER(stats.searches++); - - // We assume 'keyHash' has already been distributed. - - // Compute the primary hash address. - HashNumber h1 = hash1(keyHash); - Entry* entry = &table[h1]; - - // Miss: return space for a new entry. - if (!entry->isLive()) { - METER(stats.misses++); - return *entry; - } - - // Collision: double hash. - DoubleHash dh = hash2(keyHash); - - while (true) { - MOZ_ASSERT(!entry->isRemoved()); - entry->setCollision(); - - METER(stats.steps++); - h1 = applyDoubleHash(h1, dh); - - entry = &table[h1]; - if (!entry->isLive()) { - METER(stats.misses++); - return *entry; - } - } - } - - enum RebuildStatus { NotOverloaded, Rehashed, RehashFailed }; - - RebuildStatus changeTableSize(int deltaLog2, FailureBehavior reportFailure = ReportFailure) - { - // Look, but don't touch, until we succeed in getting new entry store. - Entry* oldTable = table; - uint32_t oldCap = capacity(); - uint32_t newLog2 = sHashBits - hashShift + deltaLog2; - uint32_t newCapacity = JS_BIT(newLog2); - if (MOZ_UNLIKELY(newCapacity > sMaxCapacity)) { - if (reportFailure) - this->reportAllocOverflow(); - return RehashFailed; - } - - Entry* newTable = createTable(*this, newCapacity, reportFailure); - if (!newTable) - return RehashFailed; - - // We can't fail from here on, so update table parameters. - setTableSizeLog2(newLog2); - removedCount = 0; - gen++; - table = newTable; - - // Copy only live entries, leaving removed ones behind. - Entry* end = oldTable + oldCap; - for (Entry* src = oldTable; src < end; ++src) { - if (src->isLive()) { - HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive( - hn, mozilla::Move(const_cast(src->get()))); - src->destroy(); - } - } - - // All entries have been destroyed, no need to destroyTable. - this->free_(oldTable); - return Rehashed; - } - - bool shouldCompressTable() - { - // Compress if a quarter or more of all entries are removed. - return removedCount >= (capacity() >> 2); - } - - RebuildStatus checkOverloaded(FailureBehavior reportFailure = ReportFailure) - { - if (!overloaded()) - return NotOverloaded; - - int deltaLog2; - if (shouldCompressTable()) { - METER(stats.compresses++); - deltaLog2 = 0; - } else { - METER(stats.grows++); - deltaLog2 = 1; - } - - return changeTableSize(deltaLog2, reportFailure); - } - - // Infallibly rehash the table if we are overloaded with removals. - void checkOverRemoved() - { - if (overloaded()) { - if (checkOverloaded(DontReportFailure) == RehashFailed) - rehashTableInPlace(); - } - } - - void remove(Entry& e) - { - MOZ_ASSERT(table); - METER(stats.removes++); - - if (e.hasCollision()) { - e.removeLive(); - removedCount++; - } else { - METER(stats.removeFrees++); - e.clearLive(); - } - entryCount--; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - void checkUnderloaded() - { - if (underloaded()) { - METER(stats.shrinks++); - (void) changeTableSize(-1, DontReportFailure); - } - } - - // Resize the table down to the largest capacity which doesn't underload the - // table. Since we call checkUnderloaded() on every remove, you only need - // to call this after a bulk removal of items done without calling remove(). - void compactIfUnderloaded() - { - int32_t resizeLog2 = 0; - uint32_t newCapacity = capacity(); - while (wouldBeUnderloaded(newCapacity, entryCount)) { - newCapacity = newCapacity >> 1; - resizeLog2--; - } - - if (resizeLog2 != 0) - (void) changeTableSize(resizeLog2, DontReportFailure); - } - - // This is identical to changeTableSize(currentSize), but without requiring - // a second table. We do this by recycling the collision bits to tell us if - // the element is already inserted or still waiting to be inserted. Since - // already-inserted elements win any conflicts, we get the same table as we - // would have gotten through random insertion order. - void rehashTableInPlace() - { - METER(stats.rehashes++); - removedCount = 0; - for (size_t i = 0; i < capacity(); ++i) - table[i].unsetCollision(); - - for (size_t i = 0; i < capacity();) { - Entry* src = &table[i]; - - if (!src->isLive() || src->hasCollision()) { - ++i; - continue; - } - - HashNumber keyHash = src->getKeyHash(); - HashNumber h1 = hash1(keyHash); - DoubleHash dh = hash2(keyHash); - Entry* tgt = &table[h1]; - while (true) { - if (!tgt->hasCollision()) { - src->swap(tgt); - tgt->setCollision(); - break; - } - - h1 = applyDoubleHash(h1, dh); - tgt = &table[h1]; - } - } - - // TODO: this algorithm leaves collision bits on *all* elements, even if - // they are on no collision path. We have the option of setting the - // collision bits correctly on a subsequent pass or skipping the rehash - // unless we are totally filled with tombstones: benchmark to find out - // which approach is best. - } - - // Note: |l| may be a reference to a piece of |u|, so this function - // must take care not to use |l| after moving |u|. - // - // Prefer to use putNewInfallible; this function does not check - // invariants. - template - void putNewInfallibleInternal(const Lookup& l, Args&&... args) - { - MOZ_ASSERT(table); - - HashNumber keyHash = prepareHash(l); - Entry* entry = &findFreeEntry(keyHash); - MOZ_ASSERT(entry); - - if (entry->isRemoved()) { - METER(stats.addOverRemoved++); - removedCount--; - keyHash |= sCollisionBit; - } - - entry->setLive(keyHash, mozilla::Forward(args)...); - entryCount++; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - public: - void clear() - { - if (mozilla::IsPod::value) { - memset(table, 0, sizeof(*table) * capacity()); - } else { - uint32_t tableCapacity = capacity(); - Entry* end = table + tableCapacity; - for (Entry* e = table; e < end; ++e) - e->clear(); - } - removedCount = 0; - entryCount = 0; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - void finish() - { -#ifdef JS_DEBUG - MOZ_ASSERT(!mEntered); -#endif - if (!table) - return; - - destroyTable(*this, table, capacity()); - table = nullptr; - gen++; - entryCount = 0; - removedCount = 0; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - Range all() const - { - MOZ_ASSERT(table); - return Range(*this, table, table + capacity()); - } - - bool empty() const - { - MOZ_ASSERT(table); - return !entryCount; - } - - uint32_t count() const - { - MOZ_ASSERT(table); - return entryCount; - } - - uint32_t capacity() const - { - MOZ_ASSERT(table); - return JS_BIT(sHashBits - hashShift); - } - - Generation generation() const - { - MOZ_ASSERT(table); - return Generation(gen); - } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const - { - return mallocSizeOf(table); - } - - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const - { - return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); - } - - Ptr lookup(const Lookup& l) const - { - mozilla::ReentrancyGuard g(*this); - if (!HasHash(l)) - return Ptr(); - HashNumber keyHash = prepareHash(l); - return Ptr(lookup(l, keyHash, 0), *this); - } - - Ptr readonlyThreadsafeLookup(const Lookup& l) const - { - if (!HasHash(l)) - return Ptr(); - HashNumber keyHash = prepareHash(l); - return Ptr(lookup(l, keyHash, 0), *this); - } - - AddPtr lookupForAdd(const Lookup& l) const - { - mozilla::ReentrancyGuard g(*this); - if (!EnsureHash(l)) - return AddPtr(); - HashNumber keyHash = prepareHash(l); - Entry& entry = lookup(l, keyHash, sCollisionBit); - AddPtr p(entry, *this, keyHash); - return p; - } - - template - MOZ_MUST_USE bool add(AddPtr& p, Args&&... args) - { - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(table); - MOZ_ASSERT(!p.found()); - MOZ_ASSERT(!(p.keyHash & sCollisionBit)); - - // Check for error from ensureHash() here. - if (p.isValid()) - return false; - - // Changing an entry from removed to live does not affect whether we - // are overloaded and can be handled separately. - if (p.entry_->isRemoved()) { - if (!this->checkSimulatedOOM()) - return false; - METER(stats.addOverRemoved++); - removedCount--; - p.keyHash |= sCollisionBit; - } else { - // Preserve the validity of |p.entry_|. - RebuildStatus status = checkOverloaded(); - if (status == RehashFailed) - return false; - if (status == NotOverloaded && !this->checkSimulatedOOM()) - return false; - if (status == Rehashed) - p.entry_ = &findFreeEntry(p.keyHash); - } - - p.entry_->setLive(p.keyHash, mozilla::Forward(args)...); - entryCount++; -#ifdef JS_DEBUG - mutationCount++; - p.generation = generation(); - p.mutationCount = mutationCount; -#endif - return true; - } - - // Note: |l| may be a reference to a piece of |u|, so this function - // must take care not to use |l| after moving |u|. - template - void putNewInfallible(const Lookup& l, Args&&... args) - { - MOZ_ASSERT(!lookup(l).found()); - mozilla::ReentrancyGuard g(*this); - putNewInfallibleInternal(l, mozilla::Forward(args)...); - } - - // Note: |l| may be alias arguments in |args|, so this function must take - // care not to use |l| after moving |args|. - template - MOZ_MUST_USE bool putNew(const Lookup& l, Args&&... args) - { - if (!this->checkSimulatedOOM()) - return false; - - if (!EnsureHash(l)) - return false; - - if (checkOverloaded() == RehashFailed) - return false; - - putNewInfallible(l, mozilla::Forward(args)...); - return true; - } - - // Note: |l| may be a reference to a piece of |u|, so this function - // must take care not to use |l| after moving |u|. - template - MOZ_MUST_USE bool relookupOrAdd(AddPtr& p, const Lookup& l, Args&&... args) - { - // Check for error from ensureHash() here. - if (p.isValid()) - return false; - -#ifdef JS_DEBUG - p.generation = generation(); - p.mutationCount = mutationCount; -#endif - { - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(prepareHash(l) == p.keyHash); // l has not been destroyed - p.entry_ = &lookup(l, p.keyHash, sCollisionBit); - } - return p.found() || add(p, mozilla::Forward(args)...); - } - - void remove(Ptr p) - { - MOZ_ASSERT(table); - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(p.found()); - remove(*p.entry_); - checkUnderloaded(); - } - - void rekeyWithoutRehash(Ptr p, const Lookup& l, const Key& k) - { - MOZ_ASSERT(table); - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(p.found()); - typename HashTableEntry::NonConstT t(mozilla::Move(*p)); - HashPolicy::setKey(t, const_cast(k)); - remove(*p.entry_); - putNewInfallibleInternal(l, mozilla::Move(t)); - } - - void rekeyAndMaybeRehash(Ptr p, const Lookup& l, const Key& k) - { - rekeyWithoutRehash(p, l, k); - checkOverRemoved(); - } - -#undef METER -}; - -} // namespace detail -} // namespace js - -#endif /* js_HashTable_h */ diff --git a/mac/include/spidermonkey/js/HeapAPI.h b/mac/include/spidermonkey/js/HeapAPI.h deleted file mode 100644 index e37d13e9..00000000 --- a/mac/include/spidermonkey/js/HeapAPI.h +++ /dev/null @@ -1,406 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_HeapAPI_h -#define js_HeapAPI_h - -#include - -#include "jspubtd.h" - -#include "js/TraceKind.h" -#include "js/Utility.h" - -/* These values are private to the JS engine. */ -namespace js { - -JS_FRIEND_API(bool) -CurrentThreadCanAccessZone(JS::Zone* zone); - -namespace gc { - -struct Cell; - -const size_t ArenaShift = 12; -const size_t ArenaSize = size_t(1) << ArenaShift; -const size_t ArenaMask = ArenaSize - 1; - -#ifdef JS_GC_SMALL_CHUNK_SIZE -const size_t ChunkShift = 18; -#else -const size_t ChunkShift = 20; -#endif -const size_t ChunkSize = size_t(1) << ChunkShift; -const size_t ChunkMask = ChunkSize - 1; - -const size_t CellShift = 3; -const size_t CellSize = size_t(1) << CellShift; -const size_t CellMask = CellSize - 1; - -/* These are magic constants derived from actual offsets in gc/Heap.h. */ -#ifdef JS_GC_SMALL_CHUNK_SIZE -const size_t ChunkMarkBitmapOffset = 258104; -const size_t ChunkMarkBitmapBits = 31744; -#else -const size_t ChunkMarkBitmapOffset = 1032352; -const size_t ChunkMarkBitmapBits = 129024; -#endif -const size_t ChunkRuntimeOffset = ChunkSize - sizeof(void*); -const size_t ChunkTrailerSize = 2 * sizeof(uintptr_t) + sizeof(uint64_t); -const size_t ChunkLocationOffset = ChunkSize - ChunkTrailerSize; -const size_t ArenaZoneOffset = sizeof(size_t); -const size_t ArenaHeaderSize = sizeof(size_t) + 2 * sizeof(uintptr_t) + - sizeof(size_t) + sizeof(uintptr_t); - -/* - * Live objects are marked black. How many other additional colors are available - * depends on the size of the GCThing. Objects marked gray are eligible for - * cycle collection. - */ -static const uint32_t BLACK = 0; -static const uint32_t GRAY = 1; - -/* - * The "location" field in the Chunk trailer is a enum indicating various roles - * of the chunk. - */ -enum class ChunkLocation : uint32_t -{ - Invalid = 0, - Nursery = 1, - TenuredHeap = 2 -}; - -#ifdef JS_DEBUG -/* When downcasting, ensure we are actually the right type. */ -extern JS_FRIEND_API(void) -AssertGCThingHasType(js::gc::Cell* cell, JS::TraceKind kind); -#else -inline void -AssertGCThingHasType(js::gc::Cell* cell, JS::TraceKind kind) {} -#endif - -MOZ_ALWAYS_INLINE bool IsInsideNursery(const js::gc::Cell* cell); - -} /* namespace gc */ -} /* namespace js */ - -namespace JS { -struct Zone; - -/* Default size for the generational nursery in bytes. */ -const uint32_t DefaultNurseryBytes = 16 * js::gc::ChunkSize; - -/* Default maximum heap size in bytes to pass to JS_NewRuntime(). */ -const uint32_t DefaultHeapMaxBytes = 32 * 1024 * 1024; - -namespace shadow { - -struct Zone -{ - protected: - JSRuntime* const runtime_; - JSTracer* const barrierTracer_; // A pointer to the JSRuntime's |gcMarker|. - - public: - // Stack GC roots for Rooted GC pointers. - js::RootedListHeads stackRoots_; - template friend class JS::Rooted; - - bool needsIncrementalBarrier_; - - Zone(JSRuntime* runtime, JSTracer* barrierTracerArg) - : runtime_(runtime), - barrierTracer_(barrierTracerArg), - needsIncrementalBarrier_(false) - { - for (auto& stackRootPtr : stackRoots_) - stackRootPtr = nullptr; - } - - bool needsIncrementalBarrier() const { - return needsIncrementalBarrier_; - } - - JSTracer* barrierTracer() { - MOZ_ASSERT(needsIncrementalBarrier_); - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); - return barrierTracer_; - } - - JSRuntime* runtimeFromMainThread() const { - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); - return runtime_; - } - - // Note: Unrestricted access to the zone's runtime from an arbitrary - // thread can easily lead to races. Use this method very carefully. - JSRuntime* runtimeFromAnyThread() const { - return runtime_; - } - - static MOZ_ALWAYS_INLINE JS::shadow::Zone* asShadowZone(JS::Zone* zone) { - return reinterpret_cast(zone); - } -}; - -} /* namespace shadow */ - -/** - * A GC pointer, tagged with the trace kind. - * - * In general, a GC pointer should be stored with an exact type. This class - * is for use when that is not possible because a single pointer must point - * to several kinds of GC thing. - */ -class JS_FRIEND_API(GCCellPtr) -{ - public: - // Construction from a void* and trace kind. - GCCellPtr(void* gcthing, JS::TraceKind traceKind) : ptr(checkedCast(gcthing, traceKind)) {} - - // Automatically construct a null GCCellPtr from nullptr. - MOZ_IMPLICIT GCCellPtr(decltype(nullptr)) : ptr(checkedCast(nullptr, JS::TraceKind::Null)) {} - - // Construction from an explicit type. - template - explicit GCCellPtr(T* p) : ptr(checkedCast(p, JS::MapTypeToTraceKind::kind)) { } - explicit GCCellPtr(JSFunction* p) : ptr(checkedCast(p, JS::TraceKind::Object)) { } - explicit GCCellPtr(JSFlatString* str) : ptr(checkedCast(str, JS::TraceKind::String)) { } - explicit GCCellPtr(const Value& v); - - JS::TraceKind kind() const { - JS::TraceKind traceKind = JS::TraceKind(ptr & OutOfLineTraceKindMask); - if (uintptr_t(traceKind) != OutOfLineTraceKindMask) - return traceKind; - return outOfLineKind(); - } - - // Allow GCCellPtr to be used in a boolean context. - explicit operator bool() const { - MOZ_ASSERT(bool(asCell()) == (kind() != JS::TraceKind::Null)); - return asCell(); - } - - // Simplify checks to the kind. - template - bool is() const { return kind() == JS::MapTypeToTraceKind::kind; } - - // Conversions to more specific types must match the kind. Access to - // further refined types is not allowed directly from a GCCellPtr. - template - T& as() const { - MOZ_ASSERT(kind() == JS::MapTypeToTraceKind::kind); - // We can't use static_cast here, because the fact that JSObject - // inherits from js::gc::Cell is not part of the public API. - return *reinterpret_cast(asCell()); - } - - // Return a pointer to the cell this |GCCellPtr| refers to, or |nullptr|. - // (It would be more symmetrical with |to| for this to return a |Cell&|, but - // the result can be |nullptr|, and null references are undefined behavior.) - js::gc::Cell* asCell() const { - return reinterpret_cast(ptr & ~OutOfLineTraceKindMask); - } - - // The CC's trace logger needs an identity that is XPIDL serializable. - uint64_t unsafeAsInteger() const { - return static_cast(unsafeAsUIntPtr()); - } - // Inline mark bitmap access requires direct pointer arithmetic. - uintptr_t unsafeAsUIntPtr() const { - MOZ_ASSERT(asCell()); - MOZ_ASSERT(!js::gc::IsInsideNursery(asCell())); - return reinterpret_cast(asCell()); - } - - bool mayBeOwnedByOtherRuntime() const; - - private: - static uintptr_t checkedCast(void* p, JS::TraceKind traceKind) { - js::gc::Cell* cell = static_cast(p); - MOZ_ASSERT((uintptr_t(p) & OutOfLineTraceKindMask) == 0); - AssertGCThingHasType(cell, traceKind); - // Note: the OutOfLineTraceKindMask bits are set on all out-of-line kinds - // so that we can mask instead of branching. - MOZ_ASSERT_IF(uintptr_t(traceKind) >= OutOfLineTraceKindMask, - (uintptr_t(traceKind) & OutOfLineTraceKindMask) == OutOfLineTraceKindMask); - return uintptr_t(p) | (uintptr_t(traceKind) & OutOfLineTraceKindMask); - } - - JS::TraceKind outOfLineKind() const; - - uintptr_t ptr; -}; - -inline bool -operator==(const GCCellPtr& ptr1, const GCCellPtr& ptr2) -{ - return ptr1.asCell() == ptr2.asCell(); -} - -inline bool -operator!=(const GCCellPtr& ptr1, const GCCellPtr& ptr2) -{ - return !(ptr1 == ptr2); -} - -// Unwraps the given GCCellPtr and calls the given functor with a template -// argument of the actual type of the pointer. -template -auto -DispatchTyped(F f, GCCellPtr thing, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - switch (thing.kind()) { -#define JS_EXPAND_DEF(name, type, _) \ - case JS::TraceKind::name: \ - return f(&thing.as(), mozilla::Forward(args)...); - JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - default: - MOZ_CRASH("Invalid trace kind in DispatchTyped for GCCellPtr."); - } -} - -} /* namespace JS */ - -namespace js { -namespace gc { -namespace detail { - -static MOZ_ALWAYS_INLINE uintptr_t* -GetGCThingMarkBitmap(const uintptr_t addr) -{ - MOZ_ASSERT(addr); - const uintptr_t bmap_addr = (addr & ~ChunkMask) | ChunkMarkBitmapOffset; - return reinterpret_cast(bmap_addr); -} - -static MOZ_ALWAYS_INLINE void -GetGCThingMarkWordAndMask(const uintptr_t addr, uint32_t color, - uintptr_t** wordp, uintptr_t* maskp) -{ - MOZ_ASSERT(addr); - const size_t bit = (addr & js::gc::ChunkMask) / js::gc::CellSize + color; - MOZ_ASSERT(bit < js::gc::ChunkMarkBitmapBits); - uintptr_t* bitmap = GetGCThingMarkBitmap(addr); - const uintptr_t nbits = sizeof(*bitmap) * CHAR_BIT; - *maskp = uintptr_t(1) << (bit % nbits); - *wordp = &bitmap[bit / nbits]; -} - -static MOZ_ALWAYS_INLINE JS::Zone* -GetGCThingZone(const uintptr_t addr) -{ - MOZ_ASSERT(addr); - const uintptr_t zone_addr = (addr & ~ArenaMask) | ArenaZoneOffset; - return *reinterpret_cast(zone_addr); - -} - -static MOZ_ALWAYS_INLINE JS::shadow::Runtime* -GetCellRuntime(const Cell* cell) -{ - MOZ_ASSERT(cell); - const uintptr_t addr = uintptr_t(cell); - const uintptr_t rt_addr = (addr & ~ChunkMask) | ChunkRuntimeOffset; - return *reinterpret_cast(rt_addr); -} - -static MOZ_ALWAYS_INLINE bool -CellIsMarkedGray(const Cell* cell) -{ - MOZ_ASSERT(cell); - if (js::gc::IsInsideNursery(cell)) - return false; - - uintptr_t* word, mask; - js::gc::detail::GetGCThingMarkWordAndMask(uintptr_t(cell), js::gc::GRAY, &word, &mask); - return *word & mask; -} - -extern JS_PUBLIC_API(bool) -CellIsMarkedGrayIfKnown(const Cell* cell); - -} /* namespace detail */ - -MOZ_ALWAYS_INLINE bool -IsInsideNursery(const js::gc::Cell* cell) -{ - if (!cell) - return false; - uintptr_t addr = uintptr_t(cell); - addr &= ~js::gc::ChunkMask; - addr |= js::gc::ChunkLocationOffset; - auto location = *reinterpret_cast(addr); - MOZ_ASSERT(location == ChunkLocation::Nursery || location == ChunkLocation::TenuredHeap); - return location == ChunkLocation::Nursery; -} - -} /* namespace gc */ -} /* namespace js */ - -namespace JS { - -static MOZ_ALWAYS_INLINE Zone* -GetTenuredGCThingZone(GCCellPtr thing) -{ - MOZ_ASSERT(!js::gc::IsInsideNursery(thing.asCell())); - return js::gc::detail::GetGCThingZone(thing.unsafeAsUIntPtr()); -} - -static MOZ_ALWAYS_INLINE Zone* -GetStringZone(JSString* str) -{ - return js::gc::detail::GetGCThingZone(uintptr_t(str)); -} - -extern JS_PUBLIC_API(Zone*) -GetObjectZone(JSObject* obj); - -static MOZ_ALWAYS_INLINE bool -GCThingIsMarkedGray(GCCellPtr thing) -{ - if (thing.mayBeOwnedByOtherRuntime()) - return false; - return js::gc::detail::CellIsMarkedGrayIfKnown(thing.asCell()); -} - -extern JS_PUBLIC_API(JS::TraceKind) -GCThingTraceKind(void* thing); - -} /* namespace JS */ - -namespace js { -namespace gc { - -static MOZ_ALWAYS_INLINE bool -IsIncrementalBarrierNeededOnTenuredGCThing(JS::shadow::Runtime* rt, const JS::GCCellPtr thing) -{ - MOZ_ASSERT(thing); - MOZ_ASSERT(!js::gc::IsInsideNursery(thing.asCell())); - - // TODO: I'd like to assert !isHeapBusy() here but this gets called while we - // are tracing the heap, e.g. during memory reporting (see bug 1313318). - MOZ_ASSERT(!rt->isHeapCollecting()); - - JS::Zone* zone = JS::GetTenuredGCThingZone(thing); - return JS::shadow::Zone::asShadowZone(zone)->needsIncrementalBarrier(); -} - -/** - * Create an object providing access to the garbage collector's internal notion - * of the current state of memory (both GC heap memory and GCthing-controlled - * malloc memory. - */ -extern JS_PUBLIC_API(JSObject*) -NewMemoryInfoObject(JSContext* cx); - -} /* namespace gc */ -} /* namespace js */ - -#endif /* js_HeapAPI_h */ diff --git a/mac/include/spidermonkey/js/Id.h b/mac/include/spidermonkey/js/Id.h deleted file mode 100644 index d474e784..00000000 --- a/mac/include/spidermonkey/js/Id.h +++ /dev/null @@ -1,207 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Id_h -#define js_Id_h - -// A jsid is an identifier for a property or method of an object which is -// either a 31-bit unsigned integer, interned string or symbol. -// -// Also, there is an additional jsid value, JSID_VOID, which does not occur in -// JS scripts but may be used to indicate the absence of a valid jsid. A void -// jsid is not a valid id and only arises as an exceptional API return value, -// such as in JS_NextProperty. Embeddings must not pass JSID_VOID into JSAPI -// entry points expecting a jsid and do not need to handle JSID_VOID in hooks -// receiving a jsid except when explicitly noted in the API contract. -// -// A jsid is not implicitly convertible to or from a Value; JS_ValueToId or -// JS_IdToValue must be used instead. - -#include "jstypes.h" - -#include "js/HeapAPI.h" -#include "js/RootingAPI.h" -#include "js/TypeDecls.h" -#include "js/Utility.h" - -struct jsid -{ - size_t asBits; - bool operator==(const jsid& rhs) const { return asBits == rhs.asBits; } - bool operator!=(const jsid& rhs) const { return asBits != rhs.asBits; } -} JS_HAZ_GC_POINTER; -#define JSID_BITS(id) (id.asBits) - -#define JSID_TYPE_STRING 0x0 -#define JSID_TYPE_INT 0x1 -#define JSID_TYPE_VOID 0x2 -#define JSID_TYPE_SYMBOL 0x4 -#define JSID_TYPE_MASK 0x7 - -// Avoid using canonical 'id' for jsid parameters since this is a magic word in -// Objective-C++ which, apparently, wants to be able to #include jsapi.h. -#define id iden - -static MOZ_ALWAYS_INLINE bool -JSID_IS_STRING(jsid id) -{ - return (JSID_BITS(id) & JSID_TYPE_MASK) == 0; -} - -static MOZ_ALWAYS_INLINE JSString* -JSID_TO_STRING(jsid id) -{ - MOZ_ASSERT(JSID_IS_STRING(id)); - return (JSString*)JSID_BITS(id); -} - -/** - * Only JSStrings that have been interned via the JSAPI can be turned into - * jsids by API clients. - * - * N.B. if a jsid is backed by a string which has not been interned, that - * string must be appropriately rooted to avoid being collected by the GC. - */ -JS_PUBLIC_API(jsid) -INTERNED_STRING_TO_JSID(JSContext* cx, JSString* str); - -static MOZ_ALWAYS_INLINE bool -JSID_IS_INT(jsid id) -{ - return !!(JSID_BITS(id) & JSID_TYPE_INT); -} - -static MOZ_ALWAYS_INLINE int32_t -JSID_TO_INT(jsid id) -{ - MOZ_ASSERT(JSID_IS_INT(id)); - return ((uint32_t)JSID_BITS(id)) >> 1; -} - -#define JSID_INT_MIN 0 -#define JSID_INT_MAX INT32_MAX - -static MOZ_ALWAYS_INLINE bool -INT_FITS_IN_JSID(int32_t i) -{ - return i >= 0; -} - -static MOZ_ALWAYS_INLINE jsid -INT_TO_JSID(int32_t i) -{ - jsid id; - MOZ_ASSERT(INT_FITS_IN_JSID(i)); - JSID_BITS(id) = ((i << 1) | JSID_TYPE_INT); - return id; -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_SYMBOL(jsid id) -{ - return (JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_SYMBOL && - JSID_BITS(id) != JSID_TYPE_SYMBOL; -} - -static MOZ_ALWAYS_INLINE JS::Symbol* -JSID_TO_SYMBOL(jsid id) -{ - MOZ_ASSERT(JSID_IS_SYMBOL(id)); - return (JS::Symbol*)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); -} - -static MOZ_ALWAYS_INLINE jsid -SYMBOL_TO_JSID(JS::Symbol* sym) -{ - jsid id; - MOZ_ASSERT(sym != nullptr); - MOZ_ASSERT((size_t(sym) & JSID_TYPE_MASK) == 0); - MOZ_ASSERT(!js::gc::IsInsideNursery(reinterpret_cast(sym))); - JSID_BITS(id) = (size_t(sym) | JSID_TYPE_SYMBOL); - return id; -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_GCTHING(jsid id) -{ - return JSID_IS_STRING(id) || JSID_IS_SYMBOL(id); -} - -static MOZ_ALWAYS_INLINE JS::GCCellPtr -JSID_TO_GCTHING(jsid id) -{ - void* thing = (void*)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); - if (JSID_IS_STRING(id)) - return JS::GCCellPtr(thing, JS::TraceKind::String); - MOZ_ASSERT(JSID_IS_SYMBOL(id)); - return JS::GCCellPtr(thing, JS::TraceKind::Symbol); -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_VOID(const jsid id) -{ - MOZ_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_VOID, - JSID_BITS(id) == JSID_TYPE_VOID); - return (size_t)JSID_BITS(id) == JSID_TYPE_VOID; -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_EMPTY(const jsid id) -{ - return (size_t)JSID_BITS(id) == JSID_TYPE_SYMBOL; -} - -extern JS_PUBLIC_DATA(const jsid) JSID_VOID; -extern JS_PUBLIC_DATA(const jsid) JSID_EMPTY; - -extern JS_PUBLIC_DATA(const JS::HandleId) JSID_VOIDHANDLE; -extern JS_PUBLIC_DATA(const JS::HandleId) JSID_EMPTYHANDLE; - -namespace JS { - -template <> -struct GCPolicy -{ - static jsid initial() { return JSID_VOID; } - static void trace(JSTracer* trc, jsid* idp, const char* name) { - js::UnsafeTraceManuallyBarrieredEdge(trc, idp, name); - } -}; - -} // namespace JS - -namespace js { - -template <> -struct BarrierMethods -{ - static void postBarrier(jsid* idp, jsid prev, jsid next) {} - static void exposeToJS(jsid id) { - if (JSID_IS_GCTHING(id)) - js::gc::ExposeGCThingToActiveJS(JSID_TO_GCTHING(id)); - } -}; - -// If the jsid is a GC pointer type, convert to that type and call |f| with -// the pointer. If the jsid is not a GC type, calls F::defaultValue. -template -auto -DispatchTyped(F f, const jsid& id, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - if (JSID_IS_STRING(id)) - return f(JSID_TO_STRING(id), mozilla::Forward(args)...); - if (JSID_IS_SYMBOL(id)) - return f(JSID_TO_SYMBOL(id), mozilla::Forward(args)...); - MOZ_ASSERT(!JSID_IS_GCTHING(id)); - return F::defaultValue(id); -} - -#undef id - -} // namespace js - -#endif /* js_Id_h */ diff --git a/mac/include/spidermonkey/js/Initialization.h b/mac/include/spidermonkey/js/Initialization.h deleted file mode 100644 index 8a1cf910..00000000 --- a/mac/include/spidermonkey/js/Initialization.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* SpiderMonkey initialization and shutdown APIs. */ - -#ifndef js_Initialization_h -#define js_Initialization_h - -#include "jstypes.h" - -namespace JS { -namespace detail { - -enum class InitState { Uninitialized = 0, Running, ShutDown }; - -/** - * SpiderMonkey's initialization status is tracked here, and it controls things - * that should happen only once across all runtimes. It's an API requirement - * that JS_Init (and JS_ShutDown, if called) be called in a thread-aware - * manner, so this (internal -- embedders, don't use!) variable doesn't need to - * be atomic. - */ -extern JS_PUBLIC_DATA(InitState) -libraryInitState; - -extern JS_PUBLIC_API(const char*) -InitWithFailureDiagnostic(bool isDebugBuild); - -} // namespace detail -} // namespace JS - -// These are equivalent to ICU's |UMemAllocFn|, |UMemReallocFn|, and -// |UMemFreeFn| types. The first argument (called |context| in the ICU docs) -// will always be nullptr and should be ignored. -typedef void* (*JS_ICUAllocFn)(const void*, size_t size); -typedef void* (*JS_ICUReallocFn)(const void*, void* p, size_t size); -typedef void (*JS_ICUFreeFn)(const void*, void* p); - -/** - * This function can be used to track memory used by ICU. If it is called, it - * *must* be called before JS_Init. Don't use it unless you know what you're - * doing! - */ -extern JS_PUBLIC_API(bool) -JS_SetICUMemoryFunctions(JS_ICUAllocFn allocFn, - JS_ICUReallocFn reallocFn, - JS_ICUFreeFn freeFn); - -/** - * Initialize SpiderMonkey, returning true only if initialization succeeded. - * Once this method has succeeded, it is safe to call JS_NewRuntime and other - * JSAPI methods. - * - * This method must be called before any other JSAPI method is used on any - * thread. Once it has been used, it is safe to call any JSAPI method, and it - * remains safe to do so until JS_ShutDown is correctly called. - * - * It is currently not possible to initialize SpiderMonkey multiple times (that - * is, calling JS_Init/JSAPI methods/JS_ShutDown in that order, then doing so - * again). This restriction may eventually be lifted. - */ -inline bool -JS_Init(void) -{ -#ifdef DEBUG - return !JS::detail::InitWithFailureDiagnostic(true); -#else - return !JS::detail::InitWithFailureDiagnostic(false); -#endif -} - -/** - * A variant of JS_Init. On success it returns nullptr. On failure it returns a - * pointer to a string literal that describes how initialization failed, which - * can be useful for debugging purposes. - */ -inline const char* -JS_InitWithFailureDiagnostic(void) -{ -#ifdef DEBUG - return JS::detail::InitWithFailureDiagnostic(true); -#else - return JS::detail::InitWithFailureDiagnostic(false); -#endif -} - -/* - * Returns true if SpiderMonkey has been initialized successfully, even if it has - * possibly been shut down. - * - * Note that it is the responsibility of the embedder to call JS_Init() and - * JS_ShutDown() at the correct times, and therefore this API should ideally not - * be necessary to use. This is only intended to be used in cases where the - * embedder isn't in full control of deciding whether to initialize SpiderMonkey - * or hand off the task to another consumer. - */ -inline bool -JS_IsInitialized(void) -{ - return JS::detail::libraryInitState != JS::detail::InitState::Uninitialized; -} - -/** - * Destroy free-standing resources allocated by SpiderMonkey, not associated - * with any runtime, context, or other structure. - * - * This method should be called after all other JSAPI data has been properly - * cleaned up: every new runtime must have been destroyed, every new context - * must have been destroyed, and so on. Calling this method before all other - * resources have been destroyed has undefined behavior. - * - * Failure to call this method, at present, has no adverse effects other than - * leaking memory. This may not always be the case; it's recommended that all - * embedders call this method when all other JSAPI operations have completed. - * - * It is currently not possible to initialize SpiderMonkey multiple times (that - * is, calling JS_Init/JSAPI methods/JS_ShutDown in that order, then doing so - * again). This restriction may eventually be lifted. - */ -extern JS_PUBLIC_API(void) -JS_ShutDown(void); - -#endif /* js_Initialization_h */ diff --git a/mac/include/spidermonkey/js/LegacyIntTypes.h b/mac/include/spidermonkey/js/LegacyIntTypes.h deleted file mode 100644 index 2c8498c8..00000000 --- a/mac/include/spidermonkey/js/LegacyIntTypes.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * This section typedefs the old 'native' types to the new types. - * These redefinitions are provided solely to allow JSAPI users to more easily - * transition to types. They are not to be used in the JSAPI, and - * new JSAPI user code should not use them. This mapping file may eventually - * be removed from SpiderMonkey, so don't depend on it in the long run. - */ - -/* - * BEWARE: Comity with other implementers of these types is not guaranteed. - * Indeed, if you use this header and third-party code defining these - * types, *expect* to encounter either compile errors or link errors, - * depending how these types are used and on the order of inclusion. - * It is safest to use only the types. - */ -#ifndef js_LegacyIntTypes_h -#define js_LegacyIntTypes_h - -#include - -#include "js-config.h" - -typedef uint8_t uint8; -typedef uint16_t uint16; -typedef uint32_t uint32; -typedef uint64_t uint64; - -/* - * On AIX 4.3, sys/inttypes.h (which is included by sys/types.h, a very - * common header file) defines the types int8, int16, int32, and int64. - * So we don't define these four types here to avoid conflicts in case - * the code also includes sys/types.h. - */ -#if defined(AIX) && defined(HAVE_SYS_INTTYPES_H) -#include -#else -typedef int8_t int8; -typedef int16_t int16; -typedef int32_t int32; -typedef int64_t int64; -#endif /* AIX && HAVE_SYS_INTTYPES_H */ - -typedef uint8_t JSUint8; -typedef uint16_t JSUint16; -typedef uint32_t JSUint32; -typedef uint64_t JSUint64; - -typedef int8_t JSInt8; -typedef int16_t JSInt16; -typedef int32_t JSInt32; -typedef int64_t JSInt64; - -#endif /* js_LegacyIntTypes_h */ diff --git a/mac/include/spidermonkey/js/MemoryMetrics.h b/mac/include/spidermonkey/js/MemoryMetrics.h deleted file mode 100644 index 9b5caa24..00000000 --- a/mac/include/spidermonkey/js/MemoryMetrics.h +++ /dev/null @@ -1,971 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_MemoryMetrics_h -#define js_MemoryMetrics_h - -// These declarations are highly likely to change in the future. Depend on them -// at your own risk. - -#include "mozilla/MemoryReporting.h" -#include "mozilla/PodOperations.h" -#include "mozilla/TypeTraits.h" - -#include - -#include "jsalloc.h" -#include "jspubtd.h" - -#include "js/HashTable.h" -#include "js/TracingAPI.h" -#include "js/Utility.h" -#include "js/Vector.h" - -class nsISupports; // Needed for ObjectPrivateVisitor. - -namespace JS { - -struct TabSizes -{ - enum Kind { - Objects, - Strings, - Private, - Other - }; - - TabSizes() { mozilla::PodZero(this); } - - void add(Kind kind, size_t n) { - switch (kind) { - case Objects: objects += n; break; - case Strings: strings += n; break; - case Private: private_ += n; break; - case Other: other += n; break; - default: MOZ_CRASH("bad TabSizes kind"); - } - } - - size_t objects; - size_t strings; - size_t private_; - size_t other; -}; - -/** These are the measurements used by Servo. */ -struct ServoSizes -{ - enum Kind { - GCHeapUsed, - GCHeapUnused, - GCHeapAdmin, - GCHeapDecommitted, - MallocHeap, - NonHeap, - Ignore - }; - - ServoSizes() { mozilla::PodZero(this); } - - void add(Kind kind, size_t n) { - switch (kind) { - case GCHeapUsed: gcHeapUsed += n; break; - case GCHeapUnused: gcHeapUnused += n; break; - case GCHeapAdmin: gcHeapAdmin += n; break; - case GCHeapDecommitted: gcHeapDecommitted += n; break; - case MallocHeap: mallocHeap += n; break; - case NonHeap: nonHeap += n; break; - case Ignore: /* do nothing */ break; - default: MOZ_CRASH("bad ServoSizes kind"); - } - } - - size_t gcHeapUsed; - size_t gcHeapUnused; - size_t gcHeapAdmin; - size_t gcHeapDecommitted; - size_t mallocHeap; - size_t nonHeap; -}; - -} // namespace JS - -namespace js { - -/** - * In memory reporting, we have concept of "sundries", line items which are too - * small to be worth reporting individually. Under some circumstances, a memory - * reporter gets tossed into the sundries bucket if it's smaller than - * MemoryReportingSundriesThreshold() bytes. - * - * We need to define this value here, rather than in the code which actually - * generates the memory reports, because NotableStringInfo uses this value. - */ -JS_FRIEND_API(size_t) MemoryReportingSundriesThreshold(); - -/** - * This hash policy avoids flattening ropes (which perturbs the site being - * measured and requires a JSContext) at the expense of doing a FULL ROPE COPY - * on every hash and match! Beware. - */ -struct InefficientNonFlatteningStringHashPolicy -{ - typedef JSString* Lookup; - static HashNumber hash(const Lookup& l); - static bool match(const JSString* const& k, const Lookup& l); -}; - -struct CStringHashPolicy -{ - typedef const char* Lookup; - static HashNumber hash(const Lookup& l); - static bool match(const char* const& k, const Lookup& l); -}; - -// This file features many classes with numerous size_t fields, and each such -// class has one or more methods that need to operate on all of these fields. -// Writing these individually is error-prone -- it's easy to add a new field -// without updating all the required methods. So we define a single macro list -// in each class to name the fields (and notable characteristics of them), and -// then use the following macros to transform those lists into the required -// methods. -// -// - The |tabKind| value is used when measuring TabSizes. -// -// - The |servoKind| value is used when measuring ServoSizes and also for -// the various sizeOfLiveGCThings() methods. -// -// In some classes, one or more of the macro arguments aren't used. We use '_' -// for those. -// -#define DECL_SIZE(tabKind, servoKind, mSize) size_t mSize; -#define ZERO_SIZE(tabKind, servoKind, mSize) mSize(0), -#define COPY_OTHER_SIZE(tabKind, servoKind, mSize) mSize(other.mSize), -#define ADD_OTHER_SIZE(tabKind, servoKind, mSize) mSize += other.mSize; -#define SUB_OTHER_SIZE(tabKind, servoKind, mSize) \ - MOZ_ASSERT(mSize >= other.mSize); \ - mSize -= other.mSize; -#define ADD_SIZE_TO_N(tabKind, servoKind, mSize) n += mSize; -#define ADD_SIZE_TO_N_IF_LIVE_GC_THING(tabKind, servoKind, mSize) \ - /* Avoid self-comparison warnings by comparing enums indirectly. */ \ - n += (mozilla::IsSame::value) \ - ? mSize \ - : 0; -#define ADD_TO_TAB_SIZES(tabKind, servoKind, mSize) sizes->add(JS::TabSizes::tabKind, mSize); -#define ADD_TO_SERVO_SIZES(tabKind, servoKind, mSize) sizes->add(JS::ServoSizes::servoKind, mSize); - -} // namespace js - -namespace JS { - -struct ClassInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(Objects, GCHeapUsed, objectsGCHeap) \ - macro(Objects, MallocHeap, objectsMallocHeapSlots) \ - macro(Objects, MallocHeap, objectsMallocHeapElementsNormal) \ - macro(Objects, MallocHeap, objectsMallocHeapElementsAsmJS) \ - macro(Objects, MallocHeap, objectsMallocHeapMisc) \ - macro(Objects, NonHeap, objectsNonHeapElementsNormal) \ - macro(Objects, NonHeap, objectsNonHeapElementsShared) \ - macro(Objects, NonHeap, objectsNonHeapElementsWasm) \ - macro(Objects, NonHeap, objectsNonHeapCodeWasm) - - ClassInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - wasmGuardPages(0) - {} - - void add(const ClassInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - } - - void subtract(const ClassInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE) - } - - size_t sizeOfAllThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n; - } - - bool isNotable() const { - static const size_t NotabilityThreshold = 16 * 1024; - return sizeOfAllThings() >= NotabilityThreshold; - } - - size_t sizeOfLiveGCThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - size_t wasmGuardPages; - -#undef FOR_EACH_SIZE -}; - -struct ShapeInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(Other, GCHeapUsed, shapesGCHeapTree) \ - macro(Other, GCHeapUsed, shapesGCHeapDict) \ - macro(Other, GCHeapUsed, shapesGCHeapBase) \ - macro(Other, MallocHeap, shapesMallocHeapTreeTables) \ - macro(Other, MallocHeap, shapesMallocHeapDictTables) \ - macro(Other, MallocHeap, shapesMallocHeapTreeKids) - - ShapeInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - void add(const ShapeInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - } - - void subtract(const ShapeInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE) - } - - size_t sizeOfAllThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n; - } - - size_t sizeOfLiveGCThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -/** - * Holds data about a notable class (one whose combined object and shape - * instances use more than a certain amount of memory) so we can report it - * individually. - * - * The only difference between this class and ClassInfo is that this class - * holds a copy of the filename. - */ -struct NotableClassInfo : public ClassInfo -{ - NotableClassInfo(); - NotableClassInfo(const char* className, const ClassInfo& info); - NotableClassInfo(NotableClassInfo&& info); - NotableClassInfo& operator=(NotableClassInfo&& info); - - ~NotableClassInfo() { - js_free(className_); - } - - char* className_; - - private: - NotableClassInfo(const NotableClassInfo& info) = delete; -}; - -/** Data for tracking JIT-code memory usage. */ -struct CodeSizes -{ -#define FOR_EACH_SIZE(macro) \ - macro(_, NonHeap, ion) \ - macro(_, NonHeap, baseline) \ - macro(_, NonHeap, regexp) \ - macro(_, NonHeap, other) \ - macro(_, NonHeap, unused) - - CodeSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -/** Data for tracking GC memory usage. */ -struct GCSizes -{ - // |nurseryDecommitted| is marked as NonHeap rather than GCHeapDecommitted - // because we don't consider the nursery to be part of the GC heap. -#define FOR_EACH_SIZE(macro) \ - macro(_, MallocHeap, marker) \ - macro(_, NonHeap, nurseryCommitted) \ - macro(_, MallocHeap, nurseryMallocedBuffers) \ - macro(_, MallocHeap, storeBufferVals) \ - macro(_, MallocHeap, storeBufferCells) \ - macro(_, MallocHeap, storeBufferSlots) \ - macro(_, MallocHeap, storeBufferWholeCells) \ - macro(_, MallocHeap, storeBufferGenerics) - - GCSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -/** - * This class holds information about the memory taken up by identical copies of - * a particular string. Multiple JSStrings may have their sizes aggregated - * together into one StringInfo object. Note that two strings with identical - * chars will not be aggregated together if one is a short string and the other - * is not. - */ -struct StringInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(Strings, GCHeapUsed, gcHeapLatin1) \ - macro(Strings, GCHeapUsed, gcHeapTwoByte) \ - macro(Strings, MallocHeap, mallocHeapLatin1) \ - macro(Strings, MallocHeap, mallocHeapTwoByte) - - StringInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - numCopies(0) - {} - - void add(const StringInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE); - numCopies++; - } - - void subtract(const StringInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE); - numCopies--; - } - - bool isNotable() const { - static const size_t NotabilityThreshold = 16 * 1024; - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n >= NotabilityThreshold; - } - - size_t sizeOfLiveGCThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - uint32_t numCopies; // How many copies of the string have we seen? - -#undef FOR_EACH_SIZE -}; - -/** - * Holds data about a notable string (one which, counting all duplicates, uses - * more than a certain amount of memory) so we can report it individually. - * - * The only difference between this class and StringInfo is that - * NotableStringInfo holds a copy of some or all of the string's chars. - */ -struct NotableStringInfo : public StringInfo -{ - static const size_t MAX_SAVED_CHARS = 1024; - - NotableStringInfo(); - NotableStringInfo(JSString* str, const StringInfo& info); - NotableStringInfo(NotableStringInfo&& info); - NotableStringInfo& operator=(NotableStringInfo&& info); - - ~NotableStringInfo() { - js_free(buffer); - } - - char* buffer; - size_t length; - - private: - NotableStringInfo(const NotableStringInfo& info) = delete; -}; - -/** - * This class holds information about the memory taken up by script sources - * from a particular file. - */ -struct ScriptSourceInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(_, MallocHeap, misc) - - ScriptSourceInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - numScripts(0) - {} - - void add(const ScriptSourceInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - numScripts++; - } - - void subtract(const ScriptSourceInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE) - numScripts--; - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - bool isNotable() const { - static const size_t NotabilityThreshold = 16 * 1024; - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n >= NotabilityThreshold; - } - - FOR_EACH_SIZE(DECL_SIZE) - uint32_t numScripts; // How many ScriptSources come from this file? (It - // can be more than one in XML files that have - // multiple scripts in CDATA sections.) -#undef FOR_EACH_SIZE -}; - -/** - * Holds data about a notable script source file (one whose combined - * script sources use more than a certain amount of memory) so we can report it - * individually. - * - * The only difference between this class and ScriptSourceInfo is that this - * class holds a copy of the filename. - */ -struct NotableScriptSourceInfo : public ScriptSourceInfo -{ - NotableScriptSourceInfo(); - NotableScriptSourceInfo(const char* filename, const ScriptSourceInfo& info); - NotableScriptSourceInfo(NotableScriptSourceInfo&& info); - NotableScriptSourceInfo& operator=(NotableScriptSourceInfo&& info); - - ~NotableScriptSourceInfo() { - js_free(filename_); - } - - char* filename_; - - private: - NotableScriptSourceInfo(const NotableScriptSourceInfo& info) = delete; -}; - -/** - * These measurements relate directly to the JSRuntime, and not to zones and - * compartments within it. - */ -struct RuntimeSizes -{ -#define FOR_EACH_SIZE(macro) \ - macro(_, MallocHeap, object) \ - macro(_, MallocHeap, atomsTable) \ - macro(_, MallocHeap, contexts) \ - macro(_, MallocHeap, temporary) \ - macro(_, MallocHeap, interpreterStack) \ - macro(_, MallocHeap, mathCache) \ - macro(_, MallocHeap, sharedImmutableStringsCache) \ - macro(_, MallocHeap, sharedIntlData) \ - macro(_, MallocHeap, uncompressedSourceCache) \ - macro(_, MallocHeap, scriptData) - - RuntimeSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - scriptSourceInfo(), - code(), - gc(), - notableScriptSources() - { - allScriptSources = js_new(); - if (!allScriptSources || !allScriptSources->init()) - MOZ_CRASH("oom"); - } - - ~RuntimeSizes() { - // |allScriptSources| is usually deleted and set to nullptr before this - // destructor runs. But there are failure cases due to OOMs that may - // prevent that, so it doesn't hurt to try again here. - js_delete(allScriptSources); - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - scriptSourceInfo.addToServoSizes(sizes); - code.addToServoSizes(sizes); - gc.addToServoSizes(sizes); - } - - // The script source measurements in |scriptSourceInfo| are initially for - // all script sources. At the end, if the measurement granularity is - // FineGrained, we subtract the measurements of the notable script sources - // and move them into |notableScriptSources|. - FOR_EACH_SIZE(DECL_SIZE) - ScriptSourceInfo scriptSourceInfo; - CodeSizes code; - GCSizes gc; - - typedef js::HashMap ScriptSourcesHashMap; - - // |allScriptSources| is only used transiently. During the reporting phase - // it is filled with info about every script source in the runtime. It's - // then used to fill in |notableScriptSources| (which actually gets - // reported), and immediately discarded afterwards. - ScriptSourcesHashMap* allScriptSources; - js::Vector notableScriptSources; - -#undef FOR_EACH_SIZE -}; - -struct UnusedGCThingSizes -{ -#define FOR_EACH_SIZE(macro) \ - macro(Other, GCHeapUnused, object) \ - macro(Other, GCHeapUnused, script) \ - macro(Other, GCHeapUnused, lazyScript) \ - macro(Other, GCHeapUnused, shape) \ - macro(Other, GCHeapUnused, baseShape) \ - macro(Other, GCHeapUnused, objectGroup) \ - macro(Other, GCHeapUnused, string) \ - macro(Other, GCHeapUnused, symbol) \ - macro(Other, GCHeapUnused, jitcode) \ - macro(Other, GCHeapUnused, scope) - - UnusedGCThingSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - UnusedGCThingSizes(UnusedGCThingSizes&& other) - : FOR_EACH_SIZE(COPY_OTHER_SIZE) - dummy() - {} - - void addToKind(JS::TraceKind kind, intptr_t n) { - switch (kind) { - case JS::TraceKind::Object: object += n; break; - case JS::TraceKind::String: string += n; break; - case JS::TraceKind::Symbol: symbol += n; break; - case JS::TraceKind::Script: script += n; break; - case JS::TraceKind::Shape: shape += n; break; - case JS::TraceKind::BaseShape: baseShape += n; break; - case JS::TraceKind::JitCode: jitcode += n; break; - case JS::TraceKind::LazyScript: lazyScript += n; break; - case JS::TraceKind::ObjectGroup: objectGroup += n; break; - case JS::TraceKind::Scope: scope += n; break; - default: - MOZ_CRASH("Bad trace kind for UnusedGCThingSizes"); - } - } - - void addSizes(const UnusedGCThingSizes& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - } - - size_t totalSize() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n; - } - - void addToTabSizes(JS::TabSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(JS::ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -struct ZoneStats -{ -#define FOR_EACH_SIZE(macro) \ - macro(Other, GCHeapUsed, symbolsGCHeap) \ - macro(Other, GCHeapAdmin, gcHeapArenaAdmin) \ - macro(Other, GCHeapUsed, lazyScriptsGCHeap) \ - macro(Other, MallocHeap, lazyScriptsMallocHeap) \ - macro(Other, GCHeapUsed, jitCodesGCHeap) \ - macro(Other, GCHeapUsed, objectGroupsGCHeap) \ - macro(Other, MallocHeap, objectGroupsMallocHeap) \ - macro(Other, GCHeapUsed, scopesGCHeap) \ - macro(Other, MallocHeap, scopesMallocHeap) \ - macro(Other, MallocHeap, typePool) \ - macro(Other, MallocHeap, baselineStubsOptimized) \ - macro(Other, MallocHeap, uniqueIdMap) \ - macro(Other, MallocHeap, shapeTables) - - ZoneStats() - : FOR_EACH_SIZE(ZERO_SIZE) - unusedGCThings(), - stringInfo(), - shapeInfo(), - extra(), - allStrings(nullptr), - notableStrings(), - isTotals(true) - {} - - ZoneStats(ZoneStats&& other) - : FOR_EACH_SIZE(COPY_OTHER_SIZE) - unusedGCThings(mozilla::Move(other.unusedGCThings)), - stringInfo(mozilla::Move(other.stringInfo)), - shapeInfo(mozilla::Move(other.shapeInfo)), - extra(other.extra), - allStrings(other.allStrings), - notableStrings(mozilla::Move(other.notableStrings)), - isTotals(other.isTotals) - { - other.allStrings = nullptr; - MOZ_ASSERT(!other.isTotals); - } - - ~ZoneStats() { - // |allStrings| is usually deleted and set to nullptr before this - // destructor runs. But there are failure cases due to OOMs that may - // prevent that, so it doesn't hurt to try again here. - js_delete(allStrings); - } - - bool initStrings(JSRuntime* rt); - - void addSizes(const ZoneStats& other) { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_OTHER_SIZE) - unusedGCThings.addSizes(other.unusedGCThings); - stringInfo.add(other.stringInfo); - shapeInfo.add(other.shapeInfo); - } - - size_t sizeOfLiveGCThings() const { - MOZ_ASSERT(isTotals); - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - n += stringInfo.sizeOfLiveGCThings(); - n += shapeInfo.sizeOfLiveGCThings(); - return n; - } - - void addToTabSizes(JS::TabSizes* sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - unusedGCThings.addToTabSizes(sizes); - stringInfo.addToTabSizes(sizes); - shapeInfo.addToTabSizes(sizes); - } - - void addToServoSizes(JS::ServoSizes *sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - unusedGCThings.addToServoSizes(sizes); - stringInfo.addToServoSizes(sizes); - shapeInfo.addToServoSizes(sizes); - } - - // These string measurements are initially for all strings. At the end, - // if the measurement granularity is FineGrained, we subtract the - // measurements of the notable script sources and move them into - // |notableStrings|. - FOR_EACH_SIZE(DECL_SIZE) - UnusedGCThingSizes unusedGCThings; - StringInfo stringInfo; - ShapeInfo shapeInfo; - void* extra; // This field can be used by embedders. - - typedef js::HashMap StringsHashMap; - - // |allStrings| is only used transiently. During the zone traversal it is - // filled with info about every string in the zone. It's then used to fill - // in |notableStrings| (which actually gets reported), and immediately - // discarded afterwards. - StringsHashMap* allStrings; - js::Vector notableStrings; - bool isTotals; - -#undef FOR_EACH_SIZE -}; - -struct CompartmentStats -{ - // We assume that |objectsPrivate| is on the malloc heap, but it's not - // actually guaranteed. But for Servo, at least, it's a moot point because - // it doesn't provide an ObjectPrivateVisitor so the value will always be - // zero. -#define FOR_EACH_SIZE(macro) \ - macro(Private, MallocHeap, objectsPrivate) \ - macro(Other, GCHeapUsed, scriptsGCHeap) \ - macro(Other, MallocHeap, scriptsMallocHeapData) \ - macro(Other, MallocHeap, baselineData) \ - macro(Other, MallocHeap, baselineStubsFallback) \ - macro(Other, MallocHeap, ionData) \ - macro(Other, MallocHeap, typeInferenceTypeScripts) \ - macro(Other, MallocHeap, typeInferenceAllocationSiteTables) \ - macro(Other, MallocHeap, typeInferenceArrayTypeTables) \ - macro(Other, MallocHeap, typeInferenceObjectTypeTables) \ - macro(Other, MallocHeap, compartmentObject) \ - macro(Other, MallocHeap, compartmentTables) \ - macro(Other, MallocHeap, innerViewsTable) \ - macro(Other, MallocHeap, lazyArrayBuffersTable) \ - macro(Other, MallocHeap, objectMetadataTable) \ - macro(Other, MallocHeap, crossCompartmentWrappersTable) \ - macro(Other, MallocHeap, regexpCompartment) \ - macro(Other, MallocHeap, savedStacksSet) \ - macro(Other, MallocHeap, varNamesSet) \ - macro(Other, MallocHeap, nonSyntacticLexicalScopesTable) \ - macro(Other, MallocHeap, jitCompartment) \ - macro(Other, MallocHeap, privateData) - - CompartmentStats() - : FOR_EACH_SIZE(ZERO_SIZE) - classInfo(), - extra(), - allClasses(nullptr), - notableClasses(), - isTotals(true) - {} - - CompartmentStats(CompartmentStats&& other) - : FOR_EACH_SIZE(COPY_OTHER_SIZE) - classInfo(mozilla::Move(other.classInfo)), - extra(other.extra), - allClasses(other.allClasses), - notableClasses(mozilla::Move(other.notableClasses)), - isTotals(other.isTotals) - { - other.allClasses = nullptr; - MOZ_ASSERT(!other.isTotals); - } - - CompartmentStats(const CompartmentStats&) = delete; // disallow copying - - ~CompartmentStats() { - // |allClasses| is usually deleted and set to nullptr before this - // destructor runs. But there are failure cases due to OOMs that may - // prevent that, so it doesn't hurt to try again here. - js_delete(allClasses); - } - - bool initClasses(JSRuntime* rt); - - void addSizes(const CompartmentStats& other) { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_OTHER_SIZE) - classInfo.add(other.classInfo); - } - - size_t sizeOfLiveGCThings() const { - MOZ_ASSERT(isTotals); - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - n += classInfo.sizeOfLiveGCThings(); - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_TAB_SIZES); - classInfo.addToTabSizes(sizes); - } - - void addToServoSizes(ServoSizes *sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES); - classInfo.addToServoSizes(sizes); - } - - // The class measurements in |classInfo| are initially for all classes. At - // the end, if the measurement granularity is FineGrained, we subtract the - // measurements of the notable classes and move them into |notableClasses|. - FOR_EACH_SIZE(DECL_SIZE) - ClassInfo classInfo; - void* extra; // This field can be used by embedders. - - typedef js::HashMap ClassesHashMap; - - // These are similar to |allStrings| and |notableStrings| in ZoneStats. - ClassesHashMap* allClasses; - js::Vector notableClasses; - bool isTotals; - -#undef FOR_EACH_SIZE -}; - -typedef js::Vector CompartmentStatsVector; -typedef js::Vector ZoneStatsVector; - -struct RuntimeStats -{ - // |gcHeapChunkTotal| is ignored because it's the sum of all the other - // values. |gcHeapGCThings| is ignored because it's the sum of some of the - // values from the zones and compartments. Both of those values are not - // reported directly, but are just present for sanity-checking other - // values. -#define FOR_EACH_SIZE(macro) \ - macro(_, Ignore, gcHeapChunkTotal) \ - macro(_, GCHeapDecommitted, gcHeapDecommittedArenas) \ - macro(_, GCHeapUnused, gcHeapUnusedChunks) \ - macro(_, GCHeapUnused, gcHeapUnusedArenas) \ - macro(_, GCHeapAdmin, gcHeapChunkAdmin) \ - macro(_, Ignore, gcHeapGCThings) - - explicit RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) - : FOR_EACH_SIZE(ZERO_SIZE) - runtime(), - cTotals(), - zTotals(), - compartmentStatsVector(), - zoneStatsVector(), - currZoneStats(nullptr), - mallocSizeOf_(mallocSizeOf) - {} - - // Here's a useful breakdown of the GC heap. - // - // - rtStats.gcHeapChunkTotal - // - decommitted bytes - // - rtStats.gcHeapDecommittedArenas (decommitted arenas in non-empty chunks) - // - unused bytes - // - rtStats.gcHeapUnusedChunks (empty chunks) - // - rtStats.gcHeapUnusedArenas (empty arenas within non-empty chunks) - // - rtStats.zTotals.unusedGCThings.totalSize() (empty GC thing slots within non-empty arenas) - // - used bytes - // - rtStats.gcHeapChunkAdmin - // - rtStats.zTotals.gcHeapArenaAdmin - // - rtStats.gcHeapGCThings (in-use GC things) - // == rtStats.zTotals.sizeOfLiveGCThings() + rtStats.cTotals.sizeOfLiveGCThings() - // - // It's possible that some arenas in empty chunks may be decommitted, but - // we don't count those under rtStats.gcHeapDecommittedArenas because (a) - // it's rare, and (b) this means that rtStats.gcHeapUnusedChunks is a - // multiple of the chunk size, which is good. - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - runtime.addToServoSizes(sizes); - } - - FOR_EACH_SIZE(DECL_SIZE) - - RuntimeSizes runtime; - - CompartmentStats cTotals; // The sum of this runtime's compartments' measurements. - ZoneStats zTotals; // The sum of this runtime's zones' measurements. - - CompartmentStatsVector compartmentStatsVector; - ZoneStatsVector zoneStatsVector; - - ZoneStats* currZoneStats; - - mozilla::MallocSizeOf mallocSizeOf_; - - virtual void initExtraCompartmentStats(JSCompartment* c, CompartmentStats* cstats) = 0; - virtual void initExtraZoneStats(JS::Zone* zone, ZoneStats* zstats) = 0; - -#undef FOR_EACH_SIZE -}; - -class ObjectPrivateVisitor -{ - public: - // Within CollectRuntimeStats, this method is called for each JS object - // that has an nsISupports pointer. - virtual size_t sizeOfIncludingThis(nsISupports* aSupports) = 0; - - // A callback that gets a JSObject's nsISupports pointer, if it has one. - // Note: this function does *not* addref |iface|. - typedef bool(*GetISupportsFun)(JSObject* obj, nsISupports** iface); - GetISupportsFun getISupports_; - - explicit ObjectPrivateVisitor(GetISupportsFun getISupports) - : getISupports_(getISupports) - {} -}; - -extern JS_PUBLIC_API(bool) -CollectRuntimeStats(JSContext* cx, RuntimeStats* rtStats, ObjectPrivateVisitor* opv, bool anonymize); - -extern JS_PUBLIC_API(size_t) -SystemCompartmentCount(JSContext* cx); - -extern JS_PUBLIC_API(size_t) -UserCompartmentCount(JSContext* cx); - -extern JS_PUBLIC_API(size_t) -PeakSizeOfTemporary(const JSContext* cx); - -extern JS_PUBLIC_API(bool) -AddSizeOfTab(JSContext* cx, JS::HandleObject obj, mozilla::MallocSizeOf mallocSizeOf, - ObjectPrivateVisitor* opv, TabSizes* sizes); - -extern JS_PUBLIC_API(bool) -AddServoSizeOf(JSContext* cx, mozilla::MallocSizeOf mallocSizeOf, - ObjectPrivateVisitor *opv, ServoSizes *sizes); - -} // namespace JS - -#undef DECL_SIZE -#undef ZERO_SIZE -#undef COPY_OTHER_SIZE -#undef ADD_OTHER_SIZE -#undef SUB_OTHER_SIZE -#undef ADD_SIZE_TO_N -#undef ADD_SIZE_TO_N_IF_LIVE_GC_THING -#undef ADD_TO_TAB_SIZES - -#endif /* js_MemoryMetrics_h */ diff --git a/mac/include/spidermonkey/js/Principals.h b/mac/include/spidermonkey/js/Principals.h deleted file mode 100644 index cf6c813a..00000000 --- a/mac/include/spidermonkey/js/Principals.h +++ /dev/null @@ -1,132 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JSPrincipals and related interfaces. */ - -#ifndef js_Principals_h -#define js_Principals_h - -#include "mozilla/Atomics.h" - -#include - -#include "jspubtd.h" - -#include "js/StructuredClone.h" - -namespace js { - struct PerformanceGroup; -} // namespace js - -struct JSPrincipals { - /* Don't call "destroy"; use reference counting macros below. */ - mozilla::Atomic refcount; - -#ifdef JS_DEBUG - /* A helper to facilitate principals debugging. */ - uint32_t debugToken; -#endif - - JSPrincipals() : refcount(0) {} - - void setDebugToken(uint32_t token) { -# ifdef JS_DEBUG - debugToken = token; -# endif - } - - /* - * Write the principals with the given |writer|. Return false on failure, - * true on success. - */ - virtual bool write(JSContext* cx, JSStructuredCloneWriter* writer) = 0; - - /* - * This is not defined by the JS engine but should be provided by the - * embedding. - */ - JS_PUBLIC_API(void) dump(); -}; - -extern JS_PUBLIC_API(void) -JS_HoldPrincipals(JSPrincipals* principals); - -extern JS_PUBLIC_API(void) -JS_DropPrincipals(JSContext* cx, JSPrincipals* principals); - -// Return whether the first principal subsumes the second. The exact meaning of -// 'subsumes' is left up to the browser. Subsumption is checked inside the JS -// engine when determining, e.g., which stack frames to display in a backtrace. -typedef bool -(* JSSubsumesOp)(JSPrincipals* first, JSPrincipals* second); - -/* - * Used to check if a CSP instance wants to disable eval() and friends. - * See js_CheckCSPPermitsJSAction() in jsobj. - */ -typedef bool -(* JSCSPEvalChecker)(JSContext* cx); - -struct JSSecurityCallbacks { - JSCSPEvalChecker contentSecurityPolicyAllows; - JSSubsumesOp subsumes; -}; - -extern JS_PUBLIC_API(void) -JS_SetSecurityCallbacks(JSContext* cx, const JSSecurityCallbacks* callbacks); - -extern JS_PUBLIC_API(const JSSecurityCallbacks*) -JS_GetSecurityCallbacks(JSContext* cx); - -/* - * Code running with "trusted" principals will be given a deeper stack - * allocation than ordinary scripts. This allows trusted script to run after - * untrusted script has exhausted the stack. This function sets the - * runtime-wide trusted principal. - * - * This principals is not held (via JS_HoldPrincipals/JS_DropPrincipals). - * Instead, the caller must ensure that the given principals stays valid for as - * long as 'cx' may point to it. If the principals would be destroyed before - * 'cx', JS_SetTrustedPrincipals must be called again, passing nullptr for - * 'prin'. - */ -extern JS_PUBLIC_API(void) -JS_SetTrustedPrincipals(JSContext* cx, JSPrincipals* prin); - -typedef void -(* JSDestroyPrincipalsOp)(JSPrincipals* principals); - -/* - * Initialize the callback that is called to destroy JSPrincipals instance - * when its reference counter drops to zero. The initialization can be done - * only once per JS runtime. - */ -extern JS_PUBLIC_API(void) -JS_InitDestroyPrincipalsCallback(JSContext* cx, JSDestroyPrincipalsOp destroyPrincipals); - -/* - * Read a JSPrincipals instance from the given |reader| and initialize the out - * paratemer |outPrincipals| to the JSPrincipals instance read. - * - * Return false on failure, true on success. The |outPrincipals| parameter - * should not be modified if false is returned. - * - * The caller is not responsible for calling JS_HoldPrincipals on the resulting - * JSPrincipals instance, the JSReadPrincipalsOp must increment the refcount of - * the resulting JSPrincipals on behalf of the caller. - */ -using JSReadPrincipalsOp = bool (*)(JSContext* cx, JSStructuredCloneReader* reader, - JSPrincipals** outPrincipals); - -/* - * Initialize the callback that is called to read JSPrincipals instances from a - * buffer. The initialization can be done only once per JS runtime. - */ -extern JS_PUBLIC_API(void) -JS_InitReadPrincipalsCallback(JSContext* cx, JSReadPrincipalsOp read); - - -#endif /* js_Principals_h */ diff --git a/mac/include/spidermonkey/js/ProfilingFrameIterator.h b/mac/include/spidermonkey/js/ProfilingFrameIterator.h deleted file mode 100644 index d082213d..00000000 --- a/mac/include/spidermonkey/js/ProfilingFrameIterator.h +++ /dev/null @@ -1,203 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_ProfilingFrameIterator_h -#define js_ProfilingFrameIterator_h - -#include "mozilla/Alignment.h" -#include "mozilla/Maybe.h" - -#include "jsbytecode.h" -#include "js/GCAPI.h" -#include "js/TypeDecls.h" -#include "js/Utility.h" - -struct JSContext; -struct JSRuntime; -class JSScript; - -namespace js { - class Activation; - namespace jit { - class JitActivation; - class JitProfilingFrameIterator; - class JitcodeGlobalEntry; - } // namespace jit - namespace wasm { - class ProfilingFrameIterator; - } // namespace wasm -} // namespace js - -namespace JS { - -struct ForEachTrackedOptimizationAttemptOp; -struct ForEachTrackedOptimizationTypeInfoOp; - -// This iterator can be used to walk the stack of a thread suspended at an -// arbitrary pc. To provide acurate results, profiling must have been enabled -// (via EnableRuntimeProfilingStack) before executing the callstack being -// unwound. -// -// Note that the caller must not do anything that could cause GC to happen while -// the iterator is alive, since this could invalidate Ion code and cause its -// contents to become out of date. -class JS_PUBLIC_API(ProfilingFrameIterator) -{ - JSRuntime* rt_; - uint32_t sampleBufferGen_; - js::Activation* activation_; - - // When moving past a JitActivation, we need to save the prevJitTop - // from it to use as the exit-frame pointer when the next caller jit - // activation (if any) comes around. - void* savedPrevJitTop_; - - JS::AutoCheckCannotGC nogc_; - - static const unsigned StorageSpace = 8 * sizeof(void*); - mozilla::AlignedStorage storage_; - js::wasm::ProfilingFrameIterator& wasmIter() { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isWasm()); - return *reinterpret_cast(storage_.addr()); - } - const js::wasm::ProfilingFrameIterator& wasmIter() const { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isWasm()); - return *reinterpret_cast(storage_.addr()); - } - - js::jit::JitProfilingFrameIterator& jitIter() { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isJit()); - return *reinterpret_cast(storage_.addr()); - } - - const js::jit::JitProfilingFrameIterator& jitIter() const { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isJit()); - return *reinterpret_cast(storage_.addr()); - } - - void settle(); - - bool hasSampleBufferGen() const { - return sampleBufferGen_ != UINT32_MAX; - } - - public: - struct RegisterState - { - RegisterState() : pc(nullptr), sp(nullptr), lr(nullptr) {} - void* pc; - void* sp; - void* lr; - }; - - ProfilingFrameIterator(JSContext* cx, const RegisterState& state, - uint32_t sampleBufferGen = UINT32_MAX); - ~ProfilingFrameIterator(); - void operator++(); - bool done() const { return !activation_; } - - // Assuming the stack grows down (we do), the return value: - // - always points into the stack - // - is weakly monotonically increasing (may be equal for successive frames) - // - will compare greater than newer native and psuedo-stack frame addresses - // and less than older native and psuedo-stack frame addresses - void* stackAddress() const; - - enum FrameKind - { - Frame_Baseline, - Frame_Ion, - Frame_Wasm - }; - - struct Frame - { - FrameKind kind; - void* stackAddress; - void* returnAddress; - void* activation; - UniqueChars label; - }; - - bool isWasm() const; - bool isJit() const; - - uint32_t extractStack(Frame* frames, uint32_t offset, uint32_t end) const; - - mozilla::Maybe getPhysicalFrameWithoutLabel() const; - - private: - mozilla::Maybe getPhysicalFrameAndEntry(js::jit::JitcodeGlobalEntry* entry) const; - - void iteratorConstruct(const RegisterState& state); - void iteratorConstruct(); - void iteratorDestroy(); - bool iteratorDone(); -}; - -JS_FRIEND_API(bool) -IsProfilingEnabledForContext(JSContext* cx); - -/** - * After each sample run, this method should be called with the latest sample - * buffer generation, and the lapCount. It will update corresponding fields on - * JSRuntime. - * - * See fields |profilerSampleBufferGen|, |profilerSampleBufferLapCount| on - * JSRuntime for documentation about what these values are used for. - */ -JS_FRIEND_API(void) -UpdateJSContextProfilerSampleBufferGen(JSContext* cx, uint32_t generation, - uint32_t lapCount); - -struct ForEachProfiledFrameOp -{ - // A handle to the underlying JitcodeGlobalEntry, so as to avoid repeated - // lookups on JitcodeGlobalTable. - class MOZ_STACK_CLASS FrameHandle - { - friend JS_PUBLIC_API(void) ForEachProfiledFrame(JSContext* cx, void* addr, - ForEachProfiledFrameOp& op); - - JSRuntime* rt_; - js::jit::JitcodeGlobalEntry& entry_; - void* addr_; - void* canonicalAddr_; - const char* label_; - uint32_t depth_; - mozilla::Maybe optsIndex_; - - FrameHandle(JSRuntime* rt, js::jit::JitcodeGlobalEntry& entry, void* addr, - const char* label, uint32_t depth); - - void updateHasTrackedOptimizations(); - - public: - const char* label() const { return label_; } - uint32_t depth() const { return depth_; } - bool hasTrackedOptimizations() const { return optsIndex_.isSome(); } - void* canonicalAddress() const { return canonicalAddr_; } - - ProfilingFrameIterator::FrameKind frameKind() const; - void forEachOptimizationAttempt(ForEachTrackedOptimizationAttemptOp& op, - JSScript** scriptOut, jsbytecode** pcOut) const; - void forEachOptimizationTypeInfo(ForEachTrackedOptimizationTypeInfoOp& op) const; - }; - - // Called once per frame. - virtual void operator()(const FrameHandle& frame) = 0; -}; - -JS_PUBLIC_API(void) -ForEachProfiledFrame(JSContext* cx, void* addr, ForEachProfiledFrameOp& op); - -} // namespace JS - -#endif /* js_ProfilingFrameIterator_h */ diff --git a/mac/include/spidermonkey/js/ProfilingStack.h b/mac/include/spidermonkey/js/ProfilingStack.h deleted file mode 100644 index 6b6c9701..00000000 --- a/mac/include/spidermonkey/js/ProfilingStack.h +++ /dev/null @@ -1,208 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_ProfilingStack_h -#define js_ProfilingStack_h - -#include "jsbytecode.h" -#include "jstypes.h" -#include "js/TypeDecls.h" - -#include "js/Utility.h" - -struct JSRuntime; -class JSTracer; - -namespace js { - -// A call stack can be specified to the JS engine such that all JS entry/exits -// to functions push/pop an entry to/from the specified stack. -// -// For more detailed information, see vm/SPSProfiler.h. -// -class ProfileEntry -{ - // All fields are marked volatile to prevent the compiler from re-ordering - // instructions. Namely this sequence: - // - // entry[size] = ...; - // size++; - // - // If the size modification were somehow reordered before the stores, then - // if a sample were taken it would be examining bogus information. - // - // A ProfileEntry represents both a C++ profile entry and a JS one. - - // Descriptive string of this entry. - const char * volatile string; - - // Stack pointer for non-JS entries, the script pointer otherwise. - void * volatile spOrScript; - - // Line number for non-JS entries, the bytecode offset otherwise. - int32_t volatile lineOrPcOffset; - - // General purpose storage describing this frame. - uint32_t volatile flags_; - - public: - // These traits are bit masks. Make sure they're powers of 2. - enum Flags : uint32_t { - // Indicate whether a profile entry represents a CPP frame. If not set, - // a JS frame is assumed by default. You're not allowed to publicly - // change the frame type. Instead, initialize the ProfileEntry as either - // a JS or CPP frame with `initJsFrame` or `initCppFrame` respectively. - IS_CPP_ENTRY = 0x01, - - // Indicate that copying the frame label is not necessary when taking a - // sample of the pseudostack. - FRAME_LABEL_COPY = 0x02, - - // This ProfileEntry is a dummy entry indicating the start of a run - // of JS pseudostack entries. - BEGIN_PSEUDO_JS = 0x04, - - // This flag is used to indicate that an interpreter JS entry has OSR-ed - // into baseline. - OSR = 0x08, - - // Union of all flags. - ALL = IS_CPP_ENTRY|FRAME_LABEL_COPY|BEGIN_PSEUDO_JS|OSR, - - // Mask for removing all flags except the category information. - CATEGORY_MASK = ~ALL - }; - - // Keep these in sync with devtools/client/performance/modules/categories.js - enum class Category : uint32_t { - OTHER = 0x10, - CSS = 0x20, - JS = 0x40, - GC = 0x80, - CC = 0x100, - NETWORK = 0x200, - GRAPHICS = 0x400, - STORAGE = 0x800, - EVENTS = 0x1000, - - FIRST = OTHER, - LAST = EVENTS - }; - - static_assert((static_cast(Category::FIRST) & Flags::ALL) == 0, - "The category bitflags should not intersect with the other flags!"); - - // All of these methods are marked with the 'volatile' keyword because SPS's - // representation of the stack is stored such that all ProfileEntry - // instances are volatile. These methods would not be available unless they - // were marked as volatile as well. - - bool isCpp() const volatile { return hasFlag(IS_CPP_ENTRY); } - bool isJs() const volatile { return !isCpp(); } - - bool isCopyLabel() const volatile { return hasFlag(FRAME_LABEL_COPY); } - - void setLabel(const char* aString) volatile { string = aString; } - const char* label() const volatile { return string; } - - void initJsFrame(JSScript* aScript, jsbytecode* aPc) volatile { - flags_ = 0; - spOrScript = aScript; - setPC(aPc); - } - void initCppFrame(void* aSp, uint32_t aLine) volatile { - flags_ = IS_CPP_ENTRY; - spOrScript = aSp; - lineOrPcOffset = static_cast(aLine); - } - - void setFlag(uint32_t flag) volatile { - MOZ_ASSERT(flag != IS_CPP_ENTRY); - flags_ |= flag; - } - void unsetFlag(uint32_t flag) volatile { - MOZ_ASSERT(flag != IS_CPP_ENTRY); - flags_ &= ~flag; - } - bool hasFlag(uint32_t flag) const volatile { - return bool(flags_ & flag); - } - - uint32_t flags() const volatile { - return flags_; - } - - uint32_t category() const volatile { - return flags_ & CATEGORY_MASK; - } - void setCategory(Category c) volatile { - MOZ_ASSERT(c >= Category::FIRST); - MOZ_ASSERT(c <= Category::LAST); - flags_ &= ~CATEGORY_MASK; - setFlag(static_cast(c)); - } - - void setOSR() volatile { - MOZ_ASSERT(isJs()); - setFlag(OSR); - } - void unsetOSR() volatile { - MOZ_ASSERT(isJs()); - unsetFlag(OSR); - } - bool isOSR() const volatile { - return hasFlag(OSR); - } - - void* stackAddress() const volatile { - MOZ_ASSERT(!isJs()); - return spOrScript; - } - JSScript* script() const volatile; - uint32_t line() const volatile { - MOZ_ASSERT(!isJs()); - return static_cast(lineOrPcOffset); - } - - // Note that the pointer returned might be invalid. - JSScript* rawScript() const volatile { - MOZ_ASSERT(isJs()); - return (JSScript*)spOrScript; - } - - // We can't know the layout of JSScript, so look in vm/SPSProfiler.cpp. - JS_FRIEND_API(jsbytecode*) pc() const volatile; - JS_FRIEND_API(void) setPC(jsbytecode* pc) volatile; - - void trace(JSTracer* trc); - - // The offset of a pc into a script's code can actually be 0, so to - // signify a nullptr pc, use a -1 index. This is checked against in - // pc() and setPC() to set/get the right pc. - static const int32_t NullPCOffset = -1; - - static size_t offsetOfLabel() { return offsetof(ProfileEntry, string); } - static size_t offsetOfSpOrScript() { return offsetof(ProfileEntry, spOrScript); } - static size_t offsetOfLineOrPcOffset() { return offsetof(ProfileEntry, lineOrPcOffset); } - static size_t offsetOfFlags() { return offsetof(ProfileEntry, flags_); } -}; - -JS_FRIEND_API(void) -SetContextProfilingStack(JSContext* cx, ProfileEntry* stack, uint32_t* size, - uint32_t max); - -JS_FRIEND_API(void) -EnableContextProfilingStack(JSContext* cx, bool enabled); - -JS_FRIEND_API(void) -RegisterContextProfilingEventMarker(JSContext* cx, void (*fn)(const char*)); - -JS_FRIEND_API(jsbytecode*) -ProfilingGetPC(JSContext* cx, JSScript* script, void* ip); - -} // namespace js - -#endif /* js_ProfilingStack_h */ diff --git a/mac/include/spidermonkey/js/Proxy.h b/mac/include/spidermonkey/js/Proxy.h deleted file mode 100644 index 3e95538d..00000000 --- a/mac/include/spidermonkey/js/Proxy.h +++ /dev/null @@ -1,632 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Proxy_h -#define js_Proxy_h - -#include "mozilla/Maybe.h" - -#include "jsfriendapi.h" - -#include "js/CallNonGenericMethod.h" -#include "js/Class.h" - -namespace js { - -using JS::AutoIdVector; -using JS::CallArgs; -using JS::Handle; -using JS::HandleId; -using JS::HandleObject; -using JS::HandleValue; -using JS::IsAcceptableThis; -using JS::MutableHandle; -using JS::MutableHandleObject; -using JS::MutableHandleValue; -using JS::NativeImpl; -using JS::ObjectOpResult; -using JS::PrivateValue; -using JS::PropertyDescriptor; -using JS::Value; - -class RegExpGuard; -class JS_FRIEND_API(Wrapper); - -/* - * A proxy is a JSObject with highly customizable behavior. ES6 specifies a - * single kind of proxy, but the customization mechanisms we use to implement - * ES6 Proxy objects are also useful wherever an object with weird behavior is - * wanted. Proxies are used to implement: - * - * - the scope objects used by the Debugger's frame.eval() method - * (see js::GetDebugScopeForFunction) - * - * - the khuey hack, whereby a whole compartment can be blown away - * even if other compartments hold references to objects in it - * (see js::NukeCrossCompartmentWrappers) - * - * - XPConnect security wrappers, which protect chrome from malicious content - * (js/xpconnect/wrappers) - * - * - DOM objects with special property behavior, like named getters - * (dom/bindings/Codegen.py generates these proxies from WebIDL) - * - * - semi-transparent use of objects that live in other processes - * (CPOWs, implemented in js/ipc) - * - * ### Proxies and internal methods - * - * ES2016 specifies 13 internal methods. The runtime semantics of just - * about everything a script can do to an object is specified in terms - * of these internal methods. For example: - * - * JS code ES6 internal method that gets called - * --------------------------- -------------------------------- - * obj.prop obj.[[Get]](obj, "prop") - * "prop" in obj obj.[[HasProperty]]("prop") - * new obj() obj.[[Construct]]() - * - * With regard to the implementation of these internal methods, there are three - * very different kinds of object in SpiderMonkey. - * - * 1. Native objects' internal methods are implemented in vm/NativeObject.cpp, - * with duplicate (but functionally identical) implementations scattered - * through the ICs and JITs. - * - * 2. Certain non-native objects have internal methods that are implemented as - * magical js::ObjectOps hooks. We're trying to get rid of these. - * - * 3. All other objects are proxies. A proxy's internal methods are - * implemented in C++, as the virtual methods of a C++ object stored on the - * proxy, known as its handler. - * - * This means that just about anything you do to a proxy will end up going - * through a C++ virtual method call. Possibly several. There's no reason the - * JITs and ICs can't specialize for particular proxies, based on the handler; - * but currently we don't do much of this, so the virtual method overhead - * typically is actually incurred. - * - * ### The proxy handler hierarchy - * - * A major use case for proxies is to forward each internal method call to - * another object, known as its target. The target can be an arbitrary JS - * object. Not every proxy has the notion of a target, however. - * - * To minimize code duplication, a set of abstract proxy handler classes is - * provided, from which other handlers may inherit. These abstract classes are - * organized in the following hierarchy: - * - * BaseProxyHandler - * | - * Wrapper // has a target, can be unwrapped to reveal - * | // target (see js::CheckedUnwrap) - * | - * CrossCompartmentWrapper // target is in another compartment; - * // implements membrane between compartments - * - * Example: Some DOM objects (including all the arraylike DOM objects) are - * implemented as proxies. Since these objects don't need to forward operations - * to any underlying JS object, DOMJSProxyHandler directly subclasses - * BaseProxyHandler. - * - * Gecko's security wrappers are examples of cross-compartment wrappers. - * - * ### Proxy prototype chains - * - * In addition to the normal methods, there are two models for proxy prototype - * chains. - * - * 1. Proxies can use the standard prototype mechanism used throughout the - * engine. To do so, simply pass a prototype to NewProxyObject() at - * creation time. All prototype accesses will then "just work" to treat the - * proxy as a "normal" object. - * - * 2. A proxy can implement more complicated prototype semantics (if, for - * example, it wants to delegate the prototype lookup to a wrapped object) - * by passing Proxy::LazyProto as the prototype at create time. This - * guarantees that the getPrototype() handler method will be called every - * time the object's prototype chain is accessed. - * - * This system is implemented with two methods: {get,set}Prototype. The - * default implementation of setPrototype throws a TypeError. Since it is - * not possible to create an object without a sense of prototype chain, - * handlers must implement getPrototype if opting in to the dynamic - * prototype system. - */ - -/* - * BaseProxyHandler is the most generic kind of proxy handler. It does not make - * any assumptions about the target. Consequently, it does not provide any - * default implementation for most methods. As a convenience, a few high-level - * methods, like get() and set(), are given default implementations that work by - * calling the low-level methods, like getOwnPropertyDescriptor(). - * - * Important: If you add a method here, you should probably also add a - * Proxy::foo entry point with an AutoEnterPolicy. If you don't, you need an - * explicit override for the method in SecurityWrapper. See bug 945826 comment 0. - */ -class JS_FRIEND_API(BaseProxyHandler) -{ - /* - * Sometimes it's desirable to designate groups of proxy handlers as "similar". - * For this, we use the notion of a "family": A consumer-provided opaque pointer - * that designates the larger group to which this proxy belongs. - * - * If it will never be important to differentiate this proxy from others as - * part of a distinct group, nullptr may be used instead. - */ - const void* mFamily; - - /* - * Proxy handlers can use mHasPrototype to request the following special - * treatment from the JS engine: - * - * - When mHasPrototype is true, the engine never calls these methods: - * getPropertyDescriptor, has, set, enumerate, iterate. Instead, for - * these operations, it calls the "own" methods like - * getOwnPropertyDescriptor, hasOwn, defineProperty, - * getOwnEnumerablePropertyKeys, etc., and consults the prototype chain - * if needed. - * - * - When mHasPrototype is true, the engine calls handler->get() only if - * handler->hasOwn() says an own property exists on the proxy. If not, - * it consults the prototype chain. - * - * This is useful because it frees the ProxyHandler from having to implement - * any behavior having to do with the prototype chain. - */ - bool mHasPrototype; - - /* - * All proxies indicate whether they have any sort of interesting security - * policy that might prevent the caller from doing something it wants to - * the object. In the case of wrappers, this distinction is used to - * determine whether the caller may strip off the wrapper if it so desires. - */ - bool mHasSecurityPolicy; - - public: - explicit constexpr BaseProxyHandler(const void* aFamily, bool aHasPrototype = false, - bool aHasSecurityPolicy = false) - : mFamily(aFamily), - mHasPrototype(aHasPrototype), - mHasSecurityPolicy(aHasSecurityPolicy) - { } - - bool hasPrototype() const { - return mHasPrototype; - } - - bool hasSecurityPolicy() const { - return mHasSecurityPolicy; - } - - inline const void* family() const { - return mFamily; - } - static size_t offsetOfFamily() { - return offsetof(BaseProxyHandler, mFamily); - } - - virtual bool finalizeInBackground(const Value& priv) const { - /* - * Called on creation of a proxy to determine whether its finalize - * method can be finalized on the background thread. - */ - return true; - } - - virtual bool canNurseryAllocate() const { - /* - * Nursery allocation is allowed if and only if it is safe to not - * run |finalize| when the ProxyObject dies. - */ - return false; - } - - /* Policy enforcement methods. - * - * enter() allows the policy to specify whether the caller may perform |act| - * on the proxy's |id| property. In the case when |act| is CALL, |id| is - * generally JSID_VOID. - * - * The |act| parameter to enter() specifies the action being performed. - * If |bp| is false, the method suggests that the caller throw (though it - * may still decide to squelch the error). - * - * We make these OR-able so that assertEnteredPolicy can pass a union of them. - * For example, get{,Own}PropertyDescriptor is invoked by calls to ::get() - * ::set(), in addition to being invoked on its own, so there are several - * valid Actions that could have been entered. - */ - typedef uint32_t Action; - enum { - NONE = 0x00, - GET = 0x01, - SET = 0x02, - CALL = 0x04, - ENUMERATE = 0x08, - GET_PROPERTY_DESCRIPTOR = 0x10 - }; - - virtual bool enter(JSContext* cx, HandleObject wrapper, HandleId id, Action act, - bool* bp) const; - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const = 0; - virtual bool defineProperty(JSContext* cx, HandleObject proxy, HandleId id, - Handle desc, - ObjectOpResult& result) const = 0; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const = 0; - virtual bool delete_(JSContext* cx, HandleObject proxy, HandleId id, - ObjectOpResult& result) const = 0; - - /* - * These methods are standard, but the engine does not normally call them. - * They're opt-in. See "Proxy prototype chains" above. - * - * getPrototype() crashes if called. setPrototype() throws a TypeError. - */ - virtual bool getPrototype(JSContext* cx, HandleObject proxy, MutableHandleObject protop) const; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const; - - /* Non-standard but conceptual kin to {g,s}etPrototype, so these live here. */ - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, - MutableHandleObject protop) const = 0; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, bool* succeeded) const; - - virtual bool preventExtensions(JSContext* cx, HandleObject proxy, - ObjectOpResult& result) const = 0; - virtual bool isExtensible(JSContext* cx, HandleObject proxy, bool* extensible) const = 0; - - /* - * These standard internal methods are implemented, as a convenience, so - * that ProxyHandler subclasses don't have to provide every single method. - * - * The base-class implementations work by calling getPropertyDescriptor(). - * They do not follow any standard. When in doubt, override them. - */ - virtual bool has(JSContext* cx, HandleObject proxy, HandleId id, bool* bp) const; - virtual bool get(JSContext* cx, HandleObject proxy, HandleValue receiver, - HandleId id, MutableHandleValue vp) const; - virtual bool set(JSContext* cx, HandleObject proxy, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const; - - /* - * [[Call]] and [[Construct]] are standard internal methods but according - * to the spec, they are not present on every object. - * - * SpiderMonkey never calls a proxy's call()/construct() internal method - * unless isCallable()/isConstructor() returns true for that proxy. - * - * BaseProxyHandler::isCallable()/isConstructor() always return false, and - * BaseProxyHandler::call()/construct() crash if called. So if you're - * creating a kind of that is never callable, you don't have to override - * anything, but otherwise you probably want to override all four. - */ - virtual bool call(JSContext* cx, HandleObject proxy, const CallArgs& args) const; - virtual bool construct(JSContext* cx, HandleObject proxy, const CallArgs& args) const; - - /* SpiderMonkey extensions. */ - virtual bool enumerate(JSContext* cx, HandleObject proxy, MutableHandleObject objp) const; - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const; - virtual bool hasOwn(JSContext* cx, HandleObject proxy, HandleId id, bool* bp) const; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const; - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const; - virtual bool hasInstance(JSContext* cx, HandleObject proxy, MutableHandleValue v, bool* bp) const; - virtual bool getBuiltinClass(JSContext* cx, HandleObject proxy, - ESClass* cls) const; - virtual bool isArray(JSContext* cx, HandleObject proxy, JS::IsArrayAnswer* answer) const; - virtual const char* className(JSContext* cx, HandleObject proxy) const; - virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, unsigned indent) const; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const; - virtual void trace(JSTracer* trc, JSObject* proxy) const; - virtual void finalize(JSFreeOp* fop, JSObject* proxy) const; - virtual void objectMoved(JSObject* proxy, const JSObject* old) const; - - // Allow proxies, wrappers in particular, to specify callability at runtime. - // Note: These do not take const JSObject*, but they do in spirit. - // We are not prepared to do this, as there's little const correctness - // in the external APIs that handle proxies. - virtual bool isCallable(JSObject* obj) const; - virtual bool isConstructor(JSObject* obj) const; - - // These two hooks must be overridden, or not overridden, in tandem -- no - // overriding just one! - virtual bool watch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, - JS::HandleObject callable) const; - virtual bool unwatch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id) const; - - virtual bool getElements(JSContext* cx, HandleObject proxy, uint32_t begin, uint32_t end, - ElementAdder* adder) const; - - /* See comment for weakmapKeyDelegateOp in js/Class.h. */ - virtual JSObject* weakmapKeyDelegate(JSObject* proxy) const; - virtual bool isScripted() const { return false; } -}; - -extern JS_FRIEND_DATA(const js::Class* const) ProxyClassPtr; - -inline bool IsProxy(const JSObject* obj) -{ - return GetObjectClass(obj)->isProxy(); -} - -namespace detail { -const uint32_t PROXY_EXTRA_SLOTS = 2; - -// Layout of the values stored by a proxy. Note that API clients require the -// private slot to be the first slot in the proxy's values, so that the private -// slot can be accessed in the same fashion as the first reserved slot, via -// {Get,Set}ReservedOrProxyPrivateSlot. - -struct ProxyValueArray -{ - Value privateSlot; - Value extraSlots[PROXY_EXTRA_SLOTS]; - - ProxyValueArray() - : privateSlot(JS::UndefinedValue()) - { - for (size_t i = 0; i < PROXY_EXTRA_SLOTS; i++) - extraSlots[i] = JS::UndefinedValue(); - } -}; - -// All proxies share the same data layout. Following the object's shape and -// type, the proxy has a ProxyDataLayout structure with a pointer to an array -// of values and the proxy's handler. This is designed both so that proxies can -// be easily swapped with other objects (via RemapWrapper) and to mimic the -// layout of other objects (proxies and other objects have the same size) so -// that common code can access either type of object. -// -// See GetReservedOrProxyPrivateSlot below. -struct ProxyDataLayout -{ - ProxyValueArray* values; - const BaseProxyHandler* handler; -}; - -const uint32_t ProxyDataOffset = 2 * sizeof(void*); - -inline ProxyDataLayout* -GetProxyDataLayout(JSObject* obj) -{ - MOZ_ASSERT(IsProxy(obj)); - return reinterpret_cast(reinterpret_cast(obj) + ProxyDataOffset); -} - -inline const ProxyDataLayout* -GetProxyDataLayout(const JSObject* obj) -{ - MOZ_ASSERT(IsProxy(obj)); - return reinterpret_cast(reinterpret_cast(obj) + - ProxyDataOffset); -} -} // namespace detail - -inline const BaseProxyHandler* -GetProxyHandler(const JSObject* obj) -{ - return detail::GetProxyDataLayout(obj)->handler; -} - -inline const Value& -GetProxyPrivate(const JSObject* obj) -{ - return detail::GetProxyDataLayout(obj)->values->privateSlot; -} - -inline JSObject* -GetProxyTargetObject(JSObject* obj) -{ - return GetProxyPrivate(obj).toObjectOrNull(); -} - -inline const Value& -GetProxyExtra(const JSObject* obj, size_t n) -{ - MOZ_ASSERT(n < detail::PROXY_EXTRA_SLOTS); - return detail::GetProxyDataLayout(obj)->values->extraSlots[n]; -} - -inline void -SetProxyHandler(JSObject* obj, const BaseProxyHandler* handler) -{ - detail::GetProxyDataLayout(obj)->handler = handler; -} - -JS_FRIEND_API(void) -SetValueInProxy(Value* slot, const Value& value); - -inline void -SetProxyExtra(JSObject* obj, size_t n, const Value& extra) -{ - MOZ_ASSERT(n < detail::PROXY_EXTRA_SLOTS); - Value* vp = &detail::GetProxyDataLayout(obj)->values->extraSlots[n]; - - // Trigger a barrier before writing the slot. - if (vp->isMarkable() || extra.isMarkable()) - SetValueInProxy(vp, extra); - else - *vp = extra; -} - -inline bool -IsScriptedProxy(const JSObject* obj) -{ - return IsProxy(obj) && GetProxyHandler(obj)->isScripted(); -} - -inline const Value& -GetReservedOrProxyPrivateSlot(const JSObject* obj, size_t slot) -{ - MOZ_ASSERT(slot == 0); - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj)) || IsProxy(obj)); - return reinterpret_cast(obj)->slotRef(slot); -} - -inline void -SetReservedOrProxyPrivateSlot(JSObject* obj, size_t slot, const Value& value) -{ - MOZ_ASSERT(slot == 0); - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj)) || IsProxy(obj)); - shadow::Object* sobj = reinterpret_cast(obj); - if (sobj->slotRef(slot).isMarkable() || value.isMarkable()) - SetReservedOrProxyPrivateSlotWithBarrier(obj, slot, value); - else - sobj->slotRef(slot) = value; -} - -class MOZ_STACK_CLASS ProxyOptions { - protected: - /* protected constructor for subclass */ - explicit ProxyOptions(bool singletonArg, bool lazyProtoArg = false) - : singleton_(singletonArg), - lazyProto_(lazyProtoArg), - clasp_(ProxyClassPtr) - {} - - public: - ProxyOptions() : singleton_(false), - lazyProto_(false), - clasp_(ProxyClassPtr) - {} - - bool singleton() const { return singleton_; } - ProxyOptions& setSingleton(bool flag) { - singleton_ = flag; - return *this; - } - - bool lazyProto() const { return lazyProto_; } - ProxyOptions& setLazyProto(bool flag) { - lazyProto_ = flag; - return *this; - } - - const Class* clasp() const { - return clasp_; - } - ProxyOptions& setClass(const Class* claspArg) { - clasp_ = claspArg; - return *this; - } - - private: - bool singleton_; - bool lazyProto_; - const Class* clasp_; -}; - -JS_FRIEND_API(JSObject*) -NewProxyObject(JSContext* cx, const BaseProxyHandler* handler, HandleValue priv, - JSObject* proto, const ProxyOptions& options = ProxyOptions()); - -JSObject* -RenewProxyObject(JSContext* cx, JSObject* obj, BaseProxyHandler* handler, const Value& priv); - -class JS_FRIEND_API(AutoEnterPolicy) -{ - public: - typedef BaseProxyHandler::Action Action; - AutoEnterPolicy(JSContext* cx, const BaseProxyHandler* handler, - HandleObject wrapper, HandleId id, Action act, bool mayThrow) -#ifdef JS_DEBUG - : context(nullptr) -#endif - { - allow = handler->hasSecurityPolicy() ? handler->enter(cx, wrapper, id, act, &rv) - : true; - recordEnter(cx, wrapper, id, act); - // We want to throw an exception if all of the following are true: - // * The policy disallowed access. - // * The policy set rv to false, indicating that we should throw. - // * The caller did not instruct us to ignore exceptions. - // * The policy did not throw itself. - if (!allow && !rv && mayThrow) - reportErrorIfExceptionIsNotPending(cx, id); - } - - virtual ~AutoEnterPolicy() { recordLeave(); } - inline bool allowed() { return allow; } - inline bool returnValue() { MOZ_ASSERT(!allowed()); return rv; } - - protected: - // no-op constructor for subclass - AutoEnterPolicy() -#ifdef JS_DEBUG - : context(nullptr) - , enteredAction(BaseProxyHandler::NONE) -#endif - {} - void reportErrorIfExceptionIsNotPending(JSContext* cx, jsid id); - bool allow; - bool rv; - -#ifdef JS_DEBUG - JSContext* context; - mozilla::Maybe enteredProxy; - mozilla::Maybe enteredId; - Action enteredAction; - - // NB: We explicitly don't track the entered action here, because sometimes - // set() methods do an implicit get() during their implementation, leading - // to spurious assertions. - AutoEnterPolicy* prev; - void recordEnter(JSContext* cx, HandleObject proxy, HandleId id, Action act); - void recordLeave(); - - friend JS_FRIEND_API(void) assertEnteredPolicy(JSContext* cx, JSObject* proxy, jsid id, Action act); -#else - inline void recordEnter(JSContext* cx, JSObject* proxy, jsid id, Action act) {} - inline void recordLeave() {} -#endif - -}; - -#ifdef JS_DEBUG -class JS_FRIEND_API(AutoWaivePolicy) : public AutoEnterPolicy { -public: - AutoWaivePolicy(JSContext* cx, HandleObject proxy, HandleId id, - BaseProxyHandler::Action act) - { - allow = true; - recordEnter(cx, proxy, id, act); - } -}; -#else -class JS_FRIEND_API(AutoWaivePolicy) { - public: - AutoWaivePolicy(JSContext* cx, HandleObject proxy, HandleId id, - BaseProxyHandler::Action act) - {} -}; -#endif - -#ifdef JS_DEBUG -extern JS_FRIEND_API(void) -assertEnteredPolicy(JSContext* cx, JSObject* obj, jsid id, - BaseProxyHandler::Action act); -#else -inline void assertEnteredPolicy(JSContext* cx, JSObject* obj, jsid id, - BaseProxyHandler::Action act) -{} -#endif - -extern JS_FRIEND_API(JSObject*) -InitProxyClass(JSContext* cx, JS::HandleObject obj); - -} /* namespace js */ - -#endif /* js_Proxy_h */ diff --git a/mac/include/spidermonkey/js/Realm.h b/mac/include/spidermonkey/js/Realm.h deleted file mode 100644 index 13a22c70..00000000 --- a/mac/include/spidermonkey/js/Realm.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Ways to get various per-Realm objects. All the getters declared in this - * header operate on the Realm corresponding to the current compartment on the - * JSContext. - */ - -#ifndef js_Realm_h -#define js_Realm_h - -#include "jstypes.h" - -struct JSContext; -class JSObject; - -namespace JS { - -extern JS_PUBLIC_API(JSObject*) -GetRealmObjectPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmFunctionPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmArrayPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmErrorPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmIteratorPrototype(JSContext* cx); - -} // namespace JS - -#endif // js_Realm_h - - diff --git a/mac/include/spidermonkey/js/RequiredDefines.h b/mac/include/spidermonkey/js/RequiredDefines.h deleted file mode 100644 index 308fd7d6..00000000 --- a/mac/include/spidermonkey/js/RequiredDefines.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Various #defines required to build SpiderMonkey. Embedders should add this - * file to the start of the command line via -include or a similar mechanism, - * or SpiderMonkey public headers may not work correctly. - */ - -#ifndef js_RequiredDefines_h -#define js_RequiredDefines_h - -/* - * The c99 defining the limit macros (UINT32_MAX for example), says: - * - * C++ implementations should define these macros only when - * __STDC_LIMIT_MACROS is defined before is included. - * - * The same also occurs with __STDC_CONSTANT_MACROS for the constant macros - * (INT8_C for example) used to specify a literal constant of the proper type, - * and with __STDC_FORMAT_MACROS for the format macros (PRId32 for example) used - * with the fprintf function family. - */ -#define __STDC_LIMIT_MACROS -#define __STDC_CONSTANT_MACROS -#define __STDC_FORMAT_MACROS - -/* Also define a char16_t type if not provided by the compiler. */ -#include "mozilla/Char16.h" - -#endif /* js_RequiredDefines_h */ diff --git a/mac/include/spidermonkey/js/RootingAPI.h b/mac/include/spidermonkey/js/RootingAPI.h deleted file mode 100644 index a99ac4ec..00000000 --- a/mac/include/spidermonkey/js/RootingAPI.h +++ /dev/null @@ -1,1308 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_RootingAPI_h -#define js_RootingAPI_h - -#include "mozilla/Attributes.h" -#include "mozilla/DebugOnly.h" -#include "mozilla/GuardObjects.h" -#include "mozilla/LinkedList.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include - -#include "jspubtd.h" - -#include "js/GCAnnotations.h" -#include "js/GCAPI.h" -#include "js/GCPolicyAPI.h" -#include "js/HeapAPI.h" -#include "js/TypeDecls.h" -#include "js/UniquePtr.h" -#include "js/Utility.h" - -/* - * Moving GC Stack Rooting - * - * A moving GC may change the physical location of GC allocated things, even - * when they are rooted, updating all pointers to the thing to refer to its new - * location. The GC must therefore know about all live pointers to a thing, - * not just one of them, in order to behave correctly. - * - * The |Rooted| and |Handle| classes below are used to root stack locations - * whose value may be held live across a call that can trigger GC. For a - * code fragment such as: - * - * JSObject* obj = NewObject(cx); - * DoSomething(cx); - * ... = obj->lastProperty(); - * - * If |DoSomething()| can trigger a GC, the stack location of |obj| must be - * rooted to ensure that the GC does not move the JSObject referred to by - * |obj| without updating |obj|'s location itself. This rooting must happen - * regardless of whether there are other roots which ensure that the object - * itself will not be collected. - * - * If |DoSomething()| cannot trigger a GC, and the same holds for all other - * calls made between |obj|'s definitions and its last uses, then no rooting - * is required. - * - * SpiderMonkey can trigger a GC at almost any time and in ways that are not - * always clear. For example, the following innocuous-looking actions can - * cause a GC: allocation of any new GC thing; JSObject::hasProperty; - * JS_ReportError and friends; and ToNumber, among many others. The following - * dangerous-looking actions cannot trigger a GC: js_malloc, cx->malloc_, - * rt->malloc_, and friends and JS_ReportOutOfMemory. - * - * The following family of three classes will exactly root a stack location. - * Incorrect usage of these classes will result in a compile error in almost - * all cases. Therefore, it is very hard to be incorrectly rooted if you use - * these classes exclusively. These classes are all templated on the type T of - * the value being rooted. - * - * - Rooted declares a variable of type T, whose value is always rooted. - * Rooted may be automatically coerced to a Handle, below. Rooted - * should be used whenever a local variable's value may be held live across a - * call which can trigger a GC. - * - * - Handle is a const reference to a Rooted. Functions which take GC - * things or values as arguments and need to root those arguments should - * generally use handles for those arguments and avoid any explicit rooting. - * This has two benefits. First, when several such functions call each other - * then redundant rooting of multiple copies of the GC thing can be avoided. - * Second, if the caller does not pass a rooted value a compile error will be - * generated, which is quicker and easier to fix than when relying on a - * separate rooting analysis. - * - * - MutableHandle is a non-const reference to Rooted. It is used in the - * same way as Handle and includes a |set(const T& v)| method to allow - * updating the value of the referenced Rooted. A MutableHandle can be - * created with an implicit cast from a Rooted*. - * - * In some cases the small performance overhead of exact rooting (measured to - * be a few nanoseconds on desktop) is too much. In these cases, try the - * following: - * - * - Move all Rooted above inner loops: this allows you to re-use the root - * on each iteration of the loop. - * - * - Pass Handle through your hot call stack to avoid re-rooting costs at - * every invocation. - * - * The following diagram explains the list of supported, implicit type - * conversions between classes of this family: - * - * Rooted ----> Handle - * | ^ - * | | - * | | - * +---> MutableHandle - * (via &) - * - * All of these types have an implicit conversion to raw pointers. - */ - -namespace js { - -template -struct BarrierMethods { -}; - -template -class RootedBase {}; - -template -class HandleBase {}; - -template -class MutableHandleBase {}; - -template -class HeapBase {}; - -// Cannot use FOR_EACH_HEAP_ABLE_GC_POINTER_TYPE, as this would import too many macros into scope -template struct IsHeapConstructibleType { static constexpr bool value = false; }; -#define DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE(T) \ - template <> struct IsHeapConstructibleType { static constexpr bool value = true; }; -FOR_EACH_PUBLIC_GC_POINTER_TYPE(DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE) -FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE) -#undef DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE - -template -class PersistentRootedBase {}; - -static void* const ConstNullValue = nullptr; - -namespace gc { -struct Cell; -template -struct PersistentRootedMarker; -} /* namespace gc */ - -#define DECLARE_POINTER_COMPARISON_OPS(T) \ - bool operator==(const T& other) const { return get() == other; } \ - bool operator!=(const T& other) const { return get() != other; } - -// Important: Return a reference so passing a Rooted, etc. to -// something that takes a |const T&| is not a GC hazard. -#define DECLARE_POINTER_CONSTREF_OPS(T) \ - operator const T&() const { return get(); } \ - const T& operator->() const { return get(); } - -// Assignment operators on a base class are hidden by the implicitly defined -// operator= on the derived class. Thus, define the operator= directly on the -// class as we would need to manually pass it through anyway. -#define DECLARE_POINTER_ASSIGN_OPS(Wrapper, T) \ - Wrapper& operator=(const T& p) { \ - set(p); \ - return *this; \ - } \ - Wrapper& operator=(const Wrapper& other) { \ - set(other.get()); \ - return *this; \ - } \ - -#define DELETE_ASSIGNMENT_OPS(Wrapper, T) \ - template Wrapper& operator=(S) = delete; \ - Wrapper& operator=(const Wrapper&) = delete; - -#define DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr) \ - const T* address() const { return &(ptr); } \ - const T& get() const { return (ptr); } \ - -#define DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr) \ - T* address() { return &(ptr); } \ - T& get() { return (ptr); } \ - -} /* namespace js */ - -namespace JS { - -template class Rooted; -template class PersistentRooted; - -/* This is exposing internal state of the GC for inlining purposes. */ -JS_FRIEND_API(bool) isGCEnabled(); - -JS_FRIEND_API(void) HeapObjectPostBarrier(JSObject** objp, JSObject* prev, JSObject* next); - -#ifdef JS_DEBUG -/** - * For generational GC, assert that an object is in the tenured generation as - * opposed to being in the nursery. - */ -extern JS_FRIEND_API(void) -AssertGCThingMustBeTenured(JSObject* obj); -extern JS_FRIEND_API(void) -AssertGCThingIsNotAnObjectSubclass(js::gc::Cell* cell); -#else -inline void -AssertGCThingMustBeTenured(JSObject* obj) {} -inline void -AssertGCThingIsNotAnObjectSubclass(js::gc::Cell* cell) {} -#endif - -/** - * The Heap class is a heap-stored reference to a JS GC thing. All members of - * heap classes that refer to GC things should use Heap (or possibly - * TenuredHeap, described below). - * - * Heap is an abstraction that hides some of the complexity required to - * maintain GC invariants for the contained reference. It uses operator - * overloading to provide a normal pointer interface, but notifies the GC every - * time the value it contains is updated. This is necessary for generational GC, - * which keeps track of all pointers into the nursery. - * - * Heap instances must be traced when their containing object is traced to - * keep the pointed-to GC thing alive. - * - * Heap objects should only be used on the heap. GC references stored on the - * C/C++ stack must use Rooted/Handle/MutableHandle instead. - * - * Type T must be a public GC pointer type. - */ -template -class Heap : public js::HeapBase -{ - // Please note: this can actually also be used by nsXBLMaybeCompiled, for legacy reasons. - static_assert(js::IsHeapConstructibleType::value, - "Type T must be a public GC pointer type"); - public: - Heap() { - static_assert(sizeof(T) == sizeof(Heap), - "Heap must be binary compatible with T."); - init(GCPolicy::initial()); - } - explicit Heap(const T& p) { init(p); } - - /* - * For Heap, move semantics are equivalent to copy semantics. In C++, a - * copy constructor taking const-ref is the way to get a single function - * that will be used for both lvalue and rvalue copies, so we can simply - * omit the rvalue variant. - */ - explicit Heap(const Heap& p) { init(p.ptr); } - - ~Heap() { - post(ptr, GCPolicy::initial()); - } - - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(Heap, T); - - const T* address() const { return &ptr; } - - void exposeToActiveJS() const { - js::BarrierMethods::exposeToJS(ptr); - } - const T& get() const { - exposeToActiveJS(); - return ptr; - } - const T& unbarrieredGet() const { - return ptr; - } - - T* unsafeGet() { return &ptr; } - - explicit operator bool() const { - return bool(js::BarrierMethods::asGCThingOrNull(ptr)); - } - explicit operator bool() { - return bool(js::BarrierMethods::asGCThingOrNull(ptr)); - } - - private: - void init(const T& newPtr) { - ptr = newPtr; - post(GCPolicy::initial(), ptr); - } - - void set(const T& newPtr) { - T tmp = ptr; - ptr = newPtr; - post(tmp, ptr); - } - - void post(const T& prev, const T& next) { - js::BarrierMethods::postBarrier(&ptr, prev, next); - } - - T ptr; -}; - -static MOZ_ALWAYS_INLINE bool -ObjectIsTenured(JSObject* obj) -{ - return !js::gc::IsInsideNursery(reinterpret_cast(obj)); -} - -static MOZ_ALWAYS_INLINE bool -ObjectIsTenured(const Heap& obj) -{ - return ObjectIsTenured(obj.unbarrieredGet()); -} - -static MOZ_ALWAYS_INLINE bool -ObjectIsMarkedGray(JSObject* obj) -{ - auto cell = reinterpret_cast(obj); - return js::gc::detail::CellIsMarkedGrayIfKnown(cell); -} - -static MOZ_ALWAYS_INLINE bool -ObjectIsMarkedGray(const JS::Heap& obj) -{ - return ObjectIsMarkedGray(obj.unbarrieredGet()); -} - -static MOZ_ALWAYS_INLINE bool -ScriptIsMarkedGray(JSScript* script) -{ - auto cell = reinterpret_cast(script); - return js::gc::detail::CellIsMarkedGrayIfKnown(cell); -} - -static MOZ_ALWAYS_INLINE bool -ScriptIsMarkedGray(const Heap& script) -{ - return ScriptIsMarkedGray(script.unbarrieredGet()); -} - -/** - * The TenuredHeap class is similar to the Heap class above in that it - * encapsulates the GC concerns of an on-heap reference to a JS object. However, - * it has two important differences: - * - * 1) Pointers which are statically known to only reference "tenured" objects - * can avoid the extra overhead of SpiderMonkey's write barriers. - * - * 2) Objects in the "tenured" heap have stronger alignment restrictions than - * those in the "nursery", so it is possible to store flags in the lower - * bits of pointers known to be tenured. TenuredHeap wraps a normal tagged - * pointer with a nice API for accessing the flag bits and adds various - * assertions to ensure that it is not mis-used. - * - * GC things are said to be "tenured" when they are located in the long-lived - * heap: e.g. they have gained tenure as an object by surviving past at least - * one GC. For performance, SpiderMonkey allocates some things which are known - * to normally be long lived directly into the tenured generation; for example, - * global objects. Additionally, SpiderMonkey does not visit individual objects - * when deleting non-tenured objects, so object with finalizers are also always - * tenured; for instance, this includes most DOM objects. - * - * The considerations to keep in mind when using a TenuredHeap vs a normal - * Heap are: - * - * - It is invalid for a TenuredHeap to refer to a non-tenured thing. - * - It is however valid for a Heap to refer to a tenured thing. - * - It is not possible to store flag bits in a Heap. - */ -template -class TenuredHeap : public js::HeapBase -{ - public: - TenuredHeap() : bits(0) { - static_assert(sizeof(T) == sizeof(TenuredHeap), - "TenuredHeap must be binary compatible with T."); - } - explicit TenuredHeap(T p) : bits(0) { setPtr(p); } - explicit TenuredHeap(const TenuredHeap& p) : bits(0) { setPtr(p.getPtr()); } - - bool operator==(const TenuredHeap& other) { return bits == other.bits; } - bool operator!=(const TenuredHeap& other) { return bits != other.bits; } - - void setPtr(T newPtr) { - MOZ_ASSERT((reinterpret_cast(newPtr) & flagsMask) == 0); - if (newPtr) - AssertGCThingMustBeTenured(newPtr); - bits = (bits & flagsMask) | reinterpret_cast(newPtr); - } - - void setFlags(uintptr_t flagsToSet) { - MOZ_ASSERT((flagsToSet & ~flagsMask) == 0); - bits |= flagsToSet; - } - - void unsetFlags(uintptr_t flagsToUnset) { - MOZ_ASSERT((flagsToUnset & ~flagsMask) == 0); - bits &= ~flagsToUnset; - } - - bool hasFlag(uintptr_t flag) const { - MOZ_ASSERT((flag & ~flagsMask) == 0); - return (bits & flag) != 0; - } - - T unbarrieredGetPtr() const { return reinterpret_cast(bits & ~flagsMask); } - uintptr_t getFlags() const { return bits & flagsMask; } - - void exposeToActiveJS() const { - js::BarrierMethods::exposeToJS(unbarrieredGetPtr()); - } - T getPtr() const { - exposeToActiveJS(); - return unbarrieredGetPtr(); - } - - operator T() const { return getPtr(); } - T operator->() const { return getPtr(); } - - explicit operator bool() const { - return bool(js::BarrierMethods::asGCThingOrNull(unbarrieredGetPtr())); - } - explicit operator bool() { - return bool(js::BarrierMethods::asGCThingOrNull(unbarrieredGetPtr())); - } - - TenuredHeap& operator=(T p) { - setPtr(p); - return *this; - } - - TenuredHeap& operator=(const TenuredHeap& other) { - bits = other.bits; - return *this; - } - - private: - enum { - maskBits = 3, - flagsMask = (1 << maskBits) - 1, - }; - - uintptr_t bits; -}; - -/** - * Reference to a T that has been rooted elsewhere. This is most useful - * as a parameter type, which guarantees that the T lvalue is properly - * rooted. See "Move GC Stack Rooting" above. - * - * If you want to add additional methods to Handle for a specific - * specialization, define a HandleBase specialization containing them. - */ -template -class MOZ_NONHEAP_CLASS Handle : public js::HandleBase -{ - friend class JS::MutableHandle; - - public: - /* Creates a handle from a handle of a type convertible to T. */ - template - MOZ_IMPLICIT Handle(Handle handle, - typename mozilla::EnableIf::value, int>::Type dummy = 0) - { - static_assert(sizeof(Handle) == sizeof(T*), - "Handle must be binary compatible with T*."); - ptr = reinterpret_cast(handle.address()); - } - - MOZ_IMPLICIT Handle(decltype(nullptr)) { - static_assert(mozilla::IsPointer::value, - "nullptr_t overload not valid for non-pointer types"); - ptr = reinterpret_cast(&js::ConstNullValue); - } - - MOZ_IMPLICIT Handle(MutableHandle handle) { - ptr = handle.address(); - } - - /* - * Take care when calling this method! - * - * This creates a Handle from the raw location of a T. - * - * It should be called only if the following conditions hold: - * - * 1) the location of the T is guaranteed to be marked (for some reason - * other than being a Rooted), e.g., if it is guaranteed to be reachable - * from an implicit root. - * - * 2) the contents of the location are immutable, or at least cannot change - * for the lifetime of the handle, as its users may not expect its value - * to change underneath them. - */ - static constexpr Handle fromMarkedLocation(const T* p) { - return Handle(p, DeliberatelyChoosingThisOverload, - ImUsingThisOnlyInFromFromMarkedLocation); - } - - /* - * Construct a handle from an explicitly rooted location. This is the - * normal way to create a handle, and normally happens implicitly. - */ - template - inline - MOZ_IMPLICIT Handle(const Rooted& root, - typename mozilla::EnableIf::value, int>::Type dummy = 0); - - template - inline - MOZ_IMPLICIT Handle(const PersistentRooted& root, - typename mozilla::EnableIf::value, int>::Type dummy = 0); - - /* Construct a read only handle from a mutable handle. */ - template - inline - MOZ_IMPLICIT Handle(MutableHandle& root, - typename mozilla::EnableIf::value, int>::Type dummy = 0); - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr); - - private: - Handle() {} - DELETE_ASSIGNMENT_OPS(Handle, T); - - enum Disambiguator { DeliberatelyChoosingThisOverload = 42 }; - enum CallerIdentity { ImUsingThisOnlyInFromFromMarkedLocation = 17 }; - constexpr Handle(const T* p, Disambiguator, CallerIdentity) : ptr(p) {} - - const T* ptr; -}; - -/** - * Similar to a handle, but the underlying storage can be changed. This is - * useful for outparams. - * - * If you want to add additional methods to MutableHandle for a specific - * specialization, define a MutableHandleBase specialization containing - * them. - */ -template -class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase -{ - public: - inline MOZ_IMPLICIT MutableHandle(Rooted* root); - inline MOZ_IMPLICIT MutableHandle(PersistentRooted* root); - - private: - // Disallow nullptr for overloading purposes. - MutableHandle(decltype(nullptr)) = delete; - - public: - void set(const T& v) { - *ptr = v; - } - - /* - * This may be called only if the location of the T is guaranteed - * to be marked (for some reason other than being a Rooted), - * e.g., if it is guaranteed to be reachable from an implicit root. - * - * Create a MutableHandle from a raw location of a T. - */ - static MutableHandle fromMarkedLocation(T* p) { - MutableHandle h; - h.ptr = p; - return h; - } - - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(*ptr); - - private: - MutableHandle() {} - DELETE_ASSIGNMENT_OPS(MutableHandle, T); - - T* ptr; -}; - -} /* namespace JS */ - -namespace js { - -template -struct BarrierMethods -{ - static T* initial() { return nullptr; } - static gc::Cell* asGCThingOrNull(T* v) { - if (!v) - return nullptr; - MOZ_ASSERT(uintptr_t(v) > 32); - return reinterpret_cast(v); - } - static void postBarrier(T** vp, T* prev, T* next) { - if (next) - JS::AssertGCThingIsNotAnObjectSubclass(reinterpret_cast(next)); - } - static void exposeToJS(T* t) { - if (t) - js::gc::ExposeGCThingToActiveJS(JS::GCCellPtr(t)); - } -}; - -template <> -struct BarrierMethods -{ - static JSObject* initial() { return nullptr; } - static gc::Cell* asGCThingOrNull(JSObject* v) { - if (!v) - return nullptr; - MOZ_ASSERT(uintptr_t(v) > 32); - return reinterpret_cast(v); - } - static void postBarrier(JSObject** vp, JSObject* prev, JSObject* next) { - JS::HeapObjectPostBarrier(vp, prev, next); - } - static void exposeToJS(JSObject* obj) { - if (obj) - JS::ExposeObjectToActiveJS(obj); - } -}; - -template <> -struct BarrierMethods -{ - static JSFunction* initial() { return nullptr; } - static gc::Cell* asGCThingOrNull(JSFunction* v) { - if (!v) - return nullptr; - MOZ_ASSERT(uintptr_t(v) > 32); - return reinterpret_cast(v); - } - static void postBarrier(JSFunction** vp, JSFunction* prev, JSFunction* next) { - JS::HeapObjectPostBarrier(reinterpret_cast(vp), - reinterpret_cast(prev), - reinterpret_cast(next)); - } - static void exposeToJS(JSFunction* fun) { - if (fun) - JS::ExposeObjectToActiveJS(reinterpret_cast(fun)); - } -}; - -// Provide hash codes for Cell kinds that may be relocated and, thus, not have -// a stable address to use as the base for a hash code. Instead of the address, -// this hasher uses Cell::getUniqueId to provide exact matches and as a base -// for generating hash codes. -// -// Note: this hasher, like PointerHasher can "hash" a nullptr. While a nullptr -// would not likely be a useful key, there are some cases where being able to -// hash a nullptr is useful, either on purpose or because of bugs: -// (1) existence checks where the key may happen to be null and (2) some -// aggregate Lookup kinds embed a JSObject* that is frequently null and do not -// null test before dispatching to the hasher. -template -struct JS_PUBLIC_API(MovableCellHasher) -{ - using Key = T; - using Lookup = T; - - static bool hasHash(const Lookup& l); - static bool ensureHash(const Lookup& l); - static HashNumber hash(const Lookup& l); - static bool match(const Key& k, const Lookup& l); - static void rekey(Key& k, const Key& newKey) { k = newKey; } -}; - -template -struct JS_PUBLIC_API(MovableCellHasher>) -{ - using Key = JS::Heap; - using Lookup = T; - - static bool hasHash(const Lookup& l) { return MovableCellHasher::hasHash(l); } - static bool ensureHash(const Lookup& l) { return MovableCellHasher::ensureHash(l); } - static HashNumber hash(const Lookup& l) { return MovableCellHasher::hash(l); } - static bool match(const Key& k, const Lookup& l) { - return MovableCellHasher::match(k.unbarrieredGet(), l); - } - static void rekey(Key& k, const Key& newKey) { k.unsafeSet(newKey); } -}; - -template -struct FallibleHashMethods> -{ - template static bool hasHash(Lookup&& l) { - return MovableCellHasher::hasHash(mozilla::Forward(l)); - } - template static bool ensureHash(Lookup&& l) { - return MovableCellHasher::ensureHash(mozilla::Forward(l)); - } -}; - -} /* namespace js */ - -namespace js { - -// The alignment must be set because the Rooted and PersistentRooted ptr fields -// may be accessed through reinterpret_cast*>, and -// the compiler may choose a different alignment for the ptr field when it -// knows the actual type stored in DispatchWrapper. -// -// It would make more sense to align only those specific fields of type -// DispatchWrapper, rather than DispatchWrapper itself, but that causes MSVC to -// fail when Rooted is used in an IsConvertible test. -template -class alignas(8) DispatchWrapper -{ - static_assert(JS::MapTypeToRootKind::kind == JS::RootKind::Traceable, - "DispatchWrapper is intended only for usage with a Traceable"); - - using TraceFn = void (*)(JSTracer*, T*, const char*); - TraceFn tracer; - alignas(gc::CellSize) T storage; - - public: - template - MOZ_IMPLICIT DispatchWrapper(U&& initial) - : tracer(&JS::GCPolicy::trace), - storage(mozilla::Forward(initial)) - { } - - // Mimic a pointer type, so that we can drop into Rooted. - T* operator &() { return &storage; } - const T* operator &() const { return &storage; } - operator T&() { return storage; } - operator const T&() const { return storage; } - - // Trace the contained storage (of unknown type) using the trace function - // we set aside when we did know the type. - static void TraceWrapped(JSTracer* trc, T* thingp, const char* name) { - auto wrapper = reinterpret_cast( - uintptr_t(thingp) - offsetof(DispatchWrapper, storage)); - wrapper->tracer(trc, &wrapper->storage, name); - } -}; - -} /* namespace js */ - -namespace JS { - -/** - * Local variable of type T whose value is always rooted. This is typically - * used for local variables, or for non-rooted values being passed to a - * function that requires a handle, e.g. Foo(Root(cx, x)). - * - * If you want to add additional methods to Rooted for a specific - * specialization, define a RootedBase specialization containing them. - */ -template -class MOZ_RAII Rooted : public js::RootedBase -{ - inline void registerWithRootLists(js::RootedListHeads& roots) { - this->stack = &roots[JS::MapTypeToRootKind::kind]; - this->prev = *stack; - *stack = reinterpret_cast*>(this); - } - - inline js::RootedListHeads& rootLists(JS::RootingContext* cx) { - return rootLists(static_cast(cx)); - } - inline js::RootedListHeads& rootLists(js::ContextFriendFields* cx) { - if (JS::Zone* zone = cx->zone_) - return JS::shadow::Zone::asShadowZone(zone)->stackRoots_; - MOZ_ASSERT(cx->isJSContext); - return cx->roots.stackRoots_; - } - inline js::RootedListHeads& rootLists(JSContext* cx) { - return rootLists(js::ContextFriendFields::get(cx)); - } - - public: - template - explicit Rooted(const RootingContext& cx) - : ptr(GCPolicy::initial()) - { - registerWithRootLists(rootLists(cx)); - } - - template - Rooted(const RootingContext& cx, S&& initial) - : ptr(mozilla::Forward(initial)) - { - registerWithRootLists(rootLists(cx)); - } - - ~Rooted() { - MOZ_ASSERT(*stack == reinterpret_cast*>(this)); - *stack = prev; - } - - Rooted* previous() { return reinterpret_cast*>(prev); } - - /* - * This method is public for Rooted so that Codegen.py can use a Rooted - * interchangeably with a MutableHandleValue. - */ - void set(const T& value) { - ptr = value; - } - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(Rooted, T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr); - - private: - /* - * These need to be templated on void* to avoid aliasing issues between, for - * example, Rooted and Rooted, which use the same - * stack head pointer for different classes. - */ - Rooted** stack; - Rooted* prev; - - /* - * For pointer types, the TraceKind for tracing is based on the list it is - * in (selected via MapTypeToRootKind), so no additional storage is - * required here. Non-pointer types, however, share the same list, so the - * function to call for tracing is stored adjacent to the struct. Since C++ - * cannot templatize on storage class, this is implemented via the wrapper - * class DispatchWrapper. - */ - using MaybeWrapped = typename mozilla::Conditional< - MapTypeToRootKind::kind == JS::RootKind::Traceable, - js::DispatchWrapper, - T>::Type; - MaybeWrapped ptr; - - Rooted(const Rooted&) = delete; -} JS_HAZ_ROOTED; - -} /* namespace JS */ - -namespace js { - -/** - * Augment the generic Rooted interface when T = JSObject* with - * class-querying and downcasting operations. - * - * Given a Rooted obj, one can view - * Handle h = obj.as(); - * as an optimization of - * Rooted rooted(cx, &obj->as()); - * Handle h = rooted; - */ -template <> -class RootedBase -{ - public: - template - JS::Handle as() const; -}; - -/** - * Augment the generic Handle interface when T = JSObject* with - * downcasting operations. - * - * Given a Handle obj, one can view - * Handle h = obj.as(); - * as an optimization of - * Rooted rooted(cx, &obj->as()); - * Handle h = rooted; - */ -template <> -class HandleBase -{ - public: - template - JS::Handle as() const; -}; - -/** Interface substitute for Rooted which does not root the variable's memory. */ -template -class MOZ_RAII FakeRooted : public RootedBase -{ - public: - template - explicit FakeRooted(CX* cx) : ptr(JS::GCPolicy::initial()) {} - - template - FakeRooted(CX* cx, T initial) : ptr(initial) {} - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(FakeRooted, T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr); - - private: - T ptr; - - void set(const T& value) { - ptr = value; - } - - FakeRooted(const FakeRooted&) = delete; -}; - -/** Interface substitute for MutableHandle which is not required to point to rooted memory. */ -template -class FakeMutableHandle : public js::MutableHandleBase -{ - public: - MOZ_IMPLICIT FakeMutableHandle(T* t) { - ptr = t; - } - - MOZ_IMPLICIT FakeMutableHandle(FakeRooted* root) { - ptr = root->address(); - } - - void set(const T& v) { - *ptr = v; - } - - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(*ptr); - - private: - FakeMutableHandle() {} - DELETE_ASSIGNMENT_OPS(FakeMutableHandle, T); - - T* ptr; -}; - -/** - * Types for a variable that either should or shouldn't be rooted, depending on - * the template parameter allowGC. Used for implementing functions that can - * operate on either rooted or unrooted data. - * - * The toHandle() and toMutableHandle() functions are for calling functions - * which require handle types and are only called in the CanGC case. These - * allow the calling code to type check. - */ -enum AllowGC { - NoGC = 0, - CanGC = 1 -}; -template -class MaybeRooted -{ -}; - -template class MaybeRooted -{ - public: - typedef JS::Handle HandleType; - typedef JS::Rooted RootType; - typedef JS::MutableHandle MutableHandleType; - - static inline JS::Handle toHandle(HandleType v) { - return v; - } - - static inline JS::MutableHandle toMutableHandle(MutableHandleType v) { - return v; - } - - template - static inline JS::Handle downcastHandle(HandleType v) { - return v.template as(); - } -}; - -template class MaybeRooted -{ - public: - typedef const T& HandleType; - typedef FakeRooted RootType; - typedef FakeMutableHandle MutableHandleType; - - static JS::Handle toHandle(HandleType v) { - MOZ_CRASH("Bad conversion"); - } - - static JS::MutableHandle toMutableHandle(MutableHandleType v) { - MOZ_CRASH("Bad conversion"); - } - - template - static inline T2* downcastHandle(HandleType v) { - return &v->template as(); - } -}; - -} /* namespace js */ - -namespace JS { - -template template -inline -Handle::Handle(const Rooted& root, - typename mozilla::EnableIf::value, int>::Type dummy) -{ - ptr = reinterpret_cast(root.address()); -} - -template template -inline -Handle::Handle(const PersistentRooted& root, - typename mozilla::EnableIf::value, int>::Type dummy) -{ - ptr = reinterpret_cast(root.address()); -} - -template template -inline -Handle::Handle(MutableHandle& root, - typename mozilla::EnableIf::value, int>::Type dummy) -{ - ptr = reinterpret_cast(root.address()); -} - -template -inline -MutableHandle::MutableHandle(Rooted* root) -{ - static_assert(sizeof(MutableHandle) == sizeof(T*), - "MutableHandle must be binary compatible with T*."); - ptr = root->address(); -} - -template -inline -MutableHandle::MutableHandle(PersistentRooted* root) -{ - static_assert(sizeof(MutableHandle) == sizeof(T*), - "MutableHandle must be binary compatible with T*."); - ptr = root->address(); -} - -/** - * A copyable, assignable global GC root type with arbitrary lifetime, an - * infallible constructor, and automatic unrooting on destruction. - * - * These roots can be used in heap-allocated data structures, so they are not - * associated with any particular JSContext or stack. They are registered with - * the JSRuntime itself, without locking, so they require a full JSContext to be - * initialized, not one of its more restricted superclasses. Initialization may - * take place on construction, or in two phases if the no-argument constructor - * is called followed by init(). - * - * Note that you must not use an PersistentRooted in an object owned by a JS - * object: - * - * Whenever one object whose lifetime is decided by the GC refers to another - * such object, that edge must be traced only if the owning JS object is traced. - * This applies not only to JS objects (which obviously are managed by the GC) - * but also to C++ objects owned by JS objects. - * - * If you put a PersistentRooted in such a C++ object, that is almost certainly - * a leak. When a GC begins, the referent of the PersistentRooted is treated as - * live, unconditionally (because a PersistentRooted is a *root*), even if the - * JS object that owns it is unreachable. If there is any path from that - * referent back to the JS object, then the C++ object containing the - * PersistentRooted will not be destructed, and the whole blob of objects will - * not be freed, even if there are no references to them from the outside. - * - * In the context of Firefox, this is a severe restriction: almost everything in - * Firefox is owned by some JS object or another, so using PersistentRooted in - * such objects would introduce leaks. For these kinds of edges, Heap or - * TenuredHeap would be better types. It's up to the implementor of the type - * containing Heap or TenuredHeap members to make sure their referents get - * marked when the object itself is marked. - */ -template -class PersistentRooted : public js::PersistentRootedBase, - private mozilla::LinkedListElement> -{ - using ListBase = mozilla::LinkedListElement>; - - friend class mozilla::LinkedList; - friend class mozilla::LinkedListElement; - - void registerWithRootLists(js::RootLists& roots) { - MOZ_ASSERT(!initialized()); - JS::RootKind kind = JS::MapTypeToRootKind::kind; - roots.heapRoots_[kind].insertBack(reinterpret_cast*>(this)); - } - - js::RootLists& rootLists(JSContext* cx) { - return rootLists(JS::RootingContext::get(cx)); - } - js::RootLists& rootLists(JS::RootingContext* cx) { - MOZ_ASSERT(cx->isJSContext); - return cx->roots; - } - - // Disallow ExclusiveContext*. - js::RootLists& rootLists(js::ContextFriendFields* cx) = delete; - - public: - PersistentRooted() : ptr(GCPolicy::initial()) {} - - template - explicit PersistentRooted(const RootingContext& cx) - : ptr(GCPolicy::initial()) - { - registerWithRootLists(rootLists(cx)); - } - - template - PersistentRooted(const RootingContext& cx, U&& initial) - : ptr(mozilla::Forward(initial)) - { - registerWithRootLists(rootLists(cx)); - } - - PersistentRooted(const PersistentRooted& rhs) - : mozilla::LinkedListElement>(), - ptr(rhs.ptr) - { - /* - * Copy construction takes advantage of the fact that the original - * is already inserted, and simply adds itself to whatever list the - * original was on - no JSRuntime pointer needed. - * - * This requires mutating rhs's links, but those should be 'mutable' - * anyway. C++ doesn't let us declare mutable base classes. - */ - const_cast(rhs).setNext(this); - } - - bool initialized() { - return ListBase::isInList(); - } - - template - void init(const RootingContext& cx) { - init(cx, GCPolicy::initial()); - } - - template - void init(const RootingContext& cx, U&& initial) { - ptr = mozilla::Forward(initial); - registerWithRootLists(rootLists(cx)); - } - - void reset() { - if (initialized()) { - set(GCPolicy::initial()); - ListBase::remove(); - } - } - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(PersistentRooted, T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr); - - // These are the same as DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS, except - // they check that |this| is initialized in case the caller later stores - // something in |ptr|. - T* address() { - MOZ_ASSERT(initialized()); - return &ptr; - } - T& get() { - MOZ_ASSERT(initialized()); - return ptr; - } - - private: - template - void set(U&& value) { - MOZ_ASSERT(initialized()); - ptr = mozilla::Forward(value); - } - - // See the comment above Rooted::ptr. - using MaybeWrapped = typename mozilla::Conditional< - MapTypeToRootKind::kind == JS::RootKind::Traceable, - js::DispatchWrapper, - T>::Type; - MaybeWrapped ptr; -} JS_HAZ_ROOTED; - -class JS_PUBLIC_API(ObjectPtr) -{ - Heap value; - - public: - ObjectPtr() : value(nullptr) {} - - explicit ObjectPtr(JSObject* obj) : value(obj) {} - - /* Always call finalize before the destructor. */ - ~ObjectPtr() { MOZ_ASSERT(!value); } - - void finalize(JSRuntime* rt); - void finalize(JSContext* cx); - - void init(JSObject* obj) { value = obj; } - - JSObject* get() const { return value; } - JSObject* unbarrieredGet() const { return value.unbarrieredGet(); } - - void writeBarrierPre(JSContext* cx) { - IncrementalObjectBarrier(value); - } - - void updateWeakPointerAfterGC(); - - ObjectPtr& operator=(JSObject* obj) { - IncrementalObjectBarrier(value); - value = obj; - return *this; - } - - void trace(JSTracer* trc, const char* name); - - JSObject& operator*() const { return *value; } - JSObject* operator->() const { return value; } - operator JSObject*() const { return value; } - - explicit operator bool() const { return value.unbarrieredGet(); } - explicit operator bool() { return value.unbarrieredGet(); } -}; - -} /* namespace JS */ - -namespace js { - -template -class UniquePtrOperations -{ - const UniquePtr& uniquePtr() const { return static_cast(this)->get(); } - - public: - explicit operator bool() const { return !!uniquePtr(); } -}; - -template -class MutableUniquePtrOperations : public UniquePtrOperations -{ - UniquePtr& uniquePtr() { return static_cast(this)->get(); } - - public: - MOZ_MUST_USE typename UniquePtr::Pointer release() { return uniquePtr().release(); } -}; - -template -class RootedBase> - : public MutableUniquePtrOperations>, T, D> -{ }; - -template -class MutableHandleBase> - : public MutableUniquePtrOperations>, T, D> -{ }; - -template -class HandleBase> - : public UniquePtrOperations>, T, D> -{ }; - -template -class PersistentRootedBase> - : public MutableUniquePtrOperations>, T, D> -{ }; - -namespace gc { - -template -void -CallTraceCallbackOnNonHeap(T* v, const TraceCallbacks& aCallbacks, const char* aName, void* aClosure) -{ - static_assert(sizeof(T) == sizeof(JS::Heap), "T and Heap must be compatible."); - MOZ_ASSERT(v); - mozilla::DebugOnly cell = BarrierMethods::asGCThingOrNull(*v); - MOZ_ASSERT(cell); - MOZ_ASSERT(!IsInsideNursery(cell)); - JS::Heap* asHeapT = reinterpret_cast*>(v); - aCallbacks.Trace(asHeapT, aName, aClosure); -} - -} /* namespace gc */ -} /* namespace js */ - -// mozilla::Swap uses a stack temporary, which prevents classes like Heap -// from being declared MOZ_HEAP_CLASS. -namespace mozilla { - -template -inline void -Swap(JS::Heap& aX, JS::Heap& aY) -{ - T tmp = aX; - aX = aY; - aY = tmp; -} - -template -inline void -Swap(JS::TenuredHeap& aX, JS::TenuredHeap& aY) -{ - T tmp = aX; - aX = aY; - aY = tmp; -} - -} /* namespace mozilla */ - -#undef DELETE_ASSIGNMENT_OPS - -#endif /* js_RootingAPI_h */ diff --git a/mac/include/spidermonkey/js/SliceBudget.h b/mac/include/spidermonkey/js/SliceBudget.h deleted file mode 100644 index 78982df0..00000000 --- a/mac/include/spidermonkey/js/SliceBudget.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_SliceBudget_h -#define js_SliceBudget_h - -#include - -namespace js { - -struct JS_PUBLIC_API(TimeBudget) -{ - int64_t budget; - - explicit TimeBudget(int64_t milliseconds) { budget = milliseconds; } -}; - -struct JS_PUBLIC_API(WorkBudget) -{ - int64_t budget; - - explicit WorkBudget(int64_t work) { budget = work; } -}; - -/* - * This class records how much work has been done in a given collection slice, - * so that we can return before pausing for too long. Some slices are allowed - * to run for unlimited time, and others are bounded. To reduce the number of - * gettimeofday calls, we only check the time every 1000 operations. - */ -class JS_PUBLIC_API(SliceBudget) -{ - static const int64_t unlimitedDeadline = INT64_MAX; - static const intptr_t unlimitedStartCounter = INTPTR_MAX; - - bool checkOverBudget(); - - SliceBudget(); - - public: - // Memory of the originally requested budget. If isUnlimited, neither of - // these are in use. If deadline==0, then workBudget is valid. Otherwise - // timeBudget is valid. - TimeBudget timeBudget; - WorkBudget workBudget; - - int64_t deadline; /* in microseconds */ - intptr_t counter; - - static const intptr_t CounterReset = 1000; - - static const int64_t UnlimitedTimeBudget = -1; - static const int64_t UnlimitedWorkBudget = -1; - - /* Use to create an unlimited budget. */ - static SliceBudget unlimited() { return SliceBudget(); } - - /* Instantiate as SliceBudget(TimeBudget(n)). */ - explicit SliceBudget(TimeBudget time); - - /* Instantiate as SliceBudget(WorkBudget(n)). */ - explicit SliceBudget(WorkBudget work); - - void makeUnlimited() { - deadline = unlimitedDeadline; - counter = unlimitedStartCounter; - } - - void step(intptr_t amt = 1) { - counter -= amt; - } - - bool isOverBudget() { - if (counter > 0) - return false; - return checkOverBudget(); - } - - bool isWorkBudget() const { return deadline == 0; } - bool isTimeBudget() const { return deadline > 0 && !isUnlimited(); } - bool isUnlimited() const { return deadline == unlimitedDeadline; } - - int describe(char* buffer, size_t maxlen) const; -}; - -} // namespace js - -#endif /* js_SliceBudget_h */ diff --git a/mac/include/spidermonkey/js/StructuredClone.h b/mac/include/spidermonkey/js/StructuredClone.h deleted file mode 100644 index e10a3073..00000000 --- a/mac/include/spidermonkey/js/StructuredClone.h +++ /dev/null @@ -1,358 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_StructuredClone_h -#define js_StructuredClone_h - -#include "mozilla/Attributes.h" -#include "mozilla/BufferList.h" - -#include - -#include "jstypes.h" - -#include "js/RootingAPI.h" -#include "js/TypeDecls.h" -#include "js/Value.h" - -struct JSRuntime; -struct JSStructuredCloneReader; -struct JSStructuredCloneWriter; - -// API for the HTML5 internal structured cloning algorithm. - -namespace JS { - -enum class StructuredCloneScope : uint32_t { - SameProcessSameThread, - SameProcessDifferentThread, - DifferentProcess -}; - -enum TransferableOwnership { - /** Transferable data has not been filled in yet */ - SCTAG_TMO_UNFILLED = 0, - - /** Structured clone buffer does not yet own the data */ - SCTAG_TMO_UNOWNED = 1, - - /** All values at least this large are owned by the clone buffer */ - SCTAG_TMO_FIRST_OWNED = 2, - - /** Data is a pointer that can be freed */ - SCTAG_TMO_ALLOC_DATA = 2, - - /** Data is a memory mapped pointer */ - SCTAG_TMO_MAPPED_DATA = 3, - - /** - * Data is embedding-specific. The engine can free it by calling the - * freeTransfer op. The embedding can also use SCTAG_TMO_USER_MIN and - * greater, up to 32 bits, to distinguish specific ownership variants. - */ - SCTAG_TMO_CUSTOM = 4, - - SCTAG_TMO_USER_MIN -}; - -class CloneDataPolicy -{ - bool sharedArrayBuffer_; - - public: - // The default is to allow all policy-controlled aspects. - - CloneDataPolicy() : - sharedArrayBuffer_(true) - {} - - // In the JS engine, SharedArrayBuffers can only be cloned intra-process - // because the shared memory areas are allocated in process-private memory. - // Clients should therefore deny SharedArrayBuffers when cloning data that - // are to be transmitted inter-process. - // - // Clients should also deny SharedArrayBuffers when cloning data that are to - // be transmitted intra-process if policy needs dictate such denial. - - CloneDataPolicy& denySharedArrayBuffer() { - sharedArrayBuffer_ = false; - return *this; - } - - bool isSharedArrayBufferAllowed() const { - return sharedArrayBuffer_; - } -}; - -} /* namespace JS */ - -/** - * Read structured data from the reader r. This hook is used to read a value - * previously serialized by a call to the WriteStructuredCloneOp hook. - * - * tag and data are the pair of uint32_t values from the header. The callback - * may use the JS_Read* APIs to read any other relevant parts of the object - * from the reader r. closure is any value passed to the JS_ReadStructuredClone - * function. Return the new object on success, nullptr on error/exception. - */ -typedef JSObject* (*ReadStructuredCloneOp)(JSContext* cx, JSStructuredCloneReader* r, - uint32_t tag, uint32_t data, void* closure); - -/** - * Structured data serialization hook. The engine can write primitive values, - * Objects, Arrays, Dates, RegExps, TypedArrays, ArrayBuffers, Sets, Maps, - * and SharedTypedArrays. Any other type of object requires application support. - * This callback must first use the JS_WriteUint32Pair API to write an object - * header, passing a value greater than JS_SCTAG_USER to the tag parameter. - * Then it can use the JS_Write* APIs to write any other relevant parts of - * the value v to the writer w. closure is any value passed to the - * JS_WriteStructuredClone function. - * - * Return true on success, false on error/exception. - */ -typedef bool (*WriteStructuredCloneOp)(JSContext* cx, JSStructuredCloneWriter* w, - JS::HandleObject obj, void* closure); - -/** - * This is called when JS_WriteStructuredClone is given an invalid transferable. - * To follow HTML5, the application must throw a DATA_CLONE_ERR DOMException - * with error set to one of the JS_SCERR_* values. - */ -typedef void (*StructuredCloneErrorOp)(JSContext* cx, uint32_t errorid); - -/** - * This is called when JS_ReadStructuredClone receives a transferable object - * not known to the engine. If this hook does not exist or returns false, the - * JS engine calls the reportError op if set, otherwise it throws a - * DATA_CLONE_ERR DOM Exception. This method is called before any other - * callback and must return a non-null object in returnObject on success. - */ -typedef bool (*ReadTransferStructuredCloneOp)(JSContext* cx, JSStructuredCloneReader* r, - uint32_t tag, void* content, uint64_t extraData, - void* closure, - JS::MutableHandleObject returnObject); - -/** - * Called when JS_WriteStructuredClone receives a transferable object not - * handled by the engine. If this hook does not exist or returns false, the JS - * engine will call the reportError hook or fall back to throwing a - * DATA_CLONE_ERR DOM Exception. This method is called before any other - * callback. - * - * tag: indicates what type of transferable this is. Must be greater than - * 0xFFFF0201 (value of the internal SCTAG_TRANSFER_MAP_PENDING_ENTRY) - * - * ownership: see TransferableOwnership, above. Used to communicate any needed - * ownership info to the FreeTransferStructuredCloneOp. - * - * content, extraData: what the ReadTransferStructuredCloneOp will receive - */ -typedef bool (*TransferStructuredCloneOp)(JSContext* cx, - JS::Handle obj, - void* closure, - // Output: - uint32_t* tag, - JS::TransferableOwnership* ownership, - void** content, - uint64_t* extraData); - -/** - * Called when freeing an unknown transferable object. Note that it - * should never trigger a garbage collection (and will assert in a - * debug build if it does.) - */ -typedef void (*FreeTransferStructuredCloneOp)(uint32_t tag, JS::TransferableOwnership ownership, - void* content, uint64_t extraData, void* closure); - -// The maximum supported structured-clone serialization format version. -// Increment this when anything at all changes in the serialization format. -// (Note that this does not need to be bumped for Transferable-only changes, -// since they are never saved to persistent storage.) -#define JS_STRUCTURED_CLONE_VERSION 8 - -struct JSStructuredCloneCallbacks { - ReadStructuredCloneOp read; - WriteStructuredCloneOp write; - StructuredCloneErrorOp reportError; - ReadTransferStructuredCloneOp readTransfer; - TransferStructuredCloneOp writeTransfer; - FreeTransferStructuredCloneOp freeTransfer; -}; - -enum OwnTransferablePolicy { - OwnsTransferablesIfAny, - IgnoreTransferablesIfAny, - NoTransferables -}; - -class MOZ_NON_MEMMOVABLE JSStructuredCloneData : public mozilla::BufferList -{ - typedef js::SystemAllocPolicy AllocPolicy; - typedef mozilla::BufferList BufferList; - - static const size_t kInitialSize = 0; - static const size_t kInitialCapacity = 4096; - static const size_t kStandardCapacity = 4096; - - const JSStructuredCloneCallbacks* callbacks_; - void* closure_; - OwnTransferablePolicy ownTransferables_; - - void setOptionalCallbacks(const JSStructuredCloneCallbacks* callbacks, - void* closure, - OwnTransferablePolicy policy) { - callbacks_ = callbacks; - closure_ = closure; - ownTransferables_ = policy; - } - - friend struct JSStructuredCloneWriter; - friend class JS_PUBLIC_API(JSAutoStructuredCloneBuffer); - -public: - explicit JSStructuredCloneData(AllocPolicy aAP = AllocPolicy()) - : BufferList(kInitialSize, kInitialCapacity, kStandardCapacity, aAP) - , callbacks_(nullptr) - , closure_(nullptr) - , ownTransferables_(OwnTransferablePolicy::NoTransferables) - {} - MOZ_IMPLICIT JSStructuredCloneData(BufferList&& buffers) - : BufferList(Move(buffers)) - , callbacks_(nullptr) - , closure_(nullptr) - , ownTransferables_(OwnTransferablePolicy::NoTransferables) - {} - JSStructuredCloneData(JSStructuredCloneData&& other) = default; - JSStructuredCloneData& operator=(JSStructuredCloneData&& other) = default; - ~JSStructuredCloneData(); - - using BufferList::BufferList; -}; - -/** Note: if the *data contains transferable objects, it can be read only once. */ -JS_PUBLIC_API(bool) -JS_ReadStructuredClone(JSContext* cx, JSStructuredCloneData& data, uint32_t version, - JS::StructuredCloneScope scope, - JS::MutableHandleValue vp, - const JSStructuredCloneCallbacks* optionalCallbacks, void* closure); - -JS_PUBLIC_API(bool) -JS_WriteStructuredClone(JSContext* cx, JS::HandleValue v, JSStructuredCloneData* data, - JS::StructuredCloneScope scope, - JS::CloneDataPolicy cloneDataPolicy, - const JSStructuredCloneCallbacks* optionalCallbacks, - void* closure, JS::HandleValue transferable); - -JS_PUBLIC_API(bool) -JS_StructuredCloneHasTransferables(JSStructuredCloneData& data, bool* hasTransferable); - -JS_PUBLIC_API(bool) -JS_StructuredClone(JSContext* cx, JS::HandleValue v, JS::MutableHandleValue vp, - const JSStructuredCloneCallbacks* optionalCallbacks, void* closure); - -/** RAII sugar for JS_WriteStructuredClone. */ -class JS_PUBLIC_API(JSAutoStructuredCloneBuffer) { - const JS::StructuredCloneScope scope_; - JSStructuredCloneData data_; - uint32_t version_; - - public: - JSAutoStructuredCloneBuffer(JS::StructuredCloneScope scope, - const JSStructuredCloneCallbacks* callbacks, void* closure) - : scope_(scope), version_(JS_STRUCTURED_CLONE_VERSION) - { - data_.setOptionalCallbacks(callbacks, closure, OwnTransferablePolicy::NoTransferables); - } - - JSAutoStructuredCloneBuffer(JSAutoStructuredCloneBuffer&& other); - JSAutoStructuredCloneBuffer& operator=(JSAutoStructuredCloneBuffer&& other); - - ~JSAutoStructuredCloneBuffer() { clear(); } - - JSStructuredCloneData& data() { return data_; } - bool empty() const { return !data_.Size(); } - - void clear(const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - /** Copy some memory. It will be automatically freed by the destructor. */ - bool copy(const JSStructuredCloneData& data, uint32_t version=JS_STRUCTURED_CLONE_VERSION, - const JSStructuredCloneCallbacks* callbacks=nullptr, void* closure=nullptr); - - /** - * Adopt some memory. It will be automatically freed by the destructor. - * data must have been allocated by the JS engine (e.g., extracted via - * JSAutoStructuredCloneBuffer::steal). - */ - void adopt(JSStructuredCloneData&& data, uint32_t version=JS_STRUCTURED_CLONE_VERSION, - const JSStructuredCloneCallbacks* callbacks=nullptr, void* closure=nullptr); - - /** - * Release the buffer and transfer ownership to the caller. - */ - void steal(JSStructuredCloneData* data, uint32_t* versionp=nullptr, - const JSStructuredCloneCallbacks** callbacks=nullptr, void** closure=nullptr); - - /** - * Abandon ownership of any transferable objects stored in the buffer, - * without freeing the buffer itself. Useful when copying the data out into - * an external container, though note that you will need to use adopt() to - * properly release that data eventually. - */ - void abandon() { data_.ownTransferables_ = OwnTransferablePolicy::IgnoreTransferablesIfAny; } - - bool read(JSContext* cx, JS::MutableHandleValue vp, - const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - bool write(JSContext* cx, JS::HandleValue v, - const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - bool write(JSContext* cx, JS::HandleValue v, JS::HandleValue transferable, - JS::CloneDataPolicy cloneDataPolicy, - const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - private: - // Copy and assignment are not supported. - JSAutoStructuredCloneBuffer(const JSAutoStructuredCloneBuffer& other) = delete; - JSAutoStructuredCloneBuffer& operator=(const JSAutoStructuredCloneBuffer& other) = delete; -}; - -// The range of tag values the application may use for its own custom object types. -#define JS_SCTAG_USER_MIN ((uint32_t) 0xFFFF8000) -#define JS_SCTAG_USER_MAX ((uint32_t) 0xFFFFFFFF) - -#define JS_SCERR_RECURSION 0 -#define JS_SCERR_TRANSFERABLE 1 -#define JS_SCERR_DUP_TRANSFERABLE 2 -#define JS_SCERR_UNSUPPORTED_TYPE 3 - -JS_PUBLIC_API(bool) -JS_ReadUint32Pair(JSStructuredCloneReader* r, uint32_t* p1, uint32_t* p2); - -JS_PUBLIC_API(bool) -JS_ReadBytes(JSStructuredCloneReader* r, void* p, size_t len); - -JS_PUBLIC_API(bool) -JS_ReadTypedArray(JSStructuredCloneReader* r, JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_WriteUint32Pair(JSStructuredCloneWriter* w, uint32_t tag, uint32_t data); - -JS_PUBLIC_API(bool) -JS_WriteBytes(JSStructuredCloneWriter* w, const void* p, size_t len); - -JS_PUBLIC_API(bool) -JS_WriteString(JSStructuredCloneWriter* w, JS::HandleString str); - -JS_PUBLIC_API(bool) -JS_WriteTypedArray(JSStructuredCloneWriter* w, JS::HandleValue v); - -JS_PUBLIC_API(bool) -JS_ObjectNotWritten(JSStructuredCloneWriter* w, JS::HandleObject obj); - -JS_PUBLIC_API(JS::StructuredCloneScope) -JS_GetStructuredCloneScope(JSStructuredCloneWriter* w); - -#endif /* js_StructuredClone_h */ diff --git a/mac/include/spidermonkey/js/SweepingAPI.h b/mac/include/spidermonkey/js/SweepingAPI.h deleted file mode 100644 index 0eb29ae4..00000000 --- a/mac/include/spidermonkey/js/SweepingAPI.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_SweepingAPI_h -#define js_SweepingAPI_h - -#include "js/HeapAPI.h" - -namespace js { -template -class WeakCacheBase {}; -} // namespace js - -namespace JS { -template class WeakCache; - -namespace shadow { -JS_PUBLIC_API(void) -RegisterWeakCache(JS::Zone* zone, JS::WeakCache* cachep); -} // namespace shadow - -// A WeakCache stores the given Sweepable container and links itself into a -// list of such caches that are swept during each GC. -template -class WeakCache : public js::WeakCacheBase, - private mozilla::LinkedListElement> -{ - friend class mozilla::LinkedListElement>; - friend class mozilla::LinkedList>; - - WeakCache() = delete; - WeakCache(const WeakCache&) = delete; - - using SweepFn = void (*)(T*); - SweepFn sweeper; - T cache; - - public: - using Type = T; - - template - WeakCache(Zone* zone, U&& initial) - : cache(mozilla::Forward(initial)) - { - sweeper = GCPolicy::sweep; - shadow::RegisterWeakCache(zone, reinterpret_cast*>(this)); - } - WeakCache(WeakCache&& other) - : sweeper(other.sweeper), - cache(mozilla::Move(other.cache)) - { - } - - const T& get() const { return cache; } - T& get() { return cache; } - - void sweep() { sweeper(&cache); } -}; - -} // namespace JS - -#endif // js_SweepingAPI_h diff --git a/mac/include/spidermonkey/js/TraceKind.h b/mac/include/spidermonkey/js/TraceKind.h deleted file mode 100644 index 2eda9cb2..00000000 --- a/mac/include/spidermonkey/js/TraceKind.h +++ /dev/null @@ -1,212 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_TraceKind_h -#define js_TraceKind_h - -#include "mozilla/UniquePtr.h" - -#include "js/TypeDecls.h" - -// Forward declarations of all the types a TraceKind can denote. -namespace js { -class BaseShape; -class LazyScript; -class ObjectGroup; -class Shape; -class Scope; -namespace jit { -class JitCode; -} // namespace jit -} // namespace js - -namespace JS { - -// When tracing a thing, the GC needs to know about the layout of the object it -// is looking at. There are a fixed number of different layouts that the GC -// knows about. The "trace kind" is a static map which tells which layout a GC -// thing has. -// -// Although this map is public, the details are completely hidden. Not all of -// the matching C++ types are exposed, and those that are, are opaque. -// -// See Value::gcKind() and JSTraceCallback in Tracer.h for more details. -enum class TraceKind -{ - // These trace kinds have a publicly exposed, although opaque, C++ type. - // Note: The order here is determined by our Value packing. Other users - // should sort alphabetically, for consistency. - Object = 0x00, - String = 0x01, - Symbol = 0x02, - Script = 0x03, - - // Shape details are exposed through JS_TraceShapeCycleCollectorChildren. - Shape = 0x04, - - // ObjectGroup details are exposed through JS_TraceObjectGroupCycleCollectorChildren. - ObjectGroup = 0x05, - - // The kind associated with a nullptr. - Null = 0x06, - - // The following kinds do not have an exposed C++ idiom. - BaseShape = 0x0F, - JitCode = 0x1F, - LazyScript = 0x2F, - Scope = 0x3F -}; -const static uintptr_t OutOfLineTraceKindMask = 0x07; -static_assert(uintptr_t(JS::TraceKind::BaseShape) & OutOfLineTraceKindMask, "mask bits are set"); -static_assert(uintptr_t(JS::TraceKind::JitCode) & OutOfLineTraceKindMask, "mask bits are set"); -static_assert(uintptr_t(JS::TraceKind::LazyScript) & OutOfLineTraceKindMask, "mask bits are set"); -static_assert(uintptr_t(JS::TraceKind::Scope) & OutOfLineTraceKindMask, "mask bits are set"); - -// When this header is imported inside SpiderMonkey, the class definitions are -// available and we can query those definitions to find the correct kind -// directly from the class hierarchy. -template -struct MapTypeToTraceKind { - static const JS::TraceKind kind = T::TraceKind; -}; - -// When this header is used outside SpiderMonkey, the class definitions are not -// available, so the following table containing all public GC types is used. -#define JS_FOR_EACH_TRACEKIND(D) \ - /* PrettyName TypeName AddToCCKind */ \ - D(BaseShape, js::BaseShape, true) \ - D(JitCode, js::jit::JitCode, true) \ - D(LazyScript, js::LazyScript, true) \ - D(Scope, js::Scope, true) \ - D(Object, JSObject, true) \ - D(ObjectGroup, js::ObjectGroup, true) \ - D(Script, JSScript, true) \ - D(Shape, js::Shape, true) \ - D(String, JSString, false) \ - D(Symbol, JS::Symbol, false) - -// Map from all public types to their trace kind. -#define JS_EXPAND_DEF(name, type, _) \ - template <> struct MapTypeToTraceKind { \ - static const JS::TraceKind kind = JS::TraceKind::name; \ - }; -JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - -// RootKind is closely related to TraceKind. Whereas TraceKind's indices are -// laid out for convenient embedding as a pointer tag, the indicies of RootKind -// are designed for use as array keys via EnumeratedArray. -enum class RootKind : int8_t -{ - // These map 1:1 with trace kinds. -#define EXPAND_ROOT_KIND(name, _0, _1) \ - name, -JS_FOR_EACH_TRACEKIND(EXPAND_ROOT_KIND) -#undef EXPAND_ROOT_KIND - - // These tagged pointers are special-cased for performance. - Id, - Value, - - // Everything else. - Traceable, - - Limit -}; - -// Most RootKind correspond directly to a trace kind. -template struct MapTraceKindToRootKind {}; -#define JS_EXPAND_DEF(name, _0, _1) \ - template <> struct MapTraceKindToRootKind { \ - static const JS::RootKind kind = JS::RootKind::name; \ - }; -JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF) -#undef JS_EXPAND_DEF - -// Specify the RootKind for all types. Value and jsid map to special cases; -// pointer types we can derive directly from the TraceKind; everything else -// should go in the Traceable list and use GCPolicy::trace for tracing. -template -struct MapTypeToRootKind { - static const JS::RootKind kind = JS::RootKind::Traceable; -}; -template -struct MapTypeToRootKind { - static const JS::RootKind kind = - JS::MapTraceKindToRootKind::kind>::kind; -}; -template -struct MapTypeToRootKind> { - static const JS::RootKind kind = JS::MapTypeToRootKind::kind; -}; -template <> struct MapTypeToRootKind { - static const JS::RootKind kind = JS::RootKind::Value; -}; -template <> struct MapTypeToRootKind { - static const JS::RootKind kind = JS::RootKind::Id; -}; -template <> struct MapTypeToRootKind : public MapTypeToRootKind {}; - -// Fortunately, few places in the system need to deal with fully abstract -// cells. In those places that do, we generally want to move to a layout -// templated function as soon as possible. This template wraps the upcast -// for that dispatch. -// -// Given a call: -// -// DispatchTraceKindTyped(f, thing, traceKind, ... args) -// -// Downcast the |void *thing| to the specific type designated by |traceKind|, -// and pass it to the functor |f| along with |... args|, forwarded. Pass the -// type designated by |traceKind| as the functor's template argument. The -// |thing| parameter is optional; without it, we simply pass through |... args|. - -// GCC and Clang require an explicit template declaration in front of the -// specialization of operator() because it is a dependent template. MSVC, on -// the other hand, gets very confused if we have a |template| token there. -// The clang-cl front end defines _MSC_VER, but still requires the explicit -// template declaration, so we must test for __clang__ here as well. -#if defined(_MSC_VER) && !defined(__clang__) -# define JS_DEPENDENT_TEMPLATE_HINT -#else -# define JS_DEPENDENT_TEMPLATE_HINT template -#endif -template -auto -DispatchTraceKindTyped(F f, JS::TraceKind traceKind, Args&&... args) - -> decltype(f. JS_DEPENDENT_TEMPLATE_HINT operator()(mozilla::Forward(args)...)) -{ - switch (traceKind) { -#define JS_EXPAND_DEF(name, type, _) \ - case JS::TraceKind::name: \ - return f. JS_DEPENDENT_TEMPLATE_HINT operator()(mozilla::Forward(args)...); - JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - default: - MOZ_CRASH("Invalid trace kind in DispatchTraceKindTyped."); - } -} -#undef JS_DEPENDENT_TEMPLATE_HINT - -template -auto -DispatchTraceKindTyped(F f, void* thing, JS::TraceKind traceKind, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - switch (traceKind) { -#define JS_EXPAND_DEF(name, type, _) \ - case JS::TraceKind::name: \ - return f(static_cast(thing), mozilla::Forward(args)...); - JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - default: - MOZ_CRASH("Invalid trace kind in DispatchTraceKindTyped."); - } -} - -} // namespace JS - -#endif // js_TraceKind_h diff --git a/mac/include/spidermonkey/js/TracingAPI.h b/mac/include/spidermonkey/js/TracingAPI.h deleted file mode 100644 index 37c69aca..00000000 --- a/mac/include/spidermonkey/js/TracingAPI.h +++ /dev/null @@ -1,403 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_TracingAPI_h -#define js_TracingAPI_h - -#include "jsalloc.h" - -#include "js/HashTable.h" -#include "js/HeapAPI.h" -#include "js/TraceKind.h" - -class JS_PUBLIC_API(JSTracer); - -namespace JS { -class JS_PUBLIC_API(CallbackTracer); -template class Heap; -template class TenuredHeap; - -/** Returns a static string equivalent of |kind|. */ -JS_FRIEND_API(const char*) -GCTraceKindToAscii(JS::TraceKind kind); - -} // namespace JS - -enum WeakMapTraceKind { - /** - * Do not trace into weak map keys or values during traversal. Users must - * handle weak maps manually. - */ - DoNotTraceWeakMaps, - - /** - * Do true ephemeron marking with a weak key lookup marking phase. This is - * the default for GCMarker. - */ - ExpandWeakMaps, - - /** - * Trace through to all values, irrespective of whether the keys are live - * or not. Used for non-marking tracers. - */ - TraceWeakMapValues, - - /** - * Trace through to all keys and values, irrespective of whether the keys - * are live or not. Used for non-marking tracers. - */ - TraceWeakMapKeysValues -}; - -class JS_PUBLIC_API(JSTracer) -{ - public: - // Return the runtime set on the tracer. - JSRuntime* runtime() const { return runtime_; } - - // Return the weak map tracing behavior currently set on this tracer. - WeakMapTraceKind weakMapAction() const { return weakMapAction_; } - - enum class TracerKindTag { - // Marking path: a tracer used only for marking liveness of cells, not - // for moving them. The kind will transition to WeakMarking after - // everything reachable by regular edges has been marked. - Marking, - - // Same as Marking, except we have now moved on to the "weak marking - // phase", in which every marked obj/script is immediately looked up to - // see if it is a weak map key (and therefore might require marking its - // weak map value). - WeakMarking, - - // A tracer that traverses the graph for the purposes of moving objects - // from the nursery to the tenured area. - Tenuring, - - // General-purpose traversal that invokes a callback on each cell. - // Traversing children is the responsibility of the callback. - Callback - }; - bool isMarkingTracer() const { return tag_ == TracerKindTag::Marking || tag_ == TracerKindTag::WeakMarking; } - bool isWeakMarkingTracer() const { return tag_ == TracerKindTag::WeakMarking; } - bool isTenuringTracer() const { return tag_ == TracerKindTag::Tenuring; } - bool isCallbackTracer() const { return tag_ == TracerKindTag::Callback; } - inline JS::CallbackTracer* asCallbackTracer(); -#ifdef DEBUG - bool checkEdges() { return checkEdges_; } -#endif - - protected: - JSTracer(JSRuntime* rt, TracerKindTag tag, - WeakMapTraceKind weakTraceKind = TraceWeakMapValues) - : runtime_(rt) - , weakMapAction_(weakTraceKind) -#ifdef DEBUG - , checkEdges_(true) -#endif - , tag_(tag) - {} - -#ifdef DEBUG - // Set whether to check edges are valid in debug builds. - void setCheckEdges(bool check) { - checkEdges_ = check; - } -#endif - - private: - JSRuntime* runtime_; - WeakMapTraceKind weakMapAction_; -#ifdef DEBUG - bool checkEdges_; -#endif - - protected: - TracerKindTag tag_; -}; - -namespace JS { - -class AutoTracingName; -class AutoTracingIndex; -class AutoTracingCallback; - -class JS_PUBLIC_API(CallbackTracer) : public JSTracer -{ - public: - CallbackTracer(JSRuntime* rt, WeakMapTraceKind weakTraceKind = TraceWeakMapValues) - : JSTracer(rt, JSTracer::TracerKindTag::Callback, weakTraceKind), - contextName_(nullptr), contextIndex_(InvalidIndex), contextFunctor_(nullptr) - {} - CallbackTracer(JSContext* cx, WeakMapTraceKind weakTraceKind = TraceWeakMapValues); - - // Override these methods to receive notification when an edge is visited - // with the type contained in the callback. The default implementation - // dispatches to the fully-generic onChild implementation, so for cases that - // do not care about boxing overhead and do not need the actual edges, - // just override the generic onChild. - virtual void onObjectEdge(JSObject** objp) { onChild(JS::GCCellPtr(*objp)); } - virtual void onStringEdge(JSString** strp) { onChild(JS::GCCellPtr(*strp)); } - virtual void onSymbolEdge(JS::Symbol** symp) { onChild(JS::GCCellPtr(*symp)); } - virtual void onScriptEdge(JSScript** scriptp) { onChild(JS::GCCellPtr(*scriptp)); } - virtual void onShapeEdge(js::Shape** shapep) { - onChild(JS::GCCellPtr(*shapep, JS::TraceKind::Shape)); - } - virtual void onObjectGroupEdge(js::ObjectGroup** groupp) { - onChild(JS::GCCellPtr(*groupp, JS::TraceKind::ObjectGroup)); - } - virtual void onBaseShapeEdge(js::BaseShape** basep) { - onChild(JS::GCCellPtr(*basep, JS::TraceKind::BaseShape)); - } - virtual void onJitCodeEdge(js::jit::JitCode** codep) { - onChild(JS::GCCellPtr(*codep, JS::TraceKind::JitCode)); - } - virtual void onLazyScriptEdge(js::LazyScript** lazyp) { - onChild(JS::GCCellPtr(*lazyp, JS::TraceKind::LazyScript)); - } - virtual void onScopeEdge(js::Scope** scopep) { - onChild(JS::GCCellPtr(*scopep, JS::TraceKind::Scope)); - } - - // Override this method to receive notification when a node in the GC - // heap graph is visited. - virtual void onChild(const JS::GCCellPtr& thing) = 0; - - // Access to the tracing context: - // When tracing with a JS::CallbackTracer, we invoke the callback with the - // edge location and the type of target. This is useful for operating on - // the edge in the abstract or on the target thing, satisfying most common - // use cases. However, some tracers need additional detail about the - // specific edge that is being traced in order to be useful. Unfortunately, - // the raw pointer to the edge that we provide is not enough information to - // infer much of anything useful about that edge. - // - // In order to better support use cases that care in particular about edges - // -- as opposed to the target thing -- tracing implementations are - // responsible for providing extra context information about each edge they - // trace, as it is traced. This contains, at a minimum, an edge name and, - // when tracing an array, the index. Further specialization can be achived - // (with some complexity), by associating a functor with the tracer so - // that, when requested, the user can generate totally custom edge - // descriptions. - - // Returns the current edge's name. It is only valid to call this when - // inside the trace callback, however, the edge name will always be set. - const char* contextName() const { MOZ_ASSERT(contextName_); return contextName_; } - - // Returns the current edge's index, if marked as part of an array of edges. - // This must be called only inside the trace callback. When not tracing an - // array, the value will be InvalidIndex. - const static size_t InvalidIndex = size_t(-1); - size_t contextIndex() const { return contextIndex_; } - - // Build a description of this edge in the heap graph. This call may invoke - // the context functor, if set, which may inspect arbitrary areas of the - // heap. On the other hand, the description provided by this method may be - // substantially more accurate and useful than those provided by only the - // contextName and contextIndex. - void getTracingEdgeName(char* buffer, size_t bufferSize); - - // The trace implementation may associate a callback with one or more edges - // using AutoTracingDetails. This functor is called by getTracingEdgeName - // and is responsible for providing a textual representation of the - // currently being traced edge. The callback has access to the full heap, - // including the currently set tracing context. - class ContextFunctor { - public: - virtual void operator()(CallbackTracer* trc, char* buf, size_t bufsize) = 0; - }; - -#ifdef DEBUG - enum class TracerKind { DoNotCare, Moving, GrayBuffering, VerifyTraceProtoAndIface }; - virtual TracerKind getTracerKind() const { return TracerKind::DoNotCare; } -#endif - - // In C++, overriding a method hides all methods in the base class with - // that name, not just methods with that signature. Thus, the typed edge - // methods have to have distinct names to allow us to override them - // individually, which is freqently useful if, for example, we only want to - // process only one type of edge. - void dispatchToOnEdge(JSObject** objp) { onObjectEdge(objp); } - void dispatchToOnEdge(JSString** strp) { onStringEdge(strp); } - void dispatchToOnEdge(JS::Symbol** symp) { onSymbolEdge(symp); } - void dispatchToOnEdge(JSScript** scriptp) { onScriptEdge(scriptp); } - void dispatchToOnEdge(js::Shape** shapep) { onShapeEdge(shapep); } - void dispatchToOnEdge(js::ObjectGroup** groupp) { onObjectGroupEdge(groupp); } - void dispatchToOnEdge(js::BaseShape** basep) { onBaseShapeEdge(basep); } - void dispatchToOnEdge(js::jit::JitCode** codep) { onJitCodeEdge(codep); } - void dispatchToOnEdge(js::LazyScript** lazyp) { onLazyScriptEdge(lazyp); } - void dispatchToOnEdge(js::Scope** scopep) { onScopeEdge(scopep); } - - private: - friend class AutoTracingName; - const char* contextName_; - - friend class AutoTracingIndex; - size_t contextIndex_; - - friend class AutoTracingDetails; - ContextFunctor* contextFunctor_; -}; - -// Set the name portion of the tracer's context for the current edge. -class MOZ_RAII AutoTracingName -{ - CallbackTracer* trc_; - const char* prior_; - - public: - AutoTracingName(CallbackTracer* trc, const char* name) : trc_(trc), prior_(trc->contextName_) { - MOZ_ASSERT(name); - trc->contextName_ = name; - } - ~AutoTracingName() { - MOZ_ASSERT(trc_->contextName_); - trc_->contextName_ = prior_; - } -}; - -// Set the index portion of the tracer's context for the current range. -class MOZ_RAII AutoTracingIndex -{ - CallbackTracer* trc_; - - public: - explicit AutoTracingIndex(JSTracer* trc, size_t initial = 0) : trc_(nullptr) { - if (trc->isCallbackTracer()) { - trc_ = trc->asCallbackTracer(); - MOZ_ASSERT(trc_->contextIndex_ == CallbackTracer::InvalidIndex); - trc_->contextIndex_ = initial; - } - } - ~AutoTracingIndex() { - if (trc_) { - MOZ_ASSERT(trc_->contextIndex_ != CallbackTracer::InvalidIndex); - trc_->contextIndex_ = CallbackTracer::InvalidIndex; - } - } - - void operator++() { - if (trc_) { - MOZ_ASSERT(trc_->contextIndex_ != CallbackTracer::InvalidIndex); - ++trc_->contextIndex_; - } - } -}; - -// Set a context callback for the trace callback to use, if it needs a detailed -// edge description. -class MOZ_RAII AutoTracingDetails -{ - CallbackTracer* trc_; - - public: - AutoTracingDetails(JSTracer* trc, CallbackTracer::ContextFunctor& func) : trc_(nullptr) { - if (trc->isCallbackTracer()) { - trc_ = trc->asCallbackTracer(); - MOZ_ASSERT(trc_->contextFunctor_ == nullptr); - trc_->contextFunctor_ = &func; - } - } - ~AutoTracingDetails() { - if (trc_) { - MOZ_ASSERT(trc_->contextFunctor_); - trc_->contextFunctor_ = nullptr; - } - } -}; - -} // namespace JS - -JS::CallbackTracer* -JSTracer::asCallbackTracer() -{ - MOZ_ASSERT(isCallbackTracer()); - return static_cast(this); -} - -namespace JS { - -// The JS::TraceEdge family of functions traces the given GC thing reference. -// This performs the tracing action configured on the given JSTracer: typically -// calling the JSTracer::callback or marking the thing as live. -// -// The argument to JS::TraceEdge is an in-out param: when the function returns, -// the garbage collector might have moved the GC thing. In this case, the -// reference passed to JS::TraceEdge will be updated to the thing's new -// location. Callers of this method are responsible for updating any state that -// is dependent on the object's address. For example, if the object's address -// is used as a key in a hashtable, then the object must be removed and -// re-inserted with the correct hash. -// -// Note that while |edgep| must never be null, it is fine for |*edgep| to be -// nullptr. -template -extern JS_PUBLIC_API(void) -TraceEdge(JSTracer* trc, JS::Heap* edgep, const char* name); - -extern JS_PUBLIC_API(void) -TraceEdge(JSTracer* trc, JS::TenuredHeap* edgep, const char* name); - -// Edges that are always traced as part of root marking do not require -// incremental barriers. This function allows for marking non-barriered -// pointers, but asserts that this happens during root marking. -// -// Note that while |edgep| must never be null, it is fine for |*edgep| to be -// nullptr. -template -extern JS_PUBLIC_API(void) -UnsafeTraceRoot(JSTracer* trc, T* edgep, const char* name); - -extern JS_PUBLIC_API(void) -TraceChildren(JSTracer* trc, GCCellPtr thing); - -using ZoneSet = js::HashSet, js::SystemAllocPolicy>; -using CompartmentSet = js::HashSet, - js::SystemAllocPolicy>; - -/** - * Trace every value within |compartments| that is wrapped by a - * cross-compartment wrapper from a compartment that is not an element of - * |compartments|. - */ -extern JS_PUBLIC_API(void) -TraceIncomingCCWs(JSTracer* trc, const JS::CompartmentSet& compartments); - -} // namespace JS - -extern JS_PUBLIC_API(void) -JS_GetTraceThingInfo(char* buf, size_t bufsize, JSTracer* trc, - void* thing, JS::TraceKind kind, bool includeDetails); - -namespace js { - -// Trace an edge that is not a GC root and is not wrapped in a barriered -// wrapper for some reason. -// -// This method does not check if |*edgep| is non-null before tracing through -// it, so callers must check any nullable pointer before calling this method. -template -extern JS_PUBLIC_API(void) -UnsafeTraceManuallyBarrieredEdge(JSTracer* trc, T* edgep, const char* name); - -namespace gc { - -// Return true if the given edge is not live and is about to be swept. -template -extern JS_PUBLIC_API(bool) -EdgeNeedsSweep(JS::Heap* edgep); - -// Not part of the public API, but declared here so we can use it in GCPolicy -// which is. -template -bool -IsAboutToBeFinalizedUnbarriered(T* thingp); - -} // namespace gc -} // namespace js - -#endif /* js_TracingAPI_h */ diff --git a/mac/include/spidermonkey/js/TrackedOptimizationInfo.h b/mac/include/spidermonkey/js/TrackedOptimizationInfo.h deleted file mode 100644 index b697765c..00000000 --- a/mac/include/spidermonkey/js/TrackedOptimizationInfo.h +++ /dev/null @@ -1,285 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_TrackedOptimizationInfo_h -#define js_TrackedOptimizationInfo_h - -#include "mozilla/Maybe.h" - -namespace JS { - -#define TRACKED_STRATEGY_LIST(_) \ - _(GetProp_ArgumentsLength) \ - _(GetProp_ArgumentsCallee) \ - _(GetProp_InferredConstant) \ - _(GetProp_Constant) \ - _(GetProp_NotDefined) \ - _(GetProp_StaticName) \ - _(GetProp_SimdGetter) \ - _(GetProp_TypedObject) \ - _(GetProp_DefiniteSlot) \ - _(GetProp_Unboxed) \ - _(GetProp_CommonGetter) \ - _(GetProp_InlineAccess) \ - _(GetProp_Innerize) \ - _(GetProp_InlineCache) \ - _(GetProp_SharedCache) \ - _(GetProp_ModuleNamespace) \ - \ - _(SetProp_CommonSetter) \ - _(SetProp_TypedObject) \ - _(SetProp_DefiniteSlot) \ - _(SetProp_Unboxed) \ - _(SetProp_InlineAccess) \ - _(SetProp_InlineCache) \ - \ - _(GetElem_TypedObject) \ - _(GetElem_Dense) \ - _(GetElem_TypedStatic) \ - _(GetElem_TypedArray) \ - _(GetElem_String) \ - _(GetElem_Arguments) \ - _(GetElem_ArgumentsInlined) \ - _(GetElem_InlineCache) \ - \ - _(SetElem_TypedObject) \ - _(SetElem_TypedStatic) \ - _(SetElem_TypedArray) \ - _(SetElem_Dense) \ - _(SetElem_Arguments) \ - _(SetElem_InlineCache) \ - \ - _(BinaryArith_Concat) \ - _(BinaryArith_SpecializedTypes) \ - _(BinaryArith_SpecializedOnBaselineTypes) \ - _(BinaryArith_SharedCache) \ - _(BinaryArith_Call) \ - \ - _(InlineCache_OptimizedStub) \ - \ - _(Call_Inline) - - -// Ordering is important below. All outcomes before GenericSuccess will be -// considered failures, and all outcomes after GenericSuccess will be -// considered successes. -#define TRACKED_OUTCOME_LIST(_) \ - _(GenericFailure) \ - _(Disabled) \ - _(NoTypeInfo) \ - _(NoAnalysisInfo) \ - _(NoShapeInfo) \ - _(UnknownObject) \ - _(UnknownProperties) \ - _(Singleton) \ - _(NotSingleton) \ - _(NotFixedSlot) \ - _(InconsistentFixedSlot) \ - _(NotObject) \ - _(NotStruct) \ - _(NotUnboxed) \ - _(NotUndefined) \ - _(UnboxedConvertedToNative) \ - _(StructNoField) \ - _(InconsistentFieldType) \ - _(InconsistentFieldOffset) \ - _(NeedsTypeBarrier) \ - _(InDictionaryMode) \ - _(NoProtoFound) \ - _(MultiProtoPaths) \ - _(NonWritableProperty) \ - _(ProtoIndexedProps) \ - _(ArrayBadFlags) \ - _(ArrayDoubleConversion) \ - _(ArrayRange) \ - _(ArraySeenNegativeIndex) \ - _(TypedObjectHasDetachedBuffer) \ - _(TypedObjectArrayRange) \ - _(AccessNotDense) \ - _(AccessNotSimdObject) \ - _(AccessNotTypedObject) \ - _(AccessNotTypedArray) \ - _(AccessNotString) \ - _(OperandNotString) \ - _(OperandNotNumber) \ - _(OperandNotStringOrNumber) \ - _(OperandNotSimpleArith) \ - _(StaticTypedArrayUint32) \ - _(StaticTypedArrayCantComputeMask) \ - _(OutOfBounds) \ - _(GetElemStringNotCached) \ - _(NonNativeReceiver) \ - _(IndexType) \ - _(SetElemNonDenseNonTANotCached) \ - _(NoSimdJitSupport) \ - _(SimdTypeNotOptimized) \ - _(UnknownSimdProperty) \ - _(NotModuleNamespace) \ - _(UnknownProperty) \ - \ - _(ICOptStub_GenericSuccess) \ - \ - _(ICGetPropStub_ReadSlot) \ - _(ICGetPropStub_CallGetter) \ - _(ICGetPropStub_ArrayLength) \ - _(ICGetPropStub_UnboxedRead) \ - _(ICGetPropStub_UnboxedReadExpando) \ - _(ICGetPropStub_UnboxedArrayLength) \ - _(ICGetPropStub_TypedArrayLength) \ - _(ICGetPropStub_DOMProxyShadowed) \ - _(ICGetPropStub_DOMProxyUnshadowed) \ - _(ICGetPropStub_GenericProxy) \ - _(ICGetPropStub_ArgumentsLength) \ - \ - _(ICSetPropStub_Slot) \ - _(ICSetPropStub_GenericProxy) \ - _(ICSetPropStub_DOMProxyShadowed) \ - _(ICSetPropStub_DOMProxyUnshadowed) \ - _(ICSetPropStub_CallSetter) \ - _(ICSetPropStub_AddSlot) \ - _(ICSetPropStub_SetUnboxed) \ - \ - _(ICGetElemStub_ReadSlot) \ - _(ICGetElemStub_CallGetter) \ - _(ICGetElemStub_ReadUnboxed) \ - _(ICGetElemStub_Dense) \ - _(ICGetElemStub_DenseHole) \ - _(ICGetElemStub_TypedArray) \ - _(ICGetElemStub_ArgsElementMapped) \ - _(ICGetElemStub_ArgsElementUnmapped) \ - \ - _(ICSetElemStub_Dense) \ - _(ICSetElemStub_TypedArray) \ - \ - _(ICNameStub_ReadSlot) \ - _(ICNameStub_CallGetter) \ - _(ICNameStub_TypeOfNoProperty) \ - \ - _(CantInlineGeneric) \ - _(CantInlineNoTarget) \ - _(CantInlineNotInterpreted) \ - _(CantInlineNoBaseline) \ - _(CantInlineLazy) \ - _(CantInlineNotConstructor) \ - _(CantInlineClassConstructor) \ - _(CantInlineDisabledIon) \ - _(CantInlineTooManyArgs) \ - _(CantInlineNeedsArgsObj) \ - _(CantInlineDebuggee) \ - _(CantInlineUnknownProps) \ - _(CantInlineExceededDepth) \ - _(CantInlineExceededTotalBytecodeLength) \ - _(CantInlineBigCaller) \ - _(CantInlineBigCallee) \ - _(CantInlineBigCalleeInlinedBytecodeLength) \ - _(CantInlineNotHot) \ - _(CantInlineNotInDispatch) \ - _(CantInlineUnreachable) \ - _(CantInlineNativeBadForm) \ - _(CantInlineNativeBadType) \ - _(CantInlineNativeNoTemplateObj) \ - _(CantInlineBound) \ - _(CantInlineNativeNoSpecialization) \ - _(HasCommonInliningPath) \ - \ - _(GenericSuccess) \ - _(Inlined) \ - _(DOM) \ - _(Monomorphic) \ - _(Polymorphic) - -#define TRACKED_TYPESITE_LIST(_) \ - _(Receiver) \ - _(Operand) \ - _(Index) \ - _(Value) \ - _(Call_Target) \ - _(Call_This) \ - _(Call_Arg) \ - _(Call_Return) - -enum class TrackedStrategy : uint32_t { -#define STRATEGY_OP(name) name, - TRACKED_STRATEGY_LIST(STRATEGY_OP) -#undef STRATEGY_OPT - - Count -}; - -enum class TrackedOutcome : uint32_t { -#define OUTCOME_OP(name) name, - TRACKED_OUTCOME_LIST(OUTCOME_OP) -#undef OUTCOME_OP - - Count -}; - -enum class TrackedTypeSite : uint32_t { -#define TYPESITE_OP(name) name, - TRACKED_TYPESITE_LIST(TYPESITE_OP) -#undef TYPESITE_OP - - Count -}; - -JS_PUBLIC_API(const char*) -TrackedStrategyString(TrackedStrategy strategy); - -JS_PUBLIC_API(const char*) -TrackedOutcomeString(TrackedOutcome outcome); - -JS_PUBLIC_API(const char*) -TrackedTypeSiteString(TrackedTypeSite site); - -struct ForEachTrackedOptimizationAttemptOp -{ - virtual void operator()(TrackedStrategy strategy, TrackedOutcome outcome) = 0; -}; - -struct ForEachTrackedOptimizationTypeInfoOp -{ - // Called 0+ times per entry, once for each type in the type set that Ion - // saw during MIR construction. readType is always called _before_ - // operator() on the same entry. - // - // The keyedBy parameter describes how the type is keyed: - // - "primitive" for primitive types - // - "constructor" for object types tied to a scripted constructor - // function. - // - "alloc site" for object types tied to an allocation site. - // - "prototype" for object types tied neither to a constructor nor - // to an allocation site, but to a prototype. - // - "singleton" for object types which only has a single value. - // - "function" for object types referring to scripted functions. - // - "native" for object types referring to native functions. - // - // The name parameter is the string representation of the type. If the - // type is keyed by "constructor", or if the type itself refers to a - // scripted function, the name is the function's displayAtom. If the type - // is keyed by "native", this is nullptr. - // - // The location parameter is the filename if the type is keyed by - // "constructor", "alloc site", or if the type itself refers to a scripted - // function. If the type is keyed by "native", it is the offset of the - // native function, suitable for use with addr2line on Linux or atos on OS - // X. Otherwise it is nullptr. - // - // The lineno parameter is the line number if the type is keyed by - // "constructor", "alloc site", or if the type itself refers to a scripted - // function. Otherwise it is Nothing(). - // - // The location parameter is the only one that may need escaping if being - // quoted. - virtual void readType(const char* keyedBy, const char* name, - const char* location, mozilla::Maybe lineno) = 0; - - // Called once per entry. - virtual void operator()(TrackedTypeSite site, const char* mirType) = 0; -}; - -} // namespace JS - -#endif // js_TrackedOptimizationInfo_h diff --git a/mac/include/spidermonkey/js/TypeDecls.h b/mac/include/spidermonkey/js/TypeDecls.h deleted file mode 100644 index acb93f97..00000000 --- a/mac/include/spidermonkey/js/TypeDecls.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// This file contains public type declarations that are used *frequently*. If -// it doesn't occur at least 10 times in Gecko, it probably shouldn't be in -// here. -// -// It includes only: -// - forward declarations of structs and classes; -// - typedefs; -// - enums (maybe). -// It does *not* contain any struct or class definitions. - -#ifndef js_TypeDecls_h -#define js_TypeDecls_h - -#include -#include - -#include "js-config.h" - -struct JSContext; -class JSFunction; -class JSObject; -class JSScript; -class JSString; -class JSAddonId; - -struct jsid; - -namespace JS { - -typedef unsigned char Latin1Char; - -class Symbol; -class Value; -template class Handle; -template class MutableHandle; -template class Rooted; -template class PersistentRooted; - -typedef Handle HandleFunction; -typedef Handle HandleId; -typedef Handle HandleObject; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleSymbol; -typedef Handle HandleValue; - -typedef MutableHandle MutableHandleFunction; -typedef MutableHandle MutableHandleId; -typedef MutableHandle MutableHandleObject; -typedef MutableHandle MutableHandleScript; -typedef MutableHandle MutableHandleString; -typedef MutableHandle MutableHandleSymbol; -typedef MutableHandle MutableHandleValue; - -typedef Rooted RootedObject; -typedef Rooted RootedFunction; -typedef Rooted RootedScript; -typedef Rooted RootedString; -typedef Rooted RootedSymbol; -typedef Rooted RootedId; -typedef Rooted RootedValue; - -typedef PersistentRooted PersistentRootedFunction; -typedef PersistentRooted PersistentRootedId; -typedef PersistentRooted PersistentRootedObject; -typedef PersistentRooted PersistentRootedScript; -typedef PersistentRooted PersistentRootedString; -typedef PersistentRooted PersistentRootedSymbol; -typedef PersistentRooted PersistentRootedValue; - -} // namespace JS - -#endif /* js_TypeDecls_h */ diff --git a/mac/include/spidermonkey/js/UbiNode.h b/mac/include/spidermonkey/js/UbiNode.h deleted file mode 100644 index c8742f33..00000000 --- a/mac/include/spidermonkey/js/UbiNode.h +++ /dev/null @@ -1,1144 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNode_h -#define js_UbiNode_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Maybe.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/RangedPtr.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Variant.h" - -#include "jspubtd.h" - -#include "js/GCAPI.h" -#include "js/HashTable.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" -#include "js/TypeDecls.h" -#include "js/UniquePtr.h" -#include "js/Value.h" -#include "js/Vector.h" - -// JS::ubi::Node -// -// JS::ubi::Node is a pointer-like type designed for internal use by heap -// analysis tools. A ubi::Node can refer to: -// -// - a JS value, like a string, object, or symbol; -// - an internal SpiderMonkey structure, like a shape or a scope chain object -// - an instance of some embedding-provided type: in Firefox, an XPCOM -// object, or an internal DOM node class instance -// -// A ubi::Node instance provides metadata about its referent, and can -// enumerate its referent's outgoing edges, so you can implement heap analysis -// algorithms that walk the graph - finding paths between objects, or -// computing heap dominator trees, say - using ubi::Node, while remaining -// ignorant of the details of the types you're operating on. -// -// Of course, when it comes to presenting the results in a developer-facing -// tool, you'll need to stop being ignorant of those details, because you have -// to discuss the ubi::Nodes' referents with the developer. Here, ubi::Node -// can hand you dynamically checked, properly typed pointers to the original -// objects via the as method, or generate descriptions of the referent -// itself. -// -// ubi::Node instances are lightweight (two-word) value types. Instances: -// - compare equal if and only if they refer to the same object; -// - have hash values that respect their equality relation; and -// - have serializations that are only equal if the ubi::Nodes are equal. -// -// A ubi::Node is only valid for as long as its referent is alive; if its -// referent goes away, the ubi::Node becomes a dangling pointer. A ubi::Node -// that refers to a GC-managed object is not automatically a GC root; if the -// GC frees or relocates its referent, the ubi::Node becomes invalid. A -// ubi::Node that refers to a reference-counted object does not bump the -// reference count. -// -// ubi::Node values require no supporting data structures, making them -// feasible for use in memory-constrained devices --- ideally, the memory -// requirements of the algorithm which uses them will be the limiting factor, -// not the demands of ubi::Node itself. -// -// One can construct a ubi::Node value given a pointer to a type that ubi::Node -// supports. In the other direction, one can convert a ubi::Node back to a -// pointer; these downcasts are checked dynamically. In particular, one can -// convert a 'JSContext*' to a ubi::Node, yielding a node with an outgoing edge -// for every root registered with the runtime; starting from this, one can walk -// the entire heap. (Of course, one could also start traversal at any other kind -// of type to which one has a pointer.) -// -// -// Extending ubi::Node To Handle Your Embedding's Types -// -// To add support for a new ubi::Node referent type R, you must define a -// specialization of the ubi::Concrete template, ubi::Concrete, which -// inherits from ubi::Base. ubi::Node itself uses the specialization for -// compile-time information (i.e. the checked conversions between R * and -// ubi::Node), and the inheritance for run-time dispatching. -// -// -// ubi::Node Exposes Implementation Details -// -// In many cases, a JavaScript developer's view of their data differs -// substantially from its actual implementation. For example, while the -// ECMAScript specification describes objects as maps from property names to -// sets of attributes (like ECMAScript's [[Value]]), in practice many objects -// have only a pointer to a shape, shared with other similar objects, and -// indexed slots that contain the [[Value]] attributes. As another example, a -// string produced by concatenating two other strings may sometimes be -// represented by a "rope", a structure that points to the two original -// strings. -// -// We intend to use ubi::Node to write tools that report memory usage, so it's -// important that ubi::Node accurately portray how much memory nodes consume. -// Thus, for example, when data that apparently belongs to multiple nodes is -// in fact shared in a common structure, ubi::Node's graph uses a separate -// node for that shared structure, and presents edges to it from the data's -// apparent owners. For example, ubi::Node exposes SpiderMonkey objects' -// shapes and base shapes, and exposes rope string and substring structure, -// because these optimizations become visible when a tool reports how much -// memory a structure consumes. -// -// However, fine granularity is not a goal. When a particular object is the -// exclusive owner of a separate block of memory, ubi::Node may present the -// object and its block as a single node, and add their sizes together when -// reporting the node's size, as there is no meaningful loss of data in this -// case. Thus, for example, a ubi::Node referring to a JavaScript object, when -// asked for the object's size in bytes, includes the object's slot and -// element arrays' sizes in the total. There is no separate ubi::Node value -// representing the slot and element arrays, since they are owned exclusively -// by the object. -// -// -// Presenting Analysis Results To JavaScript Developers -// -// If an analysis provides its results in terms of ubi::Node values, a user -// interface presenting those results will generally need to clean them up -// before they can be understood by JavaScript developers. For example, -// JavaScript developers should not need to understand shapes, only JavaScript -// objects. Similarly, they should not need to understand the distinction -// between DOM nodes and the JavaScript shadow objects that represent them. -// -// -// Rooting Restrictions -// -// At present there is no way to root ubi::Node instances, so instances can't be -// live across any operation that might GC. Analyses using ubi::Node must either -// run to completion and convert their results to some other rootable type, or -// save their intermediate state in some rooted structure if they must GC before -// they complete. (For algorithms like path-finding and dominator tree -// computation, we implement the algorithm avoiding any operation that could -// cause a GC --- and use AutoCheckCannotGC to verify this.) -// -// If this restriction prevents us from implementing interesting tools, we may -// teach the GC how to root ubi::Nodes, fix up hash tables that use them as -// keys, etc. -// -// -// Hostile Graph Structure -// -// Analyses consuming ubi::Node graphs must be robust when presented with graphs -// that are deliberately constructed to exploit their weaknesses. When operating -// on live graphs, web content has control over the object graph, and less -// direct control over shape and string structure, and analyses should be -// prepared to handle extreme cases gracefully. For example, if an analysis were -// to use the C++ stack in a depth-first traversal, carefully constructed -// content could cause the analysis to overflow the stack. -// -// When ubi::Nodes refer to nodes deserialized from a heap snapshot, analyses -// must be even more careful: since snapshots often come from potentially -// compromised e10s content processes, even properties normally guaranteed by -// the platform (the proper linking of DOM nodes, for example) might be -// corrupted. While it is the deserializer's responsibility to check the basic -// structure of the snapshot file, the analyses should be prepared for ubi::Node -// graphs constructed from snapshots to be even more bizarre. - -class JSAtom; - -namespace JS { -namespace ubi { - -class Edge; -class EdgeRange; -class StackFrame; - -} // namespace ubi -} // namespace JS - -namespace JS { -namespace ubi { - -using mozilla::Forward; -using mozilla::Maybe; -using mozilla::Move; -using mozilla::RangedPtr; -using mozilla::Variant; - -template -using Vector = mozilla::Vector; - -/*** ubi::StackFrame ******************************************************************************/ - -// Concrete JS::ubi::StackFrame instances backed by a live SavedFrame object -// store their strings as JSAtom*, while deserialized stack frames from offline -// heap snapshots store their strings as const char16_t*. In order to provide -// zero-cost accessors to these strings in a single interface that works with -// both cases, we use this variant type. -class AtomOrTwoByteChars : public Variant { - using Base = Variant; - - public: - template - MOZ_IMPLICIT AtomOrTwoByteChars(T&& rhs) : Base(Forward(rhs)) { } - - template - AtomOrTwoByteChars& operator=(T&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move disallowed"); - this->~AtomOrTwoByteChars(); - new (this) AtomOrTwoByteChars(Forward(rhs)); - return *this; - } - - // Return the length of the given AtomOrTwoByteChars string. - size_t length(); - - // Copy the given AtomOrTwoByteChars string into the destination buffer, - // inflating if necessary. Does NOT null terminate. Returns the number of - // characters written to destination. - size_t copyToBuffer(RangedPtr destination, size_t length); -}; - -// The base class implemented by each ConcreteStackFrame type. Subclasses -// must not add data members to this class. -class BaseStackFrame { - friend class StackFrame; - - BaseStackFrame(const StackFrame&) = delete; - BaseStackFrame& operator=(const StackFrame&) = delete; - - protected: - void* ptr; - explicit BaseStackFrame(void* ptr) : ptr(ptr) { } - - public: - // This is a value type that should not have a virtual destructor. Don't add - // destructors in subclasses! - - // Get a unique identifier for this StackFrame. The identifier is not valid - // across garbage collections. - virtual uint64_t identifier() const { return uint64_t(uintptr_t(ptr)); } - - // Get this frame's parent frame. - virtual StackFrame parent() const = 0; - - // Get this frame's line number. - virtual uint32_t line() const = 0; - - // Get this frame's column number. - virtual uint32_t column() const = 0; - - // Get this frame's source name. Never null. - virtual AtomOrTwoByteChars source() const = 0; - - // Return this frame's function name if named, otherwise the inferred - // display name. Can be null. - virtual AtomOrTwoByteChars functionDisplayName() const = 0; - - // Returns true if this frame's function is system JavaScript running with - // trusted principals, false otherwise. - virtual bool isSystem() const = 0; - - // Return true if this frame's function is a self-hosted JavaScript builtin, - // false otherwise. - virtual bool isSelfHosted(JSContext* cx) const = 0; - - // Construct a SavedFrame stack for the stack starting with this frame and - // containing all of its parents. The SavedFrame objects will be placed into - // cx's current compartment. - // - // Note that the process of - // - // SavedFrame - // | - // V - // JS::ubi::StackFrame - // | - // V - // offline heap snapshot - // | - // V - // JS::ubi::StackFrame - // | - // V - // SavedFrame - // - // is lossy because we cannot serialize and deserialize the SavedFrame's - // principals in the offline heap snapshot, so JS::ubi::StackFrame - // simplifies the principals check into the boolean isSystem() state. This - // is fine because we only expose JS::ubi::Stack to devtools and chrome - // code, and not to the web platform. - virtual MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx, - MutableHandleObject outSavedFrameStack) - const = 0; - - // Trace the concrete implementation of JS::ubi::StackFrame. - virtual void trace(JSTracer* trc) = 0; -}; - -// A traits template with a specialization for each backing type that implements -// the ubi::BaseStackFrame interface. Each specialization must be the a subclass -// of ubi::BaseStackFrame. -template class ConcreteStackFrame; - -// A JS::ubi::StackFrame represents a frame in a recorded stack. It can be -// backed either by a live SavedFrame object or by a structure deserialized from -// an offline heap snapshot. -// -// It is a value type that may be memcpy'd hither and thither without worrying -// about constructors or destructors, similar to POD types. -// -// Its lifetime is the same as the lifetime of the graph that is being analyzed -// by the JS::ubi::Node that the JS::ubi::StackFrame came from. That is, if the -// graph being analyzed is the live heap graph, the JS::ubi::StackFrame is only -// valid within the scope of an AutoCheckCannotGC; if the graph being analyzed -// is an offline heap snapshot, the JS::ubi::StackFrame is valid as long as the -// offline heap snapshot is alive. -class StackFrame { - // Storage in which we allocate BaseStackFrame subclasses. - mozilla::AlignedStorage2 storage; - - BaseStackFrame* base() { return storage.addr(); } - const BaseStackFrame* base() const { return storage.addr(); } - - template - void construct(T* ptr) { - static_assert(mozilla::IsBaseOf>::value, - "ConcreteStackFrame must inherit from BaseStackFrame"); - static_assert(sizeof(ConcreteStackFrame) == sizeof(*base()), - "ubi::ConcreteStackFrame specializations must be the same size as " - "ubi::BaseStackFrame"); - ConcreteStackFrame::construct(base(), ptr); - } - struct ConstructFunctor; - - public: - StackFrame() { construct(nullptr); } - - template - MOZ_IMPLICIT StackFrame(T* ptr) { - construct(ptr); - } - - template - StackFrame& operator=(T* ptr) { - construct(ptr); - return *this; - } - - // Constructors accepting SpiderMonkey's generic-pointer-ish types. - - template - explicit StackFrame(const JS::Handle& handle) { - construct(handle.get()); - } - - template - StackFrame& operator=(const JS::Handle& handle) { - construct(handle.get()); - return *this; - } - - template - explicit StackFrame(const JS::Rooted& root) { - construct(root.get()); - } - - template - StackFrame& operator=(const JS::Rooted& root) { - construct(root.get()); - return *this; - } - - // Because StackFrame is just a vtable pointer and an instance pointer, we - // can memcpy everything around instead of making concrete classes define - // virtual constructors. See the comment above Node's copy constructor for - // more details; that comment applies here as well. - StackFrame(const StackFrame& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - } - - StackFrame& operator=(const StackFrame& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - return *this; - } - - bool operator==(const StackFrame& rhs) const { return base()->ptr == rhs.base()->ptr; } - bool operator!=(const StackFrame& rhs) const { return !(*this == rhs); } - - explicit operator bool() const { - return base()->ptr != nullptr; - } - - // Copy this StackFrame's source name into the given |destination| - // buffer. Copy no more than |length| characters. The result is *not* null - // terminated. Returns how many characters were written into the buffer. - size_t source(RangedPtr destination, size_t length) const; - - // Copy this StackFrame's function display name into the given |destination| - // buffer. Copy no more than |length| characters. The result is *not* null - // terminated. Returns how many characters were written into the buffer. - size_t functionDisplayName(RangedPtr destination, size_t length) const; - - // Get the size of the respective strings. 0 is returned for null strings. - size_t sourceLength(); - size_t functionDisplayNameLength(); - - // Methods that forward to virtual calls through BaseStackFrame. - - void trace(JSTracer* trc) { base()->trace(trc); } - uint64_t identifier() const { - auto id = base()->identifier(); - MOZ_ASSERT(JS::Value::isNumberRepresentable(id)); - return id; - } - uint32_t line() const { return base()->line(); } - uint32_t column() const { return base()->column(); } - AtomOrTwoByteChars source() const { return base()->source(); } - AtomOrTwoByteChars functionDisplayName() const { return base()->functionDisplayName(); } - StackFrame parent() const { return base()->parent(); } - bool isSystem() const { return base()->isSystem(); } - bool isSelfHosted(JSContext* cx) const { return base()->isSelfHosted(cx); } - MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx, - MutableHandleObject outSavedFrameStack) const { - return base()->constructSavedFrameStack(cx, outSavedFrameStack); - } - - struct HashPolicy { - using Lookup = JS::ubi::StackFrame; - - static js::HashNumber hash(const Lookup& lookup) { - return lookup.identifier(); - } - - static bool match(const StackFrame& key, const Lookup& lookup) { - return key == lookup; - } - - static void rekey(StackFrame& k, const StackFrame& newKey) { - k = newKey; - } - }; -}; - -// The ubi::StackFrame null pointer. Any attempt to operate on a null -// ubi::StackFrame crashes. -template<> -class ConcreteStackFrame : public BaseStackFrame { - explicit ConcreteStackFrame(void* ptr) : BaseStackFrame(ptr) { } - - public: - static void construct(void* storage, void*) { new (storage) ConcreteStackFrame(nullptr); } - - uint64_t identifier() const override { return 0; } - void trace(JSTracer* trc) override { } - MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx, MutableHandleObject out) - const override - { - out.set(nullptr); - return true; - } - - uint32_t line() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - uint32_t column() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - AtomOrTwoByteChars source() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - AtomOrTwoByteChars functionDisplayName() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - StackFrame parent() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - bool isSystem() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - bool isSelfHosted(JSContext* cx) const override { MOZ_CRASH("null JS::ubi::StackFrame"); } -}; - -MOZ_MUST_USE bool ConstructSavedFrameStackSlow(JSContext* cx, JS::ubi::StackFrame& frame, - MutableHandleObject outSavedFrameStack); - - -/*** ubi::Node ************************************************************************************/ - -// A concrete node specialization can claim its referent is a member of a -// particular "coarse type" which is less specific than the actual -// implementation type but generally more palatable for web developers. For -// example, JitCode can be considered to have a coarse type of "Script". This is -// used by some analyses for putting nodes into different buckets. The default, -// if a concrete specialization does not provide its own mapping to a CoarseType -// variant, is "Other". -// -// NB: the values associated with a particular enum variant must not change or -// be reused for new variants. Doing so will cause inspecting ubi::Nodes backed -// by an offline heap snapshot from an older SpiderMonkey/Firefox version to -// break. Consider this enum append only. -enum class CoarseType: uint32_t { - Other = 0, - Object = 1, - Script = 2, - String = 3, - - FIRST = Other, - LAST = String -}; - -inline uint32_t -CoarseTypeToUint32(CoarseType type) -{ - return static_cast(type); -} - -inline bool -Uint32IsValidCoarseType(uint32_t n) -{ - auto first = static_cast(CoarseType::FIRST); - auto last = static_cast(CoarseType::LAST); - MOZ_ASSERT(first < last); - return first <= n && n <= last; -} - -inline CoarseType -Uint32ToCoarseType(uint32_t n) -{ - MOZ_ASSERT(Uint32IsValidCoarseType(n)); - return static_cast(n); -} - -// The base class implemented by each ubi::Node referent type. Subclasses must -// not add data members to this class. -class Base { - friend class Node; - - // For performance's sake, we'd prefer to avoid a virtual destructor; and - // an empty constructor seems consistent with the 'lightweight value type' - // visible behavior we're trying to achieve. But if the destructor isn't - // virtual, and a subclass overrides it, the subclass's destructor will be - // ignored. Is there a way to make the compiler catch that error? - - protected: - // Space for the actual pointer. Concrete subclasses should define a - // properly typed 'get' member function to access this. - void* ptr; - - explicit Base(void* ptr) : ptr(ptr) { } - - public: - bool operator==(const Base& rhs) const { - // Some compilers will indeed place objects of different types at - // the same address, so technically, we should include the vtable - // in this comparison. But it seems unlikely to cause problems in - // practice. - return ptr == rhs.ptr; - } - bool operator!=(const Base& rhs) const { return !(*this == rhs); } - - // An identifier for this node, guaranteed to be stable and unique for as - // long as this ubi::Node's referent is alive and at the same address. - // - // This is probably suitable for use in serializations, as it is an integral - // type. It may also help save memory when constructing HashSets of - // ubi::Nodes: since a uint64_t will always be smaller-or-equal-to the size - // of a ubi::Node, a HashSet may use less space per element - // than a HashSet. - // - // (Note that 'unique' only means 'up to equality on ubi::Node'; see the - // caveats about multiple objects allocated at the same address for - // 'ubi::Node::operator=='.) - using Id = uint64_t; - virtual Id identifier() const { return Id(uintptr_t(ptr)); } - - // Returns true if this node is pointing to something on the live heap, as - // opposed to something from a deserialized core dump. Returns false, - // otherwise. - virtual bool isLive() const { return true; }; - - // Return the coarse-grained type-of-thing that this node represents. - virtual CoarseType coarseType() const { return CoarseType::Other; } - - // Return a human-readable name for the referent's type. The result should - // be statically allocated. (You can use u"strings" for this.) - // - // This must always return Concrete::concreteTypeName; we use that - // pointer as a tag for this particular referent type. - virtual const char16_t* typeName() const = 0; - - // Return the size of this node, in bytes. Include any structures that this - // node owns exclusively that are not exposed as their own ubi::Nodes. - // |mallocSizeOf| should be a malloc block sizing function; see - // |mfbt/MemoryReporting.h|. - // - // Because we can use |JS::ubi::Node|s backed by a snapshot that was taken - // on a 64-bit platform when we are currently on a 32-bit platform, we - // cannot rely on |size_t| for node sizes. Instead, |Size| is uint64_t on - // all platforms. - using Size = uint64_t; - virtual Size size(mozilla::MallocSizeOf mallocSizeof) const { return 1; } - - // Return an EdgeRange that initially contains all the referent's outgoing - // edges. The caller takes ownership of the EdgeRange. - // - // If wantNames is true, compute names for edges. Doing so can be expensive - // in time and memory. - virtual js::UniquePtr edges(JSContext* cx, bool wantNames) const = 0; - - // Return the Zone to which this node's referent belongs, or nullptr if the - // referent is not of a type allocated in SpiderMonkey Zones. - virtual JS::Zone* zone() const { return nullptr; } - - // Return the compartment for this node. Some ubi::Node referents are not - // associated with JSCompartments, such as JSStrings (which are associated - // with Zones). When the referent is not associated with a compartment, - // nullptr is returned. - virtual JSCompartment* compartment() const { return nullptr; } - - // Return whether this node's referent's allocation stack was captured. - virtual bool hasAllocationStack() const { return false; } - - // Get the stack recorded at the time this node's referent was - // allocated. This must only be called when hasAllocationStack() is true. - virtual StackFrame allocationStack() const { - MOZ_CRASH("Concrete classes that have an allocation stack must override both " - "hasAllocationStack and allocationStack."); - } - - // Methods for JSObject Referents - // - // These methods are only semantically valid if the referent is either a - // JSObject in the live heap, or represents a previously existing JSObject - // from some deserialized heap snapshot. - - // Return the object's [[Class]]'s name. - virtual const char* jsObjectClassName() const { return nullptr; } - - // If this object was constructed with `new` and we have the data available, - // place the contructor function's display name in the out parameter. - // Otherwise, place nullptr in the out parameter. Caller maintains ownership - // of the out parameter. True is returned on success, false is returned on - // OOM. - virtual MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) - const - { - outName.reset(nullptr); - return true; - } - - // Methods for CoarseType::Script referents - - // Return the script's source's filename if available. If unavailable, - // return nullptr. - virtual const char* scriptFilename() const { return nullptr; } - - private: - Base(const Base& rhs) = delete; - Base& operator=(const Base& rhs) = delete; -}; - -// A traits template with a specialization for each referent type that -// ubi::Node supports. The specialization must be the concrete subclass of Base -// that represents a pointer to the referent type. It must include these -// members: -// -// // The specific char16_t array returned by Concrete::typeName(). -// static const char16_t concreteTypeName[]; -// -// // Construct an instance of this concrete class in |storage| referring -// // to |referent|. Implementations typically use a placement 'new'. -// // -// // In some cases, |referent| will contain dynamic type information that -// // identifies it a some more specific subclass of |Referent|. For -// // example, when |Referent| is |JSObject|, then |referent->getClass()| -// // could tell us that it's actually a JSFunction. Similarly, if -// // |Referent| is |nsISupports|, we would like a ubi::Node that knows its -// // final implementation type. -// // -// // So we delegate the actual construction to this specialization, which -// // knows Referent's details. -// static void construct(void* storage, Referent* referent); -template -class Concrete; - -// A container for a Base instance; all members simply forward to the contained -// instance. This container allows us to pass ubi::Node instances by value. -class Node { - // Storage in which we allocate Base subclasses. - mozilla::AlignedStorage2 storage; - Base* base() { return storage.addr(); } - const Base* base() const { return storage.addr(); } - - template - void construct(T* ptr) { - static_assert(sizeof(Concrete) == sizeof(*base()), - "ubi::Base specializations must be the same size as ubi::Base"); - static_assert(mozilla::IsBaseOf>::value, - "ubi::Concrete must inherit from ubi::Base"); - Concrete::construct(base(), ptr); - } - struct ConstructFunctor; - - public: - Node() { construct(nullptr); } - - template - MOZ_IMPLICIT Node(T* ptr) { - construct(ptr); - } - template - Node& operator=(T* ptr) { - construct(ptr); - return *this; - } - - // We can construct and assign from rooted forms of pointers. - template - MOZ_IMPLICIT Node(const Rooted& root) { - construct(root.get()); - } - template - Node& operator=(const Rooted& root) { - construct(root.get()); - return *this; - } - - // Constructors accepting SpiderMonkey's other generic-pointer-ish types. - // Note that we *do* want an implicit constructor here: JS::Value and - // JS::ubi::Node are both essentially tagged references to other sorts of - // objects, so letting conversions happen automatically is appropriate. - MOZ_IMPLICIT Node(JS::HandleValue value); - explicit Node(const JS::GCCellPtr& thing); - - // copy construction and copy assignment just use memcpy, since we know - // instances contain nothing but a vtable pointer and a data pointer. - // - // To be completely correct, concrete classes could provide a virtual - // 'construct' member function, which we could invoke on rhs to construct an - // instance in our storage. But this is good enough; there's no need to jump - // through vtables for copying and assignment that are just going to move - // two words around. The compiler knows how to optimize memcpy. - Node(const Node& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - } - - Node& operator=(const Node& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - return *this; - } - - bool operator==(const Node& rhs) const { return *base() == *rhs.base(); } - bool operator!=(const Node& rhs) const { return *base() != *rhs.base(); } - - explicit operator bool() const { - return base()->ptr != nullptr; - } - - bool isLive() const { return base()->isLive(); } - - // Get the canonical type name for the given type T. - template - static const char16_t* canonicalTypeName() { return Concrete::concreteTypeName; } - - template - bool is() const { - return base()->typeName() == canonicalTypeName(); - } - - template - T* as() const { - MOZ_ASSERT(isLive()); - MOZ_ASSERT(is()); - return static_cast(base()->ptr); - } - - template - T* asOrNull() const { - MOZ_ASSERT(isLive()); - return is() ? static_cast(base()->ptr) : nullptr; - } - - // If this node refers to something that can be represented as a JavaScript - // value that is safe to expose to JavaScript code, return that value. - // Otherwise return UndefinedValue(). JSStrings, JS::Symbols, and some (but - // not all!) JSObjects can be exposed. - JS::Value exposeToJS() const; - - CoarseType coarseType() const { return base()->coarseType(); } - const char16_t* typeName() const { return base()->typeName(); } - JS::Zone* zone() const { return base()->zone(); } - JSCompartment* compartment() const { return base()->compartment(); } - const char* jsObjectClassName() const { return base()->jsObjectClassName(); } - MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) const { - return base()->jsObjectConstructorName(cx, outName); - } - - const char* scriptFilename() const { return base()->scriptFilename(); } - - using Size = Base::Size; - Size size(mozilla::MallocSizeOf mallocSizeof) const { - auto size = base()->size(mallocSizeof); - MOZ_ASSERT(size > 0, - "C++ does not have zero-sized types! Choose 1 if you just need a " - "conservative default."); - return size; - } - - js::UniquePtr edges(JSContext* cx, bool wantNames = true) const { - return base()->edges(cx, wantNames); - } - - bool hasAllocationStack() const { return base()->hasAllocationStack(); } - StackFrame allocationStack() const { - return base()->allocationStack(); - } - - using Id = Base::Id; - Id identifier() const { - auto id = base()->identifier(); - MOZ_ASSERT(JS::Value::isNumberRepresentable(id)); - return id; - } - - // A hash policy for ubi::Nodes. - // This simply uses the stock PointerHasher on the ubi::Node's pointer. - // We specialize DefaultHasher below to make this the default. - class HashPolicy { - typedef js::PointerHasher::value> PtrHash; - - public: - typedef Node Lookup; - - static js::HashNumber hash(const Lookup& l) { return PtrHash::hash(l.base()->ptr); } - static bool match(const Node& k, const Lookup& l) { return k == l; } - static void rekey(Node& k, const Node& newKey) { k = newKey; } - }; -}; - -using NodeSet = js::HashSet, js::SystemAllocPolicy>; -using NodeSetPtr = mozilla::UniquePtr>; - -/*** Edge and EdgeRange ***************************************************************************/ - -using EdgeName = UniqueTwoByteChars; - -// An outgoing edge to a referent node. -class Edge { - public: - Edge() : name(nullptr), referent() { } - - // Construct an initialized Edge, taking ownership of |name|. - Edge(char16_t* name, const Node& referent) - : name(name) - , referent(referent) - { } - - // Move construction and assignment. - Edge(Edge&& rhs) - : name(mozilla::Move(rhs.name)) - , referent(rhs.referent) - { } - - Edge& operator=(Edge&& rhs) { - MOZ_ASSERT(&rhs != this); - this->~Edge(); - new (this) Edge(mozilla::Move(rhs)); - return *this; - } - - Edge(const Edge&) = delete; - Edge& operator=(const Edge&) = delete; - - // This edge's name. This may be nullptr, if Node::edges was called with - // false as the wantNames parameter. - // - // The storage is owned by this Edge, and will be freed when this Edge is - // destructed. You may take ownership of the name by `mozilla::Move`ing it - // out of the edge; it is just a UniquePtr. - // - // (In real life we'll want a better representation for names, to avoid - // creating tons of strings when the names follow a pattern; and we'll need - // to think about lifetimes carefully to ensure traversal stays cheap.) - EdgeName name; - - // This edge's referent. - Node referent; -}; - -// EdgeRange is an abstract base class for iterating over a node's outgoing -// edges. (This is modeled after js::HashTable::Range.) -// -// Concrete instances of this class need not be as lightweight as Node itself, -// since they're usually only instantiated while iterating over a particular -// object's edges. For example, a dumb implementation for JS Cells might use -// JS::TraceChildren to to get the outgoing edges, and then store them in an -// array internal to the EdgeRange. -class EdgeRange { - protected: - // The current front edge of this range, or nullptr if this range is empty. - Edge* front_; - - EdgeRange() : front_(nullptr) { } - - public: - virtual ~EdgeRange() { } - - // True if there are no more edges in this range. - bool empty() const { return !front_; } - - // The front edge of this range. This is owned by the EdgeRange, and is - // only guaranteed to live until the next call to popFront, or until - // the EdgeRange is destructed. - const Edge& front() const { return *front_; } - Edge& front() { return *front_; } - - // Remove the front edge from this range. This should only be called if - // !empty(). - virtual void popFront() = 0; - - private: - EdgeRange(const EdgeRange&) = delete; - EdgeRange& operator=(const EdgeRange&) = delete; -}; - - -typedef mozilla::Vector EdgeVector; - -// An EdgeRange concrete class that holds a pre-existing vector of -// Edges. A PreComputedEdgeRange does not take ownership of its -// EdgeVector; it is up to the PreComputedEdgeRange's consumer to manage -// that lifetime. -class PreComputedEdgeRange : public EdgeRange { - EdgeVector& edges; - size_t i; - - void settle() { - front_ = i < edges.length() ? &edges[i] : nullptr; - } - - public: - explicit PreComputedEdgeRange(EdgeVector& edges) - : edges(edges), - i(0) - { - settle(); - } - - void popFront() override { - MOZ_ASSERT(!empty()); - i++; - settle(); - } -}; - -/*** RootList *************************************************************************************/ - -// RootList is a class that can be pointed to by a |ubi::Node|, creating a -// fictional root-of-roots which has edges to every GC root in the JS -// runtime. Having a single root |ubi::Node| is useful for algorithms written -// with the assumption that there aren't multiple roots (such as computing -// dominator trees) and you want a single point of entry. It also ensures that -// the roots themselves get visited by |ubi::BreadthFirst| (they would otherwise -// only be used as starting points). -// -// RootList::init itself causes a minor collection, but once the list of roots -// has been created, GC must not occur, as the referent ubi::Nodes are not -// stable across GC. The init calls emplace on |noGC|'s AutoCheckCannotGC, whose -// lifetime must extend at least as long as the RootList itself. -// -// Example usage: -// -// { -// mozilla::Maybe maybeNoGC; -// JS::ubi::RootList rootList(cx, maybeNoGC); -// if (!rootList.init()) -// return false; -// -// // The AutoCheckCannotGC is guaranteed to exist if init returned true. -// MOZ_ASSERT(maybeNoGC.isSome()); -// -// JS::ubi::Node root(&rootList); -// -// ... -// } -class MOZ_STACK_CLASS RootList { - Maybe& noGC; - - public: - JSContext* cx; - EdgeVector edges; - bool wantNames; - - RootList(JSContext* cx, Maybe& noGC, bool wantNames = false); - - // Find all GC roots. - MOZ_MUST_USE bool init(); - // Find only GC roots in the provided set of |JSCompartment|s. - MOZ_MUST_USE bool init(CompartmentSet& debuggees); - // Find only GC roots in the given Debugger object's set of debuggee - // compartments. - MOZ_MUST_USE bool init(HandleObject debuggees); - - // Returns true if the RootList has been initialized successfully, false - // otherwise. - bool initialized() { return noGC.isSome(); } - - // Explicitly add the given Node as a root in this RootList. If wantNames is - // true, you must pass an edgeName. The RootList does not take ownership of - // edgeName. - MOZ_MUST_USE bool addRoot(Node node, const char16_t* edgeName = nullptr); -}; - - -/*** Concrete classes for ubi::Node referent types ************************************************/ - -template<> -class Concrete : public Base { - protected: - explicit Concrete(RootList* ptr) : Base(ptr) { } - RootList& get() const { return *static_cast(ptr); } - - public: - static void construct(void* storage, RootList* ptr) { new (storage) Concrete(ptr); } - - js::UniquePtr edges(JSContext* cx, bool wantNames) const override; - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// A reusable ubi::Concrete specialization base class for types supported by -// JS::TraceChildren. -template -class TracerConcrete : public Base { - js::UniquePtr edges(JSContext* cx, bool wantNames) const override; - JS::Zone* zone() const override; - - protected: - explicit TracerConcrete(Referent* ptr) : Base(ptr) { } - Referent& get() const { return *static_cast(ptr); } -}; - -// For JS::TraceChildren-based types that have a 'compartment' method. -template -class TracerConcreteWithCompartment : public TracerConcrete { - typedef TracerConcrete TracerBase; - JSCompartment* compartment() const override; - - protected: - explicit TracerConcreteWithCompartment(Referent* ptr) : TracerBase(ptr) { } -}; - -// Define specializations for some commonly-used public JSAPI types. -// These can use the generic templates above. -template<> -class Concrete : TracerConcrete { - protected: - explicit Concrete(JS::Symbol* ptr) : TracerConcrete(ptr) { } - - public: - static void construct(void* storage, JS::Symbol* ptr) { - new (storage) Concrete(ptr); - } - - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -template<> -class Concrete : TracerConcreteWithCompartment { - protected: - explicit Concrete(JSScript *ptr) : TracerConcreteWithCompartment(ptr) { } - - public: - static void construct(void *storage, JSScript *ptr) { new (storage) Concrete(ptr); } - - CoarseType coarseType() const final { return CoarseType::Script; } - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - const char* scriptFilename() const final; - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// The JSObject specialization. -template<> -class Concrete : public TracerConcreteWithCompartment { - protected: - explicit Concrete(JSObject* ptr) : TracerConcreteWithCompartment(ptr) { } - - public: - static void construct(void* storage, JSObject* ptr) { - new (storage) Concrete(ptr); - } - - const char* jsObjectClassName() const override; - MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) - const override; - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - - bool hasAllocationStack() const override; - StackFrame allocationStack() const override; - - CoarseType coarseType() const final { return CoarseType::Object; } - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// For JSString, we extend the generic template with a 'size' implementation. -template<> -class Concrete : TracerConcrete { - protected: - explicit Concrete(JSString *ptr) : TracerConcrete(ptr) { } - - public: - static void construct(void *storage, JSString *ptr) { new (storage) Concrete(ptr); } - - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - - CoarseType coarseType() const final { return CoarseType::String; } - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// The ubi::Node null pointer. Any attempt to operate on a null ubi::Node asserts. -template<> -class Concrete : public Base { - const char16_t* typeName() const override; - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - js::UniquePtr edges(JSContext* cx, bool wantNames) const override; - JS::Zone* zone() const override; - JSCompartment* compartment() const override; - CoarseType coarseType() const final; - - explicit Concrete(void* ptr) : Base(ptr) { } - - public: - static void construct(void* storage, void* ptr) { new (storage) Concrete(ptr); } -}; - - -} // namespace ubi -} // namespace JS - -namespace js { - -// Make ubi::Node::HashPolicy the default hash policy for ubi::Node. -template<> struct DefaultHasher : JS::ubi::Node::HashPolicy { }; -template<> struct DefaultHasher : JS::ubi::StackFrame::HashPolicy { }; - -} // namespace js - -#endif // js_UbiNode_h diff --git a/mac/include/spidermonkey/js/UbiNodeBreadthFirst.h b/mac/include/spidermonkey/js/UbiNodeBreadthFirst.h deleted file mode 100644 index 8446dbc6..00000000 --- a/mac/include/spidermonkey/js/UbiNodeBreadthFirst.h +++ /dev/null @@ -1,244 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeBreadthFirst_h -#define js_UbiNodeBreadthFirst_h - -#include "js/UbiNode.h" -#include "js/Utility.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -// A breadth-first traversal template for graphs of ubi::Nodes. -// -// No GC may occur while an instance of this template is live. -// -// The provided Handler type should have two members: -// -// typename NodeData; -// -// The value type of |BreadthFirst::visited|, the HashMap of -// ubi::Nodes that have been visited so far. Since the algorithm needs a -// hash table like this for its own use anyway, it is simple to let -// Handler store its own metadata about each node in the same table. -// -// For example, if you want to find a shortest path to each node from any -// traversal starting point, your |NodeData| type could record the first -// edge to reach each node, and the node from which it originates. Then, -// when the traversal is complete, you can walk backwards from any node -// to some starting point, and the path recorded will be a shortest path. -// -// This type must have a default constructor. If this type owns any other -// resources, move constructors and assignment operators are probably a -// good idea, too. -// -// bool operator() (BreadthFirst& traversal, -// Node origin, const Edge& edge, -// Handler::NodeData* referentData, bool first); -// -// The visitor function, called to report that we have traversed -// |edge| from |origin|. This is called once for each edge we traverse. -// As this is a breadth-first search, any prior calls to the visitor function -// were for origin nodes not further from the start nodes than |origin|. -// -// |traversal| is this traversal object, passed along for convenience. -// -// |referentData| is a pointer to the value of the entry in -// |traversal.visited| for |edge.referent|; the visitor function can -// store whatever metadata it likes about |edge.referent| there. -// -// |first| is true if this is the first time we have visited an edge -// leading to |edge.referent|. This could be stored in NodeData, but -// the algorithm knows whether it has just created the entry in -// |traversal.visited|, so it passes it along for convenience. -// -// The visitor function may call |traversal.abandonReferent()| if it -// doesn't want to traverse the outgoing edges of |edge.referent|. You can -// use this to limit the traversal to a given portion of the graph: it will -// never visit nodes reachable only through nodes that you have abandoned. -// Note that |abandonReferent| must be called the first time the given node -// is reached; that is, |first| must be true. -// -// The visitor function may call |traversal.stop()| if it doesn't want -// to visit any more nodes at all. -// -// The visitor function may consult |traversal.visited| for information -// about other nodes, but it should not add or remove entries. -// -// The visitor function should return true on success, or false if an -// error occurs. A false return value terminates the traversal -// immediately, and causes BreadthFirst::traverse to return -// false. -template -struct BreadthFirst { - - // Construct a breadth-first traversal object that reports the nodes it - // reaches to |handler|. The traversal asserts that no GC happens in its - // runtime during its lifetime. - // - // We do nothing with noGC, other than require it to exist, with a lifetime - // that encloses our own. - BreadthFirst(JSContext* cx, Handler& handler, const JS::AutoCheckCannotGC& noGC) - : wantNames(true), cx(cx), visited(), handler(handler), pending(), - traversalBegun(false), stopRequested(false), abandonRequested(false) - { } - - // Initialize this traversal object. Return false on OOM. - bool init() { return visited.init(); } - - // Add |node| as a starting point for the traversal. You may add - // as many starting points as you like. Return false on OOM. - bool addStart(Node node) { return pending.append(node); } - - // Add |node| as a starting point for the traversal (see addStart) and also - // add it to the |visited| set. Return false on OOM. - bool addStartVisited(Node node) { - typename NodeMap::AddPtr ptr = visited.lookupForAdd(node); - if (!ptr && !visited.add(ptr, node, typename Handler::NodeData())) - return false; - return addStart(node); - } - - // True if the handler wants us to compute edge names; doing so can be - // expensive in time and memory. True by default. - bool wantNames; - - // Traverse the graph in breadth-first order, starting at the given - // start nodes, applying |handler::operator()| for each edge traversed - // as described above. - // - // This should be called only once per instance of this class. - // - // Return false on OOM or error return from |handler::operator()|. - bool traverse() - { - MOZ_ASSERT(!traversalBegun); - traversalBegun = true; - - // While there are pending nodes, visit them. - while (!pending.empty()) { - Node origin = pending.front(); - pending.popFront(); - - // Get a range containing all origin's outgoing edges. - auto range = origin.edges(cx, wantNames); - if (!range) - return false; - - // Traverse each edge. - for (; !range->empty(); range->popFront()) { - MOZ_ASSERT(!stopRequested); - - Edge& edge = range->front(); - typename NodeMap::AddPtr a = visited.lookupForAdd(edge.referent); - bool first = !a; - - if (first) { - // This is the first time we've reached |edge.referent|. - // Mark it as visited. - if (!visited.add(a, edge.referent, typename Handler::NodeData())) - return false; - } - - MOZ_ASSERT(a); - - // Report this edge to the visitor function. - if (!handler(*this, origin, edge, &a->value(), first)) - return false; - - if (stopRequested) - return true; - - // Arrange to traverse this edge's referent's outgoing edges - // later --- unless |handler| asked us not to. - if (abandonRequested) { - // Skip the enqueue; reset flag for future iterations. - abandonRequested = false; - } else if (first) { - if (!pending.append(edge.referent)) - return false; - } - } - } - - return true; - } - - // Stop traversal, and return true from |traverse| without visiting any - // more nodes. Only |handler::operator()| should call this function; it - // may do so to stop the traversal early, without returning false and - // then making |traverse|'s caller disambiguate that result from a real - // error. - void stop() { stopRequested = true; } - - // Request that the current edge's referent's outgoing edges not be - // traversed. This must be called the first time that referent is reached. - // Other edges *to* that referent will still be traversed. - void abandonReferent() { abandonRequested = true; } - - // The context with which we were constructed. - JSContext* cx; - - // A map associating each node N that we have reached with a - // Handler::NodeData, for |handler|'s use. This is public, so that - // |handler| can access it to see the traversal thus far. - using NodeMap = js::HashMap, - js::SystemAllocPolicy>; - NodeMap visited; - - private: - // Our handler object. - Handler& handler; - - // A queue template. Appending and popping the front are constant time. - // Wasted space is never more than some recent actual population plus the - // current population. - template - class Queue { - js::Vector head, tail; - size_t frontIndex; - public: - Queue() : head(), tail(), frontIndex(0) { } - bool empty() { return frontIndex >= head.length(); } - T& front() { - MOZ_ASSERT(!empty()); - return head[frontIndex]; - } - void popFront() { - MOZ_ASSERT(!empty()); - frontIndex++; - if (frontIndex >= head.length()) { - head.clearAndFree(); - head.swap(tail); - frontIndex = 0; - } - } - bool append(const T& elt) { - return frontIndex == 0 ? head.append(elt) : tail.append(elt); - } - }; - - // A queue of nodes that we have reached, but whose outgoing edges we - // have not yet traversed. Nodes reachable in fewer edges are enqueued - // earlier. - Queue pending; - - // True if our traverse function has been called. - bool traversalBegun; - - // True if we've been asked to stop the traversal. - bool stopRequested; - - // True if we've been asked to abandon the current edge's referent. - bool abandonRequested; -}; - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeBreadthFirst_h diff --git a/mac/include/spidermonkey/js/UbiNodeCensus.h b/mac/include/spidermonkey/js/UbiNodeCensus.h deleted file mode 100644 index c0859ec5..00000000 --- a/mac/include/spidermonkey/js/UbiNodeCensus.h +++ /dev/null @@ -1,251 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeCensus_h -#define js_UbiNodeCensus_h - -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" - -#include - -#include "jsapi.h" - -#include "js/UbiNode.h" -#include "js/UbiNodeBreadthFirst.h" - -// A census is a ubi::Node traversal that assigns each node to one or more -// buckets, and returns a report with the size of each bucket. -// -// We summarize the results of a census with counts broken down according to -// criteria selected by the API consumer code that is requesting the census. For -// example, the following breakdown might give an interesting overview of the -// heap: -// -// - all nodes -// - objects -// - objects with a specific [[Class]] * -// - strings -// - scripts -// - all other Node types -// - nodes with a specific ubi::Node::typeName * -// -// Obviously, the parts of this tree marked with * represent many separate -// counts, depending on how many distinct [[Class]] values and ubi::Node type -// names we encounter. -// -// The supported types of breakdowns are documented in -// js/src/doc/Debugger/Debugger.Memory.md. -// -// When we parse the 'breakdown' argument to takeCensus, we build a tree of -// CountType nodes. For example, for the breakdown shown in the -// Debugger.Memory.prototype.takeCensus, documentation: -// -// { -// by: "coarseType", -// objects: { by: "objectClass" }, -// other: { by: "internalType" } -// } -// -// we would build the following tree of CountType subclasses: -// -// ByCoarseType -// objects: ByObjectClass -// each class: SimpleCount -// scripts: SimpleCount -// strings: SimpleCount -// other: ByUbinodeType -// each type: SimpleCount -// -// The interior nodes are all breakdown types that categorize nodes according to -// one characteristic or another; and the leaf nodes are all SimpleType. -// -// Each CountType has its own concrete C++ type that holds the counts it -// produces. SimpleCount::Count just holds totals. ByObjectClass::Count has a -// hash table whose keys are object class names and whose values are counts of -// some other type (in the example above, SimpleCount). -// -// To keep actual count nodes small, they have no vtable. Instead, each count -// points to its CountType, which knows how to carry out all the operations we -// need on a Count. A CountType can produce new count nodes; process nodes as we -// visit them; build a JS object reporting the results; and destruct count -// nodes. - - -namespace JS { -namespace ubi { - -struct Census; - -class CountBase; - -struct CountDeleter { - void operator()(CountBase*); -}; - -using CountBasePtr = js::UniquePtr; - -// Abstract base class for CountType nodes. -struct CountType { - explicit CountType() { } - virtual ~CountType() { } - - // Destruct a count tree node that this type instance constructed. - virtual void destructCount(CountBase& count) = 0; - - // Return a fresh node for the count tree that categorizes nodes according - // to this type. Return a nullptr on OOM. - virtual CountBasePtr makeCount() = 0; - - // Trace |count| and all its children, for garbage collection. - virtual void traceCount(CountBase& count, JSTracer* trc) = 0; - - // Implement the 'count' method for counts returned by this CountType - // instance's 'newCount' method. - virtual MOZ_MUST_USE bool count(CountBase& count, - mozilla::MallocSizeOf mallocSizeOf, - const Node& node) = 0; - - // Implement the 'report' method for counts returned by this CountType - // instance's 'newCount' method. - virtual MOZ_MUST_USE bool report(JSContext* cx, CountBase& count, - MutableHandleValue report) = 0; -}; - -using CountTypePtr = js::UniquePtr; - -// An abstract base class for count tree nodes. -class CountBase { - // In lieu of a vtable, each CountBase points to its type, which - // carries not only the implementations of the CountBase methods, but also - // additional parameters for the type's behavior, as specified in the - // breakdown argument passed to takeCensus. - CountType& type; - - protected: - ~CountBase() { } - - public: - explicit CountBase(CountType& type) - : type(type) - , total_(0) - , smallestNodeIdCounted_(SIZE_MAX) - { } - - // Categorize and count |node| as appropriate for this count's type. - MOZ_MUST_USE bool count(mozilla::MallocSizeOf mallocSizeOf, const Node& node) { - total_++; - - auto id = node.identifier(); - if (id < smallestNodeIdCounted_) { - smallestNodeIdCounted_ = id; - } - -#ifdef DEBUG - size_t oldTotal = total_; -#endif - - bool ret = type.count(*this, mallocSizeOf, node); - - MOZ_ASSERT(total_ == oldTotal, - "CountType::count should not increment total_, CountBase::count handles that"); - - return ret; - } - - // Construct a JavaScript object reporting the counts recorded in this - // count, and store it in |report|. Return true on success, or false on - // failure. - MOZ_MUST_USE bool report(JSContext* cx, MutableHandleValue report) { - return type.report(cx, *this, report); - } - - // Down-cast this CountBase to its true type, based on its 'type' member, - // and run its destructor. - void destruct() { return type.destructCount(*this); } - - // Trace this count for garbage collection. - void trace(JSTracer* trc) { type.traceCount(*this, trc); } - - size_t total_; - - // The smallest JS::ubi::Node::identifier() passed to this instance's - // count() method. This provides a stable way to sort sets. - Node::Id smallestNodeIdCounted_; -}; - -class RootedCount : JS::CustomAutoRooter { - CountBasePtr count; - - void trace(JSTracer* trc) override { count->trace(trc); } - - public: - RootedCount(JSContext* cx, CountBasePtr&& count) - : CustomAutoRooter(cx), - count(Move(count)) - { } - CountBase* operator->() const { return count.get(); } - explicit operator bool() const { return count.get(); } - operator CountBasePtr&() { return count; } -}; - -// Common data for a census traversal, shared across all CountType nodes. -struct Census { - JSContext* const cx; - // If the targetZones set is non-empty, then only consider nodes whose zone - // is an element of the set. If the targetZones set is empty, then nodes in - // all zones are considered. - JS::ZoneSet targetZones; - Zone* atomsZone; - - explicit Census(JSContext* cx) : cx(cx), atomsZone(nullptr) { } - - MOZ_MUST_USE bool init(); -}; - -// A BreadthFirst handler type that conducts a census, using a CountBase to -// categorize and count each node. -class CensusHandler { - Census& census; - CountBasePtr& rootCount; - mozilla::MallocSizeOf mallocSizeOf; - - public: - CensusHandler(Census& census, CountBasePtr& rootCount, mozilla::MallocSizeOf mallocSizeOf) - : census(census), - rootCount(rootCount), - mallocSizeOf(mallocSizeOf) - { } - - MOZ_MUST_USE bool report(JSContext* cx, MutableHandleValue report) { - return rootCount->report(cx, report); - } - - // This class needs to retain no per-node data. - class NodeData { }; - - MOZ_MUST_USE bool operator() (BreadthFirst& traversal, - Node origin, const Edge& edge, - NodeData* referentData, bool first); -}; - -using CensusTraversal = BreadthFirst; - -// Examine the census options supplied by the API consumer, and (among other -// things) use that to build a CountType tree. -MOZ_MUST_USE bool ParseCensusOptions(JSContext* cx, Census& census, HandleObject options, - CountTypePtr& outResult); - -// Parse the breakdown language (as described in -// js/src/doc/Debugger/Debugger.Memory.md) into a CountTypePtr. A null pointer -// is returned on error and is reported to the cx. -CountTypePtr ParseBreakdown(JSContext* cx, HandleValue breakdownValue); - - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeCensus_h diff --git a/mac/include/spidermonkey/js/UbiNodeDominatorTree.h b/mac/include/spidermonkey/js/UbiNodeDominatorTree.h deleted file mode 100644 index 3422b76b..00000000 --- a/mac/include/spidermonkey/js/UbiNodeDominatorTree.h +++ /dev/null @@ -1,677 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeDominatorTree_h -#define js_UbiNodeDominatorTree_h - -#include "mozilla/Attributes.h" -#include "mozilla/DebugOnly.h" -#include "mozilla/Maybe.h" -#include "mozilla/Move.h" -#include "mozilla/UniquePtr.h" - -#include "jsalloc.h" - -#include "js/UbiNode.h" -#include "js/UbiNodePostOrder.h" -#include "js/Utility.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -/** - * In a directed graph with a root node `R`, a node `A` is said to "dominate" a - * node `B` iff every path from `R` to `B` contains `A`. A node `A` is said to - * be the "immediate dominator" of a node `B` iff it dominates `B`, is not `B` - * itself, and does not dominate any other nodes which also dominate `B` in - * turn. - * - * If we take every node from a graph `G` and create a new graph `T` with edges - * to each node from its immediate dominator, then `T` is a tree (each node has - * only one immediate dominator, or none if it is the root). This tree is called - * a "dominator tree". - * - * This class represents a dominator tree constructed from a `JS::ubi::Node` - * heap graph. The domination relationship and dominator trees are useful tools - * for analyzing heap graphs because they tell you: - * - * - Exactly what could be reclaimed by the GC if some node `A` became - * unreachable: those nodes which are dominated by `A`, - * - * - The "retained size" of a node in the heap graph, in contrast to its - * "shallow size". The "shallow size" is the space taken by a node itself, - * not counting anything it references. The "retained size" of a node is its - * shallow size plus the size of all the things that would be collected if - * the original node wasn't (directly or indirectly) referencing them. In - * other words, the retained size is the shallow size of a node plus the - * shallow sizes of every other node it dominates. For example, the root - * node in a binary tree might have a small shallow size that does not take - * up much space itself, but it dominates the rest of the binary tree and - * its retained size is therefore significant (assuming no external - * references into the tree). - * - * The simple, engineered algorithm presented in "A Simple, Fast Dominance - * Algorithm" by Cooper el al[0] is used to find dominators and construct the - * dominator tree. This algorithm runs in O(n^2) time, but is faster in practice - * than alternative algorithms with better theoretical running times, such as - * Lengauer-Tarjan which runs in O(e * log(n)). The big caveat to that statement - * is that Cooper et al found it is faster in practice *on control flow graphs* - * and I'm not convinced that this property also holds on *heap* graphs. That - * said, the implementation of this algorithm is *much* simpler than - * Lengauer-Tarjan and has been found to be fast enough at least for the time - * being. - * - * [0]: http://www.cs.rice.edu/~keith/EMBED/dom.pdf - */ -class JS_PUBLIC_API(DominatorTree) -{ - private: - // Types. - - using PredecessorSets = js::HashMap, - js::SystemAllocPolicy>; - using NodeToIndexMap = js::HashMap, - js::SystemAllocPolicy>; - class DominatedSets; - - public: - class DominatedSetRange; - - /** - * A pointer to an immediately dominated node. - * - * Don't use this type directly; it is no safer than regular pointers. This - * is only for use indirectly with range-based for loops and - * `DominatedSetRange`. - * - * @see JS::ubi::DominatorTree::getDominatedSet - */ - class DominatedNodePtr - { - friend class DominatedSetRange; - - const JS::ubi::Vector& postOrder; - const uint32_t* ptr; - - DominatedNodePtr(const JS::ubi::Vector& postOrder, const uint32_t* ptr) - : postOrder(postOrder) - , ptr(ptr) - { } - - public: - bool operator!=(const DominatedNodePtr& rhs) const { return ptr != rhs.ptr; } - void operator++() { ptr++; } - const Node& operator*() const { return postOrder[*ptr]; } - }; - - /** - * A range of immediately dominated `JS::ubi::Node`s for use with - * range-based for loops. - * - * @see JS::ubi::DominatorTree::getDominatedSet - */ - class DominatedSetRange - { - friend class DominatedSets; - - const JS::ubi::Vector& postOrder; - const uint32_t* beginPtr; - const uint32_t* endPtr; - - DominatedSetRange(JS::ubi::Vector& postOrder, const uint32_t* begin, const uint32_t* end) - : postOrder(postOrder) - , beginPtr(begin) - , endPtr(end) - { - MOZ_ASSERT(begin <= end); - } - - public: - DominatedNodePtr begin() const { - MOZ_ASSERT(beginPtr <= endPtr); - return DominatedNodePtr(postOrder, beginPtr); - } - - DominatedNodePtr end() const { - return DominatedNodePtr(postOrder, endPtr); - } - - size_t length() const { - MOZ_ASSERT(beginPtr <= endPtr); - return endPtr - beginPtr; - } - - /** - * Safely skip ahead `n` dominators in the range, in O(1) time. - * - * Example usage: - * - * mozilla::Maybe range = myDominatorTree.getDominatedSet(myNode); - * if (range.isNothing()) { - * // Handle unknown nodes however you see fit... - * return false; - * } - * - * // Don't care about the first ten, for whatever reason. - * range->skip(10); - * for (const JS::ubi::Node& dominatedNode : *range) { - * // ... - * } - */ - void skip(size_t n) { - beginPtr += n; - if (beginPtr > endPtr) - beginPtr = endPtr; - } - }; - - private: - /** - * The set of all dominated sets in a dominator tree. - * - * Internally stores the sets in a contiguous array, with a side table of - * indices into that contiguous array to denote the start index of each - * individual set. - */ - class DominatedSets - { - JS::ubi::Vector dominated; - JS::ubi::Vector indices; - - DominatedSets(JS::ubi::Vector&& dominated, JS::ubi::Vector&& indices) - : dominated(mozilla::Move(dominated)) - , indices(mozilla::Move(indices)) - { } - - public: - // DominatedSets is not copy-able. - DominatedSets(const DominatedSets& rhs) = delete; - DominatedSets& operator=(const DominatedSets& rhs) = delete; - - // DominatedSets is move-able. - DominatedSets(DominatedSets&& rhs) - : dominated(mozilla::Move(rhs.dominated)) - , indices(mozilla::Move(rhs.indices)) - { - MOZ_ASSERT(this != &rhs, "self-move not allowed"); - } - DominatedSets& operator=(DominatedSets&& rhs) { - this->~DominatedSets(); - new (this) DominatedSets(mozilla::Move(rhs)); - return *this; - } - - /** - * Create the DominatedSets given the mapping of a node index to its - * immediate dominator. Returns `Some` on success, `Nothing` on OOM - * failure. - */ - static mozilla::Maybe Create(const JS::ubi::Vector& doms) { - auto length = doms.length(); - MOZ_ASSERT(length < UINT32_MAX); - - // Create a vector `dominated` holding a flattened set of buckets of - // immediately dominated children nodes, with a lookup table - // `indices` mapping from each node to the beginning of its bucket. - // - // This has three phases: - // - // 1. Iterate over the full set of nodes and count up the size of - // each bucket. These bucket sizes are temporarily stored in the - // `indices` vector. - // - // 2. Convert the `indices` vector to store the cumulative sum of - // the sizes of all buckets before each index, resulting in a - // mapping from node index to one past the end of that node's - // bucket. - // - // 3. Iterate over the full set of nodes again, filling in bucket - // entries from the end of the bucket's range to its - // beginning. This decrements each index as a bucket entry is - // filled in. After having filled in all of a bucket's entries, - // the index points to the start of the bucket. - - JS::ubi::Vector dominated; - JS::ubi::Vector indices; - if (!dominated.growBy(length) || !indices.growBy(length)) - return mozilla::Nothing(); - - // 1 - memset(indices.begin(), 0, length * sizeof(uint32_t)); - for (uint32_t i = 0; i < length; i++) - indices[doms[i]]++; - - // 2 - uint32_t sumOfSizes = 0; - for (uint32_t i = 0; i < length; i++) { - sumOfSizes += indices[i]; - MOZ_ASSERT(sumOfSizes <= length); - indices[i] = sumOfSizes; - } - - // 3 - for (uint32_t i = 0; i < length; i++) { - auto idxOfDom = doms[i]; - indices[idxOfDom]--; - dominated[indices[idxOfDom]] = i; - } - -#ifdef DEBUG - // Assert that our buckets are non-overlapping and don't run off the - // end of the vector. - uint32_t lastIndex = 0; - for (uint32_t i = 0; i < length; i++) { - MOZ_ASSERT(indices[i] >= lastIndex); - MOZ_ASSERT(indices[i] < length); - lastIndex = indices[i]; - } -#endif - - return mozilla::Some(DominatedSets(mozilla::Move(dominated), mozilla::Move(indices))); - } - - /** - * Get the set of nodes immediately dominated by the node at - * `postOrder[nodeIndex]`. - */ - DominatedSetRange dominatedSet(JS::ubi::Vector& postOrder, uint32_t nodeIndex) const { - MOZ_ASSERT(postOrder.length() == indices.length()); - MOZ_ASSERT(nodeIndex < indices.length()); - auto end = nodeIndex == indices.length() - 1 - ? dominated.end() - : &dominated[indices[nodeIndex + 1]]; - return DominatedSetRange(postOrder, &dominated[indices[nodeIndex]], end); - } - }; - - private: - // Data members. - JS::ubi::Vector postOrder; - NodeToIndexMap nodeToPostOrderIndex; - JS::ubi::Vector doms; - DominatedSets dominatedSets; - mozilla::Maybe> retainedSizes; - - private: - // We use `UNDEFINED` as a sentinel value in the `doms` vector to signal - // that we haven't found any dominators for the node at the corresponding - // index in `postOrder` yet. - static const uint32_t UNDEFINED = UINT32_MAX; - - DominatorTree(JS::ubi::Vector&& postOrder, NodeToIndexMap&& nodeToPostOrderIndex, - JS::ubi::Vector&& doms, DominatedSets&& dominatedSets) - : postOrder(mozilla::Move(postOrder)) - , nodeToPostOrderIndex(mozilla::Move(nodeToPostOrderIndex)) - , doms(mozilla::Move(doms)) - , dominatedSets(mozilla::Move(dominatedSets)) - , retainedSizes(mozilla::Nothing()) - { } - - static uint32_t intersect(JS::ubi::Vector& doms, uint32_t finger1, uint32_t finger2) { - while (finger1 != finger2) { - if (finger1 < finger2) - finger1 = doms[finger1]; - else if (finger2 < finger1) - finger2 = doms[finger2]; - } - return finger1; - } - - // Do the post order traversal of the heap graph and populate our - // predecessor sets. - static MOZ_MUST_USE bool doTraversal(JSContext* cx, AutoCheckCannotGC& noGC, const Node& root, - JS::ubi::Vector& postOrder, - PredecessorSets& predecessorSets) { - uint32_t nodeCount = 0; - auto onNode = [&](const Node& node) { - nodeCount++; - if (MOZ_UNLIKELY(nodeCount == UINT32_MAX)) - return false; - return postOrder.append(node); - }; - - auto onEdge = [&](const Node& origin, const Edge& edge) { - auto p = predecessorSets.lookupForAdd(edge.referent); - if (!p) { - mozilla::UniquePtr> set(js_new()); - if (!set || - !set->init() || - !predecessorSets.add(p, edge.referent, mozilla::Move(set))) - { - return false; - } - } - MOZ_ASSERT(p && p->value()); - return p->value()->put(origin); - }; - - PostOrder traversal(cx, noGC); - return traversal.init() && - traversal.addStart(root) && - traversal.traverse(onNode, onEdge); - } - - // Populates the given `map` with an entry for each node to its index in - // `postOrder`. - static MOZ_MUST_USE bool mapNodesToTheirIndices(JS::ubi::Vector& postOrder, - NodeToIndexMap& map) { - MOZ_ASSERT(!map.initialized()); - MOZ_ASSERT(postOrder.length() < UINT32_MAX); - uint32_t length = postOrder.length(); - if (!map.init(length)) - return false; - for (uint32_t i = 0; i < length; i++) - map.putNewInfallible(postOrder[i], i); - return true; - } - - // Convert the Node -> NodeSet predecessorSets to a index -> Vector - // form. - static MOZ_MUST_USE bool convertPredecessorSetsToVectors( - const Node& root, - JS::ubi::Vector& postOrder, - PredecessorSets& predecessorSets, - NodeToIndexMap& nodeToPostOrderIndex, - JS::ubi::Vector>& predecessorVectors) - { - MOZ_ASSERT(postOrder.length() < UINT32_MAX); - uint32_t length = postOrder.length(); - - MOZ_ASSERT(predecessorVectors.length() == 0); - if (!predecessorVectors.growBy(length)) - return false; - - for (uint32_t i = 0; i < length - 1; i++) { - auto& node = postOrder[i]; - MOZ_ASSERT(node != root, - "Only the last node should be root, since this was a post order traversal."); - - auto ptr = predecessorSets.lookup(node); - MOZ_ASSERT(ptr, - "Because this isn't the root, it had better have predecessors, or else how " - "did we even find it."); - - auto& predecessors = ptr->value(); - if (!predecessorVectors[i].reserve(predecessors->count())) - return false; - for (auto range = predecessors->all(); !range.empty(); range.popFront()) { - auto ptr = nodeToPostOrderIndex.lookup(range.front()); - MOZ_ASSERT(ptr); - predecessorVectors[i].infallibleAppend(ptr->value()); - } - } - predecessorSets.finish(); - return true; - } - - // Initialize `doms` such that the immediate dominator of the `root` is the - // `root` itself and all others are `UNDEFINED`. - static MOZ_MUST_USE bool initializeDominators(JS::ubi::Vector& doms, - uint32_t length) { - MOZ_ASSERT(doms.length() == 0); - if (!doms.growByUninitialized(length)) - return false; - doms[length - 1] = length - 1; - for (uint32_t i = 0; i < length - 1; i++) - doms[i] = UNDEFINED; - return true; - } - - void assertSanity() const { - MOZ_ASSERT(postOrder.length() == doms.length()); - MOZ_ASSERT(postOrder.length() == nodeToPostOrderIndex.count()); - MOZ_ASSERT_IF(retainedSizes.isSome(), postOrder.length() == retainedSizes->length()); - } - - MOZ_MUST_USE bool computeRetainedSizes(mozilla::MallocSizeOf mallocSizeOf) { - MOZ_ASSERT(retainedSizes.isNothing()); - auto length = postOrder.length(); - - retainedSizes.emplace(); - if (!retainedSizes->growBy(length)) { - retainedSizes = mozilla::Nothing(); - return false; - } - - // Iterate in forward order so that we know all of a node's children in - // the dominator tree have already had their retained size - // computed. Then we can simply say that the retained size of a node is - // its shallow size (JS::ubi::Node::size) plus the retained sizes of its - // immediate children in the tree. - - for (uint32_t i = 0; i < length; i++) { - auto size = postOrder[i].size(mallocSizeOf); - - for (const auto& dominated : dominatedSets.dominatedSet(postOrder, i)) { - // The root node dominates itself, but shouldn't contribute to - // its own retained size. - if (dominated == postOrder[length - 1]) { - MOZ_ASSERT(i == length - 1); - continue; - } - - auto ptr = nodeToPostOrderIndex.lookup(dominated); - MOZ_ASSERT(ptr); - auto idxOfDominated = ptr->value(); - MOZ_ASSERT(idxOfDominated < i); - size += retainedSizes.ref()[idxOfDominated]; - } - - retainedSizes.ref()[i] = size; - } - - return true; - } - - public: - // DominatorTree is not copy-able. - DominatorTree(const DominatorTree&) = delete; - DominatorTree& operator=(const DominatorTree&) = delete; - - // DominatorTree is move-able. - DominatorTree(DominatorTree&& rhs) - : postOrder(mozilla::Move(rhs.postOrder)) - , nodeToPostOrderIndex(mozilla::Move(rhs.nodeToPostOrderIndex)) - , doms(mozilla::Move(rhs.doms)) - , dominatedSets(mozilla::Move(rhs.dominatedSets)) - , retainedSizes(mozilla::Move(rhs.retainedSizes)) - { - MOZ_ASSERT(this != &rhs, "self-move is not allowed"); - } - DominatorTree& operator=(DominatorTree&& rhs) { - this->~DominatorTree(); - new (this) DominatorTree(mozilla::Move(rhs)); - return *this; - } - - /** - * Construct a `DominatorTree` of the heap graph visible from `root`. The - * `root` is also used as the root of the resulting dominator tree. - * - * The resulting `DominatorTree` instance must not outlive the - * `JS::ubi::Node` graph it was constructed from. - * - * - For `JS::ubi::Node` graphs backed by the live heap graph, this means - * that the `DominatorTree`'s lifetime _must_ be contained within the - * scope of the provided `AutoCheckCannotGC` reference because a GC will - * invalidate the nodes. - * - * - For `JS::ubi::Node` graphs backed by some other offline structure - * provided by the embedder, the resulting `DominatorTree`'s lifetime is - * bounded by that offline structure's lifetime. - * - * In practice, this means that within SpiderMonkey we must treat - * `DominatorTree` as if it were backed by the live heap graph and trust - * that embedders with knowledge of the graph's implementation will do the - * Right Thing. - * - * Returns `mozilla::Nothing()` on OOM failure. It is the caller's - * responsibility to handle and report the OOM. - */ - static mozilla::Maybe - Create(JSContext* cx, AutoCheckCannotGC& noGC, const Node& root) { - JS::ubi::Vector postOrder; - PredecessorSets predecessorSets; - if (!predecessorSets.init() || !doTraversal(cx, noGC, root, postOrder, predecessorSets)) - return mozilla::Nothing(); - - MOZ_ASSERT(postOrder.length() < UINT32_MAX); - uint32_t length = postOrder.length(); - MOZ_ASSERT(postOrder[length - 1] == root); - - // From here on out we wish to avoid hash table lookups, and we use - // indices into `postOrder` instead of actual nodes wherever - // possible. This greatly improves the performance of this - // implementation, but we have to pay a little bit of upfront cost to - // convert our data structures to play along first. - - NodeToIndexMap nodeToPostOrderIndex; - if (!mapNodesToTheirIndices(postOrder, nodeToPostOrderIndex)) - return mozilla::Nothing(); - - JS::ubi::Vector> predecessorVectors; - if (!convertPredecessorSetsToVectors(root, postOrder, predecessorSets, nodeToPostOrderIndex, - predecessorVectors)) - return mozilla::Nothing(); - - JS::ubi::Vector doms; - if (!initializeDominators(doms, length)) - return mozilla::Nothing(); - - bool changed = true; - while (changed) { - changed = false; - - // Iterate over the non-root nodes in reverse post order. - for (uint32_t indexPlusOne = length - 1; indexPlusOne > 0; indexPlusOne--) { - MOZ_ASSERT(postOrder[indexPlusOne - 1] != root); - - // Take the intersection of every predecessor's dominator set; - // that is the current best guess at the immediate dominator for - // this node. - - uint32_t newIDomIdx = UNDEFINED; - - auto& predecessors = predecessorVectors[indexPlusOne - 1]; - auto range = predecessors.all(); - for ( ; !range.empty(); range.popFront()) { - auto idx = range.front(); - if (doms[idx] != UNDEFINED) { - newIDomIdx = idx; - break; - } - } - - MOZ_ASSERT(newIDomIdx != UNDEFINED, - "Because the root is initialized to dominate itself and is the first " - "node in every path, there must exist a predecessor to this node that " - "also has a dominator."); - - for ( ; !range.empty(); range.popFront()) { - auto idx = range.front(); - if (doms[idx] != UNDEFINED) - newIDomIdx = intersect(doms, newIDomIdx, idx); - } - - // If the immediate dominator changed, we will have to do - // another pass of the outer while loop to continue the forward - // dataflow. - if (newIDomIdx != doms[indexPlusOne - 1]) { - doms[indexPlusOne - 1] = newIDomIdx; - changed = true; - } - } - } - - auto maybeDominatedSets = DominatedSets::Create(doms); - if (maybeDominatedSets.isNothing()) - return mozilla::Nothing(); - - return mozilla::Some(DominatorTree(mozilla::Move(postOrder), - mozilla::Move(nodeToPostOrderIndex), - mozilla::Move(doms), - mozilla::Move(*maybeDominatedSets))); - } - - /** - * Get the root node for this dominator tree. - */ - const Node& root() const { - return postOrder[postOrder.length() - 1]; - } - - /** - * Return the immediate dominator of the given `node`. If `node` was not - * reachable from the `root` that this dominator tree was constructed from, - * then return the null `JS::ubi::Node`. - */ - Node getImmediateDominator(const Node& node) const { - assertSanity(); - auto ptr = nodeToPostOrderIndex.lookup(node); - if (!ptr) - return Node(); - - auto idx = ptr->value(); - MOZ_ASSERT(idx < postOrder.length()); - return postOrder[doms[idx]]; - } - - /** - * Get the set of nodes immediately dominated by the given `node`. If `node` - * is not a member of this dominator tree, return `Nothing`. - * - * Example usage: - * - * mozilla::Maybe range = myDominatorTree.getDominatedSet(myNode); - * if (range.isNothing()) { - * // Handle unknown node however you see fit... - * return false; - * } - * - * for (const JS::ubi::Node& dominatedNode : *range) { - * // Do something with each immediately dominated node... - * } - */ - mozilla::Maybe getDominatedSet(const Node& node) { - assertSanity(); - auto ptr = nodeToPostOrderIndex.lookup(node); - if (!ptr) - return mozilla::Nothing(); - - auto idx = ptr->value(); - MOZ_ASSERT(idx < postOrder.length()); - return mozilla::Some(dominatedSets.dominatedSet(postOrder, idx)); - } - - /** - * Get the retained size of the given `node`. The size is placed in - * `outSize`, or 0 if `node` is not a member of the dominator tree. Returns - * false on OOM failure, leaving `outSize` unchanged. - */ - MOZ_MUST_USE bool getRetainedSize(const Node& node, mozilla::MallocSizeOf mallocSizeOf, - Node::Size& outSize) { - assertSanity(); - auto ptr = nodeToPostOrderIndex.lookup(node); - if (!ptr) { - outSize = 0; - return true; - } - - if (retainedSizes.isNothing() && !computeRetainedSizes(mallocSizeOf)) - return false; - - auto idx = ptr->value(); - MOZ_ASSERT(idx < postOrder.length()); - outSize = retainedSizes.ref()[idx]; - return true; - } -}; - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeDominatorTree_h diff --git a/mac/include/spidermonkey/js/UbiNodePostOrder.h b/mac/include/spidermonkey/js/UbiNodePostOrder.h deleted file mode 100644 index a5042677..00000000 --- a/mac/include/spidermonkey/js/UbiNodePostOrder.h +++ /dev/null @@ -1,191 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodePostOrder_h -#define js_UbiNodePostOrder_h - -#include "mozilla/Attributes.h" -#include "mozilla/Maybe.h" -#include "mozilla/Move.h" - -#include "jsalloc.h" - -#include "js/UbiNode.h" -#include "js/Utility.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -/** - * A post-order depth-first traversal of `ubi::Node` graphs. - * - * No GC may occur while an instance of `PostOrder` is live. - * - * The `NodeVisitor` type provided to `PostOrder::traverse` must have the - * following member: - * - * bool operator()(Node& node) - * - * The node visitor method. This method is called once for each `node` - * reachable from the start set in post-order. - * - * This visitor function should return true on success, or false if an error - * occurs. A false return value terminates the traversal immediately, and - * causes `PostOrder::traverse` to return false. - * - * The `EdgeVisitor` type provided to `PostOrder::traverse` must have the - * following member: - * - * bool operator()(Node& origin, Edge& edge) - * - * The edge visitor method. This method is called once for each outgoing - * `edge` from `origin` that is reachable from the start set. - * - * NB: UNLIKE NODES, THERE IS NO GUARANTEED ORDER IN WHICH EDGES AND THEIR - * ORIGINS ARE VISITED! - * - * This visitor function should return true on success, or false if an error - * occurs. A false return value terminates the traversal immediately, and - * causes `PostOrder::traverse` to return false. - */ -struct PostOrder { - private: - struct OriginAndEdges { - Node origin; - EdgeVector edges; - - OriginAndEdges(const Node& node, EdgeVector&& edges) - : origin(node) - , edges(mozilla::Move(edges)) - { } - - OriginAndEdges(const OriginAndEdges& rhs) = delete; - OriginAndEdges& operator=(const OriginAndEdges& rhs) = delete; - - OriginAndEdges(OriginAndEdges&& rhs) - : origin(rhs.origin) - , edges(mozilla::Move(rhs.edges)) - { - MOZ_ASSERT(&rhs != this, "self-move disallowed"); - } - - OriginAndEdges& operator=(OriginAndEdges&& rhs) { - this->~OriginAndEdges(); - new (this) OriginAndEdges(mozilla::Move(rhs)); - return *this; - } - }; - - using Stack = js::Vector; - using Set = js::HashSet, js::SystemAllocPolicy>; - - JSContext* cx; - Set seen; - Stack stack; -#ifdef DEBUG - bool traversed; -#endif - - private: - MOZ_MUST_USE bool fillEdgesFromRange(EdgeVector& edges, js::UniquePtr& range) { - MOZ_ASSERT(range); - for ( ; !range->empty(); range->popFront()) { - if (!edges.append(mozilla::Move(range->front()))) - return false; - } - return true; - } - - MOZ_MUST_USE bool pushForTraversing(const Node& node) { - EdgeVector edges; - auto range = node.edges(cx, /* wantNames */ false); - return range && - fillEdgesFromRange(edges, range) && - stack.append(OriginAndEdges(node, mozilla::Move(edges))); - } - - - public: - // Construct a post-order traversal object. - // - // The traversal asserts that no GC happens in its runtime during its - // lifetime via the `AutoCheckCannotGC&` parameter. We do nothing with it, - // other than require it to exist with a lifetime that encloses our own. - PostOrder(JSContext* cx, AutoCheckCannotGC&) - : cx(cx) - , seen() - , stack() -#ifdef DEBUG - , traversed(false) -#endif - { } - - // Initialize this traversal object. Return false on OOM. - MOZ_MUST_USE bool init() { return seen.init(); } - - // Add `node` as a starting point for the traversal. You may add - // as many starting points as you like. Returns false on OOM. - MOZ_MUST_USE bool addStart(const Node& node) { - if (!seen.put(node)) - return false; - return pushForTraversing(node); - } - - // Traverse the graph in post-order, starting with the set of nodes passed - // to `addStart` and applying `onNode::operator()` for each node in the - // graph and `onEdge::operator()` for each edge in the graph, as described - // above. - // - // This should be called only once per instance of this class. - // - // Return false on OOM or error return from `onNode::operator()` or - // `onEdge::operator()`. - template - MOZ_MUST_USE bool traverse(NodeVisitor onNode, EdgeVisitor onEdge) { -#ifdef DEBUG - MOZ_ASSERT(!traversed, "Can only traverse() once!"); - traversed = true; -#endif - - while (!stack.empty()) { - auto& origin = stack.back().origin; - auto& edges = stack.back().edges; - - if (edges.empty()) { - if (!onNode(origin)) - return false; - stack.popBack(); - continue; - } - - Edge edge = mozilla::Move(edges.back()); - edges.popBack(); - - if (!onEdge(origin, edge)) - return false; - - auto ptr = seen.lookupForAdd(edge.referent); - // We've already seen this node, don't follow its edges. - if (ptr) - continue; - - // Mark the referent as seen and follow its edges. - if (!seen.add(ptr, edge.referent) || - !pushForTraversing(edge.referent)) - { - return false; - } - } - - return true; - } -}; - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodePostOrder_h diff --git a/mac/include/spidermonkey/js/UbiNodeShortestPaths.h b/mac/include/spidermonkey/js/UbiNodeShortestPaths.h deleted file mode 100644 index edd5aebb..00000000 --- a/mac/include/spidermonkey/js/UbiNodeShortestPaths.h +++ /dev/null @@ -1,350 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeShortestPaths_h -#define js_UbiNodeShortestPaths_h - -#include "mozilla/Attributes.h" -#include "mozilla/Maybe.h" -#include "mozilla/Move.h" - -#include "jsalloc.h" - -#include "js/UbiNodeBreadthFirst.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -/** - * A back edge along a path in the heap graph. - */ -struct JS_PUBLIC_API(BackEdge) -{ - private: - Node predecessor_; - EdgeName name_; - - public: - using Ptr = mozilla::UniquePtr>; - - BackEdge() : predecessor_(), name_(nullptr) { } - - MOZ_MUST_USE bool init(const Node& predecessor, Edge& edge) { - MOZ_ASSERT(!predecessor_); - MOZ_ASSERT(!name_); - - predecessor_ = predecessor; - name_ = mozilla::Move(edge.name); - return true; - } - - BackEdge(const BackEdge&) = delete; - BackEdge& operator=(const BackEdge&) = delete; - - BackEdge(BackEdge&& rhs) - : predecessor_(rhs.predecessor_) - , name_(mozilla::Move(rhs.name_)) - { - MOZ_ASSERT(&rhs != this); - } - - BackEdge& operator=(BackEdge&& rhs) { - this->~BackEdge(); - new(this) BackEdge(Move(rhs)); - return *this; - } - - Ptr clone() const; - - const EdgeName& name() const { return name_; } - EdgeName& name() { return name_; } - - const JS::ubi::Node& predecessor() const { return predecessor_; } -}; - -/** - * A path is a series of back edges from which we discovered a target node. - */ -using Path = JS::ubi::Vector; - -/** - * The `JS::ubi::ShortestPaths` type represents a collection of up to N shortest - * retaining paths for each of a target set of nodes, starting from the same - * root node. - */ -struct JS_PUBLIC_API(ShortestPaths) -{ - private: - // Types, type aliases, and data members. - - using BackEdgeVector = JS::ubi::Vector; - using NodeToBackEdgeVectorMap = js::HashMap, - js::SystemAllocPolicy>; - - struct Handler; - using Traversal = BreadthFirst; - - /** - * A `JS::ubi::BreadthFirst` traversal handler that records back edges for - * how we reached each node, allowing us to reconstruct the shortest - * retaining paths after the traversal. - */ - struct Handler - { - using NodeData = BackEdge; - - ShortestPaths& shortestPaths; - size_t totalMaxPathsToRecord; - size_t totalPathsRecorded; - - explicit Handler(ShortestPaths& shortestPaths) - : shortestPaths(shortestPaths) - , totalMaxPathsToRecord(shortestPaths.targets_.count() * shortestPaths.maxNumPaths_) - , totalPathsRecorded(0) - { - } - - bool - operator()(Traversal& traversal, JS::ubi::Node origin, JS::ubi::Edge& edge, - BackEdge* back, bool first) - { - MOZ_ASSERT(back); - MOZ_ASSERT(origin == shortestPaths.root_ || traversal.visited.has(origin)); - MOZ_ASSERT(totalPathsRecorded < totalMaxPathsToRecord); - - if (first && !back->init(origin, edge)) - return false; - - if (!shortestPaths.targets_.has(edge.referent)) - return true; - - // If `first` is true, then we moved the edge's name into `back` in - // the above call to `init`. So clone that back edge to get the - // correct edge name. If `first` is not true, then our edge name is - // still in `edge`. This accounts for the asymmetry between - // `back->clone()` in the first branch, and the `init` call in the - // second branch. - - if (first) { - BackEdgeVector paths; - if (!paths.reserve(shortestPaths.maxNumPaths_)) - return false; - auto cloned = back->clone(); - if (!cloned) - return false; - paths.infallibleAppend(mozilla::Move(cloned)); - if (!shortestPaths.paths_.putNew(edge.referent, mozilla::Move(paths))) - return false; - totalPathsRecorded++; - } else { - auto ptr = shortestPaths.paths_.lookup(edge.referent); - MOZ_ASSERT(ptr, - "This isn't the first time we have seen the target node `edge.referent`. " - "We should have inserted it into shortestPaths.paths_ the first time we " - "saw it."); - - if (ptr->value().length() < shortestPaths.maxNumPaths_) { - BackEdge::Ptr thisBackEdge(js_new()); - if (!thisBackEdge || !thisBackEdge->init(origin, edge)) - return false; - ptr->value().infallibleAppend(mozilla::Move(thisBackEdge)); - totalPathsRecorded++; - } - } - - MOZ_ASSERT(totalPathsRecorded <= totalMaxPathsToRecord); - if (totalPathsRecorded == totalMaxPathsToRecord) - traversal.stop(); - - return true; - } - - }; - - // The maximum number of paths to record for each node. - uint32_t maxNumPaths_; - - // The root node we are starting the search from. - Node root_; - - // The set of nodes we are searching for paths to. - NodeSet targets_; - - // The resulting paths. - NodeToBackEdgeVectorMap paths_; - - // Need to keep alive the traversal's back edges so we can walk them later - // when the traversal is over when recreating the shortest paths. - Traversal::NodeMap backEdges_; - - private: - // Private methods. - - ShortestPaths(uint32_t maxNumPaths, const Node& root, NodeSet&& targets) - : maxNumPaths_(maxNumPaths) - , root_(root) - , targets_(mozilla::Move(targets)) - , paths_() - , backEdges_() - { - MOZ_ASSERT(maxNumPaths_ > 0); - MOZ_ASSERT(root_); - MOZ_ASSERT(targets_.initialized()); - } - - bool initialized() const { - return targets_.initialized() && - paths_.initialized() && - backEdges_.initialized(); - } - - public: - // Public methods. - - ShortestPaths(ShortestPaths&& rhs) - : maxNumPaths_(rhs.maxNumPaths_) - , root_(rhs.root_) - , targets_(mozilla::Move(rhs.targets_)) - , paths_(mozilla::Move(rhs.paths_)) - , backEdges_(mozilla::Move(rhs.backEdges_)) - { - MOZ_ASSERT(this != &rhs, "self-move is not allowed"); - } - - ShortestPaths& operator=(ShortestPaths&& rhs) { - this->~ShortestPaths(); - new (this) ShortestPaths(mozilla::Move(rhs)); - return *this; - } - - ShortestPaths(const ShortestPaths&) = delete; - ShortestPaths& operator=(const ShortestPaths&) = delete; - - /** - * Construct a new `JS::ubi::ShortestPaths`, finding up to `maxNumPaths` - * shortest retaining paths for each target node in `targets` starting from - * `root`. - * - * The resulting `ShortestPaths` instance must not outlive the - * `JS::ubi::Node` graph it was constructed from. - * - * - For `JS::ubi::Node` graphs backed by the live heap graph, this means - * that the `ShortestPaths`'s lifetime _must_ be contained within the - * scope of the provided `AutoCheckCannotGC` reference because a GC will - * invalidate the nodes. - * - * - For `JS::ubi::Node` graphs backed by some other offline structure - * provided by the embedder, the resulting `ShortestPaths`'s lifetime is - * bounded by that offline structure's lifetime. - * - * Returns `mozilla::Nothing()` on OOM failure. It is the caller's - * responsibility to handle and report the OOM. - */ - static mozilla::Maybe - Create(JSContext* cx, AutoCheckCannotGC& noGC, uint32_t maxNumPaths, const Node& root, NodeSet&& targets) { - MOZ_ASSERT(targets.count() > 0); - MOZ_ASSERT(maxNumPaths > 0); - - size_t count = targets.count(); - ShortestPaths paths(maxNumPaths, root, mozilla::Move(targets)); - if (!paths.paths_.init(count)) - return mozilla::Nothing(); - - Handler handler(paths); - Traversal traversal(cx, handler, noGC); - traversal.wantNames = true; - if (!traversal.init() || !traversal.addStart(root) || !traversal.traverse()) - return mozilla::Nothing(); - - // Take ownership of the back edges we created while traversing the - // graph so that we can follow them from `paths_` and don't - // use-after-free. - paths.backEdges_ = mozilla::Move(traversal.visited); - - MOZ_ASSERT(paths.initialized()); - return mozilla::Some(mozilla::Move(paths)); - } - - /** - * Get a range that iterates over each target node we searched for retaining - * paths for. The returned range must not outlive the `ShortestPaths` - * instance. - */ - NodeSet::Range eachTarget() const { - MOZ_ASSERT(initialized()); - return targets_.all(); - } - - /** - * Invoke the provided functor/lambda/callable once for each retaining path - * discovered for `target`. The `func` is passed a single `JS::ubi::Path&` - * argument, which contains each edge along the path ordered starting from - * the root and ending at the target, and must not outlive the scope of the - * call. - * - * Note that it is possible that we did not find any paths from the root to - * the given target, in which case `func` will not be invoked. - */ - template - MOZ_MUST_USE bool forEachPath(const Node& target, Func func) { - MOZ_ASSERT(initialized()); - MOZ_ASSERT(targets_.has(target)); - - auto ptr = paths_.lookup(target); - - // We didn't find any paths to this target, so nothing to do here. - if (!ptr) - return true; - - MOZ_ASSERT(ptr->value().length() <= maxNumPaths_); - - Path path; - for (const auto& backEdge : ptr->value()) { - path.clear(); - - if (!path.append(backEdge.get())) - return false; - - Node here = backEdge->predecessor(); - MOZ_ASSERT(here); - - while (here != root_) { - auto p = backEdges_.lookup(here); - MOZ_ASSERT(p); - if (!path.append(&p->value())) - return false; - here = p->value().predecessor(); - MOZ_ASSERT(here); - } - - path.reverse(); - - if (!func(path)) - return false; - } - - return true; - } -}; - -#ifdef DEBUG -// A helper function to dump the first `maxNumPaths` shortest retaining paths to -// `node` from the GC roots. Useful when GC things you expect to have been -// reclaimed by the collector haven't been! -// -// Usage: -// -// JSObject* foo = ...; -// JS::ubi::dumpPaths(rt, JS::ubi::Node(foo)); -JS_PUBLIC_API(void) -dumpPaths(JSRuntime* rt, Node node, uint32_t maxNumPaths = 10); -#endif - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeShortestPaths_h diff --git a/mac/include/spidermonkey/js/UniquePtr.h b/mac/include/spidermonkey/js/UniquePtr.h deleted file mode 100644 index 0236bab4..00000000 --- a/mac/include/spidermonkey/js/UniquePtr.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UniquePtr_h -#define js_UniquePtr_h - -#include "mozilla/UniquePtr.h" - -#include "js/Utility.h" - -namespace js { - -// Replacement for mozilla::UniquePtr that defaults to js::DefaultDelete. -template > -using UniquePtr = mozilla::UniquePtr; - -namespace detail { - -template -struct UniqueSelector -{ - typedef UniquePtr SingleObject; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr UnknownBound; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr KnownBound; -}; - -} // namespace detail - -// Replacement for mozilla::MakeUnique that correctly calls js_new and produces -// a js::UniquePtr. -template -typename detail::UniqueSelector::SingleObject -MakeUnique(Args&&... aArgs) -{ - return UniquePtr(js_new(mozilla::Forward(aArgs)...)); -} - -template -typename detail::UniqueSelector::UnknownBound -MakeUnique(decltype(sizeof(int)) aN) = delete; - -template -typename detail::UniqueSelector::KnownBound -MakeUnique(Args&&... aArgs) = delete; - -} // namespace js - -#endif /* js_UniquePtr_h */ diff --git a/mac/include/spidermonkey/js/Utility.h b/mac/include/spidermonkey/js/Utility.h deleted file mode 100644 index 75214c32..00000000 --- a/mac/include/spidermonkey/js/Utility.h +++ /dev/null @@ -1,577 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Utility_h -#define js_Utility_h - -#include "mozilla/Assertions.h" -#include "mozilla/Atomics.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/Move.h" -#include "mozilla/Scoped.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/UniquePtr.h" - -#include -#include - -#ifdef JS_OOM_DO_BACKTRACES -#include -#include -#endif - -#include "jstypes.h" - -/* The public JS engine namespace. */ -namespace JS {} - -/* The mozilla-shared reusable template/utility namespace. */ -namespace mozilla {} - -/* The private JS engine namespace. */ -namespace js {} - -#define JS_STATIC_ASSERT(cond) static_assert(cond, "JS_STATIC_ASSERT") -#define JS_STATIC_ASSERT_IF(cond, expr) MOZ_STATIC_ASSERT_IF(cond, expr, "JS_STATIC_ASSERT_IF") - -extern MOZ_NORETURN MOZ_COLD JS_PUBLIC_API(void) -JS_Assert(const char* s, const char* file, int ln); - -/* - * Custom allocator support for SpiderMonkey - */ -#if defined JS_USE_CUSTOM_ALLOCATOR -# include "jscustomallocator.h" -#else - -namespace js { -namespace oom { - -/* - * To make testing OOM in certain helper threads more effective, - * allow restricting the OOM testing to a certain helper thread - * type. This allows us to fail e.g. in off-thread script parsing - * without causing an OOM in the main thread first. - */ -enum ThreadType { - THREAD_TYPE_NONE = 0, // 0 - THREAD_TYPE_MAIN, // 1 - THREAD_TYPE_ASMJS, // 2 - THREAD_TYPE_ION, // 3 - THREAD_TYPE_PARSE, // 4 - THREAD_TYPE_COMPRESS, // 5 - THREAD_TYPE_GCHELPER, // 6 - THREAD_TYPE_GCPARALLEL, // 7 - THREAD_TYPE_PROMISE_TASK, // 8 - THREAD_TYPE_MAX // Used to check shell function arguments -}; - -/* - * Getter/Setter functions to encapsulate mozilla::ThreadLocal, - * implementation is in jsutil.cpp. - */ -# if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) -extern bool InitThreadType(void); -extern void SetThreadType(ThreadType); -extern uint32_t GetThreadType(void); -# else -inline bool InitThreadType(void) { return true; } -inline void SetThreadType(ThreadType t) {}; -inline uint32_t GetThreadType(void) { return 0; } -# endif - -} /* namespace oom */ -} /* namespace js */ - -# if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) - -#ifdef JS_OOM_BREAKPOINT -static MOZ_NEVER_INLINE void js_failedAllocBreakpoint() { asm(""); } -#define JS_OOM_CALL_BP_FUNC() js_failedAllocBreakpoint() -#else -#define JS_OOM_CALL_BP_FUNC() do {} while(0) -#endif - -namespace js { -namespace oom { - -/* - * Out of memory testing support. We provide various testing functions to - * simulate OOM conditions and so we can test that they are handled correctly. - */ - -extern JS_PUBLIC_DATA(uint32_t) targetThread; -extern JS_PUBLIC_DATA(uint64_t) maxAllocations; -extern JS_PUBLIC_DATA(uint64_t) counter; -extern JS_PUBLIC_DATA(bool) failAlways; - -extern void -SimulateOOMAfter(uint64_t allocations, uint32_t thread, bool always); - -extern void -ResetSimulatedOOM(); - -inline bool -IsThreadSimulatingOOM() -{ - return js::oom::targetThread && js::oom::targetThread == js::oom::GetThreadType(); -} - -inline bool -IsSimulatedOOMAllocation() -{ - return IsThreadSimulatingOOM() && - (counter == maxAllocations || (counter > maxAllocations && failAlways)); -} - -inline bool -ShouldFailWithOOM() -{ - if (!IsThreadSimulatingOOM()) - return false; - - counter++; - if (IsSimulatedOOMAllocation()) { - JS_OOM_CALL_BP_FUNC(); - return true; - } - return false; -} - -inline bool -HadSimulatedOOM() { - return counter >= maxAllocations; -} - -} /* namespace oom */ -} /* namespace js */ - -# define JS_OOM_POSSIBLY_FAIL() \ - do { \ - if (js::oom::ShouldFailWithOOM()) \ - return nullptr; \ - } while (0) - -# define JS_OOM_POSSIBLY_FAIL_BOOL() \ - do { \ - if (js::oom::ShouldFailWithOOM()) \ - return false; \ - } while (0) - -# else - -# define JS_OOM_POSSIBLY_FAIL() do {} while(0) -# define JS_OOM_POSSIBLY_FAIL_BOOL() do {} while(0) -namespace js { -namespace oom { -static inline bool IsSimulatedOOMAllocation() { return false; } -static inline bool ShouldFailWithOOM() { return false; } -} /* namespace oom */ -} /* namespace js */ - -# endif /* DEBUG || JS_OOM_BREAKPOINT */ - -namespace js { - -/* Disable OOM testing in sections which are not OOM safe. */ -struct MOZ_RAII AutoEnterOOMUnsafeRegion -{ - MOZ_NORETURN MOZ_COLD void crash(const char* reason); - MOZ_NORETURN MOZ_COLD void crash(size_t size, const char* reason); - - using AnnotateOOMAllocationSizeCallback = void(*)(size_t); - static AnnotateOOMAllocationSizeCallback annotateOOMSizeCallback; - static void setAnnotateOOMAllocationSizeCallback(AnnotateOOMAllocationSizeCallback callback) { - annotateOOMSizeCallback = callback; - } - -#if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) - AutoEnterOOMUnsafeRegion() - : oomEnabled_(oom::IsThreadSimulatingOOM() && oom::maxAllocations != UINT64_MAX), - oomAfter_(0) - { - if (oomEnabled_) { - MOZ_ALWAYS_TRUE(owner_.compareExchange(nullptr, this)); - oomAfter_ = int64_t(oom::maxAllocations) - int64_t(oom::counter); - oom::maxAllocations = UINT64_MAX; - } - } - - ~AutoEnterOOMUnsafeRegion() { - if (oomEnabled_) { - MOZ_ASSERT(oom::maxAllocations == UINT64_MAX); - int64_t maxAllocations = int64_t(oom::counter) + oomAfter_; - MOZ_ASSERT(maxAllocations >= 0, - "alloc count + oom limit exceeds range, your oom limit is probably too large"); - oom::maxAllocations = uint64_t(maxAllocations); - MOZ_ALWAYS_TRUE(owner_.compareExchange(this, nullptr)); - } - } - - private: - // Used to catch concurrent use from other threads. - static mozilla::Atomic owner_; - - bool oomEnabled_; - int64_t oomAfter_; -#endif -}; - -} /* namespace js */ - -static inline void* js_malloc(size_t bytes) -{ - JS_OOM_POSSIBLY_FAIL(); - return malloc(bytes); -} - -static inline void* js_calloc(size_t bytes) -{ - JS_OOM_POSSIBLY_FAIL(); - return calloc(bytes, 1); -} - -static inline void* js_calloc(size_t nmemb, size_t size) -{ - JS_OOM_POSSIBLY_FAIL(); - return calloc(nmemb, size); -} - -static inline void* js_realloc(void* p, size_t bytes) -{ - // realloc() with zero size is not portable, as some implementations may - // return nullptr on success and free |p| for this. We assume nullptr - // indicates failure and that |p| is still valid. - MOZ_ASSERT(bytes != 0); - - JS_OOM_POSSIBLY_FAIL(); - return realloc(p, bytes); -} - -static inline void js_free(void* p) -{ - free(p); -} - -static inline char* js_strdup(const char* s) -{ - JS_OOM_POSSIBLY_FAIL(); - return strdup(s); -} -#endif/* JS_USE_CUSTOM_ALLOCATOR */ - -#include - -/* - * Low-level memory management in SpiderMonkey: - * - * ** Do not use the standard malloc/free/realloc: SpiderMonkey allows these - * to be redefined (via JS_USE_CUSTOM_ALLOCATOR) and Gecko even #define's - * these symbols. - * - * ** Do not use the builtin C++ operator new and delete: these throw on - * error and we cannot override them not to. - * - * Allocation: - * - * - If the lifetime of the allocation is tied to the lifetime of a GC-thing - * (that is, finalizing the GC-thing will free the allocation), call one of - * the following functions: - * - * JSContext::{malloc_,realloc_,calloc_,new_} - * JSRuntime::{malloc_,realloc_,calloc_,new_} - * - * These functions accumulate the number of bytes allocated which is used as - * part of the GC-triggering heuristic. - * - * The difference between the JSContext and JSRuntime versions is that the - * cx version reports an out-of-memory error on OOM. (This follows from the - * general SpiderMonkey idiom that a JSContext-taking function reports its - * own errors.) - * - * - Otherwise, use js_malloc/js_realloc/js_calloc/js_new - * - * Deallocation: - * - * - Ordinarily, use js_free/js_delete. - * - * - For deallocations during GC finalization, use one of the following - * operations on the FreeOp provided to the finalizer: - * - * FreeOp::{free_,delete_} - * - * The advantage of these operations is that the memory is batched and freed - * on another thread. - */ - -/* - * Given a class which should provide a 'new' method, add - * JS_DECLARE_NEW_METHODS (see js::MallocProvider for an example). - * - * Note: Do not add a ; at the end of a use of JS_DECLARE_NEW_METHODS, - * or the build will break. - */ -#define JS_DECLARE_NEW_METHODS(NEWNAME, ALLOCATOR, QUALIFIERS) \ - template \ - QUALIFIERS T * \ - NEWNAME(Args&&... args) MOZ_HEAP_ALLOCATOR { \ - void* memory = ALLOCATOR(sizeof(T)); \ - return MOZ_LIKELY(memory) \ - ? new(memory) T(mozilla::Forward(args)...) \ - : nullptr; \ - } - -/* - * Given a class which should provide 'make' methods, add - * JS_DECLARE_MAKE_METHODS (see js::MallocProvider for an example). This - * method is functionally the same as JS_DECLARE_NEW_METHODS: it just declares - * methods that return mozilla::UniquePtr instances that will singly-manage - * ownership of the created object. - * - * Note: Do not add a ; at the end of a use of JS_DECLARE_MAKE_METHODS, - * or the build will break. - */ -#define JS_DECLARE_MAKE_METHODS(MAKENAME, NEWNAME, QUALIFIERS)\ - template \ - QUALIFIERS mozilla::UniquePtr> \ - MAKENAME(Args&&... args) MOZ_HEAP_ALLOCATOR { \ - T* ptr = NEWNAME(mozilla::Forward(args)...); \ - return mozilla::UniquePtr>(ptr); \ - } - -JS_DECLARE_NEW_METHODS(js_new, js_malloc, static MOZ_ALWAYS_INLINE) - -namespace js { - -/* - * Calculate the number of bytes needed to allocate |numElems| contiguous - * instances of type |T|. Return false if the calculation overflowed. - */ -template -MOZ_MUST_USE inline bool -CalculateAllocSize(size_t numElems, size_t* bytesOut) -{ - *bytesOut = numElems * sizeof(T); - return (numElems & mozilla::tl::MulOverflowMask::value) == 0; -} - -/* - * Calculate the number of bytes needed to allocate a single instance of type - * |T| followed by |numExtra| contiguous instances of type |Extra|. Return - * false if the calculation overflowed. - */ -template -MOZ_MUST_USE inline bool -CalculateAllocSizeWithExtra(size_t numExtra, size_t* bytesOut) -{ - *bytesOut = sizeof(T) + numExtra * sizeof(Extra); - return (numExtra & mozilla::tl::MulOverflowMask::value) == 0 && - *bytesOut >= sizeof(T); -} - -} /* namespace js */ - -template -static MOZ_ALWAYS_INLINE void -js_delete(const T* p) -{ - if (p) { - p->~T(); - js_free(const_cast(p)); - } -} - -template -static MOZ_ALWAYS_INLINE void -js_delete_poison(const T* p) -{ - if (p) { - p->~T(); - memset(const_cast(p), 0x3B, sizeof(T)); - js_free(const_cast(p)); - } -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_malloc() -{ - return static_cast(js_malloc(sizeof(T))); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_calloc() -{ - return static_cast(js_calloc(sizeof(T))); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_malloc(size_t numElems) -{ - size_t bytes; - if (MOZ_UNLIKELY(!js::CalculateAllocSize(numElems, &bytes))) - return nullptr; - return static_cast(js_malloc(bytes)); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_calloc(size_t numElems) -{ - size_t bytes; - if (MOZ_UNLIKELY(!js::CalculateAllocSize(numElems, &bytes))) - return nullptr; - return static_cast(js_calloc(bytes)); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_realloc(T* prior, size_t oldSize, size_t newSize) -{ - MOZ_ASSERT(!(oldSize & mozilla::tl::MulOverflowMask::value)); - size_t bytes; - if (MOZ_UNLIKELY(!js::CalculateAllocSize(newSize, &bytes))) - return nullptr; - return static_cast(js_realloc(prior, bytes)); -} - -namespace js { - -template -struct ScopedFreePtrTraits -{ - typedef T* type; - static T* empty() { return nullptr; } - static void release(T* ptr) { js_free(ptr); } -}; -SCOPED_TEMPLATE(ScopedJSFreePtr, ScopedFreePtrTraits) - -template -struct ScopedDeletePtrTraits : public ScopedFreePtrTraits -{ - static void release(T* ptr) { js_delete(ptr); } -}; -SCOPED_TEMPLATE(ScopedJSDeletePtr, ScopedDeletePtrTraits) - -template -struct ScopedReleasePtrTraits : public ScopedFreePtrTraits -{ - static void release(T* ptr) { if (ptr) ptr->release(); } -}; -SCOPED_TEMPLATE(ScopedReleasePtr, ScopedReleasePtrTraits) - -} /* namespace js */ - -namespace JS { - -template -struct DeletePolicy -{ - constexpr DeletePolicy() {} - - template - MOZ_IMPLICIT DeletePolicy(DeletePolicy other, - typename mozilla::EnableIf::value, - int>::Type dummy = 0) - {} - - void operator()(const T* ptr) { - js_delete(const_cast(ptr)); - } -}; - -struct FreePolicy -{ - void operator()(const void* ptr) { - js_free(const_cast(ptr)); - } -}; - -typedef mozilla::UniquePtr UniqueChars; -typedef mozilla::UniquePtr UniqueTwoByteChars; - -} // namespace JS - -namespace js { - -/* Integral types for all hash functions. */ -typedef uint32_t HashNumber; -const unsigned HashNumberSizeBits = 32; - -namespace detail { - -/* - * Given a raw hash code, h, return a number that can be used to select a hash - * bucket. - * - * This function aims to produce as uniform an output distribution as possible, - * especially in the most significant (leftmost) bits, even though the input - * distribution may be highly nonrandom, given the constraints that this must - * be deterministic and quick to compute. - * - * Since the leftmost bits of the result are best, the hash bucket index is - * computed by doing ScrambleHashCode(h) / (2^32/N) or the equivalent - * right-shift, not ScrambleHashCode(h) % N or the equivalent bit-mask. - * - * FIXME: OrderedHashTable uses a bit-mask; see bug 775896. - */ -inline HashNumber -ScrambleHashCode(HashNumber h) -{ - /* - * Simply returning h would not cause any hash tables to produce wrong - * answers. But it can produce pathologically bad performance: The caller - * right-shifts the result, keeping only the highest bits. The high bits of - * hash codes are very often completely entropy-free. (So are the lowest - * bits.) - * - * So we use Fibonacci hashing, as described in Knuth, The Art of Computer - * Programming, 6.4. This mixes all the bits of the input hash code h. - * - * The value of goldenRatio is taken from the hex - * expansion of the golden ratio, which starts 1.9E3779B9.... - * This value is especially good if values with consecutive hash codes - * are stored in a hash table; see Knuth for details. - */ - static const HashNumber goldenRatio = 0x9E3779B9U; - return h * goldenRatio; -} - -} /* namespace detail */ - -} /* namespace js */ - -/* sixgill annotation defines */ -#ifndef HAVE_STATIC_ANNOTATIONS -# define HAVE_STATIC_ANNOTATIONS -# ifdef XGILL_PLUGIN -# define STATIC_PRECONDITION(COND) __attribute__((precondition(#COND))) -# define STATIC_PRECONDITION_ASSUME(COND) __attribute__((precondition_assume(#COND))) -# define STATIC_POSTCONDITION(COND) __attribute__((postcondition(#COND))) -# define STATIC_POSTCONDITION_ASSUME(COND) __attribute__((postcondition_assume(#COND))) -# define STATIC_INVARIANT(COND) __attribute__((invariant(#COND))) -# define STATIC_INVARIANT_ASSUME(COND) __attribute__((invariant_assume(#COND))) -# define STATIC_ASSUME(COND) \ - JS_BEGIN_MACRO \ - __attribute__((assume_static(#COND), unused)) \ - int STATIC_PASTE1(assume_static_, __COUNTER__); \ - JS_END_MACRO -# else /* XGILL_PLUGIN */ -# define STATIC_PRECONDITION(COND) /* nothing */ -# define STATIC_PRECONDITION_ASSUME(COND) /* nothing */ -# define STATIC_POSTCONDITION(COND) /* nothing */ -# define STATIC_POSTCONDITION_ASSUME(COND) /* nothing */ -# define STATIC_INVARIANT(COND) /* nothing */ -# define STATIC_INVARIANT_ASSUME(COND) /* nothing */ -# define STATIC_ASSUME(COND) JS_BEGIN_MACRO /* nothing */ JS_END_MACRO -# endif /* XGILL_PLUGIN */ -# define STATIC_SKIP_INFERENCE STATIC_INVARIANT(skip_inference()) -#endif /* HAVE_STATIC_ANNOTATIONS */ - -#endif /* js_Utility_h */ diff --git a/mac/include/spidermonkey/js/Value.h b/mac/include/spidermonkey/js/Value.h deleted file mode 100644 index 00fdad58..00000000 --- a/mac/include/spidermonkey/js/Value.h +++ /dev/null @@ -1,1509 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JS::Value implementation. */ - -#ifndef js_Value_h -#define js_Value_h - -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/Likely.h" - -#include /* for std::numeric_limits */ - -#include "js-config.h" -#include "jstypes.h" - -#include "js/GCAPI.h" -#include "js/RootingAPI.h" -#include "js/Utility.h" - -namespace JS { class Value; } - -/* JS::Value can store a full int32_t. */ -#define JSVAL_INT_BITS 32 -#define JSVAL_INT_MIN ((int32_t)0x80000000) -#define JSVAL_INT_MAX ((int32_t)0x7fffffff) - -#if defined(JS_PUNBOX64) -# define JSVAL_TAG_SHIFT 47 -#endif - -// Use enums so that printing a JS::Value in the debugger shows nice -// symbolic type tags. - -#if defined(_MSC_VER) -# define JS_ENUM_HEADER(id, type) enum id : type -# define JS_ENUM_FOOTER(id) -#else -# define JS_ENUM_HEADER(id, type) enum id -# define JS_ENUM_FOOTER(id) __attribute__((packed)) -#endif - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueType, uint8_t) -{ - JSVAL_TYPE_DOUBLE = 0x00, - JSVAL_TYPE_INT32 = 0x01, - JSVAL_TYPE_UNDEFINED = 0x02, - JSVAL_TYPE_BOOLEAN = 0x03, - JSVAL_TYPE_MAGIC = 0x04, - JSVAL_TYPE_STRING = 0x05, - JSVAL_TYPE_SYMBOL = 0x06, - JSVAL_TYPE_PRIVATE_GCTHING = 0x07, - JSVAL_TYPE_NULL = 0x08, - JSVAL_TYPE_OBJECT = 0x0c, - - /* These never appear in a jsval; they are only provided as an out-of-band value. */ - JSVAL_TYPE_UNKNOWN = 0x20, - JSVAL_TYPE_MISSING = 0x21 -} JS_ENUM_FOOTER(JSValueType); - -static_assert(sizeof(JSValueType) == 1, - "compiler typed enum support is apparently buggy"); - -#if defined(JS_NUNBOX32) - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueTag, uint32_t) -{ - JSVAL_TAG_CLEAR = 0xFFFFFF80, - JSVAL_TAG_INT32 = JSVAL_TAG_CLEAR | JSVAL_TYPE_INT32, - JSVAL_TAG_UNDEFINED = JSVAL_TAG_CLEAR | JSVAL_TYPE_UNDEFINED, - JSVAL_TAG_STRING = JSVAL_TAG_CLEAR | JSVAL_TYPE_STRING, - JSVAL_TAG_SYMBOL = JSVAL_TAG_CLEAR | JSVAL_TYPE_SYMBOL, - JSVAL_TAG_BOOLEAN = JSVAL_TAG_CLEAR | JSVAL_TYPE_BOOLEAN, - JSVAL_TAG_MAGIC = JSVAL_TAG_CLEAR | JSVAL_TYPE_MAGIC, - JSVAL_TAG_NULL = JSVAL_TAG_CLEAR | JSVAL_TYPE_NULL, - JSVAL_TAG_OBJECT = JSVAL_TAG_CLEAR | JSVAL_TYPE_OBJECT, - JSVAL_TAG_PRIVATE_GCTHING = JSVAL_TAG_CLEAR | JSVAL_TYPE_PRIVATE_GCTHING -} JS_ENUM_FOOTER(JSValueTag); - -static_assert(sizeof(JSValueTag) == sizeof(uint32_t), - "compiler typed enum support is apparently buggy"); - -#elif defined(JS_PUNBOX64) - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueTag, uint32_t) -{ - JSVAL_TAG_MAX_DOUBLE = 0x1FFF0, - JSVAL_TAG_INT32 = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_INT32, - JSVAL_TAG_UNDEFINED = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_UNDEFINED, - JSVAL_TAG_STRING = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_STRING, - JSVAL_TAG_SYMBOL = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_SYMBOL, - JSVAL_TAG_BOOLEAN = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_BOOLEAN, - JSVAL_TAG_MAGIC = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_MAGIC, - JSVAL_TAG_NULL = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_NULL, - JSVAL_TAG_OBJECT = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_OBJECT, - JSVAL_TAG_PRIVATE_GCTHING = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_PRIVATE_GCTHING -} JS_ENUM_FOOTER(JSValueTag); - -static_assert(sizeof(JSValueTag) == sizeof(uint32_t), - "compiler typed enum support is apparently buggy"); - -JS_ENUM_HEADER(JSValueShiftedTag, uint64_t) -{ - JSVAL_SHIFTED_TAG_MAX_DOUBLE = ((((uint64_t)JSVAL_TAG_MAX_DOUBLE) << JSVAL_TAG_SHIFT) | 0xFFFFFFFF), - JSVAL_SHIFTED_TAG_INT32 = (((uint64_t)JSVAL_TAG_INT32) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_UNDEFINED = (((uint64_t)JSVAL_TAG_UNDEFINED) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_STRING = (((uint64_t)JSVAL_TAG_STRING) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_SYMBOL = (((uint64_t)JSVAL_TAG_SYMBOL) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_BOOLEAN = (((uint64_t)JSVAL_TAG_BOOLEAN) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_MAGIC = (((uint64_t)JSVAL_TAG_MAGIC) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_NULL = (((uint64_t)JSVAL_TAG_NULL) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_OBJECT = (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_PRIVATE_GCTHING = (((uint64_t)JSVAL_TAG_PRIVATE_GCTHING) << JSVAL_TAG_SHIFT) -} JS_ENUM_FOOTER(JSValueShiftedTag); - -static_assert(sizeof(JSValueShiftedTag) == sizeof(uint64_t), - "compiler typed enum support is apparently buggy"); - -#endif - -/* - * All our supported compilers implement C++11 |enum Foo : T| syntax, so don't - * expose these macros. (This macro exists *only* because gcc bug 51242 - * makes bit-fields of - * typed enums trigger a warning that can't be turned off. Don't expose it - * beyond this file!) - */ -#undef JS_ENUM_HEADER -#undef JS_ENUM_FOOTER - -#if defined(JS_NUNBOX32) - -#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_CLEAR | (type))) - -#define JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET JSVAL_TAG_NULL -#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT -#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32 -#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING - -#elif defined(JS_PUNBOX64) - -#define JSVAL_PAYLOAD_MASK 0x00007FFFFFFFFFFFLL -#define JSVAL_TAG_MASK 0xFFFF800000000000LL -#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_MAX_DOUBLE | (type))) -#define JSVAL_TYPE_TO_SHIFTED_TAG(type) (((uint64_t)JSVAL_TYPE_TO_TAG(type)) << JSVAL_TAG_SHIFT) - -#define JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET JSVAL_TAG_NULL -#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT -#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32 -#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING - -#define JSVAL_LOWER_INCL_SHIFTED_TAG_OF_OBJ_OR_NULL_SET JSVAL_SHIFTED_TAG_NULL -#define JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET JSVAL_SHIFTED_TAG_OBJECT -#define JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET JSVAL_SHIFTED_TAG_UNDEFINED -#define JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET JSVAL_SHIFTED_TAG_STRING - -#endif /* JS_PUNBOX64 */ - -typedef enum JSWhyMagic -{ - /** a hole in a native object's elements */ - JS_ELEMENTS_HOLE, - - /** there is not a pending iterator value */ - JS_NO_ITER_VALUE, - - /** exception value thrown when closing a generator */ - JS_GENERATOR_CLOSING, - - /** compiler sentinel value */ - JS_NO_CONSTANT, - - /** used in debug builds to catch tracing errors */ - JS_THIS_POISON, - - /** used in debug builds to catch tracing errors */ - JS_ARG_POISON, - - /** an empty subnode in the AST serializer */ - JS_SERIALIZE_NO_NODE, - - /** lazy arguments value on the stack */ - JS_LAZY_ARGUMENTS, - - /** optimized-away 'arguments' value */ - JS_OPTIMIZED_ARGUMENTS, - - /** magic value passed to natives to indicate construction */ - JS_IS_CONSTRUCTING, - - /** value of static block object slot */ - JS_BLOCK_NEEDS_CLONE, - - /** see class js::HashableValue */ - JS_HASH_KEY_EMPTY, - - /** error while running Ion code */ - JS_ION_ERROR, - - /** missing recover instruction result */ - JS_ION_BAILOUT, - - /** optimized out slot */ - JS_OPTIMIZED_OUT, - - /** uninitialized lexical bindings that produce ReferenceError on touch. */ - JS_UNINITIALIZED_LEXICAL, - - /** for local use */ - JS_GENERIC_MAGIC, - - JS_WHY_MAGIC_COUNT -} JSWhyMagic; - -namespace JS { - -static inline constexpr JS::Value UndefinedValue(); -static inline JS::Value PoisonedObjectValue(JSObject* obj); - -namespace detail { - -constexpr int CanonicalizedNaNSignBit = 0; -constexpr uint64_t CanonicalizedNaNSignificand = 0x8000000000000ULL; - -constexpr uint64_t CanonicalizedNaNBits = - mozilla::SpecificNaNBits::value; - -} // namespace detail - -/** - * Returns a generic quiet NaN value, with all payload bits set to zero. - * - * Among other properties, this NaN's bit pattern conforms to JS::Value's - * bit pattern restrictions. - */ -static MOZ_ALWAYS_INLINE double -GenericNaN() -{ - return mozilla::SpecificNaN(detail::CanonicalizedNaNSignBit, - detail::CanonicalizedNaNSignificand); -} - -/* MSVC with PGO miscompiles this function. */ -#if defined(_MSC_VER) -# pragma optimize("g", off) -#endif -static inline double -CanonicalizeNaN(double d) -{ - if (MOZ_UNLIKELY(mozilla::IsNaN(d))) - return GenericNaN(); - return d; -} -#if defined(_MSC_VER) -# pragma optimize("", on) -#endif - -/** - * JS::Value is the interface for a single JavaScript Engine value. A few - * general notes on JS::Value: - * - * - JS::Value has setX() and isX() members for X in - * - * { Int32, Double, String, Symbol, Boolean, Undefined, Null, Object, Magic } - * - * JS::Value also contains toX() for each of the non-singleton types. - * - * - Magic is a singleton type whose payload contains either a JSWhyMagic "reason" for - * the magic value or a uint32_t value. By providing JSWhyMagic values when - * creating and checking for magic values, it is possible to assert, at - * runtime, that only magic values with the expected reason flow through a - * particular value. For example, if cx->exception has a magic value, the - * reason must be JS_GENERATOR_CLOSING. - * - * - The JS::Value operations are preferred. The JSVAL_* operations remain for - * compatibility; they may be removed at some point. These operations mostly - * provide similar functionality. But there are a few key differences. One - * is that JS::Value gives null a separate type. - * Also, to help prevent mistakenly boxing a nullable JSObject* as an object, - * Value::setObject takes a JSObject&. (Conversely, Value::toObject returns a - * JSObject&.) A convenience member Value::setObjectOrNull is provided. - * - * - JSVAL_VOID is the same as the singleton value of the Undefined type. - * - * - Note that JS::Value is 8 bytes on 32 and 64-bit architectures. Thus, on - * 32-bit user code should avoid copying jsval/JS::Value as much as possible, - * preferring to pass by const Value&. - */ -class MOZ_NON_PARAM alignas(8) Value -{ - public: -#if defined(JS_NUNBOX32) - using PayloadType = uint32_t; -#elif defined(JS_PUNBOX64) - using PayloadType = uint64_t; -#endif - - /* - * N.B. the default constructor leaves Value unitialized. Adding a default - * constructor prevents Value from being stored in a union. - */ - Value() = default; - Value(const Value& v) = default; - - /** - * Returns false if creating a NumberValue containing the given type would - * be lossy, true otherwise. - */ - template - static bool isNumberRepresentable(const T t) { - return T(double(t)) == t; - } - - /*** Mutators ***/ - - void setNull() { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_NULL, 0); - } - - void setUndefined() { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_UNDEFINED, 0); - } - - void setInt32(int32_t i) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_INT32, uint32_t(i)); - } - - int32_t& getInt32Ref() { - MOZ_ASSERT(isInt32()); - return data.s.payload.i32; - } - - void setDouble(double d) { - // Don't assign to data.asDouble to fix a miscompilation with - // GCC 5.2.1 and 5.3.1. See bug 1312488. - data = layout(d); - MOZ_ASSERT(isDouble()); - } - - void setNaN() { - setDouble(GenericNaN()); - } - - double& getDoubleRef() { - MOZ_ASSERT(isDouble()); - return data.asDouble; - } - - void setString(JSString* str) { - MOZ_ASSERT(uintptr_t(str) > 0x1000); - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_STRING, PayloadType(str)); - } - - void setSymbol(JS::Symbol* sym) { - MOZ_ASSERT(uintptr_t(sym) > 0x1000); - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_SYMBOL, PayloadType(sym)); - } - - void setObject(JSObject& obj) { - MOZ_ASSERT(uintptr_t(&obj) > 0x1000 || uintptr_t(&obj) == 0x48); -#if defined(JS_PUNBOX64) - // VisualStudio cannot contain parenthesized C++ style cast and shift - // inside decltype in template parameter: - // AssertionConditionType> 1))> - // It throws syntax error. - MOZ_ASSERT((((uintptr_t)&obj) >> JSVAL_TAG_SHIFT) == 0); -#endif - setObjectNoCheck(&obj); - } - - private: - void setObjectNoCheck(JSObject* obj) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_OBJECT, PayloadType(obj)); - } - - friend inline Value PoisonedObjectValue(JSObject* obj); - - public: - void setBoolean(bool b) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_BOOLEAN, uint32_t(b)); - } - - void setMagic(JSWhyMagic why) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_MAGIC, uint32_t(why)); - } - - void setMagicUint32(uint32_t payload) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_MAGIC, payload); - } - - bool setNumber(uint32_t ui) { - if (ui > JSVAL_INT_MAX) { - setDouble((double)ui); - return false; - } else { - setInt32((int32_t)ui); - return true; - } - } - - bool setNumber(double d) { - int32_t i; - if (mozilla::NumberIsInt32(d, &i)) { - setInt32(i); - return true; - } - - setDouble(d); - return false; - } - - void setObjectOrNull(JSObject* arg) { - if (arg) - setObject(*arg); - else - setNull(); - } - - void swap(Value& rhs) { - uint64_t tmp = rhs.data.asBits; - rhs.data.asBits = data.asBits; - data.asBits = tmp; - } - - private: - JSValueTag toTag() const { -#if defined(JS_NUNBOX32) - return data.s.tag; -#elif defined(JS_PUNBOX64) - return JSValueTag(data.asBits >> JSVAL_TAG_SHIFT); -#endif - } - - public: - /*** JIT-only interfaces to interact with and create raw Values ***/ -#if defined(JS_NUNBOX32) - PayloadType toNunboxPayload() const { - return data.s.payload.i32; - } - - JSValueTag toNunboxTag() const { - return data.s.tag; - } -#elif defined(JS_PUNBOX64) - const void* bitsAsPunboxPointer() const { - return reinterpret_cast(data.asBits); - } -#endif - - /*** Value type queries ***/ - - /* - * N.B. GCC, in some but not all cases, chooses to emit signed comparison - * of JSValueTag even though its underlying type has been forced to be - * uint32_t. Thus, all comparisons should explicitly cast operands to - * uint32_t. - */ - - bool isUndefined() const { -#if defined(JS_NUNBOX32) - return toTag() == JSVAL_TAG_UNDEFINED; -#elif defined(JS_PUNBOX64) - return data.asBits == JSVAL_SHIFTED_TAG_UNDEFINED; -#endif - } - - bool isNull() const { -#if defined(JS_NUNBOX32) - return toTag() == JSVAL_TAG_NULL; -#elif defined(JS_PUNBOX64) - return data.asBits == JSVAL_SHIFTED_TAG_NULL; -#endif - } - - bool isNullOrUndefined() const { - return isNull() || isUndefined(); - } - - bool isInt32() const { - return toTag() == JSVAL_TAG_INT32; - } - - bool isInt32(int32_t i32) const { - return data.asBits == bitsFromTagAndPayload(JSVAL_TAG_INT32, uint32_t(i32)); - } - - bool isDouble() const { -#if defined(JS_NUNBOX32) - return uint32_t(toTag()) <= uint32_t(JSVAL_TAG_CLEAR); -#elif defined(JS_PUNBOX64) - return (data.asBits | mozilla::DoubleTypeTraits::kSignBit) <= JSVAL_SHIFTED_TAG_MAX_DOUBLE; -#endif - } - - bool isNumber() const { -#if defined(JS_NUNBOX32) - MOZ_ASSERT(toTag() != JSVAL_TAG_CLEAR); - return uint32_t(toTag()) <= uint32_t(JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET); -#elif defined(JS_PUNBOX64) - return data.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET; -#endif - } - - bool isString() const { - return toTag() == JSVAL_TAG_STRING; - } - - bool isSymbol() const { - return toTag() == JSVAL_TAG_SYMBOL; - } - - bool isObject() const { -#if defined(JS_NUNBOX32) - return toTag() == JSVAL_TAG_OBJECT; -#elif defined(JS_PUNBOX64) - MOZ_ASSERT((data.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_TAG_OBJECT); - return data.asBits >= JSVAL_SHIFTED_TAG_OBJECT; -#endif - } - - bool isPrimitive() const { -#if defined(JS_NUNBOX32) - return uint32_t(toTag()) < uint32_t(JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET); -#elif defined(JS_PUNBOX64) - return data.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET; -#endif - } - - bool isObjectOrNull() const { - MOZ_ASSERT(uint32_t(toTag()) <= uint32_t(JSVAL_TAG_OBJECT)); -#if defined(JS_NUNBOX32) - return uint32_t(toTag()) >= uint32_t(JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET); -#elif defined(JS_PUNBOX64) - return data.asBits >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_OBJ_OR_NULL_SET; -#endif - } - - bool isGCThing() const { -#if defined(JS_NUNBOX32) - /* gcc sometimes generates signed < without explicit casts. */ - return uint32_t(toTag()) >= uint32_t(JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET); -#elif defined(JS_PUNBOX64) - return data.asBits >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET; -#endif - } - - bool isBoolean() const { - return toTag() == JSVAL_TAG_BOOLEAN; - } - - bool isTrue() const { - return data.asBits == bitsFromTagAndPayload(JSVAL_TAG_BOOLEAN, uint32_t(true)); - } - - bool isFalse() const { - return data.asBits == bitsFromTagAndPayload(JSVAL_TAG_BOOLEAN, uint32_t(false)); - } - - bool isMagic() const { - return toTag() == JSVAL_TAG_MAGIC; - } - - bool isMagic(JSWhyMagic why) const { - MOZ_ASSERT_IF(isMagic(), data.s.payload.why == why); - return isMagic(); - } - - bool isMarkable() const { - return isGCThing() && !isNull(); - } - - JS::TraceKind traceKind() const { - MOZ_ASSERT(isMarkable()); - static_assert((JSVAL_TAG_STRING & 0x03) == size_t(JS::TraceKind::String), - "Value type tags must correspond with JS::TraceKinds."); - static_assert((JSVAL_TAG_SYMBOL & 0x03) == size_t(JS::TraceKind::Symbol), - "Value type tags must correspond with JS::TraceKinds."); - static_assert((JSVAL_TAG_OBJECT & 0x03) == size_t(JS::TraceKind::Object), - "Value type tags must correspond with JS::TraceKinds."); - if (MOZ_UNLIKELY(isPrivateGCThing())) - return JS::GCThingTraceKind(toGCThing()); - return JS::TraceKind(toTag() & 0x03); - } - - JSWhyMagic whyMagic() const { - MOZ_ASSERT(isMagic()); - return data.s.payload.why; - } - - uint32_t magicUint32() const { - MOZ_ASSERT(isMagic()); - return data.s.payload.u32; - } - - /*** Comparison ***/ - - bool operator==(const Value& rhs) const { - return data.asBits == rhs.data.asBits; - } - - bool operator!=(const Value& rhs) const { - return data.asBits != rhs.data.asBits; - } - - friend inline bool SameType(const Value& lhs, const Value& rhs); - - /*** Extract the value's typed payload ***/ - - int32_t toInt32() const { - MOZ_ASSERT(isInt32()); -#if defined(JS_NUNBOX32) - return data.s.payload.i32; -#elif defined(JS_PUNBOX64) - return int32_t(data.asBits); -#endif - } - - double toDouble() const { - MOZ_ASSERT(isDouble()); - return data.asDouble; - } - - double toNumber() const { - MOZ_ASSERT(isNumber()); - return isDouble() ? toDouble() : double(toInt32()); - } - - JSString* toString() const { - MOZ_ASSERT(isString()); -#if defined(JS_NUNBOX32) - return data.s.payload.str; -#elif defined(JS_PUNBOX64) - return reinterpret_cast(data.asBits & JSVAL_PAYLOAD_MASK); -#endif - } - - JS::Symbol* toSymbol() const { - MOZ_ASSERT(isSymbol()); -#if defined(JS_NUNBOX32) - return data.s.payload.sym; -#elif defined(JS_PUNBOX64) - return reinterpret_cast(data.asBits & JSVAL_PAYLOAD_MASK); -#endif - } - - JSObject& toObject() const { - MOZ_ASSERT(isObject()); -#if defined(JS_NUNBOX32) - return *data.s.payload.obj; -#elif defined(JS_PUNBOX64) - return *toObjectOrNull(); -#endif - } - - JSObject* toObjectOrNull() const { - MOZ_ASSERT(isObjectOrNull()); -#if defined(JS_NUNBOX32) - return data.s.payload.obj; -#elif defined(JS_PUNBOX64) - uint64_t ptrBits = data.asBits & JSVAL_PAYLOAD_MASK; - MOZ_ASSERT((ptrBits & 0x7) == 0); - return reinterpret_cast(ptrBits); -#endif - } - - js::gc::Cell* toGCThing() const { - MOZ_ASSERT(isGCThing()); -#if defined(JS_NUNBOX32) - return data.s.payload.cell; -#elif defined(JS_PUNBOX64) - uint64_t ptrBits = data.asBits & JSVAL_PAYLOAD_MASK; - MOZ_ASSERT((ptrBits & 0x7) == 0); - return reinterpret_cast(ptrBits); -#endif - } - - js::gc::Cell* toMarkablePointer() const { - MOZ_ASSERT(isMarkable()); - return toGCThing(); - } - - GCCellPtr toGCCellPtr() const { - return GCCellPtr(toGCThing(), traceKind()); - } - - bool toBoolean() const { - MOZ_ASSERT(isBoolean()); -#if defined(JS_NUNBOX32) - return bool(data.s.payload.boo); -#elif defined(JS_PUNBOX64) - return bool(data.asBits & JSVAL_PAYLOAD_MASK); -#endif - } - - uint32_t payloadAsRawUint32() const { - MOZ_ASSERT(!isDouble()); - return data.s.payload.u32; - } - - uint64_t asRawBits() const { - return data.asBits; - } - - JSValueType extractNonDoubleType() const { - uint32_t type = toTag() & 0xF; - MOZ_ASSERT(type > JSVAL_TYPE_DOUBLE); - return JSValueType(type); - } - - /* - * Private API - * - * Private setters/getters allow the caller to read/write arbitrary types - * that fit in the 64-bit payload. It is the caller's responsibility, after - * storing to a value with setPrivateX to read only using getPrivateX. - * Privates values are given a type which ensures they are not marked. - */ - - void setPrivate(void* ptr) { - MOZ_ASSERT((uintptr_t(ptr) & 1) == 0); -#if defined(JS_NUNBOX32) - data.s.tag = JSValueTag(0); - data.s.payload.ptr = ptr; -#elif defined(JS_PUNBOX64) - data.asBits = uintptr_t(ptr) >> 1; -#endif - MOZ_ASSERT(isDouble()); - } - - void* toPrivate() const { - MOZ_ASSERT(isDouble()); -#if defined(JS_NUNBOX32) - return data.s.payload.ptr; -#elif defined(JS_PUNBOX64) - MOZ_ASSERT((data.asBits & 0x8000000000000000ULL) == 0); - return reinterpret_cast(data.asBits << 1); -#endif - } - - void setPrivateUint32(uint32_t ui) { - MOZ_ASSERT(uint32_t(int32_t(ui)) == ui); - setInt32(int32_t(ui)); - } - - uint32_t toPrivateUint32() const { - return uint32_t(toInt32()); - } - - /* - * Private GC Thing API - * - * Non-JSObject, JSString, and JS::Symbol cells may be put into the 64-bit - * payload as private GC things. Such Values are considered isMarkable() - * and isGCThing(), and as such, automatically marked. Their traceKind() - * is gotten via their cells. - */ - - void setPrivateGCThing(js::gc::Cell* cell) { - MOZ_ASSERT(JS::GCThingTraceKind(cell) != JS::TraceKind::String, - "Private GC thing Values must not be strings. Make a StringValue instead."); - MOZ_ASSERT(JS::GCThingTraceKind(cell) != JS::TraceKind::Symbol, - "Private GC thing Values must not be symbols. Make a SymbolValue instead."); - MOZ_ASSERT(JS::GCThingTraceKind(cell) != JS::TraceKind::Object, - "Private GC thing Values must not be objects. Make an ObjectValue instead."); - - MOZ_ASSERT(uintptr_t(cell) > 0x1000); -#if defined(JS_PUNBOX64) - // VisualStudio cannot contain parenthesized C++ style cast and shift - // inside decltype in template parameter: - // AssertionConditionType> 1))> - // It throws syntax error. - MOZ_ASSERT((((uintptr_t)cell) >> JSVAL_TAG_SHIFT) == 0); -#endif - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_PRIVATE_GCTHING, PayloadType(cell)); - } - - bool isPrivateGCThing() const { - return toTag() == JSVAL_TAG_PRIVATE_GCTHING; - } - - const size_t* payloadWord() const { -#if defined(JS_NUNBOX32) - return &data.s.payload.word; -#elif defined(JS_PUNBOX64) - return &data.asWord; -#endif - } - - const uintptr_t* payloadUIntPtr() const { -#if defined(JS_NUNBOX32) - return &data.s.payload.uintptr; -#elif defined(JS_PUNBOX64) - return &data.asUIntPtr; -#endif - } - -#if !defined(_MSC_VER) && !defined(__sparc) - // Value must be POD so that MSVC will pass it by value and not in memory - // (bug 689101); the same is true for SPARC as well (bug 737344). More - // precisely, we don't want Value return values compiled as out params. - private: -#endif - -#if MOZ_LITTLE_ENDIAN -# if defined(JS_NUNBOX32) - union layout { - uint64_t asBits; - struct { - union { - int32_t i32; - uint32_t u32; - uint32_t boo; // Don't use |bool| -- it must be four bytes. - JSString* str; - JS::Symbol* sym; - JSObject* obj; - js::gc::Cell* cell; - void* ptr; - JSWhyMagic why; - size_t word; - uintptr_t uintptr; - } payload; - JSValueTag tag; - } s; - double asDouble; - void* asPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# elif defined(JS_PUNBOX64) - union layout { - uint64_t asBits; -#if !defined(_WIN64) - /* MSVC does not pack these correctly :-( */ - struct { - uint64_t payload47 : 47; - JSValueTag tag : 17; - } debugView; -#endif - struct { - union { - int32_t i32; - uint32_t u32; - JSWhyMagic why; - } payload; - } s; - double asDouble; - void* asPtr; - size_t asWord; - uintptr_t asUIntPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# endif /* JS_PUNBOX64 */ -#else /* MOZ_LITTLE_ENDIAN */ -# if defined(JS_NUNBOX32) - union layout { - uint64_t asBits; - struct { - JSValueTag tag; - union { - int32_t i32; - uint32_t u32; - uint32_t boo; // Don't use |bool| -- it must be four bytes. - JSString* str; - JS::Symbol* sym; - JSObject* obj; - js::gc::Cell* cell; - void* ptr; - JSWhyMagic why; - size_t word; - uintptr_t uintptr; - } payload; - } s; - double asDouble; - void* asPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# elif defined(JS_PUNBOX64) - union layout { - uint64_t asBits; - struct { - JSValueTag tag : 17; - uint64_t payload47 : 47; - } debugView; - struct { - uint32_t padding; - union { - int32_t i32; - uint32_t u32; - JSWhyMagic why; - } payload; - } s; - double asDouble; - void* asPtr; - size_t asWord; - uintptr_t asUIntPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# endif /* JS_PUNBOX64 */ -#endif /* MOZ_LITTLE_ENDIAN */ - - private: - explicit constexpr Value(uint64_t asBits) : data(asBits) {} - explicit constexpr Value(double d) : data(d) {} - - void staticAssertions() { - JS_STATIC_ASSERT(sizeof(JSValueType) == 1); - JS_STATIC_ASSERT(sizeof(JSValueTag) == 4); - JS_STATIC_ASSERT(sizeof(JSWhyMagic) <= 4); - JS_STATIC_ASSERT(sizeof(Value) == 8); - } - - friend constexpr Value JS::UndefinedValue(); - - public: - static constexpr uint64_t - bitsFromTagAndPayload(JSValueTag tag, PayloadType payload) - { -#if defined(JS_NUNBOX32) - return (uint64_t(uint32_t(tag)) << 32) | payload; -#elif defined(JS_PUNBOX64) - return (uint64_t(uint32_t(tag)) << JSVAL_TAG_SHIFT) | payload; -#endif - } - - static constexpr Value - fromTagAndPayload(JSValueTag tag, PayloadType payload) - { - return fromRawBits(bitsFromTagAndPayload(tag, payload)); - } - - static constexpr Value - fromRawBits(uint64_t asBits) { - return Value(asBits); - } - - static constexpr Value - fromInt32(int32_t i) { - return fromTagAndPayload(JSVAL_TAG_INT32, uint32_t(i)); - } - - static constexpr Value - fromDouble(double d) { - return Value(d); - } -} JS_HAZ_GC_POINTER; - -static_assert(sizeof(Value) == 8, "Value size must leave three tag bits, be a binary power, and is ubiquitously depended upon everywhere"); - -inline bool -IsOptimizedPlaceholderMagicValue(const Value& v) -{ - if (v.isMagic()) { - MOZ_ASSERT(v.whyMagic() == JS_OPTIMIZED_ARGUMENTS || v.whyMagic() == JS_OPTIMIZED_OUT); - return true; - } - return false; -} - -static MOZ_ALWAYS_INLINE void -ExposeValueToActiveJS(const Value& v) -{ - if (v.isMarkable()) - js::gc::ExposeGCThingToActiveJS(GCCellPtr(v)); -} - -/************************************************************************/ - -static inline Value -NullValue() -{ - Value v; - v.setNull(); - return v; -} - -static inline constexpr Value -UndefinedValue() -{ - return Value::fromTagAndPayload(JSVAL_TAG_UNDEFINED, 0); -} - -static inline constexpr Value -Int32Value(int32_t i32) -{ - return Value::fromInt32(i32); -} - -static inline Value -DoubleValue(double dbl) -{ - Value v; - v.setDouble(dbl); - return v; -} - -static inline Value -CanonicalizedDoubleValue(double d) -{ - return MOZ_UNLIKELY(mozilla::IsNaN(d)) - ? Value::fromRawBits(detail::CanonicalizedNaNBits) - : Value::fromDouble(d); -} - -static inline bool -IsCanonicalized(double d) -{ - if (mozilla::IsInfinite(d) || mozilla::IsFinite(d)) - return true; - - uint64_t bits; - mozilla::BitwiseCast(d, &bits); - return (bits & ~mozilla::DoubleTypeTraits::kSignBit) == detail::CanonicalizedNaNBits; -} - -static inline Value -DoubleNaNValue() -{ - Value v; - v.setNaN(); - return v; -} - -static inline Value -Float32Value(float f) -{ - Value v; - v.setDouble(f); - return v; -} - -static inline Value -StringValue(JSString* str) -{ - Value v; - v.setString(str); - return v; -} - -static inline Value -SymbolValue(JS::Symbol* sym) -{ - Value v; - v.setSymbol(sym); - return v; -} - -static inline Value -BooleanValue(bool boo) -{ - Value v; - v.setBoolean(boo); - return v; -} - -static inline Value -TrueValue() -{ - Value v; - v.setBoolean(true); - return v; -} - -static inline Value -FalseValue() -{ - Value v; - v.setBoolean(false); - return v; -} - -static inline Value -ObjectValue(JSObject& obj) -{ - Value v; - v.setObject(obj); - return v; -} - -static inline Value -ObjectValueCrashOnTouch() -{ - Value v; - v.setObject(*reinterpret_cast(0x48)); - return v; -} - -static inline Value -MagicValue(JSWhyMagic why) -{ - Value v; - v.setMagic(why); - return v; -} - -static inline Value -MagicValueUint32(uint32_t payload) -{ - Value v; - v.setMagicUint32(payload); - return v; -} - -static inline Value -NumberValue(float f) -{ - Value v; - v.setNumber(f); - return v; -} - -static inline Value -NumberValue(double dbl) -{ - Value v; - v.setNumber(dbl); - return v; -} - -static inline Value -NumberValue(int8_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(uint8_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(int16_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(uint16_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(int32_t i) -{ - return Int32Value(i); -} - -static inline constexpr Value -NumberValue(uint32_t i) -{ - return i <= JSVAL_INT_MAX - ? Int32Value(int32_t(i)) - : Value::fromDouble(double(i)); -} - -namespace detail { - -template -class MakeNumberValue -{ - public: - template - static inline Value create(const T t) - { - Value v; - if (JSVAL_INT_MIN <= t && t <= JSVAL_INT_MAX) - v.setInt32(int32_t(t)); - else - v.setDouble(double(t)); - return v; - } -}; - -template <> -class MakeNumberValue -{ - public: - template - static inline Value create(const T t) - { - Value v; - if (t <= JSVAL_INT_MAX) - v.setInt32(int32_t(t)); - else - v.setDouble(double(t)); - return v; - } -}; - -} // namespace detail - -template -static inline Value -NumberValue(const T t) -{ - MOZ_ASSERT(Value::isNumberRepresentable(t), "value creation would be lossy"); - return detail::MakeNumberValue::is_signed>::create(t); -} - -static inline Value -ObjectOrNullValue(JSObject* obj) -{ - Value v; - v.setObjectOrNull(obj); - return v; -} - -static inline Value -PrivateValue(void* ptr) -{ - Value v; - v.setPrivate(ptr); - return v; -} - -static inline Value -PrivateUint32Value(uint32_t ui) -{ - Value v; - v.setPrivateUint32(ui); - return v; -} - -static inline Value -PrivateGCThingValue(js::gc::Cell* cell) -{ - Value v; - v.setPrivateGCThing(cell); - return v; -} - -static inline Value -PoisonedObjectValue(JSObject* obj) -{ - Value v; - v.setObjectNoCheck(obj); - return v; -} - -inline bool -SameType(const Value& lhs, const Value& rhs) -{ -#if defined(JS_NUNBOX32) - JSValueTag ltag = lhs.toTag(), rtag = rhs.toTag(); - return ltag == rtag || (ltag < JSVAL_TAG_CLEAR && rtag < JSVAL_TAG_CLEAR); -#elif defined(JS_PUNBOX64) - return (lhs.isDouble() && rhs.isDouble()) || - (((lhs.data.asBits ^ rhs.data.asBits) & 0xFFFF800000000000ULL) == 0); -#endif -} - -} // namespace JS - -/************************************************************************/ - -namespace JS { -JS_PUBLIC_API(void) HeapValuePostBarrier(Value* valuep, const Value& prev, const Value& next); - -template <> -struct GCPolicy -{ - static Value initial() { return UndefinedValue(); } - static void trace(JSTracer* trc, Value* v, const char* name) { - js::UnsafeTraceManuallyBarrieredEdge(trc, v, name); - } - static bool isTenured(const Value& thing) { - return !thing.isGCThing() || !IsInsideNursery(thing.toGCThing()); - } -}; - -} // namespace JS - -namespace js { - -template <> -struct BarrierMethods -{ - static gc::Cell* asGCThingOrNull(const JS::Value& v) { - return v.isMarkable() ? v.toGCThing() : nullptr; - } - static void postBarrier(JS::Value* v, const JS::Value& prev, const JS::Value& next) { - JS::HeapValuePostBarrier(v, prev, next); - } - static void exposeToJS(const JS::Value& v) { - JS::ExposeValueToActiveJS(v); - } -}; - -template class MutableValueOperations; - -/** - * A class designed for CRTP use in implementing the non-mutating parts of the - * Value interface in Value-like classes. Outer must be a class inheriting - * ValueOperations with a visible get() method returning a const - * reference to the Value abstracted by Outer. - */ -template -class ValueOperations -{ - friend class MutableValueOperations; - - const JS::Value& value() const { return static_cast(this)->get(); } - - public: - bool isUndefined() const { return value().isUndefined(); } - bool isNull() const { return value().isNull(); } - bool isBoolean() const { return value().isBoolean(); } - bool isTrue() const { return value().isTrue(); } - bool isFalse() const { return value().isFalse(); } - bool isNumber() const { return value().isNumber(); } - bool isInt32() const { return value().isInt32(); } - bool isInt32(int32_t i32) const { return value().isInt32(i32); } - bool isDouble() const { return value().isDouble(); } - bool isString() const { return value().isString(); } - bool isSymbol() const { return value().isSymbol(); } - bool isObject() const { return value().isObject(); } - bool isMagic() const { return value().isMagic(); } - bool isMagic(JSWhyMagic why) const { return value().isMagic(why); } - bool isMarkable() const { return value().isMarkable(); } - bool isPrimitive() const { return value().isPrimitive(); } - bool isGCThing() const { return value().isGCThing(); } - - bool isNullOrUndefined() const { return value().isNullOrUndefined(); } - bool isObjectOrNull() const { return value().isObjectOrNull(); } - - bool toBoolean() const { return value().toBoolean(); } - double toNumber() const { return value().toNumber(); } - int32_t toInt32() const { return value().toInt32(); } - double toDouble() const { return value().toDouble(); } - JSString* toString() const { return value().toString(); } - JS::Symbol* toSymbol() const { return value().toSymbol(); } - JSObject& toObject() const { return value().toObject(); } - JSObject* toObjectOrNull() const { return value().toObjectOrNull(); } - gc::Cell* toGCThing() const { return value().toGCThing(); } - JS::TraceKind traceKind() const { return value().traceKind(); } - void* toPrivate() const { return value().toPrivate(); } - uint32_t toPrivateUint32() const { return value().toPrivateUint32(); } - - uint64_t asRawBits() const { return value().asRawBits(); } - JSValueType extractNonDoubleType() const { return value().extractNonDoubleType(); } - - JSWhyMagic whyMagic() const { return value().whyMagic(); } - uint32_t magicUint32() const { return value().magicUint32(); } -}; - -/** - * A class designed for CRTP use in implementing all the mutating parts of the - * Value interface in Value-like classes. Outer must be a class inheriting - * MutableValueOperations with visible get() methods returning const and - * non-const references to the Value abstracted by Outer. - */ -template -class MutableValueOperations : public ValueOperations -{ - JS::Value& value() { return static_cast(this)->get(); } - - public: - void setNull() { value().setNull(); } - void setUndefined() { value().setUndefined(); } - void setInt32(int32_t i) { value().setInt32(i); } - void setDouble(double d) { value().setDouble(d); } - void setNaN() { setDouble(JS::GenericNaN()); } - void setBoolean(bool b) { value().setBoolean(b); } - void setMagic(JSWhyMagic why) { value().setMagic(why); } - bool setNumber(uint32_t ui) { return value().setNumber(ui); } - bool setNumber(double d) { return value().setNumber(d); } - void setString(JSString* str) { this->value().setString(str); } - void setSymbol(JS::Symbol* sym) { this->value().setSymbol(sym); } - void setObject(JSObject& obj) { this->value().setObject(obj); } - void setObjectOrNull(JSObject* arg) { this->value().setObjectOrNull(arg); } - void setPrivate(void* ptr) { this->value().setPrivate(ptr); } - void setPrivateUint32(uint32_t ui) { this->value().setPrivateUint32(ui); } - void setPrivateGCThing(js::gc::Cell* cell) { this->value().setPrivateGCThing(cell); } -}; - -/* - * Augment the generic Heap interface when T = Value with - * type-querying, value-extracting, and mutating operations. - */ -template <> -class HeapBase : public ValueOperations > -{ - typedef JS::Heap Outer; - - friend class ValueOperations; - - void setBarriered(const JS::Value& v) { - *static_cast*>(this) = v; - } - - public: - void setNull() { setBarriered(JS::NullValue()); } - void setUndefined() { setBarriered(JS::UndefinedValue()); } - void setInt32(int32_t i) { setBarriered(JS::Int32Value(i)); } - void setDouble(double d) { setBarriered(JS::DoubleValue(d)); } - void setNaN() { setDouble(JS::GenericNaN()); } - void setBoolean(bool b) { setBarriered(JS::BooleanValue(b)); } - void setMagic(JSWhyMagic why) { setBarriered(JS::MagicValue(why)); } - void setString(JSString* str) { setBarriered(JS::StringValue(str)); } - void setSymbol(JS::Symbol* sym) { setBarriered(JS::SymbolValue(sym)); } - void setObject(JSObject& obj) { setBarriered(JS::ObjectValue(obj)); } - void setPrivateGCThing(js::gc::Cell* cell) { setBarriered(JS::PrivateGCThingValue(cell)); } - - bool setNumber(uint32_t ui) { - if (ui > JSVAL_INT_MAX) { - setDouble((double)ui); - return false; - } else { - setInt32((int32_t)ui); - return true; - } - } - - bool setNumber(double d) { - int32_t i; - if (mozilla::NumberIsInt32(d, &i)) { - setInt32(i); - return true; - } - - setDouble(d); - return false; - } - - void setObjectOrNull(JSObject* arg) { - if (arg) - setObject(*arg); - else - setNull(); - } -}; - -template <> -class HandleBase : public ValueOperations > -{}; - -template <> -class MutableHandleBase : public MutableValueOperations > -{}; - -template <> -class RootedBase : public MutableValueOperations > -{}; - -template <> -class PersistentRootedBase : public MutableValueOperations> -{}; - -/* - * If the Value is a GC pointer type, convert to that type and call |f| with - * the pointer. If the Value is not a GC type, calls F::defaultValue. - */ -template -auto -DispatchTyped(F f, const JS::Value& val, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - if (val.isString()) - return f(val.toString(), mozilla::Forward(args)...); - if (val.isObject()) - return f(&val.toObject(), mozilla::Forward(args)...); - if (val.isSymbol()) - return f(val.toSymbol(), mozilla::Forward(args)...); - if (MOZ_UNLIKELY(val.isPrivateGCThing())) - return DispatchTyped(f, val.toGCCellPtr(), mozilla::Forward(args)...); - MOZ_ASSERT(!val.isMarkable()); - return F::defaultValue(val); -} - -template struct VoidDefaultAdaptor { static void defaultValue(const S&) {} }; -template struct IdentityDefaultAdaptor { static S defaultValue(const S& v) {return v;} }; -template struct BoolDefaultAdaptor { static bool defaultValue(const S&) { return v; } }; - -} // namespace js - -/************************************************************************/ - -namespace JS { - -extern JS_PUBLIC_DATA(const HandleValue) NullHandleValue; -extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; -extern JS_PUBLIC_DATA(const HandleValue) TrueHandleValue; -extern JS_PUBLIC_DATA(const HandleValue) FalseHandleValue; - -} // namespace JS - -#endif /* js_Value_h */ diff --git a/mac/include/spidermonkey/js/Vector.h b/mac/include/spidermonkey/js/Vector.h deleted file mode 100644 index 6fa63e93..00000000 --- a/mac/include/spidermonkey/js/Vector.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Vector_h -#define js_Vector_h - -#include "mozilla/Vector.h" - -/* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4345) -#endif - -namespace js { - -class TempAllocPolicy; - -namespace detail { - -template -struct TypeIsGCThing : mozilla::FalseType -{}; - -// Uncomment this once we actually can assert it: -//template <> -//struct TypeIsGCThing : mozilla::TrueType -//{}; - -} // namespace detail - -template ::value>::Type - > -using Vector = mozilla::Vector; - -} // namespace js - -#endif /* js_Vector_h */ diff --git a/mac/include/spidermonkey/js/WeakMapPtr.h b/mac/include/spidermonkey/js/WeakMapPtr.h deleted file mode 100644 index 41860551..00000000 --- a/mac/include/spidermonkey/js/WeakMapPtr.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_WeakMapPtr_h -#define js_WeakMapPtr_h - -#include "jspubtd.h" - -#include "js/TypeDecls.h" - -namespace JS { - -// A wrapper around the internal C++ representation of SpiderMonkey WeakMaps, -// usable outside the engine. -// -// The supported template specializations are enumerated in WeakMapPtr.cpp. If -// you want to use this class for a different key/value combination, add it to -// the list and the compiler will generate the relevant machinery. -template -class JS_PUBLIC_API(WeakMapPtr) -{ - public: - WeakMapPtr() : ptr(nullptr) {} - bool init(JSContext* cx); - bool initialized() { return ptr != nullptr; } - void destroy(); - virtual ~WeakMapPtr() { MOZ_ASSERT(!initialized()); } - void trace(JSTracer* tracer); - - V lookup(const K& key); - bool put(JSContext* cx, const K& key, const V& value); - - private: - void* ptr; - - // WeakMapPtr is neither copyable nor assignable. - WeakMapPtr(const WeakMapPtr& wmp) = delete; - WeakMapPtr& operator=(const WeakMapPtr& wmp) = delete; -}; - -} /* namespace JS */ - -#endif /* js_WeakMapPtr_h */ diff --git a/mac/include/spidermonkey/jsalloc.h b/mac/include/spidermonkey/jsalloc.h deleted file mode 100644 index b9ae5190..00000000 --- a/mac/include/spidermonkey/jsalloc.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * JS allocation policies. - * - * The allocators here are for system memory with lifetimes which are not - * managed by the GC. See the comment at the top of vm/MallocProvider.h. - */ - -#ifndef jsalloc_h -#define jsalloc_h - -#include "js/TypeDecls.h" -#include "js/Utility.h" - -namespace js { - -enum class AllocFunction { - Malloc, - Calloc, - Realloc -}; - -struct ContextFriendFields; - -/* Policy for using system memory functions and doing no error reporting. */ -class SystemAllocPolicy -{ - public: - template T* maybe_pod_malloc(size_t numElems) { return js_pod_malloc(numElems); } - template T* maybe_pod_calloc(size_t numElems) { return js_pod_calloc(numElems); } - template T* maybe_pod_realloc(T* p, size_t oldSize, size_t newSize) { - return js_pod_realloc(p, oldSize, newSize); - } - template T* pod_malloc(size_t numElems) { return maybe_pod_malloc(numElems); } - template T* pod_calloc(size_t numElems) { return maybe_pod_calloc(numElems); } - template T* pod_realloc(T* p, size_t oldSize, size_t newSize) { - return maybe_pod_realloc(p, oldSize, newSize); - } - void free_(void* p) { js_free(p); } - void reportAllocOverflow() const {} - bool checkSimulatedOOM() const { - return !js::oom::ShouldFailWithOOM(); - } -}; - -class ExclusiveContext; -void ReportOutOfMemory(ExclusiveContext* cxArg); - -/* - * Allocation policy that calls the system memory functions and reports errors - * to the context. Since the JSContext given on construction is stored for - * the lifetime of the container, this policy may only be used for containers - * whose lifetime is a shorter than the given JSContext. - * - * FIXME bug 647103 - rewrite this in terms of temporary allocation functions, - * not the system ones. - */ -class TempAllocPolicy -{ - ContextFriendFields* const cx_; - - /* - * Non-inline helper to call JSRuntime::onOutOfMemory with minimal - * code bloat. - */ - JS_FRIEND_API(void*) onOutOfMemory(AllocFunction allocFunc, size_t nbytes, - void* reallocPtr = nullptr); - - template - T* onOutOfMemoryTyped(AllocFunction allocFunc, size_t numElems, void* reallocPtr = nullptr) { - size_t bytes; - if (MOZ_UNLIKELY(!CalculateAllocSize(numElems, &bytes))) - return nullptr; - return static_cast(onOutOfMemory(allocFunc, bytes, reallocPtr)); - } - - public: - MOZ_IMPLICIT TempAllocPolicy(JSContext* cx) : cx_((ContextFriendFields*) cx) {} // :( - MOZ_IMPLICIT TempAllocPolicy(ContextFriendFields* cx) : cx_(cx) {} - - template - T* maybe_pod_malloc(size_t numElems) { - return js_pod_malloc(numElems); - } - - template - T* maybe_pod_calloc(size_t numElems) { - return js_pod_calloc(numElems); - } - - template - T* maybe_pod_realloc(T* prior, size_t oldSize, size_t newSize) { - return js_pod_realloc(prior, oldSize, newSize); - } - - template - T* pod_malloc(size_t numElems) { - T* p = maybe_pod_malloc(numElems); - if (MOZ_UNLIKELY(!p)) - p = onOutOfMemoryTyped(AllocFunction::Malloc, numElems); - return p; - } - - template - T* pod_calloc(size_t numElems) { - T* p = maybe_pod_calloc(numElems); - if (MOZ_UNLIKELY(!p)) - p = onOutOfMemoryTyped(AllocFunction::Calloc, numElems); - return p; - } - - template - T* pod_realloc(T* prior, size_t oldSize, size_t newSize) { - T* p2 = maybe_pod_realloc(prior, oldSize, newSize); - if (MOZ_UNLIKELY(!p2)) - p2 = onOutOfMemoryTyped(AllocFunction::Realloc, newSize, prior); - return p2; - } - - void free_(void* p) { - js_free(p); - } - - JS_FRIEND_API(void) reportAllocOverflow() const; - - bool checkSimulatedOOM() const { - if (js::oom::ShouldFailWithOOM()) { - js::ReportOutOfMemory(reinterpret_cast(cx_)); - return false; - } - - return true; - } -}; - -} /* namespace js */ - -#endif /* jsalloc_h */ diff --git a/mac/include/spidermonkey/jsapi.h b/mac/include/spidermonkey/jsapi.h deleted file mode 100644 index 84d639a0..00000000 --- a/mac/include/spidermonkey/jsapi.h +++ /dev/null @@ -1,6630 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JavaScript API. */ - -#ifndef jsapi_h -#define jsapi_h - -#include "mozilla/AlreadyAddRefed.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Range.h" -#include "mozilla/RangedPtr.h" -#include "mozilla/RefCounted.h" -#include "mozilla/RefPtr.h" -#include "mozilla/Variant.h" - -#include -#include -#include -#include - -#include "jsalloc.h" -#include "jspubtd.h" - -#include "js/CallArgs.h" -#include "js/CharacterEncoding.h" -#include "js/Class.h" -#include "js/GCVector.h" -#include "js/HashTable.h" -#include "js/Id.h" -#include "js/Principals.h" -#include "js/Realm.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" -#include "js/Utility.h" -#include "js/Value.h" -#include "js/Vector.h" - -/************************************************************************/ - -namespace JS { - -class TwoByteChars; - -#ifdef JS_DEBUG - -class JS_PUBLIC_API(AutoCheckRequestDepth) -{ - JSContext* cx; - public: - explicit AutoCheckRequestDepth(JSContext* cx); - explicit AutoCheckRequestDepth(js::ContextFriendFields* cx); - ~AutoCheckRequestDepth(); -}; - -# define CHECK_REQUEST(cx) \ - JS::AutoCheckRequestDepth _autoCheckRequestDepth(cx) - -#else - -# define CHECK_REQUEST(cx) \ - ((void) 0) - -#endif /* JS_DEBUG */ - -/** AutoValueArray roots an internal fixed-size array of Values. */ -template -class MOZ_RAII AutoValueArray : public AutoGCRooter -{ - const size_t length_; - Value elements_[N]; - - public: - explicit AutoValueArray(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, VALARRAY), length_(N) - { - /* Always initialize in case we GC before assignment. */ - mozilla::PodArrayZero(elements_); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - unsigned length() const { return length_; } - const Value* begin() const { return elements_; } - Value* begin() { return elements_; } - - HandleValue operator[](unsigned i) const { - MOZ_ASSERT(i < N); - return HandleValue::fromMarkedLocation(&elements_[i]); - } - MutableHandleValue operator[](unsigned i) { - MOZ_ASSERT(i < N); - return MutableHandleValue::fromMarkedLocation(&elements_[i]); - } - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -template -class MOZ_RAII AutoVectorRooterBase : protected AutoGCRooter -{ - typedef js::Vector VectorImpl; - VectorImpl vector; - - public: - explicit AutoVectorRooterBase(JSContext* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), vector(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit AutoVectorRooterBase(js::ContextFriendFields* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), vector(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - typedef T ElementType; - typedef typename VectorImpl::Range Range; - - size_t length() const { return vector.length(); } - bool empty() const { return vector.empty(); } - - MOZ_MUST_USE bool append(const T& v) { return vector.append(v); } - MOZ_MUST_USE bool appendN(const T& v, size_t len) { return vector.appendN(v, len); } - MOZ_MUST_USE bool append(const T* ptr, size_t len) { return vector.append(ptr, len); } - MOZ_MUST_USE bool appendAll(const AutoVectorRooterBase& other) { - return vector.appendAll(other.vector); - } - - MOZ_MUST_USE bool insert(T* p, const T& val) { return vector.insert(p, val); } - - /* For use when space has already been reserved. */ - void infallibleAppend(const T& v) { vector.infallibleAppend(v); } - - void popBack() { vector.popBack(); } - T popCopy() { return vector.popCopy(); } - - MOZ_MUST_USE bool growBy(size_t inc) { - size_t oldLength = vector.length(); - if (!vector.growByUninitialized(inc)) - return false; - makeRangeGCSafe(oldLength); - return true; - } - - MOZ_MUST_USE bool resize(size_t newLength) { - size_t oldLength = vector.length(); - if (newLength <= oldLength) { - vector.shrinkBy(oldLength - newLength); - return true; - } - if (!vector.growByUninitialized(newLength - oldLength)) - return false; - makeRangeGCSafe(oldLength); - return true; - } - - void clear() { vector.clear(); } - - MOZ_MUST_USE bool reserve(size_t newLength) { - return vector.reserve(newLength); - } - - JS::MutableHandle operator[](size_t i) { - return JS::MutableHandle::fromMarkedLocation(&vector[i]); - } - JS::Handle operator[](size_t i) const { - return JS::Handle::fromMarkedLocation(&vector[i]); - } - - const T* begin() const { return vector.begin(); } - T* begin() { return vector.begin(); } - - const T* end() const { return vector.end(); } - T* end() { return vector.end(); } - - Range all() { return vector.all(); } - - const T& back() const { return vector.back(); } - - friend void AutoGCRooter::trace(JSTracer* trc); - - private: - void makeRangeGCSafe(size_t oldLength) { - T* t = vector.begin() + oldLength; - for (size_t i = oldLength; i < vector.length(); ++i, ++t) - memset(t, 0, sizeof(T)); - } - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -template -class MOZ_RAII AutoVectorRooter : public AutoVectorRooterBase -{ - public: - explicit AutoVectorRooter(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoVectorRooterBase(cx, this->GetTag(T())) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit AutoVectorRooter(js::ContextFriendFields* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoVectorRooterBase(cx, this->GetTag(T())) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -class AutoValueVector : public Rooted> { - using Vec = GCVector; - using Base = Rooted; - public: - explicit AutoValueVector(JSContext* cx) : Base(cx, Vec(cx)) {} - explicit AutoValueVector(js::ContextFriendFields* cx) : Base(cx, Vec(cx)) {} -}; - -class AutoIdVector : public Rooted> { - using Vec = GCVector; - using Base = Rooted; - public: - explicit AutoIdVector(JSContext* cx) : Base(cx, Vec(cx)) {} - explicit AutoIdVector(js::ContextFriendFields* cx) : Base(cx, Vec(cx)) {} - - bool appendAll(const AutoIdVector& other) { return this->Base::appendAll(other.get()); } -}; - -class AutoObjectVector : public Rooted> { - using Vec = GCVector; - using Base = Rooted; - public: - explicit AutoObjectVector(JSContext* cx) : Base(cx, Vec(cx)) {} - explicit AutoObjectVector(js::ContextFriendFields* cx) : Base(cx, Vec(cx)) {} -}; - -using ValueVector = JS::GCVector; -using IdVector = JS::GCVector; -using ScriptVector = JS::GCVector; -using StringVector = JS::GCVector; - -template -class MOZ_RAII AutoHashMapRooter : protected AutoGCRooter -{ - private: - typedef js::HashMap HashMapImpl; - - public: - explicit AutoHashMapRooter(JSContext* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), map(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - typedef Key KeyType; - typedef Value ValueType; - typedef typename HashMapImpl::Entry Entry; - typedef typename HashMapImpl::Lookup Lookup; - typedef typename HashMapImpl::Ptr Ptr; - typedef typename HashMapImpl::AddPtr AddPtr; - - bool init(uint32_t len = 16) { - return map.init(len); - } - bool initialized() const { - return map.initialized(); - } - Ptr lookup(const Lookup& l) const { - return map.lookup(l); - } - void remove(Ptr p) { - map.remove(p); - } - AddPtr lookupForAdd(const Lookup& l) const { - return map.lookupForAdd(l); - } - - template - bool add(AddPtr& p, const KeyInput& k, const ValueInput& v) { - return map.add(p, k, v); - } - - bool add(AddPtr& p, const Key& k) { - return map.add(p, k); - } - - template - bool relookupOrAdd(AddPtr& p, const KeyInput& k, const ValueInput& v) { - return map.relookupOrAdd(p, k, v); - } - - typedef typename HashMapImpl::Range Range; - Range all() const { - return map.all(); - } - - typedef typename HashMapImpl::Enum Enum; - - void clear() { - map.clear(); - } - - void finish() { - map.finish(); - } - - bool empty() const { - return map.empty(); - } - - uint32_t count() const { - return map.count(); - } - - size_t capacity() const { - return map.capacity(); - } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return map.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return map.sizeOfIncludingThis(mallocSizeOf); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return map.has(l); - } - - template - bool put(const KeyInput& k, const ValueInput& v) { - return map.put(k, v); - } - - template - bool putNew(const KeyInput& k, const ValueInput& v) { - return map.putNew(k, v); - } - - Ptr lookupWithDefault(const Key& k, const Value& defaultValue) { - return map.lookupWithDefault(k, defaultValue); - } - - void remove(const Lookup& l) { - map.remove(l); - } - - friend void AutoGCRooter::trace(JSTracer* trc); - - private: - AutoHashMapRooter(const AutoHashMapRooter& hmr) = delete; - AutoHashMapRooter& operator=(const AutoHashMapRooter& hmr) = delete; - - HashMapImpl map; - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -template -class MOZ_RAII AutoHashSetRooter : protected AutoGCRooter -{ - private: - typedef js::HashSet HashSetImpl; - - public: - explicit AutoHashSetRooter(JSContext* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), set(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - typedef typename HashSetImpl::Lookup Lookup; - typedef typename HashSetImpl::Ptr Ptr; - typedef typename HashSetImpl::AddPtr AddPtr; - - bool init(uint32_t len = 16) { - return set.init(len); - } - bool initialized() const { - return set.initialized(); - } - Ptr lookup(const Lookup& l) const { - return set.lookup(l); - } - void remove(Ptr p) { - set.remove(p); - } - AddPtr lookupForAdd(const Lookup& l) const { - return set.lookupForAdd(l); - } - - bool add(AddPtr& p, const T& t) { - return set.add(p, t); - } - - bool relookupOrAdd(AddPtr& p, const Lookup& l, const T& t) { - return set.relookupOrAdd(p, l, t); - } - - typedef typename HashSetImpl::Range Range; - Range all() const { - return set.all(); - } - - typedef typename HashSetImpl::Enum Enum; - - void clear() { - set.clear(); - } - - void finish() { - set.finish(); - } - - bool empty() const { - return set.empty(); - } - - uint32_t count() const { - return set.count(); - } - - size_t capacity() const { - return set.capacity(); - } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return set.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return set.sizeOfIncludingThis(mallocSizeOf); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return set.has(l); - } - - bool put(const T& t) { - return set.put(t); - } - - bool putNew(const T& t) { - return set.putNew(t); - } - - void remove(const Lookup& l) { - set.remove(l); - } - - friend void AutoGCRooter::trace(JSTracer* trc); - - private: - AutoHashSetRooter(const AutoHashSetRooter& hmr) = delete; - AutoHashSetRooter& operator=(const AutoHashSetRooter& hmr) = delete; - - HashSetImpl set; - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/** - * Custom rooting behavior for internal and external clients. - */ -class MOZ_RAII JS_PUBLIC_API(CustomAutoRooter) : private AutoGCRooter -{ - public: - template - explicit CustomAutoRooter(const CX& cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, CUSTOM) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - friend void AutoGCRooter::trace(JSTracer* trc); - - protected: - virtual ~CustomAutoRooter() {} - - /** Supplied by derived class to trace roots. */ - virtual void trace(JSTracer* trc) = 0; - - private: - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/** A handle to an array of rooted values. */ -class HandleValueArray -{ - const size_t length_; - const Value * const elements_; - - HandleValueArray(size_t len, const Value* elements) : length_(len), elements_(elements) {} - - public: - explicit HandleValueArray(const RootedValue& value) : length_(1), elements_(value.address()) {} - - MOZ_IMPLICIT HandleValueArray(const AutoValueVector& values) - : length_(values.length()), elements_(values.begin()) {} - - template - MOZ_IMPLICIT HandleValueArray(const AutoValueArray& values) : length_(N), elements_(values.begin()) {} - - /** CallArgs must already be rooted somewhere up the stack. */ - MOZ_IMPLICIT HandleValueArray(const JS::CallArgs& args) : length_(args.length()), elements_(args.array()) {} - - /** Use with care! Only call this if the data is guaranteed to be marked. */ - static HandleValueArray fromMarkedLocation(size_t len, const Value* elements) { - return HandleValueArray(len, elements); - } - - static HandleValueArray subarray(const HandleValueArray& values, size_t startIndex, size_t len) { - MOZ_ASSERT(startIndex + len <= values.length()); - return HandleValueArray(len, values.begin() + startIndex); - } - - static HandleValueArray empty() { - return HandleValueArray(0, nullptr); - } - - size_t length() const { return length_; } - const Value* begin() const { return elements_; } - - HandleValue operator[](size_t i) const { - MOZ_ASSERT(i < length_); - return HandleValue::fromMarkedLocation(&elements_[i]); - } -}; - -} /* namespace JS */ - -/************************************************************************/ - -struct JSFreeOp { - protected: - JSRuntime* runtime_; - - explicit JSFreeOp(JSRuntime* rt) - : runtime_(rt) { } - - public: - JSRuntime* runtime() const { - MOZ_ASSERT(runtime_); - return runtime_; - } -}; - -/* Callbacks and their arguments. */ - -/************************************************************************/ - -typedef enum JSGCStatus { - JSGC_BEGIN, - JSGC_END -} JSGCStatus; - -typedef void -(* JSGCCallback)(JSContext* cx, JSGCStatus status, void* data); - -typedef void -(* JSObjectsTenuredCallback)(JSContext* cx, void* data); - -typedef enum JSFinalizeStatus { - /** - * Called when preparing to sweep a group of zones, before anything has been - * swept. The collector will not yield to the mutator before calling the - * callback with JSFINALIZE_GROUP_END status. - */ - JSFINALIZE_GROUP_START, - - /** - * Called when preparing to sweep a group of zones. Weak references to - * unmarked things have been removed and things that are not swept - * incrementally have been finalized at this point. The collector may yield - * to the mutator after this point. - */ - JSFINALIZE_GROUP_END, - - /** - * Called at the end of collection when everything has been swept. - */ - JSFINALIZE_COLLECTION_END -} JSFinalizeStatus; - -typedef void -(* JSFinalizeCallback)(JSFreeOp* fop, JSFinalizeStatus status, bool isZoneGC, void* data); - -typedef void -(* JSWeakPointerZoneGroupCallback)(JSContext* cx, void* data); - -typedef void -(* JSWeakPointerCompartmentCallback)(JSContext* cx, JSCompartment* comp, void* data); - -typedef bool -(* JSInterruptCallback)(JSContext* cx); - -typedef JSObject* -(* JSGetIncumbentGlobalCallback)(JSContext* cx); - -typedef bool -(* JSEnqueuePromiseJobCallback)(JSContext* cx, JS::HandleObject job, - JS::HandleObject allocationSite, JS::HandleObject incumbentGlobal, - void* data); - -enum class PromiseRejectionHandlingState { - Unhandled, - Handled -}; - -typedef void -(* JSPromiseRejectionTrackerCallback)(JSContext* cx, JS::HandleObject promise, - PromiseRejectionHandlingState state, void* data); - -typedef void -(* JSProcessPromiseCallback)(JSContext* cx, JS::HandleObject promise); - -/** - * Possible exception types. These types are part of a JSErrorFormatString - * structure. They define which error to throw in case of a runtime error. - * - * JSEXN_WARN is used for warnings in js.msg files (for instance because we - * don't want to prepend 'Error:' to warning messages). This value can go away - * if we ever decide to use an entirely separate mechanism for warnings. - */ -typedef enum JSExnType { - JSEXN_ERR, - JSEXN_FIRST = JSEXN_ERR, - JSEXN_INTERNALERR, - JSEXN_EVALERR, - JSEXN_RANGEERR, - JSEXN_REFERENCEERR, - JSEXN_SYNTAXERR, - JSEXN_TYPEERR, - JSEXN_URIERR, - JSEXN_DEBUGGEEWOULDRUN, - JSEXN_WASMCOMPILEERROR, - JSEXN_WASMRUNTIMEERROR, - JSEXN_WARN, - JSEXN_LIMIT -} JSExnType; - -typedef struct JSErrorFormatString { - /** The error message name in ASCII. */ - const char* name; - - /** The error format string in ASCII. */ - const char* format; - - /** The number of arguments to expand in the formatted error message. */ - uint16_t argCount; - - /** One of the JSExnType constants above. */ - int16_t exnType; -} JSErrorFormatString; - -typedef const JSErrorFormatString* -(* JSErrorCallback)(void* userRef, const unsigned errorNumber); - -typedef bool -(* JSLocaleToUpperCase)(JSContext* cx, JS::HandleString src, JS::MutableHandleValue rval); - -typedef bool -(* JSLocaleToLowerCase)(JSContext* cx, JS::HandleString src, JS::MutableHandleValue rval); - -typedef bool -(* JSLocaleCompare)(JSContext* cx, JS::HandleString src1, JS::HandleString src2, - JS::MutableHandleValue rval); - -typedef bool -(* JSLocaleToUnicode)(JSContext* cx, const char* src, JS::MutableHandleValue rval); - -/** - * Callback used to ask the embedding for the cross compartment wrapper handler - * that implements the desired prolicy for this kind of object in the - * destination compartment. |obj| is the object to be wrapped. If |existing| is - * non-nullptr, it will point to an existing wrapper object that should be - * re-used if possible. |existing| is guaranteed to be a cross-compartment - * wrapper with a lazily-defined prototype and the correct global. It is - * guaranteed not to wrap a function. - */ -typedef JSObject* -(* JSWrapObjectCallback)(JSContext* cx, JS::HandleObject existing, JS::HandleObject obj); - -/** - * Callback used by the wrap hook to ask the embedding to prepare an object - * for wrapping in a context. This might include unwrapping other wrappers - * or even finding a more suitable object for the new compartment. - */ -typedef void -(* JSPreWrapCallback)(JSContext* cx, JS::HandleObject scope, JS::HandleObject obj, - JS::HandleObject objectPassedToWrap, - JS::MutableHandleObject retObj); - -struct JSWrapObjectCallbacks -{ - JSWrapObjectCallback wrap; - JSPreWrapCallback preWrap; -}; - -typedef void -(* JSDestroyCompartmentCallback)(JSFreeOp* fop, JSCompartment* compartment); - -typedef size_t -(* JSSizeOfIncludingThisCompartmentCallback)(mozilla::MallocSizeOf mallocSizeOf, - JSCompartment* compartment); - -typedef void -(* JSZoneCallback)(JS::Zone* zone); - -typedef void -(* JSCompartmentNameCallback)(JSContext* cx, JSCompartment* compartment, - char* buf, size_t bufsize); - -/************************************************************************/ - -static MOZ_ALWAYS_INLINE JS::Value -JS_NumberValue(double d) -{ - int32_t i; - d = JS::CanonicalizeNaN(d); - if (mozilla::NumberIsInt32(d, &i)) - return JS::Int32Value(i); - return JS::DoubleValue(d); -} - -/************************************************************************/ - -JS_PUBLIC_API(bool) -JS_StringHasBeenPinned(JSContext* cx, JSString* str); - -namespace JS { - -/** - * Container class for passing in script source buffers to the JS engine. This - * not only groups the buffer and length values, it also provides a way to - * optionally pass ownership of the buffer to the JS engine without copying. - * Rules for use: - * - * 1) The data array must be allocated with js_malloc() or js_realloc() if - * ownership is being granted to the SourceBufferHolder. - * 2) If ownership is not given to the SourceBufferHolder, then the memory - * must be kept alive until the JS compilation is complete. - * 3) Any code calling SourceBufferHolder::take() must guarantee to keep the - * memory alive until JS compilation completes. Normally only the JS - * engine should be calling take(). - * - * Example use: - * - * size_t length = 512; - * char16_t* chars = static_cast(js_malloc(sizeof(char16_t) * length)); - * JS::SourceBufferHolder srcBuf(chars, length, JS::SourceBufferHolder::GiveOwnership); - * JS::Compile(cx, options, srcBuf); - */ -class MOZ_STACK_CLASS SourceBufferHolder final -{ - public: - enum Ownership { - NoOwnership, - GiveOwnership - }; - - SourceBufferHolder(const char16_t* data, size_t dataLength, Ownership ownership) - : data_(data), - length_(dataLength), - ownsChars_(ownership == GiveOwnership) - { - // Ensure that null buffers properly return an unowned, empty, - // null-terminated string. - static const char16_t NullChar_ = 0; - if (!get()) { - data_ = &NullChar_; - length_ = 0; - ownsChars_ = false; - } - } - - SourceBufferHolder(SourceBufferHolder&& other) - : data_(other.data_), - length_(other.length_), - ownsChars_(other.ownsChars_) - { - other.data_ = nullptr; - other.length_ = 0; - other.ownsChars_ = false; - } - - ~SourceBufferHolder() { - if (ownsChars_) - js_free(const_cast(data_)); - } - - // Access the underlying source buffer without affecting ownership. - const char16_t* get() const { return data_; } - - // Length of the source buffer in char16_t code units (not bytes) - size_t length() const { return length_; } - - // Returns true if the SourceBufferHolder owns the buffer and will free - // it upon destruction. If true, it is legal to call take(). - bool ownsChars() const { return ownsChars_; } - - // Retrieve and take ownership of the underlying data buffer. The caller - // is now responsible for calling js_free() on the returned value, *but only - // after JS script compilation has completed*. - // - // After the buffer has been taken the SourceBufferHolder functions as if - // it had been constructed on an unowned buffer; get() and length() still - // work. In order for this to be safe the taken buffer must be kept alive - // until after JS script compilation completes as noted above. - // - // Note, it's the caller's responsibility to check ownsChars() before taking - // the buffer. Taking and then free'ing an unowned buffer will have dire - // consequences. - char16_t* take() { - MOZ_ASSERT(ownsChars_); - ownsChars_ = false; - return const_cast(data_); - } - - private: - SourceBufferHolder(SourceBufferHolder&) = delete; - SourceBufferHolder& operator=(SourceBufferHolder&) = delete; - - const char16_t* data_; - size_t length_; - bool ownsChars_; -}; - -} /* namespace JS */ - -/************************************************************************/ - -/* Property attributes, set in JSPropertySpec and passed to API functions. - * - * NB: The data structure in which some of these values are stored only uses - * a uint8_t to store the relevant information. Proceed with caution if - * trying to reorder or change the the first byte worth of flags. - */ -#define JSPROP_ENUMERATE 0x01 /* property is visible to for/in loop */ -#define JSPROP_READONLY 0x02 /* not settable: assignment is no-op. - This flag is only valid when neither - JSPROP_GETTER nor JSPROP_SETTER is - set. */ -#define JSPROP_PERMANENT 0x04 /* property cannot be deleted */ -#define JSPROP_PROPOP_ACCESSORS 0x08 /* Passed to JS_Define(UC)Property* and - JS_DefineElement if getters/setters - are JSGetterOp/JSSetterOp */ -#define JSPROP_GETTER 0x10 /* property holds getter function */ -#define JSPROP_SETTER 0x20 /* property holds setter function */ -#define JSPROP_SHARED 0x40 /* don't allocate a value slot for this - property; don't copy the property on - set of the same-named property in an - object that delegates to a prototype - containing this property */ -#define JSPROP_INTERNAL_USE_BIT 0x80 /* internal JS engine use only */ -#define JSFUN_STUB_GSOPS 0x200 /* use JS_PropertyStub getter/setter - instead of defaulting to class gsops - for property holding function */ - -#define JSFUN_CONSTRUCTOR 0x400 /* native that can be called as a ctor */ - -// 0x800 /* Unused */ - -#define JSFUN_HAS_REST 0x1000 /* function has ...rest parameter. */ - -#define JSFUN_FLAGS_MASK 0x1e00 /* | of all the JSFUN_* flags */ - -/* - * If set, will allow redefining a non-configurable property, but only on a - * non-DOM global. This is a temporary hack that will need to go away in bug - * 1105518. - */ -#define JSPROP_REDEFINE_NONCONFIGURABLE 0x1000 - -/* - * Resolve hooks and enumerate hooks must pass this flag when calling - * JS_Define* APIs to reify lazily-defined properties. - * - * JSPROP_RESOLVING is used only with property-defining APIs. It tells the - * engine to skip the resolve hook when performing the lookup at the beginning - * of property definition. This keeps the resolve hook from accidentally - * triggering itself: unchecked recursion. - * - * For enumerate hooks, triggering the resolve hook would be merely silly, not - * fatal, except in some cases involving non-configurable properties. - */ -#define JSPROP_RESOLVING 0x2000 - -#define JSPROP_IGNORE_ENUMERATE 0x4000 /* ignore the value in JSPROP_ENUMERATE. - This flag only valid when defining over - an existing property. */ -#define JSPROP_IGNORE_READONLY 0x8000 /* ignore the value in JSPROP_READONLY. - This flag only valid when defining over - an existing property. */ -#define JSPROP_IGNORE_PERMANENT 0x10000 /* ignore the value in JSPROP_PERMANENT. - This flag only valid when defining over - an existing property. */ -#define JSPROP_IGNORE_VALUE 0x20000 /* ignore the Value in the descriptor. Nothing was - specified when passed to Object.defineProperty - from script. */ - -/** Microseconds since the epoch, midnight, January 1, 1970 UTC. */ -extern JS_PUBLIC_API(int64_t) -JS_Now(void); - -/** Don't want to export data, so provide accessors for non-inline Values. */ -extern JS_PUBLIC_API(JS::Value) -JS_GetNaNValue(JSContext* cx); - -extern JS_PUBLIC_API(JS::Value) -JS_GetNegativeInfinityValue(JSContext* cx); - -extern JS_PUBLIC_API(JS::Value) -JS_GetPositiveInfinityValue(JSContext* cx); - -extern JS_PUBLIC_API(JS::Value) -JS_GetEmptyStringValue(JSContext* cx); - -extern JS_PUBLIC_API(JSString*) -JS_GetEmptyString(JSContext* cx); - -extern JS_PUBLIC_API(bool) -JS_ValueToObject(JSContext* cx, JS::HandleValue v, JS::MutableHandleObject objp); - -extern JS_PUBLIC_API(JSFunction*) -JS_ValueToFunction(JSContext* cx, JS::HandleValue v); - -extern JS_PUBLIC_API(JSFunction*) -JS_ValueToConstructor(JSContext* cx, JS::HandleValue v); - -extern JS_PUBLIC_API(JSString*) -JS_ValueToSource(JSContext* cx, JS::Handle v); - -extern JS_PUBLIC_API(bool) -JS_DoubleIsInt32(double d, int32_t* ip); - -extern JS_PUBLIC_API(JSType) -JS_TypeOfValue(JSContext* cx, JS::Handle v); - -namespace JS { - -extern JS_PUBLIC_API(const char*) -InformalValueTypeName(const JS::Value& v); - -} /* namespace JS */ - -extern JS_PUBLIC_API(bool) -JS_StrictlyEqual(JSContext* cx, JS::Handle v1, JS::Handle v2, bool* equal); - -extern JS_PUBLIC_API(bool) -JS_LooselyEqual(JSContext* cx, JS::Handle v1, JS::Handle v2, bool* equal); - -extern JS_PUBLIC_API(bool) -JS_SameValue(JSContext* cx, JS::Handle v1, JS::Handle v2, bool* same); - -/** True iff fun is the global eval function. */ -extern JS_PUBLIC_API(bool) -JS_IsBuiltinEvalFunction(JSFunction* fun); - -/** True iff fun is the Function constructor. */ -extern JS_PUBLIC_API(bool) -JS_IsBuiltinFunctionConstructor(JSFunction* fun); - -/************************************************************************/ - -/* - * Locking, contexts, and memory allocation. - * - * It is important that SpiderMonkey be initialized, and the first context - * be created, in a single-threaded fashion. Otherwise the behavior of the - * library is undefined. - * See: http://developer.mozilla.org/en/docs/Category:JSAPI_Reference - */ - -extern JS_PUBLIC_API(JSContext*) -JS_NewContext(uint32_t maxbytes, - uint32_t maxNurseryBytes = JS::DefaultNurseryBytes, - JSContext* parentContext = nullptr); - -extern JS_PUBLIC_API(void) -JS_DestroyContext(JSContext* cx); - -typedef double (*JS_CurrentEmbedderTimeFunction)(); - -/** - * The embedding can specify a time function that will be used in some - * situations. The function can return the time however it likes; but - * the norm is to return times in units of milliseconds since an - * arbitrary, but consistent, epoch. If the time function is not set, - * a built-in default will be used. - */ -JS_PUBLIC_API(void) -JS_SetCurrentEmbedderTimeFunction(JS_CurrentEmbedderTimeFunction timeFn); - -/** - * Return the time as computed using the current time function, or a - * suitable default if one has not been set. - */ -JS_PUBLIC_API(double) -JS_GetCurrentEmbedderTime(); - -JS_PUBLIC_API(void*) -JS_GetContextPrivate(JSContext* cx); - -JS_PUBLIC_API(void) -JS_SetContextPrivate(JSContext* cx, void* data); - -extern JS_PUBLIC_API(JSContext*) -JS_GetParentContext(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_BeginRequest(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_EndRequest(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_SetFutexCanWait(JSContext* cx); - -namespace js { - -void -AssertHeapIsIdle(JSRuntime* rt); - -} /* namespace js */ - -class MOZ_RAII JSAutoRequest -{ - public: - explicit JSAutoRequest(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mContext(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - JS_BeginRequest(mContext); - } - ~JSAutoRequest() { - JS_EndRequest(mContext); - } - - protected: - JSContext* mContext; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - -#if 0 - private: - static void* operator new(size_t) CPP_THROW_NEW { return 0; } - static void operator delete(void*, size_t) { } -#endif -}; - -extern JS_PUBLIC_API(JSVersion) -JS_GetVersion(JSContext* cx); - -/** - * Mutate the version on the compartment. This is generally discouraged, but - * necessary to support the version mutation in the js and xpc shell command - * set. - * - * It would be nice to put this in jsfriendapi, but the linkage requirements - * of the shells make that impossible. - */ -JS_PUBLIC_API(void) -JS_SetVersionForCompartment(JSCompartment* compartment, JSVersion version); - -extern JS_PUBLIC_API(const char*) -JS_VersionToString(JSVersion version); - -extern JS_PUBLIC_API(JSVersion) -JS_StringToVersion(const char* string); - -namespace JS { - -class JS_PUBLIC_API(ContextOptions) { - public: - ContextOptions() - : baseline_(true), - ion_(true), - asmJS_(true), - wasm_(false), - wasmAlwaysBaseline_(false), - throwOnAsmJSValidationFailure_(false), - nativeRegExp_(true), - unboxedArrays_(false), - asyncStack_(true), - throwOnDebuggeeWouldRun_(true), - dumpStackOnDebuggeeWouldRun_(false), - werror_(false), - strictMode_(false), - extraWarnings_(false) - { - } - - bool baseline() const { return baseline_; } - ContextOptions& setBaseline(bool flag) { - baseline_ = flag; - return *this; - } - ContextOptions& toggleBaseline() { - baseline_ = !baseline_; - return *this; - } - - bool ion() const { return ion_; } - ContextOptions& setIon(bool flag) { - ion_ = flag; - return *this; - } - ContextOptions& toggleIon() { - ion_ = !ion_; - return *this; - } - - bool asmJS() const { return asmJS_; } - ContextOptions& setAsmJS(bool flag) { - asmJS_ = flag; - return *this; - } - ContextOptions& toggleAsmJS() { - asmJS_ = !asmJS_; - return *this; - } - - bool wasm() const { return wasm_; } - ContextOptions& setWasm(bool flag) { - wasm_ = flag; - return *this; - } - ContextOptions& toggleWasm() { - wasm_ = !wasm_; - return *this; - } - - bool wasmAlwaysBaseline() const { return wasmAlwaysBaseline_; } - ContextOptions& setWasmAlwaysBaseline(bool flag) { - wasmAlwaysBaseline_ = flag; - return *this; - } - ContextOptions& toggleWasmAlwaysBaseline() { - wasmAlwaysBaseline_ = !wasmAlwaysBaseline_; - return *this; - } - - bool throwOnAsmJSValidationFailure() const { return throwOnAsmJSValidationFailure_; } - ContextOptions& setThrowOnAsmJSValidationFailure(bool flag) { - throwOnAsmJSValidationFailure_ = flag; - return *this; - } - ContextOptions& toggleThrowOnAsmJSValidationFailure() { - throwOnAsmJSValidationFailure_ = !throwOnAsmJSValidationFailure_; - return *this; - } - - bool nativeRegExp() const { return nativeRegExp_; } - ContextOptions& setNativeRegExp(bool flag) { - nativeRegExp_ = flag; - return *this; - } - - bool unboxedArrays() const { return unboxedArrays_; } - ContextOptions& setUnboxedArrays(bool flag) { - unboxedArrays_ = flag; - return *this; - } - - bool asyncStack() const { return asyncStack_; } - ContextOptions& setAsyncStack(bool flag) { - asyncStack_ = flag; - return *this; - } - - bool throwOnDebuggeeWouldRun() const { return throwOnDebuggeeWouldRun_; } - ContextOptions& setThrowOnDebuggeeWouldRun(bool flag) { - throwOnDebuggeeWouldRun_ = flag; - return *this; - } - - bool dumpStackOnDebuggeeWouldRun() const { return dumpStackOnDebuggeeWouldRun_; } - ContextOptions& setDumpStackOnDebuggeeWouldRun(bool flag) { - dumpStackOnDebuggeeWouldRun_ = flag; - return *this; - } - - bool werror() const { return werror_; } - ContextOptions& setWerror(bool flag) { - werror_ = flag; - return *this; - } - ContextOptions& toggleWerror() { - werror_ = !werror_; - return *this; - } - - bool strictMode() const { return strictMode_; } - ContextOptions& setStrictMode(bool flag) { - strictMode_ = flag; - return *this; - } - ContextOptions& toggleStrictMode() { - strictMode_ = !strictMode_; - return *this; - } - - bool extraWarnings() const { return extraWarnings_; } - ContextOptions& setExtraWarnings(bool flag) { - extraWarnings_ = flag; - return *this; - } - ContextOptions& toggleExtraWarnings() { - extraWarnings_ = !extraWarnings_; - return *this; - } - - private: - bool baseline_ : 1; - bool ion_ : 1; - bool asmJS_ : 1; - bool wasm_ : 1; - bool wasmAlwaysBaseline_ : 1; - bool throwOnAsmJSValidationFailure_ : 1; - bool nativeRegExp_ : 1; - bool unboxedArrays_ : 1; - bool asyncStack_ : 1; - bool throwOnDebuggeeWouldRun_ : 1; - bool dumpStackOnDebuggeeWouldRun_ : 1; - bool werror_ : 1; - bool strictMode_ : 1; - bool extraWarnings_ : 1; -}; - -JS_PUBLIC_API(ContextOptions&) -ContextOptionsRef(JSContext* cx); - -/** - * Initialize the runtime's self-hosted code. Embeddings should call this - * exactly once per runtime/context, before the first JS_NewGlobalObject - * call. - */ -JS_PUBLIC_API(bool) -InitSelfHostedCode(JSContext* cx); - -/** - * Asserts (in debug and release builds) that `obj` belongs to the current - * thread's context. - */ -JS_PUBLIC_API(void) -AssertObjectBelongsToCurrentThread(JSObject* obj); - -} /* namespace JS */ - -extern JS_PUBLIC_API(const char*) -JS_GetImplementationVersion(void); - -extern JS_PUBLIC_API(void) -JS_SetDestroyCompartmentCallback(JSContext* cx, JSDestroyCompartmentCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetSizeOfIncludingThisCompartmentCallback(JSContext* cx, - JSSizeOfIncludingThisCompartmentCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetDestroyZoneCallback(JSContext* cx, JSZoneCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetSweepZoneCallback(JSContext* cx, JSZoneCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetCompartmentNameCallback(JSContext* cx, JSCompartmentNameCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetWrapObjectCallbacks(JSContext* cx, const JSWrapObjectCallbacks* callbacks); - -extern JS_PUBLIC_API(void) -JS_SetCompartmentPrivate(JSCompartment* compartment, void* data); - -extern JS_PUBLIC_API(void*) -JS_GetCompartmentPrivate(JSCompartment* compartment); - -extern JS_PUBLIC_API(void) -JS_SetZoneUserData(JS::Zone* zone, void* data); - -extern JS_PUBLIC_API(void*) -JS_GetZoneUserData(JS::Zone* zone); - -extern JS_PUBLIC_API(bool) -JS_WrapObject(JSContext* cx, JS::MutableHandleObject objp); - -extern JS_PUBLIC_API(bool) -JS_WrapValue(JSContext* cx, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(JSObject*) -JS_TransplantObject(JSContext* cx, JS::HandleObject origobj, JS::HandleObject target); - -extern JS_PUBLIC_API(bool) -JS_RefreshCrossCompartmentWrappers(JSContext* cx, JS::Handle obj); - -/* - * At any time, a JSContext has a current (possibly-nullptr) compartment. - * Compartments are described in: - * - * developer.mozilla.org/en-US/docs/SpiderMonkey/SpiderMonkey_compartments - * - * The current compartment of a context may be changed. The preferred way to do - * this is with JSAutoCompartment: - * - * void foo(JSContext* cx, JSObject* obj) { - * // in some compartment 'c' - * { - * JSAutoCompartment ac(cx, obj); // constructor enters - * // in the compartment of 'obj' - * } // destructor leaves - * // back in compartment 'c' - * } - * - * For more complicated uses that don't neatly fit in a C++ stack frame, the - * compartment can entered and left using separate function calls: - * - * void foo(JSContext* cx, JSObject* obj) { - * // in 'oldCompartment' - * JSCompartment* oldCompartment = JS_EnterCompartment(cx, obj); - * // in the compartment of 'obj' - * JS_LeaveCompartment(cx, oldCompartment); - * // back in 'oldCompartment' - * } - * - * Note: these calls must still execute in a LIFO manner w.r.t all other - * enter/leave calls on the context. Furthermore, only the return value of a - * JS_EnterCompartment call may be passed as the 'oldCompartment' argument of - * the corresponding JS_LeaveCompartment call. - */ - -class MOZ_RAII JS_PUBLIC_API(JSAutoCompartment) -{ - JSContext* cx_; - JSCompartment* oldCompartment_; - public: - JSAutoCompartment(JSContext* cx, JSObject* target - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - JSAutoCompartment(JSContext* cx, JSScript* target - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~JSAutoCompartment(); - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -class MOZ_RAII JS_PUBLIC_API(JSAutoNullableCompartment) -{ - JSContext* cx_; - JSCompartment* oldCompartment_; - public: - explicit JSAutoNullableCompartment(JSContext* cx, JSObject* targetOrNull - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~JSAutoNullableCompartment(); - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/** NB: This API is infallible; a nullptr return value does not indicate error. */ -extern JS_PUBLIC_API(JSCompartment*) -JS_EnterCompartment(JSContext* cx, JSObject* target); - -extern JS_PUBLIC_API(void) -JS_LeaveCompartment(JSContext* cx, JSCompartment* oldCompartment); - -typedef void (*JSIterateCompartmentCallback)(JSContext* cx, void* data, JSCompartment* compartment); - -/** - * This function calls |compartmentCallback| on every compartment. Beware that - * there is no guarantee that the compartment will survive after the callback - * returns. Also, barriers are disabled via the TraceSession. - */ -extern JS_PUBLIC_API(void) -JS_IterateCompartments(JSContext* cx, void* data, - JSIterateCompartmentCallback compartmentCallback); - -/** - * Initialize standard JS class constructors, prototypes, and any top-level - * functions and constants associated with the standard classes (e.g. isNaN - * for Number). - * - * NB: This sets cx's global object to obj if it was null. - */ -extern JS_PUBLIC_API(bool) -JS_InitStandardClasses(JSContext* cx, JS::Handle obj); - -/** - * Resolve id, which must contain either a string or an int, to a standard - * class name in obj if possible, defining the class's constructor and/or - * prototype and storing true in *resolved. If id does not name a standard - * class or a top-level property induced by initializing a standard class, - * store false in *resolved and just return true. Return false on error, - * as usual for bool result-typed API entry points. - * - * This API can be called directly from a global object class's resolve op, - * to define standard classes lazily. The class's enumerate op should call - * JS_EnumerateStandardClasses(cx, obj), to define eagerly during for..in - * loops any classes not yet resolved lazily. - */ -extern JS_PUBLIC_API(bool) -JS_ResolveStandardClass(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* resolved); - -extern JS_PUBLIC_API(bool) -JS_MayResolveStandardClass(const JSAtomState& names, jsid id, JSObject* maybeObj); - -extern JS_PUBLIC_API(bool) -JS_EnumerateStandardClasses(JSContext* cx, JS::HandleObject obj); - -extern JS_PUBLIC_API(bool) -JS_GetClassObject(JSContext* cx, JSProtoKey key, JS::MutableHandle objp); - -extern JS_PUBLIC_API(bool) -JS_GetClassPrototype(JSContext* cx, JSProtoKey key, JS::MutableHandle objp); - -namespace JS { - -/* - * Determine if the given object is an instance/prototype/constructor for a standard - * class. If so, return the associated JSProtoKey. If not, return JSProto_Null. - */ - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardInstance(JSObject* obj); - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardPrototype(JSObject* obj); - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardInstanceOrPrototype(JSObject* obj); - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardConstructor(JSObject* obj); - -extern JS_PUBLIC_API(void) -ProtoKeyToId(JSContext* cx, JSProtoKey key, JS::MutableHandleId idp); - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSProtoKey) -JS_IdToProtoKey(JSContext* cx, JS::HandleId id); - -/** - * Returns the original value of |Function.prototype| from the global object in - * which |forObj| was created. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetFunctionPrototype(JSContext* cx, JS::HandleObject forObj); - -/** - * Returns the original value of |Object.prototype| from the global object in - * which |forObj| was created. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetObjectPrototype(JSContext* cx, JS::HandleObject forObj); - -/** - * Returns the original value of |Array.prototype| from the global object in - * which |forObj| was created. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetArrayPrototype(JSContext* cx, JS::HandleObject forObj); - -/** - * Returns the original value of |Error.prototype| from the global - * object of the current compartment of cx. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetErrorPrototype(JSContext* cx); - -/** - * Returns the %IteratorPrototype% object that all built-in iterator prototype - * chains go through for the global object of the current compartment of cx. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetIteratorPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -JS_GetGlobalForObject(JSContext* cx, JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_IsGlobalObject(JSObject* obj); - -extern JS_PUBLIC_API(JSObject*) -JS_GlobalLexicalEnvironment(JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_HasExtensibleLexicalEnvironment(JSObject* obj); - -extern JS_PUBLIC_API(JSObject*) -JS_ExtensibleLexicalEnvironment(JSObject* obj); - -/** - * May return nullptr, if |c| never had a global (e.g. the atoms compartment), - * or if |c|'s global has been collected. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetGlobalForCompartmentOrNull(JSContext* cx, JSCompartment* c); - -namespace JS { - -extern JS_PUBLIC_API(JSObject*) -CurrentGlobalOrNull(JSContext* cx); - -} // namespace JS - -/** - * Add 'Reflect.parse', a SpiderMonkey extension, to the Reflect object on the - * given global. - */ -extern JS_PUBLIC_API(bool) -JS_InitReflectParse(JSContext* cx, JS::HandleObject global); - -/** - * Add various profiling-related functions as properties of the given object. - * Defined in builtin/Profilers.cpp. - */ -extern JS_PUBLIC_API(bool) -JS_DefineProfilingFunctions(JSContext* cx, JS::HandleObject obj); - -/* Defined in vm/Debugger.cpp. */ -extern JS_PUBLIC_API(bool) -JS_DefineDebuggerObject(JSContext* cx, JS::HandleObject obj); - -#ifdef JS_HAS_CTYPES -/** - * Initialize the 'ctypes' object on a global variable 'obj'. The 'ctypes' - * object will be sealed. - */ -extern JS_PUBLIC_API(bool) -JS_InitCTypesClass(JSContext* cx, JS::HandleObject global); - -/** - * Convert a unicode string 'source' of length 'slen' to the platform native - * charset, returning a null-terminated string allocated with JS_malloc. On - * failure, this function should report an error. - */ -typedef char* -(* JSCTypesUnicodeToNativeFun)(JSContext* cx, const char16_t* source, size_t slen); - -/** - * Set of function pointers that ctypes can use for various internal functions. - * See JS_SetCTypesCallbacks below. Providing nullptr for a function is safe, - * and will result in the applicable ctypes functionality not being available. - */ -struct JSCTypesCallbacks { - JSCTypesUnicodeToNativeFun unicodeToNative; -}; - -typedef struct JSCTypesCallbacks JSCTypesCallbacks; - -/** - * Set the callbacks on the provided 'ctypesObj' object. 'callbacks' should be a - * pointer to static data that exists for the lifetime of 'ctypesObj', but it - * may safely be altered after calling this function and without having - * to call this function again. - */ -extern JS_PUBLIC_API(void) -JS_SetCTypesCallbacks(JSObject* ctypesObj, const JSCTypesCallbacks* callbacks); -#endif - -extern JS_PUBLIC_API(void*) -JS_malloc(JSContext* cx, size_t nbytes); - -extern JS_PUBLIC_API(void*) -JS_realloc(JSContext* cx, void* p, size_t oldBytes, size_t newBytes); - -/** - * A wrapper for js_free(p) that may delay js_free(p) invocation as a - * performance optimization. - * cx may be nullptr. - */ -extern JS_PUBLIC_API(void) -JS_free(JSContext* cx, void* p); - -/** - * A wrapper for js_free(p) that may delay js_free(p) invocation as a - * performance optimization as specified by the given JSFreeOp instance. - */ -extern JS_PUBLIC_API(void) -JS_freeop(JSFreeOp* fop, void* p); - -extern JS_PUBLIC_API(void) -JS_updateMallocCounter(JSContext* cx, size_t nbytes); - -extern JS_PUBLIC_API(char*) -JS_strdup(JSContext* cx, const char* s); - -/** - * Register externally maintained GC roots. - * - * traceOp: the trace operation. For each root the implementation should call - * JS::TraceEdge whenever the root contains a traceable thing. - * data: the data argument to pass to each invocation of traceOp. - */ -extern JS_PUBLIC_API(bool) -JS_AddExtraGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data); - -/** Undo a call to JS_AddExtraGCRootsTracer. */ -extern JS_PUBLIC_API(void) -JS_RemoveExtraGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data); - -/* - * Garbage collector API. - */ -extern JS_PUBLIC_API(void) -JS_GC(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_MaybeGC(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_SetGCCallback(JSContext* cx, JSGCCallback cb, void* data); - -extern JS_PUBLIC_API(void) -JS_SetObjectsTenuredCallback(JSContext* cx, JSObjectsTenuredCallback cb, - void* data); - -extern JS_PUBLIC_API(bool) -JS_AddFinalizeCallback(JSContext* cx, JSFinalizeCallback cb, void* data); - -extern JS_PUBLIC_API(void) -JS_RemoveFinalizeCallback(JSContext* cx, JSFinalizeCallback cb); - -/* - * Weak pointers and garbage collection - * - * Weak pointers are by their nature not marked as part of garbage collection, - * but they may need to be updated in two cases after a GC: - * - * 1) Their referent was found not to be live and is about to be finalized - * 2) Their referent has been moved by a compacting GC - * - * To handle this, any part of the system that maintain weak pointers to - * JavaScript GC things must register a callback with - * JS_(Add,Remove)WeakPointer{ZoneGroup,Compartment}Callback(). This callback - * must then call JS_UpdateWeakPointerAfterGC() on all weak pointers it knows - * about. - * - * Since sweeping is incremental, we have several callbacks to avoid repeatedly - * having to visit all embedder structures. The WeakPointerZoneGroupCallback is - * called once for each strongly connected group of zones, whereas the - * WeakPointerCompartmentCallback is called once for each compartment that is - * visited while sweeping. Structures that cannot contain references in more - * than one compartment should sweep the relevant per-compartment structures - * using the latter callback to minimizer per-slice overhead. - * - * The argument to JS_UpdateWeakPointerAfterGC() is an in-out param. If the - * referent is about to be finalized the pointer will be set to null. If the - * referent has been moved then the pointer will be updated to point to the new - * location. - * - * Callers of this method are responsible for updating any state that is - * dependent on the object's address. For example, if the object's address is - * used as a key in a hashtable, then the object must be removed and - * re-inserted with the correct hash. - */ - -extern JS_PUBLIC_API(bool) -JS_AddWeakPointerZoneGroupCallback(JSContext* cx, JSWeakPointerZoneGroupCallback cb, void* data); - -extern JS_PUBLIC_API(void) -JS_RemoveWeakPointerZoneGroupCallback(JSContext* cx, JSWeakPointerZoneGroupCallback cb); - -extern JS_PUBLIC_API(bool) -JS_AddWeakPointerCompartmentCallback(JSContext* cx, JSWeakPointerCompartmentCallback cb, - void* data); - -extern JS_PUBLIC_API(void) -JS_RemoveWeakPointerCompartmentCallback(JSContext* cx, JSWeakPointerCompartmentCallback cb); - -extern JS_PUBLIC_API(void) -JS_UpdateWeakPointerAfterGC(JS::Heap* objp); - -extern JS_PUBLIC_API(void) -JS_UpdateWeakPointerAfterGCUnbarriered(JSObject** objp); - -typedef enum JSGCParamKey { - /** Maximum nominal heap before last ditch GC. */ - JSGC_MAX_BYTES = 0, - - /** Number of JS_malloc bytes before last ditch GC. */ - JSGC_MAX_MALLOC_BYTES = 1, - - /** Amount of bytes allocated by the GC. */ - JSGC_BYTES = 3, - - /** Number of times GC has been invoked. Includes both major and minor GC. */ - JSGC_NUMBER = 4, - - /** Select GC mode. */ - JSGC_MODE = 6, - - /** Number of cached empty GC chunks. */ - JSGC_UNUSED_CHUNKS = 7, - - /** Total number of allocated GC chunks. */ - JSGC_TOTAL_CHUNKS = 8, - - /** Max milliseconds to spend in an incremental GC slice. */ - JSGC_SLICE_TIME_BUDGET = 9, - - /** Maximum size the GC mark stack can grow to. */ - JSGC_MARK_STACK_LIMIT = 10, - - /** - * GCs less than this far apart in time will be considered 'high-frequency GCs'. - * See setGCLastBytes in jsgc.cpp. - */ - JSGC_HIGH_FREQUENCY_TIME_LIMIT = 11, - - /** Start of dynamic heap growth. */ - JSGC_HIGH_FREQUENCY_LOW_LIMIT = 12, - - /** End of dynamic heap growth. */ - JSGC_HIGH_FREQUENCY_HIGH_LIMIT = 13, - - /** Upper bound of heap growth. */ - JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX = 14, - - /** Lower bound of heap growth. */ - JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN = 15, - - /** Heap growth for low frequency GCs. */ - JSGC_LOW_FREQUENCY_HEAP_GROWTH = 16, - - /** - * If false, the heap growth factor is fixed at 3. If true, it is determined - * based on whether GCs are high- or low- frequency. - */ - JSGC_DYNAMIC_HEAP_GROWTH = 17, - - /** If true, high-frequency GCs will use a longer mark slice. */ - JSGC_DYNAMIC_MARK_SLICE = 18, - - /** Lower limit after which we limit the heap growth. */ - JSGC_ALLOCATION_THRESHOLD = 19, - - /** - * We try to keep at least this many unused chunks in the free chunk pool at - * all times, even after a shrinking GC. - */ - JSGC_MIN_EMPTY_CHUNK_COUNT = 21, - - /** We never keep more than this many unused chunks in the free chunk pool. */ - JSGC_MAX_EMPTY_CHUNK_COUNT = 22, - - /** Whether compacting GC is enabled. */ - JSGC_COMPACTING_ENABLED = 23, - - /** If true, painting can trigger IGC slices. */ - JSGC_REFRESH_FRAME_SLICES_ENABLED = 24, -} JSGCParamKey; - -extern JS_PUBLIC_API(void) -JS_SetGCParameter(JSContext* cx, JSGCParamKey key, uint32_t value); - -extern JS_PUBLIC_API(uint32_t) -JS_GetGCParameter(JSContext* cx, JSGCParamKey key); - -extern JS_PUBLIC_API(void) -JS_SetGCParametersBasedOnAvailableMemory(JSContext* cx, uint32_t availMem); - -/** - * Create a new JSString whose chars member refers to external memory, i.e., - * memory requiring application-specific finalization. - */ -extern JS_PUBLIC_API(JSString*) -JS_NewExternalString(JSContext* cx, const char16_t* chars, size_t length, - const JSStringFinalizer* fin); - -/** - * Return whether 'str' was created with JS_NewExternalString or - * JS_NewExternalStringWithClosure. - */ -extern JS_PUBLIC_API(bool) -JS_IsExternalString(JSString* str); - -/** - * Return the 'fin' arg passed to JS_NewExternalString. - */ -extern JS_PUBLIC_API(const JSStringFinalizer*) -JS_GetExternalStringFinalizer(JSString* str); - -/** - * Set the size of the native stack that should not be exceed. To disable - * stack size checking pass 0. - * - * SpiderMonkey allows for a distinction between system code (such as GCs, which - * may incidentally be triggered by script but are not strictly performed on - * behalf of such script), trusted script (as determined by JS_SetTrustedPrincipals), - * and untrusted script. Each kind of code may have a different stack quota, - * allowing embedders to keep higher-priority machinery running in the face of - * scripted stack exhaustion by something else. - * - * The stack quotas for each kind of code should be monotonically descending, - * and may be specified with this function. If 0 is passed for a given kind - * of code, it defaults to the value of the next-highest-priority kind. - * - * This function may only be called immediately after the runtime is initialized - * and before any code is executed and/or interrupts requested. - */ -extern JS_PUBLIC_API(void) -JS_SetNativeStackQuota(JSContext* cx, size_t systemCodeStackSize, - size_t trustedScriptStackSize = 0, - size_t untrustedScriptStackSize = 0); - -/************************************************************************/ - -extern JS_PUBLIC_API(bool) -JS_ValueToId(JSContext* cx, JS::HandleValue v, JS::MutableHandleId idp); - -extern JS_PUBLIC_API(bool) -JS_StringToId(JSContext* cx, JS::HandleString s, JS::MutableHandleId idp); - -extern JS_PUBLIC_API(bool) -JS_IdToValue(JSContext* cx, jsid id, JS::MutableHandle vp); - -namespace JS { - -/** - * Convert obj to a primitive value. On success, store the result in vp and - * return true. - * - * The hint argument must be JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_VOID (no - * hint). - * - * Implements: ES6 7.1.1 ToPrimitive(input, [PreferredType]). - */ -extern JS_PUBLIC_API(bool) -ToPrimitive(JSContext* cx, JS::HandleObject obj, JSType hint, JS::MutableHandleValue vp); - -/** - * If args.get(0) is one of the strings "string", "number", or "default", set - * *result to JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_VOID accordingly and - * return true. Otherwise, return false with a TypeError pending. - * - * This can be useful in implementing a @@toPrimitive method. - */ -extern JS_PUBLIC_API(bool) -GetFirstArgumentAsTypeHint(JSContext* cx, CallArgs args, JSType *result); - -} /* namespace JS */ - -extern JS_PUBLIC_API(bool) -JS_PropertyStub(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_StrictPropertyStub(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp, JS::ObjectOpResult& result); - -template -struct JSConstScalarSpec { - const char* name; - T val; -}; - -typedef JSConstScalarSpec JSConstDoubleSpec; -typedef JSConstScalarSpec JSConstIntegerSpec; - -struct JSJitInfo; - -/** - * Wrapper to relace JSNative for JSPropertySpecs and JSFunctionSpecs. This will - * allow us to pass one JSJitInfo per function with the property/function spec, - * without additional field overhead. - */ -typedef struct JSNativeWrapper { - JSNative op; - const JSJitInfo* info; -} JSNativeWrapper; - -/* - * Macro static initializers which make it easy to pass no JSJitInfo as part of a - * JSPropertySpec or JSFunctionSpec. - */ -#define JSNATIVE_WRAPPER(native) { {native, nullptr} } - -/** - * Description of a property. JS_DefineProperties and JS_InitClass take arrays - * of these and define many properties at once. JS_PSG, JS_PSGS and JS_PS_END - * are helper macros for defining such arrays. - */ -struct JSPropertySpec { - struct SelfHostedWrapper { - void* unused; - const char* funname; - }; - - struct ValueWrapper { - uintptr_t type; - union { - const char* string; - int32_t int32; - }; - }; - - const char* name; - uint8_t flags; - union { - struct { - union { - JSNativeWrapper native; - SelfHostedWrapper selfHosted; - } getter; - union { - JSNativeWrapper native; - SelfHostedWrapper selfHosted; - } setter; - } accessors; - ValueWrapper value; - }; - - bool isAccessor() const { - return !(flags & JSPROP_INTERNAL_USE_BIT); - } - bool getValue(JSContext* cx, JS::MutableHandleValue value) const; - - bool isSelfHosted() const { - MOZ_ASSERT(isAccessor()); - -#ifdef DEBUG - // Verify that our accessors match our JSPROP_GETTER flag. - if (flags & JSPROP_GETTER) - checkAccessorsAreSelfHosted(); - else - checkAccessorsAreNative(); -#endif - return (flags & JSPROP_GETTER); - } - - static_assert(sizeof(SelfHostedWrapper) == sizeof(JSNativeWrapper), - "JSPropertySpec::getter/setter must be compact"); - static_assert(offsetof(SelfHostedWrapper, funname) == offsetof(JSNativeWrapper, info), - "JS_SELF_HOSTED* macros below require that " - "SelfHostedWrapper::funname overlay " - "JSNativeWrapper::info"); -private: - void checkAccessorsAreNative() const { - MOZ_ASSERT(accessors.getter.native.op); - // We may not have a setter at all. So all we can assert here, for the - // native case is that if we have a jitinfo for the setter then we have - // a setter op too. This is good enough to make sure we don't have a - // SelfHostedWrapper for the setter. - MOZ_ASSERT_IF(accessors.setter.native.info, accessors.setter.native.op); - } - - void checkAccessorsAreSelfHosted() const { - MOZ_ASSERT(!accessors.getter.selfHosted.unused); - MOZ_ASSERT(!accessors.setter.selfHosted.unused); - } -}; - -namespace JS { -namespace detail { - -/* NEVER DEFINED, DON'T USE. For use by JS_CAST_NATIVE_TO only. */ -inline int CheckIsNative(JSNative native); - -/* NEVER DEFINED, DON'T USE. For use by JS_CAST_STRING_TO only. */ -template -inline int -CheckIsCharacterLiteral(const char (&arr)[N]); - -/* NEVER DEFINED, DON'T USE. For use by JS_CAST_INT32_TO only. */ -inline int CheckIsInt32(int32_t value); - -/* NEVER DEFINED, DON'T USE. For use by JS_PROPERTYOP_GETTER only. */ -inline int CheckIsGetterOp(JSGetterOp op); - -/* NEVER DEFINED, DON'T USE. For use by JS_PROPERTYOP_SETTER only. */ -inline int CheckIsSetterOp(JSSetterOp op); - -} // namespace detail -} // namespace JS - -#define JS_CAST_NATIVE_TO(v, To) \ - (static_cast(sizeof(JS::detail::CheckIsNative(v))), \ - reinterpret_cast(v)) - -#define JS_CAST_STRING_TO(s, To) \ - (static_cast(sizeof(JS::detail::CheckIsCharacterLiteral(s))), \ - reinterpret_cast(s)) - -#define JS_CAST_INT32_TO(s, To) \ - (static_cast(sizeof(JS::detail::CheckIsInt32(s))), \ - reinterpret_cast(s)) - -#define JS_CHECK_ACCESSOR_FLAGS(flags) \ - (static_cast::Type>(0), \ - (flags)) - -#define JS_PROPERTYOP_GETTER(v) \ - (static_cast(sizeof(JS::detail::CheckIsGetterOp(v))), \ - reinterpret_cast(v)) - -#define JS_PROPERTYOP_SETTER(v) \ - (static_cast(sizeof(JS::detail::CheckIsSetterOp(v))), \ - reinterpret_cast(v)) - -#define JS_STUBGETTER JS_PROPERTYOP_GETTER(JS_PropertyStub) - -#define JS_STUBSETTER JS_PROPERTYOP_SETTER(JS_StrictPropertyStub) - -#define JS_PS_ACCESSOR_SPEC(name, getter, setter, flags, extraFlags) \ - { name, uint8_t(JS_CHECK_ACCESSOR_FLAGS(flags) | extraFlags), \ - { { getter, setter } } } -#define JS_PS_VALUE_SPEC(name, value, flags) \ - { name, uint8_t(flags | JSPROP_INTERNAL_USE_BIT), \ - { { value, JSNATIVE_WRAPPER(nullptr) } } } - -#define SELFHOSTED_WRAPPER(name) \ - { { nullptr, JS_CAST_STRING_TO(name, const JSJitInfo*) } } -#define STRINGVALUE_WRAPPER(value) \ - { { reinterpret_cast(JSVAL_TYPE_STRING), JS_CAST_STRING_TO(value, const JSJitInfo*) } } -#define INT32VALUE_WRAPPER(value) \ - { { reinterpret_cast(JSVAL_TYPE_INT32), JS_CAST_INT32_TO(value, const JSJitInfo*) } } - -/* - * JSPropertySpec uses JSNativeWrapper. These macros encapsulate the definition - * of JSNative-backed JSPropertySpecs, by defining the JSNativeWrappers for - * them. - */ -#define JS_PSG(name, getter, flags) \ - JS_PS_ACCESSOR_SPEC(name, JSNATIVE_WRAPPER(getter), JSNATIVE_WRAPPER(nullptr), flags, \ - JSPROP_SHARED) -#define JS_PSGS(name, getter, setter, flags) \ - JS_PS_ACCESSOR_SPEC(name, JSNATIVE_WRAPPER(getter), JSNATIVE_WRAPPER(setter), flags, \ - JSPROP_SHARED) -#define JS_SELF_HOSTED_GET(name, getterName, flags) \ - JS_PS_ACCESSOR_SPEC(name, SELFHOSTED_WRAPPER(getterName), JSNATIVE_WRAPPER(nullptr), flags, \ - JSPROP_SHARED | JSPROP_GETTER) -#define JS_SELF_HOSTED_GETSET(name, getterName, setterName, flags) \ - JS_PS_ACCESSOR_SPEC(name, SELFHOSTED_WRAPPER(getterName), SELFHOSTED_WRAPPER(setterName), \ - flags, JSPROP_SHARED | JSPROP_GETTER | JSPROP_SETTER) -#define JS_SELF_HOSTED_SYM_GET(symbol, getterName, flags) \ - JS_PS_ACCESSOR_SPEC(reinterpret_cast(uint32_t(::JS::SymbolCode::symbol) + 1), \ - SELFHOSTED_WRAPPER(getterName), JSNATIVE_WRAPPER(nullptr), flags, \ - JSPROP_SHARED | JSPROP_GETTER) -#define JS_STRING_PS(name, string, flags) \ - JS_PS_VALUE_SPEC(name, STRINGVALUE_WRAPPER(string), flags) -#define JS_STRING_SYM_PS(symbol, string, flags) \ - JS_PS_VALUE_SPEC(reinterpret_cast(uint32_t(::JS::SymbolCode::symbol) + 1), \ - STRINGVALUE_WRAPPER(string), flags) -#define JS_INT32_PS(name, value, flags) \ - JS_PS_VALUE_SPEC(name, INT32VALUE_WRAPPER(value), flags) -#define JS_PS_END \ - JS_PS_ACCESSOR_SPEC(nullptr, JSNATIVE_WRAPPER(nullptr), JSNATIVE_WRAPPER(nullptr), 0, 0) - -/** - * To define a native function, set call to a JSNativeWrapper. To define a - * self-hosted function, set selfHostedName to the name of a function - * compiled during JSRuntime::initSelfHosting. - */ -struct JSFunctionSpec { - const char* name; - JSNativeWrapper call; - uint16_t nargs; - uint16_t flags; - const char* selfHostedName; -}; - -/* - * Terminating sentinel initializer to put at the end of a JSFunctionSpec array - * that's passed to JS_DefineFunctions or JS_InitClass. - */ -#define JS_FS_END JS_FS(nullptr,nullptr,0,0) - -/* - * Initializer macros for a JSFunctionSpec array element. JS_FN (whose name pays - * homage to the old JSNative/JSFastNative split) simply adds the flag - * JSFUN_STUB_GSOPS. JS_FNINFO allows the simple adding of - * JSJitInfos. JS_SELF_HOSTED_FN declares a self-hosted function. - * JS_INLINABLE_FN allows specifying an InlinableNative enum value for natives - * inlined or specialized by the JIT. Finally JS_FNSPEC has slots for all the - * fields. - * - * The _SYM variants allow defining a function with a symbol key rather than a - * string key. For example, use JS_SYM_FN(iterator, ...) to define an - * @@iterator method. - */ -#define JS_FS(name,call,nargs,flags) \ - JS_FNSPEC(name, call, nullptr, nargs, flags, nullptr) -#define JS_FN(name,call,nargs,flags) \ - JS_FNSPEC(name, call, nullptr, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr) -#define JS_INLINABLE_FN(name,call,nargs,flags,native) \ - JS_FNSPEC(name, call, &js::jit::JitInfo_##native, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr) -#define JS_SYM_FN(symbol,call,nargs,flags) \ - JS_SYM_FNSPEC(symbol, call, nullptr, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr) -#define JS_FNINFO(name,call,info,nargs,flags) \ - JS_FNSPEC(name, call, info, nargs, flags, nullptr) -#define JS_SELF_HOSTED_FN(name,selfHostedName,nargs,flags) \ - JS_FNSPEC(name, nullptr, nullptr, nargs, flags, selfHostedName) -#define JS_SELF_HOSTED_SYM_FN(symbol, selfHostedName, nargs, flags) \ - JS_SYM_FNSPEC(symbol, nullptr, nullptr, nargs, flags, selfHostedName) -#define JS_SYM_FNSPEC(symbol, call, info, nargs, flags, selfHostedName) \ - JS_FNSPEC(reinterpret_cast( \ - uint32_t(::JS::SymbolCode::symbol) + 1), \ - call, info, nargs, flags, selfHostedName) -#define JS_FNSPEC(name,call,info,nargs,flags,selfHostedName) \ - {name, {call, info}, nargs, flags, selfHostedName} - -extern JS_PUBLIC_API(JSObject*) -JS_InitClass(JSContext* cx, JS::HandleObject obj, JS::HandleObject parent_proto, - const JSClass* clasp, JSNative constructor, unsigned nargs, - const JSPropertySpec* ps, const JSFunctionSpec* fs, - const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs); - -/** - * Set up ctor.prototype = proto and proto.constructor = ctor with the - * right property flags. - */ -extern JS_PUBLIC_API(bool) -JS_LinkConstructorAndPrototype(JSContext* cx, JS::Handle ctor, - JS::Handle proto); - -extern JS_PUBLIC_API(const JSClass*) -JS_GetClass(JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_InstanceOf(JSContext* cx, JS::Handle obj, const JSClass* clasp, JS::CallArgs* args); - -extern JS_PUBLIC_API(bool) -JS_HasInstance(JSContext* cx, JS::Handle obj, JS::Handle v, bool* bp); - -namespace JS { - -// Implementation of -// http://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance. If -// you're looking for the equivalent of "instanceof", you want JS_HasInstance, -// not this function. -extern JS_PUBLIC_API(bool) -OrdinaryHasInstance(JSContext* cx, HandleObject objArg, HandleValue v, bool* bp); - -} // namespace JS - -extern JS_PUBLIC_API(void*) -JS_GetPrivate(JSObject* obj); - -extern JS_PUBLIC_API(void) -JS_SetPrivate(JSObject* obj, void* data); - -extern JS_PUBLIC_API(void*) -JS_GetInstancePrivate(JSContext* cx, JS::Handle obj, const JSClass* clasp, - JS::CallArgs* args); - -extern JS_PUBLIC_API(JSObject*) -JS_GetConstructor(JSContext* cx, JS::Handle proto); - -namespace JS { - -enum ZoneSpecifier { - FreshZone = 0, - SystemZone = 1 -}; - -/** - * CompartmentCreationOptions specifies options relevant to creating a new - * compartment, that are either immutable characteristics of that compartment - * or that are discarded after the compartment has been created. - * - * Access to these options on an existing compartment is read-only: if you - * need particular selections, make them before you create the compartment. - */ -class JS_PUBLIC_API(CompartmentCreationOptions) -{ - public: - CompartmentCreationOptions() - : addonId_(nullptr), - traceGlobal_(nullptr), - invisibleToDebugger_(false), - mergeable_(false), - preserveJitCode_(false), - cloneSingletons_(false), - sharedMemoryAndAtomics_(false), - secureContext_(false) - { - zone_.spec = JS::FreshZone; - } - - // A null add-on ID means that the compartment is not associated with an - // add-on. - JSAddonId* addonIdOrNull() const { return addonId_; } - CompartmentCreationOptions& setAddonId(JSAddonId* id) { - addonId_ = id; - return *this; - } - - JSTraceOp getTrace() const { - return traceGlobal_; - } - CompartmentCreationOptions& setTrace(JSTraceOp op) { - traceGlobal_ = op; - return *this; - } - - void* zonePointer() const { - MOZ_ASSERT(uintptr_t(zone_.pointer) > uintptr_t(JS::SystemZone)); - return zone_.pointer; - } - ZoneSpecifier zoneSpecifier() const { return zone_.spec; } - CompartmentCreationOptions& setZone(ZoneSpecifier spec); - CompartmentCreationOptions& setSameZoneAs(JSObject* obj); - - // Certain scopes (i.e. XBL compilation scopes) are implementation details - // of the embedding, and references to them should never leak out to script. - // This flag causes the this compartment to skip firing onNewGlobalObject - // and makes addDebuggee a no-op for this global. - bool invisibleToDebugger() const { return invisibleToDebugger_; } - CompartmentCreationOptions& setInvisibleToDebugger(bool flag) { - invisibleToDebugger_ = flag; - return *this; - } - - // Compartments used for off-thread compilation have their contents merged - // into a target compartment when the compilation is finished. This is only - // allowed if this flag is set. The invisibleToDebugger flag must also be - // set for such compartments. - bool mergeable() const { return mergeable_; } - CompartmentCreationOptions& setMergeable(bool flag) { - mergeable_ = flag; - return *this; - } - - // Determines whether this compartment should preserve JIT code on - // non-shrinking GCs. - bool preserveJitCode() const { return preserveJitCode_; } - CompartmentCreationOptions& setPreserveJitCode(bool flag) { - preserveJitCode_ = flag; - return *this; - } - - bool cloneSingletons() const { return cloneSingletons_; } - CompartmentCreationOptions& setCloneSingletons(bool flag) { - cloneSingletons_ = flag; - return *this; - } - - bool getSharedMemoryAndAtomicsEnabled() const; - CompartmentCreationOptions& setSharedMemoryAndAtomicsEnabled(bool flag); - - // This flag doesn't affect JS engine behavior. It is used by Gecko to - // mark whether content windows and workers are "Secure Context"s. See - // https://w3c.github.io/webappsec-secure-contexts/ - // https://bugzilla.mozilla.org/show_bug.cgi?id=1162772#c34 - bool secureContext() const { return secureContext_; } - CompartmentCreationOptions& setSecureContext(bool flag) { - secureContext_ = flag; - return *this; - } - - private: - JSAddonId* addonId_; - JSTraceOp traceGlobal_; - union { - ZoneSpecifier spec; - void* pointer; // js::Zone* is not exposed in the API. - } zone_; - bool invisibleToDebugger_; - bool mergeable_; - bool preserveJitCode_; - bool cloneSingletons_; - bool sharedMemoryAndAtomics_; - bool secureContext_; -}; - -/** - * CompartmentBehaviors specifies behaviors of a compartment that can be - * changed after the compartment's been created. - */ -class JS_PUBLIC_API(CompartmentBehaviors) -{ - public: - class Override { - public: - Override() : mode_(Default) {} - - bool get(bool defaultValue) const { - if (mode_ == Default) - return defaultValue; - return mode_ == ForceTrue; - } - - void set(bool overrideValue) { - mode_ = overrideValue ? ForceTrue : ForceFalse; - } - - void reset() { - mode_ = Default; - } - - private: - enum Mode { - Default, - ForceTrue, - ForceFalse - }; - - Mode mode_; - }; - - CompartmentBehaviors() - : version_(JSVERSION_UNKNOWN) - , discardSource_(false) - , disableLazyParsing_(false) - , singletonsAsTemplates_(true) - { - } - - JSVersion version() const { return version_; } - CompartmentBehaviors& setVersion(JSVersion aVersion) { - MOZ_ASSERT(aVersion != JSVERSION_UNKNOWN); - version_ = aVersion; - return *this; - } - - // For certain globals, we know enough about the code that will run in them - // that we can discard script source entirely. - bool discardSource() const { return discardSource_; } - CompartmentBehaviors& setDiscardSource(bool flag) { - discardSource_ = flag; - return *this; - } - - bool disableLazyParsing() const { return disableLazyParsing_; } - CompartmentBehaviors& setDisableLazyParsing(bool flag) { - disableLazyParsing_ = flag; - return *this; - } - - bool extraWarnings(JSContext* cx) const; - Override& extraWarningsOverride() { return extraWarningsOverride_; } - - bool getSingletonsAsTemplates() const { - return singletonsAsTemplates_; - } - CompartmentBehaviors& setSingletonsAsValues() { - singletonsAsTemplates_ = false; - return *this; - } - - private: - JSVersion version_; - bool discardSource_; - bool disableLazyParsing_; - Override extraWarningsOverride_; - - // To XDR singletons, we need to ensure that all singletons are all used as - // templates, by making JSOP_OBJECT return a clone of the JSScript - // singleton, instead of returning the value which is baked in the JSScript. - bool singletonsAsTemplates_; -}; - -/** - * CompartmentOptions specifies compartment characteristics: both those that - * can't be changed on a compartment once it's been created - * (CompartmentCreationOptions), and those that can be changed on an existing - * compartment (CompartmentBehaviors). - */ -class JS_PUBLIC_API(CompartmentOptions) -{ - public: - explicit CompartmentOptions() - : creationOptions_(), - behaviors_() - {} - - CompartmentOptions(const CompartmentCreationOptions& compartmentCreation, - const CompartmentBehaviors& compartmentBehaviors) - : creationOptions_(compartmentCreation), - behaviors_(compartmentBehaviors) - {} - - // CompartmentCreationOptions specify fundamental compartment - // characteristics that must be specified when the compartment is created, - // that can't be changed after the compartment is created. - CompartmentCreationOptions& creationOptions() { - return creationOptions_; - } - const CompartmentCreationOptions& creationOptions() const { - return creationOptions_; - } - - // CompartmentBehaviors specify compartment characteristics that can be - // changed after the compartment is created. - CompartmentBehaviors& behaviors() { - return behaviors_; - } - const CompartmentBehaviors& behaviors() const { - return behaviors_; - } - - private: - CompartmentCreationOptions creationOptions_; - CompartmentBehaviors behaviors_; -}; - -JS_PUBLIC_API(const CompartmentCreationOptions&) -CompartmentCreationOptionsRef(JSCompartment* compartment); - -JS_PUBLIC_API(const CompartmentCreationOptions&) -CompartmentCreationOptionsRef(JSObject* obj); - -JS_PUBLIC_API(const CompartmentCreationOptions&) -CompartmentCreationOptionsRef(JSContext* cx); - -JS_PUBLIC_API(CompartmentBehaviors&) -CompartmentBehaviorsRef(JSCompartment* compartment); - -JS_PUBLIC_API(CompartmentBehaviors&) -CompartmentBehaviorsRef(JSObject* obj); - -JS_PUBLIC_API(CompartmentBehaviors&) -CompartmentBehaviorsRef(JSContext* cx); - -/** - * During global creation, we fire notifications to callbacks registered - * via the Debugger API. These callbacks are arbitrary script, and can touch - * the global in arbitrary ways. When that happens, the global should not be - * in a half-baked state. But this creates a problem for consumers that need - * to set slots on the global to put it in a consistent state. - * - * This API provides a way for consumers to set slots atomically (immediately - * after the global is created), before any debugger hooks are fired. It's - * unfortunately on the clunky side, but that's the way the cookie crumbles. - * - * If callers have no additional state on the global to set up, they may pass - * |FireOnNewGlobalHook| to JS_NewGlobalObject, which causes that function to - * fire the hook as its final act before returning. Otherwise, callers should - * pass |DontFireOnNewGlobalHook|, which means that they are responsible for - * invoking JS_FireOnNewGlobalObject upon successfully creating the global. If - * an error occurs and the operation aborts, callers should skip firing the - * hook. But otherwise, callers must take care to fire the hook exactly once - * before compiling any script in the global's scope (we have assertions in - * place to enforce this). This lets us be sure that debugger clients never miss - * breakpoints. - */ -enum OnNewGlobalHookOption { - FireOnNewGlobalHook, - DontFireOnNewGlobalHook -}; - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSObject*) -JS_NewGlobalObject(JSContext* cx, const JSClass* clasp, JSPrincipals* principals, - JS::OnNewGlobalHookOption hookOption, - const JS::CompartmentOptions& options); -/** - * Spidermonkey does not have a good way of keeping track of what compartments should be marked on - * their own. We can mark the roots unconditionally, but marking GC things only relevant in live - * compartments is hard. To mitigate this, we create a static trace hook, installed on each global - * object, from which we can be sure the compartment is relevant, and mark it. - * - * It is still possible to specify custom trace hooks for global object classes. They can be - * provided via the CompartmentOptions passed to JS_NewGlobalObject. - */ -extern JS_PUBLIC_API(void) -JS_GlobalObjectTraceHook(JSTracer* trc, JSObject* global); - -extern JS_PUBLIC_API(void) -JS_FireOnNewGlobalObject(JSContext* cx, JS::HandleObject global); - -extern JS_PUBLIC_API(JSObject*) -JS_NewObject(JSContext* cx, const JSClass* clasp); - -extern JS_PUBLIC_API(bool) -JS_IsNative(JSObject* obj); - -/** - * Unlike JS_NewObject, JS_NewObjectWithGivenProto does not compute a default - * proto. If proto is nullptr, the JS object will have `null` as [[Prototype]]. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewObjectWithGivenProto(JSContext* cx, const JSClass* clasp, JS::Handle proto); - -/** Creates a new plain object, like `new Object()`, with Object.prototype as [[Prototype]]. */ -extern JS_PUBLIC_API(JSObject*) -JS_NewPlainObject(JSContext* cx); - -/** - * Freeze obj, and all objects it refers to, recursively. This will not recurse - * through non-extensible objects, on the assumption that those are already - * deep-frozen. - */ -extern JS_PUBLIC_API(bool) -JS_DeepFreezeObject(JSContext* cx, JS::Handle obj); - -/** - * Freezes an object; see ES5's Object.freeze(obj) method. - */ -extern JS_PUBLIC_API(bool) -JS_FreezeObject(JSContext* cx, JS::Handle obj); - - -/*** Property descriptors ************************************************************************/ - -namespace JS { - -struct JS_PUBLIC_API(PropertyDescriptor) { - JSObject* obj; - unsigned attrs; - JSGetterOp getter; - JSSetterOp setter; - JS::Value value; - - PropertyDescriptor() - : obj(nullptr), attrs(0), getter(nullptr), setter(nullptr), value(JS::UndefinedValue()) - {} - - static void trace(PropertyDescriptor* self, JSTracer* trc) { self->trace(trc); } - void trace(JSTracer* trc); -}; - -template -class PropertyDescriptorOperations -{ - const PropertyDescriptor& desc() const { return static_cast(this)->get(); } - - bool has(unsigned bit) const { - MOZ_ASSERT(bit != 0); - MOZ_ASSERT((bit & (bit - 1)) == 0); // only a single bit - return (desc().attrs & bit) != 0; - } - - bool hasAny(unsigned bits) const { - return (desc().attrs & bits) != 0; - } - - bool hasAll(unsigned bits) const { - return (desc().attrs & bits) == bits; - } - - // Non-API attributes bit used internally for arguments objects. - enum { SHADOWABLE = JSPROP_INTERNAL_USE_BIT }; - - public: - // Descriptors with JSGetterOp/JSSetterOp are considered data - // descriptors. It's complicated. - bool isAccessorDescriptor() const { return hasAny(JSPROP_GETTER | JSPROP_SETTER); } - bool isGenericDescriptor() const { - return (desc().attrs& - (JSPROP_GETTER | JSPROP_SETTER | JSPROP_IGNORE_READONLY | JSPROP_IGNORE_VALUE)) == - (JSPROP_IGNORE_READONLY | JSPROP_IGNORE_VALUE); - } - bool isDataDescriptor() const { return !isAccessorDescriptor() && !isGenericDescriptor(); } - - bool hasConfigurable() const { return !has(JSPROP_IGNORE_PERMANENT); } - bool configurable() const { MOZ_ASSERT(hasConfigurable()); return !has(JSPROP_PERMANENT); } - - bool hasEnumerable() const { return !has(JSPROP_IGNORE_ENUMERATE); } - bool enumerable() const { MOZ_ASSERT(hasEnumerable()); return has(JSPROP_ENUMERATE); } - - bool hasValue() const { return !isAccessorDescriptor() && !has(JSPROP_IGNORE_VALUE); } - JS::HandleValue value() const { - return JS::HandleValue::fromMarkedLocation(&desc().value); - } - - bool hasWritable() const { return !isAccessorDescriptor() && !has(JSPROP_IGNORE_READONLY); } - bool writable() const { MOZ_ASSERT(hasWritable()); return !has(JSPROP_READONLY); } - - bool hasGetterObject() const { return has(JSPROP_GETTER); } - JS::HandleObject getterObject() const { - MOZ_ASSERT(hasGetterObject()); - return JS::HandleObject::fromMarkedLocation( - reinterpret_cast(&desc().getter)); - } - bool hasSetterObject() const { return has(JSPROP_SETTER); } - JS::HandleObject setterObject() const { - MOZ_ASSERT(hasSetterObject()); - return JS::HandleObject::fromMarkedLocation( - reinterpret_cast(&desc().setter)); - } - - bool hasGetterOrSetter() const { return desc().getter || desc().setter; } - bool isShared() const { return has(JSPROP_SHARED); } - - JS::HandleObject object() const { - return JS::HandleObject::fromMarkedLocation(&desc().obj); - } - unsigned attributes() const { return desc().attrs; } - JSGetterOp getter() const { return desc().getter; } - JSSetterOp setter() const { return desc().setter; } - - void assertValid() const { -#ifdef DEBUG - MOZ_ASSERT((attributes() & ~(JSPROP_ENUMERATE | JSPROP_IGNORE_ENUMERATE | - JSPROP_PERMANENT | JSPROP_IGNORE_PERMANENT | - JSPROP_READONLY | JSPROP_IGNORE_READONLY | - JSPROP_IGNORE_VALUE | - JSPROP_GETTER | - JSPROP_SETTER | - JSPROP_SHARED | - JSPROP_REDEFINE_NONCONFIGURABLE | - JSPROP_RESOLVING | - SHADOWABLE)) == 0); - MOZ_ASSERT(!hasAll(JSPROP_IGNORE_ENUMERATE | JSPROP_ENUMERATE)); - MOZ_ASSERT(!hasAll(JSPROP_IGNORE_PERMANENT | JSPROP_PERMANENT)); - if (isAccessorDescriptor()) { - MOZ_ASSERT(has(JSPROP_SHARED)); - MOZ_ASSERT(!has(JSPROP_READONLY)); - MOZ_ASSERT(!has(JSPROP_IGNORE_READONLY)); - MOZ_ASSERT(!has(JSPROP_IGNORE_VALUE)); - MOZ_ASSERT(!has(SHADOWABLE)); - MOZ_ASSERT(value().isUndefined()); - MOZ_ASSERT_IF(!has(JSPROP_GETTER), !getter()); - MOZ_ASSERT_IF(!has(JSPROP_SETTER), !setter()); - } else { - MOZ_ASSERT(!hasAll(JSPROP_IGNORE_READONLY | JSPROP_READONLY)); - MOZ_ASSERT_IF(has(JSPROP_IGNORE_VALUE), value().isUndefined()); - } - MOZ_ASSERT(getter() != JS_PropertyStub); - MOZ_ASSERT(setter() != JS_StrictPropertyStub); - - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_ENUMERATE)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_PERMANENT)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_READONLY)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_VALUE)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_REDEFINE_NONCONFIGURABLE)); -#endif - } - - void assertComplete() const { -#ifdef DEBUG - assertValid(); - MOZ_ASSERT((attributes() & ~(JSPROP_ENUMERATE | - JSPROP_PERMANENT | - JSPROP_READONLY | - JSPROP_GETTER | - JSPROP_SETTER | - JSPROP_SHARED | - JSPROP_REDEFINE_NONCONFIGURABLE | - JSPROP_RESOLVING | - SHADOWABLE)) == 0); - MOZ_ASSERT_IF(isAccessorDescriptor(), has(JSPROP_GETTER) && has(JSPROP_SETTER)); -#endif - } - - void assertCompleteIfFound() const { -#ifdef DEBUG - if (object()) - assertComplete(); -#endif - } -}; - -template -class MutablePropertyDescriptorOperations : public PropertyDescriptorOperations -{ - PropertyDescriptor& desc() { return static_cast(this)->get(); } - - public: - void clear() { - object().set(nullptr); - setAttributes(0); - setGetter(nullptr); - setSetter(nullptr); - value().setUndefined(); - } - - void initFields(HandleObject obj, HandleValue v, unsigned attrs, - JSGetterOp getterOp, JSSetterOp setterOp) { - MOZ_ASSERT(getterOp != JS_PropertyStub); - MOZ_ASSERT(setterOp != JS_StrictPropertyStub); - - object().set(obj); - value().set(v); - setAttributes(attrs); - setGetter(getterOp); - setSetter(setterOp); - } - - void assign(PropertyDescriptor& other) { - object().set(other.obj); - setAttributes(other.attrs); - setGetter(other.getter); - setSetter(other.setter); - value().set(other.value); - } - - void setDataDescriptor(HandleValue v, unsigned attrs) { - MOZ_ASSERT((attrs & ~(JSPROP_ENUMERATE | - JSPROP_PERMANENT | - JSPROP_READONLY | - JSPROP_IGNORE_ENUMERATE | - JSPROP_IGNORE_PERMANENT | - JSPROP_IGNORE_READONLY)) == 0); - object().set(nullptr); - setAttributes(attrs); - setGetter(nullptr); - setSetter(nullptr); - value().set(v); - } - - JS::MutableHandleObject object() { - return JS::MutableHandleObject::fromMarkedLocation(&desc().obj); - } - unsigned& attributesRef() { return desc().attrs; } - JSGetterOp& getter() { return desc().getter; } - JSSetterOp& setter() { return desc().setter; } - JS::MutableHandleValue value() { - return JS::MutableHandleValue::fromMarkedLocation(&desc().value); - } - void setValue(JS::HandleValue v) { - MOZ_ASSERT(!(desc().attrs & (JSPROP_GETTER | JSPROP_SETTER))); - attributesRef() &= ~JSPROP_IGNORE_VALUE; - value().set(v); - } - - void setConfigurable(bool configurable) { - setAttributes((desc().attrs & ~(JSPROP_IGNORE_PERMANENT | JSPROP_PERMANENT)) | - (configurable ? 0 : JSPROP_PERMANENT)); - } - void setEnumerable(bool enumerable) { - setAttributes((desc().attrs & ~(JSPROP_IGNORE_ENUMERATE | JSPROP_ENUMERATE)) | - (enumerable ? JSPROP_ENUMERATE : 0)); - } - void setWritable(bool writable) { - MOZ_ASSERT(!(desc().attrs & (JSPROP_GETTER | JSPROP_SETTER))); - setAttributes((desc().attrs & ~(JSPROP_IGNORE_READONLY | JSPROP_READONLY)) | - (writable ? 0 : JSPROP_READONLY)); - } - void setAttributes(unsigned attrs) { desc().attrs = attrs; } - - void setGetter(JSGetterOp op) { - MOZ_ASSERT(op != JS_PropertyStub); - desc().getter = op; - } - void setSetter(JSSetterOp op) { - MOZ_ASSERT(op != JS_StrictPropertyStub); - desc().setter = op; - } - void setGetterObject(JSObject* obj) { - desc().getter = reinterpret_cast(obj); - desc().attrs &= ~(JSPROP_IGNORE_VALUE | JSPROP_IGNORE_READONLY | JSPROP_READONLY); - desc().attrs |= JSPROP_GETTER | JSPROP_SHARED; - } - void setSetterObject(JSObject* obj) { - desc().setter = reinterpret_cast(obj); - desc().attrs &= ~(JSPROP_IGNORE_VALUE | JSPROP_IGNORE_READONLY | JSPROP_READONLY); - desc().attrs |= JSPROP_SETTER | JSPROP_SHARED; - } - - JS::MutableHandleObject getterObject() { - MOZ_ASSERT(this->hasGetterObject()); - return JS::MutableHandleObject::fromMarkedLocation( - reinterpret_cast(&desc().getter)); - } - JS::MutableHandleObject setterObject() { - MOZ_ASSERT(this->hasSetterObject()); - return JS::MutableHandleObject::fromMarkedLocation( - reinterpret_cast(&desc().setter)); - } -}; - -} /* namespace JS */ - -namespace js { - -template <> -class RootedBase - : public JS::MutablePropertyDescriptorOperations> -{}; - -template <> -class HandleBase - : public JS::PropertyDescriptorOperations> -{}; - -template <> -class MutableHandleBase - : public JS::MutablePropertyDescriptorOperations> -{}; - -} /* namespace js */ - -namespace JS { - -extern JS_PUBLIC_API(bool) -ObjectToCompletePropertyDescriptor(JSContext* cx, - JS::HandleObject obj, - JS::HandleValue descriptor, - JS::MutableHandle desc); - -/* - * ES6 draft rev 32 (2015 Feb 2) 6.2.4.4 FromPropertyDescriptor(Desc). - * - * If desc.object() is null, then vp is set to undefined. - */ -extern JS_PUBLIC_API(bool) -FromPropertyDescriptor(JSContext* cx, - JS::Handle desc, - JS::MutableHandleValue vp); - -} // namespace JS - - -/*** Standard internal methods ******************************************************************** - * - * The functions below are the fundamental operations on objects. - * - * ES6 specifies 14 internal methods that define how objects behave. The - * standard is actually quite good on this topic, though you may have to read - * it a few times. See ES6 sections 6.1.7.2 and 6.1.7.3. - * - * When 'obj' is an ordinary object, these functions have boring standard - * behavior as specified by ES6 section 9.1; see the section about internal - * methods in js/src/vm/NativeObject.h. - * - * Proxies override the behavior of internal methods. So when 'obj' is a proxy, - * any one of the functions below could do just about anything. See - * js/public/Proxy.h. - */ - -/** - * Get the prototype of obj, storing it in result. - * - * Implements: ES6 [[GetPrototypeOf]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_GetPrototype(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject result); - -/** - * If |obj| (underneath any functionally-transparent wrapper proxies) has as - * its [[GetPrototypeOf]] trap the ordinary [[GetPrototypeOf]] behavior defined - * for ordinary objects, set |*isOrdinary = true| and store |obj|'s prototype - * in |result|. Otherwise set |*isOrdinary = false|. In case of error, both - * outparams have unspecified value. - */ -extern JS_PUBLIC_API(bool) -JS_GetPrototypeIfOrdinary(JSContext* cx, JS::HandleObject obj, bool* isOrdinary, - JS::MutableHandleObject result); - -/** - * Change the prototype of obj. - * - * Implements: ES6 [[SetPrototypeOf]] internal method. - * - * In cases where ES6 [[SetPrototypeOf]] returns false without an exception, - * JS_SetPrototype throws a TypeError and returns false. - * - * Performance warning: JS_SetPrototype is very bad for performance. It may - * cause compiled jit-code to be invalidated. It also causes not only obj but - * all other objects in the same "group" as obj to be permanently deoptimized. - * It's better to create the object with the right prototype from the start. - */ -extern JS_PUBLIC_API(bool) -JS_SetPrototype(JSContext* cx, JS::HandleObject obj, JS::HandleObject proto); - -/** - * Determine whether obj is extensible. Extensible objects can have new - * properties defined on them. Inextensible objects can't, and their - * [[Prototype]] slot is fixed as well. - * - * Implements: ES6 [[IsExtensible]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_IsExtensible(JSContext* cx, JS::HandleObject obj, bool* extensible); - -/** - * Attempt to make |obj| non-extensible. - * - * Not all failures are treated as errors. See the comment on - * JS::ObjectOpResult in js/public/Class.h. - * - * Implements: ES6 [[PreventExtensions]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_PreventExtensions(JSContext* cx, JS::HandleObject obj, JS::ObjectOpResult& result); - -/** - * Attempt to make the [[Prototype]] of |obj| immutable, such that any attempt - * to modify it will fail. If an error occurs during the attempt, return false - * (with a pending exception set, depending upon the nature of the error). If - * no error occurs, return true with |*succeeded| set to indicate whether the - * attempt successfully made the [[Prototype]] immutable. - * - * This is a nonstandard internal method. - */ -extern JS_PUBLIC_API(bool) -JS_SetImmutablePrototype(JSContext* cx, JS::HandleObject obj, bool* succeeded); - -/** - * Get a description of one of obj's own properties. If no such property exists - * on obj, return true with desc.object() set to null. - * - * Implements: ES6 [[GetOwnProperty]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_GetOwnPropertyDescriptorById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); - -extern JS_PUBLIC_API(bool) -JS_GetOwnPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char* name, - JS::MutableHandle desc); - -extern JS_PUBLIC_API(bool) -JS_GetOwnUCPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char16_t* name, - JS::MutableHandle desc); - -/** - * Like JS_GetOwnPropertyDescriptorById, but also searches the prototype chain - * if no own property is found directly on obj. The object on which the - * property is found is returned in desc.object(). If the property is not found - * on the prototype chain, this returns true with desc.object() set to null. - */ -extern JS_PUBLIC_API(bool) -JS_GetPropertyDescriptorById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); - -extern JS_PUBLIC_API(bool) -JS_GetPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char* name, - JS::MutableHandle desc); - -/** - * Define a property on obj. - * - * This function uses JS::ObjectOpResult to indicate conditions that ES6 - * specifies as non-error failures. This is inconvenient at best, so use this - * function only if you are implementing a proxy handler's defineProperty() - * method. For all other purposes, use one of the many DefineProperty functions - * below that throw an exception in all failure cases. - * - * Implements: ES6 [[DefineOwnProperty]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc, - JS::ObjectOpResult& result); - -/** - * Define a property on obj, throwing a TypeError if the attempt fails. - * This is the C++ equivalent of `Object.defineProperty(obj, id, desc)`. - */ -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleString value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, int32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, uint32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, double value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleValue value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleObject value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleString value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, int32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, uint32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, double value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::Handle desc, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::Handle desc); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleValue value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleObject value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleString value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - int32_t value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - uint32_t value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - double value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleValue value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleObject value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleString value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, int32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, uint32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, double value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -/** - * Compute the expression `id in obj`. - * - * If obj has an own or inherited property obj[id], set *foundp = true and - * return true. If not, set *foundp = false and return true. On error, return - * false with an exception pending. - * - * Implements: ES6 [[Has]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_HasPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_HasProperty(JSContext* cx, JS::HandleObject obj, const char* name, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_HasUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - bool* vp); - -extern JS_PUBLIC_API(bool) -JS_HasElement(JSContext* cx, JS::HandleObject obj, uint32_t index, bool* foundp); - -/** - * Determine whether obj has an own property with the key `id`. - * - * Implements: ES6 7.3.11 HasOwnProperty(O, P). - */ -extern JS_PUBLIC_API(bool) -JS_HasOwnPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_HasOwnProperty(JSContext* cx, JS::HandleObject obj, const char* name, bool* foundp); - -/** - * Get the value of the property `obj[id]`, or undefined if no such property - * exists. This is the C++ equivalent of `vp = Reflect.get(obj, id, receiver)`. - * - * Most callers don't need the `receiver` argument. Consider using - * JS_GetProperty instead. (But if you're implementing a proxy handler's set() - * method, it's often correct to call this function and pass the receiver - * through.) - * - * Implements: ES6 [[Get]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_ForwardGetPropertyTo(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::HandleValue receiver, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_ForwardGetElementTo(JSContext* cx, JS::HandleObject obj, uint32_t index, - JS::HandleObject receiver, JS::MutableHandleValue vp); - -/** - * Get the value of the property `obj[id]`, or undefined if no such property - * exists. The result is stored in vp. - * - * Implements: ES6 7.3.1 Get(O, P). - */ -extern JS_PUBLIC_API(bool) -JS_GetPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_GetProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_GetUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_GetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::MutableHandleValue vp); - -/** - * Perform the same property assignment as `Reflect.set(obj, id, v, receiver)`. - * - * This function has a `receiver` argument that most callers don't need. - * Consider using JS_SetProperty instead. - * - * Implements: ES6 [[Set]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_ForwardSetPropertyTo(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v, - JS::HandleValue receiver, JS::ObjectOpResult& result); - -/** - * Perform the assignment `obj[id] = v`. - * - * This function performs non-strict assignment, so if the property is - * read-only, nothing happens and no error is thrown. - */ -extern JS_PUBLIC_API(bool) -JS_SetPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleObject v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleString v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, int32_t v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, uint32_t v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, double v); - -/** - * Delete a property. This is the C++ equivalent of - * `result = Reflect.deleteProperty(obj, id)`. - * - * This function has a `result` out parameter that most callers don't need. - * Unless you can pass through an ObjectOpResult provided by your caller, it's - * probably best to use the JS_DeletePropertyById signature with just 3 - * arguments. - * - * Implements: ES6 [[Delete]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_DeletePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DeleteProperty(JSContext* cx, JS::HandleObject obj, const char* name, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DeleteUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DeleteElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::ObjectOpResult& result); - -/** - * Delete a property, ignoring strict failures. This is the C++ equivalent of - * the JS `delete obj[id]` in non-strict mode code. - */ -extern JS_PUBLIC_API(bool) -JS_DeletePropertyById(JSContext* cx, JS::HandleObject obj, jsid id); - -extern JS_PUBLIC_API(bool) -JS_DeleteProperty(JSContext* cx, JS::HandleObject obj, const char* name); - -extern JS_PUBLIC_API(bool) -JS_DeleteElement(JSContext* cx, JS::HandleObject obj, uint32_t index); - -/** - * Get an array of the non-symbol enumerable properties of obj. - * This function is roughly equivalent to: - * - * var result = []; - * for (key in obj) - * result.push(key); - * return result; - * - * This is the closest thing we currently have to the ES6 [[Enumerate]] - * internal method. - * - * The array of ids returned by JS_Enumerate must be rooted to protect its - * contents from garbage collection. Use JS::Rooted. - */ -extern JS_PUBLIC_API(bool) -JS_Enumerate(JSContext* cx, JS::HandleObject obj, JS::MutableHandle props); - -/* - * API for determining callability and constructability. [[Call]] and - * [[Construct]] are internal methods that aren't present on all objects, so it - * is useful to ask if they are there or not. The standard itself asks these - * questions routinely. - */ -namespace JS { - -/** - * Return true if the given object is callable. In ES6 terms, an object is - * callable if it has a [[Call]] internal method. - * - * Implements: ES6 7.2.3 IsCallable(argument). - * - * Functions are callable. A scripted proxy or wrapper is callable if its - * target is callable. Most other objects aren't callable. - */ -extern JS_PUBLIC_API(bool) -IsCallable(JSObject* obj); - -/** - * Return true if the given object is a constructor. In ES6 terms, an object is - * a constructor if it has a [[Construct]] internal method. The expression - * `new obj()` throws a TypeError if obj is not a constructor. - * - * Implements: ES6 7.2.4 IsConstructor(argument). - * - * JS functions and classes are constructors. Arrow functions and most builtin - * functions are not. A scripted proxy or wrapper is a constructor if its - * target is a constructor. - */ -extern JS_PUBLIC_API(bool) -IsConstructor(JSObject* obj); - -} /* namespace JS */ - -/** - * Call a function, passing a this-value and arguments. This is the C++ - * equivalent of `rval = Reflect.apply(fun, obj, args)`. - * - * Implements: ES6 7.3.12 Call(F, V, [argumentsList]). - * Use this function to invoke the [[Call]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_CallFunctionValue(JSContext* cx, JS::HandleObject obj, JS::HandleValue fval, - const JS::HandleValueArray& args, JS::MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -JS_CallFunction(JSContext* cx, JS::HandleObject obj, JS::HandleFunction fun, - const JS::HandleValueArray& args, JS::MutableHandleValue rval); - -/** - * Perform the method call `rval = obj[name](args)`. - */ -extern JS_PUBLIC_API(bool) -JS_CallFunctionName(JSContext* cx, JS::HandleObject obj, const char* name, - const JS::HandleValueArray& args, JS::MutableHandleValue rval); - -namespace JS { - -static inline bool -Call(JSContext* cx, JS::HandleObject thisObj, JS::HandleFunction fun, - const JS::HandleValueArray& args, MutableHandleValue rval) -{ - return !!JS_CallFunction(cx, thisObj, fun, args, rval); -} - -static inline bool -Call(JSContext* cx, JS::HandleObject thisObj, JS::HandleValue fun, const JS::HandleValueArray& args, - MutableHandleValue rval) -{ - return !!JS_CallFunctionValue(cx, thisObj, fun, args, rval); -} - -static inline bool -Call(JSContext* cx, JS::HandleObject thisObj, const char* name, const JS::HandleValueArray& args, - MutableHandleValue rval) -{ - return !!JS_CallFunctionName(cx, thisObj, name, args, rval); -} - -extern JS_PUBLIC_API(bool) -Call(JSContext* cx, JS::HandleValue thisv, JS::HandleValue fun, const JS::HandleValueArray& args, - MutableHandleValue rval); - -static inline bool -Call(JSContext* cx, JS::HandleValue thisv, JS::HandleObject funObj, const JS::HandleValueArray& args, - MutableHandleValue rval) -{ - MOZ_ASSERT(funObj); - JS::RootedValue fun(cx, JS::ObjectValue(*funObj)); - return Call(cx, thisv, fun, args, rval); -} - -/** - * Invoke a constructor. This is the C++ equivalent of - * `rval = Reflect.construct(fun, args, newTarget)`. - * - * JS::Construct() takes a `newTarget` argument that most callers don't need. - * Consider using the four-argument Construct signature instead. (But if you're - * implementing a subclass or a proxy handler's construct() method, this is the - * right function to call.) - * - * Implements: ES6 7.3.13 Construct(F, [argumentsList], [newTarget]). - * Use this function to invoke the [[Construct]] internal method. - */ -extern JS_PUBLIC_API(bool) -Construct(JSContext* cx, JS::HandleValue fun, HandleObject newTarget, - const JS::HandleValueArray &args, MutableHandleObject objp); - -/** - * Invoke a constructor. This is the C++ equivalent of - * `rval = new fun(...args)`. - * - * Implements: ES6 7.3.13 Construct(F, [argumentsList], [newTarget]), when - * newTarget is omitted. - */ -extern JS_PUBLIC_API(bool) -Construct(JSContext* cx, JS::HandleValue fun, const JS::HandleValueArray& args, - MutableHandleObject objp); - -} /* namespace JS */ - -/** - * Invoke a constructor, like the JS expression `new ctor(...args)`. Returns - * the new object, or null on error. - */ -extern JS_PUBLIC_API(JSObject*) -JS_New(JSContext* cx, JS::HandleObject ctor, const JS::HandleValueArray& args); - - -/*** Other property-defining functions ***********************************************************/ - -extern JS_PUBLIC_API(JSObject*) -JS_DefineObject(JSContext* cx, JS::HandleObject obj, const char* name, - const JSClass* clasp = nullptr, unsigned attrs = 0); - -extern JS_PUBLIC_API(bool) -JS_DefineConstDoubles(JSContext* cx, JS::HandleObject obj, const JSConstDoubleSpec* cds); - -extern JS_PUBLIC_API(bool) -JS_DefineConstIntegers(JSContext* cx, JS::HandleObject obj, const JSConstIntegerSpec* cis); - -extern JS_PUBLIC_API(bool) -JS_DefineProperties(JSContext* cx, JS::HandleObject obj, const JSPropertySpec* ps); - - -/* * */ - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnProperty(JSContext* cx, JS::HandleObject obj, const char* name, - bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, - size_t namelen, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnElement(JSContext* cx, JS::HandleObject obj, uint32_t index, bool* foundp); - -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayObject(JSContext* cx, const JS::HandleValueArray& contents); - -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayObject(JSContext* cx, size_t length); - -/** - * Returns true and sets |*isArray| indicating whether |value| is an Array - * object or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isArray == false| when passed a proxy whose - * target is an Array, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_IsArrayObject(JSContext* cx, JS::HandleValue value, bool* isArray); - -/** - * Returns true and sets |*isArray| indicating whether |obj| is an Array object - * or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isArray == false| when passed a proxy whose - * target is an Array, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_IsArrayObject(JSContext* cx, JS::HandleObject obj, bool* isArray); - -extern JS_PUBLIC_API(bool) -JS_GetArrayLength(JSContext* cx, JS::Handle obj, uint32_t* lengthp); - -extern JS_PUBLIC_API(bool) -JS_SetArrayLength(JSContext* cx, JS::Handle obj, uint32_t length); - -namespace JS { - -/** - * Returns true and sets |*isMap| indicating whether |obj| is an Map object - * or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isMap == false| when passed a proxy whose - * target is an Map, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -IsMapObject(JSContext* cx, JS::HandleObject obj, bool* isMap); - -/** - * Returns true and sets |*isSet| indicating whether |obj| is an Set object - * or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isSet == false| when passed a proxy whose - * target is an Set, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -IsSetObject(JSContext* cx, JS::HandleObject obj, bool* isSet); - -} /* namespace JS */ - -/** - * Assign 'undefined' to all of the object's non-reserved slots. Note: this is - * done for all slots, regardless of the associated property descriptor. - */ -JS_PUBLIC_API(void) -JS_SetAllNonReservedSlotsToUndefined(JSContext* cx, JSObject* objArg); - -/** - * Create a new array buffer with the given contents. It must be legal to pass - * these contents to free(). On success, the ownership is transferred to the - * new array buffer. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayBufferWithContents(JSContext* cx, size_t nbytes, void* contents); - -/** - * Create a new array buffer with the given contents. The array buffer does not take ownership of - * contents, and JS_DetachArrayBuffer must be called before the contents are disposed of. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayBufferWithExternalContents(JSContext* cx, size_t nbytes, void* contents); - -/** - * Steal the contents of the given array buffer. The array buffer has its - * length set to 0 and its contents array cleared. The caller takes ownership - * of the return value and must free it or transfer ownership via - * JS_NewArrayBufferWithContents when done using it. - */ -extern JS_PUBLIC_API(void*) -JS_StealArrayBufferContents(JSContext* cx, JS::HandleObject obj); - -/** - * Returns a pointer to the ArrayBuffer |obj|'s data. |obj| and its views will store and expose - * the data in the returned pointer: assigning into the returned pointer will affect values exposed - * by views of |obj| and vice versa. - * - * The caller must ultimately deallocate the returned pointer to avoid leaking. The memory is - * *not* garbage-collected with |obj|. These steps must be followed to deallocate: - * - * 1. The ArrayBuffer |obj| must be detached using JS_DetachArrayBuffer. - * 2. The returned pointer must be freed using JS_free. - * - * To perform step 1, callers *must* hold a reference to |obj| until they finish using the returned - * pointer. They *must not* attempt to let |obj| be GC'd, then JS_free the pointer. - * - * If |obj| isn't an ArrayBuffer, this function returns null and reports an error. - */ -extern JS_PUBLIC_API(void*) -JS_ExternalizeArrayBufferContents(JSContext* cx, JS::HandleObject obj); - -/** - * Create a new mapped array buffer with the given memory mapped contents. It - * must be legal to free the contents pointer by unmapping it. On success, - * ownership is transferred to the new mapped array buffer. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewMappedArrayBufferWithContents(JSContext* cx, size_t nbytes, void* contents); - -/** - * Create memory mapped array buffer contents. - * Caller must take care of closing fd after calling this function. - */ -extern JS_PUBLIC_API(void*) -JS_CreateMappedArrayBufferContents(int fd, size_t offset, size_t length); - -/** - * Release the allocated resource of mapped array buffer contents before the - * object is created. - * If a new object has been created by JS_NewMappedArrayBufferWithContents() - * with this content, then JS_DetachArrayBuffer() should be used instead to - * release the resource used by the object. - */ -extern JS_PUBLIC_API(void) -JS_ReleaseMappedArrayBufferContents(void* contents, size_t length); - -extern JS_PUBLIC_API(JS::Value) -JS_GetReservedSlot(JSObject* obj, uint32_t index); - -extern JS_PUBLIC_API(void) -JS_SetReservedSlot(JSObject* obj, uint32_t index, const JS::Value& v); - - -/************************************************************************/ - -/* - * Functions and scripts. - */ -extern JS_PUBLIC_API(JSFunction*) -JS_NewFunction(JSContext* cx, JSNative call, unsigned nargs, unsigned flags, - const char* name); - -namespace JS { - -extern JS_PUBLIC_API(JSFunction*) -GetSelfHostedFunction(JSContext* cx, const char* selfHostedName, HandleId id, - unsigned nargs); - -/** - * Create a new function based on the given JSFunctionSpec, *fs. - * id is the result of a successful call to - * `PropertySpecNameToPermanentId(cx, fs->name, &id)`. - * - * Unlike JS_DefineFunctions, this does not treat fs as an array. - * *fs must not be JS_FS_END. - */ -extern JS_PUBLIC_API(JSFunction*) -NewFunctionFromSpec(JSContext* cx, const JSFunctionSpec* fs, HandleId id); - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSObject*) -JS_GetFunctionObject(JSFunction* fun); - -/** - * Return the function's identifier as a JSString, or null if fun is unnamed. - * The returned string lives as long as fun, so you don't need to root a saved - * reference to it if fun is well-connected or rooted, and provided you bound - * the use of the saved reference by fun's lifetime. - */ -extern JS_PUBLIC_API(JSString*) -JS_GetFunctionId(JSFunction* fun); - -/** - * Return a function's display name. This is the defined name if one was given - * where the function was defined, or it could be an inferred name by the JS - * engine in the case that the function was defined to be anonymous. This can - * still return nullptr if a useful display name could not be inferred. The - * same restrictions on rooting as those in JS_GetFunctionId apply. - */ -extern JS_PUBLIC_API(JSString*) -JS_GetFunctionDisplayId(JSFunction* fun); - -/* - * Return the arity (length) of fun. - */ -extern JS_PUBLIC_API(uint16_t) -JS_GetFunctionArity(JSFunction* fun); - -/** - * Infallible predicate to test whether obj is a function object (faster than - * comparing obj's class name to "Function", but equivalent unless someone has - * overwritten the "Function" identifier with a different constructor and then - * created instances using that constructor that might be passed in as obj). - */ -extern JS_PUBLIC_API(bool) -JS_ObjectIsFunction(JSContext* cx, JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_IsNativeFunction(JSObject* funobj, JSNative call); - -/** Return whether the given function is a valid constructor. */ -extern JS_PUBLIC_API(bool) -JS_IsConstructor(JSFunction* fun); - -extern JS_PUBLIC_API(bool) -JS_DefineFunctions(JSContext* cx, JS::Handle obj, const JSFunctionSpec* fs); - -extern JS_PUBLIC_API(JSFunction*) -JS_DefineFunction(JSContext* cx, JS::Handle obj, const char* name, JSNative call, - unsigned nargs, unsigned attrs); - -extern JS_PUBLIC_API(JSFunction*) -JS_DefineUCFunction(JSContext* cx, JS::Handle obj, - const char16_t* name, size_t namelen, JSNative call, - unsigned nargs, unsigned attrs); - -extern JS_PUBLIC_API(JSFunction*) -JS_DefineFunctionById(JSContext* cx, JS::Handle obj, JS::Handle id, JSNative call, - unsigned nargs, unsigned attrs); - -extern JS_PUBLIC_API(bool) -JS_IsFunctionBound(JSFunction* fun); - -extern JS_PUBLIC_API(JSObject*) -JS_GetBoundFunctionTarget(JSFunction* fun); - -namespace JS { - -/** - * Clone a top-level function into cx's global. This function will dynamically - * fail if funobj was lexically nested inside some other function. - */ -extern JS_PUBLIC_API(JSObject*) -CloneFunctionObject(JSContext* cx, HandleObject funobj); - -/** - * As above, but providing an explicit scope chain. scopeChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the clone's scope chain. - */ -extern JS_PUBLIC_API(JSObject*) -CloneFunctionObject(JSContext* cx, HandleObject funobj, AutoObjectVector& scopeChain); - -} // namespace JS - -/** - * Given a buffer, return false if the buffer might become a valid - * javascript statement with the addition of more lines. Otherwise return - * true. The intent is to support interactive compilation - accumulate - * lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to - * the compiler. - */ -extern JS_PUBLIC_API(bool) -JS_BufferIsCompilableUnit(JSContext* cx, JS::Handle obj, const char* utf8, - size_t length); - -/** - * |script| will always be set. On failure, it will be set to nullptr. - */ -extern JS_PUBLIC_API(bool) -JS_CompileScript(JSContext* cx, const char* ascii, size_t length, - const JS::CompileOptions& options, - JS::MutableHandleScript script); - -/** - * |script| will always be set. On failure, it will be set to nullptr. - */ -extern JS_PUBLIC_API(bool) -JS_CompileUCScript(JSContext* cx, const char16_t* chars, size_t length, - const JS::CompileOptions& options, - JS::MutableHandleScript script); - -extern JS_PUBLIC_API(JSObject*) -JS_GetGlobalFromScript(JSScript* script); - -extern JS_PUBLIC_API(const char*) -JS_GetScriptFilename(JSScript* script); - -extern JS_PUBLIC_API(unsigned) -JS_GetScriptBaseLineNumber(JSContext* cx, JSScript* script); - -extern JS_PUBLIC_API(JSScript*) -JS_GetFunctionScript(JSContext* cx, JS::HandleFunction fun); - -namespace JS { - -/* Options for JavaScript compilation. */ - -/* - * In the most common use case, a CompileOptions instance is allocated on the - * stack, and holds non-owning references to non-POD option values: strings; - * principals; objects; and so on. The code declaring the instance guarantees - * that such option values will outlive the CompileOptions itself: objects are - * otherwise rooted; principals have had their reference counts bumped; strings - * will not be freed until the CompileOptions goes out of scope. In this - * situation, CompileOptions only refers to things others own, so it can be - * lightweight. - * - * In some cases, however, we need to hold compilation options with a - * non-stack-like lifetime. For example, JS::CompileOffThread needs to save - * compilation options where a worker thread can find them, and then return - * immediately. The worker thread will come along at some later point, and use - * the options. - * - * The compiler itself just needs to be able to access a collection of options; - * it doesn't care who owns them, or what's keeping them alive. It does its own - * addrefs/copies/tracing/etc. - * - * Furthermore, in some cases compile options are propagated from one entity to - * another (e.g. from a scriipt to a function defined in that script). This - * involves copying over some, but not all, of the options. - * - * So, we have a class hierarchy that reflects these four use cases: - * - * - TransitiveCompileOptions is the common base class, representing options - * that should get propagated from a script to functions defined in that - * script. This is never instantiated directly. - * - * - ReadOnlyCompileOptions is the only subclass of TransitiveCompileOptions, - * representing a full set of compile options. It can be used by code that - * simply needs to access options set elsewhere, like the compiler. This, - * again, is never instantiated directly. - * - * - The usual CompileOptions class must be stack-allocated, and holds - * non-owning references to the filename, element, and so on. It's derived - * from ReadOnlyCompileOptions, so the compiler can use it. - * - * - OwningCompileOptions roots / copies / reference counts of all its values, - * and unroots / frees / releases them when it is destructed. It too is - * derived from ReadOnlyCompileOptions, so the compiler accepts it. - */ - -enum class AsmJSOption : uint8_t { Enabled, Disabled, DisabledByDebugger }; - -/** - * The common base class for the CompileOptions hierarchy. - * - * Use this in code that needs to propagate compile options from one compilation - * unit to another. - */ -class JS_FRIEND_API(TransitiveCompileOptions) -{ - protected: - // The Web Platform allows scripts to be loaded from arbitrary cross-origin - // sources. This allows an attack by which a malicious website loads a - // sensitive file (say, a bank statement) cross-origin (using the user's - // cookies), and sniffs the generated syntax errors (via a window.onerror - // handler) for juicy morsels of its contents. - // - // To counter this attack, HTML5 specifies that script errors should be - // sanitized ("muted") when the script is not same-origin with the global - // for which it is loaded. Callers should set this flag for cross-origin - // scripts, and it will be propagated appropriately to child scripts and - // passed back in JSErrorReports. - bool mutedErrors_; - const char* filename_; - const char* introducerFilename_; - const char16_t* sourceMapURL_; - - // This constructor leaves 'version' set to JSVERSION_UNKNOWN. The structure - // is unusable until that's set to something more specific; the derived - // classes' constructors take care of that, in ways appropriate to their - // purpose. - TransitiveCompileOptions() - : mutedErrors_(false), - filename_(nullptr), - introducerFilename_(nullptr), - sourceMapURL_(nullptr), - version(JSVERSION_UNKNOWN), - versionSet(false), - utf8(false), - selfHostingMode(false), - canLazilyParse(true), - strictOption(false), - extraWarningsOption(false), - werrorOption(false), - asmJSOption(AsmJSOption::Disabled), - throwOnAsmJSValidationFailureOption(false), - forceAsync(false), - installedFile(false), - sourceIsLazy(false), - introductionType(nullptr), - introductionLineno(0), - introductionOffset(0), - hasIntroductionInfo(false) - { } - - // Set all POD options (those not requiring reference counts, copies, - // rooting, or other hand-holding) to their values in |rhs|. - void copyPODTransitiveOptions(const TransitiveCompileOptions& rhs); - - public: - // Read-only accessors for non-POD options. The proper way to set these - // depends on the derived type. - bool mutedErrors() const { return mutedErrors_; } - const char* filename() const { return filename_; } - const char* introducerFilename() const { return introducerFilename_; } - const char16_t* sourceMapURL() const { return sourceMapURL_; } - virtual JSObject* element() const = 0; - virtual JSString* elementAttributeName() const = 0; - virtual JSScript* introductionScript() const = 0; - - // POD options. - JSVersion version; - bool versionSet; - bool utf8; - bool selfHostingMode; - bool canLazilyParse; - bool strictOption; - bool extraWarningsOption; - bool werrorOption; - AsmJSOption asmJSOption; - bool throwOnAsmJSValidationFailureOption; - bool forceAsync; - bool installedFile; // 'true' iff pre-compiling js file in packaged app - bool sourceIsLazy; - - // |introductionType| is a statically allocated C string: - // one of "eval", "Function", or "GeneratorFunction". - const char* introductionType; - unsigned introductionLineno; - uint32_t introductionOffset; - bool hasIntroductionInfo; - - private: - void operator=(const TransitiveCompileOptions&) = delete; -}; - -/** - * The class representing a full set of compile options. - * - * Use this in code that only needs to access compilation options created - * elsewhere, like the compiler. Don't instantiate this class (the constructor - * is protected anyway); instead, create instances only of the derived classes: - * CompileOptions and OwningCompileOptions. - */ -class JS_FRIEND_API(ReadOnlyCompileOptions) : public TransitiveCompileOptions -{ - friend class CompileOptions; - - protected: - ReadOnlyCompileOptions() - : TransitiveCompileOptions(), - lineno(1), - column(0), - isRunOnce(false), - noScriptRval(false) - { } - - // Set all POD options (those not requiring reference counts, copies, - // rooting, or other hand-holding) to their values in |rhs|. - void copyPODOptions(const ReadOnlyCompileOptions& rhs); - - public: - // Read-only accessors for non-POD options. The proper way to set these - // depends on the derived type. - bool mutedErrors() const { return mutedErrors_; } - const char* filename() const { return filename_; } - const char* introducerFilename() const { return introducerFilename_; } - const char16_t* sourceMapURL() const { return sourceMapURL_; } - virtual JSObject* element() const = 0; - virtual JSString* elementAttributeName() const = 0; - virtual JSScript* introductionScript() const = 0; - - // POD options. - unsigned lineno; - unsigned column; - // isRunOnce only applies to non-function scripts. - bool isRunOnce; - bool noScriptRval; - - private: - void operator=(const ReadOnlyCompileOptions&) = delete; -}; - -/** - * Compilation options, with dynamic lifetime. An instance of this type - * makes a copy of / holds / roots all dynamically allocated resources - * (principals; elements; strings) that it refers to. Its destructor frees - * / drops / unroots them. This is heavier than CompileOptions, below, but - * unlike CompileOptions, it can outlive any given stack frame. - * - * Note that this *roots* any JS values it refers to - they're live - * unconditionally. Thus, instances of this type can't be owned, directly - * or indirectly, by a JavaScript object: if any value that this roots ever - * comes to refer to the object that owns this, then the whole cycle, and - * anything else it entrains, will never be freed. - */ -class JS_FRIEND_API(OwningCompileOptions) : public ReadOnlyCompileOptions -{ - PersistentRootedObject elementRoot; - PersistentRootedString elementAttributeNameRoot; - PersistentRootedScript introductionScriptRoot; - - public: - // A minimal constructor, for use with OwningCompileOptions::copy. This - // leaves |this.version| set to JSVERSION_UNKNOWN; the instance - // shouldn't be used until we've set that to something real (as |copy| - // will). - explicit OwningCompileOptions(JSContext* cx); - ~OwningCompileOptions(); - - JSObject* element() const override { return elementRoot; } - JSString* elementAttributeName() const override { return elementAttributeNameRoot; } - JSScript* introductionScript() const override { return introductionScriptRoot; } - - // Set this to a copy of |rhs|. Return false on OOM. - bool copy(JSContext* cx, const ReadOnlyCompileOptions& rhs); - - /* These setters make copies of their string arguments, and are fallible. */ - bool setFile(JSContext* cx, const char* f); - bool setFileAndLine(JSContext* cx, const char* f, unsigned l); - bool setSourceMapURL(JSContext* cx, const char16_t* s); - bool setIntroducerFilename(JSContext* cx, const char* s); - - /* These setters are infallible, and can be chained. */ - OwningCompileOptions& setLine(unsigned l) { lineno = l; return *this; } - OwningCompileOptions& setElement(JSObject* e) { - elementRoot = e; - return *this; - } - OwningCompileOptions& setElementAttributeName(JSString* p) { - elementAttributeNameRoot = p; - return *this; - } - OwningCompileOptions& setIntroductionScript(JSScript* s) { - introductionScriptRoot = s; - return *this; - } - OwningCompileOptions& setMutedErrors(bool mute) { - mutedErrors_ = mute; - return *this; - } - OwningCompileOptions& setVersion(JSVersion v) { - version = v; - versionSet = true; - return *this; - } - OwningCompileOptions& setUTF8(bool u) { utf8 = u; return *this; } - OwningCompileOptions& setColumn(unsigned c) { column = c; return *this; } - OwningCompileOptions& setIsRunOnce(bool once) { isRunOnce = once; return *this; } - OwningCompileOptions& setNoScriptRval(bool nsr) { noScriptRval = nsr; return *this; } - OwningCompileOptions& setSelfHostingMode(bool shm) { selfHostingMode = shm; return *this; } - OwningCompileOptions& setCanLazilyParse(bool clp) { canLazilyParse = clp; return *this; } - OwningCompileOptions& setSourceIsLazy(bool l) { sourceIsLazy = l; return *this; } - OwningCompileOptions& setIntroductionType(const char* t) { introductionType = t; return *this; } - bool setIntroductionInfo(JSContext* cx, const char* introducerFn, const char* intro, - unsigned line, JSScript* script, uint32_t offset) - { - if (!setIntroducerFilename(cx, introducerFn)) - return false; - introductionType = intro; - introductionLineno = line; - introductionScriptRoot = script; - introductionOffset = offset; - hasIntroductionInfo = true; - return true; - } - - private: - void operator=(const CompileOptions& rhs) = delete; -}; - -/** - * Compilation options stored on the stack. An instance of this type - * simply holds references to dynamically allocated resources (element; - * filename; source map URL) that are owned by something else. If you - * create an instance of this type, it's up to you to guarantee that - * everything you store in it will outlive it. - */ -class MOZ_STACK_CLASS JS_FRIEND_API(CompileOptions) final : public ReadOnlyCompileOptions -{ - RootedObject elementRoot; - RootedString elementAttributeNameRoot; - RootedScript introductionScriptRoot; - - public: - explicit CompileOptions(JSContext* cx, JSVersion version = JSVERSION_UNKNOWN); - CompileOptions(js::ContextFriendFields* cx, const ReadOnlyCompileOptions& rhs) - : ReadOnlyCompileOptions(), elementRoot(cx), elementAttributeNameRoot(cx), - introductionScriptRoot(cx) - { - copyPODOptions(rhs); - - filename_ = rhs.filename(); - introducerFilename_ = rhs.introducerFilename(); - sourceMapURL_ = rhs.sourceMapURL(); - elementRoot = rhs.element(); - elementAttributeNameRoot = rhs.elementAttributeName(); - introductionScriptRoot = rhs.introductionScript(); - } - - CompileOptions(js::ContextFriendFields* cx, const TransitiveCompileOptions& rhs) - : ReadOnlyCompileOptions(), elementRoot(cx), elementAttributeNameRoot(cx), - introductionScriptRoot(cx) - { - copyPODTransitiveOptions(rhs); - - filename_ = rhs.filename(); - introducerFilename_ = rhs.introducerFilename(); - sourceMapURL_ = rhs.sourceMapURL(); - elementRoot = rhs.element(); - elementAttributeNameRoot = rhs.elementAttributeName(); - introductionScriptRoot = rhs.introductionScript(); - } - - JSObject* element() const override { return elementRoot; } - JSString* elementAttributeName() const override { return elementAttributeNameRoot; } - JSScript* introductionScript() const override { return introductionScriptRoot; } - - CompileOptions& setFile(const char* f) { filename_ = f; return *this; } - CompileOptions& setLine(unsigned l) { lineno = l; return *this; } - CompileOptions& setFileAndLine(const char* f, unsigned l) { - filename_ = f; lineno = l; return *this; - } - CompileOptions& setSourceMapURL(const char16_t* s) { sourceMapURL_ = s; return *this; } - CompileOptions& setElement(JSObject* e) { elementRoot = e; return *this; } - CompileOptions& setElementAttributeName(JSString* p) { - elementAttributeNameRoot = p; - return *this; - } - CompileOptions& setIntroductionScript(JSScript* s) { - introductionScriptRoot = s; - return *this; - } - CompileOptions& setMutedErrors(bool mute) { - mutedErrors_ = mute; - return *this; - } - CompileOptions& setVersion(JSVersion v) { - version = v; - versionSet = true; - return *this; - } - CompileOptions& setUTF8(bool u) { utf8 = u; return *this; } - CompileOptions& setColumn(unsigned c) { column = c; return *this; } - CompileOptions& setIsRunOnce(bool once) { isRunOnce = once; return *this; } - CompileOptions& setNoScriptRval(bool nsr) { noScriptRval = nsr; return *this; } - CompileOptions& setSelfHostingMode(bool shm) { selfHostingMode = shm; return *this; } - CompileOptions& setCanLazilyParse(bool clp) { canLazilyParse = clp; return *this; } - CompileOptions& setSourceIsLazy(bool l) { sourceIsLazy = l; return *this; } - CompileOptions& setIntroductionType(const char* t) { introductionType = t; return *this; } - CompileOptions& setIntroductionInfo(const char* introducerFn, const char* intro, - unsigned line, JSScript* script, uint32_t offset) - { - introducerFilename_ = introducerFn; - introductionType = intro; - introductionLineno = line; - introductionScriptRoot = script; - introductionOffset = offset; - hasIntroductionInfo = true; - return *this; - } - CompileOptions& maybeMakeStrictMode(bool strict) { - strictOption = strictOption || strict; - return *this; - } - - private: - void operator=(const CompileOptions& rhs) = delete; -}; - -/** - * |script| will always be set. On failure, it will be set to nullptr. - */ -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* bytes, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - FILE* file, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* filename, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* bytes, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - FILE* file, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* filename, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CanCompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options, size_t length); - -/* - * Off thread compilation control flow. - * - * After successfully triggering an off thread compile of a script, the - * callback will eventually be invoked with the specified data and a token - * for the compilation. The callback will be invoked while off the main thread, - * so must ensure that its operations are thread safe. Afterwards, one of the - * following functions must be invoked on the main thread: - * - * - FinishOffThreadScript, to get the result script (or nullptr on failure). - * - CancelOffThreadScript, to free the resources without creating a script. - * - * The characters passed in to CompileOffThread must remain live until the - * callback is invoked, and the resulting script will be rooted until the call - * to FinishOffThreadScript. - */ - -extern JS_PUBLIC_API(bool) -CompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, - OffThreadCompileCallback callback, void* callbackData); - -extern JS_PUBLIC_API(JSScript*) -FinishOffThreadScript(JSContext* cx, void* token); - -extern JS_PUBLIC_API(void) -CancelOffThreadScript(JSContext* cx, void* token); - -extern JS_PUBLIC_API(bool) -CompileOffThreadModule(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, - OffThreadCompileCallback callback, void* callbackData); - -extern JS_PUBLIC_API(JSObject*) -FinishOffThreadModule(JSContext* cx, void* token); - -extern JS_PUBLIC_API(void) -CancelOffThreadModule(JSContext* cx, void* token); - -/** - * Compile a function with envChain plus the global as its scope chain. - * envChain must contain objects in the current compartment of cx. The actual - * scope chain used for the function will consist of With wrappers for those - * objects, followed by the current global of the compartment cx is in. This - * global must not be explicitly included in the scope chain. - */ -extern JS_PUBLIC_API(bool) -CompileFunction(JSContext* cx, AutoObjectVector& envChain, - const ReadOnlyCompileOptions& options, - const char* name, unsigned nargs, const char* const* argnames, - const char16_t* chars, size_t length, JS::MutableHandleFunction fun); - -/** - * Same as above, but taking a SourceBufferHolder for the function body. - */ -extern JS_PUBLIC_API(bool) -CompileFunction(JSContext* cx, AutoObjectVector& envChain, - const ReadOnlyCompileOptions& options, - const char* name, unsigned nargs, const char* const* argnames, - SourceBufferHolder& srcBuf, JS::MutableHandleFunction fun); - -/** - * Same as above, but taking a const char * for the function body. - */ -extern JS_PUBLIC_API(bool) -CompileFunction(JSContext* cx, AutoObjectVector& envChain, - const ReadOnlyCompileOptions& options, - const char* name, unsigned nargs, const char* const* argnames, - const char* bytes, size_t length, JS::MutableHandleFunction fun); - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSString*) -JS_DecompileScript(JSContext* cx, JS::Handle script, const char* name, unsigned indent); - -/* - * API extension: OR this into indent to avoid pretty-printing the decompiled - * source resulting from JS_DecompileFunction. - */ -#define JS_DONT_PRETTY_PRINT ((unsigned)0x8000) - -extern JS_PUBLIC_API(JSString*) -JS_DecompileFunction(JSContext* cx, JS::Handle fun, unsigned indent); - - -/* - * NB: JS_ExecuteScript and the JS::Evaluate APIs come in two flavors: either - * they use the global as the scope, or they take an AutoObjectVector of objects - * to use as the scope chain. In the former case, the global is also used as - * the "this" keyword value and the variables object (ECMA parlance for where - * 'var' and 'function' bind names) of the execution context for script. In the - * latter case, the first object in the provided list is used, unless the list - * is empty, in which case the global is used. - * - * Why a runtime option? The alternative is to add APIs duplicating those - * for the other value of flags, and that doesn't seem worth the code bloat - * cost. Such new entry points would probably have less obvious names, too, so - * would not tend to be used. The ContextOptionsRef adjustment, OTOH, can be - * more easily hacked into existing code that does not depend on the bug; such - * code can continue to use the familiar JS::Evaluate, etc., entry points. - */ - -/** - * Evaluate a script in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::HandleScript script, JS::MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::HandleScript script); - -/** - * As above, but providing an explicit scope chain. envChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the script's scope chain. - */ -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::AutoObjectVector& envChain, - JS::HandleScript script, JS::MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::AutoObjectVector& envChain, JS::HandleScript script); - -namespace JS { - -/** - * Like the above, but handles a cross-compartment script. If the script is - * cross-compartment, it is cloned into the current compartment before executing. - */ -extern JS_PUBLIC_API(bool) -CloneAndExecuteScript(JSContext* cx, JS::Handle script, - JS::MutableHandleValue rval); - -} /* namespace JS */ - -namespace JS { - -/** - * Evaluate the given source buffer in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleValue rval); - -/** - * As above, but providing an explicit scope chain. envChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the script's scope chain. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, AutoObjectVector& envChain, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleValue rval); - -/** - * Evaluate the given character buffer in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleValue rval); - -/** - * As above, but providing an explicit scope chain. envChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the script's scope chain. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, AutoObjectVector& envChain, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleValue rval); - -/** - * Evaluate the given byte buffer in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* bytes, size_t length, JS::MutableHandleValue rval); - -/** - * Evaluate the given file in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* filename, JS::MutableHandleValue rval); - -/** - * Get the HostResolveImportedModule hook for a global. - */ -extern JS_PUBLIC_API(JSFunction*) -GetModuleResolveHook(JSContext* cx); - -/** - * Set the HostResolveImportedModule hook for a global to the given function. - */ -extern JS_PUBLIC_API(void) -SetModuleResolveHook(JSContext* cx, JS::HandleFunction func); - -/** - * Parse the given source buffer as a module in the scope of the current global - * of cx and return a source text module record. - */ -extern JS_PUBLIC_API(bool) -CompileModule(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleObject moduleRecord); - -/** - * Set the [[HostDefined]] field of a source text module record to the given - * value. - */ -extern JS_PUBLIC_API(void) -SetModuleHostDefinedField(JSObject* module, const JS::Value& value); - -/** - * Get the [[HostDefined]] field of a source text module record. - */ -extern JS_PUBLIC_API(JS::Value) -GetModuleHostDefinedField(JSObject* module); - -/* - * Perform the ModuleDeclarationInstantiation operation on on the give source - * text module record. - * - * This transitively resolves all module dependencies (calling the - * HostResolveImportedModule hook) and initializes the environment record for - * the module. - */ -extern JS_PUBLIC_API(bool) -ModuleDeclarationInstantiation(JSContext* cx, JS::HandleObject moduleRecord); - -/* - * Perform the ModuleEvaluation operation on on the give source text module - * record. - * - * This does nothing if this module has already been evaluated. Otherwise, it - * transitively evaluates all dependences of this module and then evaluates this - * module. - * - * ModuleDeclarationInstantiation must have completed prior to calling this. - */ -extern JS_PUBLIC_API(bool) -ModuleEvaluation(JSContext* cx, JS::HandleObject moduleRecord); - -/* - * Get a list of the module specifiers used by a source text module - * record to request importation of modules. - * - * The result is a JavaScript array of string values. To extract the individual - * values use only JS_GetArrayLength and JS_GetElement with indices 0 to - * length - 1. - */ -extern JS_PUBLIC_API(JSObject*) -GetRequestedModules(JSContext* cx, JS::HandleObject moduleRecord); - -/* - * Get the script associated with a module. - */ -extern JS_PUBLIC_API(JSScript*) -GetModuleScript(JSContext* cx, JS::HandleObject moduleRecord); - -} /* namespace JS */ - -extern JS_PUBLIC_API(bool) -JS_CheckForInterrupt(JSContext* cx); - -/* - * These functions allow setting an interrupt callback that will be called - * from the JS thread some time after any thread triggered the callback using - * JS_RequestInterruptCallback(cx). - * - * To schedule the GC and for other activities the engine internally triggers - * interrupt callbacks. The embedding should thus not rely on callbacks being - * triggered through the external API only. - * - * Important note: Additional callbacks can occur inside the callback handler - * if it re-enters the JS engine. The embedding must ensure that the callback - * is disconnected before attempting such re-entry. - */ -extern JS_PUBLIC_API(bool) -JS_AddInterruptCallback(JSContext* cx, JSInterruptCallback callback); - -extern JS_PUBLIC_API(bool) -JS_DisableInterruptCallback(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_ResetInterruptCallback(JSContext* cx, bool enable); - -extern JS_PUBLIC_API(void) -JS_RequestInterruptCallback(JSContext* cx); - -namespace JS { - -/** - * Sets the callback that's invoked whenever an incumbent global is required. - * - * SpiderMonkey doesn't itself have a notion of incumbent globals as defined - * by the html spec, so we need the embedding to provide this. - * See dom/base/ScriptSettings.h for details. - */ -extern JS_PUBLIC_API(void) -SetGetIncumbentGlobalCallback(JSContext* cx, JSGetIncumbentGlobalCallback callback); - -/** - * Sets the callback that's invoked whenever a Promise job should be enqeued. - * - * SpiderMonkey doesn't schedule Promise resolution jobs itself; instead, - * using this function the embedding can provide a callback to do that - * scheduling. The provided `callback` is invoked with the promise job, - * the corresponding Promise's allocation stack, and the `data` pointer - * passed here as arguments. - */ -extern JS_PUBLIC_API(void) -SetEnqueuePromiseJobCallback(JSContext* cx, JSEnqueuePromiseJobCallback callback, - void* data = nullptr); - -/** - * Sets the callback that's invoked whenever a Promise is rejected without - * a rejection handler, and when a Promise that was previously rejected - * without a handler gets a handler attached. - */ -extern JS_PUBLIC_API(void) -SetPromiseRejectionTrackerCallback(JSContext* cx, JSPromiseRejectionTrackerCallback callback, - void* data = nullptr); - -/** - * Returns a new instance of the Promise builtin class in the current - * compartment, with the right slot layout. If a `proto` is passed, that gets - * set as the instance's [[Prototype]] instead of the original value of - * `Promise.prototype`. - */ -extern JS_PUBLIC_API(JSObject*) -NewPromiseObject(JSContext* cx, JS::HandleObject executor, JS::HandleObject proto = nullptr); - -/** - * Returns true if the given object is an unwrapped PromiseObject, false - * otherwise. - */ -extern JS_PUBLIC_API(bool) -IsPromiseObject(JS::HandleObject obj); - -/** - * Returns the current compartment's original Promise constructor. - */ -extern JS_PUBLIC_API(JSObject*) -GetPromiseConstructor(JSContext* cx); - -/** - * Returns the current compartment's original Promise.prototype. - */ -extern JS_PUBLIC_API(JSObject*) -GetPromisePrototype(JSContext* cx); - -// Keep this in sync with the PROMISE_STATE defines in SelfHostingDefines.h. -enum class PromiseState { - Pending, - Fulfilled, - Rejected -}; - -/** - * Returns the given Promise's state as a JS::PromiseState enum value. - */ -extern JS_PUBLIC_API(PromiseState) -GetPromiseState(JS::HandleObject promise); - -/** - * Returns the given Promise's process-unique ID. - */ -JS_PUBLIC_API(uint64_t) -GetPromiseID(JS::HandleObject promise); - -/** - * Returns the given Promise's result: either the resolution value for - * fulfilled promises, or the rejection reason for rejected ones. - */ -extern JS_PUBLIC_API(JS::Value) -GetPromiseResult(JS::HandleObject promise); - -/** - * Returns a js::SavedFrame linked list of the stack that lead to the given - * Promise's allocation. - */ -extern JS_PUBLIC_API(JSObject*) -GetPromiseAllocationSite(JS::HandleObject promise); - -extern JS_PUBLIC_API(JSObject*) -GetPromiseResolutionSite(JS::HandleObject promise); - -#ifdef DEBUG -extern JS_PUBLIC_API(void) -DumpPromiseAllocationSite(JSContext* cx, JS::HandleObject promise); - -extern JS_PUBLIC_API(void) -DumpPromiseResolutionSite(JSContext* cx, JS::HandleObject promise); -#endif - -/** - * Calls the current compartment's original Promise.resolve on the original - * Promise constructor, with `resolutionValue` passed as an argument. - */ -extern JS_PUBLIC_API(JSObject*) -CallOriginalPromiseResolve(JSContext* cx, JS::HandleValue resolutionValue); - -/** - * Calls the current compartment's original Promise.reject on the original - * Promise constructor, with `resolutionValue` passed as an argument. - */ -extern JS_PUBLIC_API(JSObject*) -CallOriginalPromiseReject(JSContext* cx, JS::HandleValue rejectionValue); - -/** - * Resolves the given Promise with the given `resolutionValue`. - * - * Calls the `resolve` function that was passed to the executor function when - * the Promise was created. - */ -extern JS_PUBLIC_API(bool) -ResolvePromise(JSContext* cx, JS::HandleObject promise, JS::HandleValue resolutionValue); - -/** - * Rejects the given `promise` with the given `rejectionValue`. - * - * Calls the `reject` function that was passed to the executor function when - * the Promise was created. - */ -extern JS_PUBLIC_API(bool) -RejectPromise(JSContext* cx, JS::HandleObject promise, JS::HandleValue rejectionValue); - -/** - * Calls the current compartment's original Promise.prototype.then on the - * given `promise`, with `onResolve` and `onReject` passed as arguments. - * - * Asserts if the passed-in `promise` object isn't an unwrapped instance of - * `Promise` or a subclass or `onResolve` and `onReject` aren't both either - * `nullptr` or callable objects. - */ -extern JS_PUBLIC_API(JSObject*) -CallOriginalPromiseThen(JSContext* cx, JS::HandleObject promise, - JS::HandleObject onResolve, JS::HandleObject onReject); - -/** - * Unforgeable, optimized version of the JS builtin Promise.prototype.then. - * - * Takes a Promise instance and `onResolve`, `onReject` callables to enqueue - * as reactions for that promise. In difference to Promise.prototype.then, - * this doesn't create and return a new Promise instance. - * - * Asserts if the passed-in `promise` object isn't an unwrapped instance of - * `Promise` or a subclass or `onResolve` and `onReject` aren't both callable - * objects. - */ -extern JS_PUBLIC_API(bool) -AddPromiseReactions(JSContext* cx, JS::HandleObject promise, - JS::HandleObject onResolve, JS::HandleObject onReject); - -/** - * Unforgeable version of the JS builtin Promise.all. - * - * Takes an AutoObjectVector of Promise objects and returns a promise that's - * resolved with an array of resolution values when all those promises ahve - * been resolved, or rejected with the rejection value of the first rejected - * promise. - * - * Asserts if the array isn't dense or one of the entries isn't an unwrapped - * instance of Promise or a subclass. - */ -extern JS_PUBLIC_API(JSObject*) -GetWaitForAllPromise(JSContext* cx, const JS::AutoObjectVector& promises); - -/** - * An AsyncTask represents a SpiderMonkey-internal operation that starts on a - * JSContext's owner thread, possibly executes on other threads, completes, and - * then needs to be scheduled to run again on the JSContext's owner thread. The - * embedding provides for this final dispatch back to the JSContext's owner - * thread by calling methods on this interface when requested. - */ -struct JS_PUBLIC_API(AsyncTask) -{ - AsyncTask() : user(nullptr) {} - virtual ~AsyncTask() {} - - /** - * After the FinishAsyncTaskCallback is called and succeeds, one of these - * two functions will be called on the original JSContext's owner thread. - */ - virtual void finish(JSContext* cx) = 0; - virtual void cancel(JSContext* cx) = 0; - - /* The embedding may use this field to attach arbitrary data to a task. */ - void* user; -}; - -/** - * A new AsyncTask object, created inside SpiderMonkey on the JSContext's owner - * thread, will be passed to the StartAsyncTaskCallback before it is dispatched - * to another thread. The embedding may use the AsyncTask::user field to attach - * additional task state. - * - * If this function succeeds, SpiderMonkey will call the FinishAsyncTaskCallback - * at some point in the future. Otherwise, FinishAsyncTaskCallback will *not* - * be called. SpiderMonkey assumes that, if StartAsyncTaskCallback fails, it is - * because the JSContext is being shut down. - */ -typedef bool -(*StartAsyncTaskCallback)(JSContext* cx, AsyncTask* task); - -/** - * The FinishAsyncTaskCallback may be called from any thread and will only be - * passed AsyncTasks that have already been started via StartAsyncTaskCallback. - * If the embedding returns 'true', indicating success, the embedding must call - * either task->finish() or task->cancel() on the JSContext's owner thread at - * some point in the future. - */ -typedef bool -(*FinishAsyncTaskCallback)(AsyncTask* task); - -/** - * Set the above callbacks for the given context. - */ -extern JS_PUBLIC_API(void) -SetAsyncTaskCallbacks(JSContext* cx, StartAsyncTaskCallback start, FinishAsyncTaskCallback finish); - -} // namespace JS - -extern JS_PUBLIC_API(bool) -JS_IsRunning(JSContext* cx); - -namespace JS { - -/** - * This class can be used to store a pointer to the youngest frame of a saved - * stack in the specified JSContext. This reference will be picked up by any new - * calls performed until the class is destroyed, with the specified asyncCause, - * that must not be empty. - * - * Any stack capture initiated during these new calls will go through the async - * stack instead of the current stack. - * - * Capturing the stack before a new call is performed will not be affected. - * - * The provided chain of SavedFrame objects can live in any compartment, - * although it will be copied to the compartment where the stack is captured. - * - * See also `js/src/doc/SavedFrame/SavedFrame.md` for documentation on async - * stack frames. - */ -class MOZ_STACK_CLASS JS_PUBLIC_API(AutoSetAsyncStackForNewCalls) -{ - JSContext* cx; - RootedObject oldAsyncStack; - const char* oldAsyncCause; - bool oldAsyncCallIsExplicit; - - public: - enum class AsyncCallKind { - // The ordinary kind of call, where we may apply an async - // parent if there is no ordinary parent. - IMPLICIT, - // An explicit async parent, e.g., callFunctionWithAsyncStack, - // where we always want to override any ordinary parent. - EXPLICIT - }; - - // The stack parameter cannot be null by design, because it would be - // ambiguous whether that would clear any scheduled async stack and make the - // normal stack reappear in the new call, or just keep the async stack - // already scheduled for the new call, if any. - // - // asyncCause is owned by the caller and its lifetime must outlive the - // lifetime of the AutoSetAsyncStackForNewCalls object. It is strongly - // encouraged that asyncCause be a string constant or similar statically - // allocated string. - AutoSetAsyncStackForNewCalls(JSContext* cx, HandleObject stack, - const char* asyncCause, - AsyncCallKind kind = AsyncCallKind::IMPLICIT); - ~AutoSetAsyncStackForNewCalls(); -}; - -} // namespace JS - -/************************************************************************/ - -/* - * Strings. - * - * NB: JS_NewUCString takes ownership of bytes on success, avoiding a copy; - * but on error (signified by null return), it leaves chars owned by the - * caller. So the caller must free bytes in the error case, if it has no use - * for them. In contrast, all the JS_New*StringCopy* functions do not take - * ownership of the character memory passed to them -- they copy it. - */ -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyN(JSContext* cx, const char* s, size_t n); - -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyZ(JSContext* cx, const char* s); - -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyUTF8Z(JSContext* cx, const JS::ConstUTF8CharsZ s); - -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyUTF8N(JSContext* cx, const JS::UTF8Chars s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinJSString(JSContext* cx, JS::HandleString str); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeStringN(JSContext* cx, const char* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeString(JSContext* cx, const char* s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinStringN(JSContext* cx, const char* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinString(JSContext* cx, const char* s); - -extern JS_PUBLIC_API(JSString*) -JS_NewUCString(JSContext* cx, char16_t* chars, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_NewUCStringCopyN(JSContext* cx, const char16_t* s, size_t n); - -extern JS_PUBLIC_API(JSString*) -JS_NewUCStringCopyZ(JSContext* cx, const char16_t* s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeUCStringN(JSContext* cx, const char16_t* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeUCString(JSContext* cx, const char16_t* s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinUCStringN(JSContext* cx, const char16_t* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinUCString(JSContext* cx, const char16_t* s); - -extern JS_PUBLIC_API(bool) -JS_CompareStrings(JSContext* cx, JSString* str1, JSString* str2, int32_t* result); - -extern JS_PUBLIC_API(bool) -JS_StringEqualsAscii(JSContext* cx, JSString* str, const char* asciiBytes, bool* match); - -extern JS_PUBLIC_API(size_t) -JS_PutEscapedString(JSContext* cx, char* buffer, size_t size, JSString* str, char quote); - -extern JS_PUBLIC_API(bool) -JS_FileEscapedString(FILE* fp, JSString* str, char quote); - -/* - * Extracting string characters and length. - * - * While getting the length of a string is infallible, getting the chars can - * fail. As indicated by the lack of a JSContext parameter, there are two - * special cases where getting the chars is infallible: - * - * The first case is for strings that have been atomized, e.g. directly by - * JS_AtomizeAndPinString or implicitly because it is stored in a jsid. - * - * The second case is "flat" strings that have been explicitly prepared in a - * fallible context by JS_FlattenString. To catch errors, a separate opaque - * JSFlatString type is returned by JS_FlattenString and expected by - * JS_GetFlatStringChars. Note, though, that this is purely a syntactic - * distinction: the input and output of JS_FlattenString are the same actual - * GC-thing. If a JSString is known to be flat, JS_ASSERT_STRING_IS_FLAT can be - * used to make a debug-checked cast. Example: - * - * // in a fallible context - * JSFlatString* fstr = JS_FlattenString(cx, str); - * if (!fstr) - * return false; - * MOZ_ASSERT(fstr == JS_ASSERT_STRING_IS_FLAT(str)); - * - * // in an infallible context, for the same 'str' - * AutoCheckCannotGC nogc; - * const char16_t* chars = JS_GetTwoByteFlatStringChars(nogc, fstr) - * MOZ_ASSERT(chars); - * - * Flat strings and interned strings are always null-terminated, so - * JS_FlattenString can be used to get a null-terminated string. - * - * Additionally, string characters are stored as either Latin1Char (8-bit) - * or char16_t (16-bit). Clients can use JS_StringHasLatin1Chars and can then - * call either the Latin1* or TwoByte* functions. Some functions like - * JS_CopyStringChars and JS_GetStringCharAt accept both Latin1 and TwoByte - * strings. - */ - -extern JS_PUBLIC_API(size_t) -JS_GetStringLength(JSString* str); - -extern JS_PUBLIC_API(bool) -JS_StringIsFlat(JSString* str); - -/** Returns true iff the string's characters are stored as Latin1. */ -extern JS_PUBLIC_API(bool) -JS_StringHasLatin1Chars(JSString* str); - -extern JS_PUBLIC_API(const JS::Latin1Char*) -JS_GetLatin1StringCharsAndLength(JSContext* cx, const JS::AutoCheckCannotGC& nogc, JSString* str, - size_t* length); - -extern JS_PUBLIC_API(const char16_t*) -JS_GetTwoByteStringCharsAndLength(JSContext* cx, const JS::AutoCheckCannotGC& nogc, JSString* str, - size_t* length); - -extern JS_PUBLIC_API(bool) -JS_GetStringCharAt(JSContext* cx, JSString* str, size_t index, char16_t* res); - -extern JS_PUBLIC_API(char16_t) -JS_GetFlatStringCharAt(JSFlatString* str, size_t index); - -extern JS_PUBLIC_API(const char16_t*) -JS_GetTwoByteExternalStringChars(JSString* str); - -extern JS_PUBLIC_API(bool) -JS_CopyStringChars(JSContext* cx, mozilla::Range dest, JSString* str); - -extern JS_PUBLIC_API(JSFlatString*) -JS_FlattenString(JSContext* cx, JSString* str); - -extern JS_PUBLIC_API(const JS::Latin1Char*) -JS_GetLatin1FlatStringChars(const JS::AutoCheckCannotGC& nogc, JSFlatString* str); - -extern JS_PUBLIC_API(const char16_t*) -JS_GetTwoByteFlatStringChars(const JS::AutoCheckCannotGC& nogc, JSFlatString* str); - -static MOZ_ALWAYS_INLINE JSFlatString* -JSID_TO_FLAT_STRING(jsid id) -{ - MOZ_ASSERT(JSID_IS_STRING(id)); - return (JSFlatString*)(JSID_BITS(id)); -} - -static MOZ_ALWAYS_INLINE JSFlatString* -JS_ASSERT_STRING_IS_FLAT(JSString* str) -{ - MOZ_ASSERT(JS_StringIsFlat(str)); - return (JSFlatString*)str; -} - -static MOZ_ALWAYS_INLINE JSString* -JS_FORGET_STRING_FLATNESS(JSFlatString* fstr) -{ - return (JSString*)fstr; -} - -/* - * Additional APIs that avoid fallibility when given a flat string. - */ - -extern JS_PUBLIC_API(bool) -JS_FlatStringEqualsAscii(JSFlatString* str, const char* asciiBytes); - -extern JS_PUBLIC_API(size_t) -JS_PutEscapedFlatString(char* buffer, size_t size, JSFlatString* str, char quote); - -/** - * Create a dependent string, i.e., a string that owns no character storage, - * but that refers to a slice of another string's chars. Dependent strings - * are mutable by definition, so the thread safety comments above apply. - */ -extern JS_PUBLIC_API(JSString*) -JS_NewDependentString(JSContext* cx, JS::HandleString str, size_t start, - size_t length); - -/** - * Concatenate two strings, possibly resulting in a rope. - * See above for thread safety comments. - */ -extern JS_PUBLIC_API(JSString*) -JS_ConcatStrings(JSContext* cx, JS::HandleString left, JS::HandleString right); - -/** - * For JS_DecodeBytes, set *dstlenp to the size of the destination buffer before - * the call; on return, *dstlenp contains the number of characters actually - * stored. To determine the necessary destination buffer size, make a sizing - * call that passes nullptr for dst. - * - * On errors, the functions report the error. In that case, *dstlenp contains - * the number of characters or bytes transferred so far. If cx is nullptr, no - * error is reported on failure, and the functions simply return false. - * - * NB: This function does not store an additional zero byte or char16_t after the - * transcoded string. - */ -JS_PUBLIC_API(bool) -JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen, char16_t* dst, - size_t* dstlenp); - -/** - * A variation on JS_EncodeCharacters where a null terminated string is - * returned that you are expected to call JS_free on when done. - */ -JS_PUBLIC_API(char*) -JS_EncodeString(JSContext* cx, JSString* str); - -/** - * Same behavior as JS_EncodeString(), but encode into UTF-8 string - */ -JS_PUBLIC_API(char*) -JS_EncodeStringToUTF8(JSContext* cx, JS::HandleString str); - -/** - * Get number of bytes in the string encoding (without accounting for a - * terminating zero bytes. The function returns (size_t) -1 if the string - * can not be encoded into bytes and reports an error using cx accordingly. - */ -JS_PUBLIC_API(size_t) -JS_GetStringEncodingLength(JSContext* cx, JSString* str); - -/** - * Encode string into a buffer. The function does not stores an additional - * zero byte. The function returns (size_t) -1 if the string can not be - * encoded into bytes with no error reported. Otherwise it returns the number - * of bytes that are necessary to encode the string. If that exceeds the - * length parameter, the string will be cut and only length bytes will be - * written into the buffer. - */ -JS_PUBLIC_API(size_t) -JS_EncodeStringToBuffer(JSContext* cx, JSString* str, char* buffer, size_t length); - -class MOZ_RAII JSAutoByteString -{ - public: - JSAutoByteString(JSContext* cx, JSString* str - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mBytes(JS_EncodeString(cx, str)) - { - MOZ_ASSERT(cx); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit JSAutoByteString(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) - : mBytes(nullptr) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - ~JSAutoByteString() { - JS_free(nullptr, mBytes); - } - - /* Take ownership of the given byte array. */ - void initBytes(char* bytes) { - MOZ_ASSERT(!mBytes); - mBytes = bytes; - } - - char* encodeLatin1(JSContext* cx, JSString* str) { - MOZ_ASSERT(!mBytes); - MOZ_ASSERT(cx); - mBytes = JS_EncodeString(cx, str); - return mBytes; - } - - char* encodeLatin1(js::ExclusiveContext* cx, JSString* str); - - char* encodeUtf8(JSContext* cx, JS::HandleString str) { - MOZ_ASSERT(!mBytes); - MOZ_ASSERT(cx); - mBytes = JS_EncodeStringToUTF8(cx, str); - return mBytes; - } - - void clear() { - js_free(mBytes); - mBytes = nullptr; - } - - char* ptr() const { - return mBytes; - } - - bool operator!() const { - return !mBytes; - } - - size_t length() const { - if (!mBytes) - return 0; - return strlen(mBytes); - } - - private: - char* mBytes; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - - /* Copy and assignment are not supported. */ - JSAutoByteString(const JSAutoByteString& another); - JSAutoByteString& operator=(const JSAutoByteString& another); -}; - -namespace JS { - -extern JS_PUBLIC_API(JSAddonId*) -NewAddonId(JSContext* cx, JS::HandleString str); - -extern JS_PUBLIC_API(JSString*) -StringOfAddonId(JSAddonId* id); - -extern JS_PUBLIC_API(JSAddonId*) -AddonIdOfObject(JSObject* obj); - -} // namespace JS - -/************************************************************************/ -/* - * Symbols - */ - -namespace JS { - -/** - * Create a new Symbol with the given description. This function never returns - * a Symbol that is in the Runtime-wide symbol registry. - * - * If description is null, the new Symbol's [[Description]] attribute is - * undefined. - */ -JS_PUBLIC_API(Symbol*) -NewSymbol(JSContext* cx, HandleString description); - -/** - * Symbol.for as specified in ES6. - * - * Get a Symbol with the description 'key' from the Runtime-wide symbol registry. - * If there is not already a Symbol with that description in the registry, a new - * Symbol is created and registered. 'key' must not be null. - */ -JS_PUBLIC_API(Symbol*) -GetSymbolFor(JSContext* cx, HandleString key); - -/** - * Get the [[Description]] attribute of the given symbol. - * - * This function is infallible. If it returns null, that means the symbol's - * [[Description]] is undefined. - */ -JS_PUBLIC_API(JSString*) -GetSymbolDescription(HandleSymbol symbol); - -/* Well-known symbols. */ -#define JS_FOR_EACH_WELL_KNOWN_SYMBOL(macro) \ - macro(isConcatSpreadable) \ - macro(iterator) \ - macro(match) \ - macro(replace) \ - macro(search) \ - macro(species) \ - macro(hasInstance) \ - macro(split) \ - macro(toPrimitive) \ - macro(toStringTag) \ - macro(unscopables) - -enum class SymbolCode : uint32_t { - // There is one SymbolCode for each well-known symbol. -#define JS_DEFINE_SYMBOL_ENUM(name) name, - JS_FOR_EACH_WELL_KNOWN_SYMBOL(JS_DEFINE_SYMBOL_ENUM) // SymbolCode::iterator, etc. -#undef JS_DEFINE_SYMBOL_ENUM - Limit, - InSymbolRegistry = 0xfffffffe, // created by Symbol.for() or JS::GetSymbolFor() - UniqueSymbol = 0xffffffff // created by Symbol() or JS::NewSymbol() -}; - -/* For use in loops that iterate over the well-known symbols. */ -const size_t WellKnownSymbolLimit = size_t(SymbolCode::Limit); - -/** - * Return the SymbolCode telling what sort of symbol `symbol` is. - * - * A symbol's SymbolCode never changes once it is created. - */ -JS_PUBLIC_API(SymbolCode) -GetSymbolCode(Handle symbol); - -/** - * Get one of the well-known symbols defined by ES6. A single set of well-known - * symbols is shared by all compartments in a JSRuntime. - * - * `which` must be in the range [0, WellKnownSymbolLimit). - */ -JS_PUBLIC_API(Symbol*) -GetWellKnownSymbol(JSContext* cx, SymbolCode which); - -/** - * Return true if the given JSPropertySpec::name or JSFunctionSpec::name value - * is actually a symbol code and not a string. See JS_SYM_FN. - */ -inline bool -PropertySpecNameIsSymbol(const char* name) -{ - uintptr_t u = reinterpret_cast(name); - return u != 0 && u - 1 < WellKnownSymbolLimit; -} - -JS_PUBLIC_API(bool) -PropertySpecNameEqualsId(const char* name, HandleId id); - -/** - * Create a jsid that does not need to be marked for GC. - * - * 'name' is a JSPropertySpec::name or JSFunctionSpec::name value. The - * resulting jsid, on success, is either an interned string or a well-known - * symbol; either way it is immune to GC so there is no need to visit *idp - * during GC marking. - */ -JS_PUBLIC_API(bool) -PropertySpecNameToPermanentId(JSContext* cx, const char* name, jsid* idp); - -} /* namespace JS */ - -/************************************************************************/ -/* - * JSON functions - */ -typedef bool (* JSONWriteCallback)(const char16_t* buf, uint32_t len, void* data); - -/** - * JSON.stringify as specified by ES5. - */ -JS_PUBLIC_API(bool) -JS_Stringify(JSContext* cx, JS::MutableHandleValue value, JS::HandleObject replacer, - JS::HandleValue space, JSONWriteCallback callback, void* data); - -namespace JS { - -/** - * An API akin to JS_Stringify but with the goal of not having observable - * side-effects when the stringification is performed. This means it does not - * allow a replacer or a custom space, and has the following constraints on its - * input: - * - * 1) The input must be a plain object or array, not an abitrary value. - * 2) Every value in the graph reached by the algorithm starting with this - * object must be one of the following: null, undefined, a string (NOT a - * string object!), a boolean, a finite number (i.e. no NaN or Infinity or - * -Infinity), a plain object with no accessor properties, or an Array with - * no holes. - * - * The actual behavior differs from JS_Stringify only in asserting the above and - * NOT attempting to get the "toJSON" property from things, since that could - * clearly have side-effects. - */ -JS_PUBLIC_API(bool) -ToJSONMaybeSafely(JSContext* cx, JS::HandleObject input, - JSONWriteCallback callback, void* data); - -} /* namespace JS */ - -/** - * JSON.parse as specified by ES5. - */ -JS_PUBLIC_API(bool) -JS_ParseJSON(JSContext* cx, const char16_t* chars, uint32_t len, JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_ParseJSON(JSContext* cx, JS::HandleString str, JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_ParseJSONWithReviver(JSContext* cx, const char16_t* chars, uint32_t len, JS::HandleValue reviver, - JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_ParseJSONWithReviver(JSContext* cx, JS::HandleString str, JS::HandleValue reviver, - JS::MutableHandleValue vp); - -/************************************************************************/ - -/** - * The default locale for the ECMAScript Internationalization API - * (Intl.Collator, Intl.NumberFormat, Intl.DateTimeFormat). - * Note that the Internationalization API encourages clients to - * specify their own locales. - * The locale string remains owned by the caller. - */ -extern JS_PUBLIC_API(bool) -JS_SetDefaultLocale(JSContext* cx, const char* locale); - -/** - * Look up the default locale for the ECMAScript Internationalization API. - */ -extern JS_PUBLIC_API(JS::UniqueChars) -JS_GetDefaultLocale(JSContext* cx); - -/** - * Reset the default locale to OS defaults. - */ -extern JS_PUBLIC_API(void) -JS_ResetDefaultLocale(JSContext* cx); - -/** - * Locale specific string conversion and error message callbacks. - */ -struct JSLocaleCallbacks { - JSLocaleToUpperCase localeToUpperCase; - JSLocaleToLowerCase localeToLowerCase; - JSLocaleCompare localeCompare; // not used #if EXPOSE_INTL_API - JSLocaleToUnicode localeToUnicode; -}; - -/** - * Establish locale callbacks. The pointer must persist as long as the - * JSContext. Passing nullptr restores the default behaviour. - */ -extern JS_PUBLIC_API(void) -JS_SetLocaleCallbacks(JSContext* cx, const JSLocaleCallbacks* callbacks); - -/** - * Return the address of the current locale callbacks struct, which may - * be nullptr. - */ -extern JS_PUBLIC_API(const JSLocaleCallbacks*) -JS_GetLocaleCallbacks(JSContext* cx); - -/************************************************************************/ - -/* - * Error reporting. - */ - -namespace JS { -const uint16_t MaxNumErrorArguments = 10; -}; - -/** - * Report an exception represented by the sprintf-like conversion of format - * and its arguments. - */ -extern JS_PUBLIC_API(void) -JS_ReportErrorASCII(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(void) -JS_ReportErrorLatin1(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(void) -JS_ReportErrorUTF8(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -/* - * Use an errorNumber to retrieve the format string, args are char* - */ -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberASCII(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberASCIIVA(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, va_list ap); - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberLatin1(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -#ifdef va_start -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberLatin1VA(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, va_list ap); -#endif - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUTF8(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -#ifdef va_start -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUTF8VA(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, va_list ap); -#endif - -/* - * Use an errorNumber to retrieve the format string, args are char16_t* - */ -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUC(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUCArray(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, - const char16_t** args); - -/** - * As above, but report a warning instead (JSREPORT_IS_WARNING(report.flags)). - * Return true if there was no error trying to issue the warning, and if the - * warning was not converted into an error due to the JSOPTION_WERROR option - * being set, false otherwise. - */ -extern JS_PUBLIC_API(bool) -JS_ReportWarningASCII(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(bool) -JS_ReportWarningLatin1(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(bool) -JS_ReportWarningUTF8(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberASCII(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberLatin1(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberUTF8(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberUC(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -/** - * Complain when out of memory. - */ -extern JS_PUBLIC_API(void) -JS_ReportOutOfMemory(JSContext* cx); - -/** - * Complain when an allocation size overflows the maximum supported limit. - */ -extern JS_PUBLIC_API(void) -JS_ReportAllocationOverflow(JSContext* cx); - -class JSErrorReport -{ - // The (default) error message. - // If ownsMessage_ is true, the it is freed in destructor. - JS::ConstUTF8CharsZ message_; - - // Offending source line without final '\n'. - // If ownsLinebuf__ is true, the buffer is freed in destructor. - const char16_t* linebuf_; - - // Number of chars in linebuf_. Does not include trailing '\0'. - size_t linebufLength_; - - // The 0-based offset of error token in linebuf_. - size_t tokenOffset_; - - public: - JSErrorReport() - : linebuf_(nullptr), linebufLength_(0), tokenOffset_(0), - filename(nullptr), lineno(0), column(0), - flags(0), errorNumber(0), - exnType(0), isMuted(false), - ownsLinebuf_(false), ownsMessage_(false) - {} - - ~JSErrorReport() { - freeLinebuf(); - freeMessage(); - } - - const char* filename; /* source file name, URL, etc., or null */ - unsigned lineno; /* source line number */ - unsigned column; /* zero-based column index in line */ - unsigned flags; /* error/warning, etc. */ - unsigned errorNumber; /* the error number, e.g. see js.msg */ - int16_t exnType; /* One of the JSExnType constants */ - bool isMuted : 1; /* See the comment in ReadOnlyCompileOptions. */ - - private: - bool ownsLinebuf_ : 1; - bool ownsMessage_ : 1; - - public: - const char16_t* linebuf() const { - return linebuf_; - } - size_t linebufLength() const { - return linebufLength_; - } - size_t tokenOffset() const { - return tokenOffset_; - } - void initOwnedLinebuf(const char16_t* linebufArg, size_t linebufLengthArg, size_t tokenOffsetArg) { - initBorrowedLinebuf(linebufArg, linebufLengthArg, tokenOffsetArg); - ownsLinebuf_ = true; - } - void initBorrowedLinebuf(const char16_t* linebufArg, size_t linebufLengthArg, size_t tokenOffsetArg); - void freeLinebuf(); - - const JS::ConstUTF8CharsZ message() const { - return message_; - } - - void initOwnedMessage(const char* messageArg) { - initBorrowedMessage(messageArg); - ownsMessage_ = true; - } - void initBorrowedMessage(const char* messageArg) { - MOZ_ASSERT(!message_); - message_ = JS::ConstUTF8CharsZ(messageArg, strlen(messageArg)); - } - - JSString* newMessageString(JSContext* cx); - - void freeMessage(); -}; - -/* - * JSErrorReport flag values. These may be freely composed. - */ -#define JSREPORT_ERROR 0x0 /* pseudo-flag for default case */ -#define JSREPORT_WARNING 0x1 /* reported via JS_ReportWarning */ -#define JSREPORT_EXCEPTION 0x2 /* exception was thrown */ -#define JSREPORT_STRICT 0x4 /* error or warning due to strict option */ - -#define JSREPORT_USER_1 0x8 /* user-defined flag */ - -/* - * If JSREPORT_EXCEPTION is set, then a JavaScript-catchable exception - * has been thrown for this runtime error, and the host should ignore it. - * Exception-aware hosts should also check for JS_IsExceptionPending if - * JS_ExecuteScript returns failure, and signal or propagate the exception, as - * appropriate. - */ -#define JSREPORT_IS_WARNING(flags) (((flags) & JSREPORT_WARNING) != 0) -#define JSREPORT_IS_EXCEPTION(flags) (((flags) & JSREPORT_EXCEPTION) != 0) -#define JSREPORT_IS_STRICT(flags) (((flags) & JSREPORT_STRICT) != 0) - -namespace JS { - -using WarningReporter = void (*)(JSContext* cx, JSErrorReport* report); - -extern JS_PUBLIC_API(WarningReporter) -SetWarningReporter(JSContext* cx, WarningReporter reporter); - -extern JS_PUBLIC_API(WarningReporter) -GetWarningReporter(JSContext* cx); - -extern JS_PUBLIC_API(bool) -CreateError(JSContext* cx, JSExnType type, HandleObject stack, - HandleString fileName, uint32_t lineNumber, uint32_t columnNumber, - JSErrorReport* report, HandleString message, MutableHandleValue rval); - -/************************************************************************/ - -/* - * Weak Maps. - */ - -extern JS_PUBLIC_API(JSObject*) -NewWeakMapObject(JSContext* cx); - -extern JS_PUBLIC_API(bool) -IsWeakMapObject(JSObject* obj); - -extern JS_PUBLIC_API(bool) -GetWeakMapEntry(JSContext* cx, JS::HandleObject mapObj, JS::HandleObject key, - JS::MutableHandleValue val); - -extern JS_PUBLIC_API(bool) -SetWeakMapEntry(JSContext* cx, JS::HandleObject mapObj, JS::HandleObject key, - JS::HandleValue val); - -/* - * Map - */ -extern JS_PUBLIC_API(JSObject*) -NewMapObject(JSContext* cx); - -extern JS_PUBLIC_API(uint32_t) -MapSize(JSContext* cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -MapGet(JSContext* cx, HandleObject obj, - HandleValue key, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapHas(JSContext* cx, HandleObject obj, HandleValue key, bool* rval); - -extern JS_PUBLIC_API(bool) -MapSet(JSContext* cx, HandleObject obj, HandleValue key, HandleValue val); - -extern JS_PUBLIC_API(bool) -MapDelete(JSContext *cx, HandleObject obj, HandleValue key, bool *rval); - -extern JS_PUBLIC_API(bool) -MapClear(JSContext* cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -MapKeys(JSContext* cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapValues(JSContext* cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapEntries(JSContext* cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapForEach(JSContext *cx, HandleObject obj, HandleValue callbackFn, HandleValue thisVal); - -/* - * Set - */ -extern JS_PUBLIC_API(JSObject *) -NewSetObject(JSContext *cx); - -extern JS_PUBLIC_API(uint32_t) -SetSize(JSContext *cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -SetHas(JSContext *cx, HandleObject obj, HandleValue key, bool *rval); - -extern JS_PUBLIC_API(bool) -SetDelete(JSContext *cx, HandleObject obj, HandleValue key, bool *rval); - -extern JS_PUBLIC_API(bool) -SetAdd(JSContext *cx, HandleObject obj, HandleValue key); - -extern JS_PUBLIC_API(bool) -SetClear(JSContext *cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -SetKeys(JSContext *cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -SetValues(JSContext *cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -SetEntries(JSContext *cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -SetForEach(JSContext *cx, HandleObject obj, HandleValue callbackFn, HandleValue thisVal); - -} /* namespace JS */ - -/* - * Dates. - */ - -extern JS_PUBLIC_API(JSObject*) -JS_NewDateObject(JSContext* cx, int year, int mon, int mday, int hour, int min, int sec); - -/** - * Returns true and sets |*isDate| indicating whether |obj| is a Date object or - * a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isDate == false| when passed a proxy whose - * target is a Date, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_ObjectIsDate(JSContext* cx, JS::HandleObject obj, bool* isDate); - -/************************************************************************/ - -/* - * Regular Expressions. - */ -#define JSREG_FOLD 0x01u /* fold uppercase to lowercase */ -#define JSREG_GLOB 0x02u /* global exec, creates array of matches */ -#define JSREG_MULTILINE 0x04u /* treat ^ and $ as begin and end of line */ -#define JSREG_STICKY 0x08u /* only match starting at lastIndex */ -#define JSREG_UNICODE 0x10u /* unicode */ - -extern JS_PUBLIC_API(JSObject*) -JS_NewRegExpObject(JSContext* cx, const char* bytes, size_t length, unsigned flags); - -extern JS_PUBLIC_API(JSObject*) -JS_NewUCRegExpObject(JSContext* cx, const char16_t* chars, size_t length, unsigned flags); - -extern JS_PUBLIC_API(bool) -JS_SetRegExpInput(JSContext* cx, JS::HandleObject obj, JS::HandleString input); - -extern JS_PUBLIC_API(bool) -JS_ClearRegExpStatics(JSContext* cx, JS::HandleObject obj); - -extern JS_PUBLIC_API(bool) -JS_ExecuteRegExp(JSContext* cx, JS::HandleObject obj, JS::HandleObject reobj, - char16_t* chars, size_t length, size_t* indexp, bool test, - JS::MutableHandleValue rval); - -/* RegExp interface for clients without a global object. */ - -extern JS_PUBLIC_API(bool) -JS_ExecuteRegExpNoStatics(JSContext* cx, JS::HandleObject reobj, char16_t* chars, size_t length, - size_t* indexp, bool test, JS::MutableHandleValue rval); - -/** - * Returns true and sets |*isRegExp| indicating whether |obj| is a RegExp - * object or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isRegExp == false| when passed a proxy whose - * target is a RegExp, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_ObjectIsRegExp(JSContext* cx, JS::HandleObject obj, bool* isRegExp); - -extern JS_PUBLIC_API(unsigned) -JS_GetRegExpFlags(JSContext* cx, JS::HandleObject obj); - -extern JS_PUBLIC_API(JSString*) -JS_GetRegExpSource(JSContext* cx, JS::HandleObject obj); - -/************************************************************************/ - -extern JS_PUBLIC_API(bool) -JS_IsExceptionPending(JSContext* cx); - -extern JS_PUBLIC_API(bool) -JS_GetPendingException(JSContext* cx, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(void) -JS_SetPendingException(JSContext* cx, JS::HandleValue v); - -extern JS_PUBLIC_API(void) -JS_ClearPendingException(JSContext* cx); - -namespace JS { - -/** - * Save and later restore the current exception state of a given JSContext. - * This is useful for implementing behavior in C++ that's like try/catch - * or try/finally in JS. - * - * Typical usage: - * - * bool ok = JS::Evaluate(cx, ...); - * AutoSaveExceptionState savedExc(cx); - * ... cleanup that might re-enter JS ... - * return ok; - */ -class JS_PUBLIC_API(AutoSaveExceptionState) -{ - private: - JSContext* context; - bool wasPropagatingForcedReturn; - bool wasOverRecursed; - bool wasThrowing; - RootedValue exceptionValue; - - public: - /* - * Take a snapshot of cx's current exception state. Then clear any current - * pending exception in cx. - */ - explicit AutoSaveExceptionState(JSContext* cx); - - /* - * If neither drop() nor restore() was called, restore the exception - * state only if no exception is currently pending on cx. - */ - ~AutoSaveExceptionState(); - - /* - * Discard any stored exception state. - * If this is called, the destructor is a no-op. - */ - void drop() { - wasPropagatingForcedReturn = false; - wasOverRecursed = false; - wasThrowing = false; - exceptionValue.setUndefined(); - } - - /* - * Replace cx's exception state with the stored exception state. Then - * discard the stored exception state. If this is called, the - * destructor is a no-op. - */ - void restore(); -}; - -} /* namespace JS */ - -/* Deprecated API. Use AutoSaveExceptionState instead. */ -extern JS_PUBLIC_API(JSExceptionState*) -JS_SaveExceptionState(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_RestoreExceptionState(JSContext* cx, JSExceptionState* state); - -extern JS_PUBLIC_API(void) -JS_DropExceptionState(JSContext* cx, JSExceptionState* state); - -/** - * If the given object is an exception object, the exception will have (or be - * able to lazily create) an error report struct, and this function will return - * the address of that struct. Otherwise, it returns nullptr. The lifetime - * of the error report struct that might be returned is the same as the - * lifetime of the exception object. - */ -extern JS_PUBLIC_API(JSErrorReport*) -JS_ErrorFromException(JSContext* cx, JS::HandleObject obj); - -/** - * If the given object is an exception object (or an unwrappable - * cross-compartment wrapper for one), return the stack for that exception, if - * any. Will return null if the given object is not an exception object - * (including if it's null or a security wrapper that can't be unwrapped) or if - * the exception has no stack. - */ -extern JS_PUBLIC_API(JSObject*) -ExceptionStackOrNull(JS::HandleObject obj); - -/* - * Throws a StopIteration exception on cx. - */ -extern JS_PUBLIC_API(bool) -JS_ThrowStopIteration(JSContext* cx); - -extern JS_PUBLIC_API(bool) -JS_IsStopIteration(const JS::Value& v); - -/** - * A JS context always has an "owner thread". The owner thread is set when the - * context is created (to the current thread) and practically all entry points - * into the JS engine check that a context (or anything contained in the - * context: runtime, compartment, object, etc) is only touched by its owner - * thread. Embeddings may check this invariant outside the JS engine by calling - * JS_AbortIfWrongThread (which will abort if not on the owner thread, even for - * non-debug builds). - */ - -extern JS_PUBLIC_API(void) -JS_AbortIfWrongThread(JSContext* cx); - -/************************************************************************/ - -/** - * A constructor can request that the JS engine create a default new 'this' - * object of the given class, using the callee to determine parentage and - * [[Prototype]]. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewObjectForConstructor(JSContext* cx, const JSClass* clasp, const JS::CallArgs& args); - -/************************************************************************/ - -#ifdef JS_GC_ZEAL -#define JS_DEFAULT_ZEAL_FREQ 100 - -extern JS_PUBLIC_API(void) -JS_GetGCZealBits(JSContext* cx, uint32_t* zealBits, uint32_t* frequency, uint32_t* nextScheduled); - -extern JS_PUBLIC_API(void) -JS_SetGCZeal(JSContext* cx, uint8_t zeal, uint32_t frequency); - -extern JS_PUBLIC_API(void) -JS_ScheduleGC(JSContext* cx, uint32_t count); -#endif - -extern JS_PUBLIC_API(void) -JS_SetParallelParsingEnabled(JSContext* cx, bool enabled); - -extern JS_PUBLIC_API(void) -JS_SetOffthreadIonCompilationEnabled(JSContext* cx, bool enabled); - -#define JIT_COMPILER_OPTIONS(Register) \ - Register(BASELINE_WARMUP_TRIGGER, "baseline.warmup.trigger") \ - Register(ION_WARMUP_TRIGGER, "ion.warmup.trigger") \ - Register(ION_GVN_ENABLE, "ion.gvn.enable") \ - Register(ION_FORCE_IC, "ion.forceinlineCaches") \ - Register(ION_ENABLE, "ion.enable") \ - Register(ION_INTERRUPT_WITHOUT_SIGNAL, "ion.interrupt-without-signals") \ - Register(ION_CHECK_RANGE_ANALYSIS, "ion.check-range-analysis") \ - Register(BASELINE_ENABLE, "baseline.enable") \ - Register(OFFTHREAD_COMPILATION_ENABLE, "offthread-compilation.enable") \ - Register(JUMP_THRESHOLD, "jump-threshold") \ - Register(ASMJS_ATOMICS_ENABLE, "asmjs.atomics.enable") \ - Register(WASM_TEST_MODE, "wasm.test-mode") \ - Register(WASM_FOLD_OFFSETS, "wasm.fold-offsets") - -typedef enum JSJitCompilerOption { -#define JIT_COMPILER_DECLARE(key, str) \ - JSJITCOMPILER_ ## key, - - JIT_COMPILER_OPTIONS(JIT_COMPILER_DECLARE) -#undef JIT_COMPILER_DECLARE - - JSJITCOMPILER_NOT_AN_OPTION -} JSJitCompilerOption; - -extern JS_PUBLIC_API(void) -JS_SetGlobalJitCompilerOption(JSContext* cx, JSJitCompilerOption opt, uint32_t value); -extern JS_PUBLIC_API(bool) -JS_GetGlobalJitCompilerOption(JSContext* cx, JSJitCompilerOption opt, uint32_t* valueOut); - -/** - * Convert a uint32_t index into a jsid. - */ -extern JS_PUBLIC_API(bool) -JS_IndexToId(JSContext* cx, uint32_t index, JS::MutableHandleId); - -/** - * Convert chars into a jsid. - * - * |chars| may not be an index. - */ -extern JS_PUBLIC_API(bool) -JS_CharsToId(JSContext* cx, JS::TwoByteChars chars, JS::MutableHandleId); - -/** - * Test if the given string is a valid ECMAScript identifier - */ -extern JS_PUBLIC_API(bool) -JS_IsIdentifier(JSContext* cx, JS::HandleString str, bool* isIdentifier); - -/** - * Test whether the given chars + length are a valid ECMAScript identifier. - * This version is infallible, so just returns whether the chars are an - * identifier. - */ -extern JS_PUBLIC_API(bool) -JS_IsIdentifier(const char16_t* chars, size_t length); - -namespace js { -class ScriptSource; -} // namespace js - -namespace JS { - -class MOZ_RAII JS_PUBLIC_API(AutoFilename) -{ - private: - js::ScriptSource* ss_; - mozilla::Variant filename_; - - AutoFilename(const AutoFilename&) = delete; - AutoFilename& operator=(const AutoFilename&) = delete; - - public: - AutoFilename() - : ss_(nullptr), - filename_(mozilla::AsVariant(nullptr)) - {} - - ~AutoFilename() { - reset(); - } - - void reset(); - - void setOwned(UniqueChars&& filename); - void setUnowned(const char* filename); - void setScriptSource(js::ScriptSource* ss); - - const char* get() const; -}; - -/** - * Return the current filename, line number and column number of the most - * currently running frame. Returns true if a scripted frame was found, false - * otherwise. - * - * If a the embedding has hidden the scripted caller for the topmost activation - * record, this will also return false. - */ -extern JS_PUBLIC_API(bool) -DescribeScriptedCaller(JSContext* cx, AutoFilename* filename = nullptr, - unsigned* lineno = nullptr, unsigned* column = nullptr); - -extern JS_PUBLIC_API(JSObject*) -GetScriptedCallerGlobal(JSContext* cx); - -/** - * Informs the JS engine that the scripted caller should be hidden. This can be - * used by the embedding to maintain an override of the scripted caller in its - * calculations, by hiding the scripted caller in the JS engine and pushing data - * onto a separate stack, which it inspects when DescribeScriptedCaller returns - * null. - * - * We maintain a counter on each activation record. Add() increments the counter - * of the topmost activation, and Remove() decrements it. The count may never - * drop below zero, and must always be exactly zero when the activation is - * popped from the stack. - */ -extern JS_PUBLIC_API(void) -HideScriptedCaller(JSContext* cx); - -extern JS_PUBLIC_API(void) -UnhideScriptedCaller(JSContext* cx); - -class MOZ_RAII AutoHideScriptedCaller -{ - public: - explicit AutoHideScriptedCaller(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mContext(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - HideScriptedCaller(mContext); - } - ~AutoHideScriptedCaller() { - UnhideScriptedCaller(mContext); - } - - protected: - JSContext* mContext; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/* - * Encode/Decode interpreted scripts and functions to/from memory. - */ - -typedef mozilla::Vector TranscodeBuffer; - -enum TranscodeResult -{ - // Successful encoding / decoding. - TranscodeResult_Ok = 0, - - // A warning message, is set to the message out-param. - TranscodeResult_Failure = 0x100, - TranscodeResult_Failure_BadBuildId = TranscodeResult_Failure | 0x1, - TranscodeResult_Failure_RunOnceNotSupported = TranscodeResult_Failure | 0x2, - TranscodeResult_Failure_AsmJSNotSupported = TranscodeResult_Failure | 0x3, - TranscodeResult_Failure_UnknownClassKind = TranscodeResult_Failure | 0x4, - - // A error, the JSContext has a pending exception. - TranscodeResult_Throw = 0x200 -}; - -extern JS_PUBLIC_API(TranscodeResult) -EncodeScript(JSContext* cx, TranscodeBuffer& buffer, JS::HandleScript script); - -extern JS_PUBLIC_API(TranscodeResult) -EncodeInterpretedFunction(JSContext* cx, TranscodeBuffer& buffer, JS::HandleObject funobj); - -extern JS_PUBLIC_API(TranscodeResult) -DecodeScript(JSContext* cx, TranscodeBuffer& buffer, JS::MutableHandleScript scriptp, - size_t cursorIndex = 0); - -extern JS_PUBLIC_API(TranscodeResult) -DecodeInterpretedFunction(JSContext* cx, TranscodeBuffer& buffer, JS::MutableHandleFunction funp, - size_t cursorIndex = 0); - -} /* namespace JS */ - -namespace js { - -enum class StackFormat { SpiderMonkey, V8, Default }; - -/* - * Sets the format used for stringifying Error stacks. - * - * The default format is StackFormat::SpiderMonkey. Use StackFormat::V8 - * in order to emulate V8's stack formatting. StackFormat::Default can't be - * used here. - */ -extern JS_PUBLIC_API(void) -SetStackFormat(JSContext* cx, StackFormat format); - -extern JS_PUBLIC_API(StackFormat) -GetStackFormat(JSContext* cx); - -} - -namespace JS { - -/* - * This callback represents a request by the JS engine to open for reading the - * existing cache entry for the given global and char range that may contain a - * module. If a cache entry exists, the callback shall return 'true' and return - * the size, base address and an opaque file handle as outparams. If the - * callback returns 'true', the JS engine guarantees a call to - * CloseAsmJSCacheEntryForReadOp, passing the same base address, size and - * handle. - */ -typedef bool -(* OpenAsmJSCacheEntryForReadOp)(HandleObject global, const char16_t* begin, const char16_t* limit, - size_t* size, const uint8_t** memory, intptr_t* handle); -typedef void -(* CloseAsmJSCacheEntryForReadOp)(size_t size, const uint8_t* memory, intptr_t handle); - -/** The list of reasons why an asm.js module may not be stored in the cache. */ -enum AsmJSCacheResult -{ - AsmJSCache_Success, - AsmJSCache_MIN = AsmJSCache_Success, - AsmJSCache_ModuleTooSmall, - AsmJSCache_SynchronousScript, - AsmJSCache_QuotaExceeded, - AsmJSCache_StorageInitFailure, - AsmJSCache_Disabled_Internal, - AsmJSCache_Disabled_ShellFlags, - AsmJSCache_Disabled_JitInspector, - AsmJSCache_InternalError, - AsmJSCache_Disabled_PrivateBrowsing, - AsmJSCache_LIMIT -}; - -/* - * This callback represents a request by the JS engine to open for writing a - * cache entry of the given size for the given global and char range containing - * the just-compiled module. If cache entry space is available, the callback - * shall return 'true' and return the base address and an opaque file handle as - * outparams. If the callback returns 'true', the JS engine guarantees a call - * to CloseAsmJSCacheEntryForWriteOp passing the same base address, size and - * handle. - * - * If 'installed' is true, then the cache entry is associated with a permanently - * installed JS file (e.g., in a packaged webapp). This information allows the - * embedding to store the cache entry in a installed location associated with - * the principal of 'global' where it will not be evicted until the associated - * installed JS file is removed. - */ -typedef AsmJSCacheResult -(* OpenAsmJSCacheEntryForWriteOp)(HandleObject global, bool installed, - const char16_t* begin, const char16_t* end, - size_t size, uint8_t** memory, intptr_t* handle); -typedef void -(* CloseAsmJSCacheEntryForWriteOp)(size_t size, uint8_t* memory, intptr_t handle); - -struct AsmJSCacheOps -{ - OpenAsmJSCacheEntryForReadOp openEntryForRead; - CloseAsmJSCacheEntryForReadOp closeEntryForRead; - OpenAsmJSCacheEntryForWriteOp openEntryForWrite; - CloseAsmJSCacheEntryForWriteOp closeEntryForWrite; -}; - -extern JS_PUBLIC_API(void) -SetAsmJSCacheOps(JSContext* cx, const AsmJSCacheOps* callbacks); - -/** - * Return the buildId (represented as a sequence of characters) associated with - * the currently-executing build. If the JS engine is embedded such that a - * single cache entry can be observed by different compiled versions of the JS - * engine, it is critical that the buildId shall change for each new build of - * the JS engine. - */ -typedef js::Vector BuildIdCharVector; - -typedef bool -(* BuildIdOp)(BuildIdCharVector* buildId); - -extern JS_PUBLIC_API(void) -SetBuildIdOp(JSContext* cx, BuildIdOp buildIdOp); - -/** - * The WasmModule interface allows the embedding to hold a reference to the - * underying C++ implementation of a JS WebAssembly.Module object for purposes - * of (de)serialization off the object's JSRuntime's thread. - * - * - Serialization starts when WebAssembly.Module is passed to the - * structured-clone algorithm. JS::GetWasmModule is called on the JSRuntime - * thread that initiated the structured clone to get the JS::WasmModule. - * This interface is then taken to a background thread where serializedSize() - * and serialize() are called to write the object to two files: a bytecode file - * that always allows successful deserialization and a compiled-code file keyed - * on cpu- and build-id that may become invalid if either of these change between - * serialization and deserialization. After serialization, the reference is - * dropped from the background thread. - * - * - Deserialization starts when the structured clone algorithm encounters a - * serialized WebAssembly.Module. On a background thread, the compiled-code file - * is opened and CompiledWasmModuleAssumptionsMatch is called to see if it is - * still valid (as described above). DeserializeWasmModule is then called to - * construct a JS::WasmModule (also on the background thread), passing the - * bytecode file descriptor and, if valid, the compiled-code file descriptor. - * The JS::WasmObject is then transported to the JSRuntime thread (which - * originated the request) and the wrapping WebAssembly.Module object is created - * by calling createObject(). - */ - -struct WasmModule : mozilla::external::AtomicRefCounted -{ - MOZ_DECLARE_REFCOUNTED_TYPENAME(WasmModule) - virtual ~WasmModule() {} - - virtual void serializedSize(size_t* maybeBytecodeSize, size_t* maybeCompiledSize) const = 0; - virtual void serialize(uint8_t* maybeBytecodeBegin, size_t maybeBytecodeSize, - uint8_t* maybeCompiledBegin, size_t maybeCompiledSize) const = 0; - - virtual JSObject* createObject(JSContext* cx) = 0; -}; - -extern JS_PUBLIC_API(bool) -IsWasmModuleObject(HandleObject obj); - -extern JS_PUBLIC_API(RefPtr) -GetWasmModule(HandleObject obj); - -extern JS_PUBLIC_API(bool) -CompiledWasmModuleAssumptionsMatch(PRFileDesc* compiled, BuildIdCharVector&& buildId); - -extern JS_PUBLIC_API(RefPtr) -DeserializeWasmModule(PRFileDesc* bytecode, PRFileDesc* maybeCompiled, BuildIdCharVector&& buildId, - JS::UniqueChars filename, unsigned line, unsigned column); - -/** - * Convenience class for imitating a JS level for-of loop. Typical usage: - * - * ForOfIterator it(cx); - * if (!it.init(iterable)) - * return false; - * RootedValue val(cx); - * while (true) { - * bool done; - * if (!it.next(&val, &done)) - * return false; - * if (done) - * break; - * if (!DoStuff(cx, val)) - * return false; - * } - */ -class MOZ_STACK_CLASS JS_PUBLIC_API(ForOfIterator) { - protected: - JSContext* cx_; - /* - * Use the ForOfPIC on the global object (see vm/GlobalObject.h) to try - * to optimize iteration across arrays. - * - * Case 1: Regular Iteration - * iterator - pointer to the iterator object. - * index - fixed to NOT_ARRAY (== UINT32_MAX) - * - * Case 2: Optimized Array Iteration - * iterator - pointer to the array object. - * index - current position in array. - * - * The cases are distinguished by whether or not |index| is equal to NOT_ARRAY. - */ - JS::RootedObject iterator; - uint32_t index; - - static const uint32_t NOT_ARRAY = UINT32_MAX; - - ForOfIterator(const ForOfIterator&) = delete; - ForOfIterator& operator=(const ForOfIterator&) = delete; - - public: - explicit ForOfIterator(JSContext* cx) : cx_(cx), iterator(cx_), index(NOT_ARRAY) { } - - enum NonIterableBehavior { - ThrowOnNonIterable, - AllowNonIterable - }; - - /** - * Initialize the iterator. If AllowNonIterable is passed then if getting - * the @@iterator property from iterable returns undefined init() will just - * return true instead of throwing. Callers must then check - * valueIsIterable() before continuing with the iteration. - */ - bool init(JS::HandleValue iterable, - NonIterableBehavior nonIterableBehavior = ThrowOnNonIterable); - - /** - * Get the next value from the iterator. If false *done is true - * after this call, do not examine val. - */ - bool next(JS::MutableHandleValue val, bool* done); - - /** - * If initialized with throwOnNonCallable = false, check whether - * the value is iterable. - */ - bool valueIsIterable() const { - return iterator; - } - - private: - inline bool nextFromOptimizedArray(MutableHandleValue val, bool* done); - bool materializeArrayIterator(); -}; - - -/** - * If a large allocation fails when calling pod_{calloc,realloc}CanGC, the JS - * engine may call the large-allocation- failure callback, if set, to allow the - * embedding to flush caches, possibly perform shrinking GCs, etc. to make some - * room. The allocation will then be retried (and may still fail.) - */ - -typedef void -(* LargeAllocationFailureCallback)(void* data); - -extern JS_PUBLIC_API(void) -SetLargeAllocationFailureCallback(JSContext* cx, LargeAllocationFailureCallback afc, void* data); - -/** - * Unlike the error reporter, which is only called if the exception for an OOM - * bubbles up and is not caught, the OutOfMemoryCallback is called immediately - * at the OOM site to allow the embedding to capture the current state of heap - * allocation before anything is freed. If the large-allocation-failure callback - * is called at all (not all allocation sites call the large-allocation-failure - * callback on failure), it is called before the out-of-memory callback; the - * out-of-memory callback is only called if the allocation still fails after the - * large-allocation-failure callback has returned. - */ - -typedef void -(* OutOfMemoryCallback)(JSContext* cx, void* data); - -extern JS_PUBLIC_API(void) -SetOutOfMemoryCallback(JSContext* cx, OutOfMemoryCallback cb, void* data); - -/** - * Capture all frames. - */ -struct AllFrames { }; - -/** - * Capture at most this many frames. - */ -struct MaxFrames -{ - uint32_t maxFrames; - - explicit MaxFrames(uint32_t max) - : maxFrames(max) - { - MOZ_ASSERT(max > 0); - } -}; - -/** - * Capture the first frame with the given principals. By default, do not - * consider self-hosted frames with the given principals as satisfying the stack - * capture. - */ -struct FirstSubsumedFrame -{ - JSContext* cx; - JSPrincipals* principals; - bool ignoreSelfHosted; - - /** - * Use the cx's current compartment's principals. - */ - explicit FirstSubsumedFrame(JSContext* cx, bool ignoreSelfHostedFrames = true); - - explicit FirstSubsumedFrame(JSContext* ctx, JSPrincipals* p, bool ignoreSelfHostedFrames = true) - : cx(ctx) - , principals(p) - , ignoreSelfHosted(ignoreSelfHostedFrames) - { - if (principals) - JS_HoldPrincipals(principals); - } - - // No copying because we want to avoid holding and dropping principals - // unnecessarily. - FirstSubsumedFrame(const FirstSubsumedFrame&) = delete; - FirstSubsumedFrame& operator=(const FirstSubsumedFrame&) = delete; - - FirstSubsumedFrame(FirstSubsumedFrame&& rhs) - : principals(rhs.principals) - , ignoreSelfHosted(rhs.ignoreSelfHosted) - { - MOZ_ASSERT(this != &rhs, "self move disallowed"); - rhs.principals = nullptr; - } - - FirstSubsumedFrame& operator=(FirstSubsumedFrame&& rhs) { - new (this) FirstSubsumedFrame(mozilla::Move(rhs)); - return *this; - } - - ~FirstSubsumedFrame() { - if (principals) - JS_DropPrincipals(cx, principals); - } -}; - -using StackCapture = mozilla::Variant; - -/** - * Capture the current call stack as a chain of SavedFrame JSObjects, and set - * |stackp| to the SavedFrame for the youngest stack frame, or nullptr if there - * are no JS frames on the stack. - * - * The |capture| parameter describes the portion of the JS stack to capture: - * - * * |JS::AllFrames|: Capture all frames on the stack. - * - * * |JS::MaxFrames|: Capture no more than |JS::MaxFrames::maxFrames| from the - * stack. - * - * * |JS::FirstSubsumedFrame|: Capture the first frame whose principals are - * subsumed by |JS::FirstSubsumedFrame::principals|. By default, do not - * consider self-hosted frames; this can be controlled via the - * |JS::FirstSubsumedFrame::ignoreSelfHosted| flag. Do not capture any async - * stack. - */ -extern JS_PUBLIC_API(bool) -CaptureCurrentStack(JSContext* cx, MutableHandleObject stackp, - StackCapture&& capture = StackCapture(AllFrames())); - -/* - * This is a utility function for preparing an async stack to be used - * by some other object. This may be used when you need to treat a - * given stack trace as an async parent. If you just need to capture - * the current stack, async parents and all, use CaptureCurrentStack - * instead. - * - * Here |asyncStack| is the async stack to prepare. It is copied into - * |cx|'s current compartment, and the newest frame is given - * |asyncCause| as its asynchronous cause. If |maxFrameCount| is - * non-zero, capture at most the youngest |maxFrameCount| frames. The - * new stack object is written to |stackp|. Returns true on success, - * or sets an exception and returns |false| on error. - */ -extern JS_PUBLIC_API(bool) -CopyAsyncStack(JSContext* cx, HandleObject asyncStack, - HandleString asyncCause, MutableHandleObject stackp, - unsigned maxFrameCount); - -/* - * Accessors for working with SavedFrame JSObjects - * - * Each of these functions assert that if their `HandleObject savedFrame` - * argument is non-null, its JSClass is the SavedFrame class (or it is a - * cross-compartment or Xray wrapper around an object with the SavedFrame class) - * and the object is not the SavedFrame.prototype object. - * - * Each of these functions will find the first SavedFrame object in the chain - * whose underlying stack frame principals are subsumed by the cx's current - * compartment's principals, and operate on that SavedFrame object. This - * prevents leaking information about privileged frames to un-privileged - * callers. As a result, the SavedFrame in parameters do _NOT_ need to be in the - * same compartment as the cx, and the various out parameters are _NOT_ - * guaranteed to be in the same compartment as cx. - * - * You may consider or skip over self-hosted frames by passing - * `SavedFrameSelfHosted::Include` or `SavedFrameSelfHosted::Exclude` - * respectively. - * - * Additionally, it may be the case that there is no such SavedFrame object - * whose captured frame's principals are subsumed by the caller's compartment's - * principals! If the `HandleObject savedFrame` argument is null, or the - * caller's principals do not subsume any of the chained SavedFrame object's - * principals, `SavedFrameResult::AccessDenied` is returned and a (hopefully) - * sane default value is chosen for the out param. - * - * See also `js/src/doc/SavedFrame/SavedFrame.md`. - */ - -enum class SavedFrameResult { - Ok, - AccessDenied -}; - -enum class SavedFrameSelfHosted { - Include, - Exclude -}; - -/** - * Given a SavedFrame JSObject, get its source property. Defaults to the empty - * string. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameSource(JSContext* cx, HandleObject savedFrame, MutableHandleString sourcep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its line property. Defaults to 0. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameLine(JSContext* cx, HandleObject savedFrame, uint32_t* linep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its column property. Defaults to 0. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameColumn(JSContext* cx, HandleObject savedFrame, uint32_t* columnp, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its functionDisplayName string, or nullptr - * if SpiderMonkey was unable to infer a name for the captured frame's - * function. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameFunctionDisplayName(JSContext* cx, HandleObject savedFrame, MutableHandleString namep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its asyncCause string. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameAsyncCause(JSContext* cx, HandleObject savedFrame, MutableHandleString asyncCausep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its asyncParent SavedFrame object or nullptr - * if there is no asyncParent. The `asyncParentp` out parameter is _NOT_ - * guaranteed to be in the cx's compartment. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameAsyncParent(JSContext* cx, HandleObject savedFrame, MutableHandleObject asyncParentp, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its parent SavedFrame object or nullptr if - * it is the oldest frame in the stack. The `parentp` out parameter is _NOT_ - * guaranteed to be in the cx's compartment. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameParent(JSContext* cx, HandleObject savedFrame, MutableHandleObject parentp, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject stack, stringify it in the same format as - * Error.prototype.stack. The stringified stack out parameter is placed in the - * cx's compartment. Defaults to the empty string. - * - * The same notes above about SavedFrame accessors applies here as well: cx - * doesn't need to be in stack's compartment, and stack can be null, a - * SavedFrame object, or a wrapper (CCW or Xray) around a SavedFrame object. - * - * Optional indent parameter specifies the number of white spaces to indent - * each line. - */ -extern JS_PUBLIC_API(bool) -BuildStackString(JSContext* cx, HandleObject stack, MutableHandleString stringp, - size_t indent = 0, js::StackFormat stackFormat = js::StackFormat::Default); - -/** - * Return true iff the given object is either a SavedFrame object or wrapper - * around a SavedFrame object, and it is not the SavedFrame.prototype object. - */ -extern JS_PUBLIC_API(bool) -IsSavedFrame(JSObject* obj); - -} /* namespace JS */ - - -/* Stopwatch-based performance monitoring. */ - -namespace js { - -class AutoStopwatch; - -/** - * Abstract base class for a representation of the performance of a - * component. Embeddings interested in performance monitoring should - * provide a concrete implementation of this class, as well as the - * relevant callbacks (see below). - */ -struct PerformanceGroup { - PerformanceGroup(); - - // The current iteration of the event loop. - uint64_t iteration() const; - - // `true` if an instance of `AutoStopwatch` is already monitoring - // the performance of this performance group for this iteration - // of the event loop, `false` otherwise. - bool isAcquired(uint64_t it) const; - - // `true` if a specific instance of `AutoStopwatch` is already monitoring - // the performance of this performance group for this iteration - // of the event loop, `false` otherwise. - bool isAcquired(uint64_t it, const AutoStopwatch* owner) const; - - // Mark that an instance of `AutoStopwatch` is monitoring - // the performance of this group for a given iteration. - void acquire(uint64_t it, const AutoStopwatch* owner); - - // Mark that no `AutoStopwatch` is monitoring the - // performance of this group for the iteration. - void release(uint64_t it, const AutoStopwatch* owner); - - // The number of cycles spent in this group during this iteration - // of the event loop. Note that cycles are not a reliable measure, - // especially over short intervals. See Stopwatch.* for a more - // complete discussion on the imprecision of cycle measurement. - uint64_t recentCycles(uint64_t iteration) const; - void addRecentCycles(uint64_t iteration, uint64_t cycles); - - // The number of times this group has been activated during this - // iteration of the event loop. - uint64_t recentTicks(uint64_t iteration) const; - void addRecentTicks(uint64_t iteration, uint64_t ticks); - - // The number of microseconds spent doing CPOW during this - // iteration of the event loop. - uint64_t recentCPOW(uint64_t iteration) const; - void addRecentCPOW(uint64_t iteration, uint64_t CPOW); - - // Get rid of any data that pretends to be recent. - void resetRecentData(); - - // `true` if new measures should be added to this group, `false` - // otherwise. - bool isActive() const; - void setIsActive(bool); - - // `true` if this group has been used in the current iteration, - // `false` otherwise. - bool isUsedInThisIteration() const; - void setIsUsedInThisIteration(bool); - protected: - // An implementation of `delete` for this object. Must be provided - // by the embedding. - virtual void Delete() = 0; - - private: - // The number of cycles spent in this group during this iteration - // of the event loop. Note that cycles are not a reliable measure, - // especially over short intervals. See Runtime.cpp for a more - // complete discussion on the imprecision of cycle measurement. - uint64_t recentCycles_; - - // The number of times this group has been activated during this - // iteration of the event loop. - uint64_t recentTicks_; - - // The number of microseconds spent doing CPOW during this - // iteration of the event loop. - uint64_t recentCPOW_; - - // The current iteration of the event loop. If necessary, - // may safely overflow. - uint64_t iteration_; - - // `true` if new measures should be added to this group, `false` - // otherwise. - bool isActive_; - - // `true` if this group has been used in the current iteration, - // `false` otherwise. - bool isUsedInThisIteration_; - - // The stopwatch currently monitoring the group, - // or `nullptr` if none. Used ony for comparison. - const AutoStopwatch* owner_; - - public: - // Compatibility with RefPtr<> - void AddRef(); - void Release(); - uint64_t refCount_; -}; - -using PerformanceGroupVector = mozilla::Vector, 0, SystemAllocPolicy>; - -/** - * Commit any Performance Monitoring data. - * - * Until `FlushMonitoring` has been called, all PerformanceMonitoring data is invisible - * to the outside world and can cancelled with a call to `ResetMonitoring`. - */ -extern JS_PUBLIC_API(bool) -FlushPerformanceMonitoring(JSContext*); - -/** - * Cancel any measurement that hasn't been committed. - */ -extern JS_PUBLIC_API(void) -ResetPerformanceMonitoring(JSContext*); - -/** - * Cleanup any memory used by performance monitoring. - */ -extern JS_PUBLIC_API(void) -DisposePerformanceMonitoring(JSContext*); - -/** - * Turn on/off stopwatch-based CPU monitoring. - * - * `SetStopwatchIsMonitoringCPOW` or `SetStopwatchIsMonitoringJank` - * may return `false` if monitoring could not be activated, which may - * happen if we are out of memory. - */ -extern JS_PUBLIC_API(bool) -SetStopwatchIsMonitoringCPOW(JSContext*, bool); -extern JS_PUBLIC_API(bool) -GetStopwatchIsMonitoringCPOW(JSContext*); -extern JS_PUBLIC_API(bool) -SetStopwatchIsMonitoringJank(JSContext*, bool); -extern JS_PUBLIC_API(bool) -GetStopwatchIsMonitoringJank(JSContext*); - -// Extract the CPU rescheduling data. -extern JS_PUBLIC_API(void) -GetPerfMonitoringTestCpuRescheduling(JSContext*, uint64_t* stayed, uint64_t* moved); - - -/** - * Add a number of microseconds to the time spent waiting on CPOWs - * since process start. - */ -extern JS_PUBLIC_API(void) -AddCPOWPerformanceDelta(JSContext*, uint64_t delta); - -typedef bool -(*StopwatchStartCallback)(uint64_t, void*); -extern JS_PUBLIC_API(bool) -SetStopwatchStartCallback(JSContext*, StopwatchStartCallback, void*); - -typedef bool -(*StopwatchCommitCallback)(uint64_t, PerformanceGroupVector&, void*); -extern JS_PUBLIC_API(bool) -SetStopwatchCommitCallback(JSContext*, StopwatchCommitCallback, void*); - -typedef bool -(*GetGroupsCallback)(JSContext*, PerformanceGroupVector&, void*); -extern JS_PUBLIC_API(bool) -SetGetPerformanceGroupsCallback(JSContext*, GetGroupsCallback, void*); - -} /* namespace js */ - - -#endif /* jsapi_h */ diff --git a/mac/include/spidermonkey/jsbytecode.h b/mac/include/spidermonkey/jsbytecode.h deleted file mode 100644 index 8e4f4cf9..00000000 --- a/mac/include/spidermonkey/jsbytecode.h +++ /dev/null @@ -1,14 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsbytecode_h -#define jsbytecode_h - -#include - -typedef uint8_t jsbytecode; - -#endif /* jsbytecode_h */ diff --git a/mac/include/spidermonkey/jsclist.h b/mac/include/spidermonkey/jsclist.h deleted file mode 100644 index b8455152..00000000 --- a/mac/include/spidermonkey/jsclist.h +++ /dev/null @@ -1,107 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsclist_h -#define jsclist_h - -#include "jstypes.h" - -/* -** Circular linked list -*/ -typedef struct JSCListStr { - struct JSCListStr* next; - struct JSCListStr* prev; -} JSCList; - -/* -** Insert element "_e" into the list, before "_l". -*/ -#define JS_INSERT_BEFORE(_e,_l) \ - JS_BEGIN_MACRO \ - (_e)->next = (_l); \ - (_e)->prev = (_l)->prev; \ - (_l)->prev->next = (_e); \ - (_l)->prev = (_e); \ - JS_END_MACRO - -/* -** Insert element "_e" into the list, after "_l". -*/ -#define JS_INSERT_AFTER(_e,_l) \ - JS_BEGIN_MACRO \ - (_e)->next = (_l)->next; \ - (_e)->prev = (_l); \ - (_l)->next->prev = (_e); \ - (_l)->next = (_e); \ - JS_END_MACRO - -/* -** Return the element following element "_e" -*/ -#define JS_NEXT_LINK(_e) \ - ((_e)->next) -/* -** Return the element preceding element "_e" -*/ -#define JS_PREV_LINK(_e) \ - ((_e)->prev) - -/* -** Append an element "_e" to the end of the list "_l" -*/ -#define JS_APPEND_LINK(_e,_l) JS_INSERT_BEFORE(_e,_l) - -/* -** Insert an element "_e" at the head of the list "_l" -*/ -#define JS_INSERT_LINK(_e,_l) JS_INSERT_AFTER(_e,_l) - -/* Return the head/tail of the list */ -#define JS_LIST_HEAD(_l) (_l)->next -#define JS_LIST_TAIL(_l) (_l)->prev - -/* -** Remove the element "_e" from it's circular list. -*/ -#define JS_REMOVE_LINK(_e) \ - JS_BEGIN_MACRO \ - (_e)->prev->next = (_e)->next; \ - (_e)->next->prev = (_e)->prev; \ - JS_END_MACRO - -/* -** Remove the element "_e" from it's circular list. Also initializes the -** linkage. -*/ -#define JS_REMOVE_AND_INIT_LINK(_e) \ - JS_BEGIN_MACRO \ - (_e)->prev->next = (_e)->next; \ - (_e)->next->prev = (_e)->prev; \ - (_e)->next = (_e); \ - (_e)->prev = (_e); \ - JS_END_MACRO - -/* -** Return non-zero if the given circular list "_l" is empty, zero if the -** circular list is not empty -*/ -#define JS_CLIST_IS_EMPTY(_l) \ - bool((_l)->next == (_l)) - -/* -** Initialize a circular list -*/ -#define JS_INIT_CLIST(_l) \ - JS_BEGIN_MACRO \ - (_l)->next = (_l); \ - (_l)->prev = (_l); \ - JS_END_MACRO - -#define JS_INIT_STATIC_CLIST(_l) \ - {(_l), (_l)} - -#endif /* jsclist_h */ diff --git a/mac/include/spidermonkey/jscpucfg.h b/mac/include/spidermonkey/jscpucfg.h deleted file mode 100644 index 80fdf6bb..00000000 --- a/mac/include/spidermonkey/jscpucfg.h +++ /dev/null @@ -1,20 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jscpucfg_h -#define jscpucfg_h - -#include "mozilla/EndianUtils.h" - -#ifndef JS_STACK_GROWTH_DIRECTION -# ifdef __hppa -# define JS_STACK_GROWTH_DIRECTION (1) -# else -# define JS_STACK_GROWTH_DIRECTION (-1) -# endif -#endif - -#endif /* jscpucfg_h */ diff --git a/mac/include/spidermonkey/jsfriendapi.h b/mac/include/spidermonkey/jsfriendapi.h deleted file mode 100644 index d6463d3d..00000000 --- a/mac/include/spidermonkey/jsfriendapi.h +++ /dev/null @@ -1,3067 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsfriendapi_h -#define jsfriendapi_h - -#include "mozilla/Atomics.h" -#include "mozilla/Casting.h" -#include "mozilla/Maybe.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/UniquePtr.h" - -#include "jsapi.h" // For JSAutoByteString. See bug 1033916. -#include "jsbytecode.h" -#include "jspubtd.h" - -#include "js/CallArgs.h" -#include "js/CallNonGenericMethod.h" -#include "js/Class.h" -#include "js/Utility.h" - -#if JS_STACK_GROWTH_DIRECTION > 0 -# define JS_CHECK_STACK_SIZE(limit, sp) (MOZ_LIKELY((uintptr_t)(sp) < (limit))) -#else -# define JS_CHECK_STACK_SIZE(limit, sp) (MOZ_LIKELY((uintptr_t)(sp) > (limit))) -#endif - -class JSAtom; -struct JSErrorFormatString; -class JSLinearString; -struct JSJitInfo; -class JSErrorReport; - -namespace JS { -template -class Heap; -} /* namespace JS */ - -namespace js { -class JS_FRIEND_API(BaseProxyHandler); -class InterpreterFrame; -} /* namespace js */ - -extern JS_FRIEND_API(void) -JS_SetGrayGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data); - -extern JS_FRIEND_API(JSObject*) -JS_FindCompilationScope(JSContext* cx, JS::HandleObject obj); - -extern JS_FRIEND_API(JSFunction*) -JS_GetObjectFunction(JSObject* obj); - -extern JS_FRIEND_API(bool) -JS_SplicePrototype(JSContext* cx, JS::HandleObject obj, JS::HandleObject proto); - -extern JS_FRIEND_API(JSObject*) -JS_NewObjectWithUniqueType(JSContext* cx, const JSClass* clasp, JS::HandleObject proto); - -/** - * Allocate an object in exactly the same way as JS_NewObjectWithGivenProto, but - * without invoking the metadata callback on it. This allows creation of - * internal bookkeeping objects that are guaranteed to not have metadata - * attached to them. - */ -extern JS_FRIEND_API(JSObject*) -JS_NewObjectWithoutMetadata(JSContext* cx, const JSClass* clasp, JS::Handle proto); - -extern JS_FRIEND_API(uint32_t) -JS_ObjectCountDynamicSlots(JS::HandleObject obj); - -extern JS_FRIEND_API(size_t) -JS_SetProtoCalled(JSContext* cx); - -extern JS_FRIEND_API(size_t) -JS_GetCustomIteratorCount(JSContext* cx); - -extern JS_FRIEND_API(bool) -JS_NondeterministicGetWeakMapKeys(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject ret); - -extern JS_FRIEND_API(bool) -JS_NondeterministicGetWeakSetKeys(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject ret); - -// Raw JSScript* because this needs to be callable from a signal handler. -extern JS_FRIEND_API(unsigned) -JS_PCToLineNumber(JSScript* script, jsbytecode* pc, unsigned* columnp = nullptr); - -/** - * Determine whether the given object is backed by a DeadObjectProxy. - * - * Such objects hold no other objects (they have no outgoing reference edges) - * and will throw if you touch them (e.g. by reading/writing a property). - */ -extern JS_FRIEND_API(bool) -JS_IsDeadWrapper(JSObject* obj); - -/* - * Used by the cycle collector to trace through a shape or object group and - * all cycle-participating data it reaches, using bounded stack space. - */ -extern JS_FRIEND_API(void) -JS_TraceShapeCycleCollectorChildren(JS::CallbackTracer* trc, JS::GCCellPtr shape); -extern JS_FRIEND_API(void) -JS_TraceObjectGroupCycleCollectorChildren(JS::CallbackTracer* trc, JS::GCCellPtr group); - -enum { - JS_TELEMETRY_GC_REASON, - JS_TELEMETRY_GC_IS_ZONE_GC, - JS_TELEMETRY_GC_MS, - JS_TELEMETRY_GC_BUDGET_MS, - JS_TELEMETRY_GC_ANIMATION_MS, - JS_TELEMETRY_GC_MAX_PAUSE_MS, - JS_TELEMETRY_GC_MARK_MS, - JS_TELEMETRY_GC_SWEEP_MS, - JS_TELEMETRY_GC_COMPACT_MS, - JS_TELEMETRY_GC_MARK_ROOTS_MS, - JS_TELEMETRY_GC_MARK_GRAY_MS, - JS_TELEMETRY_GC_SLICE_MS, - JS_TELEMETRY_GC_SLOW_PHASE, - JS_TELEMETRY_GC_MMU_50, - JS_TELEMETRY_GC_RESET, - JS_TELEMETRY_GC_RESET_REASON, - JS_TELEMETRY_GC_INCREMENTAL_DISABLED, - JS_TELEMETRY_GC_NON_INCREMENTAL, - JS_TELEMETRY_GC_NON_INCREMENTAL_REASON, - JS_TELEMETRY_GC_SCC_SWEEP_TOTAL_MS, - JS_TELEMETRY_GC_SCC_SWEEP_MAX_PAUSE_MS, - JS_TELEMETRY_GC_MINOR_REASON, - JS_TELEMETRY_GC_MINOR_REASON_LONG, - JS_TELEMETRY_GC_MINOR_US, - JS_TELEMETRY_GC_NURSERY_BYTES, - JS_TELEMETRY_GC_PRETENURE_COUNT, - JS_TELEMETRY_DEPRECATED_LANGUAGE_EXTENSIONS_IN_CONTENT, - JS_TELEMETRY_DEPRECATED_LANGUAGE_EXTENSIONS_IN_ADDONS, - JS_TELEMETRY_ADDON_EXCEPTIONS, - JS_TELEMETRY_AOT_USAGE, - JS_TELEMETRY_END -}; - -typedef void -(*JSAccumulateTelemetryDataCallback)(int id, uint32_t sample, const char* key); - -extern JS_FRIEND_API(void) -JS_SetAccumulateTelemetryCallback(JSContext* cx, JSAccumulateTelemetryDataCallback callback); - -extern JS_FRIEND_API(bool) -JS_GetIsSecureContext(JSCompartment* compartment); - -extern JS_FRIEND_API(JSPrincipals*) -JS_GetCompartmentPrincipals(JSCompartment* compartment); - -extern JS_FRIEND_API(void) -JS_SetCompartmentPrincipals(JSCompartment* compartment, JSPrincipals* principals); - -extern JS_FRIEND_API(JSPrincipals*) -JS_GetScriptPrincipals(JSScript* script); - -extern JS_FRIEND_API(bool) -JS_ScriptHasMutedErrors(JSScript* script); - -extern JS_FRIEND_API(JSObject*) -JS_CloneObject(JSContext* cx, JS::HandleObject obj, JS::HandleObject proto); - -/** - * Copy the own properties of src to dst in a fast way. src and dst must both - * be native and must be in the compartment of cx. They must have the same - * class, the same parent, and the same prototype. Class reserved slots will - * NOT be copied. - * - * dst must not have any properties on it before this function is called. - * - * src must have been allocated via JS_NewObjectWithoutMetadata so that we can - * be sure it has no metadata that needs copying to dst. This also means that - * dst needs to have the compartment global as its parent. This function will - * preserve the existing metadata on dst, if any. - */ -extern JS_FRIEND_API(bool) -JS_InitializePropertiesFromCompatibleNativeObject(JSContext* cx, - JS::HandleObject dst, - JS::HandleObject src); - -extern JS_FRIEND_API(JSString*) -JS_BasicObjectToString(JSContext* cx, JS::HandleObject obj); - -namespace js { - -JS_FRIEND_API(bool) -GetBuiltinClass(JSContext* cx, JS::HandleObject obj, ESClass* cls); - -JS_FRIEND_API(const char*) -ObjectClassName(JSContext* cx, JS::HandleObject obj); - -JS_FRIEND_API(void) -ReportOverRecursed(JSContext* maybecx); - -JS_FRIEND_API(bool) -AddRawValueRoot(JSContext* cx, JS::Value* vp, const char* name); - -JS_FRIEND_API(void) -RemoveRawValueRoot(JSContext* cx, JS::Value* vp); - -JS_FRIEND_API(JSAtom*) -GetPropertyNameFromPC(JSScript* script, jsbytecode* pc); - -#ifdef JS_DEBUG - -/* - * Routines to print out values during debugging. These are FRIEND_API to help - * the debugger find them and to support temporarily hacking js::Dump* calls - * into other code. Note that there are overloads that do not require the FILE* - * parameter, which will default to stderr. - */ - -extern JS_FRIEND_API(void) -DumpString(JSString* str, FILE* fp); - -extern JS_FRIEND_API(void) -DumpAtom(JSAtom* atom, FILE* fp); - -extern JS_FRIEND_API(void) -DumpObject(JSObject* obj, FILE* fp); - -extern JS_FRIEND_API(void) -DumpChars(const char16_t* s, size_t n, FILE* fp); - -extern JS_FRIEND_API(void) -DumpValue(const JS::Value& val, FILE* fp); - -extern JS_FRIEND_API(void) -DumpId(jsid id, FILE* fp); - -extern JS_FRIEND_API(void) -DumpInterpreterFrame(JSContext* cx, FILE* fp, InterpreterFrame* start = nullptr); - -extern JS_FRIEND_API(bool) -DumpPC(JSContext* cx, FILE* fp); - -extern JS_FRIEND_API(bool) -DumpScript(JSContext* cx, JSScript* scriptArg, FILE* fp); - -// Versions for use directly in a debugger (default parameters are not handled -// well in gdb; built-in handles like stderr are not handled well in lldb.) -extern JS_FRIEND_API(void) DumpString(JSString* str); -extern JS_FRIEND_API(void) DumpAtom(JSAtom* atom); -extern JS_FRIEND_API(void) DumpObject(JSObject* obj); -extern JS_FRIEND_API(void) DumpChars(const char16_t* s, size_t n); -extern JS_FRIEND_API(void) DumpValue(const JS::Value& val); -extern JS_FRIEND_API(void) DumpId(jsid id); -extern JS_FRIEND_API(void) DumpInterpreterFrame(JSContext* cx, InterpreterFrame* start = nullptr); -extern JS_FRIEND_API(bool) DumpPC(JSContext* cx); -extern JS_FRIEND_API(bool) DumpScript(JSContext* cx, JSScript* scriptArg); - -#endif - -extern JS_FRIEND_API(void) -DumpBacktrace(JSContext* cx, FILE* fp); - -extern JS_FRIEND_API(void) -DumpBacktrace(JSContext* cx); - -} // namespace js - -namespace JS { - -/** Exposed for DumpJSStack */ -extern JS_FRIEND_API(char*) -FormatStackDump(JSContext* cx, char* buf, bool showArgs, bool showLocals, bool showThisProps); - -/** - * Set all of the uninitialized lexicals on an object to undefined. Return - * true if any lexicals were initialized and false otherwise. - * */ -extern JS_FRIEND_API(bool) -ForceLexicalInitialization(JSContext *cx, HandleObject obj); - -} // namespace JS - -/** - * Copies all own properties from |obj| to |target|. |obj| must be a "native" - * object (that is to say, normal-ish - not an Array or a Proxy). - * - * This function immediately enters a compartment, and does not impose any - * restrictions on the compartment of |cx|. - */ -extern JS_FRIEND_API(bool) -JS_CopyPropertiesFrom(JSContext* cx, JS::HandleObject target, JS::HandleObject obj); - -/* - * Single-property version of the above. This function asserts that an |own| - * property of the given name exists on |obj|. - * - * On entry, |cx| must be same-compartment with |obj|. - * - * The copyBehavior argument controls what happens with - * non-configurable properties. - */ -typedef enum { - MakeNonConfigurableIntoConfigurable, - CopyNonConfigurableAsIs -} PropertyCopyBehavior; - -extern JS_FRIEND_API(bool) -JS_CopyPropertyFrom(JSContext* cx, JS::HandleId id, JS::HandleObject target, - JS::HandleObject obj, - PropertyCopyBehavior copyBehavior = CopyNonConfigurableAsIs); - -extern JS_FRIEND_API(bool) -JS_WrapPropertyDescriptor(JSContext* cx, JS::MutableHandle desc); - -struct JSFunctionSpecWithHelp { - const char* name; - JSNative call; - uint16_t nargs; - uint16_t flags; - const JSJitInfo* jitInfo; - const char* usage; - const char* help; -}; - -#define JS_FN_HELP(name,call,nargs,flags,usage,help) \ - {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, nullptr, usage, help} -#define JS_INLINABLE_FN_HELP(name,call,nargs,flags,native,usage,help) \ - {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, &js::jit::JitInfo_##native,\ - usage, help} -#define JS_FS_HELP_END \ - {nullptr, nullptr, 0, 0, nullptr, nullptr} - -extern JS_FRIEND_API(bool) -JS_DefineFunctionsWithHelp(JSContext* cx, JS::HandleObject obj, const JSFunctionSpecWithHelp* fs); - -namespace js { - -extern JS_FRIEND_DATA(const js::ClassOps) ProxyClassOps; -extern JS_FRIEND_DATA(const js::ClassExtension) ProxyClassExtension; -extern JS_FRIEND_DATA(const js::ObjectOps) ProxyObjectOps; - -/* - * Helper Macros for creating JSClasses that function as proxies. - * - * NB: The macro invocation must be surrounded by braces, so as to - * allow for potential JSClass extensions. - */ -#define PROXY_MAKE_EXT(objectMoved) \ - { \ - js::proxy_WeakmapKeyDelegate, \ - objectMoved \ - } - -#define PROXY_CLASS_WITH_EXT(name, flags, extPtr) \ - { \ - name, \ - js::Class::NON_NATIVE | \ - JSCLASS_IS_PROXY | \ - JSCLASS_DELAY_METADATA_BUILDER | \ - flags, \ - &js::ProxyClassOps, \ - JS_NULL_CLASS_SPEC, \ - extPtr, \ - &js::ProxyObjectOps \ - } - -#define PROXY_CLASS_DEF(name, flags) \ - PROXY_CLASS_WITH_EXT(name, flags, &js::ProxyClassExtension) - -/* - * Proxy stubs, similar to JS_*Stub, for embedder proxy class definitions. - * - * NB: Should not be called directly. - */ - -extern JS_FRIEND_API(bool) -proxy_LookupProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleObject objp, - JS::MutableHandle propp); -extern JS_FRIEND_API(bool) -proxy_DefineProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc, - JS::ObjectOpResult& result); -extern JS_FRIEND_API(bool) -proxy_HasProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); -extern JS_FRIEND_API(bool) -proxy_GetProperty(JSContext* cx, JS::HandleObject obj, JS::HandleValue receiver, JS::HandleId id, - JS::MutableHandleValue vp); -extern JS_FRIEND_API(bool) -proxy_SetProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue bp, - JS::HandleValue receiver, JS::ObjectOpResult& result); -extern JS_FRIEND_API(bool) -proxy_GetOwnPropertyDescriptor(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); -extern JS_FRIEND_API(bool) -proxy_DeleteProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -extern JS_FRIEND_API(void) -proxy_Trace(JSTracer* trc, JSObject* obj); -extern JS_FRIEND_API(JSObject*) -proxy_WeakmapKeyDelegate(JSObject* obj); -extern JS_FRIEND_API(bool) -proxy_Convert(JSContext* cx, JS::HandleObject proxy, JSType hint, JS::MutableHandleValue vp); -extern JS_FRIEND_API(void) -proxy_Finalize(FreeOp* fop, JSObject* obj); -extern JS_FRIEND_API(void) -proxy_ObjectMoved(JSObject* obj, const JSObject* old); -extern JS_FRIEND_API(bool) -proxy_HasInstance(JSContext* cx, JS::HandleObject proxy, JS::MutableHandleValue v, bool* bp); -extern JS_FRIEND_API(bool) -proxy_Call(JSContext* cx, unsigned argc, JS::Value* vp); -extern JS_FRIEND_API(bool) -proxy_Construct(JSContext* cx, unsigned argc, JS::Value* vp); -extern JS_FRIEND_API(JSObject*) -proxy_innerObject(JSObject* obj); -extern JS_FRIEND_API(bool) -proxy_Watch(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); -extern JS_FRIEND_API(bool) -proxy_Unwatch(JSContext* cx, JS::HandleObject obj, JS::HandleId id); -extern JS_FRIEND_API(bool) -proxy_GetElements(JSContext* cx, JS::HandleObject proxy, uint32_t begin, uint32_t end, - ElementAdder* adder); -extern JS_FRIEND_API(JSString*) -proxy_FunToString(JSContext* cx, JS::HandleObject proxy, unsigned indent); - -/** - * A class of objects that return source code on demand. - * - * When code is compiled with setSourceIsLazy(true), SpiderMonkey doesn't - * retain the source code (and doesn't do lazy bytecode generation). If we ever - * need the source code, say, in response to a call to Function.prototype. - * toSource or Debugger.Source.prototype.text, then we call the 'load' member - * function of the instance of this class that has hopefully been registered - * with the runtime, passing the code's URL, and hope that it will be able to - * find the source. - */ -class SourceHook { - public: - virtual ~SourceHook() { } - - /** - * Set |*src| and |*length| to refer to the source code for |filename|. - * On success, the caller owns the buffer to which |*src| points, and - * should use JS_free to free it. - */ - virtual bool load(JSContext* cx, const char* filename, char16_t** src, size_t* length) = 0; -}; - -/** - * Have |cx| use |hook| to retrieve lazily-retrieved source code. See the - * comments for SourceHook. The context takes ownership of the hook, and - * will delete it when the context itself is deleted, or when a new hook is - * set. - */ -extern JS_FRIEND_API(void) -SetSourceHook(JSContext* cx, mozilla::UniquePtr hook); - -/** Remove |cx|'s source hook, and return it. The caller now owns the hook. */ -extern JS_FRIEND_API(mozilla::UniquePtr) -ForgetSourceHook(JSContext* cx); - -extern JS_FRIEND_API(JS::Zone*) -GetCompartmentZone(JSCompartment* comp); - -typedef bool -(* PreserveWrapperCallback)(JSContext* cx, JSObject* obj); - -typedef enum { - CollectNurseryBeforeDump, - IgnoreNurseryObjects -} DumpHeapNurseryBehaviour; - - /** - * Dump the complete object graph of heap-allocated things. - * fp is the file for the dump output. - */ -extern JS_FRIEND_API(void) -DumpHeap(JSContext* cx, FILE* fp, DumpHeapNurseryBehaviour nurseryBehaviour); - -#ifdef JS_OLD_GETTER_SETTER_METHODS -JS_FRIEND_API(bool) obj_defineGetter(JSContext* cx, unsigned argc, JS::Value* vp); -JS_FRIEND_API(bool) obj_defineSetter(JSContext* cx, unsigned argc, JS::Value* vp); -#endif - -extern JS_FRIEND_API(bool) -IsSystemCompartment(JSCompartment* comp); - -extern JS_FRIEND_API(bool) -IsSystemZone(JS::Zone* zone); - -extern JS_FRIEND_API(bool) -IsAtomsCompartment(JSCompartment* comp); - -extern JS_FRIEND_API(bool) -IsAtomsZone(JS::Zone* zone); - -struct WeakMapTracer -{ - JSContext* context; - - explicit WeakMapTracer(JSContext* cx) : context(cx) {} - - // Weak map tracer callback, called once for every binding of every - // weak map that was live at the time of the last garbage collection. - // - // m will be nullptr if the weak map is not contained in a JS Object. - // - // The callback should not GC (and will assert in a debug build if it does so.) - virtual void trace(JSObject* m, JS::GCCellPtr key, JS::GCCellPtr value) = 0; -}; - -extern JS_FRIEND_API(void) -TraceWeakMaps(WeakMapTracer* trc); - -extern JS_FRIEND_API(bool) -AreGCGrayBitsValid(JSContext* cx); - -extern JS_FRIEND_API(bool) -ZoneGlobalsAreAllGray(JS::Zone* zone); - -typedef void -(*GCThingCallback)(void* closure, JS::GCCellPtr thing); - -extern JS_FRIEND_API(void) -VisitGrayWrapperTargets(JS::Zone* zone, GCThingCallback callback, void* closure); - -extern JS_FRIEND_API(JSObject*) -GetWeakmapKeyDelegate(JSObject* key); - -/** - * Invoke cellCallback on every gray JSObject in the given zone. - */ -extern JS_FRIEND_API(void) -IterateGrayObjects(JS::Zone* zone, GCThingCallback cellCallback, void* data); - -/** - * Invoke cellCallback on every gray JSObject in the given zone while cycle - * collection is in progress. - */ -extern JS_FRIEND_API(void) -IterateGrayObjectsUnderCC(JS::Zone* zone, GCThingCallback cellCallback, void* data); - -#ifdef JS_HAS_CTYPES -extern JS_FRIEND_API(size_t) -SizeOfDataIfCDataObject(mozilla::MallocSizeOf mallocSizeOf, JSObject* obj); -#endif - -extern JS_FRIEND_API(JSCompartment*) -GetAnyCompartmentInZone(JS::Zone* zone); - -/* - * Shadow declarations of JS internal structures, for access by inline access - * functions below. Do not use these structures in any other way. When adding - * new fields for access by inline methods, make sure to add static asserts to - * the original header file to ensure that offsets are consistent. - */ -namespace shadow { - -struct ObjectGroup { - const Class* clasp; - JSObject* proto; - JSCompartment* compartment; -}; - -struct BaseShape { - const js::Class* clasp_; - JSObject* parent; -}; - -class Shape { -public: - shadow::BaseShape* base; - jsid _1; - uint32_t slotInfo; - - static const uint32_t FIXED_SLOTS_SHIFT = 27; -}; - -/** - * This layout is shared by all native objects. For non-native objects, the - * group may always be accessed safely, and other members may be as well, - * depending on the object's specific layout. - */ -struct Object { - shadow::ObjectGroup* group; - shadow::Shape* shape; - JS::Value* slots; - void* _1; - - size_t numFixedSlots() const { return shape->slotInfo >> Shape::FIXED_SLOTS_SHIFT; } - JS::Value* fixedSlots() const { - return (JS::Value*)(uintptr_t(this) + sizeof(shadow::Object)); - } - - JS::Value& slotRef(size_t slot) const { - size_t nfixed = numFixedSlots(); - if (slot < nfixed) - return fixedSlots()[slot]; - return slots[slot - nfixed]; - } -}; - -struct Function { - Object base; - uint16_t nargs; - uint16_t flags; - /* Used only for natives */ - JSNative native; - const JSJitInfo* jitinfo; - void* _1; -}; - -struct String -{ - static const uint32_t INLINE_CHARS_BIT = JS_BIT(2); - static const uint32_t LATIN1_CHARS_BIT = JS_BIT(6); - static const uint32_t ROPE_FLAGS = 0; - static const uint32_t TYPE_FLAGS_MASK = JS_BIT(6) - 1; - uint32_t flags; - uint32_t length; - union { - const JS::Latin1Char* nonInlineCharsLatin1; - const char16_t* nonInlineCharsTwoByte; - JS::Latin1Char inlineStorageLatin1[1]; - char16_t inlineStorageTwoByte[1]; - }; -}; - -} /* namespace shadow */ - -// This is equal to |&JSObject::class_|. Use it in places where you don't want -// to #include jsobj.h. -extern JS_FRIEND_DATA(const js::Class* const) ObjectClassPtr; - -inline const js::Class* -GetObjectClass(const JSObject* obj) -{ - return reinterpret_cast(obj)->group->clasp; -} - -inline const JSClass* -GetObjectJSClass(JSObject* obj) -{ - return js::Jsvalify(GetObjectClass(obj)); -} - -JS_FRIEND_API(const Class*) -ProtoKeyToClass(JSProtoKey key); - -// Returns the key for the class inherited by a given standard class (that -// is to say, the prototype of this standard class's prototype). -// -// You must be sure that this corresponds to a standard class with a cached -// JSProtoKey before calling this function. In general |key| will match the -// cached proto key, except in cases where multiple JSProtoKeys share a -// JSClass. -inline JSProtoKey -InheritanceProtoKeyForStandardClass(JSProtoKey key) -{ - // [Object] has nothing to inherit from. - if (key == JSProto_Object) - return JSProto_Null; - - // If we're ClassSpec defined return the proto key from that - if (ProtoKeyToClass(key)->specDefined()) - return ProtoKeyToClass(key)->specInheritanceProtoKey(); - - // Otherwise, we inherit [Object]. - return JSProto_Object; -} - -JS_FRIEND_API(bool) -IsFunctionObject(JSObject* obj); - -static MOZ_ALWAYS_INLINE JSCompartment* -GetObjectCompartment(JSObject* obj) -{ - return reinterpret_cast(obj)->group->compartment; -} - -JS_FRIEND_API(JSObject*) -GetGlobalForObjectCrossCompartment(JSObject* obj); - -JS_FRIEND_API(JSObject*) -GetPrototypeNoProxy(JSObject* obj); - -JS_FRIEND_API(void) -AssertSameCompartment(JSContext* cx, JSObject* obj); - -#ifdef JS_DEBUG -JS_FRIEND_API(void) -AssertSameCompartment(JSObject* objA, JSObject* objB); -#else -inline void AssertSameCompartment(JSObject* objA, JSObject* objB) {} -#endif - -JS_FRIEND_API(void) -NotifyAnimationActivity(JSObject* obj); - -/** - * Return the outermost enclosing function (script) of the scripted caller. - * This function returns nullptr in several cases: - * - no script is running on the context - * - the caller is in global or eval code - * In particular, this function will "stop" its outermost search at eval() and - * thus it will really return the outermost enclosing function *since the - * innermost eval*. - */ -JS_FRIEND_API(JSFunction*) -GetOutermostEnclosingFunctionOfScriptedCaller(JSContext* cx); - -JS_FRIEND_API(JSFunction*) -DefineFunctionWithReserved(JSContext* cx, JSObject* obj, const char* name, JSNative call, - unsigned nargs, unsigned attrs); - -JS_FRIEND_API(JSFunction*) -NewFunctionWithReserved(JSContext* cx, JSNative call, unsigned nargs, unsigned flags, - const char* name); - -JS_FRIEND_API(JSFunction*) -NewFunctionByIdWithReserved(JSContext* cx, JSNative native, unsigned nargs, unsigned flags, - jsid id); - -JS_FRIEND_API(const JS::Value&) -GetFunctionNativeReserved(JSObject* fun, size_t which); - -JS_FRIEND_API(void) -SetFunctionNativeReserved(JSObject* fun, size_t which, const JS::Value& val); - -JS_FRIEND_API(bool) -FunctionHasNativeReserved(JSObject* fun); - -JS_FRIEND_API(bool) -GetObjectProto(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject proto); - -extern JS_FRIEND_API(JSObject*) -GetStaticPrototype(JSObject* obj); - -JS_FRIEND_API(bool) -GetOriginalEval(JSContext* cx, JS::HandleObject scope, - JS::MutableHandleObject eval); - -inline void* -GetObjectPrivate(JSObject* obj) -{ - MOZ_ASSERT(GetObjectClass(obj)->flags & JSCLASS_HAS_PRIVATE); - const shadow::Object* nobj = reinterpret_cast(obj); - void** addr = reinterpret_cast(&nobj->fixedSlots()[nobj->numFixedSlots()]); - return *addr; -} - -inline const JS::Value& -GetReservedSlot(JSObject* obj, size_t slot) -{ - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); - return reinterpret_cast(obj)->slotRef(slot); -} - -JS_FRIEND_API(void) -SetReservedOrProxyPrivateSlotWithBarrier(JSObject* obj, size_t slot, const JS::Value& value); - -inline void -SetReservedSlot(JSObject* obj, size_t slot, const JS::Value& value) -{ - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); - shadow::Object* sobj = reinterpret_cast(obj); - if (sobj->slotRef(slot).isMarkable() || value.isMarkable()) - SetReservedOrProxyPrivateSlotWithBarrier(obj, slot, value); - else - sobj->slotRef(slot) = value; -} - -JS_FRIEND_API(uint32_t) -GetObjectSlotSpan(JSObject* obj); - -inline const JS::Value& -GetObjectSlot(JSObject* obj, size_t slot) -{ - MOZ_ASSERT(slot < GetObjectSlotSpan(obj)); - return reinterpret_cast(obj)->slotRef(slot); -} - -MOZ_ALWAYS_INLINE size_t -GetAtomLength(JSAtom* atom) -{ - return reinterpret_cast(atom)->length; -} - -static const uint32_t MaxStringLength = (1 << 28) - 1; - -MOZ_ALWAYS_INLINE size_t -GetStringLength(JSString* s) -{ - return reinterpret_cast(s)->length; -} - -MOZ_ALWAYS_INLINE size_t -GetFlatStringLength(JSFlatString* s) -{ - return reinterpret_cast(s)->length; -} - -MOZ_ALWAYS_INLINE size_t -GetLinearStringLength(JSLinearString* s) -{ - return reinterpret_cast(s)->length; -} - -MOZ_ALWAYS_INLINE bool -LinearStringHasLatin1Chars(JSLinearString* s) -{ - return reinterpret_cast(s)->flags & shadow::String::LATIN1_CHARS_BIT; -} - -MOZ_ALWAYS_INLINE bool -AtomHasLatin1Chars(JSAtom* atom) -{ - return reinterpret_cast(atom)->flags & shadow::String::LATIN1_CHARS_BIT; -} - -MOZ_ALWAYS_INLINE bool -StringHasLatin1Chars(JSString* s) -{ - return reinterpret_cast(s)->flags & shadow::String::LATIN1_CHARS_BIT; -} - -MOZ_ALWAYS_INLINE const JS::Latin1Char* -GetLatin1LinearStringChars(const JS::AutoCheckCannotGC& nogc, JSLinearString* linear) -{ - MOZ_ASSERT(LinearStringHasLatin1Chars(linear)); - - using shadow::String; - String* s = reinterpret_cast(linear); - if (s->flags & String::INLINE_CHARS_BIT) - return s->inlineStorageLatin1; - return s->nonInlineCharsLatin1; -} - -MOZ_ALWAYS_INLINE const char16_t* -GetTwoByteLinearStringChars(const JS::AutoCheckCannotGC& nogc, JSLinearString* linear) -{ - MOZ_ASSERT(!LinearStringHasLatin1Chars(linear)); - - using shadow::String; - String* s = reinterpret_cast(linear); - if (s->flags & String::INLINE_CHARS_BIT) - return s->inlineStorageTwoByte; - return s->nonInlineCharsTwoByte; -} - -MOZ_ALWAYS_INLINE JSLinearString* -AtomToLinearString(JSAtom* atom) -{ - return reinterpret_cast(atom); -} - -MOZ_ALWAYS_INLINE JSFlatString* -AtomToFlatString(JSAtom* atom) -{ - return reinterpret_cast(atom); -} - -MOZ_ALWAYS_INLINE JSLinearString* -FlatStringToLinearString(JSFlatString* s) -{ - return reinterpret_cast(s); -} - -MOZ_ALWAYS_INLINE const JS::Latin1Char* -GetLatin1AtomChars(const JS::AutoCheckCannotGC& nogc, JSAtom* atom) -{ - return GetLatin1LinearStringChars(nogc, AtomToLinearString(atom)); -} - -MOZ_ALWAYS_INLINE const char16_t* -GetTwoByteAtomChars(const JS::AutoCheckCannotGC& nogc, JSAtom* atom) -{ - return GetTwoByteLinearStringChars(nogc, AtomToLinearString(atom)); -} - -JS_FRIEND_API(JSLinearString*) -StringToLinearStringSlow(JSContext* cx, JSString* str); - -MOZ_ALWAYS_INLINE JSLinearString* -StringToLinearString(JSContext* cx, JSString* str) -{ - using shadow::String; - String* s = reinterpret_cast(str); - if (MOZ_UNLIKELY((s->flags & String::TYPE_FLAGS_MASK) == String::ROPE_FLAGS)) - return StringToLinearStringSlow(cx, str); - return reinterpret_cast(str); -} - -template -MOZ_ALWAYS_INLINE void -CopyLinearStringChars(CharType* dest, JSLinearString* s, size_t len, size_t start = 0); - -MOZ_ALWAYS_INLINE void -CopyLinearStringChars(char16_t* dest, JSLinearString* s, size_t len, size_t start = 0) -{ - MOZ_ASSERT(start + len <= GetLinearStringLength(s)); - JS::AutoCheckCannotGC nogc; - if (LinearStringHasLatin1Chars(s)) { - const JS::Latin1Char* src = GetLatin1LinearStringChars(nogc, s); - for (size_t i = 0; i < len; i++) - dest[i] = src[start + i]; - } else { - const char16_t* src = GetTwoByteLinearStringChars(nogc, s); - mozilla::PodCopy(dest, src + start, len); - } -} - -MOZ_ALWAYS_INLINE void -CopyLinearStringChars(char* dest, JSLinearString* s, size_t len, size_t start = 0) -{ - MOZ_ASSERT(start + len <= GetLinearStringLength(s)); - JS::AutoCheckCannotGC nogc; - if (LinearStringHasLatin1Chars(s)) { - const JS::Latin1Char* src = GetLatin1LinearStringChars(nogc, s); - for (size_t i = 0; i < len; i++) - dest[i] = char(src[start + i]); - } else { - const char16_t* src = GetTwoByteLinearStringChars(nogc, s); - for (size_t i = 0; i < len; i++) - dest[i] = char(src[start + i]); - } -} - -template -inline bool -CopyStringChars(JSContext* cx, CharType* dest, JSString* s, size_t len, size_t start = 0) -{ - JSLinearString* linear = StringToLinearString(cx, s); - if (!linear) - return false; - - CopyLinearStringChars(dest, linear, len, start); - return true; -} - -inline void -CopyFlatStringChars(char16_t* dest, JSFlatString* s, size_t len) -{ - CopyLinearStringChars(dest, FlatStringToLinearString(s), len); -} - -/** - * Add some or all property keys of obj to the id vector *props. - * - * The flags parameter controls which property keys are added. Pass a - * combination of the following bits: - * - * JSITER_OWNONLY - Don't also search the prototype chain; only consider - * obj's own properties. - * - * JSITER_HIDDEN - Include nonenumerable properties. - * - * JSITER_SYMBOLS - Include property keys that are symbols. The default - * behavior is to filter out symbols. - * - * JSITER_SYMBOLSONLY - Exclude non-symbol property keys. - * - * This is the closest C++ API we have to `Reflect.ownKeys(obj)`, or - * equivalently, the ES6 [[OwnPropertyKeys]] internal method. Pass - * `JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS` as flags to get - * results that match the output of Reflect.ownKeys. - */ -JS_FRIEND_API(bool) -GetPropertyKeys(JSContext* cx, JS::HandleObject obj, unsigned flags, JS::AutoIdVector* props); - -JS_FRIEND_API(bool) -AppendUnique(JSContext* cx, JS::AutoIdVector& base, JS::AutoIdVector& others); - -JS_FRIEND_API(bool) -StringIsArrayIndex(JSLinearString* str, uint32_t* indexp); - -JS_FRIEND_API(void) -SetPreserveWrapperCallback(JSContext* cx, PreserveWrapperCallback callback); - -JS_FRIEND_API(bool) -IsObjectInContextCompartment(JSObject* obj, const JSContext* cx); - -/* - * NB: keep these in sync with the copy in builtin/SelfHostingDefines.h. - * The first three are omitted because they shouldn't be used in new code. - */ -#define JSITER_ENUMERATE 0x1 /* for-in compatible hidden default iterator */ -#define JSITER_FOREACH 0x2 /* get obj[key] for each property */ -#define JSITER_KEYVALUE 0x4 /* obsolete destructuring for-in wants [key, value] */ -#define JSITER_OWNONLY 0x8 /* iterate over obj's own properties only */ -#define JSITER_HIDDEN 0x10 /* also enumerate non-enumerable properties */ -#define JSITER_SYMBOLS 0x20 /* also include symbol property keys */ -#define JSITER_SYMBOLSONLY 0x40 /* exclude string property keys */ - -JS_FRIEND_API(bool) -RunningWithTrustedPrincipals(JSContext* cx); - -inline uintptr_t -GetNativeStackLimit(JSContext* cx, StackKind kind, int extraAllowance = 0) -{ - uintptr_t limit = ContextFriendFields::get(cx)->nativeStackLimit[kind]; -#if JS_STACK_GROWTH_DIRECTION > 0 - limit += extraAllowance; -#else - limit -= extraAllowance; -#endif - return limit; -} - -inline uintptr_t -GetNativeStackLimit(JSContext* cx, int extraAllowance = 0) -{ - StackKind kind = RunningWithTrustedPrincipals(cx) ? StackForTrustedScript - : StackForUntrustedScript; - return GetNativeStackLimit(cx, kind, extraAllowance); -} - -/* - * These macros report a stack overflow and run |onerror| if we are close to - * using up the C stack. The JS_CHECK_CHROME_RECURSION variant gives us a - * little extra space so that we can ensure that crucial code is able to run. - * JS_CHECK_RECURSION_CONSERVATIVE allows less space than any other check, - * including a safety buffer (as in, it uses the untrusted limit and subtracts - * a little more from it). - */ - -#define JS_CHECK_RECURSION_LIMIT(cx, limit, onerror) \ - JS_BEGIN_MACRO \ - int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(limit, &stackDummy_)) { \ - js::ReportOverRecursed(cx); \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_RECURSION(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT(cx, js::GetNativeStackLimit(cx), onerror) - -#define JS_CHECK_RECURSION_LIMIT_DONT_REPORT(cx, limit, onerror) \ - JS_BEGIN_MACRO \ - int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(limit, &stackDummy_)) { \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_RECURSION_DONT_REPORT(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT_DONT_REPORT(cx, js::GetNativeStackLimit(cx), onerror) - -#define JS_CHECK_RECURSION_WITH_SP_DONT_REPORT(cx, sp, onerror) \ - JS_BEGIN_MACRO \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_RECURSION_WITH_SP(cx, sp, onerror) \ - JS_BEGIN_MACRO \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ - js::ReportOverRecursed(cx); \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_SYSTEM_RECURSION(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT(cx, js::GetNativeStackLimit(cx, js::StackForSystemCode), onerror) - -#define JS_CHECK_RECURSION_CONSERVATIVE(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT(cx, \ - js::GetNativeStackLimit(cx, js::StackForUntrustedScript, -1024 * int(sizeof(size_t))), \ - onerror) - -#define JS_CHECK_RECURSION_CONSERVATIVE_DONT_REPORT(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT_DONT_REPORT(cx, \ - js::GetNativeStackLimit(cx, js::StackForUntrustedScript, -1024 * int(sizeof(size_t))), \ - onerror) - -JS_FRIEND_API(void) -StartPCCountProfiling(JSContext* cx); - -JS_FRIEND_API(void) -StopPCCountProfiling(JSContext* cx); - -JS_FRIEND_API(void) -PurgePCCounts(JSContext* cx); - -JS_FRIEND_API(size_t) -GetPCCountScriptCount(JSContext* cx); - -JS_FRIEND_API(JSString*) -GetPCCountScriptSummary(JSContext* cx, size_t script); - -JS_FRIEND_API(JSString*) -GetPCCountScriptContents(JSContext* cx, size_t script); - -/** - * Generate lcov trace file content for the current compartment, and allocate a - * new buffer and return the content in it, the size of the newly allocated - * content within the buffer would be set to the length out-param. - * - * In case of out-of-memory, this function returns nullptr and does not set any - * value to the length out-param. - */ -JS_FRIEND_API(char*) -GetCodeCoverageSummary(JSContext* cx, size_t* length); - -typedef void -(* ActivityCallback)(void* arg, bool active); - -/** - * Sets a callback that is run whenever the runtime goes idle - the - * last active request ceases - and begins activity - when it was - * idle and a request begins. - */ -JS_FRIEND_API(void) -SetActivityCallback(JSContext* cx, ActivityCallback cb, void* arg); - -typedef bool -(* DOMInstanceClassHasProtoAtDepth)(const Class* instanceClass, - uint32_t protoID, uint32_t depth); -struct JSDOMCallbacks { - DOMInstanceClassHasProtoAtDepth instanceClassMatchesProto; -}; -typedef struct JSDOMCallbacks DOMCallbacks; - -extern JS_FRIEND_API(void) -SetDOMCallbacks(JSContext* cx, const DOMCallbacks* callbacks); - -extern JS_FRIEND_API(const DOMCallbacks*) -GetDOMCallbacks(JSContext* cx); - -extern JS_FRIEND_API(JSObject*) -GetTestingFunctions(JSContext* cx); - -/** - * Helper to convert FreeOp to JSFreeOp when the definition of FreeOp is not - * available and the compiler does not know that FreeOp inherits from - * JSFreeOp. - */ -inline JSFreeOp* -CastToJSFreeOp(FreeOp* fop) -{ - return reinterpret_cast(fop); -} - -/* Implemented in jsexn.cpp. */ - -/** - * Get an error type name from a JSExnType constant. - * Returns nullptr for invalid arguments and JSEXN_INTERNALERR - */ -extern JS_FRIEND_API(JSFlatString*) -GetErrorTypeName(JSContext* cx, int16_t exnType); - -#ifdef JS_DEBUG -extern JS_FRIEND_API(unsigned) -GetEnterCompartmentDepth(JSContext* cx); -#endif - -class RegExpGuard; -extern JS_FRIEND_API(bool) -RegExpToSharedNonInline(JSContext* cx, JS::HandleObject regexp, RegExpGuard* shared); - -/* Implemented in jswrapper.cpp. */ -typedef enum NukeReferencesToWindow { - NukeWindowReferences, - DontNukeWindowReferences -} NukeReferencesToWindow; - -/* - * These filters are designed to be ephemeral stack classes, and thus don't - * do any rooting or holding of their members. - */ -struct CompartmentFilter { - virtual bool match(JSCompartment* c) const = 0; -}; - -struct AllCompartments : public CompartmentFilter { - virtual bool match(JSCompartment* c) const override { return true; } -}; - -struct ContentCompartmentsOnly : public CompartmentFilter { - virtual bool match(JSCompartment* c) const override { - return !IsSystemCompartment(c); - } -}; - -struct ChromeCompartmentsOnly : public CompartmentFilter { - virtual bool match(JSCompartment* c) const override { - return IsSystemCompartment(c); - } -}; - -struct SingleCompartment : public CompartmentFilter { - JSCompartment* ours; - explicit SingleCompartment(JSCompartment* c) : ours(c) {} - virtual bool match(JSCompartment* c) const override { return c == ours; } -}; - -struct CompartmentsWithPrincipals : public CompartmentFilter { - JSPrincipals* principals; - explicit CompartmentsWithPrincipals(JSPrincipals* p) : principals(p) {} - virtual bool match(JSCompartment* c) const override { - return JS_GetCompartmentPrincipals(c) == principals; - } -}; - -extern JS_FRIEND_API(bool) -NukeCrossCompartmentWrappers(JSContext* cx, - const CompartmentFilter& sourceFilter, - const CompartmentFilter& targetFilter, - NukeReferencesToWindow nukeReferencesToWindow); - -/* Specify information about DOMProxy proxies in the DOM, for use by ICs. */ - -/* - * The DOMProxyShadowsCheck function will be called to check if the property for - * id should be gotten from the prototype, or if there is an own property that - * shadows it. - * * If ShadowsViaDirectExpando is returned, then the slot at - * listBaseExpandoSlot contains an expando object which has the property in - * question. - * * If ShadowsViaIndirectExpando is returned, then the slot at - * listBaseExpandoSlot contains a private pointer to an ExpandoAndGeneration - * and the expando object in the ExpandoAndGeneration has the property in - * question. - * * If DoesntShadow is returned then the slot at listBaseExpandoSlot should - * either be undefined or point to an expando object that would contain the - * own property. - * * If DoesntShadowUnique is returned then the slot at listBaseExpandoSlot - * should contain a private pointer to a ExpandoAndGeneration, which contains - * a JS::Value that should either be undefined or point to an expando object, - * and a uint64 value. If that value changes then the IC for getting a - * property will be invalidated. - * * If Shadows is returned, that means the property is an own property of the - * proxy but doesn't live on the expando object. - */ - -struct ExpandoAndGeneration { - ExpandoAndGeneration() - : expando(JS::UndefinedValue()), - generation(0) - {} - - void OwnerUnlinked() - { - ++generation; - } - - static size_t offsetOfExpando() - { - return offsetof(ExpandoAndGeneration, expando); - } - - static size_t offsetOfGeneration() - { - return offsetof(ExpandoAndGeneration, generation); - } - - JS::Heap expando; - uint64_t generation; -}; - -typedef enum DOMProxyShadowsResult { - ShadowCheckFailed, - Shadows, - DoesntShadow, - DoesntShadowUnique, - ShadowsViaDirectExpando, - ShadowsViaIndirectExpando -} DOMProxyShadowsResult; -typedef DOMProxyShadowsResult -(* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); -JS_FRIEND_API(void) -SetDOMProxyInformation(const void* domProxyHandlerFamily, uint32_t domProxyExpandoSlot, - DOMProxyShadowsCheck domProxyShadowsCheck); - -const void* GetDOMProxyHandlerFamily(); -uint32_t GetDOMProxyExpandoSlot(); -DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); -inline bool DOMProxyIsShadowing(DOMProxyShadowsResult result) { - return result == Shadows || - result == ShadowsViaDirectExpando || - result == ShadowsViaIndirectExpando; -} - -/* Implemented in jsdate.cpp. */ - -/** Detect whether the internal date value is NaN. */ -extern JS_FRIEND_API(bool) -DateIsValid(JSContext* cx, JS::HandleObject obj, bool* isValid); - -extern JS_FRIEND_API(bool) -DateGetMsecSinceEpoch(JSContext* cx, JS::HandleObject obj, double* msecSinceEpoch); - -} /* namespace js */ - -/* Implemented in jscntxt.cpp. */ - -/** - * Report an exception, which is currently realized as a printf-style format - * string and its arguments. - */ -typedef enum JSErrNum { -#define MSG_DEF(name, count, exception, format) \ - name, -#include "js.msg" -#undef MSG_DEF - JSErr_Limit -} JSErrNum; - -namespace js { - -extern JS_FRIEND_API(const JSErrorFormatString*) -GetErrorMessage(void* userRef, const unsigned errorNumber); - -// AutoStableStringChars is here so we can use it in ErrorReport. It -// should get moved out of here if we can manage it. See bug 1040316. - -/** - * This class provides safe access to a string's chars across a GC. Once - * we allocate strings and chars in the nursery (bug 903519), this class - * will have to make a copy of the string's chars if they are allocated - * in the nursery, so it's best to avoid using this class unless you really - * need it. It's usually more efficient to use the latin1Chars/twoByteChars - * JSString methods and often the code can be rewritten so that only indexes - * instead of char pointers are used in parts of the code that can GC. - */ -class MOZ_STACK_CLASS AutoStableStringChars -{ - /* - * When copying string char, use this many bytes of inline storage. This is - * chosen to allow the inline string types to be copied without allocating. - * This is asserted in AutoStableStringChars::allocOwnChars. - */ - static const size_t InlineCapacity = 24; - - /* Ensure the string is kept alive while we're using its chars. */ - JS::RootedString s_; - union { - const char16_t* twoByteChars_; - const JS::Latin1Char* latin1Chars_; - }; - mozilla::Maybe> ownChars_; - enum State { Uninitialized, Latin1, TwoByte }; - State state_; - - public: - explicit AutoStableStringChars(JSContext* cx) - : s_(cx), state_(Uninitialized) - {} - - MOZ_MUST_USE - bool init(JSContext* cx, JSString* s); - - /* Like init(), but Latin1 chars are inflated to TwoByte. */ - MOZ_MUST_USE - bool initTwoByte(JSContext* cx, JSString* s); - - bool isLatin1() const { return state_ == Latin1; } - bool isTwoByte() const { return state_ == TwoByte; } - - const char16_t* twoByteChars() const { - MOZ_ASSERT(state_ == TwoByte); - return twoByteChars_; - } - - mozilla::Range latin1Range() const { - MOZ_ASSERT(state_ == Latin1); - return mozilla::Range(latin1Chars_, - GetStringLength(s_)); - } - - mozilla::Range twoByteRange() const { - MOZ_ASSERT(state_ == TwoByte); - return mozilla::Range(twoByteChars_, - GetStringLength(s_)); - } - - /* If we own the chars, transfer ownership to the caller. */ - bool maybeGiveOwnershipToCaller() { - MOZ_ASSERT(state_ != Uninitialized); - if (!ownChars_.isSome() || !ownChars_->extractRawBuffer()) - return false; - state_ = Uninitialized; - ownChars_.reset(); - return true; - } - - private: - AutoStableStringChars(const AutoStableStringChars& other) = delete; - void operator=(const AutoStableStringChars& other) = delete; - - bool baseIsInline(JS::Handle linearString); - template T* allocOwnChars(JSContext* cx, size_t count); - bool copyLatin1Chars(JSContext* cx, JS::Handle linearString); - bool copyTwoByteChars(JSContext* cx, JS::Handle linearString); - bool copyAndInflateLatin1Chars(JSContext*, JS::Handle linearString); -}; - -struct MOZ_STACK_CLASS JS_FRIEND_API(ErrorReport) -{ - explicit ErrorReport(JSContext* cx); - ~ErrorReport(); - - enum SniffingBehavior { - WithSideEffects, - NoSideEffects - }; - - /** - * Generate a JSErrorReport from the provided thrown value. - * - * If the value is a (possibly wrapped) Error object, the JSErrorReport will - * be exactly initialized from the Error object's information, without - * observable side effects. (The Error object's JSErrorReport is reused, if - * it has one.) - * - * Otherwise various attempts are made to derive JSErrorReport information - * from |exn| and from the current execution state. This process is - * *definitely* inconsistent with any standard, and particulars of the - * behavior implemented here generally shouldn't be relied upon. - * - * If the value of |sniffingBehavior| is |WithSideEffects|, some of these - * attempts *may* invoke user-configurable behavior when |exn| is an object: - * converting |exn| to a string, detecting and getting properties on |exn|, - * accessing |exn|'s prototype chain, and others are possible. Users *must* - * tolerate |ErrorReport::init| potentially having arbitrary effects. Any - * exceptions thrown by these operations will be caught and silently - * ignored, and "default" values will be substituted into the JSErrorReport. - * - * But if the value of |sniffingBehavior| is |NoSideEffects|, these attempts - * *will not* invoke any observable side effects. The JSErrorReport will - * simply contain fewer, less precise details. - * - * Unlike some functions involved in error handling, this function adheres - * to the usual JSAPI return value error behavior. - */ - bool init(JSContext* cx, JS::HandleValue exn, - SniffingBehavior sniffingBehavior); - - JSErrorReport* report() - { - return reportp; - } - - const JS::ConstUTF8CharsZ toStringResult() - { - return toStringResult_; - } - - private: - // More or less an equivalent of JS_ReportErrorNumber/js::ReportErrorNumberVA - // but fills in an ErrorReport instead of reporting it. Uses varargs to - // make it simpler to call js::ExpandErrorArgumentsVA. - // - // Returns false if we fail to actually populate the ErrorReport - // for some reason (probably out of memory). - bool populateUncaughtExceptionReportUTF8(JSContext* cx, ...); - bool populateUncaughtExceptionReportUTF8VA(JSContext* cx, va_list ap); - - // Reports exceptions from add-on scopes to telementry. - void ReportAddonExceptionToTelementry(JSContext* cx); - - // We may have a provided JSErrorReport, so need a way to represent that. - JSErrorReport* reportp; - - // Or we may need to synthesize a JSErrorReport one of our own. - JSErrorReport ownedReport; - - // And we have a string to maybe keep alive that has pointers into - // it from ownedReport. - JS::RootedString str; - - // And keep its chars alive too. - AutoStableStringChars strChars; - - // And we need to root our exception value. - JS::RootedObject exnObject; - - // And for our filename. - JSAutoByteString filename; - - // We may have a result of error.toString(). - // FIXME: We should not call error.toString(), since it could have side - // effect (see bug 633623). - JS::ConstUTF8CharsZ toStringResult_; - JSAutoByteString toStringResultBytesStorage; -}; - -/* Implemented in vm/StructuredClone.cpp. */ -extern JS_FRIEND_API(uint64_t) -GetSCOffset(JSStructuredCloneWriter* writer); - -namespace Scalar { - -/** - * Scalar types that can appear in typed arrays and typed objects. The enum - * values must to be kept in sync with the JS_SCALARTYPEREPR_ constants, as - * well as the TypedArrayObject::classes and TypedArrayObject::protoClasses - * definitions. - */ -enum Type { - Int8 = 0, - Uint8, - Int16, - Uint16, - Int32, - Uint32, - Float32, - Float64, - - /** - * Special type that is a uint8_t, but assignments are clamped to [0, 256). - * Treat the raw data type as a uint8_t. - */ - Uint8Clamped, - - /** - * Types that don't have their own TypedArray equivalent, for now. - */ - MaxTypedArrayViewType, - - Int64, - Float32x4, - Int8x16, - Int16x8, - Int32x4 -}; - -static inline size_t -byteSize(Type atype) -{ - switch (atype) { - case Int8: - case Uint8: - case Uint8Clamped: - return 1; - case Int16: - case Uint16: - return 2; - case Int32: - case Uint32: - case Float32: - return 4; - case Int64: - case Float64: - return 8; - case Int8x16: - case Int16x8: - case Int32x4: - case Float32x4: - return 16; - default: - MOZ_CRASH("invalid scalar type"); - } -} - -static inline bool -isSignedIntType(Type atype) { - switch (atype) { - case Int8: - case Int16: - case Int32: - case Int64: - case Int8x16: - case Int16x8: - case Int32x4: - return true; - case Uint8: - case Uint8Clamped: - case Uint16: - case Uint32: - case Float32: - case Float64: - case Float32x4: - return false; - default: - MOZ_CRASH("invalid scalar type"); - } -} - -static inline bool -isSimdType(Type atype) { - switch (atype) { - case Int8: - case Uint8: - case Uint8Clamped: - case Int16: - case Uint16: - case Int32: - case Uint32: - case Int64: - case Float32: - case Float64: - return false; - case Int8x16: - case Int16x8: - case Int32x4: - case Float32x4: - return true; - case MaxTypedArrayViewType: - break; - } - MOZ_CRASH("invalid scalar type"); -} - -static inline size_t -scalarByteSize(Type atype) { - switch (atype) { - case Int8x16: - return 1; - case Int16x8: - return 2; - case Int32x4: - case Float32x4: - return 4; - case Int8: - case Uint8: - case Uint8Clamped: - case Int16: - case Uint16: - case Int32: - case Uint32: - case Int64: - case Float32: - case Float64: - case MaxTypedArrayViewType: - break; - } - MOZ_CRASH("invalid simd type"); -} - -} /* namespace Scalar */ -} /* namespace js */ - -/* - * Create a new typed array with nelements elements. - * - * These functions (except the WithBuffer variants) fill in the array with zeros. - */ - -extern JS_FRIEND_API(JSObject*) -JS_NewInt8Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ClampedArray(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewInt16Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint16Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewInt32Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint32Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat32Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat64Array(JSContext* cx, uint32_t nelements); - -/* - * Create a new typed array and copy in values from the given object. The - * object is used as if it were an array; that is, the new array (if - * successfully created) will have length given by array.length, and its - * elements will be those specified by array[0], array[1], and so on, after - * conversion to the typed array element type. - */ - -extern JS_FRIEND_API(JSObject*) -JS_NewInt8ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ClampedArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewInt16ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint16ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewInt32ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint32ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat32ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat64ArrayFromArray(JSContext* cx, JS::HandleObject array); - -/* - * Create a new typed array using the given ArrayBuffer or - * SharedArrayBuffer for storage. The length value is optional; if -1 - * is passed, enough elements to use up the remainder of the byte - * array is used as the default value. - */ - -extern JS_FRIEND_API(JSObject*) -JS_NewInt8ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ClampedArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewInt16ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint16ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewInt32ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint32ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat32ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat64ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); - -/** - * Create a new SharedArrayBuffer with the given byte length. This - * may only be called if - * JS::CompartmentCreationOptionsRef(cx).getSharedMemoryAndAtomicsEnabled() is - * true. - */ -extern JS_FRIEND_API(JSObject*) -JS_NewSharedArrayBuffer(JSContext* cx, uint32_t nbytes); - -/** - * Create a new ArrayBuffer with the given byte length. - */ -extern JS_FRIEND_API(JSObject*) -JS_NewArrayBuffer(JSContext* cx, uint32_t nbytes); - -/** - * Check whether obj supports JS_GetTypedArray* APIs. Note that this may return - * false if a security wrapper is encountered that denies the unwrapping. If - * this test or one of the JS_Is*Array tests succeeds, then it is safe to call - * the various accessor JSAPI calls defined below. - */ -extern JS_FRIEND_API(bool) -JS_IsTypedArrayObject(JSObject* obj); - -/** - * Check whether obj supports JS_GetArrayBufferView* APIs. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. If this test or one of the more specific tests succeeds, then it - * is safe to call the various ArrayBufferView accessor JSAPI calls defined - * below. - */ -extern JS_FRIEND_API(bool) -JS_IsArrayBufferViewObject(JSObject* obj); - -/* - * Test for specific typed array types (ArrayBufferView subtypes) - */ - -extern JS_FRIEND_API(bool) -JS_IsInt8Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint8Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint8ClampedArray(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsInt16Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint16Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsInt32Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint32Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsFloat32Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsFloat64Array(JSObject* obj); - -/** - * Return the isShared flag of a typed array, which denotes whether - * the underlying buffer is a SharedArrayBuffer. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(bool) -JS_GetTypedArraySharedness(JSObject* obj); - -/* - * Test for specific typed array types (ArrayBufferView subtypes) and return - * the unwrapped object if so, else nullptr. Never throws. - */ - -namespace js { - -extern JS_FRIEND_API(JSObject*) -UnwrapInt8Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint8Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint8ClampedArray(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapInt16Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint16Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapInt32Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint32Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapFloat32Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapFloat64Array(JSObject* obj); - -extern JS_FRIEND_API(JSObject*) -UnwrapArrayBuffer(JSObject* obj); - -extern JS_FRIEND_API(JSObject*) -UnwrapArrayBufferView(JSObject* obj); - -extern JS_FRIEND_API(JSObject*) -UnwrapSharedArrayBuffer(JSObject* obj); - - -namespace detail { - -extern JS_FRIEND_DATA(const Class* const) Int8ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint8ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint8ClampedArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Int16ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint16ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Int32ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint32ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Float32ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Float64ArrayClassPtr; - -const size_t TypedArrayLengthSlot = 1; - -} // namespace detail - -#define JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Type, type) \ -inline void \ -Get ## Type ## ArrayLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, type** data) \ -{ \ - MOZ_ASSERT(GetObjectClass(obj) == detail::Type ## ArrayClassPtr); \ - const JS::Value& lenSlot = GetReservedSlot(obj, detail::TypedArrayLengthSlot); \ - *length = mozilla::AssertedCast(lenSlot.toInt32()); \ - *isSharedMemory = JS_GetTypedArraySharedness(obj); \ - *data = static_cast(GetObjectPrivate(obj)); \ -} - -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Int8, int8_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint8, uint8_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint8Clamped, uint8_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Int16, int16_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint16, uint16_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Int32, int32_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint32, uint32_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Float32, float) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Float64, double) - -#undef JS_DEFINE_DATA_AND_LENGTH_ACCESSOR - -// This one isn't inlined because it's rather tricky (by dint of having to deal -// with a dozen-plus classes and varying slot layouts. -extern JS_FRIEND_API(void) -GetArrayBufferViewLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -// This one isn't inlined because there are a bunch of different ArrayBuffer -// classes that would have to be individually handled here. -// -// There is an isShared out argument for API consistency (eases use from DOM). -// It will always be set to false. -extern JS_FRIEND_API(void) -GetArrayBufferLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -// Ditto for SharedArrayBuffer. -// -// There is an isShared out argument for API consistency (eases use from DOM). -// It will always be set to true. -extern JS_FRIEND_API(void) -GetSharedArrayBufferLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -} // namespace js - -JS_FRIEND_API(uint8_t*) -JS_GetSharedArrayBufferData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/* - * Unwrap Typed arrays all at once. Return nullptr without throwing if the - * object cannot be viewed as the correct typed array, or the typed array - * object on success, filling both outparameters. - */ -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsInt8Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, int8_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint8Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint8ClampedArray(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsInt16Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, int16_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint16Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint16_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsInt32Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, int32_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint32Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint32_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsFloat32Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, float** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsFloat64Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, double** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsArrayBufferView(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -/* - * Unwrap an ArrayBuffer, return nullptr if it's a different type. - */ -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsArrayBuffer(JSObject* obj, uint32_t* length, uint8_t** data); - -/* - * Get the type of elements in a typed array, or MaxTypedArrayViewType if a DataView. - * - * |obj| must have passed a JS_IsArrayBufferView/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is an ArrayBufferView or a - * wrapper of an ArrayBufferView, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(js::Scalar::Type) -JS_GetArrayBufferViewType(JSObject* obj); - -extern JS_FRIEND_API(js::Scalar::Type) -JS_GetSharedArrayBufferViewType(JSObject* obj); - -/* - * Check whether obj supports the JS_GetArrayBuffer* APIs. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. If this test succeeds, then it is safe to call the various - * accessor JSAPI calls defined below. - */ -extern JS_FRIEND_API(bool) -JS_IsArrayBufferObject(JSObject* obj); - -extern JS_FRIEND_API(bool) -JS_IsSharedArrayBufferObject(JSObject* obj); - -/** - * Return the available byte length of an array buffer. - * - * |obj| must have passed a JS_IsArrayBufferObject test, or somehow be known - * that it would pass such a test: it is an ArrayBuffer or a wrapper of an - * ArrayBuffer, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetArrayBufferByteLength(JSObject* obj); - -extern JS_FRIEND_API(uint32_t) -JS_GetSharedArrayBufferByteLength(JSObject* obj); - -/** - * Return true if the arrayBuffer contains any data. This will return false for - * ArrayBuffer.prototype and detached ArrayBuffers. - * - * |obj| must have passed a JS_IsArrayBufferObject test, or somehow be known - * that it would pass such a test: it is an ArrayBuffer or a wrapper of an - * ArrayBuffer, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(bool) -JS_ArrayBufferHasData(JSObject* obj); - -/** - * Return a pointer to the start of the data referenced by a typed array. The - * data is still owned by the typed array, and should not be modified on - * another thread. Furthermore, the pointer can become invalid on GC (if the - * data is small and fits inside the array's GC header), so callers must take - * care not to hold on across anything that could GC. - * - * |obj| must have passed a JS_IsArrayBufferObject test, or somehow be known - * that it would pass such a test: it is an ArrayBuffer or a wrapper of an - * ArrayBuffer, and the unwrapping will succeed. - * - * *isSharedMemory will be set to false, the argument is present to simplify - * its use from code that also interacts with SharedArrayBuffer. - */ -extern JS_FRIEND_API(uint8_t*) -JS_GetArrayBufferData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/** - * Check whether the obj is ArrayBufferObject and memory mapped. Note that this - * may return false if a security wrapper is encountered that denies the - * unwrapping. - */ -extern JS_FRIEND_API(bool) -JS_IsMappedArrayBufferObject(JSObject* obj); - -/** - * Return the number of elements in a typed array. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetTypedArrayLength(JSObject* obj); - -/** - * Return the byte offset from the start of an array buffer to the start of a - * typed array view. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetTypedArrayByteOffset(JSObject* obj); - -/** - * Return the byte length of a typed array. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetTypedArrayByteLength(JSObject* obj); - -/** - * Check whether obj supports JS_ArrayBufferView* APIs. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. - */ -extern JS_FRIEND_API(bool) -JS_IsArrayBufferViewObject(JSObject* obj); - -/** - * More generic name for JS_GetTypedArrayByteLength to cover DataViews as well - */ -extern JS_FRIEND_API(uint32_t) -JS_GetArrayBufferViewByteLength(JSObject* obj); - -/* - * Return a pointer to the start of the data referenced by a typed array. The - * data is still owned by the typed array, and should not be modified on - * another thread. Furthermore, the pointer can become invalid on GC (if the - * data is small and fits inside the array's GC header), so callers must take - * care not to hold on across anything that could GC. - * - * |obj| must have passed a JS_Is*Array test, or somehow be known that it would - * pass such a test: it is a typed array or a wrapper of a typed array, and the - * unwrapping will succeed. - * - * *isSharedMemory will be set to true if the typed array maps a - * SharedArrayBuffer, otherwise to false. - */ - -extern JS_FRIEND_API(int8_t*) -JS_GetInt8ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint8_t*) -JS_GetUint8ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint8_t*) -JS_GetUint8ClampedArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(int16_t*) -JS_GetInt16ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint16_t*) -JS_GetUint16ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(int32_t*) -JS_GetInt32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint32_t*) -JS_GetUint32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(float*) -JS_GetFloat32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(double*) -JS_GetFloat64ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/** - * Same as above, but for any kind of ArrayBufferView. Prefer the type-specific - * versions when possible. - */ -extern JS_FRIEND_API(void*) -JS_GetArrayBufferViewData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/** - * Return the ArrayBuffer or SharedArrayBuffer underlying an ArrayBufferView. - * This may return a detached buffer. |obj| must be an object that would - * return true for JS_IsArrayBufferViewObject(). - */ -extern JS_FRIEND_API(JSObject*) -JS_GetArrayBufferViewBuffer(JSContext* cx, JS::HandleObject obj, bool* isSharedMemory); - -/** - * Detach an ArrayBuffer, causing all associated views to no longer refer to - * the ArrayBuffer's original attached memory. - * - * The |changeData| argument is obsolete and ignored. - */ -extern JS_FRIEND_API(bool) -JS_DetachArrayBuffer(JSContext* cx, JS::HandleObject obj); - -/** - * Check whether the obj is a detached ArrayBufferObject. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. - */ -extern JS_FRIEND_API(bool) -JS_IsDetachedArrayBufferObject(JSObject* obj); - -/** - * Check whether obj supports JS_GetDataView* APIs. - */ -JS_FRIEND_API(bool) -JS_IsDataViewObject(JSObject* obj); - -/** - * Create a new DataView using the given ArrayBuffer for storage. The given - * buffer must be an ArrayBuffer (or a cross-compartment wrapper of an - * ArrayBuffer), and the offset and length must fit within the bounds of the - * arrayBuffer. Currently, nullptr will be returned and an exception will be - * thrown if these conditions do not hold, but do not depend on that behavior. - */ -JS_FRIEND_API(JSObject*) -JS_NewDataView(JSContext* cx, JS::HandleObject arrayBuffer, uint32_t byteOffset, int32_t byteLength); - -/** - * Return the byte offset of a data view into its array buffer. |obj| must be a - * DataView. - * - * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that - * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. - */ -JS_FRIEND_API(uint32_t) -JS_GetDataViewByteOffset(JSObject* obj); - -/** - * Return the byte length of a data view. - * - * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that - * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be - * unable to assert when unwrapping should be disallowed. - */ -JS_FRIEND_API(uint32_t) -JS_GetDataViewByteLength(JSObject* obj); - -/** - * Return a pointer to the beginning of the data referenced by a DataView. - * - * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that - * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be - * unable to assert when unwrapping should be disallowed. - */ -JS_FRIEND_API(void*) -JS_GetDataViewData(JSObject* obj, const JS::AutoCheckCannotGC&); - -namespace js { - -/** - * Add a watchpoint -- in the Object.prototype.watch sense -- to |obj| for the - * property |id|, using the callable object |callable| as the function to be - * called for notifications. - * - * This is an internal function exposed -- temporarily -- only so that DOM - * proxies can be watchable. Don't use it! We'll soon kill off the - * Object.prototype.{,un}watch functions, at which point this will go too. - */ -extern JS_FRIEND_API(bool) -WatchGuts(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); - -/** - * Remove a watchpoint -- in the Object.prototype.watch sense -- from |obj| for - * the property |id|. - * - * This is an internal function exposed -- temporarily -- only so that DOM - * proxies can be watchable. Don't use it! We'll soon kill off the - * Object.prototype.{,un}watch functions, at which point this will go too. - */ -extern JS_FRIEND_API(bool) -UnwatchGuts(JSContext* cx, JS::HandleObject obj, JS::HandleId id); - -namespace jit { - -enum class InlinableNative : uint16_t; - -} // namespace jit - -} // namespace js - -/** - * A class, expected to be passed by value, which represents the CallArgs for a - * JSJitGetterOp. - */ -class JSJitGetterCallArgs : protected JS::MutableHandleValue -{ - public: - explicit JSJitGetterCallArgs(const JS::CallArgs& args) - : JS::MutableHandleValue(args.rval()) - {} - - explicit JSJitGetterCallArgs(JS::RootedValue* rooted) - : JS::MutableHandleValue(rooted) - {} - - JS::MutableHandleValue rval() { - return *this; - } -}; - -/** - * A class, expected to be passed by value, which represents the CallArgs for a - * JSJitSetterOp. - */ -class JSJitSetterCallArgs : protected JS::MutableHandleValue -{ - public: - explicit JSJitSetterCallArgs(const JS::CallArgs& args) - : JS::MutableHandleValue(args[0]) - {} - - JS::MutableHandleValue operator[](unsigned i) { - MOZ_ASSERT(i == 0); - return *this; - } - - unsigned length() const { return 1; } - - // Add get() or maybe hasDefined() as needed -}; - -struct JSJitMethodCallArgsTraits; - -/** - * A class, expected to be passed by reference, which represents the CallArgs - * for a JSJitMethodOp. - */ -class JSJitMethodCallArgs : protected JS::detail::CallArgsBase -{ - private: - typedef JS::detail::CallArgsBase Base; - friend struct JSJitMethodCallArgsTraits; - - public: - explicit JSJitMethodCallArgs(const JS::CallArgs& args) { - argv_ = args.array(); - argc_ = args.length(); - } - - JS::MutableHandleValue rval() const { - return Base::rval(); - } - - unsigned length() const { return Base::length(); } - - JS::MutableHandleValue operator[](unsigned i) const { - return Base::operator[](i); - } - - bool hasDefined(unsigned i) const { - return Base::hasDefined(i); - } - - JSObject& callee() const { - // We can't use Base::callee() because that will try to poke at - // this->usedRval_, which we don't have. - return argv_[-2].toObject(); - } - - JS::HandleValue get(unsigned i) const { - return Base::get(i); - } -}; - -struct JSJitMethodCallArgsTraits -{ - static const size_t offsetOfArgv = offsetof(JSJitMethodCallArgs, argv_); - static const size_t offsetOfArgc = offsetof(JSJitMethodCallArgs, argc_); -}; - -typedef bool -(* JSJitGetterOp)(JSContext* cx, JS::HandleObject thisObj, - void* specializedThis, JSJitGetterCallArgs args); -typedef bool -(* JSJitSetterOp)(JSContext* cx, JS::HandleObject thisObj, - void* specializedThis, JSJitSetterCallArgs args); -typedef bool -(* JSJitMethodOp)(JSContext* cx, JS::HandleObject thisObj, - void* specializedThis, const JSJitMethodCallArgs& args); - -/** - * This struct contains metadata passed from the DOM to the JS Engine for JIT - * optimizations on DOM property accessors. Eventually, this should be made - * available to general JSAPI users, but we are not currently ready to do so. - */ -struct JSJitInfo { - enum OpType { - Getter, - Setter, - Method, - StaticMethod, - InlinableNative, - // Must be last - OpTypeCount - }; - - enum ArgType { - // Basic types - String = (1 << 0), - Integer = (1 << 1), // Only 32-bit or less - Double = (1 << 2), // Maybe we want to add Float sometime too - Boolean = (1 << 3), - Object = (1 << 4), - Null = (1 << 5), - - // And derived types - Numeric = Integer | Double, - // Should "Primitive" use the WebIDL definition, which - // excludes string and null, or the typical JS one that includes them? - Primitive = Numeric | Boolean | Null | String, - ObjectOrNull = Object | Null, - Any = ObjectOrNull | Primitive, - - // Our sentinel value. - ArgTypeListEnd = (1 << 31) - }; - - static_assert(Any & String, "Any must include String."); - static_assert(Any & Integer, "Any must include Integer."); - static_assert(Any & Double, "Any must include Double."); - static_assert(Any & Boolean, "Any must include Boolean."); - static_assert(Any & Object, "Any must include Object."); - static_assert(Any & Null, "Any must include Null."); - - /** - * An enum that describes what this getter/setter/method aliases. This - * determines what things can be hoisted past this call, and if this - * call is movable what it can be hoisted past. - */ - enum AliasSet { - /** - * Alias nothing: a constant value, getting it can't affect any other - * values, nothing can affect it. - */ - AliasNone, - - /** - * Alias things that can modify the DOM but nothing else. Doing the - * call can't affect the behavior of any other function. - */ - AliasDOMSets, - - /** - * Alias the world. Calling this can change arbitrary values anywhere - * in the system. Most things fall in this bucket. - */ - AliasEverything, - - /** Must be last. */ - AliasSetCount - }; - - bool needsOuterizedThisObject() const - { - return type() != Getter && type() != Setter; - } - - bool isTypedMethodJitInfo() const - { - return isTypedMethod; - } - - OpType type() const - { - return OpType(type_); - } - - AliasSet aliasSet() const - { - return AliasSet(aliasSet_); - } - - JSValueType returnType() const - { - return JSValueType(returnType_); - } - - union { - JSJitGetterOp getter; - JSJitSetterOp setter; - JSJitMethodOp method; - /** A DOM static method, used for Promise wrappers */ - JSNative staticMethod; - }; - - union { - uint16_t protoID; - js::jit::InlinableNative inlinableNative; - }; - - union { - uint16_t depth; - - // Additional opcode for some InlinableNative functions. - uint16_t nativeOp; - }; - - // These fields are carefully packed to take up 4 bytes. If you need more - // bits for whatever reason, please see if you can steal bits from existing - // fields before adding more members to this structure. - -#define JITINFO_OP_TYPE_BITS 4 -#define JITINFO_ALIAS_SET_BITS 4 -#define JITINFO_RETURN_TYPE_BITS 8 -#define JITINFO_SLOT_INDEX_BITS 10 - - /** The OpType that says what sort of function we are. */ - uint32_t type_ : JITINFO_OP_TYPE_BITS; - - /** - * The alias set for this op. This is a _minimal_ alias set; in - * particular for a method it does not include whatever argument - * conversions might do. That's covered by argTypes and runtime - * analysis of the actual argument types being passed in. - */ - uint32_t aliasSet_ : JITINFO_ALIAS_SET_BITS; - - /** The return type tag. Might be JSVAL_TYPE_UNKNOWN. */ - uint32_t returnType_ : JITINFO_RETURN_TYPE_BITS; - - static_assert(OpTypeCount <= (1 << JITINFO_OP_TYPE_BITS), - "Not enough space for OpType"); - static_assert(AliasSetCount <= (1 << JITINFO_ALIAS_SET_BITS), - "Not enough space for AliasSet"); - static_assert((sizeof(JSValueType) * 8) <= JITINFO_RETURN_TYPE_BITS, - "Not enough space for JSValueType"); - -#undef JITINFO_RETURN_TYPE_BITS -#undef JITINFO_ALIAS_SET_BITS -#undef JITINFO_OP_TYPE_BITS - - /** Is op fallible? False in setters. */ - uint32_t isInfallible : 1; - - /** - * Is op movable? To be movable the op must - * not AliasEverything, but even that might - * not be enough (e.g. in cases when it can - * throw or is explicitly not movable). - */ - uint32_t isMovable : 1; - - /** - * Can op be dead-code eliminated? Again, this - * depends on whether the op can throw, in - * addition to the alias set. - */ - uint32_t isEliminatable : 1; - - // XXXbz should we have a JSValueType for the type of the member? - /** - * True if this is a getter that can always - * get the value from a slot of the "this" object. - */ - uint32_t isAlwaysInSlot : 1; - - /** - * True if this is a getter that can sometimes (if the slot doesn't contain - * UndefinedValue()) get the value from a slot of the "this" object. - */ - uint32_t isLazilyCachedInSlot : 1; - - /** True if this is an instance of JSTypedMethodJitInfo. */ - uint32_t isTypedMethod : 1; - - /** - * If isAlwaysInSlot or isSometimesInSlot is true, - * the index of the slot to get the value from. - * Otherwise 0. - */ - uint32_t slotIndex : JITINFO_SLOT_INDEX_BITS; - - static const size_t maxSlotIndex = (1 << JITINFO_SLOT_INDEX_BITS) - 1; - -#undef JITINFO_SLOT_INDEX_BITS -}; - -static_assert(sizeof(JSJitInfo) == (sizeof(void*) + 2 * sizeof(uint32_t)), - "There are several thousand instances of JSJitInfo stored in " - "a binary. Please don't increase its space requirements without " - "verifying that there is no other way forward (better packing, " - "smaller datatypes for fields, subclassing, etc.)."); - -struct JSTypedMethodJitInfo -{ - // We use C-style inheritance here, rather than C++ style inheritance - // because not all compilers support brace-initialization for non-aggregate - // classes. Using C++ style inheritance and constructors instead of - // brace-initialization would also force the creation of static - // constructors (on some compilers) when JSJitInfo and JSTypedMethodJitInfo - // structures are declared. Since there can be several thousand of these - // structures present and we want to have roughly equivalent performance - // across a range of compilers, we do things manually. - JSJitInfo base; - - const JSJitInfo::ArgType* const argTypes; /* For a method, a list of sets of - types that the function - expects. This can be used, - for example, to figure out - when argument coercions can - have side-effects. */ -}; - -namespace js { - -static MOZ_ALWAYS_INLINE shadow::Function* -FunctionObjectToShadowFunction(JSObject* fun) -{ - MOZ_ASSERT(GetObjectClass(fun) == FunctionClassPtr); - return reinterpret_cast(fun); -} - -/* Statically asserted in jsfun.h. */ -static const unsigned JS_FUNCTION_INTERPRETED_BITS = 0x0201; - -// Return whether the given function object is native. -static MOZ_ALWAYS_INLINE bool -FunctionObjectIsNative(JSObject* fun) -{ - return !(FunctionObjectToShadowFunction(fun)->flags & JS_FUNCTION_INTERPRETED_BITS); -} - -static MOZ_ALWAYS_INLINE JSNative -GetFunctionObjectNative(JSObject* fun) -{ - MOZ_ASSERT(FunctionObjectIsNative(fun)); - return FunctionObjectToShadowFunction(fun)->native; -} - -} // namespace js - -static MOZ_ALWAYS_INLINE const JSJitInfo* -FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) -{ - MOZ_ASSERT(js::FunctionObjectIsNative(&v.toObject())); - return js::FunctionObjectToShadowFunction(&v.toObject())->jitinfo; -} - -static MOZ_ALWAYS_INLINE void -SET_JITINFO(JSFunction * func, const JSJitInfo* info) -{ - js::shadow::Function* fun = reinterpret_cast(func); - MOZ_ASSERT(!(fun->flags & js::JS_FUNCTION_INTERPRETED_BITS)); - fun->jitinfo = info; -} - -/* - * Engine-internal extensions of jsid. This code is here only until we - * eliminate Gecko's dependencies on it! - */ - -static MOZ_ALWAYS_INLINE jsid -JSID_FROM_BITS(size_t bits) -{ - jsid id; - JSID_BITS(id) = bits; - return id; -} - -namespace js { -namespace detail { -bool IdMatchesAtom(jsid id, JSAtom* atom); -} // namespace detail -} // namespace js - -/** - * Must not be used on atoms that are representable as integer jsids. - * Prefer NameToId or AtomToId over this function: - * - * A PropertyName is an atom that does not contain an integer in the range - * [0, UINT32_MAX]. However, jsid can only hold an integer in the range - * [0, JSID_INT_MAX] (where JSID_INT_MAX == 2^31-1). Thus, for the range of - * integers (JSID_INT_MAX, UINT32_MAX], to represent as a jsid 'id', it must be - * the case JSID_IS_ATOM(id) and !JSID_TO_ATOM(id)->isPropertyName(). In most - * cases when creating a jsid, code does not have to care about this corner - * case because: - * - * - When given an arbitrary JSAtom*, AtomToId must be used, which checks for - * integer atoms representable as integer jsids, and does this conversion. - * - * - When given a PropertyName*, NameToId can be used which which does not need - * to do any dynamic checks. - * - * Thus, it is only the rare third case which needs this function, which - * handles any JSAtom* that is known not to be representable with an int jsid. - */ -static MOZ_ALWAYS_INLINE jsid -NON_INTEGER_ATOM_TO_JSID(JSAtom* atom) -{ - MOZ_ASSERT(((size_t)atom & 0x7) == 0); - jsid id = JSID_FROM_BITS((size_t)atom); - MOZ_ASSERT(js::detail::IdMatchesAtom(id, atom)); - return id; -} - -/* All strings stored in jsids are atomized, but are not necessarily property names. */ -static MOZ_ALWAYS_INLINE bool -JSID_IS_ATOM(jsid id) -{ - return JSID_IS_STRING(id); -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_ATOM(jsid id, JSAtom* atom) -{ - return id == JSID_FROM_BITS((size_t)atom); -} - -static MOZ_ALWAYS_INLINE JSAtom* -JSID_TO_ATOM(jsid id) -{ - return (JSAtom*)JSID_TO_STRING(id); -} - -JS_STATIC_ASSERT(sizeof(jsid) == sizeof(void*)); - -namespace js { - -static MOZ_ALWAYS_INLINE JS::Value -IdToValue(jsid id) -{ - if (JSID_IS_STRING(id)) - return JS::StringValue(JSID_TO_STRING(id)); - if (JSID_IS_INT(id)) - return JS::Int32Value(JSID_TO_INT(id)); - if (JSID_IS_SYMBOL(id)) - return JS::SymbolValue(JSID_TO_SYMBOL(id)); - MOZ_ASSERT(JSID_IS_VOID(id)); - return JS::UndefinedValue(); -} - -/** - * If the embedder has registered a ScriptEnvironmentPreparer, - * PrepareScriptEnvironmentAndInvoke will call the preparer's 'invoke' method - * with the given |closure|, with the assumption that the preparer will set up - * any state necessary to run script in |scope|, invoke |closure| with a valid - * JSContext*, report any exceptions thrown from the closure, and return. - * - * If no preparer is registered, PrepareScriptEnvironmentAndInvoke will assert - * that |rt| has exactly one JSContext associated with it, enter the compartment - * of |scope| on that context, and invoke |closure|. - * - * In both cases, PrepareScriptEnvironmentAndInvoke will report any exceptions - * that are thrown by the closure. Consumers who want to propagate back - * whether the closure succeeded should do so via members of the closure - * itself. - */ - -struct ScriptEnvironmentPreparer { - struct Closure { - virtual bool operator()(JSContext* cx) = 0; - }; - - virtual void invoke(JS::HandleObject scope, Closure& closure) = 0; -}; - -extern JS_FRIEND_API(void) -PrepareScriptEnvironmentAndInvoke(JSContext* cx, JS::HandleObject scope, - ScriptEnvironmentPreparer::Closure& closure); - -JS_FRIEND_API(void) -SetScriptEnvironmentPreparer(JSContext* cx, ScriptEnvironmentPreparer* preparer); - -enum CTypesActivityType { - CTYPES_CALL_BEGIN, - CTYPES_CALL_END, - CTYPES_CALLBACK_BEGIN, - CTYPES_CALLBACK_END -}; - -typedef void -(* CTypesActivityCallback)(JSContext* cx, CTypesActivityType type); - -/** - * Sets a callback that is run whenever js-ctypes is about to be used when - * calling into C. - */ -JS_FRIEND_API(void) -SetCTypesActivityCallback(JSContext* cx, CTypesActivityCallback cb); - -class MOZ_RAII JS_FRIEND_API(AutoCTypesActivityCallback) { - private: - JSContext* cx; - CTypesActivityCallback callback; - CTypesActivityType endType; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - - public: - AutoCTypesActivityCallback(JSContext* cx, CTypesActivityType beginType, - CTypesActivityType endType - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~AutoCTypesActivityCallback() { - DoEndCallback(); - } - void DoEndCallback() { - if (callback) { - callback(cx, endType); - callback = nullptr; - } - } -}; - -// Abstract base class for objects that build allocation metadata for JavaScript -// values. -struct AllocationMetadataBuilder { - AllocationMetadataBuilder() { } - - // Return a metadata object for the newly constructed object |obj|, or - // nullptr if there's no metadata to attach. - // - // Implementations should treat all errors as fatal; there is no way to - // report errors from this callback. In particular, the caller provides an - // oomUnsafe for overriding implementations to use. - virtual JSObject* build(JSContext* cx, JS::HandleObject obj, - AutoEnterOOMUnsafeRegion& oomUnsafe) const - { - return nullptr; - } -}; - -/** - * Specify a callback to invoke when creating each JS object in the current - * compartment, which may return a metadata object to associate with the - * object. - */ -JS_FRIEND_API(void) -SetAllocationMetadataBuilder(JSContext* cx, const AllocationMetadataBuilder *callback); - -/** Get the metadata associated with an object. */ -JS_FRIEND_API(JSObject*) -GetAllocationMetadata(JSObject* obj); - -JS_FRIEND_API(bool) -GetElementsWithAdder(JSContext* cx, JS::HandleObject obj, JS::HandleObject receiver, - uint32_t begin, uint32_t end, js::ElementAdder* adder); - -JS_FRIEND_API(bool) -ForwardToNative(JSContext* cx, JSNative native, const JS::CallArgs& args); - -/** - * Helper function for HTMLDocument and HTMLFormElement. - * - * These are the only two interfaces that have [OverrideBuiltins], a named - * getter, and no named setter. They're implemented as proxies with a custom - * getOwnPropertyDescriptor() method. Unfortunately, overriding - * getOwnPropertyDescriptor() automatically affects the behavior of set(), - * which normally is just common sense but is *not* desired for these two - * interfaces. - * - * The fix is for these two interfaces to override set() to ignore the - * getOwnPropertyDescriptor() override. - * - * SetPropertyIgnoringNamedGetter is exposed to make it easier to override - * set() in this way. It carries out all the steps of BaseProxyHandler::set() - * except the initial getOwnPropertyDescriptor() call. The caller must supply - * that descriptor as the 'ownDesc' parameter. - * - * Implemented in proxy/BaseProxyHandler.cpp. - */ -JS_FRIEND_API(bool) -SetPropertyIgnoringNamedGetter(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::HandleValue v, JS::HandleValue receiver, - JS::Handle ownDesc, - JS::ObjectOpResult& result); - -JS_FRIEND_API(void) -ReportASCIIErrorWithId(JSContext* cx, const char* msg, JS::HandleId id); - -// This function is for one specific use case, please don't use this for anything else! -extern JS_FRIEND_API(bool) -ExecuteInGlobalAndReturnScope(JSContext* cx, JS::HandleObject obj, JS::HandleScript script, - JS::MutableHandleObject scope); - -#if defined(XP_WIN) && defined(_WIN64) -// Parameters use void* types to avoid #including windows.h. The return value of -// this function is returned from the exception handler. -typedef long -(*JitExceptionHandler)(void* exceptionRecord, // PEXECTION_RECORD - void* context); // PCONTEXT - -/** - * Windows uses "structured exception handling" to handle faults. When a fault - * occurs, the stack is searched for a handler (similar to C++ exception - * handling). If the search does not find a handler, the "unhandled exception - * filter" is called. Breakpad uses the unhandled exception filter to do crash - * reporting. Unfortunately, on Win64, JIT code on the stack completely throws - * off this unwinding process and prevents the unhandled exception filter from - * being called. The reason is that Win64 requires unwind information be - * registered for all code regions and JIT code has none. While it is possible - * to register full unwind information for JIT code, this is a lot of work (one - * has to be able to recover the frame pointer at any PC) so instead we register - * a handler for all JIT code that simply calls breakpad's unhandled exception - * filter (which will perform crash reporting and then terminate the process). - * This would be wrong if there was an outer __try block that expected to handle - * the fault, but this is not generally allowed. - * - * Gecko must call SetJitExceptionFilter before any JIT code is compiled and - * only once per process. - */ -extern JS_FRIEND_API(void) -SetJitExceptionHandler(JitExceptionHandler handler); -#endif - -/** - * Get the nearest enclosing with environment object for a given function. If - * the function is not scripted or is not enclosed by a with scope, returns - * the global. - */ -extern JS_FRIEND_API(JSObject*) -GetNearestEnclosingWithEnvironmentObjectForFunction(JSFunction* fun); - -/** - * Get the first SavedFrame object in this SavedFrame stack whose principals are - * subsumed by the cx's principals. If there is no such frame, return nullptr. - * - * Do NOT pass a non-SavedFrame object here. - * - * The savedFrame and cx do not need to be in the same compartment. - */ -extern JS_FRIEND_API(JSObject*) -GetFirstSubsumedSavedFrame(JSContext* cx, JS::HandleObject savedFrame, JS::SavedFrameSelfHosted selfHosted); - -extern JS_FRIEND_API(bool) -ReportIsNotFunction(JSContext* cx, JS::HandleValue v); - -extern JS_FRIEND_API(JSObject*) -ConvertArgsToArray(JSContext* cx, const JS::CallArgs& args); - -/** - * Window and WindowProxy - * - * The functions below have to do with Windows and WindowProxies. There's an - * invariant that actual Window objects (the global objects of web pages) are - * never directly exposed to script. Instead we often substitute a WindowProxy. - * - * The environment chain, on the other hand, contains the Window and never its - * WindowProxy. - * - * As a result, we have calls to these "substitute-this-object-for-that-object" - * functions sprinkled at apparently arbitrary (but actually *very* carefully - * and nervously selected) places throughout the engine and indeed the - * universe. - */ - -/** - * Tell the JS engine which Class is used for WindowProxy objects. Used by the - * functions below. - */ -extern JS_FRIEND_API(void) -SetWindowProxyClass(JSContext* cx, const Class* clasp); - -/** - * Associates a WindowProxy with a Window (global object). `windowProxy` must - * have the Class set by SetWindowProxyClass. - */ -extern JS_FRIEND_API(void) -SetWindowProxy(JSContext* cx, JS::HandleObject global, JS::HandleObject windowProxy); - -namespace detail { - -JS_FRIEND_API(bool) -IsWindowSlow(JSObject* obj); - -} // namespace detail - -/** - * Returns true iff `obj` is a global object with an associated WindowProxy, - * see SetWindowProxy. - */ -inline bool -IsWindow(JSObject* obj) -{ - if (GetObjectClass(obj)->flags & JSCLASS_IS_GLOBAL) - return detail::IsWindowSlow(obj); - return false; -} - -/** - * Returns true iff `obj` has the WindowProxy Class (see SetWindowProxyClass). - */ -JS_FRIEND_API(bool) -IsWindowProxy(JSObject* obj); - -/** - * If `obj` is a Window, get its associated WindowProxy (or a CCW or dead - * wrapper if the page was navigated away from), else return `obj`. This - * function is infallible and never returns nullptr. - */ -extern JS_FRIEND_API(JSObject*) -ToWindowProxyIfWindow(JSObject* obj); - -/** - * If `obj` is a WindowProxy, get its associated Window (the compartment's - * global), else return `obj`. This function is infallible and never returns - * nullptr. - */ -extern JS_FRIEND_API(JSObject*) -ToWindowIfWindowProxy(JSObject* obj); - -} /* namespace js */ - -class NativeProfiler -{ - public: - virtual ~NativeProfiler() {}; - virtual void sampleNative(void* addr, uint32_t size) = 0; - virtual void removeNative(void* addr) = 0; - virtual void reset() = 0; -}; - -class GCHeapProfiler -{ - public: - virtual ~GCHeapProfiler() {}; - virtual void sampleTenured(void* addr, uint32_t size) = 0; - virtual void sampleNursery(void* addr, uint32_t size) = 0; - virtual void markTenuredStart() = 0; - virtual void markTenured(void* addr) = 0; - virtual void sweepTenured() = 0; - virtual void sweepNursery() = 0; - virtual void moveNurseryToTenured(void* addrOld, void* addrNew) = 0; - virtual void reset() = 0; -}; - -class MemProfiler -{ - static mozilla::Atomic sActiveProfilerCount; - static NativeProfiler* sNativeProfiler; - - static GCHeapProfiler* GetGCHeapProfiler(void* addr); - static GCHeapProfiler* GetGCHeapProfiler(JSRuntime* runtime); - - static NativeProfiler* GetNativeProfiler() { - return sNativeProfiler; - } - - GCHeapProfiler* mGCHeapProfiler; - JSRuntime* mRuntime; - - public: - explicit MemProfiler(JSRuntime* aRuntime) : mGCHeapProfiler(nullptr), mRuntime(aRuntime) {} - - void start(GCHeapProfiler* aGCHeapProfiler); - void stop(); - - GCHeapProfiler* getGCHeapProfiler() const { - return mGCHeapProfiler; - } - - static MOZ_ALWAYS_INLINE bool enabled() { - return sActiveProfilerCount > 0; - } - - static MemProfiler* GetMemProfiler(JSContext* context); - - static void SetNativeProfiler(NativeProfiler* aProfiler) { - sNativeProfiler = aProfiler; - } - - static MOZ_ALWAYS_INLINE void SampleNative(void* addr, uint32_t size) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - NativeProfiler* profiler = GetNativeProfiler(); - if (profiler) - profiler->sampleNative(addr, size); - } - - static MOZ_ALWAYS_INLINE void SampleTenured(void* addr, uint32_t size) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addr); - if (profiler) - profiler->sampleTenured(addr, size); - } - - static MOZ_ALWAYS_INLINE void SampleNursery(void* addr, uint32_t size) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addr); - if (profiler) - profiler->sampleNursery(addr, size); - } - - static MOZ_ALWAYS_INLINE void RemoveNative(void* addr) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - NativeProfiler* profiler = GetNativeProfiler(); - if (profiler) - profiler->removeNative(addr); - } - - static MOZ_ALWAYS_INLINE void MarkTenuredStart(JSRuntime* runtime) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(runtime); - if (profiler) - profiler->markTenuredStart(); - } - - static MOZ_ALWAYS_INLINE void MarkTenured(void* addr) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addr); - if (profiler) - profiler->markTenured(addr); - } - - static MOZ_ALWAYS_INLINE void SweepTenured(JSRuntime* runtime) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(runtime); - if (profiler) - profiler->sweepTenured(); - } - - static MOZ_ALWAYS_INLINE void SweepNursery(JSRuntime* runtime) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(runtime); - if (profiler) - profiler->sweepNursery(); - } - - static MOZ_ALWAYS_INLINE void MoveNurseryToTenured(void* addrOld, void* addrNew) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addrOld); - if (profiler) - profiler->moveNurseryToTenured(addrOld, addrNew); - } -}; - -#endif /* jsfriendapi_h */ diff --git a/mac/include/spidermonkey/jsperf.h b/mac/include/spidermonkey/jsperf.h deleted file mode 100644 index b8f2909a..00000000 --- a/mac/include/spidermonkey/jsperf.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef perf_jsperf_h -#define perf_jsperf_h - -#include "jstypes.h" - -#include "js/TypeDecls.h" -#include "js/Utility.h" - -namespace JS { - -/* - * JS::PerfMeasurement is a generic way to access detailed performance - * measurement APIs provided by your operating system. The details of - * exactly how this works and what can be measured are highly - * system-specific, but this interface is (one hopes) implementable - * on top of all of them. - * - * To use this API, create a PerfMeasurement object, passing its - * constructor a bitmask indicating which events you are interested - * in. Thereafter, Start() zeroes all counters and starts timing; - * Stop() stops timing again; and the counters for the events you - * requested are available as data values after calling Stop(). The - * object may be reused for many measurements. - */ -class JS_FRIEND_API(PerfMeasurement) -{ - protected: - // Implementation-specific data, if any. - void* impl; - - public: - /* - * Events that may be measured. Taken directly from the list of - * "generalized hardware performance event types" in the Linux - * perf_event API, plus some of the "software events". - */ - enum EventMask { - CPU_CYCLES = 0x00000001, - INSTRUCTIONS = 0x00000002, - CACHE_REFERENCES = 0x00000004, - CACHE_MISSES = 0x00000008, - BRANCH_INSTRUCTIONS = 0x00000010, - BRANCH_MISSES = 0x00000020, - BUS_CYCLES = 0x00000040, - PAGE_FAULTS = 0x00000080, - MAJOR_PAGE_FAULTS = 0x00000100, - CONTEXT_SWITCHES = 0x00000200, - CPU_MIGRATIONS = 0x00000400, - - ALL = 0x000007ff, - NUM_MEASURABLE_EVENTS = 11 - }; - - /* - * Bitmask of events that will be measured when this object is - * active (between Start() and Stop()). This may differ from the - * bitmask passed to the constructor if the platform does not - * support measuring all of the requested events. - */ - const EventMask eventsMeasured; - - /* - * Counters for each measurable event. - * Immediately after one of these objects is created, all of the - * counters for enabled events will be zero, and all of the - * counters for disabled events will be uint64_t(-1). - */ - uint64_t cpu_cycles; - uint64_t instructions; - uint64_t cache_references; - uint64_t cache_misses; - uint64_t branch_instructions; - uint64_t branch_misses; - uint64_t bus_cycles; - uint64_t page_faults; - uint64_t major_page_faults; - uint64_t context_switches; - uint64_t cpu_migrations; - - /* - * Prepare to measure the indicated set of events. If not all of - * the requested events can be measured on the current platform, - * then the eventsMeasured bitmask will only include the subset of - * |toMeasure| corresponding to the events that can be measured. - */ - explicit PerfMeasurement(EventMask toMeasure); - - /* Done with this set of measurements, tear down OS-level state. */ - ~PerfMeasurement(); - - /* Start a measurement cycle. */ - void start(); - - /* - * End a measurement cycle, and for each enabled counter, add the - * number of measured events of that type to the appropriate - * visible variable. - */ - void stop(); - - /* Reset all enabled counters to zero. */ - void reset(); - - /* - * True if this platform supports measuring _something_, i.e. it's - * not using the stub implementation. - */ - static bool canMeasureSomething(); -}; - -/* Inject a Javascript wrapper around the above C++ class into the - * Javascript object passed as an argument (this will normally be a - * global object). The JS-visible API is identical to the C++ API. - */ -extern JS_FRIEND_API(JSObject*) - RegisterPerfMeasurement(JSContext* cx, JS::HandleObject global); - -/* - * Given a Value which contains an instance of the aforementioned - * wrapper class, extract the C++ object. Returns nullptr if the - * Value is not an instance of the wrapper. - */ -extern JS_FRIEND_API(PerfMeasurement*) - ExtractPerfMeasurement(const Value& wrapper); - -} // namespace JS - -#endif /* perf_jsperf_h */ diff --git a/mac/include/spidermonkey/jsprf.h b/mac/include/spidermonkey/jsprf.h deleted file mode 100644 index b84b5a5c..00000000 --- a/mac/include/spidermonkey/jsprf.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsprf_h -#define jsprf_h - -/* -** API for PR printf like routines. Supports the following formats -** %d - decimal -** %u - unsigned decimal -** %x - unsigned hex -** %X - unsigned uppercase hex -** %o - unsigned octal -** %hd, %hu, %hx, %hX, %ho - "short" versions of above -** %ld, %lu, %lx, %lX, %lo - "long" versions of above -** %lld, %llu, %llx, %llX, %llo - "long long" versions of above -** %zd, %zo, %zu, %zx, %zX - size_t versions of above -** %Id, %Io, %Iu, %Ix, %IX - size_t versions of above (for Windows compat) -** You should use PRI*SIZE macros instead -** %s - string -** %c - character -** %p - pointer (deals with machine dependent pointer size) -** %f - float -** %g - float -*/ - -#include "mozilla/IntegerPrintfMacros.h" -#include "mozilla/SizePrintfMacros.h" - -#include - -#include "jstypes.h" - -/* -** sprintf into a malloc'd buffer. Return a pointer to the malloc'd -** buffer on success, nullptr on failure. Call "JS_smprintf_free" to release -** the memory returned. -*/ -extern JS_PUBLIC_API(char*) JS_smprintf(const char* fmt, ...) - MOZ_FORMAT_PRINTF(1, 2); - -/* -** Free the memory allocated, for the caller, by JS_smprintf -*/ -extern JS_PUBLIC_API(void) JS_smprintf_free(char* mem); - -/* -** "append" sprintf into a malloc'd buffer. "last" is the last value of -** the malloc'd buffer. sprintf will append data to the end of last, -** growing it as necessary using realloc. If last is nullptr, JS_sprintf_append -** will allocate the initial string. The return value is the new value of -** last for subsequent calls, or nullptr if there is a malloc failure. -*/ -extern JS_PUBLIC_API(char*) JS_sprintf_append(char* last, const char* fmt, ...) - MOZ_FORMAT_PRINTF(2, 3); - -/* -** va_list forms of the above. -*/ -extern JS_PUBLIC_API(char*) JS_vsmprintf(const char* fmt, va_list ap); -extern JS_PUBLIC_API(char*) JS_vsprintf_append(char* last, const char* fmt, va_list ap); - -#endif /* jsprf_h */ diff --git a/mac/include/spidermonkey/jsprototypes.h b/mac/include/spidermonkey/jsprototypes.h deleted file mode 100644 index f409dce9..00000000 --- a/mac/include/spidermonkey/jsprototypes.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsprototypes_h -#define jsprototypes_h - -/* A higher-order macro for enumerating all JSProtoKey values. */ -/* - * Consumers define macros as follows: - * macro(name, code, init, clasp) - * name: The canonical name of the class. - * code: The enumerator code. There are part of the XDR API, and must not change. - * init: Initialization function. These are |extern "C";|, and clients should use - * |extern "C" {}| as appropriate when using this macro. - * clasp: The JSClass for this object, or "dummy" if it doesn't exist. - * - * - * Consumers wishing to iterate over all the JSProtoKey values, can use - * JS_FOR_EACH_PROTOTYPE. However, there are certain values that don't correspond - * to real constructors, like Null or constructors that are disabled via - * preprocessor directives. We still need to include these in the JSProtoKey list - * in order to maintain binary XDR compatibility, but we need to provide a tool - * to handle them differently. JS_FOR_PROTOTYPES fills this niche. - * - * Consumers pass two macros to JS_FOR_PROTOTYPES - |real| and |imaginary|. The - * former is invoked for entries that have real client-exposed constructors, and - * the latter is called for the rest. Consumers that don't care about this - * distinction can simply pass the same macro to both, which is exactly what - * JS_FOR_EACH_PROTOTYPE does. - */ - -#define CLASP(name) (&name##Class) -#define OCLASP(name) (&name##Object::class_) -#define TYPED_ARRAY_CLASP(type) (&TypedArrayObject::classes[Scalar::type]) -#define ERROR_CLASP(type) (&ErrorObject::classes[type]) - -#ifdef EXPOSE_INTL_API -#define IF_INTL(real,imaginary) real -#else -#define IF_INTL(real,imaginary) imaginary -#endif - -#ifdef ENABLE_BINARYDATA -#define IF_BDATA(real,imaginary) real -#else -#define IF_BDATA(real,imaginary) imaginary -#endif - -#ifdef ENABLE_SIMD -# define IF_SIMD(real,imaginary) real -#else -# define IF_SIMD(real,imaginary) imaginary -#endif - -#ifdef ENABLE_SHARED_ARRAY_BUFFER -#define IF_SAB(real,imaginary) real -#else -#define IF_SAB(real,imaginary) imaginary -#endif - -#ifdef SPIDERMONKEY_PROMISE -#define IF_PROMISE(real,imaginary) real -#else -#define IF_PROMISE(real,imaginary) imaginary -#endif - -#define JS_FOR_PROTOTYPES(real,imaginary) \ - imaginary(Null, 0, InitNullClass, dummy) \ - real(Object, 1, InitViaClassSpec, OCLASP(Plain)) \ - real(Function, 2, InitViaClassSpec, &JSFunction::class_) \ - real(Array, 3, InitViaClassSpec, OCLASP(Array)) \ - real(Boolean, 4, InitBooleanClass, OCLASP(Boolean)) \ - real(JSON, 5, InitJSONClass, CLASP(JSON)) \ - real(Date, 6, InitViaClassSpec, OCLASP(Date)) \ - real(Math, 7, InitMathClass, CLASP(Math)) \ - real(Number, 8, InitNumberClass, OCLASP(Number)) \ - real(String, 9, InitStringClass, OCLASP(String)) \ - real(RegExp, 10, InitViaClassSpec, OCLASP(RegExp)) \ - real(Error, 11, InitViaClassSpec, ERROR_CLASP(JSEXN_ERR)) \ - real(InternalError, 12, InitViaClassSpec, ERROR_CLASP(JSEXN_INTERNALERR)) \ - real(EvalError, 13, InitViaClassSpec, ERROR_CLASP(JSEXN_EVALERR)) \ - real(RangeError, 14, InitViaClassSpec, ERROR_CLASP(JSEXN_RANGEERR)) \ - real(ReferenceError, 15, InitViaClassSpec, ERROR_CLASP(JSEXN_REFERENCEERR)) \ - real(SyntaxError, 16, InitViaClassSpec, ERROR_CLASP(JSEXN_SYNTAXERR)) \ - real(TypeError, 17, InitViaClassSpec, ERROR_CLASP(JSEXN_TYPEERR)) \ - real(URIError, 18, InitViaClassSpec, ERROR_CLASP(JSEXN_URIERR)) \ - real(DebuggeeWouldRun, 19, InitViaClassSpec, ERROR_CLASP(JSEXN_DEBUGGEEWOULDRUN)) \ - real(CompileError, 20, InitViaClassSpec, ERROR_CLASP(JSEXN_WASMCOMPILEERROR)) \ - real(RuntimeError, 21, InitViaClassSpec, ERROR_CLASP(JSEXN_WASMRUNTIMEERROR)) \ - real(Iterator, 22, InitLegacyIteratorClass,OCLASP(PropertyIterator)) \ - real(StopIteration, 23, InitStopIterationClass, OCLASP(StopIteration)) \ - real(ArrayBuffer, 24, InitViaClassSpec, OCLASP(ArrayBuffer)) \ - real(Int8Array, 25, InitViaClassSpec, TYPED_ARRAY_CLASP(Int8)) \ - real(Uint8Array, 26, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint8)) \ - real(Int16Array, 27, InitViaClassSpec, TYPED_ARRAY_CLASP(Int16)) \ - real(Uint16Array, 28, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint16)) \ - real(Int32Array, 29, InitViaClassSpec, TYPED_ARRAY_CLASP(Int32)) \ - real(Uint32Array, 30, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint32)) \ - real(Float32Array, 31, InitViaClassSpec, TYPED_ARRAY_CLASP(Float32)) \ - real(Float64Array, 32, InitViaClassSpec, TYPED_ARRAY_CLASP(Float64)) \ - real(Uint8ClampedArray, 33, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint8Clamped)) \ - real(Proxy, 34, InitProxyClass, js::ProxyClassPtr) \ - real(WeakMap, 35, InitWeakMapClass, OCLASP(WeakMap)) \ - real(Map, 36, InitMapClass, OCLASP(Map)) \ - real(Set, 37, InitSetClass, OCLASP(Set)) \ - real(DataView, 38, InitDataViewClass, OCLASP(DataView)) \ - real(Symbol, 39, InitSymbolClass, OCLASP(Symbol)) \ -IF_SAB(real,imaginary)(SharedArrayBuffer, 40, InitViaClassSpec, OCLASP(SharedArrayBuffer)) \ -IF_INTL(real,imaginary) (Intl, 41, InitIntlClass, CLASP(Intl)) \ -IF_BDATA(real,imaginary)(TypedObject, 42, InitTypedObjectModuleObject, OCLASP(TypedObjectModule)) \ - real(Reflect, 43, InitReflect, nullptr) \ -IF_SIMD(real,imaginary)(SIMD, 44, InitSimdClass, OCLASP(Simd)) \ - real(WeakSet, 45, InitWeakSetClass, OCLASP(WeakSet)) \ - real(TypedArray, 46, InitViaClassSpec, &js::TypedArrayObject::sharedTypedArrayPrototypeClass) \ -IF_SAB(real,imaginary)(Atomics, 47, InitAtomicsClass, OCLASP(Atomics)) \ - real(SavedFrame, 48, InitViaClassSpec, &js::SavedFrame::class_) \ - real(WebAssembly, 49, InitWebAssemblyClass, CLASP(WebAssembly)) \ - imaginary(WasmModule, 50, dummy, dummy) \ - imaginary(WasmInstance, 51, dummy, dummy) \ - imaginary(WasmMemory, 52, dummy, dummy) \ - imaginary(WasmTable, 53, dummy, dummy) \ -IF_PROMISE(real,imaginary)(Promise, 54, InitViaClassSpec, OCLASP(Promise)) \ - -#define JS_FOR_EACH_PROTOTYPE(macro) JS_FOR_PROTOTYPES(macro,macro) - -#endif /* jsprototypes_h */ diff --git a/mac/include/spidermonkey/jspubtd.h b/mac/include/spidermonkey/jspubtd.h deleted file mode 100644 index 309b9d74..00000000 --- a/mac/include/spidermonkey/jspubtd.h +++ /dev/null @@ -1,476 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jspubtd_h -#define jspubtd_h - -/* - * JS public API typedefs. - */ - -#include "mozilla/Assertions.h" -#include "mozilla/EnumeratedArray.h" -#include "mozilla/LinkedList.h" -#include "mozilla/PodOperations.h" - -#include "jsprototypes.h" -#include "jstypes.h" - -#include "js/TraceKind.h" -#include "js/TypeDecls.h" - -#if defined(JS_GC_ZEAL) || defined(DEBUG) -# define JSGC_HASH_TABLE_CHECKS -#endif - -namespace JS { - -class AutoIdVector; -class CallArgs; - -template -class Rooted; - -class JS_FRIEND_API(CompileOptions); -class JS_FRIEND_API(ReadOnlyCompileOptions); -class JS_FRIEND_API(OwningCompileOptions); -class JS_FRIEND_API(TransitiveCompileOptions); -class JS_PUBLIC_API(CompartmentOptions); - -struct RootingContext; -class Value; -struct Zone; - -namespace shadow { -struct Runtime; -} // namespace shadow - -} // namespace JS - -namespace js { -class RootLists; -} // namespace js - -/* - * Run-time version enumeration. For compile-time version checking, please use - * the JS_HAS_* macros in jsversion.h, or use MOZJS_MAJOR_VERSION, - * MOZJS_MINOR_VERSION, MOZJS_PATCH_VERSION, and MOZJS_ALPHA definitions. - */ -enum JSVersion { - JSVERSION_ECMA_3 = 148, - JSVERSION_1_6 = 160, - JSVERSION_1_7 = 170, - JSVERSION_1_8 = 180, - JSVERSION_ECMA_5 = 185, - JSVERSION_DEFAULT = 0, - JSVERSION_UNKNOWN = -1, - JSVERSION_LATEST = JSVERSION_ECMA_5 -}; - -/* Result of typeof operator enumeration. */ -enum JSType { - JSTYPE_VOID, /* undefined */ - JSTYPE_OBJECT, /* object */ - JSTYPE_FUNCTION, /* function */ - JSTYPE_STRING, /* string */ - JSTYPE_NUMBER, /* number */ - JSTYPE_BOOLEAN, /* boolean */ - JSTYPE_NULL, /* null */ - JSTYPE_SYMBOL, /* symbol */ - JSTYPE_LIMIT -}; - -/* Dense index into cached prototypes and class atoms for standard objects. */ -enum JSProtoKey { -#define PROTOKEY_AND_INITIALIZER(name,code,init,clasp) JSProto_##name = code, - JS_FOR_EACH_PROTOTYPE(PROTOKEY_AND_INITIALIZER) -#undef PROTOKEY_AND_INITIALIZER - JSProto_LIMIT -}; - -/* Struct forward declarations. */ -struct JSClass; -struct JSCompartment; -struct JSCrossCompartmentCall; -class JSErrorReport; -struct JSExceptionState; -struct JSFunctionSpec; -struct JSLocaleCallbacks; -struct JSObjectMap; -struct JSPrincipals; -struct JSPropertyName; -struct JSPropertySpec; -struct JSRuntime; -struct JSSecurityCallbacks; -struct JSStructuredCloneCallbacks; -struct JSStructuredCloneReader; -struct JSStructuredCloneWriter; -class JS_PUBLIC_API(JSTracer); - -class JSFlatString; - -typedef bool (*JSInitCallback)(void); - -template struct JSConstScalarSpec; -typedef JSConstScalarSpec JSConstDoubleSpec; -typedef JSConstScalarSpec JSConstIntegerSpec; - -/* - * Generic trace operation that calls JS::TraceEdge on each traceable thing's - * location reachable from data. - */ -typedef void -(* JSTraceDataOp)(JSTracer* trc, void* data); - -namespace js { -namespace gc { -class AutoTraceSession; -class StoreBuffer; -} // namespace gc - -// Whether the current thread is permitted access to any part of the specified -// runtime or zone. -JS_FRIEND_API(bool) -CurrentThreadCanAccessRuntime(const JSRuntime* rt); - -#ifdef DEBUG -JS_FRIEND_API(bool) -CurrentThreadIsPerformingGC(); -#endif - -} // namespace js - -namespace JS { - -class JS_PUBLIC_API(AutoEnterCycleCollection); -class JS_PUBLIC_API(AutoAssertOnBarrier); -struct JS_PUBLIC_API(PropertyDescriptor); - -typedef void (*OffThreadCompileCallback)(void* token, void* callbackData); - -enum class HeapState { - Idle, // doing nothing with the GC heap - Tracing, // tracing the GC heap without collecting, e.g. IterateCompartments() - MajorCollecting, // doing a GC of the major heap - MinorCollecting, // doing a GC of the minor heap (nursery) - CycleCollecting // in the "Unlink" phase of cycle collection -}; - -namespace shadow { - -struct Runtime -{ - private: - JS::HeapState heapState_; - - protected: - void setHeapState(JS::HeapState newState) { - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(asRuntime())); - MOZ_ASSERT(heapState_ != newState); - heapState_ = newState; - } - - JS::HeapState heapState() const { - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(asRuntime()) || - js::CurrentThreadIsPerformingGC()); - return heapState_; - } - - // In some cases, invoking GC barriers (incremental or otherwise) will break - // things. These barriers assert if this flag is set. - bool allowGCBarriers_; - friend class JS::AutoAssertOnBarrier; - - js::gc::StoreBuffer* gcStoreBufferPtr_; - - // The gray bits can become invalid if UnmarkGray overflows the stack. A - // full GC will reset this bit, since it fills in all the gray bits. - bool gcGrayBitsValid_; - - public: - Runtime() - : heapState_(JS::HeapState::Idle) - , allowGCBarriers_(true) - , gcStoreBufferPtr_(nullptr) - , gcGrayBitsValid_(false) - {} - - bool isHeapBusy() const { return heapState() != JS::HeapState::Idle; } - bool isHeapTracing() const { return heapState() == JS::HeapState::Tracing; } - bool isHeapMajorCollecting() const { return heapState() == JS::HeapState::MajorCollecting; } - bool isHeapMinorCollecting() const { return heapState() == JS::HeapState::MinorCollecting; } - bool isHeapCollecting() const { return isHeapMinorCollecting() || isHeapMajorCollecting(); } - bool isCycleCollecting() const { - return heapState() == JS::HeapState::CycleCollecting; - } - - bool allowGCBarriers() const { return allowGCBarriers_; } - - js::gc::StoreBuffer* gcStoreBufferPtr() { return gcStoreBufferPtr_; } - - bool areGCGrayBitsValid() const { return gcGrayBitsValid_; } - void setGCGrayBitsValid(bool valid) { gcGrayBitsValid_ = valid; } - - const JSRuntime* asRuntime() const { - return reinterpret_cast(this); - } - - static JS::shadow::Runtime* asShadowRuntime(JSRuntime* rt) { - return reinterpret_cast(rt); - } - - protected: - void setGCStoreBufferPtr(js::gc::StoreBuffer* storeBuffer) { - gcStoreBufferPtr_ = storeBuffer; - } -}; - -} /* namespace shadow */ - -// Decorates the Unlinking phase of CycleCollection so that accidental use -// of barriered accessors results in assertions instead of leaks. -class MOZ_STACK_CLASS JS_PUBLIC_API(AutoEnterCycleCollection) -{ -#ifdef DEBUG - JSRuntime* runtime; - - public: - explicit AutoEnterCycleCollection(JSContext* cx); - ~AutoEnterCycleCollection(); -#else - public: - explicit AutoEnterCycleCollection(JSContext* cx) {} - ~AutoEnterCycleCollection() {} -#endif -}; - -class JS_PUBLIC_API(AutoGCRooter) -{ - public: - AutoGCRooter(JSContext* cx, ptrdiff_t tag); - AutoGCRooter(JS::RootingContext* cx, ptrdiff_t tag); - - ~AutoGCRooter() { - MOZ_ASSERT(this == *stackTop); - *stackTop = down; - } - - /* Implemented in gc/RootMarking.cpp. */ - inline void trace(JSTracer* trc); - static void traceAll(JSTracer* trc); - static void traceAllWrappers(JSTracer* trc); - - protected: - AutoGCRooter * const down; - - /* - * Discriminates actual subclass of this being used. If non-negative, the - * subclass roots an array of values of the length stored in this field. - * If negative, meaning is indicated by the corresponding value in the enum - * below. Any other negative value indicates some deeper problem such as - * memory corruption. - */ - ptrdiff_t tag_; - - enum { - VALARRAY = -2, /* js::AutoValueArray */ - PARSER = -3, /* js::frontend::Parser */ - VALVECTOR = -10, /* js::AutoValueVector */ - IDVECTOR = -11, /* js::AutoIdVector */ - OBJVECTOR = -14, /* js::AutoObjectVector */ - IONMASM = -19, /* js::jit::MacroAssembler */ - WRAPVECTOR = -20, /* js::AutoWrapperVector */ - WRAPPER = -21, /* js::AutoWrapperRooter */ - CUSTOM = -26 /* js::CustomAutoRooter */ - }; - - static ptrdiff_t GetTag(const Value& value) { return VALVECTOR; } - static ptrdiff_t GetTag(const jsid& id) { return IDVECTOR; } - static ptrdiff_t GetTag(JSObject* obj) { return OBJVECTOR; } - - private: - AutoGCRooter ** const stackTop; - - /* No copy or assignment semantics. */ - AutoGCRooter(AutoGCRooter& ida) = delete; - void operator=(AutoGCRooter& ida) = delete; -}; - -// Our instantiations of Rooted and PersistentRooted require an -// instantiation of MapTypeToRootKind. -template <> -struct MapTypeToRootKind { - static const RootKind kind = RootKind::Traceable; -}; - -} /* namespace JS */ - -namespace js { - -class ExclusiveContext; - -/* - * This list enumerates the different types of conceptual stacks we have in - * SpiderMonkey. In reality, they all share the C stack, but we allow different - * stack limits depending on the type of code running. - */ -enum StackKind -{ - StackForSystemCode, // C++, such as the GC, running on behalf of the VM. - StackForTrustedScript, // Script running with trusted principals. - StackForUntrustedScript, // Script running with untrusted principals. - StackKindCount -}; - -using RootedListHeads = mozilla::EnumeratedArray*>; - -// Abstracts JS rooting mechanisms so they can be shared between the JSContext -// and JSRuntime. -class RootLists -{ - // Stack GC roots for Rooted GC heap pointers. - RootedListHeads stackRoots_; - template friend class JS::Rooted; - - // Stack GC roots for AutoFooRooter classes. - JS::AutoGCRooter* autoGCRooters_; - friend class JS::AutoGCRooter; - - // Heap GC roots for PersistentRooted pointers. - mozilla::EnumeratedArray>> heapRoots_; - template friend class JS::PersistentRooted; - - public: - RootLists() : autoGCRooters_(nullptr) { - for (auto& stackRootPtr : stackRoots_) - stackRootPtr = nullptr; - } - - ~RootLists() { - // The semantics of PersistentRooted containing pointers and tagged - // pointers are somewhat different from those of PersistentRooted - // containing a structure with a trace method. PersistentRooted - // containing pointers are allowed to outlive the owning RootLists, - // whereas those containing a traceable structure are not. - // - // The purpose of this feature is to support lazy initialization of - // global references for the several places in Gecko that do not have - // access to a tighter context, but that still need to refer to GC - // pointers. For such pointers, FinishPersistentRootedChains ensures - // that the contained references are nulled out when the owning - // RootLists dies to prevent UAF errors. - // - // However, for RootKind::Traceable, we do not know the concrete type - // of the held thing, so we simply cannot do this without accruing - // extra overhead and complexity for all users for a case that is - // unlikely to ever be used in practice. For this reason, the following - // assertion disallows usage of PersistentRooted that - // outlives the RootLists. - MOZ_ASSERT(heapRoots_[JS::RootKind::Traceable].isEmpty()); - } - - void traceStackRoots(JSTracer* trc); - void checkNoGCRooters(); - - void tracePersistentRoots(JSTracer* trc); - void finishPersistentRoots(); -}; - -} // namespace js - -namespace JS { - -/* - * JS::RootingContext is a base class of ContextFriendFields and JSContext. - * This class can be used to let code construct a Rooted<> or PersistentRooted<> - * instance, without giving it full access to the JSContext. - */ -struct RootingContext -{ - js::RootLists roots; - -#ifdef DEBUG - // Whether the derived class is a JSContext or an ExclusiveContext. - bool isJSContext; -#endif - - explicit RootingContext(bool isJSContextArg) -#ifdef DEBUG - : isJSContext(isJSContextArg) -#endif - {} - - static RootingContext* get(JSContext* cx) { - return reinterpret_cast(cx); - } -}; - -} // namespace JS - -namespace js { - -struct ContextFriendFields : public JS::RootingContext -{ - protected: - /* The current compartment. */ - JSCompartment* compartment_; - - /* The current zone. */ - JS::Zone* zone_; - - public: - /* Limit pointer for checking native stack consumption. */ - uintptr_t nativeStackLimit[js::StackKindCount]; - - explicit ContextFriendFields(bool isJSContext); - - static const ContextFriendFields* get(const JSContext* cx) { - return reinterpret_cast(cx); - } - - static ContextFriendFields* get(JSContext* cx) { - return reinterpret_cast(cx); - } - - friend JSCompartment* GetContextCompartment(const JSContext* cx); - friend JS::Zone* GetContextZone(const JSContext* cx); - template friend class JS::Rooted; -}; - -/* - * Inlinable accessors for JSContext. - * - * - These must not be available on the more restricted superclasses of - * JSContext, so we can't simply define them on ContextFriendFields. - * - * - They're perfectly ordinary JSContext functionality, so ought to be - * usable without resorting to jsfriendapi.h, and when JSContext is an - * incomplete type. - */ -inline JSCompartment* -GetContextCompartment(const JSContext* cx) -{ - return ContextFriendFields::get(cx)->compartment_; -} - -inline JS::Zone* -GetContextZone(const JSContext* cx) -{ - return ContextFriendFields::get(cx)->zone_; -} - -} /* namespace js */ - -MOZ_BEGIN_EXTERN_C - -// Defined in NSPR prio.h. -typedef struct PRFileDesc PRFileDesc; - -MOZ_END_EXTERN_C - -#endif /* jspubtd_h */ diff --git a/mac/include/spidermonkey/jstypes.h b/mac/include/spidermonkey/jstypes.h deleted file mode 100644 index 914674ab..00000000 --- a/mac/include/spidermonkey/jstypes.h +++ /dev/null @@ -1,219 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: jstypes.h -** Description: Definitions of NSPR's basic types -** -** Prototypes and macros used to make up for deficiencies in ANSI environments -** that we have found. -** -** Since we do not wrap and all the other standard headers, authors -** of portable code will not know in general that they need these definitions. -** Instead of requiring these authors to find the dependent uses in their code -** and take the following steps only in those C files, we take steps once here -** for all C files. -**/ - -#ifndef jstypes_h -#define jstypes_h - -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/Types.h" - -// jstypes.h is (or should be!) included by every file in SpiderMonkey. -// js-config.h and jsversion.h also should be included by every file. -// So include them here. -// XXX: including them in js/RequiredDefines.h should be a better option, since -// that is by definition the header file that should be included in all -// SpiderMonkey code. However, Gecko doesn't do this! See bug 909576. -#include "js-config.h" -#include "jsversion.h" - -/*********************************************************************** -** MACROS: JS_EXTERN_API -** JS_EXPORT_API -** DESCRIPTION: -** These are only for externally visible routines and globals. For -** internal routines, just use "extern" for type checking and that -** will not export internal cross-file or forward-declared symbols. -** Define a macro for declaring procedures return types. We use this to -** deal with windoze specific type hackery for DLL definitions. Use -** JS_EXTERN_API when the prototype for the method is declared. Use -** JS_EXPORT_API for the implementation of the method. -** -** Example: -** in dowhim.h -** JS_EXTERN_API( void ) DoWhatIMean( void ); -** in dowhim.c -** JS_EXPORT_API( void ) DoWhatIMean( void ) { return; } -** -** -***********************************************************************/ - -#define JS_EXTERN_API(type) extern MOZ_EXPORT type -#define JS_EXPORT_API(type) MOZ_EXPORT type -#define JS_EXPORT_DATA(type) MOZ_EXPORT type -#define JS_IMPORT_API(type) MOZ_IMPORT_API type -#define JS_IMPORT_DATA(type) MOZ_IMPORT_DATA type - -/* - * The linkage of JS API functions differs depending on whether the file is - * used within the JS library or not. Any source file within the JS - * interpreter should define EXPORT_JS_API whereas any client of the library - * should not. STATIC_JS_API is used to build JS as a static library. - */ -#if defined(STATIC_JS_API) -# define JS_PUBLIC_API(t) t -# define JS_PUBLIC_DATA(t) t -# define JS_FRIEND_API(t) t -# define JS_FRIEND_DATA(t) t -#elif defined(EXPORT_JS_API) || defined(STATIC_EXPORTABLE_JS_API) -# define JS_PUBLIC_API(t) MOZ_EXPORT t -# define JS_PUBLIC_DATA(t) MOZ_EXPORT t -# define JS_FRIEND_API(t) MOZ_EXPORT t -# define JS_FRIEND_DATA(t) MOZ_EXPORT t -#else -# define JS_PUBLIC_API(t) MOZ_IMPORT_API t -# define JS_PUBLIC_DATA(t) MOZ_IMPORT_DATA t -# define JS_FRIEND_API(t) MOZ_IMPORT_API t -# define JS_FRIEND_DATA(t) MOZ_IMPORT_DATA t -#endif - -#if defined(_MSC_VER) && defined(_M_IX86) -#define JS_FASTCALL __fastcall -#elif defined(__GNUC__) && defined(__i386__) -#define JS_FASTCALL __attribute__((fastcall)) -#else -#define JS_FASTCALL -#define JS_NO_FASTCALL -#endif - -/*********************************************************************** -** MACROS: JS_BEGIN_MACRO -** JS_END_MACRO -** DESCRIPTION: -** Macro body brackets so that macros with compound statement definitions -** behave syntactically more like functions when called. -***********************************************************************/ -#define JS_BEGIN_MACRO do { - -#if defined(_MSC_VER) -# define JS_END_MACRO \ - } __pragma(warning(push)) __pragma(warning(disable:4127)) \ - while (0) __pragma(warning(pop)) -#else -# define JS_END_MACRO } while (0) -#endif - -/*********************************************************************** -** MACROS: JS_BIT -** JS_BITMASK -** DESCRIPTION: -** Bit masking macros. XXX n must be <= 31 to be portable -***********************************************************************/ -#define JS_BIT(n) ((uint32_t)1 << (n)) -#define JS_BITMASK(n) (JS_BIT(n) - 1) - -/*********************************************************************** -** MACROS: JS_HOWMANY -** JS_ROUNDUP -** DESCRIPTION: -** Commonly used macros for operations on compatible types. -***********************************************************************/ -#define JS_HOWMANY(x,y) (((x)+(y)-1)/(y)) -#define JS_ROUNDUP(x,y) (JS_HOWMANY(x,y)*(y)) - -#include "jscpucfg.h" - -/* - * Define JS_64BIT iff we are building in an environment with 64-bit - * addresses. - */ -#ifdef _MSC_VER -# if defined(_M_X64) || defined(_M_AMD64) -# define JS_64BIT -# endif -#elif defined(__GNUC__) -/* Additional GCC defines are when running on Solaris, AIX, and HPUX */ -# if defined(__x86_64__) || defined(__sparcv9) || \ - defined(__64BIT__) || defined(__LP64__) -# define JS_64BIT -# endif -#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Sun Studio C/C++ */ -# if defined(__x86_64) || defined(__sparcv9) -# define JS_64BIT -# endif -#elif defined(__xlc__) || defined(__xlC__) /* IBM XL C/C++ */ -# if defined(__64BIT__) -# define JS_64BIT -# endif -#elif defined(__HP_cc) || defined(__HP_aCC) /* HP-UX cc/aCC */ -# if defined(__LP64__) -# define JS_64BIT -# endif -#else -# error "Implement me" -#endif - -/*********************************************************************** -** MACROS: JS_ARRAY_LENGTH -** JS_ARRAY_END -** DESCRIPTION: -** Macros to get the number of elements and the pointer to one past the -** last element of a C array. Use them like this: -** -** char16_t buf[10]; -** JSString* str; -** ... -** for (char16_t* s = buf; s != JS_ARRAY_END(buf); ++s) *s = ...; -** ... -** str = JS_NewStringCopyN(cx, buf, JS_ARRAY_LENGTH(buf)); -** ... -** -***********************************************************************/ - -#define JS_ARRAY_LENGTH(array) (sizeof (array) / sizeof (array)[0]) -#define JS_ARRAY_END(array) ((array) + JS_ARRAY_LENGTH(array)) - -#define JS_BITS_PER_BYTE 8 -#define JS_BITS_PER_BYTE_LOG2 3 - -#if defined(JS_64BIT) -# define JS_BITS_PER_WORD 64 -#else -# define JS_BITS_PER_WORD 32 -#endif - -/*********************************************************************** -** MACROS: JS_FUNC_TO_DATA_PTR -** JS_DATA_TO_FUNC_PTR -** DESCRIPTION: -** Macros to convert between function and data pointers of the same -** size. Use them like this: -** -** JSGetterOp nativeGetter; -** JSObject* scriptedGetter; -** ... -** scriptedGetter = JS_FUNC_TO_DATA_PTR(JSObject*, nativeGetter); -** ... -** nativeGetter = JS_DATA_TO_FUNC_PTR(JSGetterOp, scriptedGetter); -** -***********************************************************************/ - -#define JS_FUNC_TO_DATA_PTR(type, fun) (mozilla::BitwiseCast(fun)) -#define JS_DATA_TO_FUNC_PTR(type, ptr) (mozilla::BitwiseCast(ptr)) - -#ifdef __GNUC__ -# define JS_EXTENSION __extension__ -# define JS_EXTENSION_(s) __extension__ ({ s; }) -#else -# define JS_EXTENSION -# define JS_EXTENSION_(s) s -#endif - -#endif /* jstypes_h */ diff --git a/mac/include/spidermonkey/jsversion.h b/mac/include/spidermonkey/jsversion.h deleted file mode 100644 index 8bdfe47b..00000000 --- a/mac/include/spidermonkey/jsversion.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsversion_h -#define jsversion_h - -/* - * JS Capability Macros. - */ -#define JS_HAS_STR_HTML_HELPERS 1 /* (no longer used) */ -#define JS_HAS_OBJ_PROTO_PROP 1 /* has o.__proto__ etc. */ -#define JS_HAS_OBJ_WATCHPOINT 1 /* has o.watch and o.unwatch */ -#define JS_HAS_TOSOURCE 1 /* has Object/Array toSource method */ -#define JS_HAS_CATCH_GUARD 1 /* has exception handling catch guard */ -#define JS_HAS_UNEVAL 1 /* has uneval() top-level function */ -#define JS_HAS_CONST 1 /* (no longer used) */ -#define JS_HAS_FUN_EXPR_STMT 1 /* (no longer used) */ -#define JS_HAS_FOR_EACH_IN 1 /* has for each (lhs in iterable) */ -#define JS_HAS_GENERATORS 1 /* (no longer used) */ -#define JS_HAS_BLOCK_SCOPE 1 /* (no longer used) */ -#define JS_HAS_DESTRUCTURING 2 /* (no longer used) */ -#define JS_HAS_GENERATOR_EXPRS 1 /* (no longer used) */ -#define JS_HAS_EXPR_CLOSURES 1 /* has function (formals) listexpr */ - -/* (no longer used) */ -#define JS_HAS_NEW_GLOBAL_OBJECT 1 - -/* (no longer used) */ -#define JS_HAS_DESTRUCTURING_SHORTHAND (JS_HAS_DESTRUCTURING == 2) - -/* - * Feature for Object.prototype.__{define,lookup}{G,S}etter__ legacy support; - * support likely to be made opt-in at some future time. - */ -#define JS_OLD_GETTER_SETTER_METHODS 1 - -#endif /* jsversion_h */ diff --git a/mac/include/spidermonkey/jswrapper.h b/mac/include/spidermonkey/jswrapper.h deleted file mode 100644 index 9b14c59e..00000000 --- a/mac/include/spidermonkey/jswrapper.h +++ /dev/null @@ -1,382 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jswrapper_h -#define jswrapper_h - -#include "mozilla/Attributes.h" - -#include "js/Proxy.h" - -namespace js { - -/* - * Helper for Wrapper::New default options. - * - * Callers of Wrapper::New() who wish to specify a prototype for the created - * Wrapper, *MUST* construct a WrapperOptions with a JSContext. - */ -class MOZ_STACK_CLASS WrapperOptions : public ProxyOptions { - public: - WrapperOptions() : ProxyOptions(false), - proto_() - {} - - explicit WrapperOptions(JSContext* cx) : ProxyOptions(false), - proto_() - { - proto_.emplace(cx); - } - - inline JSObject* proto() const; - WrapperOptions& setProto(JSObject* protoArg) { - MOZ_ASSERT(proto_); - *proto_ = protoArg; - return *this; - } - - private: - mozilla::Maybe proto_; -}; - -/* - * A wrapper is a proxy with a target object to which it generally forwards - * operations, but may restrict access to certain operations or augment those - * operations in various ways. - * - * A wrapper can be "unwrapped" in C++, exposing the underlying object. - * Callers should be careful to avoid unwrapping security wrappers in the wrong - * context. - * - * Important: If you add a method implementation here, you probably also need - * to add an override in CrossCompartmentWrapper. If you don't, you risk - * compartment mismatches. See bug 945826 comment 0. - */ -class JS_FRIEND_API(Wrapper) : public BaseProxyHandler -{ - unsigned mFlags; - - public: - explicit constexpr Wrapper(unsigned aFlags, bool aHasPrototype = false, - bool aHasSecurityPolicy = false) - : BaseProxyHandler(&family, aHasPrototype, aHasSecurityPolicy), - mFlags(aFlags) - { } - - virtual bool finalizeInBackground(const Value& priv) const override; - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const override; - virtual bool defineProperty(JSContext* cx, HandleObject proxy, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const override; - virtual bool delete_(JSContext* cx, HandleObject proxy, HandleId id, - ObjectOpResult& result) const override; - virtual bool enumerate(JSContext* cx, HandleObject proxy, - MutableHandleObject objp) const override; - virtual bool getPrototype(JSContext* cx, HandleObject proxy, - MutableHandleObject protop) const override; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const override; - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, - MutableHandleObject protop) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, - bool* succeeded) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject proxy, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject proxy, bool* extensible) const override; - virtual bool has(JSContext* cx, HandleObject proxy, HandleId id, - bool* bp) const override; - virtual bool get(JSContext* cx, HandleObject proxy, HandleValue receiver, - HandleId id, MutableHandleValue vp) const override; - virtual bool set(JSContext* cx, HandleObject proxy, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const override; - virtual bool call(JSContext* cx, HandleObject proxy, const CallArgs& args) const override; - virtual bool construct(JSContext* cx, HandleObject proxy, const CallArgs& args) const override; - - /* SpiderMonkey extensions. */ - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const override; - virtual bool hasOwn(JSContext* cx, HandleObject proxy, HandleId id, - bool* bp) const override; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const override; - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const override; - virtual bool hasInstance(JSContext* cx, HandleObject proxy, MutableHandleValue v, - bool* bp) const override; - virtual bool getBuiltinClass(JSContext* cx, HandleObject proxy, ESClass* cls) const override; - virtual bool isArray(JSContext* cx, HandleObject proxy, - JS::IsArrayAnswer* answer) const override; - virtual const char* className(JSContext* cx, HandleObject proxy) const override; - virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, - unsigned indent) const override; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, - RegExpGuard* g) const override; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, - MutableHandleValue vp) const override; - virtual bool isCallable(JSObject* obj) const override; - virtual bool isConstructor(JSObject* obj) const override; - virtual JSObject* weakmapKeyDelegate(JSObject* proxy) const override; - - public: - using BaseProxyHandler::Action; - - enum Flags { - CROSS_COMPARTMENT = 1 << 0, - LAST_USED_FLAG = CROSS_COMPARTMENT - }; - - static JSObject* New(JSContext* cx, JSObject* obj, const Wrapper* handler, - const WrapperOptions& options = WrapperOptions()); - - static JSObject* Renew(JSContext* cx, JSObject* existing, JSObject* obj, const Wrapper* handler); - - static const Wrapper* wrapperHandler(JSObject* wrapper); - - static JSObject* wrappedObject(JSObject* wrapper); - - unsigned flags() const { - return mFlags; - } - - static const char family; - static const Wrapper singleton; - static const Wrapper singletonWithPrototype; - - static JSObject* defaultProto; -}; - -inline JSObject* -WrapperOptions::proto() const -{ - return proto_ ? *proto_ : Wrapper::defaultProto; -} - -/* Base class for all cross compartment wrapper handlers. */ -class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper -{ - public: - explicit constexpr CrossCompartmentWrapper(unsigned aFlags, bool aHasPrototype = false, - bool aHasSecurityPolicy = false) - : Wrapper(CROSS_COMPARTMENT | aFlags, aHasPrototype, aHasSecurityPolicy) - { } - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool delete_(JSContext* cx, HandleObject wrapper, HandleId id, - ObjectOpResult& result) const override; - virtual bool enumerate(JSContext* cx, HandleObject wrapper, MutableHandleObject objp) const override; - virtual bool getPrototype(JSContext* cx, HandleObject proxy, - MutableHandleObject protop) const override; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const override; - - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, - MutableHandleObject protop) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, - bool* succeeded) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; - virtual bool has(JSContext* cx, HandleObject wrapper, HandleId id, bool* bp) const override; - virtual bool get(JSContext* cx, HandleObject wrapper, HandleValue receiver, - HandleId id, MutableHandleValue vp) const override; - virtual bool set(JSContext* cx, HandleObject wrapper, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const override; - virtual bool call(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - virtual bool construct(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - - /* SpiderMonkey extensions. */ - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool hasOwn(JSContext* cx, HandleObject wrapper, HandleId id, bool* bp) const override; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const override; - virtual bool hasInstance(JSContext* cx, HandleObject wrapper, MutableHandleValue v, - bool* bp) const override; - virtual const char* className(JSContext* cx, HandleObject proxy) const override; - virtual JSString* fun_toString(JSContext* cx, HandleObject wrapper, - unsigned indent) const override; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const override; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const override; - - // Allocate CrossCompartmentWrappers in the nursery. - virtual bool canNurseryAllocate() const override { return true; } - - static const CrossCompartmentWrapper singleton; - static const CrossCompartmentWrapper singletonWithPrototype; -}; - -class JS_FRIEND_API(OpaqueCrossCompartmentWrapper) : public CrossCompartmentWrapper -{ - public: - explicit constexpr OpaqueCrossCompartmentWrapper() : CrossCompartmentWrapper(0) - { } - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool delete_(JSContext* cx, HandleObject wrapper, HandleId id, - ObjectOpResult& result) const override; - virtual bool enumerate(JSContext* cx, HandleObject wrapper, - MutableHandleObject objp) const override; - virtual bool getPrototype(JSContext* cx, HandleObject wrapper, - MutableHandleObject protop) const override; - virtual bool setPrototype(JSContext* cx, HandleObject wrapper, HandleObject proto, - ObjectOpResult& result) const override; - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject wrapper, bool* isOrdinary, - MutableHandleObject protop) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject wrapper, - bool* succeeded) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; - virtual bool has(JSContext* cx, HandleObject wrapper, HandleId id, - bool* bp) const override; - virtual bool get(JSContext* cx, HandleObject wrapper, HandleValue receiver, - HandleId id, MutableHandleValue vp) const override; - virtual bool set(JSContext* cx, HandleObject wrapper, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const override; - virtual bool call(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - virtual bool construct(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - - /* SpiderMonkey extensions. */ - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool hasOwn(JSContext* cx, HandleObject wrapper, HandleId id, - bool* bp) const override; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool getBuiltinClass(JSContext* cx, HandleObject wrapper, ESClass* cls) const override; - virtual bool isArray(JSContext* cx, HandleObject obj, - JS::IsArrayAnswer* answer) const override; - virtual const char* className(JSContext* cx, HandleObject wrapper) const override; - virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, unsigned indent) const override; - - static const OpaqueCrossCompartmentWrapper singleton; -}; - -/* - * Base class for security wrappers. A security wrapper is potentially hiding - * all or part of some wrapped object thus SecurityWrapper defaults to denying - * access to the wrappee. This is the opposite of Wrapper which tries to be - * completely transparent. - * - * NB: Currently, only a few ProxyHandler operations are overridden to deny - * access, relying on derived SecurityWrapper to block access when necessary. - */ -template -class JS_FRIEND_API(SecurityWrapper) : public Base -{ - public: - explicit constexpr SecurityWrapper(unsigned flags, bool hasPrototype = false) - : Base(flags, hasPrototype, /* hasSecurityPolicy = */ true) - { } - - virtual bool enter(JSContext* cx, HandleObject wrapper, HandleId id, Wrapper::Action act, - bool* bp) const override; - - virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, - ObjectOpResult& result) const override; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, bool* succeeded) const override; - - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const override; - virtual bool getBuiltinClass(JSContext* cx, HandleObject wrapper, ESClass* cls) const override; - virtual bool isArray(JSContext* cx, HandleObject wrapper, JS::IsArrayAnswer* answer) const override; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const override; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const override; - - // Allow isCallable and isConstructor. They used to be class-level, and so could not be guarded - // against. - - virtual bool watch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, - JS::HandleObject callable) const override; - virtual bool unwatch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id) const override; - - /* - * Allow our subclasses to select the superclass behavior they want without - * needing to specify an exact superclass. - */ - typedef Base Permissive; - typedef SecurityWrapper Restrictive; -}; - -typedef SecurityWrapper CrossCompartmentSecurityWrapper; - -extern JSObject* -TransparentObjectWrapper(JSContext* cx, HandleObject existing, HandleObject obj); - -inline bool -IsWrapper(JSObject* obj) -{ - return IsProxy(obj) && GetProxyHandler(obj)->family() == &Wrapper::family; -} - -// Given a JSObject, returns that object stripped of wrappers. If -// stopAtWindowProxy is true, then this returns the WindowProxy if it was -// previously wrapped. Otherwise, this returns the first object for -// which JSObject::isWrapper returns false. -JS_FRIEND_API(JSObject*) -UncheckedUnwrap(JSObject* obj, bool stopAtWindowProxy = true, unsigned* flagsp = nullptr); - -// Given a JSObject, returns that object stripped of wrappers. At each stage, -// the security wrapper has the opportunity to veto the unwrap. If -// stopAtWindowProxy is true, then this returns the WindowProxy if it was -// previously wrapped. -JS_FRIEND_API(JSObject*) -CheckedUnwrap(JSObject* obj, bool stopAtWindowProxy = true); - -// Unwrap only the outermost security wrapper, with the same semantics as -// above. This is the checked version of Wrapper::wrappedObject. -JS_FRIEND_API(JSObject*) -UnwrapOneChecked(JSObject* obj, bool stopAtWindowProxy = true); - -JS_FRIEND_API(bool) -IsCrossCompartmentWrapper(JSObject* obj); - -void -NukeCrossCompartmentWrapper(JSContext* cx, JSObject* wrapper); - -void -RemapWrapper(JSContext* cx, JSObject* wobj, JSObject* newTarget); - -JS_FRIEND_API(bool) -RemapAllWrappersForObject(JSContext* cx, JSObject* oldTarget, - JSObject* newTarget); - -// API to recompute all cross-compartment wrappers whose source and target -// match the given filters. -JS_FRIEND_API(bool) -RecomputeWrappers(JSContext* cx, const CompartmentFilter& sourceFilter, - const CompartmentFilter& targetFilter); - -} /* namespace js */ - -#endif /* jswrapper_h */ diff --git a/mac/include/spidermonkey/mozilla/Alignment.h b/mac/include/spidermonkey/mozilla/Alignment.h deleted file mode 100644 index 4fcda4f3..00000000 --- a/mac/include/spidermonkey/mozilla/Alignment.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Functionality related to memory alignment. */ - -#ifndef mozilla_Alignment_h -#define mozilla_Alignment_h - -#include "mozilla/Attributes.h" -#include -#include - -namespace mozilla { - -/* - * This class, and the corresponding macro MOZ_ALIGNOF, figures out how many - * bytes of alignment a given type needs. - */ -template -class AlignmentFinder -{ - struct Aligner - { - char mChar; - T mT; - }; - -public: - static const size_t alignment = sizeof(Aligner) - sizeof(T); -}; - -#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment - -/* - * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. - * - * For instance, - * - * MOZ_ALIGNED_DECL(char arr[2], 8); - * - * will declare a two-character array |arr| aligned to 8 bytes. - */ - -#if defined(__GNUC__) -# define MOZ_ALIGNED_DECL(_type, _align) \ - _type __attribute__((aligned(_align))) -#elif defined(_MSC_VER) -# define MOZ_ALIGNED_DECL(_type, _align) \ - __declspec(align(_align)) _type -#else -# warning "We don't know how to align variables on this compiler." -# define MOZ_ALIGNED_DECL(_type, _align) _type -#endif - -/* - * AlignedElem is a structure whose alignment is guaranteed to be at least N - * bytes. - * - * We support 1, 2, 4, 8, and 16-bit alignment. - */ -template -struct AlignedElem; - -/* - * We have to specialize this template because GCC doesn't like - * __attribute__((aligned(foo))) where foo is a template parameter. - */ - -template<> -struct AlignedElem<1> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 1); -}; - -template<> -struct AlignedElem<2> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 2); -}; - -template<> -struct AlignedElem<4> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 4); -}; - -template<> -struct AlignedElem<8> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 8); -}; - -template<> -struct AlignedElem<16> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 16); -}; - -/* - * This utility pales in comparison to Boost's aligned_storage. The utility - * simply assumes that uint64_t is enough alignment for anyone. This may need - * to be extended one day... - * - * As an important side effect, pulling the storage into this template is - * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving - * false negatives when we cast from the char buffer to whatever type we've - * constructed using the bytes. - */ -template -struct AlignedStorage -{ - union U - { - char mBytes[Nbytes]; - uint64_t mDummy; - } u; - - const void* addr() const { return u.mBytes; } - void* addr() { return u.mBytes; } - - AlignedStorage() = default; - - // AlignedStorage is non-copyable: the default copy constructor violates - // strict aliasing rules, per bug 1269319. - AlignedStorage(const AlignedStorage&) = delete; - void operator=(const AlignedStorage&) = delete; -}; - -template -struct MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS AlignedStorage2 -{ - union U - { - char mBytes[sizeof(T)]; - uint64_t mDummy; - } u; - - const T* addr() const { return reinterpret_cast(u.mBytes); } - T* addr() { return static_cast(static_cast(u.mBytes)); } - - AlignedStorage2() = default; - - // AlignedStorage2 is non-copyable: the default copy constructor violates - // strict aliasing rules, per bug 1269319. - AlignedStorage2(const AlignedStorage2&) = delete; - void operator=(const AlignedStorage2&) = delete; -}; - -} /* namespace mozilla */ - -#endif /* mozilla_Alignment_h */ diff --git a/mac/include/spidermonkey/mozilla/AllocPolicy.h b/mac/include/spidermonkey/mozilla/AllocPolicy.h deleted file mode 100644 index 81f62b03..00000000 --- a/mac/include/spidermonkey/mozilla/AllocPolicy.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * An allocation policy concept, usable for structures and algorithms to - * control how memory is allocated and how failures are handled. - */ - -#ifndef mozilla_AllocPolicy_h -#define mozilla_AllocPolicy_h - -#include "mozilla/Attributes.h" -#include "mozilla/TemplateLib.h" - -#include -#include - -namespace mozilla { - -/* - * Allocation policies are used to implement the standard allocation behaviors - * in a customizable way. Additionally, custom behaviors may be added to these - * behaviors, such as additionally reporting an error through an out-of-band - * mechanism when OOM occurs. The concept modeled here is as follows: - * - * - public copy constructor, assignment, destructor - * - template T* maybe_pod_malloc(size_t) - * Fallible, but doesn't report an error on OOM. - * - template T* maybe_pod_calloc(size_t) - * Fallible, but doesn't report an error on OOM. - * - template T* maybe_pod_realloc(T*, size_t, size_t) - * Fallible, but doesn't report an error on OOM. The old allocation - * size is passed in, in addition to the new allocation size requested. - * - template T* pod_malloc(size_t) - * Responsible for OOM reporting when null is returned. - * - template T* pod_calloc(size_t) - * Responsible for OOM reporting when null is returned. - * - template T* pod_realloc(T*, size_t, size_t) - * Responsible for OOM reporting when null is returned. The old allocation - * size is passed in, in addition to the new allocation size requested. - * - void free_(void*) - * - void reportAllocOverflow() const - * Called on allocation overflow (that is, an allocation implicitly tried - * to allocate more than the available memory space -- think allocating an - * array of large-size objects, where N * size overflows) before null is - * returned. - * - bool checkSimulatedOOM() const - * Some clients generally allocate memory yet in some circumstances won't - * need to do so. For example, appending to a vector with a small amount of - * inline storage generally allocates memory, but no allocation occurs - * unless appending exceeds inline storage. But for testing purposes, it - * can be useful to treat *every* operation as allocating. - * Clients (such as this hypothetical append method implementation) should - * call this method in situations that don't allocate, but could generally, - * to support this. The default behavior should return true; more - * complicated behavior might be to return false only after a certain - * number of allocations-or-check-simulated-OOMs (coordinating with the - * other AllocPolicy methods) have occurred. - * - * mfbt provides (and typically uses by default) only MallocAllocPolicy, which - * does nothing more than delegate to the malloc/alloc/free functions. - */ - -/* - * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no - * extra behaviors. - */ -class MallocAllocPolicy -{ -public: - template - T* maybe_pod_malloc(size_t aNumElems) - { - if (aNumElems & mozilla::tl::MulOverflowMask::value) { - return nullptr; - } - return static_cast(malloc(aNumElems * sizeof(T))); - } - - template - T* maybe_pod_calloc(size_t aNumElems) - { - return static_cast(calloc(aNumElems, sizeof(T))); - } - - template - T* maybe_pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - if (aNewSize & mozilla::tl::MulOverflowMask::value) { - return nullptr; - } - return static_cast(realloc(aPtr, aNewSize * sizeof(T))); - } - - template - T* pod_malloc(size_t aNumElems) - { - return maybe_pod_malloc(aNumElems); - } - - template - T* pod_calloc(size_t aNumElems) - { - return maybe_pod_calloc(aNumElems); - } - - template - T* pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - return maybe_pod_realloc(aPtr, aOldSize, aNewSize); - } - - void free_(void* aPtr) - { - free(aPtr); - } - - void reportAllocOverflow() const - { - } - - MOZ_MUST_USE bool checkSimulatedOOM() const - { - return true; - } -}; - -} // namespace mozilla - -#endif /* mozilla_AllocPolicy_h */ diff --git a/mac/include/spidermonkey/mozilla/AlreadyAddRefed.h b/mac/include/spidermonkey/mozilla/AlreadyAddRefed.h deleted file mode 100644 index 0d7b0cae..00000000 --- a/mac/include/spidermonkey/mozilla/AlreadyAddRefed.h +++ /dev/null @@ -1,147 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Typed temporary pointers for reference-counted smart pointers. */ - -#ifndef AlreadyAddRefed_h -#define AlreadyAddRefed_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" - -namespace mozilla { - -struct unused_t; - -} // namespace mozilla - -/** - * already_AddRefed cooperates with reference counting smart pointers to enable - * you to assign in a pointer _without_ |AddRef|ing it. You might want to use - * this as a return type from a function that returns an already |AddRef|ed - * pointer. - * - * TODO Move already_AddRefed to namespace mozilla. This has not yet been done - * because of the sheer number of usages of already_AddRefed. - */ -template -struct MOZ_MUST_USE_TYPE MOZ_NON_AUTOABLE already_AddRefed -{ - /* - * We want to allow returning nullptr from functions returning - * already_AddRefed, for simplicity. But we also don't want to allow - * returning raw T*, instead preferring creation of already_AddRefed from - * a reference counting smart pointer. - * - * We address the latter requirement by making the (T*) constructor explicit. - * But |return nullptr| won't consider an explicit constructor, so we need - * another constructor to handle it. Plain old (decltype(nullptr)) doesn't - * cut it, because if nullptr is emulated as __null (with type int or long), - * passing nullptr to an int/long parameter triggers compiler warnings. We - * need a type that no one can pass accidentally; a pointer-to-member-function - * (where no such function exists) does the trick nicely. - * - * That handles the return-value case. What about for locals, argument types, - * and so on? |already_AddRefed(nullptr)| considers both overloads (and - * the (already_AddRefed&&) overload as well!), so there's an ambiguity. - * We can target true nullptr using decltype(nullptr), but we can't target - * emulated nullptr the same way, because passing __null to an int/long - * parameter triggers compiler warnings. So just give up on this, and provide - * this behavior through the default constructor. - * - * We can revert to simply explicit (T*) and implicit (decltype(nullptr)) when - * nullptr no longer needs to be emulated to support the ancient b2g compiler. - * (The () overload could also be removed, if desired, if we changed callers.) - */ - already_AddRefed() : mRawPtr(nullptr) {} - - // The return and argument types here are arbitrarily selected so no - // corresponding member function exists. - typedef void (already_AddRefed::* MatchNullptr)(double, float); - MOZ_IMPLICIT already_AddRefed(MatchNullptr aRawPtr) : mRawPtr(nullptr) {} - - explicit already_AddRefed(T* aRawPtr) : mRawPtr(aRawPtr) {} - - // Disallow copy constructor and copy assignment operator: move semantics used instead. - already_AddRefed(const already_AddRefed& aOther) = delete; - already_AddRefed& operator=(const already_AddRefed& aOther) = delete; - - already_AddRefed(already_AddRefed&& aOther) : mRawPtr(aOther.take()) {} - - already_AddRefed& operator=(already_AddRefed&& aOther) - { - mRawPtr = aOther.take(); - return *this; - } - - /** - * This helper is useful in cases like - * - * already_AddRefed - * Foo() - * { - * RefPtr x = ...; - * return x.forget(); - * } - * - * The autoconversion allows one to omit the idiom - * - * RefPtr y = x.forget(); - * return y.forget(); - * - * Note that nsRefPtr is the XPCOM reference counting smart pointer class. - */ - template - MOZ_IMPLICIT already_AddRefed(already_AddRefed&& aOther) : mRawPtr(aOther.take()) {} - - ~already_AddRefed() { MOZ_ASSERT(!mRawPtr); } - - // Specialize the unused operator<< for already_AddRefed, to allow - // nsCOMPtr foo; - // Unused << foo.forget(); - // Note that nsCOMPtr is the XPCOM reference counting smart pointer class. - friend void operator<<(const mozilla::unused_t& aUnused, - const already_AddRefed& aRhs) - { - auto mutableAlreadyAddRefed = const_cast*>(&aRhs); - aUnused << mutableAlreadyAddRefed->take(); - } - - MOZ_MUST_USE T* take() - { - T* rawPtr = mRawPtr; - mRawPtr = nullptr; - return rawPtr; - } - - /** - * This helper provides a static_cast replacement for already_AddRefed, so - * if you have - * - * already_AddRefed F(); - * - * you can write - * - * already_AddRefed - * G() - * { - * return F().downcast(); - * } - */ - template - already_AddRefed downcast() - { - U* tmp = static_cast(mRawPtr); - mRawPtr = nullptr; - return already_AddRefed(tmp); - } - -private: - T* MOZ_OWNING_REF mRawPtr; -}; - -#endif // AlreadyAddRefed_h diff --git a/mac/include/spidermonkey/mozilla/Array.h b/mac/include/spidermonkey/mozilla/Array.h deleted file mode 100644 index 72b89ede..00000000 --- a/mac/include/spidermonkey/mozilla/Array.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A compile-time constant-length array with bounds-checking assertions. */ - -#ifndef mozilla_Array_h -#define mozilla_Array_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/ReverseIterator.h" - -#include - -namespace mozilla { - -template -class Array -{ - T mArr[Length]; - -public: - Array() {} - - template - MOZ_IMPLICIT Array(Args&&... aArgs) - : mArr{mozilla::Forward(aArgs)...} - { - static_assert(sizeof...(aArgs) == Length, - "The number of arguments should be equal to the template parameter Length"); - } - - T& operator[](size_t aIndex) - { - MOZ_ASSERT(aIndex < Length); - return mArr[aIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(aIndex < Length); - return mArr[aIndex]; - } - - typedef T* iterator; - typedef const T* const_iterator; - typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; - - // Methods for range-based for loops. - iterator begin() { return mArr; } - const_iterator begin() const { return mArr; } - const_iterator cbegin() const { return begin(); } - iterator end() { return mArr + Length; } - const_iterator end() const { return mArr + Length; } - const_iterator cend() const { return end(); } - - // Methods for reverse iterating. - reverse_iterator rbegin() { return reverse_iterator(end()); } - const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() { return reverse_iterator(begin()); } - const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } - const_reverse_iterator crend() const { return rend(); } -}; - -template -class Array -{ -public: - T& operator[](size_t aIndex) - { - MOZ_CRASH("indexing into zero-length array"); - } - - const T& operator[](size_t aIndex) const - { - MOZ_CRASH("indexing into zero-length array"); - } -}; - -} /* namespace mozilla */ - -#endif /* mozilla_Array_h */ diff --git a/mac/include/spidermonkey/mozilla/ArrayUtils.h b/mac/include/spidermonkey/mozilla/ArrayUtils.h deleted file mode 100644 index 50236ccb..00000000 --- a/mac/include/spidermonkey/mozilla/ArrayUtils.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements various helper functions related to arrays. - */ - -#ifndef mozilla_ArrayUtils_h -#define mozilla_ArrayUtils_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#include - -#ifdef __cplusplus - -#include "mozilla/Alignment.h" -#include "mozilla/Array.h" -#include "mozilla/EnumeratedArray.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/* - * Safely subtract two pointers when it is known that aEnd >= aBegin, yielding a - * size_t result. - * - * Ordinary pointer subtraction yields a ptrdiff_t result, which, being signed, - * has insufficient range to express the distance between pointers at opposite - * ends of the address space. Furthermore, most compilers use ptrdiff_t to - * represent the intermediate byte address distance, before dividing by - * sizeof(T); if that intermediate result overflows, they'll produce results - * with the wrong sign even when the correct scaled distance would fit in a - * ptrdiff_t. - */ -template -MOZ_ALWAYS_INLINE size_t -PointerRangeSize(T* aBegin, T* aEnd) -{ - MOZ_ASSERT(aEnd >= aBegin); - return (size_t(aEnd) - size_t(aBegin)) / sizeof(T); -} - -/* - * Compute the length of an array with constant length. (Use of this method - * with a non-array pointer will not compile.) - * - * Beware of the implicit trailing '\0' when using this with string constants. - */ -template -constexpr size_t -ArrayLength(T (&aArr)[N]) -{ - return N; -} - -template -constexpr size_t -ArrayLength(const Array& aArr) -{ - return N; -} - -template -constexpr size_t -ArrayLength(const EnumeratedArray& aArr) -{ - return size_t(N); -} - -/* - * Compute the address one past the last element of a constant-length array. - * - * Beware of the implicit trailing '\0' when using this with string constants. - */ -template -constexpr T* -ArrayEnd(T (&aArr)[N]) -{ - return aArr + ArrayLength(aArr); -} - -template -constexpr T* -ArrayEnd(Array& aArr) -{ - return &aArr[0] + ArrayLength(aArr); -} - -template -constexpr const T* -ArrayEnd(const Array& aArr) -{ - return &aArr[0] + ArrayLength(aArr); -} - -namespace detail { - -template::value>> -struct AlignedChecker -{ - static void - test(const Pointee* aPtr) - { - MOZ_ASSERT((uintptr_t(aPtr) % MOZ_ALIGNOF(AlignType)) == 0, - "performing a range-check with a misaligned pointer"); - } -}; - -template -struct AlignedChecker -{ - static void - test(const Pointee* aPtr) - { - } -}; - -} // namespace detail - -/** - * Determines whether |aPtr| points at an object in the range [aBegin, aEnd). - * - * |aPtr| must have the same alignment as |aBegin| and |aEnd|. This usually - * should be achieved by ensuring |aPtr| points at a |U|, not just that it - * points at a |T|. - * - * It is a usage error for any argument to be misaligned. - * - * It's okay for T* to be void*, and if so U* may also be void*. In the latter - * case no argument is required to be aligned (obviously, as void* implies no - * particular alignment). - */ -template -inline typename EnableIf::value || - IsBaseOf::value || - IsVoid::value, - bool>::Type -IsInRange(const T* aPtr, const U* aBegin, const U* aEnd) -{ - MOZ_ASSERT(aBegin <= aEnd); - detail::AlignedChecker::test(aPtr); - detail::AlignedChecker::test(aBegin); - detail::AlignedChecker::test(aEnd); - return aBegin <= reinterpret_cast(aPtr) && - reinterpret_cast(aPtr) < aEnd; -} - -/** - * Convenience version of the above method when the valid range is specified as - * uintptr_t values. As above, |aPtr| must be aligned, and |aBegin| and |aEnd| - * must be aligned with respect to |T|. - */ -template -inline bool -IsInRange(const T* aPtr, uintptr_t aBegin, uintptr_t aEnd) -{ - return IsInRange(aPtr, - reinterpret_cast(aBegin), - reinterpret_cast(aEnd)); -} - -namespace detail { - -/* - * Helper for the MOZ_ARRAY_LENGTH() macro to make the length a typesafe - * compile-time constant even on compilers lacking constexpr support. - */ -template -char (&ArrayLengthHelper(T (&array)[N]))[N]; - -} /* namespace detail */ - -} /* namespace mozilla */ - -#endif /* __cplusplus */ - -/* - * MOZ_ARRAY_LENGTH() is an alternative to mozilla::ArrayLength() for C files - * that can't use C++ template functions and for static_assert() calls that - * can't call ArrayLength() when it is not a C++11 constexpr function. - */ -#ifdef __cplusplus -# define MOZ_ARRAY_LENGTH(array) sizeof(mozilla::detail::ArrayLengthHelper(array)) -#else -# define MOZ_ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0])) -#endif - -#endif /* mozilla_ArrayUtils_h */ diff --git a/mac/include/spidermonkey/mozilla/Assertions.h b/mac/include/spidermonkey/mozilla/Assertions.h deleted file mode 100644 index e978af3d..00000000 --- a/mac/include/spidermonkey/mozilla/Assertions.h +++ /dev/null @@ -1,585 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implementations of runtime and static assertion macros for C and C++. */ - -#ifndef mozilla_Assertions_h -#define mozilla_Assertions_h - -#if defined(MOZILLA_INTERNAL_API) && defined(__cplusplus) -#define MOZ_DUMP_ASSERTION_STACK -#endif - -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/Likely.h" -#include "mozilla/MacroArgs.h" -#include "mozilla/StaticAnalysisFunctions.h" -#include "mozilla/Types.h" -#ifdef MOZ_DUMP_ASSERTION_STACK -#include "nsTraceRefcnt.h" -#endif - -#if defined(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API) -/* - * The crash reason set by MOZ_CRASH_ANNOTATE is consumed by the crash reporter - * if present. It is declared here (and defined in Assertions.cpp) to make it - * available to all code, even libraries that don't link with the crash reporter - * directly. - */ -MOZ_BEGIN_EXTERN_C -extern MFBT_DATA const char* gMozCrashReason; -MOZ_END_EXTERN_C - -static inline void -AnnotateMozCrashReason(const char* reason) -{ - gMozCrashReason = reason; -} -# define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__) -#else -# define MOZ_CRASH_ANNOTATE(...) do { /* nothing */ } while (0) -#endif - -#include -#include -#include -#ifdef WIN32 - /* - * TerminateProcess and GetCurrentProcess are defined in , which - * further depends on . We hardcode these few definitions manually - * because those headers clutter the global namespace with a significant - * number of undesired macros and symbols. - */ -# ifdef __cplusplus -extern "C" { -# endif -__declspec(dllimport) int __stdcall -TerminateProcess(void* hProcess, unsigned int uExitCode); -__declspec(dllimport) void* __stdcall GetCurrentProcess(void); -# ifdef __cplusplus -} -# endif -#else -# include -#endif -#ifdef ANDROID -# include -#endif - -/* - * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C. - * In C++11, static_assert is provided by the compiler to the same effect. - * This can be useful when you make certain assumptions about what must hold for - * optimal, or even correct, behavior. For example, you might assert that the - * size of a struct is a multiple of the target architecture's word size: - * - * struct S { ... }; - * // C - * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0, - * "S should be a multiple of word size for efficiency"); - * // C++11 - * static_assert(sizeof(S) % sizeof(size_t) == 0, - * "S should be a multiple of word size for efficiency"); - * - * This macro can be used in any location where both an extern declaration and a - * typedef could be used. - */ -#ifndef __cplusplus - /* - * Some of the definitions below create an otherwise-unused typedef. This - * triggers compiler warnings with some versions of gcc, so mark the typedefs - * as permissibly-unused to disable the warnings. - */ -# if defined(__GNUC__) -# define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused)) -# else -# define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */ -# endif -# define MOZ_STATIC_ASSERT_GLUE1(x, y) x##y -# define MOZ_STATIC_ASSERT_GLUE(x, y) MOZ_STATIC_ASSERT_GLUE1(x, y) -# if defined(__SUNPRO_CC) - /* - * The Sun Studio C++ compiler is buggy when declaring, inside a function, - * another extern'd function with an array argument whose length contains a - * sizeof, triggering the error message "sizeof expression not accepted as - * size of array parameter". This bug (6688515, not public yet) would hit - * defining moz_static_assert as a function, so we always define an extern - * array for Sun Studio. - * - * We include the line number in the symbol name in a best-effort attempt - * to avoid conflicts (see below). - */ -# define MOZ_STATIC_ASSERT(cond, reason) \ - extern char MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)[(cond) ? 1 : -1] -# elif defined(__COUNTER__) - /* - * If there was no preferred alternative, use a compiler-agnostic version. - * - * Note that the non-__COUNTER__ version has a bug in C++: it can't be used - * in both |extern "C"| and normal C++ in the same translation unit. (Alas - * |extern "C"| isn't allowed in a function.) The only affected compiler - * we really care about is gcc 4.2. For that compiler and others like it, - * we include the line number in the function name to do the best we can to - * avoid conflicts. These should be rare: a conflict would require use of - * MOZ_STATIC_ASSERT on the same line in separate files in the same - * translation unit, *and* the uses would have to be in code with - * different linkage, *and* the first observed use must be in C++-linkage - * code. - */ -# define MOZ_STATIC_ASSERT(cond, reason) \ - typedef int MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __COUNTER__)[(cond) ? 1 : -1] MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE -# else -# define MOZ_STATIC_ASSERT(cond, reason) \ - extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE -# endif - -#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason) -#else -#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Prints |aStr| as an assertion failure (using aFilename and aLine as the - * location of the assertion) to the standard debug-output channel. - * - * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This - * method is primarily for internal use in this header, and only secondarily - * for use in implementing release-build assertions. - */ -static MOZ_COLD MOZ_ALWAYS_INLINE void -MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename, int aLine) - MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS -{ -#ifdef ANDROID - __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert", - "Assertion failure: %s, at %s:%d\n", - aStr, aFilename, aLine); -#else - fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine); -#if defined (MOZ_DUMP_ASSERTION_STACK) - nsTraceRefcnt::WalkTheStack(stderr); -#endif - fflush(stderr); -#endif -} - -static MOZ_COLD MOZ_ALWAYS_INLINE void -MOZ_ReportCrash(const char* aStr, const char* aFilename, int aLine) - MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS -{ -#ifdef ANDROID - __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH", - "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine); -#else - fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine); -#if defined(MOZ_DUMP_ASSERTION_STACK) - nsTraceRefcnt::WalkTheStack(stderr); -#endif - fflush(stderr); -#endif -} - -/** - * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should - * call MOZ_CRASH instead. - */ -#if defined(_MSC_VER) - /* - * On MSVC use the __debugbreak compiler intrinsic, which produces an inline - * (not nested in a system function) breakpoint. This distinctively invokes - * Breakpad without requiring system library symbols on all stack-processing - * machines, as a nested breakpoint would require. - * - * We use TerminateProcess with the exit code aborting would generate - * because we don't want to invoke atexit handlers, destructors, library - * unload handlers, and so on when our process might be in a compromised - * state. - * - * We don't use abort() because it'd cause Windows to annoyingly pop up the - * process error dialog multiple times. See bug 345118 and bug 426163. - * - * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the - * compiler doesn't hassle us to provide a return statement after a - * MOZ_REALLY_CRASH() call. - * - * (Technically these are Windows requirements, not MSVC requirements. But - * practically you need MSVC for debugging, and we only ship builds created - * by MSVC, so doing it this way reduces complexity.) - */ - -__declspec(noreturn) __inline void MOZ_NoReturn() {} - -# ifdef __cplusplus -# define MOZ_REALLY_CRASH() \ - do { \ - ::__debugbreak(); \ - *((volatile int*) NULL) = __LINE__; \ - ::TerminateProcess(::GetCurrentProcess(), 3); \ - ::MOZ_NoReturn(); \ - } while (0) -# else -# define MOZ_REALLY_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = __LINE__; \ - TerminateProcess(GetCurrentProcess(), 3); \ - MOZ_NoReturn(); \ - } while (0) -# endif -#else -# ifdef __cplusplus -# define MOZ_REALLY_CRASH() \ - do { \ - *((volatile int*) NULL) = __LINE__; \ - ::abort(); \ - } while (0) -# else -# define MOZ_REALLY_CRASH() \ - do { \ - *((volatile int*) NULL) = __LINE__; \ - abort(); \ - } while (0) -# endif -#endif - -/* - * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a - * Breakpad-compatible way, in both debug and release builds. - * - * MOZ_CRASH is a good solution for "handling" failure cases when you're - * unwilling or unable to handle them more cleanly -- for OOM, for likely memory - * corruption, and so on. It's also a good solution if you need safe behavior - * in release builds as well as debug builds. But if the failure is one that - * should be debugged and fixed, MOZ_ASSERT is generally preferable. - * - * The optional explanation-string, if provided, must be a string literal - * explaining why we're crashing. This argument is intended for use with - * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's - * obvious why we're crashing. - * - * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an - * explanation-string, we print the string to stderr. Otherwise, we don't - * print anything; this is because we want MOZ_CRASH to be 100% safe in release - * builds, and it's hard to print to stderr safely when memory might have been - * corrupted. - */ -#ifndef DEBUG -# define MOZ_CRASH(...) \ - do { \ - MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \ - MOZ_REALLY_CRASH(); \ - } while (0) -#else -# define MOZ_CRASH(...) \ - do { \ - MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \ - MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \ - MOZ_REALLY_CRASH(); \ - } while (0) -#endif - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -/* - * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in - * debug builds. If it is, execution continues. Otherwise, an error message - * including the expression and the explanation-string (if provided) is printed, - * an attempt is made to invoke any existing debugger, and execution halts. - * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition - * which can correctly be falsy. - * - * The optional explanation-string, if provided, must be a string literal - * explaining the assertion. It is intended for use with assertions whose - * correctness or rationale is non-obvious, and for assertions where the "real" - * condition being tested is best described prosaically. Don't provide an - * explanation if it's not actually helpful. - * - * // No explanation needed: pointer arguments often must not be NULL. - * MOZ_ASSERT(arg); - * - * // An explanation can be helpful to explain exactly how we know an - * // assertion is valid. - * MOZ_ASSERT(state == WAITING_FOR_RESPONSE, - * "given that and , we must have..."); - * - * // Or it might disambiguate multiple identical (save for their location) - * // assertions of the same expression. - * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(), - * "we already set [[PrimitiveThis]] for this Boolean object"); - * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(), - * "we already set [[PrimitiveThis]] for this String object"); - * - * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs - * *only* during debugging, not "in the field". If you want the latter, use - * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well. - * - * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and - * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare - * enough to require real user testing to hit, but is not security-sensitive. - * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT - * is firing, it should promptly be converted to a MOZ_ASSERT while the failure - * is being investigated, rather than letting users suffer. - */ - -/* - * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against - * accidentally passing something unintended in lieu of an assertion condition. - */ - -#ifdef __cplusplus -# include "mozilla/TypeTraits.h" -namespace mozilla { -namespace detail { - -template -struct AssertionConditionType -{ - typedef typename RemoveReference::Type ValueT; - static_assert(!IsArray::value, - "Expected boolean assertion condition, got an array or a " - "string!"); - static_assert(!IsFunction::value, - "Expected boolean assertion condition, got a function! Did " - "you intend to call that function?"); - static_assert(!IsFloatingPoint::value, - "It's often a bad idea to assert that a floating-point number " - "is nonzero, because such assertions tend to intermittently " - "fail. Shouldn't your code gracefully handle this case instead " - "of asserting? Anyway, if you really want to do that, write an " - "explicit boolean condition, like !!x or x!=0."); - - static const bool isValid = true; -}; - -} // namespace detail -} // namespace mozilla -# define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \ - static_assert(mozilla::detail::AssertionConditionType::isValid, \ - "invalid assertion condition") -#else -# define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) -#endif - -/* First the single-argument form. */ -#define MOZ_ASSERT_HELPER1(expr) \ - do { \ - MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \ - if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \ - MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \ - MOZ_CRASH_ANNOTATE("MOZ_RELEASE_ASSERT(" #expr ")"); \ - MOZ_REALLY_CRASH(); \ - } \ - } while (0) -/* Now the two-argument form. */ -#define MOZ_ASSERT_HELPER2(expr, explain) \ - do { \ - MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \ - if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \ - MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \ - MOZ_CRASH_ANNOTATE("MOZ_RELEASE_ASSERT(" #expr ") (" explain ")"); \ - MOZ_REALLY_CRASH(); \ - } \ - } while (0) - -#define MOZ_RELEASE_ASSERT_GLUE(a, b) a b -#define MOZ_RELEASE_ASSERT(...) \ - MOZ_RELEASE_ASSERT_GLUE( \ - MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \ - (__VA_ARGS__)) - -#ifdef DEBUG -# define MOZ_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__) -#else -# define MOZ_ASSERT(...) do { } while (0) -#endif /* DEBUG */ - -#ifdef RELEASE_OR_BETA -# define MOZ_DIAGNOSTIC_ASSERT MOZ_ASSERT -#else -# define MOZ_DIAGNOSTIC_ASSERT MOZ_RELEASE_ASSERT -#endif - -/* - * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is - * true. - * - * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num)); - * - * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is - * designed to catch bugs during debugging, not "in the field". - */ -#ifdef DEBUG -# define MOZ_ASSERT_IF(cond, expr) \ - do { \ - if (cond) { \ - MOZ_ASSERT(expr); \ - } \ - } while (0) -#else -# define MOZ_ASSERT_IF(cond, expr) do { } while (0) -#endif - -/* - * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that - * it is undefined behavior for execution to reach this point. No guarantees - * are made about what will happen if this is reached at runtime. Most code - * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra - * asserts. - */ -#if defined(__clang__) || defined(__GNUC__) -# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() -#elif defined(_MSC_VER) -# define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0) -#else -# ifdef __cplusplus -# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() -# else -# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() -# endif -#endif - -/* - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it - * can assume that the macro call cannot be reached during execution. This lets - * the compiler generate better-optimized code under some circumstances, at the - * expense of the program's behavior being undefined if control reaches the - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE. - * - * In Gecko, you probably should not use this macro outside of performance- or - * size-critical code, because it's unsafe. If you don't care about code size - * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH. - * - * SpiderMonkey is a different beast, and there it's acceptable to use - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely. - * - * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid - * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE - * call. - * - * Example usage: - * - * enum ValueType { - * VALUE_STRING, - * VALUE_INT, - * VALUE_FLOAT - * }; - * - * int ptrToInt(ValueType type, void* value) { - * { - * // We know for sure that type is either INT or FLOAT, and we want this - * // code to run as quickly as possible. - * switch (type) { - * case VALUE_INT: - * return *(int*) value; - * case VALUE_FLOAT: - * return (int) *(float*) value; - * default: - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType"); - * } - * } - */ - -/* - * Unconditional assert in debug builds for (assumed) unreachable code paths - * that have a safe return without crashing in release builds. - */ -#define MOZ_ASSERT_UNREACHABLE(reason) \ - MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason) - -#define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \ - do { \ - MOZ_ASSERT_UNREACHABLE(reason); \ - MOZ_ASSUME_UNREACHABLE_MARKER(); \ - } while (0) - -/** - * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about - * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in - * debug builds, but intentionally fall through in release builds to handle - * unexpected values. - * - * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to MOZ_FALLTHROUGH? In - * release builds, the MOZ_ASSERT(false) will expand to `do { } while (0)`, - * requiring a MOZ_FALLTHROUGH annotation to suppress a -Wimplicit-fallthrough - * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like - * `if (true) { MOZ_CRASH(); }` and the MOZ_FALLTHROUGH annotation will cause - * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this - * warning stalemate. - * - * // Example before MOZ_FALLTHROUGH_ASSERT: - * switch (foo) { - * default: - * // This case wants to assert in debug builds, fall through in release. - * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds! - * MOZ_FALLTHROUGH; // but -Wunreachable-code warning in debug builds! - * case 5: - * return 5; - * } - * - * // Example with MOZ_FALLTHROUGH_ASSERT: - * switch (foo) { - * default: - * // This case asserts in debug builds, falls through in release. - * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!"); - * case 5: - * return 5; - * } - */ -#ifdef DEBUG -# define MOZ_FALLTHROUGH_ASSERT(reason) MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " reason) -#else -# define MOZ_FALLTHROUGH_ASSERT(...) MOZ_FALLTHROUGH -#endif - -/* - * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided - * expression, in debug builds and in release builds both. Then, in debug - * builds only, the value of the expression is asserted either true or false - * using MOZ_ASSERT. - */ -#ifdef DEBUG -# define MOZ_ALWAYS_TRUE(expr) \ - do { \ - if ((expr)) { \ - /* Do nothing. */ \ - } else { \ - MOZ_ASSERT(false, #expr); \ - } \ - } while (0) -# define MOZ_ALWAYS_FALSE(expr) \ - do { \ - if ((expr)) { \ - MOZ_ASSERT(false, #expr); \ - } else { \ - /* Do nothing. */ \ - } \ - } while (0) -#else -# define MOZ_ALWAYS_TRUE(expr) \ - do { \ - if ((expr)) { \ - /* Silence MOZ_MUST_USE. */ \ - } \ - } while (0) -# define MOZ_ALWAYS_FALSE(expr) \ - do { \ - if ((expr)) { \ - /* Silence MOZ_MUST_USE. */ \ - } \ - } while (0) -#endif - -#undef MOZ_DUMP_ASSERTION_STACK -#undef MOZ_CRASH_CRASHREPORT - -#endif /* mozilla_Assertions_h */ diff --git a/mac/include/spidermonkey/mozilla/Atomics.h b/mac/include/spidermonkey/mozilla/Atomics.h deleted file mode 100644 index 213d1b9f..00000000 --- a/mac/include/spidermonkey/mozilla/Atomics.h +++ /dev/null @@ -1,800 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements (almost always) lock-free atomic operations. The operations here - * are a subset of that which can be found in C++11's header, with a - * different API to enforce consistent memory ordering constraints. - * - * Anyone caught using |volatile| for inter-thread memory safety needs to be - * sent a copy of this header and the C++11 standard. - */ - -#ifndef mozilla_Atomics_h -#define mozilla_Atomics_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/TypeTraits.h" - -#include - -/* - * Our minimum deployment target on clang/OS X is OS X 10.6, whose SDK - * does not have . So be sure to check for support - * along with C++0x support. - */ -#if defined(_MSC_VER) -# define MOZ_HAVE_CXX11_ATOMICS -#elif defined(__clang__) || defined(__GNUC__) - /* - * Clang doesn't like from libstdc++ before 4.7 due to the - * loose typing of the atomic builtins. GCC 4.5 and 4.6 lacks inline - * definitions for unspecialized std::atomic and causes linking errors. - * Therefore, we require at least 4.7.0 for using libstdc++. - * - * libc++ is only functional with clang. - */ -# if MOZ_USING_LIBSTDCXX && MOZ_LIBSTDCXX_VERSION_AT_LEAST(4, 7, 0) -# define MOZ_HAVE_CXX11_ATOMICS -# elif MOZ_USING_LIBCXX && defined(__clang__) -# define MOZ_HAVE_CXX11_ATOMICS -# endif -#endif - -namespace mozilla { - -/** - * An enum of memory ordering possibilities for atomics. - * - * Memory ordering is the observable state of distinct values in memory. - * (It's a separate concept from atomicity, which concerns whether an - * operation can ever be observed in an intermediate state. Don't - * conflate the two!) Given a sequence of operations in source code on - * memory, it is *not* always the case that, at all times and on all - * cores, those operations will appear to have occurred in that exact - * sequence. First, the compiler might reorder that sequence, if it - * thinks another ordering will be more efficient. Second, the CPU may - * not expose so consistent a view of memory. CPUs will often perform - * their own instruction reordering, above and beyond that performed by - * the compiler. And each core has its own memory caches, and accesses - * (reads and writes both) to "memory" may only resolve to out-of-date - * cache entries -- not to the "most recently" performed operation in - * some global sense. Any access to a value that may be used by - * multiple threads, potentially across multiple cores, must therefore - * have a memory ordering imposed on it, for all code on all - * threads/cores to have a sufficiently coherent worldview. - * - * http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync and - * http://en.cppreference.com/w/cpp/atomic/memory_order go into more - * detail on all this, including examples of how each mode works. - * - * Note that for simplicity and practicality, not all of the modes in - * C++11 are supported. The missing C++11 modes are either subsumed by - * the modes we provide below, or not relevant for the CPUs we support - * in Gecko. These three modes are confusing enough as it is! - */ -enum MemoryOrdering { - /* - * Relaxed ordering is the simplest memory ordering: none at all. - * When the result of a write is observed, nothing may be inferred - * about other memory. Writes ostensibly performed "before" on the - * writing thread may not yet be visible. Writes performed "after" on - * the writing thread may already be visible, if the compiler or CPU - * reordered them. (The latter can happen if reads and/or writes get - * held up in per-processor caches.) Relaxed ordering means - * operations can always use cached values (as long as the actual - * updates to atomic values actually occur, correctly, eventually), so - * it's usually the fastest sort of atomic access. For this reason, - * *it's also the most dangerous kind of access*. - * - * Relaxed ordering is good for things like process-wide statistics - * counters that don't need to be consistent with anything else, so - * long as updates themselves are atomic. (And so long as any - * observations of that value can tolerate being out-of-date -- if you - * need some sort of up-to-date value, you need some sort of other - * synchronizing operation.) It's *not* good for locks, mutexes, - * reference counts, etc. that mediate access to other memory, or must - * be observably consistent with other memory. - * - * x86 architectures don't take advantage of the optimization - * opportunities that relaxed ordering permits. Thus it's possible - * that using relaxed ordering will "work" on x86 but fail elsewhere - * (ARM, say, which *does* implement non-sequentially-consistent - * relaxed ordering semantics). Be extra-careful using relaxed - * ordering if you can't easily test non-x86 architectures! - */ - Relaxed, - - /* - * When an atomic value is updated with ReleaseAcquire ordering, and - * that new value is observed with ReleaseAcquire ordering, prior - * writes (atomic or not) are also observable. What ReleaseAcquire - * *doesn't* give you is any observable ordering guarantees for - * ReleaseAcquire-ordered operations on different objects. For - * example, if there are two cores that each perform ReleaseAcquire - * operations on separate objects, each core may or may not observe - * the operations made by the other core. The only way the cores can - * be synchronized with ReleaseAcquire is if they both - * ReleaseAcquire-access the same object. This implies that you can't - * necessarily describe some global total ordering of ReleaseAcquire - * operations. - * - * ReleaseAcquire ordering is good for (as the name implies) atomic - * operations on values controlling ownership of things: reference - * counts, mutexes, and the like. However, if you are thinking about - * using these to implement your own locks or mutexes, you should take - * a good, hard look at actual lock or mutex primitives first. - */ - ReleaseAcquire, - - /* - * When an atomic value is updated with SequentiallyConsistent - * ordering, all writes observable when the update is observed, just - * as with ReleaseAcquire ordering. But, furthermore, a global total - * ordering of SequentiallyConsistent operations *can* be described. - * For example, if two cores perform SequentiallyConsistent operations - * on separate objects, one core will observably perform its update - * (and all previous operations will have completed), then the other - * core will observably perform its update (and all previous - * operations will have completed). (Although those previous - * operations aren't themselves ordered -- they could be intermixed, - * or ordered if they occur on atomic values with ordering - * requirements.) SequentiallyConsistent is the *simplest and safest* - * ordering of atomic operations -- it's always as if one operation - * happens, then another, then another, in some order -- and every - * core observes updates to happen in that single order. Because it - * has the most synchronization requirements, operations ordered this - * way also tend to be slowest. - * - * SequentiallyConsistent ordering can be desirable when multiple - * threads observe objects, and they all have to agree on the - * observable order of changes to them. People expect - * SequentiallyConsistent ordering, even if they shouldn't, when - * writing code, atomic or otherwise. SequentiallyConsistent is also - * the ordering of choice when designing lockless data structures. If - * you don't know what order to use, use this one. - */ - SequentiallyConsistent, -}; - -} // namespace mozilla - -// Build up the underlying intrinsics. -#ifdef MOZ_HAVE_CXX11_ATOMICS - -# include - -namespace mozilla { -namespace detail { - -/* - * We provide CompareExchangeFailureOrder to work around a bug in some - * versions of GCC's header. See bug 898491. - */ -template struct AtomicOrderConstraints; - -template<> -struct AtomicOrderConstraints -{ - static const std::memory_order AtomicRMWOrder = std::memory_order_relaxed; - static const std::memory_order LoadOrder = std::memory_order_relaxed; - static const std::memory_order StoreOrder = std::memory_order_relaxed; - static const std::memory_order CompareExchangeFailureOrder = - std::memory_order_relaxed; -}; - -template<> -struct AtomicOrderConstraints -{ - static const std::memory_order AtomicRMWOrder = std::memory_order_acq_rel; - static const std::memory_order LoadOrder = std::memory_order_acquire; - static const std::memory_order StoreOrder = std::memory_order_release; - static const std::memory_order CompareExchangeFailureOrder = - std::memory_order_acquire; -}; - -template<> -struct AtomicOrderConstraints -{ - static const std::memory_order AtomicRMWOrder = std::memory_order_seq_cst; - static const std::memory_order LoadOrder = std::memory_order_seq_cst; - static const std::memory_order StoreOrder = std::memory_order_seq_cst; - static const std::memory_order CompareExchangeFailureOrder = - std::memory_order_seq_cst; -}; - -template -struct IntrinsicBase -{ - typedef std::atomic ValueType; - typedef AtomicOrderConstraints OrderedOp; -}; - -template -struct IntrinsicMemoryOps : public IntrinsicBase -{ - typedef IntrinsicBase Base; - - static T load(const typename Base::ValueType& aPtr) - { - return aPtr.load(Base::OrderedOp::LoadOrder); - } - - static void store(typename Base::ValueType& aPtr, T aVal) - { - aPtr.store(aVal, Base::OrderedOp::StoreOrder); - } - - static T exchange(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.exchange(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static bool compareExchange(typename Base::ValueType& aPtr, - T aOldVal, T aNewVal) - { - return aPtr.compare_exchange_strong(aOldVal, aNewVal, - Base::OrderedOp::AtomicRMWOrder, - Base::OrderedOp::CompareExchangeFailureOrder); - } -}; - -template -struct IntrinsicAddSub : public IntrinsicBase -{ - typedef IntrinsicBase Base; - - static T add(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_add(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T sub(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_sub(aVal, Base::OrderedOp::AtomicRMWOrder); - } -}; - -template -struct IntrinsicAddSub : public IntrinsicBase -{ - typedef IntrinsicBase Base; - - static T* add(typename Base::ValueType& aPtr, ptrdiff_t aVal) - { - return aPtr.fetch_add(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T* sub(typename Base::ValueType& aPtr, ptrdiff_t aVal) - { - return aPtr.fetch_sub(aVal, Base::OrderedOp::AtomicRMWOrder); - } -}; - -template -struct IntrinsicIncDec : public IntrinsicAddSub -{ - typedef IntrinsicBase Base; - - static T inc(typename Base::ValueType& aPtr) - { - return IntrinsicAddSub::add(aPtr, 1); - } - - static T dec(typename Base::ValueType& aPtr) - { - return IntrinsicAddSub::sub(aPtr, 1); - } -}; - -template -struct AtomicIntrinsics : public IntrinsicMemoryOps, - public IntrinsicIncDec -{ - typedef IntrinsicBase Base; - - static T or_(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_or(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T xor_(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_xor(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T and_(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_and(aVal, Base::OrderedOp::AtomicRMWOrder); - } -}; - -template -struct AtomicIntrinsics - : public IntrinsicMemoryOps, public IntrinsicIncDec -{ -}; - -template -struct ToStorageTypeArgument -{ - static constexpr T convert (T aT) { return aT; } -}; - -} // namespace detail -} // namespace mozilla - -#elif defined(__GNUC__) - -namespace mozilla { -namespace detail { - -/* - * The __sync_* family of intrinsics is documented here: - * - * http://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Atomic-Builtins.html - * - * While these intrinsics are deprecated in favor of the newer __atomic_* - * family of intrincs: - * - * http://gcc.gnu.org/onlinedocs/gcc-4.7.3/gcc/_005f_005fatomic-Builtins.html - * - * any GCC version that supports the __atomic_* intrinsics will also support - * the header and so will be handled above. We provide a version of - * atomics using the __sync_* intrinsics to support older versions of GCC. - * - * All __sync_* intrinsics that we use below act as full memory barriers, for - * both compiler and hardware reordering, except for __sync_lock_test_and_set, - * which is a only an acquire barrier. When we call __sync_lock_test_and_set, - * we add a barrier above it as appropriate. - */ - -template struct Barrier; - -/* - * Some processors (in particular, x86) don't require quite so many calls to - * __sync_sychronize as our specializations of Barrier produce. If - * performance turns out to be an issue, defining these specializations - * on a per-processor basis would be a good first tuning step. - */ - -template<> -struct Barrier -{ - static void beforeLoad() {} - static void afterLoad() {} - static void beforeStore() {} - static void afterStore() {} -}; - -template<> -struct Barrier -{ - static void beforeLoad() {} - static void afterLoad() { __sync_synchronize(); } - static void beforeStore() { __sync_synchronize(); } - static void afterStore() {} -}; - -template<> -struct Barrier -{ - static void beforeLoad() { __sync_synchronize(); } - static void afterLoad() { __sync_synchronize(); } - static void beforeStore() { __sync_synchronize(); } - static void afterStore() { __sync_synchronize(); } -}; - -template::value> -struct AtomicStorageType -{ - // For non-enums, just use the type directly. - typedef T Type; -}; - -template -struct AtomicStorageType - : Conditional -{ - static_assert(sizeof(T) == 4 || sizeof(T) == 8, - "wrong type computed in conditional above"); -}; - -template -struct IntrinsicMemoryOps -{ - typedef typename AtomicStorageType::Type ValueType; - - static T load(const ValueType& aPtr) - { - Barrier::beforeLoad(); - T val = T(aPtr); - Barrier::afterLoad(); - return val; - } - - static void store(ValueType& aPtr, T aVal) - { - Barrier::beforeStore(); - aPtr = ValueType(aVal); - Barrier::afterStore(); - } - - static T exchange(ValueType& aPtr, T aVal) - { - // __sync_lock_test_and_set is only an acquire barrier; loads and stores - // can't be moved up from after to before it, but they can be moved down - // from before to after it. We may want a stricter ordering, so we need - // an explicit barrier. - Barrier::beforeStore(); - return T(__sync_lock_test_and_set(&aPtr, ValueType(aVal))); - } - - static bool compareExchange(ValueType& aPtr, T aOldVal, T aNewVal) - { - return __sync_bool_compare_and_swap(&aPtr, ValueType(aOldVal), ValueType(aNewVal)); - } -}; - -template -struct IntrinsicAddSub - : public IntrinsicMemoryOps -{ - typedef IntrinsicMemoryOps Base; - typedef typename Base::ValueType ValueType; - - static T add(ValueType& aPtr, T aVal) - { - return T(__sync_fetch_and_add(&aPtr, ValueType(aVal))); - } - - static T sub(ValueType& aPtr, T aVal) - { - return T(__sync_fetch_and_sub(&aPtr, ValueType(aVal))); - } -}; - -template -struct IntrinsicAddSub - : public IntrinsicMemoryOps -{ - typedef IntrinsicMemoryOps Base; - typedef typename Base::ValueType ValueType; - - /* - * The reinterpret_casts are needed so that - * __sync_fetch_and_{add,sub} will properly type-check. - * - * Also, these functions do not provide standard semantics for - * pointer types, so we need to adjust the addend. - */ - static ValueType add(ValueType& aPtr, ptrdiff_t aVal) - { - ValueType amount = reinterpret_cast(aVal * sizeof(T)); - return __sync_fetch_and_add(&aPtr, amount); - } - - static ValueType sub(ValueType& aPtr, ptrdiff_t aVal) - { - ValueType amount = reinterpret_cast(aVal * sizeof(T)); - return __sync_fetch_and_sub(&aPtr, amount); - } -}; - -template -struct IntrinsicIncDec : public IntrinsicAddSub -{ - typedef IntrinsicAddSub Base; - typedef typename Base::ValueType ValueType; - - static T inc(ValueType& aPtr) { return Base::add(aPtr, 1); } - static T dec(ValueType& aPtr) { return Base::sub(aPtr, 1); } -}; - -template -struct AtomicIntrinsics : public IntrinsicIncDec -{ - static T or_( T& aPtr, T aVal) { return __sync_fetch_and_or(&aPtr, aVal); } - static T xor_(T& aPtr, T aVal) { return __sync_fetch_and_xor(&aPtr, aVal); } - static T and_(T& aPtr, T aVal) { return __sync_fetch_and_and(&aPtr, aVal); } -}; - -template -struct AtomicIntrinsics : public IntrinsicIncDec -{ -}; - -template::value> -struct ToStorageTypeArgument -{ - typedef typename AtomicStorageType::Type ResultType; - - static constexpr ResultType convert (T aT) { return ResultType(aT); } -}; - -template -struct ToStorageTypeArgument -{ - static constexpr T convert (T aT) { return aT; } -}; - -} // namespace detail -} // namespace mozilla - -#else -# error "Atomic compiler intrinsics are not supported on your platform" -#endif - -namespace mozilla { - -namespace detail { - -template -class AtomicBase -{ - static_assert(sizeof(T) == 4 || sizeof(T) == 8, - "mozilla/Atomics.h only supports 32-bit and 64-bit types"); - -protected: - typedef typename detail::AtomicIntrinsics Intrinsics; - typedef typename Intrinsics::ValueType ValueType; - ValueType mValue; - -public: - constexpr AtomicBase() : mValue() {} - explicit constexpr AtomicBase(T aInit) - : mValue(ToStorageTypeArgument::convert(aInit)) - {} - - // Note: we can't provide operator T() here because Atomic inherits - // from AtomcBase with T=uint32_t and not T=bool. If we implemented - // operator T() here, it would cause errors when comparing Atomic with - // a regular bool. - - T operator=(T aVal) - { - Intrinsics::store(mValue, aVal); - return aVal; - } - - /** - * Performs an atomic swap operation. aVal is stored and the previous - * value of this variable is returned. - */ - T exchange(T aVal) - { - return Intrinsics::exchange(mValue, aVal); - } - - /** - * Performs an atomic compare-and-swap operation and returns true if it - * succeeded. This is equivalent to atomically doing - * - * if (mValue == aOldValue) { - * mValue = aNewValue; - * return true; - * } else { - * return false; - * } - */ - bool compareExchange(T aOldValue, T aNewValue) - { - return Intrinsics::compareExchange(mValue, aOldValue, aNewValue); - } - -private: - template - AtomicBase(const AtomicBase& aCopy) = delete; -}; - -template -class AtomicBaseIncDec : public AtomicBase -{ - typedef typename detail::AtomicBase Base; - -public: - constexpr AtomicBaseIncDec() : Base() {} - explicit constexpr AtomicBaseIncDec(T aInit) : Base(aInit) {} - - using Base::operator=; - - operator T() const { return Base::Intrinsics::load(Base::mValue); } - T operator++(int) { return Base::Intrinsics::inc(Base::mValue); } - T operator--(int) { return Base::Intrinsics::dec(Base::mValue); } - T operator++() { return Base::Intrinsics::inc(Base::mValue) + 1; } - T operator--() { return Base::Intrinsics::dec(Base::mValue) - 1; } - -private: - template - AtomicBaseIncDec(const AtomicBaseIncDec& aCopy) = delete; -}; - -} // namespace detail - -/** - * A wrapper for a type that enforces that all memory accesses are atomic. - * - * In general, where a variable |T foo| exists, |Atomic foo| can be used in - * its place. Implementations for integral and pointer types are provided - * below. - * - * Atomic accesses are sequentially consistent by default. You should - * use the default unless you are tall enough to ride the - * memory-ordering roller coaster (if you're not sure, you aren't) and - * you have a compelling reason to do otherwise. - * - * There is one exception to the case of atomic memory accesses: providing an - * initial value of the atomic value is not guaranteed to be atomic. This is a - * deliberate design choice that enables static atomic variables to be declared - * without introducing extra static constructors. - */ -template -class Atomic; - -/** - * Atomic implementation for integral types. - * - * In addition to atomic store and load operations, compound assignment and - * increment/decrement operators are implemented which perform the - * corresponding read-modify-write operation atomically. Finally, an atomic - * swap method is provided. - */ -template -class Atomic::value && - !IsSame::value>::Type> - : public detail::AtomicBaseIncDec -{ - typedef typename detail::AtomicBaseIncDec Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(T aInit) : Base(aInit) {} - - using Base::operator=; - - T operator+=(T aDelta) - { - return Base::Intrinsics::add(Base::mValue, aDelta) + aDelta; - } - - T operator-=(T aDelta) - { - return Base::Intrinsics::sub(Base::mValue, aDelta) - aDelta; - } - - T operator|=(T aVal) - { - return Base::Intrinsics::or_(Base::mValue, aVal) | aVal; - } - - T operator^=(T aVal) - { - return Base::Intrinsics::xor_(Base::mValue, aVal) ^ aVal; - } - - T operator&=(T aVal) - { - return Base::Intrinsics::and_(Base::mValue, aVal) & aVal; - } - -private: - Atomic(Atomic& aOther) = delete; -}; - -/** - * Atomic implementation for pointer types. - * - * An atomic compare-and-swap primitive for pointer variables is provided, as - * are atomic increment and decement operators. Also provided are the compound - * assignment operators for addition and subtraction. Atomic swap (via - * exchange()) is included as well. - */ -template -class Atomic : public detail::AtomicBaseIncDec -{ - typedef typename detail::AtomicBaseIncDec Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(T* aInit) : Base(aInit) {} - - using Base::operator=; - - T* operator+=(ptrdiff_t aDelta) - { - return Base::Intrinsics::add(Base::mValue, aDelta) + aDelta; - } - - T* operator-=(ptrdiff_t aDelta) - { - return Base::Intrinsics::sub(Base::mValue, aDelta) - aDelta; - } - -private: - Atomic(Atomic& aOther) = delete; -}; - -/** - * Atomic implementation for enum types. - * - * The atomic store and load operations and the atomic swap method is provided. - */ -template -class Atomic::value>::Type> - : public detail::AtomicBase -{ - typedef typename detail::AtomicBase Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(T aInit) : Base(aInit) {} - - operator T() const { return T(Base::Intrinsics::load(Base::mValue)); } - - using Base::operator=; - -private: - Atomic(Atomic& aOther) = delete; -}; - -/** - * Atomic implementation for boolean types. - * - * The atomic store and load operations and the atomic swap method is provided. - * - * Note: - * - * - sizeof(Atomic) != sizeof(bool) for some implementations of - * bool and/or some implementations of std::atomic. This is allowed in - * [atomic.types.generic]p9. - * - * - It's not obvious whether the 8-bit atomic functions on Windows are always - * inlined or not. If they are not inlined, the corresponding functions in the - * runtime library are not available on Windows XP. This is why we implement - * Atomic with an underlying type of uint32_t. - */ -template -class Atomic - : protected detail::AtomicBase -{ - typedef typename detail::AtomicBase Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(bool aInit) : Base(aInit) {} - - // We provide boolean wrappers for the underlying AtomicBase methods. - MOZ_IMPLICIT operator bool() const - { - return Base::Intrinsics::load(Base::mValue); - } - - bool operator=(bool aVal) - { - return Base::operator=(aVal); - } - - bool exchange(bool aVal) - { - return Base::exchange(aVal); - } - - bool compareExchange(bool aOldValue, bool aNewValue) - { - return Base::compareExchange(aOldValue, aNewValue); - } - -private: - Atomic(Atomic& aOther) = delete; -}; - -} // namespace mozilla - -#endif /* mozilla_Atomics_h */ diff --git a/mac/include/spidermonkey/mozilla/Attributes.h b/mac/include/spidermonkey/mozilla/Attributes.h deleted file mode 100644 index df6172f3..00000000 --- a/mac/include/spidermonkey/mozilla/Attributes.h +++ /dev/null @@ -1,604 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implementations of various class and method modifier attributes. */ - -#ifndef mozilla_Attributes_h -#define mozilla_Attributes_h - -#include "mozilla/Compiler.h" - -/* - * MOZ_ALWAYS_INLINE is a macro which expands to tell the compiler that the - * method decorated with it must be inlined, even if the compiler thinks - * otherwise. This is only a (much) stronger version of the inline hint: - * compilers are not guaranteed to respect it (although they're much more likely - * to do so). - * - * The MOZ_ALWAYS_INLINE_EVEN_DEBUG macro is yet stronger. It tells the - * compiler to inline even in DEBUG builds. It should be used very rarely. - */ -#if defined(_MSC_VER) -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __forceinline -#elif defined(__GNUC__) -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) inline -#else -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG inline -#endif - -#if !defined(DEBUG) -# define MOZ_ALWAYS_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG -#elif defined(_MSC_VER) && !defined(__cplusplus) -# define MOZ_ALWAYS_INLINE __inline -#else -# define MOZ_ALWAYS_INLINE inline -#endif - -#if defined(_MSC_VER) -/* - * g++ requires -std=c++0x or -std=gnu++0x to support C++11 functionality - * without warnings (functionality used by the macros below). These modes are - * detectable by checking whether __GXX_EXPERIMENTAL_CXX0X__ is defined or, more - * standardly, by checking whether __cplusplus has a C++11 or greater value. - * Current versions of g++ do not correctly set __cplusplus, so we check both - * for forward compatibility. - */ -# define MOZ_HAVE_NEVER_INLINE __declspec(noinline) -# define MOZ_HAVE_NORETURN __declspec(noreturn) -#elif defined(__clang__) - /* - * Per Clang documentation, "Note that marketing version numbers should not - * be used to check for language features, as different vendors use different - * numbering schemes. Instead, use the feature checking macros." - */ -# ifndef __has_extension -# define __has_extension __has_feature /* compatibility, for older versions of clang */ -# endif -# if __has_attribute(noinline) -# define MOZ_HAVE_NEVER_INLINE __attribute__((noinline)) -# endif -# if __has_attribute(noreturn) -# define MOZ_HAVE_NORETURN __attribute__((noreturn)) -# endif -#elif defined(__GNUC__) -# define MOZ_HAVE_NEVER_INLINE __attribute__((noinline)) -# define MOZ_HAVE_NORETURN __attribute__((noreturn)) -#endif - -/* - * When built with clang analyzer (a.k.a scan-build), define MOZ_HAVE_NORETURN - * to mark some false positives - */ -#ifdef __clang_analyzer__ -# if __has_extension(attribute_analyzer_noreturn) -# define MOZ_HAVE_ANALYZER_NORETURN __attribute__((analyzer_noreturn)) -# endif -#endif - -/* - * MOZ_NEVER_INLINE is a macro which expands to tell the compiler that the - * method decorated with it must never be inlined, even if the compiler would - * otherwise choose to inline the method. Compilers aren't absolutely - * guaranteed to support this, but most do. - */ -#if defined(MOZ_HAVE_NEVER_INLINE) -# define MOZ_NEVER_INLINE MOZ_HAVE_NEVER_INLINE -#else -# define MOZ_NEVER_INLINE /* no support */ -#endif - -/* - * MOZ_NORETURN, specified at the start of a function declaration, indicates - * that the given function does not return. (The function definition does not - * need to be annotated.) - * - * MOZ_NORETURN void abort(const char* msg); - * - * This modifier permits the compiler to optimize code assuming a call to such a - * function will never return. It also enables the compiler to avoid spurious - * warnings about not initializing variables, or about any other seemingly-dodgy - * operations performed after the function returns. - * - * This modifier does not affect the corresponding function's linking behavior. - */ -#if defined(MOZ_HAVE_NORETURN) -# define MOZ_NORETURN MOZ_HAVE_NORETURN -#else -# define MOZ_NORETURN /* no support */ -#endif - -/** - * MOZ_COLD tells the compiler that a function is "cold", meaning infrequently - * executed. This may lead it to optimize for size more aggressively than speed, - * or to allocate the body of the function in a distant part of the text segment - * to help keep it from taking up unnecessary icache when it isn't in use. - * - * Place this attribute at the very beginning of a function definition. For - * example, write - * - * MOZ_COLD int foo(); - * - * or - * - * MOZ_COLD int foo() { return 42; } - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_COLD __attribute__ ((cold)) -#else -# define MOZ_COLD -#endif - -/** - * MOZ_NONNULL tells the compiler that some of the arguments to a function are - * known to be non-null. The arguments are a list of 1-based argument indexes - * identifying arguments which are known to be non-null. - * - * Place this attribute at the very beginning of a function definition. For - * example, write - * - * MOZ_NONNULL(1, 2) int foo(char *p, char *q); - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_NONNULL(...) __attribute__ ((nonnull(__VA_ARGS__))) -#else -# define MOZ_NONNULL(...) -#endif - -/* - * MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS, specified at the end of a function - * declaration, indicates that for the purposes of static analysis, this - * function does not return. (The function definition does not need to be - * annotated.) - * - * MOZ_ReportCrash(const char* s, const char* file, int ln) - * MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS - * - * Some static analyzers, like scan-build from clang, can use this information - * to eliminate false positives. From the upstream documentation of scan-build: - * "This attribute is useful for annotating assertion handlers that actually - * can return, but for the purpose of using the analyzer we want to pretend - * that such functions do not return." - * - */ -#if defined(MOZ_HAVE_ANALYZER_NORETURN) -# define MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS MOZ_HAVE_ANALYZER_NORETURN -#else -# define MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS /* no support */ -#endif - -/* - * MOZ_ASAN_BLACKLIST is a macro to tell AddressSanitizer (a compile-time - * instrumentation shipped with Clang and GCC) to not instrument the annotated - * function. Furthermore, it will prevent the compiler from inlining the - * function because inlining currently breaks the blacklisting mechanism of - * AddressSanitizer. - */ -#if defined(__has_feature) -# if __has_feature(address_sanitizer) -# define MOZ_HAVE_ASAN_BLACKLIST -# endif -#elif defined(__GNUC__) -# if defined(__SANITIZE_ADDRESS__) -# define MOZ_HAVE_ASAN_BLACKLIST -# endif -#endif - -#if defined(MOZ_HAVE_ASAN_BLACKLIST) -# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_address)) -#else -# define MOZ_ASAN_BLACKLIST /* nothing */ -#endif - -/* - * MOZ_TSAN_BLACKLIST is a macro to tell ThreadSanitizer (a compile-time - * instrumentation shipped with Clang) to not instrument the annotated function. - * Furthermore, it will prevent the compiler from inlining the function because - * inlining currently breaks the blacklisting mechanism of ThreadSanitizer. - */ -#if defined(__has_feature) -# if __has_feature(thread_sanitizer) -# define MOZ_TSAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_thread)) -# else -# define MOZ_TSAN_BLACKLIST /* nothing */ -# endif -#else -# define MOZ_TSAN_BLACKLIST /* nothing */ -#endif - -/** - * MOZ_ALLOCATOR tells the compiler that the function it marks returns either a - * "fresh", "pointer-free" block of memory, or nullptr. "Fresh" means that the - * block is not pointed to by any other reachable pointer in the program. - * "Pointer-free" means that the block contains no pointers to any valid object - * in the program. It may be initialized with other (non-pointer) values. - * - * Placing this attribute on appropriate functions helps GCC analyze pointer - * aliasing more accurately in their callers. - * - * GCC warns if a caller ignores the value returned by a function marked with - * MOZ_ALLOCATOR: it is hard to imagine cases where dropping the value returned - * by a function that meets the criteria above would be intentional. - * - * Place this attribute after the argument list and 'this' qualifiers of a - * function definition. For example, write - * - * void *my_allocator(size_t) MOZ_ALLOCATOR; - * - * or - * - * void *my_allocator(size_t bytes) MOZ_ALLOCATOR { ... } - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_ALLOCATOR __attribute__ ((malloc, warn_unused_result)) -#else -# define MOZ_ALLOCATOR -#endif - -/** - * MOZ_MUST_USE tells the compiler to emit a warning if a function's - * return value is not used by the caller. - * - * Place this attribute at the very beginning of a function declaration. For - * example, write - * - * MOZ_MUST_USE int foo(); - * - * or - * - * MOZ_MUST_USE int foo() { return 42; } - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_MUST_USE __attribute__ ((warn_unused_result)) -#else -# define MOZ_MUST_USE -#endif - -/** - * MOZ_FALLTHROUGH is an annotation to suppress compiler warnings about switch - * cases that fall through without a break or return statement. MOZ_FALLTHROUGH - * is only needed on cases that have code. - * - * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about - * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in - * debug builds, but intentionally fall through in release builds. See comment - * in Assertions.h for more details. - * - * switch (foo) { - * case 1: // These cases have no code. No fallthrough annotations are needed. - * case 2: - * case 3: // This case has code, so a fallthrough annotation is needed! - * foo++; - * MOZ_FALLTHROUGH; - * case 4: - * return foo; - * - * default: - * // This case asserts in debug builds, falls through in release. - * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!"); - * case 5: - * return 5; - * } - */ -#if defined(__clang__) && __cplusplus >= 201103L - /* clang's fallthrough annotations are only available starting in C++11. */ -# define MOZ_FALLTHROUGH [[clang::fallthrough]] -#elif defined(_MSC_VER) - /* - * MSVC's __fallthrough annotations are checked by /analyze (Code Analysis): - * https://msdn.microsoft.com/en-us/library/ms235402%28VS.80%29.aspx - */ -# include -# define MOZ_FALLTHROUGH __fallthrough -#else -# define MOZ_FALLTHROUGH /* FALLTHROUGH */ -#endif - -#ifdef __cplusplus - -/* - * The following macros are attributes that support the static analysis plugin - * included with Mozilla, and will be implemented (when such support is enabled) - * as C++11 attributes. Since such attributes are legal pretty much everywhere - * and have subtly different semantics depending on their placement, the - * following is a guide on where to place the attributes. - * - * Attributes that apply to a struct or class precede the name of the class: - * (Note that this is different from the placement of final for classes!) - * - * class MOZ_CLASS_ATTRIBUTE SomeClass {}; - * - * Attributes that apply to functions follow the parentheses and const - * qualifiers but precede final, override and the function body: - * - * void DeclaredFunction() MOZ_FUNCTION_ATTRIBUTE; - * void SomeFunction() MOZ_FUNCTION_ATTRIBUTE {} - * void PureFunction() const MOZ_FUNCTION_ATTRIBUTE = 0; - * void OverriddenFunction() MOZ_FUNCTION_ATTIRBUTE override; - * - * Attributes that apply to variables or parameters follow the variable's name: - * - * int variable MOZ_VARIABLE_ATTRIBUTE; - * - * Attributes that apply to types follow the type name: - * - * typedef int MOZ_TYPE_ATTRIBUTE MagicInt; - * int MOZ_TYPE_ATTRIBUTE someVariable; - * int* MOZ_TYPE_ATTRIBUTE magicPtrInt; - * int MOZ_TYPE_ATTRIBUTE* ptrToMagicInt; - * - * Attributes that apply to statements precede the statement: - * - * MOZ_IF_ATTRIBUTE if (x == 0) - * MOZ_DO_ATTRIBUTE do { } while (0); - * - * Attributes that apply to labels precede the label: - * - * MOZ_LABEL_ATTRIBUTE target: - * goto target; - * MOZ_CASE_ATTRIBUTE case 5: - * MOZ_DEFAULT_ATTRIBUTE default: - * - * The static analyses that are performed by the plugin are as follows: - * - * MOZ_MUST_OVERRIDE: Applies to all C++ member functions. All immediate - * subclasses must provide an exact override of this method; if a subclass - * does not override this method, the compiler will emit an error. This - * attribute is not limited to virtual methods, so if it is applied to a - * nonvirtual method and the subclass does not provide an equivalent - * definition, the compiler will emit an error. - * MOZ_STACK_CLASS: Applies to all classes. Any class with this annotation is - * expected to live on the stack, so it is a compile-time error to use it, or - * an array of such objects, as a global or static variable, or as the type of - * a new expression (unless placement new is being used). If a member of - * another class uses this class, or if another class inherits from this - * class, then it is considered to be a stack class as well, although this - * attribute need not be provided in such cases. - * MOZ_NONHEAP_CLASS: Applies to all classes. Any class with this annotation is - * expected to live on the stack or in static storage, so it is a compile-time - * error to use it, or an array of such objects, as the type of a new - * expression. If a member of another class uses this class, or if another - * class inherits from this class, then it is considered to be a non-heap class - * as well, although this attribute need not be provided in such cases. - * MOZ_HEAP_CLASS: Applies to all classes. Any class with this annotation is - * expected to live on the heap, so it is a compile-time error to use it, or - * an array of such objects, as the type of a variable declaration, or as a - * temporary object. If a member of another class uses this class, or if - * another class inherits from this class, then it is considered to be a heap - * class as well, although this attribute need not be provided in such cases. - * MOZ_NON_TEMPORARY_CLASS: Applies to all classes. Any class with this - * annotation is expected not to live in a temporary. If a member of another - * class uses this class or if another class inherits from this class, then it - * is considered to be a non-temporary class as well, although this attribute - * need not be provided in such cases. - * MOZ_RAII: Applies to all classes. Any class with this annotation is assumed - * to be a RAII guard, which is expected to live on the stack in an automatic - * allocation. It is prohibited from being allocated in a temporary, static - * storage, or on the heap. This is a combination of MOZ_STACK_CLASS and - * MOZ_NON_TEMPORARY_CLASS. - * MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS: Applies to all classes that are - * intended to prevent introducing static initializers. This attribute - * currently makes it a compile-time error to instantiate these classes - * anywhere other than at the global scope, or as a static member of a class. - * In non-debug mode, it also prohibits non-trivial constructors and - * destructors. - * MOZ_TRIVIAL_CTOR_DTOR: Applies to all classes that must have both a trivial - * or constexpr constructor and a trivial destructor. Setting this attribute - * on a class makes it a compile-time error for that class to get a - * non-trivial constructor or destructor for any reason. - * MOZ_HEAP_ALLOCATOR: Applies to any function. This indicates that the return - * value is allocated on the heap, and will as a result check such allocations - * during MOZ_STACK_CLASS and MOZ_NONHEAP_CLASS annotation checking. - * MOZ_IMPLICIT: Applies to constructors. Implicit conversion constructors - * are disallowed by default unless they are marked as MOZ_IMPLICIT. This - * attribute must be used for constructors which intend to provide implicit - * conversions. - * MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT: Applies to functions. Makes it a compile - * time error to pass arithmetic expressions on variables to the function. - * MOZ_OWNING_REF: Applies to declarations of pointers to reference counted - * types. This attribute tells the compiler that the raw pointer is a strong - * reference, where ownership through methods such as AddRef and Release is - * managed manually. This can make the compiler ignore these pointers when - * validating the usage of pointers otherwise. - * - * Example uses include owned pointers inside of unions, and pointers stored - * in POD types where a using a smart pointer class would make the object - * non-POD. - * MOZ_NON_OWNING_REF: Applies to declarations of pointers to reference counted - * types. This attribute tells the compiler that the raw pointer is a weak - * reference, which is ensured to be valid by a guarantee that the reference - * will be nulled before the pointer becomes invalid. This can make the compiler - * ignore these pointers when validating the usage of pointers otherwise. - * - * Examples include an mOwner pointer, which is nulled by the owning class's - * destructor, and is null-checked before dereferencing. - * MOZ_UNSAFE_REF: Applies to declarations of pointers to reference counted types. - * Occasionally there are non-owning references which are valid, but do not take - * the form of a MOZ_NON_OWNING_REF. Their safety may be dependent on the behaviour - * of API consumers. The string argument passed to this macro documents the safety - * conditions. This can make the compiler ignore these pointers when validating - * the usage of pointers elsewhere. - * - * Examples include an nsIAtom* member which is known at compile time to point to a - * static atom which is valid throughout the lifetime of the program, or an API which - * stores a pointer, but doesn't take ownership over it, instead requiring the API - * consumer to correctly null the value before it becomes invalid. - * - * Use of this annotation is discouraged when a strong reference or one of the above - * two annotations can be used instead. - * MOZ_NO_ADDREF_RELEASE_ON_RETURN: Applies to function declarations. Makes it - * a compile time error to call AddRef or Release on the return value of a - * function. This is intended to be used with operator->() of our smart - * pointer classes to ensure that the refcount of an object wrapped in a - * smart pointer is not manipulated directly. - * MOZ_MUST_USE_TYPE: Applies to type declarations. Makes it a compile time - * error to not use the return value of a function which has this type. This - * is intended to be used with types which it is an error to not use. - * MOZ_NEEDS_NO_VTABLE_TYPE: Applies to template class declarations. Makes it - * a compile time error to instantiate this template with a type parameter which - * has a VTable. - * MOZ_NON_MEMMOVABLE: Applies to class declarations for types that are not safe - * to be moved in memory using memmove(). - * MOZ_NEEDS_MEMMOVABLE_TYPE: Applies to template class declarations where the - * template arguments are required to be safe to move in memory using - * memmove(). Passing MOZ_NON_MEMMOVABLE types to these templates is a - * compile time error. - * MOZ_NEEDS_MEMMOVABLE_MEMBERS: Applies to class declarations where each member - * must be safe to move in memory using memmove(). MOZ_NON_MEMMOVABLE types - * used in members of these classes are compile time errors. - * MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS: Applies to template class - * declarations where an instance of the template should be considered, for - * static analysis purposes, to inherit any type annotations (such as - * MOZ_MUST_USE_TYPE and MOZ_STACK_CLASS) from its template arguments. - * MOZ_INIT_OUTSIDE_CTOR: Applies to class member declarations. Occasionally - * there are class members that are not initialized in the constructor, - * but logic elsewhere in the class ensures they are initialized prior to use. - * Using this attribute on a member disables the check that this member must be - * initialized in constructors via list-initialization, in the constructor body, - * or via functions called from the constructor body. - * MOZ_IS_CLASS_INIT: Applies to class method declarations. Occasionally the - * constructor doesn't initialize all of the member variables and another function - * is used to initialize the rest. This marker is used to make the static analysis - * tool aware that the marked function is part of the initialization process - * and to include the marked function in the scan mechanism that determines witch - * member variables still remain uninitialized. - * MOZ_NON_PARAM: Applies to types. Makes it compile time error to use the type - * in parameter without pointer or reference. - * MOZ_NON_AUTOABLE: Applies to class declarations. Makes it a compile time error to - * use `auto` in place of this type in variable declarations. This is intended to - * be used with types which are intended to be implicitly constructed into other - * other types before being assigned to variables. - * MOZ_REQUIRED_BASE_METHOD: Applies to virtual class method declarations. - * Sometimes derived classes override methods that need to be called by their - * overridden counterparts. This marker indicates that the marked method must - * be called by the method that it overrides. - */ -#ifdef MOZ_CLANG_PLUGIN -# define MOZ_MUST_OVERRIDE __attribute__((annotate("moz_must_override"))) -# define MOZ_STACK_CLASS __attribute__((annotate("moz_stack_class"))) -# define MOZ_NONHEAP_CLASS __attribute__((annotate("moz_nonheap_class"))) -# define MOZ_HEAP_CLASS __attribute__((annotate("moz_heap_class"))) -# define MOZ_NON_TEMPORARY_CLASS __attribute__((annotate("moz_non_temporary_class"))) -# define MOZ_TRIVIAL_CTOR_DTOR __attribute__((annotate("moz_trivial_ctor_dtor"))) -# ifdef DEBUG - /* in debug builds, these classes do have non-trivial constructors. */ -# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS __attribute__((annotate("moz_global_class"))) -# else -# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS __attribute__((annotate("moz_global_class"))) \ - MOZ_TRIVIAL_CTOR_DTOR -# endif -# define MOZ_IMPLICIT __attribute__((annotate("moz_implicit"))) -# define MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT __attribute__((annotate("moz_no_arith_expr_in_arg"))) -# define MOZ_OWNING_REF __attribute__((annotate("moz_strong_ref"))) -# define MOZ_NON_OWNING_REF __attribute__((annotate("moz_weak_ref"))) -# define MOZ_UNSAFE_REF(reason) __attribute__((annotate("moz_weak_ref"))) -# define MOZ_NO_ADDREF_RELEASE_ON_RETURN __attribute__((annotate("moz_no_addref_release_on_return"))) -# define MOZ_MUST_USE_TYPE __attribute__((annotate("moz_must_use_type"))) -# define MOZ_NEEDS_NO_VTABLE_TYPE __attribute__((annotate("moz_needs_no_vtable_type"))) -# define MOZ_NON_MEMMOVABLE __attribute__((annotate("moz_non_memmovable"))) -# define MOZ_NEEDS_MEMMOVABLE_TYPE __attribute__((annotate("moz_needs_memmovable_type"))) -# define MOZ_NEEDS_MEMMOVABLE_MEMBERS __attribute__((annotate("moz_needs_memmovable_members"))) -# define MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS \ - __attribute__((annotate("moz_inherit_type_annotations_from_template_args"))) -# define MOZ_NON_AUTOABLE __attribute__((annotate("moz_non_autoable"))) -# define MOZ_INIT_OUTSIDE_CTOR \ - __attribute__((annotate("moz_ignore_ctor_initialization"))) -# define MOZ_IS_CLASS_INIT \ - __attribute__((annotate("moz_is_class_init"))) -# define MOZ_NON_PARAM \ - __attribute__((annotate("moz_non_param"))) -# define MOZ_REQUIRED_BASE_METHOD \ - __attribute__((annotate("moz_required_base_method"))) -/* - * It turns out that clang doesn't like void func() __attribute__ {} without a - * warning, so use pragmas to disable the warning. This code won't work on GCC - * anyways, so the warning is safe to ignore. - */ -# define MOZ_HEAP_ALLOCATOR \ - _Pragma("clang diagnostic push") \ - _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ - __attribute__((annotate("moz_heap_allocator"))) \ - _Pragma("clang diagnostic pop") -#else -# define MOZ_MUST_OVERRIDE /* nothing */ -# define MOZ_STACK_CLASS /* nothing */ -# define MOZ_NONHEAP_CLASS /* nothing */ -# define MOZ_HEAP_CLASS /* nothing */ -# define MOZ_NON_TEMPORARY_CLASS /* nothing */ -# define MOZ_TRIVIAL_CTOR_DTOR /* nothing */ -# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS /* nothing */ -# define MOZ_IMPLICIT /* nothing */ -# define MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT /* nothing */ -# define MOZ_HEAP_ALLOCATOR /* nothing */ -# define MOZ_OWNING_REF /* nothing */ -# define MOZ_NON_OWNING_REF /* nothing */ -# define MOZ_UNSAFE_REF(reason) /* nothing */ -# define MOZ_NO_ADDREF_RELEASE_ON_RETURN /* nothing */ -# define MOZ_MUST_USE_TYPE /* nothing */ -# define MOZ_NEEDS_NO_VTABLE_TYPE /* nothing */ -# define MOZ_NON_MEMMOVABLE /* nothing */ -# define MOZ_NEEDS_MEMMOVABLE_TYPE /* nothing */ -# define MOZ_NEEDS_MEMMOVABLE_MEMBERS /* nothing */ -# define MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS /* nothing */ -# define MOZ_INIT_OUTSIDE_CTOR /* nothing */ -# define MOZ_IS_CLASS_INIT /* nothing */ -# define MOZ_NON_PARAM /* nothing */ -# define MOZ_NON_AUTOABLE /* nothing */ -# define MOZ_REQUIRED_BASE_METHOD /* nothing */ -#endif /* MOZ_CLANG_PLUGIN */ - -#define MOZ_RAII MOZ_NON_TEMPORARY_CLASS MOZ_STACK_CLASS - -/* - * MOZ_HAVE_REF_QUALIFIERS is defined for compilers that support C++11's rvalue - * qualifier, "&&". - */ -#if defined(_MSC_VER) && _MSC_VER >= 1900 -# define MOZ_HAVE_REF_QUALIFIERS -#elif defined(__clang__) -// All supported Clang versions -# define MOZ_HAVE_REF_QUALIFIERS -#elif defined(__GNUC__) -# include "mozilla/Compiler.h" -# if MOZ_GCC_VERSION_AT_LEAST(4, 8, 1) -# define MOZ_HAVE_REF_QUALIFIERS -# endif -#endif - -#endif /* __cplusplus */ - -/** - * Printf style formats. MOZ_FORMAT_PRINTF can be used to annotate a - * function or method that is "printf-like"; this will let (some) - * compilers check that the arguments match the template string. - * - * This macro takes two arguments. The first argument is the argument - * number of the template string. The second argument is the argument - * number of the '...' argument holding the arguments. - * - * Argument numbers start at 1. Note that the implicit "this" - * argument of a non-static member function counts as an argument. - * - * So, for a simple case like: - * void print_something (int whatever, const char *fmt, ...); - * The corresponding annotation would be - * MOZ_FORMAT_PRINTF(2, 3) - * However, if "print_something" were a non-static member function, - * then the annotation would be: - * MOZ_FORMAT_PRINTF(3, 4) - * - * Note that the checking is limited to standards-conforming - * printf-likes, and in particular this should not be used for - * PR_snprintf and friends, which are "printf-like" but which assign - * different meanings to the various formats. - */ -#ifdef __GNUC__ -#define MOZ_FORMAT_PRINTF(stringIndex, firstToCheck) \ - __attribute__ ((format (printf, stringIndex, firstToCheck))) -#else -#define MOZ_FORMAT_PRINTF(stringIndex, firstToCheck) -#endif - -#endif /* mozilla_Attributes_h */ diff --git a/mac/include/spidermonkey/mozilla/BinarySearch.h b/mac/include/spidermonkey/mozilla/BinarySearch.h deleted file mode 100644 index 1bbe0566..00000000 --- a/mac/include/spidermonkey/mozilla/BinarySearch.h +++ /dev/null @@ -1,139 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_BinarySearch_h -#define mozilla_BinarySearch_h - -#include "mozilla/Assertions.h" - -#include - -namespace mozilla { - -/* - * The BinarySearch() algorithm searches the given container |aContainer| over - * the sorted index range [aBegin, aEnd) for an index |i| where - * |aContainer[i] == aTarget|. - * If such an index |i| is found, BinarySearch returns |true| and the index is - * returned via the outparam |aMatchOrInsertionPoint|. If no index is found, - * BinarySearch returns |false| and the outparam returns the first index in - * [aBegin, aEnd] where |aTarget| can be inserted to maintain sorted order. - * - * Example: - * - * Vector sortedInts = ... - * - * size_t match; - * if (BinarySearch(sortedInts, 0, sortedInts.length(), 13, &match)) { - * printf("found 13 at %lu\n", match); - * } - * - * The BinarySearchIf() version behaves similarly, but takes |aComparator|, a - * functor to compare the values with, instead of a value to find. - * That functor should take one argument - the value to compare - and return an - * |int| with the comparison result: - * - * * 0, if the argument is equal to, - * * less than 0, if the argument is greater than, - * * greater than 0, if the argument is less than - * - * the value. - * - * Example: - * - * struct Comparator { - * int operator()(int aVal) const { - * if (mTarget < aVal) { return -1; } - * if (mTarget > aVal) { return 1; } - * return 0; - * } - * explicit Comparator(int aTarget) : mTarget(aTarget) {} - * const int mTarget; - * }; - * - * Vector sortedInts = ... - * - * size_t match; - * if (BinarySearchIf(sortedInts, 0, sortedInts.length(), Comparator(13), &match)) { - * printf("found 13 at %lu\n", match); - * } - * - */ - -template -bool -BinarySearchIf(const Container& aContainer, size_t aBegin, size_t aEnd, - const Comparator& aCompare, size_t* aMatchOrInsertionPoint) -{ - MOZ_ASSERT(aBegin <= aEnd); - - size_t low = aBegin; - size_t high = aEnd; - while (high != low) { - size_t middle = low + (high - low) / 2; - - // Allow any intermediate type so long as it provides a suitable ordering - // relation. - const int result = aCompare(aContainer[middle]); - - if (result == 0) { - *aMatchOrInsertionPoint = middle; - return true; - } - - if (result < 0) { - high = middle; - } else { - low = middle + 1; - } - } - - *aMatchOrInsertionPoint = low; - return false; -} - -namespace detail { - -template -class BinarySearchDefaultComparator -{ -public: - explicit BinarySearchDefaultComparator(const T& aTarget) - : mTarget(aTarget) - {} - - template - int operator()(const U& aVal) const { - if (mTarget == aVal) { - return 0; - } - - if (mTarget < aVal) { - return -1; - } - - return 1; - } - -private: - const T& mTarget; -}; - -} // namespace detail - -template -bool -BinarySearch(const Container& aContainer, size_t aBegin, size_t aEnd, - T aTarget, size_t* aMatchOrInsertionPoint) -{ - return BinarySearchIf(aContainer, aBegin, aEnd, - detail::BinarySearchDefaultComparator(aTarget), - aMatchOrInsertionPoint); -} - -} // namespace mozilla - -#endif // mozilla_BinarySearch_h diff --git a/mac/include/spidermonkey/mozilla/BloomFilter.h b/mac/include/spidermonkey/mozilla/BloomFilter.h deleted file mode 100644 index 6757e411..00000000 --- a/mac/include/spidermonkey/mozilla/BloomFilter.h +++ /dev/null @@ -1,256 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * A counting Bloom filter implementation. This allows consumers to - * do fast probabilistic "is item X in set Y?" testing which will - * never answer "no" when the correct answer is "yes" (but might - * incorrectly answer "yes" when the correct answer is "no"). - */ - -#ifndef mozilla_BloomFilter_h -#define mozilla_BloomFilter_h - -#include "mozilla/Assertions.h" -#include "mozilla/Likely.h" - -#include -#include - -namespace mozilla { - -/* - * This class implements a counting Bloom filter as described at - * , with - * 8-bit counters. This allows quick probabilistic answers to the - * question "is object X in set Y?" where the contents of Y might not - * be time-invariant. The probabilistic nature of the test means that - * sometimes the answer will be "yes" when it should be "no". If the - * answer is "no", then X is guaranteed not to be in Y. - * - * The filter is parametrized on KeySize, which is the size of the key - * generated by each of hash functions used by the filter, in bits, - * and the type of object T being added and removed. T must implement - * a |uint32_t hash() const| method which returns a uint32_t hash key - * that will be used to generate the two separate hash functions for - * the Bloom filter. This hash key MUST be well-distributed for good - * results! KeySize is not allowed to be larger than 16. - * - * The filter uses exactly 2**KeySize bytes of memory. From now on we - * will refer to the memory used by the filter as M. - * - * The expected rate of incorrect "yes" answers depends on M and on - * the number N of objects in set Y. As long as N is small compared - * to M, the rate of such answers is expected to be approximately - * 4*(N/M)**2 for this filter. In practice, if Y has a few hundred - * elements then using a KeySize of 12 gives a reasonably low - * incorrect answer rate. A KeySize of 12 has the additional benefit - * of using exactly one page for the filter in typical hardware - * configurations. - */ - -template -class BloomFilter -{ - /* - * A counting Bloom filter with 8-bit counters. For now we assume - * that having two hash functions is enough, but we may revisit that - * decision later. - * - * The filter uses an array with 2**KeySize entries. - * - * Assuming a well-distributed hash function, a Bloom filter with - * array size M containing N elements and - * using k hash function has expected false positive rate exactly - * - * $ (1 - (1 - 1/M)^{kN})^k $ - * - * because each array slot has a - * - * $ (1 - 1/M)^{kN} $ - * - * chance of being 0, and the expected false positive rate is the - * probability that all of the k hash functions will hit a nonzero - * slot. - * - * For reasonable assumptions (M large, kN large, which should both - * hold if we're worried about false positives) about M and kN this - * becomes approximately - * - * $$ (1 - \exp(-kN/M))^k $$ - * - * For our special case of k == 2, that's $(1 - \exp(-2N/M))^2$, - * or in other words - * - * $$ N/M = -0.5 * \ln(1 - \sqrt(r)) $$ - * - * where r is the false positive rate. This can be used to compute - * the desired KeySize for a given load N and false positive rate r. - * - * If N/M is assumed small, then the false positive rate can - * further be approximated as 4*N^2/M^2. So increasing KeySize by - * 1, which doubles M, reduces the false positive rate by about a - * factor of 4, and a false positive rate of 1% corresponds to - * about M/N == 20. - * - * What this means in practice is that for a few hundred keys using a - * KeySize of 12 gives false positive rates on the order of 0.25-4%. - * - * Similarly, using a KeySize of 10 would lead to a 4% false - * positive rate for N == 100 and to quite bad false positive - * rates for larger N. - */ -public: - BloomFilter() - { - static_assert(KeySize <= kKeyShift, "KeySize too big"); - - // Should we have a custom operator new using calloc instead and - // require that we're allocated via the operator? - clear(); - } - - /* - * Clear the filter. This should be done before reusing it, because - * just removing all items doesn't clear counters that hit the upper - * bound. - */ - void clear(); - - /* - * Add an item to the filter. - */ - void add(const T* aValue); - - /* - * Remove an item from the filter. - */ - void remove(const T* aValue); - - /* - * Check whether the filter might contain an item. This can - * sometimes return true even if the item is not in the filter, - * but will never return false for items that are actually in the - * filter. - */ - bool mightContain(const T* aValue) const; - - /* - * Methods for add/remove/contain when we already have a hash computed - */ - void add(uint32_t aHash); - void remove(uint32_t aHash); - bool mightContain(uint32_t aHash) const; - -private: - static const size_t kArraySize = (1 << KeySize); - static const uint32_t kKeyMask = (1 << KeySize) - 1; - static const uint32_t kKeyShift = 16; - - static uint32_t hash1(uint32_t aHash) - { - return aHash & kKeyMask; - } - static uint32_t hash2(uint32_t aHash) - { - return (aHash >> kKeyShift) & kKeyMask; - } - - uint8_t& firstSlot(uint32_t aHash) - { - return mCounters[hash1(aHash)]; - } - uint8_t& secondSlot(uint32_t aHash) - { - return mCounters[hash2(aHash)]; - } - - const uint8_t& firstSlot(uint32_t aHash) const - { - return mCounters[hash1(aHash)]; - } - const uint8_t& secondSlot(uint32_t aHash) const - { - return mCounters[hash2(aHash)]; - } - - static bool full(const uint8_t& aSlot) { return aSlot == UINT8_MAX; } - - uint8_t mCounters[kArraySize]; -}; - -template -inline void -BloomFilter::clear() -{ - memset(mCounters, 0, kArraySize); -} - -template -inline void -BloomFilter::add(uint32_t aHash) -{ - uint8_t& slot1 = firstSlot(aHash); - if (MOZ_LIKELY(!full(slot1))) { - ++slot1; - } - uint8_t& slot2 = secondSlot(aHash); - if (MOZ_LIKELY(!full(slot2))) { - ++slot2; - } -} - -template -MOZ_ALWAYS_INLINE void -BloomFilter::add(const T* aValue) -{ - uint32_t hash = aValue->hash(); - return add(hash); -} - -template -inline void -BloomFilter::remove(uint32_t aHash) -{ - // If the slots are full, we don't know whether we bumped them to be - // there when we added or not, so just leave them full. - uint8_t& slot1 = firstSlot(aHash); - if (MOZ_LIKELY(!full(slot1))) { - --slot1; - } - uint8_t& slot2 = secondSlot(aHash); - if (MOZ_LIKELY(!full(slot2))) { - --slot2; - } -} - -template -MOZ_ALWAYS_INLINE void -BloomFilter::remove(const T* aValue) -{ - uint32_t hash = aValue->hash(); - remove(hash); -} - -template -MOZ_ALWAYS_INLINE bool -BloomFilter::mightContain(uint32_t aHash) const -{ - // Check that all the slots for this hash contain something - return firstSlot(aHash) && secondSlot(aHash); -} - -template -MOZ_ALWAYS_INLINE bool -BloomFilter::mightContain(const T* aValue) const -{ - uint32_t hash = aValue->hash(); - return mightContain(hash); -} - -} // namespace mozilla - -#endif /* mozilla_BloomFilter_h */ diff --git a/mac/include/spidermonkey/mozilla/BufferList.h b/mac/include/spidermonkey/mozilla/BufferList.h deleted file mode 100644 index 42aea12d..00000000 --- a/mac/include/spidermonkey/mozilla/BufferList.h +++ /dev/null @@ -1,517 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_BufferList_h -#define mozilla_BufferList_h - -#include -#include "mozilla/AllocPolicy.h" -#include "mozilla/Move.h" -#include "mozilla/ScopeExit.h" -#include "mozilla/Types.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Vector.h" -#include - -// BufferList represents a sequence of buffers of data. A BufferList can choose -// to own its buffers or not. The class handles writing to the buffers, -// iterating over them, and reading data out. Unlike SegmentedVector, the -// buffers may be of unequal size. Like SegmentedVector, BufferList is a nice -// way to avoid large contiguous allocations (which can trigger OOMs). - -namespace mozilla { - -template -class BufferList : private AllocPolicy -{ - // Each buffer in a BufferList has a size and a capacity. The first mSize - // bytes are initialized and the remaining |mCapacity - mSize| bytes are free. - struct Segment - { - char* mData; - size_t mSize; - size_t mCapacity; - - Segment(char* aData, size_t aSize, size_t aCapacity) - : mData(aData), - mSize(aSize), - mCapacity(aCapacity) - { - } - - Segment(const Segment&) = delete; - Segment& operator=(const Segment&) = delete; - - Segment(Segment&&) = default; - Segment& operator=(Segment&&) = default; - - char* Start() const { return mData; } - char* End() const { return mData + mSize; } - }; - - template - friend class BufferList; - - public: - // For the convenience of callers, all segments are required to be a multiple - // of 8 bytes in capacity. Also, every buffer except the last one is required - // to be full (i.e., size == capacity). Therefore, a byte at offset N within - // the BufferList and stored in memory at an address A will satisfy - // (N % Align == A % Align) if Align == 2, 4, or 8. - static const size_t kSegmentAlignment = 8; - - // Allocate a BufferList. The BufferList will free all its buffers when it is - // destroyed. An initial buffer of size aInitialSize and capacity - // aInitialCapacity is allocated automatically. This data will be contiguous - // an can be accessed via |Start()|. Subsequent buffers will be allocated with - // capacity aStandardCapacity. - BufferList(size_t aInitialSize, - size_t aInitialCapacity, - size_t aStandardCapacity, - AllocPolicy aAP = AllocPolicy()) - : AllocPolicy(aAP), - mOwning(true), - mSegments(aAP), - mSize(0), - mStandardCapacity(aStandardCapacity) - { - MOZ_ASSERT(aInitialCapacity % kSegmentAlignment == 0); - MOZ_ASSERT(aStandardCapacity % kSegmentAlignment == 0); - - if (aInitialCapacity) { - AllocateSegment(aInitialSize, aInitialCapacity); - } - } - - BufferList(const BufferList& aOther) = delete; - - BufferList(BufferList&& aOther) - : mOwning(aOther.mOwning), - mSegments(Move(aOther.mSegments)), - mSize(aOther.mSize), - mStandardCapacity(aOther.mStandardCapacity) - { - aOther.mSegments.clear(); - aOther.mSize = 0; - } - - BufferList& operator=(const BufferList& aOther) = delete; - - BufferList& operator=(BufferList&& aOther) - { - Clear(); - - mOwning = aOther.mOwning; - mSegments = Move(aOther.mSegments); - mSize = aOther.mSize; - aOther.mSegments.clear(); - aOther.mSize = 0; - return *this; - } - - ~BufferList() { Clear(); } - - // Returns the sum of the sizes of all the buffers. - size_t Size() const { return mSize; } - - void Clear() - { - if (mOwning) { - for (Segment& segment : mSegments) { - this->free_(segment.mData); - } - } - mSegments.clear(); - - mSize = 0; - } - - // Iterates over bytes in the segments. You can advance it by as many bytes as - // you choose. - class IterImpl - { - // Invariants: - // (0) mSegment <= bufferList.mSegments.size() - // (1) mData <= mDataEnd - // (2) If mSegment is not the last segment, mData < mDataEnd - uintptr_t mSegment; - char* mData; - char* mDataEnd; - - friend class BufferList; - - public: - explicit IterImpl(const BufferList& aBuffers) - : mSegment(0), - mData(nullptr), - mDataEnd(nullptr) - { - if (!aBuffers.mSegments.empty()) { - mData = aBuffers.mSegments[0].Start(); - mDataEnd = aBuffers.mSegments[0].End(); - } - } - - // Returns a pointer to the raw data. It is valid to access up to - // RemainingInSegment bytes of this buffer. - char* Data() const - { - MOZ_RELEASE_ASSERT(!Done()); - return mData; - } - - // Returns true if the memory in the range [Data(), Data() + aBytes) is all - // part of one contiguous buffer. - bool HasRoomFor(size_t aBytes) const - { - MOZ_RELEASE_ASSERT(mData <= mDataEnd); - return size_t(mDataEnd - mData) >= aBytes; - } - - // Returns the maximum value aBytes for which HasRoomFor(aBytes) will be - // true. - size_t RemainingInSegment() const - { - MOZ_RELEASE_ASSERT(mData <= mDataEnd); - return mDataEnd - mData; - } - - // Advances the iterator by aBytes bytes. aBytes must be less than - // RemainingInSegment(). If advancing by aBytes takes the iterator to the - // end of a buffer, it will be moved to the beginning of the next buffer - // unless it is the last buffer. - void Advance(const BufferList& aBuffers, size_t aBytes) - { - const Segment& segment = aBuffers.mSegments[mSegment]; - MOZ_RELEASE_ASSERT(segment.Start() <= mData); - MOZ_RELEASE_ASSERT(mData <= mDataEnd); - MOZ_RELEASE_ASSERT(mDataEnd == segment.End()); - - MOZ_RELEASE_ASSERT(HasRoomFor(aBytes)); - mData += aBytes; - - if (mData == mDataEnd && mSegment + 1 < aBuffers.mSegments.length()) { - mSegment++; - const Segment& nextSegment = aBuffers.mSegments[mSegment]; - mData = nextSegment.Start(); - mDataEnd = nextSegment.End(); - MOZ_RELEASE_ASSERT(mData < mDataEnd); - } - } - - // Advance the iterator by aBytes, possibly crossing segments. This function - // returns false if it runs out of buffers to advance through. Otherwise it - // returns true. - bool AdvanceAcrossSegments(const BufferList& aBuffers, size_t aBytes) - { - size_t bytes = aBytes; - while (bytes) { - size_t toAdvance = std::min(bytes, RemainingInSegment()); - if (!toAdvance) { - return false; - } - Advance(aBuffers, toAdvance); - bytes -= toAdvance; - } - return true; - } - - // Returns true when the iterator reaches the end of the BufferList. - bool Done() const - { - return mData == mDataEnd; - } - - private: - - // Count the bytes we would need to advance in order to reach aTarget. - size_t BytesUntil(const BufferList& aBuffers, const IterImpl& aTarget) const { - size_t offset = 0; - - MOZ_ASSERT(aTarget.IsIn(aBuffers)); - - char* data = mData; - for (uintptr_t segment = mSegment; segment < aTarget.mSegment; segment++) { - offset += aBuffers.mSegments[segment].End() - data; - data = aBuffers.mSegments[segment].mData; - } - - MOZ_RELEASE_ASSERT(IsIn(aBuffers)); - MOZ_RELEASE_ASSERT(aTarget.mData >= data); - - offset += aTarget.mData - data; - return offset; - } - - bool IsIn(const BufferList& aBuffers) const { - return mSegment < aBuffers.mSegments.length() && - mData >= aBuffers.mSegments[mSegment].mData && - mData < aBuffers.mSegments[mSegment].End(); - } - }; - - // Special convenience method that returns Iter().Data(). - char* Start() { return mSegments[0].mData; } - const char* Start() const { return mSegments[0].mData; } - - IterImpl Iter() const { return IterImpl(*this); } - - // Copies aSize bytes from aData into the BufferList. The storage for these - // bytes may be split across multiple buffers. Size() is increased by aSize. - inline bool WriteBytes(const char* aData, size_t aSize); - - // Copies possibly non-contiguous byte range starting at aIter into - // aData. aIter is advanced by aSize bytes. Returns false if it runs out of - // data before aSize. - inline bool ReadBytes(IterImpl& aIter, char* aData, size_t aSize) const; - - // Return a new BufferList that shares storage with this BufferList. The new - // BufferList is read-only. It allows iteration over aSize bytes starting at - // aIter. Borrow can fail, in which case *aSuccess will be false upon - // return. The borrowed BufferList can use a different AllocPolicy than the - // original one. However, it is not responsible for freeing buffers, so the - // AllocPolicy is only used for the buffer vector. - template - BufferList Borrow(IterImpl& aIter, size_t aSize, bool* aSuccess, - BorrowingAllocPolicy aAP = BorrowingAllocPolicy()) const; - - // Return a new BufferList and move storage from this BufferList to it. The - // new BufferList owns the buffers. Move can fail, in which case *aSuccess - // will be false upon return. The new BufferList can use a different - // AllocPolicy than the original one. The new OtherAllocPolicy is responsible - // for freeing buffers, so the OtherAllocPolicy must use freeing method - // compatible to the original one. - template - BufferList MoveFallible(bool* aSuccess, OtherAllocPolicy aAP = OtherAllocPolicy()); - - // Return a new BufferList that adopts the byte range starting at Iter so that - // range [aIter, aIter + aSize) is transplanted to the returned BufferList. - // Contents of the buffer before aIter + aSize is left undefined. - // Extract can fail, in which case *aSuccess will be false upon return. The - // moved buffers are erased from the original BufferList. In case of extract - // fails, the original BufferList is intact. All other iterators except aIter - // are invalidated. - // This method requires aIter and aSize to be 8-byte aligned. - BufferList Extract(IterImpl& aIter, size_t aSize, bool* aSuccess); - - // Return the number of bytes from 'start' to 'end', two iterators within - // this BufferList. - size_t RangeLength(const IterImpl& start, const IterImpl& end) const { - MOZ_ASSERT(start.IsIn(*this) && end.IsIn(*this)); - return start.BytesUntil(*this, end); - } - -private: - explicit BufferList(AllocPolicy aAP) - : AllocPolicy(aAP), - mOwning(false), - mSize(0), - mStandardCapacity(0) - { - } - - void* AllocateSegment(size_t aSize, size_t aCapacity) - { - MOZ_RELEASE_ASSERT(mOwning); - - char* data = this->template pod_malloc(aCapacity); - if (!data) { - return nullptr; - } - if (!mSegments.append(Segment(data, aSize, aCapacity))) { - this->free_(data); - return nullptr; - } - mSize += aSize; - return data; - } - - bool mOwning; - Vector mSegments; - size_t mSize; - size_t mStandardCapacity; -}; - -template -bool -BufferList::WriteBytes(const char* aData, size_t aSize) -{ - MOZ_RELEASE_ASSERT(mOwning); - MOZ_RELEASE_ASSERT(mStandardCapacity); - - size_t copied = 0; - size_t remaining = aSize; - - if (!mSegments.empty()) { - Segment& lastSegment = mSegments.back(); - - size_t toCopy = std::min(aSize, lastSegment.mCapacity - lastSegment.mSize); - memcpy(lastSegment.mData + lastSegment.mSize, aData, toCopy); - lastSegment.mSize += toCopy; - mSize += toCopy; - - copied += toCopy; - remaining -= toCopy; - } - - while (remaining) { - size_t toCopy = std::min(remaining, mStandardCapacity); - - void* data = AllocateSegment(toCopy, mStandardCapacity); - if (!data) { - return false; - } - memcpy(data, aData + copied, toCopy); - - copied += toCopy; - remaining -= toCopy; - } - - return true; -} - -template -bool -BufferList::ReadBytes(IterImpl& aIter, char* aData, size_t aSize) const -{ - size_t copied = 0; - size_t remaining = aSize; - while (remaining) { - size_t toCopy = std::min(aIter.RemainingInSegment(), remaining); - if (!toCopy) { - // We've run out of data in the last segment. - return false; - } - memcpy(aData + copied, aIter.Data(), toCopy); - copied += toCopy; - remaining -= toCopy; - - aIter.Advance(*this, toCopy); - } - - return true; -} - -template template -BufferList -BufferList::Borrow(IterImpl& aIter, size_t aSize, bool* aSuccess, - BorrowingAllocPolicy aAP) const -{ - BufferList result(aAP); - - size_t size = aSize; - while (size) { - size_t toAdvance = std::min(size, aIter.RemainingInSegment()); - - if (!toAdvance || !result.mSegments.append(typename BufferList::Segment(aIter.mData, toAdvance, toAdvance))) { - *aSuccess = false; - return result; - } - aIter.Advance(*this, toAdvance); - size -= toAdvance; - } - - result.mSize = aSize; - *aSuccess = true; - return result; -} - -template template -BufferList -BufferList::MoveFallible(bool* aSuccess, OtherAllocPolicy aAP) -{ - BufferList result(0, 0, mStandardCapacity, aAP); - - IterImpl iter = Iter(); - while (!iter.Done()) { - size_t toAdvance = iter.RemainingInSegment(); - - if (!toAdvance || !result.mSegments.append(typename BufferList::Segment(iter.mData, toAdvance, toAdvance))) { - *aSuccess = false; - result.mSegments.clear(); - return result; - } - iter.Advance(*this, toAdvance); - } - - result.mSize = mSize; - mSegments.clear(); - mSize = 0; - *aSuccess = true; - return result; -} - -template -BufferList -BufferList::Extract(IterImpl& aIter, size_t aSize, bool* aSuccess) -{ - MOZ_RELEASE_ASSERT(aSize); - MOZ_RELEASE_ASSERT(mOwning); - MOZ_ASSERT(aSize % kSegmentAlignment == 0); - MOZ_ASSERT(intptr_t(aIter.mData) % kSegmentAlignment == 0); - - IterImpl iter = aIter; - size_t size = aSize; - size_t toCopy = std::min(size, aIter.RemainingInSegment()); - MOZ_ASSERT(toCopy % kSegmentAlignment == 0); - - BufferList result(0, toCopy, mStandardCapacity); - BufferList error(0, 0, mStandardCapacity); - - // Copy the head - if (!result.WriteBytes(aIter.mData, toCopy)) { - *aSuccess = false; - return error; - } - iter.Advance(*this, toCopy); - size -= toCopy; - - // Move segments to result - auto resultGuard = MakeScopeExit([&] { - *aSuccess = false; - result.mSegments.erase(result.mSegments.begin()+1, result.mSegments.end()); - }); - - size_t movedSize = 0; - uintptr_t toRemoveStart = iter.mSegment; - uintptr_t toRemoveEnd = iter.mSegment; - while (!iter.Done() && - !iter.HasRoomFor(size)) { - if (!result.mSegments.append(Segment(mSegments[iter.mSegment].mData, - mSegments[iter.mSegment].mSize, - mSegments[iter.mSegment].mCapacity))) { - return error; - } - movedSize += iter.RemainingInSegment(); - size -= iter.RemainingInSegment(); - toRemoveEnd++; - iter.Advance(*this, iter.RemainingInSegment()); - } - - if (size) { - if (!iter.HasRoomFor(size) || - !result.WriteBytes(iter.Data(), size)) { - return error; - } - iter.Advance(*this, size); - } - - mSegments.erase(mSegments.begin() + toRemoveStart, mSegments.begin() + toRemoveEnd); - mSize -= movedSize; - aIter.mSegment = iter.mSegment - (toRemoveEnd - toRemoveStart); - aIter.mData = iter.mData; - aIter.mDataEnd = iter.mDataEnd; - MOZ_ASSERT(aIter.mDataEnd == mSegments[aIter.mSegment].End()); - result.mSize = aSize; - - resultGuard.release(); - *aSuccess = true; - return result; -} - -} // namespace mozilla - -#endif /* mozilla_BufferList_h */ diff --git a/mac/include/spidermonkey/mozilla/Casting.h b/mac/include/spidermonkey/mozilla/Casting.h deleted file mode 100644 index a7d0fb50..00000000 --- a/mac/include/spidermonkey/mozilla/Casting.h +++ /dev/null @@ -1,243 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Cast operations to supplement the built-in casting operations. */ - -#ifndef mozilla_Casting_h -#define mozilla_Casting_h - -#include "mozilla/Assertions.h" -#include "mozilla/TypeTraits.h" - -#include - -namespace mozilla { - -/** - * Sets the outparam value of type |To| with the same underlying bit pattern of - * |aFrom|. - * - * |To| and |From| must be types of the same size; be careful of cross-platform - * size differences, or this might fail to compile on some but not all - * platforms. - * - * There is also a variant that returns the value directly. In most cases, the - * two variants should be identical. However, in the specific case of x86 - * chips, the behavior differs: returning floating-point values directly is done - * through the x87 stack, and x87 loads and stores turn signaling NaNs into - * quiet NaNs... silently. Returning floating-point values via outparam, - * however, is done entirely within the SSE registers when SSE2 floating-point - * is enabled in the compiler, which has semantics-preserving behavior you would - * expect. - * - * If preserving the distinction between signaling NaNs and quiet NaNs is - * important to you, you should use the outparam version. In all other cases, - * you should use the direct return version. - */ -template -inline void -BitwiseCast(const From aFrom, To* aResult) -{ - static_assert(sizeof(From) == sizeof(To), - "To and From must have the same size"); - union - { - From mFrom; - To mTo; - } u; - u.mFrom = aFrom; - *aResult = u.mTo; -} - -template -inline To -BitwiseCast(const From aFrom) -{ - To temp; - BitwiseCast(aFrom, &temp); - return temp; -} - -namespace detail { - -enum ToSignedness { ToIsSigned, ToIsUnsigned }; -enum FromSignedness { FromIsSigned, FromIsUnsigned }; - -template::value ? FromIsSigned : FromIsUnsigned, - ToSignedness = IsSigned::value ? ToIsSigned : ToIsUnsigned> -struct BoundsCheckImpl; - -// Implicit conversions on operands to binary operations make this all a bit -// hard to verify. Attempt to ease the pain below by *only* comparing values -// that are obviously the same type (and will undergo no further conversions), -// even when it's not strictly necessary, for explicitness. - -enum UUComparison { FromIsBigger, FromIsNotBigger }; - -// Unsigned-to-unsigned range check - -template sizeof(To)) - ? FromIsBigger - : FromIsNotBigger> -struct UnsignedUnsignedCheck; - -template -struct UnsignedUnsignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - return aFrom <= From(To(-1)); - } -}; - -template -struct UnsignedUnsignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - return true; - } -}; - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - return UnsignedUnsignedCheck::checkBounds(aFrom); - } -}; - -// Signed-to-unsigned range check - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - if (aFrom < 0) { - return false; - } - if (sizeof(To) >= sizeof(From)) { - return true; - } - return aFrom <= From(To(-1)); - } -}; - -// Unsigned-to-signed range check - -enum USComparison { FromIsSmaller, FromIsNotSmaller }; - -template -struct UnsignedSignedCheck; - -template -struct UnsignedSignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - return true; - } -}; - -template -struct UnsignedSignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); - return aFrom <= From(MaxValue); - } -}; - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - return UnsignedSignedCheck::checkBounds(aFrom); - } -}; - -// Signed-to-signed range check - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - if (sizeof(From) <= sizeof(To)) { - return true; - } - const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); - const To MinValue = -MaxValue - To(1); - return From(MinValue) <= aFrom && - From(aFrom) <= From(MaxValue); - } -}; - -template::value && - IsIntegral::value> -class BoundsChecker; - -template -class BoundsChecker -{ -public: - static bool checkBounds(const From aFrom) { return true; } -}; - -template -class BoundsChecker -{ -public: - static bool checkBounds(const From aFrom) - { - return BoundsCheckImpl::checkBounds(aFrom); - } -}; - -template -inline bool -IsInBounds(const From aFrom) -{ - return BoundsChecker::checkBounds(aFrom); -} - -} // namespace detail - -/** - * Cast a value of integral type |From| to a value of integral type |To|, - * asserting that the cast will be a safe cast per C++ (that is, that |to| is in - * the range of values permitted for the type |From|). - */ -template -inline To -AssertedCast(const From aFrom) -{ - MOZ_ASSERT((detail::IsInBounds(aFrom))); - return static_cast(aFrom); -} - -} // namespace mozilla - -#endif /* mozilla_Casting_h */ diff --git a/mac/include/spidermonkey/mozilla/ChaosMode.h b/mac/include/spidermonkey/mozilla/ChaosMode.h deleted file mode 100644 index 94833c39..00000000 --- a/mac/include/spidermonkey/mozilla/ChaosMode.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_ChaosMode_h -#define mozilla_ChaosMode_h - -#include "mozilla/Atomics.h" -#include "mozilla/EnumSet.h" - -#include -#include - -namespace mozilla { - -enum ChaosFeature { - None = 0x0, - // Altering thread scheduling. - ThreadScheduling = 0x1, - // Altering network request scheduling. - NetworkScheduling = 0x2, - // Altering timer scheduling. - TimerScheduling = 0x4, - // Read and write less-than-requested amounts. - IOAmounts = 0x8, - // Iterate over hash tables in random order. - HashTableIteration = 0x10, - // Randomly refuse to use cached version of image (when allowed by spec). - ImageCache = 0x20, - Any = 0xffffffff, -}; - -namespace detail { -extern MFBT_DATA Atomic gChaosModeCounter; -extern MFBT_DATA ChaosFeature gChaosFeatures; -} // namespace detail - -/** - * When "chaos mode" is activated, code that makes implicitly nondeterministic - * choices is encouraged to make random and extreme choices, to test more - * code paths and uncover bugs. - */ -class ChaosMode -{ -public: - static void SetChaosFeature(ChaosFeature aChaosFeature) - { - detail::gChaosFeatures = aChaosFeature; - } - - static bool isActive(ChaosFeature aFeature) - { - if (detail::gChaosModeCounter > 0) { - return true; - } - return detail::gChaosFeatures & aFeature; - } - - /** - * Increase the chaos mode activation level. An equivalent number of - * calls to leaveChaosMode must be made in order to restore the original - * chaos mode state. If the activation level is nonzero all chaos mode - * features are activated. - */ - static void enterChaosMode() - { - detail::gChaosModeCounter++; - } - - /** - * Decrease the chaos mode activation level. See enterChaosMode(). - */ - static void leaveChaosMode() - { - MOZ_ASSERT(detail::gChaosModeCounter > 0); - detail::gChaosModeCounter--; - } - - /** - * Returns a somewhat (but not uniformly) random uint32_t < aBound. - * Not to be used for anything except ChaosMode, since it's not very random. - */ - static uint32_t randomUint32LessThan(uint32_t aBound) - { - MOZ_ASSERT(aBound != 0); - return uint32_t(rand()) % aBound; - } -}; - -} /* namespace mozilla */ - -#endif /* mozilla_ChaosMode_h */ diff --git a/mac/include/spidermonkey/mozilla/Char16.h b/mac/include/spidermonkey/mozilla/Char16.h deleted file mode 100644 index 3c2f254a..00000000 --- a/mac/include/spidermonkey/mozilla/Char16.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements a UTF-16 character type. */ - -#ifndef mozilla_Char16_h -#define mozilla_Char16_h - -#ifdef __cplusplus - -/* - * C++11 introduces a char16_t type and support for UTF-16 string and character - * literals. C++11's char16_t is a distinct builtin type. Technically, char16_t - * is a 16-bit code unit of a Unicode code point, not a "character". - */ - -#ifdef WIN32 -# define MOZ_USE_CHAR16_WRAPPER -# include - /** - * Win32 API extensively uses wchar_t, which is represented by a separated - * builtin type than char16_t per spec. It's not the case for MSVC prior to - * MSVC 2015, but other compilers follow the spec. We want to mix wchar_t and - * char16_t on Windows builds. This class is supposed to make it easier. It - * stores char16_t const pointer, but provides implicit casts for wchar_t as - * well. On other platforms, we simply use - * |typedef const char16_t* char16ptr_t|. Here, we want to make the class as - * similar to this typedef, including providing some casts that are allowed - * by the typedef. - */ -class char16ptr_t -{ -private: - const char16_t* mPtr; - static_assert(sizeof(char16_t) == sizeof(wchar_t), - "char16_t and wchar_t sizes differ"); - -public: - char16ptr_t(const char16_t* aPtr) : mPtr(aPtr) {} - char16ptr_t(const wchar_t* aPtr) : - mPtr(reinterpret_cast(aPtr)) - {} - - /* Without this, nullptr assignment would be ambiguous. */ - constexpr char16ptr_t(decltype(nullptr)) : mPtr(nullptr) {} - - operator const char16_t*() const - { - return mPtr; - } - operator const wchar_t*() const - { - return reinterpret_cast(mPtr); - } - operator const void*() const - { - return mPtr; - } - operator bool() const - { - return mPtr != nullptr; - } - - /* Explicit cast operators to allow things like (char16_t*)str. */ - explicit operator char16_t*() const - { - return const_cast(mPtr); - } - explicit operator wchar_t*() const - { - return const_cast(static_cast(*this)); - } - explicit operator int() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned int() const - { - return reinterpret_cast(mPtr); - } - explicit operator long() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned long() const - { - return reinterpret_cast(mPtr); - } - explicit operator long long() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned long long() const - { - return reinterpret_cast(mPtr); - } - - /** - * Some Windows API calls accept BYTE* but require that data actually be - * WCHAR*. Supporting this requires explicit operators to support the - * requisite explicit casts. - */ - explicit operator const char*() const - { - return reinterpret_cast(mPtr); - } - explicit operator const unsigned char*() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned char*() const - { - return - const_cast(reinterpret_cast(mPtr)); - } - explicit operator void*() const - { - return const_cast(mPtr); - } - - /* Some operators used on pointers. */ - char16_t operator[](size_t aIndex) const - { - return mPtr[aIndex]; - } - bool operator==(const char16ptr_t& aOther) const - { - return mPtr == aOther.mPtr; - } - bool operator==(decltype(nullptr)) const - { - return mPtr == nullptr; - } - bool operator!=(const char16ptr_t& aOther) const - { - return mPtr != aOther.mPtr; - } - bool operator!=(decltype(nullptr)) const - { - return mPtr != nullptr; - } - char16ptr_t operator+(int aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(unsigned int aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(unsigned long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(long long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(unsigned long long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - ptrdiff_t operator-(const char16ptr_t& aOther) const - { - return mPtr - aOther.mPtr; - } -}; - -inline decltype((char*)0-(char*)0) -operator-(const char16_t* aX, const char16ptr_t aY) -{ - return aX - static_cast(aY); -} - -#else - -typedef const char16_t* char16ptr_t; - -#endif - -static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); -static_assert(char16_t(-1) > char16_t(0), "Is char16_t type unsigned?"); -static_assert(sizeof(u'A') == 2, "Is unicode char literal 16 bits?"); -static_assert(sizeof(u""[0]) == 2, "Is unicode string char 16 bits?"); - -#endif - -#endif /* mozilla_Char16_h */ diff --git a/mac/include/spidermonkey/mozilla/CheckedInt.h b/mac/include/spidermonkey/mozilla/CheckedInt.h deleted file mode 100644 index 02ef8d5b..00000000 --- a/mac/include/spidermonkey/mozilla/CheckedInt.h +++ /dev/null @@ -1,791 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Provides checked integers, detecting integer overflow and divide-by-0. */ - -#ifndef mozilla_CheckedInt_h -#define mozilla_CheckedInt_h - -#include -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/IntegerTypeTraits.h" - -namespace mozilla { - -template class CheckedInt; - -namespace detail { - -/* - * Step 1: manually record supported types - * - * What's nontrivial here is that there are different families of integer - * types: basic integer types and stdint types. It is merrily undefined which - * types from one family may be just typedefs for a type from another family. - * - * For example, on GCC 4.6, aside from the basic integer types, the only other - * type that isn't just a typedef for some of them, is int8_t. - */ - -struct UnsupportedType {}; - -template -struct IsSupportedPass2 -{ - static const bool value = false; -}; - -template -struct IsSupported -{ - static const bool value = IsSupportedPass2::value; -}; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -/* - * Step 2: Implement the actual validity checks. - * - * Ideas taken from IntegerLib, code different. - */ - -template -struct TwiceBiggerType -{ - typedef typename detail::StdintTypeForSizeAndSignedness< - sizeof(IntegerType) * 2, - IsSigned::value - >::Type Type; -}; - -template -struct TwiceBiggerType -{ - typedef UnsupportedType Type; -}; - -template -inline bool -HasSignBit(T aX) -{ - // In C++, right bit shifts on negative values is undefined by the standard. - // Notice that signed-to-unsigned conversions are always well-defined in the - // standard, as the value congruent modulo 2**n as expected. By contrast, - // unsigned-to-signed is only well-defined if the value is representable. - return bool(typename MakeUnsigned::Type(aX) >> - PositionOfSignBit::value); -} - -// Bitwise ops may return a larger type, so it's good to use this inline -// helper guaranteeing that the result is really of type T. -template -inline T -BinaryComplement(T aX) -{ - return ~aX; -} - -template::value, - bool IsUSigned = IsSigned::value> -struct DoesRangeContainRange -{ -}; - -template -struct DoesRangeContainRange -{ - static const bool value = sizeof(T) >= sizeof(U); -}; - -template -struct DoesRangeContainRange -{ - static const bool value = sizeof(T) > sizeof(U); -}; - -template -struct DoesRangeContainRange -{ - static const bool value = false; -}; - -template::value, - bool IsUSigned = IsSigned::value, - bool DoesTRangeContainURange = DoesRangeContainRange::value> -struct IsInRangeImpl {}; - -template -struct IsInRangeImpl -{ - static bool run(U) - { - return true; - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return aX <= MaxValue::value && aX >= MinValue::value; - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return aX <= MaxValue::value; - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return sizeof(T) > sizeof(U) || aX <= U(MaxValue::value); - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return sizeof(T) >= sizeof(U) - ? aX >= 0 - : aX >= 0 && aX <= U(MaxValue::value); - } -}; - -template -inline bool -IsInRange(U aX) -{ - return IsInRangeImpl::run(aX); -} - -template -inline bool -IsAddValid(T aX, T aY) -{ - // Addition is valid if the sign of aX+aY is equal to either that of aX or - // that of aY. Since the value of aX+aY is undefined if we have a signed - // type, we compute it using the unsigned type of the same size. Beware! - // These bitwise operations can return a larger integer type, if T was a - // small type like int8_t, so we explicitly cast to T. - - typename MakeUnsigned::Type ux = aX; - typename MakeUnsigned::Type uy = aY; - typename MakeUnsigned::Type result = ux + uy; - return IsSigned::value - ? HasSignBit(BinaryComplement(T((result ^ aX) & (result ^ aY)))) - : BinaryComplement(aX) >= aY; -} - -template -inline bool -IsSubValid(T aX, T aY) -{ - // Subtraction is valid if either aX and aY have same sign, or aX-aY and aX - // have same sign. Since the value of aX-aY is undefined if we have a signed - // type, we compute it using the unsigned type of the same size. - typename MakeUnsigned::Type ux = aX; - typename MakeUnsigned::Type uy = aY; - typename MakeUnsigned::Type result = ux - uy; - - return IsSigned::value - ? HasSignBit(BinaryComplement(T((result ^ aX) & (aX ^ aY)))) - : aX >= aY; -} - -template::value, - bool TwiceBiggerTypeIsSupported = - IsSupported::Type>::value> -struct IsMulValidImpl {}; - -template -struct IsMulValidImpl -{ - static bool run(T aX, T aY) - { - typedef typename TwiceBiggerType::Type TwiceBiggerType; - TwiceBiggerType product = TwiceBiggerType(aX) * TwiceBiggerType(aY); - return IsInRange(product); - } -}; - -template -struct IsMulValidImpl -{ - static bool run(T aX, T aY) - { - const T max = MaxValue::value; - const T min = MinValue::value; - - if (aX == 0 || aY == 0) { - return true; - } - if (aX > 0) { - return aY > 0 - ? aX <= max / aY - : aY >= min / aX; - } - - // If we reach this point, we know that aX < 0. - return aY > 0 - ? aX >= min / aY - : aY >= max / aX; - } -}; - -template -struct IsMulValidImpl -{ - static bool run(T aX, T aY) - { - return aY == 0 || aX <= MaxValue::value / aY; - } -}; - -template -inline bool -IsMulValid(T aX, T aY) -{ - return IsMulValidImpl::run(aX, aY); -} - -template -inline bool -IsDivValid(T aX, T aY) -{ - // Keep in mind that in the signed case, min/-1 is invalid because - // abs(min)>max. - return aY != 0 && - !(IsSigned::value && aX == MinValue::value && aY == T(-1)); -} - -template::value> -struct IsModValidImpl; - -template -inline bool -IsModValid(T aX, T aY) -{ - return IsModValidImpl::run(aX, aY); -} - -/* - * Mod is pretty simple. - * For now, let's just use the ANSI C definition: - * If aX or aY are negative, the results are implementation defined. - * Consider these invalid. - * Undefined for aY=0. - * The result will never exceed either aX or aY. - * - * Checking that aX>=0 is a warning when T is unsigned. - */ - -template -struct IsModValidImpl -{ - static inline bool run(T aX, T aY) - { - return aY >= 1; - } -}; - -template -struct IsModValidImpl -{ - static inline bool run(T aX, T aY) - { - if (aX < 0) { - return false; - } - return aY >= 1; - } -}; - -template::value> -struct NegateImpl; - -template -struct NegateImpl -{ - static CheckedInt negate(const CheckedInt& aVal) - { - // Handle negation separately for signed/unsigned, for simpler code and to - // avoid an MSVC warning negating an unsigned value. - return CheckedInt(0, aVal.isValid() && aVal.mValue == 0); - } -}; - -template -struct NegateImpl -{ - static CheckedInt negate(const CheckedInt& aVal) - { - // Watch out for the min-value, which (with twos-complement) can't be - // negated as -min-value is then (max-value + 1). - if (!aVal.isValid() || aVal.mValue == MinValue::value) { - return CheckedInt(aVal.mValue, false); - } - return CheckedInt(-aVal.mValue, true); - } -}; - -} // namespace detail - - -/* - * Step 3: Now define the CheckedInt class. - */ - -/** - * @class CheckedInt - * @brief Integer wrapper class checking for integer overflow and other errors - * @param T the integer type to wrap. Can be any type among the following: - * - any basic integer type such as |int| - * - any stdint type such as |int8_t| - * - * This class implements guarded integer arithmetic. Do a computation, check - * that isValid() returns true, you then have a guarantee that no problem, such - * as integer overflow, happened during this computation, and you can call - * value() to get the plain integer value. - * - * The arithmetic operators in this class are guaranteed not to raise a signal - * (e.g. in case of a division by zero). - * - * For example, suppose that you want to implement a function that computes - * (aX+aY)/aZ, that doesn't crash if aZ==0, and that reports on error (divide by - * zero or integer overflow). You could code it as follows: - @code - bool computeXPlusYOverZ(int aX, int aY, int aZ, int* aResult) - { - CheckedInt checkedResult = (CheckedInt(aX) + aY) / aZ; - if (checkedResult.isValid()) { - *aResult = checkedResult.value(); - return true; - } else { - return false; - } - } - @endcode - * - * Implicit conversion from plain integers to checked integers is allowed. The - * plain integer is checked to be in range before being casted to the - * destination type. This means that the following lines all compile, and the - * resulting CheckedInts are correctly detected as valid or invalid: - * @code - // 1 is of type int, is found to be in range for uint8_t, x is valid - CheckedInt x(1); - // -1 is of type int, is found not to be in range for uint8_t, x is invalid - CheckedInt x(-1); - // -1 is of type int, is found to be in range for int8_t, x is valid - CheckedInt x(-1); - // 1000 is of type int16_t, is found not to be in range for int8_t, - // x is invalid - CheckedInt x(int16_t(1000)); - // 3123456789 is of type uint32_t, is found not to be in range for int32_t, - // x is invalid - CheckedInt x(uint32_t(3123456789)); - * @endcode - * Implicit conversion from - * checked integers to plain integers is not allowed. As shown in the - * above example, to get the value of a checked integer as a normal integer, - * call value(). - * - * Arithmetic operations between checked and plain integers is allowed; the - * result type is the type of the checked integer. - * - * Checked integers of different types cannot be used in the same arithmetic - * expression. - * - * There are convenience typedefs for all stdint types, of the following form - * (these are just 2 examples): - @code - typedef CheckedInt CheckedInt32; - typedef CheckedInt CheckedUint16; - @endcode - */ -template -class CheckedInt -{ -protected: - T mValue; - bool mIsValid; - - template - CheckedInt(U aValue, bool aIsValid) : mValue(aValue), mIsValid(aIsValid) - { - static_assert(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); - } - - friend struct detail::NegateImpl; - -public: - /** - * Constructs a checked integer with given @a value. The checked integer is - * initialized as valid or invalid depending on whether the @a value - * is in range. - * - * This constructor is not explicit. Instead, the type of its argument is a - * separate template parameter, ensuring that no conversion is performed - * before this constructor is actually called. As explained in the above - * documentation for class CheckedInt, this constructor checks that its - * argument is valid. - */ - template - MOZ_IMPLICIT CheckedInt(U aValue) MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT - : mValue(T(aValue)), - mIsValid(detail::IsInRange(aValue)) - { - static_assert(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); - } - - template - friend class CheckedInt; - - template - CheckedInt toChecked() const - { - CheckedInt ret(mValue); - ret.mIsValid = ret.mIsValid && mIsValid; - return ret; - } - - /** Constructs a valid checked integer with initial value 0 */ - CheckedInt() : mValue(0), mIsValid(true) - { - static_assert(detail::IsSupported::value, - "This type is not supported by CheckedInt"); - } - - /** @returns the actual value */ - T value() const - { - MOZ_ASSERT(mIsValid, "Invalid checked integer (division by zero or integer overflow)"); - return mValue; - } - - /** - * @returns true if the checked integer is valid, i.e. is not the result - * of an invalid operation or of an operation involving an invalid checked - * integer - */ - bool isValid() const - { - return mIsValid; - } - - template - friend CheckedInt operator +(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator +=(U aRhs); - CheckedInt& operator +=(const CheckedInt& aRhs); - - template - friend CheckedInt operator -(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator -=(U aRhs); - CheckedInt& operator -=(const CheckedInt& aRhs); - - template - friend CheckedInt operator *(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator *=(U aRhs); - CheckedInt& operator *=(const CheckedInt& aRhs); - - template - friend CheckedInt operator /(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator /=(U aRhs); - CheckedInt& operator /=(const CheckedInt& aRhs); - - template - friend CheckedInt operator %(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator %=(U aRhs); - CheckedInt& operator %=(const CheckedInt& aRhs); - - CheckedInt operator -() const - { - return detail::NegateImpl::negate(*this); - } - - /** - * @returns true if the left and right hand sides are valid - * and have the same value. - * - * Note that these semantics are the reason why we don't offer - * a operator!=. Indeed, we'd want to have a!=b be equivalent to !(a==b) - * but that would mean that whenever a or b is invalid, a!=b - * is always true, which would be very confusing. - * - * For similar reasons, operators <, >, <=, >= would be very tricky to - * specify, so we just avoid offering them. - * - * Notice that these == semantics are made more reasonable by these facts: - * 1. a==b implies equality at the raw data level - * (the converse is false, as a==b is never true among invalids) - * 2. This is similar to the behavior of IEEE floats, where a==b - * means that a and b have the same value *and* neither is NaN. - */ - bool operator ==(const CheckedInt& aOther) const - { - return mIsValid && aOther.mIsValid && mValue == aOther.mValue; - } - - /** prefix ++ */ - CheckedInt& operator++() - { - *this += 1; - return *this; - } - - /** postfix ++ */ - CheckedInt operator++(int) - { - CheckedInt tmp = *this; - *this += 1; - return tmp; - } - - /** prefix -- */ - CheckedInt& operator--() - { - *this -= 1; - return *this; - } - - /** postfix -- */ - CheckedInt operator--(int) - { - CheckedInt tmp = *this; - *this -= 1; - return tmp; - } - -private: - /** - * The !=, <, <=, >, >= operators are disabled: - * see the comment on operator==. - */ - template bool operator !=(U aOther) const = delete; - template bool operator < (U aOther) const = delete; - template bool operator <=(U aOther) const = delete; - template bool operator > (U aOther) const = delete; - template bool operator >=(U aOther) const = delete; -}; - -#define MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(NAME, OP) \ - template \ - inline CheckedInt \ - operator OP(const CheckedInt& aLhs, const CheckedInt& aRhs) \ - { \ - if (!detail::Is##NAME##Valid(aLhs.mValue, aRhs.mValue)) { \ - return CheckedInt(0, false); \ - } \ - return CheckedInt(aLhs.mValue OP aRhs.mValue, \ - aLhs.mIsValid && aRhs.mIsValid); \ - } - -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Add, +) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Sub, -) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mul, *) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Div, /) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mod, %) - -#undef MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR - -// Implement castToCheckedInt(x), making sure that -// - it allows x to be either a CheckedInt or any integer type -// that can be casted to T -// - if x is already a CheckedInt, we just return a reference to it, -// instead of copying it (optimization) - -namespace detail { - -template -struct CastToCheckedIntImpl -{ - typedef CheckedInt ReturnType; - static CheckedInt run(U aU) { return aU; } -}; - -template -struct CastToCheckedIntImpl > -{ - typedef const CheckedInt& ReturnType; - static const CheckedInt& run(const CheckedInt& aU) { return aU; } -}; - -} // namespace detail - -template -inline typename detail::CastToCheckedIntImpl::ReturnType -castToCheckedInt(U aU) -{ - static_assert(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); - return detail::CastToCheckedIntImpl::run(aU); -} - -#define MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(OP, COMPOUND_OP) \ - template \ - template \ - CheckedInt& CheckedInt::operator COMPOUND_OP(U aRhs) \ - { \ - *this = *this OP castToCheckedInt(aRhs); \ - return *this; \ - } \ - template \ - CheckedInt& CheckedInt::operator COMPOUND_OP(const CheckedInt& aRhs) \ - { \ - *this = *this OP aRhs; \ - return *this; \ - } \ - template \ - inline CheckedInt operator OP(const CheckedInt& aLhs, U aRhs) \ - { \ - return aLhs OP castToCheckedInt(aRhs); \ - } \ - template \ - inline CheckedInt operator OP(U aLhs, const CheckedInt& aRhs) \ - { \ - return castToCheckedInt(aLhs) OP aRhs; \ - } - -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(+, +=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(*, *=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(-, -=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(/, /=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(%, %=) - -#undef MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS - -template -inline bool -operator ==(const CheckedInt& aLhs, U aRhs) -{ - return aLhs == castToCheckedInt(aRhs); -} - -template -inline bool -operator ==(U aLhs, const CheckedInt& aRhs) -{ - return castToCheckedInt(aLhs) == aRhs; -} - -// Convenience typedefs. -typedef CheckedInt CheckedInt8; -typedef CheckedInt CheckedUint8; -typedef CheckedInt CheckedInt16; -typedef CheckedInt CheckedUint16; -typedef CheckedInt CheckedInt32; -typedef CheckedInt CheckedUint32; -typedef CheckedInt CheckedInt64; -typedef CheckedInt CheckedUint64; - -} // namespace mozilla - -#endif /* mozilla_CheckedInt_h */ diff --git a/mac/include/spidermonkey/mozilla/Compiler.h b/mac/include/spidermonkey/mozilla/Compiler.h deleted file mode 100644 index 1bd34d32..00000000 --- a/mac/include/spidermonkey/mozilla/Compiler.h +++ /dev/null @@ -1,113 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Various compiler checks. */ - -#ifndef mozilla_Compiler_h -#define mozilla_Compiler_h - -#define MOZ_IS_GCC 0 -#define MOZ_IS_MSVC 0 - -#if !defined(__clang__) && defined(__GNUC__) - -# undef MOZ_IS_GCC -# define MOZ_IS_GCC 1 - /* - * These macros should simplify gcc version checking. For example, to check - * for gcc 4.7.1 or later, check `#if MOZ_GCC_VERSION_AT_LEAST(4, 7, 1)`. - */ -# define MOZ_GCC_VERSION_AT_LEAST(major, minor, patchlevel) \ - ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \ - >= ((major) * 10000 + (minor) * 100 + (patchlevel))) -# define MOZ_GCC_VERSION_AT_MOST(major, minor, patchlevel) \ - ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \ - <= ((major) * 10000 + (minor) * 100 + (patchlevel))) -# if !MOZ_GCC_VERSION_AT_LEAST(4, 8, 0) -# error "mfbt (and Gecko) require at least gcc 4.8 to build." -# endif - -#elif defined(_MSC_VER) - -# undef MOZ_IS_MSVC -# define MOZ_IS_MSVC 1 - -#endif - -/* - * The situation with standard libraries is a lot worse than with compilers, - * particularly as clang and gcc could end up using one of three or so standard - * libraries, and they may not be up-to-snuff with newer C++11 versions. To - * detect the library, we're going to include cstddef (which is a small header - * which will be transitively included by everybody else at some point) to grab - * the version macros and deduce macros from there. - */ -#ifdef __cplusplus -# include -# ifdef _STLPORT_MAJOR -# define MOZ_USING_STLPORT 1 -# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) \ - (_STLPORT_VERSION >= ((major) << 8 | (minor) << 4 | (patch))) -# elif defined(_LIBCPP_VERSION) - /* - * libc++, unfortunately, doesn't appear to have useful versioning macros. - * Hopefully, the recommendations of N3694 with respect to standard libraries - * will get applied instead and we won't need to worry about version numbers - * here. - */ -# define MOZ_USING_LIBCXX 1 -# elif defined(__GLIBCXX__) -# define MOZ_USING_LIBSTDCXX 1 - /* - * libstdc++ is also annoying and doesn't give us useful versioning macros - * for the library. If we're using gcc, then assume that libstdc++ matches - * the compiler version. If we're using clang, we're going to have to fake - * major/minor combinations by looking for newly-defined config macros. - */ -# if MOZ_IS_GCC -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - MOZ_GCC_VERSION_AT_LEAST(major, minor, patch) -# elif defined(_GLIBCXX_THROW_OR_ABORT) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 8)) -# elif defined(_GLIBCXX_NOEXCEPT) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 7)) -# elif defined(_GLIBCXX_USE_DEPRECATED) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 6)) -# elif defined(_GLIBCXX_PSEUDO_VISIBILITY) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 5)) -# elif defined(_GLIBCXX_BEGIN_EXTERN_C) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 4)) -# elif defined(_GLIBCXX_VISIBILITY_ATTR) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 3)) -# elif defined(_GLIBCXX_VISIBILITY) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 2)) -# else -# error "Your version of libstdc++ is unknown to us and is likely too old." -# endif -# endif - - // Flesh out the defines for everyone else -# ifndef MOZ_USING_STLPORT -# define MOZ_USING_STLPORT 0 -# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) 0 -# endif -# ifndef MOZ_USING_LIBCXX -# define MOZ_USING_LIBCXX 0 -# endif -# ifndef MOZ_USING_LIBSTDCXX -# define MOZ_USING_LIBSTDCXX 0 -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) 0 -# endif -#endif /* __cplusplus */ - -#endif /* mozilla_Compiler_h */ diff --git a/mac/include/spidermonkey/mozilla/Compression.h b/mac/include/spidermonkey/mozilla/Compression.h deleted file mode 100644 index aa50211b..00000000 --- a/mac/include/spidermonkey/mozilla/Compression.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Various simple compression/decompression functions. */ - -#ifndef mozilla_Compression_h_ -#define mozilla_Compression_h_ - -#include "mozilla/Assertions.h" -#include "mozilla/Types.h" - -namespace mozilla { -namespace Compression { - -/** - * LZ4 is a very fast byte-wise compression algorithm. - * - * Compared to Google's Snappy it is faster to compress and decompress and - * generally produces output of about the same size. - * - * Compared to zlib it compresses at about 10x the speed, decompresses at about - * 4x the speed and produces output of about 1.5x the size. - */ - -class LZ4 -{ -public: - /** - * Compresses |aInputSize| bytes from |aSource| into |aDest|. Destination - * buffer must be already allocated, and must be sized to handle worst cases - * situations (input data not compressible). Worst case size evaluation is - * provided by function maxCompressedSize() - * - * @param aInputSize is the input size. Max supported value is ~1.9GB - * @return the number of bytes written in buffer |aDest| - */ - static MFBT_API size_t - compress(const char* aSource, size_t aInputSize, char* aDest); - - /** - * Compress |aInputSize| bytes from |aSource| into an output buffer - * |aDest| of maximum size |aMaxOutputSize|. If it cannot achieve it, - * compression will stop, and result of the function will be zero, - * |aDest| will still be written to, but since the number of input - * bytes consumed is not returned the result is not usable. - * - * This function never writes outside of provided output buffer. - * - * @param aInputSize is the input size. Max supported value is ~1.9GB - * @param aMaxOutputSize is the size of the destination buffer (which must - * be already allocated) - * @return the number of bytes written in buffer |aDest| or 0 if the - * compression fails - */ - static MFBT_API size_t - compressLimitedOutput(const char* aSource, size_t aInputSize, char* aDest, - size_t aMaxOutputSize); - - /** - * If the source stream is malformed, the function will stop decoding - * and return false. - * - * This function never writes outside of provided buffers, and never - * modifies input buffer. - * - * Note: destination buffer must be already allocated, and its size must be a - * minimum of |aOutputSize| bytes. - * - * @param aOutputSize is the output size, therefore the original size - * @return true on success, false on failure - */ - static MFBT_API MOZ_MUST_USE bool - decompress(const char* aSource, char* aDest, size_t aOutputSize); - - /** - * If the source stream is malformed, the function will stop decoding - * and return false. - * - * This function never writes beyond aDest + aMaxOutputSize, and is - * therefore protected against malicious data packets. - * - * Note: Destination buffer must be already allocated. This version is - * slightly slower than the decompress without the aMaxOutputSize. - * - * @param aInputSize is the length of the input compressed data - * @param aMaxOutputSize is the size of the destination buffer (which must be - * already allocated) - * @param aOutputSize the actual number of bytes decoded in the destination - * buffer (necessarily <= aMaxOutputSize) - * @return true on success, false on failure - */ - static MFBT_API MOZ_MUST_USE bool - decompress(const char* aSource, size_t aInputSize, char* aDest, - size_t aMaxOutputSize, size_t* aOutputSize); - - /* - * Provides the maximum size that LZ4 may output in a "worst case" - * scenario (input data not compressible) primarily useful for memory - * allocation of output buffer. - * note : this function is limited by "int" range (2^31-1) - * - * @param aInputSize is the input size. Max supported value is ~1.9GB - * @return maximum output size in a "worst case" scenario - */ - static inline size_t maxCompressedSize(size_t aInputSize) - { - size_t max = (aInputSize + (aInputSize / 255) + 16); - MOZ_ASSERT(max > aInputSize); - return max; - } -}; - -} /* namespace Compression */ -} /* namespace mozilla */ - -#endif /* mozilla_Compression_h_ */ diff --git a/mac/include/spidermonkey/mozilla/DebugOnly.h b/mac/include/spidermonkey/mozilla/DebugOnly.h deleted file mode 100644 index a1a669db..00000000 --- a/mac/include/spidermonkey/mozilla/DebugOnly.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Provides DebugOnly, a type for variables used only in debug builds (i.e. by - * assertions). - */ - -#ifndef mozilla_DebugOnly_h -#define mozilla_DebugOnly_h - -#include "mozilla/Attributes.h" - -namespace mozilla { - -/** - * DebugOnly contains a value of type T, but only in debug builds. In release - * builds, it does not contain a value. This helper is intended to be used with - * MOZ_ASSERT()-style macros, allowing one to write: - * - * DebugOnly check = func(); - * MOZ_ASSERT(check); - * - * more concisely than declaring |check| conditional on #ifdef DEBUG. - * - * DebugOnly instances can only be coerced to T in debug builds. In release - * builds they don't have a value, so type coercion is not well defined. - * - * NOTE: DebugOnly instances still take up one byte of space, plus padding, even - * in optimized, non-DEBUG builds (see bug 1253094 comment 37 for more info). - * For this reason the class is MOZ_STACK_CLASS to prevent consumers using - * DebugOnly for struct/class members and unwittingly inflating the size of - * their objects in release builds. - */ -template -class MOZ_STACK_CLASS DebugOnly -{ -public: -#ifdef DEBUG - T value; - - DebugOnly() { } - MOZ_IMPLICIT DebugOnly(const T& aOther) : value(aOther) { } - DebugOnly(const DebugOnly& aOther) : value(aOther.value) { } - DebugOnly& operator=(const T& aRhs) { - value = aRhs; - return *this; - } - - void operator++(int) { value++; } - void operator--(int) { value--; } - - // Do not define operator+=(), etc. here. These will coerce via the - // implicit cast and built-in operators. Defining explicit methods here - // will create ambiguity the compiler can't deal with. - - T* operator&() { return &value; } - - operator T&() { return value; } - operator const T&() const { return value; } - - T& operator->() { return value; } - const T& operator->() const { return value; } - -#else - DebugOnly() { } - MOZ_IMPLICIT DebugOnly(const T&) { } - DebugOnly(const DebugOnly&) { } - DebugOnly& operator=(const T&) { return *this; } - void operator++(int) { } - void operator--(int) { } - DebugOnly& operator+=(const T&) { return *this; } - DebugOnly& operator-=(const T&) { return *this; } - DebugOnly& operator&=(const T&) { return *this; } - DebugOnly& operator|=(const T&) { return *this; } - DebugOnly& operator^=(const T&) { return *this; } -#endif - - /* - * DebugOnly must always have a destructor or else it will - * generate "unused variable" warnings, exactly what it's intended - * to avoid! - */ - ~DebugOnly() {} -}; - -} // namespace mozilla - -#endif /* mozilla_DebugOnly_h */ diff --git a/mac/include/spidermonkey/mozilla/Decimal.h b/mac/include/spidermonkey/mozilla/Decimal.h deleted file mode 100644 index 10d0e2c7..00000000 --- a/mac/include/spidermonkey/mozilla/Decimal.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * Imported from: - * https://chromium.googlesource.com/chromium/src.git/+/master/third_party/WebKit/Source/platform/Decimal.h - * Check UPSTREAM-GIT-SHA for the commit ID of the last update from Blink core. - */ - -#ifndef Decimal_h -#define Decimal_h - -#include "mozilla/Assertions.h" -#include -#include "mozilla/Types.h" - -#include - -#ifndef ASSERT -#define DEFINED_ASSERT_FOR_DECIMAL_H 1 -#define ASSERT MOZ_ASSERT -#endif - -#define PLATFORM_EXPORT - -// To use USING_FAST_MALLOC we'd need: -// https://chromium.googlesource.com/chromium/src.git/+/master/third_party/WebKit/Source/wtf/Allocator.h -// Since we don't allocate Decimal objects, no need. -#define USING_FAST_MALLOC(type) \ - void ignore_this_dummy_method() = delete - -#define DISALLOW_NEW() \ - private: \ - void* operator new(size_t) = delete; \ - void* operator new(size_t, void*) = delete; \ - public: - -namespace blink { - -namespace DecimalPrivate { -class SpecialValueHandler; -} - -// This class represents decimal base floating point number. -// -// FIXME: Once all C++ compiler support decimal type, we should replace this -// class to compiler supported one. See below URI for current status of decimal -// type for C++: // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1977.html -class PLATFORM_EXPORT Decimal { - USING_FAST_MALLOC(Decimal); -public: - enum Sign { - Positive, - Negative, - }; - - // You should not use EncodedData other than unit testing. - class EncodedData { - DISALLOW_NEW(); - // For accessing FormatClass. - friend class Decimal; - friend class DecimalPrivate::SpecialValueHandler; - public: - EncodedData(Sign, int exponent, uint64_t coefficient); - - bool operator==(const EncodedData&) const; - bool operator!=(const EncodedData& another) const { return !operator==(another); } - - uint64_t coefficient() const { return m_coefficient; } - int countDigits() const; - int exponent() const { return m_exponent; } - bool isFinite() const { return !isSpecial(); } - bool isInfinity() const { return m_formatClass == ClassInfinity; } - bool isNaN() const { return m_formatClass == ClassNaN; } - bool isSpecial() const { return m_formatClass == ClassInfinity || m_formatClass == ClassNaN; } - bool isZero() const { return m_formatClass == ClassZero; } - Sign sign() const { return m_sign; } - void setSign(Sign sign) { m_sign = sign; } - - private: - enum FormatClass { - ClassInfinity, - ClassNormal, - ClassNaN, - ClassZero, - }; - - EncodedData(Sign, FormatClass); - FormatClass formatClass() const { return m_formatClass; } - - uint64_t m_coefficient; - int16_t m_exponent; - FormatClass m_formatClass; - Sign m_sign; - }; - - MFBT_API explicit Decimal(int32_t = 0); - MFBT_API Decimal(Sign, int exponent, uint64_t coefficient); - MFBT_API Decimal(const Decimal&); - - MFBT_API Decimal& operator=(const Decimal&); - MFBT_API Decimal& operator+=(const Decimal&); - MFBT_API Decimal& operator-=(const Decimal&); - MFBT_API Decimal& operator*=(const Decimal&); - MFBT_API Decimal& operator/=(const Decimal&); - - MFBT_API Decimal operator-() const; - - MFBT_API bool operator==(const Decimal&) const; - MFBT_API bool operator!=(const Decimal&) const; - MFBT_API bool operator<(const Decimal&) const; - MFBT_API bool operator<=(const Decimal&) const; - MFBT_API bool operator>(const Decimal&) const; - MFBT_API bool operator>=(const Decimal&) const; - - MFBT_API Decimal operator+(const Decimal&) const; - MFBT_API Decimal operator-(const Decimal&) const; - MFBT_API Decimal operator*(const Decimal&) const; - MFBT_API Decimal operator/(const Decimal&) const; - - int exponent() const - { - ASSERT(isFinite()); - return m_data.exponent(); - } - - bool isFinite() const { return m_data.isFinite(); } - bool isInfinity() const { return m_data.isInfinity(); } - bool isNaN() const { return m_data.isNaN(); } - bool isNegative() const { return sign() == Negative; } - bool isPositive() const { return sign() == Positive; } - bool isSpecial() const { return m_data.isSpecial(); } - bool isZero() const { return m_data.isZero(); } - - MFBT_API Decimal abs() const; - MFBT_API Decimal ceil() const; - MFBT_API Decimal floor() const; - MFBT_API Decimal remainder(const Decimal&) const; - MFBT_API Decimal round() const; - - MFBT_API double toDouble() const; - // Note: toString method supports infinity and nan but fromString not. - MFBT_API std::string toString() const; - MFBT_API bool toString(char* strBuf, size_t bufLength) const; - - static MFBT_API Decimal fromDouble(double); - // fromString supports following syntax EBNF: - // number ::= sign? digit+ ('.' digit*) (exponent-marker sign? digit+)? - // | sign? '.' digit+ (exponent-marker sign? digit+)? - // sign ::= '+' | '-' - // exponent-marker ::= 'e' | 'E' - // digit ::= '0' | '1' | ... | '9' - // Note: fromString doesn't support "infinity" and "nan". - static MFBT_API Decimal fromString(const std::string& aValue); - static MFBT_API Decimal infinity(Sign); - static MFBT_API Decimal nan(); - static MFBT_API Decimal zero(Sign); - - // You should not use below methods. We expose them for unit testing. - MFBT_API explicit Decimal(const EncodedData&); - const EncodedData& value() const { return m_data; } - -private: - struct AlignedOperands { - uint64_t lhsCoefficient; - uint64_t rhsCoefficient; - int exponent; - }; - - MFBT_API explicit Decimal(double); - MFBT_API Decimal compareTo(const Decimal&) const; - - static MFBT_API AlignedOperands alignOperands(const Decimal& lhs, const Decimal& rhs); - static inline Sign invertSign(Sign sign) { return sign == Negative ? Positive : Negative; } - - Sign sign() const { return m_data.sign(); } - - EncodedData m_data; -}; - -} // namespace blink - -namespace mozilla { -typedef blink::Decimal Decimal; -} // namespace mozilla - -#undef USING_FAST_MALLOC - -#ifdef DEFINED_ASSERT_FOR_DECIMAL_H -#undef DEFINED_ASSERT_FOR_DECIMAL_H -#undef ASSERT -#endif - -#endif // Decimal_h diff --git a/mac/include/spidermonkey/mozilla/EndianUtils.h b/mac/include/spidermonkey/mozilla/EndianUtils.h deleted file mode 100644 index 00815580..00000000 --- a/mac/include/spidermonkey/mozilla/EndianUtils.h +++ /dev/null @@ -1,695 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Functions for reading and writing integers in various endiannesses. */ - -/* - * The classes LittleEndian and BigEndian expose static methods for - * reading and writing 16-, 32-, and 64-bit signed and unsigned integers - * in their respective endianness. The naming scheme is: - * - * {Little,Big}Endian::{read,write}{Uint,Int} - * - * For instance, LittleEndian::readInt32 will read a 32-bit signed - * integer from memory in little endian format. Similarly, - * BigEndian::writeUint16 will write a 16-bit unsigned integer to memory - * in big-endian format. - * - * The class NativeEndian exposes methods for conversion of existing - * data to and from the native endianness. These methods are intended - * for cases where data needs to be transferred, serialized, etc. - * swap{To,From}{Little,Big}Endian byteswap a single value if necessary. - * Bulk conversion functions are also provided which optimize the - * no-conversion-needed case: - * - * - copyAndSwap{To,From}{Little,Big}Endian; - * - swap{To,From}{Little,Big}EndianInPlace. - * - * The *From* variants are intended to be used for reading data and the - * *To* variants for writing data. - * - * Methods on NativeEndian work with integer data of any type. - * Floating-point data is not supported. - * - * For clarity in networking code, "Network" may be used as a synonym - * for "Big" in any of the above methods or class names. - * - * As an example, reading a file format header whose fields are stored - * in big-endian format might look like: - * - * class ExampleHeader - * { - * private: - * uint32_t mMagic; - * uint32_t mLength; - * uint32_t mTotalRecords; - * uint64_t mChecksum; - * - * public: - * ExampleHeader(const void* data) - * { - * const uint8_t* ptr = static_cast(data); - * mMagic = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t); - * mLength = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t); - * mTotalRecords = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t); - * mChecksum = BigEndian::readUint64(ptr); - * } - * ... - * }; - */ - -#ifndef mozilla_EndianUtils_h -#define mozilla_EndianUtils_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/DebugOnly.h" -#include "mozilla/TypeTraits.h" - -#include -#include - -#if defined(_MSC_VER) -# include -# pragma intrinsic(_byteswap_ushort) -# pragma intrinsic(_byteswap_ulong) -# pragma intrinsic(_byteswap_uint64) -#endif - -#if defined(_WIN64) -# if defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_) -# define MOZ_LITTLE_ENDIAN 1 -# else -# error "CPU type is unknown" -# endif -#elif defined(_WIN32) -# if defined(_M_IX86) -# define MOZ_LITTLE_ENDIAN 1 -# elif defined(_M_ARM) -# define MOZ_LITTLE_ENDIAN 1 -# else -# error "CPU type is unknown" -# endif -#elif defined(__APPLE__) || defined(__powerpc__) || defined(__ppc__) -# if __LITTLE_ENDIAN__ -# define MOZ_LITTLE_ENDIAN 1 -# elif __BIG_ENDIAN__ -# define MOZ_BIG_ENDIAN 1 -# endif -#elif defined(__GNUC__) && \ - defined(__BYTE_ORDER__) && \ - defined(__ORDER_LITTLE_ENDIAN__) && \ - defined(__ORDER_BIG_ENDIAN__) - /* - * Some versions of GCC provide architecture-independent macros for - * this. Yes, there are more than two values for __BYTE_ORDER__. - */ -# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -# define MOZ_LITTLE_ENDIAN 1 -# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -# define MOZ_BIG_ENDIAN 1 -# else -# error "Can't handle mixed-endian architectures" -# endif -/* - * We can't include useful headers like or - * here because they're not present on all platforms. Instead we have - * this big conditional that ideally will catch all the interesting - * cases. - */ -#elif defined(__sparc) || defined(__sparc__) || \ - defined(_POWER) || defined(__hppa) || \ - defined(_MIPSEB) || defined(__ARMEB__) || \ - defined(__s390__) || defined(__AARCH64EB__) || \ - (defined(__sh__) && defined(__LITTLE_ENDIAN__)) || \ - (defined(__ia64) && defined(__BIG_ENDIAN__)) -# define MOZ_BIG_ENDIAN 1 -#elif defined(__i386) || defined(__i386__) || \ - defined(__x86_64) || defined(__x86_64__) || \ - defined(_MIPSEL) || defined(__ARMEL__) || \ - defined(__alpha__) || defined(__AARCH64EL__) || \ - (defined(__sh__) && defined(__BIG_ENDIAN__)) || \ - (defined(__ia64) && !defined(__BIG_ENDIAN__)) -# define MOZ_LITTLE_ENDIAN 1 -#endif - -#if MOZ_BIG_ENDIAN -# define MOZ_LITTLE_ENDIAN 0 -#elif MOZ_LITTLE_ENDIAN -# define MOZ_BIG_ENDIAN 0 -#else -# error "Cannot determine endianness" -#endif - -#if defined(__clang__) -# if __has_builtin(__builtin_bswap16) -# define MOZ_HAVE_BUILTIN_BYTESWAP16 __builtin_bswap16 -# endif -#elif defined(__GNUC__) -# define MOZ_HAVE_BUILTIN_BYTESWAP16 __builtin_bswap16 -#elif defined(_MSC_VER) -# define MOZ_HAVE_BUILTIN_BYTESWAP16 _byteswap_ushort -#endif - -namespace mozilla { - -namespace detail { - -/* - * We need wrappers here because free functions with default template - * arguments and/or partial specialization of function templates are not - * supported by all the compilers we use. - */ -template -struct Swapper; - -template -struct Swapper -{ - static T swap(T aValue) - { -#if defined(MOZ_HAVE_BUILTIN_BYTESWAP16) - return MOZ_HAVE_BUILTIN_BYTESWAP16(aValue); -#else - return T(((aValue & 0x00ff) << 8) | ((aValue & 0xff00) >> 8)); -#endif - } -}; - -template -struct Swapper -{ - static T swap(T aValue) - { -#if defined(__clang__) || defined(__GNUC__) - return T(__builtin_bswap32(aValue)); -#elif defined(_MSC_VER) - return T(_byteswap_ulong(aValue)); -#else - return T(((aValue & 0x000000ffU) << 24) | - ((aValue & 0x0000ff00U) << 8) | - ((aValue & 0x00ff0000U) >> 8) | - ((aValue & 0xff000000U) >> 24)); -#endif - } -}; - -template -struct Swapper -{ - static inline T swap(T aValue) - { -#if defined(__clang__) || defined(__GNUC__) - return T(__builtin_bswap64(aValue)); -#elif defined(_MSC_VER) - return T(_byteswap_uint64(aValue)); -#else - return T(((aValue & 0x00000000000000ffULL) << 56) | - ((aValue & 0x000000000000ff00ULL) << 40) | - ((aValue & 0x0000000000ff0000ULL) << 24) | - ((aValue & 0x00000000ff000000ULL) << 8) | - ((aValue & 0x000000ff00000000ULL) >> 8) | - ((aValue & 0x0000ff0000000000ULL) >> 24) | - ((aValue & 0x00ff000000000000ULL) >> 40) | - ((aValue & 0xff00000000000000ULL) >> 56)); -#endif - } -}; - -enum Endianness { Little, Big }; - -#if MOZ_BIG_ENDIAN -# define MOZ_NATIVE_ENDIANNESS detail::Big -#else -# define MOZ_NATIVE_ENDIANNESS detail::Little -#endif - -class EndianUtils -{ - /** - * Assert that the memory regions [aDest, aDest+aCount) and - * [aSrc, aSrc+aCount] do not overlap. aCount is given in bytes. - */ - static void assertNoOverlap(const void* aDest, const void* aSrc, - size_t aCount) - { - DebugOnly byteDestPtr = static_cast(aDest); - DebugOnly byteSrcPtr = static_cast(aSrc); - MOZ_ASSERT((byteDestPtr <= byteSrcPtr && - byteDestPtr + aCount <= byteSrcPtr) || - (byteSrcPtr <= byteDestPtr && - byteSrcPtr + aCount <= byteDestPtr)); - } - - template - static void assertAligned(T* aPtr) - { - MOZ_ASSERT((uintptr_t(aPtr) % sizeof(T)) == 0, "Unaligned pointer!"); - } - -protected: - /** - * Return |aValue| converted from SourceEndian encoding to DestEndian - * encoding. - */ - template - static inline T maybeSwap(T aValue) - { - if (SourceEndian == DestEndian) { - return aValue; - } - return Swapper::swap(aValue); - } - - /** - * Convert |aCount| elements at |aPtr| from SourceEndian encoding to - * DestEndian encoding. - */ - template - static inline void maybeSwapInPlace(T* aPtr, size_t aCount) - { - assertAligned(aPtr); - - if (SourceEndian == DestEndian) { - return; - } - for (size_t i = 0; i < aCount; i++) { - aPtr[i] = Swapper::swap(aPtr[i]); - } - } - - /** - * Write |aCount| elements to the unaligned address |aDest| in DestEndian - * format, using elements found at |aSrc| in SourceEndian format. - */ - template - static void copyAndSwapTo(void* aDest, const T* aSrc, size_t aCount) - { - assertNoOverlap(aDest, aSrc, aCount * sizeof(T)); - assertAligned(aSrc); - - if (SourceEndian == DestEndian) { - memcpy(aDest, aSrc, aCount * sizeof(T)); - return; - } - - uint8_t* byteDestPtr = static_cast(aDest); - for (size_t i = 0; i < aCount; ++i) { - union - { - T mVal; - uint8_t mBuffer[sizeof(T)]; - } u; - u.mVal = maybeSwap(aSrc[i]); - memcpy(byteDestPtr, u.mBuffer, sizeof(T)); - byteDestPtr += sizeof(T); - } - } - - /** - * Write |aCount| elements to |aDest| in DestEndian format, using elements - * found at the unaligned address |aSrc| in SourceEndian format. - */ - template - static void copyAndSwapFrom(T* aDest, const void* aSrc, size_t aCount) - { - assertNoOverlap(aDest, aSrc, aCount * sizeof(T)); - assertAligned(aDest); - - if (SourceEndian == DestEndian) { - memcpy(aDest, aSrc, aCount * sizeof(T)); - return; - } - - const uint8_t* byteSrcPtr = static_cast(aSrc); - for (size_t i = 0; i < aCount; ++i) { - union - { - T mVal; - uint8_t mBuffer[sizeof(T)]; - } u; - memcpy(u.mBuffer, byteSrcPtr, sizeof(T)); - aDest[i] = maybeSwap(u.mVal); - byteSrcPtr += sizeof(T); - } - } -}; - -template -class Endian : private EndianUtils -{ -protected: - /** Read a uint16_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE uint16_t readUint16(const void* aPtr) - { - return read(aPtr); - } - - /** Read a uint32_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE uint32_t readUint32(const void* aPtr) - { - return read(aPtr); - } - - /** Read a uint64_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE uint64_t readUint64(const void* aPtr) - { - return read(aPtr); - } - - /** Read an int16_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE int16_t readInt16(const void* aPtr) - { - return read(aPtr); - } - - /** Read an int32_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE int32_t readInt32(const void* aPtr) - { - return read(aPtr); - } - - /** Read an int64_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE int64_t readInt64(const void* aPtr) - { - return read(aPtr); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeUint16(void* aPtr, uint16_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeUint32(void* aPtr, uint32_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeUint64(void* aPtr, uint64_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeInt16(void* aPtr, int16_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeInt32(void* aPtr, int32_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeInt64(void* aPtr, int64_t aValue) - { - write(aPtr, aValue); - } - - /* - * Converts a value of type T to little-endian format. - * - * This function is intended for cases where you have data in your - * native-endian format and you need it to appear in little-endian - * format for transmission. - */ - template - MOZ_MUST_USE static T swapToLittleEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to little-endian format if ThisEndian is Big. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapToLittleEndian(void* aDest, const T* aSrc, - size_t aCount) - { - copyAndSwapTo(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapToLittleEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Converts a value of type T to big-endian format. - */ - template - MOZ_MUST_USE static T swapToBigEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to big-endian format if ThisEndian is Little. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapToBigEndian(void* aDest, const T* aSrc, - size_t aCount) - { - copyAndSwapTo(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapToBigEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Synonyms for the big-endian functions, for better readability - * in network code. - */ - - template - MOZ_MUST_USE static T swapToNetworkOrder(T aValue) - { - return swapToBigEndian(aValue); - } - - template - static void - copyAndSwapToNetworkOrder(void* aDest, const T* aSrc, size_t aCount) - { - copyAndSwapToBigEndian(aDest, aSrc, aCount); - } - - template - static void - swapToNetworkOrderInPlace(T* aPtr, size_t aCount) - { - swapToBigEndianInPlace(aPtr, aCount); - } - - /* - * Converts a value of type T from little-endian format. - */ - template - MOZ_MUST_USE static T swapFromLittleEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to little-endian format if ThisEndian is Big. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapFromLittleEndian(T* aDest, const void* aSrc, - size_t aCount) - { - copyAndSwapFrom(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapFromLittleEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Converts a value of type T from big-endian format. - */ - template - MOZ_MUST_USE static T swapFromBigEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to big-endian format if ThisEndian is Little. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapFromBigEndian(T* aDest, const void* aSrc, - size_t aCount) - { - copyAndSwapFrom(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapFromBigEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Synonyms for the big-endian functions, for better readability - * in network code. - */ - template - MOZ_MUST_USE static T swapFromNetworkOrder(T aValue) - { - return swapFromBigEndian(aValue); - } - - template - static void copyAndSwapFromNetworkOrder(T* aDest, const void* aSrc, - size_t aCount) - { - copyAndSwapFromBigEndian(aDest, aSrc, aCount); - } - - template - static void swapFromNetworkOrderInPlace(T* aPtr, size_t aCount) - { - swapFromBigEndianInPlace(aPtr, aCount); - } - -private: - /** - * Read a value of type T, encoded in endianness ThisEndian from |aPtr|. - * Return that value encoded in native endianness. - */ - template - static T read(const void* aPtr) - { - union - { - T mVal; - uint8_t mBuffer[sizeof(T)]; - } u; - memcpy(u.mBuffer, aPtr, sizeof(T)); - return maybeSwap(u.mVal); - } - - /** - * Write a value of type T, in native endianness, to |aPtr|, in ThisEndian - * endianness. - */ - template - static void write(void* aPtr, T aValue) - { - T tmp = maybeSwap(aValue); - memcpy(aPtr, &tmp, sizeof(T)); - } - - Endian() = delete; - Endian(const Endian& aTther) = delete; - void operator=(const Endian& aOther) = delete; -}; - -template -class EndianReadWrite : public Endian -{ -private: - typedef Endian super; - -public: - using super::readUint16; - using super::readUint32; - using super::readUint64; - using super::readInt16; - using super::readInt32; - using super::readInt64; - using super::writeUint16; - using super::writeUint32; - using super::writeUint64; - using super::writeInt16; - using super::writeInt32; - using super::writeInt64; -}; - -} /* namespace detail */ - -class LittleEndian final : public detail::EndianReadWrite -{}; - -class BigEndian final : public detail::EndianReadWrite -{}; - -typedef BigEndian NetworkEndian; - -class NativeEndian final : public detail::Endian -{ -private: - typedef detail::Endian super; - -public: - /* - * These functions are intended for cases where you have data in your - * native-endian format and you need the data to appear in the appropriate - * endianness for transmission, serialization, etc. - */ - using super::swapToLittleEndian; - using super::copyAndSwapToLittleEndian; - using super::swapToLittleEndianInPlace; - using super::swapToBigEndian; - using super::copyAndSwapToBigEndian; - using super::swapToBigEndianInPlace; - using super::swapToNetworkOrder; - using super::copyAndSwapToNetworkOrder; - using super::swapToNetworkOrderInPlace; - - /* - * These functions are intended for cases where you have data in the - * given endianness (e.g. reading from disk or a file-format) and you - * need the data to appear in native-endian format for processing. - */ - using super::swapFromLittleEndian; - using super::copyAndSwapFromLittleEndian; - using super::swapFromLittleEndianInPlace; - using super::swapFromBigEndian; - using super::copyAndSwapFromBigEndian; - using super::swapFromBigEndianInPlace; - using super::swapFromNetworkOrder; - using super::copyAndSwapFromNetworkOrder; - using super::swapFromNetworkOrderInPlace; -}; - -#undef MOZ_NATIVE_ENDIANNESS - -} /* namespace mozilla */ - -#endif /* mozilla_EndianUtils_h */ diff --git a/mac/include/spidermonkey/mozilla/EnumSet.h b/mac/include/spidermonkey/mozilla/EnumSet.h deleted file mode 100644 index 5282ab30..00000000 --- a/mac/include/spidermonkey/mozilla/EnumSet.h +++ /dev/null @@ -1,344 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A set abstraction for enumeration values. */ - -#ifndef mozilla_EnumSet_h -#define mozilla_EnumSet_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#include - -#include - -namespace mozilla { - -/** - * EnumSet is a set of values defined by an enumeration. It is implemented - * using a 32 bit mask for each value so it will only work for enums with an int - * representation less than 32. It works both for enum and enum class types. - */ -template -class EnumSet -{ -public: - EnumSet() - : mBitField(0) - { - initVersion(); - } - - MOZ_IMPLICIT EnumSet(T aEnum) - : mBitField(bitFor(aEnum)) - { } - - EnumSet(T aEnum1, T aEnum2) - : mBitField(bitFor(aEnum1) | - bitFor(aEnum2)) - { - initVersion(); - } - - EnumSet(T aEnum1, T aEnum2, T aEnum3) - : mBitField(bitFor(aEnum1) | - bitFor(aEnum2) | - bitFor(aEnum3)) - { - initVersion(); - } - - EnumSet(T aEnum1, T aEnum2, T aEnum3, T aEnum4) - : mBitField(bitFor(aEnum1) | - bitFor(aEnum2) | - bitFor(aEnum3) | - bitFor(aEnum4)) - { - initVersion(); - } - - MOZ_IMPLICIT EnumSet(std::initializer_list list) - : mBitField(0) - { - for (auto value : list) { - (*this) += value; - } - initVersion(); - } - - EnumSet(const EnumSet& aEnumSet) - : mBitField(aEnumSet.mBitField) - { - initVersion(); - } - - /** - * Add an element - */ - void operator+=(T aEnum) - { - incVersion(); - mBitField |= bitFor(aEnum); - } - - /** - * Add an element - */ - EnumSet operator+(T aEnum) const - { - EnumSet result(*this); - result += aEnum; - return result; - } - - /** - * Union - */ - void operator+=(const EnumSet aEnumSet) - { - incVersion(); - mBitField |= aEnumSet.mBitField; - } - - /** - * Union - */ - EnumSet operator+(const EnumSet aEnumSet) const - { - EnumSet result(*this); - result += aEnumSet; - return result; - } - - /** - * Remove an element - */ - void operator-=(T aEnum) - { - incVersion(); - mBitField &= ~(bitFor(aEnum)); - } - - /** - * Remove an element - */ - EnumSet operator-(T aEnum) const - { - EnumSet result(*this); - result -= aEnum; - return result; - } - - /** - * Remove a set of elements - */ - void operator-=(const EnumSet aEnumSet) - { - incVersion(); - mBitField &= ~(aEnumSet.mBitField); - } - - /** - * Remove a set of elements - */ - EnumSet operator-(const EnumSet aEnumSet) const - { - EnumSet result(*this); - result -= aEnumSet; - return result; - } - - /** - * Clear - */ - void clear() - { - incVersion(); - mBitField = 0; - } - - /** - * Intersection - */ - void operator&=(const EnumSet aEnumSet) - { - incVersion(); - mBitField &= aEnumSet.mBitField; - } - - /** - * Intersection - */ - EnumSet operator&(const EnumSet aEnumSet) const - { - EnumSet result(*this); - result &= aEnumSet; - return result; - } - - /** - * Equality - */ - bool operator==(const EnumSet aEnumSet) const - { - return mBitField == aEnumSet.mBitField; - } - - /** - * Test is an element is contained in the set. - */ - bool contains(T aEnum) const - { - return mBitField & bitFor(aEnum); - } - - /** - * Return the number of elements in the set. - */ - uint8_t size() const - { - uint8_t count = 0; - for (uint32_t bitField = mBitField; bitField; bitField >>= 1) { - if (bitField & 1) { - count++; - } - } - return count; - } - - bool isEmpty() const - { - return mBitField == 0; - } - - uint32_t serialize() const - { - return mBitField; - } - - void deserialize(uint32_t aValue) - { - incVersion(); - mBitField = aValue; - } - - class ConstIterator - { - const EnumSet* mSet; - uint32_t mPos; -#ifdef DEBUG - uint64_t mVersion; -#endif - - void checkVersion() { - // Check that the set has not been modified while being iterated. - MOZ_ASSERT_IF(mSet, mSet->mVersion == mVersion); - } - - public: - ConstIterator(const EnumSet& aSet, uint32_t aPos) - : mSet(&aSet), mPos(aPos) - { -#ifdef DEBUG - mVersion = mSet->mVersion; -#endif - MOZ_ASSERT(aPos <= kMaxBits); - if (aPos != kMaxBits && !mSet->contains(T(mPos))) - ++*this; - } - - ConstIterator(const ConstIterator& aOther) - : mSet(aOther.mSet), mPos(aOther.mPos) - { -#ifdef DEBUG - mVersion = aOther.mVersion; - checkVersion(); -#endif - } - - ConstIterator(ConstIterator&& aOther) - : mSet(aOther.mSet), mPos(aOther.mPos) - { -#ifdef DEBUG - mVersion = aOther.mVersion; - checkVersion(); -#endif - aOther.mSet = nullptr; - } - - ~ConstIterator() { - checkVersion(); - } - - bool operator==(const ConstIterator& other) { - MOZ_ASSERT(mSet == other.mSet); - checkVersion(); - return mPos == other.mPos; - } - - bool operator!=(const ConstIterator& other) { - return !(*this == other); - } - - T operator*() { - MOZ_ASSERT(mSet); - MOZ_ASSERT(mPos < kMaxBits); - MOZ_ASSERT(mSet->contains(T(mPos))); - checkVersion(); - return T(mPos); - } - - ConstIterator& operator++() { - MOZ_ASSERT(mSet); - MOZ_ASSERT(mPos < kMaxBits); - checkVersion(); - do { - mPos++; - } while (mPos < kMaxBits && !mSet->contains(T(mPos))); - return *this; - } - }; - - ConstIterator begin() const { - return ConstIterator(*this, 0); - } - - ConstIterator end() const { - return ConstIterator(*this, kMaxBits); - } - -private: - static uint32_t bitFor(T aEnum) - { - uint32_t bitNumber = (uint32_t)aEnum; - MOZ_ASSERT(bitNumber < kMaxBits); - return 1U << bitNumber; - } - - void initVersion() { -#ifdef DEBUG - mVersion = 0; -#endif - } - - void incVersion() { -#ifdef DEBUG - mVersion++; -#endif - } - - static const size_t kMaxBits = 32; - uint32_t mBitField; - -#ifdef DEBUG - uint64_t mVersion; -#endif -}; - -} // namespace mozilla - -#endif /* mozilla_EnumSet_h_*/ diff --git a/mac/include/spidermonkey/mozilla/EnumTypeTraits.h b/mac/include/spidermonkey/mozilla/EnumTypeTraits.h deleted file mode 100644 index 223eaf8c..00000000 --- a/mac/include/spidermonkey/mozilla/EnumTypeTraits.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Type traits for enums. */ - -#ifndef mozilla_EnumTypeTraits_h -#define mozilla_EnumTypeTraits_h - -#include - -namespace mozilla { - -namespace detail { - -template -struct EnumFitsWithinHelper; - -// Signed enum, signed storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -// Signed enum, unsigned storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -// Unsigned enum, signed storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -// Unsigned enum, unsigned storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -} // namespace detail - -/* - * Type trait that determines whether the enum type T can fit within the - * integral type Storage without data loss. This trait should be used with - * caution with an enum type whose underlying type has not been explicitly - * specified: for such enums, the C++ implementation is free to choose a type - * no smaller than int whose range encompasses all possible values of the enum. - * So for an enum with only small non-negative values, the underlying type may - * be either int or unsigned int, depending on the whims of the implementation. - */ -template -struct EnumTypeFitsWithin - : public detail::EnumFitsWithinHelper< - sizeof(T), - std::is_signed::type>::value, - sizeof(Storage), - std::is_signed::value - > -{ - static_assert(std::is_enum::value, "must provide an enum type"); - static_assert(std::is_integral::value, "must provide an integral type"); -}; - -} // namespace mozilla - -#endif /* mozilla_EnumTypeTraits_h */ diff --git a/mac/include/spidermonkey/mozilla/EnumeratedArray.h b/mac/include/spidermonkey/mozilla/EnumeratedArray.h deleted file mode 100644 index 9e74b772..00000000 --- a/mac/include/spidermonkey/mozilla/EnumeratedArray.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* EnumeratedArray is like Array, but indexed by a typed enum. */ - -#ifndef mozilla_EnumeratedArray_h -#define mozilla_EnumeratedArray_h - -#include "mozilla/Array.h" -#include "mozilla/Move.h" - -namespace mozilla { - -/** - * EnumeratedArray is a fixed-size array container for use when an - * array is indexed by a specific enum class. - * - * This provides type safety by guarding at compile time against accidentally - * indexing such arrays with unrelated values. This also removes the need - * for manual casting when using a typed enum value to index arrays. - * - * Aside from the typing of indices, EnumeratedArray is similar to Array. - * - * Example: - * - * enum class AnimalSpecies { - * Cow, - * Sheep, - * Count - * }; - * - * EnumeratedArray headCount; - * - * headCount[AnimalSpecies::Cow] = 17; - * headCount[AnimalSpecies::Sheep] = 30; - * - */ -template -class EnumeratedArray -{ -public: - static const size_t kSize = size_t(SizeAsEnumValue); - -private: - typedef Array ArrayType; - - ArrayType mArray; - -public: - EnumeratedArray() {} - - template - MOZ_IMPLICIT EnumeratedArray(Args&&... aArgs) - : mArray{mozilla::Forward(aArgs)...} - {} - - explicit EnumeratedArray(const EnumeratedArray& aOther) - { - for (size_t i = 0; i < kSize; i++) { - mArray[i] = aOther.mArray[i]; - } - } - - EnumeratedArray(EnumeratedArray&& aOther) - { - for (size_t i = 0; i < kSize; i++) { - mArray[i] = Move(aOther.mArray[i]); - } - } - - ValueType& operator[](IndexType aIndex) - { - return mArray[size_t(aIndex)]; - } - - const ValueType& operator[](IndexType aIndex) const - { - return mArray[size_t(aIndex)]; - } - - typedef typename ArrayType::iterator iterator; - typedef typename ArrayType::const_iterator const_iterator; - typedef typename ArrayType::reverse_iterator reverse_iterator; - typedef typename ArrayType::const_reverse_iterator const_reverse_iterator; - - // Methods for range-based for loops. - iterator begin() { return mArray.begin(); } - const_iterator begin() const { return mArray.begin(); } - const_iterator cbegin() const { return mArray.cbegin(); } - iterator end() { return mArray.end(); } - const_iterator end() const { return mArray.end(); } - const_iterator cend() const { return mArray.cend(); } - - // Methods for reverse iterating. - reverse_iterator rbegin() { return mArray.rbegin(); } - const_reverse_iterator rbegin() const { return mArray.rbegin(); } - const_reverse_iterator crbegin() const { return mArray.crbegin(); } - reverse_iterator rend() { return mArray.rend(); } - const_reverse_iterator rend() const { return mArray.rend(); } - const_reverse_iterator crend() const { return mArray.crend(); } -}; - -} // namespace mozilla - -#endif // mozilla_EnumeratedArray_h diff --git a/mac/include/spidermonkey/mozilla/EnumeratedRange.h b/mac/include/spidermonkey/mozilla/EnumeratedRange.h deleted file mode 100644 index b158f8a3..00000000 --- a/mac/include/spidermonkey/mozilla/EnumeratedRange.h +++ /dev/null @@ -1,201 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Iterator over contiguous enum values */ - -/* - * Implements generator functions that create a range to iterate over the values - * of a scoped or unscoped enum. Unlike IntegerRange, which can only function on - * the underlying integral type, the elements of the generated sequence will - * have the type of the enum in question. - * - * Note that the enum values should be contiguous in the iterated range; - * unfortunately there exists no way for EnumeratedRange to enforce this - * either dynamically or at compile time. - */ - -#ifndef mozilla_EnumeratedRange_h -#define mozilla_EnumeratedRange_h - -#include - -#include "mozilla/ReverseIterator.h" - -namespace mozilla { - -namespace detail { - -template -class EnumeratedIterator -{ -public: - typedef typename std::underlying_type::type IntTypeT; - - template - explicit EnumeratedIterator(EnumType aCurrent) - : mCurrent(aCurrent) { } - - template - explicit EnumeratedIterator(const EnumeratedIterator& aOther) - : mCurrent(aOther.mCurrent) { } - - EnumTypeT operator*() const { return mCurrent; } - - /* Increment and decrement operators */ - - EnumeratedIterator& operator++() - { - mCurrent = EnumTypeT(IntTypeT(mCurrent) + IntTypeT(1)); - return *this; - } - EnumeratedIterator& operator--() - { - mCurrent = EnumTypeT(IntTypeT(mCurrent) - IntTypeT(1)); - return *this; - } - EnumeratedIterator operator++(int) - { - auto ret = *this; - mCurrent = EnumTypeT(IntTypeT(mCurrent) + IntTypeT(1)); - return ret; - } - EnumeratedIterator operator--(int) - { - auto ret = *this; - mCurrent = EnumTypeT(IntTypeT(mCurrent) - IntTypeT(1)); - return ret; - } - - /* Comparison operators */ - - template - friend bool operator==(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator!=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator<(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator<=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator>(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator>=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - -private: - EnumTypeT mCurrent; -}; - -template -bool operator==(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent == aIter2.mCurrent; -} - -template -bool operator!=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent != aIter2.mCurrent; -} - -template -bool operator<(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent < aIter2.mCurrent; -} - -template -bool operator<=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent <= aIter2.mCurrent; -} - -template -bool operator>(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent > aIter2.mCurrent; -} - -template -bool operator>=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent >= aIter2.mCurrent; -} - -template -class EnumeratedRange -{ -public: - typedef EnumeratedIterator iterator; - typedef EnumeratedIterator const_iterator; - typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; - - template - EnumeratedRange(EnumType aBegin, EnumType aEnd) - : mBegin(aBegin), mEnd(aEnd) { } - - iterator begin() const { return iterator(mBegin); } - const_iterator cbegin() const { return begin(); } - iterator end() const { return iterator(mEnd); } - const_iterator cend() const { return end(); } - reverse_iterator rbegin() const { return reverse_iterator(mEnd); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() const { return reverse_iterator(mBegin); } - const_reverse_iterator crend() const { return rend(); } - -private: - EnumTypeT mBegin; - EnumTypeT mEnd; -}; - -} // namespace detail - -#ifdef __GNUC__ -// Enums can have an unsigned underlying type, which makes some of the -// comparisons below always true or always false. Temporarily disable -// -Wtype-limits to avoid breaking -Werror builds. -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wtype-limits" -#endif - -// Create a range to iterate from aBegin to aEnd, exclusive. -template -inline detail::EnumeratedRange -MakeEnumeratedRange(EnumType aBegin, EnumType aEnd) -{ - MOZ_ASSERT(aBegin <= aEnd, "Cannot generate invalid, unbounded range!"); - return detail::EnumeratedRange(aBegin, aEnd); -} - -// Create a range to iterate from EnumType(0) to aEnd, exclusive. EnumType(0) -// should exist, but note that there is no way for us to ensure that it does! -template -inline detail::EnumeratedRange -MakeEnumeratedRange(EnumType aEnd) -{ - return MakeEnumeratedRange(EnumType(0), aEnd); -} - -#ifdef __GNUC__ -# pragma GCC diagnostic pop -#endif - -} // namespace mozilla - -#endif // mozilla_EnumeratedRange_h - diff --git a/mac/include/spidermonkey/mozilla/FastBernoulliTrial.h b/mac/include/spidermonkey/mozilla/FastBernoulliTrial.h deleted file mode 100644 index 7e38b70a..00000000 --- a/mac/include/spidermonkey/mozilla/FastBernoulliTrial.h +++ /dev/null @@ -1,379 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_FastBernoulliTrial_h -#define mozilla_FastBernoulliTrial_h - -#include "mozilla/Assertions.h" -#include "mozilla/XorShift128PlusRNG.h" - -#include -#include - -namespace mozilla { - -/** - * class FastBernoulliTrial: Efficient sampling with uniform probability - * - * When gathering statistics about a program's behavior, we may be observing - * events that occur very frequently (e.g., function calls or memory - * allocations) and we may be gathering information that is somewhat expensive - * to produce (e.g., call stacks). Sampling all the events could have a - * significant impact on the program's performance. - * - * Why not just sample every N'th event? This technique is called "systematic - * sampling"; it's simple and efficient, and it's fine if we imagine a - * patternless stream of events. But what if we're sampling allocations, and the - * program happens to have a loop where each iteration does exactly N - * allocations? You would end up sampling the same allocation every time through - * the loop; the entire rest of the loop becomes invisible to your measurements! - * More generally, if each iteration does M allocations, and M and N have any - * common divisor at all, most allocation sites will never be sampled. If - * they're both even, say, the odd-numbered allocations disappear from your - * results. - * - * Ideally, we'd like each event to have some probability P of being sampled, - * independent of its neighbors and of its position in the sequence. This is - * called "Bernoulli sampling", and it doesn't suffer from any of the problems - * mentioned above. - * - * One disadvantage of Bernoulli sampling is that you can't be sure exactly how - * many samples you'll get: technically, it's possible that you might sample - * none of them, or all of them. But if the number of events N is large, these - * aren't likely outcomes; you can generally expect somewhere around P * N - * events to be sampled. - * - * The other disadvantage of Bernoulli sampling is that you have to generate a - * random number for every event, which can be slow. - * - * [significant pause] - * - * BUT NOT WITH THIS CLASS! FastBernoulliTrial lets you do true Bernoulli - * sampling, while generating a fresh random number only when we do decide to - * sample an event, not on every trial. When it decides not to sample, a call to - * |FastBernoulliTrial::trial| is nothing but decrementing a counter and - * comparing it to zero. So the lower your sampling probability is, the less - * overhead FastBernoulliTrial imposes. - * - * Probabilities of 0 and 1 are handled efficiently. (In neither case need we - * ever generate a random number at all.) - * - * The essential API: - * - * - FastBernoulliTrial(double P) - * Construct an instance that selects events with probability P. - * - * - FastBernoulliTrial::trial() - * Return true with probability P. Call this each time an event occurs, to - * decide whether to sample it or not. - * - * - FastBernoulliTrial::trial(size_t n) - * Equivalent to calling trial() |n| times, and returning true if any of those - * calls do. However, like trial, this runs in fast constant time. - * - * What is this good for? In some applications, some events are "bigger" than - * others. For example, large allocations are more significant than small - * allocations. Perhaps we'd like to imagine that we're drawing allocations - * from a stream of bytes, and performing a separate Bernoulli trial on every - * byte from the stream. We can accomplish this by calling |t.trial(S)| for - * the number of bytes S, and sampling the event if that returns true. - * - * Of course, this style of sampling needs to be paired with analysis and - * presentation that makes the size of the event apparent, lest trials with - * large values for |n| appear to be indistinguishable from those with small - * values for |n|. - */ -class FastBernoulliTrial { - /* - * This comment should just read, "Generate skip counts with a geometric - * distribution", and leave everyone to go look that up and see why it's the - * right thing to do, if they don't know already. - * - * BUT IF YOU'RE CURIOUS, COMMENTS ARE FREE... - * - * Instead of generating a fresh random number for every trial, we can - * randomly generate a count of how many times we should return false before - * the next time we return true. We call this a "skip count". Once we've - * returned true, we generate a fresh skip count, and begin counting down - * again. - * - * Here's an awesome fact: by exercising a little care in the way we generate - * skip counts, we can produce results indistinguishable from those we would - * get "rolling the dice" afresh for every trial. - * - * In short, skip counts in Bernoulli trials of probability P obey a geometric - * distribution. If a random variable X is uniformly distributed from [0..1), - * then std::floor(std::log(X) / std::log(1-P)) has the appropriate geometric - * distribution for the skip counts. - * - * Why that formula? - * - * Suppose we're to return |true| with some probability P, say, 0.3. Spread - * all possible futures along a line segment of length 1. In portion P of - * those cases, we'll return true on the next call to |trial|; the skip count - * is 0. For the remaining portion 1-P of cases, the skip count is 1 or more. - * - * skip: 0 1 or more - * |------------------^-----------------------------------------| - * portion: 0.3 0.7 - * P 1-P - * - * But the "1 or more" section of the line is subdivided the same way: *within - * that section*, in portion P the second call to |trial()| returns true, and in - * portion 1-P it returns false a second time; the skip count is two or more. - * So we return true on the second call in proportion 0.7 * 0.3, and skip at - * least the first two in proportion 0.7 * 0.7. - * - * skip: 0 1 2 or more - * |------------------^------------^----------------------------| - * portion: 0.3 0.7 * 0.3 0.7 * 0.7 - * P (1-P)*P (1-P)^2 - * - * We can continue to subdivide: - * - * skip >= 0: |------------------------------------------------- (1-P)^0 --| - * skip >= 1: | ------------------------------- (1-P)^1 --| - * skip >= 2: | ------------------ (1-P)^2 --| - * skip >= 3: | ^ ---------- (1-P)^3 --| - * skip >= 4: | . --- (1-P)^4 --| - * . - * ^X, see below - * - * In other words, the likelihood of the next n calls to |trial| returning - * false is (1-P)^n. The longer a run we require, the more the likelihood - * drops. Further calls may return false too, but this is the probability - * we'll skip at least n. - * - * This is interesting, because we can pick a point along this line segment - * and see which skip count's range it falls within; the point X above, for - * example, is within the ">= 2" range, but not within the ">= 3" range, so it - * designates a skip count of 2. So if we pick points on the line at random - * and use the skip counts they fall under, that will be indistinguishable - * from generating a fresh random number between 0 and 1 for each trial and - * comparing it to P. - * - * So to find the skip count for a point X, we must ask: To what whole power - * must we raise 1-P such that we include X, but the next power would exclude - * it? This is exactly std::floor(std::log(X) / std::log(1-P)). - * - * Our algorithm is then, simply: When constructed, compute an initial skip - * count. Return false from |trial| that many times, and then compute a new skip - * count. - * - * For a call to |trial(n)|, if the skip count is greater than n, return false - * and subtract n from the skip count. If the skip count is less than n, - * return true and compute a new skip count. Since each trial is independent, - * it doesn't matter by how much n overshoots the skip count; we can actually - * compute a new skip count at *any* time without affecting the distribution. - * This is really beautiful. - */ - public: - /** - * Construct a fast Bernoulli trial generator. Calls to |trial()| return true - * with probability |aProbability|. Use |aState0| and |aState1| to seed the - * random number generator; both may not be zero. - */ - FastBernoulliTrial(double aProbability, uint64_t aState0, uint64_t aState1) - : mProbability(0) - , mInvLogNotProbability(0) - , mGenerator(aState0, aState1) - , mSkipCount(0) - { - setProbability(aProbability); - } - - /** - * Return true with probability |mProbability|. Call this each time an event - * occurs, to decide whether to sample it or not. The lower |mProbability| is, - * the faster this function runs. - */ - bool trial() { - if (mSkipCount) { - mSkipCount--; - return false; - } - - return chooseSkipCount(); - } - - /** - * Equivalent to calling trial() |n| times, and returning true if any of those - * calls do. However, like trial, this runs in fast constant time. - * - * What is this good for? In some applications, some events are "bigger" than - * others. For example, large allocations are more significant than small - * allocations. Perhaps we'd like to imagine that we're drawing allocations - * from a stream of bytes, and performing a separate Bernoulli trial on every - * byte from the stream. We can accomplish this by calling |t.trial(S)| for - * the number of bytes S, and sampling the event if that returns true. - * - * Of course, this style of sampling needs to be paired with analysis and - * presentation that makes the "size" of the event apparent, lest trials with - * large values for |n| appear to be indistinguishable from those with small - * values for |n|, despite being potentially much more likely to be sampled. - */ - bool trial(size_t aCount) { - if (mSkipCount > aCount) { - mSkipCount -= aCount; - return false; - } - - return chooseSkipCount(); - } - - void setRandomState(uint64_t aState0, uint64_t aState1) { - mGenerator.setState(aState0, aState1); - } - - void setProbability(double aProbability) { - MOZ_ASSERT(0 <= aProbability && aProbability <= 1); - mProbability = aProbability; - if (0 < mProbability && mProbability < 1) { - /* - * Let's look carefully at how this calculation plays out in floating- - * point arithmetic. We'll assume IEEE, but the final C++ code we arrive - * at would still be fine if our numbers were mathematically perfect. So, - * while we've considered IEEE's edge cases, we haven't done anything that - * should be actively bad when using other representations. - * - * (In the below, read comparisons as exact mathematical comparisons: when - * we say something "equals 1", that means it's exactly equal to 1. We - * treat approximation using intervals with open boundaries: saying a - * value is in (0,1) doesn't specify how close to 0 or 1 the value gets. - * When we use closed boundaries like [2**-53, 1], we're careful to ensure - * the boundary values are actually representable.) - * - * - After the comparison above, we know mProbability is in (0,1). - * - * - The gaps below 1 are 2**-53, so that interval is (0, 1-2**-53]. - * - * - Because the floating-point gaps near 1 are wider than those near - * zero, there are many small positive doubles ε such that 1-ε rounds to - * exactly 1. However, 2**-53 can be represented exactly. So - * 1-mProbability is in [2**-53, 1]. - * - * - log(1 - mProbability) is thus in (-37, 0]. - * - * That range includes zero, but when we use mInvLogNotProbability, it - * would be helpful if we could trust that it's negative. So when log(1 - * - mProbability) is 0, we'll just set mProbability to 0, so that - * mInvLogNotProbability is not used in chooseSkipCount. - * - * - How much of the range of mProbability does this cause us to ignore? - * The only value for which log returns 0 is exactly 1; the slope of log - * at 1 is 1, so for small ε such that 1 - ε != 1, log(1 - ε) is -ε, - * never 0. The gaps near one are larger than the gaps near zero, so if - * 1 - ε wasn't 1, then -ε is representable. So if log(1 - mProbability) - * isn't 0, then 1 - mProbability isn't 1, which means that mProbability - * is at least 2**-53, as discussed earlier. This is a sampling - * likelihood of roughly one in ten trillion, which is unlikely to be - * distinguishable from zero in practice. - * - * So by forbidding zero, we've tightened our range to (-37, -2**-53]. - * - * - Finally, 1 / log(1 - mProbability) is in [-2**53, -1/37). This all - * falls readily within the range of an IEEE double. - * - * ALL THAT HAVING BEEN SAID: here are the five lines of actual code: - */ - double logNotProbability = std::log(1 - mProbability); - if (logNotProbability == 0.0) - mProbability = 0.0; - else - mInvLogNotProbability = 1 / logNotProbability; - } - - chooseSkipCount(); - } - - private: - /* The likelihood that any given call to |trial| should return true. */ - double mProbability; - - /* - * The value of 1/std::log(1 - mProbability), cached for repeated use. - * - * If mProbability is exactly 0 or exactly 1, we don't use this value. - * Otherwise, we guarantee this value is in the range [-2**53, -1/37), i.e. - * definitely negative, as required by chooseSkipCount. See setProbability for - * the details. - */ - double mInvLogNotProbability; - - /* Our random number generator. */ - non_crypto::XorShift128PlusRNG mGenerator; - - /* The number of times |trial| should return false before next returning true. */ - size_t mSkipCount; - - /* - * Choose the next skip count. This also returns the value that |trial| should - * return, since we have to check for the extreme values for mProbability - * anyway, and |trial| should never return true at all when mProbability is 0. - */ - bool chooseSkipCount() { - /* - * If the probability is 1.0, every call to |trial| returns true. Make sure - * mSkipCount is 0. - */ - if (mProbability == 1.0) { - mSkipCount = 0; - return true; - } - - /* - * If the probabilility is zero, |trial| never returns true. Don't bother us - * for a while. - */ - if (mProbability == 0.0) { - mSkipCount = SIZE_MAX; - return false; - } - - /* - * What sorts of values can this call to std::floor produce? - * - * Since mGenerator.nextDouble returns a value in [0, 1-2**-53], std::log - * returns a value in the range [-infinity, -2**-53], all negative. Since - * mInvLogNotProbability is negative (see its comments), the product is - * positive and possibly infinite. std::floor returns +infinity unchanged. - * So the result will always be positive. - * - * Converting a double to an integer that is out of range for that integer - * is undefined behavior, so we must clamp our result to SIZE_MAX, to ensure - * we get an acceptable value for mSkipCount. - * - * The clamp is written carefully. Note that if we had said: - * - * if (skipCount > SIZE_MAX) - * skipCount = SIZE_MAX; - * - * that leads to undefined behavior 64-bit machines: SIZE_MAX coerced to - * double is 2^64, not 2^64-1, so this doesn't actually set skipCount to a - * value that can be safely assigned to mSkipCount. - * - * Jakub Oleson cleverly suggested flipping the sense of the comparison: if - * we require that skipCount < SIZE_MAX, then because of the gaps (2048) - * between doubles at that magnitude, the highest double less than 2^64 is - * 2^64 - 2048, which is fine to store in a size_t. - * - * (On 32-bit machines, all size_t values can be represented exactly in - * double, so all is well.) - */ - double skipCount = std::floor(std::log(mGenerator.nextDouble()) - * mInvLogNotProbability); - if (skipCount < SIZE_MAX) - mSkipCount = skipCount; - else - mSkipCount = SIZE_MAX; - - return true; - } -}; - -} /* namespace mozilla */ - -#endif /* mozilla_FastBernoulliTrial_h */ diff --git a/mac/include/spidermonkey/mozilla/FloatingPoint.h b/mac/include/spidermonkey/mozilla/FloatingPoint.h deleted file mode 100644 index 59afccd1..00000000 --- a/mac/include/spidermonkey/mozilla/FloatingPoint.h +++ /dev/null @@ -1,479 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Various predicates and operations on IEEE-754 floating point types. */ - -#ifndef mozilla_FloatingPoint_h -#define mozilla_FloatingPoint_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/MathAlgorithms.h" -#include "mozilla/Types.h" - -#include - -namespace mozilla { - -/* - * It's reasonable to ask why we have this header at all. Don't isnan, - * copysign, the built-in comparison operators, and the like solve these - * problems? Unfortunately, they don't. We've found that various compilers - * (MSVC, MSVC when compiling with PGO, and GCC on OS X, at least) miscompile - * the standard methods in various situations, so we can't use them. Some of - * these compilers even have problems compiling seemingly reasonable bitwise - * algorithms! But with some care we've found algorithms that seem to not - * trigger those compiler bugs. - * - * For the aforementioned reasons, be very wary of making changes to any of - * these algorithms. If you must make changes, keep a careful eye out for - * compiler bustage, particularly PGO-specific bustage. - */ - -struct FloatTypeTraits -{ - typedef uint32_t Bits; - - static const unsigned kExponentBias = 127; - static const unsigned kExponentShift = 23; - - static const Bits kSignBit = 0x80000000UL; - static const Bits kExponentBits = 0x7F800000UL; - static const Bits kSignificandBits = 0x007FFFFFUL; -}; - -struct DoubleTypeTraits -{ - typedef uint64_t Bits; - - static const unsigned kExponentBias = 1023; - static const unsigned kExponentShift = 52; - - static const Bits kSignBit = 0x8000000000000000ULL; - static const Bits kExponentBits = 0x7ff0000000000000ULL; - static const Bits kSignificandBits = 0x000fffffffffffffULL; -}; - -template struct SelectTrait; -template<> struct SelectTrait : public FloatTypeTraits {}; -template<> struct SelectTrait : public DoubleTypeTraits {}; - -/* - * This struct contains details regarding the encoding of floating-point - * numbers that can be useful for direct bit manipulation. As of now, the - * template parameter has to be float or double. - * - * The nested typedef |Bits| is the unsigned integral type with the same size - * as T: uint32_t for float and uint64_t for double (static assertions - * double-check these assumptions). - * - * kExponentBias is the offset that is subtracted from the exponent when - * computing the value, i.e. one plus the opposite of the mininum possible - * exponent. - * kExponentShift is the shift that one needs to apply to retrieve the - * exponent component of the value. - * - * kSignBit contains a bits mask. Bit-and-ing with this mask will result in - * obtaining the sign bit. - * kExponentBits contains the mask needed for obtaining the exponent bits and - * kSignificandBits contains the mask needed for obtaining the significand - * bits. - * - * Full details of how floating point number formats are encoded are beyond - * the scope of this comment. For more information, see - * http://en.wikipedia.org/wiki/IEEE_floating_point - * http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers - */ -template -struct FloatingPoint : public SelectTrait -{ - typedef SelectTrait Base; - typedef typename Base::Bits Bits; - - static_assert((Base::kSignBit & Base::kExponentBits) == 0, - "sign bit shouldn't overlap exponent bits"); - static_assert((Base::kSignBit & Base::kSignificandBits) == 0, - "sign bit shouldn't overlap significand bits"); - static_assert((Base::kExponentBits & Base::kSignificandBits) == 0, - "exponent bits shouldn't overlap significand bits"); - - static_assert((Base::kSignBit | Base::kExponentBits | Base::kSignificandBits) == - ~Bits(0), - "all bits accounted for"); - - /* - * These implementations assume float/double are 32/64-bit single/double - * format number types compatible with the IEEE-754 standard. C++ don't - * require this to be the case. But we required this in implementations of - * these algorithms that preceded this header, so we shouldn't break anything - * if we keep doing so. - */ - static_assert(sizeof(T) == sizeof(Bits), "Bits must be same size as T"); -}; - -/** Determines whether a float/double is NaN. */ -template -static MOZ_ALWAYS_INLINE bool -IsNaN(T aValue) -{ - /* - * A float/double is NaN if all exponent bits are 1 and the significand - * contains at least one non-zero bit. - */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - return (BitwiseCast(aValue) & Traits::kExponentBits) == Traits::kExponentBits && - (BitwiseCast(aValue) & Traits::kSignificandBits) != 0; -} - -/** Determines whether a float/double is +Infinity or -Infinity. */ -template -static MOZ_ALWAYS_INLINE bool -IsInfinite(T aValue) -{ - /* Infinities have all exponent bits set to 1 and an all-0 significand. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return (bits & ~Traits::kSignBit) == Traits::kExponentBits; -} - -/** Determines whether a float/double is not NaN or infinite. */ -template -static MOZ_ALWAYS_INLINE bool -IsFinite(T aValue) -{ - /* - * NaN and Infinities are the only non-finite floats/doubles, and both have - * all exponent bits set to 1. - */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return (bits & Traits::kExponentBits) != Traits::kExponentBits; -} - -/** - * Determines whether a float/double is negative or -0. It is an error - * to call this method on a float/double which is NaN. - */ -template -static MOZ_ALWAYS_INLINE bool -IsNegative(T aValue) -{ - MOZ_ASSERT(!IsNaN(aValue), "NaN does not have a sign"); - - /* The sign bit is set if the double is negative. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return (bits & Traits::kSignBit) != 0; -} - -/** Determines whether a float/double represents -0. */ -template -static MOZ_ALWAYS_INLINE bool -IsNegativeZero(T aValue) -{ - /* Only the sign bit is set if the value is -0. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return bits == Traits::kSignBit; -} - -/** Determines wether a float/double represents +0. */ -template -static MOZ_ALWAYS_INLINE bool -IsPositiveZero(T aValue) -{ - /* All bits are zero if the value is +0. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return bits == 0; -} - -/** - * Returns 0 if a float/double is NaN or infinite; - * otherwise, the float/double is returned. - */ -template -static MOZ_ALWAYS_INLINE T -ToZeroIfNonfinite(T aValue) -{ - return IsFinite(aValue) ? aValue : 0; -} - -/** - * Returns the exponent portion of the float/double. - * - * Zero is not special-cased, so ExponentComponent(0.0) is - * -int_fast16_t(Traits::kExponentBias). - */ -template -static MOZ_ALWAYS_INLINE int_fast16_t -ExponentComponent(T aValue) -{ - /* - * The exponent component of a float/double is an unsigned number, biased - * from its actual value. Subtract the bias to retrieve the actual exponent. - */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return int_fast16_t((bits & Traits::kExponentBits) >> Traits::kExponentShift) - - int_fast16_t(Traits::kExponentBias); -} - -/** Returns +Infinity. */ -template -static MOZ_ALWAYS_INLINE T -PositiveInfinity() -{ - /* - * Positive infinity has all exponent bits set, sign bit set to 0, and no - * significand. - */ - typedef FloatingPoint Traits; - return BitwiseCast(Traits::kExponentBits); -} - -/** Returns -Infinity. */ -template -static MOZ_ALWAYS_INLINE T -NegativeInfinity() -{ - /* - * Negative infinity has all exponent bits set, sign bit set to 1, and no - * significand. - */ - typedef FloatingPoint Traits; - return BitwiseCast(Traits::kSignBit | Traits::kExponentBits); -} - -/** - * Computes the bit pattern for a NaN with the specified sign bit and - * significand bits. - */ -template::Bits Significand> -struct SpecificNaNBits -{ - using Traits = FloatingPoint; - - static_assert(SignBit == 0 || SignBit == 1, "bad sign bit"); - static_assert((Significand & ~Traits::kSignificandBits) == 0, - "significand must only have significand bits set"); - static_assert(Significand & Traits::kSignificandBits, - "significand must be nonzero"); - - static constexpr typename Traits::Bits value = - (SignBit * Traits::kSignBit) | Traits::kExponentBits | Significand; -}; - -/** - * Constructs a NaN value with the specified sign bit and significand bits. - * - * There is also a variant that returns the value directly. In most cases, the - * two variants should be identical. However, in the specific case of x86 - * chips, the behavior differs: returning floating-point values directly is done - * through the x87 stack, and x87 loads and stores turn signaling NaNs into - * quiet NaNs... silently. Returning floating-point values via outparam, - * however, is done entirely within the SSE registers when SSE2 floating-point - * is enabled in the compiler, which has semantics-preserving behavior you would - * expect. - * - * If preserving the distinction between signaling NaNs and quiet NaNs is - * important to you, you should use the outparam version. In all other cases, - * you should use the direct return version. - */ -template -static MOZ_ALWAYS_INLINE void -SpecificNaN(int signbit, typename FloatingPoint::Bits significand, T* result) -{ - typedef FloatingPoint Traits; - MOZ_ASSERT(signbit == 0 || signbit == 1); - MOZ_ASSERT((significand & ~Traits::kSignificandBits) == 0); - MOZ_ASSERT(significand & Traits::kSignificandBits); - - BitwiseCast((signbit ? Traits::kSignBit : 0) | - Traits::kExponentBits | - significand, - result); - MOZ_ASSERT(IsNaN(*result)); -} - -template -static MOZ_ALWAYS_INLINE T -SpecificNaN(int signbit, typename FloatingPoint::Bits significand) -{ - T t; - SpecificNaN(signbit, significand, &t); - return t; -} - -/** Computes the smallest non-zero positive float/double value. */ -template -static MOZ_ALWAYS_INLINE T -MinNumberValue() -{ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - return BitwiseCast(Bits(1)); -} - -/** - * If aValue is equal to some int32_t value, set *aInt32 to that value and - * return true; otherwise return false. - * - * Note that negative zero is "equal" to zero here. To test whether a value can - * be losslessly converted to int32_t and back, use NumberIsInt32 instead. - */ -template -static MOZ_ALWAYS_INLINE bool -NumberEqualsInt32(T aValue, int32_t* aInt32) -{ - /* - * XXX Casting a floating-point value that doesn't truncate to int32_t, to - * int32_t, induces undefined behavior. We should definitely fix this - * (bug 744965), but as apparently it "works" in practice, it's not a - * pressing concern now. - */ - return aValue == (*aInt32 = int32_t(aValue)); -} - -/** - * If d can be converted to int32_t and back to an identical double value, - * set *aInt32 to that value and return true; otherwise return false. - * - * The difference between this and NumberEqualsInt32 is that this method returns - * false for negative zero. - */ -template -static MOZ_ALWAYS_INLINE bool -NumberIsInt32(T aValue, int32_t* aInt32) -{ - return !IsNegativeZero(aValue) && NumberEqualsInt32(aValue, aInt32); -} - -/** - * Computes a NaN value. Do not use this method if you depend upon a particular - * NaN value being returned. - */ -template -static MOZ_ALWAYS_INLINE T -UnspecifiedNaN() -{ - /* - * If we can use any quiet NaN, we might as well use the all-ones NaN, - * since it's cheap to materialize on common platforms (such as x64, where - * this value can be represented in a 32-bit signed immediate field, allowing - * it to be stored to memory in a single instruction). - */ - typedef FloatingPoint Traits; - return SpecificNaN(1, Traits::kSignificandBits); -} - -/** - * Compare two doubles for equality, *without* equating -0 to +0, and equating - * any NaN value to any other NaN value. (The normal equality operators equate - * -0 with +0, and they equate NaN to no other value.) - */ -template -static inline bool -NumbersAreIdentical(T aValue1, T aValue2) -{ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - if (IsNaN(aValue1)) { - return IsNaN(aValue2); - } - return BitwiseCast(aValue1) == BitwiseCast(aValue2); -} - -namespace detail { - -template -struct FuzzyEqualsEpsilon; - -template<> -struct FuzzyEqualsEpsilon -{ - // A number near 1e-5 that is exactly representable in a float. - static float value() { return 1.0f / (1 << 17); } -}; - -template<> -struct FuzzyEqualsEpsilon -{ - // A number near 1e-12 that is exactly representable in a double. - static double value() { return 1.0 / (1LL << 40); } -}; - -} // namespace detail - -/** - * Compare two floating point values for equality, modulo rounding error. That - * is, the two values are considered equal if they are both not NaN and if they - * are less than or equal to aEpsilon apart. The default value of aEpsilon is - * near 1e-5. - * - * For most scenarios you will want to use FuzzyEqualsMultiplicative instead, - * as it is more reasonable over the entire range of floating point numbers. - * This additive version should only be used if you know the range of the - * numbers you are dealing with is bounded and stays around the same order of - * magnitude. - */ -template -static MOZ_ALWAYS_INLINE bool -FuzzyEqualsAdditive(T aValue1, T aValue2, - T aEpsilon = detail::FuzzyEqualsEpsilon::value()) -{ - static_assert(IsFloatingPoint::value, "floating point type required"); - return Abs(aValue1 - aValue2) <= aEpsilon; -} - -/** - * Compare two floating point values for equality, allowing for rounding error - * relative to the magnitude of the values. That is, the two values are - * considered equal if they are both not NaN and they are less than or equal to - * some aEpsilon apart, where the aEpsilon is scaled by the smaller of the two - * argument values. - * - * In most cases you will want to use this rather than FuzzyEqualsAdditive, as - * this function effectively masks out differences in the bottom few bits of - * the floating point numbers being compared, regardless of what order of - * magnitude those numbers are at. - */ -template -static MOZ_ALWAYS_INLINE bool -FuzzyEqualsMultiplicative(T aValue1, T aValue2, - T aEpsilon = detail::FuzzyEqualsEpsilon::value()) -{ - static_assert(IsFloatingPoint::value, "floating point type required"); - // can't use std::min because of bug 965340 - T smaller = Abs(aValue1) < Abs(aValue2) ? Abs(aValue1) : Abs(aValue2); - return Abs(aValue1 - aValue2) <= aEpsilon * smaller; -} - -/** - * Returns true if the given value can be losslessly represented as an IEEE-754 - * single format number, false otherwise. All NaN values are considered - * representable (notwithstanding that the exact bit pattern of a double format - * NaN value can't be exactly represented in single format). - * - * This function isn't inlined to avoid buggy optimizations by MSVC. - */ -MOZ_MUST_USE -extern MFBT_API bool -IsFloat32Representable(double aFloat32); - -} /* namespace mozilla */ - -#endif /* mozilla_FloatingPoint_h */ diff --git a/mac/include/spidermonkey/mozilla/Function.h b/mac/include/spidermonkey/mozilla/Function.h deleted file mode 100644 index d6de9c83..00000000 --- a/mac/include/spidermonkey/mozilla/Function.h +++ /dev/null @@ -1,223 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A type-erased callable wrapper. */ - -#ifndef mozilla_Function_h -#define mozilla_Function_h - -#include "mozilla/Attributes.h" // for MOZ_IMPLICIT -#include "mozilla/Move.h" -#include "mozilla/RefCounted.h" -#include "mozilla/RefPtr.h" - -// |function| is a wrapper that can hold any type of callable -// object that can be invoked in a way that's compatible with |Signature|. -// The standard "type erasure" technique is used to avoid the type of the -// wrapper depending on the concrete type of the wrapped callable. -// -// Supported callable types include non-member functions, static member -// functions, and function objects (that is to say, objects with an overloaded -// call operator; this includes C++11 lambdas). Member functions aren't -// directly supported; they first need to be wrapped into a function object -// using |std::mem_fn()| or an equivalent. -// -// |Signature| is a type of the form |ReturnType(Arguments...)|. Syntactically, -// this is a function type; it's not used in any way other than serving as a -// vehicle to encode the return and argument types into a single type. -// -// |function| is default-constructible. A default-constructed instance is -// considered "empty". Invoking an empty instance is undefined behaviour. -// An empty instance can be populated with a callable by assigning to it. -// -// This class is intended to provide functionality similar to the C++11 -// standard library class |std::function|. - -namespace mozilla { - -namespace detail { - -template -class FunctionImplBase : public mozilla::RefCounted> -{ -public: - MOZ_DECLARE_REFCOUNTED_TYPENAME(FunctionImplBase) - - virtual ~FunctionImplBase() {} - virtual ReturnType call(Arguments... aArguments) = 0; -}; - -// Normal Callable Object. -template -class FunctionImpl : public FunctionImplBase -{ - public: - explicit FunctionImpl(const Callable& aCallable) - : mCallable(aCallable) {} - - ReturnType call(Arguments... aArguments) override - { - return mCallable(Forward(aArguments)...); - } - private: - Callable mCallable; -}; - -// Base class for passing pointer to member function. -template -class MemberFunctionImplBase : public FunctionImplBase -{ -public: - explicit MemberFunctionImplBase(const Callable& aCallable) - : mCallable(aCallable) {} - - ReturnType call(Arguments... aArguments) override - { - return callInternal(Forward(aArguments)...); - } -private: - template - ReturnType callInternal(ThisType* aThis, Args&&... aArguments) - { - return (aThis->*mCallable)(Forward(aArguments)...); - } - - template - ReturnType callInternal(ThisType&& aThis, Args&&... aArguments) - { - return (aThis.*mCallable)(Forward(aArguments)...); - } - Callable mCallable; -}; - -// For non-const member function specialization of FunctionImpl. -template -class FunctionImpl - : public MemberFunctionImplBase -{ -public: - explicit FunctionImpl(ReturnType(ThisType::*aMemberFunc)(Args...)) - : MemberFunctionImplBase(aMemberFunc) - {} -}; - -// For const member function specialization of FunctionImpl. -template -class FunctionImpl - : public MemberFunctionImplBase -{ -public: - explicit FunctionImpl(ReturnType(ThisType::*aConstMemberFunc)(Args...) const) - : MemberFunctionImplBase(aConstMemberFunc) - {} -}; - -} // namespace detail - -// The primary template is never defined. As |Signature| is required to be -// of the form |ReturnType(Arguments...)|, we only define a partial -// specialization that matches this form. This allows us to use |ReturnType| -// and |Arguments| in the definition of the specialization without having to -// introspect |Signature|. -template -class function; - -template -class function -{ -public: - function() {} - - // This constructor is implicit to match the interface of |std::function|. - template - MOZ_IMPLICIT function(const Callable& aCallable) - : mImpl(new detail::FunctionImpl(aCallable)) - {} - MOZ_IMPLICIT function(const function& aFunction) - : mImpl(aFunction.mImpl) - {} - MOZ_IMPLICIT function(decltype(nullptr)) - {} - - // Move constructor and move assingment operator. - // These should be generated automatically, but MSVC doesn't do that yet. - function(function&& aOther) : mImpl(Move(aOther.mImpl)) {} - function& operator=(function&& aOther) { - mImpl = Move(aOther.mImpl); - return *this; - } - - template - function& operator=(const Callable& aCallable) - { - mImpl = new detail::FunctionImpl(aCallable); - return *this; - } - function& operator=(const function& aFunction) - { - mImpl = aFunction.mImpl; - return *this; - } - function& operator=(decltype(nullptr)) - { - mImpl = nullptr; - return *this; - } - - template - ReturnType operator()(Args&&... aArguments) const - { - MOZ_ASSERT(mImpl); - return mImpl->call(Forward(aArguments)...); - } - - explicit operator bool() const - { - return bool(mImpl); - } - -private: - // TODO: Consider implementing a small object optimization. - RefPtr> mImpl; -}; - -template -bool -operator==(const function& aX, decltype(nullptr)) -{ - return !aX; -} - -template -bool -operator==(decltype(nullptr), const function& aX) -{ - return !aX; -} - -template -bool -operator!=(const function& aX, decltype(nullptr)) -{ - return bool(aX); -} - -template -bool -operator!=(decltype(nullptr), const function& aX) -{ - return bool(aX); -} - -} // namespace mozilla - -#endif /* mozilla_Function_h */ diff --git a/mac/include/spidermonkey/mozilla/GuardObjects.h b/mac/include/spidermonkey/mozilla/GuardObjects.h deleted file mode 100644 index 9440c71c..00000000 --- a/mac/include/spidermonkey/mozilla/GuardObjects.h +++ /dev/null @@ -1,167 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implementation of macros to ensure correct use of RAII Auto* objects. */ - -#ifndef mozilla_GuardObjects_h -#define mozilla_GuardObjects_h - -#include "mozilla/Assertions.h" -#include "mozilla/Move.h" -#include "mozilla/Types.h" - -#ifdef __cplusplus - -#ifdef DEBUG - -/** - * A custom define is used rather than |mozPoisonValue()| due to cascading - * build failures relating to how mfbt is linked on different operating - * systems. See bug 1160253. - */ -#define MOZ_POISON uintptr_t(-1) - -namespace mozilla { -namespace detail { - -/* - * The following classes are designed to cause assertions to detect - * inadvertent use of guard objects as temporaries. In other words, - * when we have a guard object whose only purpose is its constructor and - * destructor (and is never otherwise referenced), the intended use - * might be: - * - * AutoRestore savePainting(mIsPainting); - * - * but is is easy to accidentally write: - * - * AutoRestore(mIsPainting); - * - * which compiles just fine, but runs the destructor well before the - * intended time. - * - * They work by adding (#ifdef DEBUG) an additional parameter to the - * guard object's constructor, with a default value, so that users of - * the guard object's API do not need to do anything. The default value - * of this parameter is a temporary object. C++ (ISO/IEC 14882:1998), - * section 12.2 [class.temporary], clauses 4 and 5 seem to assume a - * guarantee that temporaries are destroyed in the reverse of their - * construction order, but I actually can't find a statement that that - * is true in the general case (beyond the two specific cases mentioned - * there). However, it seems to be true. - * - * These classes are intended to be used only via the macros immediately - * below them: - * - * MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER declares (ifdef DEBUG) a member - * variable, and should be put where a declaration of a private - * member variable would be placed. - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM should be placed at the end of the - * parameters to each constructor of the guard object; it declares - * (ifdef DEBUG) an additional parameter. (But use the *_ONLY_PARAM - * variant for constructors that take no other parameters.) - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL should likewise be used in - * the implementation of such constructors when they are not inline. - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT should be used in - * the implementation of such constructors to pass the parameter to - * a base class that also uses these macros - * MOZ_GUARD_OBJECT_NOTIFIER_INIT is a statement that belongs in each - * constructor. It uses the parameter declared by - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM. - * - * For more details, and examples of using these macros, see - * https://developer.mozilla.org/en/Using_RAII_classes_in_Mozilla - */ -class GuardObjectNotifier -{ -private: - bool* mStatementDone; - -public: - GuardObjectNotifier() - : mStatementDone(reinterpret_cast(MOZ_POISON)) - { - } - - ~GuardObjectNotifier() - { - // Assert that the GuardObjectNotifier has been properly initialized by - // using the |MOZ_GUARD_OBJECT_NOTIFIER_INIT| macro. A poison value is - // used rather than a null check to appease static analyzers that were - // (incorrectly) detecting null pointer dereferences. - MOZ_ASSERT(mStatementDone != reinterpret_cast(MOZ_POISON)); - *mStatementDone = true; - } - - void setStatementDone(bool* aStatementIsDone) - { - mStatementDone = aStatementIsDone; - } -}; - -class GuardObjectNotificationReceiver -{ -private: - bool mStatementDone; - -public: - GuardObjectNotificationReceiver() : mStatementDone(false) { } - - ~GuardObjectNotificationReceiver() { - /* - * Assert that the guard object was not used as a temporary. (Note that - * this assert might also fire if init is not called because the guard - * object's implementation is not using the above macros correctly.) - */ - MOZ_ASSERT(mStatementDone); - } - - void init(GuardObjectNotifier& aNotifier) - { - aNotifier.setStatementDone(&mStatementDone); - } -}; - -} /* namespace detail */ -} /* namespace mozilla */ - -#undef MOZ_POISON - -#endif /* DEBUG */ - -#ifdef DEBUG -# define MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER \ - mozilla::detail::GuardObjectNotificationReceiver _mCheckNotUsedAsTemporary; -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM \ - , mozilla::detail::GuardObjectNotifier&& _notifier = \ - mozilla::detail::GuardObjectNotifier() -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM \ - mozilla::detail::GuardObjectNotifier&& _notifier = \ - mozilla::detail::GuardObjectNotifier() -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL \ - , mozilla::detail::GuardObjectNotifier&& _notifier -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_IN_IMPL \ - mozilla::detail::GuardObjectNotifier&& _notifier -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT \ - , mozilla::Move(_notifier) -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT \ - mozilla::Move(_notifier) -# define MOZ_GUARD_OBJECT_NOTIFIER_INIT \ - do { _mCheckNotUsedAsTemporary.init(_notifier); } while (0) -#else -# define MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_IN_IMPL -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT -# define MOZ_GUARD_OBJECT_NOTIFIER_INIT do { } while (0) -#endif - -#endif /* __cplusplus */ - -#endif /* mozilla_GuardObjects_h */ diff --git a/mac/include/spidermonkey/mozilla/HashFunctions.h b/mac/include/spidermonkey/mozilla/HashFunctions.h deleted file mode 100644 index eeb192c3..00000000 --- a/mac/include/spidermonkey/mozilla/HashFunctions.h +++ /dev/null @@ -1,389 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Utilities for hashing. */ - -/* - * This file exports functions for hashing data down to a 32-bit value, - * including: - * - * - HashString Hash a char* or char16_t/wchar_t* of known or unknown - * length. - * - * - HashBytes Hash a byte array of known length. - * - * - HashGeneric Hash one or more values. Currently, we support uint32_t, - * types which can be implicitly cast to uint32_t, data - * pointers, and function pointers. - * - * - AddToHash Add one or more values to the given hash. This supports the - * same list of types as HashGeneric. - * - * - * You can chain these functions together to hash complex objects. For example: - * - * class ComplexObject - * { - * char* mStr; - * uint32_t mUint1, mUint2; - * void (*mCallbackFn)(); - * - * public: - * uint32_t hash() - * { - * uint32_t hash = HashString(mStr); - * hash = AddToHash(hash, mUint1, mUint2); - * return AddToHash(hash, mCallbackFn); - * } - * }; - * - * If you want to hash an nsAString or nsACString, use the HashString functions - * in nsHashKeys.h. - */ - -#ifndef mozilla_HashFunctions_h -#define mozilla_HashFunctions_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Char16.h" -#include "mozilla/MathAlgorithms.h" -#include "mozilla/Types.h" - -#include - -#ifdef __cplusplus -namespace mozilla { - -/** - * The golden ratio as a 32-bit fixed-point value. - */ -static const uint32_t kGoldenRatioU32 = 0x9E3779B9U; - -inline uint32_t -RotateBitsLeft32(uint32_t aValue, uint8_t aBits) -{ - MOZ_ASSERT(aBits < 32); - return (aValue << aBits) | (aValue >> (32 - aBits)); -} - -namespace detail { - -inline uint32_t -AddU32ToHash(uint32_t aHash, uint32_t aValue) -{ - /* - * This is the meat of all our hash routines. This hash function is not - * particularly sophisticated, but it seems to work well for our mostly - * plain-text inputs. Implementation notes follow. - * - * Our use of the golden ratio here is arbitrary; we could pick almost any - * number which: - * - * * is odd (because otherwise, all our hash values will be even) - * - * * has a reasonably-even mix of 1's and 0's (consider the extreme case - * where we multiply by 0x3 or 0xeffffff -- this will not produce good - * mixing across all bits of the hash). - * - * The rotation length of 5 is also arbitrary, although an odd number is again - * preferable so our hash explores the whole universe of possible rotations. - * - * Finally, we multiply by the golden ratio *after* xor'ing, not before. - * Otherwise, if |aHash| is 0 (as it often is for the beginning of a - * message), the expression - * - * (kGoldenRatioU32 * RotateBitsLeft(aHash, 5)) |xor| aValue - * - * evaluates to |aValue|. - * - * (Number-theoretic aside: Because any odd number |m| is relatively prime to - * our modulus (2^32), the list - * - * [x * m (mod 2^32) for 0 <= x < 2^32] - * - * has no duplicate elements. This means that multiplying by |m| does not - * cause us to skip any possible hash values. - * - * It's also nice if |m| has large-ish order mod 2^32 -- that is, if the - * smallest k such that m^k == 1 (mod 2^32) is large -- so we can safely - * multiply our hash value by |m| a few times without negating the - * multiplicative effect. Our golden ratio constant has order 2^29, which is - * more than enough for our purposes.) - */ - return kGoldenRatioU32 * (RotateBitsLeft32(aHash, 5) ^ aValue); -} - -/** - * AddUintptrToHash takes sizeof(uintptr_t) as a template parameter. - */ -template -inline uint32_t -AddUintptrToHash(uint32_t aHash, uintptr_t aValue); - -template<> -inline uint32_t -AddUintptrToHash<4>(uint32_t aHash, uintptr_t aValue) -{ - return AddU32ToHash(aHash, static_cast(aValue)); -} - -template<> -inline uint32_t -AddUintptrToHash<8>(uint32_t aHash, uintptr_t aValue) -{ - /* - * The static cast to uint64_t below is necessary because this function - * sometimes gets compiled on 32-bit platforms (yes, even though it's a - * template and we never call this particular override in a 32-bit build). If - * we do aValue >> 32 on a 32-bit machine, we're shifting a 32-bit uintptr_t - * right 32 bits, and the compiler throws an error. - */ - uint32_t v1 = static_cast(aValue); - uint32_t v2 = static_cast(static_cast(aValue) >> 32); - return AddU32ToHash(AddU32ToHash(aHash, v1), v2); -} - -} /* namespace detail */ - -/** - * AddToHash takes a hash and some values and returns a new hash based on the - * inputs. - * - * Currently, we support hashing uint32_t's, values which we can implicitly - * convert to uint32_t, data pointers, and function pointers. - */ -template -MOZ_MUST_USE inline uint32_t -AddToHash(uint32_t aHash, A aA) -{ - /* - * Try to convert |A| to uint32_t implicitly. If this works, great. If not, - * we'll error out. - */ - return detail::AddU32ToHash(aHash, aA); -} - -template -MOZ_MUST_USE inline uint32_t -AddToHash(uint32_t aHash, A* aA) -{ - /* - * You might think this function should just take a void*. But then we'd only - * catch data pointers and couldn't handle function pointers. - */ - - static_assert(sizeof(aA) == sizeof(uintptr_t), "Strange pointer!"); - - return detail::AddUintptrToHash(aHash, uintptr_t(aA)); -} - -template<> -MOZ_MUST_USE inline uint32_t -AddToHash(uint32_t aHash, uintptr_t aA) -{ - return detail::AddUintptrToHash(aHash, aA); -} - -template -MOZ_MUST_USE uint32_t -AddToHash(uint32_t aHash, A aArg, Args... aArgs) -{ - return AddToHash(AddToHash(aHash, aArg), aArgs...); -} - -/** - * The HashGeneric class of functions let you hash one or more values. - * - * If you want to hash together two values x and y, calling HashGeneric(x, y) is - * much better than calling AddToHash(x, y), because AddToHash(x, y) assumes - * that x has already been hashed. - */ -template -MOZ_MUST_USE inline uint32_t -HashGeneric(Args... aArgs) -{ - return AddToHash(0, aArgs...); -} - -namespace detail { - -template -uint32_t -HashUntilZero(const T* aStr) -{ - uint32_t hash = 0; - for (T c; (c = *aStr); aStr++) { - hash = AddToHash(hash, c); - } - return hash; -} - -template -uint32_t -HashKnownLength(const T* aStr, size_t aLength) -{ - uint32_t hash = 0; - for (size_t i = 0; i < aLength; i++) { - hash = AddToHash(hash, aStr[i]); - } - return hash; -} - -} /* namespace detail */ - -/** - * The HashString overloads below do just what you'd expect. - * - * If you have the string's length, you might as well call the overload which - * includes the length. It may be marginally faster. - */ -MOZ_MUST_USE inline uint32_t -HashString(const char* aStr) -{ - return detail::HashUntilZero(reinterpret_cast(aStr)); -} - -MOZ_MUST_USE inline uint32_t -HashString(const char* aStr, size_t aLength) -{ - return detail::HashKnownLength(reinterpret_cast(aStr), aLength); -} - -MOZ_MUST_USE -inline uint32_t -HashString(const unsigned char* aStr, size_t aLength) -{ - return detail::HashKnownLength(aStr, aLength); -} - -MOZ_MUST_USE inline uint32_t -HashString(const char16_t* aStr) -{ - return detail::HashUntilZero(aStr); -} - -MOZ_MUST_USE inline uint32_t -HashString(const char16_t* aStr, size_t aLength) -{ - return detail::HashKnownLength(aStr, aLength); -} - -/* - * On Windows, wchar_t is not the same as char16_t, even though it's - * the same width! - */ -#ifdef WIN32 -MOZ_MUST_USE inline uint32_t -HashString(const wchar_t* aStr) -{ - return detail::HashUntilZero(aStr); -} - -MOZ_MUST_USE inline uint32_t -HashString(const wchar_t* aStr, size_t aLength) -{ - return detail::HashKnownLength(aStr, aLength); -} -#endif - -/** - * Hash some number of bytes. - * - * This hash walks word-by-word, rather than byte-by-byte, so you won't get the - * same result out of HashBytes as you would out of HashString. - */ -MOZ_MUST_USE extern MFBT_API uint32_t -HashBytes(const void* bytes, size_t aLength); - -/** - * A pseudorandom function mapping 32-bit integers to 32-bit integers. - * - * This is for when you're feeding private data (like pointer values or credit - * card numbers) to a non-crypto hash function (like HashBytes) and then using - * the hash code for something that untrusted parties could observe (like a JS - * Map). Plug in a HashCodeScrambler before that last step to avoid leaking the - * private data. - * - * By itself, this does not prevent hash-flooding DoS attacks, because an - * attacker can still generate many values with exactly equal hash codes by - * attacking the non-crypto hash function alone. Equal hash codes will, of - * course, still be equal however much you scramble them. - * - * The algorithm is SipHash-1-3. See . - */ -class HashCodeScrambler -{ - struct SipHasher; - - uint64_t mK0, mK1; - -public: - /** Creates a new scrambler with the given 128-bit key. */ - constexpr HashCodeScrambler(uint64_t aK0, uint64_t aK1) : mK0(aK0), mK1(aK1) {} - - /** - * Scramble a hash code. Always produces the same result for the same - * combination of key and hash code. - */ - uint32_t scramble(uint32_t aHashCode) const - { - SipHasher hasher(mK0, mK1); - return uint32_t(hasher.sipHash(aHashCode)); - } - -private: - struct SipHasher - { - SipHasher(uint64_t aK0, uint64_t aK1) - { - // 1. Initialization. - mV0 = aK0 ^ UINT64_C(0x736f6d6570736575); - mV1 = aK1 ^ UINT64_C(0x646f72616e646f6d); - mV2 = aK0 ^ UINT64_C(0x6c7967656e657261); - mV3 = aK1 ^ UINT64_C(0x7465646279746573); - } - - uint64_t sipHash(uint64_t aM) - { - // 2. Compression. - mV3 ^= aM; - sipRound(); - mV0 ^= aM; - - // 3. Finalization. - mV2 ^= 0xff; - for (int i = 0; i < 3; i++) - sipRound(); - return mV0 ^ mV1 ^ mV2 ^ mV3; - } - - void sipRound() - { - mV0 += mV1; - mV1 = RotateLeft(mV1, 13); - mV1 ^= mV0; - mV0 = RotateLeft(mV0, 32); - mV2 += mV3; - mV3 = RotateLeft(mV3, 16); - mV3 ^= mV2; - mV0 += mV3; - mV3 = RotateLeft(mV3, 21); - mV3 ^= mV0; - mV2 += mV1; - mV1 = RotateLeft(mV1, 17); - mV1 ^= mV2; - mV2 = RotateLeft(mV2, 32); - } - - uint64_t mV0, mV1, mV2, mV3; - }; -}; - -} /* namespace mozilla */ -#endif /* __cplusplus */ - -#endif /* mozilla_HashFunctions_h */ diff --git a/mac/include/spidermonkey/mozilla/IndexSequence.h b/mac/include/spidermonkey/mozilla/IndexSequence.h deleted file mode 100644 index 1ccace02..00000000 --- a/mac/include/spidermonkey/mozilla/IndexSequence.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A utility for expanding a tuple into a variadic argument list. - * Based on std::index_sequence. */ - -/** - * Example usage: - * - * Problem: - * - * You have a variadic function Foo: - * - * template void Foo(Args...); - * - * And a variadic function Bar, which contains a tuple: - * - * template - * void Bar() { - * // ... - * Tuple t; - * } - * - * And inside Bar, you want to call Foo with the elements of the tuple as - * arguments to Foo. - * - * You want to write: - * - * Foo(Get<0>(t), Get<1>(t), ..., Get(t)) - * - * but you can't literally write that, because N is different for different - * instantiations of Bar. - * - * Solution: - * - * Write a helper function which takes the tuple, and an index sequence - * containing indices corresponding to the tuple indices. - * - * template - * void Helper(const Tuple& t, IndexSequence) - * { - * Foo(Get(t)...); - * } - * - * Assuming 'Indices...' are 0, 1, ..., N - 1, where N is the size of the - * tuple, pack expansion will expand the pack 'Get(t)...' to - * 'Get<0>(t), Get<1>(t), ..., Get(t)'. - * - * Finally, call the helper, creating the index sequence to pass in like so: - * - * template - * void Bar() { - * // ... - * Tuple t; - * Helper(t, typename IndexSequenceFor::Type()); - * } - */ - -#ifndef mozilla_IndexSequence_h -#define mozilla_IndexSequence_h - -#include "mozilla/Attributes.h" - -#include - -namespace mozilla { - -/** - * Represents a compile-time sequence of integer indices. - */ -template -struct IndexSequence -{ - static constexpr size_t Size() { return sizeof...(Indices); } -}; - -namespace detail { - -// Helpers used by MakeIndexSequence. - -template -struct IndexTuple -{ - typedef IndexTuple Next; -}; - -// Builds IndexTuple<0, 1, ..., N - 1>. -template -struct BuildIndexTuple -{ - typedef typename BuildIndexTuple::Type::Next Type; -}; - -template<> -struct BuildIndexTuple<0> -{ - typedef IndexTuple<> Type; -}; - -template -struct MakeIndexSequenceImpl; - -template -struct MakeIndexSequenceImpl> -{ - typedef IndexSequence Type; -}; - -} // namespace detail - -/** - * A utility for building an IndexSequence of consecutive indices. - * MakeIndexSequence::Type evaluates to IndexSequence<0, 1, .., N - 1>. - * Note: unlike std::make_index_sequence, this is not an alias template - * to work around bugs in MSVC 2013. - */ -template -struct MakeIndexSequence -{ - typedef typename detail::MakeIndexSequenceImpl::Type>::Type Type; -}; - -/** - * A utility for building an IndexSequence of consecutive indices - * corresponding to a variadic argument list. - * IndexSequenceFor evaluates to IndexSequence<0, 1, ..., N - 1> - * where N is the number of types in Types. - * Note: unlike std::index_sequence_for, this is not an alias template - * to work around bugs in MSVC 2013. - */ -template -struct IndexSequenceFor -{ - typedef typename MakeIndexSequence::Type Type; -}; - -} // namespace mozilla - -#endif /* mozilla_IndexSequence_h */ diff --git a/mac/include/spidermonkey/mozilla/IntegerPrintfMacros.h b/mac/include/spidermonkey/mozilla/IntegerPrintfMacros.h deleted file mode 100644 index c534a0ba..00000000 --- a/mac/include/spidermonkey/mozilla/IntegerPrintfMacros.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements the C99 interface. */ - -#ifndef mozilla_IntegerPrintfMacros_h_ -#define mozilla_IntegerPrintfMacros_h_ - -/* - * These macros should not be used with the NSPR printf-like functions or their - * users, e.g. mozilla/Logging.h. If you need to use NSPR's facilities, see the - * comment on supported formats at the top of nsprpub/pr/include/prprf.h. - */ - -/* - * scanf is a footgun: if the input number exceeds the bounds of the target - * type, behavior is undefined (in the compiler sense: that is, this code - * could overwrite your hard drive with zeroes): - * - * uint8_t u; - * sscanf("256", "%" SCNu8, &u); // BAD - * - * For this reason, *never* use the SCN* macros provided by this header! - */ - -#include - -/* - * Fix up Android's broken [u]intptr_t inttype macros. Android's PRI*PTR - * macros are defined as "ld", but sizeof(long) is 8 and sizeof(intptr_t) - * is 4 on 32-bit Android. TestTypeTraits.cpp asserts that these new macro - * definitions match the actual type sizes seen at compile time. - */ -#if defined(ANDROID) && !defined(__LP64__) -# undef PRIdPTR /* intptr_t */ -# define PRIdPTR "d" /* intptr_t */ -# undef PRIiPTR /* intptr_t */ -# define PRIiPTR "i" /* intptr_t */ -# undef PRIoPTR /* uintptr_t */ -# define PRIoPTR "o" /* uintptr_t */ -# undef PRIuPTR /* uintptr_t */ -# define PRIuPTR "u" /* uintptr_t */ -# undef PRIxPTR /* uintptr_t */ -# define PRIxPTR "x" /* uintptr_t */ -# undef PRIXPTR /* uintptr_t */ -# define PRIXPTR "X" /* uintptr_t */ -#endif - -#endif /* mozilla_IntegerPrintfMacros_h_ */ diff --git a/mac/include/spidermonkey/mozilla/IntegerRange.h b/mac/include/spidermonkey/mozilla/IntegerRange.h deleted file mode 100644 index 8d5d2e4d..00000000 --- a/mac/include/spidermonkey/mozilla/IntegerRange.h +++ /dev/null @@ -1,181 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Iterator over ranges of integers */ - -#ifndef mozilla_IntegerRange_h -#define mozilla_IntegerRange_h - -#include "mozilla/Assertions.h" -#include "mozilla/ReverseIterator.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -namespace detail { - -template -class IntegerIterator -{ -public: - template - explicit IntegerIterator(IntType aCurrent) - : mCurrent(aCurrent) { } - - template - explicit IntegerIterator(const IntegerIterator& aOther) - : mCurrent(aOther.mCurrent) { } - - IntTypeT operator*() const { return mCurrent; } - - /* Increment and decrement operators */ - - IntegerIterator& operator++() { ++mCurrent; return *this; } - IntegerIterator& operator--() { --mCurrent; return *this; } - IntegerIterator operator++(int) { auto ret = *this; ++mCurrent; return ret; } - IntegerIterator operator--(int) { auto ret = *this; --mCurrent; return ret; } - - /* Comparison operators */ - - template - friend bool operator==(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator!=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator<(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator<=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator>(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator>=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - -private: - IntTypeT mCurrent; -}; - -template -bool operator==(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent == aIter2.mCurrent; -} - -template -bool operator!=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent != aIter2.mCurrent; -} - -template -bool operator<(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent < aIter2.mCurrent; -} - -template -bool operator<=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent <= aIter2.mCurrent; -} - -template -bool operator>(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent > aIter2.mCurrent; -} - -template -bool operator>=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent >= aIter2.mCurrent; -} - -template -class IntegerRange -{ -public: - typedef IntegerIterator iterator; - typedef IntegerIterator const_iterator; - typedef ReverseIterator> reverse_iterator; - typedef ReverseIterator> const_reverse_iterator; - - template - explicit IntegerRange(IntType aEnd) - : mBegin(0), mEnd(aEnd) { } - - template - IntegerRange(IntType1 aBegin, IntType2 aEnd) - : mBegin(aBegin), mEnd(aEnd) { } - - iterator begin() const { return iterator(mBegin); } - const_iterator cbegin() const { return begin(); } - iterator end() const { return iterator(mEnd); } - const_iterator cend() const { return end(); } - reverse_iterator rbegin() const { return reverse_iterator(mEnd); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() const { return reverse_iterator(mBegin); } - const_reverse_iterator crend() const { return rend(); } - -private: - IntTypeT mBegin; - IntTypeT mEnd; -}; - -template::value> -struct GeqZero -{ - static bool check(T t) { - return t >= 0; - } -}; - -template -struct GeqZero -{ - static bool check(T t) { - return true; - } -}; - -} // namespace detail - -template -detail::IntegerRange -MakeRange(IntType aEnd) -{ - static_assert(IsIntegral::value, "value must be integral"); - MOZ_ASSERT(detail::GeqZero::check(aEnd), - "Should never have negative value here"); - return detail::IntegerRange(aEnd); -} - -template -detail::IntegerRange -MakeRange(IntType1 aBegin, IntType2 aEnd) -{ - static_assert(IsIntegral::value && IsIntegral::value, - "values must both be integral"); - static_assert(IsSigned::value == IsSigned::value, - "signed/unsigned mismatch"); - MOZ_ASSERT(aEnd >= aBegin, "End value should be larger than begin value"); - return detail::IntegerRange(aBegin, aEnd); -} - -} // namespace mozilla - -#endif // mozilla_IntegerRange_h diff --git a/mac/include/spidermonkey/mozilla/IntegerTypeTraits.h b/mac/include/spidermonkey/mozilla/IntegerTypeTraits.h deleted file mode 100644 index 6144d208..00000000 --- a/mac/include/spidermonkey/mozilla/IntegerTypeTraits.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Helpers to manipulate integer types that don't fit in TypeTraits.h */ - -#ifndef mozilla_IntegerTypeTraits_h -#define mozilla_IntegerTypeTraits_h - -#include "mozilla/TypeTraits.h" -#include - -namespace mozilla { - -namespace detail { - -/** - * StdintTypeForSizeAndSignedness returns the stdint integer type - * of given size (can be 1, 2, 4 or 8) and given signedness - * (false means unsigned, true means signed). - */ -template -struct StdintTypeForSizeAndSignedness; - -template<> -struct StdintTypeForSizeAndSignedness<1, true> -{ - typedef int8_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<1, false> -{ - typedef uint8_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<2, true> -{ - typedef int16_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<2, false> -{ - typedef uint16_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<4, true> -{ - typedef int32_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<4, false> -{ - typedef uint32_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<8, true> -{ - typedef int64_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<8, false> -{ - typedef uint64_t Type; -}; - -} // namespace detail - -template -struct UnsignedStdintTypeForSize - : detail::StdintTypeForSizeAndSignedness -{}; - -template -struct SignedStdintTypeForSize - : detail::StdintTypeForSizeAndSignedness -{}; - -template -struct PositionOfSignBit -{ - static_assert(IsIntegral::value, - "PositionOfSignBit is only for integral types"); - // 8 here should be CHAR_BIT from limits.h, but the world has moved on. - static const size_t value = 8 * sizeof(IntegerType) - 1; -}; - -/** - * MinValue returns the minimum value of the given integer type as a - * compile-time constant, which std::numeric_limits::min() - * cannot do in c++98. - */ -template -struct MinValue -{ -private: - static_assert(IsIntegral::value, - "MinValue is only for integral types"); - - typedef typename MakeUnsigned::Type UnsignedIntegerType; - static const size_t PosOfSignBit = PositionOfSignBit::value; - -public: - // Bitwise ops may return a larger type, that's why we cast explicitly. - // In C++, left bit shifts on signed values is undefined by the standard - // unless the shifted value is representable. - // Notice that signed-to-unsigned conversions are always well-defined in - // the standard as the value congruent to 2**n, as expected. By contrast, - // unsigned-to-signed is only well-defined if the value is representable. - static const IntegerType value = - IsSigned::value - ? IntegerType(UnsignedIntegerType(1) << PosOfSignBit) - : IntegerType(0); -}; - -/** - * MaxValue returns the maximum value of the given integer type as a - * compile-time constant, which std::numeric_limits::max() - * cannot do in c++98. - */ -template -struct MaxValue -{ - static_assert(IsIntegral::value, - "MaxValue is only for integral types"); - - // Tricksy, but covered by the CheckedInt unit test. - // Relies on the type of MinValue::value - // being IntegerType. - static const IntegerType value = ~MinValue::value; -}; - -} // namespace mozilla - -#endif // mozilla_IntegerTypeTraits_h diff --git a/mac/include/spidermonkey/mozilla/JSONWriter.h b/mac/include/spidermonkey/mozilla/JSONWriter.h deleted file mode 100644 index 7d44dc7f..00000000 --- a/mac/include/spidermonkey/mozilla/JSONWriter.h +++ /dev/null @@ -1,460 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A JSON pretty-printer class. */ - -// A typical JSON-writing library requires you to first build up a data -// structure that represents a JSON object and then serialize it (to file, or -// somewhere else). This approach makes for a clean API, but building the data -// structure takes up memory. Sometimes that isn't desirable, such as when the -// JSON data is produced for memory reporting. -// -// The JSONWriter class instead allows JSON data to be written out -// incrementally without building up large data structures. -// -// The API is slightly uglier than you would see in a typical JSON-writing -// library, but still fairly easy to use. It's possible to generate invalid -// JSON with JSONWriter, but typically the most basic testing will identify any -// such problems. -// -// Similarly, there are no RAII facilities for automatically closing objects -// and arrays. These would be nice if you are generating all your code within -// nested functions, but in other cases you'd have to maintain an explicit -// stack of RAII objects and manually unwind it, which is no better than just -// calling "end" functions. Furthermore, the consequences of forgetting to -// close an object or array are obvious and, again, will be identified via -// basic testing, unlike other cases where RAII is typically used (e.g. smart -// pointers) and the consequences of defects are more subtle. -// -// Importantly, the class does solve the two hard problems of JSON -// pretty-printing, which are (a) correctly escaping strings, and (b) adding -// appropriate indentation and commas between items. -// -// By default, every property is placed on its own line. However, it is -// possible to request that objects and arrays be placed entirely on a single -// line, which can reduce output size significantly in some cases. -// -// Strings used (for property names and string property values) are |const -// char*| throughout, and can be ASCII or UTF-8. -// -// EXAMPLE -// ------- -// Assume that |MyWriteFunc| is a class that implements |JSONWriteFunc|. The -// following code: -// -// JSONWriter w(MakeUnique()); -// w.Start(); -// { -// w.NullProperty("null"); -// w.BoolProperty("bool", true); -// w.IntProperty("int", 1); -// w.StartArrayProperty("array"); -// { -// w.StringElement("string"); -// w.StartObjectElement(); -// { -// w.DoubleProperty("double", 3.4); -// w.StartArrayProperty("single-line array", w.SingleLineStyle); -// { -// w.IntElement(1); -// w.StartObjectElement(); // SingleLineStyle is inherited from -// w.EndObjectElement(); // above for this collection -// } -// w.EndArray(); -// } -// w.EndObjectElement(); -// } -// w.EndArrayProperty(); -// } -// w.End(); -// -// will produce pretty-printed output for the following JSON object: -// -// { -// "null": null, -// "bool": true, -// "int": 1, -// "array": [ -// "string", -// { -// "double": 3.4, -// "single-line array": [1, {}] -// } -// ] -// } -// -// The nesting in the example code is obviously optional, but can aid -// readability. - -#ifndef mozilla_JSONWriter_h -#define mozilla_JSONWriter_h - -#include "mozilla/double-conversion.h" -#include "mozilla/IntegerPrintfMacros.h" -#include "mozilla/PodOperations.h" -#include "mozilla/Sprintf.h" -#include "mozilla/UniquePtr.h" -#include "mozilla/Vector.h" - -#include - -namespace mozilla { - -// A quasi-functor for JSONWriter. We don't use a true functor because that -// requires templatizing JSONWriter, and the templatization seeps to lots of -// places we don't want it to. -class JSONWriteFunc -{ -public: - virtual void Write(const char* aStr) = 0; - virtual ~JSONWriteFunc() {} -}; - -// Ideally this would be within |EscapedString| but when compiling with GCC -// on Linux that caused link errors, whereas this formulation didn't. -namespace detail { -extern MFBT_DATA const char gTwoCharEscapes[256]; -} // namespace detail - -class JSONWriter -{ - // From http://www.ietf.org/rfc/rfc4627.txt: - // - // "All Unicode characters may be placed within the quotation marks except - // for the characters that must be escaped: quotation mark, reverse - // solidus, and the control characters (U+0000 through U+001F)." - // - // This implementation uses two-char escape sequences where possible, namely: - // - // \", \\, \b, \f, \n, \r, \t - // - // All control characters not in the above list are represented with a - // six-char escape sequence, e.g. '\u000b' (a.k.a. '\v'). - // - class EscapedString - { - // Only one of |mUnownedStr| and |mOwnedStr| are ever non-null. |mIsOwned| - // indicates which one is in use. They're not within a union because that - // wouldn't work with UniquePtr. - bool mIsOwned; - const char* mUnownedStr; - UniquePtr mOwnedStr; - - void SanityCheck() const - { - MOZ_ASSERT_IF( mIsOwned, mOwnedStr.get() && !mUnownedStr); - MOZ_ASSERT_IF(!mIsOwned, !mOwnedStr.get() && mUnownedStr); - } - - static char hexDigitToAsciiChar(uint8_t u) - { - u = u & 0xf; - return u < 10 ? '0' + u : 'a' + (u - 10); - } - - public: - explicit EscapedString(const char* aStr) - : mUnownedStr(nullptr) - , mOwnedStr(nullptr) - { - const char* p; - - // First, see if we need to modify the string. - size_t nExtra = 0; - p = aStr; - while (true) { - uint8_t u = *p; // ensure it can't be interpreted as negative - if (u == 0) { - break; - } - if (detail::gTwoCharEscapes[u]) { - nExtra += 1; - } else if (u <= 0x1f) { - nExtra += 5; - } - p++; - } - - if (nExtra == 0) { - // No escapes needed. Easy. - mIsOwned = false; - mUnownedStr = aStr; - return; - } - - // Escapes are needed. We'll create a new string. - mIsOwned = true; - size_t len = (p - aStr) + nExtra; - mOwnedStr = MakeUnique(len + 1); - - p = aStr; - size_t i = 0; - - while (true) { - uint8_t u = *p; // ensure it can't be interpreted as negative - if (u == 0) { - mOwnedStr[i] = 0; - break; - } - if (detail::gTwoCharEscapes[u]) { - mOwnedStr[i++] = '\\'; - mOwnedStr[i++] = detail::gTwoCharEscapes[u]; - } else if (u <= 0x1f) { - mOwnedStr[i++] = '\\'; - mOwnedStr[i++] = 'u'; - mOwnedStr[i++] = '0'; - mOwnedStr[i++] = '0'; - mOwnedStr[i++] = hexDigitToAsciiChar((u & 0x00f0) >> 4); - mOwnedStr[i++] = hexDigitToAsciiChar(u & 0x000f); - } else { - mOwnedStr[i++] = u; - } - p++; - } - } - - ~EscapedString() - { - SanityCheck(); - } - - const char* get() const - { - SanityCheck(); - return mIsOwned ? mOwnedStr.get() : mUnownedStr; - } - }; - -public: - // Collections (objects and arrays) are printed in a multi-line style by - // default. This can be changed to a single-line style if SingleLineStyle is - // specified. If a collection is printed in single-line style, every nested - // collection within it is also printed in single-line style, even if - // multi-line style is requested. - enum CollectionStyle { - MultiLineStyle, // the default - SingleLineStyle - }; - -protected: - const UniquePtr mWriter; - Vector mNeedComma; // do we need a comma at depth N? - Vector mNeedNewlines; // do we need newlines at depth N? - size_t mDepth; // the current nesting depth - - void Indent() - { - for (size_t i = 0; i < mDepth; i++) { - mWriter->Write(" "); - } - } - - // Adds whatever is necessary (maybe a comma, and then a newline and - // whitespace) to separate an item (property or element) from what's come - // before. - void Separator() - { - if (mNeedComma[mDepth]) { - mWriter->Write(","); - } - if (mDepth > 0 && mNeedNewlines[mDepth]) { - mWriter->Write("\n"); - Indent(); - } else if (mNeedComma[mDepth]) { - mWriter->Write(" "); - } - } - - void PropertyNameAndColon(const char* aName) - { - EscapedString escapedName(aName); - mWriter->Write("\""); - mWriter->Write(escapedName.get()); - mWriter->Write("\": "); - } - - void Scalar(const char* aMaybePropertyName, const char* aStringValue) - { - Separator(); - if (aMaybePropertyName) { - PropertyNameAndColon(aMaybePropertyName); - } - mWriter->Write(aStringValue); - mNeedComma[mDepth] = true; - } - - void QuotedScalar(const char* aMaybePropertyName, const char* aStringValue) - { - Separator(); - if (aMaybePropertyName) { - PropertyNameAndColon(aMaybePropertyName); - } - mWriter->Write("\""); - mWriter->Write(aStringValue); - mWriter->Write("\""); - mNeedComma[mDepth] = true; - } - - void NewVectorEntries() - { - // If these tiny allocations OOM we might as well just crash because we - // must be in serious memory trouble. - MOZ_RELEASE_ASSERT(mNeedComma.resizeUninitialized(mDepth + 1)); - MOZ_RELEASE_ASSERT(mNeedNewlines.resizeUninitialized(mDepth + 1)); - mNeedComma[mDepth] = false; - mNeedNewlines[mDepth] = true; - } - - void StartCollection(const char* aMaybePropertyName, const char* aStartChar, - CollectionStyle aStyle = MultiLineStyle) - { - Separator(); - if (aMaybePropertyName) { - mWriter->Write("\""); - mWriter->Write(aMaybePropertyName); - mWriter->Write("\": "); - } - mWriter->Write(aStartChar); - mNeedComma[mDepth] = true; - mDepth++; - NewVectorEntries(); - mNeedNewlines[mDepth] = - mNeedNewlines[mDepth - 1] && aStyle == MultiLineStyle; - } - - // Adds the whitespace and closing char necessary to end a collection. - void EndCollection(const char* aEndChar) - { - if (mNeedNewlines[mDepth]) { - mWriter->Write("\n"); - mDepth--; - Indent(); - } else { - mDepth--; - } - mWriter->Write(aEndChar); - } - -public: - explicit JSONWriter(UniquePtr aWriter) - : mWriter(Move(aWriter)) - , mNeedComma() - , mNeedNewlines() - , mDepth(0) - { - NewVectorEntries(); - } - - // Returns the JSONWriteFunc passed in at creation, for temporary use. The - // JSONWriter object still owns the JSONWriteFunc. - JSONWriteFunc* WriteFunc() const { return mWriter.get(); } - - // For all the following functions, the "Prints:" comment indicates what the - // basic output looks like. However, it doesn't indicate the whitespace and - // trailing commas, which are automatically added as required. - // - // All property names and string properties are escaped as necessary. - - // Prints: { - void Start(CollectionStyle aStyle = MultiLineStyle) - { - StartCollection(nullptr, "{", aStyle); - } - - // Prints: } - void End() { EndCollection("}\n"); } - - // Prints: "": null - void NullProperty(const char* aName) - { - Scalar(aName, "null"); - } - - // Prints: null - void NullElement() { NullProperty(nullptr); } - - // Prints: "": - void BoolProperty(const char* aName, bool aBool) - { - Scalar(aName, aBool ? "true" : "false"); - } - - // Prints: - void BoolElement(bool aBool) { BoolProperty(nullptr, aBool); } - - // Prints: "": - void IntProperty(const char* aName, int64_t aInt) - { - char buf[64]; - SprintfLiteral(buf, "%" PRId64, aInt); - Scalar(aName, buf); - } - - // Prints: - void IntElement(int64_t aInt) { IntProperty(nullptr, aInt); } - - // Prints: "": - void DoubleProperty(const char* aName, double aDouble) - { - static const size_t buflen = 64; - char buf[buflen]; - const double_conversion::DoubleToStringConverter &converter = - double_conversion::DoubleToStringConverter::EcmaScriptConverter(); - double_conversion::StringBuilder builder(buf, buflen); - converter.ToShortest(aDouble, &builder); - Scalar(aName, builder.Finalize()); - } - - // Prints: - void DoubleElement(double aDouble) { DoubleProperty(nullptr, aDouble); } - - // Prints: "": "" - void StringProperty(const char* aName, const char* aStr) - { - EscapedString escapedStr(aStr); - QuotedScalar(aName, escapedStr.get()); - } - - // Prints: "" - void StringElement(const char* aStr) { StringProperty(nullptr, aStr); } - - // Prints: "": [ - void StartArrayProperty(const char* aName, - CollectionStyle aStyle = MultiLineStyle) - { - StartCollection(aName, "[", aStyle); - } - - // Prints: [ - void StartArrayElement(CollectionStyle aStyle = MultiLineStyle) - { - StartArrayProperty(nullptr, aStyle); - } - - // Prints: ] - void EndArray() { EndCollection("]"); } - - // Prints: "": { - void StartObjectProperty(const char* aName, - CollectionStyle aStyle = MultiLineStyle) - { - StartCollection(aName, "{", aStyle); - } - - // Prints: { - void StartObjectElement(CollectionStyle aStyle = MultiLineStyle) - { - StartObjectProperty(nullptr, aStyle); - } - - // Prints: } - void EndObject() { EndCollection("}"); } -}; - -} // namespace mozilla - -#endif /* mozilla_JSONWriter_h */ - diff --git a/mac/include/spidermonkey/mozilla/Likely.h b/mac/include/spidermonkey/mozilla/Likely.h deleted file mode 100644 index 4f216092..00000000 --- a/mac/include/spidermonkey/mozilla/Likely.h +++ /dev/null @@ -1,23 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * MOZ_LIKELY and MOZ_UNLIKELY macros to hint to the compiler how a - * boolean predicate should be branch-predicted. - */ - -#ifndef mozilla_Likely_h -#define mozilla_Likely_h - -#if defined(__clang__) || defined(__GNUC__) -# define MOZ_LIKELY(x) (__builtin_expect(!!(x), 1)) -# define MOZ_UNLIKELY(x) (__builtin_expect(!!(x), 0)) -#else -# define MOZ_LIKELY(x) (!!(x)) -# define MOZ_UNLIKELY(x) (!!(x)) -#endif - -#endif /* mozilla_Likely_h */ diff --git a/mac/include/spidermonkey/mozilla/LinkedList.h b/mac/include/spidermonkey/mozilla/LinkedList.h deleted file mode 100644 index 6e14aa16..00000000 --- a/mac/include/spidermonkey/mozilla/LinkedList.h +++ /dev/null @@ -1,659 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A type-safe doubly-linked list class. */ - -/* - * The classes LinkedList and LinkedListElement together form a - * convenient, type-safe doubly-linked list implementation. - * - * The class T which will be inserted into the linked list must inherit from - * LinkedListElement. A given object may be in only one linked list at a - * time. - * - * A LinkedListElement automatically removes itself from the list upon - * destruction, and a LinkedList will fatally assert in debug builds if it's - * non-empty when it's destructed. - * - * For example, you might use LinkedList in a simple observer list class as - * follows. - * - * class Observer : public LinkedListElement - * { - * public: - * void observe(char* aTopic) { ... } - * }; - * - * class ObserverContainer - * { - * private: - * LinkedList list; - * - * public: - * void addObserver(Observer* aObserver) - * { - * // Will assert if |aObserver| is part of another list. - * list.insertBack(aObserver); - * } - * - * void removeObserver(Observer* aObserver) - * { - * // Will assert if |aObserver| is not part of some list. - * aObserver.remove(); - * // Or, will assert if |aObserver| is not part of |list| specifically. - * // aObserver.removeFrom(list); - * } - * - * void notifyObservers(char* aTopic) - * { - * for (Observer* o = list.getFirst(); o != nullptr; o = o->getNext()) { - * o->observe(aTopic); - * } - * } - * }; - * - * Additionally, the class AutoCleanLinkedList is a LinkedList that will - * remove and delete each element still within itself upon destruction. Note - * that because each element is deleted, elements must have been allocated - * using |new|. - */ - -#ifndef mozilla_LinkedList_h -#define mozilla_LinkedList_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/RefPtr.h" - -#ifdef __cplusplus - -namespace mozilla { - -template -class LinkedListElement; - -namespace detail { - -/** - * LinkedList supports refcounted elements using this adapter class. Clients - * using LinkedList> will get a data structure that holds a strong - * reference to T as long as T is in the list. - */ -template -struct LinkedListElementTraits -{ - typedef T* RawType; - typedef const T* ConstRawType; - typedef T* ClientType; - typedef const T* ConstClientType; - - // These static methods are called when an element is added to or removed from - // a linked list. It can be used to keep track ownership in lists that are - // supposed to own their elements. If elements are transferred from one list - // to another, no enter or exit calls happen since the elements still belong - // to a list. - static void enterList(LinkedListElement* elt) {} - static void exitList(LinkedListElement* elt) {} -}; - -template -struct LinkedListElementTraits> -{ - typedef T* RawType; - typedef const T* ConstRawType; - typedef RefPtr ClientType; - typedef RefPtr ConstClientType; - - static void enterList(LinkedListElement>* elt) { elt->asT()->AddRef(); } - static void exitList(LinkedListElement>* elt) { elt->asT()->Release(); } -}; - -} /* namespace detail */ - -template -class LinkedList; - -template -class LinkedListElement -{ - typedef typename detail::LinkedListElementTraits Traits; - typedef typename Traits::RawType RawType; - typedef typename Traits::ConstRawType ConstRawType; - typedef typename Traits::ClientType ClientType; - typedef typename Traits::ConstClientType ConstClientType; - - /* - * It's convenient that we return nullptr when getNext() or getPrevious() - * hits the end of the list, but doing so costs an extra word of storage in - * each linked list node (to keep track of whether |this| is the sentinel - * node) and a branch on this value in getNext/getPrevious. - * - * We could get rid of the extra word of storage by shoving the "is - * sentinel" bit into one of the pointers, although this would, of course, - * have performance implications of its own. - * - * But the goal here isn't to win an award for the fastest or slimmest - * linked list; rather, we want a *convenient* linked list. So we won't - * waste time guessing which micro-optimization strategy is best. - * - * - * Speaking of unnecessary work, it's worth addressing here why we wrote - * mozilla::LinkedList in the first place, instead of using stl::list. - * - * The key difference between mozilla::LinkedList and stl::list is that - * mozilla::LinkedList stores the mPrev/mNext pointers in the object itself, - * while stl::list stores the mPrev/mNext pointers in a list element which - * itself points to the object being stored. - * - * mozilla::LinkedList's approach makes it harder to store an object in more - * than one list. But the upside is that you can call next() / prev() / - * remove() directly on the object. With stl::list, you'd need to store a - * pointer to its iterator in the object in order to accomplish this. Not - * only would this waste space, but you'd have to remember to update that - * pointer every time you added or removed the object from a list. - * - * In-place, constant-time removal is a killer feature of doubly-linked - * lists, and supporting this painlessly was a key design criterion. - */ - -private: - LinkedListElement* mNext; - LinkedListElement* mPrev; - const bool mIsSentinel; - -public: - LinkedListElement() - : mNext(this), - mPrev(this), - mIsSentinel(false) - { } - - /* - * Moves |aOther| into |*this|. If |aOther| is already in a list, then - * |aOther| is removed from the list and replaced by |*this|. - */ - LinkedListElement(LinkedListElement&& aOther) - : mIsSentinel(aOther.mIsSentinel) - { - adjustLinkForMove(Move(aOther)); - } - - LinkedListElement& operator=(LinkedListElement&& aOther) - { - MOZ_ASSERT(mIsSentinel == aOther.mIsSentinel, "Mismatch NodeKind!"); - MOZ_ASSERT(!isInList(), - "Assigning to an element in a list messes up that list!"); - adjustLinkForMove(Move(aOther)); - return *this; - } - - ~LinkedListElement() - { - if (!mIsSentinel && isInList()) { - remove(); - } - } - - /* - * Get the next element in the list, or nullptr if this is the last element - * in the list. - */ - RawType getNext() { return mNext->asT(); } - ConstRawType getNext() const { return mNext->asT(); } - - /* - * Get the previous element in the list, or nullptr if this is the first - * element in the list. - */ - RawType getPrevious() { return mPrev->asT(); } - ConstRawType getPrevious() const { return mPrev->asT(); } - - /* - * Insert aElem after this element in the list. |this| must be part of a - * linked list when you call setNext(); otherwise, this method will assert. - */ - void setNext(RawType aElem) - { - MOZ_ASSERT(isInList()); - setNextUnsafe(aElem); - } - - /* - * Insert aElem before this element in the list. |this| must be part of a - * linked list when you call setPrevious(); otherwise, this method will - * assert. - */ - void setPrevious(RawType aElem) - { - MOZ_ASSERT(isInList()); - setPreviousUnsafe(aElem); - } - - /* - * Remove this element from the list which contains it. If this element is - * not currently part of a linked list, this method asserts. - */ - void remove() - { - MOZ_ASSERT(isInList()); - - mPrev->mNext = mNext; - mNext->mPrev = mPrev; - mNext = this; - mPrev = this; - - Traits::exitList(this); - } - - /* - * Remove this element from the list containing it. Returns a pointer to the - * element that follows this element (before it was removed). This method - * asserts if the element does not belong to a list. - */ - ClientType removeAndGetNext() - { - ClientType r = getNext(); - remove(); - return r; - } - - /* - * Remove this element from the list containing it. Returns a pointer to the - * previous element in the containing list (before the removal). This method - * asserts if the element does not belong to a list. - */ - ClientType removeAndGetPrevious() - { - ClientType r = getPrevious(); - remove(); - return r; - } - - /* - * Identical to remove(), but also asserts in debug builds that this element - * is in aList. - */ - void removeFrom(const LinkedList& aList) - { - aList.assertContains(asT()); - remove(); - } - - /* - * Return true if |this| part is of a linked list, and false otherwise. - */ - bool isInList() const - { - MOZ_ASSERT((mNext == this) == (mPrev == this)); - return mNext != this; - } - -private: - friend class LinkedList; - friend struct detail::LinkedListElementTraits; - - enum class NodeKind { - Normal, - Sentinel - }; - - explicit LinkedListElement(NodeKind nodeKind) - : mNext(this), - mPrev(this), - mIsSentinel(nodeKind == NodeKind::Sentinel) - { } - - /* - * Return |this| cast to T* if we're a normal node, or return nullptr if - * we're a sentinel node. - */ - RawType asT() - { - return mIsSentinel ? nullptr : static_cast(this); - } - ConstRawType asT() const - { - return mIsSentinel ? nullptr : static_cast(this); - } - - /* - * Insert aElem after this element, but don't check that this element is in - * the list. This is called by LinkedList::insertFront(). - */ - void setNextUnsafe(RawType aElem) - { - LinkedListElement *listElem = static_cast(aElem); - MOZ_ASSERT(!listElem->isInList()); - - listElem->mNext = this->mNext; - listElem->mPrev = this; - this->mNext->mPrev = listElem; - this->mNext = listElem; - - Traits::enterList(aElem); - } - - /* - * Insert aElem before this element, but don't check that this element is in - * the list. This is called by LinkedList::insertBack(). - */ - void setPreviousUnsafe(RawType aElem) - { - LinkedListElement* listElem = static_cast*>(aElem); - MOZ_ASSERT(!listElem->isInList()); - - listElem->mNext = this; - listElem->mPrev = this->mPrev; - this->mPrev->mNext = listElem; - this->mPrev = listElem; - - Traits::enterList(aElem); - } - - /* - * Adjust mNext and mPrev for implementing move constructor and move - * assignment. - */ - void adjustLinkForMove(LinkedListElement&& aOther) - { - if (!aOther.isInList()) { - mNext = this; - mPrev = this; - return; - } - - if (!mIsSentinel) { - Traits::enterList(this); - } - - MOZ_ASSERT(aOther.mNext->mPrev == &aOther); - MOZ_ASSERT(aOther.mPrev->mNext == &aOther); - - /* - * Initialize |this| with |aOther|'s mPrev/mNext pointers, and adjust those - * element to point to this one. - */ - mNext = aOther.mNext; - mPrev = aOther.mPrev; - - mNext->mPrev = this; - mPrev->mNext = this; - - /* - * Adjust |aOther| so it doesn't think it's in a list. This makes it - * safely destructable. - */ - aOther.mNext = &aOther; - aOther.mPrev = &aOther; - - if (!mIsSentinel) { - Traits::exitList(&aOther); - } - } - - LinkedListElement& operator=(const LinkedListElement& aOther) = delete; - LinkedListElement(const LinkedListElement& aOther) = delete; -}; - -template -class LinkedList -{ -private: - typedef typename detail::LinkedListElementTraits Traits; - typedef typename Traits::RawType RawType; - typedef typename Traits::ConstRawType ConstRawType; - typedef typename Traits::ClientType ClientType; - typedef typename Traits::ConstClientType ConstClientType; - - LinkedListElement sentinel; - -public: - class Iterator { - RawType mCurrent; - - public: - explicit Iterator(RawType aCurrent) : mCurrent(aCurrent) {} - - RawType operator *() const { - return mCurrent; - } - - const Iterator& operator++() { - mCurrent = mCurrent->getNext(); - return *this; - } - - bool operator!=(Iterator& aOther) const { - return mCurrent != aOther.mCurrent; - } - }; - - LinkedList() : sentinel(LinkedListElement::NodeKind::Sentinel) { } - - LinkedList(LinkedList&& aOther) - : sentinel(mozilla::Move(aOther.sentinel)) - { } - - LinkedList& operator=(LinkedList&& aOther) - { - MOZ_ASSERT(isEmpty(), "Assigning to a non-empty list leaks elements in that list!"); - sentinel = mozilla::Move(aOther.sentinel); - return *this; - } - - ~LinkedList() { - MOZ_ASSERT(isEmpty(), - "failing this assertion means this LinkedList's creator is " - "buggy: it should have removed all this list's elements before " - "the list's destruction"); - } - - /* - * Add aElem to the front of the list. - */ - void insertFront(RawType aElem) - { - /* Bypass setNext()'s this->isInList() assertion. */ - sentinel.setNextUnsafe(aElem); - } - - /* - * Add aElem to the back of the list. - */ - void insertBack(RawType aElem) - { - sentinel.setPreviousUnsafe(aElem); - } - - /* - * Get the first element of the list, or nullptr if the list is empty. - */ - RawType getFirst() { return sentinel.getNext(); } - ConstRawType getFirst() const { return sentinel.getNext(); } - - /* - * Get the last element of the list, or nullptr if the list is empty. - */ - RawType getLast() { return sentinel.getPrevious(); } - ConstRawType getLast() const { return sentinel.getPrevious(); } - - /* - * Get and remove the first element of the list. If the list is empty, - * return nullptr. - */ - ClientType popFirst() - { - ClientType ret = sentinel.getNext(); - if (ret) { - static_cast*>(RawType(ret))->remove(); - } - return ret; - } - - /* - * Get and remove the last element of the list. If the list is empty, - * return nullptr. - */ - ClientType popLast() - { - ClientType ret = sentinel.getPrevious(); - if (ret) { - static_cast*>(RawType(ret))->remove(); - } - return ret; - } - - /* - * Return true if the list is empty, or false otherwise. - */ - bool isEmpty() const - { - return !sentinel.isInList(); - } - - /* - * Remove all the elements from the list. - * - * This runs in time linear to the list's length, because we have to mark - * each element as not in the list. - */ - void clear() - { - while (popFirst()) { - continue; - } - } - - /* - * Allow range-based iteration: - * - * for (MyElementType* elt : myList) { ... } - */ - Iterator begin() { - return Iterator(getFirst()); - } - Iterator end() { - return Iterator(nullptr); - } - - /* - * Measures the memory consumption of the list excluding |this|. Note that - * it only measures the list elements themselves. If the list elements - * contain pointers to other memory blocks, those blocks must be measured - * separately during a subsequent iteration over the list. - */ - size_t sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const - { - size_t n = 0; - for (const T* t = getFirst(); t; t = t->getNext()) { - n += aMallocSizeOf(t); - } - return n; - } - - /* - * Like sizeOfExcludingThis(), but measures |this| as well. - */ - size_t sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const - { - return aMallocSizeOf(this) + sizeOfExcludingThis(aMallocSizeOf); - } - - /* - * In a debug build, make sure that the list is sane (no cycles, consistent - * mNext/mPrev pointers, only one sentinel). Has no effect in release builds. - */ - void debugAssertIsSane() const - { -#ifdef DEBUG - const LinkedListElement* slow; - const LinkedListElement* fast1; - const LinkedListElement* fast2; - - /* - * Check for cycles in the forward singly-linked list using the - * tortoise/hare algorithm. - */ - for (slow = sentinel.mNext, - fast1 = sentinel.mNext->mNext, - fast2 = sentinel.mNext->mNext->mNext; - slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; - slow = slow->mNext, fast1 = fast2->mNext, fast2 = fast1->mNext) { - MOZ_ASSERT(slow != fast1); - MOZ_ASSERT(slow != fast2); - } - - /* Check for cycles in the backward singly-linked list. */ - for (slow = sentinel.mPrev, - fast1 = sentinel.mPrev->mPrev, - fast2 = sentinel.mPrev->mPrev->mPrev; - slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; - slow = slow->mPrev, fast1 = fast2->mPrev, fast2 = fast1->mPrev) { - MOZ_ASSERT(slow != fast1); - MOZ_ASSERT(slow != fast2); - } - - /* - * Check that |sentinel| is the only node in the list with - * mIsSentinel == true. - */ - for (const LinkedListElement* elem = sentinel.mNext; - elem != &sentinel; - elem = elem->mNext) { - MOZ_ASSERT(!elem->mIsSentinel); - } - - /* Check that the mNext/mPrev pointers match up. */ - const LinkedListElement* prev = &sentinel; - const LinkedListElement* cur = sentinel.mNext; - do { - MOZ_ASSERT(cur->mPrev == prev); - MOZ_ASSERT(prev->mNext == cur); - - prev = cur; - cur = cur->mNext; - } while (cur != &sentinel); -#endif /* ifdef DEBUG */ - } - -private: - friend class LinkedListElement; - - void assertContains(const RawType aValue) const - { -#ifdef DEBUG - for (ConstRawType elem = getFirst(); elem; elem = elem->getNext()) { - if (elem == aValue) { - return; - } - } - MOZ_CRASH("element wasn't found in this list!"); -#endif - } - - LinkedList& operator=(const LinkedList& aOther) = delete; - LinkedList(const LinkedList& aOther) = delete; -}; - -template -class AutoCleanLinkedList : public LinkedList -{ -public: - ~AutoCleanLinkedList() - { - while (T* element = this->popFirst()) { - delete element; - } - } -}; - -} /* namespace mozilla */ - -#endif /* __cplusplus */ - -#endif /* mozilla_LinkedList_h */ diff --git a/mac/include/spidermonkey/mozilla/MacroArgs.h b/mac/include/spidermonkey/mozilla/MacroArgs.h deleted file mode 100644 index 52ed1e82..00000000 --- a/mac/include/spidermonkey/mozilla/MacroArgs.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements various macros meant to ease the use of variadic macros. - */ - -#ifndef mozilla_MacroArgs_h -#define mozilla_MacroArgs_h - -// Concatenates pre-processor tokens in a way that can be used with __LINE__. -#define MOZ_CONCAT2(x, y) x ## y -#define MOZ_CONCAT(x, y) MOZ_CONCAT2(x, y) - -/* - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(aPrefix, ...) counts the number of variadic - * arguments and prefixes it with |aPrefix|. For example: - * - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(, foo, 42) expands to 2 - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(A, foo, 42, bar) expands to A3 - * - * You must pass in between 1 and 50 (inclusive) variadic arguments, past - * |aPrefix|. It is not legal to do - * - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(prefix) - * - * (that is, pass in 0 variadic arguments). To ensure that a compile-time - * error occurs when these constraints are violated, use the - * MOZ_STATIC_ASSERT_VALID_ARG_COUNT macro with the same variaidc arguments - * wherever this macro is used. - * - * Passing (__VA_ARGS__, ) rather than simply calling - * MOZ_MACROARGS_ARG_COUNT_HELPER2(__VA_ARGS__, ) very - * carefully tiptoes around a MSVC bug where it improperly expands __VA_ARGS__ - * as a single token in argument lists. For details, see: - * - * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement - * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644 - */ -#define MOZ_PASTE_PREFIX_AND_ARG_COUNT(aPrefix, ...) \ - MOZ_MACROARGS_ARG_COUNT_HELPER((__VA_ARGS__, \ - aPrefix##50, aPrefix##49, aPrefix##48, aPrefix##47, aPrefix##46, \ - aPrefix##45, aPrefix##44, aPrefix##43, aPrefix##42, aPrefix##41, \ - aPrefix##40, aPrefix##39, aPrefix##38, aPrefix##37, aPrefix##36, \ - aPrefix##35, aPrefix##34, aPrefix##33, aPrefix##32, aPrefix##31, \ - aPrefix##30, aPrefix##29, aPrefix##28, aPrefix##27, aPrefix##26, \ - aPrefix##25, aPrefix##24, aPrefix##23, aPrefix##22, aPrefix##21, \ - aPrefix##20, aPrefix##19, aPrefix##18, aPrefix##17, aPrefix##16, \ - aPrefix##15, aPrefix##14, aPrefix##13, aPrefix##12, aPrefix##11, \ - aPrefix##10, aPrefix##9, aPrefix##8, aPrefix##7, aPrefix##6, \ - aPrefix##5, aPrefix##4, aPrefix##3, aPrefix##2, aPrefix##1, aPrefix##0)) - -#define MOZ_MACROARGS_ARG_COUNT_HELPER(aArgs) \ - MOZ_MACROARGS_ARG_COUNT_HELPER2 aArgs - -#define MOZ_MACROARGS_ARG_COUNT_HELPER2( \ - a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, \ - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, \ - a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, \ - a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, \ - a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, \ - a51, ...) a51 - -/* - * MOZ_STATIC_ASSERT_VALID_ARG_COUNT ensures that a compile-time error occurs - * when the argument count constraints of MOZ_PASTE_PREFIX_AND_ARG_COUNT are - * violated. Use this macro wherever MOZ_PASTE_PREFIX_AND_ARG_COUNT is used - * and pass it the same variadic arguments. - * - * This macro employs a few dirty tricks to function. To detect the zero - * argument case, |(__VA_ARGS__)| is stringified, sizeof-ed, and compared to - * what it should be in the absence of arguments. - * - * Detecting too many arguments is a little trickier. With a valid argument - * count and a prefix of 1, MOZ_PASTE_PREFIX_AND_ARG_COUNT expands to e.g. 14. - * With a prefix of 0.0, it expands to e.g. 0.04. If there are too many - * arguments, it expands to the first argument over the limit. If this - * exceeding argument is a number, the assertion will fail as there is no - * number than can simultaneously be both > 10 and == 0. If the exceeding - * argument is not a number, a compile-time error should still occur due to - * the operations performed on it. - */ -#define MOZ_MACROARGS_STRINGIFY_HELPER(x) #x -#define MOZ_STATIC_ASSERT_VALID_ARG_COUNT(...) \ - static_assert( \ - sizeof(MOZ_MACROARGS_STRINGIFY_HELPER((__VA_ARGS__))) != sizeof("()") && \ - (MOZ_PASTE_PREFIX_AND_ARG_COUNT(1, __VA_ARGS__)) > 10 && \ - (int)(MOZ_PASTE_PREFIX_AND_ARG_COUNT(0.0, __VA_ARGS__)) == 0, \ - "MOZ_STATIC_ASSERT_VALID_ARG_COUNT requires 1 to 50 arguments") /* ; */ - -/* - * MOZ_ARGS_AFTER_N expands to its arguments excluding the first |N| - * arguments. For example: - * - * MOZ_ARGS_AFTER_2(a, b, c, d) expands to: c, d - */ -#define MOZ_ARGS_AFTER_1(a1, ...) __VA_ARGS__ -#define MOZ_ARGS_AFTER_2(a1, a2, ...) __VA_ARGS__ - -/* - * MOZ_ARG_N expands to its |N|th argument. - */ -#define MOZ_ARG_1(a1, ...) a1 -#define MOZ_ARG_2(a1, a2, ...) a2 - -#endif /* mozilla_MacroArgs_h */ diff --git a/mac/include/spidermonkey/mozilla/MacroForEach.h b/mac/include/spidermonkey/mozilla/MacroForEach.h deleted file mode 100644 index 7c0e3cfb..00000000 --- a/mac/include/spidermonkey/mozilla/MacroForEach.h +++ /dev/null @@ -1,158 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements a higher-order macro for iteratively calling another macro with - * fixed leading arguments, plus a trailing element picked from a second list - * of arguments. - */ - -#ifndef mozilla_MacroForEach_h -#define mozilla_MacroForEach_h - -#include "mozilla/MacroArgs.h" - -/* - * MOZ_FOR_EACH(aMacro, aFixedArgs, aArgs) expands to N calls to the macro - * |aMacro| where N is equal the number of items in the list |aArgs|. The - * arguments for each |aMacro| call are composed of *all* arguments in the list - * |aFixedArgs| as well as a single argument in the list |aArgs|. For example: - * - * #define MACRO_A(x) x + - * int a = MOZ_FOR_EACH(MACRO_A, (), (1, 2, 3)) 0; - * // Expands to: MACRO_A(1) MACRO_A(2) MACRO_A(3) 0; - * // And further to: 1 + 2 + 3 + 0; - * - * #define MACRO_B(k, x) (k + x) + - * int b = MOZ_FOR_EACH(MACRO_B, (5,), (1, 2)) 0; - * // Expands to: MACRO_B(5, 1) MACRO_B(5, 2) 0; - * - * #define MACRO_C(k1, k2, x) (k1 + k2 + x) + - * int c = MOZ_FOR_EACH(MACRO_C, (5, 8,), (1, 2)) 0; - * // Expands to: MACRO_B(5, 8, 1) MACRO_B(5, 8, 2) 0; - * - * If the |aFixedArgs| list is not empty, a trailing comma must be included. - * - * The |aArgs| list must be not be empty and may be up to 50 items long. Use - * MOZ_STATIC_ASSERT_VALID_ARG_COUNT to ensure that violating this constraint - * results in a compile-time error. - */ -#define MOZ_FOR_EACH_EXPAND_HELPER(...) __VA_ARGS__ -#define MOZ_FOR_EACH_GLUE(a, b) a b -#define MOZ_FOR_EACH(aMacro, aFixedArgs, aArgs) \ - MOZ_FOR_EACH_GLUE( \ - MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_FOR_EACH_, \ - MOZ_FOR_EACH_EXPAND_HELPER aArgs), \ - (aMacro, aFixedArgs, aArgs)) - -#define MOZ_FOR_EACH_HELPER_GLUE(a, b) a b -#define MOZ_FOR_EACH_HELPER(aMacro, aFixedArgs, aArgs) \ - MOZ_FOR_EACH_HELPER_GLUE( \ - aMacro, \ - (MOZ_FOR_EACH_EXPAND_HELPER aFixedArgs MOZ_ARG_1 aArgs)) - -#define MOZ_FOR_EACH_1(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) -#define MOZ_FOR_EACH_2(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_1(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_3(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_2(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_4(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_3(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_5(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_4(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_6(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_5(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_7(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_6(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_8(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_7(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_9(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_8(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_10(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_9(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_11(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_10(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_12(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_11(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_13(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_12(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_14(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_13(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_15(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_14(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_16(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_15(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_17(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_16(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_18(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_17(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_19(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_18(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_20(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_19(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_21(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_20(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_22(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_21(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_23(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_22(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_24(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_23(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_25(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_24(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_26(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_25(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_27(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_26(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_28(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_27(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_29(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_28(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_30(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_29(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_31(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_30(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_32(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_31(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_33(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_32(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_34(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_33(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_35(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_34(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_36(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_35(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_37(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_36(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_38(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_37(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_39(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_38(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_40(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_39(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_41(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_40(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_42(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_41(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_43(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_42(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_44(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_43(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_45(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_44(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_46(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_45(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_47(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_46(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_48(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_47(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_49(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_48(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_50(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_49(m, fa, (MOZ_ARGS_AFTER_1 a)) - -#endif /* mozilla_MacroForEach_h */ diff --git a/mac/include/spidermonkey/mozilla/MathAlgorithms.h b/mac/include/spidermonkey/mozilla/MathAlgorithms.h deleted file mode 100644 index 4db6de49..00000000 --- a/mac/include/spidermonkey/mozilla/MathAlgorithms.h +++ /dev/null @@ -1,547 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* mfbt maths algorithms. */ - -#ifndef mozilla_MathAlgorithms_h -#define mozilla_MathAlgorithms_h - -#include "mozilla/Assertions.h" -#include "mozilla/TypeTraits.h" - -#include -#include -#include - -namespace mozilla { - -// Greatest Common Divisor -template -MOZ_ALWAYS_INLINE IntegerType -EuclidGCD(IntegerType aA, IntegerType aB) -{ - // Euclid's algorithm; O(N) in the worst case. (There are better - // ways, but we don't need them for the current use of this algo.) - MOZ_ASSERT(aA > IntegerType(0)); - MOZ_ASSERT(aB > IntegerType(0)); - - while (aA != aB) { - if (aA > aB) { - aA = aA - aB; - } else { - aB = aB - aA; - } - } - - return aA; -} - -// Least Common Multiple -template -MOZ_ALWAYS_INLINE IntegerType -EuclidLCM(IntegerType aA, IntegerType aB) -{ - // Divide first to reduce overflow risk. - return (aA / EuclidGCD(aA, aB)) * aB; -} - -namespace detail { - -template -struct AllowDeprecatedAbsFixed : FalseType {}; - -template<> struct AllowDeprecatedAbsFixed : TrueType {}; -template<> struct AllowDeprecatedAbsFixed : TrueType {}; - -template -struct AllowDeprecatedAbs : AllowDeprecatedAbsFixed {}; - -template<> struct AllowDeprecatedAbs : TrueType {}; -template<> struct AllowDeprecatedAbs : TrueType {}; - -} // namespace detail - -// DO NOT USE DeprecatedAbs. It exists only until its callers can be converted -// to Abs below, and it will be removed when all callers have been changed. -template -inline typename mozilla::EnableIf::value, T>::Type -DeprecatedAbs(const T aValue) -{ - // The absolute value of the smallest possible value of a signed-integer type - // won't fit in that type (on twos-complement systems -- and we're blithely - // assuming we're on such systems, for the non- types listed above), - // so assert that the input isn't that value. - // - // This is the case if: the value is non-negative; or if adding one (giving a - // value in the range [-maxvalue, 0]), then negating (giving a value in the - // range [0, maxvalue]), doesn't produce maxvalue (because in twos-complement, - // (minvalue + 1) == -maxvalue). - MOZ_ASSERT(aValue >= 0 || - -(aValue + 1) != T((1ULL << (CHAR_BIT * sizeof(T) - 1)) - 1), - "You can't negate the smallest possible negative integer!"); - return aValue >= 0 ? aValue : -aValue; -} - -namespace detail { - -// For now mozilla::Abs only takes intN_T, the signed natural types, and -// float/double/long double. Feel free to add overloads for other standard, -// signed types if you need them. - -template -struct AbsReturnTypeFixed; - -template<> struct AbsReturnTypeFixed { typedef uint8_t Type; }; -template<> struct AbsReturnTypeFixed { typedef uint16_t Type; }; -template<> struct AbsReturnTypeFixed { typedef uint32_t Type; }; -template<> struct AbsReturnTypeFixed { typedef uint64_t Type; }; - -template -struct AbsReturnType : AbsReturnTypeFixed {}; - -template<> struct AbsReturnType : - EnableIf {}; -template<> struct AbsReturnType { typedef unsigned char Type; }; -template<> struct AbsReturnType { typedef unsigned short Type; }; -template<> struct AbsReturnType { typedef unsigned int Type; }; -template<> struct AbsReturnType { typedef unsigned long Type; }; -template<> struct AbsReturnType { typedef unsigned long long Type; }; -template<> struct AbsReturnType { typedef float Type; }; -template<> struct AbsReturnType { typedef double Type; }; -template<> struct AbsReturnType { typedef long double Type; }; - -} // namespace detail - -template -inline typename detail::AbsReturnType::Type -Abs(const T aValue) -{ - typedef typename detail::AbsReturnType::Type ReturnType; - return aValue >= 0 ? ReturnType(aValue) : ~ReturnType(aValue) + 1; -} - -template<> -inline float -Abs(const float aFloat) -{ - return std::fabs(aFloat); -} - -template<> -inline double -Abs(const double aDouble) -{ - return std::fabs(aDouble); -} - -template<> -inline long double -Abs(const long double aLongDouble) -{ - return std::fabs(aLongDouble); -} - -} // namespace mozilla - -#if defined(_MSC_VER) && \ - (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) -# define MOZ_BITSCAN_WINDOWS - -# include -# pragma intrinsic(_BitScanForward, _BitScanReverse) - -# if defined(_M_AMD64) || defined(_M_X64) -# define MOZ_BITSCAN_WINDOWS64 -# pragma intrinsic(_BitScanForward64, _BitScanReverse64) -# endif - -#endif - -namespace mozilla { - -namespace detail { - -#if defined(MOZ_BITSCAN_WINDOWS) - -inline uint_fast8_t -CountLeadingZeroes32(uint32_t aValue) -{ - unsigned long index; - if (!_BitScanReverse(&index, static_cast(aValue))) - return 32; - return uint_fast8_t(31 - index); -} - - -inline uint_fast8_t -CountTrailingZeroes32(uint32_t aValue) -{ - unsigned long index; - if (!_BitScanForward(&index, static_cast(aValue))) - return 32; - return uint_fast8_t(index); -} - -inline uint_fast8_t -CountPopulation32(uint32_t aValue) -{ - uint32_t x = aValue - ((aValue >> 1) & 0x55555555); - x = (x & 0x33333333) + ((x >> 2) & 0x33333333); - return (((x + (x >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24; -} -inline uint_fast8_t -CountPopulation64(uint64_t aValue) -{ - return uint_fast8_t(CountPopulation32(aValue & 0xffffffff) + - CountPopulation32(aValue >> 32)); -} - -inline uint_fast8_t -CountLeadingZeroes64(uint64_t aValue) -{ -#if defined(MOZ_BITSCAN_WINDOWS64) - unsigned long index; - if (!_BitScanReverse64(&index, static_cast(aValue))) - return 64; - return uint_fast8_t(63 - index); -#else - uint32_t hi = uint32_t(aValue >> 32); - if (hi != 0) { - return CountLeadingZeroes32(hi); - } - return 32u + CountLeadingZeroes32(uint32_t(aValue)); -#endif -} - -inline uint_fast8_t -CountTrailingZeroes64(uint64_t aValue) -{ -#if defined(MOZ_BITSCAN_WINDOWS64) - unsigned long index; - if (!_BitScanForward64(&index, static_cast(aValue))) - return 64; - return uint_fast8_t(index); -#else - uint32_t lo = uint32_t(aValue); - if (lo != 0) { - return CountTrailingZeroes32(lo); - } - return 32u + CountTrailingZeroes32(uint32_t(aValue >> 32)); -#endif -} - -# ifdef MOZ_HAVE_BITSCAN64 -# undef MOZ_HAVE_BITSCAN64 -# endif - -#elif defined(__clang__) || defined(__GNUC__) - -# if defined(__clang__) -# if !__has_builtin(__builtin_ctz) || !__has_builtin(__builtin_clz) -# error "A clang providing __builtin_c[lt]z is required to build" -# endif -# else - // gcc has had __builtin_clz and friends since 3.4: no need to check. -# endif - -inline uint_fast8_t -CountLeadingZeroes32(uint32_t aValue) -{ - return __builtin_clz(aValue); -} - -inline uint_fast8_t -CountTrailingZeroes32(uint32_t aValue) -{ - return __builtin_ctz(aValue); -} - -inline uint_fast8_t -CountPopulation32(uint32_t aValue) -{ - return __builtin_popcount(aValue); -} - -inline uint_fast8_t -CountPopulation64(uint64_t aValue) -{ - return __builtin_popcountll(aValue); -} - -inline uint_fast8_t -CountLeadingZeroes64(uint64_t aValue) -{ - return __builtin_clzll(aValue); -} - -inline uint_fast8_t -CountTrailingZeroes64(uint64_t aValue) -{ - return __builtin_ctzll(aValue); -} - -#else -# error "Implement these!" -inline uint_fast8_t CountLeadingZeroes32(uint32_t aValue) = delete; -inline uint_fast8_t CountTrailingZeroes32(uint32_t aValue) = delete; -inline uint_fast8_t CountPopulation32(uint32_t aValue) = delete; -inline uint_fast8_t CountPopulation64(uint64_t aValue) = delete; -inline uint_fast8_t CountLeadingZeroes64(uint64_t aValue) = delete; -inline uint_fast8_t CountTrailingZeroes64(uint64_t aValue) = delete; -#endif - -} // namespace detail - -/** - * Compute the number of high-order zero bits in the NON-ZERO number |aValue|. - * That is, looking at the bitwise representation of the number, with the - * highest- valued bits at the start, return the number of zeroes before the - * first one is observed. - * - * CountLeadingZeroes32(0xF0FF1000) is 0; - * CountLeadingZeroes32(0x7F8F0001) is 1; - * CountLeadingZeroes32(0x3FFF0100) is 2; - * CountLeadingZeroes32(0x1FF50010) is 3; and so on. - */ -inline uint_fast8_t -CountLeadingZeroes32(uint32_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountLeadingZeroes32(aValue); -} - -/** - * Compute the number of low-order zero bits in the NON-ZERO number |aValue|. - * That is, looking at the bitwise representation of the number, with the - * lowest- valued bits at the start, return the number of zeroes before the - * first one is observed. - * - * CountTrailingZeroes32(0x0100FFFF) is 0; - * CountTrailingZeroes32(0x7000FFFE) is 1; - * CountTrailingZeroes32(0x0080FFFC) is 2; - * CountTrailingZeroes32(0x0080FFF8) is 3; and so on. - */ -inline uint_fast8_t -CountTrailingZeroes32(uint32_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountTrailingZeroes32(aValue); -} - -/** - * Compute the number of one bits in the number |aValue|, - */ -inline uint_fast8_t -CountPopulation32(uint32_t aValue) -{ - return detail::CountPopulation32(aValue); -} - -/** Analogous to CountPopulation32, but for 64-bit numbers */ -inline uint_fast8_t -CountPopulation64(uint64_t aValue) -{ - return detail::CountPopulation64(aValue); -} - -/** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ -inline uint_fast8_t -CountLeadingZeroes64(uint64_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountLeadingZeroes64(aValue); -} - -/** Analogous to CountTrailingZeroes32, but for 64-bit numbers. */ -inline uint_fast8_t -CountTrailingZeroes64(uint64_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountTrailingZeroes64(aValue); -} - -namespace detail { - -template -class CeilingLog2; - -template -class CeilingLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - // Check for <= 1 to avoid the == 0 undefined case. - return aValue <= 1 ? 0u : 32u - CountLeadingZeroes32(aValue - 1); - } -}; - -template -class CeilingLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - // Check for <= 1 to avoid the == 0 undefined case. - return aValue <= 1 ? 0u : 64u - CountLeadingZeroes64(aValue - 1); - } -}; - -} // namespace detail - -/** - * Compute the log of the least power of 2 greater than or equal to |aValue|. - * - * CeilingLog2(0..1) is 0; - * CeilingLog2(2) is 1; - * CeilingLog2(3..4) is 2; - * CeilingLog2(5..8) is 3; - * CeilingLog2(9..16) is 4; and so on. - */ -template -inline uint_fast8_t -CeilingLog2(const T aValue) -{ - return detail::CeilingLog2::compute(aValue); -} - -/** A CeilingLog2 variant that accepts only size_t. */ -inline uint_fast8_t -CeilingLog2Size(size_t aValue) -{ - return CeilingLog2(aValue); -} - -namespace detail { - -template -class FloorLog2; - -template -class FloorLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - return 31u - CountLeadingZeroes32(aValue | 1); - } -}; - -template -class FloorLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - return 63u - CountLeadingZeroes64(aValue | 1); - } -}; - -} // namespace detail - -/** - * Compute the log of the greatest power of 2 less than or equal to |aValue|. - * - * FloorLog2(0..1) is 0; - * FloorLog2(2..3) is 1; - * FloorLog2(4..7) is 2; - * FloorLog2(8..15) is 3; and so on. - */ -template -inline uint_fast8_t -FloorLog2(const T aValue) -{ - return detail::FloorLog2::compute(aValue); -} - -/** A FloorLog2 variant that accepts only size_t. */ -inline uint_fast8_t -FloorLog2Size(size_t aValue) -{ - return FloorLog2(aValue); -} - -/* - * Compute the smallest power of 2 greater than or equal to |x|. |x| must not - * be so great that the computed value would overflow |size_t|. - */ -inline size_t -RoundUpPow2(size_t aValue) -{ - MOZ_ASSERT(aValue <= (size_t(1) << (sizeof(size_t) * CHAR_BIT - 1)), - "can't round up -- will overflow!"); - return size_t(1) << CeilingLog2(aValue); -} - -/** - * Rotates the bits of the given value left by the amount of the shift width. - */ -template -inline T -RotateLeft(const T aValue, uint_fast8_t aShift) -{ - MOZ_ASSERT(aShift < sizeof(T) * CHAR_BIT, "Shift value is too large!"); - MOZ_ASSERT(aShift > 0, - "Rotation by value length is undefined behavior, but compilers " - "do not currently fold a test into the rotate instruction. " - "Please remove this restriction when compilers optimize the " - "zero case (http://blog.regehr.org/archives/1063)."); - static_assert(IsUnsigned::value, "Rotates require unsigned values"); - return (aValue << aShift) | (aValue >> (sizeof(T) * CHAR_BIT - aShift)); -} - -/** - * Rotates the bits of the given value right by the amount of the shift width. - */ -template -inline T -RotateRight(const T aValue, uint_fast8_t aShift) -{ - MOZ_ASSERT(aShift < sizeof(T) * CHAR_BIT, "Shift value is too large!"); - MOZ_ASSERT(aShift > 0, - "Rotation by value length is undefined behavior, but compilers " - "do not currently fold a test into the rotate instruction. " - "Please remove this restriction when compilers optimize the " - "zero case (http://blog.regehr.org/archives/1063)."); - static_assert(IsUnsigned::value, "Rotates require unsigned values"); - return (aValue >> aShift) | (aValue << (sizeof(T) * CHAR_BIT - aShift)); -} - -/** - * Returns true if |x| is a power of two. - * Zero is not an integer power of two. (-Inf is not an integer) - */ -template -constexpr bool -IsPowerOfTwo(T x) -{ - static_assert(IsUnsigned::value, - "IsPowerOfTwo requires unsigned values"); - return x && (x & (x - 1)) == 0; -} - -template -inline T -Clamp(const T aValue, const T aMin, const T aMax) -{ - static_assert(IsIntegral::value, - "Clamp accepts only integral types, so that it doesn't have" - " to distinguish differently-signed zeroes (which users may" - " or may not care to distinguish, likely at a perf cost) or" - " to decide how to clamp NaN or a range with a NaN" - " endpoint."); - MOZ_ASSERT(aMin <= aMax); - - if (aValue <= aMin) - return aMin; - if (aValue >= aMax) - return aMax; - return aValue; -} - -} /* namespace mozilla */ - -#endif /* mozilla_MathAlgorithms_h */ diff --git a/mac/include/spidermonkey/mozilla/Maybe.h b/mac/include/spidermonkey/mozilla/Maybe.h deleted file mode 100644 index 2a601ac4..00000000 --- a/mac/include/spidermonkey/mozilla/Maybe.h +++ /dev/null @@ -1,551 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A class for optional values and in-place lazy construction. */ - -#ifndef mozilla_Maybe_h -#define mozilla_Maybe_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include // for placement new -#include - -namespace mozilla { - -struct Nothing { }; - -/* - * Maybe is a container class which contains either zero or one elements. It - * serves two roles. It can represent values which are *semantically* optional, - * augmenting a type with an explicit 'Nothing' value. In this role, it provides - * methods that make it easy to work with values that may be missing, along with - * equality and comparison operators so that Maybe values can be stored in - * containers. Maybe values can be constructed conveniently in expressions using - * type inference, as follows: - * - * void doSomething(Maybe aFoo) { - * if (aFoo) // Make sure that aFoo contains a value... - * aFoo->takeAction(); // and then use |aFoo->| to access it. - * } // |*aFoo| also works! - * - * doSomething(Nothing()); // Passes a Maybe containing no value. - * doSomething(Some(Foo(100))); // Passes a Maybe containing |Foo(100)|. - * - * You'll note that it's important to check whether a Maybe contains a value - * before using it, using conversion to bool, |isSome()|, or |isNothing()|. You - * can avoid these checks, and sometimes write more readable code, using - * |valueOr()|, |ptrOr()|, and |refOr()|, which allow you to retrieve the value - * in the Maybe and provide a default for the 'Nothing' case. You can also use - * |apply()| to call a function only if the Maybe holds a value, and |map()| to - * transform the value in the Maybe, returning another Maybe with a possibly - * different type. - * - * Maybe's other role is to support lazily constructing objects without using - * dynamic storage. A Maybe directly contains storage for a value, but it's - * empty by default. |emplace()|, as mentioned above, can be used to construct a - * value in Maybe's storage. The value a Maybe contains can be destroyed by - * calling |reset()|; this will happen automatically if a Maybe is destroyed - * while holding a value. - * - * It's a common idiom in C++ to use a pointer as a 'Maybe' type, with a null - * value meaning 'Nothing' and any other value meaning 'Some'. You can convert - * from such a pointer to a Maybe value using 'ToMaybe()'. - * - * Maybe is inspired by similar types in the standard library of many other - * languages (e.g. Haskell's Maybe and Rust's Option). In the C++ world it's - * very similar to std::optional, which was proposed for C++14 and originated in - * Boost. The most important differences between Maybe and std::optional are: - * - * - std::optional may be compared with T. We deliberately forbid that. - * - std::optional allows in-place construction without a separate call to - * |emplace()| by using a dummy |in_place_t| value to tag the appropriate - * constructor. - * - std::optional has |valueOr()|, equivalent to Maybe's |valueOr()|, but - * lacks corresponding methods for |refOr()| and |ptrOr()|. - * - std::optional lacks |map()| and |apply()|, making it less suitable for - * functional-style code. - * - std::optional lacks many convenience functions that Maybe has. Most - * unfortunately, it lacks equivalents of the type-inferred constructor - * functions |Some()| and |Nothing()|. - * - * N.B. GCC has missed optimizations with Maybe in the past and may generate - * extra branches/loads/stores. Use with caution on hot paths; it's not known - * whether or not this is still a problem. - */ -template -class Maybe -{ - bool mIsSome; - AlignedStorage2 mStorage; - -public: - typedef T ValueType; - - Maybe() : mIsSome(false) { } - ~Maybe() { reset(); } - - MOZ_IMPLICIT Maybe(Nothing) : mIsSome(false) { } - - Maybe(const Maybe& aOther) - : mIsSome(false) - { - if (aOther.mIsSome) { - emplace(*aOther); - } - } - - /** - * Maybe can be copy-constructed from a Maybe if U* and T* are - * compatible, or from Maybe. - */ - template::value && - (std::is_same::value || - (std::is_pointer::value && - std::is_base_of::type, - typename std::remove_pointer::type>::value))>::type> - MOZ_IMPLICIT - Maybe(const Maybe& aOther) - : mIsSome(false) - { - if (aOther.isSome()) { - emplace(*aOther); - } - } - - Maybe(Maybe&& aOther) - : mIsSome(false) - { - if (aOther.mIsSome) { - emplace(Move(*aOther)); - aOther.reset(); - } - } - - /** - * Maybe can be move-constructed from a Maybe if U* and T* are - * compatible, or from Maybe. - */ - template::value && - (std::is_same::value || - (std::is_pointer::value && - std::is_base_of::type, - typename std::remove_pointer::type>::value))>::type> - MOZ_IMPLICIT - Maybe(Maybe&& aOther) - : mIsSome(false) - { - if (aOther.isSome()) { - emplace(Move(*aOther)); - aOther.reset(); - } - } - - Maybe& operator=(const Maybe& aOther) - { - if (&aOther != this) { - if (aOther.mIsSome) { - if (mIsSome) { - // XXX(seth): The correct code for this branch, below, can't be used - // due to a bug in Visual Studio 2010. See bug 1052940. - /* - ref() = aOther.ref(); - */ - reset(); - emplace(*aOther); - } else { - emplace(*aOther); - } - } else { - reset(); - } - } - return *this; - } - - Maybe& operator=(Maybe&& aOther) - { - MOZ_ASSERT(this != &aOther, "Self-moves are prohibited"); - - if (aOther.mIsSome) { - if (mIsSome) { - ref() = Move(aOther.ref()); - } else { - emplace(Move(*aOther)); - } - aOther.reset(); - } else { - reset(); - } - - return *this; - } - - /* Methods that check whether this Maybe contains a value */ - explicit operator bool() const { return isSome(); } - bool isSome() const { return mIsSome; } - bool isNothing() const { return !mIsSome; } - - /* Returns the contents of this Maybe by value. Unsafe unless |isSome()|. */ - T value() const - { - MOZ_ASSERT(mIsSome); - return ref(); - } - - /* - * Returns the contents of this Maybe by value. If |isNothing()|, returns - * the default value provided. - */ - template - T valueOr(V&& aDefault) const - { - if (isSome()) { - return ref(); - } - return Forward(aDefault); - } - - /* - * Returns the contents of this Maybe by value. If |isNothing()|, returns - * the value returned from the function or functor provided. - */ - template - T valueOrFrom(F&& aFunc) const - { - if (isSome()) { - return ref(); - } - return aFunc(); - } - - /* Returns the contents of this Maybe by pointer. Unsafe unless |isSome()|. */ - T* ptr() - { - MOZ_ASSERT(mIsSome); - return &ref(); - } - - const T* ptr() const - { - MOZ_ASSERT(mIsSome); - return &ref(); - } - - /* - * Returns the contents of this Maybe by pointer. If |isNothing()|, - * returns the default value provided. - */ - T* ptrOr(T* aDefault) - { - if (isSome()) { - return ptr(); - } - return aDefault; - } - - const T* ptrOr(const T* aDefault) const - { - if (isSome()) { - return ptr(); - } - return aDefault; - } - - /* - * Returns the contents of this Maybe by pointer. If |isNothing()|, - * returns the value returned from the function or functor provided. - */ - template - T* ptrOrFrom(F&& aFunc) - { - if (isSome()) { - return ptr(); - } - return aFunc(); - } - - template - const T* ptrOrFrom(F&& aFunc) const - { - if (isSome()) { - return ptr(); - } - return aFunc(); - } - - T* operator->() - { - MOZ_ASSERT(mIsSome); - return ptr(); - } - - const T* operator->() const - { - MOZ_ASSERT(mIsSome); - return ptr(); - } - - /* Returns the contents of this Maybe by ref. Unsafe unless |isSome()|. */ - T& ref() - { - MOZ_ASSERT(mIsSome); - return *mStorage.addr(); - } - - const T& ref() const - { - MOZ_ASSERT(mIsSome); - return *mStorage.addr(); - } - - /* - * Returns the contents of this Maybe by ref. If |isNothing()|, returns - * the default value provided. - */ - T& refOr(T& aDefault) - { - if (isSome()) { - return ref(); - } - return aDefault; - } - - const T& refOr(const T& aDefault) const - { - if (isSome()) { - return ref(); - } - return aDefault; - } - - /* - * Returns the contents of this Maybe by ref. If |isNothing()|, returns the - * value returned from the function or functor provided. - */ - template - T& refOrFrom(F&& aFunc) - { - if (isSome()) { - return ref(); - } - return aFunc(); - } - - template - const T& refOrFrom(F&& aFunc) const - { - if (isSome()) { - return ref(); - } - return aFunc(); - } - - T& operator*() - { - MOZ_ASSERT(mIsSome); - return ref(); - } - - const T& operator*() const - { - MOZ_ASSERT(mIsSome); - return ref(); - } - - /* If |isSome()|, runs the provided function or functor on the contents of - * this Maybe. */ - template - Maybe& apply(Func aFunc) - { - if (isSome()) { - aFunc(ref()); - } - return *this; - } - - template - const Maybe& apply(Func aFunc) const - { - if (isSome()) { - aFunc(ref()); - } - return *this; - } - - /* - * If |isSome()|, runs the provided function and returns the result wrapped - * in a Maybe. If |isNothing()|, returns an empty Maybe value. - */ - template - auto map(Func aFunc) -> Maybe>().ref()))> - { - using ReturnType = decltype(aFunc(ref())); - if (isSome()) { - Maybe val; - val.emplace(aFunc(ref())); - return val; - } - return Maybe(); - } - - template - auto map(Func aFunc) const -> Maybe>().ref()))> - { - using ReturnType = decltype(aFunc(ref())); - if (isSome()) { - Maybe val; - val.emplace(aFunc(ref())); - return val; - } - return Maybe(); - } - - /* If |isSome()|, empties this Maybe and destroys its contents. */ - void reset() - { - if (isSome()) { - ref().T::~T(); - mIsSome = false; - } - } - - /* - * Constructs a T value in-place in this empty Maybe's storage. The - * arguments to |emplace()| are the parameters to T's constructor. - */ - template - void emplace(Args&&... aArgs) - { - MOZ_ASSERT(!mIsSome); - ::new (mStorage.addr()) T(Forward(aArgs)...); - mIsSome = true; - } -}; - -/* - * Some() creates a Maybe value containing the provided T value. If T has a - * move constructor, it's used to make this as efficient as possible. - * - * Some() selects the type of Maybe it returns by removing any const, volatile, - * or reference qualifiers from the type of the value you pass to it. This gives - * it more intuitive behavior when used in expressions, but it also means that - * if you need to construct a Maybe value that holds a const, volatile, or - * reference value, you need to use emplace() instead. - */ -template -Maybe::Type>::Type> -Some(T&& aValue) -{ - typedef typename RemoveCV::Type>::Type U; - Maybe value; - value.emplace(Forward(aValue)); - return value; -} - -template -Maybe::Type>::Type> -ToMaybe(T* aPtr) -{ - if (aPtr) { - return Some(*aPtr); - } - return Nothing(); -} - -/* - * Two Maybe values are equal if - * - both are Nothing, or - * - both are Some, and the values they contain are equal. - */ -template bool -operator==(const Maybe& aLHS, const Maybe& aRHS) -{ - if (aLHS.isNothing() != aRHS.isNothing()) { - return false; - } - return aLHS.isNothing() || *aLHS == *aRHS; -} - -template bool -operator!=(const Maybe& aLHS, const Maybe& aRHS) -{ - return !(aLHS == aRHS); -} - -/* - * We support comparison to Nothing to allow reasonable expressions like: - * if (maybeValue == Nothing()) { ... } - */ -template bool -operator==(const Maybe& aLHS, const Nothing& aRHS) -{ - return aLHS.isNothing(); -} - -template bool -operator!=(const Maybe& aLHS, const Nothing& aRHS) -{ - return !(aLHS == aRHS); -} - -template bool -operator==(const Nothing& aLHS, const Maybe& aRHS) -{ - return aRHS.isNothing(); -} - -template bool -operator!=(const Nothing& aLHS, const Maybe& aRHS) -{ - return !(aLHS == aRHS); -} - -/* - * Maybe values are ordered in the same way T values are ordered, except that - * Nothing comes before anything else. - */ -template bool -operator<(const Maybe& aLHS, const Maybe& aRHS) -{ - if (aLHS.isNothing()) { - return aRHS.isSome(); - } - if (aRHS.isNothing()) { - return false; - } - return *aLHS < *aRHS; -} - -template bool -operator>(const Maybe& aLHS, const Maybe& aRHS) -{ - return !(aLHS < aRHS || aLHS == aRHS); -} - -template bool -operator<=(const Maybe& aLHS, const Maybe& aRHS) -{ - return aLHS < aRHS || aLHS == aRHS; -} - -template bool -operator>=(const Maybe& aLHS, const Maybe& aRHS) -{ - return !(aLHS < aRHS); -} - -} // namespace mozilla - -#endif /* mozilla_Maybe_h */ diff --git a/mac/include/spidermonkey/mozilla/MaybeOneOf.h b/mac/include/spidermonkey/mozilla/MaybeOneOf.h deleted file mode 100644 index 9c38ff8b..00000000 --- a/mac/include/spidermonkey/mozilla/MaybeOneOf.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_MaybeOneOf_h -#define mozilla_MaybeOneOf_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Move.h" -#include "mozilla/TemplateLib.h" - -#include // For placement new - -namespace mozilla { - -/* - * MaybeOneOf is like Maybe, but it supports constructing either T1 - * or T2. When a MaybeOneOf is constructed, it is |empty()|, i.e., - * no value has been constructed and no destructor will be called when the - * MaybeOneOf is destroyed. Upon calling |construct()| or - * |construct()|, a T1 or T2 object will be constructed with the given - * arguments and that object will be destroyed when the owning MaybeOneOf is - * destroyed. - */ -template -class MaybeOneOf -{ - AlignedStorage::value> storage; - - enum State { None, SomeT1, SomeT2 } state; - template struct Type2State {}; - - template - T& as() - { - MOZ_ASSERT(state == Type2State::result); - return *(T*)storage.addr(); - } - - template - const T& as() const - { - MOZ_ASSERT(state == Type2State::result); - return *(T*)storage.addr(); - } - -public: - MaybeOneOf() : state(None) {} - ~MaybeOneOf() { destroyIfConstructed(); } - - MaybeOneOf(MaybeOneOf&& rhs) - : state(None) - { - if (!rhs.empty()) { - if (rhs.constructed()) { - construct(Move(rhs.as())); - rhs.as().~T1(); - } else { - construct(Move(rhs.as())); - rhs.as().~T2(); - } - rhs.state = None; - } - } - - MaybeOneOf &operator=(MaybeOneOf&& rhs) - { - MOZ_ASSERT(this != &rhs, "Self-move is prohibited"); - this->~MaybeOneOf(); - new(this) MaybeOneOf(Move(rhs)); - return *this; - } - - bool empty() const { return state == None; } - - template - bool constructed() const { return state == Type2State::result; } - - template - void construct(Args&&... aArgs) - { - MOZ_ASSERT(state == None); - state = Type2State::result; - ::new (storage.addr()) T(Forward(aArgs)...); - } - - template - T& ref() - { - return as(); - } - - template - const T& ref() const - { - return as(); - } - - void destroy() - { - MOZ_ASSERT(state == SomeT1 || state == SomeT2); - if (state == SomeT1) { - as().~T1(); - } else if (state == SomeT2) { - as().~T2(); - } - state = None; - } - - void destroyIfConstructed() - { - if (!empty()) { - destroy(); - } - } - -private: - MaybeOneOf(const MaybeOneOf& aOther) = delete; - const MaybeOneOf& operator=(const MaybeOneOf& aOther) = delete; -}; - -template -template -struct MaybeOneOf::Type2State -{ - typedef MaybeOneOf Enclosing; - static const typename Enclosing::State result = Enclosing::SomeT1; -}; - -template -template -struct MaybeOneOf::Type2State -{ - typedef MaybeOneOf Enclosing; - static const typename Enclosing::State result = Enclosing::SomeT2; -}; - -} // namespace mozilla - -#endif /* mozilla_MaybeOneOf_h */ diff --git a/mac/include/spidermonkey/mozilla/MemoryChecking.h b/mac/include/spidermonkey/mozilla/MemoryChecking.h deleted file mode 100644 index ff42d7f1..00000000 --- a/mac/include/spidermonkey/mozilla/MemoryChecking.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Provides a common interface to the ASan (AddressSanitizer) and Valgrind - * functions used to mark memory in certain ways. In detail, the following - * three macros are provided: - * - * MOZ_MAKE_MEM_NOACCESS - Mark memory as unsafe to access (e.g. freed) - * MOZ_MAKE_MEM_UNDEFINED - Mark memory as accessible, with content undefined - * MOZ_MAKE_MEM_DEFINED - Mark memory as accessible, with content defined - * - * With Valgrind in use, these directly map to the three respective Valgrind - * macros. With ASan in use, the NOACCESS macro maps to poisoning the memory, - * while the UNDEFINED/DEFINED macros unpoison memory. - * - * With no memory checker available, all macros expand to the empty statement. - */ - -#ifndef mozilla_MemoryChecking_h -#define mozilla_MemoryChecking_h - -#if defined(MOZ_VALGRIND) -#include "valgrind/memcheck.h" -#endif - -#if defined(MOZ_ASAN) || defined(MOZ_VALGRIND) -#define MOZ_HAVE_MEM_CHECKS 1 -#endif - -#if defined(MOZ_ASAN) -#include - -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" - -#ifdef _MSC_VER -// In clang-cl based ASAN, we link against the memory poisoning functions -// statically. -#define MOZ_ASAN_VISIBILITY -#else -#define MOZ_ASAN_VISIBILITY MOZ_EXPORT -#endif - -extern "C" { -/* These definitions are usually provided through the - * sanitizer/asan_interface.h header installed by ASan. - */ -void MOZ_ASAN_VISIBILITY -__asan_poison_memory_region(void const volatile *addr, size_t size); -void MOZ_ASAN_VISIBILITY -__asan_unpoison_memory_region(void const volatile *addr, size_t size); - -#define MOZ_MAKE_MEM_NOACCESS(addr, size) \ - __asan_poison_memory_region((addr), (size)) - -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \ - __asan_unpoison_memory_region((addr), (size)) - -#define MOZ_MAKE_MEM_DEFINED(addr, size) \ - __asan_unpoison_memory_region((addr), (size)) - -/* - * These definitions are usually provided through the - * sanitizer/lsan_interface.h header installed by LSan. - */ -void MOZ_EXPORT -__lsan_ignore_object(const void *p); - -} -#elif defined(MOZ_MSAN) -#include - -#include "mozilla/Types.h" - -extern "C" { -/* These definitions are usually provided through the - * sanitizer/msan_interface.h header installed by MSan. - */ -void MOZ_EXPORT -__msan_poison(void const volatile *addr, size_t size); -void MOZ_EXPORT -__msan_unpoison(void const volatile *addr, size_t size); - -#define MOZ_MAKE_MEM_NOACCESS(addr, size) \ - __msan_poison((addr), (size)) - -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \ - __msan_poison((addr), (size)) - -#define MOZ_MAKE_MEM_DEFINED(addr, size) \ - __msan_unpoison((addr), (size)) -} -#elif defined(MOZ_VALGRIND) -#define MOZ_MAKE_MEM_NOACCESS(addr, size) \ - VALGRIND_MAKE_MEM_NOACCESS((addr), (size)) - -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \ - VALGRIND_MAKE_MEM_UNDEFINED((addr), (size)) - -#define MOZ_MAKE_MEM_DEFINED(addr, size) \ - VALGRIND_MAKE_MEM_DEFINED((addr), (size)) -#else - -#define MOZ_MAKE_MEM_NOACCESS(addr, size) do {} while (0) -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) do {} while (0) -#define MOZ_MAKE_MEM_DEFINED(addr, size) do {} while (0) - -#endif - -/* - * MOZ_LSAN_INTENTIONAL_LEAK(X) is a macro to tell LeakSanitizer that X - * points to a value that will intentionally never be deallocated during - * the execution of the process. - * - * Additional uses of this macro should be reviewed by people - * conversant in leak-checking and/or MFBT peers. - */ -#if defined(MOZ_ASAN) -# define MOZ_LSAN_INTENTIONALLY_LEAK_OBJECT(X) __lsan_ignore_object(X) -#else -# define MOZ_LSAN_INTENTIONALLY_LEAK_OBJECT(X) /* nothing */ -#endif // defined(MOZ_ASAN) - - -#endif /* mozilla_MemoryChecking_h */ diff --git a/mac/include/spidermonkey/mozilla/MemoryReporting.h b/mac/include/spidermonkey/mozilla/MemoryReporting.h deleted file mode 100644 index d2340ecf..00000000 --- a/mac/include/spidermonkey/mozilla/MemoryReporting.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Memory reporting infrastructure. */ - -#ifndef mozilla_MemoryReporting_h -#define mozilla_MemoryReporting_h - -#include - -#ifdef __cplusplus - -namespace mozilla { - -/* - * This is for functions that are like malloc_usable_size. Such functions are - * used for measuring the size of data structures. - */ -typedef size_t (*MallocSizeOf)(const void* p); - -} /* namespace mozilla */ - -#endif /* __cplusplus */ - -typedef size_t (*MozMallocSizeOf)(const void* p); - -#endif /* mozilla_MemoryReporting_h */ diff --git a/mac/include/spidermonkey/mozilla/Move.h b/mac/include/spidermonkey/mozilla/Move.h deleted file mode 100644 index f6d0bfc1..00000000 --- a/mac/include/spidermonkey/mozilla/Move.h +++ /dev/null @@ -1,238 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* C++11-style, but C++98-usable, "move references" implementation. */ - -#ifndef mozilla_Move_h -#define mozilla_Move_h - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/* - * "Move" References - * - * Some types can be copied much more efficiently if we know the original's - * value need not be preserved --- that is, if we are doing a "move", not a - * "copy". For example, if we have: - * - * Vector u; - * Vector v(u); - * - * the constructor for v must apply a copy constructor to each element of u --- - * taking time linear in the length of u. However, if we know we will not need u - * any more once v has been initialized, then we could initialize v very - * efficiently simply by stealing u's dynamically allocated buffer and giving it - * to v --- a constant-time operation, regardless of the size of u. - * - * Moves often appear in container implementations. For example, when we append - * to a vector, we may need to resize its buffer. This entails moving each of - * its extant elements from the old, smaller buffer to the new, larger buffer. - * But once the elements have been migrated, we're just going to throw away the - * old buffer; we don't care if they still have their values. So if the vector's - * element type can implement "move" more efficiently than "copy", the vector - * resizing should by all means use a "move" operation. Hash tables should also - * use moves when resizing their internal array as entries are added and - * removed. - * - * The details of the optimization, and whether it's worth applying, vary - * from one type to the next: copying an 'int' is as cheap as moving it, so - * there's no benefit in distinguishing 'int' moves from copies. And while - * some constructor calls for complex types are moves, many really have to - * be copies, and can't be optimized this way. So we need: - * - * 1) a way for a type (like Vector) to announce that it can be moved more - * efficiently than it can be copied, and provide an implementation of that - * move operation; and - * - * 2) a way for a particular invocation of a copy constructor to say that it's - * really a move, not a copy, and that the value of the original isn't - * important afterwards (although it must still be safe to destroy). - * - * If a constructor has a single argument of type 'T&&' (an 'rvalue reference - * to T'), that indicates that it is a 'move constructor'. That's 1). It should - * move, not copy, its argument into the object being constructed. It may leave - * the original in any safely-destructible state. - * - * If a constructor's argument is an rvalue, as in 'C(f(x))' or 'C(x + y)', as - * opposed to an lvalue, as in 'C(x)', then overload resolution will prefer the - * move constructor, if there is one. The 'mozilla::Move' function, defined in - * this file, is an identity function you can use in a constructor invocation to - * make any argument into an rvalue, like this: C(Move(x)). That's 2). (You - * could use any function that works, but 'Move' indicates your intention - * clearly.) - * - * Where we might define a copy constructor for a class C like this: - * - * C(const C& rhs) { ... copy rhs to this ... } - * - * we would declare a move constructor like this: - * - * C(C&& rhs) { .. move rhs to this ... } - * - * And where we might perform a copy like this: - * - * C c2(c1); - * - * we would perform a move like this: - * - * C c2(Move(c1)); - * - * Note that 'T&&' implicitly converts to 'T&'. So you can pass a 'T&&' to an - * ordinary copy constructor for a type that doesn't support a special move - * constructor, and you'll just get a copy. This means that templates can use - * Move whenever they know they won't use the original value any more, even if - * they're not sure whether the type at hand has a specialized move constructor. - * If it doesn't, the 'T&&' will just convert to a 'T&', and the ordinary copy - * constructor will apply. - * - * A class with a move constructor can also provide a move assignment operator. - * A generic definition would run this's destructor, and then apply the move - * constructor to *this's memory. A typical definition: - * - * C& operator=(C&& rhs) { - * MOZ_ASSERT(&rhs != this, "self-moves are prohibited"); - * this->~C(); - * new(this) C(Move(rhs)); - * return *this; - * } - * - * With that in place, one can write move assignments like this: - * - * c2 = Move(c1); - * - * This destroys c2, moves c1's value to c2, and leaves c1 in an undefined but - * destructible state. - * - * As we say, a move must leave the original in a "destructible" state. The - * original's destructor will still be called, so if a move doesn't - * actually steal all its resources, that's fine. We require only that the - * move destination must take on the original's value; and that destructing - * the original must not break the move destination. - * - * (Opinions differ on whether move assignment operators should deal with move - * assignment of an object onto itself. It seems wise to either handle that - * case, or assert that it does not occur.) - * - * Forwarding: - * - * Sometimes we want copy construction or assignment if we're passed an ordinary - * value, but move construction if passed an rvalue reference. For example, if - * our constructor takes two arguments and either could usefully be a move, it - * seems silly to write out all four combinations: - * - * C::C(X& x, Y& y) : x(x), y(y) { } - * C::C(X& x, Y&& y) : x(x), y(Move(y)) { } - * C::C(X&& x, Y& y) : x(Move(x)), y(y) { } - * C::C(X&& x, Y&& y) : x(Move(x)), y(Move(y)) { } - * - * To avoid this, C++11 has tweaks to make it possible to write what you mean. - * The four constructor overloads above can be written as one constructor - * template like so[0]: - * - * template - * C::C(XArg&& x, YArg&& y) : x(Forward(x)), y(Forward(y)) { } - * - * ("'Don't Repeat Yourself'? What's that?") - * - * This takes advantage of two new rules in C++11: - * - * - First, when a function template takes an argument that is an rvalue - * reference to a template argument (like 'XArg&& x' and 'YArg&& y' above), - * then when the argument is applied to an lvalue, the template argument - * resolves to 'T&'; and when it is applied to an rvalue, the template - * argument resolves to 'T'. Thus, in a call to C::C like: - * - * X foo(int); - * Y yy; - * - * C(foo(5), yy) - * - * XArg would resolve to 'X', and YArg would resolve to 'Y&'. - * - * - Second, Whereas C++ used to forbid references to references, C++11 defines - * 'collapsing rules': 'T& &', 'T&& &', and 'T& &&' (that is, any combination - * involving an lvalue reference) now collapse to simply 'T&'; and 'T&& &&' - * collapses to 'T&&'. - * - * Thus, in the call above, 'XArg&&' is 'X&&'; and 'YArg&&' is 'Y& &&', which - * collapses to 'Y&'. Because the arguments are declared as rvalue references - * to template arguments, the lvalue-ness "shines through" where present. - * - * Then, the 'Forward' function --- you must invoke 'Forward' with its type - * argument --- returns an lvalue reference or an rvalue reference to its - * argument, depending on what T is. In our unified constructor definition, that - * means that we'll invoke either the copy or move constructors for x and y, - * depending on what we gave C's constructor. In our call, we'll move 'foo()' - * into 'x', but copy 'yy' into 'y'. - * - * This header file defines Move and Forward in the mozilla namespace. It's up - * to individual containers to annotate moves as such, by calling Move; and it's - * up to individual types to define move constructors and assignment operators - * when valuable. - * - * (C++11 says that the header file should define 'std::move' and - * 'std::forward', which are just like our 'Move' and 'Forward'; but those - * definitions aren't available in that header on all our platforms, so we - * define them ourselves here.) - * - * 0. This pattern is known as "perfect forwarding". Interestingly, it is not - * actually perfect, and it can't forward all possible argument expressions! - * There is a C++11 issue: you can't form a reference to a bit-field. As a - * workaround, assign the bit-field to a local variable and use that: - * - * // C is as above - * struct S { int x : 1; } s; - * C(s.x, 0); // BAD: s.x is a reference to a bit-field, can't form those - * int tmp = s.x; - * C(tmp, 0); // OK: tmp not a bit-field - */ - -/** - * Identical to std::Move(); this is necessary until our stlport supports - * std::move(). - */ -template -inline typename RemoveReference::Type&& -Move(T&& aX) -{ - return static_cast::Type&&>(aX); -} - -/** - * These two overloads are identical to std::forward(); they are necessary until - * our stlport supports std::forward(). - */ -template -inline T&& -Forward(typename RemoveReference::Type& aX) -{ - return static_cast(aX); -} - -template -inline T&& -Forward(typename RemoveReference::Type&& aX) -{ - static_assert(!IsLvalueReference::value, - "misuse of Forward detected! try the other overload"); - return static_cast(aX); -} - -/** Swap |aX| and |aY| using move-construction if possible. */ -template -inline void -Swap(T& aX, T& aY) -{ - T tmp(Move(aX)); - aX = Move(aY); - aY = Move(tmp); -} - -} // namespace mozilla - -#endif /* mozilla_Move_h */ diff --git a/mac/include/spidermonkey/mozilla/NotNull.h b/mac/include/spidermonkey/mozilla/NotNull.h deleted file mode 100644 index 0c3c333e..00000000 --- a/mac/include/spidermonkey/mozilla/NotNull.h +++ /dev/null @@ -1,209 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_NotNull_h -#define mozilla_NotNull_h - -// It's often unclear if a particular pointer, be it raw (T*) or smart -// (RefPtr, nsCOMPtr, etc.) can be null. This leads to missing null -// checks (which can cause crashes) and unnecessary null checks (which clutter -// the code). -// -// C++ has a built-in alternative that avoids these problems: references. This -// module defines another alternative, NotNull, which can be used in cases -// where references are not suitable. -// -// In the comments below we use the word "handle" to cover all varieties of -// pointers and references. -// -// References -// ---------- -// References are always non-null. (You can do |T& r = *p;| where |p| is null, -// but that's undefined behaviour. C++ doesn't provide any built-in, ironclad -// guarantee of non-nullness.) -// -// A reference works well when you need a temporary handle to an existing -// single object, e.g. for passing a handle to a function, or as a local handle -// within another object. (In Rust parlance, this is a "borrow".) -// -// A reference is less appropriate in the following cases. -// -// - As a primary handle to an object. E.g. code such as this is possible but -// strange: |T& t = *new T(); ...; delete &t;| -// -// - As a handle to an array. It's common for |T*| to refer to either a single -// |T| or an array of |T|, but |T&| cannot refer to an array of |T| because -// you can't index off a reference (at least, not without first converting it -// to a pointer). -// -// - When the handle identity is meaningful, e.g. if you have a hashtable of -// handles, because you have to use |&| on the reference to convert it to a -// pointer. -// -// - Some people don't like using non-const references as function parameters, -// because it is not clear at the call site that the argument might be -// modified. -// -// - When you need "smart" behaviour. E.g. we lack reference equivalents to -// RefPtr and nsCOMPtr. -// -// - When interfacing with code that uses pointers a lot, sometimes using a -// reference just feels like an odd fit. -// -// Furthermore, a reference is impossible in the following cases. -// -// - When the handle is rebound to another object. References don't allow this. -// -// - When the handle has type |void|. |void&| is not allowed. -// -// NotNull is an alternative that can be used in any of the above cases except -// for the last one, where the handle type is |void|. See below. - -#include "mozilla/Assertions.h" - -namespace mozilla { - -// NotNull can be used to wrap a "base" pointer (raw or smart) to indicate it -// is not null. Some examples: -// -// - NotNull -// - NotNull> -// - NotNull> -// -// NotNull has the following notable properties. -// -// - It has zero space overhead. -// -// - It must be initialized explicitly. There is no default initialization. -// -// - It auto-converts to the base pointer type. -// -// - It does not auto-convert from a base pointer. Implicit conversion from a -// less-constrained type (e.g. T*) to a more-constrained type (e.g. -// NotNull) is dangerous. Creation and assignment from a base pointer can -// only be done with WrapNotNull(), which makes them impossible to overlook, -// both when writing and reading code. -// -// - When initialized (or assigned) it is checked, and if it is null we abort. -// This guarantees that it cannot be null. -// -// - |operator bool()| is deleted. This means you cannot check a NotNull in a -// boolean context, which eliminates the possibility of unnecessary null -// checks. -// -// NotNull currently doesn't work with UniquePtr. See -// https://github.com/Microsoft/GSL/issues/89 for some discussion. -// -template -class NotNull -{ - template friend NotNull WrapNotNull(U aBasePtr); - - T mBasePtr; - - // This constructor is only used by WrapNotNull(). - template - explicit NotNull(U aBasePtr) : mBasePtr(aBasePtr) {} - -public: - // Disallow default construction. - NotNull() = delete; - - // Construct/assign from another NotNull with a compatible base pointer type. - template - MOZ_IMPLICIT NotNull(const NotNull& aOther) : mBasePtr(aOther.get()) {} - - // Default copy/move construction and assignment. - NotNull(const NotNull&) = default; - NotNull& operator=(const NotNull&) = default; - NotNull(NotNull&&) = default; - NotNull& operator=(NotNull&&) = default; - - // Disallow null checks, which are unnecessary for this type. - explicit operator bool() const = delete; - - // Explicit conversion to a base pointer. Use only to resolve ambiguity or to - // get a castable pointer. - const T& get() const { return mBasePtr; } - - // Implicit conversion to a base pointer. Preferable to get(). - operator const T&() const { return get(); } - - // Dereference operators. - const T& operator->() const { return get(); } - decltype(*mBasePtr) operator*() const { return *mBasePtr; } -}; - -template -NotNull -WrapNotNull(const T aBasePtr) -{ - NotNull notNull(aBasePtr); - MOZ_RELEASE_ASSERT(aBasePtr); - return notNull; -} - -// Compare two NotNulls. -template -inline bool -operator==(const NotNull& aLhs, const NotNull& aRhs) -{ - return aLhs.get() == aRhs.get(); -} -template -inline bool -operator!=(const NotNull& aLhs, const NotNull& aRhs) -{ - return aLhs.get() != aRhs.get(); -} - -// Compare a NotNull to a base pointer. -template -inline bool -operator==(const NotNull& aLhs, const U& aRhs) -{ - return aLhs.get() == aRhs; -} -template -inline bool -operator!=(const NotNull& aLhs, const U& aRhs) -{ - return aLhs.get() != aRhs; -} - -// Compare a base pointer to a NotNull. -template -inline bool -operator==(const T& aLhs, const NotNull& aRhs) -{ - return aLhs == aRhs.get(); -} -template -inline bool -operator!=(const T& aLhs, const NotNull& aRhs) -{ - return aLhs != aRhs.get(); -} - -// Disallow comparing a NotNull to a nullptr. -template -bool -operator==(const NotNull&, decltype(nullptr)) = delete; -template -bool -operator!=(const NotNull&, decltype(nullptr)) = delete; - -// Disallow comparing a nullptr to a NotNull. -template -bool -operator==(decltype(nullptr), const NotNull&) = delete; -template -bool -operator!=(decltype(nullptr), const NotNull&) = delete; - -} // namespace mozilla - -#endif /* mozilla_NotNull_h */ diff --git a/mac/include/spidermonkey/mozilla/NullPtr.h b/mac/include/spidermonkey/mozilla/NullPtr.h deleted file mode 100644 index d2248f4b..00000000 --- a/mac/include/spidermonkey/mozilla/NullPtr.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements a mozilla::IsNullPointer type trait. */ - -#ifndef mozilla_NullPtr_h -#define mozilla_NullPtr_h - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/** - * IsNullPointer::value is true iff T is decltype(nullptr). - * - * Ideally this would be in TypeTraits.h, but C++11 omitted std::is_null_pointer - * (fixed in C++14), so in the interests of easing a switch to , - * this trait lives elsewhere. - */ -template -struct IsNullPointer : FalseType {}; - -template<> -struct IsNullPointer : TrueType {}; - -} // namespace mozilla - -#endif /* mozilla_NullPtr_h */ diff --git a/mac/include/spidermonkey/mozilla/Opaque.h b/mac/include/spidermonkey/mozilla/Opaque.h deleted file mode 100644 index d7239ee7..00000000 --- a/mac/include/spidermonkey/mozilla/Opaque.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* An opaque integral type supporting only comparison operators. */ - -#ifndef mozilla_Opaque_h -#define mozilla_Opaque_h - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/** - * Opaque is a replacement for integral T in cases where only comparisons - * must be supported, and it's desirable to prevent accidental dependency on - * exact values. - */ -template -class Opaque final -{ - static_assert(mozilla::IsIntegral::value, - "mozilla::Opaque only supports integral types"); - - T mValue; - -public: - Opaque() {} - explicit Opaque(T aValue) : mValue(aValue) {} - - bool operator==(const Opaque& aOther) const { - return mValue == aOther.mValue; - } - - bool operator!=(const Opaque& aOther) const { - return !(*this == aOther); - } -}; - -} // namespace mozilla - -#endif /* mozilla_Opaque_h */ diff --git a/mac/include/spidermonkey/mozilla/OperatorNewExtensions.h b/mac/include/spidermonkey/mozilla/OperatorNewExtensions.h deleted file mode 100644 index 52fd88a6..00000000 --- a/mac/include/spidermonkey/mozilla/OperatorNewExtensions.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A version of |operator new| that eschews mandatory null-checks. */ - -#ifndef mozilla_OperatorNewExtensions_h -#define mozilla_OperatorNewExtensions_h - -#include "mozilla/Assertions.h" - -// Credit goes to WebKit for this implementation, cf. -// https://bugs.webkit.org/show_bug.cgi?id=74676 -namespace mozilla { -enum NotNullTag { - KnownNotNull, -}; -} // namespace mozilla - -/* - * The logic here is a little subtle. [expr.new] states that if the allocation - * function being called returns null, then object initialization must not be - * done, and the entirety of the new expression must return null. Non-throwing - * (noexcept) functions are defined to return null to indicate failure. The - * standard placement operator new is defined in such a way, and so it requires - * a null check, even when that null check would be extraneous. Functions - * declared without such a specification are defined to throw std::bad_alloc if - * they fail, and return a non-null pointer otherwise. We compile without - * exceptions, so any placement new overload we define that doesn't declare - * itself as noexcept must therefore avoid generating a null check. Below is - * just such an overload. - * - * You might think that MOZ_NONNULL might perform the same function, but - * MOZ_NONNULL isn't supported on all of our compilers, and even when it is - * supported, doesn't work on all the versions we support. And even keeping - * those limitations in mind, we can't put MOZ_NONNULL on the global, - * standardized placement new function in any event. - * - * We deliberately don't add MOZ_NONNULL(3) to tag |p| as non-null, to benefit - * hypothetical static analyzers. Doing so makes |MOZ_ASSERT(p)|'s internal - * test vacuous, and some compilers warn about such vacuous tests. - */ -inline void* -operator new(size_t, mozilla::NotNullTag, void* p) -{ - MOZ_ASSERT(p); - return p; -} - -#endif // mozilla_OperatorNewExtensions_h diff --git a/mac/include/spidermonkey/mozilla/Pair.h b/mac/include/spidermonkey/mozilla/Pair.h deleted file mode 100644 index ad7b86a2..00000000 --- a/mac/include/spidermonkey/mozilla/Pair.h +++ /dev/null @@ -1,219 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A class holding a pair of objects that tries to conserve storage space. */ - -#ifndef mozilla_Pair_h -#define mozilla_Pair_h - -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -namespace detail { - -enum StorageType { AsBase, AsMember }; - -// Optimize storage using the Empty Base Optimization -- that empty base classes -// don't take up space -- to optimize size when one or the other class is -// stateless and can be used as a base class. -// -// The extra conditions on storage for B are necessary so that PairHelper won't -// ambiguously inherit from either A or B, such that one or the other base class -// would be inaccessible. -template::value ? detail::AsBase : detail::AsMember, - detail::StorageType = - IsEmpty::value && !IsBaseOf::value && !IsBaseOf::value - ? detail::AsBase - : detail::AsMember> -struct PairHelper; - -template -struct PairHelper -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : mFirstA(Forward(aA)), - mSecondB(Forward(aB)) - {} - - A& first() { return mFirstA; } - const A& first() const { return mFirstA; } - B& second() { return mSecondB; } - const B& second() const { return mSecondB; } - - void swap(PairHelper& aOther) - { - Swap(mFirstA, aOther.mFirstA); - Swap(mSecondB, aOther.mSecondB); - } - -private: - A mFirstA; - B mSecondB; -}; - -template -struct PairHelper : private B -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : B(Forward(aB)), - mFirstA(Forward(aA)) - {} - - A& first() { return mFirstA; } - const A& first() const { return mFirstA; } - B& second() { return *this; } - const B& second() const { return *this; } - - void swap(PairHelper& aOther) - { - Swap(mFirstA, aOther.mFirstA); - Swap(static_cast(*this), static_cast(aOther)); - } - -private: - A mFirstA; -}; - -template -struct PairHelper : private A -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : A(Forward(aA)), - mSecondB(Forward(aB)) - {} - - A& first() { return *this; } - const A& first() const { return *this; } - B& second() { return mSecondB; } - const B& second() const { return mSecondB; } - - void swap(PairHelper& aOther) - { - Swap(static_cast(*this), static_cast(aOther)); - Swap(mSecondB, aOther.mSecondB); - } - -private: - B mSecondB; -}; - -template -struct PairHelper : private A, private B -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : A(Forward(aA)), - B(Forward(aB)) - {} - - A& first() { return static_cast(*this); } - const A& first() const { return static_cast(*this); } - B& second() { return static_cast(*this); } - const B& second() const { return static_cast(*this); } - - void swap(PairHelper& aOther) - { - Swap(static_cast(*this), static_cast(aOther)); - Swap(static_cast(*this), static_cast(aOther)); - } -}; - -} // namespace detail - -/** - * Pair is the logical concatenation of an instance of A with an instance B. - * Space is conserved when possible. Neither A nor B may be a final class. - * - * It's typically clearer to have individual A and B member fields. Except if - * you want the space-conserving qualities of Pair, you're probably better off - * not using this! - * - * No guarantees are provided about the memory layout of A and B, the order of - * initialization or destruction of A and B, and so on. (This is approximately - * required to optimize space usage.) The first/second names are merely - * conceptual! - */ -template -struct Pair - : private detail::PairHelper -{ - typedef typename detail::PairHelper Base; - -public: - template - Pair(AArg&& aA, BArg&& aB) - : Base(Forward(aA), Forward(aB)) - {} - - Pair(Pair&& aOther) - : Base(Move(aOther.first()), Move(aOther.second())) - { } - - Pair(const Pair& aOther) = default; - - Pair& operator=(Pair&& aOther) - { - MOZ_ASSERT(this != &aOther, "Self-moves are prohibited"); - - first() = Move(aOther.first()); - second() = Move(aOther.second()); - - return *this; - } - - Pair& operator=(const Pair& aOther) = default; - - /** The A instance. */ - using Base::first; - /** The B instance. */ - using Base::second; - - /** Swap this pair with another pair. */ - void swap(Pair& aOther) { Base::swap(aOther); } -}; - -template -void -Swap(Pair& aX, Pair& aY) -{ - aX.swap(aY); -} - -/** - * MakePair allows you to construct a Pair instance using type inference. A call - * like this: - * - * MakePair(Foo(), Bar()) - * - * will return a Pair. - */ -template -Pair::Type>::Type, - typename RemoveCV::Type>::Type> -MakePair(A&& aA, B&& aB) -{ - return - Pair::Type>::Type, - typename RemoveCV::Type>::Type>( - Forward(aA), - Forward(aB)); -} - -} // namespace mozilla - -#endif /* mozilla_Pair_h */ diff --git a/mac/include/spidermonkey/mozilla/PodOperations.h b/mac/include/spidermonkey/mozilla/PodOperations.h deleted file mode 100644 index e6f4df21..00000000 --- a/mac/include/spidermonkey/mozilla/PodOperations.h +++ /dev/null @@ -1,196 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Operations for zeroing POD types, arrays, and so on. - * - * These operations are preferable to memset, memcmp, and the like because they - * don't require remembering to multiply by sizeof(T), array lengths, and so on - * everywhere. - */ - -#ifndef mozilla_PodOperations_h -#define mozilla_PodOperations_h - -#include "mozilla/Array.h" -#include "mozilla/ArrayUtils.h" -#include "mozilla/Attributes.h" - -#include -#include - -namespace mozilla { - -/** Set the contents of |aT| to 0. */ -template -static MOZ_ALWAYS_INLINE void -PodZero(T* aT) -{ - memset(aT, 0, sizeof(T)); -} - -/** Set the contents of |aNElem| elements starting at |aT| to 0. */ -template -static MOZ_ALWAYS_INLINE void -PodZero(T* aT, size_t aNElem) -{ - /* - * This function is often called with 'aNElem' small; we use an inline loop - * instead of calling 'memset' with a non-constant length. The compiler - * should inline the memset call with constant size, though. - */ - for (T* end = aT + aNElem; aT < end; aT++) { - memset(aT, 0, sizeof(T)); - } -} - -/* - * Arrays implicitly convert to pointers to their first element, which is - * dangerous when combined with the above PodZero definitions. Adding an - * overload for arrays is ambiguous, so we need another identifier. The - * ambiguous overload is left to catch mistaken uses of PodZero; if you get a - * compile error involving PodZero and array types, use PodArrayZero instead. - */ -template -static void PodZero(T (&aT)[N]) = delete; -template -static void PodZero(T (&aT)[N], size_t aNElem) = delete; - -/** Set the contents of the array |aT| to zero. */ -template -static MOZ_ALWAYS_INLINE void -PodArrayZero(T (&aT)[N]) -{ - memset(aT, 0, N * sizeof(T)); -} - -template -static MOZ_ALWAYS_INLINE void -PodArrayZero(Array& aArr) -{ - memset(&aArr[0], 0, N * sizeof(T)); -} - -/** - * Assign |*aSrc| to |*aDst|. The locations must not be the same and must not - * overlap. - */ -template -static MOZ_ALWAYS_INLINE void -PodAssign(T* aDst, const T* aSrc) -{ - MOZ_ASSERT(aDst + 1 <= aSrc || aSrc + 1 <= aDst, - "destination and source must not overlap"); - memcpy(reinterpret_cast(aDst), reinterpret_cast(aSrc), - sizeof(T)); -} - -/** - * Copy |aNElem| T elements from |aSrc| to |aDst|. The two memory ranges must - * not overlap! - */ -template -static MOZ_ALWAYS_INLINE void -PodCopy(T* aDst, const T* aSrc, size_t aNElem) -{ - MOZ_ASSERT(aDst + aNElem <= aSrc || aSrc + aNElem <= aDst, - "destination and source must not overlap"); - if (aNElem < 128) { - /* - * Avoid using operator= in this loop, as it may have been - * intentionally deleted by the POD type. - */ - for (const T* srcend = aSrc + aNElem; aSrc < srcend; aSrc++, aDst++) { - PodAssign(aDst, aSrc); - } - } else { - memcpy(aDst, aSrc, aNElem * sizeof(T)); - } -} - -template -static MOZ_ALWAYS_INLINE void -PodCopy(volatile T* aDst, const volatile T* aSrc, size_t aNElem) -{ - MOZ_ASSERT(aDst + aNElem <= aSrc || aSrc + aNElem <= aDst, - "destination and source must not overlap"); - - /* - * Volatile |aDst| requires extra work, because it's undefined behavior to - * modify volatile objects using the mem* functions. Just write out the - * loops manually, using operator= rather than memcpy for the same reason, - * and let the compiler optimize to the extent it can. - */ - for (const volatile T* srcend = aSrc + aNElem; - aSrc < srcend; - aSrc++, aDst++) { - *aDst = *aSrc; - } -} - -/* - * Copy the contents of the array |aSrc| into the array |aDst|, both of size N. - * The arrays must not overlap! - */ -template -static MOZ_ALWAYS_INLINE void -PodArrayCopy(T (&aDst)[N], const T (&aSrc)[N]) -{ - PodCopy(aDst, aSrc, N); -} - -/** - * Copy the memory for |aNElem| T elements from |aSrc| to |aDst|. If the two - * memory ranges overlap, then the effect is as if the |aNElem| elements are - * first copied from |aSrc| to a temporary array, and then from the temporary - * array to |aDst|. - */ -template -static MOZ_ALWAYS_INLINE void -PodMove(T* aDst, const T* aSrc, size_t aNElem) -{ - MOZ_ASSERT(aNElem <= SIZE_MAX / sizeof(T), - "trying to move an impossible number of elements"); - memmove(aDst, aSrc, aNElem * sizeof(T)); -} - -/** - * Determine whether the |len| elements at |one| are memory-identical to the - * |len| elements at |two|. - */ -template -static MOZ_ALWAYS_INLINE bool -PodEqual(const T* one, const T* two, size_t len) -{ - if (len < 128) { - const T* p1end = one + len; - const T* p1 = one; - const T* p2 = two; - for (; p1 < p1end; p1++, p2++) { - if (*p1 != *p2) { - return false; - } - } - return true; - } - - return !memcmp(one, two, len * sizeof(T)); -} - -/* - * Determine whether the |N| elements at |one| are memory-identical to the - * |N| elements at |two|. - */ -template -static MOZ_ALWAYS_INLINE bool -PodEqual(const T (&one)[N], const T (&two)[N]) -{ - return PodEqual(one, two, N); -} - -} // namespace mozilla - -#endif /* mozilla_PodOperations_h */ diff --git a/mac/include/spidermonkey/mozilla/Poison.h b/mac/include/spidermonkey/mozilla/Poison.h deleted file mode 100644 index aae56765..00000000 --- a/mac/include/spidermonkey/mozilla/Poison.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * A poison value that can be used to fill a memory space with - * an address that leads to a safe crash when dereferenced. - */ - -#ifndef mozilla_Poison_h -#define mozilla_Poison_h - -#include "mozilla/Assertions.h" -#include "mozilla/Types.h" - -#include - -MOZ_BEGIN_EXTERN_C - -extern MFBT_DATA uintptr_t gMozillaPoisonValue; - -/** - * @return the poison value. - */ -inline uintptr_t mozPoisonValue() -{ - return gMozillaPoisonValue; -} - -/** - * Overwrite the memory block of aSize bytes at aPtr with the poison value. - * aPtr MUST be aligned at a sizeof(uintptr_t) boundary. - * Only an even number of sizeof(uintptr_t) bytes are overwritten, the last - * few bytes (if any) is not overwritten. - */ -inline void mozWritePoison(void* aPtr, size_t aSize) -{ - const uintptr_t POISON = mozPoisonValue(); - char* p = (char*)aPtr; - char* limit = p + aSize; - MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); - MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); - for (; p < limit; p += sizeof(uintptr_t)) { - *((uintptr_t*)p) = POISON; - } -} - -/** - * Initialize the poison value. - * This should only be called once. - */ -extern MFBT_API void mozPoisonValueInit(); - -/* Values annotated by CrashReporter */ -extern MFBT_DATA uintptr_t gMozillaPoisonBase; -extern MFBT_DATA uintptr_t gMozillaPoisonSize; - -MOZ_END_EXTERN_C - -#if defined(__cplusplus) - -namespace mozilla { - -/** - * This class is designed to cause crashes when various kinds of memory - * corruption are observed. For instance, let's say we have a class C where we - * suspect out-of-bounds writes to some members. We can insert a member of type - * Poison near the members we suspect are being corrupted by out-of-bounds - * writes. Or perhaps we have a class K we suspect is subject to use-after-free - * violations, in which case it doesn't particularly matter where in the class - * we add the member of type Poison. - * - * In either case, we then insert calls to Check() throughout the code. Doing - * so enables us to narrow down the location where the corruption is occurring. - * A pleasant side-effect of these additional Check() calls is that crash - * signatures may become more regular, as crashes will ideally occur - * consolidated at the point of a Check(), rather than scattered about at - * various uses of the corrupted memory. - */ -class CorruptionCanary { -public: - CorruptionCanary() { - mValue = kCanarySet; - } - - ~CorruptionCanary() { - Check(); - mValue = mozPoisonValue(); - } - - void Check() const { - if (mValue != kCanarySet) { - MOZ_CRASH("Canary check failed, check lifetime"); - } - } - -private: - static const uintptr_t kCanarySet = 0x0f0b0f0b; - uintptr_t mValue; -}; - -} // mozilla - -#endif - -#endif /* mozilla_Poison_h */ diff --git a/mac/include/spidermonkey/mozilla/Range.h b/mac/include/spidermonkey/mozilla/Range.h deleted file mode 100644 index 47d91bb0..00000000 --- a/mac/include/spidermonkey/mozilla/Range.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_Range_h -#define mozilla_Range_h - -#include "mozilla/RangedPtr.h" -#include "mozilla/TypeTraits.h" - -#include - -namespace mozilla { - -// Range is a tuple containing a pointer and a length. -template -class Range -{ - const RangedPtr mStart; - const RangedPtr mEnd; - -public: - Range() : mStart(nullptr, 0), mEnd(nullptr, 0) {} - Range(T* aPtr, size_t aLength) - : mStart(aPtr, aPtr, aPtr + aLength), - mEnd(aPtr + aLength, aPtr, aPtr + aLength) - {} - Range(const RangedPtr& aStart, const RangedPtr& aEnd) - : mStart(aStart.get(), aStart.get(), aEnd.get()), - mEnd(aEnd.get(), aStart.get(), aEnd.get()) - { - // Only accept two RangedPtrs within the same range. - aStart.checkIdenticalRange(aEnd); - MOZ_ASSERT(aStart <= aEnd); - } - - template::value, - int>::Type> - MOZ_IMPLICIT Range(const Range& aOther) - : mStart(aOther.mStart), - mEnd(aOther.mEnd) - {} - - RangedPtr begin() const { return mStart; } - RangedPtr end() const { return mEnd; } - size_t length() const { return mEnd - mStart; } - - T& operator[](size_t aOffset) const { return mStart[aOffset]; } - - explicit operator bool() const { return mStart != nullptr; } -}; - -} // namespace mozilla - -#endif /* mozilla_Range_h */ diff --git a/mac/include/spidermonkey/mozilla/RangedArray.h b/mac/include/spidermonkey/mozilla/RangedArray.h deleted file mode 100644 index afe6267f..00000000 --- a/mac/include/spidermonkey/mozilla/RangedArray.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * A compile-time constant-length array, with bounds-checking assertions -- but - * unlike mozilla::Array, with indexes biased by a constant. - * - * Thus where mozilla::Array is a three-element array indexed by [0, 3), - * mozilla::RangedArray is a three-element array indexed by [8, 11). - */ - -#ifndef mozilla_RangedArray_h -#define mozilla_RangedArray_h - -#include "mozilla/Array.h" - -namespace mozilla { - -template -class RangedArray -{ -private: - typedef Array ArrayType; - ArrayType mArr; - -public: - T& operator[](size_t aIndex) - { - MOZ_ASSERT(aIndex == MinIndex || aIndex > MinIndex); - return mArr[aIndex - MinIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(aIndex == MinIndex || aIndex > MinIndex); - return mArr[aIndex - MinIndex]; - } - - typedef typename ArrayType::iterator iterator; - typedef typename ArrayType::const_iterator const_iterator; - typedef typename ArrayType::reverse_iterator reverse_iterator; - typedef typename ArrayType::const_reverse_iterator const_reverse_iterator; - - // Methods for range-based for loops. - iterator begin() { return mArr.begin(); } - const_iterator begin() const { return mArr.begin(); } - const_iterator cbegin() const { return mArr.cbegin(); } - iterator end() { return mArr.end(); } - const_iterator end() const { return mArr.end(); } - const_iterator cend() const { return mArr.cend(); } - - // Methods for reverse iterating. - reverse_iterator rbegin() { return mArr.rbegin(); } - const_reverse_iterator rbegin() const { return mArr.rbegin(); } - const_reverse_iterator crbegin() const { return mArr.crbegin(); } - reverse_iterator rend() { return mArr.rend(); } - const_reverse_iterator rend() const { return mArr.rend(); } - const_reverse_iterator crend() const { return mArr.crend(); } -}; - -} // namespace mozilla - -#endif // mozilla_RangedArray_h diff --git a/mac/include/spidermonkey/mozilla/RangedPtr.h b/mac/include/spidermonkey/mozilla/RangedPtr.h deleted file mode 100644 index a07c1f4f..00000000 --- a/mac/include/spidermonkey/mozilla/RangedPtr.h +++ /dev/null @@ -1,292 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements a smart pointer asserted to remain within a range specified at - * construction. - */ - -#ifndef mozilla_RangedPtr_h -#define mozilla_RangedPtr_h - -#include "mozilla/ArrayUtils.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#include - -namespace mozilla { - -/* - * RangedPtr is a smart pointer restricted to an address range specified at - * creation. The pointer (and any smart pointers derived from it) must remain - * within the range [start, end] (inclusive of end to facilitate use as - * sentinels). Dereferencing or indexing into the pointer (or pointers derived - * from it) must remain within the range [start, end). All the standard pointer - * operators are defined on it; in debug builds these operations assert that the - * range specified at construction is respected. - * - * In theory passing a smart pointer instance as an argument can be slightly - * slower than passing a T* (due to ABI requirements for passing structs versus - * passing pointers), if the method being called isn't inlined. If you are in - * extremely performance-critical code, you may want to be careful using this - * smart pointer as an argument type. - * - * RangedPtr intentionally does not implicitly convert to T*. Use get() to - * explicitly convert to T*. Keep in mind that the raw pointer of course won't - * implement bounds checking in debug builds. - */ -template -class RangedPtr -{ - T* mPtr; - -#ifdef DEBUG - T* const mRangeStart; - T* const mRangeEnd; -#endif - - void checkSanity() - { - MOZ_ASSERT(mRangeStart <= mPtr); - MOZ_ASSERT(mPtr <= mRangeEnd); - } - - /* Creates a new pointer for |aPtr|, restricted to this pointer's range. */ - RangedPtr create(T* aPtr) const - { -#ifdef DEBUG - return RangedPtr(aPtr, mRangeStart, mRangeEnd); -#else - return RangedPtr(aPtr, nullptr, size_t(0)); -#endif - } - - uintptr_t asUintptr() const { return reinterpret_cast(mPtr); } - -public: - RangedPtr(T* aPtr, T* aStart, T* aEnd) - : mPtr(aPtr) -#ifdef DEBUG - , mRangeStart(aStart), mRangeEnd(aEnd) -#endif - { - MOZ_ASSERT(mRangeStart <= mRangeEnd); - checkSanity(); - } - RangedPtr(T* aPtr, T* aStart, size_t aLength) - : mPtr(aPtr) -#ifdef DEBUG - , mRangeStart(aStart), mRangeEnd(aStart + aLength) -#endif - { - MOZ_ASSERT(aLength <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(reinterpret_cast(mRangeStart) + aLength * sizeof(T) >= - reinterpret_cast(mRangeStart)); - checkSanity(); - } - - /* Equivalent to RangedPtr(aPtr, aPtr, aLength). */ - RangedPtr(T* aPtr, size_t aLength) - : mPtr(aPtr) -#ifdef DEBUG - , mRangeStart(aPtr), mRangeEnd(aPtr + aLength) -#endif - { - MOZ_ASSERT(aLength <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(reinterpret_cast(mRangeStart) + aLength * sizeof(T) >= - reinterpret_cast(mRangeStart)); - checkSanity(); - } - - /* Equivalent to RangedPtr(aArr, aArr, N). */ - template - explicit RangedPtr(T (&aArr)[N]) - : mPtr(aArr) -#ifdef DEBUG - , mRangeStart(aArr), mRangeEnd(aArr + N) -#endif - { - checkSanity(); - } - - T* get() const { return mPtr; } - - explicit operator bool() const { return mPtr != nullptr; } - - void checkIdenticalRange(const RangedPtr& aOther) const - { - MOZ_ASSERT(mRangeStart == aOther.mRangeStart); - MOZ_ASSERT(mRangeEnd == aOther.mRangeEnd); - } - - /* - * You can only assign one RangedPtr into another if the two pointers have - * the same valid range: - * - * char arr1[] = "hi"; - * char arr2[] = "bye"; - * RangedPtr p1(arr1, 2); - * p1 = RangedPtr(arr1 + 1, arr1, arr1 + 2); // works - * p1 = RangedPtr(arr2, 3); // asserts - */ - RangedPtr& operator=(const RangedPtr& aOther) - { - checkIdenticalRange(aOther); - mPtr = aOther.mPtr; - checkSanity(); - return *this; - } - - RangedPtr operator+(size_t aInc) const - { - MOZ_ASSERT(aInc <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(asUintptr() + aInc * sizeof(T) >= asUintptr()); - return create(mPtr + aInc); - } - - RangedPtr operator-(size_t aDec) const - { - MOZ_ASSERT(aDec <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(asUintptr() - aDec * sizeof(T) <= asUintptr()); - return create(mPtr - aDec); - } - - /* - * You can assign a raw pointer into a RangedPtr if the raw pointer is - * within the range specified at creation. - */ - template - RangedPtr& operator=(U* aPtr) - { - *this = create(aPtr); - return *this; - } - - template - RangedPtr& operator=(const RangedPtr& aPtr) - { - MOZ_ASSERT(mRangeStart <= aPtr.mPtr); - MOZ_ASSERT(aPtr.mPtr <= mRangeEnd); - mPtr = aPtr.mPtr; - checkSanity(); - return *this; - } - - RangedPtr& operator++() - { - return (*this += 1); - } - - RangedPtr operator++(int) - { - RangedPtr rcp = *this; - ++*this; - return rcp; - } - - RangedPtr& operator--() - { - return (*this -= 1); - } - - RangedPtr operator--(int) - { - RangedPtr rcp = *this; - --*this; - return rcp; - } - - RangedPtr& operator+=(size_t aInc) - { - *this = *this + aInc; - return *this; - } - - RangedPtr& operator-=(size_t aDec) - { - *this = *this - aDec; - return *this; - } - - T& operator[](int aIndex) const - { - MOZ_ASSERT(size_t(aIndex > 0 ? aIndex : -aIndex) <= size_t(-1) / sizeof(T)); - return *create(mPtr + aIndex); - } - - T& operator*() const - { - MOZ_ASSERT(mPtr >= mRangeStart); - MOZ_ASSERT(mPtr < mRangeEnd); - return *mPtr; - } - - T* operator->() const - { - MOZ_ASSERT(mPtr >= mRangeStart); - MOZ_ASSERT(mPtr < mRangeEnd); - return mPtr; - } - - template - bool operator==(const RangedPtr& aOther) const - { - return mPtr == aOther.mPtr; - } - template - bool operator!=(const RangedPtr& aOther) const - { - return !(*this == aOther); - } - - template - bool operator==(const U* u) const - { - return mPtr == u; - } - template - bool operator!=(const U* u) const - { - return !(*this == u); - } - - template - bool operator<(const RangedPtr& aOther) const - { - return mPtr < aOther.mPtr; - } - template - bool operator<=(const RangedPtr& aOther) const - { - return mPtr <= aOther.mPtr; - } - - template - bool operator>(const RangedPtr& aOther) const - { - return mPtr > aOther.mPtr; - } - template - bool operator>=(const RangedPtr& aOther) const - { - return mPtr >= aOther.mPtr; - } - - size_t operator-(const RangedPtr& aOther) const - { - MOZ_ASSERT(mPtr >= aOther.mPtr); - return PointerRangeSize(aOther.mPtr, mPtr); - } - -private: - RangedPtr() = delete; - T* operator&() = delete; -}; - -} /* namespace mozilla */ - -#endif /* mozilla_RangedPtr_h */ diff --git a/mac/include/spidermonkey/mozilla/ReentrancyGuard.h b/mac/include/spidermonkey/mozilla/ReentrancyGuard.h deleted file mode 100644 index 9963974e..00000000 --- a/mac/include/spidermonkey/mozilla/ReentrancyGuard.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Small helper class for asserting uses of a class are non-reentrant. */ - -#ifndef mozilla_ReentrancyGuard_h -#define mozilla_ReentrancyGuard_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/GuardObjects.h" - -namespace mozilla { - -/* Useful for implementing containers that assert non-reentrancy */ -class MOZ_RAII ReentrancyGuard -{ - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -#ifdef DEBUG - bool& mEntered; -#endif - -public: - template -#ifdef DEBUG - explicit ReentrancyGuard(T& aObj - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mEntered(aObj.mEntered) -#else - explicit ReentrancyGuard(T& - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) -#endif - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; -#ifdef DEBUG - MOZ_ASSERT(!mEntered); - mEntered = true; -#endif - } - ~ReentrancyGuard() - { -#ifdef DEBUG - mEntered = false; -#endif - } - -private: - ReentrancyGuard(const ReentrancyGuard&) = delete; - void operator=(const ReentrancyGuard&) = delete; -}; - -} // namespace mozilla - -#endif /* mozilla_ReentrancyGuard_h */ diff --git a/mac/include/spidermonkey/mozilla/RefCountType.h b/mac/include/spidermonkey/mozilla/RefCountType.h deleted file mode 100644 index e95a22a0..00000000 --- a/mac/include/spidermonkey/mozilla/RefCountType.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_RefCountType_h -#define mozilla_RefCountType_h - -#include - -/** - * MozRefCountType is Mozilla's reference count type. - * - * We use the same type to represent the refcount of RefCounted objects - * as well, in order to be able to use the leak detection facilities - * that are implemented by XPCOM. - * - * Note that this type is not in the mozilla namespace so that it is - * usable for both C and C++ code. - */ -typedef uintptr_t MozRefCountType; - -/* - * This is the return type for AddRef() and Release() in nsISupports. - * IUnknown of COM returns an unsigned long from equivalent functions. - * - * The following ifdef exists to maintain binary compatibility with - * IUnknown, the base interface in Microsoft COM. - */ -#ifdef XP_WIN -typedef unsigned long MozExternalRefCountType; -#else -typedef uint32_t MozExternalRefCountType; -#endif - -#endif diff --git a/mac/include/spidermonkey/mozilla/RefCounted.h b/mac/include/spidermonkey/mozilla/RefCounted.h deleted file mode 100644 index ae05f1e0..00000000 --- a/mac/include/spidermonkey/mozilla/RefCounted.h +++ /dev/null @@ -1,210 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* CRTP refcounting templates. Do not use unless you are an Expert. */ - -#ifndef mozilla_RefCounted_h -#define mozilla_RefCounted_h - -#include "mozilla/AlreadyAddRefed.h" -#include "mozilla/Assertions.h" -#include "mozilla/Atomics.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/RefCountType.h" -#include "mozilla/TypeTraits.h" - -#if defined(MOZILLA_INTERNAL_API) -#include "nsXPCOM.h" -#endif - -#if defined(MOZILLA_INTERNAL_API) && \ - (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING)) -#define MOZ_REFCOUNTED_LEAK_CHECKING -#endif - -namespace mozilla { - -/** - * RefCounted is a sort of a "mixin" for a class T. RefCounted - * manages, well, refcounting for T, and because RefCounted is - * parameterized on T, RefCounted can call T's destructor directly. - * This means T doesn't need to have a virtual dtor and so doesn't - * need a vtable. - * - * RefCounted is created with refcount == 0. Newly-allocated - * RefCounted must immediately be assigned to a RefPtr to make the - * refcount > 0. It's an error to allocate and free a bare - * RefCounted, i.e. outside of the RefPtr machinery. Attempts to - * do so will abort DEBUG builds. - * - * Live RefCounted have refcount > 0. The lifetime (refcounts) of - * live RefCounted are controlled by RefPtr and - * RefPtr. Upon a transition from refcounted==1 - * to 0, the RefCounted "dies" and is destroyed. The "destroyed" - * state is represented in DEBUG builds by refcount==0xffffdead. This - * state distinguishes use-before-ref (refcount==0) from - * use-after-destroy (refcount==0xffffdead). - * - * Note that when deriving from RefCounted or AtomicRefCounted, you - * should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public - * section of your class, where ClassName is the name of your class. - */ -namespace detail { -const MozRefCountType DEAD = 0xffffdead; - -// When building code that gets compiled into Gecko, try to use the -// trace-refcount leak logging facilities. -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING -class RefCountLogger -{ -public: - static void logAddRef(const void* aPointer, MozRefCountType aRefCount, - const char* aTypeName, uint32_t aInstanceSize) - { - MOZ_ASSERT(aRefCount != DEAD); - NS_LogAddRef(const_cast(aPointer), aRefCount, aTypeName, - aInstanceSize); - } - - static void logRelease(const void* aPointer, MozRefCountType aRefCount, - const char* aTypeName) - { - MOZ_ASSERT(aRefCount != DEAD); - NS_LogRelease(const_cast(aPointer), aRefCount, aTypeName); - } -}; -#endif - -// This is used WeakPtr.h as well as this file. -enum RefCountAtomicity -{ - AtomicRefCount, - NonAtomicRefCount -}; - -template -class RefCounted -{ -protected: - RefCounted() : mRefCnt(0) {} - ~RefCounted() { MOZ_ASSERT(mRefCnt == detail::DEAD); } - -public: - // Compatibility with nsRefPtr. - void AddRef() const - { - // Note: this method must be thread safe for AtomicRefCounted. - MOZ_ASSERT(int32_t(mRefCnt) >= 0); -#ifndef MOZ_REFCOUNTED_LEAK_CHECKING - ++mRefCnt; -#else - const char* type = static_cast(this)->typeName(); - uint32_t size = static_cast(this)->typeSize(); - const void* ptr = static_cast(this); - MozRefCountType cnt = ++mRefCnt; - detail::RefCountLogger::logAddRef(ptr, cnt, type, size); -#endif - } - - void Release() const - { - // Note: this method must be thread safe for AtomicRefCounted. - MOZ_ASSERT(int32_t(mRefCnt) > 0); -#ifndef MOZ_REFCOUNTED_LEAK_CHECKING - MozRefCountType cnt = --mRefCnt; -#else - const char* type = static_cast(this)->typeName(); - const void* ptr = static_cast(this); - MozRefCountType cnt = --mRefCnt; - // Note: it's not safe to touch |this| after decrementing the refcount, - // except for below. - detail::RefCountLogger::logRelease(ptr, cnt, type); -#endif - if (0 == cnt) { - // Because we have atomically decremented the refcount above, only - // one thread can get a 0 count here, so as long as we can assume that - // everything else in the system is accessing this object through - // RefPtrs, it's safe to access |this| here. -#ifdef DEBUG - mRefCnt = detail::DEAD; -#endif - delete static_cast(this); - } - } - - // Compatibility with wtf::RefPtr. - void ref() { AddRef(); } - void deref() { Release(); } - MozRefCountType refCount() const { return mRefCnt; } - bool hasOneRef() const - { - MOZ_ASSERT(mRefCnt > 0); - return mRefCnt == 1; - } - -private: - mutable typename Conditional, - MozRefCountType>::Type mRefCnt; -}; - -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING -// Passing override for the optional argument marks the typeName and -// typeSize functions defined by this macro as overrides. -#define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \ - virtual const char* typeName() const __VA_ARGS__ { return #T; } \ - virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); } -#else -#define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) -#endif - -// Note that this macro is expanded unconditionally because it declares only -// two small inline functions which will hopefully get eliminated by the linker -// in non-leak-checking builds. -#define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \ - const char* typeName() const { return #T; } \ - size_t typeSize() const { return sizeof(*this); } - -} // namespace detail - -template -class RefCounted : public detail::RefCounted -{ -public: - ~RefCounted() - { - static_assert(IsBaseOf::value, - "T must derive from RefCounted"); - } -}; - -namespace external { - -/** - * AtomicRefCounted is like RefCounted, with an atomically updated - * reference counter. - * - * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING - * instead. - */ -template -class AtomicRefCounted : - public mozilla::detail::RefCounted -{ -public: - ~AtomicRefCounted() - { - static_assert(IsBaseOf::value, - "T must derive from AtomicRefCounted"); - } -}; - -} // namespace external - -} // namespace mozilla - -#endif // mozilla_RefCounted_h diff --git a/mac/include/spidermonkey/mozilla/RefPtr.h b/mac/include/spidermonkey/mozilla/RefPtr.h deleted file mode 100644 index bfa8f6e0..00000000 --- a/mac/include/spidermonkey/mozilla/RefPtr.h +++ /dev/null @@ -1,656 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_RefPtr_h -#define mozilla_RefPtr_h - -#include "mozilla/AlreadyAddRefed.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -/*****************************************************************************/ - -// template class RefPtrGetterAddRefs; - -class nsCOMPtr_helper; - -namespace mozilla { -template class OwningNonNull; -template class StaticRefPtr; - -// Traditionally, RefPtr supports automatic refcounting of any pointer type -// with AddRef() and Release() methods that follow the traditional semantics. -// -// This traits class can be specialized to operate on other pointer types. For -// example, we specialize this trait for opaque FFI types that represent -// refcounted objects in Rust. -// -// Given the use of ConstRemovingRefPtrTraits below, U should not be a const- -// qualified type. -template -struct RefPtrTraits -{ - static void AddRef(U* aPtr) { - aPtr->AddRef(); - } - static void Release(U* aPtr) { - aPtr->Release(); - } -}; - -} // namespace mozilla - -template -class RefPtr -{ -private: - void - assign_with_AddRef(T* aRawPtr) - { - if (aRawPtr) { - ConstRemovingRefPtrTraits::AddRef(aRawPtr); - } - assign_assuming_AddRef(aRawPtr); - } - - void - assign_assuming_AddRef(T* aNewPtr) - { - T* oldPtr = mRawPtr; - mRawPtr = aNewPtr; - if (oldPtr) { - ConstRemovingRefPtrTraits::Release(oldPtr); - } - } - -private: - T* MOZ_OWNING_REF mRawPtr; - -public: - typedef T element_type; - - ~RefPtr() - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::Release(mRawPtr); - } - } - - // Constructors - - RefPtr() - : mRawPtr(nullptr) - // default constructor - { - } - - RefPtr(const RefPtr& aSmartPtr) - : mRawPtr(aSmartPtr.mRawPtr) - // copy-constructor - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::AddRef(mRawPtr); - } - } - - RefPtr(RefPtr&& aRefPtr) - : mRawPtr(aRefPtr.mRawPtr) - { - aRefPtr.mRawPtr = nullptr; - } - - // construct from a raw pointer (of the right type) - - MOZ_IMPLICIT RefPtr(T* aRawPtr) - : mRawPtr(aRawPtr) - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::AddRef(mRawPtr); - } - } - - MOZ_IMPLICIT RefPtr(decltype(nullptr)) - : mRawPtr(nullptr) - { - } - - template - MOZ_IMPLICIT RefPtr(already_AddRefed& aSmartPtr) - : mRawPtr(aSmartPtr.take()) - // construct from |already_AddRefed| - { - } - - template - MOZ_IMPLICIT RefPtr(already_AddRefed&& aSmartPtr) - : mRawPtr(aSmartPtr.take()) - // construct from |otherRefPtr.forget()| - { - } - - template - MOZ_IMPLICIT RefPtr(const RefPtr& aSmartPtr) - : mRawPtr(aSmartPtr.get()) - // copy-construct from a smart pointer with a related pointer type - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::AddRef(mRawPtr); - } - } - - template - MOZ_IMPLICIT RefPtr(RefPtr&& aSmartPtr) - : mRawPtr(aSmartPtr.forget().take()) - // construct from |Move(RefPtr)|. - { - } - - MOZ_IMPLICIT RefPtr(const nsCOMPtr_helper& aHelper); - - // Defined in OwningNonNull.h - template - MOZ_IMPLICIT RefPtr(const mozilla::OwningNonNull& aOther); - - // Defined in StaticPtr.h - template - MOZ_IMPLICIT RefPtr(const mozilla::StaticRefPtr& aOther); - - // Assignment operators - - RefPtr& - operator=(decltype(nullptr)) - { - assign_assuming_AddRef(nullptr); - return *this; - } - - RefPtr& - operator=(const RefPtr& aRhs) - // copy assignment operator - { - assign_with_AddRef(aRhs.mRawPtr); - return *this; - } - - template - RefPtr& - operator=(const RefPtr& aRhs) - // assign from an RefPtr of a related pointer type - { - assign_with_AddRef(aRhs.get()); - return *this; - } - - RefPtr& - operator=(T* aRhs) - // assign from a raw pointer (of the right type) - { - assign_with_AddRef(aRhs); - return *this; - } - - template - RefPtr& - operator=(already_AddRefed& aRhs) - // assign from |already_AddRefed| - { - assign_assuming_AddRef(aRhs.take()); - return *this; - } - - template - RefPtr& - operator=(already_AddRefed && aRhs) - // assign from |otherRefPtr.forget()| - { - assign_assuming_AddRef(aRhs.take()); - return *this; - } - - RefPtr& operator=(const nsCOMPtr_helper& aHelper); - - RefPtr& - operator=(RefPtr && aRefPtr) - { - assign_assuming_AddRef(aRefPtr.mRawPtr); - aRefPtr.mRawPtr = nullptr; - return *this; - } - - // Defined in OwningNonNull.h - template - RefPtr& - operator=(const mozilla::OwningNonNull& aOther); - - // Defined in StaticPtr.h - template - RefPtr& - operator=(const mozilla::StaticRefPtr& aOther); - - // Other pointer operators - - void - swap(RefPtr& aRhs) - // ...exchange ownership with |aRhs|; can save a pair of refcount operations - { - T* temp = aRhs.mRawPtr; - aRhs.mRawPtr = mRawPtr; - mRawPtr = temp; - } - - void - swap(T*& aRhs) - // ...exchange ownership with |aRhs|; can save a pair of refcount operations - { - T* temp = aRhs; - aRhs = mRawPtr; - mRawPtr = temp; - } - - already_AddRefed - forget() - // return the value of mRawPtr and null out mRawPtr. Useful for - // already_AddRefed return values. - { - T* temp = nullptr; - swap(temp); - return already_AddRefed(temp); - } - - template - void - forget(I** aRhs) - // Set the target of aRhs to the value of mRawPtr and null out mRawPtr. - // Useful to avoid unnecessary AddRef/Release pairs with "out" - // parameters where aRhs bay be a T** or an I** where I is a base class - // of T. - { - MOZ_ASSERT(aRhs, "Null pointer passed to forget!"); - *aRhs = mRawPtr; - mRawPtr = nullptr; - } - - T* - get() const - /* - Prefer the implicit conversion provided automatically by |operator T*() const|. - Use |get()| to resolve ambiguity or to get a castable pointer. - */ - { - return const_cast(mRawPtr); - } - - operator T*() const -#ifdef MOZ_HAVE_REF_QUALIFIERS - & -#endif - /* - ...makes an |RefPtr| act like its underlying raw pointer type whenever it - is used in a context where a raw pointer is expected. It is this operator - that makes an |RefPtr| substitutable for a raw pointer. - - Prefer the implicit use of this operator to calling |get()|, except where - necessary to resolve ambiguity. - */ - { - return get(); - } - -#ifdef MOZ_HAVE_REF_QUALIFIERS - // Don't allow implicit conversion of temporary RefPtr to raw pointer, - // because the refcount might be one and the pointer will immediately become - // invalid. - operator T*() const && = delete; - - // These are needed to avoid the deleted operator above. XXX Why is operator! - // needed separately? Shouldn't the compiler prefer using the non-deleted - // operator bool instead of the deleted operator T*? - explicit operator bool() const { return !!mRawPtr; } - bool operator!() const { return !mRawPtr; } -#endif - - T* - operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN - { - MOZ_ASSERT(mRawPtr != nullptr, - "You can't dereference a NULL RefPtr with operator->()."); - return get(); - } - - template - class Proxy - { - typedef R (T::*member_function)(Args...); - T* mRawPtr; - member_function mFunction; - public: - Proxy(T* aRawPtr, member_function aFunction) - : mRawPtr(aRawPtr), - mFunction(aFunction) - { - } - template - R operator()(ActualArgs&&... aArgs) - { - return ((*mRawPtr).*mFunction)(mozilla::Forward(aArgs)...); - } - }; - - template - Proxy operator->*(R (T::*aFptr)(Args...)) const - { - MOZ_ASSERT(mRawPtr != nullptr, - "You can't dereference a NULL RefPtr with operator->*()."); - return Proxy(get(), aFptr); - } - - RefPtr* - get_address() - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } - - const RefPtr* - get_address() const - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } - -public: - T& - operator*() const - { - MOZ_ASSERT(mRawPtr != nullptr, - "You can't dereference a NULL RefPtr with operator*()."); - return *get(); - } - - T** - StartAssignment() - { - assign_assuming_AddRef(nullptr); - return reinterpret_cast(&mRawPtr); - } -private: - // This helper class makes |RefPtr| possible by casting away - // the constness from the pointer when calling AddRef() and Release(). - // - // This is necessary because AddRef() and Release() implementations can't - // generally expected to be const themselves (without heavy use of |mutable| - // and |const_cast| in their own implementations). - // - // This should be sound because while |RefPtr| provides a - // const view of an object, the object itself should not be const (it - // would have to be allocated as |new const T| or similar to be const). - template - struct ConstRemovingRefPtrTraits - { - static void AddRef(U* aPtr) { - mozilla::RefPtrTraits::AddRef(aPtr); - } - static void Release(U* aPtr) { - mozilla::RefPtrTraits::Release(aPtr); - } - }; - template - struct ConstRemovingRefPtrTraits - { - static void AddRef(const U* aPtr) { - mozilla::RefPtrTraits::AddRef(const_cast(aPtr)); - } - static void Release(const U* aPtr) { - mozilla::RefPtrTraits::Release(const_cast(aPtr)); - } - }; -}; - -class nsCycleCollectionTraversalCallback; -template -void -CycleCollectionNoteChild(nsCycleCollectionTraversalCallback& aCallback, - T* aChild, const char* aName, uint32_t aFlags); - -template -inline void -ImplCycleCollectionUnlink(RefPtr& aField) -{ - aField = nullptr; -} - -template -inline void -ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback, - RefPtr& aField, - const char* aName, - uint32_t aFlags = 0) -{ - CycleCollectionNoteChild(aCallback, aField.get(), aName, aFlags); -} - -template -inline RefPtr* -address_of(RefPtr& aPtr) -{ - return aPtr.get_address(); -} - -template -inline const RefPtr* -address_of(const RefPtr& aPtr) -{ - return aPtr.get_address(); -} - -template -class RefPtrGetterAddRefs -/* - ... - - This class is designed to be used for anonymous temporary objects in the - argument list of calls that return COM interface pointers, e.g., - - RefPtr fooP; - ...->GetAddRefedPointer(getter_AddRefs(fooP)) - - DO NOT USE THIS TYPE DIRECTLY IN YOUR CODE. Use |getter_AddRefs()| instead. - - When initialized with a |RefPtr|, as in the example above, it returns - a |void**|, a |T**|, or an |nsISupports**| as needed, that the - outer call (|GetAddRefedPointer| in this case) can fill in. - - This type should be a nested class inside |RefPtr|. -*/ -{ -public: - explicit - RefPtrGetterAddRefs(RefPtr& aSmartPtr) - : mTargetSmartPtr(aSmartPtr) - { - // nothing else to do - } - - operator void**() - { - return reinterpret_cast(mTargetSmartPtr.StartAssignment()); - } - - operator T**() - { - return mTargetSmartPtr.StartAssignment(); - } - - T*& - operator*() - { - return *(mTargetSmartPtr.StartAssignment()); - } - -private: - RefPtr& mTargetSmartPtr; -}; - -template -inline RefPtrGetterAddRefs -getter_AddRefs(RefPtr& aSmartPtr) -/* - Used around a |RefPtr| when - ...makes the class |RefPtrGetterAddRefs| invisible. -*/ -{ - return RefPtrGetterAddRefs(aSmartPtr); -} - - -// Comparing two |RefPtr|s - -template -inline bool -operator==(const RefPtr& aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs.get()) == static_cast(aRhs.get()); -} - - -template -inline bool -operator!=(const RefPtr& aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs.get()) != static_cast(aRhs.get()); -} - - -// Comparing an |RefPtr| to a raw pointer - -template -inline bool -operator==(const RefPtr& aLhs, const U* aRhs) -{ - return static_cast(aLhs.get()) == static_cast(aRhs); -} - -template -inline bool -operator==(const U* aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs) == static_cast(aRhs.get()); -} - -template -inline bool -operator!=(const RefPtr& aLhs, const U* aRhs) -{ - return static_cast(aLhs.get()) != static_cast(aRhs); -} - -template -inline bool -operator!=(const U* aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs) != static_cast(aRhs.get()); -} - -template -inline bool -operator==(const RefPtr& aLhs, U* aRhs) -{ - return static_cast(aLhs.get()) == const_cast(aRhs); -} - -template -inline bool -operator==(U* aLhs, const RefPtr& aRhs) -{ - return const_cast(aLhs) == static_cast(aRhs.get()); -} - -template -inline bool -operator!=(const RefPtr& aLhs, U* aRhs) -{ - return static_cast(aLhs.get()) != const_cast(aRhs); -} - -template -inline bool -operator!=(U* aLhs, const RefPtr& aRhs) -{ - return const_cast(aLhs) != static_cast(aRhs.get()); -} - -// Comparing an |RefPtr| to |nullptr| - -template -inline bool -operator==(const RefPtr& aLhs, decltype(nullptr)) -{ - return aLhs.get() == nullptr; -} - -template -inline bool -operator==(decltype(nullptr), const RefPtr& aRhs) -{ - return nullptr == aRhs.get(); -} - -template -inline bool -operator!=(const RefPtr& aLhs, decltype(nullptr)) -{ - return aLhs.get() != nullptr; -} - -template -inline bool -operator!=(decltype(nullptr), const RefPtr& aRhs) -{ - return nullptr != aRhs.get(); -} - -/*****************************************************************************/ - -template -inline already_AddRefed -do_AddRef(T* aObj) -{ - RefPtr ref(aObj); - return ref.forget(); -} - -template -inline already_AddRefed -do_AddRef(const RefPtr& aObj) -{ - RefPtr ref(aObj); - return ref.forget(); -} - -namespace mozilla { - -/** - * Helper function to be able to conveniently write things like: - * - * already_AddRefed - * f(...) - * { - * return MakeAndAddRef(...); - * } - */ -template -already_AddRefed -MakeAndAddRef(Args&&... aArgs) -{ - RefPtr p(new T(Forward(aArgs)...)); - return p.forget(); -} - -} // namespace mozilla - -#endif /* mozilla_RefPtr_h */ diff --git a/mac/include/spidermonkey/mozilla/ReverseIterator.h b/mac/include/spidermonkey/mozilla/ReverseIterator.h deleted file mode 100644 index 49c2e279..00000000 --- a/mac/include/spidermonkey/mozilla/ReverseIterator.h +++ /dev/null @@ -1,168 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* An iterator that acts like another iterator, but iterating in - * the negative direction. (Note that not all iterators can iterate - * in the negative direction.) */ - -#ifndef mozilla_ReverseIterator_h -#define mozilla_ReverseIterator_h - -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -template -class ReverseIterator -{ -public: - template - explicit ReverseIterator(Iterator aIter) - : mCurrent(aIter) { } - - template - MOZ_IMPLICIT ReverseIterator(const ReverseIterator& aOther) - : mCurrent(aOther.mCurrent) { } - - decltype(*DeclVal()) operator*() const - { - IteratorT tmp = mCurrent; - return *--tmp; - } - - /* Increments and decrements operators */ - - ReverseIterator& operator++() { --mCurrent; return *this; } - ReverseIterator& operator--() { ++mCurrent; return *this; } - ReverseIterator operator++(int) { auto ret = *this; mCurrent--; return ret; } - ReverseIterator operator--(int) { auto ret = *this; mCurrent++; return ret; } - - /* Comparison operators */ - - template - friend bool operator==(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator!=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator<(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator<=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator>(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator>=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - -private: - IteratorT mCurrent; -}; - -template -bool -operator==(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent == aIter2.mCurrent; -} - -template -bool -operator!=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent != aIter2.mCurrent; -} - -template -bool -operator<(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent > aIter2.mCurrent; -} - -template -bool -operator<=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent >= aIter2.mCurrent; -} - -template -bool -operator>(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent < aIter2.mCurrent; -} - -template -bool -operator>=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent <= aIter2.mCurrent; -} - -namespace detail { - -template -class IteratorRange -{ -public: - typedef IteratorT iterator; - typedef IteratorT const_iterator; - typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; - - template - MOZ_IMPLICIT IteratorRange(Iterator1 aIterBegin, Iterator2 aIterEnd) - : mIterBegin(aIterBegin), mIterEnd(aIterEnd) { } - - template - MOZ_IMPLICIT IteratorRange(const IteratorRange& aOther) - : mIterBegin(aOther.mIterBegin), mIterEnd(aOther.mIterEnd) { } - - iterator begin() const { return mIterBegin; } - const_iterator cbegin() const { return begin(); } - iterator end() const { return mIterEnd; } - const_iterator cend() const { return end(); } - reverse_iterator rbegin() const { return reverse_iterator(mIterEnd); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() const { return reverse_iterator(mIterBegin); } - const_reverse_iterator crend() const { return rend(); } - -private: - IteratorT mIterBegin; - IteratorT mIterEnd; -}; - -} // namespace detail - -template -detail::IteratorRange -Reversed(Range& aRange) -{ - return {aRange.rbegin(), aRange.rend()}; -} - -template -detail::IteratorRange -Reversed(const Range& aRange) -{ - return {aRange.rbegin(), aRange.rend()}; -} - -} // namespace mozilla - -#endif // mozilla_ReverseIterator_h diff --git a/mac/include/spidermonkey/mozilla/RollingMean.h b/mac/include/spidermonkey/mozilla/RollingMean.h deleted file mode 100644 index 8cc3148e..00000000 --- a/mac/include/spidermonkey/mozilla/RollingMean.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A set abstraction for enumeration values. */ - -#ifndef mozilla_RollingMean_h_ -#define mozilla_RollingMean_h_ - -#include "mozilla/Assertions.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Vector.h" - -#include - -namespace mozilla { - -/** - * RollingMean calculates a rolling mean of the values it is given. It - * accumulates the total as values are added and removed. The second type - * argument S specifies the type of the total. This may need to be a bigger - * type in order to maintain that the sum of all values in the average doesn't - * exceed the maximum input value. - * - * WARNING: Float types are not supported due to rounding errors. - */ -template -class RollingMean -{ -private: - size_t mInsertIndex; - size_t mMaxValues; - Vector mValues; - S mTotal; - -public: - static_assert(!IsFloatingPoint::value, - "floating-point types are unsupported due to rounding " - "errors"); - - explicit RollingMean(size_t aMaxValues) - : mInsertIndex(0), - mMaxValues(aMaxValues), - mTotal(0) - { - MOZ_ASSERT(aMaxValues > 0); - } - - RollingMean& operator=(RollingMean&& aOther) - { - MOZ_ASSERT(this != &aOther, "self-assignment is forbidden"); - this->~RollingMean(); - new(this) RollingMean(aOther.mMaxValues); - mInsertIndex = aOther.mInsertIndex; - mTotal = aOther.mTotal; - mValues.swap(aOther.mValues); - return *this; - } - - /** - * Insert a value into the rolling mean. - */ - bool insert(T aValue) - { - MOZ_ASSERT(mValues.length() <= mMaxValues); - - if (mValues.length() == mMaxValues) { - mTotal = mTotal - mValues[mInsertIndex] + aValue; - mValues[mInsertIndex] = aValue; - } else { - if (!mValues.append(aValue)) { - return false; - } - mTotal = mTotal + aValue; - } - - mInsertIndex = (mInsertIndex + 1) % mMaxValues; - return true; - } - - /** - * Calculate the rolling mean. - */ - T mean() - { - MOZ_ASSERT(!empty()); - return T(mTotal / int64_t(mValues.length())); - } - - bool empty() - { - return mValues.empty(); - } - - /** - * Remove all values from the rolling mean. - */ - void clear() - { - mValues.clear(); - mInsertIndex = 0; - mTotal = T(0); - } - - size_t maxValues() - { - return mMaxValues; - } -}; - -} // namespace mozilla - -#endif // mozilla_RollingMean_h_ diff --git a/mac/include/spidermonkey/mozilla/SHA1.h b/mac/include/spidermonkey/mozilla/SHA1.h deleted file mode 100644 index ddccaa67..00000000 --- a/mac/include/spidermonkey/mozilla/SHA1.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Simple class for computing SHA1. */ - -#ifndef mozilla_SHA1_h -#define mozilla_SHA1_h - -#include "mozilla/Types.h" - -#include -#include - -namespace mozilla { - -/** - * This class computes the SHA1 hash of a byte sequence, or of the concatenation - * of multiple sequences. For example, computing the SHA1 of two sequences of - * bytes could be done as follows: - * - * void SHA1(const uint8_t* buf1, uint32_t size1, - * const uint8_t* buf2, uint32_t size2, - * SHA1Sum::Hash& hash) - * { - * SHA1Sum s; - * s.update(buf1, size1); - * s.update(buf2, size2); - * s.finish(hash); - * } - * - * The finish method may only be called once and cannot be followed by calls - * to update. - */ -class SHA1Sum -{ - union - { - uint32_t mW[16]; /* input buffer */ - uint8_t mB[64]; - } mU; - uint64_t mSize; /* count of hashed bytes. */ - unsigned mH[22]; /* 5 state variables, 16 tmp values, 1 extra */ - bool mDone; - -public: - MFBT_API SHA1Sum(); - - static const size_t kHashSize = 20; - typedef uint8_t Hash[kHashSize]; - - /* Add len bytes of dataIn to the data sequence being hashed. */ - MFBT_API void update(const void* aData, uint32_t aLength); - - /* Compute the final hash of all data into hashOut. */ - MFBT_API void finish(SHA1Sum::Hash& aHashOut); -}; - -} /* namespace mozilla */ - -#endif /* mozilla_SHA1_h */ diff --git a/mac/include/spidermonkey/mozilla/Saturate.h b/mac/include/spidermonkey/mozilla/Saturate.h deleted file mode 100644 index b79364d2..00000000 --- a/mac/include/spidermonkey/mozilla/Saturate.h +++ /dev/null @@ -1,288 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Provides saturation arithmetics for scalar types. */ - -#ifndef mozilla_Saturate_h -#define mozilla_Saturate_h - -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include - -namespace mozilla { -namespace detail { - -/** - * |SaturateOp| wraps scalar values for saturation arithmetics. Usage: - * - * uint32_t value = 1; - * - * ++SaturateOp(value); // value is 2 - * --SaturateOp(value); // value is 1 - * --SaturateOp(value); // value is 0 - * --SaturateOp(value); // value is still 0 - * - * Please add new operators when required. - * - * |SaturateOp| will saturate at the minimum and maximum values of - * type T. If you need other bounds, implement a clamped-type class and - * specialize the type traits accordingly. - */ -template -class SaturateOp -{ -public: - explicit SaturateOp(T& aValue) - : mValue(aValue) - { - // We should actually check for |std::is_scalar::value| to be - // true, but this type trait is not available everywhere. Relax - // this assertion if you want to use floating point values as well. - static_assert(IsIntegral::value, - "Integral type required in instantiation"); - } - - // Add and subtract operators - - T operator+(const T& aRhs) const - { - return T(mValue) += aRhs; - } - - T operator-(const T& aRhs) const - { - return T(mValue) -= aRhs; - } - - // Compound operators - - const T& operator+=(const T& aRhs) const - { - const T min = std::numeric_limits::min(); - const T max = std::numeric_limits::max(); - - if (aRhs > static_cast(0)) { - mValue = (max - aRhs) < mValue ? max : mValue + aRhs; - } else { - mValue = (min - aRhs) > mValue ? min : mValue + aRhs; - } - return mValue; - } - - const T& operator-=(const T& aRhs) const - { - const T min = std::numeric_limits::min(); - const T max = std::numeric_limits::max(); - - if (aRhs > static_cast(0)) { - mValue = (min + aRhs) > mValue ? min : mValue - aRhs; - } else { - mValue = (max + aRhs) < mValue ? max : mValue - aRhs; - } - return mValue; - } - - // Increment and decrement operators - - const T& operator++() const // prefix - { - return operator+=(static_cast(1)); - } - - T operator++(int) const // postfix - { - const T value(mValue); - operator++(); - return value; - } - - const T& operator--() const // prefix - { - return operator-=(static_cast(1)); - } - - T operator--(int) const // postfix - { - const T value(mValue); - operator--(); - return value; - } - -private: - SaturateOp(const SaturateOp&) = delete; - SaturateOp(SaturateOp&&) = delete; - SaturateOp& operator=(const SaturateOp&) = delete; - SaturateOp& operator=(SaturateOp&&) = delete; - - T& mValue; -}; - -/** - * |Saturate| is a value type for saturation arithmetics. It's - * build on top of |SaturateOp|. - */ -template -class Saturate -{ -public: - Saturate() = default; - MOZ_IMPLICIT Saturate(const Saturate&) = default; - - MOZ_IMPLICIT Saturate(Saturate&& aValue) - { - mValue = Move(aValue.mValue); - } - - explicit Saturate(const T& aValue) - : mValue(aValue) - { } - - const T& value() const - { - return mValue; - } - - // Compare operators - - bool operator==(const Saturate& aRhs) const - { - return mValue == aRhs.mValue; - } - - bool operator!=(const Saturate& aRhs) const - { - return !operator==(aRhs); - } - - bool operator==(const T& aRhs) const - { - return mValue == aRhs; - } - - bool operator!=(const T& aRhs) const - { - return !operator==(aRhs); - } - - // Assignment operators - - Saturate& operator=(const Saturate&) = default; - - Saturate& operator=(Saturate&& aRhs) - { - mValue = Move(aRhs.mValue); - return *this; - } - - // Add and subtract operators - - Saturate operator+(const Saturate& aRhs) const - { - Saturate lhs(mValue); - return lhs += aRhs.mValue; - } - - Saturate operator+(const T& aRhs) const - { - Saturate lhs(mValue); - return lhs += aRhs; - } - - Saturate operator-(const Saturate& aRhs) const - { - Saturate lhs(mValue); - return lhs -= aRhs.mValue; - } - - Saturate operator-(const T& aRhs) const - { - Saturate lhs(mValue); - return lhs -= aRhs; - } - - // Compound operators - - Saturate& operator+=(const Saturate& aRhs) - { - SaturateOp(mValue) += aRhs.mValue; - return *this; - } - - Saturate& operator+=(const T& aRhs) - { - SaturateOp(mValue) += aRhs; - return *this; - } - - Saturate& operator-=(const Saturate& aRhs) - { - SaturateOp(mValue) -= aRhs.mValue; - return *this; - } - - Saturate& operator-=(const T& aRhs) - { - SaturateOp(mValue) -= aRhs; - return *this; - } - - // Increment and decrement operators - - Saturate& operator++() // prefix - { - ++SaturateOp(mValue); - return *this; - } - - Saturate operator++(int) // postfix - { - return Saturate(SaturateOp(mValue)++); - } - - Saturate& operator--() // prefix - { - --SaturateOp(mValue); - return *this; - } - - Saturate operator--(int) // postfix - { - return Saturate(SaturateOp(mValue)--); - } - -private: - T mValue; -}; - -} // namespace detail - -typedef detail::Saturate SaturateInt8; -typedef detail::Saturate SaturateInt16; -typedef detail::Saturate SaturateInt32; -typedef detail::Saturate SaturateUint8; -typedef detail::Saturate SaturateUint16; -typedef detail::Saturate SaturateUint32; - -} // namespace mozilla - -template -bool -operator==(LhsT aLhs, const mozilla::detail::Saturate& aRhs) -{ - return aRhs.operator==(static_cast(aLhs)); -} - -template -bool -operator!=(LhsT aLhs, const mozilla::detail::Saturate& aRhs) -{ - return !(aLhs == aRhs); -} - -#endif // mozilla_Saturate_h diff --git a/mac/include/spidermonkey/mozilla/ScopeExit.h b/mac/include/spidermonkey/mozilla/ScopeExit.h deleted file mode 100644 index 7aff82d8..00000000 --- a/mac/include/spidermonkey/mozilla/ScopeExit.h +++ /dev/null @@ -1,135 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* RAII class for executing arbitrary actions at scope end. */ - -#ifndef mozilla_ScopeExit_h -#define mozilla_ScopeExit_h - -/* - * See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189.pdf for a - * standards-track version of this. - * - * Error handling can be complex when various actions need to be performed that - * need to be undone if an error occurs midway. This can be handled with a - * collection of boolean state variables and gotos, which can get clunky and - * error-prone: - * - * { - * if (!a.setup()) - * goto fail; - * isASetup = true; - * - * if (!b.setup()) - * goto fail; - * isBSetup = true; - * - * ... - * return true; - * - * fail: - * if (isASetup) - * a.teardown(); - * if (isBSetup) - * b.teardown(); - * return false; - * } - * - * ScopeExit is a mechanism to simplify this pattern by keeping an RAII guard - * class that will perform the teardown on destruction, unless released. So the - * above would become: - * - * { - * if (!a.setup()) { - * return false; - * } - * auto guardA = MakeScopeExit([&] { - * a.teardown(); - * }); - * - * if (!b.setup()) { - * return false; - * } - * auto guardB = MakeScopeExit([&] { - * b.teardown(); - * }); - * - * ... - * guardA.release(); - * guardB.release(); - * return true; - * } - * - * This header provides: - * - * - |ScopeExit| - a container for a cleanup call, automically called at the - * end of the scope; - * - |MakeScopeExit| - a convenience function for constructing a |ScopeExit| - * with a given cleanup routine, commonly used with a lambda function. - * - * Note that the RAII classes defined in this header do _not_ perform any form - * of reference-counting or garbage-collection. These classes have exactly two - * behaviors: - * - * - if |release()| has not been called, the cleanup is always performed at - * the end of the scope; - * - if |release()| has been called, nothing will happen at the end of the - * scope. - */ - -#include "mozilla/GuardObjects.h" -#include "mozilla/Move.h" - -namespace mozilla { - -template -class MOZ_STACK_CLASS ScopeExit { - ExitFunction mExitFunction; - bool mExecuteOnDestruction; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - -public: - explicit ScopeExit(ExitFunction&& cleanup - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mExitFunction(cleanup) - , mExecuteOnDestruction(true) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - ScopeExit(ScopeExit&& rhs) - : mExitFunction(mozilla::Move(rhs.mExitFunction)) - , mExecuteOnDestruction(rhs.mExecuteOnDestruction) - { - rhs.release(); - } - - ~ScopeExit() { - if (mExecuteOnDestruction) { - mExitFunction(); - } - } - - void release() { - mExecuteOnDestruction = false; - } - -private: - explicit ScopeExit(const ScopeExit&) = delete; - ScopeExit& operator=(const ScopeExit&) = delete; - ScopeExit& operator=(ScopeExit&&) = delete; -}; - -template -ScopeExit -MakeScopeExit(ExitFunction&& exitFunction) -{ - return ScopeExit(mozilla::Move(exitFunction)); -} - -} /* namespace mozilla */ - -#endif /* mozilla_ScopeExit_h */ diff --git a/mac/include/spidermonkey/mozilla/Scoped.h b/mac/include/spidermonkey/mozilla/Scoped.h deleted file mode 100644 index c935434a..00000000 --- a/mac/include/spidermonkey/mozilla/Scoped.h +++ /dev/null @@ -1,255 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* DEPRECATED: Use UniquePtr.h instead. */ - -#ifndef mozilla_Scoped_h -#define mozilla_Scoped_h - -/* - * DEPRECATED: Use UniquePtr.h instead. - * - * Resource Acquisition Is Initialization is a programming idiom used - * to write robust code that is able to deallocate resources properly, - * even in presence of execution errors or exceptions that need to be - * propagated. The Scoped* classes defined via the |SCOPED_TEMPLATE| - * and |MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLTE| macros perform the - * deallocation of the resource they hold once program execution - * reaches the end of the scope for which they have been defined. - * These macros have been used to automatically close file - * descriptors/file handles when reaching the end of the scope, - * graphics contexts, etc. - * - * The general scenario for RAII classes created by the above macros - * is the following: - * - * ScopedClass foo(create_value()); - * // ... In this scope, |foo| is defined. Use |foo.get()| or |foo.rwget()| - * to access the value. - * // ... In case of |return| or |throw|, |foo| is deallocated automatically. - * // ... If |foo| needs to be returned or stored, use |foo.forget()| - * - * Note that the RAII classes defined in this header do _not_ perform any form - * of reference-counting or garbage-collection. These classes have exactly two - * behaviors: - * - * - if |forget()| has not been called, the resource is always deallocated at - * the end of the scope; - * - if |forget()| has been called, any control on the resource is unbound - * and the resource is not deallocated by the class. - */ - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/GuardObjects.h" -#include "mozilla/Move.h" - -namespace mozilla { - -/* - * Scoped is a helper to create RAII wrappers - * Type argument |Traits| is expected to have the following structure: - * - * struct Traits - * { - * // Define the type of the value stored in the wrapper - * typedef value_type type; - * // Returns the value corresponding to the uninitialized or freed state - * const static type empty(); - * // Release resources corresponding to the wrapped value - * // This function is responsible for not releasing an |empty| value - * const static void release(type); - * } - */ -template -class MOZ_NON_TEMPORARY_CLASS Scoped -{ -public: - typedef typename Traits::type Resource; - - explicit Scoped(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) - : mValue(Traits::empty()) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit Scoped(const Resource& aValue - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mValue(aValue) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - /* Move constructor. */ - Scoped(Scoped&& aOther - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mValue(Move(aOther.mValue)) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - aOther.mValue = Traits::empty(); - } - - ~Scoped() { Traits::release(mValue); } - - // Constant getter - operator const Resource&() const { return mValue; } - const Resource& operator->() const { return mValue; } - const Resource& get() const { return mValue; } - // Non-constant getter. - Resource& rwget() { return mValue; } - - /* - * Forget the resource. - * - * Once |forget| has been called, the |Scoped| is neutralized, i.e. it will - * have no effect at destruction (unless it is reset to another resource by - * |operator=|). - * - * @return The original resource. - */ - Resource forget() - { - Resource tmp = mValue; - mValue = Traits::empty(); - return tmp; - } - - /* - * Perform immediate clean-up of this |Scoped|. - * - * If this |Scoped| is currently empty, this method has no effect. - */ - void dispose() - { - Traits::release(mValue); - mValue = Traits::empty(); - } - - bool operator==(const Resource& aOther) const { return mValue == aOther; } - - /* - * Replace the resource with another resource. - * - * Calling |operator=| has the side-effect of triggering clean-up. If you do - * not want to trigger clean-up, you should first invoke |forget|. - * - * @return this - */ - Scoped& operator=(const Resource& aOther) { return reset(aOther); } - - Scoped& reset(const Resource& aOther) - { - Traits::release(mValue); - mValue = aOther; - return *this; - } - - /* Move assignment operator. */ - Scoped& operator=(Scoped&& aRhs) - { - MOZ_ASSERT(&aRhs != this, "self-move-assignment not allowed"); - this->~Scoped(); - new(this) Scoped(Move(aRhs)); - return *this; - } - -private: - explicit Scoped(const Scoped& aValue) = delete; - Scoped& operator=(const Scoped& aValue) = delete; - -private: - Resource mValue; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/* - * SCOPED_TEMPLATE defines a templated class derived from Scoped - * This allows to implement templates such as ScopedFreePtr. - * - * @param name The name of the class to define. - * @param Traits A struct implementing clean-up. See the implementations - * for more details. - */ -#define SCOPED_TEMPLATE(name, Traits) \ -template \ -struct MOZ_NON_TEMPORARY_CLASS name : public mozilla::Scoped > \ -{ \ - typedef mozilla::Scoped > Super; \ - typedef typename Super::Resource Resource; \ - name& operator=(Resource aRhs) \ - { \ - Super::operator=(aRhs); \ - return *this; \ - } \ - name& operator=(name&& aRhs) \ - { \ - Super::operator=(Move(aRhs)); \ - return *this; \ - } \ - explicit name(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) \ - : Super(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT) \ - {} \ - explicit name(Resource aRhs \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) \ - : Super(aRhs \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT) \ - {} \ - name(name&& aRhs \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) \ - : Super(Move(aRhs) \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT) \ - {} \ -private: \ - explicit name(name&) = delete; \ - name& operator=(name&) = delete; \ -}; - -/* - * MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE makes it easy to create scoped - * pointers for types with custom deleters; just overload - * TypeSpecificDelete(T*) in the same namespace as T to call the deleter for - * type T. - * - * @param name The name of the class to define. - * @param Type A struct implementing clean-up. See the implementations - * for more details. - * *param Deleter The function that is used to delete/destroy/free a - * non-null value of Type*. - * - * Example: - * - * MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPRFileDesc, PRFileDesc, \ - * PR_Close) - * ... - * { - * ScopedPRFileDesc file(PR_OpenFile(...)); - * ... - * } // file is closed with PR_Close here - */ -#define MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(name, Type, Deleter) \ -template <> inline void TypeSpecificDelete(Type* aValue) { Deleter(aValue); } \ -typedef ::mozilla::TypeSpecificScopedPointer name; - -template void TypeSpecificDelete(T* aValue); - -template -struct TypeSpecificScopedPointerTraits -{ - typedef T* type; - static type empty() { return nullptr; } - static void release(type aValue) - { - if (aValue) { - TypeSpecificDelete(aValue); - } - } -}; - -SCOPED_TEMPLATE(TypeSpecificScopedPointer, TypeSpecificScopedPointerTraits) - -} /* namespace mozilla */ - -#endif /* mozilla_Scoped_h */ diff --git a/mac/include/spidermonkey/mozilla/SegmentedVector.h b/mac/include/spidermonkey/mozilla/SegmentedVector.h deleted file mode 100644 index 1bf60e46..00000000 --- a/mac/include/spidermonkey/mozilla/SegmentedVector.h +++ /dev/null @@ -1,339 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// A simple segmented vector class. -// -// This class should be used in preference to mozilla::Vector or nsTArray when -// you are simply gathering items in order to later iterate over them. -// -// - In the case where you don't know the final size in advance, using -// SegmentedVector avoids the need to repeatedly allocate increasingly large -// buffers and copy the data into them. -// -// - In the case where you know the final size in advance and so can set the -// capacity appropriately, using SegmentedVector still avoids the need for -// large allocations (which can trigger OOMs). - -#ifndef mozilla_SegmentedVector_h -#define mozilla_SegmentedVector_h - -#include "mozilla/Alignment.h" -#include "mozilla/AllocPolicy.h" -#include "mozilla/Array.h" -#include "mozilla/LinkedList.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include // for placement new - -namespace mozilla { - -// |IdealSegmentSize| specifies how big each segment will be in bytes (or as -// close as is possible). Use the following guidelines to choose a size. -// -// - It should be a power-of-two, to avoid slop. -// -// - It should not be too small, so that segment allocations are infrequent, -// and so that per-segment bookkeeping overhead is low. Typically each -// segment should be able to hold hundreds of elements, at least. -// -// - It should not be too large, so that OOMs are unlikely when allocating -// segments, and so that not too much space is wasted when the final segment -// is not full. -// -// The ideal size depends on how the SegmentedVector is used and the size of -// |T|, but reasonable sizes include 1024, 4096 (the default), 8192, and 16384. -// -template -class SegmentedVector : private AllocPolicy -{ - template - struct SegmentImpl - : public mozilla::LinkedListElement> - { - SegmentImpl() : mLength(0) {} - - ~SegmentImpl() - { - for (uint32_t i = 0; i < mLength; i++) { - (*this)[i].~T(); - } - } - - uint32_t Length() const { return mLength; } - - T* Elems() { return reinterpret_cast(&mStorage.mBuf); } - - T& operator[](size_t aIndex) - { - MOZ_ASSERT(aIndex < mLength); - return Elems()[aIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(aIndex < mLength); - return Elems()[aIndex]; - } - - template - void Append(U&& aU) - { - MOZ_ASSERT(mLength < SegmentCapacity); - // Pre-increment mLength so that the bounds-check in operator[] passes. - mLength++; - T* elem = &(*this)[mLength - 1]; - new (elem) T(mozilla::Forward(aU)); - } - - void PopLast() - { - MOZ_ASSERT(mLength > 0); - (*this)[mLength - 1].~T(); - mLength--; - } - - uint32_t mLength; - - // The union ensures that the elements are appropriately aligned. - union Storage - { - char mBuf[sizeof(T) * SegmentCapacity]; - mozilla::AlignedElem mAlign; - } mStorage; - - static_assert(MOZ_ALIGNOF(T) == MOZ_ALIGNOF(Storage), - "SegmentedVector provides incorrect alignment"); - }; - - // See how many we elements we can fit in a segment of IdealSegmentSize. If - // IdealSegmentSize is too small, it'll be just one. The +1 is because - // kSingleElementSegmentSize already accounts for one element. - static const size_t kSingleElementSegmentSize = sizeof(SegmentImpl<1>); - static const size_t kSegmentCapacity = - kSingleElementSegmentSize <= IdealSegmentSize - ? (IdealSegmentSize - kSingleElementSegmentSize) / sizeof(T) + 1 - : 1; - - typedef SegmentImpl Segment; - -public: - // The |aIdealSegmentSize| is only for sanity checking. If it's specified, we - // check that the actual segment size is as close as possible to it. This - // serves as a sanity check for SegmentedVectorCapacity's capacity - // computation. - explicit SegmentedVector(size_t aIdealSegmentSize = 0) - { - // The difference between the actual segment size and the ideal segment - // size should be less than the size of a single element... unless the - // ideal size was too small, in which case the capacity should be one. - MOZ_ASSERT_IF( - aIdealSegmentSize != 0, - (sizeof(Segment) > aIdealSegmentSize && kSegmentCapacity == 1) || - aIdealSegmentSize - sizeof(Segment) < sizeof(T)); - } - - ~SegmentedVector() { Clear(); } - - bool IsEmpty() const { return !mSegments.getFirst(); } - - // Note that this is O(n) rather than O(1), but the constant factor is very - // small because it only has to do one addition per segment. - size_t Length() const - { - size_t n = 0; - for (auto segment = mSegments.getFirst(); - segment; - segment = segment->getNext()) { - n += segment->Length(); - } - return n; - } - - // Returns false if the allocation failed. (If you are using an infallible - // allocation policy, use InfallibleAppend() instead.) - template - MOZ_MUST_USE bool Append(U&& aU) - { - Segment* last = mSegments.getLast(); - if (!last || last->Length() == kSegmentCapacity) { - last = this->template pod_malloc(1); - if (!last) { - return false; - } - new (last) Segment(); - mSegments.insertBack(last); - } - last->Append(mozilla::Forward(aU)); - return true; - } - - // You should probably only use this instead of Append() if you are using an - // infallible allocation policy. It will crash if the allocation fails. - template - void InfallibleAppend(U&& aU) - { - bool ok = Append(mozilla::Forward(aU)); - MOZ_RELEASE_ASSERT(ok); - } - - void Clear() - { - Segment* segment; - while ((segment = mSegments.popFirst())) { - segment->~Segment(); - this->free_(segment); - } - } - - T& GetLast() - { - MOZ_ASSERT(!IsEmpty()); - Segment* last = mSegments.getLast(); - return (*last)[last->Length() - 1]; - } - - const T& GetLast() const - { - MOZ_ASSERT(!IsEmpty()); - Segment* last = mSegments.getLast(); - return (*last)[last->Length() - 1]; - } - - void PopLast() - { - MOZ_ASSERT(!IsEmpty()); - Segment* last = mSegments.getLast(); - last->PopLast(); - if (!last->Length()) { - mSegments.popLast(); - last->~Segment(); - this->free_(last); - } - } - - // Equivalent to calling |PopLast| |aNumElements| times, but potentially - // more efficient. - void PopLastN(uint32_t aNumElements) - { - MOZ_ASSERT(aNumElements <= Length()); - - Segment* last; - - // Pop full segments for as long as we can. Note that this loop - // cleanly handles the case when the initial last segment is not - // full and we are popping more elements than said segment contains. - do { - last = mSegments.getLast(); - - // The list is empty. We're all done. - if (!last) { - return; - } - - // Check to see if the list contains too many elements. Handle - // that in the epilogue. - uint32_t segmentLen = last->Length(); - if (segmentLen > aNumElements) { - break; - } - - // Destroying the segment destroys all elements contained therein. - mSegments.popLast(); - last->~Segment(); - this->free_(last); - - MOZ_ASSERT(aNumElements >= segmentLen); - aNumElements -= segmentLen; - if (aNumElements == 0) { - return; - } - } while (true); - - // Handle the case where the last segment contains more elements - // than we want to pop. - MOZ_ASSERT(last); - MOZ_ASSERT(last == mSegments.getLast()); - MOZ_ASSERT(aNumElements != 0); - MOZ_ASSERT(aNumElements < last->Length()); - for (uint32_t i = 0; i < aNumElements; ++i) { - last->PopLast(); - } - MOZ_ASSERT(last->Length() != 0); - } - - // Use this class to iterate over a SegmentedVector, like so: - // - // for (auto iter = v.Iter(); !iter.Done(); iter.Next()) { - // MyElem& elem = iter.Get(); - // f(elem); - // } - // - class IterImpl - { - friend class SegmentedVector; - - Segment* mSegment; - size_t mIndex; - - explicit IterImpl(SegmentedVector* aVector) - : mSegment(aVector->mSegments.getFirst()) - , mIndex(0) - {} - - public: - bool Done() const { return !mSegment; } - - T& Get() - { - MOZ_ASSERT(!Done()); - return (*mSegment)[mIndex]; - } - - const T& Get() const - { - MOZ_ASSERT(!Done()); - return (*mSegment)[mIndex]; - } - - void Next() - { - MOZ_ASSERT(!Done()); - mIndex++; - if (mIndex == mSegment->Length()) { - mSegment = mSegment->getNext(); - mIndex = 0; - } - } - }; - - IterImpl Iter() { return IterImpl(this); } - - // Measure the memory consumption of the vector excluding |this|. Note that - // it only measures the vector itself. If the vector elements contain - // pointers to other memory blocks, those blocks must be measured separately - // during a subsequent iteration over the vector. - size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const - { - return mSegments.sizeOfExcludingThis(aMallocSizeOf); - } - - // Like sizeOfExcludingThis(), but measures |this| as well. - size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const - { - return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf); - } - -private: - mozilla::LinkedList mSegments; -}; - -} // namespace mozilla - -#endif /* mozilla_SegmentedVector_h */ diff --git a/mac/include/spidermonkey/mozilla/SizePrintfMacros.h b/mac/include/spidermonkey/mozilla/SizePrintfMacros.h deleted file mode 100644 index ec55c62c..00000000 --- a/mac/include/spidermonkey/mozilla/SizePrintfMacros.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements (nonstandard) PRI{ouxX}SIZE format macros for size_t types. */ - -#ifndef mozilla_SizePrintfMacros_h_ -#define mozilla_SizePrintfMacros_h_ - -/* - * MSVC's libc does not support C99's %z format length modifier for size_t - * types. Instead, we use Microsoft's nonstandard %I modifier for size_t, which - * is unsigned __int32 on 32-bit platforms and unsigned __int64 on 64-bit - * platforms: - * - * http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx - */ - -#if defined(XP_WIN) -# define PRIoSIZE "Io" -# define PRIuSIZE "Iu" -# define PRIxSIZE "Ix" -# define PRIXSIZE "IX" -#else -# define PRIoSIZE "zo" -# define PRIuSIZE "zu" -# define PRIxSIZE "zx" -# define PRIXSIZE "zX" -#endif - -#endif /* mozilla_SizePrintfMacros_h_ */ diff --git a/mac/include/spidermonkey/mozilla/SplayTree.h b/mac/include/spidermonkey/mozilla/SplayTree.h deleted file mode 100644 index 2b3b838b..00000000 --- a/mac/include/spidermonkey/mozilla/SplayTree.h +++ /dev/null @@ -1,330 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/** - * A sorted tree with optimal access times, where recently-accessed elements - * are faster to access again. - */ - -#ifndef mozilla_SplayTree_h -#define mozilla_SplayTree_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -namespace mozilla { - -template -class SplayTree; - -template -class SplayTreeNode -{ -public: - template - friend class SplayTree; - - SplayTreeNode() - : mLeft(nullptr) - , mRight(nullptr) - , mParent(nullptr) - {} - -private: - T* mLeft; - T* mRight; - T* mParent; -}; - - -/** - * Class which represents a splay tree. - * Splay trees are balanced binary search trees for which search, insert and - * remove are all amortized O(log n), but where accessing a node makes it - * faster to access that node in the future. - * - * T indicates the type of tree elements, Comparator must have a static - * compare(const T&, const T&) method ordering the elements. The compare - * method must be free from side effects. - */ -template -class SplayTree -{ - T* mRoot; - -public: - constexpr SplayTree() - : mRoot(nullptr) - {} - - bool empty() const - { - return !mRoot; - } - - T* find(const T& aValue) - { - if (empty()) { - return nullptr; - } - - T* last = lookup(aValue); - splay(last); - return Comparator::compare(aValue, *last) == 0 ? last : nullptr; - } - - void insert(T* aValue) - { - MOZ_ASSERT(!find(*aValue), "Duplicate elements are not allowed."); - - if (!mRoot) { - mRoot = aValue; - return; - } - T* last = lookup(*aValue); - int cmp = Comparator::compare(*aValue, *last); - - finishInsertion(last, cmp, aValue); - return; - } - - T* findOrInsert(const T& aValue); - - T* remove(const T& aValue) - { - T* last = lookup(aValue); - MOZ_ASSERT(last, "This tree must contain the element being removed."); - MOZ_ASSERT(Comparator::compare(aValue, *last) == 0); - - // Splay the tree so that the item to remove is the root. - splay(last); - MOZ_ASSERT(last == mRoot); - - // Find another node which can be swapped in for the root: either the - // rightmost child of the root's left, or the leftmost child of the - // root's right. - T* swap; - T* swapChild; - if (mRoot->mLeft) { - swap = mRoot->mLeft; - while (swap->mRight) { - swap = swap->mRight; - } - swapChild = swap->mLeft; - } else if (mRoot->mRight) { - swap = mRoot->mRight; - while (swap->mLeft) { - swap = swap->mLeft; - } - swapChild = swap->mRight; - } else { - T* result = mRoot; - mRoot = nullptr; - return result; - } - - // The selected node has at most one child, in swapChild. Detach it - // from the subtree by replacing it with that child. - if (swap == swap->mParent->mLeft) { - swap->mParent->mLeft = swapChild; - } else { - swap->mParent->mRight = swapChild; - } - if (swapChild) { - swapChild->mParent = swap->mParent; - } - - // Make the selected node the new root. - mRoot = swap; - mRoot->mParent = nullptr; - mRoot->mLeft = last->mLeft; - mRoot->mRight = last->mRight; - if (mRoot->mLeft) { - mRoot->mLeft->mParent = mRoot; - } - if (mRoot->mRight) { - mRoot->mRight->mParent = mRoot; - } - - return last; - } - - T* removeMin() - { - MOZ_ASSERT(mRoot, "No min to remove!"); - - T* min = mRoot; - while (min->mLeft) { - min = min->mLeft; - } - return remove(*min); - } - - // For testing purposes only. - void checkCoherency() - { - checkCoherency(mRoot, nullptr); - } - -private: - /** - * Returns the node in this comparing equal to |aValue|, or a node just - * greater or just less than |aValue| if there is no such node. - */ - T* lookup(const T& aValue) - { - MOZ_ASSERT(!empty()); - - T* node = mRoot; - T* parent; - do { - parent = node; - int c = Comparator::compare(aValue, *node); - if (c == 0) { - return node; - } else if (c < 0) { - node = node->mLeft; - } else { - node = node->mRight; - } - } while (node); - return parent; - } - - void finishInsertion(T* aLast, int32_t aCmp, T* aNew) - { - MOZ_ASSERT(aCmp, "Nodes shouldn't be equal!"); - - T** parentPointer = (aCmp < 0) ? &aLast->mLeft : &aLast->mRight; - MOZ_ASSERT(!*parentPointer); - *parentPointer = aNew; - aNew->mParent = aLast; - - splay(aNew); - } - - /** - * Rotate the tree until |node| is at the root of the tree. Performing - * the rotations in this fashion preserves the amortized balancing of - * the tree. - */ - void splay(T* aNode) - { - MOZ_ASSERT(aNode); - - while (aNode != mRoot) { - T* parent = aNode->mParent; - if (parent == mRoot) { - // Zig rotation. - rotate(aNode); - MOZ_ASSERT(aNode == mRoot); - return; - } - T* grandparent = parent->mParent; - if ((parent->mLeft == aNode) == (grandparent->mLeft == parent)) { - // Zig-zig rotation. - rotate(parent); - rotate(aNode); - } else { - // Zig-zag rotation. - rotate(aNode); - rotate(aNode); - } - } - } - - void rotate(T* aNode) - { - // Rearrange nodes so that aNode becomes the parent of its current - // parent, while preserving the sortedness of the tree. - T* parent = aNode->mParent; - if (parent->mLeft == aNode) { - // x y - // y c ==> a x - // a b b c - parent->mLeft = aNode->mRight; - if (aNode->mRight) { - aNode->mRight->mParent = parent; - } - aNode->mRight = parent; - } else { - MOZ_ASSERT(parent->mRight == aNode); - // x y - // a y ==> x c - // b c a b - parent->mRight = aNode->mLeft; - if (aNode->mLeft) { - aNode->mLeft->mParent = parent; - } - aNode->mLeft = parent; - } - aNode->mParent = parent->mParent; - parent->mParent = aNode; - if (T* grandparent = aNode->mParent) { - if (grandparent->mLeft == parent) { - grandparent->mLeft = aNode; - } else { - grandparent->mRight = aNode; - } - } else { - mRoot = aNode; - } - } - - T* checkCoherency(T* aNode, T* aMinimum) - { - if (mRoot) { - MOZ_RELEASE_ASSERT(!mRoot->mParent); - } - if (!aNode) { - MOZ_RELEASE_ASSERT(!mRoot); - return nullptr; - } - if (!aNode->mParent) { - MOZ_RELEASE_ASSERT(aNode == mRoot); - } - if (aMinimum) { - MOZ_RELEASE_ASSERT(Comparator::compare(*aMinimum, *aNode) < 0); - } - if (aNode->mLeft) { - MOZ_RELEASE_ASSERT(aNode->mLeft->mParent == aNode); - T* leftMaximum = checkCoherency(aNode->mLeft, aMinimum); - MOZ_RELEASE_ASSERT(Comparator::compare(*leftMaximum, *aNode) < 0); - } - if (aNode->mRight) { - MOZ_RELEASE_ASSERT(aNode->mRight->mParent == aNode); - return checkCoherency(aNode->mRight, aNode); - } - return aNode; - } - - SplayTree(const SplayTree&) = delete; - void operator=(const SplayTree&) = delete; -}; - -template -T* -SplayTree::findOrInsert(const T& aValue) -{ - if (!mRoot) { - mRoot = new T(aValue); - return mRoot; - } - - T* last = lookup(aValue); - int cmp = Comparator::compare(aValue, *last); - if (!cmp) { - return last; - } - - T* t = new T(aValue); - finishInsertion(last, cmp, t); - return t; -} - -} /* namespace mozilla */ - -#endif /* mozilla_SplayTree_h */ diff --git a/mac/include/spidermonkey/mozilla/Sprintf.h b/mac/include/spidermonkey/mozilla/Sprintf.h deleted file mode 100644 index e0be271e..00000000 --- a/mac/include/spidermonkey/mozilla/Sprintf.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Provides a safer sprintf for printing to fixed-size character arrays. */ - -#ifndef mozilla_Sprintf_h_ -#define mozilla_Sprintf_h_ - -#include -#include - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#ifdef __cplusplus - -template -int VsprintfLiteral(char (&buffer)[N], const char* format, va_list args) -{ - MOZ_ASSERT(format != buffer); - int result = vsnprintf(buffer, N, format, args); - buffer[N - 1] = '\0'; - return result; -} - -template -MOZ_FORMAT_PRINTF(2, 3) -int SprintfLiteral(char (&buffer)[N], const char* format, ...) -{ - va_list args; - va_start(args, format); - int result = VsprintfLiteral(buffer, format, args); - va_end(args); - return result; -} - -#endif -#endif /* mozilla_Sprintf_h_ */ diff --git a/mac/include/spidermonkey/mozilla/StackWalk.h b/mac/include/spidermonkey/mozilla/StackWalk.h deleted file mode 100644 index 534c0bd8..00000000 --- a/mac/include/spidermonkey/mozilla/StackWalk.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* API for getting a stack trace of the C/C++ stack on the current thread */ - -#ifndef mozilla_StackWalk_h -#define mozilla_StackWalk_h - -/* WARNING: This file is intended to be included from C or C++ files. */ - -#include "mozilla/Types.h" -#include - -/** - * The callback for MozStackWalk. - * - * @param aFrameNumber The frame number (starts at 1, not 0). - * @param aPC The program counter value. - * @param aSP The best approximation possible of what the stack - * pointer will be pointing to when the execution returns - * to executing that at aPC. If no approximation can - * be made it will be nullptr. - * @param aClosure Extra data passed in via MozStackWalk(). - */ -typedef void -(*MozWalkStackCallback)(uint32_t aFrameNumber, void* aPC, void* aSP, - void* aClosure); - -/** - * Call aCallback for the C/C++ stack frames on the current thread, from - * the caller of MozStackWalk to main (or above). - * - * @param aCallback Callback function, called once per frame. - * @param aSkipFrames Number of initial frames to skip. 0 means that - * the first callback will be for the caller of - * MozStackWalk. - * @param aMaxFrames Maximum number of frames to trace. 0 means no limit. - * @param aClosure Caller-supplied data passed through to aCallback. - * @param aThread The thread for which the stack is to be retrieved. - * Passing null causes us to walk the stack of the - * current thread. On Windows, this is a thread HANDLE. - * It is currently not supported on any other platform. - * @param aPlatformData Platform specific data that can help in walking the - * stack, this should be nullptr unless you really know - * what you're doing! This needs to be a pointer to a - * CONTEXT on Windows and should not be passed on other - * platforms. - * - * May skip some stack frames due to compiler optimizations or code - * generation. - * - */ -MFBT_API bool -MozStackWalk(MozWalkStackCallback aCallback, uint32_t aSkipFrames, - uint32_t aMaxFrames, void* aClosure, uintptr_t aThread, - void* aPlatformData); - -typedef struct -{ - /* - * The name of the shared library or executable containing an - * address and the address's offset within that library, or empty - * string and zero if unknown. - */ - char library[256]; - ptrdiff_t loffset; - /* - * The name of the file name and line number of the code - * corresponding to the address, or empty string and zero if - * unknown. - */ - char filename[256]; - unsigned long lineno; - /* - * The name of the function containing an address and the address's - * offset within that function, or empty string and zero if unknown. - */ - char function[256]; - ptrdiff_t foffset; -} MozCodeAddressDetails; - -/** - * For a given pointer to code, fill in the pieces of information used - * when printing a stack trace. - * - * @param aPC The code address. - * @param aDetails A structure to be filled in with the result. - */ -MFBT_API bool -MozDescribeCodeAddress(void* aPC, MozCodeAddressDetails* aDetails); - -/** - * Format the information about a code address in a format suitable for - * stack traces on the current platform. When available, this string - * should contain the function name, source file, and line number. When - * these are not available, library and offset should be reported, if - * possible. - * - * Note that this output is parsed by several scripts including the fix*.py and - * make-tree.pl scripts in tools/rb/. It should only be change with care, and - * in conjunction with those scripts. - * - * @param aBuffer A string to be filled in with the description. - * The string will always be null-terminated. - * @param aBufferSize The size, in bytes, of aBuffer, including - * room for the terminating null. If the information - * to be printed would be larger than aBuffer, it - * will be truncated so that aBuffer[aBufferSize-1] - * is the terminating null. - * @param aFrameNumber The frame number. - * @param aPC The code address. - * @param aFunction The function name. Possibly null or the empty string. - * @param aLibrary The library name. Possibly null or the empty string. - * @param aLOffset The library offset. - * @param aFileName The filename. Possibly null or the empty string. - * @param aLineNo The line number. Possibly zero. - */ -MFBT_API void -MozFormatCodeAddress(char* aBuffer, uint32_t aBufferSize, uint32_t aFrameNumber, - const void* aPC, const char* aFunction, - const char* aLibrary, ptrdiff_t aLOffset, - const char* aFileName, uint32_t aLineNo); - -/** - * Format the information about a code address in the same fashion as - * MozFormatCodeAddress. - * - * @param aBuffer A string to be filled in with the description. - * The string will always be null-terminated. - * @param aBufferSize The size, in bytes, of aBuffer, including - * room for the terminating null. If the information - * to be printed would be larger than aBuffer, it - * will be truncated so that aBuffer[aBufferSize-1] - * is the terminating null. - * @param aFrameNumber The frame number. - * @param aPC The code address. - * @param aDetails The value filled in by MozDescribeCodeAddress(aPC). - */ -MFBT_API void -MozFormatCodeAddressDetails(char* aBuffer, uint32_t aBufferSize, - uint32_t aFrameNumber, void* aPC, - const MozCodeAddressDetails* aDetails); - -namespace mozilla { - -MFBT_API bool -FramePointerStackWalk(MozWalkStackCallback aCallback, uint32_t aSkipFrames, - uint32_t aMaxFrames, void* aClosure, void** aBp, - void* aStackEnd); - -} // namespace mozilla - -/** - * Initialize the critical sections for this platform so that we can - * abort stack walks when needed. - */ -MFBT_API void -StackWalkInitCriticalAddress(void); - -#endif diff --git a/mac/include/spidermonkey/mozilla/StaticAnalysisFunctions.h b/mac/include/spidermonkey/mozilla/StaticAnalysisFunctions.h deleted file mode 100644 index a06809dc..00000000 --- a/mac/include/spidermonkey/mozilla/StaticAnalysisFunctions.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_StaticAnalysisFunctions_h -#define mozilla_StaticAnalysisFunctions_h - -#ifndef __cplusplus -#ifndef bool -#include -#endif -#endif -/* - * Functions that are used as markers in Gecko code for static analysis. Their - * purpose is to have different AST nodes generated during compile time and to - * match them based on different checkers implemented in build/clang-plugin - */ - -#ifdef MOZ_CLANG_PLUGIN - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * MOZ_AssertAssignmentTest - used in MOZ_ASSERT in order to test the possible - * presence of assignment instead of logical comparisons. - * - * Example: - * MOZ_ASSERT(retVal = true); - */ -static MOZ_ALWAYS_INLINE bool MOZ_AssertAssignmentTest(bool exprResult) { - return exprResult; -} - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#define MOZ_CHECK_ASSERT_ASSIGNMENT(expr) MOZ_AssertAssignmentTest(!!(expr)) - -#else - -#define MOZ_CHECK_ASSERT_ASSIGNMENT(expr) (!!(expr)) - -#endif /* MOZ_CLANG_PLUGIN */ -#endif /* StaticAnalysisFunctions_h */ \ No newline at end of file diff --git a/mac/include/spidermonkey/mozilla/TaggedAnonymousMemory.h b/mac/include/spidermonkey/mozilla/TaggedAnonymousMemory.h deleted file mode 100644 index d26b06df..00000000 --- a/mac/include/spidermonkey/mozilla/TaggedAnonymousMemory.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// Some Linux kernels -- specifically, newer versions of Android and -// some B2G devices -- have a feature for assigning names to ranges of -// anonymous memory (i.e., memory that doesn't have a "name" in the -// form of an underlying mapped file). These names are reported in -// /proc//smaps alongside system-level memory usage information -// such as Proportional Set Size (memory usage adjusted for sharing -// between processes), which allows reporting this information at a -// finer granularity than would otherwise be possible (e.g., -// separating malloc() heap from JS heap). -// -// Existing memory can be tagged with MozTagAnonymousMemory(); it will -// tag the range of complete pages containing the given interval, so -// the results may be inexact if the range isn't page-aligned. -// MozTaggedAnonymousMmap() can be used like mmap() with an extra -// parameter, and will tag the returned memory if the mapping was -// successful (and if it was in fact anonymous). -// -// NOTE: The pointer given as the "tag" argument MUST remain valid as -// long as the mapping exists. The referenced string is read when -// /proc//smaps or /proc//maps is read, not when the tag is -// established, so freeing it or changing its contents will have -// unexpected results. Using a static string is probably best. -// -// Also note that this header can be used by both C and C++ code. - -#ifndef mozilla_TaggedAnonymousMemory_h -#define mozilla_TaggedAnonymousMemory_h - -#ifndef XP_WIN - -#include -#include - -#include "mozilla/Types.h" - -#ifdef ANDROID - -#ifdef __cplusplus -extern "C" { -#endif - -MFBT_API void -MozTagAnonymousMemory(const void* aPtr, size_t aLength, const char* aTag); - -MFBT_API void* -MozTaggedAnonymousMmap(void* aAddr, size_t aLength, int aProt, int aFlags, - int aFd, off_t aOffset, const char* aTag); - -MFBT_API int -MozTaggedMemoryIsSupported(void); - -#ifdef __cplusplus -} // extern "C" -#endif - -#else // ANDROID - -static inline void -MozTagAnonymousMemory(const void* aPtr, size_t aLength, const char* aTag) -{ -} - -static inline void* -MozTaggedAnonymousMmap(void* aAddr, size_t aLength, int aProt, int aFlags, - int aFd, off_t aOffset, const char* aTag) -{ - return mmap(aAddr, aLength, aProt, aFlags, aFd, aOffset); -} - -static inline int -MozTaggedMemoryIsSupported(void) -{ - return 0; -} - -#endif // ANDROID - -#endif // !XP_WIN - -#endif // mozilla_TaggedAnonymousMemory_h diff --git a/mac/include/spidermonkey/mozilla/TemplateLib.h b/mac/include/spidermonkey/mozilla/TemplateLib.h deleted file mode 100644 index 6286452d..00000000 --- a/mac/include/spidermonkey/mozilla/TemplateLib.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Reusable template meta-functions on types and compile-time values. Meta- - * functions are placed inside the 'tl' namespace to avoid conflict with non- - * meta functions of the same name (e.g., mozilla::tl::FloorLog2 vs. - * mozilla::FloorLog2). - * - * When constexpr support becomes universal, we should probably use that instead - * of some of these templates, for simplicity. - */ - -#ifndef mozilla_TemplateLib_h -#define mozilla_TemplateLib_h - -#include -#include - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -namespace tl { - -/** Compute min/max. */ -template -struct Min -{ - static const size_t value = I < J ? I : J; -}; -template -struct Max -{ - static const size_t value = I > J ? I : J; -}; - -/** Compute floor(log2(i)). */ -template -struct FloorLog2 -{ - static const size_t value = 1 + FloorLog2::value; -}; -template<> struct FloorLog2<0> { /* Error */ }; -template<> struct FloorLog2<1> { static const size_t value = 0; }; - -/** Compute ceiling(log2(i)). */ -template -struct CeilingLog2 -{ - static const size_t value = FloorLog2<2 * I - 1>::value; -}; - -/** Round up to the nearest power of 2. */ -template -struct RoundUpPow2 -{ - static const size_t value = size_t(1) << CeilingLog2::value; -}; -template<> -struct RoundUpPow2<0> -{ - static const size_t value = 1; -}; - -/** Compute the number of bits in the given unsigned type. */ -template -struct BitSize -{ - static const size_t value = sizeof(T) * CHAR_BIT; -}; - -/** - * Produce an N-bit mask, where N <= BitSize::value. Handle the - * language-undefined edge case when N = BitSize::value. - */ -template -struct NBitMask -{ - // Assert the precondition. On success this evaluates to 0. Otherwise it - // triggers divide-by-zero at compile time: a guaranteed compile error in - // C++11, and usually one in C++98. Add this value to |value| to assure - // its computation. - static const size_t checkPrecondition = - 0 / size_t(N < BitSize::value); - static const size_t value = (size_t(1) << N) - 1 + checkPrecondition; -}; -template<> -struct NBitMask::value> -{ - static const size_t value = size_t(-1); -}; - -/** - * For the unsigned integral type size_t, compute a mask M for N such that - * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) - */ -template -struct MulOverflowMask -{ - static const size_t value = - ~NBitMask::value - CeilingLog2::value>::value; -}; -template<> struct MulOverflowMask<0> { /* Error */ }; -template<> struct MulOverflowMask<1> { static const size_t value = 0; }; - -/** - * And computes the logical 'and' of its argument booleans. - * - * Examples: - * mozilla::t1::And::value is true. - * mozilla::t1::And::value is false. - * mozilla::t1::And<>::value is true. - */ - -template -struct And; - -template<> -struct And<> : public TrueType { }; - -template -struct And - : public Conditional, FalseType>::Type { }; - -} // namespace tl - -} // namespace mozilla - -#endif /* mozilla_TemplateLib_h */ diff --git a/mac/include/spidermonkey/mozilla/ThreadLocal.h b/mac/include/spidermonkey/mozilla/ThreadLocal.h deleted file mode 100644 index 880e6773..00000000 --- a/mac/include/spidermonkey/mozilla/ThreadLocal.h +++ /dev/null @@ -1,222 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Cross-platform lightweight thread local data wrappers. */ - -#ifndef mozilla_ThreadLocal_h -#define mozilla_ThreadLocal_h - -#if defined(XP_WIN) -// This file will get included in any file that wants to add a profiler mark. -// In order to not bring together we could include windef.h and -// winbase.h which are sufficient to get the prototypes for the Tls* functions. -// # include -// # include -// Unfortunately, even including these headers causes us to add a bunch of ugly -// stuff to our namespace e.g #define CreateEvent CreateEventW -extern "C" { -__declspec(dllimport) void* __stdcall TlsGetValue(unsigned long); -__declspec(dllimport) int __stdcall TlsSetValue(unsigned long, void*); -__declspec(dllimport) unsigned long __stdcall TlsAlloc(); -} -#else -# include -# include -#endif - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -// sig_safe_t denotes an atomic type which can be read or stored in a single -// instruction. This means that data of this type is safe to be manipulated -// from a signal handler, or other similar asynchronous execution contexts. -#if defined(XP_WIN) -typedef unsigned long sig_safe_t; -#else -typedef sig_atomic_t sig_safe_t; -#endif - -namespace detail { - -#if defined(HAVE_THREAD_TLS_KEYWORD) -#define MOZ_HAS_THREAD_LOCAL -#endif - -/* - * Thread Local Storage helpers. - * - * Usage: - * - * Do not directly instantiate this class. Instead, use the - * MOZ_THREAD_LOCAL macro to declare or define instances. The macro - * takes a type name as its argument. - * - * Declare like this: - * extern MOZ_THREAD_LOCAL(int) tlsInt; - * Define like this: - * MOZ_THREAD_LOCAL(int) tlsInt; - * or: - * static MOZ_THREAD_LOCAL(int) tlsInt; - * - * Only static-storage-duration (e.g. global variables, or static class members) - * objects of this class should be instantiated. This class relies on - * zero-initialization, which is implicit for static-storage-duration objects. - * It doesn't have a custom default constructor, to avoid static initializers. - * - * API usage: - * - * // Create a TLS item. - * // - * // Note that init() should be invoked before the first use of set() - * // or get(). It is ok to call it multiple times. This must be - * // called in a way that avoids possible races with other threads. - * MOZ_THREAD_LOCAL(int) tlsKey; - * if (!tlsKey.init()) { - * // deal with the error - * } - * - * // Set the TLS value - * tlsKey.set(123); - * - * // Get the TLS value - * int value = tlsKey.get(); - */ -template -class ThreadLocal -{ -#ifndef MOZ_HAS_THREAD_LOCAL -#if defined(XP_WIN) - typedef unsigned long key_t; -#else - typedef pthread_key_t key_t; -#endif - - // Integral types narrower than void* must be extended to avoid - // warnings from valgrind on some platforms. This helper type - // achieves that without penalizing the common case of ThreadLocals - // instantiated using a pointer type. - template - struct Helper - { - typedef uintptr_t Type; - }; - - template - struct Helper - { - typedef S *Type; - }; -#endif - - bool initialized() const { -#ifdef MOZ_HAS_THREAD_LOCAL - return true; -#else - return mInited; -#endif - } - -public: - // __thread does not allow non-trivial constructors, but we can - // instead rely on zero-initialization. -#ifndef MOZ_HAS_THREAD_LOCAL - ThreadLocal() - : mKey(0), mInited(false) - {} -#endif - - MOZ_MUST_USE inline bool init(); - - inline T get() const; - - inline void set(const T aValue); - -private: -#ifdef MOZ_HAS_THREAD_LOCAL - T mValue; -#else - key_t mKey; - bool mInited; -#endif -}; - -template -inline bool -ThreadLocal::init() -{ - static_assert(mozilla::IsPointer::value || mozilla::IsIntegral::value, - "mozilla::ThreadLocal must be used with a pointer or " - "integral type"); - static_assert(sizeof(T) <= sizeof(void*), - "mozilla::ThreadLocal can't be used for types larger than " - "a pointer"); - -#ifdef MOZ_HAS_THREAD_LOCAL - return true; -#else - if (!initialized()) { -#ifdef XP_WIN - mKey = TlsAlloc(); - mInited = mKey != 0xFFFFFFFFUL; // TLS_OUT_OF_INDEXES -#else - mInited = !pthread_key_create(&mKey, nullptr); -#endif - } - return mInited; -#endif -} - -template -inline T -ThreadLocal::get() const -{ -#ifdef MOZ_HAS_THREAD_LOCAL - return mValue; -#else - MOZ_ASSERT(initialized()); - void* h; -#ifdef XP_WIN - h = TlsGetValue(mKey); -#else - h = pthread_getspecific(mKey); -#endif - return static_cast(reinterpret_cast::Type>(h)); -#endif -} - -template -inline void -ThreadLocal::set(const T aValue) -{ -#ifdef MOZ_HAS_THREAD_LOCAL - mValue = aValue; -#else - MOZ_ASSERT(initialized()); - void* h = reinterpret_cast(static_cast::Type>(aValue)); -#ifdef XP_WIN - bool succeeded = TlsSetValue(mKey, h); -#else - bool succeeded = !pthread_setspecific(mKey, h); -#endif - if (!succeeded) { - MOZ_CRASH(); - } -#endif -} - -#ifdef MOZ_HAS_THREAD_LOCAL -#define MOZ_THREAD_LOCAL(TYPE) __thread mozilla::detail::ThreadLocal -#else -#define MOZ_THREAD_LOCAL(TYPE) mozilla::detail::ThreadLocal -#endif - -} // namespace detail -} // namespace mozilla - -#endif /* mozilla_ThreadLocal_h */ diff --git a/mac/include/spidermonkey/mozilla/TimeStamp.h b/mac/include/spidermonkey/mozilla/TimeStamp.h deleted file mode 100644 index a1a0eb36..00000000 --- a/mac/include/spidermonkey/mozilla/TimeStamp.h +++ /dev/null @@ -1,609 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_TimeStamp_h -#define mozilla_TimeStamp_h - -#include -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Types.h" - -namespace IPC { -template struct ParamTraits; -} // namespace IPC - -#ifdef XP_WIN -// defines TimeStampValue as a complex value keeping both -// GetTickCount and QueryPerformanceCounter values -#include "TimeStamp_windows.h" -#endif - -namespace mozilla { - -#ifndef XP_WIN -typedef uint64_t TimeStampValue; -#endif - -class TimeStamp; - -/** - * Platform-specific implementation details of BaseTimeDuration. - */ -class BaseTimeDurationPlatformUtils -{ -public: - static MFBT_API double ToSeconds(int64_t aTicks); - static MFBT_API double ToSecondsSigDigits(int64_t aTicks); - static MFBT_API int64_t TicksFromMilliseconds(double aMilliseconds); - static MFBT_API int64_t ResolutionInTicks(); -}; - -/** - * Instances of this class represent the length of an interval of time. - * Negative durations are allowed, meaning the end is before the start. - * - * Internally the duration is stored as a int64_t in units of - * PR_TicksPerSecond() when building with NSPR interval timers, or a - * system-dependent unit when building with system clocks. The - * system-dependent unit must be constant, otherwise the semantics of - * this class would be broken. - * - * The ValueCalculator template parameter determines how arithmetic - * operations are performed on the integer count of ticks (mValue). - */ -template -class BaseTimeDuration -{ -public: - // The default duration is 0. - constexpr BaseTimeDuration() : mValue(0) {} - // Allow construction using '0' as the initial value, for readability, - // but no other numbers (so we don't have any implicit unit conversions). - struct _SomethingVeryRandomHere; - MOZ_IMPLICIT BaseTimeDuration(_SomethingVeryRandomHere* aZero) : mValue(0) - { - MOZ_ASSERT(!aZero, "Who's playing funny games here?"); - } - // Default copy-constructor and assignment are OK - - // Converting copy-constructor and assignment operator - template - explicit BaseTimeDuration(const BaseTimeDuration& aOther) - : mValue(aOther.mValue) - { } - - template - BaseTimeDuration& operator=(const BaseTimeDuration& aOther) - { - mValue = aOther.mValue; - return *this; - } - - double ToSeconds() const - { - if (mValue == INT64_MAX) { - return PositiveInfinity(); - } - if (mValue == INT64_MIN) { - return NegativeInfinity(); - } - return BaseTimeDurationPlatformUtils::ToSeconds(mValue); - } - // Return a duration value that includes digits of time we think to - // be significant. This method should be used when displaying a - // time to humans. - double ToSecondsSigDigits() const - { - if (mValue == INT64_MAX) { - return PositiveInfinity(); - } - if (mValue == INT64_MIN) { - return NegativeInfinity(); - } - return BaseTimeDurationPlatformUtils::ToSecondsSigDigits(mValue); - } - double ToMilliseconds() const { return ToSeconds() * 1000.0; } - double ToMicroseconds() const { return ToMilliseconds() * 1000.0; } - - // Using a double here is safe enough; with 53 bits we can represent - // durations up to over 280,000 years exactly. If the units of - // mValue do not allow us to represent durations of that length, - // long durations are clamped to the max/min representable value - // instead of overflowing. - static inline BaseTimeDuration FromSeconds(double aSeconds) - { - return FromMilliseconds(aSeconds * 1000.0); - } - static BaseTimeDuration FromMilliseconds(double aMilliseconds) - { - if (aMilliseconds == PositiveInfinity()) { - return Forever(); - } - if (aMilliseconds == NegativeInfinity()) { - return FromTicks(INT64_MIN); - } - return FromTicks( - BaseTimeDurationPlatformUtils::TicksFromMilliseconds(aMilliseconds)); - } - static inline BaseTimeDuration FromMicroseconds(double aMicroseconds) - { - return FromMilliseconds(aMicroseconds / 1000.0); - } - - static BaseTimeDuration Forever() - { - return FromTicks(INT64_MAX); - } - - BaseTimeDuration operator+(const BaseTimeDuration& aOther) const - { - return FromTicks(ValueCalculator::Add(mValue, aOther.mValue)); - } - BaseTimeDuration operator-(const BaseTimeDuration& aOther) const - { - return FromTicks(ValueCalculator::Subtract(mValue, aOther.mValue)); - } - BaseTimeDuration& operator+=(const BaseTimeDuration& aOther) - { - mValue = ValueCalculator::Add(mValue, aOther.mValue); - return *this; - } - BaseTimeDuration& operator-=(const BaseTimeDuration& aOther) - { - mValue = ValueCalculator::Subtract(mValue, aOther.mValue); - return *this; - } - BaseTimeDuration operator-() const - { - // We don't just use FromTicks(ValueCalculator::Subtract(0, mValue)) - // since that won't give the correct result for -TimeDuration::Forever(). - int64_t ticks; - if (mValue == INT64_MAX) { - ticks = INT64_MIN; - } else if (mValue == INT64_MIN) { - ticks = INT64_MAX; - } else { - ticks = -mValue; - } - - return FromTicks(ticks); - } - -private: - // Block double multiplier (slower, imprecise if long duration) - Bug 853398. - // If required, use MultDouble explicitly and with care. - BaseTimeDuration operator*(const double aMultiplier) const = delete; - - // Block double divisor (for the same reason, and because dividing by - // fractional values would otherwise invoke the int64_t variant, and rounding - // the passed argument can then cause divide-by-zero) - Bug 1147491. - BaseTimeDuration operator/(const double aDivisor) const = delete; - -public: - BaseTimeDuration MultDouble(double aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const int32_t aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const uint32_t aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const int64_t aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const uint64_t aMultiplier) const - { - if (aMultiplier > INT64_MAX) { - return Forever(); - } - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator/(const int64_t aDivisor) const - { - MOZ_ASSERT(aDivisor != 0, "Division by zero"); - return FromTicks(ValueCalculator::Divide(mValue, aDivisor)); - } - double operator/(const BaseTimeDuration& aOther) const - { -#ifndef MOZ_B2G - // Bug 1066388 - This fails on B2G ICS Emulator - MOZ_ASSERT(aOther.mValue != 0, "Division by zero"); -#endif - return ValueCalculator::DivideDouble(mValue, aOther.mValue); - } - BaseTimeDuration operator%(const BaseTimeDuration& aOther) const - { - MOZ_ASSERT(aOther.mValue != 0, "Division by zero"); - return FromTicks(ValueCalculator::Modulo(mValue, aOther.mValue)); - } - - template - bool operator<(const BaseTimeDuration& aOther) const - { - return mValue < aOther.mValue; - } - template - bool operator<=(const BaseTimeDuration& aOther) const - { - return mValue <= aOther.mValue; - } - template - bool operator>=(const BaseTimeDuration& aOther) const - { - return mValue >= aOther.mValue; - } - template - bool operator>(const BaseTimeDuration& aOther) const - { - return mValue > aOther.mValue; - } - template - bool operator==(const BaseTimeDuration& aOther) const - { - return mValue == aOther.mValue; - } - template - bool operator!=(const BaseTimeDuration& aOther) const - { - return mValue != aOther.mValue; - } - bool IsZero() const - { - return mValue == 0; - } - explicit operator bool() const - { - return mValue != 0; - } - - // Return a best guess at the system's current timing resolution, - // which might be variable. BaseTimeDurations below this order of - // magnitude are meaningless, and those at the same order of - // magnitude or just above are suspect. - static BaseTimeDuration Resolution() { - return FromTicks(BaseTimeDurationPlatformUtils::ResolutionInTicks()); - } - - // We could define additional operators here: - // -- convert to/from other time units - // -- scale duration by a float - // but let's do that on demand. - // Comparing durations for equality will only lead to bugs on - // platforms with high-resolution timers. - -private: - friend class TimeStamp; - friend struct IPC::ParamTraits>; - template - friend class BaseTimeDuration; - - static BaseTimeDuration FromTicks(int64_t aTicks) - { - BaseTimeDuration t; - t.mValue = aTicks; - return t; - } - - static BaseTimeDuration FromTicks(double aTicks) - { - // NOTE: this MUST be a >= test, because int64_t(double(INT64_MAX)) - // overflows and gives INT64_MIN. - if (aTicks >= double(INT64_MAX)) { - return FromTicks(INT64_MAX); - } - - // This MUST be a <= test. - if (aTicks <= double(INT64_MIN)) { - return FromTicks(INT64_MIN); - } - - return FromTicks(int64_t(aTicks)); - } - - // Duration, result is implementation-specific difference of two TimeStamps - int64_t mValue; -}; - -/** - * Perform arithmetic operations on the value of a BaseTimeDuration without - * doing strict checks on the range of values. - */ -class TimeDurationValueCalculator -{ -public: - static int64_t Add(int64_t aA, int64_t aB) { return aA + aB; } - static int64_t Subtract(int64_t aA, int64_t aB) { return aA - aB; } - - template - static int64_t Multiply(int64_t aA, T aB) - { - static_assert(IsIntegral::value, - "Using integer multiplication routine with non-integer type." - " Further specialization required"); - return aA * static_cast(aB); - } - - static int64_t Divide(int64_t aA, int64_t aB) { return aA / aB; } - static double DivideDouble(int64_t aA, int64_t aB) - { - return static_cast(aA) / aB; - } - static int64_t Modulo(int64_t aA, int64_t aB) { return aA % aB; } -}; - -template <> -inline int64_t -TimeDurationValueCalculator::Multiply(int64_t aA, double aB) -{ - return static_cast(aA * aB); -} - -/** - * Specialization of BaseTimeDuration that uses TimeDurationValueCalculator for - * arithmetic on the mValue member. - * - * Use this class for time durations that are *not* expected to hold values of - * Forever (or the negative equivalent) or when such time duration are *not* - * expected to be used in arithmetic operations. - */ -typedef BaseTimeDuration TimeDuration; - -/** - * Instances of this class represent moments in time, or a special - * "null" moment. We do not use the non-monotonic system clock or - * local time, since they can be reset, causing apparent backward - * travel in time, which can confuse algorithms. Instead we measure - * elapsed time according to the system. This time can never go - * backwards (i.e. it never wraps around, at least not in less than - * five million years of system elapsed time). It might not advance - * while the system is sleeping. If TimeStamp::SetNow() is not called - * at all for hours or days, we might not notice the passage of some - * of that time. - * - * We deliberately do not expose a way to convert TimeStamps to some - * particular unit. All you can do is compute a difference between two - * TimeStamps to get a TimeDuration. You can also add a TimeDuration - * to a TimeStamp to get a new TimeStamp. You can't do something - * meaningless like add two TimeStamps. - * - * Internally this is implemented as either a wrapper around - * - high-resolution, monotonic, system clocks if they exist on this - * platform - * - PRIntervalTime otherwise. We detect wraparounds of - * PRIntervalTime and work around them. - * - * This class is similar to C++11's time_point, however it is - * explicitly nullable and provides an IsNull() method. time_point - * is initialized to the clock's epoch and provides a - * time_since_epoch() method that functions similiarly. i.e. - * t.IsNull() is equivalent to t.time_since_epoch() == decltype(t)::duration::zero(); - */ -class TimeStamp -{ -public: - /** - * Initialize to the "null" moment - */ - constexpr TimeStamp() : mValue(0) {} - // Default copy-constructor and assignment are OK - - /** - * The system timestamps are the same as the TimeStamp - * retrieved by mozilla::TimeStamp. Since we need this for - * vsync timestamps, we enable the creation of mozilla::TimeStamps - * on platforms that support vsync aligned refresh drivers / compositors - * Verified true as of Jan 31, 2015: B2G and OS X - * False on Windows 7 - * UNTESTED ON OTHER PLATFORMS - */ -#if defined(MOZ_WIDGET_GONK) || defined(XP_DARWIN) - static TimeStamp FromSystemTime(int64_t aSystemTime) - { - static_assert(sizeof(aSystemTime) == sizeof(TimeStampValue), - "System timestamp should be same units as TimeStampValue"); - return TimeStamp(aSystemTime); - } -#endif - - /** - * Return true if this is the "null" moment - */ - bool IsNull() const { return mValue == 0; } - - /** - * Return true if this is not the "null" moment, may be used in tests, e.g.: - * |if (timestamp) { ... }| - */ - explicit operator bool() const - { - return mValue != 0; - } - - /** - * Return a timestamp reflecting the current elapsed system time. This - * is monotonically increasing (i.e., does not decrease) over the - * lifetime of this process' XPCOM session. - * - * Now() is trying to ensure the best possible precision on each platform, - * at least one millisecond. - * - * NowLoRes() has been introduced to workaround performance problems of - * QueryPerformanceCounter on the Windows platform. NowLoRes() is giving - * lower precision, usually 15.6 ms, but with very good performance benefit. - * Use it for measurements of longer times, like >200ms timeouts. - */ - static TimeStamp Now() { return Now(true); } - static TimeStamp NowLoRes() { return Now(false); } - - /** - * Return a timestamp representing the time when the current process was - * created which will be comparable with other timestamps taken with this - * class. If the actual process creation time is detected to be inconsistent - * the @a aIsInconsistent parameter will be set to true, the returned - * timestamp however will still be valid though inaccurate. - * - * @param aIsInconsistent Set to true if an inconsistency was detected in the - * process creation time - * @returns A timestamp representing the time when the process was created, - * this timestamp is always valid even when errors are reported - */ - static MFBT_API TimeStamp ProcessCreation(bool& aIsInconsistent); - - /** - * Records a process restart. After this call ProcessCreation() will return - * the time when the browser was restarted instead of the actual time when - * the process was created. - */ - static MFBT_API void RecordProcessRestart(); - - /** - * Compute the difference between two timestamps. Both must be non-null. - */ - TimeDuration operator-(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - static_assert(-INT64_MAX > INT64_MIN, "int64_t sanity check"); - int64_t ticks = int64_t(mValue - aOther.mValue); - // Check for overflow. - if (mValue > aOther.mValue) { - if (ticks < 0) { - ticks = INT64_MAX; - } - } else { - if (ticks > 0) { - ticks = INT64_MIN; - } - } - return TimeDuration::FromTicks(ticks); - } - - TimeStamp operator+(const TimeDuration& aOther) const - { - TimeStamp result = *this; - result += aOther; - return result; - } - TimeStamp operator-(const TimeDuration& aOther) const - { - TimeStamp result = *this; - result -= aOther; - return result; - } - TimeStamp& operator+=(const TimeDuration& aOther) - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - TimeStampValue value = mValue + aOther.mValue; - // Check for underflow. - // (We don't check for overflow because it's not obvious what the error - // behavior should be in that case.) - if (aOther.mValue < 0 && value > mValue) { - value = 0; - } - mValue = value; - return *this; - } - TimeStamp& operator-=(const TimeDuration& aOther) - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - TimeStampValue value = mValue - aOther.mValue; - // Check for underflow. - // (We don't check for overflow because it's not obvious what the error - // behavior should be in that case.) - if (aOther.mValue > 0 && value > mValue) { - value = 0; - } - mValue = value; - return *this; - } - - bool operator<(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue < aOther.mValue; - } - bool operator<=(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue <= aOther.mValue; - } - bool operator>=(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue >= aOther.mValue; - } - bool operator>(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue > aOther.mValue; - } - bool operator==(const TimeStamp& aOther) const - { - return IsNull() - ? aOther.IsNull() - : !aOther.IsNull() && mValue == aOther.mValue; - } - bool operator!=(const TimeStamp& aOther) const - { - return !(*this == aOther); - } - - // Comparing TimeStamps for equality should be discouraged. Adding - // two TimeStamps, or scaling TimeStamps, is nonsense and must never - // be allowed. - - static MFBT_API void Startup(); - static MFBT_API void Shutdown(); - -private: - friend struct IPC::ParamTraits; - friend void StartupTimelineRecordExternal(int, uint64_t); - - MOZ_IMPLICIT TimeStamp(TimeStampValue aValue) : mValue(aValue) {} - - static MFBT_API TimeStamp Now(bool aHighResolution); - - /** - * Computes the uptime of the current process in microseconds. The result - * is platform-dependent and needs to be checked against existing timestamps - * for consistency. - * - * @returns The number of microseconds since the calling process was started - * or 0 if an error was encountered while computing the uptime - */ - static MFBT_API uint64_t ComputeProcessUptime(); - - /** - * When built with PRIntervalTime, a value of 0 means this instance - * is "null". Otherwise, the low 32 bits represent a PRIntervalTime, - * and the high 32 bits represent a counter of the number of - * rollovers of PRIntervalTime that we've seen. This counter starts - * at 1 to avoid a real time colliding with the "null" value. - * - * PR_INTERVAL_MAX is set at 100,000 ticks per second. So the minimum - * time to wrap around is about 2^64/100000 seconds, i.e. about - * 5,849,424 years. - * - * When using a system clock, a value is system dependent. - */ - TimeStampValue mValue; -}; - -} // namespace mozilla - -#endif /* mozilla_TimeStamp_h */ diff --git a/mac/include/spidermonkey/mozilla/ToString.h b/mac/include/spidermonkey/mozilla/ToString.h deleted file mode 100644 index f11cad5c..00000000 --- a/mac/include/spidermonkey/mozilla/ToString.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Utilities for converting an object to a string representation. */ - -#ifndef mozilla_ToString_h -#define mozilla_ToString_h - -#include -#include - -namespace mozilla { - -/** - * A convenience function for converting an object to a string representation. - * Supports any object which can be streamed to an std::ostream. - */ -template -std::string -ToString(const T& aValue) -{ - std::ostringstream stream; - stream << aValue; - return stream.str(); -} - -} // namespace mozilla - -#endif /* mozilla_ToString_h */ diff --git a/mac/include/spidermonkey/mozilla/Tuple.h b/mac/include/spidermonkey/mozilla/Tuple.h deleted file mode 100644 index a7f9bee6..00000000 --- a/mac/include/spidermonkey/mozilla/Tuple.h +++ /dev/null @@ -1,461 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A variadic tuple class. */ - -#ifndef mozilla_Tuple_h -#define mozilla_Tuple_h - -#include "mozilla/Move.h" -#include "mozilla/Pair.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/TypeTraits.h" - -#include -#include - -namespace mozilla { - -namespace detail { - -/* - * A helper class that allows passing around multiple variadic argument lists - * by grouping them. - */ -template -struct Group; - -/* - * CheckConvertibility checks whether each type in a source pack of types - * is convertible to the corresponding type in a target pack of types. - * - * It is intended to be invoked like this: - * CheckConvertibility, Group> - * 'Group' is used to separate types in the two packs (otherwise if we just - * wrote 'CheckConvertibility -struct CheckConvertibilityImpl; - -template -struct CheckConvertibilityImpl - : FalseType {}; - -template -struct CheckConvertibilityImpl, Group, true> - : IntegralConstant::value...>::value> { }; - -template -struct CheckConvertibility; - -template -struct CheckConvertibility, Group> - : CheckConvertibilityImpl, Group, - sizeof...(SourceTypes) == sizeof...(TargetTypes)> { }; - -/* - * TupleImpl is a helper class used to implement mozilla::Tuple. - * It represents one node in a recursive inheritance hierarchy. - * 'Index' is the 0-based index of the tuple element stored in this node; - * 'Elements...' are the types of the elements stored in this node and its - * base classes. - * - * Example: - * Tuple inherits from - * TupleImpl<0, int, float, char>, which stores the 'int' and inherits from - * TupleImpl<1, float, char>, which stores the 'float' and inherits from - * TupleImpl<2, char>, which stores the 'char' and inherits from - * TupleImpl<3>, which stores nothing and terminates the recursion. - * - * The purpose of the 'Index' parameter is to allow efficient index-based - * access to a tuple element: given a tuple, and an index 'I' that we wish to - * access, we can cast the tuple to the base which stores the I'th element - * by performing template argument deduction against 'TupleImpl', - * where 'I' is specified explicitly and 'E...' is deduced (this is what the - * non-member 'Get(t)' function does). - * - * This implementation strategy is borrowed from libstdc++'s std::tuple - * implementation. - */ -template -struct TupleImpl; - -/* - * The base case of the inheritance recursion (and also the implementation - * of an empty tuple). - */ -template -struct TupleImpl { - bool operator==(const TupleImpl& aOther) const - { - return true; - } -}; - -/* - * One node of the recursive inheritance hierarchy. It stores the element at - * index 'Index' of a tuple, of type 'HeadT', and inherits from the nodes - * that store the remaining elements, of types 'TailT...'. - */ -template -struct TupleImpl - : public TupleImpl -{ - typedef TupleImpl Base; - - // Accessors for the head and the tail. - // These are static, because the intended usage is for the caller to, - // given a tuple, obtain the type B of the base class which stores the - // element of interest, and then call B::Head(tuple) to access it. - // (Tail() is mostly for internal use, but is exposed for consistency.) - static HeadT& Head(TupleImpl& aTuple) { return aTuple.mHead; } - static const HeadT& Head(const TupleImpl& aTuple) { return aTuple.mHead; } - static Base& Tail(TupleImpl& aTuple) { return aTuple; } - static const Base& Tail(const TupleImpl& aTuple) { return aTuple; } - - TupleImpl() : Base(), mHead() { } - - // Construct from const references to the elements. - explicit TupleImpl(const HeadT& aHead, const TailT&... aTail) - : Base(aTail...), mHead(aHead) { } - - // Construct from objects that are convertible to the elements. - // This constructor is enabled only when the argument types are actually - // convertible to the element types, otherwise it could become a better - // match for certain invocations than the copy constructor. - template , - Group>::value>::Type> - explicit TupleImpl(OtherHeadT&& aHead, OtherTailT&&... aTail) - : Base(Forward(aTail)...), mHead(Forward(aHead)) { } - - // Copy and move constructors. - // We'd like to use '= default' to implement these, but MSVC 2013's support - // for '= default' is incomplete and this doesn't work. - TupleImpl(const TupleImpl& aOther) - : Base(Tail(aOther)) - , mHead(Head(aOther)) {} - TupleImpl(TupleImpl&& aOther) - : Base(Move(Tail(aOther))) - , mHead(Forward(Head(aOther))) {} - - // Assign from a tuple whose elements are convertible to the elements - // of this tuple. - template ::Type> - TupleImpl& operator=(const TupleImpl& aOther) - { - typedef TupleImpl OtherT; - Head(*this) = OtherT::Head(aOther); - Tail(*this) = OtherT::Tail(aOther); - return *this; - } - template ::Type> - TupleImpl& operator=(TupleImpl&& aOther) - { - typedef TupleImpl OtherT; - Head(*this) = Move(OtherT::Head(aOther)); - Tail(*this) = Move(OtherT::Tail(aOther)); - return *this; - } - - // Copy and move assignment operators. - TupleImpl& operator=(const TupleImpl& aOther) - { - Head(*this) = Head(aOther); - Tail(*this) = Tail(aOther); - return *this; - } - TupleImpl& operator=(TupleImpl&& aOther) - { - Head(*this) = Move(Head(aOther)); - Tail(*this) = Move(Tail(aOther)); - return *this; - } - bool operator==(const TupleImpl& aOther) const - { - return Head(*this) == Head(aOther) && Tail(*this) == Tail(aOther); - } -private: - HeadT mHead; // The element stored at this index in the tuple. -}; - -} // namespace detail - -/** - * Tuple is a class that stores zero or more objects, whose types are specified - * as template parameters. It can be thought of as a generalization of Pair, - * (which can be thought of as a 2-tuple). - * - * Tuple allows index-based access to its elements (with the index having to be - * known at compile time) via the non-member function 'Get(tuple)'. - */ -template -class Tuple : public detail::TupleImpl<0, Elements...> -{ - typedef detail::TupleImpl<0, Elements...> Impl; -public: - // The constructors and assignment operators here are simple wrappers - // around those in TupleImpl. - - Tuple() : Impl() { } - explicit Tuple(const Elements&... aElements) : Impl(aElements...) { } - // Here, we can't just use 'typename... OtherElements' because MSVC will give - // a warning "C4520: multiple default constructors specified" (even if no one - // actually instantiates the constructor with an empty parameter pack - - // that's probably a bug) and we compile with warnings-as-errors. - template , - detail::Group>::value>::Type> - explicit Tuple(OtherHead&& aHead, OtherTail&&... aTail) - : Impl(Forward(aHead), Forward(aTail)...) { } - Tuple(const Tuple& aOther) : Impl(aOther) { } - Tuple(Tuple&& aOther) : Impl(Move(aOther)) { } - - template ::Type> - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - template ::Type> - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - bool operator==(const Tuple& aOther) const - { - return static_cast(*this) == static_cast(aOther); - } -}; - -/** - * Specialization of Tuple for two elements. - * This is created to support construction and assignment from a Pair or std::pair. - */ -template -class Tuple : public detail::TupleImpl<0, A, B> -{ - typedef detail::TupleImpl<0, A, B> Impl; - -public: - // The constructors and assignment operators here are simple wrappers - // around those in TupleImpl. - - Tuple() : Impl() { } - explicit Tuple(const A& aA, const B& aB) : Impl(aA, aB) { } - template , - detail::Group>::value>::Type> - explicit Tuple(AArg&& aA, BArg&& aB) - : Impl(Forward(aA), Forward(aB)) { } - Tuple(const Tuple& aOther) : Impl(aOther) { } - Tuple(Tuple&& aOther) : Impl(Move(aOther)) { } - explicit Tuple(const Pair& aOther) - : Impl(aOther.first(), aOther.second()) { } - explicit Tuple(Pair&& aOther) : Impl(Forward(aOther.first()), - Forward(aOther.second())) { } - explicit Tuple(const std::pair& aOther) - : Impl(aOther.first, aOther.second) { } - explicit Tuple(std::pair&& aOther) : Impl(Forward(aOther.first), - Forward(aOther.second)) { } - - template - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - template - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - template - Tuple& operator=(const Pair& aOther) - { - Impl::Head(*this) = aOther.first(); - Impl::Tail(*this).Head(*this) = aOther.second(); - return *this; - } - template - Tuple& operator=(Pair&& aOther) - { - Impl::Head(*this) = Forward(aOther.first()); - Impl::Tail(*this).Head(*this) = Forward(aOther.second()); - return *this; - } - template - Tuple& operator=(const std::pair& aOther) - { - Impl::Head(*this) = aOther.first; - Impl::Tail(*this).Head(*this) = aOther.second; - return *this; - } - template - Tuple& operator=(std::pair&& aOther) - { - Impl::Head(*this) = Forward(aOther.first); - Impl::Tail(*this).Head(*this) = Forward(aOther.second); - return *this; - } -}; - -/** - * Specialization of Tuple for zero arguments. - * This is necessary because if the primary template were instantiated with - * an empty parameter pack, the 'Tuple(Elements...)' constructors would - * become illegal overloads of the default constructor. - */ -template <> -class Tuple<> {}; - -namespace detail { - -/* - * Helper functions for implementing Get(tuple). - * These functions take a TupleImpl, with Index being - * explicitly specified, and Elements being deduced. By passing a Tuple - * object as argument, template argument deduction will do its magic and - * cast the tuple to the base class which stores the element at Index. - */ - -// Const reference version. -template -auto TupleGetHelper(TupleImpl& aTuple) - -> decltype(TupleImpl::Head(aTuple)) -{ - return TupleImpl::Head(aTuple); -} - -// Non-const reference version. -template -auto TupleGetHelper(const TupleImpl& aTuple) - -> decltype(TupleImpl::Head(aTuple)) -{ - return TupleImpl::Head(aTuple); -} - -} // namespace detail - -/** - * Index-based access to an element of a tuple. - * The syntax is Get(tuple). The index is zero-based. - * - * Example: - * - * Tuple t; - * ... - * float f = Get<1>(t); - */ - -// Non-const reference version. -template -auto Get(Tuple& aTuple) - -> decltype(detail::TupleGetHelper(aTuple)) -{ - return detail::TupleGetHelper(aTuple); -} - -// Const reference version. -template -auto Get(const Tuple& aTuple) - -> decltype(detail::TupleGetHelper(aTuple)) -{ - return detail::TupleGetHelper(aTuple); -} - -// Rvalue reference version. -template -auto Get(Tuple&& aTuple) - -> decltype(Move(mozilla::Get(aTuple))) -{ - // We need a 'mozilla::' qualification here to avoid - // name lookup only finding the current function. - return Move(mozilla::Get(aTuple)); -} - -/** - * A convenience function for constructing a tuple out of a sequence of - * values without specifying the type of the tuple. - * The type of the tuple is deduced from the types of its elements. - * - * Example: - * - * auto tuple = MakeTuple(42, 0.5f, 'c'); // has type Tuple - */ -template -inline Tuple::Type...> -MakeTuple(Elements&&... aElements) -{ - return Tuple::Type...>(Forward(aElements)...); -} - -/** - * A convenience function for constructing a tuple of references to a - * sequence of variables. Since assignments to the elements of the tuple - * "go through" to the referenced variables, this can be used to "unpack" - * a tuple into individual variables. - * - * Example: - * - * int i; - * float f; - * char c; - * Tie(i, f, c) = FunctionThatReturnsATuple(); - */ -template -inline Tuple -Tie(Elements&... aVariables) -{ - return Tuple(aVariables...); -} - -} // namespace mozilla - -#endif /* mozilla_Tuple_h */ diff --git a/mac/include/spidermonkey/mozilla/TypeTraits.h b/mac/include/spidermonkey/mozilla/TypeTraits.h deleted file mode 100644 index 084f608c..00000000 --- a/mac/include/spidermonkey/mozilla/TypeTraits.h +++ /dev/null @@ -1,1262 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Template-based metaprogramming and type-testing facilities. */ - -#ifndef mozilla_TypeTraits_h -#define mozilla_TypeTraits_h - -#include "mozilla/Types.h" - -/* - * These traits are approximate copies of the traits and semantics from C++11's - * header. Don't add traits not in that header! When all - * platforms provide that header, we can convert all users and remove this one. - */ - -#include - -namespace mozilla { - -/* Forward declarations. */ - -template struct RemoveCV; -template struct AddRvalueReference; - -/* 20.2.4 Function template declval [declval] */ - -/** - * DeclVal simplifies the definition of expressions which occur as unevaluated - * operands. It converts T to a reference type, making it possible to use in - * decltype expressions even if T does not have a default constructor, e.g.: - * decltype(DeclVal().foo()) - */ -template -typename AddRvalueReference::Type DeclVal(); - -/* 20.9.3 Helper classes [meta.help] */ - -/** - * Helper class used as a base for various type traits, exposed publicly - * because exposes it as well. - */ -template -struct IntegralConstant -{ - static const T value = Value; - typedef T ValueType; - typedef IntegralConstant Type; -}; - -/** Convenient aliases. */ -typedef IntegralConstant TrueType; -typedef IntegralConstant FalseType; - -/* 20.9.4 Unary type traits [meta.unary] */ - -/* 20.9.4.1 Primary type categories [meta.unary.cat] */ - -namespace detail { - -template -struct IsVoidHelper : FalseType {}; - -template<> -struct IsVoidHelper : TrueType {}; - -} // namespace detail - -/** - * IsVoid determines whether a type is void. - * - * mozilla::IsVoid::value is false; - * mozilla::IsVoid::value is true; - * mozilla::IsVoid::value is false; - * mozilla::IsVoid::value is true. - */ -template -struct IsVoid : detail::IsVoidHelper::Type> {}; - -namespace detail { - -template -struct IsIntegralHelper : FalseType {}; - -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; - -} /* namespace detail */ - -/** - * IsIntegral determines whether a type is an integral type. - * - * mozilla::IsIntegral::value is true; - * mozilla::IsIntegral::value is true; - * mozilla::IsIntegral::value is true; - * mozilla::IsIntegral::value is false; - * mozilla::IsIntegral::value is false; - */ -template -struct IsIntegral : detail::IsIntegralHelper::Type> -{}; - -template -struct IsSame; - -namespace detail { - -template -struct IsFloatingPointHelper - : IntegralConstant::value || - IsSame::value || - IsSame::value> -{}; - -} // namespace detail - -/** - * IsFloatingPoint determines whether a type is a floating point type (float, - * double, long double). - * - * mozilla::IsFloatingPoint::value is false; - * mozilla::IsFloatingPoint::value is true; - * mozilla::IsFloatingPoint::value is true; - * mozilla::IsFloatingPoint::value is false. - */ -template -struct IsFloatingPoint - : detail::IsFloatingPointHelper::Type> -{}; - -namespace detail { - -template -struct IsArrayHelper : FalseType {}; - -template -struct IsArrayHelper : TrueType {}; - -template -struct IsArrayHelper : TrueType {}; - -} // namespace detail - -/** - * IsArray determines whether a type is an array type, of known or unknown - * length. - * - * mozilla::IsArray::value is false; - * mozilla::IsArray::value is true; - * mozilla::IsArray::value is true. - */ -template -struct IsArray : detail::IsArrayHelper::Type> -{}; - -namespace detail { - -template -struct IsFunPtr; - -template -struct IsFunPtr - : public FalseType -{}; - -template -struct IsFunPtr - : public TrueType -{}; - -}; // namespace detail - -/** - * IsFunction determines whether a type is a function type. Function pointers - * don't qualify here--only the type of an actual function symbol. We do not - * correctly handle varags function types because of a bug in MSVC. - * - * Given the function: - * void f(int) {} - * - * mozilla::IsFunction is true; - * mozilla::IsFunction is false; - * mozilla::IsFunction is true. - */ -template -struct IsFunction - : public detail::IsFunPtr::Type *> -{}; - -namespace detail { - -template -struct IsPointerHelper : FalseType {}; - -template -struct IsPointerHelper : TrueType {}; - -} // namespace detail - -/** - * IsPointer determines whether a type is a possibly-CV-qualified pointer type - * (but not a pointer-to-member type). - * - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is false; - * mozilla::IsPointer::value is false. - * mozilla::IsPointer::value is false - */ -template -struct IsPointer : detail::IsPointerHelper::Type> -{}; - -/** - * IsLvalueReference determines whether a type is an lvalue reference. - * - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is true; - * mozilla::IsLvalueReference::value is false. - */ -template -struct IsLvalueReference : FalseType {}; - -template -struct IsLvalueReference : TrueType {}; - -/** - * IsRvalueReference determines whether a type is an rvalue reference. - * - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is true. - */ -template -struct IsRvalueReference : FalseType {}; - -template -struct IsRvalueReference : TrueType {}; - -namespace detail { - -// __is_enum is a supported extension across all of our supported compilers. -template -struct IsEnumHelper - : IntegralConstant -{}; - -} // namespace detail - -/** - * IsEnum determines whether a type is an enum type. - * - * mozilla::IsEnum::value is true; - * mozilla::IsEnum::value is false; - * mozilla::IsEnum::value is false; - */ -template -struct IsEnum - : detail::IsEnumHelper::Type> -{}; - -namespace detail { - -// __is_class is a supported extension across all of our supported compilers: -// http://llvm.org/releases/3.0/docs/ClangReleaseNotes.html -// http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Type-Traits.html#Type-Traits -// http://msdn.microsoft.com/en-us/library/ms177194%28v=vs.100%29.aspx -template -struct IsClassHelper - : IntegralConstant -{}; - -} // namespace detail - -/** - * IsClass determines whether a type is a class type (but not a union). - * - * struct S {}; - * union U {}; - * mozilla::IsClass::value is false; - * mozilla::IsClass::value is true; - * mozilla::IsClass::value is false; - */ -template -struct IsClass - : detail::IsClassHelper::Type> -{}; - -/* 20.9.4.2 Composite type traits [meta.unary.comp] */ - -/** - * IsReference determines whether a type is an lvalue or rvalue reference. - * - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is true. - */ -template -struct IsReference - : IntegralConstant::value || IsRvalueReference::value> -{}; - -/** - * IsArithmetic determines whether a type is arithmetic. A type is arithmetic - * iff it is an integral type or a floating point type. - * - * mozilla::IsArithmetic::value is true; - * mozilla::IsArithmetic::value is true; - * mozilla::IsArithmetic::value is false. - */ -template -struct IsArithmetic - : IntegralConstant::value || IsFloatingPoint::value> -{}; - -namespace detail { - -template -struct IsMemberPointerHelper : FalseType {}; - -template -struct IsMemberPointerHelper : TrueType {}; - -} // namespace detail - -/** - * IsMemberPointer determines whether a type is pointer to non-static member - * object or a pointer to non-static member function. - * - * mozilla::IsMemberPointer::value is true - * mozilla::IsMemberPointer::value is false - */ -template -struct IsMemberPointer - : detail::IsMemberPointerHelper::Type> -{}; - -/** - * IsScalar determines whether a type is a scalar type. - * - * mozilla::IsScalar::value is true - * mozilla::IsScalar::value is true - * mozilla::IsScalar::value is false - */ -template -struct IsScalar - : IntegralConstant::value || IsEnum::value || - IsPointer::value || IsMemberPointer::value> -{}; - -/* 20.9.4.3 Type properties [meta.unary.prop] */ - -/** - * IsConst determines whether a type is const or not. - * - * mozilla::IsConst::value is false; - * mozilla::IsConst::value is true; - * mozilla::IsConst::value is false. - */ -template -struct IsConst : FalseType {}; - -template -struct IsConst : TrueType {}; - -/** - * IsVolatile determines whether a type is volatile or not. - * - * mozilla::IsVolatile::value is false; - * mozilla::IsVolatile::value is true; - * mozilla::IsVolatile::value is false. - */ -template -struct IsVolatile : FalseType {}; - -template -struct IsVolatile : TrueType {}; - -/** - * Traits class for identifying POD types. Until C++11 there's no automatic - * way to detect PODs, so for the moment this is done manually. Users may - * define specializations of this class that inherit from mozilla::TrueType and - * mozilla::FalseType (or equivalently mozilla::IntegralConstant, or conveniently from mozilla::IsPod for composite types) as needed to - * ensure correct IsPod behavior. - */ -template -struct IsPod : public FalseType {}; - -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template struct IsPod : TrueType {}; - -namespace detail { - -// __is_empty is a supported extension across all of our supported compilers: -// http://llvm.org/releases/3.0/docs/ClangReleaseNotes.html -// http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Type-Traits.html#Type-Traits -// http://msdn.microsoft.com/en-us/library/ms177194%28v=vs.100%29.aspx -template -struct IsEmptyHelper - : IntegralConstant::value && __is_empty(T)> -{}; - -} // namespace detail - -/** - * IsEmpty determines whether a type is a class (but not a union) that is empty. - * - * A class is empty iff it and all its base classes have no non-static data - * members (except bit-fields of length 0) and no virtual member functions, and - * no base class is empty or a virtual base class. - * - * Intuitively, empty classes don't have any data that has to be stored in - * instances of those classes. (The size of the class must still be non-zero, - * because distinct array elements of any type must have different addresses. - * However, if the Empty Base Optimization is implemented by the compiler [most - * compilers implement it, and in certain cases C++11 requires it], the size of - * a class inheriting from an empty |Base| class need not be inflated by - * |sizeof(Base)|.) And intuitively, non-empty classes have data members and/or - * vtable pointers that must be stored in each instance for proper behavior. - * - * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); - * union U1 { int x; }; - * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); - * struct E1 {}; - * struct E2 { int : 0 }; - * struct E3 : E1 {}; - * struct E4 : E2 {}; - * static_assert(mozilla::IsEmpty::value && - * mozilla::IsEmpty::value && - * mozilla::IsEmpty::value && - * mozilla::IsEmpty::value, - * "all empty"); - * union U2 { E1 e1; }; - * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); - * struct NE1 { int x; }; - * struct NE2 : virtual E1 {}; - * struct NE3 : E2 { virtual ~NE3() {} }; - * struct NE4 { virtual void f() {} }; - * static_assert(!mozilla::IsEmpty::value && - * !mozilla::IsEmpty::value && - * !mozilla::IsEmpty::value && - * !mozilla::IsEmpty::value, - * "all empty"); - */ -template -struct IsEmpty : detail::IsEmptyHelper::Type> -{}; - - -namespace detail { - -template::value, - bool = IsIntegral::value, - typename NoCV = typename RemoveCV::Type> -struct IsSignedHelper; - -// Floating point is signed. -template -struct IsSignedHelper : TrueType {}; - -// Integral is conditionally signed. -template -struct IsSignedHelper - : IntegralConstant -{}; - -// Non-floating point, non-integral is not signed. -template -struct IsSignedHelper : FalseType {}; - -} // namespace detail - -/** - * IsSigned determines whether a type is a signed arithmetic type. |char| is - * considered a signed type if it has the same representation as |signed char|. - * - * mozilla::IsSigned::value is true; - * mozilla::IsSigned::value is false; - * mozilla::IsSigned::value is false; - * mozilla::IsSigned::value is true. - */ -template -struct IsSigned : detail::IsSignedHelper {}; - -namespace detail { - -template::value, - bool = IsIntegral::value, - typename NoCV = typename RemoveCV::Type> -struct IsUnsignedHelper; - -// Floating point is not unsigned. -template -struct IsUnsignedHelper : FalseType {}; - -// Integral is conditionally unsigned. -template -struct IsUnsignedHelper - : IntegralConstant::value || bool(NoCV(1) < NoCV(-1)))> -{}; - -// Non-floating point, non-integral is not unsigned. -template -struct IsUnsignedHelper : FalseType {}; - -} // namespace detail - -/** - * IsUnsigned determines whether a type is an unsigned arithmetic type. - * - * mozilla::IsUnsigned::value is false; - * mozilla::IsUnsigned::value is true; - * mozilla::IsUnsigned::value is true; - * mozilla::IsUnsigned::value is false. - */ -template -struct IsUnsigned : detail::IsUnsignedHelper {}; - -namespace detail { - -struct DoIsDestructibleImpl -{ - template().~T())> - static TrueType test(int); - template - static FalseType test(...); -}; - -template -struct IsDestructibleImpl : public DoIsDestructibleImpl -{ - typedef decltype(test(0)) Type; -}; - -} // namespace detail - -template -struct IsDestructible : public detail::IsDestructibleImpl::Type {}; - -/* 20.9.5 Type property queries [meta.unary.prop.query] */ - -/* 20.9.6 Relationships between types [meta.rel] */ - -/** - * IsSame tests whether two types are the same type. - * - * mozilla::IsSame::value is true; - * mozilla::IsSame::value is true; - * mozilla::IsSame::value is false; - * mozilla::IsSame::value is true; - * mozilla::IsSame::value is false; - * mozilla::IsSame::value is true. - */ -template -struct IsSame : FalseType {}; - -template -struct IsSame : TrueType {}; - -namespace detail { - -#if defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) - -template -struct BaseOfTester : IntegralConstant {}; - -#else - -// The trickery used to implement IsBaseOf here makes it possible to use it for -// the cases of private and multiple inheritance. This code was inspired by the -// sample code here: -// -// http://stackoverflow.com/questions/2910979/how-is-base-of-works -template -struct BaseOfHelper -{ -public: - operator Base*() const; - operator Derived*(); -}; - -template -struct BaseOfTester -{ -private: - template - static char test(Derived*, T); - static int test(Base*, int); - -public: - static const bool value = - sizeof(test(BaseOfHelper(), int())) == sizeof(char); -}; - -template -struct BaseOfTester -{ -private: - template - static char test(Derived*, T); - static int test(Base*, int); - -public: - static const bool value = - sizeof(test(BaseOfHelper(), int())) == sizeof(char); -}; - -template -struct BaseOfTester : FalseType {}; - -template -struct BaseOfTester : TrueType {}; - -template -struct BaseOfTester : TrueType {}; - -#endif - -} /* namespace detail */ - -/* - * IsBaseOf allows to know whether a given class is derived from another. - * - * Consider the following class definitions: - * - * class A {}; - * class B : public A {}; - * class C {}; - * - * mozilla::IsBaseOf::value is true; - * mozilla::IsBaseOf::value is false; - */ -template -struct IsBaseOf - : IntegralConstant::value> -{}; - -namespace detail { - -template -struct ConvertibleTester -{ -private: - template - static char test_helper(To1); - - template - static decltype(test_helper(DeclVal())) test(int); - - template - static int test(...); - -public: - static const bool value = - sizeof(test(0)) == sizeof(char); -}; - -} // namespace detail - -/** - * IsConvertible determines whether a value of type From will implicitly convert - * to a value of type To. For example: - * - * struct A {}; - * struct B : public A {}; - * struct C {}; - * - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is false; - * mozilla::IsConvertible::value is false; - * mozilla::IsConvertible::value is false; - * mozilla::IsConvertible::value is false. - * - * For obscure reasons, you can't use IsConvertible when the types being tested - * are related through private inheritance, and you'll get a compile error if - * you try. Just don't do it! - * - * Note - we need special handling for void, which ConvertibleTester doesn't - * handle. The void handling here doesn't handle const/volatile void correctly, - * which could be easily fixed if the need arises. - */ -template -struct IsConvertible - : IntegralConstant::value> -{}; - -template -struct IsConvertible - : IntegralConstant::value> -{}; - -template -struct IsConvertible - : IntegralConstant::value> -{}; - -template<> -struct IsConvertible - : TrueType -{}; - -/* 20.9.7 Transformations between types [meta.trans] */ - -/* 20.9.7.1 Const-volatile modifications [meta.trans.cv] */ - -/** - * RemoveConst removes top-level const qualifications on a type. - * - * mozilla::RemoveConst::Type is int; - * mozilla::RemoveConst::Type is int; - * mozilla::RemoveConst::Type is const int*; - * mozilla::RemoveConst::Type is int*. - */ -template -struct RemoveConst -{ - typedef T Type; -}; - -template -struct RemoveConst -{ - typedef T Type; -}; - -/** - * RemoveVolatile removes top-level volatile qualifications on a type. - * - * mozilla::RemoveVolatile::Type is int; - * mozilla::RemoveVolatile::Type is int; - * mozilla::RemoveVolatile::Type is volatile int*; - * mozilla::RemoveVolatile::Type is int*. - */ -template -struct RemoveVolatile -{ - typedef T Type; -}; - -template -struct RemoveVolatile -{ - typedef T Type; -}; - -/** - * RemoveCV removes top-level const and volatile qualifications on a type. - * - * mozilla::RemoveCV::Type is int; - * mozilla::RemoveCV::Type is int; - * mozilla::RemoveCV::Type is int; - * mozilla::RemoveCV::Type is int*. - */ -template -struct RemoveCV -{ - typedef typename RemoveConst::Type>::Type Type; -}; - -/* 20.9.7.2 Reference modifications [meta.trans.ref] */ - -/** - * Converts reference types to the underlying types. - * - * mozilla::RemoveReference::Type is T; - * mozilla::RemoveReference::Type is T; - * mozilla::RemoveReference::Type is T; - */ - -template -struct RemoveReference -{ - typedef T Type; -}; - -template -struct RemoveReference -{ - typedef T Type; -}; - -template -struct RemoveReference -{ - typedef T Type; -}; - -template -struct Conditional; - -namespace detail { - -enum Voidness { TIsVoid, TIsNotVoid }; - -template::value ? TIsVoid : TIsNotVoid> -struct AddLvalueReferenceHelper; - -template -struct AddLvalueReferenceHelper -{ - typedef void Type; -}; - -template -struct AddLvalueReferenceHelper -{ - typedef T& Type; -}; - -} // namespace detail - -/** - * AddLvalueReference adds an lvalue & reference to T if one isn't already - * present. (Note: adding an lvalue reference to an rvalue && reference in - * essence replaces the && with a &&, per C+11 reference collapsing rules. For - * example, int&& would become int&.) - * - * The final computed type will only *not* be an lvalue reference if T is void. - * - * mozilla::AddLvalueReference::Type is int&; - * mozilla::AddLvalueRference::Type is volatile int&; - * mozilla::AddLvalueReference::Type is void*&; - * mozilla::AddLvalueReference::Type is void; - * mozilla::AddLvalueReference::Type is struct S&. - */ -template -struct AddLvalueReference - : detail::AddLvalueReferenceHelper -{}; - -namespace detail { - -template::value ? TIsVoid : TIsNotVoid> -struct AddRvalueReferenceHelper; - -template -struct AddRvalueReferenceHelper -{ - typedef void Type; -}; - -template -struct AddRvalueReferenceHelper -{ - typedef T&& Type; -}; - -} // namespace detail - -/** - * AddRvalueReference adds an rvalue && reference to T if one isn't already - * present. (Note: adding an rvalue reference to an lvalue & reference in - * essence keeps the &, per C+11 reference collapsing rules. For example, - * int& would remain int&.) - * - * The final computed type will only *not* be a reference if T is void. - * - * mozilla::AddRvalueReference::Type is int&&; - * mozilla::AddRvalueRference::Type is volatile int&; - * mozilla::AddRvalueRference::Type is const int&&; - * mozilla::AddRvalueReference::Type is void*&&; - * mozilla::AddRvalueReference::Type is void; - * mozilla::AddRvalueReference::Type is struct S&. - */ -template -struct AddRvalueReference - : detail::AddRvalueReferenceHelper -{}; - -/* 20.9.7.3 Sign modifications [meta.trans.sign] */ - -template -struct EnableIf; - -namespace detail { - -template -struct WithC : Conditional -{}; - -template -struct WithV : Conditional -{}; - - -template -struct WithCV : WithC::Type> -{}; - -template -struct CorrespondingSigned; - -template<> -struct CorrespondingSigned { typedef signed char Type; }; -template<> -struct CorrespondingSigned { typedef signed char Type; }; -template<> -struct CorrespondingSigned { typedef short Type; }; -template<> -struct CorrespondingSigned { typedef int Type; }; -template<> -struct CorrespondingSigned { typedef long Type; }; -template<> -struct CorrespondingSigned { typedef long long Type; }; - -template::Type, - bool IsSignedIntegerType = IsSigned::value && - !IsSame::value> -struct MakeSigned; - -template -struct MakeSigned -{ - typedef T Type; -}; - -template -struct MakeSigned - : WithCV::value, IsVolatile::value, - typename CorrespondingSigned::Type> -{}; - -} // namespace detail - -/** - * MakeSigned produces the corresponding signed integer type for a given - * integral type T, with the const/volatile qualifiers of T. T must be a - * possibly-const/volatile-qualified integral type that isn't bool. - * - * If T is already a signed integer type (not including char!), then T is - * produced. - * - * Otherwise, if T is an unsigned integer type, the signed variety of T, with - * T's const/volatile qualifiers, is produced. - * - * Otherwise, the integral type of the same size as T, with the lowest rank, - * with T's const/volatile qualifiers, is produced. (This basically only acts - * to produce signed char when T = char.) - * - * mozilla::MakeSigned::Type is signed long; - * mozilla::MakeSigned::Type is volatile int; - * mozilla::MakeSigned::Type is const signed short; - * mozilla::MakeSigned::Type is const signed char; - * mozilla::MakeSigned is an error; - * mozilla::MakeSigned is an error. - */ -template -struct MakeSigned - : EnableIf::value && - !IsSame::Type>::value, - typename detail::MakeSigned - >::Type -{}; - -namespace detail { - -template -struct CorrespondingUnsigned; - -template<> -struct CorrespondingUnsigned { typedef unsigned char Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned char Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned short Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned int Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned long Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned long long Type; }; - - -template::Type, - bool IsUnsignedIntegerType = IsUnsigned::value && - !IsSame::value> -struct MakeUnsigned; - -template -struct MakeUnsigned -{ - typedef T Type; -}; - -template -struct MakeUnsigned - : WithCV::value, IsVolatile::value, - typename CorrespondingUnsigned::Type> -{}; - -} // namespace detail - -/** - * MakeUnsigned produces the corresponding unsigned integer type for a given - * integral type T, with the const/volatile qualifiers of T. T must be a - * possibly-const/volatile-qualified integral type that isn't bool. - * - * If T is already an unsigned integer type (not including char!), then T is - * produced. - * - * Otherwise, if T is an signed integer type, the unsigned variety of T, with - * T's const/volatile qualifiers, is produced. - * - * Otherwise, the unsigned integral type of the same size as T, with the lowest - * rank, with T's const/volatile qualifiers, is produced. (This basically only - * acts to produce unsigned char when T = char.) - * - * mozilla::MakeUnsigned::Type is unsigned long; - * mozilla::MakeUnsigned::Type is volatile unsigned int; - * mozilla::MakeUnsigned::Type is const unsigned short; - * mozilla::MakeUnsigned::Type is const unsigned char; - * mozilla::MakeUnsigned is an error; - * mozilla::MakeUnsigned is an error. - */ -template -struct MakeUnsigned - : EnableIf::value && - !IsSame::Type>::value, - typename detail::MakeUnsigned - >::Type -{}; - -/* 20.9.7.4 Array modifications [meta.trans.arr] */ - -/** - * RemoveExtent produces either the type of the elements of the array T, or T - * itself. - * - * mozilla::RemoveExtent::Type is int; - * mozilla::RemoveExtent::Type is const int; - * mozilla::RemoveExtent::Type is volatile int; - * mozilla::RemoveExtent::Type is long[17]. - */ -template -struct RemoveExtent -{ - typedef T Type; -}; - -template -struct RemoveExtent -{ - typedef T Type; -}; - -template -struct RemoveExtent -{ - typedef T Type; -}; - -/* 20.9.7.5 Pointer modifications [meta.trans.ptr] */ - -namespace detail { - -template -struct RemovePointerHelper -{ - typedef T Type; -}; - -template -struct RemovePointerHelper -{ - typedef Pointee Type; -}; - -} // namespace detail - -/** - * Produces the pointed-to type if a pointer is provided, else returns the input - * type. Note that this does not dereference pointer-to-member pointers. - * - * struct S { bool m; void f(); }; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is const long; - * mozilla::RemovePointer::Type is void; - * mozilla::RemovePointer::Type is void (S::*)(); - * mozilla::RemovePointer::Type is void(); - * mozilla::RemovePointer::Type is bool S::*. - */ -template -struct RemovePointer - : detail::RemovePointerHelper::Type> -{}; - -/** - * Converts T& to T*. Otherwise returns T* given T. Note that C++17 wants - * std::add_pointer to work differently for function types. We don't implement - * that behavior here. - * - * mozilla::AddPointer is int*; - * mozilla::AddPointer is int**; - * mozilla::AddPointer is int*; - * mozilla::AddPointer is int** const. - */ -template -struct AddPointer -{ - typedef typename RemoveReference::Type* Type; -}; - -/* 20.9.7.6 Other transformations [meta.trans.other] */ - -/** - * EnableIf is a struct containing a typedef of T if and only if B is true. - * - * mozilla::EnableIf::Type is int; - * mozilla::EnableIf::Type is a compile-time error. - * - * Use this template to implement SFINAE-style (Substitution Failure Is not An - * Error) requirements. For example, you might use it to impose a restriction - * on a template parameter: - * - * template - * class PodVector // vector optimized to store POD (memcpy-able) types - * { - * EnableIf::value, T>::Type* vector; - * size_t length; - * ... - * }; - */ -template -struct EnableIf -{}; - -template -struct EnableIf -{ - typedef T Type; -}; - -/** - * Conditional selects a class between two, depending on a given boolean value. - * - * mozilla::Conditional::Type is A; - * mozilla::Conditional::Type is B; - */ -template -struct Conditional -{ - typedef A Type; -}; - -template -struct Conditional -{ - typedef B Type; -}; - -namespace detail { - -template::value, - bool IsFunction = IsFunction::value> -struct DecaySelector; - -template -struct DecaySelector -{ - typedef typename RemoveCV::Type Type; -}; - -template -struct DecaySelector -{ - typedef typename RemoveExtent::Type* Type; -}; - -template -struct DecaySelector -{ - typedef typename AddPointer::Type Type; -}; - -}; // namespace detail - -/** - * Strips const/volatile off a type and decays it from an lvalue to an - * rvalue. So function types are converted to function pointers, arrays to - * pointers, and references are removed. - * - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int* - * mozilla::Decay::Type is int(*)(int) - */ -template -class Decay - : public detail::DecaySelector::Type> -{ -}; - -} /* namespace mozilla */ - -#endif /* mozilla_TypeTraits_h */ diff --git a/mac/include/spidermonkey/mozilla/TypedEnumBits.h b/mac/include/spidermonkey/mozilla/TypedEnumBits.h deleted file mode 100644 index 5ee6315c..00000000 --- a/mac/include/spidermonkey/mozilla/TypedEnumBits.h +++ /dev/null @@ -1,156 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS allows using a typed enum as bit flags. - */ - -#ifndef mozilla_TypedEnumBits_h -#define mozilla_TypedEnumBits_h - -#include "mozilla/Attributes.h" -#include "mozilla/IntegerTypeTraits.h" - -namespace mozilla { - -/* - * The problem that CastableTypedEnumResult aims to solve is that - * typed enums are not convertible to bool, and there is no way to make them - * be, yet user code wants to be able to write - * - * if (myFlags & Flags::SOME_PARTICULAR_FLAG) (1) - * - * There are different approaches to solving this. Most of them require - * adapting user code. For example, we could implement operator! and have - * the user write - * - * if (!!(myFlags & Flags::SOME_PARTICULAR_FLAG)) (2) - * - * Or we could supply a IsNonZero() or Any() function returning whether - * an enum value is nonzero, and have the user write - * - * if (Any(Flags & Flags::SOME_PARTICULAR_FLAG)) (3) - * - * But instead, we choose to preserve the original user syntax (1) as it - * is inherently more readable, and to ease porting existing code to typed - * enums. We achieve this by having operator& and other binary bitwise - * operators have as return type a class, CastableTypedEnumResult, - * that wraps a typed enum but adds bool convertibility. - */ -template -class CastableTypedEnumResult -{ -private: - const E mValue; - -public: - explicit constexpr CastableTypedEnumResult(E aValue) - : mValue(aValue) - {} - - constexpr operator E() const { return mValue; } - - template - explicit constexpr - operator DestinationType() const { return DestinationType(mValue); } - - constexpr bool operator !() const { return !bool(mValue); } -}; - -#define MOZ_CASTABLETYPEDENUMRESULT_BINOP(Op, OtherType, ReturnType) \ -template \ -constexpr ReturnType \ -operator Op(const OtherType& aE, const CastableTypedEnumResult& aR) \ -{ \ - return ReturnType(aE Op OtherType(aR)); \ -} \ -template \ -constexpr ReturnType \ -operator Op(const CastableTypedEnumResult& aR, const OtherType& aE) \ -{ \ - return ReturnType(OtherType(aR) Op aE); \ -} \ -template \ -constexpr ReturnType \ -operator Op(const CastableTypedEnumResult& aR1, \ - const CastableTypedEnumResult& aR2) \ -{ \ - return ReturnType(OtherType(aR1) Op OtherType(aR2)); \ -} - -MOZ_CASTABLETYPEDENUMRESULT_BINOP(|, E, CastableTypedEnumResult) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(&, E, CastableTypedEnumResult) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(^, E, CastableTypedEnumResult) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(==, E, bool) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(!=, E, bool) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(||, bool, bool) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(&&, bool, bool) - -template -constexpr CastableTypedEnumResult -operator ~(const CastableTypedEnumResult& aR) -{ - return CastableTypedEnumResult(~(E(aR))); -} - -#define MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(Op) \ -template \ -E& \ -operator Op(E& aR1, \ - const CastableTypedEnumResult& aR2) \ -{ \ - return aR1 Op E(aR2); \ -} - -MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(&=) -MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(|=) -MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(^=) - -#undef MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP - -#undef MOZ_CASTABLETYPEDENUMRESULT_BINOP - -namespace detail { -template -struct UnsignedIntegerTypeForEnum - : UnsignedStdintTypeForSize -{}; -} // namespace detail - -} // namespace mozilla - -#define MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, Op) \ - inline constexpr mozilla::CastableTypedEnumResult \ - operator Op(Name a, Name b) \ - { \ - typedef mozilla::CastableTypedEnumResult Result; \ - typedef mozilla::detail::UnsignedIntegerTypeForEnum::Type U; \ - return Result(Name(U(a) Op U(b))); \ - } \ - \ - inline Name& \ - operator Op##=(Name& a, Name b) \ - { \ - return a = a Op b; \ - } - -/** - * MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS generates standard bitwise operators - * for the given enum type. Use this to enable using an enum type as bit-field. - */ -#define MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Name) \ - MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, |) \ - MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, &) \ - MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, ^) \ - inline constexpr mozilla::CastableTypedEnumResult \ - operator~(Name a) \ - { \ - typedef mozilla::CastableTypedEnumResult Result; \ - typedef mozilla::detail::UnsignedIntegerTypeForEnum::Type U; \ - return Result(Name(~(U(a)))); \ - } - -#endif // mozilla_TypedEnumBits_h diff --git a/mac/include/spidermonkey/mozilla/Types.h b/mac/include/spidermonkey/mozilla/Types.h deleted file mode 100644 index e7e18abb..00000000 --- a/mac/include/spidermonkey/mozilla/Types.h +++ /dev/null @@ -1,134 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* mfbt foundational types and macros. */ - -#ifndef mozilla_Types_h -#define mozilla_Types_h - -/* - * This header must be valid C and C++, includable by code embedding either - * SpiderMonkey or Gecko. - */ - -/* Expose all types and size_t. */ -#include -#include - -/* Implement compiler and linker macros needed for APIs. */ - -/* - * MOZ_EXPORT is used to declare and define a symbol or type which is externally - * visible to users of the current library. It encapsulates various decorations - * needed to properly export the method's symbol. - * - * api.h: - * extern MOZ_EXPORT int MeaningOfLife(void); - * extern MOZ_EXPORT int LuggageCombination; - * - * api.c: - * int MeaningOfLife(void) { return 42; } - * int LuggageCombination = 12345; - * - * If you are merely sharing a method across files, just use plain |extern|. - * These macros are designed for use by library interfaces -- not for normal - * methods or data used cross-file. - */ -#if defined(WIN32) -# define MOZ_EXPORT __declspec(dllexport) -#else /* Unix */ -# ifdef HAVE_VISIBILITY_ATTRIBUTE -# define MOZ_EXPORT __attribute__((visibility("default"))) -# elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) -# define MOZ_EXPORT __global -# else -# define MOZ_EXPORT /* nothing */ -# endif -#endif - - -/* - * Whereas implementers use MOZ_EXPORT to declare and define library symbols, - * users use MOZ_IMPORT_API and MOZ_IMPORT_DATA to access them. Most often the - * implementer of the library will expose an API macro which expands to either - * the export or import version of the macro, depending upon the compilation - * mode. - */ -#ifdef _WIN32 -# if defined(__MWERKS__) -# define MOZ_IMPORT_API /* nothing */ -# else -# define MOZ_IMPORT_API __declspec(dllimport) -# endif -#else -# define MOZ_IMPORT_API MOZ_EXPORT -#endif - -#if defined(_WIN32) && !defined(__MWERKS__) -# define MOZ_IMPORT_DATA __declspec(dllimport) -#else -# define MOZ_IMPORT_DATA MOZ_EXPORT -#endif - -/* - * Consistent with the above comment, the MFBT_API and MFBT_DATA macros expose - * export mfbt declarations when building mfbt, and they expose import mfbt - * declarations when using mfbt. - */ -#if defined(IMPL_MFBT) -# define MFBT_API MOZ_EXPORT -# define MFBT_DATA MOZ_EXPORT -#else - /* - * On linux mozglue is linked in the program and we link libxul.so with - * -z,defs. Normally that causes the linker to reject undefined references in - * libxul.so, but as a loophole it allows undefined references to weak - * symbols. We add the weak attribute to the import version of the MFBT API - * macros to exploit this. - */ -# if defined(MOZ_GLUE_IN_PROGRAM) -# define MFBT_API __attribute__((weak)) MOZ_IMPORT_API -# define MFBT_DATA __attribute__((weak)) MOZ_IMPORT_DATA -# else -# define MFBT_API MOZ_IMPORT_API -# define MFBT_DATA MOZ_IMPORT_DATA -# endif -#endif - -/* - * C symbols in C++ code must be declared immediately within |extern "C"| - * blocks. However, in C code, they need not be declared specially. This - * difference is abstracted behind the MOZ_BEGIN_EXTERN_C and MOZ_END_EXTERN_C - * macros, so that the user need not know whether he is being used in C or C++ - * code. - * - * MOZ_BEGIN_EXTERN_C - * - * extern MOZ_EXPORT int MostRandomNumber(void); - * ...other declarations... - * - * MOZ_END_EXTERN_C - * - * This said, it is preferable to just use |extern "C"| in C++ header files for - * its greater clarity. - */ -#ifdef __cplusplus -# define MOZ_BEGIN_EXTERN_C extern "C" { -# define MOZ_END_EXTERN_C } -#else -# define MOZ_BEGIN_EXTERN_C -# define MOZ_END_EXTERN_C -#endif - -/* - * GCC's typeof is available when decltype is not. - */ -#if defined(__GNUC__) && defined(__cplusplus) && \ - !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L -# define decltype __typeof__ -#endif - -#endif /* mozilla_Types_h */ diff --git a/mac/include/spidermonkey/mozilla/UniquePtr.h b/mac/include/spidermonkey/mozilla/UniquePtr.h deleted file mode 100644 index 7e1035bc..00000000 --- a/mac/include/spidermonkey/mozilla/UniquePtr.h +++ /dev/null @@ -1,697 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Smart pointer managing sole ownership of a resource. */ - -#ifndef mozilla_UniquePtr_h -#define mozilla_UniquePtr_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/Move.h" -#include "mozilla/Pair.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -template class DefaultDelete; -template> class UniquePtr; - -} // namespace mozilla - -namespace mozilla { - -namespace detail { - -struct HasPointerTypeHelper -{ - template static double Test(...); - template static char Test(typename U::pointer* = 0); -}; - -template -class HasPointerType : public IntegralConstant(0)) == 1> -{ -}; - -template ::value> -struct PointerTypeImpl -{ - typedef typename D::pointer Type; -}; - -template -struct PointerTypeImpl -{ - typedef T* Type; -}; - -template -struct PointerType -{ - typedef typename PointerTypeImpl::Type>::Type Type; -}; - -} // namespace detail - -/** - * UniquePtr is a smart pointer that wholly owns a resource. Ownership may be - * transferred out of a UniquePtr through explicit action, but otherwise the - * resource is destroyed when the UniquePtr is destroyed. - * - * UniquePtr is similar to C++98's std::auto_ptr, but it improves upon auto_ptr - * in one crucial way: it's impossible to copy a UniquePtr. Copying an auto_ptr - * obviously *can't* copy ownership of its singly-owned resource. So what - * happens if you try to copy one? Bizarrely, ownership is implicitly - * *transferred*, preserving single ownership but breaking code that assumes a - * copy of an object is identical to the original. (This is why auto_ptr is - * prohibited in STL containers.) - * - * UniquePtr solves this problem by being *movable* rather than copyable. - * Instead of passing a |UniquePtr u| directly to the constructor or assignment - * operator, you pass |Move(u)|. In doing so you indicate that you're *moving* - * ownership out of |u|, into the target of the construction/assignment. After - * the transfer completes, |u| contains |nullptr| and may be safely destroyed. - * This preserves single ownership but also allows UniquePtr to be moved by - * algorithms that have been made move-safe. (Note: if |u| is instead a - * temporary expression, don't use |Move()|: just pass the expression, because - * it's already move-ready. For more information see Move.h.) - * - * UniquePtr is also better than std::auto_ptr in that the deletion operation is - * customizable. An optional second template parameter specifies a class that - * (through its operator()(T*)) implements the desired deletion policy. If no - * policy is specified, mozilla::DefaultDelete is used -- which will either - * |delete| or |delete[]| the resource, depending whether the resource is an - * array. Custom deletion policies ideally should be empty classes (no member - * fields, no member fields in base classes, no virtual methods/inheritance), - * because then UniquePtr can be just as efficient as a raw pointer. - * - * Use of UniquePtr proceeds like so: - * - * UniquePtr g1; // initializes to nullptr - * g1.reset(new int); // switch resources using reset() - * g1 = nullptr; // clears g1, deletes the int - * - * UniquePtr g2(new int); // owns that int - * int* p = g2.release(); // g2 leaks its int -- still requires deletion - * delete p; // now freed - * - * struct S { int x; S(int x) : x(x) {} }; - * UniquePtr g3, g4(new S(5)); - * g3 = Move(g4); // g3 owns the S, g4 cleared - * S* p = g3.get(); // g3 still owns |p| - * assert(g3->x == 5); // operator-> works (if .get() != nullptr) - * assert((*g3).x == 5); // also operator* (again, if not cleared) - * Swap(g3, g4); // g4 now owns the S, g3 cleared - * g3.swap(g4); // g3 now owns the S, g4 cleared - * UniquePtr g5(Move(g3)); // g5 owns the S, g3 cleared - * g5.reset(); // deletes the S, g5 cleared - * - * struct FreePolicy { void operator()(void* p) { free(p); } }; - * UniquePtr g6(static_cast(malloc(sizeof(int)))); - * int* ptr = g6.get(); - * g6 = nullptr; // calls free(ptr) - * - * Now, carefully note a few things you *can't* do: - * - * UniquePtr b1; - * b1 = new int; // BAD: can only assign another UniquePtr - * int* ptr = b1; // BAD: no auto-conversion to pointer, use get() - * - * UniquePtr b2(b1); // BAD: can't copy a UniquePtr - * UniquePtr b3 = b1; // BAD: can't copy-assign a UniquePtr - * - * (Note that changing a UniquePtr to store a direct |new| expression is - * permitted, but usually you should use MakeUnique, defined at the end of this - * header.) - * - * A few miscellaneous notes: - * - * UniquePtr, when not instantiated for an array type, can be move-constructed - * and move-assigned, not only from itself but from "derived" UniquePtr - * instantiations where U converts to T and E converts to D. If you want to use - * this, you're going to have to specify a deletion policy for both UniquePtr - * instantations, and T pretty much has to have a virtual destructor. In other - * words, this doesn't work: - * - * struct Base { virtual ~Base() {} }; - * struct Derived : Base {}; - * - * UniquePtr b1; - * // BAD: DefaultDelete and DefaultDelete don't interconvert - * UniquePtr d1(Move(b)); - * - * UniquePtr b2; - * UniquePtr> d2(Move(b2)); // okay - * - * UniquePtr is specialized for array types. Specializing with an array type - * creates a smart-pointer version of that array -- not a pointer to such an - * array. - * - * UniquePtr arr(new int[5]); - * arr[0] = 4; - * - * What else is different? Deletion of course uses |delete[]|. An operator[] - * is provided. Functionality that doesn't make sense for arrays is removed. - * The constructors and mutating methods only accept array pointers (not T*, U* - * that converts to T*, or UniquePtr or UniquePtr) or |nullptr|. - * - * It's perfectly okay for a function to return a UniquePtr. This transfers - * the UniquePtr's sole ownership of the data, to the fresh UniquePtr created - * in the calling function, that will then solely own that data. Such functions - * can return a local variable UniquePtr, |nullptr|, |UniquePtr(ptr)| where - * |ptr| is a |T*|, or a UniquePtr |Move()|'d from elsewhere. - * - * UniquePtr will commonly be a member of a class, with lifetime equivalent to - * that of that class. If you want to expose the related resource, you could - * expose a raw pointer via |get()|, but ownership of a raw pointer is - * inherently unclear. So it's better to expose a |const UniquePtr&| instead. - * This prohibits mutation but still allows use of |get()| when needed (but - * operator-> is preferred). Of course, you can only use this smart pointer as - * long as the enclosing class instance remains live -- no different than if you - * exposed the |get()| raw pointer. - * - * To pass a UniquePtr-managed resource as a pointer, use a |const UniquePtr&| - * argument. To specify an inout parameter (where the method may or may not - * take ownership of the resource, or reset it), or to specify an out parameter - * (where simply returning a |UniquePtr| isn't possible), use a |UniquePtr&| - * argument. To unconditionally transfer ownership of a UniquePtr - * into a method, use a |UniquePtr| argument. To conditionally transfer - * ownership of a resource into a method, should the method want it, use a - * |UniquePtr&&| argument. - */ -template -class UniquePtr -{ -public: - typedef T ElementType; - typedef D DeleterType; - typedef typename detail::PointerType::Type Pointer; - -private: - Pair mTuple; - - Pointer& ptr() { return mTuple.first(); } - const Pointer& ptr() const { return mTuple.first(); } - - DeleterType& del() { return mTuple.second(); } - const DeleterType& del() const { return mTuple.second(); } - -public: - /** - * Construct a UniquePtr containing |nullptr|. - */ - constexpr UniquePtr() - : mTuple(static_cast(nullptr), DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - /** - * Construct a UniquePtr containing |aPtr|. - */ - explicit UniquePtr(Pointer aPtr) - : mTuple(aPtr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - UniquePtr(Pointer aPtr, - typename Conditional::value, - D, - const D&>::Type aD1) - : mTuple(aPtr, aD1) - {} - - // If you encounter an error with MSVC10 about RemoveReference below, along - // the lines that "more than one partial specialization matches the template - // argument list": don't use UniquePtr! Ideally - // you should make deletion use the same function every time, using a - // deleter policy: - // - // // BAD, won't compile with MSVC10, deleter doesn't need to be a - // // variable at all - // typedef void (&FreeSignature)(void*); - // UniquePtr ptr((int*) malloc(sizeof(int)), free); - // - // // GOOD, compiles with MSVC10, deletion behavior statically known and - // // optimizable - // struct DeleteByFreeing - // { - // void operator()(void* aPtr) { free(aPtr); } - // }; - // - // If deletion really, truly, must be a variable: you might be able to work - // around this with a deleter class that contains the function reference. - // But this workaround is untried and untested, because variable deletion - // behavior really isn't something you should use. - UniquePtr(Pointer aPtr, - typename RemoveReference::Type&& aD2) - : mTuple(aPtr, Move(aD2)) - { - static_assert(!IsReference::value, - "rvalue deleter can't be stored by reference"); - } - - UniquePtr(UniquePtr&& aOther) - : mTuple(aOther.release(), Forward(aOther.get_deleter())) - {} - - MOZ_IMPLICIT - UniquePtr(decltype(nullptr)) - : mTuple(nullptr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - template - MOZ_IMPLICIT - UniquePtr(UniquePtr&& aOther, - typename EnableIf::Pointer, - Pointer>::value && - !IsArray::value && - (IsReference::value - ? IsSame::value - : IsConvertible::value), - int>::Type aDummy = 0) - : mTuple(aOther.release(), Forward(aOther.get_deleter())) - { - } - - ~UniquePtr() { reset(nullptr); } - - UniquePtr& operator=(UniquePtr&& aOther) - { - reset(aOther.release()); - get_deleter() = Forward(aOther.get_deleter()); - return *this; - } - - template - UniquePtr& operator=(UniquePtr&& aOther) - { - static_assert(IsConvertible::Pointer, - Pointer>::value, - "incompatible UniquePtr pointees"); - static_assert(!IsArray::value, - "can't assign from UniquePtr holding an array"); - - reset(aOther.release()); - get_deleter() = Forward(aOther.get_deleter()); - return *this; - } - - UniquePtr& operator=(decltype(nullptr)) - { - reset(nullptr); - return *this; - } - - T& operator*() const { return *get(); } - Pointer operator->() const - { - MOZ_ASSERT(get(), "dereferencing a UniquePtr containing nullptr"); - return get(); - } - - explicit operator bool() const { return get() != nullptr; } - - Pointer get() const { return ptr(); } - - DeleterType& get_deleter() { return del(); } - const DeleterType& get_deleter() const { return del(); } - - MOZ_MUST_USE Pointer release() - { - Pointer p = ptr(); - ptr() = nullptr; - return p; - } - - void reset(Pointer aPtr = Pointer()) - { - Pointer old = ptr(); - ptr() = aPtr; - if (old != nullptr) { - get_deleter()(old); - } - } - - void swap(UniquePtr& aOther) - { - mTuple.swap(aOther.mTuple); - } - - UniquePtr(const UniquePtr& aOther) = delete; // construct using Move()! - void operator=(const UniquePtr& aOther) = delete; // assign using Move()! -}; - -// In case you didn't read the comment by the main definition (you should!): the -// UniquePtr specialization exists to manage array pointers. It deletes -// such pointers using delete[], it will reject construction and modification -// attempts using U* or U[]. Otherwise it works like the normal UniquePtr. -template -class UniquePtr -{ -public: - typedef T* Pointer; - typedef T ElementType; - typedef D DeleterType; - -private: - Pair mTuple; - -public: - /** - * Construct a UniquePtr containing nullptr. - */ - constexpr UniquePtr() - : mTuple(static_cast(nullptr), DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - /** - * Construct a UniquePtr containing |aPtr|. - */ - explicit UniquePtr(Pointer aPtr) - : mTuple(aPtr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - // delete[] knows how to handle *only* an array of a single class type. For - // delete[] to work correctly, it must know the size of each element, the - // fields and base classes of each element requiring destruction, and so on. - // So forbid all overloads which would end up invoking delete[] on a pointer - // of the wrong type. - template - UniquePtr(U&& aU, - typename EnableIf::value && - IsConvertible::value, - int>::Type aDummy = 0) - = delete; - - UniquePtr(Pointer aPtr, - typename Conditional::value, - D, - const D&>::Type aD1) - : mTuple(aPtr, aD1) - {} - - // If you encounter an error with MSVC10 about RemoveReference below, along - // the lines that "more than one partial specialization matches the template - // argument list": don't use UniquePtr! See the - // comment by this constructor in the non-T[] specialization above. - UniquePtr(Pointer aPtr, - typename RemoveReference::Type&& aD2) - : mTuple(aPtr, Move(aD2)) - { - static_assert(!IsReference::value, - "rvalue deleter can't be stored by reference"); - } - - // Forbidden for the same reasons as stated above. - template - UniquePtr(U&& aU, V&& aV, - typename EnableIf::value && - IsConvertible::value, - int>::Type aDummy = 0) - = delete; - - UniquePtr(UniquePtr&& aOther) - : mTuple(aOther.release(), Forward(aOther.get_deleter())) - {} - - MOZ_IMPLICIT - UniquePtr(decltype(nullptr)) - : mTuple(nullptr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - ~UniquePtr() { reset(nullptr); } - - UniquePtr& operator=(UniquePtr&& aOther) - { - reset(aOther.release()); - get_deleter() = Forward(aOther.get_deleter()); - return *this; - } - - UniquePtr& operator=(decltype(nullptr)) - { - reset(); - return *this; - } - - explicit operator bool() const { return get() != nullptr; } - - T& operator[](decltype(sizeof(int)) aIndex) const { return get()[aIndex]; } - Pointer get() const { return mTuple.first(); } - - DeleterType& get_deleter() { return mTuple.second(); } - const DeleterType& get_deleter() const { return mTuple.second(); } - - MOZ_MUST_USE Pointer release() - { - Pointer p = mTuple.first(); - mTuple.first() = nullptr; - return p; - } - - void reset(Pointer aPtr = Pointer()) - { - Pointer old = mTuple.first(); - mTuple.first() = aPtr; - if (old != nullptr) { - mTuple.second()(old); - } - } - - void reset(decltype(nullptr)) - { - Pointer old = mTuple.first(); - mTuple.first() = nullptr; - if (old != nullptr) { - mTuple.second()(old); - } - } - - template - void reset(U) = delete; - - void swap(UniquePtr& aOther) { mTuple.swap(aOther.mTuple); } - - UniquePtr(const UniquePtr& aOther) = delete; // construct using Move()! - void operator=(const UniquePtr& aOther) = delete; // assign using Move()! -}; - -/** - * A default deletion policy using plain old operator delete. - * - * Note that this type can be specialized, but authors should beware of the risk - * that the specialization may at some point cease to match (either because it - * gets moved to a different compilation unit or the signature changes). If the - * non-specialized (|delete|-based) version compiles for that type but does the - * wrong thing, bad things could happen. - * - * This is a non-issue for types which are always incomplete (i.e. opaque handle - * types), since |delete|-ing such a type will always trigger a compilation - * error. - */ -template -class DefaultDelete -{ -public: - constexpr DefaultDelete() {} - - template - MOZ_IMPLICIT DefaultDelete(const DefaultDelete& aOther, - typename EnableIf::value, - int>::Type aDummy = 0) - {} - - void operator()(T* aPtr) const - { - static_assert(sizeof(T) > 0, "T must be complete"); - delete aPtr; - } -}; - -/** A default deletion policy using operator delete[]. */ -template -class DefaultDelete -{ -public: - constexpr DefaultDelete() {} - - void operator()(T* aPtr) const - { - static_assert(sizeof(T) > 0, "T must be complete"); - delete[] aPtr; - } - - template - void operator()(U* aPtr) const = delete; -}; - -template -void -Swap(UniquePtr& aX, UniquePtr& aY) -{ - aX.swap(aY); -} - -template -bool -operator==(const UniquePtr& aX, const UniquePtr& aY) -{ - return aX.get() == aY.get(); -} - -template -bool -operator!=(const UniquePtr& aX, const UniquePtr& aY) -{ - return aX.get() != aY.get(); -} - -template -bool -operator==(const UniquePtr& aX, decltype(nullptr)) -{ - return !aX; -} - -template -bool -operator==(decltype(nullptr), const UniquePtr& aX) -{ - return !aX; -} - -template -bool -operator!=(const UniquePtr& aX, decltype(nullptr)) -{ - return bool(aX); -} - -template -bool -operator!=(decltype(nullptr), const UniquePtr& aX) -{ - return bool(aX); -} - -// No operator<, operator>, operator<=, operator>= for now because simplicity. - -namespace detail { - -template -struct UniqueSelector -{ - typedef UniquePtr SingleObject; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr UnknownBound; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr KnownBound; -}; - -} // namespace detail - -/** - * MakeUnique is a helper function for allocating new'd objects and arrays, - * returning a UniquePtr containing the resulting pointer. The semantics of - * MakeUnique(...) are as follows. - * - * If Type is an array T[n]: - * Disallowed, deleted, no overload for you! - * If Type is an array T[]: - * MakeUnique(size_t) is the only valid overload. The pointer returned - * is as if by |new T[n]()|, which value-initializes each element. (If T - * isn't a class type, this will zero each element. If T is a class type, - * then roughly speaking, each element will be constructed using its default - * constructor. See C++11 [dcl.init]p7 for the full gory details.) - * If Type is non-array T: - * The arguments passed to MakeUnique(...) are forwarded into a - * |new T(...)| call, initializing the T as would happen if executing - * |T(...)|. - * - * There are various benefits to using MakeUnique instead of |new| expressions. - * - * First, MakeUnique eliminates use of |new| from code entirely. If objects are - * only created through UniquePtr, then (assuming all explicit release() calls - * are safe, including transitively, and no type-safety casting funniness) - * correctly maintained ownership of the UniquePtr guarantees no leaks are - * possible. (This pays off best if a class is only ever created through a - * factory method on the class, using a private constructor.) - * - * Second, initializing a UniquePtr using a |new| expression requires repeating - * the name of the new'd type, whereas MakeUnique in concert with the |auto| - * keyword names it only once: - * - * UniquePtr ptr1(new char()); // repetitive - * auto ptr2 = MakeUnique(); // shorter - * - * Of course this assumes the reader understands the operation MakeUnique - * performs. In the long run this is probably a reasonable assumption. In the - * short run you'll have to use your judgment about what readers can be expected - * to know, or to quickly look up. - * - * Third, a call to MakeUnique can be assigned directly to a UniquePtr. In - * contrast you can't assign a pointer into a UniquePtr without using the - * cumbersome reset(). - * - * UniquePtr p; - * p = new char; // ERROR - * p.reset(new char); // works, but fugly - * p = MakeUnique(); // preferred - * - * (And third, although not relevant to Mozilla: MakeUnique is exception-safe. - * An exception thrown after |new T| succeeds will leak that memory, unless the - * pointer is assigned to an object that will manage its ownership. UniquePtr - * ably serves this function.) - */ - -template -typename detail::UniqueSelector::SingleObject -MakeUnique(Args&&... aArgs) -{ - return UniquePtr(new T(Forward(aArgs)...)); -} - -template -typename detail::UniqueSelector::UnknownBound -MakeUnique(decltype(sizeof(int)) aN) -{ - typedef typename RemoveExtent::Type ArrayType; - return UniquePtr(new ArrayType[aN]()); -} - -template -typename detail::UniqueSelector::KnownBound -MakeUnique(Args&&... aArgs) = delete; - -} // namespace mozilla - -#endif /* mozilla_UniquePtr_h */ diff --git a/mac/include/spidermonkey/mozilla/UniquePtrExtensions.h b/mac/include/spidermonkey/mozilla/UniquePtrExtensions.h deleted file mode 100644 index d94f33ee..00000000 --- a/mac/include/spidermonkey/mozilla/UniquePtrExtensions.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Useful extensions to UniquePtr. */ - -#ifndef mozilla_UniquePtrExtensions_h -#define mozilla_UniquePtrExtensions_h - -#include "mozilla/fallible.h" -#include "mozilla/UniquePtr.h" - -namespace mozilla { - -/** - * MakeUniqueFallible works exactly like MakeUnique, except that the memory - * allocation performed is done fallibly, i.e. it can return nullptr. - */ -template -typename detail::UniqueSelector::SingleObject -MakeUniqueFallible(Args&&... aArgs) -{ - return UniquePtr(new (fallible) T(Forward(aArgs)...)); -} - -template -typename detail::UniqueSelector::UnknownBound -MakeUniqueFallible(decltype(sizeof(int)) aN) -{ - typedef typename RemoveExtent::Type ArrayType; - return UniquePtr(new (fallible) ArrayType[aN]()); -} - -template -typename detail::UniqueSelector::KnownBound -MakeUniqueFallible(Args&&... aArgs) = delete; - -namespace detail { - -template -struct FreePolicy -{ - void operator()(const void* ptr) { - free(const_cast(ptr)); - } -}; - -} // namespace detail - -template -using UniqueFreePtr = UniquePtr>; - -} // namespace mozilla - -#endif // mozilla_UniquePtrExtensions_h diff --git a/mac/include/spidermonkey/mozilla/Unused.h b/mac/include/spidermonkey/mozilla/Unused.h deleted file mode 100644 index e693e32a..00000000 --- a/mac/include/spidermonkey/mozilla/Unused.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_unused_h -#define mozilla_unused_h - -#include "mozilla/Types.h" - -#ifdef __cplusplus - -namespace mozilla { - -// -// Suppress GCC warnings about unused return values with -// Unused << SomeFuncDeclaredWarnUnusedReturnValue(); -// -struct unused_t -{ - template - inline void - operator<<(const T& /*unused*/) const {} -}; - -extern MFBT_DATA const unused_t Unused; - -} // namespace mozilla - -#endif // __cplusplus - -// An alternative to mozilla::Unused for use in (a) C code and (b) code where -// linking with unused.o is difficult. -#define MOZ_UNUSED(expr) \ - do { if (expr) { (void)0; } } while (0) - -#endif // mozilla_unused_h diff --git a/mac/include/spidermonkey/mozilla/Variant.h b/mac/include/spidermonkey/mozilla/Variant.h deleted file mode 100644 index 8a33286e..00000000 --- a/mac/include/spidermonkey/mozilla/Variant.h +++ /dev/null @@ -1,625 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A template class for tagged unions. */ - -#include -#include - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#ifndef mozilla_Variant_h -#define mozilla_Variant_h - -namespace mozilla { - -template -class Variant; - -namespace detail { - -// MaxSizeOf computes the maximum sizeof(T) for each T in Ts. - -template -struct MaxSizeOf -{ - static const size_t size = sizeof(T) > MaxSizeOf::size - ? sizeof(T) - : MaxSizeOf::size; -}; - -template -struct MaxSizeOf -{ - static const size_t size = sizeof(T); -}; - -// The `IsVariant` helper is used in conjunction with static_assert and -// `mozilla::EnableIf` to catch passing non-variant types to `Variant::is()` -// and friends at compile time, rather than at runtime. It ensures that the -// given type `Needle` is one of the types in the set of types `Haystack`. - -template -struct IsVariant; - -template -struct IsVariant -{ - static const bool value = false; -}; - -template -struct IsVariant -{ - static const bool value = true; -}; - -template -struct IsVariant : public IsVariant { }; - -/// SelectVariantTypeHelper is used in the implementation of SelectVariantType. -template -struct SelectVariantTypeHelper; - -template -struct SelectVariantTypeHelper -{ }; - -template -struct SelectVariantTypeHelper -{ - typedef T Type; -}; - -template -struct SelectVariantTypeHelper -{ - typedef const T Type; -}; - -template -struct SelectVariantTypeHelper -{ - typedef const T& Type; -}; - -template -struct SelectVariantTypeHelper -{ - typedef T&& Type; -}; - -template -struct SelectVariantTypeHelper - : public SelectVariantTypeHelper -{ }; - -/** - * SelectVariantType takes a type T and a list of variant types Variants and - * yields a type Type, selected from Variants, that can store a value of type T - * or a reference to type T. If no such type was found, Type is not defined. - */ -template -struct SelectVariantType - : public SelectVariantTypeHelper::Type>::Type, - Variants...> -{ }; - -// Compute a fast, compact type that can be used to hold integral values that -// distinctly map to every type in Ts. -template -struct VariantTag -{ -private: - static const size_t TypeCount = sizeof...(Ts); - -public: - using Type = - typename Conditional::Type - >::Type; -}; - -// TagHelper gets the given sentinel tag value for the given type T. This has to -// be split out from VariantImplementation because you can't nest a partial -// template specialization within a template class. - -template -struct TagHelper; - -// In the case where T != U, we continue recursion. -template -struct TagHelper -{ - static Tag tag() { return Next::template tag(); } -}; - -// In the case where T == U, return the tag number. -template -struct TagHelper -{ - static Tag tag() { return Tag(N); } -}; - -// The VariantImplementation template provides the guts of mozilla::Variant. We -// create a VariantImplementation for each T in Ts... which handles -// construction, destruction, etc for when the Variant's type is T. If the -// Variant's type isn't T, it punts the request on to the next -// VariantImplementation. - -template -struct VariantImplementation; - -// The singly typed Variant / recursion base case. -template -struct VariantImplementation -{ - template - static Tag tag() { - static_assert(mozilla::IsSame::value, - "mozilla::Variant: tag: bad type!"); - return Tag(N); - } - - template - static void copyConstruct(void* aLhs, const Variant& aRhs) { - new (aLhs) T(aRhs.template as()); - } - - template - static void moveConstruct(void* aLhs, Variant&& aRhs) { - new (aLhs) T(aRhs.template extract()); - } - - template - static void destroy(Variant& aV) { - aV.template as().~T(); - } - - template - static bool - equal(const Variant& aLhs, const Variant& aRhs) { - return aLhs.template as() == aRhs.template as(); - } - - template - static auto - match(Matcher&& aMatcher, ConcreteVariant& aV) - -> decltype(aMatcher.match(aV.template as())) - { - return aMatcher.match(aV.template as()); - } -}; - -// VariantImplementation for some variant type T. -template -struct VariantImplementation -{ - // The next recursive VariantImplementation. - using Next = VariantImplementation; - - template - static Tag tag() { - return TagHelper::value>::tag(); - } - - template - static void copyConstruct(void* aLhs, const Variant& aRhs) { - if (aRhs.template is()) { - new (aLhs) T(aRhs.template as()); - } else { - Next::copyConstruct(aLhs, aRhs); - } - } - - template - static void moveConstruct(void* aLhs, Variant&& aRhs) { - if (aRhs.template is()) { - new (aLhs) T(aRhs.template extract()); - } else { - Next::moveConstruct(aLhs, aRhs); - } - } - - template - static void destroy(Variant& aV) { - if (aV.template is()) { - aV.template as().~T(); - } else { - Next::destroy(aV); - } - } - - template - static bool equal(const Variant& aLhs, const Variant& aRhs) { - if (aLhs.template is()) { - MOZ_ASSERT(aRhs.template is()); - return aLhs.template as() == aRhs.template as(); - } else { - return Next::equal(aLhs, aRhs); - } - } - - template - static auto - match(Matcher&& aMatcher, ConcreteVariant& aV) - -> decltype(aMatcher.match(aV.template as())) - { - if (aV.template is()) { - return aMatcher.match(aV.template as()); - } else { - // If you're seeing compilation errors here like "no matching - // function for call to 'match'" then that means that the - // Matcher doesn't exhaust all variant types. There must exist a - // Matcher::match(T&) for every variant type T. - // - // If you're seeing compilation errors here like "cannot - // initialize return object of type <...> with an rvalue of type - // <...>" then that means that the Matcher::match(T&) overloads - // are returning different types. They must all return the same - // Matcher::ReturnType type. - return Next::match(aMatcher, aV); - } - } -}; - -/** - * AsVariantTemporary stores a value of type T to allow construction of a - * Variant value via type inference. Because T is copied and there's no - * guarantee that the copy can be elided, AsVariantTemporary is best used with - * primitive or very small types. - */ -template -struct AsVariantTemporary -{ - explicit AsVariantTemporary(const T& aValue) - : mValue(aValue) - {} - - template - explicit AsVariantTemporary(U&& aValue) - : mValue(Forward(aValue)) - {} - - AsVariantTemporary(const AsVariantTemporary& aOther) - : mValue(aOther.mValue) - {} - - AsVariantTemporary(AsVariantTemporary&& aOther) - : mValue(Move(aOther.mValue)) - {} - - AsVariantTemporary() = delete; - void operator=(const AsVariantTemporary&) = delete; - void operator=(AsVariantTemporary&&) = delete; - - typename RemoveConst::Type>::Type mValue; -}; - -} // namespace detail - -/** - * # mozilla::Variant - * - * A variant / tagged union / heterogenous disjoint union / sum-type template - * class. Similar in concept to (but not derived from) `boost::variant`. - * - * Sometimes, you may wish to use a C union with non-POD types. However, this is - * forbidden in C++ because it is not clear which type in the union should have - * its constructor and destructor run on creation and deletion - * respectively. This is the problem that `mozilla::Variant` solves. - * - * ## Usage - * - * A `mozilla::Variant` instance is constructed (via move or copy) from one of - * its variant types (ignoring const and references). It does *not* support - * construction from subclasses of variant types or types that coerce to one of - * the variant types. - * - * Variant v1('a'); - * Variant, B, C> v2(MakeUnique()); - * - * Because specifying the full type of a Variant value is often verbose, - * AsVariant() can be used to construct a Variant value using type inference in - * contexts such as expressions or when returning values from functions. Because - * AsVariant() must copy or move the value into a temporary and this cannot - * necessarily be elided by the compiler, it's mostly appropriate only for use - * with primitive or very small types. - * - * - * Variant Foo() { return AsVariant('x'); } - * // ... - * Variant v1 = Foo(); // v1 holds char('x'). - * - * All access to the contained value goes through type-safe accessors. - * - * void - * Foo(Variant v) - * { - * if (v.is()) { - * A& ref = v.as(); - * ... - * } else { - * ... - * } - * } - * - * Attempting to use the contained value as type `T1` when the `Variant` - * instance contains a value of type `T2` causes an assertion failure. - * - * A a; - * Variant v(a); - * v.as(); // <--- Assertion failure! - * - * Trying to use a `Variant` instance as some type `U` that is not a - * member of the set of `Ts...` is a compiler error. - * - * A a; - * Variant v(a); - * v.as(); // <--- Compiler error! - * - * Additionally, you can turn a `Variant` that `is` into a `T` by moving it - * out of the containing `Variant` instance with the `extract` method: - * - * Variant, B, C> v(MakeUnique()); - * auto ptr = v.extract>(); - * - * Finally, you can exhaustively match on the contained variant and branch into - * different code paths depending which type is contained. This is preferred to - * manually checking every variant type T with is() because it provides - * compile-time checking that you handled every type, rather than runtime - * assertion failures. - * - * // Bad! - * char* foo(Variant& v) { - * if (v.is()) { - * return ...; - * } else if (v.is()) { - * return ...; - * } else { - * return doSomething(v.as()); // Forgot about case D! - * } - * } - * - * // Good! - * struct FooMatcher - * { - * // The return type of all matchers must be identical. - * char* match(A& a) { ... } - * char* match(B& b) { ... } - * char* match(C& c) { ... } - * char* match(D& d) { ... } // Compile-time error to forget D! - * } - * char* foo(Variant& v) { - * return v.match(FooMatcher()); - * } - * - * ## Examples - * - * A tree is either an empty leaf, or a node with a value and two children: - * - * struct Leaf { }; - * - * template - * struct Node - * { - * T value; - * Tree* left; - * Tree* right; - * }; - * - * template - * using Tree = Variant>; - * - * A copy-on-write string is either a non-owning reference to some existing - * string, or an owning reference to our copy: - * - * class CopyOnWriteString - * { - * Variant> string; - * - * ... - * }; - */ -template -class MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS Variant -{ - using Tag = typename detail::VariantTag::Type; - using Impl = detail::VariantImplementation; - using RawData = AlignedStorage::size>; - - // Raw storage for the contained variant value. - RawData raw; - - // Each type is given a unique tag value that lets us keep track of the - // contained variant value's type. - Tag tag; - - void* ptr() { - return reinterpret_cast(&raw); - } - -public: - /** Perfect forwarding construction for some variant type T. */ - template::Type> - explicit Variant(RefT&& aT) - : tag(Impl::template tag()) - { - new (ptr()) T(Forward(aT)); - } - - /** - * Constructs this Variant from an AsVariantTemporary such that T can be - * stored in one of the types allowable in this Variant. This is used in the - * implementation of AsVariant(). - */ - template::Type> - MOZ_IMPLICIT Variant(detail::AsVariantTemporary&& aValue) - : tag(Impl::template tag()) - { - new (ptr()) T(Move(aValue.mValue)); - } - - /** Copy construction. */ - Variant(const Variant& aRhs) - : tag(aRhs.tag) - { - Impl::copyConstruct(ptr(), aRhs); - } - - /** Move construction. */ - Variant(Variant&& aRhs) - : tag(aRhs.tag) - { - Impl::moveConstruct(ptr(), Move(aRhs)); - } - - /** Copy assignment. */ - Variant& operator=(const Variant& aRhs) { - MOZ_ASSERT(&aRhs != this, "self-assign disallowed"); - this->~Variant(); - new (this) Variant(aRhs); - return *this; - } - - /** Move assignment. */ - Variant& operator=(Variant&& aRhs) { - MOZ_ASSERT(&aRhs != this, "self-assign disallowed"); - this->~Variant(); - new (this) Variant(Move(aRhs)); - return *this; - } - - /** Move assignment from AsVariant(). */ - template - Variant& operator=(detail::AsVariantTemporary&& aValue) - { - this->~Variant(); - new (this) Variant(Move(aValue)); - return *this; - } - - ~Variant() - { - Impl::destroy(*this); - } - - /** Check which variant type is currently contained. */ - template - bool is() const { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - return Impl::template tag() == tag; - } - - /** - * Operator == overload that defers to the variant type's operator== - * implementation if the rhs is tagged as the same type as this one. - */ - bool operator==(const Variant& aRhs) const { - return tag == aRhs.tag && Impl::equal(*this, aRhs); - } - - /** - * Operator != overload that defers to the negation of the variant type's - * operator== implementation if the rhs is tagged as the same type as this - * one. - */ - bool operator!=(const Variant& aRhs) const { - return !(*this == aRhs); - } - - // Accessors for working with the contained variant value. - - /** Mutable reference. */ - template - T& as() { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - MOZ_ASSERT(is()); - return *reinterpret_cast(&raw); - } - - /** Immutable const reference. */ - template - const T& as() const { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - MOZ_ASSERT(is()); - return *reinterpret_cast(&raw); - } - - /** - * Extract the contained variant value from this container into a temporary - * value. On completion, the value in the variant will be in a - * safely-destructible state, as determined by the behavior of T's move - * constructor when provided the variant's internal value. - */ - template - T extract() { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - MOZ_ASSERT(is()); - return T(Move(as())); - } - - // Exhaustive matching of all variant types on the contained value. - - /** Match on an immutable const reference. */ - template - auto - match(Matcher&& aMatcher) const - -> decltype(Impl::match(aMatcher, *this)) - { - return Impl::match(aMatcher, *this); - } - - /** Match on a mutable non-const reference. */ - template - auto - match(Matcher&& aMatcher) - -> decltype(Impl::match(aMatcher, *this)) - { - return Impl::match(aMatcher, *this); - } -}; - -/* - * AsVariant() is used to construct a Variant value containing the - * provided T value using type inference. It can be used to construct Variant - * values in expressions or return them from functions without specifying the - * entire Variant type. - * - * Because AsVariant() must copy or move the value into a temporary and this - * cannot necessarily be elided by the compiler, it's mostly appropriate only - * for use with primitive or very small types. - * - * AsVariant() returns a AsVariantTemporary value which is implicitly - * convertible to any Variant that can hold a value of type T. - */ -template -detail::AsVariantTemporary -AsVariant(T&& aValue) -{ - return detail::AsVariantTemporary(Forward(aValue)); -} - -} // namespace mozilla - -#endif /* mozilla_Variant_h */ diff --git a/mac/include/spidermonkey/mozilla/Vector.h b/mac/include/spidermonkey/mozilla/Vector.h deleted file mode 100644 index fc43afcf..00000000 --- a/mac/include/spidermonkey/mozilla/Vector.h +++ /dev/null @@ -1,1491 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A type/length-parametrized vector class. */ - -#ifndef mozilla_Vector_h -#define mozilla_Vector_h - -#include "mozilla/Alignment.h" -#include "mozilla/AllocPolicy.h" -#include "mozilla/ArrayUtils.h" // for PointerRangeSize -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/MathAlgorithms.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/OperatorNewExtensions.h" -#include "mozilla/ReentrancyGuard.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/TypeTraits.h" - -#include // for placement new - -/* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4345) -#endif - -namespace mozilla { - -template -class Vector; - -namespace detail { - -/* - * Check that the given capacity wastes the minimal amount of space if - * allocated on the heap. This means that aCapacity*sizeof(T) is as close to a - * power-of-two as possible. growStorageBy() is responsible for ensuring this. - */ -template -static bool CapacityHasExcessSpace(size_t aCapacity) -{ - size_t size = aCapacity * sizeof(T); - return RoundUpPow2(size) - size >= sizeof(T); -} - -/* - * This template class provides a default implementation for vector operations - * when the element type is not known to be a POD, as judged by IsPod. - */ -template -struct VectorImpl -{ - /* - * Constructs an object in the uninitialized memory at *aDst with aArgs. - */ - template - MOZ_NONNULL(1) - static inline void new_(T* aDst, Args&&... aArgs) - { - new(KnownNotNull, aDst) T(Forward(aArgs)...); - } - - /* Destroys constructed objects in the range [aBegin, aEnd). */ - static inline void destroy(T* aBegin, T* aEnd) - { - MOZ_ASSERT(aBegin <= aEnd); - for (T* p = aBegin; p < aEnd; ++p) { - p->~T(); - } - } - - /* Constructs objects in the uninitialized range [aBegin, aEnd). */ - static inline void initialize(T* aBegin, T* aEnd) - { - MOZ_ASSERT(aBegin <= aEnd); - for (T* p = aBegin; p < aEnd; ++p) { - new_(p); - } - } - - /* - * Copy-constructs objects in the uninitialized range - * [aDst, aDst+(aSrcEnd-aSrcStart)) from the range [aSrcStart, aSrcEnd). - */ - template - static inline void copyConstruct(T* aDst, - const U* aSrcStart, const U* aSrcEnd) - { - MOZ_ASSERT(aSrcStart <= aSrcEnd); - for (const U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) { - new_(aDst, *p); - } - } - - /* - * Move-constructs objects in the uninitialized range - * [aDst, aDst+(aSrcEnd-aSrcStart)) from the range [aSrcStart, aSrcEnd). - */ - template - static inline void moveConstruct(T* aDst, U* aSrcStart, U* aSrcEnd) - { - MOZ_ASSERT(aSrcStart <= aSrcEnd); - for (U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) { - new_(aDst, Move(*p)); - } - } - - /* - * Copy-constructs objects in the uninitialized range [aDst, aDst+aN) from - * the same object aU. - */ - template - static inline void copyConstructN(T* aDst, size_t aN, const U& aU) - { - for (T* end = aDst + aN; aDst < end; ++aDst) { - new_(aDst, aU); - } - } - - /* - * Grows the given buffer to have capacity aNewCap, preserving the objects - * constructed in the range [begin, end) and updating aV. Assumes that (1) - * aNewCap has not overflowed, and (2) multiplying aNewCap by sizeof(T) will - * not overflow. - */ - static inline MOZ_MUST_USE bool - growTo(Vector& aV, size_t aNewCap) - { - MOZ_ASSERT(!aV.usingInlineStorage()); - MOZ_ASSERT(!CapacityHasExcessSpace(aNewCap)); - T* newbuf = aV.template pod_malloc(aNewCap); - if (MOZ_UNLIKELY(!newbuf)) { - return false; - } - T* dst = newbuf; - T* src = aV.beginNoCheck(); - for (; src < aV.endNoCheck(); ++dst, ++src) { - new_(dst, Move(*src)); - } - VectorImpl::destroy(aV.beginNoCheck(), aV.endNoCheck()); - aV.free_(aV.mBegin); - aV.mBegin = newbuf; - /* aV.mLength is unchanged. */ - aV.mCapacity = aNewCap; - return true; - } -}; - -/* - * This partial template specialization provides a default implementation for - * vector operations when the element type is known to be a POD, as judged by - * IsPod. - */ -template -struct VectorImpl -{ - template - MOZ_NONNULL(1) - static inline void new_(T* aDst, Args&&... aArgs) - { - // Explicitly construct a local object instead of using a temporary since - // T(args...) will be treated like a C-style cast in the unary case and - // allow unsafe conversions. Both forms should be equivalent to an - // optimizing compiler. - T temp(Forward(aArgs)...); - *aDst = temp; - } - - static inline void destroy(T*, T*) {} - - static inline void initialize(T* aBegin, T* aEnd) - { - /* - * You would think that memset would be a big win (or even break even) - * when we know T is a POD. But currently it's not. This is probably - * because |append| tends to be given small ranges and memset requires - * a function call that doesn't get inlined. - * - * memset(aBegin, 0, sizeof(T) * (aEnd - aBegin)); - */ - MOZ_ASSERT(aBegin <= aEnd); - for (T* p = aBegin; p < aEnd; ++p) { - new_(p); - } - } - - template - static inline void copyConstruct(T* aDst, - const U* aSrcStart, const U* aSrcEnd) - { - /* - * See above memset comment. Also, notice that copyConstruct is - * currently templated (T != U), so memcpy won't work without - * requiring T == U. - * - * memcpy(aDst, aSrcStart, sizeof(T) * (aSrcEnd - aSrcStart)); - */ - MOZ_ASSERT(aSrcStart <= aSrcEnd); - for (const U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) { - new_(aDst, *p); - } - } - - template - static inline void moveConstruct(T* aDst, - const U* aSrcStart, const U* aSrcEnd) - { - copyConstruct(aDst, aSrcStart, aSrcEnd); - } - - static inline void copyConstructN(T* aDst, size_t aN, const T& aT) - { - for (T* end = aDst + aN; aDst < end; ++aDst) { - new_(aDst, aT); - } - } - - static inline MOZ_MUST_USE bool - growTo(Vector& aV, size_t aNewCap) - { - MOZ_ASSERT(!aV.usingInlineStorage()); - MOZ_ASSERT(!CapacityHasExcessSpace(aNewCap)); - T* newbuf = aV.template pod_realloc(aV.mBegin, aV.mCapacity, aNewCap); - if (MOZ_UNLIKELY(!newbuf)) { - return false; - } - aV.mBegin = newbuf; - /* aV.mLength is unchanged. */ - aV.mCapacity = aNewCap; - return true; - } - - static inline void - podResizeToFit(Vector& aV) - { - if (aV.usingInlineStorage() || aV.mLength == aV.mCapacity) { - return; - } - T* newbuf = aV.template pod_realloc(aV.mBegin, aV.mCapacity, aV.mLength); - if (MOZ_UNLIKELY(!newbuf)) { - return; - } - aV.mBegin = newbuf; - aV.mCapacity = aV.mLength; - } -}; - -// A struct for TestVector.cpp to access private internal fields. -// DO NOT DEFINE IN YOUR OWN CODE. -struct VectorTesting; - -} // namespace detail - -/* - * STL-like container providing a short-lived, dynamic buffer. Vector calls the - * constructors/destructors of all elements stored in its internal buffer, so - * non-PODs may be safely used. Additionally, Vector will store the first N - * elements in-place before resorting to dynamic allocation. - * - * T requirements: - * - default and copy constructible, assignable, destructible - * - operations do not throw - * MinInlineCapacity requirements: - * - any value, however, MinInlineCapacity is clamped to min/max values - * AllocPolicy: - * - see "Allocation policies" in AllocPolicy.h (defaults to - * mozilla::MallocAllocPolicy) - * - * Vector is not reentrant: T member functions called during Vector member - * functions must not call back into the same object! - */ -template -class Vector final : private AllocPolicy -{ - /* utilities */ - - static const bool kElemIsPod = IsPod::value; - typedef detail::VectorImpl Impl; - friend struct detail::VectorImpl; - - friend struct detail::VectorTesting; - - MOZ_MUST_USE bool growStorageBy(size_t aIncr); - MOZ_MUST_USE bool convertToHeapStorage(size_t aNewCap); - MOZ_MUST_USE bool maybeCheckSimulatedOOM(size_t aRequestedSize); - - /* magic constants */ - - static const int kMaxInlineBytes = 1024; - - /* compute constants */ - - /* - * Consider element size to be 1 for buffer sizing if there are 0 inline - * elements. This allows us to compile when the definition of the element - * type is not visible here. - * - * Explicit specialization is only allowed at namespace scope, so in order - * to keep everything here, we use a dummy template parameter with partial - * specialization. - */ - template - struct ElemSize - { - static const size_t value = sizeof(T); - }; - template - struct ElemSize<0, Dummy> - { - static const size_t value = 1; - }; - - static const size_t kInlineCapacity = - tl::Min::value>::value; - - /* Calculate inline buffer size; avoid 0-sized array. */ - static const size_t kInlineBytes = - tl::Max<1, kInlineCapacity * ElemSize::value>::value; - - /* member data */ - - /* - * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, - * mBegin + mLength) hold valid constructed T objects. The range [mBegin + - * mLength, mBegin + mCapacity) holds uninitialized memory. The range - * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory - * previously allocated by a call to reserve(). - */ - T* mBegin; - - /* Number of elements in the vector. */ - size_t mLength; - - /* Max number of elements storable in the vector without resizing. */ - size_t mCapacity; - -#ifdef DEBUG - /* Max elements of reserved or used space in this vector. */ - size_t mReserved; -#endif - - /* Memory used for inline storage. */ - AlignedStorage mStorage; - -#ifdef DEBUG - friend class ReentrancyGuard; - bool mEntered; -#endif - - /* private accessors */ - - bool usingInlineStorage() const - { - return mBegin == const_cast(this)->inlineStorage(); - } - - T* inlineStorage() - { - return static_cast(mStorage.addr()); - } - - T* beginNoCheck() const - { - return mBegin; - } - - T* endNoCheck() - { - return mBegin + mLength; - } - - const T* endNoCheck() const - { - return mBegin + mLength; - } - -#ifdef DEBUG - /** - * The amount of explicitly allocated space in this vector that is immediately - * available to be filled by appending additional elements. This value is - * always greater than or equal to |length()| -- the vector's actual elements - * are implicitly reserved. This value is always less than or equal to - * |capacity()|. It may be explicitly increased using the |reserve()| method. - */ - size_t reserved() const - { - MOZ_ASSERT(mLength <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - return mReserved; - } -#endif - - /* Append operations guaranteed to succeed due to pre-reserved space. */ - template void internalAppend(U&& aU); - template - void internalAppendAll(const Vector& aU); - void internalAppendN(const T& aT, size_t aN); - template void internalAppend(const U* aBegin, size_t aLength); - -public: - static const size_t sMaxInlineStorage = MinInlineCapacity; - - typedef T ElementType; - - explicit Vector(AllocPolicy = AllocPolicy()); - Vector(Vector&&); /* Move constructor. */ - Vector& operator=(Vector&&); /* Move assignment. */ - ~Vector(); - - /* accessors */ - - const AllocPolicy& allocPolicy() const { return *this; } - - AllocPolicy& allocPolicy() { return *this; } - - enum { InlineLength = MinInlineCapacity }; - - size_t length() const { return mLength; } - - bool empty() const { return mLength == 0; } - - size_t capacity() const { return mCapacity; } - - T* begin() - { - MOZ_ASSERT(!mEntered); - return mBegin; - } - - const T* begin() const - { - MOZ_ASSERT(!mEntered); - return mBegin; - } - - T* end() - { - MOZ_ASSERT(!mEntered); - return mBegin + mLength; - } - - const T* end() const - { - MOZ_ASSERT(!mEntered); - return mBegin + mLength; - } - - T& operator[](size_t aIndex) - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(aIndex < mLength); - return begin()[aIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(aIndex < mLength); - return begin()[aIndex]; - } - - T& back() - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(!empty()); - return *(end() - 1); - } - - const T& back() const - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(!empty()); - return *(end() - 1); - } - - class Range - { - friend class Vector; - T* mCur; - T* mEnd; - Range(T* aCur, T* aEnd) - : mCur(aCur) - , mEnd(aEnd) - { - MOZ_ASSERT(aCur <= aEnd); - } - - public: - bool empty() const { return mCur == mEnd; } - size_t remain() const { return PointerRangeSize(mCur, mEnd); } - T& front() const { MOZ_ASSERT(!empty()); return *mCur; } - void popFront() { MOZ_ASSERT(!empty()); ++mCur; } - T popCopyFront() { MOZ_ASSERT(!empty()); return *mCur++; } - }; - - class ConstRange - { - friend class Vector; - const T* mCur; - const T* mEnd; - ConstRange(const T* aCur, const T* aEnd) - : mCur(aCur) - , mEnd(aEnd) - { - MOZ_ASSERT(aCur <= aEnd); - } - - public: - bool empty() const { return mCur == mEnd; } - size_t remain() const { return PointerRangeSize(mCur, mEnd); } - const T& front() const { MOZ_ASSERT(!empty()); return *mCur; } - void popFront() { MOZ_ASSERT(!empty()); ++mCur; } - T popCopyFront() { MOZ_ASSERT(!empty()); return *mCur++; } - }; - - Range all() { return Range(begin(), end()); } - ConstRange all() const { return ConstRange(begin(), end()); } - - /* mutators */ - - /** - * Reverse the order of the elements in the vector in place. - */ - void reverse(); - - /** - * Given that the vector is empty, grow the internal capacity to |aRequest|, - * keeping the length 0. - */ - MOZ_MUST_USE bool initCapacity(size_t aRequest); - - /** - * Given that the vector is empty, grow the internal capacity and length to - * |aRequest| leaving the elements' memory completely uninitialized (with all - * the associated hazards and caveats). This avoids the usual allocation-size - * rounding that happens in resize and overhead of initialization for elements - * that are about to be overwritten. - */ - MOZ_MUST_USE bool initLengthUninitialized(size_t aRequest); - - /** - * If reserve(aRequest) succeeds and |aRequest >= length()|, then appending - * |aRequest - length()| elements, in any sequence of append/appendAll calls, - * is guaranteed to succeed. - * - * A request to reserve an amount less than the current length does not affect - * reserved space. - */ - MOZ_MUST_USE bool reserve(size_t aRequest); - - /** - * Destroy elements in the range [end() - aIncr, end()). Does not deallocate - * or unreserve storage for those elements. - */ - void shrinkBy(size_t aIncr); - - /** - * Destroy elements in the range [aNewLength, end()). Does not deallocate - * or unreserve storage for those elements. - */ - void shrinkTo(size_t aNewLength); - - /** Grow the vector by aIncr elements. */ - MOZ_MUST_USE bool growBy(size_t aIncr); - - /** Call shrinkBy or growBy based on whether newSize > length(). */ - MOZ_MUST_USE bool resize(size_t aNewLength); - - /** - * Increase the length of the vector, but don't initialize the new elements - * -- leave them as uninitialized memory. - */ - MOZ_MUST_USE bool growByUninitialized(size_t aIncr); - void infallibleGrowByUninitialized(size_t aIncr); - MOZ_MUST_USE bool resizeUninitialized(size_t aNewLength); - - /** Shorthand for shrinkBy(length()). */ - void clear(); - - /** Clears and releases any heap-allocated storage. */ - void clearAndFree(); - - /** - * Calls the AllocPolicy's pod_realloc to release excess capacity. Since - * realloc is only safe on PODs, this method fails to compile if IsPod - * is false. - */ - void podResizeToFit(); - - /** - * If true, appending |aNeeded| elements won't reallocate elements storage. - * This *doesn't* mean that infallibleAppend may be used! You still must - * reserve the extra space, even if this method indicates that appends won't - * need to reallocate elements storage. - */ - bool canAppendWithoutRealloc(size_t aNeeded) const; - - /** Potentially fallible append operations. */ - - /** - * This can take either a T& or a T&&. Given a T&&, it moves |aU| into the - * vector, instead of copying it. If it fails, |aU| is left unmoved. ("We are - * not amused.") - */ - template MOZ_MUST_USE bool append(U&& aU); - - /** - * Construct a T in-place as a new entry at the end of this vector. - */ - template - MOZ_MUST_USE bool emplaceBack(Args&&... aArgs) - { - if (!growByUninitialized(1)) - return false; - Impl::new_(&back(), Forward(aArgs)...); - return true; - } - - template - MOZ_MUST_USE bool appendAll(const Vector& aU); - MOZ_MUST_USE bool appendN(const T& aT, size_t aN); - template MOZ_MUST_USE bool append(const U* aBegin, const U* aEnd); - template MOZ_MUST_USE bool append(const U* aBegin, size_t aLength); - - /* - * Guaranteed-infallible append operations for use upon vectors whose - * memory has been pre-reserved. Don't use this if you haven't reserved the - * memory! - */ - template void infallibleAppend(U&& aU) - { - internalAppend(Forward(aU)); - } - void infallibleAppendN(const T& aT, size_t aN) - { - internalAppendN(aT, aN); - } - template void infallibleAppend(const U* aBegin, const U* aEnd) - { - internalAppend(aBegin, PointerRangeSize(aBegin, aEnd)); - } - template void infallibleAppend(const U* aBegin, size_t aLength) - { - internalAppend(aBegin, aLength); - } - template - void infallibleEmplaceBack(Args&&... aArgs) - { - infallibleGrowByUninitialized(1); - Impl::new_(&back(), Forward(aArgs)...); - } - - void popBack(); - - T popCopy(); - - /** - * If elements are stored in-place, return nullptr and leave this vector - * unmodified. - * - * Otherwise return this vector's elements buffer, and clear this vector as if - * by clearAndFree(). The caller now owns the buffer and is responsible for - * deallocating it consistent with this vector's AllocPolicy. - * - * N.B. Although a T*, only the range [0, length()) is constructed. - */ - MOZ_MUST_USE T* extractRawBuffer(); - - /** - * If elements are stored in-place, allocate a new buffer, move this vector's - * elements into it, and return that buffer. - * - * Otherwise return this vector's elements buffer. The caller now owns the - * buffer and is responsible for deallocating it consistent with this vector's - * AllocPolicy. - * - * This vector is cleared, as if by clearAndFree(), when this method - * succeeds. This method fails and returns nullptr only if new elements buffer - * allocation fails. - * - * N.B. Only the range [0, length()) of the returned buffer is constructed. - * If any of these elements are uninitialized (as growByUninitialized - * enables), behavior is undefined. - */ - MOZ_MUST_USE T* extractOrCopyRawBuffer(); - - /** - * Transfer ownership of an array of objects into the vector. The caller - * must have allocated the array in accordance with this vector's - * AllocPolicy. - * - * N.B. This call assumes that there are no uninitialized elements in the - * passed array. - */ - void replaceRawBuffer(T* aP, size_t aLength); - - /** - * Places |aVal| at position |aP|, shifting existing elements from |aP| onward - * one position higher. On success, |aP| should not be reused because it'll - * be a dangling pointer if reallocation of the vector storage occurred; the - * return value should be used instead. On failure, nullptr is returned. - * - * Example usage: - * - * if (!(p = vec.insert(p, val))) { - * - * } - * - * - * This is inherently a linear-time operation. Be careful! - */ - template - MOZ_MUST_USE T* insert(T* aP, U&& aVal); - - /** - * Removes the element |aT|, which must fall in the bounds [begin, end), - * shifting existing elements from |aT + 1| onward one position lower. - */ - void erase(T* aT); - - /** - * Removes the elements [|aBegin|, |aEnd|), which must fall in the bounds - * [begin, end), shifting existing elements from |aEnd + 1| onward to aBegin's - * old position. - */ - void erase(T* aBegin, T* aEnd); - - /** - * Measure the size of the vector's heap-allocated storage. - */ - size_t sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const; - - /** - * Like sizeOfExcludingThis, but also measures the size of the vector - * object (which must be heap-allocated) itself. - */ - size_t sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const; - - void swap(Vector& aOther); - -private: - Vector(const Vector&) = delete; - void operator=(const Vector&) = delete; -}; - -/* This does the re-entrancy check plus several other sanity checks. */ -#define MOZ_REENTRANCY_GUARD_ET_AL \ - ReentrancyGuard g(*this); \ - MOZ_ASSERT_IF(usingInlineStorage(), mCapacity == kInlineCapacity); \ - MOZ_ASSERT(reserved() <= mCapacity); \ - MOZ_ASSERT(mLength <= reserved()); \ - MOZ_ASSERT(mLength <= mCapacity) - -/* Vector Implementation */ - -template -MOZ_ALWAYS_INLINE -Vector::Vector(AP aAP) - : AP(aAP) - , mLength(0) - , mCapacity(kInlineCapacity) -#ifdef DEBUG - , mReserved(0) - , mEntered(false) -#endif -{ - mBegin = static_cast(mStorage.addr()); -} - -/* Move constructor. */ -template -MOZ_ALWAYS_INLINE -Vector::Vector(Vector&& aRhs) - : AllocPolicy(Move(aRhs)) -#ifdef DEBUG - , mEntered(false) -#endif -{ - mLength = aRhs.mLength; - mCapacity = aRhs.mCapacity; -#ifdef DEBUG - mReserved = aRhs.mReserved; -#endif - - if (aRhs.usingInlineStorage()) { - /* We can't move the buffer over in this case, so copy elements. */ - mBegin = static_cast(mStorage.addr()); - Impl::moveConstruct(mBegin, aRhs.beginNoCheck(), aRhs.endNoCheck()); - /* - * Leave aRhs's mLength, mBegin, mCapacity, and mReserved as they are. - * The elements in its in-line storage still need to be destroyed. - */ - } else { - /* - * Take src's buffer, and turn src into an empty vector using - * in-line storage. - */ - mBegin = aRhs.mBegin; - aRhs.mBegin = static_cast(aRhs.mStorage.addr()); - aRhs.mCapacity = kInlineCapacity; - aRhs.mLength = 0; -#ifdef DEBUG - aRhs.mReserved = 0; -#endif - } -} - -/* Move assignment. */ -template -MOZ_ALWAYS_INLINE Vector& -Vector::operator=(Vector&& aRhs) -{ - MOZ_ASSERT(this != &aRhs, "self-move assignment is prohibited"); - this->~Vector(); - new(KnownNotNull, this) Vector(Move(aRhs)); - return *this; -} - -template -MOZ_ALWAYS_INLINE -Vector::~Vector() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) { - this->free_(beginNoCheck()); - } -} - -template -MOZ_ALWAYS_INLINE void -Vector::reverse() { - MOZ_REENTRANCY_GUARD_ET_AL; - T* elems = mBegin; - size_t len = mLength; - size_t mid = len / 2; - for (size_t i = 0; i < mid; i++) { - Swap(elems[i], elems[len - i - 1]); - } -} - -/* - * This function will create a new heap buffer with capacity aNewCap, - * move all elements in the inline buffer to this new buffer, - * and fail on OOM. - */ -template -inline bool -Vector::convertToHeapStorage(size_t aNewCap) -{ - MOZ_ASSERT(usingInlineStorage()); - - /* Allocate buffer. */ - MOZ_ASSERT(!detail::CapacityHasExcessSpace(aNewCap)); - T* newBuf = this->template pod_malloc(aNewCap); - if (MOZ_UNLIKELY(!newBuf)) { - return false; - } - - /* Copy inline elements into heap buffer. */ - Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - - /* Switch in heap buffer. */ - mBegin = newBuf; - /* mLength is unchanged. */ - mCapacity = aNewCap; - return true; -} - -template -MOZ_NEVER_INLINE bool -Vector::growStorageBy(size_t aIncr) -{ - MOZ_ASSERT(mLength + aIncr > mCapacity); - - /* - * When choosing a new capacity, its size should is as close to 2**N bytes - * as possible. 2**N-sized requests are best because they are unlikely to - * be rounded up by the allocator. Asking for a 2**N number of elements - * isn't as good, because if sizeof(T) is not a power-of-two that would - * result in a non-2**N request size. - */ - - size_t newCap; - - if (aIncr == 1) { - if (usingInlineStorage()) { - /* This case occurs in ~70--80% of the calls to this function. */ - size_t newSize = - tl::RoundUpPow2<(kInlineCapacity + 1) * sizeof(T)>::value; - newCap = newSize / sizeof(T); - goto convert; - } - - if (mLength == 0) { - /* This case occurs in ~0--10% of the calls to this function. */ - newCap = 1; - goto grow; - } - - /* This case occurs in ~15--20% of the calls to this function. */ - - /* - * Will mLength * 4 *sizeof(T) overflow? This condition limits a vector - * to 1GB of memory on a 32-bit system, which is a reasonable limit. It - * also ensures that - * - * static_cast(end()) - static_cast(begin()) - * - * doesn't overflow ptrdiff_t (see bug 510319). - */ - if (MOZ_UNLIKELY(mLength & tl::MulOverflowMask<4 * sizeof(T)>::value)) { - this->reportAllocOverflow(); - return false; - } - - /* - * If we reach here, the existing capacity will have a size that is already - * as close to 2^N as sizeof(T) will allow. Just double the capacity, and - * then there might be space for one more element. - */ - newCap = mLength * 2; - if (detail::CapacityHasExcessSpace(newCap)) { - newCap += 1; - } - } else { - /* This case occurs in ~2% of the calls to this function. */ - size_t newMinCap = mLength + aIncr; - - /* Did mLength + aIncr overflow? Will newCap * sizeof(T) overflow? */ - if (MOZ_UNLIKELY(newMinCap < mLength || - newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::value)) - { - this->reportAllocOverflow(); - return false; - } - - size_t newMinSize = newMinCap * sizeof(T); - size_t newSize = RoundUpPow2(newMinSize); - newCap = newSize / sizeof(T); - } - - if (usingInlineStorage()) { -convert: - return convertToHeapStorage(newCap); - } - -grow: - return Impl::growTo(*this, newCap); -} - -template -inline bool -Vector::initCapacity(size_t aRequest) -{ - MOZ_ASSERT(empty()); - MOZ_ASSERT(usingInlineStorage()); - if (aRequest == 0) { - return true; - } - T* newbuf = this->template pod_malloc(aRequest); - if (MOZ_UNLIKELY(!newbuf)) { - return false; - } - mBegin = newbuf; - mCapacity = aRequest; -#ifdef DEBUG - mReserved = aRequest; -#endif - return true; -} - -template -inline bool -Vector::initLengthUninitialized(size_t aRequest) -{ - if (!initCapacity(aRequest)) { - return false; - } - infallibleGrowByUninitialized(aRequest); - return true; -} - -template -inline bool -Vector::maybeCheckSimulatedOOM(size_t aRequestedSize) -{ - if (aRequestedSize <= N) { - return true; - } - -#ifdef DEBUG - if (aRequestedSize <= mReserved) { - return true; - } -#endif - - return allocPolicy().checkSimulatedOOM(); -} - -template -inline bool -Vector::reserve(size_t aRequest) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (aRequest > mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(aRequest - mLength))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(aRequest)) { - return false; - } -#ifdef DEBUG - if (aRequest > mReserved) { - mReserved = aRequest; - } - MOZ_ASSERT(mLength <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); -#endif - return true; -} - -template -inline void -Vector::shrinkBy(size_t aIncr) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - MOZ_ASSERT(aIncr <= mLength); - Impl::destroy(endNoCheck() - aIncr, endNoCheck()); - mLength -= aIncr; -} - -template -MOZ_ALWAYS_INLINE void -Vector::shrinkTo(size_t aNewLength) -{ - MOZ_ASSERT(aNewLength <= mLength); - shrinkBy(mLength - aNewLength); -} - -template -MOZ_ALWAYS_INLINE bool -Vector::growBy(size_t aIncr) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (aIncr > mCapacity - mLength) { - if (MOZ_UNLIKELY(!growStorageBy(aIncr))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aIncr)) { - return false; - } - MOZ_ASSERT(mLength + aIncr <= mCapacity); - T* newend = endNoCheck() + aIncr; - Impl::initialize(endNoCheck(), newend); - mLength += aIncr; -#ifdef DEBUG - if (mLength > mReserved) { - mReserved = mLength; - } -#endif - return true; -} - -template -MOZ_ALWAYS_INLINE bool -Vector::growByUninitialized(size_t aIncr) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (aIncr > mCapacity - mLength) { - if (MOZ_UNLIKELY(!growStorageBy(aIncr))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aIncr)) { - return false; - } -#ifdef DEBUG - if (mLength + aIncr > mReserved) { - mReserved = mLength + aIncr; - } -#endif - infallibleGrowByUninitialized(aIncr); - return true; -} - -template -MOZ_ALWAYS_INLINE void -Vector::infallibleGrowByUninitialized(size_t aIncr) -{ - MOZ_ASSERT(mLength + aIncr <= reserved()); - mLength += aIncr; -} - -template -inline bool -Vector::resize(size_t aNewLength) -{ - size_t curLength = mLength; - if (aNewLength > curLength) { - return growBy(aNewLength - curLength); - } - shrinkBy(curLength - aNewLength); - return true; -} - -template -MOZ_ALWAYS_INLINE bool -Vector::resizeUninitialized(size_t aNewLength) -{ - size_t curLength = mLength; - if (aNewLength > curLength) { - return growByUninitialized(aNewLength - curLength); - } - shrinkBy(curLength - aNewLength); - return true; -} - -template -inline void -Vector::clear() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - mLength = 0; -} - -template -inline void -Vector::clearAndFree() -{ - clear(); - - if (usingInlineStorage()) { - return; - } - this->free_(beginNoCheck()); - mBegin = static_cast(mStorage.addr()); - mCapacity = kInlineCapacity; -#ifdef DEBUG - mReserved = 0; -#endif -} - -template -inline void -Vector::podResizeToFit() -{ - // This function is only defined if IsPod is true and will fail to compile - // otherwise. - Impl::podResizeToFit(*this); -} - -template -inline bool -Vector::canAppendWithoutRealloc(size_t aNeeded) const -{ - return mLength + aNeeded <= mCapacity; -} - -template -template -MOZ_ALWAYS_INLINE void -Vector::internalAppendAll(const Vector& aOther) -{ - internalAppend(aOther.begin(), aOther.length()); -} - -template -template -MOZ_ALWAYS_INLINE void -Vector::internalAppend(U&& aU) -{ - MOZ_ASSERT(mLength + 1 <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - Impl::new_(endNoCheck(), Forward(aU)); - ++mLength; -} - -template -MOZ_ALWAYS_INLINE bool -Vector::appendN(const T& aT, size_t aNeeded) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (mLength + aNeeded > mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(aNeeded))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aNeeded)) { - return false; - } -#ifdef DEBUG - if (mLength + aNeeded > mReserved) { - mReserved = mLength + aNeeded; - } -#endif - internalAppendN(aT, aNeeded); - return true; -} - -template -MOZ_ALWAYS_INLINE void -Vector::internalAppendN(const T& aT, size_t aNeeded) -{ - MOZ_ASSERT(mLength + aNeeded <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - Impl::copyConstructN(endNoCheck(), aNeeded, aT); - mLength += aNeeded; -} - -template -template -inline T* -Vector::insert(T* aP, U&& aVal) -{ - MOZ_ASSERT(begin() <= aP); - MOZ_ASSERT(aP <= end()); - size_t pos = aP - begin(); - MOZ_ASSERT(pos <= mLength); - size_t oldLength = mLength; - if (pos == oldLength) { - if (!append(Forward(aVal))) { - return nullptr; - } - } else { - T oldBack = Move(back()); - if (!append(Move(oldBack))) { /* Dup the last element. */ - return nullptr; - } - for (size_t i = oldLength; i > pos; --i) { - (*this)[i] = Move((*this)[i - 1]); - } - (*this)[pos] = Forward(aVal); - } - return begin() + pos; -} - -template -inline void -Vector::erase(T* aIt) -{ - MOZ_ASSERT(begin() <= aIt); - MOZ_ASSERT(aIt < end()); - while (aIt + 1 < end()) { - *aIt = Move(*(aIt + 1)); - ++aIt; - } - popBack(); -} - -template -inline void -Vector::erase(T* aBegin, T* aEnd) -{ - MOZ_ASSERT(begin() <= aBegin); - MOZ_ASSERT(aBegin <= aEnd); - MOZ_ASSERT(aEnd <= end()); - while (aEnd < end()) { - *aBegin++ = Move(*aEnd++); - } - shrinkBy(aEnd - aBegin); -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::append(const U* aInsBegin, const U* aInsEnd) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - size_t aNeeded = PointerRangeSize(aInsBegin, aInsEnd); - if (mLength + aNeeded > mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(aNeeded))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aNeeded)) { - return false; - } -#ifdef DEBUG - if (mLength + aNeeded > mReserved) { - mReserved = mLength + aNeeded; - } -#endif - internalAppend(aInsBegin, aNeeded); - return true; -} - -template -template -MOZ_ALWAYS_INLINE void -Vector::internalAppend(const U* aInsBegin, size_t aInsLength) -{ - MOZ_ASSERT(mLength + aInsLength <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - Impl::copyConstruct(endNoCheck(), aInsBegin, aInsBegin + aInsLength); - mLength += aInsLength; -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::append(U&& aU) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (mLength == mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(1))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + 1)) { - return false; - } -#ifdef DEBUG - if (mLength + 1 > mReserved) { - mReserved = mLength + 1; - } -#endif - internalAppend(Forward(aU)); - return true; -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::appendAll(const Vector& aOther) -{ - return append(aOther.begin(), aOther.length()); -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::append(const U* aInsBegin, size_t aInsLength) -{ - return append(aInsBegin, aInsBegin + aInsLength); -} - -template -MOZ_ALWAYS_INLINE void -Vector::popBack() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - MOZ_ASSERT(!empty()); - --mLength; - endNoCheck()->~T(); -} - -template -MOZ_ALWAYS_INLINE T -Vector::popCopy() -{ - T ret = back(); - popBack(); - return ret; -} - -template -inline T* -Vector::extractRawBuffer() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - - if (usingInlineStorage()) { - return nullptr; - } - - T* ret = mBegin; - mBegin = static_cast(mStorage.addr()); - mLength = 0; - mCapacity = kInlineCapacity; -#ifdef DEBUG - mReserved = 0; -#endif - return ret; -} - -template -inline T* -Vector::extractOrCopyRawBuffer() -{ - if (T* ret = extractRawBuffer()) { - return ret; - } - - MOZ_REENTRANCY_GUARD_ET_AL; - - T* copy = this->template pod_malloc(mLength); - if (!copy) { - return nullptr; - } - - Impl::moveConstruct(copy, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - mBegin = static_cast(mStorage.addr()); - mLength = 0; - mCapacity = kInlineCapacity; -#ifdef DEBUG - mReserved = 0; -#endif - return copy; -} - -template -inline void -Vector::replaceRawBuffer(T* aP, size_t aLength) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - - /* Destroy what we have. */ - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) { - this->free_(beginNoCheck()); - } - - /* Take in the new buffer. */ - if (aLength <= kInlineCapacity) { - /* - * We convert to inline storage if possible, even though aP might - * otherwise be acceptable. Maybe this behaviour should be - * specifiable with an argument to this function. - */ - mBegin = static_cast(mStorage.addr()); - mLength = aLength; - mCapacity = kInlineCapacity; - Impl::moveConstruct(mBegin, aP, aP + aLength); - Impl::destroy(aP, aP + aLength); - this->free_(aP); - } else { - mBegin = aP; - mLength = aLength; - mCapacity = aLength; - } -#ifdef DEBUG - mReserved = aLength; -#endif -} - -template -inline size_t -Vector::sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const -{ - return usingInlineStorage() ? 0 : aMallocSizeOf(beginNoCheck()); -} - -template -inline size_t -Vector::sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const -{ - return aMallocSizeOf(this) + sizeOfExcludingThis(aMallocSizeOf); -} - -template -inline void -Vector::swap(Vector& aOther) -{ - static_assert(N == 0, - "still need to implement this for N != 0"); - - // This only works when inline storage is always empty. - if (!usingInlineStorage() && aOther.usingInlineStorage()) { - aOther.mBegin = mBegin; - mBegin = inlineStorage(); - } else if (usingInlineStorage() && !aOther.usingInlineStorage()) { - mBegin = aOther.mBegin; - aOther.mBegin = aOther.inlineStorage(); - } else if (!usingInlineStorage() && !aOther.usingInlineStorage()) { - Swap(mBegin, aOther.mBegin); - } else { - // This case is a no-op, since we'd set both to use their inline storage. - } - - Swap(mLength, aOther.mLength); - Swap(mCapacity, aOther.mCapacity); -#ifdef DEBUG - Swap(mReserved, aOther.mReserved); -#endif -} - -} // namespace mozilla - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif /* mozilla_Vector_h */ diff --git a/mac/include/spidermonkey/mozilla/WeakPtr.h b/mac/include/spidermonkey/mozilla/WeakPtr.h deleted file mode 100644 index ef0c19f4..00000000 --- a/mac/include/spidermonkey/mozilla/WeakPtr.h +++ /dev/null @@ -1,283 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Weak pointer functionality, implemented as a mixin for use with any class. */ - -/** - * SupportsWeakPtr lets you have a pointer to an object 'Foo' without affecting - * its lifetime. It works by creating a single shared reference counted object - * (WeakReference) that each WeakPtr will access 'Foo' through. This lets 'Foo' - * clear the pointer in the WeakReference without having to know about all of - * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime - * of 'Foo'. - * - * PLEASE NOTE: This weak pointer implementation is not thread-safe. - * - * Note that when deriving from SupportsWeakPtr you should add - * MOZ_DECLARE_WEAKREFERENCE_TYPENAME(ClassName) to the public section of your - * class, where ClassName is the name of your class. - * - * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional - * dereference, and an additional heap allocated pointer sized object shared - * between all of the WeakPtrs. - * - * Example of usage: - * - * // To have a class C support weak pointers, inherit from - * // SupportsWeakPtr. - * class C : public SupportsWeakPtr - * { - * public: - * MOZ_DECLARE_WEAKREFERENCE_TYPENAME(C) - * int mNum; - * void act(); - * }; - * - * C* ptr = new C(); - * - * // Get weak pointers to ptr. The first time a weak pointer - * // is obtained, a reference counted WeakReference object is created that - * // can live beyond the lifetime of 'ptr'. The WeakReference - * // object will be notified of 'ptr's destruction. - * WeakPtr weak = ptr; - * WeakPtr other = ptr; - * - * // Test a weak pointer for validity before using it. - * if (weak) { - * weak->mNum = 17; - * weak->act(); - * } - * - * // Destroying the underlying object clears weak pointers to it. - * delete ptr; - * - * MOZ_ASSERT(!weak, "Deleting |ptr| clears weak pointers to it."); - * MOZ_ASSERT(!other, "Deleting |ptr| clears all weak pointers to it."); - * - * WeakPtr is typesafe and may be used with any class. It is not required that - * the class be reference-counted or allocated in any particular way. - * - * The API was loosely inspired by Chromium's weak_ptr.h: - * http://src.chromium.org/svn/trunk/src/base/memory/weak_ptr.h - */ - -#ifndef mozilla_WeakPtr_h -#define mozilla_WeakPtr_h - -#include "mozilla/ArrayUtils.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/RefCounted.h" -#include "mozilla/RefPtr.h" -#include "mozilla/TypeTraits.h" - -#include - -// Weak referencing is not implemeted as thread safe. When a WeakPtr -// is created or dereferenced on thread A but the real object is just -// being Released() on thread B, there is a possibility of a race -// when the proxy object (detail::WeakReference) is notified about -// the real object destruction just between when thread A is storing -// the object pointer locally and is about to add a reference to it. -// -// Hence, a non-null weak proxy object is considered to have a single -// "owning thread". It means that each query for a weak reference, -// its dereference, and destruction of the real object must all happen -// on a single thread. The following macros implement assertions for -// checking these conditions. -// -// We disable this on MinGW. MinGW has two threading models: win32 -// API based, which disables std::thread; and POSIX based which -// enables it but requires an emulation library (winpthreads). -// Rather than attempting to switch to pthread emulation at this point, -// we are disabling the std::thread based assertion checking. -// -// In the future, to enable it we could -// a. have libgcc/stdc++ support win32 threads natively -// b. switch to POSIX-based threading in MinGW with pthread emulation -// c. refactor it to not use std::thread - -#if !defined(__MINGW32__) && (defined(DEBUG) || (defined(NIGHTLY_BUILD) && !defined(MOZ_PROFILING))) - -#include -#define MOZ_WEAKPTR_DECLARE_THREAD_SAFETY_CHECK \ - std::thread::id _owningThread; \ - bool _empty; // If it was initialized as a placeholder with mPtr = nullptr. -#define MOZ_WEAKPTR_INIT_THREAD_SAFETY_CHECK() \ - do { \ - _owningThread = std::this_thread::get_id(); \ - _empty = !p; \ - } while (false) -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY() \ - MOZ_DIAGNOSTIC_ASSERT(_empty || _owningThread == std::this_thread::get_id(), \ - "WeakPtr used on multiple threads") -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(that) \ - (that)->AssertThreadSafety(); - -#define MOZ_WEAKPTR_THREAD_SAFETY_CHECKING 1 - -#else - -#define MOZ_WEAKPTR_DECLARE_THREAD_SAFETY_CHECK -#define MOZ_WEAKPTR_INIT_THREAD_SAFETY_CHECK() do { } while (false) -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY() do { } while (false) -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(that) do { } while (false) - -#endif - -namespace mozilla { - -template class WeakPtr; -template class SupportsWeakPtr; - -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING -#define MOZ_DECLARE_WEAKREFERENCE_TYPENAME(T) \ - static const char* weakReferenceTypeName() { return "WeakReference<" #T ">"; } -#else -#define MOZ_DECLARE_WEAKREFERENCE_TYPENAME(T) -#endif - -namespace detail { - -// This can live beyond the lifetime of the class derived from -// SupportsWeakPtr. -template -class WeakReference : public ::mozilla::RefCounted > -{ -public: - explicit WeakReference(T* p) : mPtr(p) - { - MOZ_WEAKPTR_INIT_THREAD_SAFETY_CHECK(); - } - - T* get() const { - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY(); - return mPtr; - } - -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING - const char* typeName() const - { - // The first time this is called mPtr is null, so don't - // invoke any methods on mPtr. - return T::weakReferenceTypeName(); - } - size_t typeSize() const { return sizeof(*this); } -#endif - -#ifdef MOZ_WEAKPTR_THREAD_SAFETY_CHECKING - void AssertThreadSafety() { MOZ_WEAKPTR_ASSERT_THREAD_SAFETY(); } -#endif - -private: - friend class mozilla::SupportsWeakPtr; - - void detach() { - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY(); - mPtr = nullptr; - } - - T* MOZ_NON_OWNING_REF mPtr; - MOZ_WEAKPTR_DECLARE_THREAD_SAFETY_CHECK -}; - -} // namespace detail - -template -class SupportsWeakPtr -{ -protected: - ~SupportsWeakPtr() - { - static_assert(IsBaseOf, T>::value, - "T must derive from SupportsWeakPtr"); - if (mSelfReferencingWeakPtr) { - mSelfReferencingWeakPtr.mRef->detach(); - } - } - -private: - const WeakPtr& SelfReferencingWeakPtr() - { - if (!mSelfReferencingWeakPtr) { - mSelfReferencingWeakPtr.mRef = new detail::WeakReference(static_cast(this)); - } else { - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(mSelfReferencingWeakPtr.mRef); - } - return mSelfReferencingWeakPtr; - } - - const WeakPtr& SelfReferencingWeakPtr() const - { - const WeakPtr& p = const_cast(this)->SelfReferencingWeakPtr(); - return reinterpret_cast&>(p); - } - - friend class WeakPtr; - friend class WeakPtr; - - WeakPtr mSelfReferencingWeakPtr; -}; - -template -class WeakPtr -{ - typedef detail::WeakReference WeakReference; - -public: - WeakPtr& operator=(const WeakPtr& aOther) - { - mRef = aOther.mRef; - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(mRef); - return *this; - } - - WeakPtr(const WeakPtr& aOther) - { - // The thread safety check is performed inside of the operator= method. - *this = aOther; - } - - WeakPtr& operator=(T* aOther) - { - if (aOther) { - *this = aOther->SelfReferencingWeakPtr(); - } else if (!mRef || mRef->get()) { - // Ensure that mRef is dereferenceable in the uninitialized state. - mRef = new WeakReference(nullptr); - } - // The thread safety check happens inside SelfReferencingWeakPtr - // or is initialized in the WeakReference constructor. - return *this; - } - - MOZ_IMPLICIT WeakPtr(T* aOther) - { - *this = aOther; - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(mRef); - } - - // Ensure that mRef is dereferenceable in the uninitialized state. - WeakPtr() : mRef(new WeakReference(nullptr)) {} - - operator T*() const { return mRef->get(); } - T& operator*() const { return *mRef->get(); } - - T* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN { return mRef->get(); } - - T* get() const { return mRef->get(); } - -private: - friend class SupportsWeakPtr; - - explicit WeakPtr(const RefPtr& aOther) : mRef(aOther) {} - - RefPtr mRef; -}; - -} // namespace mozilla - -#endif /* mozilla_WeakPtr_h */ diff --git a/mac/include/spidermonkey/mozilla/XorShift128PlusRNG.h b/mac/include/spidermonkey/mozilla/XorShift128PlusRNG.h deleted file mode 100644 index 2f182f0f..00000000 --- a/mac/include/spidermonkey/mozilla/XorShift128PlusRNG.h +++ /dev/null @@ -1,121 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* The xorshift128+ pseudo-random number generator. */ - -#ifndef mozilla_XorShift128Plus_h -#define mozilla_XorShift128Plus_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/FloatingPoint.h" - -#include - -namespace mozilla { -namespace non_crypto { - -/* - * A stream of pseudo-random numbers generated using the xorshift+ technique - * described here: - * - * Vigna, Sebastiano (2014). "Further scramblings of Marsaglia's xorshift - * generators". arXiv:1404.0390 (http://arxiv.org/abs/1404.0390) - * - * That paper says: - * - * In particular, we propose a tightly coded xorshift128+ generator that - * does not fail systematically any test from the BigCrush suite of TestU01 - * (even reversed) and generates 64 pseudorandom bits in 1.10 ns on an - * Intel(R) Core(TM) i7-4770 CPU @3.40GHz (Haswell). It is the fastest - * generator we are aware of with such empirical statistical properties. - * - * The stream of numbers produced by this method repeats every 2**128 - 1 calls - * (i.e. never, for all practical purposes). Zero appears 2**64 - 1 times in - * this period; all other numbers appear 2**64 times. Additionally, each *bit* - * in the produced numbers repeats every 2**128 - 1 calls. - * - * This generator is not suitable as a cryptographically secure random number - * generator. - */ -class XorShift128PlusRNG { - uint64_t mState[2]; - - public: - /* - * Construct a xorshift128+ pseudo-random number stream using |aInitial0| and - * |aInitial1| as the initial state. These MUST NOT both be zero. - * - * If the initial states contain many zeros, for a few iterations you'll see - * many zeroes in the generated numbers. It's suggested to seed a SplitMix64 - * generator and use its first two - * outputs to seed xorshift128+. - */ - XorShift128PlusRNG(uint64_t aInitial0, uint64_t aInitial1) { - setState(aInitial0, aInitial1); - } - - /** - * Return a pseudo-random 64-bit number. - */ - uint64_t next() { - /* - * The offsetOfState*() methods below are provided so that exceedingly-rare - * callers that want to observe or poke at RNG state in C++ type-system- - * ignoring means can do so. Don't change the next() or nextDouble() - * algorithms without altering code that uses offsetOfState*()! - */ - uint64_t s1 = mState[0]; - const uint64_t s0 = mState[1]; - mState[0] = s0; - s1 ^= s1 << 23; - mState[1] = s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26); - return mState[1] + s0; - } - - /* - * Return a pseudo-random floating-point value in the range [0, 1). More - * precisely, choose an integer in the range [0, 2**53) and divide it by - * 2**53. Given the 2**128 - 1 period noted above, the produced doubles are - * all but uniformly distributed in this range. - */ - double nextDouble() { - /* - * Because the IEEE 64-bit floating point format stores the leading '1' bit - * of the mantissa implicitly, it effectively represents a mantissa in the - * range [0, 2**53) in only 52 bits. FloatingPoint::kExponentShift - * is the width of the bitfield in the in-memory format, so we must add one - * to get the mantissa's range. - */ - static constexpr int kMantissaBits = - mozilla::FloatingPoint::kExponentShift + 1; - uint64_t mantissa = next() & ((UINT64_C(1) << kMantissaBits) - 1); - return double(mantissa) / (UINT64_C(1) << kMantissaBits); - } - - /* - * Set the stream's current state to |aState0| and |aState1|. These must not - * both be zero; ideally, they should have an almost even mix of zero and one - * bits. - */ - void setState(uint64_t aState0, uint64_t aState1) { - MOZ_ASSERT(aState0 || aState1); - mState[0] = aState0; - mState[1] = aState1; - } - - static size_t offsetOfState0() { - return offsetof(XorShift128PlusRNG, mState[0]); - } - static size_t offsetOfState1() { - return offsetof(XorShift128PlusRNG, mState[1]); - } -}; - -} // namespace non_crypto -} // namespace mozilla - -#endif // mozilla_XorShift128Plus_h diff --git a/mac/include/spidermonkey/mozilla/double-conversion.h b/mac/include/spidermonkey/mozilla/double-conversion.h deleted file mode 100644 index 957575cf..00000000 --- a/mac/include/spidermonkey/mozilla/double-conversion.h +++ /dev/null @@ -1,538 +0,0 @@ -// Copyright 2012 the V8 project authors. All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following -// disclaimer in the documentation and/or other materials provided -// with the distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ -#define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ - -#include "mozilla/Types.h" -#include "utils.h" - -namespace double_conversion { - -class DoubleToStringConverter { - public: - // When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint - // or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the - // function returns false. - static const int kMaxFixedDigitsBeforePoint = 60; - static const int kMaxFixedDigitsAfterPoint = 60; - - // When calling ToExponential with a requested_digits - // parameter > kMaxExponentialDigits then the function returns false. - static const int kMaxExponentialDigits = 120; - - // When calling ToPrecision with a requested_digits - // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits - // then the function returns false. - static const int kMinPrecisionDigits = 1; - static const int kMaxPrecisionDigits = 120; - - enum Flags { - NO_FLAGS = 0, - EMIT_POSITIVE_EXPONENT_SIGN = 1, - EMIT_TRAILING_DECIMAL_POINT = 2, - EMIT_TRAILING_ZERO_AFTER_POINT = 4, - UNIQUE_ZERO = 8 - }; - - // Flags should be a bit-or combination of the possible Flags-enum. - // - NO_FLAGS: no special flags. - // - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent - // form, emits a '+' for positive exponents. Example: 1.2e+2. - // - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is - // converted into decimal format then a trailing decimal point is appended. - // Example: 2345.0 is converted to "2345.". - // - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point - // emits a trailing '0'-character. This flag requires the - // EXMIT_TRAILING_DECIMAL_POINT flag. - // Example: 2345.0 is converted to "2345.0". - // - UNIQUE_ZERO: "-0.0" is converted to "0.0". - // - // Infinity symbol and nan_symbol provide the string representation for these - // special values. If the string is NULL and the special value is encountered - // then the conversion functions return false. - // - // The exponent_character is used in exponential representations. It is - // usually 'e' or 'E'. - // - // When converting to the shortest representation the converter will - // represent input numbers in decimal format if they are in the interval - // [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[ - // (lower boundary included, greater boundary excluded). - // Example: with decimal_in_shortest_low = -6 and - // decimal_in_shortest_high = 21: - // ToShortest(0.000001) -> "0.000001" - // ToShortest(0.0000001) -> "1e-7" - // ToShortest(111111111111111111111.0) -> "111111111111111110000" - // ToShortest(100000000000000000000.0) -> "100000000000000000000" - // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21" - // - // When converting to precision mode the converter may add - // max_leading_padding_zeroes before returning the number in exponential - // format. - // Example with max_leading_padding_zeroes_in_precision_mode = 6. - // ToPrecision(0.0000012345, 2) -> "0.0000012" - // ToPrecision(0.00000012345, 2) -> "1.2e-7" - // Similarily the converter may add up to - // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid - // returning an exponential representation. A zero added by the - // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit. - // Examples for max_trailing_padding_zeroes_in_precision_mode = 1: - // ToPrecision(230.0, 2) -> "230" - // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT. - // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT. - DoubleToStringConverter(int flags, - const char* infinity_symbol, - const char* nan_symbol, - char exponent_character, - int decimal_in_shortest_low, - int decimal_in_shortest_high, - int max_leading_padding_zeroes_in_precision_mode, - int max_trailing_padding_zeroes_in_precision_mode) - : flags_(flags), - infinity_symbol_(infinity_symbol), - nan_symbol_(nan_symbol), - exponent_character_(exponent_character), - decimal_in_shortest_low_(decimal_in_shortest_low), - decimal_in_shortest_high_(decimal_in_shortest_high), - max_leading_padding_zeroes_in_precision_mode_( - max_leading_padding_zeroes_in_precision_mode), - max_trailing_padding_zeroes_in_precision_mode_( - max_trailing_padding_zeroes_in_precision_mode) { - // When 'trailing zero after the point' is set, then 'trailing point' - // must be set too. - ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) || - !((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0)); - } - - // Returns a converter following the EcmaScript specification. - static MFBT_API const DoubleToStringConverter& EcmaScriptConverter(); - - // Computes the shortest string of digits that correctly represent the input - // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high - // (see constructor) it then either returns a decimal representation, or an - // exponential representation. - // Example with decimal_in_shortest_low = -6, - // decimal_in_shortest_high = 21, - // EMIT_POSITIVE_EXPONENT_SIGN activated, and - // EMIT_TRAILING_DECIMAL_POINT deactived: - // ToShortest(0.000001) -> "0.000001" - // ToShortest(0.0000001) -> "1e-7" - // ToShortest(111111111111111111111.0) -> "111111111111111110000" - // ToShortest(100000000000000000000.0) -> "100000000000000000000" - // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21" - // - // Note: the conversion may round the output if the returned string - // is accurate enough to uniquely identify the input-number. - // For example the most precise representation of the double 9e59 equals - // "899999999999999918767229449717619953810131273674690656206848", but - // the converter will return the shorter (but still correct) "9e59". - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except when the input value is special and no infinity_symbol or - // nan_symbol has been given to the constructor. - bool ToShortest(double value, StringBuilder* result_builder) const { - return ToShortestIeeeNumber(value, result_builder, SHORTEST); - } - - // Same as ToShortest, but for single-precision floats. - bool ToShortestSingle(float value, StringBuilder* result_builder) const { - return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE); - } - - - // Computes a decimal representation with a fixed number of digits after the - // decimal point. The last emitted digit is rounded. - // - // Examples: - // ToFixed(3.12, 1) -> "3.1" - // ToFixed(3.1415, 3) -> "3.142" - // ToFixed(1234.56789, 4) -> "1234.5679" - // ToFixed(1.23, 5) -> "1.23000" - // ToFixed(0.1, 4) -> "0.1000" - // ToFixed(1e30, 2) -> "1000000000000000019884624838656.00" - // ToFixed(0.1, 30) -> "0.100000000000000005551115123126" - // ToFixed(0.1, 17) -> "0.10000000000000001" - // - // If requested_digits equals 0, then the tail of the result depends on - // the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT. - // Examples, for requested_digits == 0, - // let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be - // - false and false: then 123.45 -> 123 - // 0.678 -> 1 - // - true and false: then 123.45 -> 123. - // 0.678 -> 1. - // - true and true: then 123.45 -> 123.0 - // 0.678 -> 1.0 - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except for the following cases: - // - the input value is special and no infinity_symbol or nan_symbol has - // been provided to the constructor, - // - 'value' > 10^kMaxFixedDigitsBeforePoint, or - // - 'requested_digits' > kMaxFixedDigitsAfterPoint. - // The last two conditions imply that the result will never contain more than - // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters - // (one additional character for the sign, and one for the decimal point). - MFBT_API bool ToFixed(double value, - int requested_digits, - StringBuilder* result_builder) const; - - // Computes a representation in exponential format with requested_digits - // after the decimal point. The last emitted digit is rounded. - // If requested_digits equals -1, then the shortest exponential representation - // is computed. - // - // Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and - // exponent_character set to 'e'. - // ToExponential(3.12, 1) -> "3.1e0" - // ToExponential(5.0, 3) -> "5.000e0" - // ToExponential(0.001, 2) -> "1.00e-3" - // ToExponential(3.1415, -1) -> "3.1415e0" - // ToExponential(3.1415, 4) -> "3.1415e0" - // ToExponential(3.1415, 3) -> "3.142e0" - // ToExponential(123456789000000, 3) -> "1.235e14" - // ToExponential(1000000000000000019884624838656.0, -1) -> "1e30" - // ToExponential(1000000000000000019884624838656.0, 32) -> - // "1.00000000000000001988462483865600e30" - // ToExponential(1234, 0) -> "1e3" - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except for the following cases: - // - the input value is special and no infinity_symbol or nan_symbol has - // been provided to the constructor, - // - 'requested_digits' > kMaxExponentialDigits. - // The last condition implies that the result will never contain more than - // kMaxExponentialDigits + 8 characters (the sign, the digit before the - // decimal point, the decimal point, the exponent character, the - // exponent's sign, and at most 3 exponent digits). - MFBT_API bool ToExponential(double value, - int requested_digits, - StringBuilder* result_builder) const; - - // Computes 'precision' leading digits of the given 'value' and returns them - // either in exponential or decimal format, depending on - // max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the - // constructor). - // The last computed digit is rounded. - // - // Example with max_leading_padding_zeroes_in_precision_mode = 6. - // ToPrecision(0.0000012345, 2) -> "0.0000012" - // ToPrecision(0.00000012345, 2) -> "1.2e-7" - // Similarily the converter may add up to - // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid - // returning an exponential representation. A zero added by the - // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit. - // Examples for max_trailing_padding_zeroes_in_precision_mode = 1: - // ToPrecision(230.0, 2) -> "230" - // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT. - // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT. - // Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no - // EMIT_TRAILING_ZERO_AFTER_POINT: - // ToPrecision(123450.0, 6) -> "123450" - // ToPrecision(123450.0, 5) -> "123450" - // ToPrecision(123450.0, 4) -> "123500" - // ToPrecision(123450.0, 3) -> "123000" - // ToPrecision(123450.0, 2) -> "1.2e5" - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except for the following cases: - // - the input value is special and no infinity_symbol or nan_symbol has - // been provided to the constructor, - // - precision < kMinPericisionDigits - // - precision > kMaxPrecisionDigits - // The last condition implies that the result will never contain more than - // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the - // exponent character, the exponent's sign, and at most 3 exponent digits). - MFBT_API bool ToPrecision(double value, - int precision, - bool* used_exponential_notation, - StringBuilder* result_builder) const; - - enum DtoaMode { - // Produce the shortest correct representation. - // For example the output of 0.299999999999999988897 is (the less accurate - // but correct) 0.3. - SHORTEST, - // Same as SHORTEST, but for single-precision floats. - SHORTEST_SINGLE, - // Produce a fixed number of digits after the decimal point. - // For instance fixed(0.1, 4) becomes 0.1000 - // If the input number is big, the output will be big. - FIXED, - // Fixed number of digits (independent of the decimal point). - PRECISION - }; - - // The maximal number of digits that are needed to emit a double in base 10. - // A higher precision can be achieved by using more digits, but the shortest - // accurate representation of any double will never use more digits than - // kBase10MaximalLength. - // Note that DoubleToAscii null-terminates its input. So the given buffer - // should be at least kBase10MaximalLength + 1 characters long. - static const MFBT_DATA int kBase10MaximalLength = 17; - - // Converts the given double 'v' to ascii. 'v' must not be NaN, +Infinity, or - // -Infinity. In SHORTEST_SINGLE-mode this restriction also applies to 'v' - // after it has been casted to a single-precision float. That is, in this - // mode static_cast(v) must not be NaN, +Infinity or -Infinity. - // - // The result should be interpreted as buffer * 10^(point-length). - // - // The output depends on the given mode: - // - SHORTEST: produce the least amount of digits for which the internal - // identity requirement is still satisfied. If the digits are printed - // (together with the correct exponent) then reading this number will give - // 'v' again. The buffer will choose the representation that is closest to - // 'v'. If there are two at the same distance, than the one farther away - // from 0 is chosen (halfway cases - ending with 5 - are rounded up). - // In this mode the 'requested_digits' parameter is ignored. - // - SHORTEST_SINGLE: same as SHORTEST but with single-precision. - // - FIXED: produces digits necessary to print a given number with - // 'requested_digits' digits after the decimal point. The produced digits - // might be too short in which case the caller has to fill the remainder - // with '0's. - // Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2. - // Halfway cases are rounded towards +/-Infinity (away from 0). The call - // toFixed(0.15, 2) thus returns buffer="2", point=0. - // The returned buffer may contain digits that would be truncated from the - // shortest representation of the input. - // - PRECISION: produces 'requested_digits' where the first digit is not '0'. - // Even though the length of produced digits usually equals - // 'requested_digits', the function is allowed to return fewer digits, in - // which case the caller has to fill the missing digits with '0's. - // Halfway cases are again rounded away from 0. - // DoubleToAscii expects the given buffer to be big enough to hold all - // digits and a terminating null-character. In SHORTEST-mode it expects a - // buffer of at least kBase10MaximalLength + 1. In all other modes the - // requested_digits parameter and the padding-zeroes limit the size of the - // output. Don't forget the decimal point, the exponent character and the - // terminating null-character when computing the maximal output size. - // The given length is only used in debug mode to ensure the buffer is big - // enough. - static MFBT_API void DoubleToAscii(double v, - DtoaMode mode, - int requested_digits, - char* buffer, - int buffer_length, - bool* sign, - int* length, - int* point); - - private: - // Implementation for ToShortest and ToShortestSingle. - MFBT_API bool ToShortestIeeeNumber(double value, - StringBuilder* result_builder, - DtoaMode mode) const; - - // If the value is a special value (NaN or Infinity) constructs the - // corresponding string using the configured infinity/nan-symbol. - // If either of them is NULL or the value is not special then the - // function returns false. - MFBT_API bool HandleSpecialValues(double value, StringBuilder* result_builder) const; - // Constructs an exponential representation (i.e. 1.234e56). - // The given exponent assumes a decimal point after the first decimal digit. - MFBT_API void CreateExponentialRepresentation(const char* decimal_digits, - int length, - int exponent, - StringBuilder* result_builder) const; - // Creates a decimal representation (i.e 1234.5678). - MFBT_API void CreateDecimalRepresentation(const char* decimal_digits, - int length, - int decimal_point, - int digits_after_point, - StringBuilder* result_builder) const; - - const int flags_; - const char* const infinity_symbol_; - const char* const nan_symbol_; - const char exponent_character_; - const int decimal_in_shortest_low_; - const int decimal_in_shortest_high_; - const int max_leading_padding_zeroes_in_precision_mode_; - const int max_trailing_padding_zeroes_in_precision_mode_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter); -}; - - -class StringToDoubleConverter { - public: - // Enumeration for allowing octals and ignoring junk when converting - // strings to numbers. - enum Flags { - NO_FLAGS = 0, - ALLOW_HEX = 1, - ALLOW_OCTALS = 2, - ALLOW_TRAILING_JUNK = 4, - ALLOW_LEADING_SPACES = 8, - ALLOW_TRAILING_SPACES = 16, - ALLOW_SPACES_AFTER_SIGN = 32 - }; - - // Flags should be a bit-or combination of the possible Flags-enum. - // - NO_FLAGS: no special flags. - // - ALLOW_HEX: recognizes the prefix "0x". Hex numbers may only be integers. - // Ex: StringToDouble("0x1234") -> 4660.0 - // In StringToDouble("0x1234.56") the characters ".56" are trailing - // junk. The result of the call is hence dependent on - // the ALLOW_TRAILING_JUNK flag and/or the junk value. - // With this flag "0x" is a junk-string. Even with ALLOW_TRAILING_JUNK, - // the string will not be parsed as "0" followed by junk. - // - // - ALLOW_OCTALS: recognizes the prefix "0" for octals: - // If a sequence of octal digits starts with '0', then the number is - // read as octal integer. Octal numbers may only be integers. - // Ex: StringToDouble("01234") -> 668.0 - // StringToDouble("012349") -> 12349.0 // Not a sequence of octal - // // digits. - // In StringToDouble("01234.56") the characters ".56" are trailing - // junk. The result of the call is hence dependent on - // the ALLOW_TRAILING_JUNK flag and/or the junk value. - // In StringToDouble("01234e56") the characters "e56" are trailing - // junk, too. - // - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of - // a double literal. - // - ALLOW_LEADING_SPACES: skip over leading spaces. - // - ALLOW_TRAILING_SPACES: ignore trailing spaces. - // - ALLOW_SPACES_AFTER_SIGN: ignore spaces after the sign. - // Ex: StringToDouble("- 123.2") -> -123.2. - // StringToDouble("+ 123.2") -> 123.2 - // - // empty_string_value is returned when an empty string is given as input. - // If ALLOW_LEADING_SPACES or ALLOW_TRAILING_SPACES are set, then a string - // containing only spaces is converted to the 'empty_string_value', too. - // - // junk_string_value is returned when - // a) ALLOW_TRAILING_JUNK is not set, and a junk character (a character not - // part of a double-literal) is found. - // b) ALLOW_TRAILING_JUNK is set, but the string does not start with a - // double literal. - // - // infinity_symbol and nan_symbol are strings that are used to detect - // inputs that represent infinity and NaN. They can be null, in which case - // they are ignored. - // The conversion routine first reads any possible signs. Then it compares the - // following character of the input-string with the first character of - // the infinity, and nan-symbol. If either matches, the function assumes, that - // a match has been found, and expects the following input characters to match - // the remaining characters of the special-value symbol. - // This means that the following restrictions apply to special-value symbols: - // - they must not start with signs ('+', or '-'), - // - they must not have the same first character. - // - they must not start with digits. - // - // Examples: - // flags = ALLOW_HEX | ALLOW_TRAILING_JUNK, - // empty_string_value = 0.0, - // junk_string_value = NaN, - // infinity_symbol = "infinity", - // nan_symbol = "nan": - // StringToDouble("0x1234") -> 4660.0. - // StringToDouble("0x1234K") -> 4660.0. - // StringToDouble("") -> 0.0 // empty_string_value. - // StringToDouble(" ") -> NaN // junk_string_value. - // StringToDouble(" 1") -> NaN // junk_string_value. - // StringToDouble("0x") -> NaN // junk_string_value. - // StringToDouble("-123.45") -> -123.45. - // StringToDouble("--123.45") -> NaN // junk_string_value. - // StringToDouble("123e45") -> 123e45. - // StringToDouble("123E45") -> 123e45. - // StringToDouble("123e+45") -> 123e45. - // StringToDouble("123E-45") -> 123e-45. - // StringToDouble("123e") -> 123.0 // trailing junk ignored. - // StringToDouble("123e-") -> 123.0 // trailing junk ignored. - // StringToDouble("+NaN") -> NaN // NaN string literal. - // StringToDouble("-infinity") -> -inf. // infinity literal. - // StringToDouble("Infinity") -> NaN // junk_string_value. - // - // flags = ALLOW_OCTAL | ALLOW_LEADING_SPACES, - // empty_string_value = 0.0, - // junk_string_value = NaN, - // infinity_symbol = NULL, - // nan_symbol = NULL: - // StringToDouble("0x1234") -> NaN // junk_string_value. - // StringToDouble("01234") -> 668.0. - // StringToDouble("") -> 0.0 // empty_string_value. - // StringToDouble(" ") -> 0.0 // empty_string_value. - // StringToDouble(" 1") -> 1.0 - // StringToDouble("0x") -> NaN // junk_string_value. - // StringToDouble("0123e45") -> NaN // junk_string_value. - // StringToDouble("01239E45") -> 1239e45. - // StringToDouble("-infinity") -> NaN // junk_string_value. - // StringToDouble("NaN") -> NaN // junk_string_value. - StringToDoubleConverter(int flags, - double empty_string_value, - double junk_string_value, - const char* infinity_symbol, - const char* nan_symbol) - : flags_(flags), - empty_string_value_(empty_string_value), - junk_string_value_(junk_string_value), - infinity_symbol_(infinity_symbol), - nan_symbol_(nan_symbol) { - } - - // Performs the conversion. - // The output parameter 'processed_characters_count' is set to the number - // of characters that have been processed to read the number. - // Spaces than are processed with ALLOW_{LEADING|TRAILING}_SPACES are included - // in the 'processed_characters_count'. Trailing junk is never included. - double StringToDouble(const char* buffer, - int length, - int* processed_characters_count) const { - return StringToIeee(buffer, length, processed_characters_count, true); - } - - // Same as StringToDouble but reads a float. - // Note that this is not equivalent to static_cast(StringToDouble(...)) - // due to potential double-rounding. - float StringToFloat(const char* buffer, - int length, - int* processed_characters_count) const { - return static_cast(StringToIeee(buffer, length, - processed_characters_count, false)); - } - - private: - const int flags_; - const double empty_string_value_; - const double junk_string_value_; - const char* const infinity_symbol_; - const char* const nan_symbol_; - - double StringToIeee(const char* buffer, - int length, - int* processed_characters_count, - bool read_as_double) const; - - DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter); -}; - -} // namespace double_conversion - -#endif // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ diff --git a/mac/include/spidermonkey/mozilla/fallible.h b/mac/include/spidermonkey/mozilla/fallible.h deleted file mode 100644 index c028360b..00000000 --- a/mac/include/spidermonkey/mozilla/fallible.h +++ /dev/null @@ -1,68 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_fallible_h -#define mozilla_fallible_h - -#if defined(__cplusplus) - -/* Explicit fallible allocation - * - * Memory allocation (normally) defaults to abort in case of failed - * allocation. That is, it never returns NULL, and crashes instead. - * - * Code can explicitely request for fallible memory allocation thanks - * to the declarations below. - * - * The typical use of the mozilla::fallible const is with placement new, - * like the following: - * - * foo = new (mozilla::fallible) Foo(); - * - * The following forms, or derivatives, are also possible but deprecated: - * - * foo = new ((mozilla::fallible_t())) Foo(); - * - * const mozilla::fallible_t fallible = mozilla::fallible_t(); - * bar = new (f) Bar(); - * - * It is also possible to declare method overloads with fallible allocation - * alternatives, like so: - * - * class Foo { - * public: - * void Method(void *); - * void Method(void *, const mozilla::fallible_t&); - * }; - * - * Foo foo; - * foo.Method(nullptr, mozilla::fallible); - * - * If that last method call is in a method that itself takes a const - * fallible_t& argument, it is recommended to propagate that argument - * instead of using mozilla::fallible: - * - * void Func(Foo &foo, const mozilla::fallible_t& aFallible) { - * foo.Method(nullptr, aFallible); - * } - * - */ -namespace mozilla { - -struct fallible_t { }; - -/* This symbol is kept unexported, such that in corner cases where the - * compiler can't remove its use (essentially, cross compilation-unit - * calls), the smallest machine code is used. - * Depending how the linker packs symbols, it will consume between 1 and - * 8 bytes of read-only data in each executable or shared library, but - * only in those where it's actually not optimized out by the compiler. - */ -extern const fallible_t fallible; - -} // namespace mozilla - -#endif - -#endif // mozilla_fallible_h diff --git a/mac/include/spidermonkey/mozilla/mozalloc.h b/mac/include/spidermonkey/mozilla/mozalloc.h deleted file mode 100644 index f7ddb7e6..00000000 --- a/mac/include/spidermonkey/mozilla/mozalloc.h +++ /dev/null @@ -1,361 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: sw=4 ts=4 et : - */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_mozalloc_h -#define mozilla_mozalloc_h - -/* - * https://bugzilla.mozilla.org/show_bug.cgi?id=427099 - */ - -#if defined(__cplusplus) -# include -// Since libstdc++ 6, including the C headers (e.g. stdlib.h) instead of the -// corresponding C++ header (e.g. cstdlib) can cause confusion in C++ code -// using things defined there. Specifically, with stdlib.h, the use of abs() -// in gfx/graphite2/src/inc/UtfCodec.h somehow ends up picking the wrong abs() -# include -# include -#else -# include -# include -#endif - -#if defined(__cplusplus) -#include "mozilla/fallible.h" -#include "mozilla/mozalloc_abort.h" -#include "mozilla/TemplateLib.h" -#endif -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" - -#define MOZALLOC_HAVE_XMALLOC - -#if defined(MOZ_ALWAYS_INLINE_EVEN_DEBUG) -# define MOZALLOC_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG -#elif defined(HAVE_FORCEINLINE) -# define MOZALLOC_INLINE __forceinline -#else -# define MOZALLOC_INLINE inline -#endif - -/* Workaround build problem with Sun Studio 12 */ -#if defined(__SUNPRO_C) || defined(__SUNPRO_CC) -# undef MOZ_MUST_USE -# define MOZ_MUST_USE -# undef MOZ_ALLOCATOR -# define MOZ_ALLOCATOR -#endif - -#if defined(__cplusplus) -extern "C" { -#endif /* ifdef __cplusplus */ - -/* - * We need to use malloc_impl and free_impl in this file when they are - * defined, because of how mozglue.dll is linked on Windows, where using - * malloc/free would end up using the symbols from the MSVCRT instead of - * ours. - */ -#ifndef free_impl -#define free_impl free -#define free_impl_ -#endif -#ifndef malloc_impl -#define malloc_impl malloc -#define malloc_impl_ -#endif - -/* - * Each declaration below is analogous to a "standard" allocation - * function, except that the out-of-memory handling is made explicit. - * The |moz_x| versions will never return a NULL pointer; if memory - * is exhausted, they abort. The |moz_| versions may return NULL - * pointers if memory is exhausted: their return value must be checked. - * - * All these allocation functions are *guaranteed* to return a pointer - * to memory allocated in such a way that that memory can be freed by - * passing that pointer to |free()|. - */ - -MFBT_API void* moz_xmalloc(size_t size) - MOZ_ALLOCATOR; - -MFBT_API void* moz_xcalloc(size_t nmemb, size_t size) - MOZ_ALLOCATOR; - -MFBT_API void* moz_xrealloc(void* ptr, size_t size) - MOZ_ALLOCATOR; - -MFBT_API char* moz_xstrdup(const char* str) - MOZ_ALLOCATOR; - -MFBT_API size_t moz_malloc_usable_size(void *ptr); - -MFBT_API size_t moz_malloc_size_of(const void *ptr); - -#if defined(HAVE_STRNDUP) -MFBT_API char* moz_xstrndup(const char* str, size_t strsize) - MOZ_ALLOCATOR; -#endif /* if defined(HAVE_STRNDUP) */ - - -#if defined(HAVE_POSIX_MEMALIGN) -MFBT_API MOZ_MUST_USE -int moz_xposix_memalign(void **ptr, size_t alignment, size_t size); - -MFBT_API MOZ_MUST_USE -int moz_posix_memalign(void **ptr, size_t alignment, size_t size); -#endif /* if defined(HAVE_POSIX_MEMALIGN) */ - - -#if defined(HAVE_MEMALIGN) -MFBT_API void* moz_xmemalign(size_t boundary, size_t size) - MOZ_ALLOCATOR; -#endif /* if defined(HAVE_MEMALIGN) */ - - -#if defined(HAVE_VALLOC) -MFBT_API void* moz_xvalloc(size_t size) - MOZ_ALLOCATOR; -#endif /* if defined(HAVE_VALLOC) */ - - -#ifdef __cplusplus -} /* extern "C" */ -#endif /* ifdef __cplusplus */ - - -#ifdef __cplusplus - -/* - * We implement the default operators new/delete as part of - * libmozalloc, replacing their definitions in libstdc++. The - * operator new* definitions in libmozalloc will never return a NULL - * pointer. - * - * Each operator new immediately below returns a pointer to memory - * that can be delete'd by any of - * - * (1) the matching infallible operator delete immediately below - * (2) the matching "fallible" operator delete further below - * (3) the matching system |operator delete(void*, std::nothrow)| - * (4) the matching system |operator delete(void*) throw(std::bad_alloc)| - * - * NB: these are declared |throw(std::bad_alloc)|, though they will never - * throw that exception. This declaration is consistent with the rule - * that |::operator new() throw(std::bad_alloc)| will never return NULL. - */ - -/* NB: This is defined just to silence vacuous warnings about symbol - * visibility on OS X/gcc. These symbols are force-inline and not - * exported. */ -#if defined(XP_MACOSX) -# define MOZALLOC_EXPORT_NEW MFBT_API -#else -# define MOZALLOC_EXPORT_NEW -#endif - -#if defined(ANDROID) -/* - * It's important to always specify 'throw()' in GCC because it's used to tell - * GCC that 'new' may return null. That makes GCC null-check the result before - * potentially initializing the memory to zero. - * Also, the Android minimalistic headers don't include std::bad_alloc. - */ -#define MOZALLOC_THROW_IF_HAS_EXCEPTIONS throw() -#define MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS -#elif defined(_MSC_VER) -/* - * Suppress build warning spam (bug 578546). - */ -#define MOZALLOC_THROW_IF_HAS_EXCEPTIONS -#define MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS -#else -#define MOZALLOC_THROW_IF_HAS_EXCEPTIONS throw() -#define MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS throw(std::bad_alloc) -#endif - -#define MOZALLOC_THROW_BAD_ALLOC MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS - -MOZALLOC_EXPORT_NEW -#if defined(__GNUC__) && !defined(__clang__) && defined(__SANITIZE_ADDRESS__) -/* gcc's asan somehow doesn't like always_inline on this function. */ -__attribute__((gnu_inline)) inline -#else -MOZALLOC_INLINE -#endif -void* operator new(size_t size) MOZALLOC_THROW_BAD_ALLOC -{ - return moz_xmalloc(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void* operator new(size_t size, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void* operator new[](size_t size) MOZALLOC_THROW_BAD_ALLOC -{ - return moz_xmalloc(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void* operator new[](size_t size, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete(void* ptr) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete(void* ptr, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete[](void* ptr) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete[](void* ptr, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - - -/* - * We also add a new allocator variant: "fallible operator new." - * Unlike libmozalloc's implementations of the standard nofail - * allocators, this allocator is allowed to return NULL. It can be used - * as follows - * - * Foo* f = new (mozilla::fallible) Foo(...); - * - * operator delete(fallible) is defined for completeness only. - * - * Each operator new below returns a pointer to memory that can be - * delete'd by any of - * - * (1) the matching "fallible" operator delete below - * (2) the matching infallible operator delete above - * (3) the matching system |operator delete(void*, std::nothrow)| - * (4) the matching system |operator delete(void*) throw(std::bad_alloc)| - */ - -MOZALLOC_INLINE -void* operator new(size_t size, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_INLINE -void* operator new[](size_t size, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_INLINE -void operator delete(void* ptr, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - free_impl(ptr); -} - -MOZALLOC_INLINE -void operator delete[](void* ptr, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - free_impl(ptr); -} - - -/* - * This policy is identical to MallocAllocPolicy, except it uses - * moz_xmalloc/moz_xcalloc/moz_xrealloc instead of - * malloc/calloc/realloc. - */ -class InfallibleAllocPolicy -{ -public: - template - T* maybe_pod_malloc(size_t aNumElems) - { - return pod_malloc(aNumElems); - } - - template - T* maybe_pod_calloc(size_t aNumElems) - { - return pod_calloc(aNumElems); - } - - template - T* maybe_pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - return pod_realloc(aPtr, aOldSize, aNewSize); - } - - template - T* pod_malloc(size_t aNumElems) - { - if (aNumElems & mozilla::tl::MulOverflowMask::value) { - reportAllocOverflow(); - } - return static_cast(moz_xmalloc(aNumElems * sizeof(T))); - } - - template - T* pod_calloc(size_t aNumElems) - { - return static_cast(moz_xcalloc(aNumElems, sizeof(T))); - } - - template - T* pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - if (aNewSize & mozilla::tl::MulOverflowMask::value) { - reportAllocOverflow(); - } - return static_cast(moz_xrealloc(aPtr, aNewSize * sizeof(T))); - } - - void free_(void* aPtr) - { - free_impl(aPtr); - } - - void reportAllocOverflow() const - { - mozalloc_abort("alloc overflow"); - } - - bool checkSimulatedOOM() const - { - return true; - } -}; - -#endif /* ifdef __cplusplus */ - -#ifdef malloc_impl_ -#undef malloc_impl_ -#undef malloc_impl -#endif -#ifdef free_impl_ -#undef free_impl_ -#undef free_impl -#endif - -#endif /* ifndef mozilla_mozalloc_h */ diff --git a/mac/include/spidermonkey/mozilla/mozalloc_abort.h b/mac/include/spidermonkey/mozilla/mozalloc_abort.h deleted file mode 100644 index 065cebcb..00000000 --- a/mac/include/spidermonkey/mozilla/mozalloc_abort.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: sw=4 ts=4 et : - */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_mozalloc_abort_h -#define mozilla_mozalloc_abort_h - -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" - -/** - * Terminate this process in such a way that breakpad is triggered, if - * at all possible. - * - * Note: MOZ_NORETURN seems to break crash stacks on ARM, so we don't - * use that annotation there. - */ -MFBT_API -#if !defined(__arm__) - MOZ_NORETURN -#endif - void mozalloc_abort(const char* const msg); - - -#endif /* ifndef mozilla_mozalloc_abort_h */ diff --git a/mac/include/spidermonkey/mozilla/mozalloc_oom.h b/mac/include/spidermonkey/mozilla/mozalloc_oom.h deleted file mode 100644 index 35bb9acc..00000000 --- a/mac/include/spidermonkey/mozilla/mozalloc_oom.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: sw=4 ts=4 et : - */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_mozalloc_oom_h -#define mozilla_mozalloc_oom_h - -#include "mozalloc.h" - -/** - * Called when memory is critically low. Returns iff it was able to - * remedy the critical memory situation; if not, it will abort(). - */ -MFBT_API void mozalloc_handle_oom(size_t requestedSize); - -/** - * Called by embedders (specifically Mozilla breakpad) which wants to be - * notified of an intentional abort, to annotate any crash report with - * the size of the allocation on which we aborted. - */ -typedef void (*mozalloc_oom_abort_handler)(size_t size); -MFBT_API void mozalloc_set_oom_abort_handler(mozalloc_oom_abort_handler handler); - -/* TODO: functions to query system memory usage and register - * critical-memory handlers. */ - - -#endif /* ifndef mozilla_mozalloc_oom_h */ diff --git a/mac/include/spidermonkey/mozilla/utils.h b/mac/include/spidermonkey/mozilla/utils.h deleted file mode 100644 index 15dd4bfb..00000000 --- a/mac/include/spidermonkey/mozilla/utils.h +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright 2010 the V8 project authors. All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following -// disclaimer in the documentation and/or other materials provided -// with the distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef DOUBLE_CONVERSION_UTILS_H_ -#define DOUBLE_CONVERSION_UTILS_H_ - -#include -#include - -#include "mozilla/Assertions.h" -#ifndef ASSERT -#define ASSERT(condition) MOZ_ASSERT(condition) -#endif -#ifndef UNIMPLEMENTED -#define UNIMPLEMENTED() MOZ_CRASH() -#endif -#ifndef UNREACHABLE -#define UNREACHABLE() MOZ_CRASH() -#endif - -// Double operations detection based on target architecture. -// Linux uses a 80bit wide floating point stack on x86. This induces double -// rounding, which in turn leads to wrong results. -// An easy way to test if the floating-point operations are correct is to -// evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then -// the result is equal to 89255e-22. -// The best way to test this, is to create a division-function and to compare -// the output of the division with the expected result. (Inlining must be -// disabled.) -// On Linux,x86 89255e-22 != Div_double(89255.0/1e22) -#if defined(_M_X64) || defined(__x86_64__) || \ - defined(__ARMEL__) || defined(__avr32__) || \ - defined(__hppa__) || defined(__ia64__) || \ - defined(__mips__) || \ - defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \ - defined(__sparc__) || defined(__sparc) || defined(__s390__) || \ - defined(__SH4__) || defined(__alpha__) || \ - defined(_MIPS_ARCH_MIPS32R2) || \ - defined(__AARCH64EL__) || defined(__aarch64__) -#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 -#elif defined(_M_IX86) || defined(__i386__) || defined(__i386) -#if defined(_WIN32) -// Windows uses a 64bit wide floating point stack. -#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 -#else -#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS -#endif // _WIN32 -#else -#error Target architecture was not detected as supported by Double-Conversion. -#endif - - -#include - -// The following macro works on both 32 and 64-bit platforms. -// Usage: instead of writing 0x1234567890123456 -// write UINT64_2PART_C(0x12345678,90123456); -#define UINT64_2PART_C(a, b) (((static_cast(a) << 32) + 0x##b##u)) - - -// The expression ARRAY_SIZE(a) is a compile-time constant of type -// size_t which represents the number of elements of the given -// array. You should only use ARRAY_SIZE on statically allocated -// arrays. -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(a) \ - ((sizeof(a) / sizeof(*(a))) / \ - static_cast(!(sizeof(a) % sizeof(*(a))))) -#endif - -// A macro to disallow the evil copy constructor and operator= functions -// This should be used in the private: declarations for a class -#ifndef DISALLOW_COPY_AND_ASSIGN -#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&); \ - void operator=(const TypeName&) -#endif - -// A macro to disallow all the implicit constructors, namely the -// default constructor, copy constructor and operator= functions. -// -// This should be used in the private: declarations for a class -// that wants to prevent anyone from instantiating it. This is -// especially useful for classes containing only static methods. -#ifndef DISALLOW_IMPLICIT_CONSTRUCTORS -#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ - TypeName(); \ - DISALLOW_COPY_AND_ASSIGN(TypeName) -#endif - -namespace double_conversion { - -static const int kCharSize = sizeof(char); - -// Returns the maximum of the two parameters. -template -static T Max(T a, T b) { - return a < b ? b : a; -} - - -// Returns the minimum of the two parameters. -template -static T Min(T a, T b) { - return a < b ? a : b; -} - - -inline int StrLength(const char* string) { - size_t length = strlen(string); - ASSERT(length == static_cast(static_cast(length))); - return static_cast(length); -} - -// This is a simplified version of V8's Vector class. -template -class Vector { - public: - Vector() : start_(NULL), length_(0) {} - Vector(T* data, int len) : start_(data), length_(len) { - ASSERT(len == 0 || (len > 0 && data != NULL)); - } - - // Returns a vector using the same backing storage as this one, - // spanning from and including 'from', to but not including 'to'. - Vector SubVector(int from, int to) { - ASSERT(to <= length_); - ASSERT(from < to); - ASSERT(0 <= from); - return Vector(start() + from, to - from); - } - - // Returns the length of the vector. - int length() const { return length_; } - - // Returns whether or not the vector is empty. - bool is_empty() const { return length_ == 0; } - - // Returns the pointer to the start of the data in the vector. - T* start() const { return start_; } - - // Access individual vector elements - checks bounds in debug mode. - T& operator[](int index) const { - ASSERT(0 <= index && index < length_); - return start_[index]; - } - - T& first() { return start_[0]; } - - T& last() { return start_[length_ - 1]; } - - private: - T* start_; - int length_; -}; - - -// Helper class for building result strings in a character buffer. The -// purpose of the class is to use safe operations that checks the -// buffer bounds on all operations in debug mode. -class StringBuilder { - public: - StringBuilder(char* buffer, int buffer_size) - : buffer_(buffer, buffer_size), position_(0) { } - - ~StringBuilder() { if (!is_finalized()) Finalize(); } - - int size() const { return buffer_.length(); } - - // Get the current position in the builder. - int position() const { - ASSERT(!is_finalized()); - return position_; - } - - // Reset the position. - void Reset() { position_ = 0; } - - // Add a single character to the builder. It is not allowed to add - // 0-characters; use the Finalize() method to terminate the string - // instead. - void AddCharacter(char c) { - ASSERT(c != '\0'); - ASSERT(!is_finalized() && position_ < buffer_.length()); - buffer_[position_++] = c; - } - - // Add an entire string to the builder. Uses strlen() internally to - // compute the length of the input string. - void AddString(const char* s) { - AddSubstring(s, StrLength(s)); - } - - // Add the first 'n' characters of the given string 's' to the - // builder. The input string must have enough characters. - void AddSubstring(const char* s, int n) { - ASSERT(!is_finalized() && position_ + n < buffer_.length()); - ASSERT(static_cast(n) <= strlen(s)); - memmove(&buffer_[position_], s, n * kCharSize); - position_ += n; - } - - - // Add character padding to the builder. If count is non-positive, - // nothing is added to the builder. - void AddPadding(char c, int count) { - for (int i = 0; i < count; i++) { - AddCharacter(c); - } - } - - // Finalize the string by 0-terminating it and returning the buffer. - char* Finalize() { - ASSERT(!is_finalized() && position_ < buffer_.length()); - buffer_[position_] = '\0'; - // Make sure nobody managed to add a 0-character to the - // buffer while building the string. - ASSERT(strlen(buffer_.start()) == static_cast(position_)); - position_ = -1; - ASSERT(is_finalized()); - return buffer_.start(); - } - - private: - Vector buffer_; - int position_; - - bool is_finalized() const { return position_ < 0; } - - DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder); -}; - -// The type-based aliasing rule allows the compiler to assume that pointers of -// different types (for some definition of different) never alias each other. -// Thus the following code does not work: -// -// float f = foo(); -// int fbits = *(int*)(&f); -// -// The compiler 'knows' that the int pointer can't refer to f since the types -// don't match, so the compiler may cache f in a register, leaving random data -// in fbits. Using C++ style casts makes no difference, however a pointer to -// char data is assumed to alias any other pointer. This is the 'memcpy -// exception'. -// -// Bit_cast uses the memcpy exception to move the bits from a variable of one -// type of a variable of another type. Of course the end result is likely to -// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005) -// will completely optimize BitCast away. -// -// There is an additional use for BitCast. -// Recent gccs will warn when they see casts that may result in breakage due to -// the type-based aliasing rule. If you have checked that there is no breakage -// you can use BitCast to cast one pointer type to another. This confuses gcc -// enough that it can no longer see that you have cast one pointer type to -// another thus avoiding the warning. -template -inline Dest BitCast(const Source& source) { - static_assert(sizeof(Dest) == sizeof(Source), - "BitCast's source and destination types must be the same size"); - - Dest dest; - memmove(&dest, &source, sizeof(dest)); - return dest; -} - -template -inline Dest BitCast(Source* source) { - return BitCast(reinterpret_cast(source)); -} - -} // namespace double_conversion - -#endif // DOUBLE_CONVERSION_UTILS_H_ diff --git a/mac/include/spidermonkey/mozmemory.h b/mac/include/spidermonkey/mozmemory.h deleted file mode 100644 index 84007fff..00000000 --- a/mac/include/spidermonkey/mozmemory.h +++ /dev/null @@ -1,91 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozmemory_h -#define mozmemory_h - -/* - * This header is meant to be used when the following functions are - * necessary: - * - malloc_good_size (used to be called je_malloc_usable_in_advance) - * - jemalloc_stats - * - jemalloc_purge_freed_pages - * - jemalloc_free_dirty_pages - */ - -#ifndef MOZ_MEMORY -# error Should not include mozmemory.h when MOZ_MEMORY is not set -#endif - -#include "mozmemory_wrap.h" -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" -#include "jemalloc_types.h" - -MOZ_BEGIN_EXTERN_C - -/* - * On OSX, malloc/malloc.h contains the declaration for malloc_good_size, - * which will call back in jemalloc, through the zone allocator so just use it. - */ -#ifdef XP_DARWIN -# include -#else -MOZ_MEMORY_API size_t malloc_good_size_impl(size_t size); - -/* Note: the MOZ_GLUE_IN_PROGRAM ifdef below is there to avoid -Werror turning - * the protective if into errors. MOZ_GLUE_IN_PROGRAM is what triggers MFBT_API - * to use weak imports. */ - -static inline size_t _malloc_good_size(size_t size) { -# if defined(MOZ_GLUE_IN_PROGRAM) && !defined(IMPL_MFBT) - if (!malloc_good_size) - return size; -# endif - return malloc_good_size_impl(size); -} - -# define malloc_good_size _malloc_good_size -#endif - -MOZ_JEMALLOC_API void jemalloc_stats(jemalloc_stats_t *stats); - -/* - * On some operating systems (Mac), we use madvise(MADV_FREE) to hand pages - * back to the operating system. On Mac, the operating system doesn't take - * this memory back immediately; instead, the OS takes it back only when the - * machine is running out of physical memory. - * - * This is great from the standpoint of efficiency, but it makes measuring our - * actual RSS difficult, because pages which we've MADV_FREE'd shouldn't count - * against our RSS. - * - * This function explicitly purges any MADV_FREE'd pages from physical memory, - * causing our reported RSS match the amount of memory we're actually using. - * - * Note that this call is expensive in two ways. First, it may be slow to - * execute, because it may make a number of slow syscalls to free memory. This - * function holds the big jemalloc locks, so basically all threads are blocked - * while this function runs. - * - * This function is also expensive in that the next time we go to access a page - * which we've just explicitly decommitted, the operating system has to attach - * to it a physical page! If we hadn't run this function, the OS would have - * less work to do. - * - * If MALLOC_DOUBLE_PURGE is not defined, this function does nothing. - */ -MOZ_JEMALLOC_API void jemalloc_purge_freed_pages(); - -/* - * Free all unused dirty pages in all arenas. Calling this function will slow - * down subsequent allocations so it is recommended to use it only when - * memory needs to be reclaimed at all costs (see bug 805855). This function - * provides functionality similar to mallctl("arenas.purge") in jemalloc 3. - */ -MOZ_JEMALLOC_API void jemalloc_free_dirty_pages(); - -MOZ_END_EXTERN_C - -#endif /* mozmemory_h */ diff --git a/mac/include/spidermonkey/mozmemory_wrap.h b/mac/include/spidermonkey/mozmemory_wrap.h deleted file mode 100644 index 066d5778..00000000 --- a/mac/include/spidermonkey/mozmemory_wrap.h +++ /dev/null @@ -1,219 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozmemory_wrap_h -#define mozmemory_wrap_h - -/* - * This header contains #defines which tweak the names of various memory - * allocation functions. - * - * There are several types of functions related to memory allocation - * that are meant to be used publicly by the Gecko codebase: - * - * - malloc implementation functions: - * - malloc - * - posix_memalign - * - aligned_alloc - * - calloc - * - realloc - * - free - * - memalign - * - valloc - * - malloc_usable_size - * - malloc_good_size - * Some of these functions are specific to some systems, but for - * convenience, they are treated as being cross-platform, and available - * as such. - * - * - duplication functions: - * - strndup - * - strdup - * - wcsdup (Windows only) - * - * - jemalloc specific functions: - * - jemalloc_stats - * - jemalloc_purge_freed_pages - * - jemalloc_free_dirty_pages - * (these functions are native to mozjemalloc, and have compatibility - * implementations for jemalloc3) - * - * These functions are all exported as part of libmozglue (see - * $(topsrcdir)/mozglue/build/Makefile.in), with a few implementation - * peculiarities: - * - * - On Windows, the malloc implementation functions are all prefixed with - * "je_", the duplication functions are prefixed with "wrap_", and jemalloc - * specific functions are left unprefixed. All these functions are however - * aliased when exporting them, such that the resulting mozglue.dll exports - * them unprefixed (see $(topsrcdir)/mozglue/build/mozglue.def.in). The - * prefixed malloc implementation and duplication functions are not - * exported. - * - * - On MacOSX, the system libc has a zone allocator, which allows us to - * hook custom malloc implementation functions without exporting them. - * The malloc implementation functions are all prefixed with "je_" and used - * this way from the custom zone allocator. They are not exported. - * Duplication functions are not included, since they will call the custom - * zone allocator anyways. Jemalloc-specific functions are also left - * unprefixed. - * - * - On Android and Gonk, all functions are left unprefixed. Additionally, - * C++ allocation functions (operator new/delete) are also exported and - * unprefixed. - * - * - On other systems (mostly Linux), all functions are left unprefixed. - * - * Only Android and Gonk add C++ allocation functions. - * - * Proper exporting of the various functions is done with the MOZ_MEMORY_API - * and MOZ_JEMALLOC_API macros. MOZ_MEMORY_API is meant to be used for malloc - * implementation and duplication functions, while MOZ_JEMALLOC_API is - * dedicated to jemalloc specific functions. - * - * - * All these functions are meant to be called with no prefix from Gecko code. - * In most cases, this is because that's how they are available at runtime. - * However, on Android, this relies on faulty.lib (the custom dynamic linker) - * resolving mozglue symbols before libc symbols, which is guaranteed by the - * way faulty.lib works (it respects the DT_NEEDED order, and libc always - * appears after mozglue ; which we double check when building anyways) - * - * - * Within libmozglue (when MOZ_MEMORY_IMPL is defined), all the functions - * should be suffixed with "_impl" both for declarations and use. - * That is, the implementation declaration for e.g. strdup would look like: - * char* strdup_impl(const char *) - * That implementation would call malloc by using "malloc_impl". - * - * While mozjemalloc uses these "_impl" suffixed helpers, jemalloc3, being - * third-party code, doesn't, but instead has an elaborate way to mangle - * individual functions. See under "Run jemalloc configure script" in - * $(topsrcdir)/configure.in. - * - * - * When building with replace-malloc support, the above still holds, but - * the malloc implementation and jemalloc specific functions are the - * replace-malloc functions from replace_malloc.c. - * - * The actual jemalloc/mozjemalloc implementation is prefixed with "je_". - * - * Thus, when MOZ_REPLACE_MALLOC is defined, the "_impl" suffixed macros - * expand to "je_" prefixed function when building mozjemalloc or - * jemalloc3/mozjemalloc_compat, where MOZ_JEMALLOC_IMPL is defined. - * - * In other cases, the "_impl" suffixed macros follow the original scheme, - * except on Windows and MacOSX, where they would expand to "je_" prefixed - * functions. Instead, they are left unmodified (malloc_impl expands to - * malloc_impl). - */ - -#ifndef MOZ_MEMORY -# error Should only include mozmemory_wrap.h when MOZ_MEMORY is set. -#endif - -#if defined(MOZ_JEMALLOC_IMPL) && !defined(MOZ_MEMORY_IMPL) -# define MOZ_MEMORY_IMPL -#endif -#if defined(MOZ_MEMORY_IMPL) && !defined(IMPL_MFBT) -# ifdef MFBT_API /* mozilla/Types.h was already included */ -# error mozmemory_wrap.h has to be included before mozilla/Types.h when MOZ_MEMORY_IMPL is set and IMPL_MFBT is not. -# endif -# define IMPL_MFBT -#endif - -#include "mozilla/Types.h" - -#if !defined(MOZ_SYSTEM_JEMALLOC) -# ifdef MOZ_MEMORY_IMPL -# if defined(MOZ_JEMALLOC_IMPL) && defined(MOZ_REPLACE_MALLOC) && !defined(MOZ_REPLACE_JEMALLOC) -# define mozmem_malloc_impl(a) je_ ## a -# define mozmem_jemalloc_impl(a) je_ ## a -# else -# define MOZ_JEMALLOC_API MFBT_API -# ifdef MOZ_REPLACE_JEMALLOC -# define MOZ_MEMORY_API MFBT_API -# define mozmem_malloc_impl(a) replace_ ## a -# define mozmem_jemalloc_impl(a) replace_ ## a -# elif (defined(XP_WIN) || defined(XP_DARWIN)) -# if defined(MOZ_REPLACE_MALLOC) -# define mozmem_malloc_impl(a) a ## _impl -# else -# define mozmem_malloc_impl(a) je_ ## a -# endif -# else -# define MOZ_MEMORY_API MFBT_API -# if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK) -# define MOZ_WRAP_NEW_DELETE -# endif -# endif -# endif -# ifdef XP_WIN -# define mozmem_dup_impl(a) wrap_ ## a -# endif -# endif - -/* All other jemalloc3 functions are prefixed with "je_", except when - * building against an unprefixed system jemalloc library */ -# define je_(a) je_ ## a -#else /* defined(MOZ_SYSTEM_JEMALLOC) */ -# define je_(a) a -#endif - -#if !defined(MOZ_MEMORY_IMPL) || defined(MOZ_SYSTEM_JEMALLOC) -# define MOZ_MEMORY_API MFBT_API -# define MOZ_JEMALLOC_API MFBT_API -#endif - -#ifndef MOZ_MEMORY_API -# define MOZ_MEMORY_API -#endif -#ifndef MOZ_JEMALLOC_API -# define MOZ_JEMALLOC_API -#endif - -#ifndef mozmem_malloc_impl -# define mozmem_malloc_impl(a) a -#endif -#ifndef mozmem_dup_impl -# define mozmem_dup_impl(a) a -#endif -#ifndef mozmem_jemalloc_impl -# define mozmem_jemalloc_impl(a) a -#endif - -/* Malloc implementation functions */ -#define malloc_impl mozmem_malloc_impl(malloc) -#define posix_memalign_impl mozmem_malloc_impl(posix_memalign) -#define aligned_alloc_impl mozmem_malloc_impl(aligned_alloc) -#define calloc_impl mozmem_malloc_impl(calloc) -#define realloc_impl mozmem_malloc_impl(realloc) -#define free_impl mozmem_malloc_impl(free) -#define memalign_impl mozmem_malloc_impl(memalign) -#define valloc_impl mozmem_malloc_impl(valloc) -#define malloc_usable_size_impl mozmem_malloc_impl(malloc_usable_size) -#define malloc_good_size_impl mozmem_malloc_impl(malloc_good_size) - -/* Duplication functions */ -#define strndup_impl mozmem_dup_impl(strndup) -#define strdup_impl mozmem_dup_impl(strdup) -#ifdef XP_WIN -# define wcsdup_impl mozmem_dup_impl(wcsdup) -#endif - -/* String functions */ -#ifdef ANDROID -/* Bug 801571 and Bug 879668, libstagefright uses vasprintf, causing malloc()/ - * free() to be mismatched between bionic and mozglue implementation. - */ -#define vasprintf_impl mozmem_dup_impl(vasprintf) -#define asprintf_impl mozmem_dup_impl(asprintf) -#endif - -/* Jemalloc specific function */ -#define jemalloc_stats_impl mozmem_jemalloc_impl(jemalloc_stats) -#define jemalloc_purge_freed_pages_impl mozmem_jemalloc_impl(jemalloc_purge_freed_pages) -#define jemalloc_free_dirty_pages_impl mozmem_jemalloc_impl(jemalloc_free_dirty_pages) - -#endif /* mozmemory_wrap_h */ diff --git a/mac/libs/libglfw3.a b/mac/libs/libglfw3.a deleted file mode 100644 index 3bab3a47..00000000 Binary files a/mac/libs/libglfw3.a and /dev/null differ diff --git a/mac/libs/libjs_static.a b/mac/libs/libjs_static.a deleted file mode 100644 index 50bc9222..00000000 Binary files a/mac/libs/libjs_static.a and /dev/null differ diff --git a/mac/libs/libmozglue.a b/mac/libs/libmozglue.a deleted file mode 100644 index 6dbcee72..00000000 Binary files a/mac/libs/libmozglue.a and /dev/null differ diff --git a/sources/CMakeLists.txt b/sources/CMakeLists.txt index e1fb5c85..c09e4d31 100644 --- a/sources/CMakeLists.txt +++ b/sources/CMakeLists.txt @@ -20,6 +20,37 @@ set(CC_EXTERNAL_SROUCES ${CMAKE_CURRENT_LIST_DIR}/ConvertUTF/ConvertUTF.c ${CMAKE_CURRENT_LIST_DIR}/ConvertUTF/ConvertUTF.h ${CMAKE_CURRENT_LIST_DIR}/ConvertUTF/ConvertUTFWrapper.cpp + + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommy.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommy.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyalloc.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyalloc.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyarray.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyarray.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyarrayblk.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyarrayblk.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyarrayblkof.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyarrayblkof.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyarrayof.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyarrayof.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommychain.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyhash.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyhash.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyhashdyn.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyhashdyn.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyhashlin.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyhashlin.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyhashtbl.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommyhashtbl.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommylist.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommylist.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommytree.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommytree.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommytrie.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommytrie.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommytrieinp.c + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommytrieinp.h + ${CMAKE_CURRENT_LIST_DIR}/tommyds/tommytypes.h ) if(ANDROID) @@ -31,16 +62,7 @@ if(ANDROID) pvmp3dec vorbisidec ) - - if(ANDROID_NDK) - list(APPEND CC_EXTERNAL_SROUCES - ${ANDROID_NDK}/sources/android/cpufeatures/cpu-features.c - ) - list(APPEND CC_EXTERNAL_INCLUDES - ${ANDROID_NDK}/sources/android/cpufeatures - ) - endif() - + elseif(WINDOWS) set_source_files_properties(${CMAKE_CURRENT_LIST_DIR}/ConvertUTF/ConvertUTF.c PROPERTIES LANGUAGE C diff --git a/sources/SocketRocket/CMakeLists.txt b/sources/SocketRocket/CMakeLists.txt index 4d3a0dde..a76081e1 100644 --- a/sources/SocketRocket/CMakeLists.txt +++ b/sources/SocketRocket/CMakeLists.txt @@ -46,8 +46,12 @@ set(SOCKET_ROCKET_SOURCES ) add_library(SocketRocket ${SOCKET_ROCKET_SOURCES}) - -cocos_mark_code_files(SocketRocket) +if(IOS) + set_property(TARGET SocketRocket PROPERTY XCODE_ATTRIBUTE_IPHONEOS_DEPLOYMENT_TARGET ${TARGET_IOS_VERSION}) + set_property(TARGET SocketRocket PROPERTY XCODE_ATTRIBUTE_ENABLE_BITCODE "NO") + set_property(TARGET SocketRocket PROPERTY XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "YES") +endif() +source_group(TREE ${CMAKE_CURRENT_LIST_DIR} PREFIX "Source Files" FILES ${SOCKET_ROCKET_SOURCES}) target_include_directories(SocketRocket PUBLIC ${CMAKE_CURRENT_LIST_DIR} diff --git a/sources/pvmp3dec/CMakeLists.txt b/sources/pvmp3dec/CMakeLists.txt index 3ba4cd88..6098d32a 100644 --- a/sources/pvmp3dec/CMakeLists.txt +++ b/sources/pvmp3dec/CMakeLists.txt @@ -1,7 +1,6 @@ cmake_minimum_required(VERSION 3.8) - set(PVMP3SOURCE ${CMAKE_CURRENT_LIST_DIR}/src/pvmp3_normalize.cpp ${CMAKE_CURRENT_LIST_DIR}/src/pvmp3_alias_reduction.cpp @@ -31,10 +30,6 @@ set(PVMP3SOURCE ) - - -message(STATUS "-------------------abi for pvmp3:${ANDROID_ABI}------------------------------") - if("${ANDROID_ABI}" MATCHES "armeabi.*") message(STATUS "pvmp3dec compile with asm") set(PVMP3SOURCE_ASM @@ -56,9 +51,6 @@ else() ) endif() -message(STATUS "pvmp3dec source list ->") -message(STATUS "${PVMP3SOURCE}") - add_library(pvmp3dec ${PVMP3SOURCE}) target_include_directories(pvmp3dec PUBLIC @@ -66,18 +58,10 @@ target_include_directories(pvmp3dec PUBLIC ${CMAKE_CURRENT_LIST_DIR}/include ) -# set_target_properties(pvmp3dec -# PROPERTIES LINK_LANGUAGE ASM -# ) - -file(WRITE ${CMAKE_CURRENT_LIST_DIR}/def.h "#pragma once\n#define OSCL_UNUSED_ARG(x) (void)(x)") - -# target_compile_definitions(pvmp3dec PRIVATE -# OSCL_UNUSED_ARG(x)=(void)(x) -# ) +file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/pvmp3dec_tmp_def.h "#pragma once\n#define OSCL_UNUSED_ARG(x) (void)(x)") target_compile_options(pvmp3dec PRIVATE #-fsanitize=signed-integer-overflow - -include ${CMAKE_CURRENT_LIST_DIR}/def.h + -include ${CMAKE_CURRENT_BINARY_DIR}/pvmp3dec_tmp_def.h # ) \ No newline at end of file diff --git a/sources/xxtea/xxtea.h b/sources/xxtea/xxtea.h index 117d81ec..87f1d109 100644 --- a/sources/xxtea/xxtea.h +++ b/sources/xxtea/xxtea.h @@ -22,10 +22,14 @@ #include /* for size_t & NULL declarations */ #if defined(_WIN32) && defined(_WINDOWS) -#if defined(_USRDLL) -#define XXTEA_DLL __declspec(dllexport) -#else /* use a DLL library */ -#define XXTEA_DLL __declspec(dllimport) +#if CC_STATIC + #define XXTEA_DLL +#else + #if defined(_USRDLL) + #define XXTEA_DLL __declspec(dllexport) + #else /* use a DLL library */ + #define XXTEA_DLL __declspec(dllimport) + #endif #endif #else #define XXTEA_DLL diff --git a/win32/CMakeLists.txt b/win32/CMakeLists.txt index c2c329a0..f34e34e7 100644 --- a/win32/CMakeLists.txt +++ b/win32/CMakeLists.txt @@ -17,20 +17,6 @@ set_target_properties(glew32 PROPERTIES IMPORTED_IMPLIB ${CMAKE_CURRENT_LIST_DIR}/libs/glew32.lib ) -# add_library(glfw3-2015 STATIC IMPORTED GLOBAL) - -# set_target_properties(glfw3-2015 PROPERTIES -# IMPORTED_IMPLIB ${CMAKE_CURRENT_LIST_DIR}/libs/glfw3-2015.lib -# ) - -# add_library(glfw3 STATIC IMPORTED GLOBAL) - -# set_target_properties(glfw3 PROPERTIES -# #IMPORTED_LOCATION ${CMAKE_CURRENT_LIST_DIR}/libs/glfw3.lib -# IMPORTED_LOCATION ${CMAKE_CURRENT_LIST_DIR}/libs/glfw3-2015.lib -# #IMPORTED_IMPLIB ${CMAKE_CURRENT_LIST_DIR}/libs/glfw3-2015.lib -# ) - add_library(iconv SHARED IMPORTED GLOBAL) set_target_properties(iconv PROPERTIES @@ -215,6 +201,7 @@ if(USE_SE_V8) set_target_properties(v8 PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_LIST_DIR}/include/v8 + INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_LIST_DIR}/include/v8 ) set(se_libs_name v8) diff --git a/win32/include/glfw3/glfw3.h b/win32/include/glfw3/glfw3.h deleted file mode 100644 index 0f97738c..00000000 --- a/win32/include/glfw3/glfw3.h +++ /dev/null @@ -1,2312 +0,0 @@ -/************************************************************************* - * GLFW 3.0 - www.glfw.org - * A library for OpenGL, window and input - *------------------------------------------------------------------------ - * Copyright (c) 2002-2006 Marcus Geelnard - * Copyright (c) 2006-2010 Camilla Berglund - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would - * be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and must not - * be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - *************************************************************************/ - -#ifndef _glfw3_h_ -#define _glfw3_h_ - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************************************************* - * Doxygen documentation - *************************************************************************/ - -/*! @defgroup clipboard Clipboard support - */ -/*! @defgroup context Context handling - */ -/*! @defgroup error Error handling - */ -/*! @defgroup init Initialization and version information - */ -/*! @defgroup input Input handling - */ -/*! @defgroup monitor Monitor handling - * - * This is the reference documentation for monitor related functions and types. - * For more information, see the @ref monitor. - */ -/*! @defgroup time Time input - */ -/*! @defgroup window Window handling - * - * This is the reference documentation for window related functions and types, - * including creation, deletion and event polling. For more information, see - * the @ref window. - */ - - -/************************************************************************* - * Global definitions - *************************************************************************/ - -/* ------------------- BEGIN SYSTEM/COMPILER SPECIFIC -------------------- */ - -/* Please report any problems that you find with your compiler, which may - * be solved in this section! There are several compilers that I have not - * been able to test this file with yet. - * - * First: If we are we on Windows, we want a single define for it (_WIN32) - * (Note: For Cygwin the compiler flag -mwin32 should be used, but to - * make sure that things run smoothly for Cygwin users, we add __CYGWIN__ - * to the list of "valid Win32 identifiers", which removes the need for - * -mwin32) - */ -#if !defined(_WIN32) && (defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__)) - #define _WIN32 -#endif /* _WIN32 */ - -/* In order for extension support to be portable, we need to define an - * OpenGL function call method. We use the keyword APIENTRY, which is - * defined for Win32. (Note: Windows also needs this for ) - */ -#ifndef APIENTRY - #ifdef _WIN32 - #define APIENTRY __stdcall - #else - #define APIENTRY - #endif -#endif /* APIENTRY */ - -/* The following three defines are here solely to make some Windows-based - * files happy. Theoretically we could include , but - * it has the major drawback of severely polluting our namespace. - */ - -/* Under Windows, we need WINGDIAPI defined */ -#if !defined(WINGDIAPI) && defined(_WIN32) - #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__POCC__) - /* Microsoft Visual C++, Borland C++ Builder and Pelles C */ - #define WINGDIAPI __declspec(dllimport) - #elif defined(__LCC__) - /* LCC-Win32 */ - #define WINGDIAPI __stdcall - #else - /* Others (e.g. MinGW, Cygwin) */ - #define WINGDIAPI extern - #endif - #define GLFW_WINGDIAPI_DEFINED -#endif /* WINGDIAPI */ - -/* Some files also need CALLBACK defined */ -#if !defined(CALLBACK) && defined(_WIN32) - #if defined(_MSC_VER) - /* Microsoft Visual C++ */ - #if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS) - #define CALLBACK __stdcall - #else - #define CALLBACK - #endif - #else - /* Other Windows compilers */ - #define CALLBACK __stdcall - #endif - #define GLFW_CALLBACK_DEFINED -#endif /* CALLBACK */ - -/* Most GL/glu.h variants on Windows need wchar_t - * OpenGL/gl.h blocks the definition of ptrdiff_t by glext.h on OS X */ -#if !defined(GLFW_INCLUDE_NONE) - #include -#endif - -/* Include the chosen client API headers. - */ -#if defined(__APPLE_CC__) - #if defined(GLFW_INCLUDE_GLCOREARB) - #include - #elif !defined(GLFW_INCLUDE_NONE) - #define GL_GLEXT_LEGACY - #include - #endif - #if defined(GLFW_INCLUDE_GLU) - #include - #endif -#else - #if defined(GLFW_INCLUDE_GLCOREARB) - #include - #elif defined(GLFW_INCLUDE_ES1) - #include - #elif defined(GLFW_INCLUDE_ES2) - #include - #elif defined(GLFW_INCLUDE_ES3) - #include - #elif !defined(GLFW_INCLUDE_NONE) - #include - #endif - #if defined(GLFW_INCLUDE_GLU) - #include - #endif -#endif - -#if defined(GLFW_DLL) && defined(_GLFW_BUILD_DLL) - /* GLFW_DLL is defined by users of GLFW when compiling programs that will link - * to the DLL version of the GLFW library. _GLFW_BUILD_DLL is defined by the - * GLFW configuration header when compiling the DLL version of the library. - */ - #error "You must not have both GLFW_DLL and _GLFW_BUILD_DLL defined" -#endif - -#if defined(_WIN32) && defined(_GLFW_BUILD_DLL) - - /* We are building a Win32 DLL */ - #define GLFWAPI __declspec(dllexport) - -#elif defined(_WIN32) && defined(GLFW_DLL) - - /* We are calling a Win32 DLL */ - #if defined(__LCC__) - #define GLFWAPI extern - #else - #define GLFWAPI __declspec(dllimport) - #endif - -#elif defined(__GNUC__) && defined(_GLFW_BUILD_DLL) - - #define GLFWAPI __attribute__((visibility("default"))) - -#else - - /* We are either building/calling a static lib or we are non-win32 */ - #define GLFWAPI - -#endif - -/* -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- */ - - -/************************************************************************* - * GLFW API tokens - *************************************************************************/ - -/*! @name GLFW version macros - * @{ */ -/*! @brief The major version number of the GLFW library. - * - * This is incremented when the API is changed in non-compatible ways. - * @ingroup init - */ -#define GLFW_VERSION_MAJOR 3 -/*! @brief The minor version number of the GLFW library. - * - * This is incremented when features are added to the API but it remains - * backward-compatible. - * @ingroup init - */ -#define GLFW_VERSION_MINOR 0 -/*! @brief The revision number of the GLFW library. - * - * This is incremented when a bug fix release is made that does not contain any - * API changes. - * @ingroup init - */ -#define GLFW_VERSION_REVISION 4 -/*! @} */ - -/*! @name Key and button actions - * @{ */ -/*! @brief The key or button was released. - * @ingroup input - */ -#define GLFW_RELEASE 0 -/*! @brief The key or button was pressed. - * @ingroup input - */ -#define GLFW_PRESS 1 -/*! @brief The key was held down until it repeated. - * @ingroup input - */ -#define GLFW_REPEAT 2 -/*! @} */ - -/*! @defgroup keys Keyboard keys - * - * These key codes are inspired by the *USB HID Usage Tables v1.12* (p. 53-60), - * but re-arranged to map to 7-bit ASCII for printable keys (function keys are - * put in the 256+ range). - * - * The naming of the key codes follow these rules: - * - The US keyboard layout is used - * - Names of printable alpha-numeric characters are used (e.g. "A", "R", - * "3", etc.) - * - For non-alphanumeric characters, Unicode:ish names are used (e.g. - * "COMMA", "LEFT_SQUARE_BRACKET", etc.). Note that some names do not - * correspond to the Unicode standard (usually for brevity) - * - Keys that lack a clear US mapping are named "WORLD_x" - * - For non-printable keys, custom names are used (e.g. "F4", - * "BACKSPACE", etc.) - * - * @ingroup input - * @{ - */ - -/* The unknown key */ -#define GLFW_KEY_UNKNOWN -1 - -/* Printable keys */ -#define GLFW_KEY_SPACE 32 -#define GLFW_KEY_APOSTROPHE 39 /* ' */ -#define GLFW_KEY_COMMA 44 /* , */ -#define GLFW_KEY_MINUS 45 /* - */ -#define GLFW_KEY_PERIOD 46 /* . */ -#define GLFW_KEY_SLASH 47 /* / */ -#define GLFW_KEY_0 48 -#define GLFW_KEY_1 49 -#define GLFW_KEY_2 50 -#define GLFW_KEY_3 51 -#define GLFW_KEY_4 52 -#define GLFW_KEY_5 53 -#define GLFW_KEY_6 54 -#define GLFW_KEY_7 55 -#define GLFW_KEY_8 56 -#define GLFW_KEY_9 57 -#define GLFW_KEY_SEMICOLON 59 /* ; */ -#define GLFW_KEY_EQUAL 61 /* = */ -#define GLFW_KEY_A 65 -#define GLFW_KEY_B 66 -#define GLFW_KEY_C 67 -#define GLFW_KEY_D 68 -#define GLFW_KEY_E 69 -#define GLFW_KEY_F 70 -#define GLFW_KEY_G 71 -#define GLFW_KEY_H 72 -#define GLFW_KEY_I 73 -#define GLFW_KEY_J 74 -#define GLFW_KEY_K 75 -#define GLFW_KEY_L 76 -#define GLFW_KEY_M 77 -#define GLFW_KEY_N 78 -#define GLFW_KEY_O 79 -#define GLFW_KEY_P 80 -#define GLFW_KEY_Q 81 -#define GLFW_KEY_R 82 -#define GLFW_KEY_S 83 -#define GLFW_KEY_T 84 -#define GLFW_KEY_U 85 -#define GLFW_KEY_V 86 -#define GLFW_KEY_W 87 -#define GLFW_KEY_X 88 -#define GLFW_KEY_Y 89 -#define GLFW_KEY_Z 90 -#define GLFW_KEY_LEFT_BRACKET 91 /* [ */ -#define GLFW_KEY_BACKSLASH 92 /* \ */ -#define GLFW_KEY_RIGHT_BRACKET 93 /* ] */ -#define GLFW_KEY_GRAVE_ACCENT 96 /* ` */ -#define GLFW_KEY_WORLD_1 161 /* non-US #1 */ -#define GLFW_KEY_WORLD_2 162 /* non-US #2 */ - -/* Function keys */ -#define GLFW_KEY_ESCAPE 256 -#define GLFW_KEY_ENTER 257 -#define GLFW_KEY_TAB 258 -#define GLFW_KEY_BACKSPACE 259 -#define GLFW_KEY_INSERT 260 -#define GLFW_KEY_DELETE 261 -#define GLFW_KEY_RIGHT 262 -#define GLFW_KEY_LEFT 263 -#define GLFW_KEY_DOWN 264 -#define GLFW_KEY_UP 265 -#define GLFW_KEY_PAGE_UP 266 -#define GLFW_KEY_PAGE_DOWN 267 -#define GLFW_KEY_HOME 268 -#define GLFW_KEY_END 269 -#define GLFW_KEY_CAPS_LOCK 280 -#define GLFW_KEY_SCROLL_LOCK 281 -#define GLFW_KEY_NUM_LOCK 282 -#define GLFW_KEY_PRINT_SCREEN 283 -#define GLFW_KEY_PAUSE 284 -#define GLFW_KEY_F1 290 -#define GLFW_KEY_F2 291 -#define GLFW_KEY_F3 292 -#define GLFW_KEY_F4 293 -#define GLFW_KEY_F5 294 -#define GLFW_KEY_F6 295 -#define GLFW_KEY_F7 296 -#define GLFW_KEY_F8 297 -#define GLFW_KEY_F9 298 -#define GLFW_KEY_F10 299 -#define GLFW_KEY_F11 300 -#define GLFW_KEY_F12 301 -#define GLFW_KEY_F13 302 -#define GLFW_KEY_F14 303 -#define GLFW_KEY_F15 304 -#define GLFW_KEY_F16 305 -#define GLFW_KEY_F17 306 -#define GLFW_KEY_F18 307 -#define GLFW_KEY_F19 308 -#define GLFW_KEY_F20 309 -#define GLFW_KEY_F21 310 -#define GLFW_KEY_F22 311 -#define GLFW_KEY_F23 312 -#define GLFW_KEY_F24 313 -#define GLFW_KEY_F25 314 -#define GLFW_KEY_KP_0 320 -#define GLFW_KEY_KP_1 321 -#define GLFW_KEY_KP_2 322 -#define GLFW_KEY_KP_3 323 -#define GLFW_KEY_KP_4 324 -#define GLFW_KEY_KP_5 325 -#define GLFW_KEY_KP_6 326 -#define GLFW_KEY_KP_7 327 -#define GLFW_KEY_KP_8 328 -#define GLFW_KEY_KP_9 329 -#define GLFW_KEY_KP_DECIMAL 330 -#define GLFW_KEY_KP_DIVIDE 331 -#define GLFW_KEY_KP_MULTIPLY 332 -#define GLFW_KEY_KP_SUBTRACT 333 -#define GLFW_KEY_KP_ADD 334 -#define GLFW_KEY_KP_ENTER 335 -#define GLFW_KEY_KP_EQUAL 336 -#define GLFW_KEY_LEFT_SHIFT 340 -#define GLFW_KEY_LEFT_CONTROL 341 -#define GLFW_KEY_LEFT_ALT 342 -#define GLFW_KEY_LEFT_SUPER 343 -#define GLFW_KEY_RIGHT_SHIFT 344 -#define GLFW_KEY_RIGHT_CONTROL 345 -#define GLFW_KEY_RIGHT_ALT 346 -#define GLFW_KEY_RIGHT_SUPER 347 -#define GLFW_KEY_MENU 348 -#define GLFW_KEY_LAST GLFW_KEY_MENU - -/*! @} */ - -/*! @defgroup mods Modifier key flags - * @ingroup input - * @{ */ - -/*! @brief If this bit is set one or more Shift keys were held down. - */ -#define GLFW_MOD_SHIFT 0x0001 -/*! @brief If this bit is set one or more Control keys were held down. - */ -#define GLFW_MOD_CONTROL 0x0002 -/*! @brief If this bit is set one or more Alt keys were held down. - */ -#define GLFW_MOD_ALT 0x0004 -/*! @brief If this bit is set one or more Super keys were held down. - */ -#define GLFW_MOD_SUPER 0x0008 - -/*! @} */ - -/*! @defgroup buttons Mouse buttons - * @ingroup input - * @{ */ -#define GLFW_MOUSE_BUTTON_1 0 -#define GLFW_MOUSE_BUTTON_2 1 -#define GLFW_MOUSE_BUTTON_3 2 -#define GLFW_MOUSE_BUTTON_4 3 -#define GLFW_MOUSE_BUTTON_5 4 -#define GLFW_MOUSE_BUTTON_6 5 -#define GLFW_MOUSE_BUTTON_7 6 -#define GLFW_MOUSE_BUTTON_8 7 -#define GLFW_MOUSE_BUTTON_LAST GLFW_MOUSE_BUTTON_8 -#define GLFW_MOUSE_BUTTON_LEFT GLFW_MOUSE_BUTTON_1 -#define GLFW_MOUSE_BUTTON_RIGHT GLFW_MOUSE_BUTTON_2 -#define GLFW_MOUSE_BUTTON_MIDDLE GLFW_MOUSE_BUTTON_3 -/*! @} */ - -/*! @defgroup joysticks Joysticks - * @ingroup input - * @{ */ -#define GLFW_JOYSTICK_1 0 -#define GLFW_JOYSTICK_2 1 -#define GLFW_JOYSTICK_3 2 -#define GLFW_JOYSTICK_4 3 -#define GLFW_JOYSTICK_5 4 -#define GLFW_JOYSTICK_6 5 -#define GLFW_JOYSTICK_7 6 -#define GLFW_JOYSTICK_8 7 -#define GLFW_JOYSTICK_9 8 -#define GLFW_JOYSTICK_10 9 -#define GLFW_JOYSTICK_11 10 -#define GLFW_JOYSTICK_12 11 -#define GLFW_JOYSTICK_13 12 -#define GLFW_JOYSTICK_14 13 -#define GLFW_JOYSTICK_15 14 -#define GLFW_JOYSTICK_16 15 -#define GLFW_JOYSTICK_LAST GLFW_JOYSTICK_16 -/*! @} */ - -/*! @defgroup errors Error codes - * @ingroup error - * @{ */ -/*! @brief GLFW has not been initialized. - */ -#define GLFW_NOT_INITIALIZED 0x00010001 -/*! @brief No context is current for this thread. - */ -#define GLFW_NO_CURRENT_CONTEXT 0x00010002 -/*! @brief One of the enum parameters for the function was given an invalid - * enum. - */ -#define GLFW_INVALID_ENUM 0x00010003 -/*! @brief One of the parameters for the function was given an invalid value. - */ -#define GLFW_INVALID_VALUE 0x00010004 -/*! @brief A memory allocation failed. - */ -#define GLFW_OUT_OF_MEMORY 0x00010005 -/*! @brief GLFW could not find support for the requested client API on the - * system. - */ -#define GLFW_API_UNAVAILABLE 0x00010006 -/*! @brief The requested client API version is not available. - */ -#define GLFW_VERSION_UNAVAILABLE 0x00010007 -/*! @brief A platform-specific error occurred that does not match any of the - * more specific categories. - */ -#define GLFW_PLATFORM_ERROR 0x00010008 -/*! @brief The clipboard did not contain data in the requested format. - */ -#define GLFW_FORMAT_UNAVAILABLE 0x00010009 -/*! @} */ - -#define GLFW_FOCUSED 0x00020001 -#define GLFW_ICONIFIED 0x00020002 -#define GLFW_RESIZABLE 0x00020003 -#define GLFW_VISIBLE 0x00020004 -#define GLFW_DECORATED 0x00020005 - -#define GLFW_RED_BITS 0x00021001 -#define GLFW_GREEN_BITS 0x00021002 -#define GLFW_BLUE_BITS 0x00021003 -#define GLFW_ALPHA_BITS 0x00021004 -#define GLFW_DEPTH_BITS 0x00021005 -#define GLFW_STENCIL_BITS 0x00021006 -#define GLFW_ACCUM_RED_BITS 0x00021007 -#define GLFW_ACCUM_GREEN_BITS 0x00021008 -#define GLFW_ACCUM_BLUE_BITS 0x00021009 -#define GLFW_ACCUM_ALPHA_BITS 0x0002100A -#define GLFW_AUX_BUFFERS 0x0002100B -#define GLFW_STEREO 0x0002100C -#define GLFW_SAMPLES 0x0002100D -#define GLFW_SRGB_CAPABLE 0x0002100E -#define GLFW_REFRESH_RATE 0x0002100F - -#define GLFW_CLIENT_API 0x00022001 -#define GLFW_CONTEXT_VERSION_MAJOR 0x00022002 -#define GLFW_CONTEXT_VERSION_MINOR 0x00022003 -#define GLFW_CONTEXT_REVISION 0x00022004 -#define GLFW_CONTEXT_ROBUSTNESS 0x00022005 -#define GLFW_OPENGL_FORWARD_COMPAT 0x00022006 -#define GLFW_OPENGL_DEBUG_CONTEXT 0x00022007 -#define GLFW_OPENGL_PROFILE 0x00022008 - -#define GLFW_OPENGL_API 0x00030001 -#define GLFW_OPENGL_ES_API 0x00030002 - -#define GLFW_NO_ROBUSTNESS 0 -#define GLFW_NO_RESET_NOTIFICATION 0x00031001 -#define GLFW_LOSE_CONTEXT_ON_RESET 0x00031002 - -#define GLFW_OPENGL_ANY_PROFILE 0 -#define GLFW_OPENGL_CORE_PROFILE 0x00032001 -#define GLFW_OPENGL_COMPAT_PROFILE 0x00032002 - -#define GLFW_CURSOR 0x00033001 -#define GLFW_STICKY_KEYS 0x00033002 -#define GLFW_STICKY_MOUSE_BUTTONS 0x00033003 - -#define GLFW_CURSOR_NORMAL 0x00034001 -#define GLFW_CURSOR_HIDDEN 0x00034002 -#define GLFW_CURSOR_DISABLED 0x00034003 - -#define GLFW_CONNECTED 0x00040001 -#define GLFW_DISCONNECTED 0x00040002 - - -/************************************************************************* - * GLFW API types - *************************************************************************/ - -/*! @brief Client API function pointer type. - * - * Generic function pointer used for returning client API function pointers - * without forcing a cast from a regular pointer. - * - * @ingroup context - */ -typedef void (*GLFWglproc)(void); - -/*! @brief Opaque monitor object. - * - * Opaque monitor object. - * - * @ingroup monitor - */ -typedef struct GLFWmonitor GLFWmonitor; - -/*! @brief Opaque window object. - * - * Opaque window object. - * - * @ingroup window - */ -typedef struct GLFWwindow GLFWwindow; - -/*! @brief The function signature for error callbacks. - * - * This is the function signature for error callback functions. - * - * @param[in] error An [error code](@ref errors). - * @param[in] description A UTF-8 encoded string describing the error. - * - * @sa glfwSetErrorCallback - * - * @ingroup error - */ -typedef void (* GLFWerrorfun)(int,const char*); - -/*! @brief The function signature for window position callbacks. - * - * This is the function signature for window position callback functions. - * - * @param[in] window The window that the user moved. - * @param[in] xpos The new x-coordinate, in screen coordinates, of the - * upper-left corner of the client area of the window. - * @param[in] ypos The new y-coordinate, in screen coordinates, of the - * upper-left corner of the client area of the window. - * - * @sa glfwSetWindowPosCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowposfun)(GLFWwindow*,int,int); - -/*! @brief The function signature for window resize callbacks. - * - * This is the function signature for window size callback functions. - * - * @param[in] window The window that the user resized. - * @param[in] width The new width, in screen coordinates, of the window. - * @param[in] height The new height, in screen coordinates, of the window. - * - * @sa glfwSetWindowSizeCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowsizefun)(GLFWwindow*,int,int); - -/*! @brief The function signature for window close callbacks. - * - * This is the function signature for window close callback functions. - * - * @param[in] window The window that the user attempted to close. - * - * @sa glfwSetWindowCloseCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowclosefun)(GLFWwindow*); - -/*! @brief The function signature for window content refresh callbacks. - * - * This is the function signature for window refresh callback functions. - * - * @param[in] window The window whose content needs to be refreshed. - * - * @sa glfwSetWindowRefreshCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowrefreshfun)(GLFWwindow*); - -/*! @brief The function signature for window focus/defocus callbacks. - * - * This is the function signature for window focus callback functions. - * - * @param[in] window The window that was focused or defocused. - * @param[in] focused `GL_TRUE` if the window was focused, or `GL_FALSE` if - * it was defocused. - * - * @sa glfwSetWindowFocusCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowfocusfun)(GLFWwindow*,int); - -/*! @brief The function signature for window iconify/restore callbacks. - * - * This is the function signature for window iconify/restore callback - * functions. - * - * @param[in] window The window that was iconified or restored. - * @param[in] iconified `GL_TRUE` if the window was iconified, or `GL_FALSE` - * if it was restored. - * - * @sa glfwSetWindowIconifyCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowiconifyfun)(GLFWwindow*,int); - -/*! @brief The function signature for framebuffer resize callbacks. - * - * This is the function signature for framebuffer resize callback - * functions. - * - * @param[in] window The window whose framebuffer was resized. - * @param[in] width The new width, in pixels, of the framebuffer. - * @param[in] height The new height, in pixels, of the framebuffer. - * - * @sa glfwSetFramebufferSizeCallback - * - * @ingroup window - */ -typedef void (* GLFWframebuffersizefun)(GLFWwindow*,int,int); - -/*! @brief The function signature for mouse button callbacks. - * - * This is the function signature for mouse button callback functions. - * - * @param[in] window The window that received the event. - * @param[in] button The [mouse button](@ref buttons) that was pressed or - * released. - * @param[in] action One of `GLFW_PRESS` or `GLFW_RELEASE`. - * @param[in] mods Bit field describing which [modifier keys](@ref mods) were - * held down. - * - * @sa glfwSetMouseButtonCallback - * - * @ingroup input - */ -typedef void (* GLFWmousebuttonfun)(GLFWwindow*,int,int,int); - -/*! @brief The function signature for cursor position callbacks. - * - * This is the function signature for cursor position callback functions. - * - * @param[in] window The window that received the event. - * @param[in] xpos The new x-coordinate, in screen coordinates, of the cursor. - * @param[in] ypos The new y-coordinate, in screen coordinates, of the cursor. - * - * @sa glfwSetCursorPosCallback - * - * @ingroup input - */ -typedef void (* GLFWcursorposfun)(GLFWwindow*,double,double); - -/*! @brief The function signature for cursor enter/leave callbacks. - * - * This is the function signature for cursor enter/leave callback functions. - * - * @param[in] window The window that received the event. - * @param[in] entered `GL_TRUE` if the cursor entered the window's client - * area, or `GL_FALSE` if it left it. - * - * @sa glfwSetCursorEnterCallback - * - * @ingroup input - */ -typedef void (* GLFWcursorenterfun)(GLFWwindow*,int); - -/*! @brief The function signature for scroll callbacks. - * - * This is the function signature for scroll callback functions. - * - * @param[in] window The window that received the event. - * @param[in] xoffset The scroll offset along the x-axis. - * @param[in] yoffset The scroll offset along the y-axis. - * - * @sa glfwSetScrollCallback - * - * @ingroup input - */ -typedef void (* GLFWscrollfun)(GLFWwindow*,double,double); - -/*! @brief The function signature for keyboard key callbacks. - * - * This is the function signature for keyboard key callback functions. - * - * @param[in] window The window that received the event. - * @param[in] key The [keyboard key](@ref keys) that was pressed or released. - * @param[in] scancode The system-specific scancode of the key. - * @param[in] action @ref GLFW_PRESS, @ref GLFW_RELEASE or @ref GLFW_REPEAT. - * @param[in] mods Bit field describing which [modifier keys](@ref mods) were - * held down. - * - * @sa glfwSetKeyCallback - * - * @ingroup input - */ -typedef void (* GLFWkeyfun)(GLFWwindow*,int,int,int,int); - -/*! @brief The function signature for Unicode character callbacks. - * - * This is the function signature for Unicode character callback functions. - * - * @param[in] window The window that received the event. - * @param[in] codepoint The Unicode code point of the character. - * - * @sa glfwSetCharCallback - * - * @ingroup input - */ -typedef void (* GLFWcharfun)(GLFWwindow*,unsigned int); - -/*! @brief The function signature for monitor configuration callbacks. - * - * This is the function signature for monitor configuration callback functions. - * - * @param[in] monitor The monitor that was connected or disconnected. - * @param[in] event One of `GLFW_CONNECTED` or `GLFW_DISCONNECTED`. - * - * @sa glfwSetMonitorCallback - * - * @ingroup monitor - */ -typedef void (* GLFWmonitorfun)(GLFWmonitor*,int); - -/*! @brief Video mode type. - * - * This describes a single video mode. - * - * @ingroup monitor - */ -typedef struct GLFWvidmode -{ - /*! The width, in screen coordinates, of the video mode. - */ - int width; - /*! The height, in screen coordinates, of the video mode. - */ - int height; - /*! The bit depth of the red channel of the video mode. - */ - int redBits; - /*! The bit depth of the green channel of the video mode. - */ - int greenBits; - /*! The bit depth of the blue channel of the video mode. - */ - int blueBits; - /*! The refresh rate, in Hz, of the video mode. - */ - int refreshRate; -} GLFWvidmode; - -/*! @brief Gamma ramp. - * - * This describes the gamma ramp for a monitor. - * - * @sa glfwGetGammaRamp glfwSetGammaRamp - * - * @ingroup monitor - */ -typedef struct GLFWgammaramp -{ - /*! An array of value describing the response of the red channel. - */ - unsigned short* red; - /*! An array of value describing the response of the green channel. - */ - unsigned short* green; - /*! An array of value describing the response of the blue channel. - */ - unsigned short* blue; - /*! The number of elements in each array. - */ - unsigned int size; -} GLFWgammaramp; - - -/************************************************************************* - * GLFW API functions - *************************************************************************/ - -/*! @brief Initializes the GLFW library. - * - * This function initializes the GLFW library. Before most GLFW functions can - * be used, GLFW must be initialized, and before a program terminates GLFW - * should be terminated in order to free any resources allocated during or - * after initialization. - * - * If this function fails, it calls @ref glfwTerminate before returning. If it - * succeeds, you should call @ref glfwTerminate before the program exits. - * - * Additional calls to this function after successful initialization but before - * termination will succeed but will do nothing. - * - * @return `GL_TRUE` if successful, or `GL_FALSE` if an error occurred. - * - * @par New in GLFW 3 - * This function no longer registers @ref glfwTerminate with `atexit`. - * - * @note This function may only be called from the main thread. - * - * @note **OS X:** This function will change the current directory of the - * application to the `Contents/Resources` subdirectory of the application's - * bundle, if present. - * - * @sa glfwTerminate - * - * @ingroup init - */ -GLFWAPI int glfwInit(void); - -/*! @brief Terminates the GLFW library. - * - * This function destroys all remaining windows, frees any allocated resources - * and sets the library to an uninitialized state. Once this is called, you - * must again call @ref glfwInit successfully before you will be able to use - * most GLFW functions. - * - * If GLFW has been successfully initialized, this function should be called - * before the program exits. If initialization fails, there is no need to call - * this function, as it is called by @ref glfwInit before it returns failure. - * - * @remarks This function may be called before @ref glfwInit. - * - * @note This function may only be called from the main thread. - * - * @warning No window's context may be current on another thread when this - * function is called. - * - * @sa glfwInit - * - * @ingroup init - */ -GLFWAPI void glfwTerminate(void); - -/*! @brief Retrieves the version of the GLFW library. - * - * This function retrieves the major, minor and revision numbers of the GLFW - * library. It is intended for when you are using GLFW as a shared library and - * want to ensure that you are using the minimum required version. - * - * @param[out] major Where to store the major version number, or `NULL`. - * @param[out] minor Where to store the minor version number, or `NULL`. - * @param[out] rev Where to store the revision number, or `NULL`. - * - * @remarks This function may be called before @ref glfwInit. - * - * @remarks This function may be called from any thread. - * - * @sa glfwGetVersionString - * - * @ingroup init - */ -GLFWAPI void glfwGetVersion(int* major, int* minor, int* rev); - -/*! @brief Returns a string describing the compile-time configuration. - * - * This function returns a static string generated at compile-time according to - * which configuration macros were defined. This is intended for use when - * submitting bug reports, to allow developers to see which code paths are - * enabled in a binary. - * - * The format of the string is as follows: - * - The version of GLFW - * - The name of the window system API - * - The name of the context creation API - * - Any additional options or APIs - * - * For example, when compiling GLFW 3.0 with MinGW using the Win32 and WGL - * back ends, the version string may look something like this: - * - * 3.0.0 Win32 WGL MinGW - * - * @return The GLFW version string. - * - * @remarks This function may be called before @ref glfwInit. - * - * @remarks This function may be called from any thread. - * - * @sa glfwGetVersion - * - * @ingroup init - */ -GLFWAPI const char* glfwGetVersionString(void); - -/*! @brief Sets the error callback. - * - * This function sets the error callback, which is called with an error code - * and a human-readable description each time a GLFW error occurs. - * - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @remarks This function may be called before @ref glfwInit. - * - * @note The error callback is called by the thread where the error was - * generated. If you are using GLFW from multiple threads, your error callback - * needs to be written accordingly. - * - * @note Because the description string provided to the callback may have been - * generated specifically for that error, it is not guaranteed to be valid - * after the callback has returned. If you wish to use it after that, you need - * to make your own copy of it before returning. - * - * @ingroup error - */ -GLFWAPI GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun); - -/*! @brief Returns the currently connected monitors. - * - * This function returns an array of handles for all currently connected - * monitors. - * - * @param[out] count Where to store the size of the returned array. This is - * set to zero if an error occurred. - * @return An array of monitor handles, or `NULL` if an error occurred. - * - * @note The returned array is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned array is valid only until the monitor configuration - * changes. See @ref glfwSetMonitorCallback to receive notifications of - * configuration changes. - * - * @sa glfwGetPrimaryMonitor - * - * @ingroup monitor - */ -GLFWAPI GLFWmonitor** glfwGetMonitors(int* count); - -/*! @brief Returns the primary monitor. - * - * This function returns the primary monitor. This is usually the monitor - * where elements like the Windows task bar or the OS X menu bar is located. - * - * @return The primary monitor, or `NULL` if an error occurred. - * - * @sa glfwGetMonitors - * - * @ingroup monitor - */ -GLFWAPI GLFWmonitor* glfwGetPrimaryMonitor(void); - -/*! @brief Returns the position of the monitor's viewport on the virtual screen. - * - * This function returns the position, in screen coordinates, of the upper-left - * corner of the specified monitor. - * - * @param[in] monitor The monitor to query. - * @param[out] xpos Where to store the monitor x-coordinate, or `NULL`. - * @param[out] ypos Where to store the monitor y-coordinate, or `NULL`. - * - * @ingroup monitor - */ -GLFWAPI void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos); - -/*! @brief Returns the physical size of the monitor. - * - * This function returns the size, in millimetres, of the display area of the - * specified monitor. - * - * @param[in] monitor The monitor to query. - * @param[out] width Where to store the width, in mm, of the monitor's display - * area, or `NULL`. - * @param[out] height Where to store the height, in mm, of the monitor's - * display area, or `NULL`. - * - * @note Some operating systems do not provide accurate information, either - * because the monitor's EDID data is incorrect, or because the driver does not - * report it accurately. - * - * @ingroup monitor - */ -GLFWAPI void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height); - -/*! @brief Returns the name of the specified monitor. - * - * This function returns a human-readable name, encoded as UTF-8, of the - * specified monitor. - * - * @param[in] monitor The monitor to query. - * @return The UTF-8 encoded name of the monitor, or `NULL` if an error - * occurred. - * - * @note The returned string is allocated and freed by GLFW. You should not - * free it yourself. - * - * @ingroup monitor - */ -GLFWAPI const char* glfwGetMonitorName(GLFWmonitor* monitor); - -/*! @brief Sets the monitor configuration callback. - * - * This function sets the monitor configuration callback, or removes the - * currently set callback. This is called when a monitor is connected to or - * disconnected from the system. - * - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @bug **X11:** This callback is not yet called on monitor configuration - * changes. - * - * @ingroup monitor - */ -GLFWAPI GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun); - -/*! @brief Returns the available video modes for the specified monitor. - * - * This function returns an array of all video modes supported by the specified - * monitor. The returned array is sorted in ascending order, first by color - * bit depth (the sum of all channel depths) and then by resolution area (the - * product of width and height). - * - * @param[in] monitor The monitor to query. - * @param[out] count Where to store the number of video modes in the returned - * array. This is set to zero if an error occurred. - * @return An array of video modes, or `NULL` if an error occurred. - * - * @note The returned array is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned array is valid only until this function is called again - * for the specified monitor. - * - * @sa glfwGetVideoMode - * - * @ingroup monitor - */ -GLFWAPI const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count); - -/*! @brief Returns the current mode of the specified monitor. - * - * This function returns the current video mode of the specified monitor. If - * you are using a full screen window, the return value will therefore depend - * on whether it is focused. - * - * @param[in] monitor The monitor to query. - * @return The current mode of the monitor, or `NULL` if an error occurred. - * - * @note The returned struct is allocated and freed by GLFW. You should not - * free it yourself. - * - * @sa glfwGetVideoModes - * - * @ingroup monitor - */ -GLFWAPI const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor); - -/*! @brief Generates a gamma ramp and sets it for the specified monitor. - * - * This function generates a 256-element gamma ramp from the specified exponent - * and then calls @ref glfwSetGammaRamp with it. - * - * @param[in] monitor The monitor whose gamma ramp to set. - * @param[in] gamma The desired exponent. - * - * @ingroup monitor - */ -GLFWAPI void glfwSetGamma(GLFWmonitor* monitor, float gamma); - -/*! @brief Retrieves the current gamma ramp for the specified monitor. - * - * This function retrieves the current gamma ramp of the specified monitor. - * - * @param[in] monitor The monitor to query. - * @return The current gamma ramp, or `NULL` if an error occurred. - * - * @note The value arrays of the returned ramp are allocated and freed by GLFW. - * You should not free them yourself. - * - * @ingroup monitor - */ -GLFWAPI const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor); - -/*! @brief Sets the current gamma ramp for the specified monitor. - * - * This function sets the current gamma ramp for the specified monitor. - * - * @param[in] monitor The monitor whose gamma ramp to set. - * @param[in] ramp The gamma ramp to use. - * - * @note Gamma ramp sizes other than 256 are not supported by all hardware. - * - * @ingroup monitor - */ -GLFWAPI void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); - -/*! @brief Resets all window hints to their default values. - * - * This function resets all window hints to their - * [default values](@ref window_hints_values). - * - * @note This function may only be called from the main thread. - * - * @sa glfwWindowHint - * - * @ingroup window - */ -GLFWAPI void glfwDefaultWindowHints(void); - -/*! @brief Sets the specified window hint to the desired value. - * - * This function sets hints for the next call to @ref glfwCreateWindow. The - * hints, once set, retain their values until changed by a call to @ref - * glfwWindowHint or @ref glfwDefaultWindowHints, or until the library is - * terminated with @ref glfwTerminate. - * - * @param[in] target The [window hint](@ref window_hints) to set. - * @param[in] hint The new value of the window hint. - * - * @par New in GLFW 3 - * Hints are no longer reset to their default values on window creation. To - * set default hint values, use @ref glfwDefaultWindowHints. - * - * @note This function may only be called from the main thread. - * - * @sa glfwDefaultWindowHints - * - * @ingroup window - */ -GLFWAPI void glfwWindowHint(int target, int hint); - -/*! @brief Creates a window and its associated context. - * - * This function creates a window and its associated context. Most of the - * options controlling how the window and its context should be created are - * specified through @ref glfwWindowHint. - * - * Successful creation does not change which context is current. Before you - * can use the newly created context, you need to make it current using @ref - * glfwMakeContextCurrent. - * - * Note that the created window and context may differ from what you requested, - * as not all parameters and hints are - * [hard constraints](@ref window_hints_hard). This includes the size of the - * window, especially for full screen windows. To retrieve the actual - * attributes of the created window and context, use queries like @ref - * glfwGetWindowAttrib and @ref glfwGetWindowSize. - * - * To create a full screen window, you need to specify the monitor to use. If - * no monitor is specified, windowed mode will be used. Unless you have a way - * for the user to choose a specific monitor, it is recommended that you pick - * the primary monitor. For more information on how to retrieve monitors, see - * @ref monitor_monitors. - * - * To create the window at a specific position, make it initially invisible - * using the `GLFW_VISIBLE` window hint, set its position and then show it. - * - * If a full screen window is active, the screensaver is prohibited from - * starting. - * - * @param[in] width The desired width, in screen coordinates, of the window. - * This must be greater than zero. - * @param[in] height The desired height, in screen coordinates, of the window. - * This must be greater than zero. - * @param[in] title The initial, UTF-8 encoded window title. - * @param[in] monitor The monitor to use for full screen mode, or `NULL` to use - * windowed mode. - * @param[in] share The window whose context to share resources with, or `NULL` - * to not share resources. - * @return The handle of the created window, or `NULL` if an error occurred. - * - * @remarks **Windows:** Window creation will fail if the Microsoft GDI - * software OpenGL implementation is the only one available. - * - * @remarks **Windows:** If the executable has an icon resource named - * `GLFW_ICON,` it will be set as the icon for the window. If no such icon is - * present, the `IDI_WINLOGO` icon will be used instead. - * - * @remarks **OS X:** The GLFW window has no icon, as it is not a document - * window, but the dock icon will be the same as the application bundle's icon. - * Also, the first time a window is opened the menu bar is populated with - * common commands like Hide, Quit and About. The (minimal) about dialog uses - * information from the application's bundle. For more information on bundles, - * see the Bundle Programming Guide provided by Apple. - * - * @remarks **X11:** There is no mechanism for setting the window icon yet. - * - * @remarks The swap interval is not set during window creation, but is left at - * the default value for that platform. For more information, see @ref - * glfwSwapInterval. - * - * @note This function may only be called from the main thread. - * - * @sa glfwDestroyWindow - * - * @ingroup window - */ -GLFWAPI GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share); - -/*! @brief Destroys the specified window and its context. - * - * This function destroys the specified window and its context. On calling - * this function, no further callbacks will be called for that window. - * - * @param[in] window The window to destroy. - * - * @note This function may only be called from the main thread. - * - * @note This function may not be called from a callback. - * - * @note If the window's context is current on the main thread, it is - * detached before being destroyed. - * - * @warning The window's context must not be current on any other thread. - * - * @sa glfwCreateWindow - * - * @ingroup window - */ -GLFWAPI void glfwDestroyWindow(GLFWwindow* window); - -/*! @brief Checks the close flag of the specified window. - * - * This function returns the value of the close flag of the specified window. - * - * @param[in] window The window to query. - * @return The value of the close flag. - * - * @remarks This function may be called from secondary threads. - * - * @ingroup window - */ -GLFWAPI int glfwWindowShouldClose(GLFWwindow* window); - -/*! @brief Sets the close flag of the specified window. - * - * This function sets the value of the close flag of the specified window. - * This can be used to override the user's attempt to close the window, or - * to signal that it should be closed. - * - * @param[in] window The window whose flag to change. - * @param[in] value The new value. - * - * @remarks This function may be called from secondary threads. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowShouldClose(GLFWwindow* window, int value); - -/*! @brief Sets the title of the specified window. - * - * This function sets the window title, encoded as UTF-8, of the specified - * window. - * - * @param[in] window The window whose title to change. - * @param[in] title The UTF-8 encoded window title. - * - * @note This function may only be called from the main thread. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowTitle(GLFWwindow* window, const char* title); - -/*! @brief Retrieves the position of the client area of the specified window. - * - * This function retrieves the position, in screen coordinates, of the - * upper-left corner of the client area of the specified window. - * - * @param[in] window The window to query. - * @param[out] xpos Where to store the x-coordinate of the upper-left corner of - * the client area, or `NULL`. - * @param[out] ypos Where to store the y-coordinate of the upper-left corner of - * the client area, or `NULL`. - * - * @sa glfwSetWindowPos - * - * @ingroup window - */ -GLFWAPI void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); - -/*! @brief Sets the position of the client area of the specified window. - * - * This function sets the position, in screen coordinates, of the upper-left - * corner of the client area of the window. - * - * If the specified window is a full screen window, this function does nothing. - * - * If you wish to set an initial window position you should create a hidden - * window (using @ref glfwWindowHint and `GLFW_VISIBLE`), set its position and - * then show it. - * - * @param[in] window The window to query. - * @param[in] xpos The x-coordinate of the upper-left corner of the client area. - * @param[in] ypos The y-coordinate of the upper-left corner of the client area. - * - * @note It is very rarely a good idea to move an already visible window, as it - * will confuse and annoy the user. - * - * @note This function may only be called from the main thread. - * - * @note The window manager may put limits on what positions are allowed. - * - * @sa glfwGetWindowPos - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos); - -/*! @brief Retrieves the size of the client area of the specified window. - * - * This function retrieves the size, in screen coordinates, of the client area - * of the specified window. If you wish to retrieve the size of the - * framebuffer in pixels, see @ref glfwGetFramebufferSize. - * - * @param[in] window The window whose size to retrieve. - * @param[out] width Where to store the width, in screen coordinates, of the - * client area, or `NULL`. - * @param[out] height Where to store the height, in screen coordinates, of the - * client area, or `NULL`. - * - * @sa glfwSetWindowSize - * - * @ingroup window - */ -GLFWAPI void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); - -/*! @brief Sets the size of the client area of the specified window. - * - * This function sets the size, in screen coordinates, of the client area of - * the specified window. - * - * For full screen windows, this function selects and switches to the resolution - * closest to the specified size, without affecting the window's context. As - * the context is unaffected, the bit depths of the framebuffer remain - * unchanged. - * - * @param[in] window The window to resize. - * @param[in] width The desired width of the specified window. - * @param[in] height The desired height of the specified window. - * - * @note This function may only be called from the main thread. - * - * @note The window manager may put limits on what window sizes are allowed. - * - * @sa glfwGetWindowSize - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowSize(GLFWwindow* window, int width, int height); - -/*! @brief Retrieves the size of the framebuffer of the specified window. - * - * This function retrieves the size, in pixels, of the framebuffer of the - * specified window. If you wish to retrieve the size of the window in screen - * coordinates, see @ref glfwGetWindowSize. - * - * @param[in] window The window whose framebuffer to query. - * @param[out] width Where to store the width, in pixels, of the framebuffer, - * or `NULL`. - * @param[out] height Where to store the height, in pixels, of the framebuffer, - * or `NULL`. - * - * @sa glfwSetFramebufferSizeCallback - * - * @ingroup window - */ -GLFWAPI void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height); - -/*! @brief Iconifies the specified window. - * - * This function iconifies/minimizes the specified window, if it was previously - * restored. If it is a full screen window, the original monitor resolution is - * restored until the window is restored. If the window is already iconified, - * this function does nothing. - * - * @param[in] window The window to iconify. - * - * @note This function may only be called from the main thread. - * - * @sa glfwRestoreWindow - * - * @ingroup window - */ -GLFWAPI void glfwIconifyWindow(GLFWwindow* window); - -/*! @brief Restores the specified window. - * - * This function restores the specified window, if it was previously - * iconified/minimized. If it is a full screen window, the resolution chosen - * for the window is restored on the selected monitor. If the window is - * already restored, this function does nothing. - * - * @param[in] window The window to restore. - * - * @note This function may only be called from the main thread. - * - * @sa glfwIconifyWindow - * - * @ingroup window - */ -GLFWAPI void glfwRestoreWindow(GLFWwindow* window); - -/*! @brief Makes the specified window visible. - * - * This function makes the specified window visible, if it was previously - * hidden. If the window is already visible or is in full screen mode, this - * function does nothing. - * - * @param[in] window The window to make visible. - * - * @note This function may only be called from the main thread. - * - * @sa glfwHideWindow - * - * @ingroup window - */ -GLFWAPI void glfwShowWindow(GLFWwindow* window); - -/*! @brief Hides the specified window. - * - * This function hides the specified window, if it was previously visible. If - * the window is already hidden or is in full screen mode, this function does - * nothing. - * - * @param[in] window The window to hide. - * - * @note This function may only be called from the main thread. - * - * @sa glfwShowWindow - * - * @ingroup window - */ -GLFWAPI void glfwHideWindow(GLFWwindow* window); - -/*! @brief Returns the monitor that the window uses for full screen mode. - * - * This function returns the handle of the monitor that the specified window is - * in full screen on. - * - * @param[in] window The window to query. - * @return The monitor, or `NULL` if the window is in windowed mode. - * - * @ingroup window - */ -GLFWAPI GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window); - -/*! @brief Returns an attribute of the specified window. - * - * This function returns an attribute of the specified window. There are many - * attributes, some related to the window and others to its context. - * - * @param[in] window The window to query. - * @param[in] attrib The [window attribute](@ref window_attribs) whose value to - * return. - * @return The value of the attribute, or zero if an error occurred. - * - * @ingroup window - */ -GLFWAPI int glfwGetWindowAttrib(GLFWwindow* window, int attrib); - -/*! @brief Sets the user pointer of the specified window. - * - * This function sets the user-defined pointer of the specified window. The - * current value is retained until the window is destroyed. The initial value - * is `NULL`. - * - * @param[in] window The window whose pointer to set. - * @param[in] pointer The new value. - * - * @sa glfwGetWindowUserPointer - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer); - -/*! @brief Returns the user pointer of the specified window. - * - * This function returns the current value of the user-defined pointer of the - * specified window. The initial value is `NULL`. - * - * @param[in] window The window whose pointer to return. - * - * @sa glfwSetWindowUserPointer - * - * @ingroup window - */ -GLFWAPI void* glfwGetWindowUserPointer(GLFWwindow* window); - -/*! @brief Sets the position callback for the specified window. - * - * This function sets the position callback of the specified window, which is - * called when the window is moved. The callback is provided with the screen - * position of the upper-left corner of the client area of the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup window - */ -GLFWAPI GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun); - -/*! @brief Sets the size callback for the specified window. - * - * This function sets the size callback of the specified window, which is - * called when the window is resized. The callback is provided with the size, - * in screen coordinates, of the client area of the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup window - */ -GLFWAPI GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun); - -/*! @brief Sets the close callback for the specified window. - * - * This function sets the close callback of the specified window, which is - * called when the user attempts to close the window, for example by clicking - * the close widget in the title bar. - * - * The close flag is set before this callback is called, but you can modify it - * at any time with @ref glfwSetWindowShouldClose. - * - * The close callback is not triggered by @ref glfwDestroyWindow. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @par New in GLFW 3 - * The close callback no longer returns a value. - * - * @remarks **OS X:** Selecting Quit from the application menu will - * trigger the close callback for all windows. - * - * @ingroup window - */ -GLFWAPI GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun); - -/*! @brief Sets the refresh callback for the specified window. - * - * This function sets the refresh callback of the specified window, which is - * called when the client area of the window needs to be redrawn, for example - * if the window has been exposed after having been covered by another window. - * - * On compositing window systems such as Aero, Compiz or Aqua, where the window - * contents are saved off-screen, this callback may be called only very - * infrequently or never at all. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @note On compositing window systems such as Aero, Compiz or Aqua, where the - * window contents are saved off-screen, this callback may be called only very - * infrequently or never at all. - * - * @ingroup window - */ -GLFWAPI GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, GLFWwindowrefreshfun cbfun); - -/*! @brief Sets the focus callback for the specified window. - * - * This function sets the focus callback of the specified window, which is - * called when the window gains or loses focus. - * - * After the focus callback is called for a window that lost focus, synthetic - * key and mouse button release events will be generated for all such that had - * been pressed. For more information, see @ref glfwSetKeyCallback and @ref - * glfwSetMouseButtonCallback. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup window - */ -GLFWAPI GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun); - -/*! @brief Sets the iconify callback for the specified window. - * - * This function sets the iconification callback of the specified window, which - * is called when the window is iconified or restored. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup window - */ -GLFWAPI GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun); - -/*! @brief Sets the framebuffer resize callback for the specified window. - * - * This function sets the framebuffer resize callback of the specified window, - * which is called when the framebuffer of the specified window is resized. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup window - */ -GLFWAPI GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun); - -/*! @brief Processes all pending events. - * - * This function processes only those events that have already been received - * and then returns immediately. Processing events will cause the window and - * input callbacks associated with those events to be called. - * - * This function is not required for joystick input to work. - * - * @par New in GLFW 3 - * This function is no longer called by @ref glfwSwapBuffers. You need to call - * it or @ref glfwWaitEvents yourself. - * - * @remarks On some platforms, a window move, resize or menu operation will - * cause event processing to block. This is due to how event processing is - * designed on those platforms. You can use the - * [window refresh callback](@ref GLFWwindowrefreshfun) to redraw the contents - * of your window when necessary during the operation. - * - * @note This function may only be called from the main thread. - * - * @note This function may not be called from a callback. - * - * @note On some platforms, certain callbacks may be called outside of a call - * to one of the event processing functions. - * - * @sa glfwWaitEvents - * - * @ingroup window - */ -GLFWAPI void glfwPollEvents(void); - -/*! @brief Waits until events are pending and processes them. - * - * This function puts the calling thread to sleep until at least one event has - * been received. Once one or more events have been received, it behaves as if - * @ref glfwPollEvents was called, i.e. the events are processed and the - * function then returns immediately. Processing events will cause the window - * and input callbacks associated with those events to be called. - * - * Since not all events are associated with callbacks, this function may return - * without a callback having been called even if you are monitoring all - * callbacks. - * - * This function is not required for joystick input to work. - * - * @remarks On some platforms, a window move, resize or menu operation will - * cause event processing to block. This is due to how event processing is - * designed on those platforms. You can use the - * [window refresh callback](@ref GLFWwindowrefreshfun) to redraw the contents - * of your window when necessary during the operation. - * - * @note This function may only be called from the main thread. - * - * @note This function may not be called from a callback. - * - * @note On some platforms, certain callbacks may be called outside of a call - * to one of the event processing functions. - * - * @sa glfwPollEvents - * - * @ingroup window - */ -GLFWAPI void glfwWaitEvents(void); - -/*! @brief Returns the value of an input option for the specified window. - * - * @param[in] window The window to query. - * @param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or - * `GLFW_STICKY_MOUSE_BUTTONS`. - * - * @sa glfwSetInputMode - * - * @ingroup input - */ -GLFWAPI int glfwGetInputMode(GLFWwindow* window, int mode); - -/*! @brief Sets an input option for the specified window. - * @param[in] window The window whose input mode to set. - * @param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or - * `GLFW_STICKY_MOUSE_BUTTONS`. - * @param[in] value The new value of the specified input mode. - * - * If `mode` is `GLFW_CURSOR`, the value must be one of the supported input - * modes: - * - `GLFW_CURSOR_NORMAL` makes the cursor visible and behaving normally. - * - `GLFW_CURSOR_HIDDEN` makes the cursor invisible when it is over the client - * area of the window but does not restrict the cursor from leaving. This is - * useful if you wish to render your own cursor or have no visible cursor at - * all. - * - `GLFW_CURSOR_DISABLED` hides and grabs the cursor, providing virtual - * and unlimited cursor movement. This is useful for implementing for - * example 3D camera controls. - * - * If `mode` is `GLFW_STICKY_KEYS`, the value must be either `GL_TRUE` to - * enable sticky keys, or `GL_FALSE` to disable it. If sticky keys are - * enabled, a key press will ensure that @ref glfwGetKey returns @ref - * GLFW_PRESS the next time it is called even if the key had been released - * before the call. This is useful when you are only interested in whether - * keys have been pressed but not when or in which order. - * - * If `mode` is `GLFW_STICKY_MOUSE_BUTTONS`, the value must be either `GL_TRUE` - * to enable sticky mouse buttons, or `GL_FALSE` to disable it. If sticky - * mouse buttons are enabled, a mouse button press will ensure that @ref - * glfwGetMouseButton returns @ref GLFW_PRESS the next time it is called even - * if the mouse button had been released before the call. This is useful when - * you are only interested in whether mouse buttons have been pressed but not - * when or in which order. - * - * @sa glfwGetInputMode - * - * @ingroup input - */ -GLFWAPI void glfwSetInputMode(GLFWwindow* window, int mode, int value); - -/*! @brief Returns the last reported state of a keyboard key for the specified - * window. - * - * This function returns the last state reported for the specified key to the - * specified window. The returned state is one of `GLFW_PRESS` or - * `GLFW_RELEASE`. The higher-level state `GLFW_REPEAT` is only reported to - * the key callback. - * - * If the `GLFW_STICKY_KEYS` input mode is enabled, this function returns - * `GLFW_PRESS` the first time you call this function after a key has been - * pressed, even if the key has already been released. - * - * The key functions deal with physical keys, with [key tokens](@ref keys) - * named after their use on the standard US keyboard layout. If you want to - * input text, use the Unicode character callback instead. - * - * @param[in] window The desired window. - * @param[in] key The desired [keyboard key](@ref keys). - * @return One of `GLFW_PRESS` or `GLFW_RELEASE`. - * - * @note `GLFW_KEY_UNKNOWN` is not a valid key for this function. - * - * @ingroup input - */ -GLFWAPI int glfwGetKey(GLFWwindow* window, int key); - -/*! @brief Returns the last reported state of a mouse button for the specified - * window. - * - * This function returns the last state reported for the specified mouse button - * to the specified window. - * - * If the `GLFW_STICKY_MOUSE_BUTTONS` input mode is enabled, this function - * returns `GLFW_PRESS` the first time you call this function after a mouse - * button has been pressed, even if the mouse button has already been released. - * - * @param[in] window The desired window. - * @param[in] button The desired [mouse button](@ref buttons). - * @return One of `GLFW_PRESS` or `GLFW_RELEASE`. - * - * @ingroup input - */ -GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); - -/*! @brief Retrieves the last reported cursor position, relative to the client - * area of the window. - * - * This function returns the last reported position of the cursor, in screen - * coordinates, relative to the upper-left corner of the client area of the - * specified window. - * - * If the cursor is disabled (with `GLFW_CURSOR_DISABLED`) then the cursor - * position is unbounded and limited only by the minimum and maximum values of - * a `double`. - * - * The coordinate can be converted to their integer equivalents with the - * `floor` function. Casting directly to an integer type works for positive - * coordinates, but fails for negative ones. - * - * @param[in] window The desired window. - * @param[out] xpos Where to store the cursor x-coordinate, relative to the - * left edge of the client area, or `NULL`. - * @param[out] ypos Where to store the cursor y-coordinate, relative to the to - * top edge of the client area, or `NULL`. - * - * @sa glfwSetCursorPos - * - * @ingroup input - */ -GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); - -/*! @brief Sets the position of the cursor, relative to the client area of the - * window. - * - * This function sets the position, in screen coordinates, of the cursor - * relative to the upper-left corner of the client area of the specified - * window. The window must be focused. If the window does not have focus when - * this function is called, it fails silently. - * - * If the cursor is disabled (with `GLFW_CURSOR_DISABLED`) then the cursor - * position is unbounded and limited only by the minimum and maximum values of - * a `double`. - * - * @param[in] window The desired window. - * @param[in] xpos The desired x-coordinate, relative to the left edge of the - * client area. - * @param[in] ypos The desired y-coordinate, relative to the top edge of the - * client area. - * - * @sa glfwGetCursorPos - * - * @ingroup input - */ -GLFWAPI void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos); - -/*! @brief Sets the key callback. - * - * This function sets the key callback of the specific window, which is called - * when a key is pressed, repeated or released. - * - * The key functions deal with physical keys, with layout independent - * [key tokens](@ref keys) named after their values in the standard US keyboard - * layout. If you want to input text, use the - * [character callback](@ref glfwSetCharCallback) instead. - * - * When a window loses focus, it will generate synthetic key release events - * for all pressed keys. You can tell these events from user-generated events - * by the fact that the synthetic ones are generated after the window has lost - * focus, i.e. `GLFW_FOCUSED` will be false and the focus callback will have - * already been called. - * - * The scancode of a key is specific to that platform or sometimes even to that - * machine. Scancodes are intended to allow users to bind keys that don't have - * a GLFW key token. Such keys have `key` set to `GLFW_KEY_UNKNOWN`, their - * state is not saved and so it cannot be retrieved with @ref glfwGetKey. - * - * Sometimes GLFW needs to generate synthetic key events, in which case the - * scancode may be zero. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new key callback, or `NULL` to remove the currently - * set callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun); - -/*! @brief Sets the Unicode character callback. - * - * This function sets the character callback of the specific window, which is - * called when a Unicode character is input. - * - * The character callback is intended for text input. If you want to know - * whether a specific key was pressed or released, use the - * [key callback](@ref glfwSetKeyCallback) instead. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun); - -/*! @brief Sets the mouse button callback. - * - * This function sets the mouse button callback of the specified window, which - * is called when a mouse button is pressed or released. - * - * When a window loses focus, it will generate synthetic mouse button release - * events for all pressed mouse buttons. You can tell these events from - * user-generated events by the fact that the synthetic ones are generated - * after the window has lost focus, i.e. `GLFW_FOCUSED` will be false and the - * focus callback will have already been called. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun); - -/*! @brief Sets the cursor position callback. - * - * This function sets the cursor position callback of the specified window, - * which is called when the cursor is moved. The callback is provided with the - * position, in screen coordinates, relative to the upper-left corner of the - * client area of the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun); - -/*! @brief Sets the cursor enter/exit callback. - * - * This function sets the cursor boundary crossing callback of the specified - * window, which is called when the cursor enters or leaves the client area of - * the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun cbfun); - -/*! @brief Sets the scroll callback. - * - * This function sets the scroll callback of the specified window, which is - * called when a scrolling device is used, such as a mouse wheel or scrolling - * area of a touchpad. - * - * The scroll callback receives all scrolling input, like that from a mouse - * wheel or a touchpad scrolling area. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new scroll callback, or `NULL` to remove the currently - * set callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun); - -/*! @brief Returns whether the specified joystick is present. - * - * This function returns whether the specified joystick is present. - * - * @param[in] joy The joystick to query. - * @return `GL_TRUE` if the joystick is present, or `GL_FALSE` otherwise. - * - * @ingroup input - */ -GLFWAPI int glfwJoystickPresent(int joy); - -/*! @brief Returns the values of all axes of the specified joystick. - * - * This function returns the values of all axes of the specified joystick. - * - * @param[in] joy The joystick to query. - * @param[out] count Where to store the size of the returned array. This is - * set to zero if an error occurred. - * @return An array of axis values, or `NULL` if the joystick is not present. - * - * @note The returned array is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned array is valid only until the next call to @ref - * glfwGetJoystickAxes for that joystick. - * - * @ingroup input - */ -GLFWAPI const float* glfwGetJoystickAxes(int joy, int* count); - -/*! @brief Returns the state of all buttons of the specified joystick. - * - * This function returns the state of all buttons of the specified joystick. - * - * @param[in] joy The joystick to query. - * @param[out] count Where to store the size of the returned array. This is - * set to zero if an error occurred. - * @return An array of button states, or `NULL` if the joystick is not present. - * - * @note The returned array is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned array is valid only until the next call to @ref - * glfwGetJoystickButtons for that joystick. - * - * @ingroup input - */ -GLFWAPI const unsigned char* glfwGetJoystickButtons(int joy, int* count); - -/*! @brief Returns the name of the specified joystick. - * - * This function returns the name, encoded as UTF-8, of the specified joystick. - * - * @param[in] joy The joystick to query. - * @return The UTF-8 encoded name of the joystick, or `NULL` if the joystick - * is not present. - * - * @note The returned string is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned string is valid only until the next call to @ref - * glfwGetJoystickName for that joystick. - * - * @ingroup input - */ -GLFWAPI const char* glfwGetJoystickName(int joy); - -/*! @brief Sets the clipboard to the specified string. - * - * This function sets the system clipboard to the specified, UTF-8 encoded - * string. The string is copied before returning, so you don't have to retain - * it afterwards. - * - * @param[in] window The window that will own the clipboard contents. - * @param[in] string A UTF-8 encoded string. - * - * @note This function may only be called from the main thread. - * - * @sa glfwGetClipboardString - * - * @ingroup clipboard - */ -GLFWAPI void glfwSetClipboardString(GLFWwindow* window, const char* string); - -/*! @brief Retrieves the contents of the clipboard as a string. - * - * This function returns the contents of the system clipboard, if it contains - * or is convertible to a UTF-8 encoded string. - * - * @param[in] window The window that will request the clipboard contents. - * @return The contents of the clipboard as a UTF-8 encoded string, or `NULL` - * if an error occurred. - * - * @note This function may only be called from the main thread. - * - * @note The returned string is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned string is valid only until the next call to @ref - * glfwGetClipboardString or @ref glfwSetClipboardString. - * - * @sa glfwSetClipboardString - * - * @ingroup clipboard - */ -GLFWAPI const char* glfwGetClipboardString(GLFWwindow* window); - -/*! @brief Returns the value of the GLFW timer. - * - * This function returns the value of the GLFW timer. Unless the timer has - * been set using @ref glfwSetTime, the timer measures time elapsed since GLFW - * was initialized. - * - * @return The current value, in seconds, or zero if an error occurred. - * - * @remarks This function may be called from secondary threads. - * - * @note The resolution of the timer is system dependent, but is usually on the - * order of a few micro- or nanoseconds. It uses the highest-resolution - * monotonic time source on each supported platform. - * - * @ingroup time - */ -GLFWAPI double glfwGetTime(void); - -/*! @brief Sets the GLFW timer. - * - * This function sets the value of the GLFW timer. It then continues to count - * up from that value. - * - * @param[in] time The new value, in seconds. - * - * @note The resolution of the timer is system dependent, but is usually on the - * order of a few micro- or nanoseconds. It uses the highest-resolution - * monotonic time source on each supported platform. - * - * @ingroup time - */ -GLFWAPI void glfwSetTime(double time); - -/*! @brief Makes the context of the specified window current for the calling - * thread. - * - * This function makes the context of the specified window current on the - * calling thread. A context can only be made current on a single thread at - * a time and each thread can have only a single current context at a time. - * - * @param[in] window The window whose context to make current, or `NULL` to - * detach the current context. - * - * @remarks This function may be called from secondary threads. - * - * @sa glfwGetCurrentContext - * - * @ingroup context - */ -GLFWAPI void glfwMakeContextCurrent(GLFWwindow* window); - -/*! @brief Returns the window whose context is current on the calling thread. - * - * This function returns the window whose context is current on the calling - * thread. - * - * @return The window whose context is current, or `NULL` if no window's - * context is current. - * - * @remarks This function may be called from secondary threads. - * - * @sa glfwMakeContextCurrent - * - * @ingroup context - */ -GLFWAPI GLFWwindow* glfwGetCurrentContext(void); - -/*! @brief Swaps the front and back buffers of the specified window. - * - * This function swaps the front and back buffers of the specified window. If - * the swap interval is greater than zero, the GPU driver waits the specified - * number of screen updates before swapping the buffers. - * - * @param[in] window The window whose buffers to swap. - * - * @remarks This function may be called from secondary threads. - * - * @par New in GLFW 3 - * This function no longer calls @ref glfwPollEvents. You need to call it or - * @ref glfwWaitEvents yourself. - * - * @sa glfwSwapInterval - * - * @ingroup context - */ -GLFWAPI void glfwSwapBuffers(GLFWwindow* window); - -/*! @brief Sets the swap interval for the current context. - * - * This function sets the swap interval for the current context, i.e. the - * number of screen updates to wait before swapping the buffers of a window and - * returning from @ref glfwSwapBuffers. This is sometimes called 'vertical - * synchronization', 'vertical retrace synchronization' or 'vsync'. - * - * Contexts that support either of the `WGL_EXT_swap_control_tear` and - * `GLX_EXT_swap_control_tear` extensions also accept negative swap intervals, - * which allow the driver to swap even if a frame arrives a little bit late. - * You can check for the presence of these extensions using @ref - * glfwExtensionSupported. For more information about swap tearing, see the - * extension specifications. - * - * @param[in] interval The minimum number of screen updates to wait for - * until the buffers are swapped by @ref glfwSwapBuffers. - * - * @remarks This function may be called from secondary threads. - * - * @note This function is not called during window creation, leaving the swap - * interval set to whatever is the default on that platform. This is done - * because some swap interval extensions used by GLFW do not allow the swap - * interval to be reset to zero once it has been set to a non-zero value. - * - * @note Some GPU drivers do not honor the requested swap interval, either - * because of user settings that override the request or due to bugs in the - * driver. - * - * @sa glfwSwapBuffers - * - * @ingroup context - */ -GLFWAPI void glfwSwapInterval(int interval); - -/*! @brief Returns whether the specified extension is available. - * - * This function returns whether the specified - * [OpenGL or context creation API extension](@ref context_glext) is supported - * by the current context. For example, on Windows both the OpenGL and WGL - * extension strings are checked. - * - * @param[in] extension The ASCII encoded name of the extension. - * @return `GL_TRUE` if the extension is available, or `GL_FALSE` otherwise. - * - * @remarks This function may be called from secondary threads. - * - * @note As this functions searches one or more extension strings on each call, - * it is recommended that you cache its results if it's going to be used - * frequently. The extension strings will not change during the lifetime of - * a context, so there is no danger in doing this. - * - * @ingroup context - */ -GLFWAPI int glfwExtensionSupported(const char* extension); - -/*! @brief Returns the address of the specified function for the current - * context. - * - * This function returns the address of the specified - * [client API or extension function](@ref context_glext), if it is supported - * by the current context. - * - * @param[in] procname The ASCII encoded name of the function. - * @return The address of the function, or `NULL` if the function is - * unavailable. - * - * @remarks This function may be called from secondary threads. - * - * @note The addresses of these functions are not guaranteed to be the same for - * all contexts, especially if they use different client APIs or even different - * context creation hints. - * - * @ingroup context - */ -GLFWAPI GLFWglproc glfwGetProcAddress(const char* procname); - - -/************************************************************************* - * Global definition cleanup - *************************************************************************/ - -/* ------------------- BEGIN SYSTEM/COMPILER SPECIFIC -------------------- */ - -#ifdef GLFW_WINGDIAPI_DEFINED - #undef WINGDIAPI - #undef GLFW_WINGDIAPI_DEFINED -#endif - -#ifdef GLFW_CALLBACK_DEFINED - #undef CALLBACK - #undef GLFW_CALLBACK_DEFINED -#endif - -/* -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- */ - - -#ifdef __cplusplus -} -#endif - -#endif /* _glfw3_h_ */ - diff --git a/win32/include/glfw3/glfw3native.h b/win32/include/glfw3/glfw3native.h deleted file mode 100644 index d570f587..00000000 --- a/win32/include/glfw3/glfw3native.h +++ /dev/null @@ -1,180 +0,0 @@ -/************************************************************************* - * GLFW 3.0 - www.glfw.org - * A library for OpenGL, window and input - *------------------------------------------------------------------------ - * Copyright (c) 2002-2006 Marcus Geelnard - * Copyright (c) 2006-2010 Camilla Berglund - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would - * be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and must not - * be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - *************************************************************************/ - -#ifndef _glfw3_native_h_ -#define _glfw3_native_h_ - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************************************************* - * Doxygen documentation - *************************************************************************/ - -/*! @defgroup native Native access - * - * **By using the native API, you assert that you know what you're doing and - * how to fix problems caused by using it. If you don't, you shouldn't be - * using it.** - * - * Before the inclusion of @ref glfw3native.h, you must define exactly one - * window API macro and exactly one context API macro. Failure to do this - * will cause a compile-time error. - * - * The available window API macros are: - * * `GLFW_EXPOSE_NATIVE_WIN32` - * * `GLFW_EXPOSE_NATIVE_COCOA` - * * `GLFW_EXPOSE_NATIVE_X11` - * - * The available context API macros are: - * * `GLFW_EXPOSE_NATIVE_WGL` - * * `GLFW_EXPOSE_NATIVE_NSGL` - * * `GLFW_EXPOSE_NATIVE_GLX` - * * `GLFW_EXPOSE_NATIVE_EGL` - * - * These macros select which of the native access functions that are declared - * and which platform-specific headers to include. It is then up your (by - * definition platform-specific) code to handle which of these should be - * defined. - */ - - -/************************************************************************* - * System headers and types - *************************************************************************/ - -#if defined(GLFW_EXPOSE_NATIVE_WIN32) - #include -#elif defined(GLFW_EXPOSE_NATIVE_COCOA) - #if defined(__OBJC__) - #import - #else - typedef void* id; - #endif -#elif defined(GLFW_EXPOSE_NATIVE_X11) - #include -#else - #error "No window API specified" -#endif - -#if defined(GLFW_EXPOSE_NATIVE_WGL) - /* WGL is declared by windows.h */ -#elif defined(GLFW_EXPOSE_NATIVE_NSGL) - /* NSGL is declared by Cocoa.h */ -#elif defined(GLFW_EXPOSE_NATIVE_GLX) - #include -#elif defined(GLFW_EXPOSE_NATIVE_EGL) - #include -#else - #error "No context API specified" -#endif - - -/************************************************************************* - * Functions - *************************************************************************/ - -#if defined(GLFW_EXPOSE_NATIVE_WIN32) -/*! @brief Returns the `HWND` of the specified window. - * @return The `HWND` of the specified window. - * @ingroup native - */ -GLFWAPI HWND glfwGetWin32Window(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_WGL) -/*! @brief Returns the `HGLRC` of the specified window. - * @return The `HGLRC` of the specified window. - * @ingroup native - */ -GLFWAPI HGLRC glfwGetWGLContext(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_COCOA) -/*! @brief Returns the `NSWindow` of the specified window. - * @return The `NSWindow` of the specified window. - * @ingroup native - */ -GLFWAPI id glfwGetCocoaWindow(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_NSGL) -/*! @brief Returns the `NSOpenGLContext` of the specified window. - * @return The `NSOpenGLContext` of the specified window. - * @ingroup native - */ -GLFWAPI id glfwGetNSGLContext(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_X11) -/*! @brief Returns the `Display` used by GLFW. - * @return The `Display` used by GLFW. - * @ingroup native - */ -GLFWAPI Display* glfwGetX11Display(void); -/*! @brief Returns the `Window` of the specified window. - * @return The `Window` of the specified window. - * @ingroup native - */ -GLFWAPI Window glfwGetX11Window(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_GLX) -/*! @brief Returns the `GLXContext` of the specified window. - * @return The `GLXContext` of the specified window. - * @ingroup native - */ -GLFWAPI GLXContext glfwGetGLXContext(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_EGL) -/*! @brief Returns the `EGLDisplay` used by GLFW. - * @return The `EGLDisplay` used by GLFW. - * @ingroup native - */ -GLFWAPI EGLDisplay glfwGetEGLDisplay(void); -/*! @brief Returns the `EGLContext` of the specified window. - * @return The `EGLContext` of the specified window. - * @ingroup native - */ -GLFWAPI EGLContext glfwGetEGLContext(GLFWwindow* window); -/*! @brief Returns the `EGLSurface` of the specified window. - * @return The `EGLSurface` of the specified window. - * @ingroup native - */ -GLFWAPI EGLSurface glfwGetEGLSurface(GLFWwindow* window); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* _glfw3_native_h_ */ - diff --git a/win32/include/jpeg/jmorecfg.h b/win32/include/jpeg/jmorecfg.h index 2407edbe..a3a58878 100644 --- a/win32/include/jpeg/jmorecfg.h +++ b/win32/include/jpeg/jmorecfg.h @@ -263,7 +263,6 @@ typedef void noreturn_t; typedef enum { FALSE = 0, TRUE = 1 } boolean; #endif - /* * The remaining options affect code selection within the JPEG library, * but they don't need to be visible to most applications using the library. diff --git a/win32/include/spidermonkey/fdlibm.h b/win32/include/spidermonkey/fdlibm.h deleted file mode 100755 index 0ad21591..00000000 --- a/win32/include/spidermonkey/fdlibm.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ==================================================== - * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. - * - * Developed at SunPro, a Sun Microsystems, Inc. business. - * Permission to use, copy, modify, and distribute this - * software is freely granted, provided that this notice - * is preserved. - * ==================================================== - */ - -/* - * from: @(#)fdlibm.h 5.1 93/09/24 - * $FreeBSD$ - */ - -#ifndef mozilla_imported_fdlibm_h -#define mozilla_imported_fdlibm_h - -namespace fdlibm { - -double acos(double); -double asin(double); -double atan(double); -double atan2(double, double); - -double cosh(double); -double sinh(double); -double tanh(double); - -double exp(double); -double log(double); -double log10(double); - -double pow(double, double); -double sqrt(double); -double fabs(double); - -double floor(double); -double trunc(double); -double ceil(double); - -double acosh(double); -double asinh(double); -double atanh(double); -double cbrt(double); -double expm1(double); -double hypot(double, double); -double log1p(double); -double log2(double); -double rint(double); -double copysign(double, double); -double nearbyint(double); -double scalbn(double, int); - -float ceilf(float); -float floorf(float); - -float nearbyintf(float); -float rintf(float); -float truncf(float); - -} /* namespace fdlibm */ - -#endif /* mozilla_imported_fdlibm_h */ diff --git a/win32/include/spidermonkey/js-config.h b/win32/include/spidermonkey/js-config.h deleted file mode 100755 index f21bdf41..00000000 --- a/win32/include/spidermonkey/js-config.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sw=4 et tw=78: - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_config_h -#define js_config_h - -/* Definitions set at build time that affect SpiderMonkey's public API. - This header file is generated by the SpiderMonkey configure script, - and installed along with jsapi.h. */ - -/* Define to 1 if SpiderMonkey is in debug mode. */ -/* #undef JS_DEBUG */ - -/* - * NB: We have a special case for rust-bindgen, which wants to be able to - * generate both debug and release bindings on a single objdir. - */ -#ifdef JS_DEBUG -#if !defined(DEBUG) && !defined(RUST_BINDGEN) -# error "SpiderMonkey was configured with --enable-debug, so DEBUG must be defined when including this header" -# endif -#else -# if defined(DEBUG) && !defined(RUST_BINDGEN) -# error "SpiderMonkey was configured with --disable-debug, so DEBUG must be not defined when including this header" -# endif -#endif - -/* Define to 1 if SpiderMonkey should not use struct types in debug builds. */ -/* #undef JS_NO_JSVAL_JSID_STRUCT_TYPES */ - -/* Define to 1 if SpiderMonkey should support multi-threaded clients. */ -/* #undef JS_THREADSAFE */ - -/* Define to 1 if SpiderMonkey should include ctypes support. */ -/* #undef JS_HAS_CTYPES */ - -/* Define to 1 if SpiderMonkey should support the ability to perform - entirely too much GC. */ -/* #undef JS_GC_ZEAL */ - -/* Define to 1 if SpiderMonkey should use small chunks. */ -/* #undef JS_GC_SMALL_CHUNK_SIZE */ - -/* Define to 1 to perform extra assertions and heap poisoning. */ -/* #undef JS_CRASH_DIAGNOSTICS */ - -/* Define to 1 if SpiderMonkey is in NUNBOX32 mode. */ -#define JS_NUNBOX32 1 - -/* Define to 1 if SpiderMonkey is in PUNBOX64 mode. */ -/* #undef JS_PUNBOX64 */ - -/* MOZILLA JSAPI version number components */ -#define MOZJS_MAJOR_VERSION 52 -#define MOZJS_MINOR_VERSION 0 - -#endif /* js_config_h */ diff --git a/win32/include/spidermonkey/js.msg b/win32/include/spidermonkey/js.msg deleted file mode 100755 index 246e363c..00000000 --- a/win32/include/spidermonkey/js.msg +++ /dev/null @@ -1,581 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * This is the JavaScript error message file. - * - * The format for each JS error message is: - * - * MSG_DEF(, , , - * ) - * - * where ; - * is a legal C identifer that will be used in the - * JS engine source. - * - * is an integer literal specifying the total number of - * replaceable arguments in the following format string. - * - * is an exception index from the enum in jsexn.c; - * JSEXN_NONE for none. The given exception index will be raised by the - * engine when the corresponding error occurs. - * - * is a string literal, optionally containing sequences - * {X} where X is an integer representing the argument number that will - * be replaced with a string value when the error is reported. - * - * e.g. - * - * MSG_DEF(JSMSG_NOT_A_SUBSPECIES, 2, JSEXN_NONE, - * "{0} is not a member of the {1} family") - * - * can be used: - * - * JS_ReportErrorNumberASCII(JSMSG_NOT_A_SUBSPECIES, "Rhino", "Monkey"); - * - * to report: - * - * "Rhino is not a member of the Monkey family" - */ - -MSG_DEF(JSMSG_NOT_AN_ERROR, 0, JSEXN_ERR, "") -MSG_DEF(JSMSG_NOT_DEFINED, 1, JSEXN_REFERENCEERR, "{0} is not defined") -MSG_DEF(JSMSG_MORE_ARGS_NEEDED, 3, JSEXN_TYPEERR, "{0} requires more than {1} argument{2}") -MSG_DEF(JSMSG_INCOMPATIBLE_PROTO, 3, JSEXN_TYPEERR, "{0}.prototype.{1} called on incompatible {2}") -MSG_DEF(JSMSG_NO_CONSTRUCTOR, 1, JSEXN_TYPEERR, "{0} has no constructor") -MSG_DEF(JSMSG_BAD_SORT_ARG, 0, JSEXN_TYPEERR, "invalid Array.prototype.sort argument") -MSG_DEF(JSMSG_CANT_WATCH, 1, JSEXN_TYPEERR, "can't watch non-native objects of class {0}") -MSG_DEF(JSMSG_READ_ONLY, 1, JSEXN_TYPEERR, "{0} is read-only") -MSG_DEF(JSMSG_CANT_DELETE, 1, JSEXN_TYPEERR, "property {0} is non-configurable and can't be deleted") -MSG_DEF(JSMSG_CANT_TRUNCATE_ARRAY, 0, JSEXN_TYPEERR, "can't delete non-configurable array element") -MSG_DEF(JSMSG_NOT_FUNCTION, 1, JSEXN_TYPEERR, "{0} is not a function") -MSG_DEF(JSMSG_NOT_CONSTRUCTOR, 1, JSEXN_TYPEERR, "{0} is not a constructor") -MSG_DEF(JSMSG_CANT_CONVERT_TO, 2, JSEXN_TYPEERR, "can't convert {0} to {1}") -MSG_DEF(JSMSG_TOPRIMITIVE_NOT_CALLABLE, 2, JSEXN_TYPEERR, "can't convert {0} to {1}: its [Symbol.toPrimitive] property is not a function") -MSG_DEF(JSMSG_TOPRIMITIVE_RETURNED_OBJECT, 2, JSEXN_TYPEERR, "can't convert {0} to {1}: its [Symbol.toPrimitive] method returned an object") -MSG_DEF(JSMSG_NO_PROPERTIES, 1, JSEXN_TYPEERR, "{0} has no properties") -MSG_DEF(JSMSG_BAD_REGEXP_FLAG, 1, JSEXN_SYNTAXERR, "invalid regular expression flag {0}") -MSG_DEF(JSMSG_ARG_INDEX_OUT_OF_RANGE, 1, JSEXN_RANGEERR, "argument {0} accesses an index that is out of range") -MSG_DEF(JSMSG_SPREAD_TOO_LARGE, 0, JSEXN_RANGEERR, "array too large due to spread operand(s)") -MSG_DEF(JSMSG_BAD_WEAKMAP_KEY, 0, JSEXN_TYPEERR, "cannot use the given object as a weak map key") -MSG_DEF(JSMSG_BAD_GETTER_OR_SETTER, 1, JSEXN_TYPEERR, "invalid {0} usage") -MSG_DEF(JSMSG_BAD_ARRAY_LENGTH, 0, JSEXN_RANGEERR, "invalid array length") -MSG_DEF(JSMSG_REDECLARED_VAR, 2, JSEXN_SYNTAXERR, "redeclaration of {0} {1}") -MSG_DEF(JSMSG_UNDECLARED_VAR, 1, JSEXN_REFERENCEERR, "assignment to undeclared variable {0}") -MSG_DEF(JSMSG_GETTER_ONLY, 0, JSEXN_TYPEERR, "setting a property that has only a getter") -MSG_DEF(JSMSG_OVERWRITING_ACCESSOR, 1, JSEXN_TYPEERR, "can't overwrite accessor property {0}") -MSG_DEF(JSMSG_UNDEFINED_PROP, 1, JSEXN_REFERENCEERR, "reference to undefined property {0}") -MSG_DEF(JSMSG_INVALID_MAP_ITERABLE, 1, JSEXN_TYPEERR, "iterable for {0} should have array-like objects") -MSG_DEF(JSMSG_NESTING_GENERATOR, 0, JSEXN_TYPEERR, "already executing generator") -MSG_DEF(JSMSG_INCOMPATIBLE_METHOD, 3, JSEXN_TYPEERR, "{0} {1} called on incompatible {2}") -MSG_DEF(JSMSG_OBJECT_WATCH_DEPRECATED, 0, JSEXN_WARN, "Object.prototype.watch and unwatch are very slow, non-standard, and deprecated; use a getter/setter instead") -MSG_DEF(JSMSG_ARRAYBUFFER_SLICE_DEPRECATED, 0, JSEXN_WARN, "ArrayBuffer.slice is deprecated; use ArrayBuffer.prototype.slice instead") -MSG_DEF(JSMSG_BAD_SURROGATE_CHAR, 1, JSEXN_TYPEERR, "bad surrogate character {0}") -MSG_DEF(JSMSG_UTF8_CHAR_TOO_LARGE, 1, JSEXN_TYPEERR, "UTF-8 character {0} too large") -MSG_DEF(JSMSG_MALFORMED_UTF8_CHAR, 1, JSEXN_TYPEERR, "malformed UTF-8 character sequence at offset {0}") -MSG_DEF(JSMSG_BUILTIN_CTOR_NO_NEW, 1, JSEXN_TYPEERR, "calling a builtin {0} constructor without new is forbidden") -MSG_DEF(JSMSG_BAD_GENERATOR_YIELD, 1, JSEXN_TYPEERR, "yield from closing generator {0}") -MSG_DEF(JSMSG_EMPTY_ARRAY_REDUCE, 0, JSEXN_TYPEERR, "reduce of empty array with no initial value") -MSG_DEF(JSMSG_UNEXPECTED_TYPE, 2, JSEXN_TYPEERR, "{0} is {1}") -MSG_DEF(JSMSG_MISSING_FUN_ARG, 2, JSEXN_TYPEERR, "missing argument {0} when calling function {1}") -MSG_DEF(JSMSG_NOT_NONNULL_OBJECT, 1, JSEXN_TYPEERR, "{0} is not a non-null object") -MSG_DEF(JSMSG_SET_NON_OBJECT_RECEIVER, 1, JSEXN_TYPEERR, "can't assign to properties of {0}: not an object") -MSG_DEF(JSMSG_INVALID_DESCRIPTOR, 0, JSEXN_TYPEERR, "property descriptors must not specify a value or be writable when a getter or setter has been specified") -MSG_DEF(JSMSG_OBJECT_NOT_EXTENSIBLE, 1, JSEXN_TYPEERR, "{0}: Object is not extensible") -MSG_DEF(JSMSG_CANT_DEFINE_PROP_OBJECT_NOT_EXTENSIBLE, 2, JSEXN_TYPEERR, "can't define property {1}: {0} is not extensible") -MSG_DEF(JSMSG_CANT_REDEFINE_PROP, 1, JSEXN_TYPEERR, "can't redefine non-configurable property {0}") -MSG_DEF(JSMSG_CANT_REDEFINE_ARRAY_LENGTH, 0, JSEXN_TYPEERR, "can't redefine array length") -MSG_DEF(JSMSG_CANT_DEFINE_PAST_ARRAY_LENGTH, 0, JSEXN_TYPEERR, "can't define array index property past the end of an array with non-writable length") -MSG_DEF(JSMSG_BAD_GET_SET_FIELD, 1, JSEXN_TYPEERR, "property descriptor's {0} field is neither undefined nor a function") -MSG_DEF(JSMSG_THROW_TYPE_ERROR, 0, JSEXN_TYPEERR, "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them") -MSG_DEF(JSMSG_NOT_EXPECTED_TYPE, 3, JSEXN_TYPEERR, "{0}: expected {1}, got {2}") -MSG_DEF(JSMSG_NOT_ITERABLE, 1, JSEXN_TYPEERR, "{0} is not iterable") -MSG_DEF(JSMSG_NOT_ITERATOR, 1, JSEXN_TYPEERR, "{0} is not iterator") -MSG_DEF(JSMSG_ALREADY_HAS_PRAGMA, 2, JSEXN_WARN, "{0} is being assigned a {1}, but already has one") -MSG_DEF(JSMSG_GET_ITER_RETURNED_PRIMITIVE, 0, JSEXN_TYPEERR, "[Symbol.iterator]() returned a non-object value") -MSG_DEF(JSMSG_NEXT_RETURNED_PRIMITIVE, 0, JSEXN_TYPEERR, "iterator.next() returned a non-object value") -MSG_DEF(JSMSG_CANT_SET_PROTO, 0, JSEXN_TYPEERR, "can't set prototype of this object") -MSG_DEF(JSMSG_CANT_SET_PROTO_OF, 1, JSEXN_TYPEERR, "can't set prototype of {0}") -MSG_DEF(JSMSG_CANT_SET_PROTO_CYCLE, 0, JSEXN_TYPEERR, "can't set prototype: it would cause a prototype chain cycle") -MSG_DEF(JSMSG_INVALID_ARG_TYPE, 3, JSEXN_TYPEERR, "Invalid type: {0} can't be a{1} {2}") -MSG_DEF(JSMSG_TERMINATED, 1, JSEXN_ERR, "Script terminated by timeout at:\n{0}") -MSG_DEF(JSMSG_PROTO_NOT_OBJORNULL, 1, JSEXN_TYPEERR, "{0}.prototype is not an object or null") -MSG_DEF(JSMSG_CANT_CALL_CLASS_CONSTRUCTOR, 0, JSEXN_TYPEERR, "class constructors must be invoked with |new|") -MSG_DEF(JSMSG_UNINITIALIZED_THIS, 1, JSEXN_REFERENCEERR, "|this| used uninitialized in {0} class constructor") -MSG_DEF(JSMSG_UNINITIALIZED_THIS_ARROW, 0, JSEXN_REFERENCEERR, "|this| used uninitialized in arrow function in class constructor") -MSG_DEF(JSMSG_BAD_DERIVED_RETURN, 1, JSEXN_TYPEERR, "derived class constructor returned invalid value {0}") - -// JSON -MSG_DEF(JSMSG_JSON_BAD_PARSE, 3, JSEXN_SYNTAXERR, "JSON.parse: {0} at line {1} column {2} of the JSON data") -MSG_DEF(JSMSG_JSON_CYCLIC_VALUE, 0, JSEXN_TYPEERR, "cyclic object value") - -// Runtime errors -MSG_DEF(JSMSG_BAD_INSTANCEOF_RHS, 1, JSEXN_TYPEERR, "invalid 'instanceof' operand {0}") -MSG_DEF(JSMSG_BAD_LEFTSIDE_OF_ASS, 0, JSEXN_REFERENCEERR, "invalid assignment left-hand side") -MSG_DEF(JSMSG_BAD_PROTOTYPE, 1, JSEXN_TYPEERR, "'prototype' property of {0} is not an object") -MSG_DEF(JSMSG_IN_NOT_OBJECT, 1, JSEXN_TYPEERR, "invalid 'in' operand {0}") -MSG_DEF(JSMSG_TOO_MANY_CON_SPREADARGS, 0, JSEXN_RANGEERR, "too many constructor arguments") -MSG_DEF(JSMSG_TOO_MANY_FUN_SPREADARGS, 0, JSEXN_RANGEERR, "too many function arguments") -MSG_DEF(JSMSG_UNINITIALIZED_LEXICAL, 1, JSEXN_REFERENCEERR, "can't access lexical declaration `{0}' before initialization") -MSG_DEF(JSMSG_BAD_CONST_ASSIGN, 1, JSEXN_TYPEERR, "invalid assignment to const `{0}'") -MSG_DEF(JSMSG_CANT_DECLARE_GLOBAL_BINDING, 2, JSEXN_TYPEERR, "cannot declare global binding `{0}': {1}") - -// Date -MSG_DEF(JSMSG_INVALID_DATE, 0, JSEXN_RANGEERR, "invalid date") -MSG_DEF(JSMSG_BAD_TOISOSTRING_PROP, 0, JSEXN_TYPEERR, "toISOString property is not callable") - -// String -MSG_DEF(JSMSG_BAD_URI, 0, JSEXN_URIERR, "malformed URI sequence") -MSG_DEF(JSMSG_INVALID_NORMALIZE_FORM, 0, JSEXN_RANGEERR, "form must be one of 'NFC', 'NFD', 'NFKC', or 'NFKD'") -MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 0, JSEXN_RANGEERR, "repeat count must be non-negative") -MSG_DEF(JSMSG_NOT_A_CODEPOINT, 1, JSEXN_RANGEERR, "{0} is not a valid code point") -MSG_DEF(JSMSG_RESULTING_STRING_TOO_LARGE, 0, JSEXN_RANGEERR, "repeat count must be less than infinity and not overflow maximum string size") - -// Number -MSG_DEF(JSMSG_BAD_RADIX, 0, JSEXN_RANGEERR, "radix must be an integer at least 2 and no greater than 36") -MSG_DEF(JSMSG_PRECISION_RANGE, 1, JSEXN_RANGEERR, "precision {0} out of range") - -// Function -MSG_DEF(JSMSG_BAD_APPLY_ARGS, 1, JSEXN_TYPEERR, "second argument to Function.prototype.{0} must be an array") -MSG_DEF(JSMSG_BAD_FORMAL, 0, JSEXN_SYNTAXERR, "malformed formal parameter") -MSG_DEF(JSMSG_CALLER_IS_STRICT, 0, JSEXN_TYPEERR, "access to strict mode caller function is censored") -MSG_DEF(JSMSG_DEPRECATED_USAGE, 1, JSEXN_REFERENCEERR, "deprecated {0} usage") -MSG_DEF(JSMSG_NOT_SCRIPTED_FUNCTION, 1, JSEXN_TYPEERR, "{0} is not a scripted function") -MSG_DEF(JSMSG_NO_REST_NAME, 0, JSEXN_SYNTAXERR, "no parameter name after ...") -MSG_DEF(JSMSG_PARAMETER_AFTER_REST, 0, JSEXN_SYNTAXERR, "parameter after rest parameter") -MSG_DEF(JSMSG_TOO_MANY_ARGUMENTS, 0, JSEXN_RANGEERR, "too many arguments provided for a function call") - -// CSP -MSG_DEF(JSMSG_CSP_BLOCKED_EVAL, 0, JSEXN_ERR, "call to eval() blocked by CSP") -MSG_DEF(JSMSG_CSP_BLOCKED_FUNCTION, 0, JSEXN_ERR, "call to Function() blocked by CSP") - -// Wrappers -MSG_DEF(JSMSG_ACCESSOR_DEF_DENIED, 1, JSEXN_ERR, "Permission denied to define accessor property {0}") -MSG_DEF(JSMSG_DEAD_OBJECT, 0, JSEXN_TYPEERR, "can't access dead object") -MSG_DEF(JSMSG_UNWRAP_DENIED, 0, JSEXN_ERR, "permission denied to unwrap object") - -// JSAPI-only (Not thrown as JS exceptions) -MSG_DEF(JSMSG_BAD_CLONE_FUNOBJ_SCOPE, 0, JSEXN_TYPEERR, "bad cloned function scope chain") -MSG_DEF(JSMSG_CANT_CLONE_OBJECT, 0, JSEXN_TYPEERR, "can't clone object") -MSG_DEF(JSMSG_CANT_OPEN, 2, JSEXN_ERR, "can't open {0}: {1}") -MSG_DEF(JSMSG_USER_DEFINED_ERROR, 0, JSEXN_ERR, "JS_ReportError was called") - -// Internal errors -MSG_DEF(JSMSG_ALLOC_OVERFLOW, 0, JSEXN_INTERNALERR, "allocation size overflow") -MSG_DEF(JSMSG_BAD_BYTECODE, 1, JSEXN_INTERNALERR, "unimplemented JavaScript bytecode {0}") -MSG_DEF(JSMSG_BUFFER_TOO_SMALL, 0, JSEXN_INTERNALERR, "buffer too small") -MSG_DEF(JSMSG_BUILD_ID_NOT_AVAILABLE, 0, JSEXN_INTERNALERR, "build ID is not available") -MSG_DEF(JSMSG_BYTECODE_TOO_BIG, 2, JSEXN_INTERNALERR, "bytecode {0} too large (limit {1})") -MSG_DEF(JSMSG_ERR_DURING_THROW, 0, JSEXN_INTERNALERR, "an internal error occurred while throwing an exception") -MSG_DEF(JSMSG_NEED_DIET, 1, JSEXN_INTERNALERR, "{0} too large") -MSG_DEF(JSMSG_OUT_OF_MEMORY, 0, JSEXN_INTERNALERR, "out of memory") -MSG_DEF(JSMSG_OVER_RECURSED, 0, JSEXN_INTERNALERR, "too much recursion") -MSG_DEF(JSMSG_TOO_BIG_TO_ENCODE, 0, JSEXN_INTERNALERR, "data are to big to encode") -MSG_DEF(JSMSG_TOO_DEEP, 1, JSEXN_INTERNALERR, "{0} nested too deeply") -MSG_DEF(JSMSG_UNCAUGHT_EXCEPTION, 1, JSEXN_INTERNALERR, "uncaught exception: {0}") -MSG_DEF(JSMSG_UNKNOWN_FORMAT, 1, JSEXN_INTERNALERR, "unknown bytecode format {0}") - -// Frontend -MSG_DEF(JSMSG_ACCESSOR_WRONG_ARGS, 3, JSEXN_SYNTAXERR, "{0} functions must have {1} argument{2}") -MSG_DEF(JSMSG_ARRAY_COMP_LEFTSIDE, 0, JSEXN_SYNTAXERR, "invalid array comprehension left-hand side") -MSG_DEF(JSMSG_ARRAY_INIT_TOO_BIG, 0, JSEXN_INTERNALERR, "array initializer too large") -MSG_DEF(JSMSG_AS_AFTER_IMPORT_STAR, 0, JSEXN_SYNTAXERR, "missing keyword 'as' after import *") -MSG_DEF(JSMSG_AS_AFTER_RESERVED_WORD, 1, JSEXN_SYNTAXERR, "missing keyword 'as' after reserved word '{0}'") -MSG_DEF(JSMSG_ASYNC_GENERATOR, 0, JSEXN_SYNTAXERR, "generator function or method can't be async") -MSG_DEF(JSMSG_AWAIT_IN_DEFAULT, 0, JSEXN_SYNTAXERR, "await can't be used in default expression") -MSG_DEF(JSMSG_BAD_ANON_GENERATOR_RETURN, 0, JSEXN_TYPEERR, "anonymous generator function returns a value") -MSG_DEF(JSMSG_BAD_ARROW_ARGS, 0, JSEXN_SYNTAXERR, "invalid arrow-function arguments (parentheses around the arrow-function may help)") -MSG_DEF(JSMSG_BAD_BINDING, 1, JSEXN_SYNTAXERR, "redefining {0} is deprecated") -MSG_DEF(JSMSG_BAD_CONST_DECL, 0, JSEXN_SYNTAXERR, "missing = in const declaration") -MSG_DEF(JSMSG_BAD_CONTINUE, 0, JSEXN_SYNTAXERR, "continue must be inside loop") -MSG_DEF(JSMSG_BAD_DESTRUCT_ASS, 0, JSEXN_REFERENCEERR, "invalid destructuring assignment operator") -MSG_DEF(JSMSG_BAD_DESTRUCT_TARGET, 0, JSEXN_SYNTAXERR, "invalid destructuring target") -MSG_DEF(JSMSG_BAD_DESTRUCT_PARENS, 0, JSEXN_SYNTAXERR, "destructuring patterns in assignments can't be parenthesized") -MSG_DEF(JSMSG_BAD_DESTRUCT_DECL, 0, JSEXN_SYNTAXERR, "missing = in destructuring declaration") -MSG_DEF(JSMSG_BAD_DUP_ARGS, 0, JSEXN_SYNTAXERR, "duplicate argument names not allowed in this context") -MSG_DEF(JSMSG_BAD_FOR_EACH_LOOP, 0, JSEXN_SYNTAXERR, "invalid for each loop") -MSG_DEF(JSMSG_BAD_FOR_LEFTSIDE, 0, JSEXN_SYNTAXERR, "invalid for-in/of left-hand side") -MSG_DEF(JSMSG_LEXICAL_DECL_DEFINES_LET,0, JSEXN_SYNTAXERR, "a lexical declaration can't define a 'let' binding") -MSG_DEF(JSMSG_LET_STARTING_FOROF_LHS, 0, JSEXN_SYNTAXERR, "an expression X in 'for (X of Y)' must not start with 'let'") -MSG_DEF(JSMSG_BAD_GENERATOR_RETURN, 1, JSEXN_TYPEERR, "generator function {0} returns a value") -MSG_DEF(JSMSG_BAD_GENEXP_BODY, 1, JSEXN_SYNTAXERR, "illegal use of {0} in generator expression") -MSG_DEF(JSMSG_BAD_INCOP_OPERAND, 0, JSEXN_REFERENCEERR, "invalid increment/decrement operand") -MSG_DEF(JSMSG_BAD_METHOD_DEF, 0, JSEXN_SYNTAXERR, "bad method definition") -MSG_DEF(JSMSG_BAD_OCTAL, 1, JSEXN_SYNTAXERR, "{0} is not a legal ECMA-262 octal constant") -MSG_DEF(JSMSG_BAD_OPERAND, 1, JSEXN_SYNTAXERR, "invalid {0} operand") -MSG_DEF(JSMSG_BAD_POW_LEFTSIDE, 0, JSEXN_SYNTAXERR, "unparenthesized unary expression can't appear on the left-hand side of '**'") -MSG_DEF(JSMSG_BAD_PROP_ID, 0, JSEXN_SYNTAXERR, "invalid property id") -MSG_DEF(JSMSG_BAD_RETURN_OR_YIELD, 1, JSEXN_SYNTAXERR, "{0} not in function") -MSG_DEF(JSMSG_BAD_STRICT_ASSIGN, 1, JSEXN_SYNTAXERR, "'{0}' can't be defined or assigned to in strict mode code") -MSG_DEF(JSMSG_BAD_SWITCH, 0, JSEXN_SYNTAXERR, "invalid switch statement") -MSG_DEF(JSMSG_BAD_SUPER, 0, JSEXN_SYNTAXERR, "invalid use of keyword 'super'") -MSG_DEF(JSMSG_BAD_SUPERPROP, 1, JSEXN_SYNTAXERR, "use of super {0} accesses only valid within methods or eval code within methods") -MSG_DEF(JSMSG_BAD_SUPERCALL, 0, JSEXN_SYNTAXERR, "super() is only valid in derived class constructors") -MSG_DEF(JSMSG_BRACKET_AFTER_ARRAY_COMPREHENSION, 0, JSEXN_SYNTAXERR, "missing ] after array comprehension") -MSG_DEF(JSMSG_BRACKET_AFTER_LIST, 0, JSEXN_SYNTAXERR, "missing ] after element list") -MSG_DEF(JSMSG_BRACKET_IN_INDEX, 0, JSEXN_SYNTAXERR, "missing ] in index expression") -MSG_DEF(JSMSG_CATCH_AFTER_GENERAL, 0, JSEXN_SYNTAXERR, "catch after unconditional catch") -MSG_DEF(JSMSG_CATCH_IDENTIFIER, 0, JSEXN_SYNTAXERR, "missing identifier in catch") -MSG_DEF(JSMSG_CATCH_OR_FINALLY, 0, JSEXN_SYNTAXERR, "missing catch or finally after try") -MSG_DEF(JSMSG_CATCH_WITHOUT_TRY, 0, JSEXN_SYNTAXERR, "catch without try") -MSG_DEF(JSMSG_COLON_AFTER_CASE, 0, JSEXN_SYNTAXERR, "missing : after case label") -MSG_DEF(JSMSG_COLON_AFTER_ID, 0, JSEXN_SYNTAXERR, "missing : after property id") -MSG_DEF(JSMSG_COLON_IN_COND, 0, JSEXN_SYNTAXERR, "missing : in conditional expression") -MSG_DEF(JSMSG_COMP_PROP_UNTERM_EXPR, 0, JSEXN_SYNTAXERR, "missing ] in computed property name") -MSG_DEF(JSMSG_CONTRARY_NONDIRECTIVE, 1, JSEXN_SYNTAXERR, "'{0}' statement won't be enforced as a directive because it isn't in directive prologue position") -MSG_DEF(JSMSG_CURLY_AFTER_BODY, 0, JSEXN_SYNTAXERR, "missing } after function body") -MSG_DEF(JSMSG_CURLY_AFTER_CATCH, 0, JSEXN_SYNTAXERR, "missing } after catch block") -MSG_DEF(JSMSG_CURLY_AFTER_FINALLY, 0, JSEXN_SYNTAXERR, "missing } after finally block") -MSG_DEF(JSMSG_CURLY_AFTER_LIST, 0, JSEXN_SYNTAXERR, "missing } after property list") -MSG_DEF(JSMSG_CURLY_AFTER_TRY, 0, JSEXN_SYNTAXERR, "missing } after try block") -MSG_DEF(JSMSG_CURLY_BEFORE_BODY, 0, JSEXN_SYNTAXERR, "missing { before function body") -MSG_DEF(JSMSG_CURLY_BEFORE_CATCH, 0, JSEXN_SYNTAXERR, "missing { before catch block") -MSG_DEF(JSMSG_CURLY_BEFORE_CLASS, 0, JSEXN_SYNTAXERR, "missing { before class body") -MSG_DEF(JSMSG_CURLY_BEFORE_FINALLY, 0, JSEXN_SYNTAXERR, "missing { before finally block") -MSG_DEF(JSMSG_CURLY_BEFORE_SWITCH, 0, JSEXN_SYNTAXERR, "missing { before switch body") -MSG_DEF(JSMSG_CURLY_BEFORE_TRY, 0, JSEXN_SYNTAXERR, "missing { before try block") -MSG_DEF(JSMSG_CURLY_IN_COMPOUND, 0, JSEXN_SYNTAXERR, "missing } in compound statement") -MSG_DEF(JSMSG_DECLARATION_AFTER_EXPORT,0, JSEXN_SYNTAXERR, "missing declaration after 'export' keyword") -MSG_DEF(JSMSG_DECLARATION_AFTER_IMPORT,0, JSEXN_SYNTAXERR, "missing declaration after 'import' keyword") -MSG_DEF(JSMSG_DEPRECATED_DELETE_OPERAND, 0, JSEXN_SYNTAXERR, "applying the 'delete' operator to an unqualified name is deprecated") -MSG_DEF(JSMSG_DEPRECATED_EXPR_CLOSURE, 0, JSEXN_WARN, "expression closures are deprecated") -MSG_DEF(JSMSG_DEPRECATED_FOR_EACH, 0, JSEXN_WARN, "JavaScript 1.6's for-each-in loops are deprecated; consider using ES6 for-of instead") -MSG_DEF(JSMSG_DEPRECATED_OCTAL, 0, JSEXN_SYNTAXERR, "\"0\"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the \"0o\" prefix instead") -MSG_DEF(JSMSG_DEPRECATED_PRAGMA, 1, JSEXN_WARN, "Using //@ to indicate {0} pragmas is deprecated. Use //# instead") -MSG_DEF(JSMSG_DEPRECATED_BLOCK_SCOPE_FUN_REDECL, 1, JSEXN_WARN, "redeclaration of block-scoped function `{0}' is deprecated") -MSG_DEF(JSMSG_DUPLICATE_EXPORT_NAME, 1, JSEXN_SYNTAXERR, "duplicate export name '{0}'") -MSG_DEF(JSMSG_DUPLICATE_FORMAL, 1, JSEXN_SYNTAXERR, "duplicate formal argument {0}") -MSG_DEF(JSMSG_DUPLICATE_LABEL, 0, JSEXN_SYNTAXERR, "duplicate label") -MSG_DEF(JSMSG_DUPLICATE_PROPERTY, 1, JSEXN_SYNTAXERR, "property name {0} appears more than once in object literal") -MSG_DEF(JSMSG_DUPLICATE_PROTO_PROPERTY, 0, JSEXN_SYNTAXERR, "property name __proto__ appears more than once in object literal") -MSG_DEF(JSMSG_EMPTY_CONSEQUENT, 0, JSEXN_SYNTAXERR, "mistyped ; after conditional?") -MSG_DEF(JSMSG_EQUAL_AS_ASSIGN, 0, JSEXN_SYNTAXERR, "test for equality (==) mistyped as assignment (=)?") -MSG_DEF(JSMSG_EXPORT_DECL_AT_TOP_LEVEL,0, JSEXN_SYNTAXERR, "export declarations may only appear at top level of a module") -MSG_DEF(JSMSG_FINALLY_WITHOUT_TRY, 0, JSEXN_SYNTAXERR, "finally without try") -MSG_DEF(JSMSG_FORBIDDEN_AS_STATEMENT, 1, JSEXN_SYNTAXERR, "{0} can't appear in single-statement context") -MSG_DEF(JSMSG_FROM_AFTER_IMPORT_CLAUSE, 0, JSEXN_SYNTAXERR, "missing keyword 'from' after import clause") -MSG_DEF(JSMSG_FROM_AFTER_EXPORT_STAR, 0, JSEXN_SYNTAXERR, "missing keyword 'from' after export *") -MSG_DEF(JSMSG_GARBAGE_AFTER_INPUT, 2, JSEXN_SYNTAXERR, "unexpected garbage after {0}, starting with {1}") -MSG_DEF(JSMSG_IDSTART_AFTER_NUMBER, 0, JSEXN_SYNTAXERR, "identifier starts immediately after numeric literal") -MSG_DEF(JSMSG_ILLEGAL_CHARACTER, 0, JSEXN_SYNTAXERR, "illegal character") -MSG_DEF(JSMSG_IMPORT_DECL_AT_TOP_LEVEL, 0, JSEXN_SYNTAXERR, "import declarations may only appear at top level of a module") -MSG_DEF(JSMSG_INVALID_FOR_IN_DECL_WITH_INIT,0,JSEXN_SYNTAXERR,"for-in loop head declarations may not have initializers") -MSG_DEF(JSMSG_LABEL_NOT_FOUND, 0, JSEXN_SYNTAXERR, "label not found") -MSG_DEF(JSMSG_LET_COMP_BINDING, 0, JSEXN_SYNTAXERR, "'let' is not a valid name for a comprehension variable") -MSG_DEF(JSMSG_LEXICAL_DECL_NOT_IN_BLOCK, 1, JSEXN_SYNTAXERR, "{0} declaration not directly within block") -MSG_DEF(JSMSG_LEXICAL_DECL_LABEL, 1, JSEXN_SYNTAXERR, "{0} declarations cannot be labelled") -MSG_DEF(JSMSG_GENERATOR_LABEL, 0, JSEXN_SYNTAXERR, "generator functions cannot be labelled") -MSG_DEF(JSMSG_FUNCTION_LABEL, 0, JSEXN_SYNTAXERR, "functions cannot be labelled") -MSG_DEF(JSMSG_SLOPPY_FUNCTION_LABEL, 0, JSEXN_SYNTAXERR, "functions can only be labelled inside blocks") -MSG_DEF(JSMSG_LINE_BREAK_AFTER_THROW, 0, JSEXN_SYNTAXERR, "no line break is allowed between 'throw' and its expression") -MSG_DEF(JSMSG_LINE_BREAK_BEFORE_ARROW, 0, JSEXN_SYNTAXERR, "no line break is allowed before '=>'") -MSG_DEF(JSMSG_MALFORMED_ESCAPE, 1, JSEXN_SYNTAXERR, "malformed {0} character escape sequence") -MSG_DEF(JSMSG_MISSING_BINARY_DIGITS, 0, JSEXN_SYNTAXERR, "missing binary digits after '0b'") -MSG_DEF(JSMSG_MISSING_EXPONENT, 0, JSEXN_SYNTAXERR, "missing exponent") -MSG_DEF(JSMSG_MISSING_EXPR_AFTER_THROW,0, JSEXN_SYNTAXERR, "throw statement is missing an expression") -MSG_DEF(JSMSG_MISSING_FORMAL, 0, JSEXN_SYNTAXERR, "missing formal parameter") -MSG_DEF(JSMSG_MISSING_HEXDIGITS, 0, JSEXN_SYNTAXERR, "missing hexadecimal digits after '0x'") -MSG_DEF(JSMSG_MISSING_OCTAL_DIGITS, 0, JSEXN_SYNTAXERR, "missing octal digits after '0o'") -MSG_DEF(JSMSG_MODULE_SPEC_AFTER_FROM, 0, JSEXN_SYNTAXERR, "missing module specifier after 'from' keyword") -MSG_DEF(JSMSG_NAME_AFTER_DOT, 0, JSEXN_SYNTAXERR, "missing name after . operator") -MSG_DEF(JSMSG_NAMED_IMPORTS_OR_NAMESPACE_IMPORT, 0, JSEXN_SYNTAXERR, "expected named imports or namespace import after comma") -MSG_DEF(JSMSG_NO_BINDING_NAME, 0, JSEXN_SYNTAXERR, "missing binding name") -MSG_DEF(JSMSG_NO_EXPORT_NAME, 0, JSEXN_SYNTAXERR, "missing export name") -MSG_DEF(JSMSG_NO_IMPORT_NAME, 0, JSEXN_SYNTAXERR, "missing import name") -MSG_DEF(JSMSG_NO_VARIABLE_NAME, 0, JSEXN_SYNTAXERR, "missing variable name") -MSG_DEF(JSMSG_OF_AFTER_FOR_NAME, 0, JSEXN_SYNTAXERR, "missing 'of' after for") -MSG_DEF(JSMSG_PAREN_AFTER_ARGS, 0, JSEXN_SYNTAXERR, "missing ) after argument list") -MSG_DEF(JSMSG_PAREN_AFTER_CATCH, 0, JSEXN_SYNTAXERR, "missing ) after catch") -MSG_DEF(JSMSG_PAREN_AFTER_COND, 0, JSEXN_SYNTAXERR, "missing ) after condition") -MSG_DEF(JSMSG_PAREN_AFTER_FOR, 0, JSEXN_SYNTAXERR, "missing ( after for") -MSG_DEF(JSMSG_PAREN_AFTER_FORMAL, 0, JSEXN_SYNTAXERR, "missing ) after formal parameters") -MSG_DEF(JSMSG_PAREN_AFTER_FOR_CTRL, 0, JSEXN_SYNTAXERR, "missing ) after for-loop control") -MSG_DEF(JSMSG_PAREN_AFTER_FOR_OF_ITERABLE, 0, JSEXN_SYNTAXERR, "missing ) after for-of iterable") -MSG_DEF(JSMSG_PAREN_AFTER_SWITCH, 0, JSEXN_SYNTAXERR, "missing ) after switch expression") -MSG_DEF(JSMSG_PAREN_AFTER_WITH, 0, JSEXN_SYNTAXERR, "missing ) after with-statement object") -MSG_DEF(JSMSG_PAREN_BEFORE_CATCH, 0, JSEXN_SYNTAXERR, "missing ( before catch") -MSG_DEF(JSMSG_PAREN_BEFORE_COND, 0, JSEXN_SYNTAXERR, "missing ( before condition") -MSG_DEF(JSMSG_PAREN_BEFORE_FORMAL, 0, JSEXN_SYNTAXERR, "missing ( before formal parameters") -MSG_DEF(JSMSG_PAREN_BEFORE_SWITCH, 0, JSEXN_SYNTAXERR, "missing ( before switch expression") -MSG_DEF(JSMSG_PAREN_BEFORE_WITH, 0, JSEXN_SYNTAXERR, "missing ( before with-statement object") -MSG_DEF(JSMSG_PAREN_IN_PAREN, 0, JSEXN_SYNTAXERR, "missing ) in parenthetical") -MSG_DEF(JSMSG_RC_AFTER_EXPORT_SPEC_LIST, 0, JSEXN_SYNTAXERR, "missing '}' after export specifier list") -MSG_DEF(JSMSG_RC_AFTER_IMPORT_SPEC_LIST, 0, JSEXN_SYNTAXERR, "missing '}' after module specifier list") -MSG_DEF(JSMSG_REDECLARED_CATCH_IDENTIFIER, 1, JSEXN_SYNTAXERR, "redeclaration of identifier '{0}' in catch") -MSG_DEF(JSMSG_RESERVED_ID, 1, JSEXN_SYNTAXERR, "{0} is a reserved identifier") -MSG_DEF(JSMSG_REST_WITH_COMMA, 0, JSEXN_SYNTAXERR, "rest element may not have a trailing comma") -MSG_DEF(JSMSG_REST_WITH_DEFAULT, 0, JSEXN_SYNTAXERR, "rest parameter may not have a default") -MSG_DEF(JSMSG_SELFHOSTED_TOP_LEVEL_LEXICAL, 1, JSEXN_SYNTAXERR, "self-hosted code cannot contain top-level {0} declarations") -MSG_DEF(JSMSG_SELFHOSTED_METHOD_CALL, 0, JSEXN_SYNTAXERR, "self-hosted code may not contain direct method calls. Use callFunction() or callContentFunction()") -MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") -MSG_DEF(JSMSG_SEMI_AFTER_FOR_COND, 0, JSEXN_SYNTAXERR, "missing ; after for-loop condition") -MSG_DEF(JSMSG_SEMI_AFTER_FOR_INIT, 0, JSEXN_SYNTAXERR, "missing ; after for-loop initializer") -MSG_DEF(JSMSG_SEMI_BEFORE_STMNT, 0, JSEXN_SYNTAXERR, "missing ; before statement") -MSG_DEF(JSMSG_SOURCE_TOO_LONG, 0, JSEXN_RANGEERR, "source is too long") -MSG_DEF(JSMSG_STMT_AFTER_RETURN, 0, JSEXN_WARN, "unreachable code after return statement") -MSG_DEF(JSMSG_STRICT_CODE_WITH, 0, JSEXN_SYNTAXERR, "strict mode code may not contain 'with' statements") -MSG_DEF(JSMSG_STRICT_NON_SIMPLE_PARAMS, 1, JSEXN_SYNTAXERR, "\"use strict\" not allowed in function with {0} parameter") -MSG_DEF(JSMSG_TEMPLSTR_UNTERM_EXPR, 0, JSEXN_SYNTAXERR, "missing } in template string") -MSG_DEF(JSMSG_SIMD_NOT_A_VECTOR, 2, JSEXN_TYPEERR, "expecting a SIMD {0} object as argument {1}") -MSG_DEF(JSMSG_TOO_MANY_CASES, 0, JSEXN_INTERNALERR, "too many switch cases") -MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 0, JSEXN_SYNTAXERR, "too many catch variables") -MSG_DEF(JSMSG_TOO_MANY_CON_ARGS, 0, JSEXN_SYNTAXERR, "too many constructor arguments") -MSG_DEF(JSMSG_TOO_MANY_DEFAULTS, 0, JSEXN_SYNTAXERR, "more than one switch default") -MSG_DEF(JSMSG_TOO_MANY_FUN_ARGS, 0, JSEXN_SYNTAXERR, "too many function arguments") -MSG_DEF(JSMSG_TOO_MANY_LOCALS, 0, JSEXN_SYNTAXERR, "too many local variables") -MSG_DEF(JSMSG_TOO_MANY_YIELDS, 0, JSEXN_SYNTAXERR, "too many yield expressions") -MSG_DEF(JSMSG_TOUGH_BREAK, 0, JSEXN_SYNTAXERR, "unlabeled break must be inside loop or switch") -MSG_DEF(JSMSG_UNEXPECTED_TOKEN, 2, JSEXN_SYNTAXERR, "expected {0}, got {1}") -MSG_DEF(JSMSG_UNNAMED_CLASS_STMT, 0, JSEXN_SYNTAXERR, "class statement requires a name") -MSG_DEF(JSMSG_UNNAMED_FUNCTION_STMT, 0, JSEXN_SYNTAXERR, "function statement requires a name") -MSG_DEF(JSMSG_UNTERMINATED_COMMENT, 0, JSEXN_SYNTAXERR, "unterminated comment") -MSG_DEF(JSMSG_UNTERMINATED_REGEXP, 0, JSEXN_SYNTAXERR, "unterminated regular expression literal") -MSG_DEF(JSMSG_UNTERMINATED_STRING, 0, JSEXN_SYNTAXERR, "unterminated string literal") -MSG_DEF(JSMSG_USELESS_EXPR, 0, JSEXN_TYPEERR, "useless expression") -MSG_DEF(JSMSG_USE_ASM_DIRECTIVE_FAIL, 0, JSEXN_SYNTAXERR, "\"use asm\" is only meaningful in the Directive Prologue of a function body") -MSG_DEF(JSMSG_VAR_HIDES_ARG, 1, JSEXN_TYPEERR, "variable {0} redeclares argument") -MSG_DEF(JSMSG_WHILE_AFTER_DO, 0, JSEXN_SYNTAXERR, "missing while after do-loop body") -MSG_DEF(JSMSG_YIELD_IN_ARROW, 0, JSEXN_SYNTAXERR, "arrow function may not contain yield") -MSG_DEF(JSMSG_YIELD_IN_DEFAULT, 0, JSEXN_SYNTAXERR, "yield in default expression") -MSG_DEF(JSMSG_YIELD_IN_METHOD, 0, JSEXN_SYNTAXERR, "non-generator method definitions may not contain yield") -MSG_DEF(JSMSG_BAD_COLUMN_NUMBER, 0, JSEXN_RANGEERR, "column number out of range") -MSG_DEF(JSMSG_COMPUTED_NAME_IN_PATTERN,0, JSEXN_SYNTAXERR, "computed property names aren't supported in this destructuring declaration") -MSG_DEF(JSMSG_DEFAULT_IN_PATTERN, 0, JSEXN_SYNTAXERR, "destructuring defaults aren't supported in this destructuring declaration") -MSG_DEF(JSMSG_BAD_NEWTARGET, 0, JSEXN_SYNTAXERR, "new.target only allowed within functions") -MSG_DEF(JSMSG_ESCAPED_KEYWORD, 0, JSEXN_SYNTAXERR, "keywords must be written literally, without embedded escapes") - -// asm.js -MSG_DEF(JSMSG_USE_ASM_TYPE_FAIL, 1, JSEXN_TYPEERR, "asm.js type error: {0}") -MSG_DEF(JSMSG_USE_ASM_LINK_FAIL, 1, JSEXN_TYPEERR, "asm.js link error: {0}") -MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 1, JSEXN_WARN, "Successfully compiled asm.js code ({0})") - -// wasm -MSG_DEF(JSMSG_WASM_COMPILE_ERROR, 1, JSEXN_WASMCOMPILEERROR, "{0}") -MSG_DEF(JSMSG_WASM_IND_CALL_TO_NULL, 0, JSEXN_WASMRUNTIMEERROR, "indirect call to null") -MSG_DEF(JSMSG_WASM_IND_CALL_BAD_SIG, 0, JSEXN_WASMRUNTIMEERROR, "indirect call signature mismatch") -MSG_DEF(JSMSG_WASM_UNREACHABLE, 0, JSEXN_WASMRUNTIMEERROR, "unreachable executed") -MSG_DEF(JSMSG_WASM_INTEGER_OVERFLOW, 0, JSEXN_WASMRUNTIMEERROR, "integer overflow") -MSG_DEF(JSMSG_WASM_INVALID_CONVERSION, 0, JSEXN_WASMRUNTIMEERROR, "invalid conversion to integer") -MSG_DEF(JSMSG_WASM_INT_DIVIDE_BY_ZERO, 0, JSEXN_WASMRUNTIMEERROR, "integer divide by zero") -MSG_DEF(JSMSG_WASM_OUT_OF_BOUNDS, 0, JSEXN_WASMRUNTIMEERROR, "index out of bounds") -MSG_DEF(JSMSG_WASM_UNALIGNED_ACCESS, 0, JSEXN_WASMRUNTIMEERROR, "unaligned memory access") -MSG_DEF(JSMSG_WASM_BAD_UINT32, 2, JSEXN_RANGEERR, "bad {0} {1}") -MSG_DEF(JSMSG_WASM_BAD_GROW, 1, JSEXN_RANGEERR, "failed to grow {0}") -MSG_DEF(JSMSG_WASM_BAD_FIT, 2, JSEXN_RANGEERR, "{0} segment does not fit in {1}") -MSG_DEF(JSMSG_WASM_BAD_BUF_ARG, 0, JSEXN_TYPEERR, "first argument must be an ArrayBuffer or typed array object") -MSG_DEF(JSMSG_WASM_BAD_MOD_ARG, 0, JSEXN_TYPEERR, "first argument must be a WebAssembly.Module") -MSG_DEF(JSMSG_WASM_BAD_BUF_MOD_ARG, 0, JSEXN_TYPEERR, "first argument must be a WebAssembly.Module, ArrayBuffer or typed array object") -MSG_DEF(JSMSG_WASM_BAD_DESC_ARG, 1, JSEXN_TYPEERR, "first argument must be a {0} descriptor") -MSG_DEF(JSMSG_WASM_BAD_IMP_SIZE, 1, JSEXN_TYPEERR, "imported {0} with incompatible size") -MSG_DEF(JSMSG_WASM_BAD_IMP_MAX, 1, JSEXN_TYPEERR, "imported {0} with incompatible maximum size") -MSG_DEF(JSMSG_WASM_BAD_ELEMENT, 0, JSEXN_TYPEERR, "\"element\" property of table descriptor must be \"anyfunc\"") -MSG_DEF(JSMSG_WASM_BAD_IMPORT_ARG, 0, JSEXN_TYPEERR, "second argument must be an object") -MSG_DEF(JSMSG_WASM_BAD_IMPORT_FIELD, 2, JSEXN_TYPEERR, "import object field '{0}' is not {1}") -MSG_DEF(JSMSG_WASM_BAD_IMPORT_SIG, 0, JSEXN_TYPEERR, "imported function signature mismatch") -MSG_DEF(JSMSG_WASM_BAD_TABLE_VALUE, 0, JSEXN_TYPEERR, "can only assign WebAssembly exported functions to Table") -MSG_DEF(JSMSG_WASM_BAD_I64, 0, JSEXN_TYPEERR, "cannot pass i64 to or from JS") -MSG_DEF(JSMSG_WASM_NO_TRANSFER, 0, JSEXN_TYPEERR, "cannot transfer WebAssembly/asm.js ArrayBuffer") -MSG_DEF(JSMSG_WASM_TEXT_FAIL, 1, JSEXN_SYNTAXERR, "wasm text error: {0}") - -// Proxy -MSG_DEF(JSMSG_BAD_TRAP_RETURN_VALUE, 2, JSEXN_TYPEERR,"trap {1} for {0} returned a primitive value") -MSG_DEF(JSMSG_BAD_GETPROTOTYPEOF_TRAP_RETURN,0,JSEXN_TYPEERR,"proxy getPrototypeOf handler returned a non-object, non-null value") -MSG_DEF(JSMSG_INCONSISTENT_GETPROTOTYPEOF_TRAP,0,JSEXN_TYPEERR,"proxy getPrototypeOf handler didn't return the target object's prototype") -MSG_DEF(JSMSG_PROXY_SETPROTOTYPEOF_RETURNED_FALSE, 0, JSEXN_TYPEERR, "proxy setPrototypeOf handler returned false") -MSG_DEF(JSMSG_PROXY_ISEXTENSIBLE_RETURNED_FALSE,0,JSEXN_TYPEERR,"proxy isExtensible handler must return the same extensibility as target") -MSG_DEF(JSMSG_INCONSISTENT_SETPROTOTYPEOF_TRAP,0,JSEXN_TYPEERR,"proxy setPrototypeOf handler returned true, even though the target's prototype is immutable because the target is non-extensible") -MSG_DEF(JSMSG_CANT_CHANGE_EXTENSIBILITY, 0, JSEXN_TYPEERR, "can't change object's extensibility") -MSG_DEF(JSMSG_CANT_DEFINE_INVALID, 0, JSEXN_TYPEERR, "proxy can't define an incompatible property descriptor") -MSG_DEF(JSMSG_CANT_DEFINE_NEW, 0, JSEXN_TYPEERR, "proxy can't define a new property on a non-extensible object") -MSG_DEF(JSMSG_CANT_DEFINE_NE_AS_NC, 0, JSEXN_TYPEERR, "proxy can't define a non-existent property as non-configurable") -MSG_DEF(JSMSG_PROXY_DEFINE_RETURNED_FALSE, 1, JSEXN_TYPEERR, "proxy defineProperty handler returned false for property '{0}'") -MSG_DEF(JSMSG_PROXY_DELETE_RETURNED_FALSE, 1, JSEXN_TYPEERR, "can't delete property '{0}': proxy deleteProperty handler returned false") -MSG_DEF(JSMSG_PROXY_PREVENTEXTENSIONS_RETURNED_FALSE, 0, JSEXN_TYPEERR, "proxy preventExtensions handler returned false") -MSG_DEF(JSMSG_PROXY_SET_RETURNED_FALSE, 1, JSEXN_TYPEERR, "proxy set handler returned false for property '{0}'") -MSG_DEF(JSMSG_CANT_REPORT_AS_NON_EXTENSIBLE, 0, JSEXN_TYPEERR, "proxy can't report an extensible object as non-extensible") -MSG_DEF(JSMSG_CANT_REPORT_C_AS_NC, 0, JSEXN_TYPEERR, "proxy can't report existing configurable property as non-configurable") -MSG_DEF(JSMSG_CANT_REPORT_E_AS_NE, 0, JSEXN_TYPEERR, "proxy can't report an existing own property as non-existent on a non-extensible object") -MSG_DEF(JSMSG_CANT_REPORT_INVALID, 0, JSEXN_TYPEERR, "proxy can't report an incompatible property descriptor") -MSG_DEF(JSMSG_CANT_REPORT_NC_AS_NE, 0, JSEXN_TYPEERR, "proxy can't report a non-configurable own property as non-existent") -MSG_DEF(JSMSG_CANT_REPORT_NEW, 0, JSEXN_TYPEERR, "proxy can't report a new property on a non-extensible object") -MSG_DEF(JSMSG_CANT_REPORT_NE_AS_NC, 0, JSEXN_TYPEERR, "proxy can't report a non-existent property as non-configurable") -MSG_DEF(JSMSG_CANT_SET_NW_NC, 0, JSEXN_TYPEERR, "proxy can't successfully set a non-writable, non-configurable property") -MSG_DEF(JSMSG_CANT_SET_WO_SETTER, 0, JSEXN_TYPEERR, "proxy can't succesfully set an accessor property without a setter") -MSG_DEF(JSMSG_CANT_SKIP_NC, 0, JSEXN_TYPEERR, "proxy can't skip a non-configurable property") -MSG_DEF(JSMSG_ONWKEYS_STR_SYM, 0, JSEXN_TYPEERR, "proxy [[OwnPropertyKeys]] must return an array with only string and symbol elements") -MSG_DEF(JSMSG_MUST_REPORT_SAME_VALUE, 0, JSEXN_TYPEERR, "proxy must report the same value for a non-writable, non-configurable property") -MSG_DEF(JSMSG_MUST_REPORT_UNDEFINED, 0, JSEXN_TYPEERR, "proxy must report undefined for a non-configurable accessor property without a getter") -MSG_DEF(JSMSG_OBJECT_ACCESS_DENIED, 0, JSEXN_ERR, "Permission denied to access object") -MSG_DEF(JSMSG_PROPERTY_ACCESS_DENIED, 1, JSEXN_ERR, "Permission denied to access property {0}") -MSG_DEF(JSMSG_PROXY_CONSTRUCT_OBJECT, 0, JSEXN_TYPEERR, "proxy [[Construct]] must return an object") -MSG_DEF(JSMSG_PROXY_EXTENSIBILITY, 0, JSEXN_TYPEERR, "proxy must report same extensiblitity as target") -MSG_DEF(JSMSG_PROXY_GETOWN_OBJORUNDEF, 0, JSEXN_TYPEERR, "proxy [[GetOwnProperty]] must return an object or undefined") -MSG_DEF(JSMSG_PROXY_REVOKED, 0, JSEXN_TYPEERR, "illegal operation attempted on a revoked proxy") -MSG_DEF(JSMSG_PROXY_ARG_REVOKED, 1, JSEXN_TYPEERR, "argument {0} cannot be a revoked proxy") -MSG_DEF(JSMSG_BAD_TRAP, 1, JSEXN_TYPEERR, "proxy handler's {0} trap wasn't undefined, null, or callable") - -// Structured cloning -MSG_DEF(JSMSG_SC_BAD_CLONE_VERSION, 0, JSEXN_ERR, "unsupported structured clone version") -MSG_DEF(JSMSG_SC_BAD_SERIALIZED_DATA, 1, JSEXN_INTERNALERR, "bad serialized structured data ({0})") -MSG_DEF(JSMSG_SC_DUP_TRANSFERABLE, 0, JSEXN_TYPEERR, "duplicate transferable for structured clone") -MSG_DEF(JSMSG_SC_NOT_TRANSFERABLE, 0, JSEXN_TYPEERR, "invalid transferable array for structured clone") -MSG_DEF(JSMSG_SC_UNSUPPORTED_TYPE, 0, JSEXN_TYPEERR, "unsupported type for structured data") -MSG_DEF(JSMSG_SC_NOT_CLONABLE, 1, JSEXN_TYPEERR, "{0} cannot be cloned in this context") -MSG_DEF(JSMSG_SC_SAB_TRANSFER, 0, JSEXN_WARN, "SharedArrayBuffer must not be in the transfer list") -MSG_DEF(JSMSG_SC_SAB_DISABLED, 0, JSEXN_TYPEERR, "SharedArrayBuffer not cloned - shared memory disabled in receiver") - -// Debugger -MSG_DEF(JSMSG_ASSIGN_FUNCTION_OR_NULL, 1, JSEXN_TYPEERR, "value assigned to {0} must be a function or null") -MSG_DEF(JSMSG_DEBUG_BAD_AWAIT, 0, JSEXN_TYPEERR, "await expression received invalid value") -MSG_DEF(JSMSG_DEBUG_BAD_LINE, 0, JSEXN_TYPEERR, "invalid line number") -MSG_DEF(JSMSG_DEBUG_BAD_OFFSET, 0, JSEXN_TYPEERR, "invalid script offset") -MSG_DEF(JSMSG_DEBUG_BAD_REFERENT, 2, JSEXN_TYPEERR, "{0} does not refer to {1}") -MSG_DEF(JSMSG_DEBUG_BAD_RESUMPTION, 0, JSEXN_TYPEERR, "debugger resumption value must be undefined, {throw: val}, {return: val}, or null") -MSG_DEF(JSMSG_DEBUG_BAD_YIELD, 0, JSEXN_TYPEERR, "generator yielded invalid value") -MSG_DEF(JSMSG_DEBUG_CANT_DEBUG_GLOBAL, 0, JSEXN_TYPEERR, "passing non-debuggable global to addDebuggee") -MSG_DEF(JSMSG_DEBUG_CCW_REQUIRED, 1, JSEXN_TYPEERR, "{0}: argument must be an object from a different compartment") -MSG_DEF(JSMSG_DEBUG_COMPARTMENT_MISMATCH, 2, JSEXN_TYPEERR, "{0}: descriptor .{1} property is an object in a different compartment than the target object") -MSG_DEF(JSMSG_DEBUG_LOOP, 0, JSEXN_TYPEERR, "cannot debug an object in same compartment as debugger or a compartment that is already debugging the debugger") -MSG_DEF(JSMSG_DEBUG_NOT_DEBUGGEE, 2, JSEXN_ERR, "{0} is not a debuggee {1}") -MSG_DEF(JSMSG_DEBUG_NOT_DEBUGGING, 0, JSEXN_ERR, "can't set breakpoint: script global is not a debuggee") -MSG_DEF(JSMSG_DEBUG_NOT_IDLE, 0, JSEXN_ERR, "can't start debugging: a debuggee script is on the stack") -MSG_DEF(JSMSG_DEBUG_NOT_LIVE, 1, JSEXN_ERR, "{0} is not live") -MSG_DEF(JSMSG_DEBUG_NO_ENV_OBJECT, 0, JSEXN_TYPEERR, "declarative Environments don't have binding objects") -MSG_DEF(JSMSG_DEBUG_PROTO, 2, JSEXN_TYPEERR, "{0}.prototype is not a valid {1} instance") -MSG_DEF(JSMSG_DEBUG_WRONG_OWNER, 1, JSEXN_TYPEERR, "{0} belongs to a different Debugger") -MSG_DEF(JSMSG_DEBUG_OPTIMIZED_OUT, 1, JSEXN_ERR, "variable `{0}' has been optimized out") -MSG_DEF(JSMSG_DEBUG_RESUMPTION_VALUE_DISALLOWED, 0, JSEXN_TYPEERR, "resumption values are disallowed in this hook") -MSG_DEF(JSMSG_DEBUG_VARIABLE_NOT_FOUND,0, JSEXN_TYPEERR, "variable not found in environment") -MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 3, JSEXN_TYPEERR, "{0} is {1}{2}a global object, but a direct reference is required") -MSG_DEF(JSMSG_DEBUGGEE_WOULD_RUN, 2, JSEXN_DEBUGGEEWOULDRUN, "debuggee `{0}:{1}' would run") -MSG_DEF(JSMSG_NOT_CALLABLE_OR_UNDEFINED, 0, JSEXN_TYPEERR, "value is not a function or undefined") -MSG_DEF(JSMSG_NOT_TRACKING_ALLOCATIONS, 1, JSEXN_ERR, "Cannot call {0} without setting trackingAllocationSites to true") -MSG_DEF(JSMSG_OBJECT_METADATA_CALLBACK_ALREADY_SET, 0, JSEXN_ERR, "Cannot track object allocation, because other tools are already doing so") -MSG_DEF(JSMSG_QUERY_INNERMOST_WITHOUT_LINE_URL, 0, JSEXN_TYPEERR, "findScripts query object with 'innermost' property must have 'line' and either 'displayURL', 'url', or 'source'") -MSG_DEF(JSMSG_QUERY_LINE_WITHOUT_URL, 0, JSEXN_TYPEERR, "findScripts query object has 'line' property, but no 'displayURL', 'url', or 'source' property") -MSG_DEF(JSMSG_DEBUG_CANT_SET_OPT_ENV, 1, JSEXN_REFERENCEERR, "can't set `{0}' in an optimized-out environment") -MSG_DEF(JSMSG_DEBUG_INVISIBLE_COMPARTMENT, 0, JSEXN_TYPEERR, "object in compartment marked as invisible to Debugger") -MSG_DEF(JSMSG_DEBUG_CENSUS_BREAKDOWN, 1, JSEXN_TYPEERR, "unrecognized 'by' value in takeCensus breakdown: {0}") -MSG_DEF(JSMSG_DEBUG_PROMISE_NOT_RESOLVED, 0, JSEXN_TYPEERR, "Promise hasn't been resolved") -MSG_DEF(JSMSG_DEBUG_PROMISE_NOT_FULFILLED, 0, JSEXN_TYPEERR, "Promise hasn't been fulfilled") -MSG_DEF(JSMSG_DEBUG_PROMISE_NOT_REJECTED, 0, JSEXN_TYPEERR, "Promise hasn't been rejected") - -// Tracelogger -MSG_DEF(JSMSG_TRACELOGGER_ENABLE_FAIL, 1, JSEXN_ERR, "enabling tracelogger failed: {0}") - -// Intl -MSG_DEF(JSMSG_DATE_NOT_FINITE, 0, JSEXN_RANGEERR, "date value is not finite in DateTimeFormat.format()") -MSG_DEF(JSMSG_INTERNAL_INTL_ERROR, 0, JSEXN_ERR, "internal error while computing Intl data") -MSG_DEF(JSMSG_INTL_OBJECT_NOT_INITED, 3, JSEXN_TYPEERR, "Intl.{0}.prototype.{1} called on value that's not an object initialized as a {2}") -MSG_DEF(JSMSG_INTL_OBJECT_REINITED, 0, JSEXN_TYPEERR, "can't initialize object twice as an object of an Intl constructor") -MSG_DEF(JSMSG_INVALID_CURRENCY_CODE, 1, JSEXN_RANGEERR, "invalid currency code in NumberFormat(): {0}") -MSG_DEF(JSMSG_INVALID_DIGITS_VALUE, 1, JSEXN_RANGEERR, "invalid digits value: {0}") -MSG_DEF(JSMSG_INVALID_LANGUAGE_TAG, 1, JSEXN_RANGEERR, "invalid language tag: {0}") -MSG_DEF(JSMSG_INVALID_LOCALES_ELEMENT, 0, JSEXN_TYPEERR, "invalid element in locales argument") -MSG_DEF(JSMSG_INVALID_LOCALE_MATCHER, 1, JSEXN_RANGEERR, "invalid locale matcher in supportedLocalesOf(): {0}") -MSG_DEF(JSMSG_INVALID_OPTION_VALUE, 2, JSEXN_RANGEERR, "invalid value {1} for option {0}") -MSG_DEF(JSMSG_INVALID_TIME_ZONE, 1, JSEXN_RANGEERR, "invalid time zone in DateTimeFormat(): {0}") -MSG_DEF(JSMSG_UNDEFINED_CURRENCY, 0, JSEXN_TYPEERR, "undefined currency in NumberFormat() with currency style") - -// RegExp -MSG_DEF(JSMSG_BACK_REF_OUT_OF_RANGE, 0, JSEXN_SYNTAXERR, "back reference out of range in regular expression") -MSG_DEF(JSMSG_BAD_CLASS_RANGE, 0, JSEXN_SYNTAXERR, "invalid range in character class") -MSG_DEF(JSMSG_ESCAPE_AT_END_OF_REGEXP, 0, JSEXN_SYNTAXERR, "\\ at end of pattern") -MSG_DEF(JSMSG_EXEC_NOT_OBJORNULL, 0, JSEXN_TYPEERR, "RegExp exec method should return object or null") -MSG_DEF(JSMSG_INVALID_DECIMAL_ESCAPE, 0, JSEXN_SYNTAXERR, "invalid decimal escape in regular expression") -MSG_DEF(JSMSG_INVALID_GROUP, 0, JSEXN_SYNTAXERR, "invalid regexp group") -MSG_DEF(JSMSG_INVALID_IDENTITY_ESCAPE, 0, JSEXN_SYNTAXERR, "invalid identity escape in regular expression") -MSG_DEF(JSMSG_INVALID_UNICODE_ESCAPE, 0, JSEXN_SYNTAXERR, "invalid unicode escape in regular expression") -MSG_DEF(JSMSG_MISSING_PAREN, 0, JSEXN_SYNTAXERR, "unterminated parenthetical") -MSG_DEF(JSMSG_NEWREGEXP_FLAGGED, 0, JSEXN_TYPEERR, "can't supply flags when constructing one RegExp from another") -MSG_DEF(JSMSG_NOTHING_TO_REPEAT, 0, JSEXN_SYNTAXERR, "nothing to repeat") -MSG_DEF(JSMSG_NUMBERS_OUT_OF_ORDER, 0, JSEXN_SYNTAXERR, "numbers out of order in {} quantifier.") -MSG_DEF(JSMSG_RANGE_WITH_CLASS_ESCAPE, 0, JSEXN_SYNTAXERR, "character class escape cannot be used in class range in regular expression") -MSG_DEF(JSMSG_RAW_BRACE_IN_REGEP, 0, JSEXN_SYNTAXERR, "raw brace is not allowed in regular expression with unicode flag") -MSG_DEF(JSMSG_RAW_BRACKET_IN_REGEP, 0, JSEXN_SYNTAXERR, "raw bracket is not allowed in regular expression with unicode flag") -MSG_DEF(JSMSG_TOO_MANY_PARENS, 0, JSEXN_INTERNALERR, "too many parentheses in regular expression") -MSG_DEF(JSMSG_UNICODE_OVERFLOW, 0, JSEXN_SYNTAXERR, "unicode codepoint should not be greater than 0x10FFFF in regular expression") -MSG_DEF(JSMSG_UNMATCHED_RIGHT_PAREN, 0, JSEXN_SYNTAXERR, "unmatched ) in regular expression") -MSG_DEF(JSMSG_UNTERM_CLASS, 0, JSEXN_SYNTAXERR, "unterminated character class") - -// Self-hosting -MSG_DEF(JSMSG_DEFAULT_LOCALE_ERROR, 0, JSEXN_ERR, "internal error getting the default locale") -MSG_DEF(JSMSG_NO_SUCH_SELF_HOSTED_PROP,1, JSEXN_ERR, "No such property on self-hosted object: {0}") - -// Typed object / SIMD -MSG_DEF(JSMSG_INVALID_PROTOTYPE, 0, JSEXN_TYPEERR, "prototype field is not an object") -MSG_DEF(JSMSG_TYPEDOBJECT_BAD_ARGS, 0, JSEXN_TYPEERR, "invalid arguments") -MSG_DEF(JSMSG_TYPEDOBJECT_BINARYARRAY_BAD_INDEX, 0, JSEXN_RANGEERR, "invalid or out-of-range index") -MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_UNATTACHED, 0, JSEXN_TYPEERR, "handle unattached") -MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_ARGS, 0, JSEXN_RANGEERR, "invalid field descriptor") -MSG_DEF(JSMSG_TYPEDOBJECT_TOO_BIG, 0, JSEXN_ERR, "Type is too large to allocate") -MSG_DEF(JSMSG_SIMD_FAILED_CONVERSION, 0, JSEXN_RANGEERR, "SIMD conversion loses precision") -MSG_DEF(JSMSG_SIMD_TO_NUMBER, 0, JSEXN_TYPEERR, "can't convert SIMD value to number") - -// Array -MSG_DEF(JSMSG_TOO_LONG_ARRAY, 0, JSEXN_TYPEERR, "Too long array") - -// Typed array -MSG_DEF(JSMSG_BAD_INDEX, 0, JSEXN_RANGEERR, "invalid or out-of-range index") -MSG_DEF(JSMSG_NON_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected ArrayBuffer, but species constructor returned non-ArrayBuffer") -MSG_DEF(JSMSG_SAME_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected different ArrayBuffer, but species constructor returned same ArrayBuffer") -MSG_DEF(JSMSG_SHORT_ARRAY_BUFFER_RETURNED, 2, JSEXN_TYPEERR, "expected ArrayBuffer with at least {0} bytes, but species constructor returns ArrayBuffer with {1} bytes") -MSG_DEF(JSMSG_TYPED_ARRAY_BAD_ARGS, 0, JSEXN_TYPEERR, "invalid arguments") -MSG_DEF(JSMSG_TYPED_ARRAY_NEGATIVE_ARG,1, JSEXN_RANGEERR, "argument {0} must be >= 0") -MSG_DEF(JSMSG_TYPED_ARRAY_DETACHED, 0, JSEXN_TYPEERR, "attempting to access detached ArrayBuffer") -MSG_DEF(JSMSG_TYPED_ARRAY_CONSTRUCT_BOUNDS, 0, JSEXN_RANGEERR, "attempting to construct out-of-bounds TypedArray on ArrayBuffer") -MSG_DEF(JSMSG_TYPED_ARRAY_CALL_OR_CONSTRUCT, 1, JSEXN_TYPEERR, "cannot directly {0} builtin %TypedArray%") -MSG_DEF(JSMSG_NON_TYPED_ARRAY_RETURNED, 0, JSEXN_TYPEERR, "constructor didn't return TypedArray object") -MSG_DEF(JSMSG_SHORT_TYPED_ARRAY_RETURNED, 2, JSEXN_TYPEERR, "expected TypedArray of at least length {0}, but constructor returned TypedArray of length {1}") - -// Shared array buffer -MSG_DEF(JSMSG_SHARED_ARRAY_BAD_LENGTH, 0, JSEXN_RANGEERR, "length argument out of range") -MSG_DEF(JSMSG_NON_SHARED_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected SharedArrayBuffer, but species constructor returned non-SharedArrayBuffer") -MSG_DEF(JSMSG_SAME_SHARED_ARRAY_BUFFER_RETURNED, 0, JSEXN_TYPEERR, "expected different SharedArrayBuffer, but species constructor returned same SharedArrayBuffer") -MSG_DEF(JSMSG_SHORT_SHARED_ARRAY_BUFFER_RETURNED, 2, JSEXN_TYPEERR, "expected SharedArrayBuffer with at least {0} bytes, but species constructor returns SharedArrayBuffer with {1} bytes") - -// Reflect -MSG_DEF(JSMSG_BAD_PARSE_NODE, 0, JSEXN_INTERNALERR, "bad parse node") - -// Symbol -MSG_DEF(JSMSG_SYMBOL_TO_STRING, 0, JSEXN_TYPEERR, "can't convert symbol to string") -MSG_DEF(JSMSG_SYMBOL_TO_NUMBER, 0, JSEXN_TYPEERR, "can't convert symbol to number") - -// Atomics and futexes -MSG_DEF(JSMSG_ATOMICS_BAD_ARRAY, 0, JSEXN_TYPEERR, "invalid array type for the operation") -MSG_DEF(JSMSG_ATOMICS_TOO_LONG, 0, JSEXN_RANGEERR, "timeout value too large") -MSG_DEF(JSMSG_ATOMICS_WAIT_NOT_ALLOWED, 0, JSEXN_ERR, "waiting is not allowed on this thread") - -// XPConnect wrappers and DOM bindings -MSG_DEF(JSMSG_CANT_SET_INTERPOSED, 1, JSEXN_TYPEERR, "unable to set interposed data property '{0}'") -MSG_DEF(JSMSG_CANT_DEFINE_WINDOW_ELEMENT, 0, JSEXN_TYPEERR, "can't define elements on a Window object") -MSG_DEF(JSMSG_CANT_DELETE_WINDOW_ELEMENT, 0, JSEXN_TYPEERR, "can't delete elements from a Window object") -MSG_DEF(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY, 1, JSEXN_TYPEERR, "can't delete property {0} from window's named properties object") -MSG_DEF(JSMSG_CANT_PREVENT_EXTENSIONS, 0, JSEXN_TYPEERR, "can't prevent extensions on this proxy object") -MSG_DEF(JSMSG_NO_NAMED_SETTER, 2, JSEXN_TYPEERR, "{0} doesn't have a named property setter for '{1}'") -MSG_DEF(JSMSG_NO_INDEXED_SETTER, 2, JSEXN_TYPEERR, "{0} doesn't have an indexed property setter for '{1}'") - -// Super -MSG_DEF(JSMSG_CANT_DELETE_SUPER, 0, JSEXN_REFERENCEERR, "invalid delete involving 'super'") -MSG_DEF(JSMSG_REINIT_THIS, 0, JSEXN_REFERENCEERR, "super() called twice in derived class constructor") - -// Modules -MSG_DEF(JSMSG_BAD_DEFAULT_EXPORT, 0, JSEXN_SYNTAXERR, "default export cannot be provided by export *") -MSG_DEF(JSMSG_MISSING_INDIRECT_EXPORT, 1, JSEXN_SYNTAXERR, "indirect export '{0}' not found") -MSG_DEF(JSMSG_AMBIGUOUS_INDIRECT_EXPORT, 1, JSEXN_SYNTAXERR, "ambiguous indirect export '{0}'") -MSG_DEF(JSMSG_MISSING_IMPORT, 1, JSEXN_SYNTAXERR, "import '{0}' not found") -MSG_DEF(JSMSG_AMBIGUOUS_IMPORT, 1, JSEXN_SYNTAXERR, "ambiguous import '{0}'") -MSG_DEF(JSMSG_MISSING_NAMESPACE_EXPORT, 0, JSEXN_SYNTAXERR, "export not found for namespace") -MSG_DEF(JSMSG_MISSING_EXPORT, 1, JSEXN_SYNTAXERR, "local binding for export '{0}' not found") -MSG_DEF(JSMSG_MODULE_INSTANTIATE_FAILED, 0, JSEXN_INTERNALERR, "attempt to re-instantiate module after failure") -MSG_DEF(JSMSG_BAD_MODULE_STATE, 0, JSEXN_INTERNALERR, "module record in unexpected state") - -// Promise -MSG_DEF(JSMSG_CANNOT_RESOLVE_PROMISE_WITH_ITSELF, 0, JSEXN_TYPEERR, "A promise cannot be resolved with itself.") -MSG_DEF(JSMSG_PROMISE_CAPABILITY_HAS_SOMETHING_ALREADY, 0, JSEXN_TYPEERR, "GetCapabilitiesExecutor function already invoked with non-undefined values.") -MSG_DEF(JSMSG_PROMISE_RESOLVE_FUNCTION_NOT_CALLABLE, 0, JSEXN_TYPEERR, "A Promise subclass passed a non-callable value as the resolve function.") -MSG_DEF(JSMSG_PROMISE_REJECT_FUNCTION_NOT_CALLABLE, 0, JSEXN_TYPEERR, "A Promise subclass passed a non-callable value as the reject function.") -MSG_DEF(JSMSG_PROMISE_ERROR_IN_WRAPPED_REJECTION_REASON,0, JSEXN_INTERNALERR, "Promise rejection value is a non-unwrappable cross-compartment wrapper.") diff --git a/win32/include/spidermonkey/js/CallArgs.h b/win32/include/spidermonkey/js/CallArgs.h deleted file mode 100755 index 1e0d909a..00000000 --- a/win32/include/spidermonkey/js/CallArgs.h +++ /dev/null @@ -1,369 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Helper classes encapsulating access to the callee, |this| value, arguments, - * and argument count for a call/construct operation. - * - * JS::CallArgs encapsulates access to a JSNative's un-abstracted - * |unsigned argc, Value* vp| arguments. The principal way to create a - * JS::CallArgs is using JS::CallArgsFromVp: - * - * // If provided no arguments or a non-numeric first argument, return zero. - * // Otherwise return |this| exactly as given, without boxing. - * static bool - * Func(JSContext* cx, unsigned argc, JS::Value* vp) - * { - * JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - * - * // Guard against no arguments or a non-numeric arg0. - * if (args.length() == 0 || !args[0].isNumber()) { - * args.rval().setInt32(0); - * return true; - * } - * - * // Access to the callee must occur before accessing/setting - * // the return value. - * JSObject& callee = args.callee(); - * args.rval().setObject(callee); - * - * // callee() and calleev() will now assert. - * - * // It's always fine to access thisv(). - * HandleValue thisv = args.thisv(); - * args.rval().set(thisv); - * - * // As the return value was last set to |this|, returns |this|. - * return true; - * } - * - * CallArgs is exposed publicly and used internally. Not all parts of its - * public interface are meant to be used by embedders! See inline comments to - * for details. - * - * It's possible (albeit deprecated) to manually index into |vp| to access the - * callee, |this|, and arguments of a function, and to set its return value. - * It's also possible to use the supported API of JS_CALLEE, JS_THIS, JS_ARGV, - * JS_RVAL, and JS_SET_RVAL to the same ends. - * - * But neither API has the error-handling or moving-GC correctness of CallArgs. - * New code should use CallArgs instead whenever possible. - * - * The eventual plan is to change JSNative to take |const CallArgs&| directly, - * for automatic assertion of correct use and to make calling functions more - * efficient. Embedders should start internally switching away from using - * |argc| and |vp| directly, except to create a |CallArgs|. Then, when an - * eventual release making that change occurs, porting efforts will require - * changing methods' signatures but won't require invasive changes to the - * methods' implementations, potentially under time pressure. - */ - -#ifndef js_CallArgs_h -#define js_CallArgs_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -#include "jstypes.h" - -#include "js/RootingAPI.h" -#include "js/Value.h" - -/* Typedef for native functions called by the JS VM. */ -typedef bool -(* JSNative)(JSContext* cx, unsigned argc, JS::Value* vp); - -namespace JS { - -extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; - -namespace detail { - -/* - * Compute |this| for the |vp| inside a JSNative, either boxing primitives or - * replacing with the global object as necessary. - */ -extern JS_PUBLIC_API(Value) -ComputeThis(JSContext* cx, JS::Value* vp); - -#ifdef JS_DEBUG -extern JS_PUBLIC_API(void) -CheckIsValidConstructible(const Value& v); -#endif - -class MOZ_STACK_CLASS IncludeUsedRval -{ - protected: -#ifdef JS_DEBUG - mutable bool usedRval_; - void setUsedRval() const { usedRval_ = true; } - void clearUsedRval() const { usedRval_ = false; } - void assertUnusedRval() const { MOZ_ASSERT(!usedRval_); } -#else - void setUsedRval() const {} - void clearUsedRval() const {} - void assertUnusedRval() const {} -#endif -}; - -class MOZ_STACK_CLASS NoUsedRval -{ - protected: - void setUsedRval() const {} - void clearUsedRval() const {} - void assertUnusedRval() const {} -}; - -template -class MOZ_STACK_CLASS CallArgsBase : public WantUsedRval -{ - static_assert(mozilla::IsSame::value || - mozilla::IsSame::value, - "WantUsedRval can only be IncludeUsedRval or NoUsedRval"); - - protected: - Value* argv_; - unsigned argc_; - bool constructing_; - - public: - // CALLEE ACCESS - - /* - * Returns the function being called, as a value. Must not be called after - * rval() has been used! - */ - HandleValue calleev() const { - this->assertUnusedRval(); - return HandleValue::fromMarkedLocation(&argv_[-2]); - } - - /* - * Returns the function being called, as an object. Must not be called - * after rval() has been used! - */ - JSObject& callee() const { - return calleev().toObject(); - } - - // CALLING/CONSTRUCTING-DIFFERENTIATIONS - - bool isConstructing() const { - if (!argv_[-1].isMagic()) - return false; - -#ifdef JS_DEBUG - if (!this->usedRval_) - CheckIsValidConstructible(calleev()); -#endif - - return true; - } - - MutableHandleValue newTarget() const { - MOZ_ASSERT(constructing_); - return MutableHandleValue::fromMarkedLocation(&this->argv_[argc_]); - } - - /* - * Returns the |this| value passed to the function. This method must not - * be called when the function is being called as a constructor via |new|. - * The value may or may not be an object: it is the individual function's - * responsibility to box the value if needed. - */ - HandleValue thisv() const { - // Some internal code uses thisv() in constructing cases, so don't do - // this yet. - // MOZ_ASSERT(!argv_[-1].isMagic(JS_IS_CONSTRUCTING)); - return HandleValue::fromMarkedLocation(&argv_[-1]); - } - - Value computeThis(JSContext* cx) const { - if (thisv().isObject()) - return thisv(); - - return ComputeThis(cx, base()); - } - - // ARGUMENTS - - /* Returns the number of arguments. */ - unsigned length() const { return argc_; } - - /* Returns the i-th zero-indexed argument. */ - MutableHandleValue operator[](unsigned i) const { - MOZ_ASSERT(i < argc_); - return MutableHandleValue::fromMarkedLocation(&this->argv_[i]); - } - - /* - * Returns the i-th zero-indexed argument, or |undefined| if there's no - * such argument. - */ - HandleValue get(unsigned i) const { - return i < length() - ? HandleValue::fromMarkedLocation(&this->argv_[i]) - : UndefinedHandleValue; - } - - /* - * Returns true if the i-th zero-indexed argument is present and is not - * |undefined|. - */ - bool hasDefined(unsigned i) const { - return i < argc_ && !this->argv_[i].isUndefined(); - } - - // RETURN VALUE - - /* - * Returns the currently-set return value. The initial contents of this - * value are unspecified. Once this method has been called, callee() and - * calleev() can no longer be used. (If you're compiling against a debug - * build of SpiderMonkey, these methods will assert to aid debugging.) - * - * If the method you're implementing succeeds by returning true, you *must* - * set this. (SpiderMonkey doesn't currently assert this, but it will do - * so eventually.) You don't need to use or change this if your method - * fails. - */ - MutableHandleValue rval() const { - this->setUsedRval(); - return MutableHandleValue::fromMarkedLocation(&argv_[-2]); - } - - public: - // These methods are publicly exposed, but they are *not* to be used when - // implementing a JSNative method and encapsulating access to |vp| within - // it. You probably don't want to use these! - - void setCallee(const Value& aCalleev) const { - this->clearUsedRval(); - argv_[-2] = aCalleev; - } - - void setThis(const Value& aThisv) const { - argv_[-1] = aThisv; - } - - MutableHandleValue mutableThisv() const { - return MutableHandleValue::fromMarkedLocation(&argv_[-1]); - } - - public: - // These methods are publicly exposed, but we're unsure of the interfaces - // (because they're hackish and drop assertions). Avoid using these if you - // can. - - Value* array() const { return argv_; } - Value* end() const { return argv_ + argc_ + constructing_; } - - public: - // These methods are only intended for internal use. Embedders shouldn't - // use them! - - Value* base() const { return argv_ - 2; } - - Value* spAfterCall() const { - this->setUsedRval(); - return argv_ - 1; - } -}; - -} // namespace detail - -class MOZ_STACK_CLASS CallArgs : public detail::CallArgsBase -{ - private: - friend CallArgs CallArgsFromVp(unsigned argc, Value* vp); - friend CallArgs CallArgsFromSp(unsigned stackSlots, Value* sp, bool constructing); - - static CallArgs create(unsigned argc, Value* argv, bool constructing) { - CallArgs args; - args.clearUsedRval(); - args.argv_ = argv; - args.argc_ = argc; - args.constructing_ = constructing; -#ifdef DEBUG - for (unsigned i = 0; i < argc; ++i) - MOZ_ASSERT_IF(argv[i].isMarkable(), !GCThingIsMarkedGray(GCCellPtr(argv[i]))); -#endif - return args; - } - - public: - /* - * Returns true if there are at least |required| arguments passed in. If - * false, it reports an error message on the context. - */ - bool requireAtLeast(JSContext* cx, const char* fnname, unsigned required) const; - -}; - -MOZ_ALWAYS_INLINE CallArgs -CallArgsFromVp(unsigned argc, Value* vp) -{ - return CallArgs::create(argc, vp + 2, vp[1].isMagic(JS_IS_CONSTRUCTING)); -} - -// This method is only intended for internal use in SpiderMonkey. We may -// eventually move it to an internal header. Embedders should use -// JS::CallArgsFromVp! -MOZ_ALWAYS_INLINE CallArgs -CallArgsFromSp(unsigned stackSlots, Value* sp, bool constructing = false) -{ - return CallArgs::create(stackSlots - constructing, sp - stackSlots, constructing); -} - -} // namespace JS - -/* - * Macros to hide interpreter stack layout details from a JSNative using its - * JS::Value* vp parameter. DO NOT USE THESE! Instead use JS::CallArgs and - * friends, above. These macros will be removed when we change JSNative to - * take a const JS::CallArgs&. - */ - -/* - * Return |this| if |this| is an object. Otherwise, return the global object - * if |this| is null or undefined, and finally return a boxed version of any - * other primitive. - * - * Note: if this method returns null, an error has occurred and must be - * propagated or caught. - */ -MOZ_ALWAYS_INLINE JS::Value -JS_THIS(JSContext* cx, JS::Value* vp) -{ - return vp[1].isPrimitive() ? JS::detail::ComputeThis(cx, vp) : vp[1]; -} - -/* - * A note on JS_THIS_OBJECT: no equivalent method is part of the CallArgs - * interface, and we're unlikely to add one (functions shouldn't be implicitly - * exposing the global object to arbitrary callers). Continue using |vp| - * directly for this case, but be aware this API will eventually be replaced - * with a function that operates directly upon |args.thisv()|. - */ -#define JS_THIS_OBJECT(cx,vp) (JS_THIS(cx,vp).toObjectOrNull()) - -/* - * |this| is passed to functions in ES5 without change. Functions themselves - * do any post-processing they desire to box |this|, compute the global object, - * &c. This macro retrieves a function's unboxed |this| value. - * - * This macro must not be used in conjunction with JS_THIS or JS_THIS_OBJECT, - * or vice versa. Either use the provided this value with this macro, or - * compute the boxed |this| value using those. JS_THIS_VALUE must not be used - * if the function is being called as a constructor. - * - * But: DO NOT USE THIS! Instead use JS::CallArgs::thisv(), above. - * - */ -#define JS_THIS_VALUE(cx,vp) ((vp)[1]) - -#endif /* js_CallArgs_h */ diff --git a/win32/include/spidermonkey/js/CallNonGenericMethod.h b/win32/include/spidermonkey/js/CallNonGenericMethod.h deleted file mode 100755 index 9a1cf010..00000000 --- a/win32/include/spidermonkey/js/CallNonGenericMethod.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_CallNonGenericMethod_h -#define js_CallNonGenericMethod_h - -#include "jstypes.h" - -#include "js/CallArgs.h" - -namespace JS { - -// Returns true if |v| is considered an acceptable this-value. -typedef bool (*IsAcceptableThis)(HandleValue v); - -// Implements the guts of a method; guaranteed to be provided an acceptable -// this-value, as determined by a corresponding IsAcceptableThis method. -typedef bool (*NativeImpl)(JSContext* cx, const CallArgs& args); - -namespace detail { - -// DON'T CALL THIS DIRECTLY. It's for use only by CallNonGenericMethod! -extern JS_PUBLIC_API(bool) -CallMethodIfWrapped(JSContext* cx, IsAcceptableThis test, NativeImpl impl, const CallArgs& args); - -} // namespace detail - -// Methods usually act upon |this| objects only from a single global object and -// compartment. Sometimes, however, a method must act upon |this| values from -// multiple global objects or compartments. In such cases the |this| value a -// method might see will be wrapped, such that various access to the object -- -// to its class, its private data, its reserved slots, and so on -- will not -// work properly without entering that object's compartment. This method -// implements a solution to this problem. -// -// To implement a method that accepts |this| values from multiple compartments, -// define two functions. The first function matches the IsAcceptableThis type -// and indicates whether the provided value is an acceptable |this| for the -// method; it must be a pure function only of its argument. -// -// static const JSClass AnswerClass = { ... }; -// -// static bool -// IsAnswerObject(const Value& v) -// { -// if (!v.isObject()) -// return false; -// return JS_GetClass(&v.toObject()) == &AnswerClass; -// } -// -// The second function implements the NativeImpl signature and defines the -// behavior of the method when it is provided an acceptable |this| value. -// Aside from some typing niceties -- see the CallArgs interface for details -- -// its interface is the same as that of JSNative. -// -// static bool -// answer_getAnswer_impl(JSContext* cx, JS::CallArgs args) -// { -// args.rval().setInt32(42); -// return true; -// } -// -// The implementation function is guaranteed to be called *only* with a |this| -// value which is considered acceptable. -// -// Now to implement the actual method, write a JSNative that calls the method -// declared below, passing the appropriate template and runtime arguments. -// -// static bool -// answer_getAnswer(JSContext* cx, unsigned argc, JS::Value* vp) -// { -// JS::CallArgs args = JS::CallArgsFromVp(argc, vp); -// return JS::CallNonGenericMethod(cx, args); -// } -// -// Note that, because they are used as template arguments, the predicate -// and implementation functions must have external linkage. (This is -// unfortunate, but GCC wasn't inlining things as one would hope when we -// passed them as function arguments.) -// -// JS::CallNonGenericMethod will test whether |args.thisv()| is acceptable. If -// it is, it will call the provided implementation function, which will return -// a value and indicate success. If it is not, it will attempt to unwrap -// |this| and call the implementation function on the unwrapped |this|. If -// that succeeds, all well and good. If it doesn't succeed, a TypeError will -// be thrown. -// -// Note: JS::CallNonGenericMethod will only work correctly if it's called in -// tail position in a JSNative. Do not call it from any other place. -// -template -MOZ_ALWAYS_INLINE bool -CallNonGenericMethod(JSContext* cx, const CallArgs& args) -{ - HandleValue thisv = args.thisv(); - if (Test(thisv)) - return Impl(cx, args); - - return detail::CallMethodIfWrapped(cx, Test, Impl, args); -} - -MOZ_ALWAYS_INLINE bool -CallNonGenericMethod(JSContext* cx, IsAcceptableThis Test, NativeImpl Impl, const CallArgs& args) -{ - HandleValue thisv = args.thisv(); - if (Test(thisv)) - return Impl(cx, args); - - return detail::CallMethodIfWrapped(cx, Test, Impl, args); -} - -} // namespace JS - -#endif /* js_CallNonGenericMethod_h */ diff --git a/win32/include/spidermonkey/js/CharacterEncoding.h b/win32/include/spidermonkey/js/CharacterEncoding.h deleted file mode 100755 index fe39a415..00000000 --- a/win32/include/spidermonkey/js/CharacterEncoding.h +++ /dev/null @@ -1,338 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_CharacterEncoding_h -#define js_CharacterEncoding_h - -#include "mozilla/Range.h" - -#include "js/TypeDecls.h" -#include "js/Utility.h" - -namespace js { -class ExclusiveContext; -} // namespace js - -class JSFlatString; - -namespace JS { - -/* - * By default, all C/C++ 1-byte-per-character strings passed into the JSAPI - * are treated as ISO/IEC 8859-1, also known as Latin-1. That is, each - * byte is treated as a 2-byte character, and there is no way to pass in a - * string containing characters beyond U+00FF. - */ -class Latin1Chars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = Latin1Char; - - Latin1Chars() : Base() {} - Latin1Chars(char* aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) {} - Latin1Chars(const Latin1Char* aBytes, size_t aLength) - : Base(const_cast(aBytes), aLength) - {} - Latin1Chars(const char* aBytes, size_t aLength) - : Base(reinterpret_cast(const_cast(aBytes)), aLength) - {} -}; - -/* - * A Latin1Chars, but with \0 termination for C compatibility. - */ -class Latin1CharsZ : public mozilla::RangedPtr -{ - typedef mozilla::RangedPtr Base; - - public: - using CharT = Latin1Char; - - Latin1CharsZ() : Base(nullptr, 0) {} - - Latin1CharsZ(char* aBytes, size_t aLength) - : Base(reinterpret_cast(aBytes), aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - Latin1CharsZ(Latin1Char* aBytes, size_t aLength) - : Base(aBytes, aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - using Base::operator=; - - char* c_str() { return reinterpret_cast(get()); } -}; - -class UTF8Chars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = unsigned char; - - UTF8Chars() : Base() {} - UTF8Chars(char* aBytes, size_t aLength) - : Base(reinterpret_cast(aBytes), aLength) - {} - UTF8Chars(const char* aBytes, size_t aLength) - : Base(reinterpret_cast(const_cast(aBytes)), aLength) - {} -}; - -/* - * SpiderMonkey also deals directly with UTF-8 encoded text in some places. - */ -class UTF8CharsZ : public mozilla::RangedPtr -{ - typedef mozilla::RangedPtr Base; - - public: - using CharT = unsigned char; - - UTF8CharsZ() : Base(nullptr, 0) {} - - UTF8CharsZ(char* aBytes, size_t aLength) - : Base(reinterpret_cast(aBytes), aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - UTF8CharsZ(unsigned char* aBytes, size_t aLength) - : Base(aBytes, aLength) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); - } - - using Base::operator=; - - char* c_str() { return reinterpret_cast(get()); } -}; - -/* - * A wrapper for a "const char*" that is encoded using UTF-8. - * This class does not manage ownership of the data; that is left - * to others. This differs from UTF8CharsZ in that the chars are - * const and it allows assignment. - */ -class ConstUTF8CharsZ -{ - const char* data_; - - public: - using CharT = unsigned char; - - ConstUTF8CharsZ() : data_(nullptr) - {} - - ConstUTF8CharsZ(const char* aBytes, size_t aLength) - : data_(aBytes) - { - MOZ_ASSERT(aBytes[aLength] == '\0'); -#ifdef DEBUG - validate(aLength); -#endif - } - - const void* get() const { return data_; } - - const char* c_str() const { return data_; } - - explicit operator bool() const { return data_ != nullptr; } - - private: -#ifdef DEBUG - void validate(size_t aLength); -#endif -}; - -/* - * SpiderMonkey uses a 2-byte character representation: it is a - * 2-byte-at-a-time view of a UTF-16 byte stream. This is similar to UCS-2, - * but unlike UCS-2, we do not strip UTF-16 extension bytes. This allows a - * sufficiently dedicated JavaScript program to be fully unicode-aware by - * manually interpreting UTF-16 extension characters embedded in the JS - * string. - */ -class TwoByteChars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = char16_t; - - TwoByteChars() : Base() {} - TwoByteChars(char16_t* aChars, size_t aLength) : Base(aChars, aLength) {} - TwoByteChars(const char16_t* aChars, size_t aLength) : Base(const_cast(aChars), aLength) {} -}; - -/* - * A TwoByteChars, but \0 terminated for compatibility with JSFlatString. - */ -class TwoByteCharsZ : public mozilla::RangedPtr -{ - typedef mozilla::RangedPtr Base; - - public: - using CharT = char16_t; - - TwoByteCharsZ() : Base(nullptr, 0) {} - - TwoByteCharsZ(char16_t* chars, size_t length) - : Base(chars, length) - { - MOZ_ASSERT(chars[length] == '\0'); - } - - using Base::operator=; -}; - -typedef mozilla::RangedPtr ConstCharPtr; - -/* - * Like TwoByteChars, but the chars are const. - */ -class ConstTwoByteChars : public mozilla::Range -{ - typedef mozilla::Range Base; - - public: - using CharT = char16_t; - - ConstTwoByteChars() : Base() {} - ConstTwoByteChars(const char16_t* aChars, size_t aLength) : Base(aChars, aLength) {} -}; - -/* - * Convert a 2-byte character sequence to "ISO-Latin-1". This works by - * truncating each 2-byte pair in the sequence to a 1-byte pair. If the source - * contains any UTF-16 extension characters, then this may give invalid Latin1 - * output. The returned string is zero terminated. The returned string or the - * returned string's |start()| must be freed with JS_free or js_free, - * respectively. If allocation fails, an OOM error will be set and the method - * will return a nullptr chars (which can be tested for with the ! operator). - * This method cannot trigger GC. - */ -extern Latin1CharsZ -LossyTwoByteCharsToNewLatin1CharsZ(js::ExclusiveContext* cx, - const mozilla::Range tbchars); - -inline Latin1CharsZ -LossyTwoByteCharsToNewLatin1CharsZ(js::ExclusiveContext* cx, const char16_t* begin, size_t length) -{ - const mozilla::Range tbchars(begin, length); - return JS::LossyTwoByteCharsToNewLatin1CharsZ(cx, tbchars); -} - -template -extern UTF8CharsZ -CharsToNewUTF8CharsZ(js::ExclusiveContext* maybeCx, const mozilla::Range chars); - -uint32_t -Utf8ToOneUcs4Char(const uint8_t* utf8Buffer, int utf8Length); - -/* - * Inflate bytes in UTF-8 encoding to char16_t. - * - On error, returns an empty TwoByteCharsZ. - * - On success, returns a malloc'd TwoByteCharsZ, and updates |outlen| to hold - * its length; the length value excludes the trailing null. - */ -extern TwoByteCharsZ -UTF8CharsToNewTwoByteCharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -/* - * Like UTF8CharsToNewTwoByteCharsZ, but for ConstUTF8CharsZ. - */ -extern TwoByteCharsZ -UTF8CharsToNewTwoByteCharsZ(JSContext* cx, const ConstUTF8CharsZ& utf8, size_t* outlen); - -/* - * The same as UTF8CharsToNewTwoByteCharsZ(), except that any malformed UTF-8 characters - * will be replaced by \uFFFD. No exception will be thrown for malformed UTF-8 - * input. - */ -extern TwoByteCharsZ -LossyUTF8CharsToNewTwoByteCharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -extern TwoByteCharsZ -LossyUTF8CharsToNewTwoByteCharsZ(JSContext* cx, const ConstUTF8CharsZ& utf8, size_t* outlen); - -/* - * Returns the length of the char buffer required to encode |s| as UTF8. - * Does not include the null-terminator. - */ -JS_PUBLIC_API(size_t) -GetDeflatedUTF8StringLength(JSFlatString* s); - -/* - * Encode |src| as UTF8. The caller must either ensure |dst| has enough space - * to encode the entire string or pass the length of the buffer as |dstlenp|, - * in which case the function will encode characters from the string until - * the buffer is exhausted. Does not write the null terminator. - * - * If |dstlenp| is provided, it will be updated to hold the number of bytes - * written to the buffer. If |numcharsp| is provided, it will be updated to hold - * the number of Unicode characters written to the buffer (which can be less - * than the length of the string, if the buffer is exhausted before the string - * is fully encoded). - */ -JS_PUBLIC_API(void) -DeflateStringToUTF8Buffer(JSFlatString* src, mozilla::RangedPtr dst, - size_t* dstlenp = nullptr, size_t* numcharsp = nullptr); - -/* - * The smallest character encoding capable of fully representing a particular - * string. - */ -enum class SmallestEncoding { - ASCII, - Latin1, - UTF16 -}; - -/* - * Returns the smallest encoding possible for the given string: if all - * codepoints are <128 then ASCII, otherwise if all codepoints are <256 - * Latin-1, else UTF16. - */ -JS_PUBLIC_API(SmallestEncoding) -FindSmallestEncoding(UTF8Chars utf8); - -/* - * Return a null-terminated Latin-1 string copied from the input string, - * storing its length (excluding null terminator) in |*outlen|. Fail and - * report an error if the string contains non-Latin-1 codepoints. Returns - * Latin1CharsZ() on failure. - */ -extern Latin1CharsZ -UTF8CharsToNewLatin1CharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -/* - * Return a null-terminated Latin-1 string copied from the input string, - * storing its length (excluding null terminator) in |*outlen|. Non-Latin-1 - * codepoints are replaced by '?'. Returns Latin1CharsZ() on failure. - */ -extern Latin1CharsZ -LossyUTF8CharsToNewLatin1CharsZ(JSContext* cx, const UTF8Chars utf8, size_t* outlen); - -/* - * Returns true if all characters in the given null-terminated string are - * ASCII, i.e. < 0x80, false otherwise. - */ -extern bool -StringIsASCII(const char* s); - -} // namespace JS - -inline void JS_free(JS::Latin1CharsZ& ptr) { js_free((void*)ptr.get()); } -inline void JS_free(JS::UTF8CharsZ& ptr) { js_free((void*)ptr.get()); } - -#endif /* js_CharacterEncoding_h */ diff --git a/win32/include/spidermonkey/js/Class.h b/win32/include/spidermonkey/js/Class.h deleted file mode 100755 index 3b502387..00000000 --- a/win32/include/spidermonkey/js/Class.h +++ /dev/null @@ -1,995 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JSClass definition and its component types, plus related interfaces. */ - -#ifndef js_Class_h -#define js_Class_h - -#include "jstypes.h" - -#include "js/CallArgs.h" -#include "js/Id.h" -#include "js/TypeDecls.h" - -/* - * A JSClass acts as a vtable for JS objects that allows JSAPI clients to - * control various aspects of the behavior of an object like property lookup. - * js::Class is an engine-private extension that allows more control over - * object behavior and, e.g., allows custom slow layout. - */ - -struct JSAtomState; -struct JSFreeOp; -struct JSFunctionSpec; - -namespace js { - -struct Class; -class FreeOp; -class Shape; - -// This is equal to JSFunction::class_. Use it in places where you don't want -// to #include jsfun.h. -extern JS_FRIEND_DATA(const js::Class* const) FunctionClassPtr; - -} // namespace js - -namespace JS { - -class AutoIdVector; - -/** - * The answer to a successful query as to whether an object is an Array per - * ES6's internal |IsArray| operation (as exposed by |Array.isArray|). - */ -enum class IsArrayAnswer -{ - Array, - NotArray, - RevokedProxy -}; - -/** - * ES6 7.2.2. - * - * Returns false on failure, otherwise returns true and sets |*isArray| - * indicating whether the object passes ECMAScript's IsArray test. This is the - * same test performed by |Array.isArray|. - * - * This is NOT the same as asking whether |obj| is an Array or a wrapper around - * one. If |obj| is a proxy created by |Proxy.revocable()| and has been - * revoked, or if |obj| is a proxy whose target (at any number of hops) is a - * revoked proxy, this method throws a TypeError and returns false. - */ -extern JS_PUBLIC_API(bool) -IsArray(JSContext* cx, HandleObject obj, bool* isArray); - -/** - * Identical to IsArray above, but the nature of the object (if successfully - * determined) is communicated via |*answer|. In particular this method - * returns true and sets |*answer = IsArrayAnswer::RevokedProxy| when called on - * a revoked proxy. - * - * Most users will want the overload above, not this one. - */ -extern JS_PUBLIC_API(bool) -IsArray(JSContext* cx, HandleObject obj, IsArrayAnswer* answer); - -/** - * Per ES6, the [[DefineOwnProperty]] internal method has three different - * possible outcomes: - * - * - It can throw an exception (which we indicate by returning false). - * - * - It can return true, indicating unvarnished success. - * - * - It can return false, indicating "strict failure". The property could - * not be defined. It's an error, but no exception was thrown. - * - * It's not just [[DefineOwnProperty]]: all the mutating internal methods have - * the same three outcomes. (The other affected internal methods are [[Set]], - * [[Delete]], [[SetPrototypeOf]], and [[PreventExtensions]].) - * - * If you think this design is awful, you're not alone. But as it's the - * standard, we must represent these boolean "success" values somehow. - * ObjectOpSuccess is the class for this. It's like a bool, but when it's false - * it also stores an error code. - * - * Typical usage: - * - * ObjectOpResult result; - * if (!DefineProperty(cx, obj, id, ..., result)) - * return false; - * if (!result) - * return result.reportError(cx, obj, id); - * - * Users don't have to call `result.report()`; another possible ending is: - * - * argv.rval().setBoolean(bool(result)); - * return true; - */ -class ObjectOpResult -{ - private: - /** - * code_ is either one of the special codes OkCode or Uninitialized, or - * an error code. For now the error codes are private to the JS engine; - * they're defined in js/src/js.msg. - * - * code_ is uintptr_t (rather than uint32_t) for the convenience of the - * JITs, which would otherwise have to deal with either padding or stack - * alignment on 64-bit platforms. - */ - uintptr_t code_; - - public: - enum SpecialCodes : uintptr_t { - OkCode = 0, - Uninitialized = uintptr_t(-1) - }; - - ObjectOpResult() : code_(Uninitialized) {} - - /* Return true if succeed() was called. */ - bool ok() const { - MOZ_ASSERT(code_ != Uninitialized); - return code_ == OkCode; - } - - explicit operator bool() const { return ok(); } - - /* Set this ObjectOpResult to true and return true. */ - bool succeed() { - code_ = OkCode; - return true; - } - - /* - * Set this ObjectOpResult to false with an error code. - * - * Always returns true, as a convenience. Typical usage will be: - * - * if (funny condition) - * return result.fail(JSMSG_CANT_DO_THE_THINGS); - * - * The true return value indicates that no exception is pending, and it - * would be OK to ignore the failure and continue. - */ - bool fail(uint32_t msg) { - MOZ_ASSERT(msg != OkCode); - code_ = msg; - return true; - } - - JS_PUBLIC_API(bool) failCantRedefineProp(); - JS_PUBLIC_API(bool) failReadOnly(); - JS_PUBLIC_API(bool) failGetterOnly(); - JS_PUBLIC_API(bool) failCantDelete(); - - JS_PUBLIC_API(bool) failCantSetInterposed(); - JS_PUBLIC_API(bool) failCantDefineWindowElement(); - JS_PUBLIC_API(bool) failCantDeleteWindowElement(); - JS_PUBLIC_API(bool) failCantDeleteWindowNamedProperty(); - JS_PUBLIC_API(bool) failCantPreventExtensions(); - JS_PUBLIC_API(bool) failCantSetProto(); - JS_PUBLIC_API(bool) failNoNamedSetter(); - JS_PUBLIC_API(bool) failNoIndexedSetter(); - - uint32_t failureCode() const { - MOZ_ASSERT(!ok()); - return uint32_t(code_); - } - - /* - * Report an error or warning if necessary; return true to proceed and - * false if an error was reported. Call this when failure should cause - * a warning if extraWarnings are enabled. - * - * The precise rules are like this: - * - * - If ok(), then we succeeded. Do nothing and return true. - * - Otherwise, if |strict| is true, or if cx has both extraWarnings and - * werrorOption enabled, throw a TypeError and return false. - * - Otherwise, if cx has extraWarnings enabled, emit a warning and - * return true. - * - Otherwise, do nothing and return true. - */ - bool checkStrictErrorOrWarning(JSContext* cx, HandleObject obj, HandleId id, bool strict) { - if (ok()) - return true; - return reportStrictErrorOrWarning(cx, obj, id, strict); - } - - /* - * The same as checkStrictErrorOrWarning(cx, id, strict), except the - * operation is not associated with a particular property id. This is - * used for [[PreventExtensions]] and [[SetPrototypeOf]]. failureCode() - * must not be an error that has "{0}" in the error message. - */ - bool checkStrictErrorOrWarning(JSContext* cx, HandleObject obj, bool strict) { - return ok() || reportStrictErrorOrWarning(cx, obj, strict); - } - - /* Throw a TypeError. Call this only if !ok(). */ - bool reportError(JSContext* cx, HandleObject obj, HandleId id) { - return reportStrictErrorOrWarning(cx, obj, id, true); - } - - /* - * The same as reportError(cx, obj, id), except the operation is not - * associated with a particular property id. - */ - bool reportError(JSContext* cx, HandleObject obj) { - return reportStrictErrorOrWarning(cx, obj, true); - } - - /* Helper function for checkStrictErrorOrWarning's slow path. */ - JS_PUBLIC_API(bool) reportStrictErrorOrWarning(JSContext* cx, HandleObject obj, HandleId id, bool strict); - JS_PUBLIC_API(bool) reportStrictErrorOrWarning(JSContext* cx, HandleObject obj, bool strict); - - /* - * Convenience method. Return true if ok() or if strict is false; otherwise - * throw a TypeError and return false. - */ - bool checkStrict(JSContext* cx, HandleObject obj, HandleId id) { - return checkStrictErrorOrWarning(cx, obj, id, true); - } - - /* - * Convenience method. The same as checkStrict(cx, id), except the - * operation is not associated with a particular property id. - */ - bool checkStrict(JSContext* cx, HandleObject obj) { - return checkStrictErrorOrWarning(cx, obj, true); - } -}; - -} // namespace JS - -// JSClass operation signatures. - -/** - * Get a property named by id in obj. Note the jsid id type -- id may - * be a string (Unicode property identifier) or an int (element index). The - * *vp out parameter, on success, is the new property value after the action. - */ -typedef bool -(* JSGetterOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp); - -/** Add a property named by id to obj. */ -typedef bool -(* JSAddPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v); - -/** - * Set a property named by id in obj, treating the assignment as strict - * mode code if strict is true. Note the jsid id type -- id may be a string - * (Unicode property identifier) or an int (element index). The *vp out - * parameter, on success, is the new property value after the - * set. - */ -typedef bool -(* JSSetterOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp, JS::ObjectOpResult& result); - -/** - * Delete a property named by id in obj. - * - * If an error occurred, return false as per normal JSAPI error practice. - * - * If no error occurred, but the deletion attempt wasn't allowed (perhaps - * because the property was non-configurable), call result.fail() and - * return true. This will cause |delete obj[id]| to evaluate to false in - * non-strict mode code, and to throw a TypeError in strict mode code. - * - * If no error occurred and the deletion wasn't disallowed (this is *not* the - * same as saying that a deletion actually occurred -- deleting a non-existent - * property, or an inherited property, is allowed -- it's just pointless), - * call result.succeed() and return true. - */ -typedef bool -(* JSDeletePropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -/** - * The type of ObjectOps::enumerate. This callback overrides a portion of - * SpiderMonkey's default [[Enumerate]] internal method. When an ordinary object - * is enumerated, that object and each object on its prototype chain is tested - * for an enumerate op, and those ops are called in order. The properties each - * op adds to the 'properties' vector are added to the set of values the for-in - * loop will iterate over. All of this is nonstandard. - * - * An object is "enumerated" when it's the target of a for-in loop or - * JS_Enumerate(). The callback's job is to populate 'properties' with the - * object's property keys. If `enumerableOnly` is true, the callback should only - * add enumerable properties. - */ -typedef bool -(* JSNewEnumerateOp)(JSContext* cx, JS::HandleObject obj, JS::AutoIdVector& properties, - bool enumerableOnly); - -/** - * The old-style JSClass.enumerate op should define all lazy properties not - * yet reflected in obj. - */ -typedef bool -(* JSEnumerateOp)(JSContext* cx, JS::HandleObject obj); - -/** - * The type of ObjectOps::funToString. This callback allows an object to - * provide a custom string to use when Function.prototype.toString is invoked on - * that object. A null return value means OOM. - */ -typedef JSString* -(* JSFunToStringOp)(JSContext* cx, JS::HandleObject obj, unsigned indent); - -/** - * Resolve a lazy property named by id in obj by defining it directly in obj. - * Lazy properties are those reflected from some peer native property space - * (e.g., the DOM attributes for a given node reflected as obj) on demand. - * - * JS looks for a property in an object, and if not found, tries to resolve - * the given id. *resolvedp should be set to true iff the property was defined - * on |obj|. - */ -typedef bool -(* JSResolveOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - bool* resolvedp); - -/** - * A class with a resolve hook can optionally have a mayResolve hook. This hook - * must have no side effects and must return true for a given id if the resolve - * hook may resolve this id. This is useful when we're doing a "pure" lookup: if - * mayResolve returns false, we know we don't have to call the effectful resolve - * hook. - * - * maybeObj, if non-null, is the object on which we're doing the lookup. This - * can be nullptr: during JIT compilation we sometimes know the Class but not - * the object. - */ -typedef bool -(* JSMayResolveOp)(const JSAtomState& names, jsid id, JSObject* maybeObj); - -/** - * Finalize obj, which the garbage collector has determined to be unreachable - * from other live objects or from GC roots. Obviously, finalizers must never - * store a reference to obj. - */ -typedef void -(* JSFinalizeOp)(JSFreeOp* fop, JSObject* obj); - -/** Finalizes external strings created by JS_NewExternalString. */ -struct JSStringFinalizer { - void (*finalize)(JS::Zone* zone, const JSStringFinalizer* fin, char16_t* chars); -}; - -/** - * Check whether v is an instance of obj. Return false on error or exception, - * true on success with true in *bp if v is an instance of obj, false in - * *bp otherwise. - */ -typedef bool -(* JSHasInstanceOp)(JSContext* cx, JS::HandleObject obj, JS::MutableHandleValue vp, - bool* bp); - -/** - * Function type for trace operation of the class called to enumerate all - * traceable things reachable from obj's private data structure. For each such - * thing, a trace implementation must call JS::TraceEdge on the thing's - * location. - * - * JSTraceOp implementation can assume that no other threads mutates object - * state. It must not change state of the object or corresponding native - * structures. The only exception for this rule is the case when the embedding - * needs a tight integration with GC. In that case the embedding can check if - * the traversal is a part of the marking phase through calling - * JS_IsGCMarkingTracer and apply a special code like emptying caches or - * marking its native structures. - */ -typedef void -(* JSTraceOp)(JSTracer* trc, JSObject* obj); - -typedef JSObject* -(* JSWeakmapKeyDelegateOp)(JSObject* obj); - -typedef void -(* JSObjectMovedOp)(JSObject* obj, const JSObject* old); - -/* js::Class operation signatures. */ - -namespace js { - -typedef bool -(* LookupPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleObject objp, JS::MutableHandle propp); -typedef bool -(* DefinePropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc, - JS::ObjectOpResult& result); -typedef bool -(* HasPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); -typedef bool -(* GetPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleValue receiver, JS::HandleId id, - JS::MutableHandleValue vp); -typedef bool -(* SetPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v, - JS::HandleValue receiver, JS::ObjectOpResult& result); -typedef bool -(* GetOwnPropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); -typedef bool -(* DeletePropertyOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -typedef bool -(* WatchOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); - -typedef bool -(* UnwatchOp)(JSContext* cx, JS::HandleObject obj, JS::HandleId id); - -class JS_FRIEND_API(ElementAdder) -{ - public: - enum GetBehavior { - // Check if the element exists before performing the Get and preserve - // holes. - CheckHasElemPreserveHoles, - - // Perform a Get operation, like obj[index] in JS. - GetElement - }; - - private: - // Only one of these is used. - JS::RootedObject resObj_; - JS::Value* vp_; - - uint32_t index_; -#ifdef DEBUG - uint32_t length_; -#endif - GetBehavior getBehavior_; - - public: - ElementAdder(JSContext* cx, JSObject* obj, uint32_t length, GetBehavior behavior) - : resObj_(cx, obj), vp_(nullptr), index_(0), -#ifdef DEBUG - length_(length), -#endif - getBehavior_(behavior) - {} - ElementAdder(JSContext* cx, JS::Value* vp, uint32_t length, GetBehavior behavior) - : resObj_(cx), vp_(vp), index_(0), -#ifdef DEBUG - length_(length), -#endif - getBehavior_(behavior) - {} - - GetBehavior getBehavior() const { return getBehavior_; } - - bool append(JSContext* cx, JS::HandleValue v); - void appendHole(); -}; - -typedef bool -(* GetElementsOp)(JSContext* cx, JS::HandleObject obj, uint32_t begin, uint32_t end, - ElementAdder* adder); - -typedef void -(* FinalizeOp)(FreeOp* fop, JSObject* obj); - -// The special treatment of |finalize| and |trace| is necessary because if we -// assign either of those hooks to a local variable and then call it -- as is -// done with the other hooks -- the GC hazard analysis gets confused. -#define JS_CLASS_MEMBERS(ClassOpsType, FreeOpType) \ - const char* name; \ - uint32_t flags; \ - const ClassOpsType* cOps; \ - \ - JSAddPropertyOp getAddProperty() const { return cOps ? cOps->addProperty : nullptr; } \ - JSDeletePropertyOp getDelProperty() const { return cOps ? cOps->delProperty : nullptr; } \ - JSGetterOp getGetProperty() const { return cOps ? cOps->getProperty : nullptr; } \ - JSSetterOp getSetProperty() const { return cOps ? cOps->setProperty : nullptr; } \ - JSEnumerateOp getEnumerate() const { return cOps ? cOps->enumerate : nullptr; } \ - JSResolveOp getResolve() const { return cOps ? cOps->resolve : nullptr; } \ - JSMayResolveOp getMayResolve() const { return cOps ? cOps->mayResolve : nullptr; } \ - JSNative getCall() const { return cOps ? cOps->call : nullptr; } \ - JSHasInstanceOp getHasInstance() const { return cOps ? cOps->hasInstance : nullptr; } \ - JSNative getConstruct() const { return cOps ? cOps->construct : nullptr; } \ - \ - bool hasFinalize() const { return cOps && cOps->finalize; } \ - bool hasTrace() const { return cOps && cOps->trace; } \ - \ - bool isTrace(JSTraceOp trace) const { return cOps && cOps->trace == trace; } \ - \ - void doFinalize(FreeOpType* fop, JSObject* obj) const { \ - MOZ_ASSERT(cOps && cOps->finalize); \ - cOps->finalize(fop, obj); \ - } \ - void doTrace(JSTracer* trc, JSObject* obj) const { \ - MOZ_ASSERT(cOps && cOps->trace); \ - cOps->trace(trc, obj); \ - } - -struct ClassOps -{ - /* Function pointer members (may be null). */ - JSAddPropertyOp addProperty; - JSDeletePropertyOp delProperty; - JSGetterOp getProperty; - JSSetterOp setProperty; - JSEnumerateOp enumerate; - JSResolveOp resolve; - JSMayResolveOp mayResolve; - FinalizeOp finalize; - JSNative call; - JSHasInstanceOp hasInstance; - JSNative construct; - JSTraceOp trace; -}; - -/** Callback for the creation of constructor and prototype objects. */ -typedef JSObject* (*ClassObjectCreationOp)(JSContext* cx, JSProtoKey key); - -/** Callback for custom post-processing after class initialization via ClassSpec. */ -typedef bool (*FinishClassInitOp)(JSContext* cx, JS::HandleObject ctor, - JS::HandleObject proto); - -const size_t JSCLASS_CACHED_PROTO_WIDTH = 6; - -struct ClassSpec -{ - // All properties except flags should be accessed through accessor. - ClassObjectCreationOp createConstructor_; - ClassObjectCreationOp createPrototype_; - const JSFunctionSpec* constructorFunctions_; - const JSPropertySpec* constructorProperties_; - const JSFunctionSpec* prototypeFunctions_; - const JSPropertySpec* prototypeProperties_; - FinishClassInitOp finishInit_; - uintptr_t flags; - - static const size_t ProtoKeyWidth = JSCLASS_CACHED_PROTO_WIDTH; - - static const uintptr_t ProtoKeyMask = (1 << ProtoKeyWidth) - 1; - static const uintptr_t DontDefineConstructor = 1 << ProtoKeyWidth; - static const uintptr_t IsDelegated = 1 << (ProtoKeyWidth + 1); - - bool defined() const { return !!createConstructor_; } - - bool delegated() const { - return (flags & IsDelegated); - } - - // The ProtoKey this class inherits from. - JSProtoKey inheritanceProtoKey() const { - MOZ_ASSERT(defined()); - static_assert(JSProto_Null == 0, "zeroed key must be null"); - - // Default: Inherit from Object. - if (!(flags & ProtoKeyMask)) - return JSProto_Object; - - return JSProtoKey(flags & ProtoKeyMask); - } - - bool shouldDefineConstructor() const { - MOZ_ASSERT(defined()); - return !(flags & DontDefineConstructor); - } - - const ClassSpec* delegatedClassSpec() const { - MOZ_ASSERT(delegated()); - return reinterpret_cast(createConstructor_); - } - - ClassObjectCreationOp createConstructorHook() const { - if (delegated()) - return delegatedClassSpec()->createConstructorHook(); - return createConstructor_; - } - ClassObjectCreationOp createPrototypeHook() const { - if (delegated()) - return delegatedClassSpec()->createPrototypeHook(); - return createPrototype_; - } - const JSFunctionSpec* constructorFunctions() const { - if (delegated()) - return delegatedClassSpec()->constructorFunctions(); - return constructorFunctions_; - } - const JSPropertySpec* constructorProperties() const { - if (delegated()) - return delegatedClassSpec()->constructorProperties(); - return constructorProperties_; - } - const JSFunctionSpec* prototypeFunctions() const { - if (delegated()) - return delegatedClassSpec()->prototypeFunctions(); - return prototypeFunctions_; - } - const JSPropertySpec* prototypeProperties() const { - if (delegated()) - return delegatedClassSpec()->prototypeProperties(); - return prototypeProperties_; - } - FinishClassInitOp finishInitHook() const { - if (delegated()) - return delegatedClassSpec()->finishInitHook(); - return finishInit_; - } -}; - -struct ClassExtension -{ - /** - * If an object is used as a key in a weakmap, it may be desirable for the - * garbage collector to keep that object around longer than it otherwise - * would. A common case is when the key is a wrapper around an object in - * another compartment, and we want to avoid collecting the wrapper (and - * removing the weakmap entry) as long as the wrapped object is alive. In - * that case, the wrapped object is returned by the wrapper's - * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap - * key, it will not be collected (and remain in the weakmap) until the - * wrapped object is collected. - */ - JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; - - /** - * Optional hook called when an object is moved by a compacting GC. - * - * There may exist weak pointers to an object that are not traced through - * when the normal trace APIs are used, for example objects in the wrapper - * cache. This hook allows these pointers to be updated. - * - * Note that this hook can be called before JS_NewObject() returns if a GC - * is triggered during construction of the object. This can happen for - * global objects for example. - */ - JSObjectMovedOp objectMovedOp; -}; - -inline ClassObjectCreationOp DELEGATED_CLASSSPEC(const ClassSpec* spec) { - return reinterpret_cast(const_cast(spec)); -} - -#define JS_NULL_CLASS_SPEC nullptr -#define JS_NULL_CLASS_EXT nullptr - -struct ObjectOps -{ - LookupPropertyOp lookupProperty; - DefinePropertyOp defineProperty; - HasPropertyOp hasProperty; - GetPropertyOp getProperty; - SetPropertyOp setProperty; - GetOwnPropertyOp getOwnPropertyDescriptor; - DeletePropertyOp deleteProperty; - WatchOp watch; - UnwatchOp unwatch; - GetElementsOp getElements; - JSNewEnumerateOp enumerate; - JSFunToStringOp funToString; -}; - -#define JS_NULL_OBJECT_OPS nullptr - -} // namespace js - -// Classes, objects, and properties. - -typedef void (*JSClassInternal)(); - -struct JSClassOps -{ - /* Function pointer members (may be null). */ - JSAddPropertyOp addProperty; - JSDeletePropertyOp delProperty; - JSGetterOp getProperty; - JSSetterOp setProperty; - JSEnumerateOp enumerate; - JSResolveOp resolve; - JSMayResolveOp mayResolve; - JSFinalizeOp finalize; - JSNative call; - JSHasInstanceOp hasInstance; - JSNative construct; - JSTraceOp trace; -}; - -#define JS_NULL_CLASS_OPS nullptr - -struct JSClass { - JS_CLASS_MEMBERS(JSClassOps, JSFreeOp); - - void* reserved[3]; -}; - -#define JSCLASS_HAS_PRIVATE (1<<0) // objects have private slot -#define JSCLASS_DELAY_METADATA_BUILDER (1<<1) // class's initialization code - // will call - // SetNewObjectMetadata itself -#define JSCLASS_IS_WRAPPED_NATIVE (1<<2) // class is an XPCWrappedNative. - // WeakMaps use this to override - // the wrapper disposal - // mechanism. -#define JSCLASS_PRIVATE_IS_NSISUPPORTS (1<<3) // private is (nsISupports*) -#define JSCLASS_IS_DOMJSCLASS (1<<4) // objects are DOM -#define JSCLASS_HAS_XRAYED_CONSTRUCTOR (1<<5) // if wrapped by an xray - // wrapper, the builtin - // class's constructor won't - // be unwrapped and invoked. - // Instead, the constructor is - // resolved in the caller's - // compartment and invoked - // with a wrapped newTarget. - // The constructor has to - // detect and handle this - // situation. - // See PromiseConstructor for - // details. -#define JSCLASS_EMULATES_UNDEFINED (1<<6) // objects of this class act - // like the value undefined, - // in some contexts -#define JSCLASS_USERBIT1 (1<<7) // Reserved for embeddings. - -// To reserve slots fetched and stored via JS_Get/SetReservedSlot, bitwise-or -// JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where -// n is a constant in [1, 255]. Reserved slots are indexed from 0 to n-1. -#define JSCLASS_RESERVED_SLOTS_SHIFT 8 // room for 8 flags below */ -#define JSCLASS_RESERVED_SLOTS_WIDTH 8 // and 16 above this field */ -#define JSCLASS_RESERVED_SLOTS_MASK JS_BITMASK(JSCLASS_RESERVED_SLOTS_WIDTH) -#define JSCLASS_HAS_RESERVED_SLOTS(n) (((n) & JSCLASS_RESERVED_SLOTS_MASK) \ - << JSCLASS_RESERVED_SLOTS_SHIFT) -#define JSCLASS_RESERVED_SLOTS(clasp) (((clasp)->flags \ - >> JSCLASS_RESERVED_SLOTS_SHIFT) \ - & JSCLASS_RESERVED_SLOTS_MASK) - -#define JSCLASS_HIGH_FLAGS_SHIFT (JSCLASS_RESERVED_SLOTS_SHIFT + \ - JSCLASS_RESERVED_SLOTS_WIDTH) - -#define JSCLASS_IS_ANONYMOUS (1<<(JSCLASS_HIGH_FLAGS_SHIFT+0)) -#define JSCLASS_IS_GLOBAL (1<<(JSCLASS_HIGH_FLAGS_SHIFT+1)) -#define JSCLASS_INTERNAL_FLAG2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+2)) -#define JSCLASS_INTERNAL_FLAG3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+3)) - -#define JSCLASS_IS_PROXY (1<<(JSCLASS_HIGH_FLAGS_SHIFT+4)) - -#define JSCLASS_SKIP_NURSERY_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+5)) - -// Reserved for embeddings. -#define JSCLASS_USERBIT2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+6)) -#define JSCLASS_USERBIT3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+7)) - -#define JSCLASS_BACKGROUND_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+8)) -#define JSCLASS_FOREGROUND_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+9)) - -// Bits 26 through 31 are reserved for the CACHED_PROTO_KEY mechanism, see -// below. - -// ECMA-262 requires that most constructors used internally create objects -// with "the original Foo.prototype value" as their [[Prototype]] (__proto__) -// member initial value. The "original ... value" verbiage is there because -// in ECMA-262, global properties naming class objects are read/write and -// deleteable, for the most part. -// -// Implementing this efficiently requires that global objects have classes -// with the following flags. Failure to use JSCLASS_GLOBAL_FLAGS was -// previously allowed, but is now an ES5 violation and thus unsupported. -// -// JSCLASS_GLOBAL_APPLICATION_SLOTS is the number of slots reserved at -// the beginning of every global object's slots for use by the -// application. -#define JSCLASS_GLOBAL_APPLICATION_SLOTS 5 -#define JSCLASS_GLOBAL_SLOT_COUNT \ - (JSCLASS_GLOBAL_APPLICATION_SLOTS + JSProto_LIMIT * 2 + 39) -#define JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(n) \ - (JSCLASS_IS_GLOBAL | JSCLASS_HAS_RESERVED_SLOTS(JSCLASS_GLOBAL_SLOT_COUNT + (n))) -#define JSCLASS_GLOBAL_FLAGS \ - JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(0) -#define JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(clasp) \ - (((clasp)->flags & JSCLASS_IS_GLOBAL) \ - && JSCLASS_RESERVED_SLOTS(clasp) >= JSCLASS_GLOBAL_SLOT_COUNT) - -// Fast access to the original value of each standard class's prototype. -#define JSCLASS_CACHED_PROTO_SHIFT (JSCLASS_HIGH_FLAGS_SHIFT + 10) -#define JSCLASS_CACHED_PROTO_MASK JS_BITMASK(js::JSCLASS_CACHED_PROTO_WIDTH) -#define JSCLASS_HAS_CACHED_PROTO(key) (uint32_t(key) << JSCLASS_CACHED_PROTO_SHIFT) -#define JSCLASS_CACHED_PROTO_KEY(clasp) ((JSProtoKey) \ - (((clasp)->flags \ - >> JSCLASS_CACHED_PROTO_SHIFT) \ - & JSCLASS_CACHED_PROTO_MASK)) - -// Initializer for unused members of statically initialized JSClass structs. -#define JSCLASS_NO_INTERNAL_MEMBERS {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} -#define JSCLASS_NO_OPTIONAL_MEMBERS 0,0,0,0,0,JSCLASS_NO_INTERNAL_MEMBERS - -namespace js { - -struct Class -{ - JS_CLASS_MEMBERS(js::ClassOps, FreeOp); - const ClassSpec* spec; - const ClassExtension* ext; - const ObjectOps* oOps; - - /* - * Objects of this class aren't native objects. They don't have Shapes that - * describe their properties and layout. Classes using this flag must - * provide their own property behavior, either by being proxy classes (do - * this) or by overriding all the ObjectOps except getElements, watch and - * unwatch (don't do this). - */ - static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; - - bool isNative() const { - return !(flags & NON_NATIVE); - } - - bool hasPrivate() const { - return !!(flags & JSCLASS_HAS_PRIVATE); - } - - bool emulatesUndefined() const { - return flags & JSCLASS_EMULATES_UNDEFINED; - } - - bool isJSFunction() const { - return this == js::FunctionClassPtr; - } - - bool nonProxyCallable() const { - MOZ_ASSERT(!isProxy()); - return isJSFunction() || getCall(); - } - - bool isProxy() const { - return flags & JSCLASS_IS_PROXY; - } - - bool isDOMClass() const { - return flags & JSCLASS_IS_DOMJSCLASS; - } - - bool shouldDelayMetadataBuilder() const { - return flags & JSCLASS_DELAY_METADATA_BUILDER; - } - - bool isWrappedNative() const { - return flags & JSCLASS_IS_WRAPPED_NATIVE; - } - - static size_t offsetOfFlags() { return offsetof(Class, flags); } - - bool specDefined() const { return spec ? spec->defined() : false; } - JSProtoKey specInheritanceProtoKey() - const { return spec ? spec->inheritanceProtoKey() : JSProto_Null; } - bool specShouldDefineConstructor() - const { return spec ? spec->shouldDefineConstructor() : true; } - ClassObjectCreationOp specCreateConstructorHook() - const { return spec ? spec->createConstructorHook() : nullptr; } - ClassObjectCreationOp specCreatePrototypeHook() - const { return spec ? spec->createPrototypeHook() : nullptr; } - const JSFunctionSpec* specConstructorFunctions() - const { return spec ? spec->constructorFunctions() : nullptr; } - const JSPropertySpec* specConstructorProperties() - const { return spec ? spec->constructorProperties() : nullptr; } - const JSFunctionSpec* specPrototypeFunctions() - const { return spec ? spec->prototypeFunctions() : nullptr; } - const JSPropertySpec* specPrototypeProperties() - const { return spec ? spec->prototypeProperties() : nullptr; } - FinishClassInitOp specFinishInitHook() - const { return spec ? spec->finishInitHook() : nullptr; } - - JSWeakmapKeyDelegateOp extWeakmapKeyDelegateOp() - const { return ext ? ext->weakmapKeyDelegateOp : nullptr; } - JSObjectMovedOp extObjectMovedOp() - const { return ext ? ext->objectMovedOp : nullptr; } - - LookupPropertyOp getOpsLookupProperty() const { return oOps ? oOps->lookupProperty : nullptr; } - DefinePropertyOp getOpsDefineProperty() const { return oOps ? oOps->defineProperty : nullptr; } - HasPropertyOp getOpsHasProperty() const { return oOps ? oOps->hasProperty : nullptr; } - GetPropertyOp getOpsGetProperty() const { return oOps ? oOps->getProperty : nullptr; } - SetPropertyOp getOpsSetProperty() const { return oOps ? oOps->setProperty : nullptr; } - GetOwnPropertyOp getOpsGetOwnPropertyDescriptor() - const { return oOps ? oOps->getOwnPropertyDescriptor - : nullptr; } - DeletePropertyOp getOpsDeleteProperty() const { return oOps ? oOps->deleteProperty : nullptr; } - WatchOp getOpsWatch() const { return oOps ? oOps->watch : nullptr; } - UnwatchOp getOpsUnwatch() const { return oOps ? oOps->unwatch : nullptr; } - GetElementsOp getOpsGetElements() const { return oOps ? oOps->getElements : nullptr; } - JSNewEnumerateOp getOpsEnumerate() const { return oOps ? oOps->enumerate : nullptr; } - JSFunToStringOp getOpsFunToString() const { return oOps ? oOps->funToString : nullptr; } -}; - -static_assert(offsetof(JSClassOps, addProperty) == offsetof(ClassOps, addProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, delProperty) == offsetof(ClassOps, delProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, getProperty) == offsetof(ClassOps, getProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, setProperty) == offsetof(ClassOps, setProperty), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, enumerate) == offsetof(ClassOps, enumerate), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, resolve) == offsetof(ClassOps, resolve), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, mayResolve) == offsetof(ClassOps, mayResolve), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, finalize) == offsetof(ClassOps, finalize), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, call) == offsetof(ClassOps, call), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, construct) == offsetof(ClassOps, construct), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, hasInstance) == offsetof(ClassOps, hasInstance), - "ClassOps and JSClassOps must be consistent"); -static_assert(offsetof(JSClassOps, trace) == offsetof(ClassOps, trace), - "ClassOps and JSClassOps must be consistent"); -static_assert(sizeof(JSClassOps) == sizeof(ClassOps), - "ClassOps and JSClassOps must be consistent"); - -static_assert(offsetof(JSClass, name) == offsetof(Class, name), - "Class and JSClass must be consistent"); -static_assert(offsetof(JSClass, flags) == offsetof(Class, flags), - "Class and JSClass must be consistent"); -static_assert(offsetof(JSClass, cOps) == offsetof(Class, cOps), - "Class and JSClass must be consistent"); -static_assert(sizeof(JSClass) == sizeof(Class), - "Class and JSClass must be consistent"); - -static MOZ_ALWAYS_INLINE const JSClass* -Jsvalify(const Class* c) -{ - return (const JSClass*)c; -} - -static MOZ_ALWAYS_INLINE const Class* -Valueify(const JSClass* c) -{ - return (const Class*)c; -} - -/** - * Enumeration describing possible values of the [[Class]] internal property - * value of objects. - */ -enum class ESClass { - Object, - Array, - Number, - String, - Boolean, - RegExp, - ArrayBuffer, - SharedArrayBuffer, - Date, - Set, - Map, - Promise, - MapIterator, - SetIterator, - Arguments, - Error, - - /** None of the above. */ - Other -}; - -/* Fills |vp| with the unboxed value for boxed types, or undefined otherwise. */ -bool -Unbox(JSContext* cx, JS::HandleObject obj, JS::MutableHandleValue vp); - -#ifdef DEBUG -JS_FRIEND_API(bool) -HasObjectMovedOp(JSObject* obj); -#endif - -} /* namespace js */ - -#endif /* js_Class_h */ diff --git a/win32/include/spidermonkey/js/Conversions.h b/win32/include/spidermonkey/js/Conversions.h deleted file mode 100755 index 1cee31c5..00000000 --- a/win32/include/spidermonkey/js/Conversions.h +++ /dev/null @@ -1,581 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* ECMAScript conversion operations. */ - -#ifndef js_Conversions_h -#define js_Conversions_h - -#include "mozilla/Casting.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/TypeTraits.h" - -#include - -#include "jspubtd.h" - -#include "js/RootingAPI.h" -#include "js/Value.h" - -struct JSContext; - -namespace js { - -/* DO NOT CALL THIS. Use JS::ToBoolean. */ -extern JS_PUBLIC_API(bool) -ToBooleanSlow(JS::HandleValue v); - -/* DO NOT CALL THIS. Use JS::ToNumber. */ -extern JS_PUBLIC_API(bool) -ToNumberSlow(JSContext* cx, JS::HandleValue v, double* dp); - -/* DO NOT CALL THIS. Use JS::ToInt8. */ -extern JS_PUBLIC_API(bool) -ToInt8Slow(JSContext *cx, JS::HandleValue v, int8_t *out); - -/* DO NOT CALL THIS. Use JS::ToUint8. */ -extern JS_PUBLIC_API(bool) -ToUint8Slow(JSContext *cx, JS::HandleValue v, uint8_t *out); - -/* DO NOT CALL THIS. Use JS::ToInt16. */ -extern JS_PUBLIC_API(bool) -ToInt16Slow(JSContext *cx, JS::HandleValue v, int16_t *out); - -/* DO NOT CALL THIS. Use JS::ToInt32. */ -extern JS_PUBLIC_API(bool) -ToInt32Slow(JSContext* cx, JS::HandleValue v, int32_t* out); - -/* DO NOT CALL THIS. Use JS::ToUint32. */ -extern JS_PUBLIC_API(bool) -ToUint32Slow(JSContext* cx, JS::HandleValue v, uint32_t* out); - -/* DO NOT CALL THIS. Use JS::ToUint16. */ -extern JS_PUBLIC_API(bool) -ToUint16Slow(JSContext* cx, JS::HandleValue v, uint16_t* out); - -/* DO NOT CALL THIS. Use JS::ToInt64. */ -extern JS_PUBLIC_API(bool) -ToInt64Slow(JSContext* cx, JS::HandleValue v, int64_t* out); - -/* DO NOT CALL THIS. Use JS::ToUint64. */ -extern JS_PUBLIC_API(bool) -ToUint64Slow(JSContext* cx, JS::HandleValue v, uint64_t* out); - -/* DO NOT CALL THIS. Use JS::ToString. */ -extern JS_PUBLIC_API(JSString*) -ToStringSlow(JSContext* cx, JS::HandleValue v); - -/* DO NOT CALL THIS. Use JS::ToObject. */ -extern JS_PUBLIC_API(JSObject*) -ToObjectSlow(JSContext* cx, JS::HandleValue v, bool reportScanStack); - -} // namespace js - -namespace JS { - -namespace detail { - -#ifdef JS_DEBUG -/** - * Assert that we're not doing GC on cx, that we're in a request as - * needed, and that the compartments for cx and v are correct. - * Also check that GC would be safe at this point. - */ -extern JS_PUBLIC_API(void) -AssertArgumentsAreSane(JSContext* cx, HandleValue v); -#else -inline void AssertArgumentsAreSane(JSContext* cx, HandleValue v) -{} -#endif /* JS_DEBUG */ - -} // namespace detail - -/** - * ES6 draft 20141224, 7.1.1, second algorithm. - * - * Most users shouldn't call this -- use JS::ToBoolean, ToNumber, or ToString - * instead. This will typically only be called from custom convert hooks that - * wish to fall back to the ES6 default conversion behavior shared by most - * objects in JS, codified as OrdinaryToPrimitive. - */ -extern JS_PUBLIC_API(bool) -OrdinaryToPrimitive(JSContext* cx, HandleObject obj, JSType type, MutableHandleValue vp); - -/* ES6 draft 20141224, 7.1.2. */ -MOZ_ALWAYS_INLINE bool -ToBoolean(HandleValue v) -{ - if (v.isBoolean()) - return v.toBoolean(); - if (v.isInt32()) - return v.toInt32() != 0; - if (v.isNullOrUndefined()) - return false; - if (v.isDouble()) { - double d = v.toDouble(); - return !mozilla::IsNaN(d) && d != 0; - } - if (v.isSymbol()) - return true; - - /* The slow path handles strings and objects. */ - return js::ToBooleanSlow(v); -} - -/* ES6 draft 20141224, 7.1.3. */ -MOZ_ALWAYS_INLINE bool -ToNumber(JSContext* cx, HandleValue v, double* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isNumber()) { - *out = v.toNumber(); - return true; - } - return js::ToNumberSlow(cx, v, out); -} - -/* ES6 draft 20141224, ToInteger (specialized for doubles). */ -inline double -ToInteger(double d) -{ - if (d == 0) - return d; - - if (!mozilla::IsFinite(d)) { - if (mozilla::IsNaN(d)) - return 0; - return d; - } - - return d < 0 ? ceil(d) : floor(d); -} - -/* ES6 draft 20141224, 7.1.5. */ -MOZ_ALWAYS_INLINE bool -ToInt32(JSContext* cx, JS::HandleValue v, int32_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = v.toInt32(); - return true; - } - return js::ToInt32Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.6. */ -MOZ_ALWAYS_INLINE bool -ToUint32(JSContext* cx, HandleValue v, uint32_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint32_t(v.toInt32()); - return true; - } - return js::ToUint32Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.7. */ -MOZ_ALWAYS_INLINE bool -ToInt16(JSContext *cx, JS::HandleValue v, int16_t *out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = int16_t(v.toInt32()); - return true; - } - return js::ToInt16Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.8. */ -MOZ_ALWAYS_INLINE bool -ToUint16(JSContext* cx, HandleValue v, uint16_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint16_t(v.toInt32()); - return true; - } - return js::ToUint16Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.9 */ -MOZ_ALWAYS_INLINE bool -ToInt8(JSContext *cx, JS::HandleValue v, int8_t *out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = int8_t(v.toInt32()); - return true; - } - return js::ToInt8Slow(cx, v, out); -} - -/* ES6 ECMA-262, 7.1.10 */ -MOZ_ALWAYS_INLINE bool -ToUint8(JSContext *cx, JS::HandleValue v, uint8_t *out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint8_t(v.toInt32()); - return true; - } - return js::ToUint8Slow(cx, v, out); -} - -/* - * Non-standard, with behavior similar to that of ToInt32, except in its - * producing an int64_t. - */ -MOZ_ALWAYS_INLINE bool -ToInt64(JSContext* cx, HandleValue v, int64_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = int64_t(v.toInt32()); - return true; - } - return js::ToInt64Slow(cx, v, out); -} - -/* - * Non-standard, with behavior similar to that of ToUint32, except in its - * producing a uint64_t. - */ -MOZ_ALWAYS_INLINE bool -ToUint64(JSContext* cx, HandleValue v, uint64_t* out) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isInt32()) { - *out = uint64_t(v.toInt32()); - return true; - } - return js::ToUint64Slow(cx, v, out); -} - -/* ES6 draft 20141224, 7.1.12. */ -MOZ_ALWAYS_INLINE JSString* -ToString(JSContext* cx, HandleValue v) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isString()) - return v.toString(); - return js::ToStringSlow(cx, v); -} - -/* ES6 draft 20141224, 7.1.13. */ -inline JSObject* -ToObject(JSContext* cx, HandleValue v) -{ - detail::AssertArgumentsAreSane(cx, v); - - if (v.isObject()) - return &v.toObject(); - return js::ToObjectSlow(cx, v, false); -} - -namespace detail { - -/* - * Convert a double value to ResultType (an unsigned integral type) using - * ECMAScript-style semantics (that is, in like manner to how ECMAScript's - * ToInt32 converts to int32_t). - * - * If d is infinite or NaN, return 0. - * Otherwise compute d2 = sign(d) * floor(abs(d)), and return the ResultType - * value congruent to d2 mod 2**(bit width of ResultType). - * - * The algorithm below is inspired by that found in - * - * but has been generalized to all integer widths. - */ -template -inline ResultType -ToUintWidth(double d) -{ - static_assert(mozilla::IsUnsigned::value, - "ResultType must be an unsigned type"); - - uint64_t bits = mozilla::BitwiseCast(d); - unsigned DoubleExponentShift = mozilla::FloatingPoint::kExponentShift; - - // Extract the exponent component. (Be careful here! It's not technically - // the exponent in NaN, infinities, and subnormals.) - int_fast16_t exp = - int_fast16_t((bits & mozilla::FloatingPoint::kExponentBits) >> DoubleExponentShift) - - int_fast16_t(mozilla::FloatingPoint::kExponentBias); - - // If the exponent's less than zero, abs(d) < 1, so the result is 0. (This - // also handles subnormals.) - if (exp < 0) - return 0; - - uint_fast16_t exponent = mozilla::AssertedCast(exp); - - // If the exponent is greater than or equal to the bits of precision of a - // double plus ResultType's width, the number is either infinite, NaN, or - // too large to have lower-order bits in the congruent value. (Example: - // 2**84 is exactly representable as a double. The next exact double is - // 2**84 + 2**32. Thus if ResultType is int32_t, an exponent >= 84 implies - // floor(abs(d)) == 0 mod 2**32.) Return 0 in all these cases. - const size_t ResultWidth = CHAR_BIT * sizeof(ResultType); - if (exponent >= DoubleExponentShift + ResultWidth) - return 0; - - // The significand contains the bits that will determine the final result. - // Shift those bits left or right, according to the exponent, to their - // locations in the unsigned binary representation of floor(abs(d)). - static_assert(sizeof(ResultType) <= sizeof(uint64_t), - "Left-shifting below would lose upper bits"); - ResultType result = (exponent > DoubleExponentShift) - ? ResultType(bits << (exponent - DoubleExponentShift)) - : ResultType(bits >> (DoubleExponentShift - exponent)); - - // Two further complications remain. First, |result| may contain bogus - // sign/exponent bits. Second, IEEE-754 numbers' significands (excluding - // subnormals, but we already handled those) have an implicit leading 1 - // which may affect the final result. - // - // It may appear that there's complexity here depending on how ResultWidth - // and DoubleExponentShift relate, but it turns out there's not. - // - // Assume ResultWidth < DoubleExponentShift: - // Only right-shifts leave bogus bits in |result|. For this to happen, - // we must right-shift by > |DoubleExponentShift - ResultWidth|, implying - // |exponent < ResultWidth|. - // The implicit leading bit only matters if it appears in the final - // result -- if |2**exponent mod 2**ResultWidth != 0|. This implies - // |exponent < ResultWidth|. - // Otherwise assume ResultWidth >= DoubleExponentShift: - // Any left-shift less than |ResultWidth - DoubleExponentShift| leaves - // bogus bits in |result|. This implies |exponent < ResultWidth|. Any - // right-shift less than |ResultWidth| does too, which implies - // |DoubleExponentShift - ResultWidth < exponent|. By assumption, then, - // |exponent| is negative, but we excluded that above. So bogus bits - // need only |exponent < ResultWidth|. - // The implicit leading bit matters identically to the other case, so - // again, |exponent < ResultWidth|. - if (exponent < ResultWidth) { - ResultType implicitOne = ResultType(1) << exponent; - result &= implicitOne - 1; // remove bogus bits - result += implicitOne; // add the implicit bit - } - - // Compute the congruent value in the signed range. - return (bits & mozilla::FloatingPoint::kSignBit) ? ~result + 1 : result; -} - -template -inline ResultType -ToIntWidth(double d) -{ - static_assert(mozilla::IsSigned::value, - "ResultType must be a signed type"); - - const ResultType MaxValue = (1ULL << (CHAR_BIT * sizeof(ResultType) - 1)) - 1; - const ResultType MinValue = -MaxValue - 1; - - typedef typename mozilla::MakeUnsigned::Type UnsignedResult; - UnsignedResult u = ToUintWidth(d); - if (u <= UnsignedResult(MaxValue)) - return static_cast(u); - return (MinValue + static_cast(u - MaxValue)) - 1; -} - -} // namespace detail - -/* ES5 9.5 ToInt32 (specialized for doubles). */ -inline int32_t -ToInt32(double d) -{ - // clang crashes compiling this when targeting arm: - // https://llvm.org/bugs/show_bug.cgi?id=22974 -#if defined (__arm__) && defined (__GNUC__) && !defined(__clang__) - int32_t i; - uint32_t tmp0; - uint32_t tmp1; - uint32_t tmp2; - asm ( - // We use a pure integer solution here. In the 'softfp' ABI, the argument - // will start in r0 and r1, and VFP can't do all of the necessary ECMA - // conversions by itself so some integer code will be required anyway. A - // hybrid solution is faster on A9, but this pure integer solution is - // notably faster for A8. - - // %0 is the result register, and may alias either of the %[QR]1 registers. - // %Q4 holds the lower part of the mantissa. - // %R4 holds the sign, exponent, and the upper part of the mantissa. - // %1, %2 and %3 are used as temporary values. - - // Extract the exponent. -" mov %1, %R4, LSR #20\n" -" bic %1, %1, #(1 << 11)\n" // Clear the sign. - - // Set the implicit top bit of the mantissa. This clobbers a bit of the - // exponent, but we have already extracted that. -" orr %R4, %R4, #(1 << 20)\n" - - // Special Cases - // We should return zero in the following special cases: - // - Exponent is 0x000 - 1023: +/-0 or subnormal. - // - Exponent is 0x7ff - 1023: +/-INFINITY or NaN - // - This case is implicitly handled by the standard code path anyway, - // as shifting the mantissa up by the exponent will result in '0'. - // - // The result is composed of the mantissa, prepended with '1' and - // bit-shifted left by the (decoded) exponent. Note that because the r1[20] - // is the bit with value '1', r1 is effectively already shifted (left) by - // 20 bits, and r0 is already shifted by 52 bits. - - // Adjust the exponent to remove the encoding offset. If the decoded - // exponent is negative, quickly bail out with '0' as such values round to - // zero anyway. This also catches +/-0 and subnormals. -" sub %1, %1, #0xff\n" -" subs %1, %1, #0x300\n" -" bmi 8f\n" - - // %1 = (decoded) exponent >= 0 - // %R4 = upper mantissa and sign - - // ---- Lower Mantissa ---- -" subs %3, %1, #52\n" // Calculate exp-52 -" bmi 1f\n" - - // Shift r0 left by exp-52. - // Ensure that we don't overflow ARM's 8-bit shift operand range. - // We need to handle anything up to an 11-bit value here as we know that - // 52 <= exp <= 1024 (0x400). Any shift beyond 31 bits results in zero - // anyway, so as long as we don't touch the bottom 5 bits, we can use - // a logical OR to push long shifts into the 32 <= (exp&0xff) <= 255 range. -" bic %2, %3, #0xff\n" -" orr %3, %3, %2, LSR #3\n" - // We can now perform a straight shift, avoiding the need for any - // conditional instructions or extra branches. -" mov %Q4, %Q4, LSL %3\n" -" b 2f\n" -"1:\n" // Shift r0 right by 52-exp. - // We know that 0 <= exp < 52, and we can shift up to 255 bits so 52-exp - // will always be a valid shift and we can sk%3 the range check for this case. -" rsb %3, %1, #52\n" -" mov %Q4, %Q4, LSR %3\n" - - // %1 = (decoded) exponent - // %R4 = upper mantissa and sign - // %Q4 = partially-converted integer - -"2:\n" - // ---- Upper Mantissa ---- - // This is much the same as the lower mantissa, with a few different - // boundary checks and some masking to hide the exponent & sign bit in the - // upper word. - // Note that the upper mantissa is pre-shifted by 20 in %R4, but we shift - // it left more to remove the sign and exponent so it is effectively - // pre-shifted by 31 bits. -" subs %3, %1, #31\n" // Calculate exp-31 -" mov %1, %R4, LSL #11\n" // Re-use %1 as a temporary register. -" bmi 3f\n" - - // Shift %R4 left by exp-31. - // Avoid overflowing the 8-bit shift range, as before. -" bic %2, %3, #0xff\n" -" orr %3, %3, %2, LSR #3\n" - // Perform the shift. -" mov %2, %1, LSL %3\n" -" b 4f\n" -"3:\n" // Shift r1 right by 31-exp. - // We know that 0 <= exp < 31, and we can shift up to 255 bits so 31-exp - // will always be a valid shift and we can skip the range check for this case. -" rsb %3, %3, #0\n" // Calculate 31-exp from -(exp-31) -" mov %2, %1, LSR %3\n" // Thumb-2 can't do "LSR %3" in "orr". - - // %Q4 = partially-converted integer (lower) - // %R4 = upper mantissa and sign - // %2 = partially-converted integer (upper) - -"4:\n" - // Combine the converted parts. -" orr %Q4, %Q4, %2\n" - // Negate the result if we have to, and move it to %0 in the process. To - // avoid conditionals, we can do this by inverting on %R4[31], then adding - // %R4[31]>>31. -" eor %Q4, %Q4, %R4, ASR #31\n" -" add %0, %Q4, %R4, LSR #31\n" -" b 9f\n" -"8:\n" - // +/-INFINITY, +/-0, subnormals, NaNs, and anything else out-of-range that - // will result in a conversion of '0'. -" mov %0, #0\n" -"9:\n" - : "=r" (i), "=&r" (tmp0), "=&r" (tmp1), "=&r" (tmp2), "=&r" (d) - : "4" (d) - : "cc" - ); - return i; -#else - return detail::ToIntWidth(d); -#endif -} - -/* ES5 9.6 (specialized for doubles). */ -inline uint32_t -ToUint32(double d) -{ - return detail::ToUintWidth(d); -} - -/* WEBIDL 4.2.4 */ -inline int8_t -ToInt8(double d) -{ - return detail::ToIntWidth(d); -} - -/* ECMA-262 7.1.10 ToUInt8() specialized for doubles. */ -inline int8_t -ToUint8(double d) -{ - return detail::ToUintWidth(d); -} - -/* WEBIDL 4.2.6 */ -inline int16_t -ToInt16(double d) -{ - return detail::ToIntWidth(d); -} - -inline uint16_t -ToUint16(double d) -{ - return detail::ToUintWidth(d); -} - -/* WEBIDL 4.2.10 */ -inline int64_t -ToInt64(double d) -{ - return detail::ToIntWidth(d); -} - -/* WEBIDL 4.2.11 */ -inline uint64_t -ToUint64(double d) -{ - return detail::ToUintWidth(d); -} - -} // namespace JS - -#endif /* js_Conversions_h */ diff --git a/win32/include/spidermonkey/js/Date.h b/win32/include/spidermonkey/js/Date.h deleted file mode 100755 index cba0ea87..00000000 --- a/win32/include/spidermonkey/js/Date.h +++ /dev/null @@ -1,170 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JavaScript date/time computation and creation functions. */ - -#ifndef js_Date_h -#define js_Date_h - -/* - * Dates in JavaScript are defined by IEEE-754 double precision numbers from - * the set: - * - * { t ∈ ℕ : -8.64e15 ≤ t ≤ +8.64e15 } ∪ { NaN } - * - * The single NaN value represents any invalid-date value. All other values - * represent idealized durations in milliseconds since the UTC epoch. (Leap - * seconds are ignored; leap days are not.) +0 is the only zero in this set. - * The limit represented by 8.64e15 milliseconds is 100 million days either - * side of 00:00 January 1, 1970 UTC. - * - * Dates in the above set are represented by the |ClippedTime| class. The - * double type is a superset of the above set, so it *may* (but need not) - * represent a date. Use ECMAScript's |TimeClip| method to produce a date from - * a double. - * - * Date *objects* are simply wrappers around |TimeClip|'d numbers, with a bunch - * of accessor methods to the various aspects of the represented date. - */ - -#include "mozilla/FloatingPoint.h" -#include "mozilla/MathAlgorithms.h" - -#include "js/Conversions.h" -#include "js/Value.h" - -struct JSContext; - -namespace JS { - -/** - * Re-query the system to determine the current time zone adjustment from UTC, - * including any component due to DST. If the time zone has changed, this will - * cause all Date object non-UTC methods and formatting functions to produce - * appropriately adjusted results. - * - * Left to its own devices, SpiderMonkey itself may occasionally call this - * method to attempt to keep up with system time changes. However, no - * particular frequency of checking is guaranteed. Embedders unable to accept - * occasional inaccuracies should call this method in response to system time - * changes, or immediately before operations requiring instantaneous - * correctness, to guarantee correct behavior. - */ -extern JS_PUBLIC_API(void) -ResetTimeZone(); - -class ClippedTime; -inline ClippedTime TimeClip(double time); - -/* - * |ClippedTime| represents the limited subset of dates/times described above. - * - * An invalid date/time may be created through the |ClippedTime::invalid| - * method. Otherwise, a |ClippedTime| may be created using the |TimeClip| - * method. - * - * In typical use, the user might wish to manipulate a timestamp. The user - * performs a series of operations on it, but the final value might not be a - * date as defined above -- it could have overflowed, acquired a fractional - * component, &c. So as a *final* step, the user passes that value through - * |TimeClip| to produce a number restricted to JavaScript's date range. - * - * APIs that accept a JavaScript date value thus accept a |ClippedTime|, not a - * double. This ensures that date/time APIs will only ever receive acceptable - * JavaScript dates. This also forces users to perform any desired clipping, - * as only the user knows what behavior is desired when clipping occurs. - */ -class ClippedTime -{ - double t; - - explicit ClippedTime(double time) : t(time) {} - friend ClippedTime TimeClip(double time); - - public: - // Create an invalid date. - ClippedTime() : t(mozilla::UnspecifiedNaN()) {} - - // Create an invalid date/time, more explicitly; prefer this to the default - // constructor. - static ClippedTime invalid() { return ClippedTime(); } - - double toDouble() const { return t; } - - bool isValid() const { return !mozilla::IsNaN(t); } -}; - -// ES6 20.3.1.15. -// -// Clip a double to JavaScript's date range (or to an invalid date) using the -// ECMAScript TimeClip algorithm. -inline ClippedTime -TimeClip(double time) -{ - // Steps 1-2. - const double MaxTimeMagnitude = 8.64e15; - if (!mozilla::IsFinite(time) || mozilla::Abs(time) > MaxTimeMagnitude) - return ClippedTime(mozilla::UnspecifiedNaN()); - - // Step 3. - return ClippedTime(ToInteger(time) + (+0.0)); -} - -// Produce a double Value from the given time. Because times may be NaN, -// prefer using this to manual canonicalization. -inline Value -TimeValue(ClippedTime time) -{ - return DoubleValue(JS::CanonicalizeNaN(time.toDouble())); -} - -// Create a new Date object whose [[DateValue]] internal slot contains the -// clipped |time|. (Users who must represent times outside that range must use -// another representation.) -extern JS_PUBLIC_API(JSObject*) -NewDateObject(JSContext* cx, ClippedTime time); - -// Year is a year, month is 0-11, day is 1-based. The return value is a number -// of milliseconds since the epoch. -// -// Consistent with the MakeDate algorithm defined in ECMAScript, this value is -// *not* clipped! Use JS::TimeClip if you need a clipped date. -JS_PUBLIC_API(double) -MakeDate(double year, unsigned month, unsigned day); - -// Takes an integer number of milliseconds since the epoch and returns the -// year. Can return NaN, and will do so if NaN is passed in. -JS_PUBLIC_API(double) -YearFromTime(double time); - -// Takes an integer number of milliseconds since the epoch and returns the -// month (0-11). Can return NaN, and will do so if NaN is passed in. -JS_PUBLIC_API(double) -MonthFromTime(double time); - -// Takes an integer number of milliseconds since the epoch and returns the -// day (1-based). Can return NaN, and will do so if NaN is passed in. -JS_PUBLIC_API(double) -DayFromTime(double time); - -// Takes an integer year and returns the number of days from epoch to the given -// year. -// NOTE: The calculation performed by this function is literally that given in -// the ECMAScript specification. Nonfinite years, years containing fractional -// components, and years outside ECMAScript's date range are not handled with -// any particular intelligence. Garbage in, garbage out. -JS_PUBLIC_API(double) -DayFromYear(double year); - -// Takes an integer number of milliseconds since the epoch and an integer year, -// returns the number of days in that year. If |time| is nonfinite, returns NaN. -// Otherwise |time| *must* correspond to a time within the valid year |year|. -// This should usually be ensured by computing |year| as |JS::DayFromYear(time)|. -JS_PUBLIC_API(double) -DayWithinYear(double time, double year); - -} // namespace JS - -#endif /* js_Date_h */ diff --git a/win32/include/spidermonkey/js/Debug.h b/win32/include/spidermonkey/js/Debug.h deleted file mode 100755 index 3e4183f0..00000000 --- a/win32/include/spidermonkey/js/Debug.h +++ /dev/null @@ -1,384 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// Interfaces by which the embedding can interact with the Debugger API. - -#ifndef js_Debug_h -#define js_Debug_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/MemoryReporting.h" - -#include "jsapi.h" -#include "jspubtd.h" - -#include "js/GCAPI.h" -#include "js/RootingAPI.h" -#include "js/TypeDecls.h" - -namespace js { -class Debugger; -} // namespace js - -namespace JS { -namespace dbg { - -// Helping embedding code build objects for Debugger -// ------------------------------------------------- -// -// Some Debugger API features lean on the embedding application to construct -// their result values. For example, Debugger.Frame.prototype.scriptEntryReason -// calls hooks provided by the embedding to construct values explaining why it -// invoked JavaScript; if F is a frame called from a mouse click event handler, -// F.scriptEntryReason would return an object of the form: -// -// { eventType: "mousedown", event: } -// -// where is a Debugger.Object whose referent is the event being -// dispatched. -// -// However, Debugger implements a trust boundary. Debuggee code may be -// considered untrusted; debugger code needs to be protected from debuggee -// getters, setters, proxies, Object.watch watchpoints, and any other feature -// that might accidentally cause debugger code to set the debuggee running. The -// Debugger API tries to make it easy to write safe debugger code by only -// offering access to debuggee objects via Debugger.Object instances, which -// ensure that only those operations whose explicit purpose is to invoke -// debuggee code do so. But this protective membrane is only helpful if we -// interpose Debugger.Object instances in all the necessary spots. -// -// SpiderMonkey's compartment system also implements a trust boundary. The -// debuggee and debugger are always in different compartments. Inter-compartment -// work requires carefully tracking which compartment each JSObject or JS::Value -// belongs to, and ensuring that is is correctly wrapped for each operation. -// -// It seems precarious to expect the embedding's hooks to implement these trust -// boundaries. Instead, the JS::dbg::Builder API segregates the code which -// constructs trusted objects from that which deals with untrusted objects. -// Trusted objects have an entirely different C++ type, so code that improperly -// mixes trusted and untrusted objects is caught at compile time. -// -// In the structure shown above, there are two trusted objects, and one -// untrusted object: -// -// - The overall object, with the 'eventType' and 'event' properties, is a -// trusted object. We're going to return it to D.F.p.scriptEntryReason's -// caller, which will handle it directly. -// -// - The Debugger.Object instance appearing as the value of the 'event' property -// is a trusted object. It belongs to the same Debugger instance as the -// Debugger.Frame instance whose scriptEntryReason accessor was called, and -// presents a safe reflection-oriented API for inspecting its referent, which -// is: -// -// - The actual event object, an untrusted object, and the referent of the -// Debugger.Object above. (Content can do things like replacing accessors on -// Event.prototype.) -// -// Using JS::dbg::Builder, all objects and values the embedding deals with -// directly are considered untrusted, and are assumed to be debuggee values. The -// only way to construct trusted objects is to use Builder's own methods, which -// return a separate Object type. The only way to set a property on a trusted -// object is through that Object type. The actual trusted object is never -// exposed to the embedding. -// -// So, for example, the embedding might use code like the following to construct -// the object shown above, given a Builder passed to it by Debugger: -// -// bool -// MyScriptEntryReason::explain(JSContext* cx, -// Builder& builder, -// Builder::Object& result) -// { -// JSObject* eventObject = ... obtain debuggee event object somehow ...; -// if (!eventObject) -// return false; -// result = builder.newObject(cx); -// return result && -// result.defineProperty(cx, "eventType", SafelyFetchType(eventObject)) && -// result.defineProperty(cx, "event", eventObject); -// } -// -// -// Object::defineProperty also accepts an Object as the value to store on the -// property. By its type, we know that the value is trusted, so we set it -// directly as the property's value, without interposing a Debugger.Object -// wrapper. This allows the embedding to builted nested structures of trusted -// objects. -// -// The Builder and Builder::Object methods take care of doing whatever -// compartment switching and wrapping are necessary to construct the trusted -// values in the Debugger's compartment. -// -// The Object type is self-rooting. Construction, assignment, and destruction -// all properly root the referent object. - -class BuilderOrigin; - -class Builder { - // The Debugger instance whose client we are building a value for. We build - // objects in this object's compartment. - PersistentRootedObject debuggerObject; - - // debuggerObject's Debugger structure, for convenience. - js::Debugger* debugger; - - // Check that |thing| is in the same compartment as our debuggerObject. Used - // for assertions when constructing BuiltThings. We can overload this as we - // add more instantiations of BuiltThing. -#if DEBUG - void assertBuilt(JSObject* obj); -#else - void assertBuilt(JSObject* obj) { } -#endif - - protected: - // A reference to a trusted object or value. At the moment, we only use it - // with JSObject*. - template - class BuiltThing { - friend class BuilderOrigin; - - protected: - // The Builder to which this trusted thing belongs. - Builder& owner; - - // A rooted reference to our value. - PersistentRooted value; - - BuiltThing(JSContext* cx, Builder& owner_, T value_ = GCPolicy::initial()) - : owner(owner_), value(cx, value_) - { - owner.assertBuilt(value_); - } - - // Forward some things from our owner, for convenience. - js::Debugger* debugger() const { return owner.debugger; } - JSObject* debuggerObject() const { return owner.debuggerObject; } - - public: - BuiltThing(const BuiltThing& rhs) : owner(rhs.owner), value(rhs.value) { } - BuiltThing& operator=(const BuiltThing& rhs) { - MOZ_ASSERT(&owner == &rhs.owner); - owner.assertBuilt(rhs.value); - value = rhs.value; - return *this; - } - - explicit operator bool() const { - // If we ever instantiate BuiltThing, this might not suffice. - return value; - } - - private: - BuiltThing() = delete; - }; - - public: - // A reference to a trusted object, possibly null. Instances of Object are - // always properly rooted. They can be copied and assigned, as if they were - // pointers. - class Object: private BuiltThing { - friend class Builder; // for construction - friend class BuilderOrigin; // for unwrapping - - typedef BuiltThing Base; - - // This is private, because only Builders can create Objects that - // actually point to something (hence the 'friend' declaration). - Object(JSContext* cx, Builder& owner_, HandleObject obj) : Base(cx, owner_, obj.get()) { } - - bool definePropertyToTrusted(JSContext* cx, const char* name, - JS::MutableHandleValue value); - - public: - Object(JSContext* cx, Builder& owner_) : Base(cx, owner_, nullptr) { } - Object(const Object& rhs) : Base(rhs) { } - - // Our automatically-generated assignment operator can see our base - // class's assignment operator, so we don't need to write one out here. - - // Set the property named |name| on this object to |value|. - // - // If |value| is a string or primitive, re-wrap it for the debugger's - // compartment. - // - // If |value| is an object, assume it is a debuggee object and make a - // Debugger.Object instance referring to it. Set that as the propery's - // value. - // - // If |value| is another trusted object, store it directly as the - // property's value. - // - // On error, report the problem on cx and return false. - bool defineProperty(JSContext* cx, const char* name, JS::HandleValue value); - bool defineProperty(JSContext* cx, const char* name, JS::HandleObject value); - bool defineProperty(JSContext* cx, const char* name, Object& value); - - using Base::operator bool; - }; - - // Build an empty object for direct use by debugger code, owned by this - // Builder. If an error occurs, report it on cx and return a false Object. - Object newObject(JSContext* cx); - - protected: - Builder(JSContext* cx, js::Debugger* debugger); -}; - -// Debugger itself instantiates this subclass of Builder, which can unwrap -// BuiltThings that belong to it. -class BuilderOrigin : public Builder { - template - T unwrapAny(const BuiltThing& thing) { - MOZ_ASSERT(&thing.owner == this); - return thing.value.get(); - } - - public: - BuilderOrigin(JSContext* cx, js::Debugger* debugger_) - : Builder(cx, debugger_) - { } - - JSObject* unwrap(Object& object) { return unwrapAny(object); } -}; - - - -// Finding the size of blocks allocated with malloc -// ------------------------------------------------ -// -// Debugger.Memory wants to be able to report how many bytes items in memory are -// consuming. To do this, it needs a function that accepts a pointer to a block, -// and returns the number of bytes allocated to that block. SpiderMonkey itself -// doesn't know which function is appropriate to use, but the embedding does. - -// Tell Debuggers in |cx| to use |mallocSizeOf| to find the size of -// malloc'd blocks. -JS_PUBLIC_API(void) -SetDebuggerMallocSizeOf(JSContext* cx, mozilla::MallocSizeOf mallocSizeOf); - -// Get the MallocSizeOf function that the given context is using to find the -// size of malloc'd blocks. -JS_PUBLIC_API(mozilla::MallocSizeOf) -GetDebuggerMallocSizeOf(JSContext* cx); - - - -// Debugger and Garbage Collection Events -// -------------------------------------- -// -// The Debugger wants to report about its debuggees' GC cycles, however entering -// JS after a GC is troublesome since SpiderMonkey will often do something like -// force a GC and then rely on the nursery being empty. If we call into some -// Debugger's hook after the GC, then JS runs and the nursery won't be -// empty. Instead, we rely on embedders to call back into SpiderMonkey after a -// GC and notify Debuggers to call their onGarbageCollection hook. - - -// For each Debugger that observed a debuggee involved in the given GC event, -// call its `onGarbageCollection` hook. -JS_PUBLIC_API(bool) -FireOnGarbageCollectionHook(JSContext* cx, GarbageCollectionEvent::Ptr&& data); - - - -// Handlers for observing Promises -// ------------------------------- -// -// The Debugger wants to observe behavior of promises, which are implemented by -// Gecko with webidl and which SpiderMonkey knows nothing about. On the other -// hand, Gecko knows nothing about which (if any) debuggers are observing a -// promise's global. The compromise is that Gecko is responsible for calling -// these handlers at the appropriate times, and SpiderMonkey will handle -// notifying any Debugger instances that are observing the given promise's -// global. - -// Notify any Debugger instances observing this promise's global that a new -// promise was allocated. -JS_PUBLIC_API(void) -onNewPromise(JSContext* cx, HandleObject promise); - -// Notify any Debugger instances observing this promise's global that the -// promise has settled (ie, it has either been fulfilled or rejected). Note that -// this is *not* equivalent to the promise resolution (ie, the promise's fate -// getting locked in) because you can resolve a promise with another pending -// promise, in which case neither promise has settled yet. -// -// It is Gecko's responsibility to ensure that this is never called on the same -// promise more than once (because a promise can only make the transition from -// unsettled to settled once). -JS_PUBLIC_API(void) -onPromiseSettled(JSContext* cx, HandleObject promise); - - - -// Return true if the given value is a Debugger object, false otherwise. -JS_PUBLIC_API(bool) -IsDebugger(JSObject& obj); - -// Append each of the debuggee global objects observed by the Debugger object -// |dbgObj| to |vector|. Returns true on success, false on failure. -JS_PUBLIC_API(bool) -GetDebuggeeGlobals(JSContext* cx, JSObject& dbgObj, AutoObjectVector& vector); - - -// Hooks for reporting where JavaScript execution began. -// -// Our performance tools would like to be able to label blocks of JavaScript -// execution with the function name and source location where execution began: -// the event handler, the callback, etc. -// -// Construct an instance of this class on the stack, providing a JSContext -// belonging to the runtime in which execution will occur. Each time we enter -// JavaScript --- specifically, each time we push a JavaScript stack frame that -// has no older JS frames younger than this AutoEntryMonitor --- we will -// call the appropriate |Entry| member function to indicate where we've begun -// execution. - -class MOZ_STACK_CLASS AutoEntryMonitor { - JSRuntime* runtime_; - AutoEntryMonitor* savedMonitor_; - - public: - explicit AutoEntryMonitor(JSContext* cx); - ~AutoEntryMonitor(); - - // SpiderMonkey reports the JavaScript entry points occuring within this - // AutoEntryMonitor's scope to the following member functions, which the - // embedding is expected to override. - // - // It is important to note that |asyncCause| is owned by the caller and its - // lifetime must outlive the lifetime of the AutoEntryMonitor object. It is - // strongly encouraged that |asyncCause| be a string constant or similar - // statically allocated string. - - // We have begun executing |function|. Note that |function| may not be the - // actual closure we are running, but only the canonical function object to - // which the script refers. - virtual void Entry(JSContext* cx, JSFunction* function, - HandleValue asyncStack, - const char* asyncCause) = 0; - - // Execution has begun at the entry point of |script|, which is not a - // function body. (This is probably being executed by 'eval' or some - // JSAPI equivalent.) - virtual void Entry(JSContext* cx, JSScript* script, - HandleValue asyncStack, - const char* asyncCause) = 0; - - // Execution of the function or script has ended. - virtual void Exit(JSContext* cx) { } -}; - - - -} // namespace dbg -} // namespace JS - - -#endif /* js_Debug_h */ diff --git a/win32/include/spidermonkey/js/GCAPI.h b/win32/include/spidermonkey/js/GCAPI.h deleted file mode 100755 index 7a6675ca..00000000 --- a/win32/include/spidermonkey/js/GCAPI.h +++ /dev/null @@ -1,723 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCAPI_h -#define js_GCAPI_h - -#include "mozilla/Vector.h" - -#include "js/GCAnnotations.h" -#include "js/HeapAPI.h" -#include "js/UniquePtr.h" - -namespace js { -namespace gc { -class GCRuntime; -} // namespace gc -namespace gcstats { -struct Statistics; -} // namespace gcstats -} // namespace js - -typedef enum JSGCMode { - /** Perform only global GCs. */ - JSGC_MODE_GLOBAL = 0, - - /** Perform per-zone GCs until too much garbage has accumulated. */ - JSGC_MODE_ZONE = 1, - - /** - * Collect in short time slices rather than all at once. Implies - * JSGC_MODE_ZONE. - */ - JSGC_MODE_INCREMENTAL = 2 -} JSGCMode; - -/** - * Kinds of js_GC invocation. - */ -typedef enum JSGCInvocationKind { - /* Normal invocation. */ - GC_NORMAL = 0, - - /* Minimize GC triggers and release empty GC chunks right away. */ - GC_SHRINK = 1 -} JSGCInvocationKind; - -namespace JS { - -#define GCREASONS(D) \ - /* Reasons internal to the JS engine */ \ - D(API) \ - D(EAGER_ALLOC_TRIGGER) \ - D(DESTROY_RUNTIME) \ - D(UNUSED0) \ - D(LAST_DITCH) \ - D(TOO_MUCH_MALLOC) \ - D(ALLOC_TRIGGER) \ - D(DEBUG_GC) \ - D(COMPARTMENT_REVIVED) \ - D(RESET) \ - D(OUT_OF_NURSERY) \ - D(EVICT_NURSERY) \ - D(FULL_STORE_BUFFER) \ - D(SHARED_MEMORY_LIMIT) \ - D(UNUSED1) \ - D(INCREMENTAL_TOO_SLOW) \ - D(ABORT_GC) \ - \ - /* These are reserved for future use. */ \ - D(RESERVED0) \ - D(RESERVED1) \ - D(RESERVED2) \ - D(RESERVED3) \ - D(RESERVED4) \ - D(RESERVED5) \ - D(RESERVED6) \ - D(RESERVED7) \ - D(RESERVED8) \ - D(RESERVED9) \ - D(RESERVED10) \ - D(RESERVED11) \ - D(RESERVED12) \ - D(RESERVED13) \ - D(RESERVED14) \ - D(RESERVED15) \ - \ - /* Reasons from Firefox */ \ - D(DOM_WINDOW_UTILS) \ - D(COMPONENT_UTILS) \ - D(MEM_PRESSURE) \ - D(CC_WAITING) \ - D(CC_FORCED) \ - D(LOAD_END) \ - D(POST_COMPARTMENT) \ - D(PAGE_HIDE) \ - D(NSJSCONTEXT_DESTROY) \ - D(SET_NEW_DOCUMENT) \ - D(SET_DOC_SHELL) \ - D(DOM_UTILS) \ - D(DOM_IPC) \ - D(DOM_WORKER) \ - D(INTER_SLICE_GC) \ - D(REFRESH_FRAME) \ - D(FULL_GC_TIMER) \ - D(SHUTDOWN_CC) \ - D(FINISH_LARGE_EVALUATE) \ - D(USER_INACTIVE) \ - D(XPCONNECT_SHUTDOWN) - -namespace gcreason { - -/* GCReasons will end up looking like JSGC_MAYBEGC */ -enum Reason { -#define MAKE_REASON(name) name, - GCREASONS(MAKE_REASON) -#undef MAKE_REASON - NO_REASON, - NUM_REASONS, - - /* - * For telemetry, we want to keep a fixed max bucket size over time so we - * don't have to switch histograms. 100 is conservative; as of this writing - * there are 52. But the cost of extra buckets seems to be low while the - * cost of switching histograms is high. - */ - NUM_TELEMETRY_REASONS = 100 -}; - -/** - * Get a statically allocated C string explaining the given GC reason. - */ -extern JS_PUBLIC_API(const char*) -ExplainReason(JS::gcreason::Reason reason); - -} /* namespace gcreason */ - -/* - * Zone GC: - * - * SpiderMonkey's GC is capable of performing a collection on an arbitrary - * subset of the zones in the system. This allows an embedding to minimize - * collection time by only collecting zones that have run code recently, - * ignoring the parts of the heap that are unlikely to have changed. - * - * When triggering a GC using one of the functions below, it is first necessary - * to select the zones to be collected. To do this, you can call - * PrepareZoneForGC on each zone, or you can call PrepareForFullGC to select - * all zones. Failing to select any zone is an error. - */ - -/** - * Schedule the given zone to be collected as part of the next GC. - */ -extern JS_PUBLIC_API(void) -PrepareZoneForGC(Zone* zone); - -/** - * Schedule all zones to be collected in the next GC. - */ -extern JS_PUBLIC_API(void) -PrepareForFullGC(JSContext* cx); - -/** - * When performing an incremental GC, the zones that were selected for the - * previous incremental slice must be selected in subsequent slices as well. - * This function selects those slices automatically. - */ -extern JS_PUBLIC_API(void) -PrepareForIncrementalGC(JSContext* cx); - -/** - * Returns true if any zone in the system has been scheduled for GC with one of - * the functions above or by the JS engine. - */ -extern JS_PUBLIC_API(bool) -IsGCScheduled(JSContext* cx); - -/** - * Undoes the effect of the Prepare methods above. The given zone will not be - * collected in the next GC. - */ -extern JS_PUBLIC_API(void) -SkipZoneForGC(Zone* zone); - -/* - * Non-Incremental GC: - * - * The following functions perform a non-incremental GC. - */ - -/** - * Performs a non-incremental collection of all selected zones. - * - * If the gckind argument is GC_NORMAL, then some objects that are unreachable - * from the program may still be alive afterwards because of internal - * references; if GC_SHRINK is passed then caches and other temporary references - * to objects will be cleared and all unreferenced objects will be removed from - * the system. - */ -extern JS_PUBLIC_API(void) -GCForReason(JSContext* cx, JSGCInvocationKind gckind, gcreason::Reason reason); - -/* - * Incremental GC: - * - * Incremental GC divides the full mark-and-sweep collection into multiple - * slices, allowing client JavaScript code to run between each slice. This - * allows interactive apps to avoid long collection pauses. Incremental GC does - * not make collection take less time, it merely spreads that time out so that - * the pauses are less noticable. - * - * For a collection to be carried out incrementally the following conditions - * must be met: - * - The collection must be run by calling JS::IncrementalGC() rather than - * JS_GC(). - * - The GC mode must have been set to JSGC_MODE_INCREMENTAL with - * JS_SetGCParameter(). - * - * Note: Even if incremental GC is enabled and working correctly, - * non-incremental collections can still happen when low on memory. - */ - -/** - * Begin an incremental collection and perform one slice worth of work. When - * this function returns, the collection may not be complete. - * IncrementalGCSlice() must be called repeatedly until - * !IsIncrementalGCInProgress(cx). - * - * Note: SpiderMonkey's GC is not realtime. Slices in practice may be longer or - * shorter than the requested interval. - */ -extern JS_PUBLIC_API(void) -StartIncrementalGC(JSContext* cx, JSGCInvocationKind gckind, gcreason::Reason reason, - int64_t millis = 0); - -/** - * Perform a slice of an ongoing incremental collection. When this function - * returns, the collection may not be complete. It must be called repeatedly - * until !IsIncrementalGCInProgress(cx). - * - * Note: SpiderMonkey's GC is not realtime. Slices in practice may be longer or - * shorter than the requested interval. - */ -extern JS_PUBLIC_API(void) -IncrementalGCSlice(JSContext* cx, gcreason::Reason reason, int64_t millis = 0); - -/** - * If IsIncrementalGCInProgress(cx), this call finishes the ongoing collection - * by performing an arbitrarily long slice. If !IsIncrementalGCInProgress(cx), - * this is equivalent to GCForReason. When this function returns, - * IsIncrementalGCInProgress(cx) will always be false. - */ -extern JS_PUBLIC_API(void) -FinishIncrementalGC(JSContext* cx, gcreason::Reason reason); - -/** - * If IsIncrementalGCInProgress(cx), this call aborts the ongoing collection and - * performs whatever work needs to be done to return the collector to its idle - * state. This may take an arbitrarily long time. When this function returns, - * IsIncrementalGCInProgress(cx) will always be false. - */ -extern JS_PUBLIC_API(void) -AbortIncrementalGC(JSContext* cx); - -namespace dbg { - -// The `JS::dbg::GarbageCollectionEvent` class is essentially a view of the -// `js::gcstats::Statistics` data without the uber implementation-specific bits. -// It should generally be palatable for web developers. -class GarbageCollectionEvent -{ - // The major GC number of the GC cycle this data pertains to. - uint64_t majorGCNumber_; - - // Reference to a non-owned, statically allocated C string. This is a very - // short reason explaining why a GC was triggered. - const char* reason; - - // Reference to a nullable, non-owned, statically allocated C string. If the - // collection was forced to be non-incremental, this is a short reason of - // why the GC could not perform an incremental collection. - const char* nonincrementalReason; - - // Represents a single slice of a possibly multi-slice incremental garbage - // collection. - struct Collection { - double startTimestamp; - double endTimestamp; - }; - - // The set of garbage collection slices that made up this GC cycle. - mozilla::Vector collections; - - GarbageCollectionEvent(const GarbageCollectionEvent& rhs) = delete; - GarbageCollectionEvent& operator=(const GarbageCollectionEvent& rhs) = delete; - - public: - explicit GarbageCollectionEvent(uint64_t majorGCNum) - : majorGCNumber_(majorGCNum) - , reason(nullptr) - , nonincrementalReason(nullptr) - , collections() - { } - - using Ptr = js::UniquePtr; - static Ptr Create(JSRuntime* rt, ::js::gcstats::Statistics& stats, uint64_t majorGCNumber); - - JSObject* toJSObject(JSContext* cx) const; - - uint64_t majorGCNumber() const { return majorGCNumber_; } -}; - -} // namespace dbg - -enum GCProgress { - /* - * During non-incremental GC, the GC is bracketed by JSGC_CYCLE_BEGIN/END - * callbacks. During an incremental GC, the sequence of callbacks is as - * follows: - * JSGC_CYCLE_BEGIN, JSGC_SLICE_END (first slice) - * JSGC_SLICE_BEGIN, JSGC_SLICE_END (second slice) - * ... - * JSGC_SLICE_BEGIN, JSGC_CYCLE_END (last slice) - */ - - GC_CYCLE_BEGIN, - GC_SLICE_BEGIN, - GC_SLICE_END, - GC_CYCLE_END -}; - -struct JS_PUBLIC_API(GCDescription) { - bool isZone_; - JSGCInvocationKind invocationKind_; - gcreason::Reason reason_; - - GCDescription(bool isZone, JSGCInvocationKind kind, gcreason::Reason reason) - : isZone_(isZone), invocationKind_(kind), reason_(reason) {} - - char16_t* formatSliceMessage(JSContext* cx) const; - char16_t* formatSummaryMessage(JSContext* cx) const; - char16_t* formatJSON(JSContext* cx, uint64_t timestamp) const; - - JS::dbg::GarbageCollectionEvent::Ptr toGCEvent(JSContext* cx) const; -}; - -typedef void -(* GCSliceCallback)(JSContext* cx, GCProgress progress, const GCDescription& desc); - -/** - * The GC slice callback is called at the beginning and end of each slice. This - * callback may be used for GC notifications as well as to perform additional - * marking. - */ -extern JS_PUBLIC_API(GCSliceCallback) -SetGCSliceCallback(JSContext* cx, GCSliceCallback callback); - -/** - * Describes the progress of an observed nursery collection. - */ -enum class GCNurseryProgress { - /** - * The nursery collection is starting. - */ - GC_NURSERY_COLLECTION_START, - /** - * The nursery collection is ending. - */ - GC_NURSERY_COLLECTION_END -}; - -/** - * A nursery collection callback receives the progress of the nursery collection - * and the reason for the collection. - */ -using GCNurseryCollectionCallback = void(*)(JSContext* cx, GCNurseryProgress progress, - gcreason::Reason reason); - -/** - * Set the nursery collection callback for the given runtime. When set, it will - * be called at the start and end of every nursery collection. - */ -extern JS_PUBLIC_API(GCNurseryCollectionCallback) -SetGCNurseryCollectionCallback(JSContext* cx, GCNurseryCollectionCallback callback); - -typedef void -(* DoCycleCollectionCallback)(JSContext* cx); - -/** - * The purge gray callback is called after any COMPARTMENT_REVIVED GC in which - * the majority of compartments have been marked gray. - */ -extern JS_PUBLIC_API(DoCycleCollectionCallback) -SetDoCycleCollectionCallback(JSContext* cx, DoCycleCollectionCallback callback); - -/** - * Incremental GC defaults to enabled, but may be disabled for testing or in - * embeddings that have not yet implemented barriers on their native classes. - * There is not currently a way to re-enable incremental GC once it has been - * disabled on the runtime. - */ -extern JS_PUBLIC_API(void) -DisableIncrementalGC(JSContext* cx); - -/** - * Returns true if incremental GC is enabled. Simply having incremental GC - * enabled is not sufficient to ensure incremental collections are happening. - * See the comment "Incremental GC" above for reasons why incremental GC may be - * suppressed. Inspection of the "nonincremental reason" field of the - * GCDescription returned by GCSliceCallback may help narrow down the cause if - * collections are not happening incrementally when expected. - */ -extern JS_PUBLIC_API(bool) -IsIncrementalGCEnabled(JSContext* cx); - -/** - * Returns true while an incremental GC is ongoing, both when actively - * collecting and between slices. - */ -extern JS_PUBLIC_API(bool) -IsIncrementalGCInProgress(JSContext* cx); - -/* - * Returns true when writes to GC things must call an incremental (pre) barrier. - * This is generally only true when running mutator code in-between GC slices. - * At other times, the barrier may be elided for performance. - */ -extern JS_PUBLIC_API(bool) -IsIncrementalBarrierNeeded(JSContext* cx); - -/* - * Notify the GC that a reference to a GC thing is about to be overwritten. - * These methods must be called if IsIncrementalBarrierNeeded. - */ -extern JS_PUBLIC_API(void) -IncrementalReferenceBarrier(GCCellPtr thing); - -extern JS_PUBLIC_API(void) -IncrementalValueBarrier(const Value& v); - -extern JS_PUBLIC_API(void) -IncrementalObjectBarrier(JSObject* obj); - -/** - * Returns true if the most recent GC ran incrementally. - */ -extern JS_PUBLIC_API(bool) -WasIncrementalGC(JSContext* cx); - -/* - * Generational GC: - * - * Note: Generational GC is not yet enabled by default. The following class - * is non-functional unless SpiderMonkey was configured with - * --enable-gcgenerational. - */ - -/** Ensure that generational GC is disabled within some scope. */ -class JS_PUBLIC_API(AutoDisableGenerationalGC) -{ - js::gc::GCRuntime* gc; - - public: - explicit AutoDisableGenerationalGC(JSRuntime* rt); - ~AutoDisableGenerationalGC(); -}; - -/** - * Returns true if generational allocation and collection is currently enabled - * on the given runtime. - */ -extern JS_PUBLIC_API(bool) -IsGenerationalGCEnabled(JSRuntime* rt); - -/** - * Returns the GC's "number". This does not correspond directly to the number - * of GCs that have been run, but is guaranteed to be monotonically increasing - * with GC activity. - */ -extern JS_PUBLIC_API(size_t) -GetGCNumber(); - -/** - * Pass a subclass of this "abstract" class to callees to require that they - * never GC. Subclasses can use assertions or the hazard analysis to ensure no - * GC happens. - */ -class JS_PUBLIC_API(AutoRequireNoGC) -{ - protected: - AutoRequireNoGC() {} - ~AutoRequireNoGC() {} -}; - -/** - * Diagnostic assert (see MOZ_DIAGNOSTIC_ASSERT) that GC cannot occur while this - * class is live. This class does not disable the static rooting hazard - * analysis. - * - * This works by entering a GC unsafe region, which is checked on allocation and - * on GC. - */ -class JS_PUBLIC_API(AutoAssertNoGC) : public AutoRequireNoGC -{ - js::gc::GCRuntime* gc; - size_t gcNumber; - - public: - AutoAssertNoGC(); - explicit AutoAssertNoGC(JSRuntime* rt); - explicit AutoAssertNoGC(JSContext* cx); - ~AutoAssertNoGC(); -}; - -/** - * Assert if an allocation of a GC thing occurs while this class is live. This - * class does not disable the static rooting hazard analysis. - */ -class JS_PUBLIC_API(AutoAssertNoAlloc) -{ -#ifdef JS_DEBUG - js::gc::GCRuntime* gc; - - public: - AutoAssertNoAlloc() : gc(nullptr) {} - explicit AutoAssertNoAlloc(JSContext* cx); - void disallowAlloc(JSRuntime* rt); - ~AutoAssertNoAlloc(); -#else - public: - AutoAssertNoAlloc() {} - explicit AutoAssertNoAlloc(JSContext* cx) {} - void disallowAlloc(JSRuntime* rt) {} -#endif -}; - -/** - * Assert if a GC barrier is invoked while this class is live. This class does - * not disable the static rooting hazard analysis. - */ -class JS_PUBLIC_API(AutoAssertOnBarrier) -{ - JSContext* context; - bool prev; - - public: - explicit AutoAssertOnBarrier(JSContext* cx); - ~AutoAssertOnBarrier(); -}; - -/** - * Disable the static rooting hazard analysis in the live region and assert if - * any allocation that could potentially trigger a GC occurs while this guard - * object is live. This is most useful to help the exact rooting hazard analysis - * in complex regions, since it cannot understand dataflow. - * - * Note: GC behavior is unpredictable even when deterministic and is generally - * non-deterministic in practice. The fact that this guard has not - * asserted is not a guarantee that a GC cannot happen in the guarded - * region. As a rule, anyone performing a GC unsafe action should - * understand the GC properties of all code in that region and ensure - * that the hazard analysis is correct for that code, rather than relying - * on this class. - */ -class JS_PUBLIC_API(AutoSuppressGCAnalysis) : public AutoAssertNoAlloc -{ - public: - AutoSuppressGCAnalysis() : AutoAssertNoAlloc() {} - explicit AutoSuppressGCAnalysis(JSContext* cx) : AutoAssertNoAlloc(cx) {} -} JS_HAZ_GC_SUPPRESSED; - -/** - * Assert that code is only ever called from a GC callback, disable the static - * rooting hazard analysis and assert if any allocation that could potentially - * trigger a GC occurs while this guard object is live. - * - * This is useful to make the static analysis ignore code that runs in GC - * callbacks. - */ -class JS_PUBLIC_API(AutoAssertGCCallback) : public AutoSuppressGCAnalysis -{ - public: - explicit AutoAssertGCCallback(JSObject* obj); -}; - -/** - * Place AutoCheckCannotGC in scopes that you believe can never GC. These - * annotations will be verified both dynamically via AutoAssertNoGC, and - * statically with the rooting hazard analysis (implemented by making the - * analysis consider AutoCheckCannotGC to be a GC pointer, and therefore - * complain if it is live across a GC call.) It is useful when dealing with - * internal pointers to GC things where the GC thing itself may not be present - * for the static analysis: e.g. acquiring inline chars from a JSString* on the - * heap. - * - * We only do the assertion checking in DEBUG builds. - */ -#ifdef DEBUG -class JS_PUBLIC_API(AutoCheckCannotGC) : public AutoAssertNoGC -{ - public: - AutoCheckCannotGC() : AutoAssertNoGC() {} - explicit AutoCheckCannotGC(JSContext* cx) : AutoAssertNoGC(cx) {} -} JS_HAZ_GC_INVALIDATED; -#else -class JS_PUBLIC_API(AutoCheckCannotGC) : public AutoRequireNoGC -{ - public: - AutoCheckCannotGC() {} - explicit AutoCheckCannotGC(JSContext* cx) {} -} JS_HAZ_GC_INVALIDATED; -#endif - -/** - * Unsets the gray bit for anything reachable from |thing|. |kind| should not be - * JS::TraceKind::Shape. |thing| should be non-null. The return value indicates - * if anything was unmarked. - */ -extern JS_FRIEND_API(bool) -UnmarkGrayGCThingRecursively(GCCellPtr thing); - -} /* namespace JS */ - -namespace js { -namespace gc { - -static MOZ_ALWAYS_INLINE void -ExposeGCThingToActiveJS(JS::GCCellPtr thing) -{ - // GC things residing in the nursery cannot be gray: they have no mark bits. - // All live objects in the nursery are moved to tenured at the beginning of - // each GC slice, so the gray marker never sees nursery things. - if (IsInsideNursery(thing.asCell())) - return; - - // There's nothing to do for permanent GC things that might be owned by - // another runtime. - if (thing.mayBeOwnedByOtherRuntime()) - return; - - JS::shadow::Runtime* rt = detail::GetCellRuntime(thing.asCell()); - MOZ_DIAGNOSTIC_ASSERT(rt->allowGCBarriers()); - - if (IsIncrementalBarrierNeededOnTenuredGCThing(rt, thing)) - JS::IncrementalReferenceBarrier(thing); - else if (!thing.mayBeOwnedByOtherRuntime() && js::gc::detail::CellIsMarkedGray(thing.asCell())) - JS::UnmarkGrayGCThingRecursively(thing); -} - -static MOZ_ALWAYS_INLINE void -MarkGCThingAsLive(JSRuntime* aRt, JS::GCCellPtr thing) -{ - // Any object in the nursery will not be freed during any GC running at that - // time. - if (IsInsideNursery(thing.asCell())) - return; - - // There's nothing to do for permanent GC things that might be owned by - // another runtime. - if (thing.mayBeOwnedByOtherRuntime()) - return; - - JS::shadow::Runtime* rt = JS::shadow::Runtime::asShadowRuntime(aRt); - MOZ_DIAGNOSTIC_ASSERT(rt->allowGCBarriers()); - - if (IsIncrementalBarrierNeededOnTenuredGCThing(rt, thing)) - JS::IncrementalReferenceBarrier(thing); -} - -} /* namespace gc */ -} /* namespace js */ - -namespace JS { - -/* - * This should be called when an object that is marked gray is exposed to the JS - * engine (by handing it to running JS code or writing it into live JS - * data). During incremental GC, since the gray bits haven't been computed yet, - * we conservatively mark the object black. - */ -static MOZ_ALWAYS_INLINE void -ExposeObjectToActiveJS(JSObject* obj) -{ - MOZ_ASSERT(obj); - js::gc::ExposeGCThingToActiveJS(GCCellPtr(obj)); -} - -static MOZ_ALWAYS_INLINE void -ExposeScriptToActiveJS(JSScript* script) -{ - js::gc::ExposeGCThingToActiveJS(GCCellPtr(script)); -} - -/* - * If a GC is currently marking, mark the string black. - */ -static MOZ_ALWAYS_INLINE void -MarkStringAsLive(Zone* zone, JSString* string) -{ - JSRuntime* rt = JS::shadow::Zone::asShadowZone(zone)->runtimeFromMainThread(); - js::gc::MarkGCThingAsLive(rt, GCCellPtr(string)); -} - -/* - * Internal to Firefox. - * - * Note: this is not related to the PokeGC in nsJSEnvironment. - */ -extern JS_FRIEND_API(void) -PokeGC(JSContext* cx); - -/* - * Internal to Firefox. - */ -extern JS_FRIEND_API(void) -NotifyDidPaint(JSContext* cx); - -} /* namespace JS */ - -#endif /* js_GCAPI_h */ diff --git a/win32/include/spidermonkey/js/GCAnnotations.h b/win32/include/spidermonkey/js/GCAnnotations.h deleted file mode 100755 index 366d787b..00000000 --- a/win32/include/spidermonkey/js/GCAnnotations.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCAnnotations_h -#define js_GCAnnotations_h - -// Set of annotations for the rooting hazard analysis, used to categorize types -// and functions. -#ifdef XGILL_PLUGIN - -// Mark a type as being a GC thing (eg js::gc::Cell has this annotation). -# define JS_HAZ_GC_THING __attribute__((tag("GC Thing"))) - -// Mark a type as holding a pointer to a GC thing (eg JS::Value has this -// annotation.) -# define JS_HAZ_GC_POINTER __attribute__((tag("GC Pointer"))) - -// Mark a type as a rooted pointer, suitable for use on the stack (eg all -// Rooted instantiations should have this.) -# define JS_HAZ_ROOTED __attribute__((tag("Rooted Pointer"))) - -// Mark a type as something that should not be held live across a GC, but which -// is not itself a GC pointer. -# define JS_HAZ_GC_INVALIDATED __attribute__((tag("Invalidated by GC"))) - -// Mark a type that would otherwise be considered a GC Pointer (eg because it -// contains a JS::Value field) as a non-GC pointer. It is handled almost the -// same in the analysis as a rooted pointer, except it will not be reported as -// an unnecessary root if used across a GC call. This should rarely be used, -// but makes sense for something like ErrorResult, which only contains a GC -// pointer when it holds an exception (and it does its own rooting, -// conditionally.) -# define JS_HAZ_NON_GC_POINTER __attribute__((tag("Suppressed GC Pointer"))) - -// Mark a function as something that runs a garbage collection, potentially -// invalidating GC pointers. -# define JS_HAZ_GC_CALL __attribute__((tag("GC Call"))) - -// Mark an RAII class as suppressing GC within its scope. -# define JS_HAZ_GC_SUPPRESSED __attribute__((tag("Suppress GC"))) - -#else - -# define JS_HAZ_GC_THING -# define JS_HAZ_GC_POINTER -# define JS_HAZ_ROOTED -# define JS_HAZ_GC_INVALIDATED -# define JS_HAZ_NON_GC_POINTER -# define JS_HAZ_GC_CALL -# define JS_HAZ_GC_SUPPRESSED - -#endif - -#endif /* js_GCAnnotations_h */ diff --git a/win32/include/spidermonkey/js/GCHashTable.h b/win32/include/spidermonkey/js/GCHashTable.h deleted file mode 100755 index d6c2ce75..00000000 --- a/win32/include/spidermonkey/js/GCHashTable.h +++ /dev/null @@ -1,399 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef GCHashTable_h -#define GCHashTable_h - -#include "js/GCPolicyAPI.h" -#include "js/HashTable.h" -#include "js/RootingAPI.h" -#include "js/SweepingAPI.h" -#include "js/TracingAPI.h" - -namespace JS { - -// Define a reasonable default GC policy for GC-aware Maps. -template -struct DefaultMapSweepPolicy { - static bool needsSweep(Key* key, Value* value) { - return GCPolicy::needsSweep(key) || GCPolicy::needsSweep(value); - } -}; - -// A GCHashMap is a GC-aware HashMap, meaning that it has additional trace and -// sweep methods that know how to visit all keys and values in the table. -// HashMaps that contain GC pointers will generally want to use this GCHashMap -// specialization instead of HashMap, because this conveniently supports tracing -// keys and values, and cleaning up weak entries. -// -// GCHashMap::trace applies GCPolicy::trace to each entry's key and value. -// Most types of GC pointers already have appropriate specializations of -// GCPolicy, so they should just work as keys and values. Any struct type with a -// default constructor and trace and sweep functions should work as well. If you -// need to define your own GCPolicy specialization, generic helpers can be found -// in js/public/TracingAPI.h. -// -// The MapSweepPolicy template parameter controls how the table drops entries -// when swept. GCHashMap::sweep applies MapSweepPolicy::needsSweep to each table -// entry; if it returns true, the entry is dropped. The default MapSweepPolicy -// drops the entry if either the key or value is about to be finalized, -// according to its GCPolicy::needsSweep method. (This default is almost -// always fine: it's hard to imagine keeping such an entry around anyway.) -// -// Note that this HashMap only knows *how* to trace and sweep, but it does not -// itself cause tracing or sweeping to be invoked. For tracing, it must be used -// with Rooted or PersistentRooted, or barriered and traced manually. For -// sweeping, currently it requires an explicit call to .sweep(). -template , - typename AllocPolicy = js::TempAllocPolicy, - typename MapSweepPolicy = DefaultMapSweepPolicy> -class GCHashMap : public js::HashMap -{ - using Base = js::HashMap; - - public: - explicit GCHashMap(AllocPolicy a = AllocPolicy()) : Base(a) {} - - static void trace(GCHashMap* map, JSTracer* trc) { map->trace(trc); } - void trace(JSTracer* trc) { - if (!this->initialized()) - return; - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - GCPolicy::trace(trc, &e.front().value(), "hashmap value"); - GCPolicy::trace(trc, &e.front().mutableKey(), "hashmap key"); - } - } - - void sweep() { - if (!this->initialized()) - return; - - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - if (MapSweepPolicy::needsSweep(&e.front().mutableKey(), &e.front().value())) - e.removeFront(); - } - } - - // GCHashMap is movable - GCHashMap(GCHashMap&& rhs) : Base(mozilla::Move(rhs)) {} - void operator=(GCHashMap&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - Base::operator=(mozilla::Move(rhs)); - } - - private: - // GCHashMap is not copyable or assignable - GCHashMap(const GCHashMap& hm) = delete; - GCHashMap& operator=(const GCHashMap& hm) = delete; -}; - -} // namespace JS - -namespace js { - -// HashMap that supports rekeying. -// -// If your keys are pointers to something like JSObject that can be tenured or -// compacted, prefer to use GCHashMap with MovableCellHasher, which takes -// advantage of the Zone's stable id table to make rekeying unnecessary. -template , - typename AllocPolicy = TempAllocPolicy, - typename MapSweepPolicy = JS::DefaultMapSweepPolicy> -class GCRekeyableHashMap : public JS::GCHashMap -{ - using Base = JS::GCHashMap; - - public: - explicit GCRekeyableHashMap(AllocPolicy a = AllocPolicy()) : Base(a) {} - - void sweep() { - if (!this->initialized()) - return; - - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - Key key(e.front().key()); - if (MapSweepPolicy::needsSweep(&key, &e.front().value())) - e.removeFront(); - else if (!HashPolicy::match(key, e.front().key())) - e.rekeyFront(key); - } - } - - // GCRekeyableHashMap is movable - GCRekeyableHashMap(GCRekeyableHashMap&& rhs) : Base(mozilla::Move(rhs)) {} - void operator=(GCRekeyableHashMap&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - Base::operator=(mozilla::Move(rhs)); - } -}; - -template -class GCHashMapOperations -{ - using Map = JS::GCHashMap; - using Lookup = typename Map::Lookup; - - const Map& map() const { return static_cast(this)->get(); } - - public: - using AddPtr = typename Map::AddPtr; - using Ptr = typename Map::Ptr; - using Range = typename Map::Range; - - bool initialized() const { return map().initialized(); } - Ptr lookup(const Lookup& l) const { return map().lookup(l); } - AddPtr lookupForAdd(const Lookup& l) const { return map().lookupForAdd(l); } - Range all() const { return map().all(); } - bool empty() const { return map().empty(); } - uint32_t count() const { return map().count(); } - size_t capacity() const { return map().capacity(); } - bool has(const Lookup& l) const { return map().lookup(l).found(); } - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return map().sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + map().sizeOfExcludingThis(mallocSizeOf); - } -}; - -template -class MutableGCHashMapOperations - : public GCHashMapOperations -{ - using Map = JS::GCHashMap; - using Lookup = typename Map::Lookup; - - Map& map() { return static_cast(this)->get(); } - - public: - using AddPtr = typename Map::AddPtr; - struct Enum : public Map::Enum { explicit Enum(Outer& o) : Map::Enum(o.map()) {} }; - using Ptr = typename Map::Ptr; - using Range = typename Map::Range; - - bool init(uint32_t len = 16) { return map().init(len); } - void clear() { map().clear(); } - void finish() { map().finish(); } - void remove(Ptr p) { map().remove(p); } - - template - bool add(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return map().add(p, mozilla::Forward(k), mozilla::Forward(v)); - } - - template - bool add(AddPtr& p, KeyInput&& k) { - return map().add(p, mozilla::Forward(k), Map::Value()); - } - - template - bool relookupOrAdd(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return map().relookupOrAdd(p, k, - mozilla::Forward(k), - mozilla::Forward(v)); - } - - template - bool put(KeyInput&& k, ValueInput&& v) { - return map().put(mozilla::Forward(k), mozilla::Forward(v)); - } - - template - bool putNew(KeyInput&& k, ValueInput&& v) { - return map().putNew(mozilla::Forward(k), mozilla::Forward(v)); - } -}; - -template -class RootedBase> - : public MutableGCHashMapOperations>, A,B,C,D,E> -{}; - -template -class MutableHandleBase> - : public MutableGCHashMapOperations>, A,B,C,D,E> -{}; - -template -class HandleBase> - : public GCHashMapOperations>, A,B,C,D,E> -{}; - -template -class WeakCacheBase> - : public MutableGCHashMapOperations>, A,B,C,D,E> -{}; - -} // namespace js - -namespace JS { - -// A GCHashSet is a HashSet with an additional trace method that knows -// be traced to be kept alive will generally want to use this GCHashSet -// specialization in lieu of HashSet. -// -// Most types of GC pointers can be traced with no extra infrastructure. For -// structs and non-gc-pointer members, ensure that there is a specialization of -// GCPolicy with an appropriate trace method available to handle the custom -// type. Generic helpers can be found in js/public/TracingAPI.h. -// -// Note that although this HashSet's trace will deal correctly with moved -// elements, it does not itself know when to barrier or trace elements. To -// function properly it must either be used with Rooted or barriered and traced -// manually. -template , - typename AllocPolicy = js::TempAllocPolicy> -class GCHashSet : public js::HashSet -{ - using Base = js::HashSet; - - public: - explicit GCHashSet(AllocPolicy a = AllocPolicy()) : Base(a) {} - - static void trace(GCHashSet* set, JSTracer* trc) { set->trace(trc); } - void trace(JSTracer* trc) { - if (!this->initialized()) - return; - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) - GCPolicy::trace(trc, &e.mutableFront(), "hashset element"); - } - - void sweep() { - if (!this->initialized()) - return; - for (typename Base::Enum e(*this); !e.empty(); e.popFront()) { - if (GCPolicy::needsSweep(&e.mutableFront())) - e.removeFront(); - } - } - - // GCHashSet is movable - GCHashSet(GCHashSet&& rhs) : Base(mozilla::Move(rhs)) {} - void operator=(GCHashSet&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - Base::operator=(mozilla::Move(rhs)); - } - - private: - // GCHashSet is not copyable or assignable - GCHashSet(const GCHashSet& hs) = delete; - GCHashSet& operator=(const GCHashSet& hs) = delete; -}; - -} // namespace JS - -namespace js { - -template -class GCHashSetOperations -{ - using Set = JS::GCHashSet; - using Lookup = typename Set::Lookup; - - const Set& set() const { return static_cast(this)->get(); } - - public: - using AddPtr = typename Set::AddPtr; - using Entry = typename Set::Entry; - using Ptr = typename Set::Ptr; - using Range = typename Set::Range; - - bool initialized() const { return set().initialized(); } - Ptr lookup(const Lookup& l) const { return set().lookup(l); } - AddPtr lookupForAdd(const Lookup& l) const { return set().lookupForAdd(l); } - Range all() const { return set().all(); } - bool empty() const { return set().empty(); } - uint32_t count() const { return set().count(); } - size_t capacity() const { return set().capacity(); } - bool has(const Lookup& l) const { return set().lookup(l).found(); } - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return set().sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + set().sizeOfExcludingThis(mallocSizeOf); - } -}; - -template -class MutableGCHashSetOperations - : public GCHashSetOperations -{ - using Set = JS::GCHashSet; - using Lookup = typename Set::Lookup; - - Set& set() { return static_cast(this)->get(); } - - public: - using AddPtr = typename Set::AddPtr; - using Entry = typename Set::Entry; - struct Enum : public Set::Enum { explicit Enum(Outer& o) : Set::Enum(o.set()) {} }; - using Ptr = typename Set::Ptr; - using Range = typename Set::Range; - - bool init(uint32_t len = 16) { return set().init(len); } - void clear() { set().clear(); } - void finish() { set().finish(); } - void remove(Ptr p) { set().remove(p); } - void remove(const Lookup& l) { set().remove(l); } - - template - bool add(AddPtr& p, TInput&& t) { - return set().add(p, mozilla::Forward(t)); - } - - template - bool relookupOrAdd(AddPtr& p, const Lookup& l, TInput&& t) { - return set().relookupOrAdd(p, l, mozilla::Forward(t)); - } - - template - bool put(TInput&& t) { - return set().put(mozilla::Forward(t)); - } - - template - bool putNew(TInput&& t) { - return set().putNew(mozilla::Forward(t)); - } - - template - bool putNew(const Lookup& l, TInput&& t) { - return set().putNew(l, mozilla::Forward(t)); - } -}; - -template -class RootedBase> - : public MutableGCHashSetOperations>, T, HP, AP> -{ -}; - -template -class MutableHandleBase> - : public MutableGCHashSetOperations>, T, HP, AP> -{ -}; - -template -class HandleBase> - : public GCHashSetOperations>, T, HP, AP> -{ -}; - -template -class WeakCacheBase> - : public MutableGCHashSetOperations>, T, HP, AP> -{ -}; - -} /* namespace js */ - -#endif /* GCHashTable_h */ diff --git a/win32/include/spidermonkey/js/GCPolicyAPI.h b/win32/include/spidermonkey/js/GCPolicyAPI.h deleted file mode 100755 index 054e397a..00000000 --- a/win32/include/spidermonkey/js/GCPolicyAPI.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// GC Policy Mechanism - -// A GCPolicy controls how the GC interacts with both direct pointers to GC -// things (e.g. JSObject* or JSString*), tagged and/or optional pointers to GC -// things (e.g. Value or jsid), and C++ container types (e.g. -// JSPropertyDescriptor or GCHashMap). -// -// The GCPolicy provides at a minimum: -// -// static T initial() -// - Construct and return an empty T. -// -// static void trace(JSTracer, T* tp, const char* name) -// - Trace the edge |*tp|, calling the edge |name|. Containers like -// GCHashMap and GCHashSet use this method to trace their children. -// -// static bool needsSweep(T* tp) -// - Return true if |*tp| is about to be finalized. Otherwise, update the -// edge for moving GC, and return false. Containers like GCHashMap and -// GCHashSet use this method to decide when to remove an entry: if this -// function returns true on a key/value/member/etc, its entry is dropped -// from the container. Specializing this method is the standard way to -// get custom weak behavior from a container type. -// -// The default GCPolicy assumes that T has a default constructor and |trace| -// and |needsSweep| methods, and forwards to them. GCPolicy has appropriate -// specializations for pointers to GC things and pointer-like types like -// JS::Heap and mozilla::UniquePtr. -// -// There are some stock structs your specializations can inherit from. -// IgnoreGCPolicy does nothing. StructGCPolicy forwards the methods to the -// referent type T. - -#ifndef GCPolicyAPI_h -#define GCPolicyAPI_h - -#include "mozilla/UniquePtr.h" - -#include "js/TraceKind.h" -#include "js/TracingAPI.h" - -// Expand the given macro D for each public GC pointer. -#define FOR_EACH_PUBLIC_GC_POINTER_TYPE(D) \ - D(JS::Symbol*) \ - D(JSAtom*) \ - D(JSFunction*) \ - D(JSObject*) \ - D(JSScript*) \ - D(JSString*) - -// Expand the given macro D for each public tagged GC pointer type. -#define FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(D) \ - D(JS::Value) \ - D(jsid) - -#define FOR_EACH_PUBLIC_AGGREGATE_GC_POINTER_TYPE(D) \ - D(JSPropertyDescriptor) - -class JSAtom; -class JSFunction; -class JSObject; -class JSScript; -class JSString; -namespace JS { -class Symbol; -} - -namespace JS { - -// Defines a policy for container types with non-GC, i.e. C storage. This -// policy dispatches to the underlying struct for GC interactions. -template -struct StructGCPolicy -{ - static T initial() { - return T(); - } - - static void trace(JSTracer* trc, T* tp, const char* name) { - tp->trace(trc); - } - - static void sweep(T* tp) { - return tp->sweep(); - } - - static bool needsSweep(T* tp) { - return tp->needsSweep(); - } -}; - -// The default GC policy attempts to defer to methods on the underlying type. -// Most C++ structures that contain a default constructor, a trace function and -// a sweep function will work out of the box with Rooted, Handle, GCVector, -// and GCHash{Set,Map}. -template struct GCPolicy : public StructGCPolicy {}; - -// This policy ignores any GC interaction, e.g. for non-GC types. -template -struct IgnoreGCPolicy { - static T initial() { return T(); } - static void trace(JSTracer* trc, T* t, const char* name) {} - static bool needsSweep(T* v) { return false; } -}; -template <> struct GCPolicy : public IgnoreGCPolicy {}; -template <> struct GCPolicy : public IgnoreGCPolicy {}; - -template -struct GCPointerPolicy -{ - static T initial() { return nullptr; } - static void trace(JSTracer* trc, T* vp, const char* name) { - if (*vp) - js::UnsafeTraceManuallyBarrieredEdge(trc, vp, name); - } - static bool needsSweep(T* vp) { - if (*vp) - return js::gc::IsAboutToBeFinalizedUnbarriered(vp); - return false; - } -}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; -template <> struct GCPolicy : public GCPointerPolicy {}; - -template -struct GCPolicy> -{ - static void trace(JSTracer* trc, JS::Heap* thingp, const char* name) { - TraceEdge(trc, thingp, name); - } - static bool needsSweep(JS::Heap* thingp) { - return js::gc::EdgeNeedsSweep(thingp); - } -}; - -// GCPolicy> forwards the contained pointer to GCPolicy. -template -struct GCPolicy> -{ - static mozilla::UniquePtr initial() { return mozilla::UniquePtr(); } - static void trace(JSTracer* trc, mozilla::UniquePtr* tp, const char* name) { - if (tp->get()) - GCPolicy::trace(trc, tp->get(), name); - } - static bool needsSweep(mozilla::UniquePtr* tp) { - if (tp->get()) - return GCPolicy::needsSweep(tp->get()); - return false; - } -}; - -} // namespace JS - -#endif // GCPolicyAPI_h diff --git a/win32/include/spidermonkey/js/GCVariant.h b/win32/include/spidermonkey/js/GCVariant.h deleted file mode 100755 index 31ab23f5..00000000 --- a/win32/include/spidermonkey/js/GCVariant.h +++ /dev/null @@ -1,198 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCVariant_h -#define js_GCVariant_h - -#include "mozilla/Variant.h" - -#include "js/GCPolicyAPI.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" - -namespace JS { - -// These template specializations allow Variant to be used inside GC wrappers. -// -// When matching on GC wrappers around Variants, matching should be done on -// the wrapper itself. The matcher class's methods should take Handles or -// MutableHandles. For example, -// -// struct MyMatcher -// { -// using ReturnType = const char*; -// ReturnType match(HandleObject o) { return "object"; } -// ReturnType match(HandleScript s) { return "script"; } -// }; -// -// Rooted> v(cx, someScript); -// MyMatcher mm; -// v.match(mm); -// -// If you get compile errors about inability to upcast subclasses (e.g., from -// NativeObject* to JSObject*) and are inside js/src, be sure to also include -// "gc/Policy.h". - -namespace detail { - -template -struct GCVariantImplementation; - -// The base case. -template -struct GCVariantImplementation -{ - template - static void trace(JSTracer* trc, ConcreteVariant* v, const char* name) { - T& thing = v->template as(); - if (!mozilla::IsPointer::value || thing) - GCPolicy::trace(trc, &thing, name); - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, Handle v) { - const T& thing = v.get().template as(); - return matcher.match(Handle::fromMarkedLocation(&thing)); - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, MutableHandle v) { - T& thing = v.get().template as(); - return matcher.match(MutableHandle::fromMarkedLocation(&thing)); - } -}; - -// The inductive case. -template -struct GCVariantImplementation -{ - using Next = GCVariantImplementation; - - template - static void trace(JSTracer* trc, ConcreteVariant* v, const char* name) { - if (v->template is()) { - T& thing = v->template as(); - if (!mozilla::IsPointer::value || thing) - GCPolicy::trace(trc, &thing, name); - } else { - Next::trace(trc, v, name); - } - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, Handle v) { - if (v.get().template is()) { - const T& thing = v.get().template as(); - return matcher.match(Handle::fromMarkedLocation(&thing)); - } - return Next::match(matcher, v); - } - - template - static typename Matcher::ReturnType - match(Matcher& matcher, MutableHandle v) { - if (v.get().template is()) { - T& thing = v.get().template as(); - return matcher.match(MutableHandle::fromMarkedLocation(&thing)); - } - return Next::match(matcher, v); - } -}; - -} // namespace detail - -template -struct GCPolicy> -{ - using Impl = detail::GCVariantImplementation; - - // Variants do not provide initial(). They do not have a default initial - // value and one must be provided. - - static void trace(JSTracer* trc, mozilla::Variant* v, const char* name) { - Impl::trace(trc, v, name); - } -}; - -} // namespace JS - -namespace js { - -template -class GCVariantOperations -{ - using Impl = JS::detail::GCVariantImplementation; - using Variant = mozilla::Variant; - - const Variant& variant() const { return static_cast(this)->get(); } - - public: - template - bool is() const { - return variant().template is(); - } - - template - JS::Handle as() const { - return Handle::fromMarkedLocation(&variant().template as()); - } - - template - typename Matcher::ReturnType - match(Matcher& matcher) const { - return Impl::match(matcher, JS::Handle::fromMarkedLocation(&variant())); - } -}; - -template -class MutableGCVariantOperations - : public GCVariantOperations -{ - using Impl = JS::detail::GCVariantImplementation; - using Variant = mozilla::Variant; - - const Variant& variant() const { return static_cast(this)->get(); } - Variant& variant() { return static_cast(this)->get(); } - - public: - template - JS::MutableHandle as() { - return JS::MutableHandle::fromMarkedLocation(&variant().template as()); - } - - template - typename Matcher::ReturnType - match(Matcher& matcher) { - return Impl::match(matcher, JS::MutableHandle::fromMarkedLocation(&variant())); - } -}; - -template -class RootedBase> - : public MutableGCVariantOperations>, Ts...> -{ }; - -template -class MutableHandleBase> - : public MutableGCVariantOperations>, Ts...> -{ }; - -template -class HandleBase> - : public GCVariantOperations>, Ts...> -{ }; - -template -class PersistentRootedBase> - : public MutableGCVariantOperations>, Ts...> -{ }; - -} // namespace js - -#endif // js_GCVariant_h diff --git a/win32/include/spidermonkey/js/GCVector.h b/win32/include/spidermonkey/js/GCVector.h deleted file mode 100755 index 2668e65b..00000000 --- a/win32/include/spidermonkey/js/GCVector.h +++ /dev/null @@ -1,249 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_GCVector_h -#define js_GCVector_h - -#include "mozilla/Vector.h" - -#include "js/GCPolicyAPI.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" -#include "js/Vector.h" - -namespace JS { - -// A GCVector is a Vector with an additional trace method that knows how -// to visit all of the items stored in the Vector. For vectors that contain GC -// things, this is usually more convenient than manually iterating and marking -// the contents. -// -// Most types of GC pointers as keys and values can be traced with no extra -// infrastructure. For structs and non-gc-pointer members, ensure that there is -// a specialization of GCPolicy with an appropriate trace method available -// to handle the custom type. Generic helpers can be found in -// js/public/TracingAPI.h. -// -// Note that although this Vector's trace will deal correctly with moved items, -// it does not itself know when to barrier or trace items. To function properly -// it must either be used with Rooted, or barriered and traced manually. -template -class GCVector -{ - mozilla::Vector vector; - - public: - explicit GCVector(AllocPolicy alloc = AllocPolicy()) - : vector(alloc) - {} - - GCVector(GCVector&& vec) - : vector(mozilla::Move(vec.vector)) - {} - - GCVector& operator=(GCVector&& vec) { - vector = mozilla::Move(vec.vector); - return *this; - } - - size_t length() const { return vector.length(); } - bool empty() const { return vector.empty(); } - size_t capacity() const { return vector.capacity(); } - - T* begin() { return vector.begin(); } - const T* begin() const { return vector.begin(); } - - T* end() { return vector.end(); } - const T* end() const { return vector.end(); } - - T& operator[](size_t i) { return vector[i]; } - const T& operator[](size_t i) const { return vector[i]; } - - T& back() { return vector.back(); } - const T& back() const { return vector.back(); } - - bool initCapacity(size_t cap) { return vector.initCapacity(cap); } - bool reserve(size_t req) { return vector.reserve(req); } - void shrinkBy(size_t amount) { return vector.shrinkBy(amount); } - bool growBy(size_t amount) { return vector.growBy(amount); } - bool resize(size_t newLen) { return vector.resize(newLen); } - - void clear() { return vector.clear(); } - - template bool append(U&& item) { return vector.append(mozilla::Forward(item)); } - - template - bool - emplaceBack(Args&&... args) { - return vector.emplaceBack(mozilla::Forward(args)...); - } - - template - void infallibleAppend(U&& aU) { - return vector.infallibleAppend(mozilla::Forward(aU)); - } - void infallibleAppendN(const T& aT, size_t aN) { - return vector.infallibleAppendN(aT, aN); - } - template void - infallibleAppend(const U* aBegin, const U* aEnd) { - return vector.infallibleAppend(aBegin, aEnd); - } - template void infallibleAppend(const U* aBegin, size_t aLength) { - return vector.infallibleAppend(aBegin, aLength); - } - - template - bool appendAll(const mozilla::Vector& aU) { return vector.appendAll(aU); } - template - bool appendAll(const GCVector& aU) { return vector.append(aU.begin(), aU.length()); } - - bool appendN(const T& val, size_t count) { return vector.appendN(val, count); } - - template bool append(const U* aBegin, const U* aEnd) { - return vector.append(aBegin, aEnd); - } - template bool append(const U* aBegin, size_t aLength) { - return vector.append(aBegin, aLength); - } - - void popBack() { return vector.popBack(); } - T popCopy() { return vector.popCopy(); } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return vector.sizeOfExcludingThis(mallocSizeOf); - } - - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return vector.sizeOfIncludingThis(mallocSizeOf); - } - - static void trace(GCVector* vec, JSTracer* trc) { vec->trace(trc); } - - void trace(JSTracer* trc) { - for (auto& elem : vector) - GCPolicy::trace(trc, &elem, "vector element"); - } -}; - -} // namespace JS - -namespace js { - -template -class GCVectorOperations -{ - using Vec = JS::GCVector; - const Vec& vec() const { return static_cast(this)->get(); } - - public: - const AllocPolicy& allocPolicy() const { return vec().allocPolicy(); } - size_t length() const { return vec().length(); } - bool empty() const { return vec().empty(); } - size_t capacity() const { return vec().capacity(); } - const T* begin() const { return vec().begin(); } - const T* end() const { return vec().end(); } - const T& back() const { return vec().back(); } - - JS::Handle operator[](size_t aIndex) const { - return JS::Handle::fromMarkedLocation(&vec().operator[](aIndex)); - } -}; - -template -class MutableGCVectorOperations - : public GCVectorOperations -{ - using Vec = JS::GCVector; - const Vec& vec() const { return static_cast(this)->get(); } - Vec& vec() { return static_cast(this)->get(); } - - public: - const AllocPolicy& allocPolicy() const { return vec().allocPolicy(); } - AllocPolicy& allocPolicy() { return vec().allocPolicy(); } - const T* begin() const { return vec().begin(); } - T* begin() { return vec().begin(); } - const T* end() const { return vec().end(); } - T* end() { return vec().end(); } - const T& back() const { return vec().back(); } - T& back() { return vec().back(); } - - JS::Handle operator[](size_t aIndex) const { - return JS::Handle::fromMarkedLocation(&vec().operator[](aIndex)); - } - JS::MutableHandle operator[](size_t aIndex) { - return JS::MutableHandle::fromMarkedLocation(&vec().operator[](aIndex)); - } - - bool initCapacity(size_t aRequest) { return vec().initCapacity(aRequest); } - bool reserve(size_t aRequest) { return vec().reserve(aRequest); } - void shrinkBy(size_t aIncr) { vec().shrinkBy(aIncr); } - bool growBy(size_t aIncr) { return vec().growBy(aIncr); } - bool resize(size_t aNewLength) { return vec().resize(aNewLength); } - bool growByUninitialized(size_t aIncr) { return vec().growByUninitialized(aIncr); } - void infallibleGrowByUninitialized(size_t aIncr) { vec().infallibleGrowByUninitialized(aIncr); } - bool resizeUninitialized(size_t aNewLength) { return vec().resizeUninitialized(aNewLength); } - void clear() { vec().clear(); } - void clearAndFree() { vec().clearAndFree(); } - template bool append(U&& aU) { return vec().append(mozilla::Forward(aU)); } - template bool emplaceBack(Args&&... aArgs) { - return vec().emplaceBack(mozilla::Forward(aArgs...)); - } - template - bool appendAll(const mozilla::Vector& aU) { return vec().appendAll(aU); } - template - bool appendAll(const JS::GCVector& aU) { return vec().appendAll(aU); } - bool appendN(const T& aT, size_t aN) { return vec().appendN(aT, aN); } - template bool append(const U* aBegin, const U* aEnd) { - return vec().append(aBegin, aEnd); - } - template bool append(const U* aBegin, size_t aLength) { - return vec().append(aBegin, aLength); - } - template void infallibleAppend(U&& aU) { - vec().infallibleAppend(mozilla::Forward(aU)); - } - void infallibleAppendN(const T& aT, size_t aN) { vec().infallibleAppendN(aT, aN); } - template void infallibleAppend(const U* aBegin, const U* aEnd) { - vec().infallibleAppend(aBegin, aEnd); - } - template void infallibleAppend(const U* aBegin, size_t aLength) { - vec().infallibleAppend(aBegin, aLength); - } - void popBack() { vec().popBack(); } - T popCopy() { return vec().popCopy(); } - template T* insert(T* aP, U&& aVal) { - return vec().insert(aP, mozilla::Forward(aVal)); - } - void erase(T* aT) { vec().erase(aT); } - void erase(T* aBegin, T* aEnd) { vec().erase(aBegin, aEnd); } -}; - -template -class RootedBase> - : public MutableGCVectorOperations>, T,N,AP> -{}; - -template -class MutableHandleBase> - : public MutableGCVectorOperations>, T,N,AP> -{}; - -template -class HandleBase> - : public GCVectorOperations>, T,N,AP> -{}; - -template -class PersistentRootedBase> - : public MutableGCVectorOperations>, T,N,AP> -{}; - -} // namespace js - -#endif // js_GCVector_h diff --git a/win32/include/spidermonkey/js/HashTable.h b/win32/include/spidermonkey/js/HashTable.h deleted file mode 100755 index 5d4c0665..00000000 --- a/win32/include/spidermonkey/js/HashTable.h +++ /dev/null @@ -1,1880 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_HashTable_h -#define js_HashTable_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/HashFunctions.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/Opaque.h" -#include "mozilla/PodOperations.h" -#include "mozilla/ReentrancyGuard.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/UniquePtr.h" - -#include "js/Utility.h" - -namespace js { - -class TempAllocPolicy; -template struct DefaultHasher; -template class HashMapEntry; -namespace detail { - template class HashTableEntry; - template class HashTable; -} // namespace detail - -/*****************************************************************************/ - -// The "generation" of a hash table is an opaque value indicating the state of -// modification of the hash table through its lifetime. If the generation of -// a hash table compares equal at times T1 and T2, then lookups in the hash -// table, pointers to (or into) hash table entries, etc. at time T1 are valid -// at time T2. If the generation compares unequal, these computations are all -// invalid and must be performed again to be used. -// -// Generations are meaningfully comparable only with respect to a single hash -// table. It's always nonsensical to compare the generation of distinct hash -// tables H1 and H2. -using Generation = mozilla::Opaque; - -// A JS-friendly, STL-like container providing a hash-based map from keys to -// values. In particular, HashMap calls constructors and destructors of all -// objects added so non-PODs may be used safely. -// -// Key/Value requirements: -// - movable, destructible, assignable -// HashPolicy requirements: -// - see Hash Policy section below -// AllocPolicy: -// - see jsalloc.h -// -// Note: -// - HashMap is not reentrant: Key/Value/HashPolicy/AllocPolicy members -// called by HashMap must not call back into the same HashMap object. -// - Due to the lack of exception handling, the user must call |init()|. -template , - class AllocPolicy = TempAllocPolicy> -class HashMap -{ - typedef HashMapEntry TableEntry; - - struct MapHashPolicy : HashPolicy - { - using Base = HashPolicy; - typedef Key KeyType; - static const Key& getKey(TableEntry& e) { return e.key(); } - static void setKey(TableEntry& e, Key& k) { HashPolicy::rekey(e.mutableKey(), k); } - }; - - typedef detail::HashTable Impl; - Impl impl; - - public: - typedef typename HashPolicy::Lookup Lookup; - typedef TableEntry Entry; - - // HashMap construction is fallible (due to OOM); thus the user must call - // init after constructing a HashMap and check the return value. - explicit HashMap(AllocPolicy a = AllocPolicy()) : impl(a) {} - MOZ_MUST_USE bool init(uint32_t len = 16) { return impl.init(len); } - bool initialized() const { return impl.initialized(); } - - // Return whether the given lookup value is present in the map. E.g.: - // - // typedef HashMap HM; - // HM h; - // if (HM::Ptr p = h.lookup(3)) { - // const HM::Entry& e = *p; // p acts like a pointer to Entry - // assert(p->key == 3); // Entry contains the key - // char val = p->value; // and value - // } - // - // Also see the definition of Ptr in HashTable above (with T = Entry). - typedef typename Impl::Ptr Ptr; - Ptr lookup(const Lookup& l) const { return impl.lookup(l); } - - // Like lookup, but does not assert if two threads call lookup at the same - // time. Only use this method when none of the threads will modify the map. - Ptr readonlyThreadsafeLookup(const Lookup& l) const { return impl.readonlyThreadsafeLookup(l); } - - // Assuming |p.found()|, remove |*p|. - void remove(Ptr p) { impl.remove(p); } - - // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient - // insertion of Key |k| (where |HashPolicy::match(k,l) == true|) using - // |add(p,k,v)|. After |add(p,k,v)|, |p| points to the new Entry. E.g.: - // - // typedef HashMap HM; - // HM h; - // HM::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // if (!h.add(p, 3, 'a')) - // return false; - // } - // const HM::Entry& e = *p; // p acts like a pointer to Entry - // assert(p->key == 3); // Entry contains the key - // char val = p->value; // and value - // - // Also see the definition of AddPtr in HashTable above (with T = Entry). - // - // N.B. The caller must ensure that no mutating hash table operations - // occur between a pair of |lookupForAdd| and |add| calls. To avoid - // looking up the key a second time, the caller may use the more efficient - // relookupOrAdd method. This method reuses part of the hashing computation - // to more efficiently insert the key if it has not been added. For - // example, a mutation-handling version of the previous example: - // - // HM::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // call_that_may_mutate_h(); - // if (!h.relookupOrAdd(p, 3, 'a')) - // return false; - // } - // const HM::Entry& e = *p; - // assert(p->key == 3); - // char val = p->value; - typedef typename Impl::AddPtr AddPtr; - AddPtr lookupForAdd(const Lookup& l) const { - return impl.lookupForAdd(l); - } - - template - MOZ_MUST_USE bool add(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return impl.add(p, - mozilla::Forward(k), - mozilla::Forward(v)); - } - - template - MOZ_MUST_USE bool add(AddPtr& p, KeyInput&& k) { - return impl.add(p, mozilla::Forward(k), Value()); - } - - template - MOZ_MUST_USE bool relookupOrAdd(AddPtr& p, KeyInput&& k, ValueInput&& v) { - return impl.relookupOrAdd(p, k, - mozilla::Forward(k), - mozilla::Forward(v)); - } - - // |all()| returns a Range containing |count()| elements. E.g.: - // - // typedef HashMap HM; - // HM h; - // for (HM::Range r = h.all(); !r.empty(); r.popFront()) - // char c = r.front().value(); - // - // Also see the definition of Range in HashTable above (with T = Entry). - typedef typename Impl::Range Range; - Range all() const { return impl.all(); } - - // Typedef for the enumeration class. An Enum may be used to examine and - // remove table entries: - // - // typedef HashMap HM; - // HM s; - // for (HM::Enum e(s); !e.empty(); e.popFront()) - // if (e.front().value() == 'l') - // e.removeFront(); - // - // Table resize may occur in Enum's destructor. Also see the definition of - // Enum in HashTable above (with T = Entry). - typedef typename Impl::Enum Enum; - - // Remove all entries. This does not shrink the table. For that consider - // using the finish() method. - void clear() { impl.clear(); } - - // Remove all the entries and release all internal buffers. The map must - // be initialized again before any use. - void finish() { impl.finish(); } - - // Does the table contain any entries? - bool empty() const { return impl.empty(); } - - // Number of live elements in the map. - uint32_t count() const { return impl.count(); } - - // Total number of allocation in the dynamic table. Note: resize will - // happen well before count() == capacity(). - size_t capacity() const { return impl.capacity(); } - - // Don't just call |impl.sizeOfExcludingThis()| because there's no - // guarantee that |impl| is the first field in HashMap. - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return impl.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); - } - - Generation generation() const { - return impl.generation(); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return impl.lookup(l).found(); - } - - // Overwrite existing value with v. Return false on oom. - template - MOZ_MUST_USE bool put(KeyInput&& k, ValueInput&& v) { - AddPtr p = lookupForAdd(k); - if (p) { - p->value() = mozilla::Forward(v); - return true; - } - return add(p, mozilla::Forward(k), mozilla::Forward(v)); - } - - // Like put, but assert that the given key is not already present. - template - MOZ_MUST_USE bool putNew(KeyInput&& k, ValueInput&& v) { - return impl.putNew(k, mozilla::Forward(k), mozilla::Forward(v)); - } - - // Only call this to populate an empty map after reserving space with init(). - template - void putNewInfallible(KeyInput&& k, ValueInput&& v) { - impl.putNewInfallible(k, mozilla::Forward(k), mozilla::Forward(v)); - } - - // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. - Ptr lookupWithDefault(const Key& k, const Value& defaultValue) { - AddPtr p = lookupForAdd(k); - if (p) - return p; - bool ok = add(p, k, defaultValue); - MOZ_ASSERT_IF(!ok, !p); // p is left false-y on oom. - (void)ok; - return p; - } - - // Remove if present. - void remove(const Lookup& l) { - if (Ptr p = lookup(l)) - remove(p); - } - - // Infallibly rekey one entry, if necessary. - // Requires template parameters Key and HashPolicy::Lookup to be the same type. - void rekeyIfMoved(const Key& old_key, const Key& new_key) { - if (old_key != new_key) - rekeyAs(old_key, new_key, new_key); - } - - // Infallibly rekey one entry if present, and return whether that happened. - bool rekeyAs(const Lookup& old_lookup, const Lookup& new_lookup, const Key& new_key) { - if (Ptr p = lookup(old_lookup)) { - impl.rekeyAndMaybeRehash(p, new_lookup, new_key); - return true; - } - return false; - } - - // HashMap is movable - HashMap(HashMap&& rhs) : impl(mozilla::Move(rhs.impl)) {} - void operator=(HashMap&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - impl = mozilla::Move(rhs.impl); - } - - private: - // HashMap is not copyable or assignable - HashMap(const HashMap& hm) = delete; - HashMap& operator=(const HashMap& hm) = delete; - - friend class Impl::Enum; -}; - -/*****************************************************************************/ - -// A JS-friendly, STL-like container providing a hash-based set of values. In -// particular, HashSet calls constructors and destructors of all objects added -// so non-PODs may be used safely. -// -// T requirements: -// - movable, destructible, assignable -// HashPolicy requirements: -// - see Hash Policy section below -// AllocPolicy: -// - see jsalloc.h -// -// Note: -// - HashSet is not reentrant: T/HashPolicy/AllocPolicy members called by -// HashSet must not call back into the same HashSet object. -// - Due to the lack of exception handling, the user must call |init()|. -template , - class AllocPolicy = TempAllocPolicy> -class HashSet -{ - struct SetOps : HashPolicy - { - using Base = HashPolicy; - typedef T KeyType; - static const KeyType& getKey(const T& t) { return t; } - static void setKey(T& t, KeyType& k) { HashPolicy::rekey(t, k); } - }; - - typedef detail::HashTable Impl; - Impl impl; - - public: - typedef typename HashPolicy::Lookup Lookup; - typedef T Entry; - - // HashSet construction is fallible (due to OOM); thus the user must call - // init after constructing a HashSet and check the return value. - explicit HashSet(AllocPolicy a = AllocPolicy()) : impl(a) {} - MOZ_MUST_USE bool init(uint32_t len = 16) { return impl.init(len); } - bool initialized() const { return impl.initialized(); } - - // Return whether the given lookup value is present in the map. E.g.: - // - // typedef HashSet HS; - // HS h; - // if (HS::Ptr p = h.lookup(3)) { - // assert(*p == 3); // p acts like a pointer to int - // } - // - // Also see the definition of Ptr in HashTable above. - typedef typename Impl::Ptr Ptr; - Ptr lookup(const Lookup& l) const { return impl.lookup(l); } - - // Like lookup, but does not assert if two threads call lookup at the same - // time. Only use this method when none of the threads will modify the map. - Ptr readonlyThreadsafeLookup(const Lookup& l) const { return impl.readonlyThreadsafeLookup(l); } - - // Assuming |p.found()|, remove |*p|. - void remove(Ptr p) { impl.remove(p); } - - // Like |lookup(l)|, but on miss, |p = lookupForAdd(l)| allows efficient - // insertion of T value |t| (where |HashPolicy::match(t,l) == true|) using - // |add(p,t)|. After |add(p,t)|, |p| points to the new element. E.g.: - // - // typedef HashSet HS; - // HS h; - // HS::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // if (!h.add(p, 3)) - // return false; - // } - // assert(*p == 3); // p acts like a pointer to int - // - // Also see the definition of AddPtr in HashTable above. - // - // N.B. The caller must ensure that no mutating hash table operations - // occur between a pair of |lookupForAdd| and |add| calls. To avoid - // looking up the key a second time, the caller may use the more efficient - // relookupOrAdd method. This method reuses part of the hashing computation - // to more efficiently insert the key if it has not been added. For - // example, a mutation-handling version of the previous example: - // - // HS::AddPtr p = h.lookupForAdd(3); - // if (!p) { - // call_that_may_mutate_h(); - // if (!h.relookupOrAdd(p, 3, 3)) - // return false; - // } - // assert(*p == 3); - // - // Note that relookupOrAdd(p,l,t) performs Lookup using |l| and adds the - // entry |t|, where the caller ensures match(l,t). - typedef typename Impl::AddPtr AddPtr; - AddPtr lookupForAdd(const Lookup& l) const { return impl.lookupForAdd(l); } - - template - MOZ_MUST_USE bool add(AddPtr& p, U&& u) { - return impl.add(p, mozilla::Forward(u)); - } - - template - MOZ_MUST_USE bool relookupOrAdd(AddPtr& p, const Lookup& l, U&& u) { - return impl.relookupOrAdd(p, l, mozilla::Forward(u)); - } - - // |all()| returns a Range containing |count()| elements: - // - // typedef HashSet HS; - // HS h; - // for (HS::Range r = h.all(); !r.empty(); r.popFront()) - // int i = r.front(); - // - // Also see the definition of Range in HashTable above. - typedef typename Impl::Range Range; - Range all() const { return impl.all(); } - - // Typedef for the enumeration class. An Enum may be used to examine and - // remove table entries: - // - // typedef HashSet HS; - // HS s; - // for (HS::Enum e(s); !e.empty(); e.popFront()) - // if (e.front() == 42) - // e.removeFront(); - // - // Table resize may occur in Enum's destructor. Also see the definition of - // Enum in HashTable above. - typedef typename Impl::Enum Enum; - - // Remove all entries. This does not shrink the table. For that consider - // using the finish() method. - void clear() { impl.clear(); } - - // Remove all the entries and release all internal buffers. The set must - // be initialized again before any use. - void finish() { impl.finish(); } - - // Does the table contain any entries? - bool empty() const { return impl.empty(); } - - // Number of live elements in the map. - uint32_t count() const { return impl.count(); } - - // Total number of allocation in the dynamic table. Note: resize will - // happen well before count() == capacity(). - size_t capacity() const { return impl.capacity(); } - - // Don't just call |impl.sizeOfExcludingThis()| because there's no - // guarantee that |impl| is the first field in HashSet. - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return impl.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return mallocSizeOf(this) + impl.sizeOfExcludingThis(mallocSizeOf); - } - - Generation generation() const { - return impl.generation(); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return impl.lookup(l).found(); - } - - // Add |u| if it is not present already. Return false on oom. - template - MOZ_MUST_USE bool put(U&& u) { - AddPtr p = lookupForAdd(u); - return p ? true : add(p, mozilla::Forward(u)); - } - - // Like put, but assert that the given key is not already present. - template - MOZ_MUST_USE bool putNew(U&& u) { - return impl.putNew(u, mozilla::Forward(u)); - } - - template - MOZ_MUST_USE bool putNew(const Lookup& l, U&& u) { - return impl.putNew(l, mozilla::Forward(u)); - } - - // Only call this to populate an empty set after reserving space with init(). - template - void putNewInfallible(const Lookup& l, U&& u) { - impl.putNewInfallible(l, mozilla::Forward(u)); - } - - void remove(const Lookup& l) { - if (Ptr p = lookup(l)) - remove(p); - } - - // Infallibly rekey one entry, if present. - // Requires template parameters T and HashPolicy::Lookup to be the same type. - void rekeyIfMoved(const Lookup& old_value, const T& new_value) { - if (old_value != new_value) - rekeyAs(old_value, new_value, new_value); - } - - // Infallibly rekey one entry if present, and return whether that happened. - bool rekeyAs(const Lookup& old_lookup, const Lookup& new_lookup, const T& new_value) { - if (Ptr p = lookup(old_lookup)) { - impl.rekeyAndMaybeRehash(p, new_lookup, new_value); - return true; - } - return false; - } - - // Infallibly replace the current key at |p| with an equivalent key. - // Specifically, both HashPolicy::hash and HashPolicy::match must return - // identical results for the new and old key when applied against all - // possible matching values. - void replaceKey(Ptr p, const T& new_value) { - MOZ_ASSERT(p.found()); - MOZ_ASSERT(*p != new_value); - MOZ_ASSERT(HashPolicy::hash(*p) == HashPolicy::hash(new_value)); - MOZ_ASSERT(HashPolicy::match(*p, new_value)); - const_cast(*p) = new_value; - } - - // HashSet is movable - HashSet(HashSet&& rhs) : impl(mozilla::Move(rhs.impl)) {} - void operator=(HashSet&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - impl = mozilla::Move(rhs.impl); - } - - private: - // HashSet is not copyable or assignable - HashSet(const HashSet& hs) = delete; - HashSet& operator=(const HashSet& hs) = delete; - - friend class Impl::Enum; -}; - -/*****************************************************************************/ - -// Hash Policy -// -// A hash policy P for a hash table with key-type Key must provide: -// - a type |P::Lookup| to use to lookup table entries; -// - a static member function |P::hash| with signature -// -// static js::HashNumber hash(Lookup) -// -// to use to hash the lookup type; and -// - a static member function |P::match| with signature -// -// static bool match(Key, Lookup) -// -// to use to test equality of key and lookup values. -// -// Normally, Lookup = Key. In general, though, different values and types of -// values can be used to lookup and store. If a Lookup value |l| is != to the -// added Key value |k|, the user must ensure that |P::match(k,l)|. E.g.: -// -// js::HashSet::AddPtr p = h.lookup(l); -// if (!p) { -// assert(P::match(k, l)); // must hold -// h.add(p, k); -// } - -// Pointer hashing policy that strips the lowest zeroBits when calculating the -// hash to improve key distribution. -template -struct PointerHasher -{ - typedef Key Lookup; - static HashNumber hash(const Lookup& l) { - size_t word = reinterpret_cast(l) >> zeroBits; - static_assert(sizeof(HashNumber) == 4, - "subsequent code assumes a four-byte hash"); -#if JS_BITS_PER_WORD == 32 - return HashNumber(word); -#else - static_assert(sizeof(word) == 8, - "unexpected word size, new hashing strategy required to " - "properly incorporate all bits"); - return HashNumber((word >> 32) ^ word); -#endif - } - static bool match(const Key& k, const Lookup& l) { - return k == l; - } - static void rekey(Key& k, const Key& newKey) { - k = newKey; - } -}; - -// Default hash policy: just use the 'lookup' value. This of course only -// works if the lookup value is integral. HashTable applies ScrambleHashCode to -// the result of the 'hash' which means that it is 'ok' if the lookup value is -// not well distributed over the HashNumber domain. -template -struct DefaultHasher -{ - typedef Key Lookup; - static HashNumber hash(const Lookup& l) { - // Hash if can implicitly cast to hash number type. - return l; - } - static bool match(const Key& k, const Lookup& l) { - // Use builtin or overloaded operator==. - return k == l; - } - static void rekey(Key& k, const Key& newKey) { - k = newKey; - } -}; - -// Specialize hashing policy for pointer types. It assumes that the type is -// at least word-aligned. For types with smaller size use PointerHasher. -template -struct DefaultHasher : PointerHasher::value> -{}; - -// Specialize hashing policy for mozilla::UniquePtr to proxy the UniquePtr's -// raw pointer to PointerHasher. -template -struct DefaultHasher> -{ - using Lookup = mozilla::UniquePtr; - using PtrHasher = PointerHasher::value>; - - static HashNumber hash(const Lookup& l) { - return PtrHasher::hash(l.get()); - } - static bool match(const mozilla::UniquePtr& k, const Lookup& l) { - return PtrHasher::match(k.get(), l.get()); - } - static void rekey(mozilla::UniquePtr& k, mozilla::UniquePtr&& newKey) { - k = mozilla::Move(newKey); - } -}; - -// For doubles, we can xor the two uint32s. -template <> -struct DefaultHasher -{ - typedef double Lookup; - static HashNumber hash(double d) { - static_assert(sizeof(HashNumber) == 4, - "subsequent code assumes a four-byte hash"); - uint64_t u = mozilla::BitwiseCast(d); - return HashNumber(u ^ (u >> 32)); - } - static bool match(double lhs, double rhs) { - return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); - } -}; - -template <> -struct DefaultHasher -{ - typedef float Lookup; - static HashNumber hash(float f) { - static_assert(sizeof(HashNumber) == 4, - "subsequent code assumes a four-byte hash"); - return HashNumber(mozilla::BitwiseCast(f)); - } - static bool match(float lhs, float rhs) { - return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); - } -}; - -// A hash policy that compares C strings. -struct CStringHasher -{ - typedef const char* Lookup; - static js::HashNumber hash(Lookup l) { - return mozilla::HashString(l); - } - static bool match(const char* key, Lookup lookup) { - return strcmp(key, lookup) == 0; - } -}; - -// Fallible hashing interface. -// -// Most of the time generating a hash code is infallible so this class provides -// default methods that always succeed. Specialize this class for your own hash -// policy to provide fallible hashing. -// -// This is used by MovableCellHasher to handle the fact that generating a unique -// ID for cell pointer may fail due to OOM. -template -struct FallibleHashMethods -{ - // Return true if a hashcode is already available for its argument. Once - // this returns true for a specific argument it must continue to do so. - template static bool hasHash(Lookup&& l) { return true; } - - // Fallible method to ensure a hashcode exists for its argument and create - // one if not. Returns false on error, e.g. out of memory. - template static bool ensureHash(Lookup&& l) { return true; } -}; - -template -static bool -HasHash(Lookup&& l) { - return FallibleHashMethods::hasHash(mozilla::Forward(l)); -} - -template -static bool -EnsureHash(Lookup&& l) { - return FallibleHashMethods::ensureHash(mozilla::Forward(l)); -} - -/*****************************************************************************/ - -// Both HashMap and HashSet are implemented by a single HashTable that is even -// more heavily parameterized than the other two. This leaves HashTable gnarly -// and extremely coupled to HashMap and HashSet; thus code should not use -// HashTable directly. - -template -class HashMapEntry -{ - Key key_; - Value value_; - - template friend class detail::HashTable; - template friend class detail::HashTableEntry; - template friend class HashMap; - - public: - template - HashMapEntry(KeyInput&& k, ValueInput&& v) - : key_(mozilla::Forward(k)), - value_(mozilla::Forward(v)) - {} - - HashMapEntry(HashMapEntry&& rhs) - : key_(mozilla::Move(rhs.key_)), - value_(mozilla::Move(rhs.value_)) - {} - - void operator=(HashMapEntry&& rhs) { - key_ = mozilla::Move(rhs.key_); - value_ = mozilla::Move(rhs.value_); - } - - typedef Key KeyType; - typedef Value ValueType; - - const Key& key() const { return key_; } - Key& mutableKey() { return key_; } - const Value& value() const { return value_; } - Value& value() { return value_; } - - private: - HashMapEntry(const HashMapEntry&) = delete; - void operator=(const HashMapEntry&) = delete; -}; - -} // namespace js - -namespace mozilla { - -template -struct IsPod > : IsPod {}; - -template -struct IsPod > - : IntegralConstant::value && IsPod::value> -{}; - -} // namespace mozilla - -namespace js { - -namespace detail { - -template -class HashTable; - -template -class HashTableEntry -{ - template friend class HashTable; - typedef typename mozilla::RemoveConst::Type NonConstT; - - HashNumber keyHash; - mozilla::AlignedStorage2 mem; - - static const HashNumber sFreeKey = 0; - static const HashNumber sRemovedKey = 1; - static const HashNumber sCollisionBit = 1; - - static bool isLiveHash(HashNumber hash) - { - return hash > sRemovedKey; - } - - HashTableEntry(const HashTableEntry&) = delete; - void operator=(const HashTableEntry&) = delete; - ~HashTableEntry() = delete; - - public: - // NB: HashTableEntry is treated as a POD: no constructor or destructor calls. - - void destroyIfLive() { - if (isLive()) - mem.addr()->~T(); - } - - void destroy() { - MOZ_ASSERT(isLive()); - mem.addr()->~T(); - } - - void swap(HashTableEntry* other) { - if (this == other) - return; - MOZ_ASSERT(isLive()); - if (other->isLive()) { - mozilla::Swap(*mem.addr(), *other->mem.addr()); - } else { - *other->mem.addr() = mozilla::Move(*mem.addr()); - destroy(); - } - mozilla::Swap(keyHash, other->keyHash); - } - - T& get() { MOZ_ASSERT(isLive()); return *mem.addr(); } - NonConstT& getMutable() { MOZ_ASSERT(isLive()); return *mem.addr(); } - - bool isFree() const { return keyHash == sFreeKey; } - void clearLive() { MOZ_ASSERT(isLive()); keyHash = sFreeKey; mem.addr()->~T(); } - void clear() { if (isLive()) mem.addr()->~T(); keyHash = sFreeKey; } - bool isRemoved() const { return keyHash == sRemovedKey; } - void removeLive() { MOZ_ASSERT(isLive()); keyHash = sRemovedKey; mem.addr()->~T(); } - bool isLive() const { return isLiveHash(keyHash); } - void setCollision() { MOZ_ASSERT(isLive()); keyHash |= sCollisionBit; } - void unsetCollision() { keyHash &= ~sCollisionBit; } - bool hasCollision() const { return keyHash & sCollisionBit; } - bool matchHash(HashNumber hn) { return (keyHash & ~sCollisionBit) == hn; } - HashNumber getKeyHash() const { return keyHash & ~sCollisionBit; } - - template - void setLive(HashNumber hn, Args&&... args) - { - MOZ_ASSERT(!isLive()); - keyHash = hn; - new(mem.addr()) T(mozilla::Forward(args)...); - MOZ_ASSERT(isLive()); - } -}; - -template -class HashTable : private AllocPolicy -{ - friend class mozilla::ReentrancyGuard; - - typedef typename mozilla::RemoveConst::Type NonConstT; - typedef typename HashPolicy::KeyType Key; - typedef typename HashPolicy::Lookup Lookup; - - public: - typedef HashTableEntry Entry; - - // A nullable pointer to a hash table element. A Ptr |p| can be tested - // either explicitly |if (p.found()) p->...| or using boolean conversion - // |if (p) p->...|. Ptr objects must not be used after any mutating hash - // table operations unless |generation()| is tested. - class Ptr - { - friend class HashTable; - - Entry* entry_; -#ifdef JS_DEBUG - const HashTable* table_; - Generation generation; -#endif - - protected: - Ptr(Entry& entry, const HashTable& tableArg) - : entry_(&entry) -#ifdef JS_DEBUG - , table_(&tableArg) - , generation(tableArg.generation()) -#endif - {} - - public: - Ptr() - : entry_(nullptr) -#ifdef JS_DEBUG - , table_(nullptr) - , generation(0) -#endif - {} - - bool isValid() const { - return !entry_; - } - - bool found() const { - if (isValid()) - return false; -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); -#endif - return entry_->isLive(); - } - - explicit operator bool() const { - return found(); - } - - bool operator==(const Ptr& rhs) const { - MOZ_ASSERT(found() && rhs.found()); - return entry_ == rhs.entry_; - } - - bool operator!=(const Ptr& rhs) const { -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); -#endif - return !(*this == rhs); - } - - T& operator*() const { -#ifdef JS_DEBUG - MOZ_ASSERT(found()); - MOZ_ASSERT(generation == table_->generation()); -#endif - return entry_->get(); - } - - T* operator->() const { -#ifdef JS_DEBUG - MOZ_ASSERT(found()); - MOZ_ASSERT(generation == table_->generation()); -#endif - return &entry_->get(); - } - }; - - // A Ptr that can be used to add a key after a failed lookup. - class AddPtr : public Ptr - { - friend class HashTable; - HashNumber keyHash; -#ifdef JS_DEBUG - uint64_t mutationCount; -#endif - - AddPtr(Entry& entry, const HashTable& tableArg, HashNumber hn) - : Ptr(entry, tableArg) - , keyHash(hn) -#ifdef JS_DEBUG - , mutationCount(tableArg.mutationCount) -#endif - {} - - public: - AddPtr() : keyHash(0) {} - }; - - // A collection of hash table entries. The collection is enumerated by - // calling |front()| followed by |popFront()| as long as |!empty()|. As - // with Ptr/AddPtr, Range objects must not be used after any mutating hash - // table operation unless the |generation()| is tested. - class Range - { - protected: - friend class HashTable; - - Range(const HashTable& tableArg, Entry* c, Entry* e) - : cur(c) - , end(e) -#ifdef JS_DEBUG - , table_(&tableArg) - , mutationCount(tableArg.mutationCount) - , generation(tableArg.generation()) - , validEntry(true) -#endif - { - while (cur < end && !cur->isLive()) - ++cur; - } - - Entry* cur; - Entry* end; -#ifdef JS_DEBUG - const HashTable* table_; - uint64_t mutationCount; - Generation generation; - bool validEntry; -#endif - - public: - Range() - : cur(nullptr) - , end(nullptr) -#ifdef JS_DEBUG - , table_(nullptr) - , mutationCount(0) - , generation(0) - , validEntry(false) -#endif - {} - - bool empty() const { -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); - MOZ_ASSERT(mutationCount == table_->mutationCount); -#endif - return cur == end; - } - - T& front() const { - MOZ_ASSERT(!empty()); -#ifdef JS_DEBUG - MOZ_ASSERT(validEntry); - MOZ_ASSERT(generation == table_->generation()); - MOZ_ASSERT(mutationCount == table_->mutationCount); -#endif - return cur->get(); - } - - void popFront() { - MOZ_ASSERT(!empty()); -#ifdef JS_DEBUG - MOZ_ASSERT(generation == table_->generation()); - MOZ_ASSERT(mutationCount == table_->mutationCount); -#endif - while (++cur < end && !cur->isLive()) - continue; -#ifdef JS_DEBUG - validEntry = true; -#endif - } - }; - - // A Range whose lifetime delimits a mutating enumeration of a hash table. - // Since rehashing when elements were removed during enumeration would be - // bad, it is postponed until the Enum is destructed. Since the Enum's - // destructor touches the hash table, the user must ensure that the hash - // table is still alive when the destructor runs. - class Enum : public Range - { - friend class HashTable; - - HashTable& table_; - bool rekeyed; - bool removed; - - /* Not copyable. */ - Enum(const Enum&) = delete; - void operator=(const Enum&) = delete; - - public: - template explicit - Enum(Map& map) : Range(map.all()), table_(map.impl), rekeyed(false), removed(false) {} - - // Removes the |front()| element from the table, leaving |front()| - // invalid until the next call to |popFront()|. For example: - // - // HashSet s; - // for (HashSet::Enum e(s); !e.empty(); e.popFront()) - // if (e.front() == 42) - // e.removeFront(); - void removeFront() { - table_.remove(*this->cur); - removed = true; -#ifdef JS_DEBUG - this->validEntry = false; - this->mutationCount = table_.mutationCount; -#endif - } - - NonConstT& mutableFront() { - MOZ_ASSERT(!this->empty()); -#ifdef JS_DEBUG - MOZ_ASSERT(this->validEntry); - MOZ_ASSERT(this->generation == this->Range::table_->generation()); - MOZ_ASSERT(this->mutationCount == this->Range::table_->mutationCount); -#endif - return this->cur->getMutable(); - } - - // Removes the |front()| element and re-inserts it into the table with - // a new key at the new Lookup position. |front()| is invalid after - // this operation until the next call to |popFront()|. - void rekeyFront(const Lookup& l, const Key& k) { - MOZ_ASSERT(&k != &HashPolicy::getKey(this->cur->get())); - Ptr p(*this->cur, table_); - table_.rekeyWithoutRehash(p, l, k); - rekeyed = true; -#ifdef JS_DEBUG - this->validEntry = false; - this->mutationCount = table_.mutationCount; -#endif - } - - void rekeyFront(const Key& k) { - rekeyFront(k, k); - } - - // Potentially rehashes the table. - ~Enum() { - if (rekeyed) { - table_.gen++; - table_.checkOverRemoved(); - } - - if (removed) - table_.compactIfUnderloaded(); - } - }; - - // HashTable is movable - HashTable(HashTable&& rhs) - : AllocPolicy(rhs) - { - mozilla::PodAssign(this, &rhs); - rhs.table = nullptr; - } - void operator=(HashTable&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move assignment is prohibited"); - if (table) - destroyTable(*this, table, capacity()); - mozilla::PodAssign(this, &rhs); - rhs.table = nullptr; - } - - private: - // HashTable is not copyable or assignable - HashTable(const HashTable&) = delete; - void operator=(const HashTable&) = delete; - - private: - static const size_t CAP_BITS = 30; - - public: - uint64_t gen:56; // entry storage generation number - uint64_t hashShift:8; // multiplicative hash shift - Entry* table; // entry storage - uint32_t entryCount; // number of entries in table - uint32_t removedCount; // removed entry sentinels in table - -#ifdef JS_DEBUG - uint64_t mutationCount; - mutable bool mEntered; - // Note that some updates to these stats are not thread-safe. See the - // comment on the three-argument overloading of HashTable::lookup(). - mutable struct Stats - { - uint32_t searches; // total number of table searches - uint32_t steps; // hash chain links traversed - uint32_t hits; // searches that found key - uint32_t misses; // searches that didn't find key - uint32_t addOverRemoved; // adds that recycled a removed entry - uint32_t removes; // calls to remove - uint32_t removeFrees; // calls to remove that freed the entry - uint32_t grows; // table expansions - uint32_t shrinks; // table contractions - uint32_t compresses; // table compressions - uint32_t rehashes; // tombstone decontaminations - } stats; -# define METER(x) x -#else -# define METER(x) -#endif - - // The default initial capacity is 32 (enough to hold 16 elements), but it - // can be as low as 4. - static const unsigned sMinCapacityLog2 = 2; - static const unsigned sMinCapacity = 1 << sMinCapacityLog2; - static const unsigned sMaxInit = JS_BIT(CAP_BITS - 1); - static const unsigned sMaxCapacity = JS_BIT(CAP_BITS); - static const unsigned sHashBits = mozilla::tl::BitSize::value; - - // Hash-table alpha is conceptually a fraction, but to avoid floating-point - // math we implement it as a ratio of integers. - static const uint8_t sAlphaDenominator = 4; - static const uint8_t sMinAlphaNumerator = 1; // min alpha: 1/4 - static const uint8_t sMaxAlphaNumerator = 3; // max alpha: 3/4 - - static const HashNumber sFreeKey = Entry::sFreeKey; - static const HashNumber sRemovedKey = Entry::sRemovedKey; - static const HashNumber sCollisionBit = Entry::sCollisionBit; - - void setTableSizeLog2(unsigned sizeLog2) - { - hashShift = sHashBits - sizeLog2; - } - - static bool isLiveHash(HashNumber hash) - { - return Entry::isLiveHash(hash); - } - - static HashNumber prepareHash(const Lookup& l) - { - HashNumber keyHash = ScrambleHashCode(HashPolicy::hash(l)); - - // Avoid reserved hash codes. - if (!isLiveHash(keyHash)) - keyHash -= (sRemovedKey + 1); - return keyHash & ~sCollisionBit; - } - - enum FailureBehavior { DontReportFailure = false, ReportFailure = true }; - - static Entry* createTable(AllocPolicy& alloc, uint32_t capacity, - FailureBehavior reportFailure = ReportFailure) - { - static_assert(sFreeKey == 0, - "newly-calloc'd tables have to be considered empty"); - if (reportFailure) - return alloc.template pod_calloc(capacity); - - return alloc.template maybe_pod_calloc(capacity); - } - - static Entry* maybeCreateTable(AllocPolicy& alloc, uint32_t capacity) - { - static_assert(sFreeKey == 0, - "newly-calloc'd tables have to be considered empty"); - return alloc.template maybe_pod_calloc(capacity); - } - - static void destroyTable(AllocPolicy& alloc, Entry* oldTable, uint32_t capacity) - { - Entry* end = oldTable + capacity; - for (Entry* e = oldTable; e < end; ++e) - e->destroyIfLive(); - alloc.free_(oldTable); - } - - public: - explicit HashTable(AllocPolicy ap) - : AllocPolicy(ap) - , gen(0) - , hashShift(sHashBits) - , table(nullptr) - , entryCount(0) - , removedCount(0) -#ifdef JS_DEBUG - , mutationCount(0) - , mEntered(false) -#endif - {} - - MOZ_MUST_USE bool init(uint32_t length) - { - MOZ_ASSERT(!initialized()); - - // Reject all lengths whose initial computed capacity would exceed - // sMaxCapacity. Round that maximum length down to the nearest power - // of two for speedier code. - if (MOZ_UNLIKELY(length > sMaxInit)) { - this->reportAllocOverflow(); - return false; - } - - static_assert((sMaxInit * sAlphaDenominator) / sAlphaDenominator == sMaxInit, - "multiplication in numerator below could overflow"); - static_assert(sMaxInit * sAlphaDenominator <= UINT32_MAX - sMaxAlphaNumerator, - "numerator calculation below could potentially overflow"); - - // Compute the smallest capacity allowing |length| elements to be - // inserted without rehashing: ceil(length / max-alpha). (Ceiling - // integral division: .) - uint32_t newCapacity = - (length * sAlphaDenominator + sMaxAlphaNumerator - 1) / sMaxAlphaNumerator; - if (newCapacity < sMinCapacity) - newCapacity = sMinCapacity; - - // FIXME: use JS_CEILING_LOG2 when PGO stops crashing (bug 543034). - uint32_t roundUp = sMinCapacity, roundUpLog2 = sMinCapacityLog2; - while (roundUp < newCapacity) { - roundUp <<= 1; - ++roundUpLog2; - } - - newCapacity = roundUp; - MOZ_ASSERT(newCapacity >= length); - MOZ_ASSERT(newCapacity <= sMaxCapacity); - - table = createTable(*this, newCapacity); - if (!table) - return false; - - setTableSizeLog2(roundUpLog2); - METER(memset(&stats, 0, sizeof(stats))); - return true; - } - - bool initialized() const - { - return !!table; - } - - ~HashTable() - { - if (table) - destroyTable(*this, table, capacity()); - } - - private: - HashNumber hash1(HashNumber hash0) const - { - return hash0 >> hashShift; - } - - struct DoubleHash - { - HashNumber h2; - HashNumber sizeMask; - }; - - DoubleHash hash2(HashNumber curKeyHash) const - { - unsigned sizeLog2 = sHashBits - hashShift; - DoubleHash dh = { - ((curKeyHash << sizeLog2) >> hashShift) | 1, - (HashNumber(1) << sizeLog2) - 1 - }; - return dh; - } - - static HashNumber applyDoubleHash(HashNumber h1, const DoubleHash& dh) - { - return (h1 - dh.h2) & dh.sizeMask; - } - - bool overloaded() - { - static_assert(sMaxCapacity <= UINT32_MAX / sMaxAlphaNumerator, - "multiplication below could overflow"); - return entryCount + removedCount >= - capacity() * sMaxAlphaNumerator / sAlphaDenominator; - } - - // Would the table be underloaded if it had the given capacity and entryCount? - static bool wouldBeUnderloaded(uint32_t capacity, uint32_t entryCount) - { - static_assert(sMaxCapacity <= UINT32_MAX / sMinAlphaNumerator, - "multiplication below could overflow"); - return capacity > sMinCapacity && - entryCount <= capacity * sMinAlphaNumerator / sAlphaDenominator; - } - - bool underloaded() - { - return wouldBeUnderloaded(capacity(), entryCount); - } - - static bool match(Entry& e, const Lookup& l) - { - return HashPolicy::match(HashPolicy::getKey(e.get()), l); - } - - // Warning: in order for readonlyThreadsafeLookup() to be safe this - // function must not modify the table in any way when |collisionBit| is 0. - // (The use of the METER() macro to increment stats violates this - // restriction but we will live with that for now because it's enabled so - // rarely.) - Entry& lookup(const Lookup& l, HashNumber keyHash, unsigned collisionBit) const - { - MOZ_ASSERT(isLiveHash(keyHash)); - MOZ_ASSERT(!(keyHash & sCollisionBit)); - MOZ_ASSERT(collisionBit == 0 || collisionBit == sCollisionBit); - MOZ_ASSERT(table); - METER(stats.searches++); - - // Compute the primary hash address. - HashNumber h1 = hash1(keyHash); - Entry* entry = &table[h1]; - - // Miss: return space for a new entry. - if (entry->isFree()) { - METER(stats.misses++); - return *entry; - } - - // Hit: return entry. - if (entry->matchHash(keyHash) && match(*entry, l)) { - METER(stats.hits++); - return *entry; - } - - // Collision: double hash. - DoubleHash dh = hash2(keyHash); - - // Save the first removed entry pointer so we can recycle later. - Entry* firstRemoved = nullptr; - - while (true) { - if (MOZ_UNLIKELY(entry->isRemoved())) { - if (!firstRemoved) - firstRemoved = entry; - } else { - if (collisionBit == sCollisionBit) - entry->setCollision(); - } - - METER(stats.steps++); - h1 = applyDoubleHash(h1, dh); - - entry = &table[h1]; - if (entry->isFree()) { - METER(stats.misses++); - return firstRemoved ? *firstRemoved : *entry; - } - - if (entry->matchHash(keyHash) && match(*entry, l)) { - METER(stats.hits++); - return *entry; - } - } - } - - // This is a copy of lookup hardcoded to the assumptions: - // 1. the lookup is a lookupForAdd - // 2. the key, whose |keyHash| has been passed is not in the table, - // 3. no entries have been removed from the table. - // This specialized search avoids the need for recovering lookup values - // from entries, which allows more flexible Lookup/Key types. - Entry& findFreeEntry(HashNumber keyHash) - { - MOZ_ASSERT(!(keyHash & sCollisionBit)); - MOZ_ASSERT(table); - METER(stats.searches++); - - // We assume 'keyHash' has already been distributed. - - // Compute the primary hash address. - HashNumber h1 = hash1(keyHash); - Entry* entry = &table[h1]; - - // Miss: return space for a new entry. - if (!entry->isLive()) { - METER(stats.misses++); - return *entry; - } - - // Collision: double hash. - DoubleHash dh = hash2(keyHash); - - while (true) { - MOZ_ASSERT(!entry->isRemoved()); - entry->setCollision(); - - METER(stats.steps++); - h1 = applyDoubleHash(h1, dh); - - entry = &table[h1]; - if (!entry->isLive()) { - METER(stats.misses++); - return *entry; - } - } - } - - enum RebuildStatus { NotOverloaded, Rehashed, RehashFailed }; - - RebuildStatus changeTableSize(int deltaLog2, FailureBehavior reportFailure = ReportFailure) - { - // Look, but don't touch, until we succeed in getting new entry store. - Entry* oldTable = table; - uint32_t oldCap = capacity(); - uint32_t newLog2 = sHashBits - hashShift + deltaLog2; - uint32_t newCapacity = JS_BIT(newLog2); - if (MOZ_UNLIKELY(newCapacity > sMaxCapacity)) { - if (reportFailure) - this->reportAllocOverflow(); - return RehashFailed; - } - - Entry* newTable = createTable(*this, newCapacity, reportFailure); - if (!newTable) - return RehashFailed; - - // We can't fail from here on, so update table parameters. - setTableSizeLog2(newLog2); - removedCount = 0; - gen++; - table = newTable; - - // Copy only live entries, leaving removed ones behind. - Entry* end = oldTable + oldCap; - for (Entry* src = oldTable; src < end; ++src) { - if (src->isLive()) { - HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive( - hn, mozilla::Move(const_cast(src->get()))); - src->destroy(); - } - } - - // All entries have been destroyed, no need to destroyTable. - this->free_(oldTable); - return Rehashed; - } - - bool shouldCompressTable() - { - // Compress if a quarter or more of all entries are removed. - return removedCount >= (capacity() >> 2); - } - - RebuildStatus checkOverloaded(FailureBehavior reportFailure = ReportFailure) - { - if (!overloaded()) - return NotOverloaded; - - int deltaLog2; - if (shouldCompressTable()) { - METER(stats.compresses++); - deltaLog2 = 0; - } else { - METER(stats.grows++); - deltaLog2 = 1; - } - - return changeTableSize(deltaLog2, reportFailure); - } - - // Infallibly rehash the table if we are overloaded with removals. - void checkOverRemoved() - { - if (overloaded()) { - if (checkOverloaded(DontReportFailure) == RehashFailed) - rehashTableInPlace(); - } - } - - void remove(Entry& e) - { - MOZ_ASSERT(table); - METER(stats.removes++); - - if (e.hasCollision()) { - e.removeLive(); - removedCount++; - } else { - METER(stats.removeFrees++); - e.clearLive(); - } - entryCount--; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - void checkUnderloaded() - { - if (underloaded()) { - METER(stats.shrinks++); - (void) changeTableSize(-1, DontReportFailure); - } - } - - // Resize the table down to the largest capacity which doesn't underload the - // table. Since we call checkUnderloaded() on every remove, you only need - // to call this after a bulk removal of items done without calling remove(). - void compactIfUnderloaded() - { - int32_t resizeLog2 = 0; - uint32_t newCapacity = capacity(); - while (wouldBeUnderloaded(newCapacity, entryCount)) { - newCapacity = newCapacity >> 1; - resizeLog2--; - } - - if (resizeLog2 != 0) - (void) changeTableSize(resizeLog2, DontReportFailure); - } - - // This is identical to changeTableSize(currentSize), but without requiring - // a second table. We do this by recycling the collision bits to tell us if - // the element is already inserted or still waiting to be inserted. Since - // already-inserted elements win any conflicts, we get the same table as we - // would have gotten through random insertion order. - void rehashTableInPlace() - { - METER(stats.rehashes++); - removedCount = 0; - for (size_t i = 0; i < capacity(); ++i) - table[i].unsetCollision(); - - for (size_t i = 0; i < capacity();) { - Entry* src = &table[i]; - - if (!src->isLive() || src->hasCollision()) { - ++i; - continue; - } - - HashNumber keyHash = src->getKeyHash(); - HashNumber h1 = hash1(keyHash); - DoubleHash dh = hash2(keyHash); - Entry* tgt = &table[h1]; - while (true) { - if (!tgt->hasCollision()) { - src->swap(tgt); - tgt->setCollision(); - break; - } - - h1 = applyDoubleHash(h1, dh); - tgt = &table[h1]; - } - } - - // TODO: this algorithm leaves collision bits on *all* elements, even if - // they are on no collision path. We have the option of setting the - // collision bits correctly on a subsequent pass or skipping the rehash - // unless we are totally filled with tombstones: benchmark to find out - // which approach is best. - } - - // Note: |l| may be a reference to a piece of |u|, so this function - // must take care not to use |l| after moving |u|. - // - // Prefer to use putNewInfallible; this function does not check - // invariants. - template - void putNewInfallibleInternal(const Lookup& l, Args&&... args) - { - MOZ_ASSERT(table); - - HashNumber keyHash = prepareHash(l); - Entry* entry = &findFreeEntry(keyHash); - MOZ_ASSERT(entry); - - if (entry->isRemoved()) { - METER(stats.addOverRemoved++); - removedCount--; - keyHash |= sCollisionBit; - } - - entry->setLive(keyHash, mozilla::Forward(args)...); - entryCount++; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - public: - void clear() - { - if (mozilla::IsPod::value) { - memset(table, 0, sizeof(*table) * capacity()); - } else { - uint32_t tableCapacity = capacity(); - Entry* end = table + tableCapacity; - for (Entry* e = table; e < end; ++e) - e->clear(); - } - removedCount = 0; - entryCount = 0; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - void finish() - { -#ifdef JS_DEBUG - MOZ_ASSERT(!mEntered); -#endif - if (!table) - return; - - destroyTable(*this, table, capacity()); - table = nullptr; - gen++; - entryCount = 0; - removedCount = 0; -#ifdef JS_DEBUG - mutationCount++; -#endif - } - - Range all() const - { - MOZ_ASSERT(table); - return Range(*this, table, table + capacity()); - } - - bool empty() const - { - MOZ_ASSERT(table); - return !entryCount; - } - - uint32_t count() const - { - MOZ_ASSERT(table); - return entryCount; - } - - uint32_t capacity() const - { - MOZ_ASSERT(table); - return JS_BIT(sHashBits - hashShift); - } - - Generation generation() const - { - MOZ_ASSERT(table); - return Generation(gen); - } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const - { - return mallocSizeOf(table); - } - - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const - { - return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf); - } - - Ptr lookup(const Lookup& l) const - { - mozilla::ReentrancyGuard g(*this); - if (!HasHash(l)) - return Ptr(); - HashNumber keyHash = prepareHash(l); - return Ptr(lookup(l, keyHash, 0), *this); - } - - Ptr readonlyThreadsafeLookup(const Lookup& l) const - { - if (!HasHash(l)) - return Ptr(); - HashNumber keyHash = prepareHash(l); - return Ptr(lookup(l, keyHash, 0), *this); - } - - AddPtr lookupForAdd(const Lookup& l) const - { - mozilla::ReentrancyGuard g(*this); - if (!EnsureHash(l)) - return AddPtr(); - HashNumber keyHash = prepareHash(l); - Entry& entry = lookup(l, keyHash, sCollisionBit); - AddPtr p(entry, *this, keyHash); - return p; - } - - template - MOZ_MUST_USE bool add(AddPtr& p, Args&&... args) - { - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(table); - MOZ_ASSERT(!p.found()); - MOZ_ASSERT(!(p.keyHash & sCollisionBit)); - - // Check for error from ensureHash() here. - if (p.isValid()) - return false; - - // Changing an entry from removed to live does not affect whether we - // are overloaded and can be handled separately. - if (p.entry_->isRemoved()) { - if (!this->checkSimulatedOOM()) - return false; - METER(stats.addOverRemoved++); - removedCount--; - p.keyHash |= sCollisionBit; - } else { - // Preserve the validity of |p.entry_|. - RebuildStatus status = checkOverloaded(); - if (status == RehashFailed) - return false; - if (status == NotOverloaded && !this->checkSimulatedOOM()) - return false; - if (status == Rehashed) - p.entry_ = &findFreeEntry(p.keyHash); - } - - p.entry_->setLive(p.keyHash, mozilla::Forward(args)...); - entryCount++; -#ifdef JS_DEBUG - mutationCount++; - p.generation = generation(); - p.mutationCount = mutationCount; -#endif - return true; - } - - // Note: |l| may be a reference to a piece of |u|, so this function - // must take care not to use |l| after moving |u|. - template - void putNewInfallible(const Lookup& l, Args&&... args) - { - MOZ_ASSERT(!lookup(l).found()); - mozilla::ReentrancyGuard g(*this); - putNewInfallibleInternal(l, mozilla::Forward(args)...); - } - - // Note: |l| may be alias arguments in |args|, so this function must take - // care not to use |l| after moving |args|. - template - MOZ_MUST_USE bool putNew(const Lookup& l, Args&&... args) - { - if (!this->checkSimulatedOOM()) - return false; - - if (!EnsureHash(l)) - return false; - - if (checkOverloaded() == RehashFailed) - return false; - - putNewInfallible(l, mozilla::Forward(args)...); - return true; - } - - // Note: |l| may be a reference to a piece of |u|, so this function - // must take care not to use |l| after moving |u|. - template - MOZ_MUST_USE bool relookupOrAdd(AddPtr& p, const Lookup& l, Args&&... args) - { - // Check for error from ensureHash() here. - if (p.isValid()) - return false; - -#ifdef JS_DEBUG - p.generation = generation(); - p.mutationCount = mutationCount; -#endif - { - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(prepareHash(l) == p.keyHash); // l has not been destroyed - p.entry_ = &lookup(l, p.keyHash, sCollisionBit); - } - return p.found() || add(p, mozilla::Forward(args)...); - } - - void remove(Ptr p) - { - MOZ_ASSERT(table); - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(p.found()); - remove(*p.entry_); - checkUnderloaded(); - } - - void rekeyWithoutRehash(Ptr p, const Lookup& l, const Key& k) - { - MOZ_ASSERT(table); - mozilla::ReentrancyGuard g(*this); - MOZ_ASSERT(p.found()); - typename HashTableEntry::NonConstT t(mozilla::Move(*p)); - HashPolicy::setKey(t, const_cast(k)); - remove(*p.entry_); - putNewInfallibleInternal(l, mozilla::Move(t)); - } - - void rekeyAndMaybeRehash(Ptr p, const Lookup& l, const Key& k) - { - rekeyWithoutRehash(p, l, k); - checkOverRemoved(); - } - -#undef METER -}; - -} // namespace detail -} // namespace js - -#endif /* js_HashTable_h */ diff --git a/win32/include/spidermonkey/js/HeapAPI.h b/win32/include/spidermonkey/js/HeapAPI.h deleted file mode 100755 index e37d13e9..00000000 --- a/win32/include/spidermonkey/js/HeapAPI.h +++ /dev/null @@ -1,406 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_HeapAPI_h -#define js_HeapAPI_h - -#include - -#include "jspubtd.h" - -#include "js/TraceKind.h" -#include "js/Utility.h" - -/* These values are private to the JS engine. */ -namespace js { - -JS_FRIEND_API(bool) -CurrentThreadCanAccessZone(JS::Zone* zone); - -namespace gc { - -struct Cell; - -const size_t ArenaShift = 12; -const size_t ArenaSize = size_t(1) << ArenaShift; -const size_t ArenaMask = ArenaSize - 1; - -#ifdef JS_GC_SMALL_CHUNK_SIZE -const size_t ChunkShift = 18; -#else -const size_t ChunkShift = 20; -#endif -const size_t ChunkSize = size_t(1) << ChunkShift; -const size_t ChunkMask = ChunkSize - 1; - -const size_t CellShift = 3; -const size_t CellSize = size_t(1) << CellShift; -const size_t CellMask = CellSize - 1; - -/* These are magic constants derived from actual offsets in gc/Heap.h. */ -#ifdef JS_GC_SMALL_CHUNK_SIZE -const size_t ChunkMarkBitmapOffset = 258104; -const size_t ChunkMarkBitmapBits = 31744; -#else -const size_t ChunkMarkBitmapOffset = 1032352; -const size_t ChunkMarkBitmapBits = 129024; -#endif -const size_t ChunkRuntimeOffset = ChunkSize - sizeof(void*); -const size_t ChunkTrailerSize = 2 * sizeof(uintptr_t) + sizeof(uint64_t); -const size_t ChunkLocationOffset = ChunkSize - ChunkTrailerSize; -const size_t ArenaZoneOffset = sizeof(size_t); -const size_t ArenaHeaderSize = sizeof(size_t) + 2 * sizeof(uintptr_t) + - sizeof(size_t) + sizeof(uintptr_t); - -/* - * Live objects are marked black. How many other additional colors are available - * depends on the size of the GCThing. Objects marked gray are eligible for - * cycle collection. - */ -static const uint32_t BLACK = 0; -static const uint32_t GRAY = 1; - -/* - * The "location" field in the Chunk trailer is a enum indicating various roles - * of the chunk. - */ -enum class ChunkLocation : uint32_t -{ - Invalid = 0, - Nursery = 1, - TenuredHeap = 2 -}; - -#ifdef JS_DEBUG -/* When downcasting, ensure we are actually the right type. */ -extern JS_FRIEND_API(void) -AssertGCThingHasType(js::gc::Cell* cell, JS::TraceKind kind); -#else -inline void -AssertGCThingHasType(js::gc::Cell* cell, JS::TraceKind kind) {} -#endif - -MOZ_ALWAYS_INLINE bool IsInsideNursery(const js::gc::Cell* cell); - -} /* namespace gc */ -} /* namespace js */ - -namespace JS { -struct Zone; - -/* Default size for the generational nursery in bytes. */ -const uint32_t DefaultNurseryBytes = 16 * js::gc::ChunkSize; - -/* Default maximum heap size in bytes to pass to JS_NewRuntime(). */ -const uint32_t DefaultHeapMaxBytes = 32 * 1024 * 1024; - -namespace shadow { - -struct Zone -{ - protected: - JSRuntime* const runtime_; - JSTracer* const barrierTracer_; // A pointer to the JSRuntime's |gcMarker|. - - public: - // Stack GC roots for Rooted GC pointers. - js::RootedListHeads stackRoots_; - template friend class JS::Rooted; - - bool needsIncrementalBarrier_; - - Zone(JSRuntime* runtime, JSTracer* barrierTracerArg) - : runtime_(runtime), - barrierTracer_(barrierTracerArg), - needsIncrementalBarrier_(false) - { - for (auto& stackRootPtr : stackRoots_) - stackRootPtr = nullptr; - } - - bool needsIncrementalBarrier() const { - return needsIncrementalBarrier_; - } - - JSTracer* barrierTracer() { - MOZ_ASSERT(needsIncrementalBarrier_); - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); - return barrierTracer_; - } - - JSRuntime* runtimeFromMainThread() const { - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); - return runtime_; - } - - // Note: Unrestricted access to the zone's runtime from an arbitrary - // thread can easily lead to races. Use this method very carefully. - JSRuntime* runtimeFromAnyThread() const { - return runtime_; - } - - static MOZ_ALWAYS_INLINE JS::shadow::Zone* asShadowZone(JS::Zone* zone) { - return reinterpret_cast(zone); - } -}; - -} /* namespace shadow */ - -/** - * A GC pointer, tagged with the trace kind. - * - * In general, a GC pointer should be stored with an exact type. This class - * is for use when that is not possible because a single pointer must point - * to several kinds of GC thing. - */ -class JS_FRIEND_API(GCCellPtr) -{ - public: - // Construction from a void* and trace kind. - GCCellPtr(void* gcthing, JS::TraceKind traceKind) : ptr(checkedCast(gcthing, traceKind)) {} - - // Automatically construct a null GCCellPtr from nullptr. - MOZ_IMPLICIT GCCellPtr(decltype(nullptr)) : ptr(checkedCast(nullptr, JS::TraceKind::Null)) {} - - // Construction from an explicit type. - template - explicit GCCellPtr(T* p) : ptr(checkedCast(p, JS::MapTypeToTraceKind::kind)) { } - explicit GCCellPtr(JSFunction* p) : ptr(checkedCast(p, JS::TraceKind::Object)) { } - explicit GCCellPtr(JSFlatString* str) : ptr(checkedCast(str, JS::TraceKind::String)) { } - explicit GCCellPtr(const Value& v); - - JS::TraceKind kind() const { - JS::TraceKind traceKind = JS::TraceKind(ptr & OutOfLineTraceKindMask); - if (uintptr_t(traceKind) != OutOfLineTraceKindMask) - return traceKind; - return outOfLineKind(); - } - - // Allow GCCellPtr to be used in a boolean context. - explicit operator bool() const { - MOZ_ASSERT(bool(asCell()) == (kind() != JS::TraceKind::Null)); - return asCell(); - } - - // Simplify checks to the kind. - template - bool is() const { return kind() == JS::MapTypeToTraceKind::kind; } - - // Conversions to more specific types must match the kind. Access to - // further refined types is not allowed directly from a GCCellPtr. - template - T& as() const { - MOZ_ASSERT(kind() == JS::MapTypeToTraceKind::kind); - // We can't use static_cast here, because the fact that JSObject - // inherits from js::gc::Cell is not part of the public API. - return *reinterpret_cast(asCell()); - } - - // Return a pointer to the cell this |GCCellPtr| refers to, or |nullptr|. - // (It would be more symmetrical with |to| for this to return a |Cell&|, but - // the result can be |nullptr|, and null references are undefined behavior.) - js::gc::Cell* asCell() const { - return reinterpret_cast(ptr & ~OutOfLineTraceKindMask); - } - - // The CC's trace logger needs an identity that is XPIDL serializable. - uint64_t unsafeAsInteger() const { - return static_cast(unsafeAsUIntPtr()); - } - // Inline mark bitmap access requires direct pointer arithmetic. - uintptr_t unsafeAsUIntPtr() const { - MOZ_ASSERT(asCell()); - MOZ_ASSERT(!js::gc::IsInsideNursery(asCell())); - return reinterpret_cast(asCell()); - } - - bool mayBeOwnedByOtherRuntime() const; - - private: - static uintptr_t checkedCast(void* p, JS::TraceKind traceKind) { - js::gc::Cell* cell = static_cast(p); - MOZ_ASSERT((uintptr_t(p) & OutOfLineTraceKindMask) == 0); - AssertGCThingHasType(cell, traceKind); - // Note: the OutOfLineTraceKindMask bits are set on all out-of-line kinds - // so that we can mask instead of branching. - MOZ_ASSERT_IF(uintptr_t(traceKind) >= OutOfLineTraceKindMask, - (uintptr_t(traceKind) & OutOfLineTraceKindMask) == OutOfLineTraceKindMask); - return uintptr_t(p) | (uintptr_t(traceKind) & OutOfLineTraceKindMask); - } - - JS::TraceKind outOfLineKind() const; - - uintptr_t ptr; -}; - -inline bool -operator==(const GCCellPtr& ptr1, const GCCellPtr& ptr2) -{ - return ptr1.asCell() == ptr2.asCell(); -} - -inline bool -operator!=(const GCCellPtr& ptr1, const GCCellPtr& ptr2) -{ - return !(ptr1 == ptr2); -} - -// Unwraps the given GCCellPtr and calls the given functor with a template -// argument of the actual type of the pointer. -template -auto -DispatchTyped(F f, GCCellPtr thing, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - switch (thing.kind()) { -#define JS_EXPAND_DEF(name, type, _) \ - case JS::TraceKind::name: \ - return f(&thing.as(), mozilla::Forward(args)...); - JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - default: - MOZ_CRASH("Invalid trace kind in DispatchTyped for GCCellPtr."); - } -} - -} /* namespace JS */ - -namespace js { -namespace gc { -namespace detail { - -static MOZ_ALWAYS_INLINE uintptr_t* -GetGCThingMarkBitmap(const uintptr_t addr) -{ - MOZ_ASSERT(addr); - const uintptr_t bmap_addr = (addr & ~ChunkMask) | ChunkMarkBitmapOffset; - return reinterpret_cast(bmap_addr); -} - -static MOZ_ALWAYS_INLINE void -GetGCThingMarkWordAndMask(const uintptr_t addr, uint32_t color, - uintptr_t** wordp, uintptr_t* maskp) -{ - MOZ_ASSERT(addr); - const size_t bit = (addr & js::gc::ChunkMask) / js::gc::CellSize + color; - MOZ_ASSERT(bit < js::gc::ChunkMarkBitmapBits); - uintptr_t* bitmap = GetGCThingMarkBitmap(addr); - const uintptr_t nbits = sizeof(*bitmap) * CHAR_BIT; - *maskp = uintptr_t(1) << (bit % nbits); - *wordp = &bitmap[bit / nbits]; -} - -static MOZ_ALWAYS_INLINE JS::Zone* -GetGCThingZone(const uintptr_t addr) -{ - MOZ_ASSERT(addr); - const uintptr_t zone_addr = (addr & ~ArenaMask) | ArenaZoneOffset; - return *reinterpret_cast(zone_addr); - -} - -static MOZ_ALWAYS_INLINE JS::shadow::Runtime* -GetCellRuntime(const Cell* cell) -{ - MOZ_ASSERT(cell); - const uintptr_t addr = uintptr_t(cell); - const uintptr_t rt_addr = (addr & ~ChunkMask) | ChunkRuntimeOffset; - return *reinterpret_cast(rt_addr); -} - -static MOZ_ALWAYS_INLINE bool -CellIsMarkedGray(const Cell* cell) -{ - MOZ_ASSERT(cell); - if (js::gc::IsInsideNursery(cell)) - return false; - - uintptr_t* word, mask; - js::gc::detail::GetGCThingMarkWordAndMask(uintptr_t(cell), js::gc::GRAY, &word, &mask); - return *word & mask; -} - -extern JS_PUBLIC_API(bool) -CellIsMarkedGrayIfKnown(const Cell* cell); - -} /* namespace detail */ - -MOZ_ALWAYS_INLINE bool -IsInsideNursery(const js::gc::Cell* cell) -{ - if (!cell) - return false; - uintptr_t addr = uintptr_t(cell); - addr &= ~js::gc::ChunkMask; - addr |= js::gc::ChunkLocationOffset; - auto location = *reinterpret_cast(addr); - MOZ_ASSERT(location == ChunkLocation::Nursery || location == ChunkLocation::TenuredHeap); - return location == ChunkLocation::Nursery; -} - -} /* namespace gc */ -} /* namespace js */ - -namespace JS { - -static MOZ_ALWAYS_INLINE Zone* -GetTenuredGCThingZone(GCCellPtr thing) -{ - MOZ_ASSERT(!js::gc::IsInsideNursery(thing.asCell())); - return js::gc::detail::GetGCThingZone(thing.unsafeAsUIntPtr()); -} - -static MOZ_ALWAYS_INLINE Zone* -GetStringZone(JSString* str) -{ - return js::gc::detail::GetGCThingZone(uintptr_t(str)); -} - -extern JS_PUBLIC_API(Zone*) -GetObjectZone(JSObject* obj); - -static MOZ_ALWAYS_INLINE bool -GCThingIsMarkedGray(GCCellPtr thing) -{ - if (thing.mayBeOwnedByOtherRuntime()) - return false; - return js::gc::detail::CellIsMarkedGrayIfKnown(thing.asCell()); -} - -extern JS_PUBLIC_API(JS::TraceKind) -GCThingTraceKind(void* thing); - -} /* namespace JS */ - -namespace js { -namespace gc { - -static MOZ_ALWAYS_INLINE bool -IsIncrementalBarrierNeededOnTenuredGCThing(JS::shadow::Runtime* rt, const JS::GCCellPtr thing) -{ - MOZ_ASSERT(thing); - MOZ_ASSERT(!js::gc::IsInsideNursery(thing.asCell())); - - // TODO: I'd like to assert !isHeapBusy() here but this gets called while we - // are tracing the heap, e.g. during memory reporting (see bug 1313318). - MOZ_ASSERT(!rt->isHeapCollecting()); - - JS::Zone* zone = JS::GetTenuredGCThingZone(thing); - return JS::shadow::Zone::asShadowZone(zone)->needsIncrementalBarrier(); -} - -/** - * Create an object providing access to the garbage collector's internal notion - * of the current state of memory (both GC heap memory and GCthing-controlled - * malloc memory. - */ -extern JS_PUBLIC_API(JSObject*) -NewMemoryInfoObject(JSContext* cx); - -} /* namespace gc */ -} /* namespace js */ - -#endif /* js_HeapAPI_h */ diff --git a/win32/include/spidermonkey/js/Id.h b/win32/include/spidermonkey/js/Id.h deleted file mode 100755 index d474e784..00000000 --- a/win32/include/spidermonkey/js/Id.h +++ /dev/null @@ -1,207 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Id_h -#define js_Id_h - -// A jsid is an identifier for a property or method of an object which is -// either a 31-bit unsigned integer, interned string or symbol. -// -// Also, there is an additional jsid value, JSID_VOID, which does not occur in -// JS scripts but may be used to indicate the absence of a valid jsid. A void -// jsid is not a valid id and only arises as an exceptional API return value, -// such as in JS_NextProperty. Embeddings must not pass JSID_VOID into JSAPI -// entry points expecting a jsid and do not need to handle JSID_VOID in hooks -// receiving a jsid except when explicitly noted in the API contract. -// -// A jsid is not implicitly convertible to or from a Value; JS_ValueToId or -// JS_IdToValue must be used instead. - -#include "jstypes.h" - -#include "js/HeapAPI.h" -#include "js/RootingAPI.h" -#include "js/TypeDecls.h" -#include "js/Utility.h" - -struct jsid -{ - size_t asBits; - bool operator==(const jsid& rhs) const { return asBits == rhs.asBits; } - bool operator!=(const jsid& rhs) const { return asBits != rhs.asBits; } -} JS_HAZ_GC_POINTER; -#define JSID_BITS(id) (id.asBits) - -#define JSID_TYPE_STRING 0x0 -#define JSID_TYPE_INT 0x1 -#define JSID_TYPE_VOID 0x2 -#define JSID_TYPE_SYMBOL 0x4 -#define JSID_TYPE_MASK 0x7 - -// Avoid using canonical 'id' for jsid parameters since this is a magic word in -// Objective-C++ which, apparently, wants to be able to #include jsapi.h. -#define id iden - -static MOZ_ALWAYS_INLINE bool -JSID_IS_STRING(jsid id) -{ - return (JSID_BITS(id) & JSID_TYPE_MASK) == 0; -} - -static MOZ_ALWAYS_INLINE JSString* -JSID_TO_STRING(jsid id) -{ - MOZ_ASSERT(JSID_IS_STRING(id)); - return (JSString*)JSID_BITS(id); -} - -/** - * Only JSStrings that have been interned via the JSAPI can be turned into - * jsids by API clients. - * - * N.B. if a jsid is backed by a string which has not been interned, that - * string must be appropriately rooted to avoid being collected by the GC. - */ -JS_PUBLIC_API(jsid) -INTERNED_STRING_TO_JSID(JSContext* cx, JSString* str); - -static MOZ_ALWAYS_INLINE bool -JSID_IS_INT(jsid id) -{ - return !!(JSID_BITS(id) & JSID_TYPE_INT); -} - -static MOZ_ALWAYS_INLINE int32_t -JSID_TO_INT(jsid id) -{ - MOZ_ASSERT(JSID_IS_INT(id)); - return ((uint32_t)JSID_BITS(id)) >> 1; -} - -#define JSID_INT_MIN 0 -#define JSID_INT_MAX INT32_MAX - -static MOZ_ALWAYS_INLINE bool -INT_FITS_IN_JSID(int32_t i) -{ - return i >= 0; -} - -static MOZ_ALWAYS_INLINE jsid -INT_TO_JSID(int32_t i) -{ - jsid id; - MOZ_ASSERT(INT_FITS_IN_JSID(i)); - JSID_BITS(id) = ((i << 1) | JSID_TYPE_INT); - return id; -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_SYMBOL(jsid id) -{ - return (JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_SYMBOL && - JSID_BITS(id) != JSID_TYPE_SYMBOL; -} - -static MOZ_ALWAYS_INLINE JS::Symbol* -JSID_TO_SYMBOL(jsid id) -{ - MOZ_ASSERT(JSID_IS_SYMBOL(id)); - return (JS::Symbol*)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); -} - -static MOZ_ALWAYS_INLINE jsid -SYMBOL_TO_JSID(JS::Symbol* sym) -{ - jsid id; - MOZ_ASSERT(sym != nullptr); - MOZ_ASSERT((size_t(sym) & JSID_TYPE_MASK) == 0); - MOZ_ASSERT(!js::gc::IsInsideNursery(reinterpret_cast(sym))); - JSID_BITS(id) = (size_t(sym) | JSID_TYPE_SYMBOL); - return id; -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_GCTHING(jsid id) -{ - return JSID_IS_STRING(id) || JSID_IS_SYMBOL(id); -} - -static MOZ_ALWAYS_INLINE JS::GCCellPtr -JSID_TO_GCTHING(jsid id) -{ - void* thing = (void*)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); - if (JSID_IS_STRING(id)) - return JS::GCCellPtr(thing, JS::TraceKind::String); - MOZ_ASSERT(JSID_IS_SYMBOL(id)); - return JS::GCCellPtr(thing, JS::TraceKind::Symbol); -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_VOID(const jsid id) -{ - MOZ_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_VOID, - JSID_BITS(id) == JSID_TYPE_VOID); - return (size_t)JSID_BITS(id) == JSID_TYPE_VOID; -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_EMPTY(const jsid id) -{ - return (size_t)JSID_BITS(id) == JSID_TYPE_SYMBOL; -} - -extern JS_PUBLIC_DATA(const jsid) JSID_VOID; -extern JS_PUBLIC_DATA(const jsid) JSID_EMPTY; - -extern JS_PUBLIC_DATA(const JS::HandleId) JSID_VOIDHANDLE; -extern JS_PUBLIC_DATA(const JS::HandleId) JSID_EMPTYHANDLE; - -namespace JS { - -template <> -struct GCPolicy -{ - static jsid initial() { return JSID_VOID; } - static void trace(JSTracer* trc, jsid* idp, const char* name) { - js::UnsafeTraceManuallyBarrieredEdge(trc, idp, name); - } -}; - -} // namespace JS - -namespace js { - -template <> -struct BarrierMethods -{ - static void postBarrier(jsid* idp, jsid prev, jsid next) {} - static void exposeToJS(jsid id) { - if (JSID_IS_GCTHING(id)) - js::gc::ExposeGCThingToActiveJS(JSID_TO_GCTHING(id)); - } -}; - -// If the jsid is a GC pointer type, convert to that type and call |f| with -// the pointer. If the jsid is not a GC type, calls F::defaultValue. -template -auto -DispatchTyped(F f, const jsid& id, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - if (JSID_IS_STRING(id)) - return f(JSID_TO_STRING(id), mozilla::Forward(args)...); - if (JSID_IS_SYMBOL(id)) - return f(JSID_TO_SYMBOL(id), mozilla::Forward(args)...); - MOZ_ASSERT(!JSID_IS_GCTHING(id)); - return F::defaultValue(id); -} - -#undef id - -} // namespace js - -#endif /* js_Id_h */ diff --git a/win32/include/spidermonkey/js/Initialization.h b/win32/include/spidermonkey/js/Initialization.h deleted file mode 100755 index 8a1cf910..00000000 --- a/win32/include/spidermonkey/js/Initialization.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* SpiderMonkey initialization and shutdown APIs. */ - -#ifndef js_Initialization_h -#define js_Initialization_h - -#include "jstypes.h" - -namespace JS { -namespace detail { - -enum class InitState { Uninitialized = 0, Running, ShutDown }; - -/** - * SpiderMonkey's initialization status is tracked here, and it controls things - * that should happen only once across all runtimes. It's an API requirement - * that JS_Init (and JS_ShutDown, if called) be called in a thread-aware - * manner, so this (internal -- embedders, don't use!) variable doesn't need to - * be atomic. - */ -extern JS_PUBLIC_DATA(InitState) -libraryInitState; - -extern JS_PUBLIC_API(const char*) -InitWithFailureDiagnostic(bool isDebugBuild); - -} // namespace detail -} // namespace JS - -// These are equivalent to ICU's |UMemAllocFn|, |UMemReallocFn|, and -// |UMemFreeFn| types. The first argument (called |context| in the ICU docs) -// will always be nullptr and should be ignored. -typedef void* (*JS_ICUAllocFn)(const void*, size_t size); -typedef void* (*JS_ICUReallocFn)(const void*, void* p, size_t size); -typedef void (*JS_ICUFreeFn)(const void*, void* p); - -/** - * This function can be used to track memory used by ICU. If it is called, it - * *must* be called before JS_Init. Don't use it unless you know what you're - * doing! - */ -extern JS_PUBLIC_API(bool) -JS_SetICUMemoryFunctions(JS_ICUAllocFn allocFn, - JS_ICUReallocFn reallocFn, - JS_ICUFreeFn freeFn); - -/** - * Initialize SpiderMonkey, returning true only if initialization succeeded. - * Once this method has succeeded, it is safe to call JS_NewRuntime and other - * JSAPI methods. - * - * This method must be called before any other JSAPI method is used on any - * thread. Once it has been used, it is safe to call any JSAPI method, and it - * remains safe to do so until JS_ShutDown is correctly called. - * - * It is currently not possible to initialize SpiderMonkey multiple times (that - * is, calling JS_Init/JSAPI methods/JS_ShutDown in that order, then doing so - * again). This restriction may eventually be lifted. - */ -inline bool -JS_Init(void) -{ -#ifdef DEBUG - return !JS::detail::InitWithFailureDiagnostic(true); -#else - return !JS::detail::InitWithFailureDiagnostic(false); -#endif -} - -/** - * A variant of JS_Init. On success it returns nullptr. On failure it returns a - * pointer to a string literal that describes how initialization failed, which - * can be useful for debugging purposes. - */ -inline const char* -JS_InitWithFailureDiagnostic(void) -{ -#ifdef DEBUG - return JS::detail::InitWithFailureDiagnostic(true); -#else - return JS::detail::InitWithFailureDiagnostic(false); -#endif -} - -/* - * Returns true if SpiderMonkey has been initialized successfully, even if it has - * possibly been shut down. - * - * Note that it is the responsibility of the embedder to call JS_Init() and - * JS_ShutDown() at the correct times, and therefore this API should ideally not - * be necessary to use. This is only intended to be used in cases where the - * embedder isn't in full control of deciding whether to initialize SpiderMonkey - * or hand off the task to another consumer. - */ -inline bool -JS_IsInitialized(void) -{ - return JS::detail::libraryInitState != JS::detail::InitState::Uninitialized; -} - -/** - * Destroy free-standing resources allocated by SpiderMonkey, not associated - * with any runtime, context, or other structure. - * - * This method should be called after all other JSAPI data has been properly - * cleaned up: every new runtime must have been destroyed, every new context - * must have been destroyed, and so on. Calling this method before all other - * resources have been destroyed has undefined behavior. - * - * Failure to call this method, at present, has no adverse effects other than - * leaking memory. This may not always be the case; it's recommended that all - * embedders call this method when all other JSAPI operations have completed. - * - * It is currently not possible to initialize SpiderMonkey multiple times (that - * is, calling JS_Init/JSAPI methods/JS_ShutDown in that order, then doing so - * again). This restriction may eventually be lifted. - */ -extern JS_PUBLIC_API(void) -JS_ShutDown(void); - -#endif /* js_Initialization_h */ diff --git a/win32/include/spidermonkey/js/LegacyIntTypes.h b/win32/include/spidermonkey/js/LegacyIntTypes.h deleted file mode 100755 index 2c8498c8..00000000 --- a/win32/include/spidermonkey/js/LegacyIntTypes.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * This section typedefs the old 'native' types to the new types. - * These redefinitions are provided solely to allow JSAPI users to more easily - * transition to types. They are not to be used in the JSAPI, and - * new JSAPI user code should not use them. This mapping file may eventually - * be removed from SpiderMonkey, so don't depend on it in the long run. - */ - -/* - * BEWARE: Comity with other implementers of these types is not guaranteed. - * Indeed, if you use this header and third-party code defining these - * types, *expect* to encounter either compile errors or link errors, - * depending how these types are used and on the order of inclusion. - * It is safest to use only the types. - */ -#ifndef js_LegacyIntTypes_h -#define js_LegacyIntTypes_h - -#include - -#include "js-config.h" - -typedef uint8_t uint8; -typedef uint16_t uint16; -typedef uint32_t uint32; -typedef uint64_t uint64; - -/* - * On AIX 4.3, sys/inttypes.h (which is included by sys/types.h, a very - * common header file) defines the types int8, int16, int32, and int64. - * So we don't define these four types here to avoid conflicts in case - * the code also includes sys/types.h. - */ -#if defined(AIX) && defined(HAVE_SYS_INTTYPES_H) -#include -#else -typedef int8_t int8; -typedef int16_t int16; -typedef int32_t int32; -typedef int64_t int64; -#endif /* AIX && HAVE_SYS_INTTYPES_H */ - -typedef uint8_t JSUint8; -typedef uint16_t JSUint16; -typedef uint32_t JSUint32; -typedef uint64_t JSUint64; - -typedef int8_t JSInt8; -typedef int16_t JSInt16; -typedef int32_t JSInt32; -typedef int64_t JSInt64; - -#endif /* js_LegacyIntTypes_h */ diff --git a/win32/include/spidermonkey/js/MemoryMetrics.h b/win32/include/spidermonkey/js/MemoryMetrics.h deleted file mode 100755 index 9b5caa24..00000000 --- a/win32/include/spidermonkey/js/MemoryMetrics.h +++ /dev/null @@ -1,971 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_MemoryMetrics_h -#define js_MemoryMetrics_h - -// These declarations are highly likely to change in the future. Depend on them -// at your own risk. - -#include "mozilla/MemoryReporting.h" -#include "mozilla/PodOperations.h" -#include "mozilla/TypeTraits.h" - -#include - -#include "jsalloc.h" -#include "jspubtd.h" - -#include "js/HashTable.h" -#include "js/TracingAPI.h" -#include "js/Utility.h" -#include "js/Vector.h" - -class nsISupports; // Needed for ObjectPrivateVisitor. - -namespace JS { - -struct TabSizes -{ - enum Kind { - Objects, - Strings, - Private, - Other - }; - - TabSizes() { mozilla::PodZero(this); } - - void add(Kind kind, size_t n) { - switch (kind) { - case Objects: objects += n; break; - case Strings: strings += n; break; - case Private: private_ += n; break; - case Other: other += n; break; - default: MOZ_CRASH("bad TabSizes kind"); - } - } - - size_t objects; - size_t strings; - size_t private_; - size_t other; -}; - -/** These are the measurements used by Servo. */ -struct ServoSizes -{ - enum Kind { - GCHeapUsed, - GCHeapUnused, - GCHeapAdmin, - GCHeapDecommitted, - MallocHeap, - NonHeap, - Ignore - }; - - ServoSizes() { mozilla::PodZero(this); } - - void add(Kind kind, size_t n) { - switch (kind) { - case GCHeapUsed: gcHeapUsed += n; break; - case GCHeapUnused: gcHeapUnused += n; break; - case GCHeapAdmin: gcHeapAdmin += n; break; - case GCHeapDecommitted: gcHeapDecommitted += n; break; - case MallocHeap: mallocHeap += n; break; - case NonHeap: nonHeap += n; break; - case Ignore: /* do nothing */ break; - default: MOZ_CRASH("bad ServoSizes kind"); - } - } - - size_t gcHeapUsed; - size_t gcHeapUnused; - size_t gcHeapAdmin; - size_t gcHeapDecommitted; - size_t mallocHeap; - size_t nonHeap; -}; - -} // namespace JS - -namespace js { - -/** - * In memory reporting, we have concept of "sundries", line items which are too - * small to be worth reporting individually. Under some circumstances, a memory - * reporter gets tossed into the sundries bucket if it's smaller than - * MemoryReportingSundriesThreshold() bytes. - * - * We need to define this value here, rather than in the code which actually - * generates the memory reports, because NotableStringInfo uses this value. - */ -JS_FRIEND_API(size_t) MemoryReportingSundriesThreshold(); - -/** - * This hash policy avoids flattening ropes (which perturbs the site being - * measured and requires a JSContext) at the expense of doing a FULL ROPE COPY - * on every hash and match! Beware. - */ -struct InefficientNonFlatteningStringHashPolicy -{ - typedef JSString* Lookup; - static HashNumber hash(const Lookup& l); - static bool match(const JSString* const& k, const Lookup& l); -}; - -struct CStringHashPolicy -{ - typedef const char* Lookup; - static HashNumber hash(const Lookup& l); - static bool match(const char* const& k, const Lookup& l); -}; - -// This file features many classes with numerous size_t fields, and each such -// class has one or more methods that need to operate on all of these fields. -// Writing these individually is error-prone -- it's easy to add a new field -// without updating all the required methods. So we define a single macro list -// in each class to name the fields (and notable characteristics of them), and -// then use the following macros to transform those lists into the required -// methods. -// -// - The |tabKind| value is used when measuring TabSizes. -// -// - The |servoKind| value is used when measuring ServoSizes and also for -// the various sizeOfLiveGCThings() methods. -// -// In some classes, one or more of the macro arguments aren't used. We use '_' -// for those. -// -#define DECL_SIZE(tabKind, servoKind, mSize) size_t mSize; -#define ZERO_SIZE(tabKind, servoKind, mSize) mSize(0), -#define COPY_OTHER_SIZE(tabKind, servoKind, mSize) mSize(other.mSize), -#define ADD_OTHER_SIZE(tabKind, servoKind, mSize) mSize += other.mSize; -#define SUB_OTHER_SIZE(tabKind, servoKind, mSize) \ - MOZ_ASSERT(mSize >= other.mSize); \ - mSize -= other.mSize; -#define ADD_SIZE_TO_N(tabKind, servoKind, mSize) n += mSize; -#define ADD_SIZE_TO_N_IF_LIVE_GC_THING(tabKind, servoKind, mSize) \ - /* Avoid self-comparison warnings by comparing enums indirectly. */ \ - n += (mozilla::IsSame::value) \ - ? mSize \ - : 0; -#define ADD_TO_TAB_SIZES(tabKind, servoKind, mSize) sizes->add(JS::TabSizes::tabKind, mSize); -#define ADD_TO_SERVO_SIZES(tabKind, servoKind, mSize) sizes->add(JS::ServoSizes::servoKind, mSize); - -} // namespace js - -namespace JS { - -struct ClassInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(Objects, GCHeapUsed, objectsGCHeap) \ - macro(Objects, MallocHeap, objectsMallocHeapSlots) \ - macro(Objects, MallocHeap, objectsMallocHeapElementsNormal) \ - macro(Objects, MallocHeap, objectsMallocHeapElementsAsmJS) \ - macro(Objects, MallocHeap, objectsMallocHeapMisc) \ - macro(Objects, NonHeap, objectsNonHeapElementsNormal) \ - macro(Objects, NonHeap, objectsNonHeapElementsShared) \ - macro(Objects, NonHeap, objectsNonHeapElementsWasm) \ - macro(Objects, NonHeap, objectsNonHeapCodeWasm) - - ClassInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - wasmGuardPages(0) - {} - - void add(const ClassInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - } - - void subtract(const ClassInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE) - } - - size_t sizeOfAllThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n; - } - - bool isNotable() const { - static const size_t NotabilityThreshold = 16 * 1024; - return sizeOfAllThings() >= NotabilityThreshold; - } - - size_t sizeOfLiveGCThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - size_t wasmGuardPages; - -#undef FOR_EACH_SIZE -}; - -struct ShapeInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(Other, GCHeapUsed, shapesGCHeapTree) \ - macro(Other, GCHeapUsed, shapesGCHeapDict) \ - macro(Other, GCHeapUsed, shapesGCHeapBase) \ - macro(Other, MallocHeap, shapesMallocHeapTreeTables) \ - macro(Other, MallocHeap, shapesMallocHeapDictTables) \ - macro(Other, MallocHeap, shapesMallocHeapTreeKids) - - ShapeInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - void add(const ShapeInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - } - - void subtract(const ShapeInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE) - } - - size_t sizeOfAllThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n; - } - - size_t sizeOfLiveGCThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -/** - * Holds data about a notable class (one whose combined object and shape - * instances use more than a certain amount of memory) so we can report it - * individually. - * - * The only difference between this class and ClassInfo is that this class - * holds a copy of the filename. - */ -struct NotableClassInfo : public ClassInfo -{ - NotableClassInfo(); - NotableClassInfo(const char* className, const ClassInfo& info); - NotableClassInfo(NotableClassInfo&& info); - NotableClassInfo& operator=(NotableClassInfo&& info); - - ~NotableClassInfo() { - js_free(className_); - } - - char* className_; - - private: - NotableClassInfo(const NotableClassInfo& info) = delete; -}; - -/** Data for tracking JIT-code memory usage. */ -struct CodeSizes -{ -#define FOR_EACH_SIZE(macro) \ - macro(_, NonHeap, ion) \ - macro(_, NonHeap, baseline) \ - macro(_, NonHeap, regexp) \ - macro(_, NonHeap, other) \ - macro(_, NonHeap, unused) - - CodeSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -/** Data for tracking GC memory usage. */ -struct GCSizes -{ - // |nurseryDecommitted| is marked as NonHeap rather than GCHeapDecommitted - // because we don't consider the nursery to be part of the GC heap. -#define FOR_EACH_SIZE(macro) \ - macro(_, MallocHeap, marker) \ - macro(_, NonHeap, nurseryCommitted) \ - macro(_, MallocHeap, nurseryMallocedBuffers) \ - macro(_, MallocHeap, storeBufferVals) \ - macro(_, MallocHeap, storeBufferCells) \ - macro(_, MallocHeap, storeBufferSlots) \ - macro(_, MallocHeap, storeBufferWholeCells) \ - macro(_, MallocHeap, storeBufferGenerics) - - GCSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -/** - * This class holds information about the memory taken up by identical copies of - * a particular string. Multiple JSStrings may have their sizes aggregated - * together into one StringInfo object. Note that two strings with identical - * chars will not be aggregated together if one is a short string and the other - * is not. - */ -struct StringInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(Strings, GCHeapUsed, gcHeapLatin1) \ - macro(Strings, GCHeapUsed, gcHeapTwoByte) \ - macro(Strings, MallocHeap, mallocHeapLatin1) \ - macro(Strings, MallocHeap, mallocHeapTwoByte) - - StringInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - numCopies(0) - {} - - void add(const StringInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE); - numCopies++; - } - - void subtract(const StringInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE); - numCopies--; - } - - bool isNotable() const { - static const size_t NotabilityThreshold = 16 * 1024; - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n >= NotabilityThreshold; - } - - size_t sizeOfLiveGCThings() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - uint32_t numCopies; // How many copies of the string have we seen? - -#undef FOR_EACH_SIZE -}; - -/** - * Holds data about a notable string (one which, counting all duplicates, uses - * more than a certain amount of memory) so we can report it individually. - * - * The only difference between this class and StringInfo is that - * NotableStringInfo holds a copy of some or all of the string's chars. - */ -struct NotableStringInfo : public StringInfo -{ - static const size_t MAX_SAVED_CHARS = 1024; - - NotableStringInfo(); - NotableStringInfo(JSString* str, const StringInfo& info); - NotableStringInfo(NotableStringInfo&& info); - NotableStringInfo& operator=(NotableStringInfo&& info); - - ~NotableStringInfo() { - js_free(buffer); - } - - char* buffer; - size_t length; - - private: - NotableStringInfo(const NotableStringInfo& info) = delete; -}; - -/** - * This class holds information about the memory taken up by script sources - * from a particular file. - */ -struct ScriptSourceInfo -{ -#define FOR_EACH_SIZE(macro) \ - macro(_, MallocHeap, misc) - - ScriptSourceInfo() - : FOR_EACH_SIZE(ZERO_SIZE) - numScripts(0) - {} - - void add(const ScriptSourceInfo& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - numScripts++; - } - - void subtract(const ScriptSourceInfo& other) { - FOR_EACH_SIZE(SUB_OTHER_SIZE) - numScripts--; - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - bool isNotable() const { - static const size_t NotabilityThreshold = 16 * 1024; - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n >= NotabilityThreshold; - } - - FOR_EACH_SIZE(DECL_SIZE) - uint32_t numScripts; // How many ScriptSources come from this file? (It - // can be more than one in XML files that have - // multiple scripts in CDATA sections.) -#undef FOR_EACH_SIZE -}; - -/** - * Holds data about a notable script source file (one whose combined - * script sources use more than a certain amount of memory) so we can report it - * individually. - * - * The only difference between this class and ScriptSourceInfo is that this - * class holds a copy of the filename. - */ -struct NotableScriptSourceInfo : public ScriptSourceInfo -{ - NotableScriptSourceInfo(); - NotableScriptSourceInfo(const char* filename, const ScriptSourceInfo& info); - NotableScriptSourceInfo(NotableScriptSourceInfo&& info); - NotableScriptSourceInfo& operator=(NotableScriptSourceInfo&& info); - - ~NotableScriptSourceInfo() { - js_free(filename_); - } - - char* filename_; - - private: - NotableScriptSourceInfo(const NotableScriptSourceInfo& info) = delete; -}; - -/** - * These measurements relate directly to the JSRuntime, and not to zones and - * compartments within it. - */ -struct RuntimeSizes -{ -#define FOR_EACH_SIZE(macro) \ - macro(_, MallocHeap, object) \ - macro(_, MallocHeap, atomsTable) \ - macro(_, MallocHeap, contexts) \ - macro(_, MallocHeap, temporary) \ - macro(_, MallocHeap, interpreterStack) \ - macro(_, MallocHeap, mathCache) \ - macro(_, MallocHeap, sharedImmutableStringsCache) \ - macro(_, MallocHeap, sharedIntlData) \ - macro(_, MallocHeap, uncompressedSourceCache) \ - macro(_, MallocHeap, scriptData) - - RuntimeSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - scriptSourceInfo(), - code(), - gc(), - notableScriptSources() - { - allScriptSources = js_new(); - if (!allScriptSources || !allScriptSources->init()) - MOZ_CRASH("oom"); - } - - ~RuntimeSizes() { - // |allScriptSources| is usually deleted and set to nullptr before this - // destructor runs. But there are failure cases due to OOMs that may - // prevent that, so it doesn't hurt to try again here. - js_delete(allScriptSources); - } - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - scriptSourceInfo.addToServoSizes(sizes); - code.addToServoSizes(sizes); - gc.addToServoSizes(sizes); - } - - // The script source measurements in |scriptSourceInfo| are initially for - // all script sources. At the end, if the measurement granularity is - // FineGrained, we subtract the measurements of the notable script sources - // and move them into |notableScriptSources|. - FOR_EACH_SIZE(DECL_SIZE) - ScriptSourceInfo scriptSourceInfo; - CodeSizes code; - GCSizes gc; - - typedef js::HashMap ScriptSourcesHashMap; - - // |allScriptSources| is only used transiently. During the reporting phase - // it is filled with info about every script source in the runtime. It's - // then used to fill in |notableScriptSources| (which actually gets - // reported), and immediately discarded afterwards. - ScriptSourcesHashMap* allScriptSources; - js::Vector notableScriptSources; - -#undef FOR_EACH_SIZE -}; - -struct UnusedGCThingSizes -{ -#define FOR_EACH_SIZE(macro) \ - macro(Other, GCHeapUnused, object) \ - macro(Other, GCHeapUnused, script) \ - macro(Other, GCHeapUnused, lazyScript) \ - macro(Other, GCHeapUnused, shape) \ - macro(Other, GCHeapUnused, baseShape) \ - macro(Other, GCHeapUnused, objectGroup) \ - macro(Other, GCHeapUnused, string) \ - macro(Other, GCHeapUnused, symbol) \ - macro(Other, GCHeapUnused, jitcode) \ - macro(Other, GCHeapUnused, scope) - - UnusedGCThingSizes() - : FOR_EACH_SIZE(ZERO_SIZE) - dummy() - {} - - UnusedGCThingSizes(UnusedGCThingSizes&& other) - : FOR_EACH_SIZE(COPY_OTHER_SIZE) - dummy() - {} - - void addToKind(JS::TraceKind kind, intptr_t n) { - switch (kind) { - case JS::TraceKind::Object: object += n; break; - case JS::TraceKind::String: string += n; break; - case JS::TraceKind::Symbol: symbol += n; break; - case JS::TraceKind::Script: script += n; break; - case JS::TraceKind::Shape: shape += n; break; - case JS::TraceKind::BaseShape: baseShape += n; break; - case JS::TraceKind::JitCode: jitcode += n; break; - case JS::TraceKind::LazyScript: lazyScript += n; break; - case JS::TraceKind::ObjectGroup: objectGroup += n; break; - case JS::TraceKind::Scope: scope += n; break; - default: - MOZ_CRASH("Bad trace kind for UnusedGCThingSizes"); - } - } - - void addSizes(const UnusedGCThingSizes& other) { - FOR_EACH_SIZE(ADD_OTHER_SIZE) - } - - size_t totalSize() const { - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N) - return n; - } - - void addToTabSizes(JS::TabSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - } - - void addToServoSizes(JS::ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - } - - FOR_EACH_SIZE(DECL_SIZE) - int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) - -#undef FOR_EACH_SIZE -}; - -struct ZoneStats -{ -#define FOR_EACH_SIZE(macro) \ - macro(Other, GCHeapUsed, symbolsGCHeap) \ - macro(Other, GCHeapAdmin, gcHeapArenaAdmin) \ - macro(Other, GCHeapUsed, lazyScriptsGCHeap) \ - macro(Other, MallocHeap, lazyScriptsMallocHeap) \ - macro(Other, GCHeapUsed, jitCodesGCHeap) \ - macro(Other, GCHeapUsed, objectGroupsGCHeap) \ - macro(Other, MallocHeap, objectGroupsMallocHeap) \ - macro(Other, GCHeapUsed, scopesGCHeap) \ - macro(Other, MallocHeap, scopesMallocHeap) \ - macro(Other, MallocHeap, typePool) \ - macro(Other, MallocHeap, baselineStubsOptimized) \ - macro(Other, MallocHeap, uniqueIdMap) \ - macro(Other, MallocHeap, shapeTables) - - ZoneStats() - : FOR_EACH_SIZE(ZERO_SIZE) - unusedGCThings(), - stringInfo(), - shapeInfo(), - extra(), - allStrings(nullptr), - notableStrings(), - isTotals(true) - {} - - ZoneStats(ZoneStats&& other) - : FOR_EACH_SIZE(COPY_OTHER_SIZE) - unusedGCThings(mozilla::Move(other.unusedGCThings)), - stringInfo(mozilla::Move(other.stringInfo)), - shapeInfo(mozilla::Move(other.shapeInfo)), - extra(other.extra), - allStrings(other.allStrings), - notableStrings(mozilla::Move(other.notableStrings)), - isTotals(other.isTotals) - { - other.allStrings = nullptr; - MOZ_ASSERT(!other.isTotals); - } - - ~ZoneStats() { - // |allStrings| is usually deleted and set to nullptr before this - // destructor runs. But there are failure cases due to OOMs that may - // prevent that, so it doesn't hurt to try again here. - js_delete(allStrings); - } - - bool initStrings(JSRuntime* rt); - - void addSizes(const ZoneStats& other) { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_OTHER_SIZE) - unusedGCThings.addSizes(other.unusedGCThings); - stringInfo.add(other.stringInfo); - shapeInfo.add(other.shapeInfo); - } - - size_t sizeOfLiveGCThings() const { - MOZ_ASSERT(isTotals); - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - n += stringInfo.sizeOfLiveGCThings(); - n += shapeInfo.sizeOfLiveGCThings(); - return n; - } - - void addToTabSizes(JS::TabSizes* sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_TAB_SIZES) - unusedGCThings.addToTabSizes(sizes); - stringInfo.addToTabSizes(sizes); - shapeInfo.addToTabSizes(sizes); - } - - void addToServoSizes(JS::ServoSizes *sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - unusedGCThings.addToServoSizes(sizes); - stringInfo.addToServoSizes(sizes); - shapeInfo.addToServoSizes(sizes); - } - - // These string measurements are initially for all strings. At the end, - // if the measurement granularity is FineGrained, we subtract the - // measurements of the notable script sources and move them into - // |notableStrings|. - FOR_EACH_SIZE(DECL_SIZE) - UnusedGCThingSizes unusedGCThings; - StringInfo stringInfo; - ShapeInfo shapeInfo; - void* extra; // This field can be used by embedders. - - typedef js::HashMap StringsHashMap; - - // |allStrings| is only used transiently. During the zone traversal it is - // filled with info about every string in the zone. It's then used to fill - // in |notableStrings| (which actually gets reported), and immediately - // discarded afterwards. - StringsHashMap* allStrings; - js::Vector notableStrings; - bool isTotals; - -#undef FOR_EACH_SIZE -}; - -struct CompartmentStats -{ - // We assume that |objectsPrivate| is on the malloc heap, but it's not - // actually guaranteed. But for Servo, at least, it's a moot point because - // it doesn't provide an ObjectPrivateVisitor so the value will always be - // zero. -#define FOR_EACH_SIZE(macro) \ - macro(Private, MallocHeap, objectsPrivate) \ - macro(Other, GCHeapUsed, scriptsGCHeap) \ - macro(Other, MallocHeap, scriptsMallocHeapData) \ - macro(Other, MallocHeap, baselineData) \ - macro(Other, MallocHeap, baselineStubsFallback) \ - macro(Other, MallocHeap, ionData) \ - macro(Other, MallocHeap, typeInferenceTypeScripts) \ - macro(Other, MallocHeap, typeInferenceAllocationSiteTables) \ - macro(Other, MallocHeap, typeInferenceArrayTypeTables) \ - macro(Other, MallocHeap, typeInferenceObjectTypeTables) \ - macro(Other, MallocHeap, compartmentObject) \ - macro(Other, MallocHeap, compartmentTables) \ - macro(Other, MallocHeap, innerViewsTable) \ - macro(Other, MallocHeap, lazyArrayBuffersTable) \ - macro(Other, MallocHeap, objectMetadataTable) \ - macro(Other, MallocHeap, crossCompartmentWrappersTable) \ - macro(Other, MallocHeap, regexpCompartment) \ - macro(Other, MallocHeap, savedStacksSet) \ - macro(Other, MallocHeap, varNamesSet) \ - macro(Other, MallocHeap, nonSyntacticLexicalScopesTable) \ - macro(Other, MallocHeap, jitCompartment) \ - macro(Other, MallocHeap, privateData) - - CompartmentStats() - : FOR_EACH_SIZE(ZERO_SIZE) - classInfo(), - extra(), - allClasses(nullptr), - notableClasses(), - isTotals(true) - {} - - CompartmentStats(CompartmentStats&& other) - : FOR_EACH_SIZE(COPY_OTHER_SIZE) - classInfo(mozilla::Move(other.classInfo)), - extra(other.extra), - allClasses(other.allClasses), - notableClasses(mozilla::Move(other.notableClasses)), - isTotals(other.isTotals) - { - other.allClasses = nullptr; - MOZ_ASSERT(!other.isTotals); - } - - CompartmentStats(const CompartmentStats&) = delete; // disallow copying - - ~CompartmentStats() { - // |allClasses| is usually deleted and set to nullptr before this - // destructor runs. But there are failure cases due to OOMs that may - // prevent that, so it doesn't hurt to try again here. - js_delete(allClasses); - } - - bool initClasses(JSRuntime* rt); - - void addSizes(const CompartmentStats& other) { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_OTHER_SIZE) - classInfo.add(other.classInfo); - } - - size_t sizeOfLiveGCThings() const { - MOZ_ASSERT(isTotals); - size_t n = 0; - FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) - n += classInfo.sizeOfLiveGCThings(); - return n; - } - - void addToTabSizes(TabSizes* sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_TAB_SIZES); - classInfo.addToTabSizes(sizes); - } - - void addToServoSizes(ServoSizes *sizes) const { - MOZ_ASSERT(isTotals); - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES); - classInfo.addToServoSizes(sizes); - } - - // The class measurements in |classInfo| are initially for all classes. At - // the end, if the measurement granularity is FineGrained, we subtract the - // measurements of the notable classes and move them into |notableClasses|. - FOR_EACH_SIZE(DECL_SIZE) - ClassInfo classInfo; - void* extra; // This field can be used by embedders. - - typedef js::HashMap ClassesHashMap; - - // These are similar to |allStrings| and |notableStrings| in ZoneStats. - ClassesHashMap* allClasses; - js::Vector notableClasses; - bool isTotals; - -#undef FOR_EACH_SIZE -}; - -typedef js::Vector CompartmentStatsVector; -typedef js::Vector ZoneStatsVector; - -struct RuntimeStats -{ - // |gcHeapChunkTotal| is ignored because it's the sum of all the other - // values. |gcHeapGCThings| is ignored because it's the sum of some of the - // values from the zones and compartments. Both of those values are not - // reported directly, but are just present for sanity-checking other - // values. -#define FOR_EACH_SIZE(macro) \ - macro(_, Ignore, gcHeapChunkTotal) \ - macro(_, GCHeapDecommitted, gcHeapDecommittedArenas) \ - macro(_, GCHeapUnused, gcHeapUnusedChunks) \ - macro(_, GCHeapUnused, gcHeapUnusedArenas) \ - macro(_, GCHeapAdmin, gcHeapChunkAdmin) \ - macro(_, Ignore, gcHeapGCThings) - - explicit RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) - : FOR_EACH_SIZE(ZERO_SIZE) - runtime(), - cTotals(), - zTotals(), - compartmentStatsVector(), - zoneStatsVector(), - currZoneStats(nullptr), - mallocSizeOf_(mallocSizeOf) - {} - - // Here's a useful breakdown of the GC heap. - // - // - rtStats.gcHeapChunkTotal - // - decommitted bytes - // - rtStats.gcHeapDecommittedArenas (decommitted arenas in non-empty chunks) - // - unused bytes - // - rtStats.gcHeapUnusedChunks (empty chunks) - // - rtStats.gcHeapUnusedArenas (empty arenas within non-empty chunks) - // - rtStats.zTotals.unusedGCThings.totalSize() (empty GC thing slots within non-empty arenas) - // - used bytes - // - rtStats.gcHeapChunkAdmin - // - rtStats.zTotals.gcHeapArenaAdmin - // - rtStats.gcHeapGCThings (in-use GC things) - // == rtStats.zTotals.sizeOfLiveGCThings() + rtStats.cTotals.sizeOfLiveGCThings() - // - // It's possible that some arenas in empty chunks may be decommitted, but - // we don't count those under rtStats.gcHeapDecommittedArenas because (a) - // it's rare, and (b) this means that rtStats.gcHeapUnusedChunks is a - // multiple of the chunk size, which is good. - - void addToServoSizes(ServoSizes *sizes) const { - FOR_EACH_SIZE(ADD_TO_SERVO_SIZES) - runtime.addToServoSizes(sizes); - } - - FOR_EACH_SIZE(DECL_SIZE) - - RuntimeSizes runtime; - - CompartmentStats cTotals; // The sum of this runtime's compartments' measurements. - ZoneStats zTotals; // The sum of this runtime's zones' measurements. - - CompartmentStatsVector compartmentStatsVector; - ZoneStatsVector zoneStatsVector; - - ZoneStats* currZoneStats; - - mozilla::MallocSizeOf mallocSizeOf_; - - virtual void initExtraCompartmentStats(JSCompartment* c, CompartmentStats* cstats) = 0; - virtual void initExtraZoneStats(JS::Zone* zone, ZoneStats* zstats) = 0; - -#undef FOR_EACH_SIZE -}; - -class ObjectPrivateVisitor -{ - public: - // Within CollectRuntimeStats, this method is called for each JS object - // that has an nsISupports pointer. - virtual size_t sizeOfIncludingThis(nsISupports* aSupports) = 0; - - // A callback that gets a JSObject's nsISupports pointer, if it has one. - // Note: this function does *not* addref |iface|. - typedef bool(*GetISupportsFun)(JSObject* obj, nsISupports** iface); - GetISupportsFun getISupports_; - - explicit ObjectPrivateVisitor(GetISupportsFun getISupports) - : getISupports_(getISupports) - {} -}; - -extern JS_PUBLIC_API(bool) -CollectRuntimeStats(JSContext* cx, RuntimeStats* rtStats, ObjectPrivateVisitor* opv, bool anonymize); - -extern JS_PUBLIC_API(size_t) -SystemCompartmentCount(JSContext* cx); - -extern JS_PUBLIC_API(size_t) -UserCompartmentCount(JSContext* cx); - -extern JS_PUBLIC_API(size_t) -PeakSizeOfTemporary(const JSContext* cx); - -extern JS_PUBLIC_API(bool) -AddSizeOfTab(JSContext* cx, JS::HandleObject obj, mozilla::MallocSizeOf mallocSizeOf, - ObjectPrivateVisitor* opv, TabSizes* sizes); - -extern JS_PUBLIC_API(bool) -AddServoSizeOf(JSContext* cx, mozilla::MallocSizeOf mallocSizeOf, - ObjectPrivateVisitor *opv, ServoSizes *sizes); - -} // namespace JS - -#undef DECL_SIZE -#undef ZERO_SIZE -#undef COPY_OTHER_SIZE -#undef ADD_OTHER_SIZE -#undef SUB_OTHER_SIZE -#undef ADD_SIZE_TO_N -#undef ADD_SIZE_TO_N_IF_LIVE_GC_THING -#undef ADD_TO_TAB_SIZES - -#endif /* js_MemoryMetrics_h */ diff --git a/win32/include/spidermonkey/js/Principals.h b/win32/include/spidermonkey/js/Principals.h deleted file mode 100755 index cf6c813a..00000000 --- a/win32/include/spidermonkey/js/Principals.h +++ /dev/null @@ -1,132 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JSPrincipals and related interfaces. */ - -#ifndef js_Principals_h -#define js_Principals_h - -#include "mozilla/Atomics.h" - -#include - -#include "jspubtd.h" - -#include "js/StructuredClone.h" - -namespace js { - struct PerformanceGroup; -} // namespace js - -struct JSPrincipals { - /* Don't call "destroy"; use reference counting macros below. */ - mozilla::Atomic refcount; - -#ifdef JS_DEBUG - /* A helper to facilitate principals debugging. */ - uint32_t debugToken; -#endif - - JSPrincipals() : refcount(0) {} - - void setDebugToken(uint32_t token) { -# ifdef JS_DEBUG - debugToken = token; -# endif - } - - /* - * Write the principals with the given |writer|. Return false on failure, - * true on success. - */ - virtual bool write(JSContext* cx, JSStructuredCloneWriter* writer) = 0; - - /* - * This is not defined by the JS engine but should be provided by the - * embedding. - */ - JS_PUBLIC_API(void) dump(); -}; - -extern JS_PUBLIC_API(void) -JS_HoldPrincipals(JSPrincipals* principals); - -extern JS_PUBLIC_API(void) -JS_DropPrincipals(JSContext* cx, JSPrincipals* principals); - -// Return whether the first principal subsumes the second. The exact meaning of -// 'subsumes' is left up to the browser. Subsumption is checked inside the JS -// engine when determining, e.g., which stack frames to display in a backtrace. -typedef bool -(* JSSubsumesOp)(JSPrincipals* first, JSPrincipals* second); - -/* - * Used to check if a CSP instance wants to disable eval() and friends. - * See js_CheckCSPPermitsJSAction() in jsobj. - */ -typedef bool -(* JSCSPEvalChecker)(JSContext* cx); - -struct JSSecurityCallbacks { - JSCSPEvalChecker contentSecurityPolicyAllows; - JSSubsumesOp subsumes; -}; - -extern JS_PUBLIC_API(void) -JS_SetSecurityCallbacks(JSContext* cx, const JSSecurityCallbacks* callbacks); - -extern JS_PUBLIC_API(const JSSecurityCallbacks*) -JS_GetSecurityCallbacks(JSContext* cx); - -/* - * Code running with "trusted" principals will be given a deeper stack - * allocation than ordinary scripts. This allows trusted script to run after - * untrusted script has exhausted the stack. This function sets the - * runtime-wide trusted principal. - * - * This principals is not held (via JS_HoldPrincipals/JS_DropPrincipals). - * Instead, the caller must ensure that the given principals stays valid for as - * long as 'cx' may point to it. If the principals would be destroyed before - * 'cx', JS_SetTrustedPrincipals must be called again, passing nullptr for - * 'prin'. - */ -extern JS_PUBLIC_API(void) -JS_SetTrustedPrincipals(JSContext* cx, JSPrincipals* prin); - -typedef void -(* JSDestroyPrincipalsOp)(JSPrincipals* principals); - -/* - * Initialize the callback that is called to destroy JSPrincipals instance - * when its reference counter drops to zero. The initialization can be done - * only once per JS runtime. - */ -extern JS_PUBLIC_API(void) -JS_InitDestroyPrincipalsCallback(JSContext* cx, JSDestroyPrincipalsOp destroyPrincipals); - -/* - * Read a JSPrincipals instance from the given |reader| and initialize the out - * paratemer |outPrincipals| to the JSPrincipals instance read. - * - * Return false on failure, true on success. The |outPrincipals| parameter - * should not be modified if false is returned. - * - * The caller is not responsible for calling JS_HoldPrincipals on the resulting - * JSPrincipals instance, the JSReadPrincipalsOp must increment the refcount of - * the resulting JSPrincipals on behalf of the caller. - */ -using JSReadPrincipalsOp = bool (*)(JSContext* cx, JSStructuredCloneReader* reader, - JSPrincipals** outPrincipals); - -/* - * Initialize the callback that is called to read JSPrincipals instances from a - * buffer. The initialization can be done only once per JS runtime. - */ -extern JS_PUBLIC_API(void) -JS_InitReadPrincipalsCallback(JSContext* cx, JSReadPrincipalsOp read); - - -#endif /* js_Principals_h */ diff --git a/win32/include/spidermonkey/js/ProfilingFrameIterator.h b/win32/include/spidermonkey/js/ProfilingFrameIterator.h deleted file mode 100755 index d082213d..00000000 --- a/win32/include/spidermonkey/js/ProfilingFrameIterator.h +++ /dev/null @@ -1,203 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_ProfilingFrameIterator_h -#define js_ProfilingFrameIterator_h - -#include "mozilla/Alignment.h" -#include "mozilla/Maybe.h" - -#include "jsbytecode.h" -#include "js/GCAPI.h" -#include "js/TypeDecls.h" -#include "js/Utility.h" - -struct JSContext; -struct JSRuntime; -class JSScript; - -namespace js { - class Activation; - namespace jit { - class JitActivation; - class JitProfilingFrameIterator; - class JitcodeGlobalEntry; - } // namespace jit - namespace wasm { - class ProfilingFrameIterator; - } // namespace wasm -} // namespace js - -namespace JS { - -struct ForEachTrackedOptimizationAttemptOp; -struct ForEachTrackedOptimizationTypeInfoOp; - -// This iterator can be used to walk the stack of a thread suspended at an -// arbitrary pc. To provide acurate results, profiling must have been enabled -// (via EnableRuntimeProfilingStack) before executing the callstack being -// unwound. -// -// Note that the caller must not do anything that could cause GC to happen while -// the iterator is alive, since this could invalidate Ion code and cause its -// contents to become out of date. -class JS_PUBLIC_API(ProfilingFrameIterator) -{ - JSRuntime* rt_; - uint32_t sampleBufferGen_; - js::Activation* activation_; - - // When moving past a JitActivation, we need to save the prevJitTop - // from it to use as the exit-frame pointer when the next caller jit - // activation (if any) comes around. - void* savedPrevJitTop_; - - JS::AutoCheckCannotGC nogc_; - - static const unsigned StorageSpace = 8 * sizeof(void*); - mozilla::AlignedStorage storage_; - js::wasm::ProfilingFrameIterator& wasmIter() { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isWasm()); - return *reinterpret_cast(storage_.addr()); - } - const js::wasm::ProfilingFrameIterator& wasmIter() const { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isWasm()); - return *reinterpret_cast(storage_.addr()); - } - - js::jit::JitProfilingFrameIterator& jitIter() { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isJit()); - return *reinterpret_cast(storage_.addr()); - } - - const js::jit::JitProfilingFrameIterator& jitIter() const { - MOZ_ASSERT(!done()); - MOZ_ASSERT(isJit()); - return *reinterpret_cast(storage_.addr()); - } - - void settle(); - - bool hasSampleBufferGen() const { - return sampleBufferGen_ != UINT32_MAX; - } - - public: - struct RegisterState - { - RegisterState() : pc(nullptr), sp(nullptr), lr(nullptr) {} - void* pc; - void* sp; - void* lr; - }; - - ProfilingFrameIterator(JSContext* cx, const RegisterState& state, - uint32_t sampleBufferGen = UINT32_MAX); - ~ProfilingFrameIterator(); - void operator++(); - bool done() const { return !activation_; } - - // Assuming the stack grows down (we do), the return value: - // - always points into the stack - // - is weakly monotonically increasing (may be equal for successive frames) - // - will compare greater than newer native and psuedo-stack frame addresses - // and less than older native and psuedo-stack frame addresses - void* stackAddress() const; - - enum FrameKind - { - Frame_Baseline, - Frame_Ion, - Frame_Wasm - }; - - struct Frame - { - FrameKind kind; - void* stackAddress; - void* returnAddress; - void* activation; - UniqueChars label; - }; - - bool isWasm() const; - bool isJit() const; - - uint32_t extractStack(Frame* frames, uint32_t offset, uint32_t end) const; - - mozilla::Maybe getPhysicalFrameWithoutLabel() const; - - private: - mozilla::Maybe getPhysicalFrameAndEntry(js::jit::JitcodeGlobalEntry* entry) const; - - void iteratorConstruct(const RegisterState& state); - void iteratorConstruct(); - void iteratorDestroy(); - bool iteratorDone(); -}; - -JS_FRIEND_API(bool) -IsProfilingEnabledForContext(JSContext* cx); - -/** - * After each sample run, this method should be called with the latest sample - * buffer generation, and the lapCount. It will update corresponding fields on - * JSRuntime. - * - * See fields |profilerSampleBufferGen|, |profilerSampleBufferLapCount| on - * JSRuntime for documentation about what these values are used for. - */ -JS_FRIEND_API(void) -UpdateJSContextProfilerSampleBufferGen(JSContext* cx, uint32_t generation, - uint32_t lapCount); - -struct ForEachProfiledFrameOp -{ - // A handle to the underlying JitcodeGlobalEntry, so as to avoid repeated - // lookups on JitcodeGlobalTable. - class MOZ_STACK_CLASS FrameHandle - { - friend JS_PUBLIC_API(void) ForEachProfiledFrame(JSContext* cx, void* addr, - ForEachProfiledFrameOp& op); - - JSRuntime* rt_; - js::jit::JitcodeGlobalEntry& entry_; - void* addr_; - void* canonicalAddr_; - const char* label_; - uint32_t depth_; - mozilla::Maybe optsIndex_; - - FrameHandle(JSRuntime* rt, js::jit::JitcodeGlobalEntry& entry, void* addr, - const char* label, uint32_t depth); - - void updateHasTrackedOptimizations(); - - public: - const char* label() const { return label_; } - uint32_t depth() const { return depth_; } - bool hasTrackedOptimizations() const { return optsIndex_.isSome(); } - void* canonicalAddress() const { return canonicalAddr_; } - - ProfilingFrameIterator::FrameKind frameKind() const; - void forEachOptimizationAttempt(ForEachTrackedOptimizationAttemptOp& op, - JSScript** scriptOut, jsbytecode** pcOut) const; - void forEachOptimizationTypeInfo(ForEachTrackedOptimizationTypeInfoOp& op) const; - }; - - // Called once per frame. - virtual void operator()(const FrameHandle& frame) = 0; -}; - -JS_PUBLIC_API(void) -ForEachProfiledFrame(JSContext* cx, void* addr, ForEachProfiledFrameOp& op); - -} // namespace JS - -#endif /* js_ProfilingFrameIterator_h */ diff --git a/win32/include/spidermonkey/js/ProfilingStack.h b/win32/include/spidermonkey/js/ProfilingStack.h deleted file mode 100755 index 6b6c9701..00000000 --- a/win32/include/spidermonkey/js/ProfilingStack.h +++ /dev/null @@ -1,208 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_ProfilingStack_h -#define js_ProfilingStack_h - -#include "jsbytecode.h" -#include "jstypes.h" -#include "js/TypeDecls.h" - -#include "js/Utility.h" - -struct JSRuntime; -class JSTracer; - -namespace js { - -// A call stack can be specified to the JS engine such that all JS entry/exits -// to functions push/pop an entry to/from the specified stack. -// -// For more detailed information, see vm/SPSProfiler.h. -// -class ProfileEntry -{ - // All fields are marked volatile to prevent the compiler from re-ordering - // instructions. Namely this sequence: - // - // entry[size] = ...; - // size++; - // - // If the size modification were somehow reordered before the stores, then - // if a sample were taken it would be examining bogus information. - // - // A ProfileEntry represents both a C++ profile entry and a JS one. - - // Descriptive string of this entry. - const char * volatile string; - - // Stack pointer for non-JS entries, the script pointer otherwise. - void * volatile spOrScript; - - // Line number for non-JS entries, the bytecode offset otherwise. - int32_t volatile lineOrPcOffset; - - // General purpose storage describing this frame. - uint32_t volatile flags_; - - public: - // These traits are bit masks. Make sure they're powers of 2. - enum Flags : uint32_t { - // Indicate whether a profile entry represents a CPP frame. If not set, - // a JS frame is assumed by default. You're not allowed to publicly - // change the frame type. Instead, initialize the ProfileEntry as either - // a JS or CPP frame with `initJsFrame` or `initCppFrame` respectively. - IS_CPP_ENTRY = 0x01, - - // Indicate that copying the frame label is not necessary when taking a - // sample of the pseudostack. - FRAME_LABEL_COPY = 0x02, - - // This ProfileEntry is a dummy entry indicating the start of a run - // of JS pseudostack entries. - BEGIN_PSEUDO_JS = 0x04, - - // This flag is used to indicate that an interpreter JS entry has OSR-ed - // into baseline. - OSR = 0x08, - - // Union of all flags. - ALL = IS_CPP_ENTRY|FRAME_LABEL_COPY|BEGIN_PSEUDO_JS|OSR, - - // Mask for removing all flags except the category information. - CATEGORY_MASK = ~ALL - }; - - // Keep these in sync with devtools/client/performance/modules/categories.js - enum class Category : uint32_t { - OTHER = 0x10, - CSS = 0x20, - JS = 0x40, - GC = 0x80, - CC = 0x100, - NETWORK = 0x200, - GRAPHICS = 0x400, - STORAGE = 0x800, - EVENTS = 0x1000, - - FIRST = OTHER, - LAST = EVENTS - }; - - static_assert((static_cast(Category::FIRST) & Flags::ALL) == 0, - "The category bitflags should not intersect with the other flags!"); - - // All of these methods are marked with the 'volatile' keyword because SPS's - // representation of the stack is stored such that all ProfileEntry - // instances are volatile. These methods would not be available unless they - // were marked as volatile as well. - - bool isCpp() const volatile { return hasFlag(IS_CPP_ENTRY); } - bool isJs() const volatile { return !isCpp(); } - - bool isCopyLabel() const volatile { return hasFlag(FRAME_LABEL_COPY); } - - void setLabel(const char* aString) volatile { string = aString; } - const char* label() const volatile { return string; } - - void initJsFrame(JSScript* aScript, jsbytecode* aPc) volatile { - flags_ = 0; - spOrScript = aScript; - setPC(aPc); - } - void initCppFrame(void* aSp, uint32_t aLine) volatile { - flags_ = IS_CPP_ENTRY; - spOrScript = aSp; - lineOrPcOffset = static_cast(aLine); - } - - void setFlag(uint32_t flag) volatile { - MOZ_ASSERT(flag != IS_CPP_ENTRY); - flags_ |= flag; - } - void unsetFlag(uint32_t flag) volatile { - MOZ_ASSERT(flag != IS_CPP_ENTRY); - flags_ &= ~flag; - } - bool hasFlag(uint32_t flag) const volatile { - return bool(flags_ & flag); - } - - uint32_t flags() const volatile { - return flags_; - } - - uint32_t category() const volatile { - return flags_ & CATEGORY_MASK; - } - void setCategory(Category c) volatile { - MOZ_ASSERT(c >= Category::FIRST); - MOZ_ASSERT(c <= Category::LAST); - flags_ &= ~CATEGORY_MASK; - setFlag(static_cast(c)); - } - - void setOSR() volatile { - MOZ_ASSERT(isJs()); - setFlag(OSR); - } - void unsetOSR() volatile { - MOZ_ASSERT(isJs()); - unsetFlag(OSR); - } - bool isOSR() const volatile { - return hasFlag(OSR); - } - - void* stackAddress() const volatile { - MOZ_ASSERT(!isJs()); - return spOrScript; - } - JSScript* script() const volatile; - uint32_t line() const volatile { - MOZ_ASSERT(!isJs()); - return static_cast(lineOrPcOffset); - } - - // Note that the pointer returned might be invalid. - JSScript* rawScript() const volatile { - MOZ_ASSERT(isJs()); - return (JSScript*)spOrScript; - } - - // We can't know the layout of JSScript, so look in vm/SPSProfiler.cpp. - JS_FRIEND_API(jsbytecode*) pc() const volatile; - JS_FRIEND_API(void) setPC(jsbytecode* pc) volatile; - - void trace(JSTracer* trc); - - // The offset of a pc into a script's code can actually be 0, so to - // signify a nullptr pc, use a -1 index. This is checked against in - // pc() and setPC() to set/get the right pc. - static const int32_t NullPCOffset = -1; - - static size_t offsetOfLabel() { return offsetof(ProfileEntry, string); } - static size_t offsetOfSpOrScript() { return offsetof(ProfileEntry, spOrScript); } - static size_t offsetOfLineOrPcOffset() { return offsetof(ProfileEntry, lineOrPcOffset); } - static size_t offsetOfFlags() { return offsetof(ProfileEntry, flags_); } -}; - -JS_FRIEND_API(void) -SetContextProfilingStack(JSContext* cx, ProfileEntry* stack, uint32_t* size, - uint32_t max); - -JS_FRIEND_API(void) -EnableContextProfilingStack(JSContext* cx, bool enabled); - -JS_FRIEND_API(void) -RegisterContextProfilingEventMarker(JSContext* cx, void (*fn)(const char*)); - -JS_FRIEND_API(jsbytecode*) -ProfilingGetPC(JSContext* cx, JSScript* script, void* ip); - -} // namespace js - -#endif /* js_ProfilingStack_h */ diff --git a/win32/include/spidermonkey/js/Proxy.h b/win32/include/spidermonkey/js/Proxy.h deleted file mode 100755 index 3e95538d..00000000 --- a/win32/include/spidermonkey/js/Proxy.h +++ /dev/null @@ -1,632 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Proxy_h -#define js_Proxy_h - -#include "mozilla/Maybe.h" - -#include "jsfriendapi.h" - -#include "js/CallNonGenericMethod.h" -#include "js/Class.h" - -namespace js { - -using JS::AutoIdVector; -using JS::CallArgs; -using JS::Handle; -using JS::HandleId; -using JS::HandleObject; -using JS::HandleValue; -using JS::IsAcceptableThis; -using JS::MutableHandle; -using JS::MutableHandleObject; -using JS::MutableHandleValue; -using JS::NativeImpl; -using JS::ObjectOpResult; -using JS::PrivateValue; -using JS::PropertyDescriptor; -using JS::Value; - -class RegExpGuard; -class JS_FRIEND_API(Wrapper); - -/* - * A proxy is a JSObject with highly customizable behavior. ES6 specifies a - * single kind of proxy, but the customization mechanisms we use to implement - * ES6 Proxy objects are also useful wherever an object with weird behavior is - * wanted. Proxies are used to implement: - * - * - the scope objects used by the Debugger's frame.eval() method - * (see js::GetDebugScopeForFunction) - * - * - the khuey hack, whereby a whole compartment can be blown away - * even if other compartments hold references to objects in it - * (see js::NukeCrossCompartmentWrappers) - * - * - XPConnect security wrappers, which protect chrome from malicious content - * (js/xpconnect/wrappers) - * - * - DOM objects with special property behavior, like named getters - * (dom/bindings/Codegen.py generates these proxies from WebIDL) - * - * - semi-transparent use of objects that live in other processes - * (CPOWs, implemented in js/ipc) - * - * ### Proxies and internal methods - * - * ES2016 specifies 13 internal methods. The runtime semantics of just - * about everything a script can do to an object is specified in terms - * of these internal methods. For example: - * - * JS code ES6 internal method that gets called - * --------------------------- -------------------------------- - * obj.prop obj.[[Get]](obj, "prop") - * "prop" in obj obj.[[HasProperty]]("prop") - * new obj() obj.[[Construct]]() - * - * With regard to the implementation of these internal methods, there are three - * very different kinds of object in SpiderMonkey. - * - * 1. Native objects' internal methods are implemented in vm/NativeObject.cpp, - * with duplicate (but functionally identical) implementations scattered - * through the ICs and JITs. - * - * 2. Certain non-native objects have internal methods that are implemented as - * magical js::ObjectOps hooks. We're trying to get rid of these. - * - * 3. All other objects are proxies. A proxy's internal methods are - * implemented in C++, as the virtual methods of a C++ object stored on the - * proxy, known as its handler. - * - * This means that just about anything you do to a proxy will end up going - * through a C++ virtual method call. Possibly several. There's no reason the - * JITs and ICs can't specialize for particular proxies, based on the handler; - * but currently we don't do much of this, so the virtual method overhead - * typically is actually incurred. - * - * ### The proxy handler hierarchy - * - * A major use case for proxies is to forward each internal method call to - * another object, known as its target. The target can be an arbitrary JS - * object. Not every proxy has the notion of a target, however. - * - * To minimize code duplication, a set of abstract proxy handler classes is - * provided, from which other handlers may inherit. These abstract classes are - * organized in the following hierarchy: - * - * BaseProxyHandler - * | - * Wrapper // has a target, can be unwrapped to reveal - * | // target (see js::CheckedUnwrap) - * | - * CrossCompartmentWrapper // target is in another compartment; - * // implements membrane between compartments - * - * Example: Some DOM objects (including all the arraylike DOM objects) are - * implemented as proxies. Since these objects don't need to forward operations - * to any underlying JS object, DOMJSProxyHandler directly subclasses - * BaseProxyHandler. - * - * Gecko's security wrappers are examples of cross-compartment wrappers. - * - * ### Proxy prototype chains - * - * In addition to the normal methods, there are two models for proxy prototype - * chains. - * - * 1. Proxies can use the standard prototype mechanism used throughout the - * engine. To do so, simply pass a prototype to NewProxyObject() at - * creation time. All prototype accesses will then "just work" to treat the - * proxy as a "normal" object. - * - * 2. A proxy can implement more complicated prototype semantics (if, for - * example, it wants to delegate the prototype lookup to a wrapped object) - * by passing Proxy::LazyProto as the prototype at create time. This - * guarantees that the getPrototype() handler method will be called every - * time the object's prototype chain is accessed. - * - * This system is implemented with two methods: {get,set}Prototype. The - * default implementation of setPrototype throws a TypeError. Since it is - * not possible to create an object without a sense of prototype chain, - * handlers must implement getPrototype if opting in to the dynamic - * prototype system. - */ - -/* - * BaseProxyHandler is the most generic kind of proxy handler. It does not make - * any assumptions about the target. Consequently, it does not provide any - * default implementation for most methods. As a convenience, a few high-level - * methods, like get() and set(), are given default implementations that work by - * calling the low-level methods, like getOwnPropertyDescriptor(). - * - * Important: If you add a method here, you should probably also add a - * Proxy::foo entry point with an AutoEnterPolicy. If you don't, you need an - * explicit override for the method in SecurityWrapper. See bug 945826 comment 0. - */ -class JS_FRIEND_API(BaseProxyHandler) -{ - /* - * Sometimes it's desirable to designate groups of proxy handlers as "similar". - * For this, we use the notion of a "family": A consumer-provided opaque pointer - * that designates the larger group to which this proxy belongs. - * - * If it will never be important to differentiate this proxy from others as - * part of a distinct group, nullptr may be used instead. - */ - const void* mFamily; - - /* - * Proxy handlers can use mHasPrototype to request the following special - * treatment from the JS engine: - * - * - When mHasPrototype is true, the engine never calls these methods: - * getPropertyDescriptor, has, set, enumerate, iterate. Instead, for - * these operations, it calls the "own" methods like - * getOwnPropertyDescriptor, hasOwn, defineProperty, - * getOwnEnumerablePropertyKeys, etc., and consults the prototype chain - * if needed. - * - * - When mHasPrototype is true, the engine calls handler->get() only if - * handler->hasOwn() says an own property exists on the proxy. If not, - * it consults the prototype chain. - * - * This is useful because it frees the ProxyHandler from having to implement - * any behavior having to do with the prototype chain. - */ - bool mHasPrototype; - - /* - * All proxies indicate whether they have any sort of interesting security - * policy that might prevent the caller from doing something it wants to - * the object. In the case of wrappers, this distinction is used to - * determine whether the caller may strip off the wrapper if it so desires. - */ - bool mHasSecurityPolicy; - - public: - explicit constexpr BaseProxyHandler(const void* aFamily, bool aHasPrototype = false, - bool aHasSecurityPolicy = false) - : mFamily(aFamily), - mHasPrototype(aHasPrototype), - mHasSecurityPolicy(aHasSecurityPolicy) - { } - - bool hasPrototype() const { - return mHasPrototype; - } - - bool hasSecurityPolicy() const { - return mHasSecurityPolicy; - } - - inline const void* family() const { - return mFamily; - } - static size_t offsetOfFamily() { - return offsetof(BaseProxyHandler, mFamily); - } - - virtual bool finalizeInBackground(const Value& priv) const { - /* - * Called on creation of a proxy to determine whether its finalize - * method can be finalized on the background thread. - */ - return true; - } - - virtual bool canNurseryAllocate() const { - /* - * Nursery allocation is allowed if and only if it is safe to not - * run |finalize| when the ProxyObject dies. - */ - return false; - } - - /* Policy enforcement methods. - * - * enter() allows the policy to specify whether the caller may perform |act| - * on the proxy's |id| property. In the case when |act| is CALL, |id| is - * generally JSID_VOID. - * - * The |act| parameter to enter() specifies the action being performed. - * If |bp| is false, the method suggests that the caller throw (though it - * may still decide to squelch the error). - * - * We make these OR-able so that assertEnteredPolicy can pass a union of them. - * For example, get{,Own}PropertyDescriptor is invoked by calls to ::get() - * ::set(), in addition to being invoked on its own, so there are several - * valid Actions that could have been entered. - */ - typedef uint32_t Action; - enum { - NONE = 0x00, - GET = 0x01, - SET = 0x02, - CALL = 0x04, - ENUMERATE = 0x08, - GET_PROPERTY_DESCRIPTOR = 0x10 - }; - - virtual bool enter(JSContext* cx, HandleObject wrapper, HandleId id, Action act, - bool* bp) const; - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const = 0; - virtual bool defineProperty(JSContext* cx, HandleObject proxy, HandleId id, - Handle desc, - ObjectOpResult& result) const = 0; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const = 0; - virtual bool delete_(JSContext* cx, HandleObject proxy, HandleId id, - ObjectOpResult& result) const = 0; - - /* - * These methods are standard, but the engine does not normally call them. - * They're opt-in. See "Proxy prototype chains" above. - * - * getPrototype() crashes if called. setPrototype() throws a TypeError. - */ - virtual bool getPrototype(JSContext* cx, HandleObject proxy, MutableHandleObject protop) const; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const; - - /* Non-standard but conceptual kin to {g,s}etPrototype, so these live here. */ - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, - MutableHandleObject protop) const = 0; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, bool* succeeded) const; - - virtual bool preventExtensions(JSContext* cx, HandleObject proxy, - ObjectOpResult& result) const = 0; - virtual bool isExtensible(JSContext* cx, HandleObject proxy, bool* extensible) const = 0; - - /* - * These standard internal methods are implemented, as a convenience, so - * that ProxyHandler subclasses don't have to provide every single method. - * - * The base-class implementations work by calling getPropertyDescriptor(). - * They do not follow any standard. When in doubt, override them. - */ - virtual bool has(JSContext* cx, HandleObject proxy, HandleId id, bool* bp) const; - virtual bool get(JSContext* cx, HandleObject proxy, HandleValue receiver, - HandleId id, MutableHandleValue vp) const; - virtual bool set(JSContext* cx, HandleObject proxy, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const; - - /* - * [[Call]] and [[Construct]] are standard internal methods but according - * to the spec, they are not present on every object. - * - * SpiderMonkey never calls a proxy's call()/construct() internal method - * unless isCallable()/isConstructor() returns true for that proxy. - * - * BaseProxyHandler::isCallable()/isConstructor() always return false, and - * BaseProxyHandler::call()/construct() crash if called. So if you're - * creating a kind of that is never callable, you don't have to override - * anything, but otherwise you probably want to override all four. - */ - virtual bool call(JSContext* cx, HandleObject proxy, const CallArgs& args) const; - virtual bool construct(JSContext* cx, HandleObject proxy, const CallArgs& args) const; - - /* SpiderMonkey extensions. */ - virtual bool enumerate(JSContext* cx, HandleObject proxy, MutableHandleObject objp) const; - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const; - virtual bool hasOwn(JSContext* cx, HandleObject proxy, HandleId id, bool* bp) const; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const; - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const; - virtual bool hasInstance(JSContext* cx, HandleObject proxy, MutableHandleValue v, bool* bp) const; - virtual bool getBuiltinClass(JSContext* cx, HandleObject proxy, - ESClass* cls) const; - virtual bool isArray(JSContext* cx, HandleObject proxy, JS::IsArrayAnswer* answer) const; - virtual const char* className(JSContext* cx, HandleObject proxy) const; - virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, unsigned indent) const; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const; - virtual void trace(JSTracer* trc, JSObject* proxy) const; - virtual void finalize(JSFreeOp* fop, JSObject* proxy) const; - virtual void objectMoved(JSObject* proxy, const JSObject* old) const; - - // Allow proxies, wrappers in particular, to specify callability at runtime. - // Note: These do not take const JSObject*, but they do in spirit. - // We are not prepared to do this, as there's little const correctness - // in the external APIs that handle proxies. - virtual bool isCallable(JSObject* obj) const; - virtual bool isConstructor(JSObject* obj) const; - - // These two hooks must be overridden, or not overridden, in tandem -- no - // overriding just one! - virtual bool watch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, - JS::HandleObject callable) const; - virtual bool unwatch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id) const; - - virtual bool getElements(JSContext* cx, HandleObject proxy, uint32_t begin, uint32_t end, - ElementAdder* adder) const; - - /* See comment for weakmapKeyDelegateOp in js/Class.h. */ - virtual JSObject* weakmapKeyDelegate(JSObject* proxy) const; - virtual bool isScripted() const { return false; } -}; - -extern JS_FRIEND_DATA(const js::Class* const) ProxyClassPtr; - -inline bool IsProxy(const JSObject* obj) -{ - return GetObjectClass(obj)->isProxy(); -} - -namespace detail { -const uint32_t PROXY_EXTRA_SLOTS = 2; - -// Layout of the values stored by a proxy. Note that API clients require the -// private slot to be the first slot in the proxy's values, so that the private -// slot can be accessed in the same fashion as the first reserved slot, via -// {Get,Set}ReservedOrProxyPrivateSlot. - -struct ProxyValueArray -{ - Value privateSlot; - Value extraSlots[PROXY_EXTRA_SLOTS]; - - ProxyValueArray() - : privateSlot(JS::UndefinedValue()) - { - for (size_t i = 0; i < PROXY_EXTRA_SLOTS; i++) - extraSlots[i] = JS::UndefinedValue(); - } -}; - -// All proxies share the same data layout. Following the object's shape and -// type, the proxy has a ProxyDataLayout structure with a pointer to an array -// of values and the proxy's handler. This is designed both so that proxies can -// be easily swapped with other objects (via RemapWrapper) and to mimic the -// layout of other objects (proxies and other objects have the same size) so -// that common code can access either type of object. -// -// See GetReservedOrProxyPrivateSlot below. -struct ProxyDataLayout -{ - ProxyValueArray* values; - const BaseProxyHandler* handler; -}; - -const uint32_t ProxyDataOffset = 2 * sizeof(void*); - -inline ProxyDataLayout* -GetProxyDataLayout(JSObject* obj) -{ - MOZ_ASSERT(IsProxy(obj)); - return reinterpret_cast(reinterpret_cast(obj) + ProxyDataOffset); -} - -inline const ProxyDataLayout* -GetProxyDataLayout(const JSObject* obj) -{ - MOZ_ASSERT(IsProxy(obj)); - return reinterpret_cast(reinterpret_cast(obj) + - ProxyDataOffset); -} -} // namespace detail - -inline const BaseProxyHandler* -GetProxyHandler(const JSObject* obj) -{ - return detail::GetProxyDataLayout(obj)->handler; -} - -inline const Value& -GetProxyPrivate(const JSObject* obj) -{ - return detail::GetProxyDataLayout(obj)->values->privateSlot; -} - -inline JSObject* -GetProxyTargetObject(JSObject* obj) -{ - return GetProxyPrivate(obj).toObjectOrNull(); -} - -inline const Value& -GetProxyExtra(const JSObject* obj, size_t n) -{ - MOZ_ASSERT(n < detail::PROXY_EXTRA_SLOTS); - return detail::GetProxyDataLayout(obj)->values->extraSlots[n]; -} - -inline void -SetProxyHandler(JSObject* obj, const BaseProxyHandler* handler) -{ - detail::GetProxyDataLayout(obj)->handler = handler; -} - -JS_FRIEND_API(void) -SetValueInProxy(Value* slot, const Value& value); - -inline void -SetProxyExtra(JSObject* obj, size_t n, const Value& extra) -{ - MOZ_ASSERT(n < detail::PROXY_EXTRA_SLOTS); - Value* vp = &detail::GetProxyDataLayout(obj)->values->extraSlots[n]; - - // Trigger a barrier before writing the slot. - if (vp->isMarkable() || extra.isMarkable()) - SetValueInProxy(vp, extra); - else - *vp = extra; -} - -inline bool -IsScriptedProxy(const JSObject* obj) -{ - return IsProxy(obj) && GetProxyHandler(obj)->isScripted(); -} - -inline const Value& -GetReservedOrProxyPrivateSlot(const JSObject* obj, size_t slot) -{ - MOZ_ASSERT(slot == 0); - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj)) || IsProxy(obj)); - return reinterpret_cast(obj)->slotRef(slot); -} - -inline void -SetReservedOrProxyPrivateSlot(JSObject* obj, size_t slot, const Value& value) -{ - MOZ_ASSERT(slot == 0); - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj)) || IsProxy(obj)); - shadow::Object* sobj = reinterpret_cast(obj); - if (sobj->slotRef(slot).isMarkable() || value.isMarkable()) - SetReservedOrProxyPrivateSlotWithBarrier(obj, slot, value); - else - sobj->slotRef(slot) = value; -} - -class MOZ_STACK_CLASS ProxyOptions { - protected: - /* protected constructor for subclass */ - explicit ProxyOptions(bool singletonArg, bool lazyProtoArg = false) - : singleton_(singletonArg), - lazyProto_(lazyProtoArg), - clasp_(ProxyClassPtr) - {} - - public: - ProxyOptions() : singleton_(false), - lazyProto_(false), - clasp_(ProxyClassPtr) - {} - - bool singleton() const { return singleton_; } - ProxyOptions& setSingleton(bool flag) { - singleton_ = flag; - return *this; - } - - bool lazyProto() const { return lazyProto_; } - ProxyOptions& setLazyProto(bool flag) { - lazyProto_ = flag; - return *this; - } - - const Class* clasp() const { - return clasp_; - } - ProxyOptions& setClass(const Class* claspArg) { - clasp_ = claspArg; - return *this; - } - - private: - bool singleton_; - bool lazyProto_; - const Class* clasp_; -}; - -JS_FRIEND_API(JSObject*) -NewProxyObject(JSContext* cx, const BaseProxyHandler* handler, HandleValue priv, - JSObject* proto, const ProxyOptions& options = ProxyOptions()); - -JSObject* -RenewProxyObject(JSContext* cx, JSObject* obj, BaseProxyHandler* handler, const Value& priv); - -class JS_FRIEND_API(AutoEnterPolicy) -{ - public: - typedef BaseProxyHandler::Action Action; - AutoEnterPolicy(JSContext* cx, const BaseProxyHandler* handler, - HandleObject wrapper, HandleId id, Action act, bool mayThrow) -#ifdef JS_DEBUG - : context(nullptr) -#endif - { - allow = handler->hasSecurityPolicy() ? handler->enter(cx, wrapper, id, act, &rv) - : true; - recordEnter(cx, wrapper, id, act); - // We want to throw an exception if all of the following are true: - // * The policy disallowed access. - // * The policy set rv to false, indicating that we should throw. - // * The caller did not instruct us to ignore exceptions. - // * The policy did not throw itself. - if (!allow && !rv && mayThrow) - reportErrorIfExceptionIsNotPending(cx, id); - } - - virtual ~AutoEnterPolicy() { recordLeave(); } - inline bool allowed() { return allow; } - inline bool returnValue() { MOZ_ASSERT(!allowed()); return rv; } - - protected: - // no-op constructor for subclass - AutoEnterPolicy() -#ifdef JS_DEBUG - : context(nullptr) - , enteredAction(BaseProxyHandler::NONE) -#endif - {} - void reportErrorIfExceptionIsNotPending(JSContext* cx, jsid id); - bool allow; - bool rv; - -#ifdef JS_DEBUG - JSContext* context; - mozilla::Maybe enteredProxy; - mozilla::Maybe enteredId; - Action enteredAction; - - // NB: We explicitly don't track the entered action here, because sometimes - // set() methods do an implicit get() during their implementation, leading - // to spurious assertions. - AutoEnterPolicy* prev; - void recordEnter(JSContext* cx, HandleObject proxy, HandleId id, Action act); - void recordLeave(); - - friend JS_FRIEND_API(void) assertEnteredPolicy(JSContext* cx, JSObject* proxy, jsid id, Action act); -#else - inline void recordEnter(JSContext* cx, JSObject* proxy, jsid id, Action act) {} - inline void recordLeave() {} -#endif - -}; - -#ifdef JS_DEBUG -class JS_FRIEND_API(AutoWaivePolicy) : public AutoEnterPolicy { -public: - AutoWaivePolicy(JSContext* cx, HandleObject proxy, HandleId id, - BaseProxyHandler::Action act) - { - allow = true; - recordEnter(cx, proxy, id, act); - } -}; -#else -class JS_FRIEND_API(AutoWaivePolicy) { - public: - AutoWaivePolicy(JSContext* cx, HandleObject proxy, HandleId id, - BaseProxyHandler::Action act) - {} -}; -#endif - -#ifdef JS_DEBUG -extern JS_FRIEND_API(void) -assertEnteredPolicy(JSContext* cx, JSObject* obj, jsid id, - BaseProxyHandler::Action act); -#else -inline void assertEnteredPolicy(JSContext* cx, JSObject* obj, jsid id, - BaseProxyHandler::Action act) -{} -#endif - -extern JS_FRIEND_API(JSObject*) -InitProxyClass(JSContext* cx, JS::HandleObject obj); - -} /* namespace js */ - -#endif /* js_Proxy_h */ diff --git a/win32/include/spidermonkey/js/Realm.h b/win32/include/spidermonkey/js/Realm.h deleted file mode 100755 index 13a22c70..00000000 --- a/win32/include/spidermonkey/js/Realm.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Ways to get various per-Realm objects. All the getters declared in this - * header operate on the Realm corresponding to the current compartment on the - * JSContext. - */ - -#ifndef js_Realm_h -#define js_Realm_h - -#include "jstypes.h" - -struct JSContext; -class JSObject; - -namespace JS { - -extern JS_PUBLIC_API(JSObject*) -GetRealmObjectPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmFunctionPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmArrayPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmErrorPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -GetRealmIteratorPrototype(JSContext* cx); - -} // namespace JS - -#endif // js_Realm_h - - diff --git a/win32/include/spidermonkey/js/RequiredDefines.h b/win32/include/spidermonkey/js/RequiredDefines.h deleted file mode 100755 index 308fd7d6..00000000 --- a/win32/include/spidermonkey/js/RequiredDefines.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Various #defines required to build SpiderMonkey. Embedders should add this - * file to the start of the command line via -include or a similar mechanism, - * or SpiderMonkey public headers may not work correctly. - */ - -#ifndef js_RequiredDefines_h -#define js_RequiredDefines_h - -/* - * The c99 defining the limit macros (UINT32_MAX for example), says: - * - * C++ implementations should define these macros only when - * __STDC_LIMIT_MACROS is defined before is included. - * - * The same also occurs with __STDC_CONSTANT_MACROS for the constant macros - * (INT8_C for example) used to specify a literal constant of the proper type, - * and with __STDC_FORMAT_MACROS for the format macros (PRId32 for example) used - * with the fprintf function family. - */ -#define __STDC_LIMIT_MACROS -#define __STDC_CONSTANT_MACROS -#define __STDC_FORMAT_MACROS - -/* Also define a char16_t type if not provided by the compiler. */ -#include "mozilla/Char16.h" - -#endif /* js_RequiredDefines_h */ diff --git a/win32/include/spidermonkey/js/RootingAPI.h b/win32/include/spidermonkey/js/RootingAPI.h deleted file mode 100755 index a99ac4ec..00000000 --- a/win32/include/spidermonkey/js/RootingAPI.h +++ /dev/null @@ -1,1308 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_RootingAPI_h -#define js_RootingAPI_h - -#include "mozilla/Attributes.h" -#include "mozilla/DebugOnly.h" -#include "mozilla/GuardObjects.h" -#include "mozilla/LinkedList.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include - -#include "jspubtd.h" - -#include "js/GCAnnotations.h" -#include "js/GCAPI.h" -#include "js/GCPolicyAPI.h" -#include "js/HeapAPI.h" -#include "js/TypeDecls.h" -#include "js/UniquePtr.h" -#include "js/Utility.h" - -/* - * Moving GC Stack Rooting - * - * A moving GC may change the physical location of GC allocated things, even - * when they are rooted, updating all pointers to the thing to refer to its new - * location. The GC must therefore know about all live pointers to a thing, - * not just one of them, in order to behave correctly. - * - * The |Rooted| and |Handle| classes below are used to root stack locations - * whose value may be held live across a call that can trigger GC. For a - * code fragment such as: - * - * JSObject* obj = NewObject(cx); - * DoSomething(cx); - * ... = obj->lastProperty(); - * - * If |DoSomething()| can trigger a GC, the stack location of |obj| must be - * rooted to ensure that the GC does not move the JSObject referred to by - * |obj| without updating |obj|'s location itself. This rooting must happen - * regardless of whether there are other roots which ensure that the object - * itself will not be collected. - * - * If |DoSomething()| cannot trigger a GC, and the same holds for all other - * calls made between |obj|'s definitions and its last uses, then no rooting - * is required. - * - * SpiderMonkey can trigger a GC at almost any time and in ways that are not - * always clear. For example, the following innocuous-looking actions can - * cause a GC: allocation of any new GC thing; JSObject::hasProperty; - * JS_ReportError and friends; and ToNumber, among many others. The following - * dangerous-looking actions cannot trigger a GC: js_malloc, cx->malloc_, - * rt->malloc_, and friends and JS_ReportOutOfMemory. - * - * The following family of three classes will exactly root a stack location. - * Incorrect usage of these classes will result in a compile error in almost - * all cases. Therefore, it is very hard to be incorrectly rooted if you use - * these classes exclusively. These classes are all templated on the type T of - * the value being rooted. - * - * - Rooted declares a variable of type T, whose value is always rooted. - * Rooted may be automatically coerced to a Handle, below. Rooted - * should be used whenever a local variable's value may be held live across a - * call which can trigger a GC. - * - * - Handle is a const reference to a Rooted. Functions which take GC - * things or values as arguments and need to root those arguments should - * generally use handles for those arguments and avoid any explicit rooting. - * This has two benefits. First, when several such functions call each other - * then redundant rooting of multiple copies of the GC thing can be avoided. - * Second, if the caller does not pass a rooted value a compile error will be - * generated, which is quicker and easier to fix than when relying on a - * separate rooting analysis. - * - * - MutableHandle is a non-const reference to Rooted. It is used in the - * same way as Handle and includes a |set(const T& v)| method to allow - * updating the value of the referenced Rooted. A MutableHandle can be - * created with an implicit cast from a Rooted*. - * - * In some cases the small performance overhead of exact rooting (measured to - * be a few nanoseconds on desktop) is too much. In these cases, try the - * following: - * - * - Move all Rooted above inner loops: this allows you to re-use the root - * on each iteration of the loop. - * - * - Pass Handle through your hot call stack to avoid re-rooting costs at - * every invocation. - * - * The following diagram explains the list of supported, implicit type - * conversions between classes of this family: - * - * Rooted ----> Handle - * | ^ - * | | - * | | - * +---> MutableHandle - * (via &) - * - * All of these types have an implicit conversion to raw pointers. - */ - -namespace js { - -template -struct BarrierMethods { -}; - -template -class RootedBase {}; - -template -class HandleBase {}; - -template -class MutableHandleBase {}; - -template -class HeapBase {}; - -// Cannot use FOR_EACH_HEAP_ABLE_GC_POINTER_TYPE, as this would import too many macros into scope -template struct IsHeapConstructibleType { static constexpr bool value = false; }; -#define DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE(T) \ - template <> struct IsHeapConstructibleType { static constexpr bool value = true; }; -FOR_EACH_PUBLIC_GC_POINTER_TYPE(DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE) -FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE) -#undef DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE - -template -class PersistentRootedBase {}; - -static void* const ConstNullValue = nullptr; - -namespace gc { -struct Cell; -template -struct PersistentRootedMarker; -} /* namespace gc */ - -#define DECLARE_POINTER_COMPARISON_OPS(T) \ - bool operator==(const T& other) const { return get() == other; } \ - bool operator!=(const T& other) const { return get() != other; } - -// Important: Return a reference so passing a Rooted, etc. to -// something that takes a |const T&| is not a GC hazard. -#define DECLARE_POINTER_CONSTREF_OPS(T) \ - operator const T&() const { return get(); } \ - const T& operator->() const { return get(); } - -// Assignment operators on a base class are hidden by the implicitly defined -// operator= on the derived class. Thus, define the operator= directly on the -// class as we would need to manually pass it through anyway. -#define DECLARE_POINTER_ASSIGN_OPS(Wrapper, T) \ - Wrapper& operator=(const T& p) { \ - set(p); \ - return *this; \ - } \ - Wrapper& operator=(const Wrapper& other) { \ - set(other.get()); \ - return *this; \ - } \ - -#define DELETE_ASSIGNMENT_OPS(Wrapper, T) \ - template Wrapper& operator=(S) = delete; \ - Wrapper& operator=(const Wrapper&) = delete; - -#define DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr) \ - const T* address() const { return &(ptr); } \ - const T& get() const { return (ptr); } \ - -#define DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr) \ - T* address() { return &(ptr); } \ - T& get() { return (ptr); } \ - -} /* namespace js */ - -namespace JS { - -template class Rooted; -template class PersistentRooted; - -/* This is exposing internal state of the GC for inlining purposes. */ -JS_FRIEND_API(bool) isGCEnabled(); - -JS_FRIEND_API(void) HeapObjectPostBarrier(JSObject** objp, JSObject* prev, JSObject* next); - -#ifdef JS_DEBUG -/** - * For generational GC, assert that an object is in the tenured generation as - * opposed to being in the nursery. - */ -extern JS_FRIEND_API(void) -AssertGCThingMustBeTenured(JSObject* obj); -extern JS_FRIEND_API(void) -AssertGCThingIsNotAnObjectSubclass(js::gc::Cell* cell); -#else -inline void -AssertGCThingMustBeTenured(JSObject* obj) {} -inline void -AssertGCThingIsNotAnObjectSubclass(js::gc::Cell* cell) {} -#endif - -/** - * The Heap class is a heap-stored reference to a JS GC thing. All members of - * heap classes that refer to GC things should use Heap (or possibly - * TenuredHeap, described below). - * - * Heap is an abstraction that hides some of the complexity required to - * maintain GC invariants for the contained reference. It uses operator - * overloading to provide a normal pointer interface, but notifies the GC every - * time the value it contains is updated. This is necessary for generational GC, - * which keeps track of all pointers into the nursery. - * - * Heap instances must be traced when their containing object is traced to - * keep the pointed-to GC thing alive. - * - * Heap objects should only be used on the heap. GC references stored on the - * C/C++ stack must use Rooted/Handle/MutableHandle instead. - * - * Type T must be a public GC pointer type. - */ -template -class Heap : public js::HeapBase -{ - // Please note: this can actually also be used by nsXBLMaybeCompiled, for legacy reasons. - static_assert(js::IsHeapConstructibleType::value, - "Type T must be a public GC pointer type"); - public: - Heap() { - static_assert(sizeof(T) == sizeof(Heap), - "Heap must be binary compatible with T."); - init(GCPolicy::initial()); - } - explicit Heap(const T& p) { init(p); } - - /* - * For Heap, move semantics are equivalent to copy semantics. In C++, a - * copy constructor taking const-ref is the way to get a single function - * that will be used for both lvalue and rvalue copies, so we can simply - * omit the rvalue variant. - */ - explicit Heap(const Heap& p) { init(p.ptr); } - - ~Heap() { - post(ptr, GCPolicy::initial()); - } - - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(Heap, T); - - const T* address() const { return &ptr; } - - void exposeToActiveJS() const { - js::BarrierMethods::exposeToJS(ptr); - } - const T& get() const { - exposeToActiveJS(); - return ptr; - } - const T& unbarrieredGet() const { - return ptr; - } - - T* unsafeGet() { return &ptr; } - - explicit operator bool() const { - return bool(js::BarrierMethods::asGCThingOrNull(ptr)); - } - explicit operator bool() { - return bool(js::BarrierMethods::asGCThingOrNull(ptr)); - } - - private: - void init(const T& newPtr) { - ptr = newPtr; - post(GCPolicy::initial(), ptr); - } - - void set(const T& newPtr) { - T tmp = ptr; - ptr = newPtr; - post(tmp, ptr); - } - - void post(const T& prev, const T& next) { - js::BarrierMethods::postBarrier(&ptr, prev, next); - } - - T ptr; -}; - -static MOZ_ALWAYS_INLINE bool -ObjectIsTenured(JSObject* obj) -{ - return !js::gc::IsInsideNursery(reinterpret_cast(obj)); -} - -static MOZ_ALWAYS_INLINE bool -ObjectIsTenured(const Heap& obj) -{ - return ObjectIsTenured(obj.unbarrieredGet()); -} - -static MOZ_ALWAYS_INLINE bool -ObjectIsMarkedGray(JSObject* obj) -{ - auto cell = reinterpret_cast(obj); - return js::gc::detail::CellIsMarkedGrayIfKnown(cell); -} - -static MOZ_ALWAYS_INLINE bool -ObjectIsMarkedGray(const JS::Heap& obj) -{ - return ObjectIsMarkedGray(obj.unbarrieredGet()); -} - -static MOZ_ALWAYS_INLINE bool -ScriptIsMarkedGray(JSScript* script) -{ - auto cell = reinterpret_cast(script); - return js::gc::detail::CellIsMarkedGrayIfKnown(cell); -} - -static MOZ_ALWAYS_INLINE bool -ScriptIsMarkedGray(const Heap& script) -{ - return ScriptIsMarkedGray(script.unbarrieredGet()); -} - -/** - * The TenuredHeap class is similar to the Heap class above in that it - * encapsulates the GC concerns of an on-heap reference to a JS object. However, - * it has two important differences: - * - * 1) Pointers which are statically known to only reference "tenured" objects - * can avoid the extra overhead of SpiderMonkey's write barriers. - * - * 2) Objects in the "tenured" heap have stronger alignment restrictions than - * those in the "nursery", so it is possible to store flags in the lower - * bits of pointers known to be tenured. TenuredHeap wraps a normal tagged - * pointer with a nice API for accessing the flag bits and adds various - * assertions to ensure that it is not mis-used. - * - * GC things are said to be "tenured" when they are located in the long-lived - * heap: e.g. they have gained tenure as an object by surviving past at least - * one GC. For performance, SpiderMonkey allocates some things which are known - * to normally be long lived directly into the tenured generation; for example, - * global objects. Additionally, SpiderMonkey does not visit individual objects - * when deleting non-tenured objects, so object with finalizers are also always - * tenured; for instance, this includes most DOM objects. - * - * The considerations to keep in mind when using a TenuredHeap vs a normal - * Heap are: - * - * - It is invalid for a TenuredHeap to refer to a non-tenured thing. - * - It is however valid for a Heap to refer to a tenured thing. - * - It is not possible to store flag bits in a Heap. - */ -template -class TenuredHeap : public js::HeapBase -{ - public: - TenuredHeap() : bits(0) { - static_assert(sizeof(T) == sizeof(TenuredHeap), - "TenuredHeap must be binary compatible with T."); - } - explicit TenuredHeap(T p) : bits(0) { setPtr(p); } - explicit TenuredHeap(const TenuredHeap& p) : bits(0) { setPtr(p.getPtr()); } - - bool operator==(const TenuredHeap& other) { return bits == other.bits; } - bool operator!=(const TenuredHeap& other) { return bits != other.bits; } - - void setPtr(T newPtr) { - MOZ_ASSERT((reinterpret_cast(newPtr) & flagsMask) == 0); - if (newPtr) - AssertGCThingMustBeTenured(newPtr); - bits = (bits & flagsMask) | reinterpret_cast(newPtr); - } - - void setFlags(uintptr_t flagsToSet) { - MOZ_ASSERT((flagsToSet & ~flagsMask) == 0); - bits |= flagsToSet; - } - - void unsetFlags(uintptr_t flagsToUnset) { - MOZ_ASSERT((flagsToUnset & ~flagsMask) == 0); - bits &= ~flagsToUnset; - } - - bool hasFlag(uintptr_t flag) const { - MOZ_ASSERT((flag & ~flagsMask) == 0); - return (bits & flag) != 0; - } - - T unbarrieredGetPtr() const { return reinterpret_cast(bits & ~flagsMask); } - uintptr_t getFlags() const { return bits & flagsMask; } - - void exposeToActiveJS() const { - js::BarrierMethods::exposeToJS(unbarrieredGetPtr()); - } - T getPtr() const { - exposeToActiveJS(); - return unbarrieredGetPtr(); - } - - operator T() const { return getPtr(); } - T operator->() const { return getPtr(); } - - explicit operator bool() const { - return bool(js::BarrierMethods::asGCThingOrNull(unbarrieredGetPtr())); - } - explicit operator bool() { - return bool(js::BarrierMethods::asGCThingOrNull(unbarrieredGetPtr())); - } - - TenuredHeap& operator=(T p) { - setPtr(p); - return *this; - } - - TenuredHeap& operator=(const TenuredHeap& other) { - bits = other.bits; - return *this; - } - - private: - enum { - maskBits = 3, - flagsMask = (1 << maskBits) - 1, - }; - - uintptr_t bits; -}; - -/** - * Reference to a T that has been rooted elsewhere. This is most useful - * as a parameter type, which guarantees that the T lvalue is properly - * rooted. See "Move GC Stack Rooting" above. - * - * If you want to add additional methods to Handle for a specific - * specialization, define a HandleBase specialization containing them. - */ -template -class MOZ_NONHEAP_CLASS Handle : public js::HandleBase -{ - friend class JS::MutableHandle; - - public: - /* Creates a handle from a handle of a type convertible to T. */ - template - MOZ_IMPLICIT Handle(Handle handle, - typename mozilla::EnableIf::value, int>::Type dummy = 0) - { - static_assert(sizeof(Handle) == sizeof(T*), - "Handle must be binary compatible with T*."); - ptr = reinterpret_cast(handle.address()); - } - - MOZ_IMPLICIT Handle(decltype(nullptr)) { - static_assert(mozilla::IsPointer::value, - "nullptr_t overload not valid for non-pointer types"); - ptr = reinterpret_cast(&js::ConstNullValue); - } - - MOZ_IMPLICIT Handle(MutableHandle handle) { - ptr = handle.address(); - } - - /* - * Take care when calling this method! - * - * This creates a Handle from the raw location of a T. - * - * It should be called only if the following conditions hold: - * - * 1) the location of the T is guaranteed to be marked (for some reason - * other than being a Rooted), e.g., if it is guaranteed to be reachable - * from an implicit root. - * - * 2) the contents of the location are immutable, or at least cannot change - * for the lifetime of the handle, as its users may not expect its value - * to change underneath them. - */ - static constexpr Handle fromMarkedLocation(const T* p) { - return Handle(p, DeliberatelyChoosingThisOverload, - ImUsingThisOnlyInFromFromMarkedLocation); - } - - /* - * Construct a handle from an explicitly rooted location. This is the - * normal way to create a handle, and normally happens implicitly. - */ - template - inline - MOZ_IMPLICIT Handle(const Rooted& root, - typename mozilla::EnableIf::value, int>::Type dummy = 0); - - template - inline - MOZ_IMPLICIT Handle(const PersistentRooted& root, - typename mozilla::EnableIf::value, int>::Type dummy = 0); - - /* Construct a read only handle from a mutable handle. */ - template - inline - MOZ_IMPLICIT Handle(MutableHandle& root, - typename mozilla::EnableIf::value, int>::Type dummy = 0); - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr); - - private: - Handle() {} - DELETE_ASSIGNMENT_OPS(Handle, T); - - enum Disambiguator { DeliberatelyChoosingThisOverload = 42 }; - enum CallerIdentity { ImUsingThisOnlyInFromFromMarkedLocation = 17 }; - constexpr Handle(const T* p, Disambiguator, CallerIdentity) : ptr(p) {} - - const T* ptr; -}; - -/** - * Similar to a handle, but the underlying storage can be changed. This is - * useful for outparams. - * - * If you want to add additional methods to MutableHandle for a specific - * specialization, define a MutableHandleBase specialization containing - * them. - */ -template -class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase -{ - public: - inline MOZ_IMPLICIT MutableHandle(Rooted* root); - inline MOZ_IMPLICIT MutableHandle(PersistentRooted* root); - - private: - // Disallow nullptr for overloading purposes. - MutableHandle(decltype(nullptr)) = delete; - - public: - void set(const T& v) { - *ptr = v; - } - - /* - * This may be called only if the location of the T is guaranteed - * to be marked (for some reason other than being a Rooted), - * e.g., if it is guaranteed to be reachable from an implicit root. - * - * Create a MutableHandle from a raw location of a T. - */ - static MutableHandle fromMarkedLocation(T* p) { - MutableHandle h; - h.ptr = p; - return h; - } - - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(*ptr); - - private: - MutableHandle() {} - DELETE_ASSIGNMENT_OPS(MutableHandle, T); - - T* ptr; -}; - -} /* namespace JS */ - -namespace js { - -template -struct BarrierMethods -{ - static T* initial() { return nullptr; } - static gc::Cell* asGCThingOrNull(T* v) { - if (!v) - return nullptr; - MOZ_ASSERT(uintptr_t(v) > 32); - return reinterpret_cast(v); - } - static void postBarrier(T** vp, T* prev, T* next) { - if (next) - JS::AssertGCThingIsNotAnObjectSubclass(reinterpret_cast(next)); - } - static void exposeToJS(T* t) { - if (t) - js::gc::ExposeGCThingToActiveJS(JS::GCCellPtr(t)); - } -}; - -template <> -struct BarrierMethods -{ - static JSObject* initial() { return nullptr; } - static gc::Cell* asGCThingOrNull(JSObject* v) { - if (!v) - return nullptr; - MOZ_ASSERT(uintptr_t(v) > 32); - return reinterpret_cast(v); - } - static void postBarrier(JSObject** vp, JSObject* prev, JSObject* next) { - JS::HeapObjectPostBarrier(vp, prev, next); - } - static void exposeToJS(JSObject* obj) { - if (obj) - JS::ExposeObjectToActiveJS(obj); - } -}; - -template <> -struct BarrierMethods -{ - static JSFunction* initial() { return nullptr; } - static gc::Cell* asGCThingOrNull(JSFunction* v) { - if (!v) - return nullptr; - MOZ_ASSERT(uintptr_t(v) > 32); - return reinterpret_cast(v); - } - static void postBarrier(JSFunction** vp, JSFunction* prev, JSFunction* next) { - JS::HeapObjectPostBarrier(reinterpret_cast(vp), - reinterpret_cast(prev), - reinterpret_cast(next)); - } - static void exposeToJS(JSFunction* fun) { - if (fun) - JS::ExposeObjectToActiveJS(reinterpret_cast(fun)); - } -}; - -// Provide hash codes for Cell kinds that may be relocated and, thus, not have -// a stable address to use as the base for a hash code. Instead of the address, -// this hasher uses Cell::getUniqueId to provide exact matches and as a base -// for generating hash codes. -// -// Note: this hasher, like PointerHasher can "hash" a nullptr. While a nullptr -// would not likely be a useful key, there are some cases where being able to -// hash a nullptr is useful, either on purpose or because of bugs: -// (1) existence checks where the key may happen to be null and (2) some -// aggregate Lookup kinds embed a JSObject* that is frequently null and do not -// null test before dispatching to the hasher. -template -struct JS_PUBLIC_API(MovableCellHasher) -{ - using Key = T; - using Lookup = T; - - static bool hasHash(const Lookup& l); - static bool ensureHash(const Lookup& l); - static HashNumber hash(const Lookup& l); - static bool match(const Key& k, const Lookup& l); - static void rekey(Key& k, const Key& newKey) { k = newKey; } -}; - -template -struct JS_PUBLIC_API(MovableCellHasher>) -{ - using Key = JS::Heap; - using Lookup = T; - - static bool hasHash(const Lookup& l) { return MovableCellHasher::hasHash(l); } - static bool ensureHash(const Lookup& l) { return MovableCellHasher::ensureHash(l); } - static HashNumber hash(const Lookup& l) { return MovableCellHasher::hash(l); } - static bool match(const Key& k, const Lookup& l) { - return MovableCellHasher::match(k.unbarrieredGet(), l); - } - static void rekey(Key& k, const Key& newKey) { k.unsafeSet(newKey); } -}; - -template -struct FallibleHashMethods> -{ - template static bool hasHash(Lookup&& l) { - return MovableCellHasher::hasHash(mozilla::Forward(l)); - } - template static bool ensureHash(Lookup&& l) { - return MovableCellHasher::ensureHash(mozilla::Forward(l)); - } -}; - -} /* namespace js */ - -namespace js { - -// The alignment must be set because the Rooted and PersistentRooted ptr fields -// may be accessed through reinterpret_cast*>, and -// the compiler may choose a different alignment for the ptr field when it -// knows the actual type stored in DispatchWrapper. -// -// It would make more sense to align only those specific fields of type -// DispatchWrapper, rather than DispatchWrapper itself, but that causes MSVC to -// fail when Rooted is used in an IsConvertible test. -template -class alignas(8) DispatchWrapper -{ - static_assert(JS::MapTypeToRootKind::kind == JS::RootKind::Traceable, - "DispatchWrapper is intended only for usage with a Traceable"); - - using TraceFn = void (*)(JSTracer*, T*, const char*); - TraceFn tracer; - alignas(gc::CellSize) T storage; - - public: - template - MOZ_IMPLICIT DispatchWrapper(U&& initial) - : tracer(&JS::GCPolicy::trace), - storage(mozilla::Forward(initial)) - { } - - // Mimic a pointer type, so that we can drop into Rooted. - T* operator &() { return &storage; } - const T* operator &() const { return &storage; } - operator T&() { return storage; } - operator const T&() const { return storage; } - - // Trace the contained storage (of unknown type) using the trace function - // we set aside when we did know the type. - static void TraceWrapped(JSTracer* trc, T* thingp, const char* name) { - auto wrapper = reinterpret_cast( - uintptr_t(thingp) - offsetof(DispatchWrapper, storage)); - wrapper->tracer(trc, &wrapper->storage, name); - } -}; - -} /* namespace js */ - -namespace JS { - -/** - * Local variable of type T whose value is always rooted. This is typically - * used for local variables, or for non-rooted values being passed to a - * function that requires a handle, e.g. Foo(Root(cx, x)). - * - * If you want to add additional methods to Rooted for a specific - * specialization, define a RootedBase specialization containing them. - */ -template -class MOZ_RAII Rooted : public js::RootedBase -{ - inline void registerWithRootLists(js::RootedListHeads& roots) { - this->stack = &roots[JS::MapTypeToRootKind::kind]; - this->prev = *stack; - *stack = reinterpret_cast*>(this); - } - - inline js::RootedListHeads& rootLists(JS::RootingContext* cx) { - return rootLists(static_cast(cx)); - } - inline js::RootedListHeads& rootLists(js::ContextFriendFields* cx) { - if (JS::Zone* zone = cx->zone_) - return JS::shadow::Zone::asShadowZone(zone)->stackRoots_; - MOZ_ASSERT(cx->isJSContext); - return cx->roots.stackRoots_; - } - inline js::RootedListHeads& rootLists(JSContext* cx) { - return rootLists(js::ContextFriendFields::get(cx)); - } - - public: - template - explicit Rooted(const RootingContext& cx) - : ptr(GCPolicy::initial()) - { - registerWithRootLists(rootLists(cx)); - } - - template - Rooted(const RootingContext& cx, S&& initial) - : ptr(mozilla::Forward(initial)) - { - registerWithRootLists(rootLists(cx)); - } - - ~Rooted() { - MOZ_ASSERT(*stack == reinterpret_cast*>(this)); - *stack = prev; - } - - Rooted* previous() { return reinterpret_cast*>(prev); } - - /* - * This method is public for Rooted so that Codegen.py can use a Rooted - * interchangeably with a MutableHandleValue. - */ - void set(const T& value) { - ptr = value; - } - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(Rooted, T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr); - - private: - /* - * These need to be templated on void* to avoid aliasing issues between, for - * example, Rooted and Rooted, which use the same - * stack head pointer for different classes. - */ - Rooted** stack; - Rooted* prev; - - /* - * For pointer types, the TraceKind for tracing is based on the list it is - * in (selected via MapTypeToRootKind), so no additional storage is - * required here. Non-pointer types, however, share the same list, so the - * function to call for tracing is stored adjacent to the struct. Since C++ - * cannot templatize on storage class, this is implemented via the wrapper - * class DispatchWrapper. - */ - using MaybeWrapped = typename mozilla::Conditional< - MapTypeToRootKind::kind == JS::RootKind::Traceable, - js::DispatchWrapper, - T>::Type; - MaybeWrapped ptr; - - Rooted(const Rooted&) = delete; -} JS_HAZ_ROOTED; - -} /* namespace JS */ - -namespace js { - -/** - * Augment the generic Rooted interface when T = JSObject* with - * class-querying and downcasting operations. - * - * Given a Rooted obj, one can view - * Handle h = obj.as(); - * as an optimization of - * Rooted rooted(cx, &obj->as()); - * Handle h = rooted; - */ -template <> -class RootedBase -{ - public: - template - JS::Handle as() const; -}; - -/** - * Augment the generic Handle interface when T = JSObject* with - * downcasting operations. - * - * Given a Handle obj, one can view - * Handle h = obj.as(); - * as an optimization of - * Rooted rooted(cx, &obj->as()); - * Handle h = rooted; - */ -template <> -class HandleBase -{ - public: - template - JS::Handle as() const; -}; - -/** Interface substitute for Rooted which does not root the variable's memory. */ -template -class MOZ_RAII FakeRooted : public RootedBase -{ - public: - template - explicit FakeRooted(CX* cx) : ptr(JS::GCPolicy::initial()) {} - - template - FakeRooted(CX* cx, T initial) : ptr(initial) {} - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(FakeRooted, T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr); - - private: - T ptr; - - void set(const T& value) { - ptr = value; - } - - FakeRooted(const FakeRooted&) = delete; -}; - -/** Interface substitute for MutableHandle which is not required to point to rooted memory. */ -template -class FakeMutableHandle : public js::MutableHandleBase -{ - public: - MOZ_IMPLICIT FakeMutableHandle(T* t) { - ptr = t; - } - - MOZ_IMPLICIT FakeMutableHandle(FakeRooted* root) { - ptr = root->address(); - } - - void set(const T& v) { - *ptr = v; - } - - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr); - DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(*ptr); - - private: - FakeMutableHandle() {} - DELETE_ASSIGNMENT_OPS(FakeMutableHandle, T); - - T* ptr; -}; - -/** - * Types for a variable that either should or shouldn't be rooted, depending on - * the template parameter allowGC. Used for implementing functions that can - * operate on either rooted or unrooted data. - * - * The toHandle() and toMutableHandle() functions are for calling functions - * which require handle types and are only called in the CanGC case. These - * allow the calling code to type check. - */ -enum AllowGC { - NoGC = 0, - CanGC = 1 -}; -template -class MaybeRooted -{ -}; - -template class MaybeRooted -{ - public: - typedef JS::Handle HandleType; - typedef JS::Rooted RootType; - typedef JS::MutableHandle MutableHandleType; - - static inline JS::Handle toHandle(HandleType v) { - return v; - } - - static inline JS::MutableHandle toMutableHandle(MutableHandleType v) { - return v; - } - - template - static inline JS::Handle downcastHandle(HandleType v) { - return v.template as(); - } -}; - -template class MaybeRooted -{ - public: - typedef const T& HandleType; - typedef FakeRooted RootType; - typedef FakeMutableHandle MutableHandleType; - - static JS::Handle toHandle(HandleType v) { - MOZ_CRASH("Bad conversion"); - } - - static JS::MutableHandle toMutableHandle(MutableHandleType v) { - MOZ_CRASH("Bad conversion"); - } - - template - static inline T2* downcastHandle(HandleType v) { - return &v->template as(); - } -}; - -} /* namespace js */ - -namespace JS { - -template template -inline -Handle::Handle(const Rooted& root, - typename mozilla::EnableIf::value, int>::Type dummy) -{ - ptr = reinterpret_cast(root.address()); -} - -template template -inline -Handle::Handle(const PersistentRooted& root, - typename mozilla::EnableIf::value, int>::Type dummy) -{ - ptr = reinterpret_cast(root.address()); -} - -template template -inline -Handle::Handle(MutableHandle& root, - typename mozilla::EnableIf::value, int>::Type dummy) -{ - ptr = reinterpret_cast(root.address()); -} - -template -inline -MutableHandle::MutableHandle(Rooted* root) -{ - static_assert(sizeof(MutableHandle) == sizeof(T*), - "MutableHandle must be binary compatible with T*."); - ptr = root->address(); -} - -template -inline -MutableHandle::MutableHandle(PersistentRooted* root) -{ - static_assert(sizeof(MutableHandle) == sizeof(T*), - "MutableHandle must be binary compatible with T*."); - ptr = root->address(); -} - -/** - * A copyable, assignable global GC root type with arbitrary lifetime, an - * infallible constructor, and automatic unrooting on destruction. - * - * These roots can be used in heap-allocated data structures, so they are not - * associated with any particular JSContext or stack. They are registered with - * the JSRuntime itself, without locking, so they require a full JSContext to be - * initialized, not one of its more restricted superclasses. Initialization may - * take place on construction, or in two phases if the no-argument constructor - * is called followed by init(). - * - * Note that you must not use an PersistentRooted in an object owned by a JS - * object: - * - * Whenever one object whose lifetime is decided by the GC refers to another - * such object, that edge must be traced only if the owning JS object is traced. - * This applies not only to JS objects (which obviously are managed by the GC) - * but also to C++ objects owned by JS objects. - * - * If you put a PersistentRooted in such a C++ object, that is almost certainly - * a leak. When a GC begins, the referent of the PersistentRooted is treated as - * live, unconditionally (because a PersistentRooted is a *root*), even if the - * JS object that owns it is unreachable. If there is any path from that - * referent back to the JS object, then the C++ object containing the - * PersistentRooted will not be destructed, and the whole blob of objects will - * not be freed, even if there are no references to them from the outside. - * - * In the context of Firefox, this is a severe restriction: almost everything in - * Firefox is owned by some JS object or another, so using PersistentRooted in - * such objects would introduce leaks. For these kinds of edges, Heap or - * TenuredHeap would be better types. It's up to the implementor of the type - * containing Heap or TenuredHeap members to make sure their referents get - * marked when the object itself is marked. - */ -template -class PersistentRooted : public js::PersistentRootedBase, - private mozilla::LinkedListElement> -{ - using ListBase = mozilla::LinkedListElement>; - - friend class mozilla::LinkedList; - friend class mozilla::LinkedListElement; - - void registerWithRootLists(js::RootLists& roots) { - MOZ_ASSERT(!initialized()); - JS::RootKind kind = JS::MapTypeToRootKind::kind; - roots.heapRoots_[kind].insertBack(reinterpret_cast*>(this)); - } - - js::RootLists& rootLists(JSContext* cx) { - return rootLists(JS::RootingContext::get(cx)); - } - js::RootLists& rootLists(JS::RootingContext* cx) { - MOZ_ASSERT(cx->isJSContext); - return cx->roots; - } - - // Disallow ExclusiveContext*. - js::RootLists& rootLists(js::ContextFriendFields* cx) = delete; - - public: - PersistentRooted() : ptr(GCPolicy::initial()) {} - - template - explicit PersistentRooted(const RootingContext& cx) - : ptr(GCPolicy::initial()) - { - registerWithRootLists(rootLists(cx)); - } - - template - PersistentRooted(const RootingContext& cx, U&& initial) - : ptr(mozilla::Forward(initial)) - { - registerWithRootLists(rootLists(cx)); - } - - PersistentRooted(const PersistentRooted& rhs) - : mozilla::LinkedListElement>(), - ptr(rhs.ptr) - { - /* - * Copy construction takes advantage of the fact that the original - * is already inserted, and simply adds itself to whatever list the - * original was on - no JSRuntime pointer needed. - * - * This requires mutating rhs's links, but those should be 'mutable' - * anyway. C++ doesn't let us declare mutable base classes. - */ - const_cast(rhs).setNext(this); - } - - bool initialized() { - return ListBase::isInList(); - } - - template - void init(const RootingContext& cx) { - init(cx, GCPolicy::initial()); - } - - template - void init(const RootingContext& cx, U&& initial) { - ptr = mozilla::Forward(initial); - registerWithRootLists(rootLists(cx)); - } - - void reset() { - if (initialized()) { - set(GCPolicy::initial()); - ListBase::remove(); - } - } - - DECLARE_POINTER_COMPARISON_OPS(T); - DECLARE_POINTER_CONSTREF_OPS(T); - DECLARE_POINTER_ASSIGN_OPS(PersistentRooted, T); - DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr); - - // These are the same as DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS, except - // they check that |this| is initialized in case the caller later stores - // something in |ptr|. - T* address() { - MOZ_ASSERT(initialized()); - return &ptr; - } - T& get() { - MOZ_ASSERT(initialized()); - return ptr; - } - - private: - template - void set(U&& value) { - MOZ_ASSERT(initialized()); - ptr = mozilla::Forward(value); - } - - // See the comment above Rooted::ptr. - using MaybeWrapped = typename mozilla::Conditional< - MapTypeToRootKind::kind == JS::RootKind::Traceable, - js::DispatchWrapper, - T>::Type; - MaybeWrapped ptr; -} JS_HAZ_ROOTED; - -class JS_PUBLIC_API(ObjectPtr) -{ - Heap value; - - public: - ObjectPtr() : value(nullptr) {} - - explicit ObjectPtr(JSObject* obj) : value(obj) {} - - /* Always call finalize before the destructor. */ - ~ObjectPtr() { MOZ_ASSERT(!value); } - - void finalize(JSRuntime* rt); - void finalize(JSContext* cx); - - void init(JSObject* obj) { value = obj; } - - JSObject* get() const { return value; } - JSObject* unbarrieredGet() const { return value.unbarrieredGet(); } - - void writeBarrierPre(JSContext* cx) { - IncrementalObjectBarrier(value); - } - - void updateWeakPointerAfterGC(); - - ObjectPtr& operator=(JSObject* obj) { - IncrementalObjectBarrier(value); - value = obj; - return *this; - } - - void trace(JSTracer* trc, const char* name); - - JSObject& operator*() const { return *value; } - JSObject* operator->() const { return value; } - operator JSObject*() const { return value; } - - explicit operator bool() const { return value.unbarrieredGet(); } - explicit operator bool() { return value.unbarrieredGet(); } -}; - -} /* namespace JS */ - -namespace js { - -template -class UniquePtrOperations -{ - const UniquePtr& uniquePtr() const { return static_cast(this)->get(); } - - public: - explicit operator bool() const { return !!uniquePtr(); } -}; - -template -class MutableUniquePtrOperations : public UniquePtrOperations -{ - UniquePtr& uniquePtr() { return static_cast(this)->get(); } - - public: - MOZ_MUST_USE typename UniquePtr::Pointer release() { return uniquePtr().release(); } -}; - -template -class RootedBase> - : public MutableUniquePtrOperations>, T, D> -{ }; - -template -class MutableHandleBase> - : public MutableUniquePtrOperations>, T, D> -{ }; - -template -class HandleBase> - : public UniquePtrOperations>, T, D> -{ }; - -template -class PersistentRootedBase> - : public MutableUniquePtrOperations>, T, D> -{ }; - -namespace gc { - -template -void -CallTraceCallbackOnNonHeap(T* v, const TraceCallbacks& aCallbacks, const char* aName, void* aClosure) -{ - static_assert(sizeof(T) == sizeof(JS::Heap), "T and Heap must be compatible."); - MOZ_ASSERT(v); - mozilla::DebugOnly cell = BarrierMethods::asGCThingOrNull(*v); - MOZ_ASSERT(cell); - MOZ_ASSERT(!IsInsideNursery(cell)); - JS::Heap* asHeapT = reinterpret_cast*>(v); - aCallbacks.Trace(asHeapT, aName, aClosure); -} - -} /* namespace gc */ -} /* namespace js */ - -// mozilla::Swap uses a stack temporary, which prevents classes like Heap -// from being declared MOZ_HEAP_CLASS. -namespace mozilla { - -template -inline void -Swap(JS::Heap& aX, JS::Heap& aY) -{ - T tmp = aX; - aX = aY; - aY = tmp; -} - -template -inline void -Swap(JS::TenuredHeap& aX, JS::TenuredHeap& aY) -{ - T tmp = aX; - aX = aY; - aY = tmp; -} - -} /* namespace mozilla */ - -#undef DELETE_ASSIGNMENT_OPS - -#endif /* js_RootingAPI_h */ diff --git a/win32/include/spidermonkey/js/SliceBudget.h b/win32/include/spidermonkey/js/SliceBudget.h deleted file mode 100755 index 78982df0..00000000 --- a/win32/include/spidermonkey/js/SliceBudget.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_SliceBudget_h -#define js_SliceBudget_h - -#include - -namespace js { - -struct JS_PUBLIC_API(TimeBudget) -{ - int64_t budget; - - explicit TimeBudget(int64_t milliseconds) { budget = milliseconds; } -}; - -struct JS_PUBLIC_API(WorkBudget) -{ - int64_t budget; - - explicit WorkBudget(int64_t work) { budget = work; } -}; - -/* - * This class records how much work has been done in a given collection slice, - * so that we can return before pausing for too long. Some slices are allowed - * to run for unlimited time, and others are bounded. To reduce the number of - * gettimeofday calls, we only check the time every 1000 operations. - */ -class JS_PUBLIC_API(SliceBudget) -{ - static const int64_t unlimitedDeadline = INT64_MAX; - static const intptr_t unlimitedStartCounter = INTPTR_MAX; - - bool checkOverBudget(); - - SliceBudget(); - - public: - // Memory of the originally requested budget. If isUnlimited, neither of - // these are in use. If deadline==0, then workBudget is valid. Otherwise - // timeBudget is valid. - TimeBudget timeBudget; - WorkBudget workBudget; - - int64_t deadline; /* in microseconds */ - intptr_t counter; - - static const intptr_t CounterReset = 1000; - - static const int64_t UnlimitedTimeBudget = -1; - static const int64_t UnlimitedWorkBudget = -1; - - /* Use to create an unlimited budget. */ - static SliceBudget unlimited() { return SliceBudget(); } - - /* Instantiate as SliceBudget(TimeBudget(n)). */ - explicit SliceBudget(TimeBudget time); - - /* Instantiate as SliceBudget(WorkBudget(n)). */ - explicit SliceBudget(WorkBudget work); - - void makeUnlimited() { - deadline = unlimitedDeadline; - counter = unlimitedStartCounter; - } - - void step(intptr_t amt = 1) { - counter -= amt; - } - - bool isOverBudget() { - if (counter > 0) - return false; - return checkOverBudget(); - } - - bool isWorkBudget() const { return deadline == 0; } - bool isTimeBudget() const { return deadline > 0 && !isUnlimited(); } - bool isUnlimited() const { return deadline == unlimitedDeadline; } - - int describe(char* buffer, size_t maxlen) const; -}; - -} // namespace js - -#endif /* js_SliceBudget_h */ diff --git a/win32/include/spidermonkey/js/StructuredClone.h b/win32/include/spidermonkey/js/StructuredClone.h deleted file mode 100755 index e10a3073..00000000 --- a/win32/include/spidermonkey/js/StructuredClone.h +++ /dev/null @@ -1,358 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_StructuredClone_h -#define js_StructuredClone_h - -#include "mozilla/Attributes.h" -#include "mozilla/BufferList.h" - -#include - -#include "jstypes.h" - -#include "js/RootingAPI.h" -#include "js/TypeDecls.h" -#include "js/Value.h" - -struct JSRuntime; -struct JSStructuredCloneReader; -struct JSStructuredCloneWriter; - -// API for the HTML5 internal structured cloning algorithm. - -namespace JS { - -enum class StructuredCloneScope : uint32_t { - SameProcessSameThread, - SameProcessDifferentThread, - DifferentProcess -}; - -enum TransferableOwnership { - /** Transferable data has not been filled in yet */ - SCTAG_TMO_UNFILLED = 0, - - /** Structured clone buffer does not yet own the data */ - SCTAG_TMO_UNOWNED = 1, - - /** All values at least this large are owned by the clone buffer */ - SCTAG_TMO_FIRST_OWNED = 2, - - /** Data is a pointer that can be freed */ - SCTAG_TMO_ALLOC_DATA = 2, - - /** Data is a memory mapped pointer */ - SCTAG_TMO_MAPPED_DATA = 3, - - /** - * Data is embedding-specific. The engine can free it by calling the - * freeTransfer op. The embedding can also use SCTAG_TMO_USER_MIN and - * greater, up to 32 bits, to distinguish specific ownership variants. - */ - SCTAG_TMO_CUSTOM = 4, - - SCTAG_TMO_USER_MIN -}; - -class CloneDataPolicy -{ - bool sharedArrayBuffer_; - - public: - // The default is to allow all policy-controlled aspects. - - CloneDataPolicy() : - sharedArrayBuffer_(true) - {} - - // In the JS engine, SharedArrayBuffers can only be cloned intra-process - // because the shared memory areas are allocated in process-private memory. - // Clients should therefore deny SharedArrayBuffers when cloning data that - // are to be transmitted inter-process. - // - // Clients should also deny SharedArrayBuffers when cloning data that are to - // be transmitted intra-process if policy needs dictate such denial. - - CloneDataPolicy& denySharedArrayBuffer() { - sharedArrayBuffer_ = false; - return *this; - } - - bool isSharedArrayBufferAllowed() const { - return sharedArrayBuffer_; - } -}; - -} /* namespace JS */ - -/** - * Read structured data from the reader r. This hook is used to read a value - * previously serialized by a call to the WriteStructuredCloneOp hook. - * - * tag and data are the pair of uint32_t values from the header. The callback - * may use the JS_Read* APIs to read any other relevant parts of the object - * from the reader r. closure is any value passed to the JS_ReadStructuredClone - * function. Return the new object on success, nullptr on error/exception. - */ -typedef JSObject* (*ReadStructuredCloneOp)(JSContext* cx, JSStructuredCloneReader* r, - uint32_t tag, uint32_t data, void* closure); - -/** - * Structured data serialization hook. The engine can write primitive values, - * Objects, Arrays, Dates, RegExps, TypedArrays, ArrayBuffers, Sets, Maps, - * and SharedTypedArrays. Any other type of object requires application support. - * This callback must first use the JS_WriteUint32Pair API to write an object - * header, passing a value greater than JS_SCTAG_USER to the tag parameter. - * Then it can use the JS_Write* APIs to write any other relevant parts of - * the value v to the writer w. closure is any value passed to the - * JS_WriteStructuredClone function. - * - * Return true on success, false on error/exception. - */ -typedef bool (*WriteStructuredCloneOp)(JSContext* cx, JSStructuredCloneWriter* w, - JS::HandleObject obj, void* closure); - -/** - * This is called when JS_WriteStructuredClone is given an invalid transferable. - * To follow HTML5, the application must throw a DATA_CLONE_ERR DOMException - * with error set to one of the JS_SCERR_* values. - */ -typedef void (*StructuredCloneErrorOp)(JSContext* cx, uint32_t errorid); - -/** - * This is called when JS_ReadStructuredClone receives a transferable object - * not known to the engine. If this hook does not exist or returns false, the - * JS engine calls the reportError op if set, otherwise it throws a - * DATA_CLONE_ERR DOM Exception. This method is called before any other - * callback and must return a non-null object in returnObject on success. - */ -typedef bool (*ReadTransferStructuredCloneOp)(JSContext* cx, JSStructuredCloneReader* r, - uint32_t tag, void* content, uint64_t extraData, - void* closure, - JS::MutableHandleObject returnObject); - -/** - * Called when JS_WriteStructuredClone receives a transferable object not - * handled by the engine. If this hook does not exist or returns false, the JS - * engine will call the reportError hook or fall back to throwing a - * DATA_CLONE_ERR DOM Exception. This method is called before any other - * callback. - * - * tag: indicates what type of transferable this is. Must be greater than - * 0xFFFF0201 (value of the internal SCTAG_TRANSFER_MAP_PENDING_ENTRY) - * - * ownership: see TransferableOwnership, above. Used to communicate any needed - * ownership info to the FreeTransferStructuredCloneOp. - * - * content, extraData: what the ReadTransferStructuredCloneOp will receive - */ -typedef bool (*TransferStructuredCloneOp)(JSContext* cx, - JS::Handle obj, - void* closure, - // Output: - uint32_t* tag, - JS::TransferableOwnership* ownership, - void** content, - uint64_t* extraData); - -/** - * Called when freeing an unknown transferable object. Note that it - * should never trigger a garbage collection (and will assert in a - * debug build if it does.) - */ -typedef void (*FreeTransferStructuredCloneOp)(uint32_t tag, JS::TransferableOwnership ownership, - void* content, uint64_t extraData, void* closure); - -// The maximum supported structured-clone serialization format version. -// Increment this when anything at all changes in the serialization format. -// (Note that this does not need to be bumped for Transferable-only changes, -// since they are never saved to persistent storage.) -#define JS_STRUCTURED_CLONE_VERSION 8 - -struct JSStructuredCloneCallbacks { - ReadStructuredCloneOp read; - WriteStructuredCloneOp write; - StructuredCloneErrorOp reportError; - ReadTransferStructuredCloneOp readTransfer; - TransferStructuredCloneOp writeTransfer; - FreeTransferStructuredCloneOp freeTransfer; -}; - -enum OwnTransferablePolicy { - OwnsTransferablesIfAny, - IgnoreTransferablesIfAny, - NoTransferables -}; - -class MOZ_NON_MEMMOVABLE JSStructuredCloneData : public mozilla::BufferList -{ - typedef js::SystemAllocPolicy AllocPolicy; - typedef mozilla::BufferList BufferList; - - static const size_t kInitialSize = 0; - static const size_t kInitialCapacity = 4096; - static const size_t kStandardCapacity = 4096; - - const JSStructuredCloneCallbacks* callbacks_; - void* closure_; - OwnTransferablePolicy ownTransferables_; - - void setOptionalCallbacks(const JSStructuredCloneCallbacks* callbacks, - void* closure, - OwnTransferablePolicy policy) { - callbacks_ = callbacks; - closure_ = closure; - ownTransferables_ = policy; - } - - friend struct JSStructuredCloneWriter; - friend class JS_PUBLIC_API(JSAutoStructuredCloneBuffer); - -public: - explicit JSStructuredCloneData(AllocPolicy aAP = AllocPolicy()) - : BufferList(kInitialSize, kInitialCapacity, kStandardCapacity, aAP) - , callbacks_(nullptr) - , closure_(nullptr) - , ownTransferables_(OwnTransferablePolicy::NoTransferables) - {} - MOZ_IMPLICIT JSStructuredCloneData(BufferList&& buffers) - : BufferList(Move(buffers)) - , callbacks_(nullptr) - , closure_(nullptr) - , ownTransferables_(OwnTransferablePolicy::NoTransferables) - {} - JSStructuredCloneData(JSStructuredCloneData&& other) = default; - JSStructuredCloneData& operator=(JSStructuredCloneData&& other) = default; - ~JSStructuredCloneData(); - - using BufferList::BufferList; -}; - -/** Note: if the *data contains transferable objects, it can be read only once. */ -JS_PUBLIC_API(bool) -JS_ReadStructuredClone(JSContext* cx, JSStructuredCloneData& data, uint32_t version, - JS::StructuredCloneScope scope, - JS::MutableHandleValue vp, - const JSStructuredCloneCallbacks* optionalCallbacks, void* closure); - -JS_PUBLIC_API(bool) -JS_WriteStructuredClone(JSContext* cx, JS::HandleValue v, JSStructuredCloneData* data, - JS::StructuredCloneScope scope, - JS::CloneDataPolicy cloneDataPolicy, - const JSStructuredCloneCallbacks* optionalCallbacks, - void* closure, JS::HandleValue transferable); - -JS_PUBLIC_API(bool) -JS_StructuredCloneHasTransferables(JSStructuredCloneData& data, bool* hasTransferable); - -JS_PUBLIC_API(bool) -JS_StructuredClone(JSContext* cx, JS::HandleValue v, JS::MutableHandleValue vp, - const JSStructuredCloneCallbacks* optionalCallbacks, void* closure); - -/** RAII sugar for JS_WriteStructuredClone. */ -class JS_PUBLIC_API(JSAutoStructuredCloneBuffer) { - const JS::StructuredCloneScope scope_; - JSStructuredCloneData data_; - uint32_t version_; - - public: - JSAutoStructuredCloneBuffer(JS::StructuredCloneScope scope, - const JSStructuredCloneCallbacks* callbacks, void* closure) - : scope_(scope), version_(JS_STRUCTURED_CLONE_VERSION) - { - data_.setOptionalCallbacks(callbacks, closure, OwnTransferablePolicy::NoTransferables); - } - - JSAutoStructuredCloneBuffer(JSAutoStructuredCloneBuffer&& other); - JSAutoStructuredCloneBuffer& operator=(JSAutoStructuredCloneBuffer&& other); - - ~JSAutoStructuredCloneBuffer() { clear(); } - - JSStructuredCloneData& data() { return data_; } - bool empty() const { return !data_.Size(); } - - void clear(const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - /** Copy some memory. It will be automatically freed by the destructor. */ - bool copy(const JSStructuredCloneData& data, uint32_t version=JS_STRUCTURED_CLONE_VERSION, - const JSStructuredCloneCallbacks* callbacks=nullptr, void* closure=nullptr); - - /** - * Adopt some memory. It will be automatically freed by the destructor. - * data must have been allocated by the JS engine (e.g., extracted via - * JSAutoStructuredCloneBuffer::steal). - */ - void adopt(JSStructuredCloneData&& data, uint32_t version=JS_STRUCTURED_CLONE_VERSION, - const JSStructuredCloneCallbacks* callbacks=nullptr, void* closure=nullptr); - - /** - * Release the buffer and transfer ownership to the caller. - */ - void steal(JSStructuredCloneData* data, uint32_t* versionp=nullptr, - const JSStructuredCloneCallbacks** callbacks=nullptr, void** closure=nullptr); - - /** - * Abandon ownership of any transferable objects stored in the buffer, - * without freeing the buffer itself. Useful when copying the data out into - * an external container, though note that you will need to use adopt() to - * properly release that data eventually. - */ - void abandon() { data_.ownTransferables_ = OwnTransferablePolicy::IgnoreTransferablesIfAny; } - - bool read(JSContext* cx, JS::MutableHandleValue vp, - const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - bool write(JSContext* cx, JS::HandleValue v, - const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - bool write(JSContext* cx, JS::HandleValue v, JS::HandleValue transferable, - JS::CloneDataPolicy cloneDataPolicy, - const JSStructuredCloneCallbacks* optionalCallbacks=nullptr, void* closure=nullptr); - - private: - // Copy and assignment are not supported. - JSAutoStructuredCloneBuffer(const JSAutoStructuredCloneBuffer& other) = delete; - JSAutoStructuredCloneBuffer& operator=(const JSAutoStructuredCloneBuffer& other) = delete; -}; - -// The range of tag values the application may use for its own custom object types. -#define JS_SCTAG_USER_MIN ((uint32_t) 0xFFFF8000) -#define JS_SCTAG_USER_MAX ((uint32_t) 0xFFFFFFFF) - -#define JS_SCERR_RECURSION 0 -#define JS_SCERR_TRANSFERABLE 1 -#define JS_SCERR_DUP_TRANSFERABLE 2 -#define JS_SCERR_UNSUPPORTED_TYPE 3 - -JS_PUBLIC_API(bool) -JS_ReadUint32Pair(JSStructuredCloneReader* r, uint32_t* p1, uint32_t* p2); - -JS_PUBLIC_API(bool) -JS_ReadBytes(JSStructuredCloneReader* r, void* p, size_t len); - -JS_PUBLIC_API(bool) -JS_ReadTypedArray(JSStructuredCloneReader* r, JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_WriteUint32Pair(JSStructuredCloneWriter* w, uint32_t tag, uint32_t data); - -JS_PUBLIC_API(bool) -JS_WriteBytes(JSStructuredCloneWriter* w, const void* p, size_t len); - -JS_PUBLIC_API(bool) -JS_WriteString(JSStructuredCloneWriter* w, JS::HandleString str); - -JS_PUBLIC_API(bool) -JS_WriteTypedArray(JSStructuredCloneWriter* w, JS::HandleValue v); - -JS_PUBLIC_API(bool) -JS_ObjectNotWritten(JSStructuredCloneWriter* w, JS::HandleObject obj); - -JS_PUBLIC_API(JS::StructuredCloneScope) -JS_GetStructuredCloneScope(JSStructuredCloneWriter* w); - -#endif /* js_StructuredClone_h */ diff --git a/win32/include/spidermonkey/js/SweepingAPI.h b/win32/include/spidermonkey/js/SweepingAPI.h deleted file mode 100755 index 0eb29ae4..00000000 --- a/win32/include/spidermonkey/js/SweepingAPI.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_SweepingAPI_h -#define js_SweepingAPI_h - -#include "js/HeapAPI.h" - -namespace js { -template -class WeakCacheBase {}; -} // namespace js - -namespace JS { -template class WeakCache; - -namespace shadow { -JS_PUBLIC_API(void) -RegisterWeakCache(JS::Zone* zone, JS::WeakCache* cachep); -} // namespace shadow - -// A WeakCache stores the given Sweepable container and links itself into a -// list of such caches that are swept during each GC. -template -class WeakCache : public js::WeakCacheBase, - private mozilla::LinkedListElement> -{ - friend class mozilla::LinkedListElement>; - friend class mozilla::LinkedList>; - - WeakCache() = delete; - WeakCache(const WeakCache&) = delete; - - using SweepFn = void (*)(T*); - SweepFn sweeper; - T cache; - - public: - using Type = T; - - template - WeakCache(Zone* zone, U&& initial) - : cache(mozilla::Forward(initial)) - { - sweeper = GCPolicy::sweep; - shadow::RegisterWeakCache(zone, reinterpret_cast*>(this)); - } - WeakCache(WeakCache&& other) - : sweeper(other.sweeper), - cache(mozilla::Move(other.cache)) - { - } - - const T& get() const { return cache; } - T& get() { return cache; } - - void sweep() { sweeper(&cache); } -}; - -} // namespace JS - -#endif // js_SweepingAPI_h diff --git a/win32/include/spidermonkey/js/TraceKind.h b/win32/include/spidermonkey/js/TraceKind.h deleted file mode 100755 index 2eda9cb2..00000000 --- a/win32/include/spidermonkey/js/TraceKind.h +++ /dev/null @@ -1,212 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_TraceKind_h -#define js_TraceKind_h - -#include "mozilla/UniquePtr.h" - -#include "js/TypeDecls.h" - -// Forward declarations of all the types a TraceKind can denote. -namespace js { -class BaseShape; -class LazyScript; -class ObjectGroup; -class Shape; -class Scope; -namespace jit { -class JitCode; -} // namespace jit -} // namespace js - -namespace JS { - -// When tracing a thing, the GC needs to know about the layout of the object it -// is looking at. There are a fixed number of different layouts that the GC -// knows about. The "trace kind" is a static map which tells which layout a GC -// thing has. -// -// Although this map is public, the details are completely hidden. Not all of -// the matching C++ types are exposed, and those that are, are opaque. -// -// See Value::gcKind() and JSTraceCallback in Tracer.h for more details. -enum class TraceKind -{ - // These trace kinds have a publicly exposed, although opaque, C++ type. - // Note: The order here is determined by our Value packing. Other users - // should sort alphabetically, for consistency. - Object = 0x00, - String = 0x01, - Symbol = 0x02, - Script = 0x03, - - // Shape details are exposed through JS_TraceShapeCycleCollectorChildren. - Shape = 0x04, - - // ObjectGroup details are exposed through JS_TraceObjectGroupCycleCollectorChildren. - ObjectGroup = 0x05, - - // The kind associated with a nullptr. - Null = 0x06, - - // The following kinds do not have an exposed C++ idiom. - BaseShape = 0x0F, - JitCode = 0x1F, - LazyScript = 0x2F, - Scope = 0x3F -}; -const static uintptr_t OutOfLineTraceKindMask = 0x07; -static_assert(uintptr_t(JS::TraceKind::BaseShape) & OutOfLineTraceKindMask, "mask bits are set"); -static_assert(uintptr_t(JS::TraceKind::JitCode) & OutOfLineTraceKindMask, "mask bits are set"); -static_assert(uintptr_t(JS::TraceKind::LazyScript) & OutOfLineTraceKindMask, "mask bits are set"); -static_assert(uintptr_t(JS::TraceKind::Scope) & OutOfLineTraceKindMask, "mask bits are set"); - -// When this header is imported inside SpiderMonkey, the class definitions are -// available and we can query those definitions to find the correct kind -// directly from the class hierarchy. -template -struct MapTypeToTraceKind { - static const JS::TraceKind kind = T::TraceKind; -}; - -// When this header is used outside SpiderMonkey, the class definitions are not -// available, so the following table containing all public GC types is used. -#define JS_FOR_EACH_TRACEKIND(D) \ - /* PrettyName TypeName AddToCCKind */ \ - D(BaseShape, js::BaseShape, true) \ - D(JitCode, js::jit::JitCode, true) \ - D(LazyScript, js::LazyScript, true) \ - D(Scope, js::Scope, true) \ - D(Object, JSObject, true) \ - D(ObjectGroup, js::ObjectGroup, true) \ - D(Script, JSScript, true) \ - D(Shape, js::Shape, true) \ - D(String, JSString, false) \ - D(Symbol, JS::Symbol, false) - -// Map from all public types to their trace kind. -#define JS_EXPAND_DEF(name, type, _) \ - template <> struct MapTypeToTraceKind { \ - static const JS::TraceKind kind = JS::TraceKind::name; \ - }; -JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - -// RootKind is closely related to TraceKind. Whereas TraceKind's indices are -// laid out for convenient embedding as a pointer tag, the indicies of RootKind -// are designed for use as array keys via EnumeratedArray. -enum class RootKind : int8_t -{ - // These map 1:1 with trace kinds. -#define EXPAND_ROOT_KIND(name, _0, _1) \ - name, -JS_FOR_EACH_TRACEKIND(EXPAND_ROOT_KIND) -#undef EXPAND_ROOT_KIND - - // These tagged pointers are special-cased for performance. - Id, - Value, - - // Everything else. - Traceable, - - Limit -}; - -// Most RootKind correspond directly to a trace kind. -template struct MapTraceKindToRootKind {}; -#define JS_EXPAND_DEF(name, _0, _1) \ - template <> struct MapTraceKindToRootKind { \ - static const JS::RootKind kind = JS::RootKind::name; \ - }; -JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF) -#undef JS_EXPAND_DEF - -// Specify the RootKind for all types. Value and jsid map to special cases; -// pointer types we can derive directly from the TraceKind; everything else -// should go in the Traceable list and use GCPolicy::trace for tracing. -template -struct MapTypeToRootKind { - static const JS::RootKind kind = JS::RootKind::Traceable; -}; -template -struct MapTypeToRootKind { - static const JS::RootKind kind = - JS::MapTraceKindToRootKind::kind>::kind; -}; -template -struct MapTypeToRootKind> { - static const JS::RootKind kind = JS::MapTypeToRootKind::kind; -}; -template <> struct MapTypeToRootKind { - static const JS::RootKind kind = JS::RootKind::Value; -}; -template <> struct MapTypeToRootKind { - static const JS::RootKind kind = JS::RootKind::Id; -}; -template <> struct MapTypeToRootKind : public MapTypeToRootKind {}; - -// Fortunately, few places in the system need to deal with fully abstract -// cells. In those places that do, we generally want to move to a layout -// templated function as soon as possible. This template wraps the upcast -// for that dispatch. -// -// Given a call: -// -// DispatchTraceKindTyped(f, thing, traceKind, ... args) -// -// Downcast the |void *thing| to the specific type designated by |traceKind|, -// and pass it to the functor |f| along with |... args|, forwarded. Pass the -// type designated by |traceKind| as the functor's template argument. The -// |thing| parameter is optional; without it, we simply pass through |... args|. - -// GCC and Clang require an explicit template declaration in front of the -// specialization of operator() because it is a dependent template. MSVC, on -// the other hand, gets very confused if we have a |template| token there. -// The clang-cl front end defines _MSC_VER, but still requires the explicit -// template declaration, so we must test for __clang__ here as well. -#if defined(_MSC_VER) && !defined(__clang__) -# define JS_DEPENDENT_TEMPLATE_HINT -#else -# define JS_DEPENDENT_TEMPLATE_HINT template -#endif -template -auto -DispatchTraceKindTyped(F f, JS::TraceKind traceKind, Args&&... args) - -> decltype(f. JS_DEPENDENT_TEMPLATE_HINT operator()(mozilla::Forward(args)...)) -{ - switch (traceKind) { -#define JS_EXPAND_DEF(name, type, _) \ - case JS::TraceKind::name: \ - return f. JS_DEPENDENT_TEMPLATE_HINT operator()(mozilla::Forward(args)...); - JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - default: - MOZ_CRASH("Invalid trace kind in DispatchTraceKindTyped."); - } -} -#undef JS_DEPENDENT_TEMPLATE_HINT - -template -auto -DispatchTraceKindTyped(F f, void* thing, JS::TraceKind traceKind, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - switch (traceKind) { -#define JS_EXPAND_DEF(name, type, _) \ - case JS::TraceKind::name: \ - return f(static_cast(thing), mozilla::Forward(args)...); - JS_FOR_EACH_TRACEKIND(JS_EXPAND_DEF); -#undef JS_EXPAND_DEF - default: - MOZ_CRASH("Invalid trace kind in DispatchTraceKindTyped."); - } -} - -} // namespace JS - -#endif // js_TraceKind_h diff --git a/win32/include/spidermonkey/js/TracingAPI.h b/win32/include/spidermonkey/js/TracingAPI.h deleted file mode 100755 index 37c69aca..00000000 --- a/win32/include/spidermonkey/js/TracingAPI.h +++ /dev/null @@ -1,403 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_TracingAPI_h -#define js_TracingAPI_h - -#include "jsalloc.h" - -#include "js/HashTable.h" -#include "js/HeapAPI.h" -#include "js/TraceKind.h" - -class JS_PUBLIC_API(JSTracer); - -namespace JS { -class JS_PUBLIC_API(CallbackTracer); -template class Heap; -template class TenuredHeap; - -/** Returns a static string equivalent of |kind|. */ -JS_FRIEND_API(const char*) -GCTraceKindToAscii(JS::TraceKind kind); - -} // namespace JS - -enum WeakMapTraceKind { - /** - * Do not trace into weak map keys or values during traversal. Users must - * handle weak maps manually. - */ - DoNotTraceWeakMaps, - - /** - * Do true ephemeron marking with a weak key lookup marking phase. This is - * the default for GCMarker. - */ - ExpandWeakMaps, - - /** - * Trace through to all values, irrespective of whether the keys are live - * or not. Used for non-marking tracers. - */ - TraceWeakMapValues, - - /** - * Trace through to all keys and values, irrespective of whether the keys - * are live or not. Used for non-marking tracers. - */ - TraceWeakMapKeysValues -}; - -class JS_PUBLIC_API(JSTracer) -{ - public: - // Return the runtime set on the tracer. - JSRuntime* runtime() const { return runtime_; } - - // Return the weak map tracing behavior currently set on this tracer. - WeakMapTraceKind weakMapAction() const { return weakMapAction_; } - - enum class TracerKindTag { - // Marking path: a tracer used only for marking liveness of cells, not - // for moving them. The kind will transition to WeakMarking after - // everything reachable by regular edges has been marked. - Marking, - - // Same as Marking, except we have now moved on to the "weak marking - // phase", in which every marked obj/script is immediately looked up to - // see if it is a weak map key (and therefore might require marking its - // weak map value). - WeakMarking, - - // A tracer that traverses the graph for the purposes of moving objects - // from the nursery to the tenured area. - Tenuring, - - // General-purpose traversal that invokes a callback on each cell. - // Traversing children is the responsibility of the callback. - Callback - }; - bool isMarkingTracer() const { return tag_ == TracerKindTag::Marking || tag_ == TracerKindTag::WeakMarking; } - bool isWeakMarkingTracer() const { return tag_ == TracerKindTag::WeakMarking; } - bool isTenuringTracer() const { return tag_ == TracerKindTag::Tenuring; } - bool isCallbackTracer() const { return tag_ == TracerKindTag::Callback; } - inline JS::CallbackTracer* asCallbackTracer(); -#ifdef DEBUG - bool checkEdges() { return checkEdges_; } -#endif - - protected: - JSTracer(JSRuntime* rt, TracerKindTag tag, - WeakMapTraceKind weakTraceKind = TraceWeakMapValues) - : runtime_(rt) - , weakMapAction_(weakTraceKind) -#ifdef DEBUG - , checkEdges_(true) -#endif - , tag_(tag) - {} - -#ifdef DEBUG - // Set whether to check edges are valid in debug builds. - void setCheckEdges(bool check) { - checkEdges_ = check; - } -#endif - - private: - JSRuntime* runtime_; - WeakMapTraceKind weakMapAction_; -#ifdef DEBUG - bool checkEdges_; -#endif - - protected: - TracerKindTag tag_; -}; - -namespace JS { - -class AutoTracingName; -class AutoTracingIndex; -class AutoTracingCallback; - -class JS_PUBLIC_API(CallbackTracer) : public JSTracer -{ - public: - CallbackTracer(JSRuntime* rt, WeakMapTraceKind weakTraceKind = TraceWeakMapValues) - : JSTracer(rt, JSTracer::TracerKindTag::Callback, weakTraceKind), - contextName_(nullptr), contextIndex_(InvalidIndex), contextFunctor_(nullptr) - {} - CallbackTracer(JSContext* cx, WeakMapTraceKind weakTraceKind = TraceWeakMapValues); - - // Override these methods to receive notification when an edge is visited - // with the type contained in the callback. The default implementation - // dispatches to the fully-generic onChild implementation, so for cases that - // do not care about boxing overhead and do not need the actual edges, - // just override the generic onChild. - virtual void onObjectEdge(JSObject** objp) { onChild(JS::GCCellPtr(*objp)); } - virtual void onStringEdge(JSString** strp) { onChild(JS::GCCellPtr(*strp)); } - virtual void onSymbolEdge(JS::Symbol** symp) { onChild(JS::GCCellPtr(*symp)); } - virtual void onScriptEdge(JSScript** scriptp) { onChild(JS::GCCellPtr(*scriptp)); } - virtual void onShapeEdge(js::Shape** shapep) { - onChild(JS::GCCellPtr(*shapep, JS::TraceKind::Shape)); - } - virtual void onObjectGroupEdge(js::ObjectGroup** groupp) { - onChild(JS::GCCellPtr(*groupp, JS::TraceKind::ObjectGroup)); - } - virtual void onBaseShapeEdge(js::BaseShape** basep) { - onChild(JS::GCCellPtr(*basep, JS::TraceKind::BaseShape)); - } - virtual void onJitCodeEdge(js::jit::JitCode** codep) { - onChild(JS::GCCellPtr(*codep, JS::TraceKind::JitCode)); - } - virtual void onLazyScriptEdge(js::LazyScript** lazyp) { - onChild(JS::GCCellPtr(*lazyp, JS::TraceKind::LazyScript)); - } - virtual void onScopeEdge(js::Scope** scopep) { - onChild(JS::GCCellPtr(*scopep, JS::TraceKind::Scope)); - } - - // Override this method to receive notification when a node in the GC - // heap graph is visited. - virtual void onChild(const JS::GCCellPtr& thing) = 0; - - // Access to the tracing context: - // When tracing with a JS::CallbackTracer, we invoke the callback with the - // edge location and the type of target. This is useful for operating on - // the edge in the abstract or on the target thing, satisfying most common - // use cases. However, some tracers need additional detail about the - // specific edge that is being traced in order to be useful. Unfortunately, - // the raw pointer to the edge that we provide is not enough information to - // infer much of anything useful about that edge. - // - // In order to better support use cases that care in particular about edges - // -- as opposed to the target thing -- tracing implementations are - // responsible for providing extra context information about each edge they - // trace, as it is traced. This contains, at a minimum, an edge name and, - // when tracing an array, the index. Further specialization can be achived - // (with some complexity), by associating a functor with the tracer so - // that, when requested, the user can generate totally custom edge - // descriptions. - - // Returns the current edge's name. It is only valid to call this when - // inside the trace callback, however, the edge name will always be set. - const char* contextName() const { MOZ_ASSERT(contextName_); return contextName_; } - - // Returns the current edge's index, if marked as part of an array of edges. - // This must be called only inside the trace callback. When not tracing an - // array, the value will be InvalidIndex. - const static size_t InvalidIndex = size_t(-1); - size_t contextIndex() const { return contextIndex_; } - - // Build a description of this edge in the heap graph. This call may invoke - // the context functor, if set, which may inspect arbitrary areas of the - // heap. On the other hand, the description provided by this method may be - // substantially more accurate and useful than those provided by only the - // contextName and contextIndex. - void getTracingEdgeName(char* buffer, size_t bufferSize); - - // The trace implementation may associate a callback with one or more edges - // using AutoTracingDetails. This functor is called by getTracingEdgeName - // and is responsible for providing a textual representation of the - // currently being traced edge. The callback has access to the full heap, - // including the currently set tracing context. - class ContextFunctor { - public: - virtual void operator()(CallbackTracer* trc, char* buf, size_t bufsize) = 0; - }; - -#ifdef DEBUG - enum class TracerKind { DoNotCare, Moving, GrayBuffering, VerifyTraceProtoAndIface }; - virtual TracerKind getTracerKind() const { return TracerKind::DoNotCare; } -#endif - - // In C++, overriding a method hides all methods in the base class with - // that name, not just methods with that signature. Thus, the typed edge - // methods have to have distinct names to allow us to override them - // individually, which is freqently useful if, for example, we only want to - // process only one type of edge. - void dispatchToOnEdge(JSObject** objp) { onObjectEdge(objp); } - void dispatchToOnEdge(JSString** strp) { onStringEdge(strp); } - void dispatchToOnEdge(JS::Symbol** symp) { onSymbolEdge(symp); } - void dispatchToOnEdge(JSScript** scriptp) { onScriptEdge(scriptp); } - void dispatchToOnEdge(js::Shape** shapep) { onShapeEdge(shapep); } - void dispatchToOnEdge(js::ObjectGroup** groupp) { onObjectGroupEdge(groupp); } - void dispatchToOnEdge(js::BaseShape** basep) { onBaseShapeEdge(basep); } - void dispatchToOnEdge(js::jit::JitCode** codep) { onJitCodeEdge(codep); } - void dispatchToOnEdge(js::LazyScript** lazyp) { onLazyScriptEdge(lazyp); } - void dispatchToOnEdge(js::Scope** scopep) { onScopeEdge(scopep); } - - private: - friend class AutoTracingName; - const char* contextName_; - - friend class AutoTracingIndex; - size_t contextIndex_; - - friend class AutoTracingDetails; - ContextFunctor* contextFunctor_; -}; - -// Set the name portion of the tracer's context for the current edge. -class MOZ_RAII AutoTracingName -{ - CallbackTracer* trc_; - const char* prior_; - - public: - AutoTracingName(CallbackTracer* trc, const char* name) : trc_(trc), prior_(trc->contextName_) { - MOZ_ASSERT(name); - trc->contextName_ = name; - } - ~AutoTracingName() { - MOZ_ASSERT(trc_->contextName_); - trc_->contextName_ = prior_; - } -}; - -// Set the index portion of the tracer's context for the current range. -class MOZ_RAII AutoTracingIndex -{ - CallbackTracer* trc_; - - public: - explicit AutoTracingIndex(JSTracer* trc, size_t initial = 0) : trc_(nullptr) { - if (trc->isCallbackTracer()) { - trc_ = trc->asCallbackTracer(); - MOZ_ASSERT(trc_->contextIndex_ == CallbackTracer::InvalidIndex); - trc_->contextIndex_ = initial; - } - } - ~AutoTracingIndex() { - if (trc_) { - MOZ_ASSERT(trc_->contextIndex_ != CallbackTracer::InvalidIndex); - trc_->contextIndex_ = CallbackTracer::InvalidIndex; - } - } - - void operator++() { - if (trc_) { - MOZ_ASSERT(trc_->contextIndex_ != CallbackTracer::InvalidIndex); - ++trc_->contextIndex_; - } - } -}; - -// Set a context callback for the trace callback to use, if it needs a detailed -// edge description. -class MOZ_RAII AutoTracingDetails -{ - CallbackTracer* trc_; - - public: - AutoTracingDetails(JSTracer* trc, CallbackTracer::ContextFunctor& func) : trc_(nullptr) { - if (trc->isCallbackTracer()) { - trc_ = trc->asCallbackTracer(); - MOZ_ASSERT(trc_->contextFunctor_ == nullptr); - trc_->contextFunctor_ = &func; - } - } - ~AutoTracingDetails() { - if (trc_) { - MOZ_ASSERT(trc_->contextFunctor_); - trc_->contextFunctor_ = nullptr; - } - } -}; - -} // namespace JS - -JS::CallbackTracer* -JSTracer::asCallbackTracer() -{ - MOZ_ASSERT(isCallbackTracer()); - return static_cast(this); -} - -namespace JS { - -// The JS::TraceEdge family of functions traces the given GC thing reference. -// This performs the tracing action configured on the given JSTracer: typically -// calling the JSTracer::callback or marking the thing as live. -// -// The argument to JS::TraceEdge is an in-out param: when the function returns, -// the garbage collector might have moved the GC thing. In this case, the -// reference passed to JS::TraceEdge will be updated to the thing's new -// location. Callers of this method are responsible for updating any state that -// is dependent on the object's address. For example, if the object's address -// is used as a key in a hashtable, then the object must be removed and -// re-inserted with the correct hash. -// -// Note that while |edgep| must never be null, it is fine for |*edgep| to be -// nullptr. -template -extern JS_PUBLIC_API(void) -TraceEdge(JSTracer* trc, JS::Heap* edgep, const char* name); - -extern JS_PUBLIC_API(void) -TraceEdge(JSTracer* trc, JS::TenuredHeap* edgep, const char* name); - -// Edges that are always traced as part of root marking do not require -// incremental barriers. This function allows for marking non-barriered -// pointers, but asserts that this happens during root marking. -// -// Note that while |edgep| must never be null, it is fine for |*edgep| to be -// nullptr. -template -extern JS_PUBLIC_API(void) -UnsafeTraceRoot(JSTracer* trc, T* edgep, const char* name); - -extern JS_PUBLIC_API(void) -TraceChildren(JSTracer* trc, GCCellPtr thing); - -using ZoneSet = js::HashSet, js::SystemAllocPolicy>; -using CompartmentSet = js::HashSet, - js::SystemAllocPolicy>; - -/** - * Trace every value within |compartments| that is wrapped by a - * cross-compartment wrapper from a compartment that is not an element of - * |compartments|. - */ -extern JS_PUBLIC_API(void) -TraceIncomingCCWs(JSTracer* trc, const JS::CompartmentSet& compartments); - -} // namespace JS - -extern JS_PUBLIC_API(void) -JS_GetTraceThingInfo(char* buf, size_t bufsize, JSTracer* trc, - void* thing, JS::TraceKind kind, bool includeDetails); - -namespace js { - -// Trace an edge that is not a GC root and is not wrapped in a barriered -// wrapper for some reason. -// -// This method does not check if |*edgep| is non-null before tracing through -// it, so callers must check any nullable pointer before calling this method. -template -extern JS_PUBLIC_API(void) -UnsafeTraceManuallyBarrieredEdge(JSTracer* trc, T* edgep, const char* name); - -namespace gc { - -// Return true if the given edge is not live and is about to be swept. -template -extern JS_PUBLIC_API(bool) -EdgeNeedsSweep(JS::Heap* edgep); - -// Not part of the public API, but declared here so we can use it in GCPolicy -// which is. -template -bool -IsAboutToBeFinalizedUnbarriered(T* thingp); - -} // namespace gc -} // namespace js - -#endif /* js_TracingAPI_h */ diff --git a/win32/include/spidermonkey/js/TrackedOptimizationInfo.h b/win32/include/spidermonkey/js/TrackedOptimizationInfo.h deleted file mode 100755 index b697765c..00000000 --- a/win32/include/spidermonkey/js/TrackedOptimizationInfo.h +++ /dev/null @@ -1,285 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_TrackedOptimizationInfo_h -#define js_TrackedOptimizationInfo_h - -#include "mozilla/Maybe.h" - -namespace JS { - -#define TRACKED_STRATEGY_LIST(_) \ - _(GetProp_ArgumentsLength) \ - _(GetProp_ArgumentsCallee) \ - _(GetProp_InferredConstant) \ - _(GetProp_Constant) \ - _(GetProp_NotDefined) \ - _(GetProp_StaticName) \ - _(GetProp_SimdGetter) \ - _(GetProp_TypedObject) \ - _(GetProp_DefiniteSlot) \ - _(GetProp_Unboxed) \ - _(GetProp_CommonGetter) \ - _(GetProp_InlineAccess) \ - _(GetProp_Innerize) \ - _(GetProp_InlineCache) \ - _(GetProp_SharedCache) \ - _(GetProp_ModuleNamespace) \ - \ - _(SetProp_CommonSetter) \ - _(SetProp_TypedObject) \ - _(SetProp_DefiniteSlot) \ - _(SetProp_Unboxed) \ - _(SetProp_InlineAccess) \ - _(SetProp_InlineCache) \ - \ - _(GetElem_TypedObject) \ - _(GetElem_Dense) \ - _(GetElem_TypedStatic) \ - _(GetElem_TypedArray) \ - _(GetElem_String) \ - _(GetElem_Arguments) \ - _(GetElem_ArgumentsInlined) \ - _(GetElem_InlineCache) \ - \ - _(SetElem_TypedObject) \ - _(SetElem_TypedStatic) \ - _(SetElem_TypedArray) \ - _(SetElem_Dense) \ - _(SetElem_Arguments) \ - _(SetElem_InlineCache) \ - \ - _(BinaryArith_Concat) \ - _(BinaryArith_SpecializedTypes) \ - _(BinaryArith_SpecializedOnBaselineTypes) \ - _(BinaryArith_SharedCache) \ - _(BinaryArith_Call) \ - \ - _(InlineCache_OptimizedStub) \ - \ - _(Call_Inline) - - -// Ordering is important below. All outcomes before GenericSuccess will be -// considered failures, and all outcomes after GenericSuccess will be -// considered successes. -#define TRACKED_OUTCOME_LIST(_) \ - _(GenericFailure) \ - _(Disabled) \ - _(NoTypeInfo) \ - _(NoAnalysisInfo) \ - _(NoShapeInfo) \ - _(UnknownObject) \ - _(UnknownProperties) \ - _(Singleton) \ - _(NotSingleton) \ - _(NotFixedSlot) \ - _(InconsistentFixedSlot) \ - _(NotObject) \ - _(NotStruct) \ - _(NotUnboxed) \ - _(NotUndefined) \ - _(UnboxedConvertedToNative) \ - _(StructNoField) \ - _(InconsistentFieldType) \ - _(InconsistentFieldOffset) \ - _(NeedsTypeBarrier) \ - _(InDictionaryMode) \ - _(NoProtoFound) \ - _(MultiProtoPaths) \ - _(NonWritableProperty) \ - _(ProtoIndexedProps) \ - _(ArrayBadFlags) \ - _(ArrayDoubleConversion) \ - _(ArrayRange) \ - _(ArraySeenNegativeIndex) \ - _(TypedObjectHasDetachedBuffer) \ - _(TypedObjectArrayRange) \ - _(AccessNotDense) \ - _(AccessNotSimdObject) \ - _(AccessNotTypedObject) \ - _(AccessNotTypedArray) \ - _(AccessNotString) \ - _(OperandNotString) \ - _(OperandNotNumber) \ - _(OperandNotStringOrNumber) \ - _(OperandNotSimpleArith) \ - _(StaticTypedArrayUint32) \ - _(StaticTypedArrayCantComputeMask) \ - _(OutOfBounds) \ - _(GetElemStringNotCached) \ - _(NonNativeReceiver) \ - _(IndexType) \ - _(SetElemNonDenseNonTANotCached) \ - _(NoSimdJitSupport) \ - _(SimdTypeNotOptimized) \ - _(UnknownSimdProperty) \ - _(NotModuleNamespace) \ - _(UnknownProperty) \ - \ - _(ICOptStub_GenericSuccess) \ - \ - _(ICGetPropStub_ReadSlot) \ - _(ICGetPropStub_CallGetter) \ - _(ICGetPropStub_ArrayLength) \ - _(ICGetPropStub_UnboxedRead) \ - _(ICGetPropStub_UnboxedReadExpando) \ - _(ICGetPropStub_UnboxedArrayLength) \ - _(ICGetPropStub_TypedArrayLength) \ - _(ICGetPropStub_DOMProxyShadowed) \ - _(ICGetPropStub_DOMProxyUnshadowed) \ - _(ICGetPropStub_GenericProxy) \ - _(ICGetPropStub_ArgumentsLength) \ - \ - _(ICSetPropStub_Slot) \ - _(ICSetPropStub_GenericProxy) \ - _(ICSetPropStub_DOMProxyShadowed) \ - _(ICSetPropStub_DOMProxyUnshadowed) \ - _(ICSetPropStub_CallSetter) \ - _(ICSetPropStub_AddSlot) \ - _(ICSetPropStub_SetUnboxed) \ - \ - _(ICGetElemStub_ReadSlot) \ - _(ICGetElemStub_CallGetter) \ - _(ICGetElemStub_ReadUnboxed) \ - _(ICGetElemStub_Dense) \ - _(ICGetElemStub_DenseHole) \ - _(ICGetElemStub_TypedArray) \ - _(ICGetElemStub_ArgsElementMapped) \ - _(ICGetElemStub_ArgsElementUnmapped) \ - \ - _(ICSetElemStub_Dense) \ - _(ICSetElemStub_TypedArray) \ - \ - _(ICNameStub_ReadSlot) \ - _(ICNameStub_CallGetter) \ - _(ICNameStub_TypeOfNoProperty) \ - \ - _(CantInlineGeneric) \ - _(CantInlineNoTarget) \ - _(CantInlineNotInterpreted) \ - _(CantInlineNoBaseline) \ - _(CantInlineLazy) \ - _(CantInlineNotConstructor) \ - _(CantInlineClassConstructor) \ - _(CantInlineDisabledIon) \ - _(CantInlineTooManyArgs) \ - _(CantInlineNeedsArgsObj) \ - _(CantInlineDebuggee) \ - _(CantInlineUnknownProps) \ - _(CantInlineExceededDepth) \ - _(CantInlineExceededTotalBytecodeLength) \ - _(CantInlineBigCaller) \ - _(CantInlineBigCallee) \ - _(CantInlineBigCalleeInlinedBytecodeLength) \ - _(CantInlineNotHot) \ - _(CantInlineNotInDispatch) \ - _(CantInlineUnreachable) \ - _(CantInlineNativeBadForm) \ - _(CantInlineNativeBadType) \ - _(CantInlineNativeNoTemplateObj) \ - _(CantInlineBound) \ - _(CantInlineNativeNoSpecialization) \ - _(HasCommonInliningPath) \ - \ - _(GenericSuccess) \ - _(Inlined) \ - _(DOM) \ - _(Monomorphic) \ - _(Polymorphic) - -#define TRACKED_TYPESITE_LIST(_) \ - _(Receiver) \ - _(Operand) \ - _(Index) \ - _(Value) \ - _(Call_Target) \ - _(Call_This) \ - _(Call_Arg) \ - _(Call_Return) - -enum class TrackedStrategy : uint32_t { -#define STRATEGY_OP(name) name, - TRACKED_STRATEGY_LIST(STRATEGY_OP) -#undef STRATEGY_OPT - - Count -}; - -enum class TrackedOutcome : uint32_t { -#define OUTCOME_OP(name) name, - TRACKED_OUTCOME_LIST(OUTCOME_OP) -#undef OUTCOME_OP - - Count -}; - -enum class TrackedTypeSite : uint32_t { -#define TYPESITE_OP(name) name, - TRACKED_TYPESITE_LIST(TYPESITE_OP) -#undef TYPESITE_OP - - Count -}; - -JS_PUBLIC_API(const char*) -TrackedStrategyString(TrackedStrategy strategy); - -JS_PUBLIC_API(const char*) -TrackedOutcomeString(TrackedOutcome outcome); - -JS_PUBLIC_API(const char*) -TrackedTypeSiteString(TrackedTypeSite site); - -struct ForEachTrackedOptimizationAttemptOp -{ - virtual void operator()(TrackedStrategy strategy, TrackedOutcome outcome) = 0; -}; - -struct ForEachTrackedOptimizationTypeInfoOp -{ - // Called 0+ times per entry, once for each type in the type set that Ion - // saw during MIR construction. readType is always called _before_ - // operator() on the same entry. - // - // The keyedBy parameter describes how the type is keyed: - // - "primitive" for primitive types - // - "constructor" for object types tied to a scripted constructor - // function. - // - "alloc site" for object types tied to an allocation site. - // - "prototype" for object types tied neither to a constructor nor - // to an allocation site, but to a prototype. - // - "singleton" for object types which only has a single value. - // - "function" for object types referring to scripted functions. - // - "native" for object types referring to native functions. - // - // The name parameter is the string representation of the type. If the - // type is keyed by "constructor", or if the type itself refers to a - // scripted function, the name is the function's displayAtom. If the type - // is keyed by "native", this is nullptr. - // - // The location parameter is the filename if the type is keyed by - // "constructor", "alloc site", or if the type itself refers to a scripted - // function. If the type is keyed by "native", it is the offset of the - // native function, suitable for use with addr2line on Linux or atos on OS - // X. Otherwise it is nullptr. - // - // The lineno parameter is the line number if the type is keyed by - // "constructor", "alloc site", or if the type itself refers to a scripted - // function. Otherwise it is Nothing(). - // - // The location parameter is the only one that may need escaping if being - // quoted. - virtual void readType(const char* keyedBy, const char* name, - const char* location, mozilla::Maybe lineno) = 0; - - // Called once per entry. - virtual void operator()(TrackedTypeSite site, const char* mirType) = 0; -}; - -} // namespace JS - -#endif // js_TrackedOptimizationInfo_h diff --git a/win32/include/spidermonkey/js/TypeDecls.h b/win32/include/spidermonkey/js/TypeDecls.h deleted file mode 100755 index acb93f97..00000000 --- a/win32/include/spidermonkey/js/TypeDecls.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// This file contains public type declarations that are used *frequently*. If -// it doesn't occur at least 10 times in Gecko, it probably shouldn't be in -// here. -// -// It includes only: -// - forward declarations of structs and classes; -// - typedefs; -// - enums (maybe). -// It does *not* contain any struct or class definitions. - -#ifndef js_TypeDecls_h -#define js_TypeDecls_h - -#include -#include - -#include "js-config.h" - -struct JSContext; -class JSFunction; -class JSObject; -class JSScript; -class JSString; -class JSAddonId; - -struct jsid; - -namespace JS { - -typedef unsigned char Latin1Char; - -class Symbol; -class Value; -template class Handle; -template class MutableHandle; -template class Rooted; -template class PersistentRooted; - -typedef Handle HandleFunction; -typedef Handle HandleId; -typedef Handle HandleObject; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleSymbol; -typedef Handle HandleValue; - -typedef MutableHandle MutableHandleFunction; -typedef MutableHandle MutableHandleId; -typedef MutableHandle MutableHandleObject; -typedef MutableHandle MutableHandleScript; -typedef MutableHandle MutableHandleString; -typedef MutableHandle MutableHandleSymbol; -typedef MutableHandle MutableHandleValue; - -typedef Rooted RootedObject; -typedef Rooted RootedFunction; -typedef Rooted RootedScript; -typedef Rooted RootedString; -typedef Rooted RootedSymbol; -typedef Rooted RootedId; -typedef Rooted RootedValue; - -typedef PersistentRooted PersistentRootedFunction; -typedef PersistentRooted PersistentRootedId; -typedef PersistentRooted PersistentRootedObject; -typedef PersistentRooted PersistentRootedScript; -typedef PersistentRooted PersistentRootedString; -typedef PersistentRooted PersistentRootedSymbol; -typedef PersistentRooted PersistentRootedValue; - -} // namespace JS - -#endif /* js_TypeDecls_h */ diff --git a/win32/include/spidermonkey/js/UbiNode.h b/win32/include/spidermonkey/js/UbiNode.h deleted file mode 100755 index c8742f33..00000000 --- a/win32/include/spidermonkey/js/UbiNode.h +++ /dev/null @@ -1,1144 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNode_h -#define js_UbiNode_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Maybe.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/RangedPtr.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Variant.h" - -#include "jspubtd.h" - -#include "js/GCAPI.h" -#include "js/HashTable.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" -#include "js/TypeDecls.h" -#include "js/UniquePtr.h" -#include "js/Value.h" -#include "js/Vector.h" - -// JS::ubi::Node -// -// JS::ubi::Node is a pointer-like type designed for internal use by heap -// analysis tools. A ubi::Node can refer to: -// -// - a JS value, like a string, object, or symbol; -// - an internal SpiderMonkey structure, like a shape or a scope chain object -// - an instance of some embedding-provided type: in Firefox, an XPCOM -// object, or an internal DOM node class instance -// -// A ubi::Node instance provides metadata about its referent, and can -// enumerate its referent's outgoing edges, so you can implement heap analysis -// algorithms that walk the graph - finding paths between objects, or -// computing heap dominator trees, say - using ubi::Node, while remaining -// ignorant of the details of the types you're operating on. -// -// Of course, when it comes to presenting the results in a developer-facing -// tool, you'll need to stop being ignorant of those details, because you have -// to discuss the ubi::Nodes' referents with the developer. Here, ubi::Node -// can hand you dynamically checked, properly typed pointers to the original -// objects via the as method, or generate descriptions of the referent -// itself. -// -// ubi::Node instances are lightweight (two-word) value types. Instances: -// - compare equal if and only if they refer to the same object; -// - have hash values that respect their equality relation; and -// - have serializations that are only equal if the ubi::Nodes are equal. -// -// A ubi::Node is only valid for as long as its referent is alive; if its -// referent goes away, the ubi::Node becomes a dangling pointer. A ubi::Node -// that refers to a GC-managed object is not automatically a GC root; if the -// GC frees or relocates its referent, the ubi::Node becomes invalid. A -// ubi::Node that refers to a reference-counted object does not bump the -// reference count. -// -// ubi::Node values require no supporting data structures, making them -// feasible for use in memory-constrained devices --- ideally, the memory -// requirements of the algorithm which uses them will be the limiting factor, -// not the demands of ubi::Node itself. -// -// One can construct a ubi::Node value given a pointer to a type that ubi::Node -// supports. In the other direction, one can convert a ubi::Node back to a -// pointer; these downcasts are checked dynamically. In particular, one can -// convert a 'JSContext*' to a ubi::Node, yielding a node with an outgoing edge -// for every root registered with the runtime; starting from this, one can walk -// the entire heap. (Of course, one could also start traversal at any other kind -// of type to which one has a pointer.) -// -// -// Extending ubi::Node To Handle Your Embedding's Types -// -// To add support for a new ubi::Node referent type R, you must define a -// specialization of the ubi::Concrete template, ubi::Concrete, which -// inherits from ubi::Base. ubi::Node itself uses the specialization for -// compile-time information (i.e. the checked conversions between R * and -// ubi::Node), and the inheritance for run-time dispatching. -// -// -// ubi::Node Exposes Implementation Details -// -// In many cases, a JavaScript developer's view of their data differs -// substantially from its actual implementation. For example, while the -// ECMAScript specification describes objects as maps from property names to -// sets of attributes (like ECMAScript's [[Value]]), in practice many objects -// have only a pointer to a shape, shared with other similar objects, and -// indexed slots that contain the [[Value]] attributes. As another example, a -// string produced by concatenating two other strings may sometimes be -// represented by a "rope", a structure that points to the two original -// strings. -// -// We intend to use ubi::Node to write tools that report memory usage, so it's -// important that ubi::Node accurately portray how much memory nodes consume. -// Thus, for example, when data that apparently belongs to multiple nodes is -// in fact shared in a common structure, ubi::Node's graph uses a separate -// node for that shared structure, and presents edges to it from the data's -// apparent owners. For example, ubi::Node exposes SpiderMonkey objects' -// shapes and base shapes, and exposes rope string and substring structure, -// because these optimizations become visible when a tool reports how much -// memory a structure consumes. -// -// However, fine granularity is not a goal. When a particular object is the -// exclusive owner of a separate block of memory, ubi::Node may present the -// object and its block as a single node, and add their sizes together when -// reporting the node's size, as there is no meaningful loss of data in this -// case. Thus, for example, a ubi::Node referring to a JavaScript object, when -// asked for the object's size in bytes, includes the object's slot and -// element arrays' sizes in the total. There is no separate ubi::Node value -// representing the slot and element arrays, since they are owned exclusively -// by the object. -// -// -// Presenting Analysis Results To JavaScript Developers -// -// If an analysis provides its results in terms of ubi::Node values, a user -// interface presenting those results will generally need to clean them up -// before they can be understood by JavaScript developers. For example, -// JavaScript developers should not need to understand shapes, only JavaScript -// objects. Similarly, they should not need to understand the distinction -// between DOM nodes and the JavaScript shadow objects that represent them. -// -// -// Rooting Restrictions -// -// At present there is no way to root ubi::Node instances, so instances can't be -// live across any operation that might GC. Analyses using ubi::Node must either -// run to completion and convert their results to some other rootable type, or -// save their intermediate state in some rooted structure if they must GC before -// they complete. (For algorithms like path-finding and dominator tree -// computation, we implement the algorithm avoiding any operation that could -// cause a GC --- and use AutoCheckCannotGC to verify this.) -// -// If this restriction prevents us from implementing interesting tools, we may -// teach the GC how to root ubi::Nodes, fix up hash tables that use them as -// keys, etc. -// -// -// Hostile Graph Structure -// -// Analyses consuming ubi::Node graphs must be robust when presented with graphs -// that are deliberately constructed to exploit their weaknesses. When operating -// on live graphs, web content has control over the object graph, and less -// direct control over shape and string structure, and analyses should be -// prepared to handle extreme cases gracefully. For example, if an analysis were -// to use the C++ stack in a depth-first traversal, carefully constructed -// content could cause the analysis to overflow the stack. -// -// When ubi::Nodes refer to nodes deserialized from a heap snapshot, analyses -// must be even more careful: since snapshots often come from potentially -// compromised e10s content processes, even properties normally guaranteed by -// the platform (the proper linking of DOM nodes, for example) might be -// corrupted. While it is the deserializer's responsibility to check the basic -// structure of the snapshot file, the analyses should be prepared for ubi::Node -// graphs constructed from snapshots to be even more bizarre. - -class JSAtom; - -namespace JS { -namespace ubi { - -class Edge; -class EdgeRange; -class StackFrame; - -} // namespace ubi -} // namespace JS - -namespace JS { -namespace ubi { - -using mozilla::Forward; -using mozilla::Maybe; -using mozilla::Move; -using mozilla::RangedPtr; -using mozilla::Variant; - -template -using Vector = mozilla::Vector; - -/*** ubi::StackFrame ******************************************************************************/ - -// Concrete JS::ubi::StackFrame instances backed by a live SavedFrame object -// store their strings as JSAtom*, while deserialized stack frames from offline -// heap snapshots store their strings as const char16_t*. In order to provide -// zero-cost accessors to these strings in a single interface that works with -// both cases, we use this variant type. -class AtomOrTwoByteChars : public Variant { - using Base = Variant; - - public: - template - MOZ_IMPLICIT AtomOrTwoByteChars(T&& rhs) : Base(Forward(rhs)) { } - - template - AtomOrTwoByteChars& operator=(T&& rhs) { - MOZ_ASSERT(this != &rhs, "self-move disallowed"); - this->~AtomOrTwoByteChars(); - new (this) AtomOrTwoByteChars(Forward(rhs)); - return *this; - } - - // Return the length of the given AtomOrTwoByteChars string. - size_t length(); - - // Copy the given AtomOrTwoByteChars string into the destination buffer, - // inflating if necessary. Does NOT null terminate. Returns the number of - // characters written to destination. - size_t copyToBuffer(RangedPtr destination, size_t length); -}; - -// The base class implemented by each ConcreteStackFrame type. Subclasses -// must not add data members to this class. -class BaseStackFrame { - friend class StackFrame; - - BaseStackFrame(const StackFrame&) = delete; - BaseStackFrame& operator=(const StackFrame&) = delete; - - protected: - void* ptr; - explicit BaseStackFrame(void* ptr) : ptr(ptr) { } - - public: - // This is a value type that should not have a virtual destructor. Don't add - // destructors in subclasses! - - // Get a unique identifier for this StackFrame. The identifier is not valid - // across garbage collections. - virtual uint64_t identifier() const { return uint64_t(uintptr_t(ptr)); } - - // Get this frame's parent frame. - virtual StackFrame parent() const = 0; - - // Get this frame's line number. - virtual uint32_t line() const = 0; - - // Get this frame's column number. - virtual uint32_t column() const = 0; - - // Get this frame's source name. Never null. - virtual AtomOrTwoByteChars source() const = 0; - - // Return this frame's function name if named, otherwise the inferred - // display name. Can be null. - virtual AtomOrTwoByteChars functionDisplayName() const = 0; - - // Returns true if this frame's function is system JavaScript running with - // trusted principals, false otherwise. - virtual bool isSystem() const = 0; - - // Return true if this frame's function is a self-hosted JavaScript builtin, - // false otherwise. - virtual bool isSelfHosted(JSContext* cx) const = 0; - - // Construct a SavedFrame stack for the stack starting with this frame and - // containing all of its parents. The SavedFrame objects will be placed into - // cx's current compartment. - // - // Note that the process of - // - // SavedFrame - // | - // V - // JS::ubi::StackFrame - // | - // V - // offline heap snapshot - // | - // V - // JS::ubi::StackFrame - // | - // V - // SavedFrame - // - // is lossy because we cannot serialize and deserialize the SavedFrame's - // principals in the offline heap snapshot, so JS::ubi::StackFrame - // simplifies the principals check into the boolean isSystem() state. This - // is fine because we only expose JS::ubi::Stack to devtools and chrome - // code, and not to the web platform. - virtual MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx, - MutableHandleObject outSavedFrameStack) - const = 0; - - // Trace the concrete implementation of JS::ubi::StackFrame. - virtual void trace(JSTracer* trc) = 0; -}; - -// A traits template with a specialization for each backing type that implements -// the ubi::BaseStackFrame interface. Each specialization must be the a subclass -// of ubi::BaseStackFrame. -template class ConcreteStackFrame; - -// A JS::ubi::StackFrame represents a frame in a recorded stack. It can be -// backed either by a live SavedFrame object or by a structure deserialized from -// an offline heap snapshot. -// -// It is a value type that may be memcpy'd hither and thither without worrying -// about constructors or destructors, similar to POD types. -// -// Its lifetime is the same as the lifetime of the graph that is being analyzed -// by the JS::ubi::Node that the JS::ubi::StackFrame came from. That is, if the -// graph being analyzed is the live heap graph, the JS::ubi::StackFrame is only -// valid within the scope of an AutoCheckCannotGC; if the graph being analyzed -// is an offline heap snapshot, the JS::ubi::StackFrame is valid as long as the -// offline heap snapshot is alive. -class StackFrame { - // Storage in which we allocate BaseStackFrame subclasses. - mozilla::AlignedStorage2 storage; - - BaseStackFrame* base() { return storage.addr(); } - const BaseStackFrame* base() const { return storage.addr(); } - - template - void construct(T* ptr) { - static_assert(mozilla::IsBaseOf>::value, - "ConcreteStackFrame must inherit from BaseStackFrame"); - static_assert(sizeof(ConcreteStackFrame) == sizeof(*base()), - "ubi::ConcreteStackFrame specializations must be the same size as " - "ubi::BaseStackFrame"); - ConcreteStackFrame::construct(base(), ptr); - } - struct ConstructFunctor; - - public: - StackFrame() { construct(nullptr); } - - template - MOZ_IMPLICIT StackFrame(T* ptr) { - construct(ptr); - } - - template - StackFrame& operator=(T* ptr) { - construct(ptr); - return *this; - } - - // Constructors accepting SpiderMonkey's generic-pointer-ish types. - - template - explicit StackFrame(const JS::Handle& handle) { - construct(handle.get()); - } - - template - StackFrame& operator=(const JS::Handle& handle) { - construct(handle.get()); - return *this; - } - - template - explicit StackFrame(const JS::Rooted& root) { - construct(root.get()); - } - - template - StackFrame& operator=(const JS::Rooted& root) { - construct(root.get()); - return *this; - } - - // Because StackFrame is just a vtable pointer and an instance pointer, we - // can memcpy everything around instead of making concrete classes define - // virtual constructors. See the comment above Node's copy constructor for - // more details; that comment applies here as well. - StackFrame(const StackFrame& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - } - - StackFrame& operator=(const StackFrame& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - return *this; - } - - bool operator==(const StackFrame& rhs) const { return base()->ptr == rhs.base()->ptr; } - bool operator!=(const StackFrame& rhs) const { return !(*this == rhs); } - - explicit operator bool() const { - return base()->ptr != nullptr; - } - - // Copy this StackFrame's source name into the given |destination| - // buffer. Copy no more than |length| characters. The result is *not* null - // terminated. Returns how many characters were written into the buffer. - size_t source(RangedPtr destination, size_t length) const; - - // Copy this StackFrame's function display name into the given |destination| - // buffer. Copy no more than |length| characters. The result is *not* null - // terminated. Returns how many characters were written into the buffer. - size_t functionDisplayName(RangedPtr destination, size_t length) const; - - // Get the size of the respective strings. 0 is returned for null strings. - size_t sourceLength(); - size_t functionDisplayNameLength(); - - // Methods that forward to virtual calls through BaseStackFrame. - - void trace(JSTracer* trc) { base()->trace(trc); } - uint64_t identifier() const { - auto id = base()->identifier(); - MOZ_ASSERT(JS::Value::isNumberRepresentable(id)); - return id; - } - uint32_t line() const { return base()->line(); } - uint32_t column() const { return base()->column(); } - AtomOrTwoByteChars source() const { return base()->source(); } - AtomOrTwoByteChars functionDisplayName() const { return base()->functionDisplayName(); } - StackFrame parent() const { return base()->parent(); } - bool isSystem() const { return base()->isSystem(); } - bool isSelfHosted(JSContext* cx) const { return base()->isSelfHosted(cx); } - MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx, - MutableHandleObject outSavedFrameStack) const { - return base()->constructSavedFrameStack(cx, outSavedFrameStack); - } - - struct HashPolicy { - using Lookup = JS::ubi::StackFrame; - - static js::HashNumber hash(const Lookup& lookup) { - return lookup.identifier(); - } - - static bool match(const StackFrame& key, const Lookup& lookup) { - return key == lookup; - } - - static void rekey(StackFrame& k, const StackFrame& newKey) { - k = newKey; - } - }; -}; - -// The ubi::StackFrame null pointer. Any attempt to operate on a null -// ubi::StackFrame crashes. -template<> -class ConcreteStackFrame : public BaseStackFrame { - explicit ConcreteStackFrame(void* ptr) : BaseStackFrame(ptr) { } - - public: - static void construct(void* storage, void*) { new (storage) ConcreteStackFrame(nullptr); } - - uint64_t identifier() const override { return 0; } - void trace(JSTracer* trc) override { } - MOZ_MUST_USE bool constructSavedFrameStack(JSContext* cx, MutableHandleObject out) - const override - { - out.set(nullptr); - return true; - } - - uint32_t line() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - uint32_t column() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - AtomOrTwoByteChars source() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - AtomOrTwoByteChars functionDisplayName() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - StackFrame parent() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - bool isSystem() const override { MOZ_CRASH("null JS::ubi::StackFrame"); } - bool isSelfHosted(JSContext* cx) const override { MOZ_CRASH("null JS::ubi::StackFrame"); } -}; - -MOZ_MUST_USE bool ConstructSavedFrameStackSlow(JSContext* cx, JS::ubi::StackFrame& frame, - MutableHandleObject outSavedFrameStack); - - -/*** ubi::Node ************************************************************************************/ - -// A concrete node specialization can claim its referent is a member of a -// particular "coarse type" which is less specific than the actual -// implementation type but generally more palatable for web developers. For -// example, JitCode can be considered to have a coarse type of "Script". This is -// used by some analyses for putting nodes into different buckets. The default, -// if a concrete specialization does not provide its own mapping to a CoarseType -// variant, is "Other". -// -// NB: the values associated with a particular enum variant must not change or -// be reused for new variants. Doing so will cause inspecting ubi::Nodes backed -// by an offline heap snapshot from an older SpiderMonkey/Firefox version to -// break. Consider this enum append only. -enum class CoarseType: uint32_t { - Other = 0, - Object = 1, - Script = 2, - String = 3, - - FIRST = Other, - LAST = String -}; - -inline uint32_t -CoarseTypeToUint32(CoarseType type) -{ - return static_cast(type); -} - -inline bool -Uint32IsValidCoarseType(uint32_t n) -{ - auto first = static_cast(CoarseType::FIRST); - auto last = static_cast(CoarseType::LAST); - MOZ_ASSERT(first < last); - return first <= n && n <= last; -} - -inline CoarseType -Uint32ToCoarseType(uint32_t n) -{ - MOZ_ASSERT(Uint32IsValidCoarseType(n)); - return static_cast(n); -} - -// The base class implemented by each ubi::Node referent type. Subclasses must -// not add data members to this class. -class Base { - friend class Node; - - // For performance's sake, we'd prefer to avoid a virtual destructor; and - // an empty constructor seems consistent with the 'lightweight value type' - // visible behavior we're trying to achieve. But if the destructor isn't - // virtual, and a subclass overrides it, the subclass's destructor will be - // ignored. Is there a way to make the compiler catch that error? - - protected: - // Space for the actual pointer. Concrete subclasses should define a - // properly typed 'get' member function to access this. - void* ptr; - - explicit Base(void* ptr) : ptr(ptr) { } - - public: - bool operator==(const Base& rhs) const { - // Some compilers will indeed place objects of different types at - // the same address, so technically, we should include the vtable - // in this comparison. But it seems unlikely to cause problems in - // practice. - return ptr == rhs.ptr; - } - bool operator!=(const Base& rhs) const { return !(*this == rhs); } - - // An identifier for this node, guaranteed to be stable and unique for as - // long as this ubi::Node's referent is alive and at the same address. - // - // This is probably suitable for use in serializations, as it is an integral - // type. It may also help save memory when constructing HashSets of - // ubi::Nodes: since a uint64_t will always be smaller-or-equal-to the size - // of a ubi::Node, a HashSet may use less space per element - // than a HashSet. - // - // (Note that 'unique' only means 'up to equality on ubi::Node'; see the - // caveats about multiple objects allocated at the same address for - // 'ubi::Node::operator=='.) - using Id = uint64_t; - virtual Id identifier() const { return Id(uintptr_t(ptr)); } - - // Returns true if this node is pointing to something on the live heap, as - // opposed to something from a deserialized core dump. Returns false, - // otherwise. - virtual bool isLive() const { return true; }; - - // Return the coarse-grained type-of-thing that this node represents. - virtual CoarseType coarseType() const { return CoarseType::Other; } - - // Return a human-readable name for the referent's type. The result should - // be statically allocated. (You can use u"strings" for this.) - // - // This must always return Concrete::concreteTypeName; we use that - // pointer as a tag for this particular referent type. - virtual const char16_t* typeName() const = 0; - - // Return the size of this node, in bytes. Include any structures that this - // node owns exclusively that are not exposed as their own ubi::Nodes. - // |mallocSizeOf| should be a malloc block sizing function; see - // |mfbt/MemoryReporting.h|. - // - // Because we can use |JS::ubi::Node|s backed by a snapshot that was taken - // on a 64-bit platform when we are currently on a 32-bit platform, we - // cannot rely on |size_t| for node sizes. Instead, |Size| is uint64_t on - // all platforms. - using Size = uint64_t; - virtual Size size(mozilla::MallocSizeOf mallocSizeof) const { return 1; } - - // Return an EdgeRange that initially contains all the referent's outgoing - // edges. The caller takes ownership of the EdgeRange. - // - // If wantNames is true, compute names for edges. Doing so can be expensive - // in time and memory. - virtual js::UniquePtr edges(JSContext* cx, bool wantNames) const = 0; - - // Return the Zone to which this node's referent belongs, or nullptr if the - // referent is not of a type allocated in SpiderMonkey Zones. - virtual JS::Zone* zone() const { return nullptr; } - - // Return the compartment for this node. Some ubi::Node referents are not - // associated with JSCompartments, such as JSStrings (which are associated - // with Zones). When the referent is not associated with a compartment, - // nullptr is returned. - virtual JSCompartment* compartment() const { return nullptr; } - - // Return whether this node's referent's allocation stack was captured. - virtual bool hasAllocationStack() const { return false; } - - // Get the stack recorded at the time this node's referent was - // allocated. This must only be called when hasAllocationStack() is true. - virtual StackFrame allocationStack() const { - MOZ_CRASH("Concrete classes that have an allocation stack must override both " - "hasAllocationStack and allocationStack."); - } - - // Methods for JSObject Referents - // - // These methods are only semantically valid if the referent is either a - // JSObject in the live heap, or represents a previously existing JSObject - // from some deserialized heap snapshot. - - // Return the object's [[Class]]'s name. - virtual const char* jsObjectClassName() const { return nullptr; } - - // If this object was constructed with `new` and we have the data available, - // place the contructor function's display name in the out parameter. - // Otherwise, place nullptr in the out parameter. Caller maintains ownership - // of the out parameter. True is returned on success, false is returned on - // OOM. - virtual MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) - const - { - outName.reset(nullptr); - return true; - } - - // Methods for CoarseType::Script referents - - // Return the script's source's filename if available. If unavailable, - // return nullptr. - virtual const char* scriptFilename() const { return nullptr; } - - private: - Base(const Base& rhs) = delete; - Base& operator=(const Base& rhs) = delete; -}; - -// A traits template with a specialization for each referent type that -// ubi::Node supports. The specialization must be the concrete subclass of Base -// that represents a pointer to the referent type. It must include these -// members: -// -// // The specific char16_t array returned by Concrete::typeName(). -// static const char16_t concreteTypeName[]; -// -// // Construct an instance of this concrete class in |storage| referring -// // to |referent|. Implementations typically use a placement 'new'. -// // -// // In some cases, |referent| will contain dynamic type information that -// // identifies it a some more specific subclass of |Referent|. For -// // example, when |Referent| is |JSObject|, then |referent->getClass()| -// // could tell us that it's actually a JSFunction. Similarly, if -// // |Referent| is |nsISupports|, we would like a ubi::Node that knows its -// // final implementation type. -// // -// // So we delegate the actual construction to this specialization, which -// // knows Referent's details. -// static void construct(void* storage, Referent* referent); -template -class Concrete; - -// A container for a Base instance; all members simply forward to the contained -// instance. This container allows us to pass ubi::Node instances by value. -class Node { - // Storage in which we allocate Base subclasses. - mozilla::AlignedStorage2 storage; - Base* base() { return storage.addr(); } - const Base* base() const { return storage.addr(); } - - template - void construct(T* ptr) { - static_assert(sizeof(Concrete) == sizeof(*base()), - "ubi::Base specializations must be the same size as ubi::Base"); - static_assert(mozilla::IsBaseOf>::value, - "ubi::Concrete must inherit from ubi::Base"); - Concrete::construct(base(), ptr); - } - struct ConstructFunctor; - - public: - Node() { construct(nullptr); } - - template - MOZ_IMPLICIT Node(T* ptr) { - construct(ptr); - } - template - Node& operator=(T* ptr) { - construct(ptr); - return *this; - } - - // We can construct and assign from rooted forms of pointers. - template - MOZ_IMPLICIT Node(const Rooted& root) { - construct(root.get()); - } - template - Node& operator=(const Rooted& root) { - construct(root.get()); - return *this; - } - - // Constructors accepting SpiderMonkey's other generic-pointer-ish types. - // Note that we *do* want an implicit constructor here: JS::Value and - // JS::ubi::Node are both essentially tagged references to other sorts of - // objects, so letting conversions happen automatically is appropriate. - MOZ_IMPLICIT Node(JS::HandleValue value); - explicit Node(const JS::GCCellPtr& thing); - - // copy construction and copy assignment just use memcpy, since we know - // instances contain nothing but a vtable pointer and a data pointer. - // - // To be completely correct, concrete classes could provide a virtual - // 'construct' member function, which we could invoke on rhs to construct an - // instance in our storage. But this is good enough; there's no need to jump - // through vtables for copying and assignment that are just going to move - // two words around. The compiler knows how to optimize memcpy. - Node(const Node& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - } - - Node& operator=(const Node& rhs) { - memcpy(storage.u.mBytes, rhs.storage.u.mBytes, sizeof(storage.u)); - return *this; - } - - bool operator==(const Node& rhs) const { return *base() == *rhs.base(); } - bool operator!=(const Node& rhs) const { return *base() != *rhs.base(); } - - explicit operator bool() const { - return base()->ptr != nullptr; - } - - bool isLive() const { return base()->isLive(); } - - // Get the canonical type name for the given type T. - template - static const char16_t* canonicalTypeName() { return Concrete::concreteTypeName; } - - template - bool is() const { - return base()->typeName() == canonicalTypeName(); - } - - template - T* as() const { - MOZ_ASSERT(isLive()); - MOZ_ASSERT(is()); - return static_cast(base()->ptr); - } - - template - T* asOrNull() const { - MOZ_ASSERT(isLive()); - return is() ? static_cast(base()->ptr) : nullptr; - } - - // If this node refers to something that can be represented as a JavaScript - // value that is safe to expose to JavaScript code, return that value. - // Otherwise return UndefinedValue(). JSStrings, JS::Symbols, and some (but - // not all!) JSObjects can be exposed. - JS::Value exposeToJS() const; - - CoarseType coarseType() const { return base()->coarseType(); } - const char16_t* typeName() const { return base()->typeName(); } - JS::Zone* zone() const { return base()->zone(); } - JSCompartment* compartment() const { return base()->compartment(); } - const char* jsObjectClassName() const { return base()->jsObjectClassName(); } - MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) const { - return base()->jsObjectConstructorName(cx, outName); - } - - const char* scriptFilename() const { return base()->scriptFilename(); } - - using Size = Base::Size; - Size size(mozilla::MallocSizeOf mallocSizeof) const { - auto size = base()->size(mallocSizeof); - MOZ_ASSERT(size > 0, - "C++ does not have zero-sized types! Choose 1 if you just need a " - "conservative default."); - return size; - } - - js::UniquePtr edges(JSContext* cx, bool wantNames = true) const { - return base()->edges(cx, wantNames); - } - - bool hasAllocationStack() const { return base()->hasAllocationStack(); } - StackFrame allocationStack() const { - return base()->allocationStack(); - } - - using Id = Base::Id; - Id identifier() const { - auto id = base()->identifier(); - MOZ_ASSERT(JS::Value::isNumberRepresentable(id)); - return id; - } - - // A hash policy for ubi::Nodes. - // This simply uses the stock PointerHasher on the ubi::Node's pointer. - // We specialize DefaultHasher below to make this the default. - class HashPolicy { - typedef js::PointerHasher::value> PtrHash; - - public: - typedef Node Lookup; - - static js::HashNumber hash(const Lookup& l) { return PtrHash::hash(l.base()->ptr); } - static bool match(const Node& k, const Lookup& l) { return k == l; } - static void rekey(Node& k, const Node& newKey) { k = newKey; } - }; -}; - -using NodeSet = js::HashSet, js::SystemAllocPolicy>; -using NodeSetPtr = mozilla::UniquePtr>; - -/*** Edge and EdgeRange ***************************************************************************/ - -using EdgeName = UniqueTwoByteChars; - -// An outgoing edge to a referent node. -class Edge { - public: - Edge() : name(nullptr), referent() { } - - // Construct an initialized Edge, taking ownership of |name|. - Edge(char16_t* name, const Node& referent) - : name(name) - , referent(referent) - { } - - // Move construction and assignment. - Edge(Edge&& rhs) - : name(mozilla::Move(rhs.name)) - , referent(rhs.referent) - { } - - Edge& operator=(Edge&& rhs) { - MOZ_ASSERT(&rhs != this); - this->~Edge(); - new (this) Edge(mozilla::Move(rhs)); - return *this; - } - - Edge(const Edge&) = delete; - Edge& operator=(const Edge&) = delete; - - // This edge's name. This may be nullptr, if Node::edges was called with - // false as the wantNames parameter. - // - // The storage is owned by this Edge, and will be freed when this Edge is - // destructed. You may take ownership of the name by `mozilla::Move`ing it - // out of the edge; it is just a UniquePtr. - // - // (In real life we'll want a better representation for names, to avoid - // creating tons of strings when the names follow a pattern; and we'll need - // to think about lifetimes carefully to ensure traversal stays cheap.) - EdgeName name; - - // This edge's referent. - Node referent; -}; - -// EdgeRange is an abstract base class for iterating over a node's outgoing -// edges. (This is modeled after js::HashTable::Range.) -// -// Concrete instances of this class need not be as lightweight as Node itself, -// since they're usually only instantiated while iterating over a particular -// object's edges. For example, a dumb implementation for JS Cells might use -// JS::TraceChildren to to get the outgoing edges, and then store them in an -// array internal to the EdgeRange. -class EdgeRange { - protected: - // The current front edge of this range, or nullptr if this range is empty. - Edge* front_; - - EdgeRange() : front_(nullptr) { } - - public: - virtual ~EdgeRange() { } - - // True if there are no more edges in this range. - bool empty() const { return !front_; } - - // The front edge of this range. This is owned by the EdgeRange, and is - // only guaranteed to live until the next call to popFront, or until - // the EdgeRange is destructed. - const Edge& front() const { return *front_; } - Edge& front() { return *front_; } - - // Remove the front edge from this range. This should only be called if - // !empty(). - virtual void popFront() = 0; - - private: - EdgeRange(const EdgeRange&) = delete; - EdgeRange& operator=(const EdgeRange&) = delete; -}; - - -typedef mozilla::Vector EdgeVector; - -// An EdgeRange concrete class that holds a pre-existing vector of -// Edges. A PreComputedEdgeRange does not take ownership of its -// EdgeVector; it is up to the PreComputedEdgeRange's consumer to manage -// that lifetime. -class PreComputedEdgeRange : public EdgeRange { - EdgeVector& edges; - size_t i; - - void settle() { - front_ = i < edges.length() ? &edges[i] : nullptr; - } - - public: - explicit PreComputedEdgeRange(EdgeVector& edges) - : edges(edges), - i(0) - { - settle(); - } - - void popFront() override { - MOZ_ASSERT(!empty()); - i++; - settle(); - } -}; - -/*** RootList *************************************************************************************/ - -// RootList is a class that can be pointed to by a |ubi::Node|, creating a -// fictional root-of-roots which has edges to every GC root in the JS -// runtime. Having a single root |ubi::Node| is useful for algorithms written -// with the assumption that there aren't multiple roots (such as computing -// dominator trees) and you want a single point of entry. It also ensures that -// the roots themselves get visited by |ubi::BreadthFirst| (they would otherwise -// only be used as starting points). -// -// RootList::init itself causes a minor collection, but once the list of roots -// has been created, GC must not occur, as the referent ubi::Nodes are not -// stable across GC. The init calls emplace on |noGC|'s AutoCheckCannotGC, whose -// lifetime must extend at least as long as the RootList itself. -// -// Example usage: -// -// { -// mozilla::Maybe maybeNoGC; -// JS::ubi::RootList rootList(cx, maybeNoGC); -// if (!rootList.init()) -// return false; -// -// // The AutoCheckCannotGC is guaranteed to exist if init returned true. -// MOZ_ASSERT(maybeNoGC.isSome()); -// -// JS::ubi::Node root(&rootList); -// -// ... -// } -class MOZ_STACK_CLASS RootList { - Maybe& noGC; - - public: - JSContext* cx; - EdgeVector edges; - bool wantNames; - - RootList(JSContext* cx, Maybe& noGC, bool wantNames = false); - - // Find all GC roots. - MOZ_MUST_USE bool init(); - // Find only GC roots in the provided set of |JSCompartment|s. - MOZ_MUST_USE bool init(CompartmentSet& debuggees); - // Find only GC roots in the given Debugger object's set of debuggee - // compartments. - MOZ_MUST_USE bool init(HandleObject debuggees); - - // Returns true if the RootList has been initialized successfully, false - // otherwise. - bool initialized() { return noGC.isSome(); } - - // Explicitly add the given Node as a root in this RootList. If wantNames is - // true, you must pass an edgeName. The RootList does not take ownership of - // edgeName. - MOZ_MUST_USE bool addRoot(Node node, const char16_t* edgeName = nullptr); -}; - - -/*** Concrete classes for ubi::Node referent types ************************************************/ - -template<> -class Concrete : public Base { - protected: - explicit Concrete(RootList* ptr) : Base(ptr) { } - RootList& get() const { return *static_cast(ptr); } - - public: - static void construct(void* storage, RootList* ptr) { new (storage) Concrete(ptr); } - - js::UniquePtr edges(JSContext* cx, bool wantNames) const override; - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// A reusable ubi::Concrete specialization base class for types supported by -// JS::TraceChildren. -template -class TracerConcrete : public Base { - js::UniquePtr edges(JSContext* cx, bool wantNames) const override; - JS::Zone* zone() const override; - - protected: - explicit TracerConcrete(Referent* ptr) : Base(ptr) { } - Referent& get() const { return *static_cast(ptr); } -}; - -// For JS::TraceChildren-based types that have a 'compartment' method. -template -class TracerConcreteWithCompartment : public TracerConcrete { - typedef TracerConcrete TracerBase; - JSCompartment* compartment() const override; - - protected: - explicit TracerConcreteWithCompartment(Referent* ptr) : TracerBase(ptr) { } -}; - -// Define specializations for some commonly-used public JSAPI types. -// These can use the generic templates above. -template<> -class Concrete : TracerConcrete { - protected: - explicit Concrete(JS::Symbol* ptr) : TracerConcrete(ptr) { } - - public: - static void construct(void* storage, JS::Symbol* ptr) { - new (storage) Concrete(ptr); - } - - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -template<> -class Concrete : TracerConcreteWithCompartment { - protected: - explicit Concrete(JSScript *ptr) : TracerConcreteWithCompartment(ptr) { } - - public: - static void construct(void *storage, JSScript *ptr) { new (storage) Concrete(ptr); } - - CoarseType coarseType() const final { return CoarseType::Script; } - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - const char* scriptFilename() const final; - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// The JSObject specialization. -template<> -class Concrete : public TracerConcreteWithCompartment { - protected: - explicit Concrete(JSObject* ptr) : TracerConcreteWithCompartment(ptr) { } - - public: - static void construct(void* storage, JSObject* ptr) { - new (storage) Concrete(ptr); - } - - const char* jsObjectClassName() const override; - MOZ_MUST_USE bool jsObjectConstructorName(JSContext* cx, UniqueTwoByteChars& outName) - const override; - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - - bool hasAllocationStack() const override; - StackFrame allocationStack() const override; - - CoarseType coarseType() const final { return CoarseType::Object; } - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// For JSString, we extend the generic template with a 'size' implementation. -template<> -class Concrete : TracerConcrete { - protected: - explicit Concrete(JSString *ptr) : TracerConcrete(ptr) { } - - public: - static void construct(void *storage, JSString *ptr) { new (storage) Concrete(ptr); } - - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - - CoarseType coarseType() const final { return CoarseType::String; } - - const char16_t* typeName() const override { return concreteTypeName; } - static const char16_t concreteTypeName[]; -}; - -// The ubi::Node null pointer. Any attempt to operate on a null ubi::Node asserts. -template<> -class Concrete : public Base { - const char16_t* typeName() const override; - Size size(mozilla::MallocSizeOf mallocSizeOf) const override; - js::UniquePtr edges(JSContext* cx, bool wantNames) const override; - JS::Zone* zone() const override; - JSCompartment* compartment() const override; - CoarseType coarseType() const final; - - explicit Concrete(void* ptr) : Base(ptr) { } - - public: - static void construct(void* storage, void* ptr) { new (storage) Concrete(ptr); } -}; - - -} // namespace ubi -} // namespace JS - -namespace js { - -// Make ubi::Node::HashPolicy the default hash policy for ubi::Node. -template<> struct DefaultHasher : JS::ubi::Node::HashPolicy { }; -template<> struct DefaultHasher : JS::ubi::StackFrame::HashPolicy { }; - -} // namespace js - -#endif // js_UbiNode_h diff --git a/win32/include/spidermonkey/js/UbiNodeBreadthFirst.h b/win32/include/spidermonkey/js/UbiNodeBreadthFirst.h deleted file mode 100755 index 8446dbc6..00000000 --- a/win32/include/spidermonkey/js/UbiNodeBreadthFirst.h +++ /dev/null @@ -1,244 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeBreadthFirst_h -#define js_UbiNodeBreadthFirst_h - -#include "js/UbiNode.h" -#include "js/Utility.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -// A breadth-first traversal template for graphs of ubi::Nodes. -// -// No GC may occur while an instance of this template is live. -// -// The provided Handler type should have two members: -// -// typename NodeData; -// -// The value type of |BreadthFirst::visited|, the HashMap of -// ubi::Nodes that have been visited so far. Since the algorithm needs a -// hash table like this for its own use anyway, it is simple to let -// Handler store its own metadata about each node in the same table. -// -// For example, if you want to find a shortest path to each node from any -// traversal starting point, your |NodeData| type could record the first -// edge to reach each node, and the node from which it originates. Then, -// when the traversal is complete, you can walk backwards from any node -// to some starting point, and the path recorded will be a shortest path. -// -// This type must have a default constructor. If this type owns any other -// resources, move constructors and assignment operators are probably a -// good idea, too. -// -// bool operator() (BreadthFirst& traversal, -// Node origin, const Edge& edge, -// Handler::NodeData* referentData, bool first); -// -// The visitor function, called to report that we have traversed -// |edge| from |origin|. This is called once for each edge we traverse. -// As this is a breadth-first search, any prior calls to the visitor function -// were for origin nodes not further from the start nodes than |origin|. -// -// |traversal| is this traversal object, passed along for convenience. -// -// |referentData| is a pointer to the value of the entry in -// |traversal.visited| for |edge.referent|; the visitor function can -// store whatever metadata it likes about |edge.referent| there. -// -// |first| is true if this is the first time we have visited an edge -// leading to |edge.referent|. This could be stored in NodeData, but -// the algorithm knows whether it has just created the entry in -// |traversal.visited|, so it passes it along for convenience. -// -// The visitor function may call |traversal.abandonReferent()| if it -// doesn't want to traverse the outgoing edges of |edge.referent|. You can -// use this to limit the traversal to a given portion of the graph: it will -// never visit nodes reachable only through nodes that you have abandoned. -// Note that |abandonReferent| must be called the first time the given node -// is reached; that is, |first| must be true. -// -// The visitor function may call |traversal.stop()| if it doesn't want -// to visit any more nodes at all. -// -// The visitor function may consult |traversal.visited| for information -// about other nodes, but it should not add or remove entries. -// -// The visitor function should return true on success, or false if an -// error occurs. A false return value terminates the traversal -// immediately, and causes BreadthFirst::traverse to return -// false. -template -struct BreadthFirst { - - // Construct a breadth-first traversal object that reports the nodes it - // reaches to |handler|. The traversal asserts that no GC happens in its - // runtime during its lifetime. - // - // We do nothing with noGC, other than require it to exist, with a lifetime - // that encloses our own. - BreadthFirst(JSContext* cx, Handler& handler, const JS::AutoCheckCannotGC& noGC) - : wantNames(true), cx(cx), visited(), handler(handler), pending(), - traversalBegun(false), stopRequested(false), abandonRequested(false) - { } - - // Initialize this traversal object. Return false on OOM. - bool init() { return visited.init(); } - - // Add |node| as a starting point for the traversal. You may add - // as many starting points as you like. Return false on OOM. - bool addStart(Node node) { return pending.append(node); } - - // Add |node| as a starting point for the traversal (see addStart) and also - // add it to the |visited| set. Return false on OOM. - bool addStartVisited(Node node) { - typename NodeMap::AddPtr ptr = visited.lookupForAdd(node); - if (!ptr && !visited.add(ptr, node, typename Handler::NodeData())) - return false; - return addStart(node); - } - - // True if the handler wants us to compute edge names; doing so can be - // expensive in time and memory. True by default. - bool wantNames; - - // Traverse the graph in breadth-first order, starting at the given - // start nodes, applying |handler::operator()| for each edge traversed - // as described above. - // - // This should be called only once per instance of this class. - // - // Return false on OOM or error return from |handler::operator()|. - bool traverse() - { - MOZ_ASSERT(!traversalBegun); - traversalBegun = true; - - // While there are pending nodes, visit them. - while (!pending.empty()) { - Node origin = pending.front(); - pending.popFront(); - - // Get a range containing all origin's outgoing edges. - auto range = origin.edges(cx, wantNames); - if (!range) - return false; - - // Traverse each edge. - for (; !range->empty(); range->popFront()) { - MOZ_ASSERT(!stopRequested); - - Edge& edge = range->front(); - typename NodeMap::AddPtr a = visited.lookupForAdd(edge.referent); - bool first = !a; - - if (first) { - // This is the first time we've reached |edge.referent|. - // Mark it as visited. - if (!visited.add(a, edge.referent, typename Handler::NodeData())) - return false; - } - - MOZ_ASSERT(a); - - // Report this edge to the visitor function. - if (!handler(*this, origin, edge, &a->value(), first)) - return false; - - if (stopRequested) - return true; - - // Arrange to traverse this edge's referent's outgoing edges - // later --- unless |handler| asked us not to. - if (abandonRequested) { - // Skip the enqueue; reset flag for future iterations. - abandonRequested = false; - } else if (first) { - if (!pending.append(edge.referent)) - return false; - } - } - } - - return true; - } - - // Stop traversal, and return true from |traverse| without visiting any - // more nodes. Only |handler::operator()| should call this function; it - // may do so to stop the traversal early, without returning false and - // then making |traverse|'s caller disambiguate that result from a real - // error. - void stop() { stopRequested = true; } - - // Request that the current edge's referent's outgoing edges not be - // traversed. This must be called the first time that referent is reached. - // Other edges *to* that referent will still be traversed. - void abandonReferent() { abandonRequested = true; } - - // The context with which we were constructed. - JSContext* cx; - - // A map associating each node N that we have reached with a - // Handler::NodeData, for |handler|'s use. This is public, so that - // |handler| can access it to see the traversal thus far. - using NodeMap = js::HashMap, - js::SystemAllocPolicy>; - NodeMap visited; - - private: - // Our handler object. - Handler& handler; - - // A queue template. Appending and popping the front are constant time. - // Wasted space is never more than some recent actual population plus the - // current population. - template - class Queue { - js::Vector head, tail; - size_t frontIndex; - public: - Queue() : head(), tail(), frontIndex(0) { } - bool empty() { return frontIndex >= head.length(); } - T& front() { - MOZ_ASSERT(!empty()); - return head[frontIndex]; - } - void popFront() { - MOZ_ASSERT(!empty()); - frontIndex++; - if (frontIndex >= head.length()) { - head.clearAndFree(); - head.swap(tail); - frontIndex = 0; - } - } - bool append(const T& elt) { - return frontIndex == 0 ? head.append(elt) : tail.append(elt); - } - }; - - // A queue of nodes that we have reached, but whose outgoing edges we - // have not yet traversed. Nodes reachable in fewer edges are enqueued - // earlier. - Queue pending; - - // True if our traverse function has been called. - bool traversalBegun; - - // True if we've been asked to stop the traversal. - bool stopRequested; - - // True if we've been asked to abandon the current edge's referent. - bool abandonRequested; -}; - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeBreadthFirst_h diff --git a/win32/include/spidermonkey/js/UbiNodeCensus.h b/win32/include/spidermonkey/js/UbiNodeCensus.h deleted file mode 100755 index c0859ec5..00000000 --- a/win32/include/spidermonkey/js/UbiNodeCensus.h +++ /dev/null @@ -1,251 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeCensus_h -#define js_UbiNodeCensus_h - -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" - -#include - -#include "jsapi.h" - -#include "js/UbiNode.h" -#include "js/UbiNodeBreadthFirst.h" - -// A census is a ubi::Node traversal that assigns each node to one or more -// buckets, and returns a report with the size of each bucket. -// -// We summarize the results of a census with counts broken down according to -// criteria selected by the API consumer code that is requesting the census. For -// example, the following breakdown might give an interesting overview of the -// heap: -// -// - all nodes -// - objects -// - objects with a specific [[Class]] * -// - strings -// - scripts -// - all other Node types -// - nodes with a specific ubi::Node::typeName * -// -// Obviously, the parts of this tree marked with * represent many separate -// counts, depending on how many distinct [[Class]] values and ubi::Node type -// names we encounter. -// -// The supported types of breakdowns are documented in -// js/src/doc/Debugger/Debugger.Memory.md. -// -// When we parse the 'breakdown' argument to takeCensus, we build a tree of -// CountType nodes. For example, for the breakdown shown in the -// Debugger.Memory.prototype.takeCensus, documentation: -// -// { -// by: "coarseType", -// objects: { by: "objectClass" }, -// other: { by: "internalType" } -// } -// -// we would build the following tree of CountType subclasses: -// -// ByCoarseType -// objects: ByObjectClass -// each class: SimpleCount -// scripts: SimpleCount -// strings: SimpleCount -// other: ByUbinodeType -// each type: SimpleCount -// -// The interior nodes are all breakdown types that categorize nodes according to -// one characteristic or another; and the leaf nodes are all SimpleType. -// -// Each CountType has its own concrete C++ type that holds the counts it -// produces. SimpleCount::Count just holds totals. ByObjectClass::Count has a -// hash table whose keys are object class names and whose values are counts of -// some other type (in the example above, SimpleCount). -// -// To keep actual count nodes small, they have no vtable. Instead, each count -// points to its CountType, which knows how to carry out all the operations we -// need on a Count. A CountType can produce new count nodes; process nodes as we -// visit them; build a JS object reporting the results; and destruct count -// nodes. - - -namespace JS { -namespace ubi { - -struct Census; - -class CountBase; - -struct CountDeleter { - void operator()(CountBase*); -}; - -using CountBasePtr = js::UniquePtr; - -// Abstract base class for CountType nodes. -struct CountType { - explicit CountType() { } - virtual ~CountType() { } - - // Destruct a count tree node that this type instance constructed. - virtual void destructCount(CountBase& count) = 0; - - // Return a fresh node for the count tree that categorizes nodes according - // to this type. Return a nullptr on OOM. - virtual CountBasePtr makeCount() = 0; - - // Trace |count| and all its children, for garbage collection. - virtual void traceCount(CountBase& count, JSTracer* trc) = 0; - - // Implement the 'count' method for counts returned by this CountType - // instance's 'newCount' method. - virtual MOZ_MUST_USE bool count(CountBase& count, - mozilla::MallocSizeOf mallocSizeOf, - const Node& node) = 0; - - // Implement the 'report' method for counts returned by this CountType - // instance's 'newCount' method. - virtual MOZ_MUST_USE bool report(JSContext* cx, CountBase& count, - MutableHandleValue report) = 0; -}; - -using CountTypePtr = js::UniquePtr; - -// An abstract base class for count tree nodes. -class CountBase { - // In lieu of a vtable, each CountBase points to its type, which - // carries not only the implementations of the CountBase methods, but also - // additional parameters for the type's behavior, as specified in the - // breakdown argument passed to takeCensus. - CountType& type; - - protected: - ~CountBase() { } - - public: - explicit CountBase(CountType& type) - : type(type) - , total_(0) - , smallestNodeIdCounted_(SIZE_MAX) - { } - - // Categorize and count |node| as appropriate for this count's type. - MOZ_MUST_USE bool count(mozilla::MallocSizeOf mallocSizeOf, const Node& node) { - total_++; - - auto id = node.identifier(); - if (id < smallestNodeIdCounted_) { - smallestNodeIdCounted_ = id; - } - -#ifdef DEBUG - size_t oldTotal = total_; -#endif - - bool ret = type.count(*this, mallocSizeOf, node); - - MOZ_ASSERT(total_ == oldTotal, - "CountType::count should not increment total_, CountBase::count handles that"); - - return ret; - } - - // Construct a JavaScript object reporting the counts recorded in this - // count, and store it in |report|. Return true on success, or false on - // failure. - MOZ_MUST_USE bool report(JSContext* cx, MutableHandleValue report) { - return type.report(cx, *this, report); - } - - // Down-cast this CountBase to its true type, based on its 'type' member, - // and run its destructor. - void destruct() { return type.destructCount(*this); } - - // Trace this count for garbage collection. - void trace(JSTracer* trc) { type.traceCount(*this, trc); } - - size_t total_; - - // The smallest JS::ubi::Node::identifier() passed to this instance's - // count() method. This provides a stable way to sort sets. - Node::Id smallestNodeIdCounted_; -}; - -class RootedCount : JS::CustomAutoRooter { - CountBasePtr count; - - void trace(JSTracer* trc) override { count->trace(trc); } - - public: - RootedCount(JSContext* cx, CountBasePtr&& count) - : CustomAutoRooter(cx), - count(Move(count)) - { } - CountBase* operator->() const { return count.get(); } - explicit operator bool() const { return count.get(); } - operator CountBasePtr&() { return count; } -}; - -// Common data for a census traversal, shared across all CountType nodes. -struct Census { - JSContext* const cx; - // If the targetZones set is non-empty, then only consider nodes whose zone - // is an element of the set. If the targetZones set is empty, then nodes in - // all zones are considered. - JS::ZoneSet targetZones; - Zone* atomsZone; - - explicit Census(JSContext* cx) : cx(cx), atomsZone(nullptr) { } - - MOZ_MUST_USE bool init(); -}; - -// A BreadthFirst handler type that conducts a census, using a CountBase to -// categorize and count each node. -class CensusHandler { - Census& census; - CountBasePtr& rootCount; - mozilla::MallocSizeOf mallocSizeOf; - - public: - CensusHandler(Census& census, CountBasePtr& rootCount, mozilla::MallocSizeOf mallocSizeOf) - : census(census), - rootCount(rootCount), - mallocSizeOf(mallocSizeOf) - { } - - MOZ_MUST_USE bool report(JSContext* cx, MutableHandleValue report) { - return rootCount->report(cx, report); - } - - // This class needs to retain no per-node data. - class NodeData { }; - - MOZ_MUST_USE bool operator() (BreadthFirst& traversal, - Node origin, const Edge& edge, - NodeData* referentData, bool first); -}; - -using CensusTraversal = BreadthFirst; - -// Examine the census options supplied by the API consumer, and (among other -// things) use that to build a CountType tree. -MOZ_MUST_USE bool ParseCensusOptions(JSContext* cx, Census& census, HandleObject options, - CountTypePtr& outResult); - -// Parse the breakdown language (as described in -// js/src/doc/Debugger/Debugger.Memory.md) into a CountTypePtr. A null pointer -// is returned on error and is reported to the cx. -CountTypePtr ParseBreakdown(JSContext* cx, HandleValue breakdownValue); - - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeCensus_h diff --git a/win32/include/spidermonkey/js/UbiNodeDominatorTree.h b/win32/include/spidermonkey/js/UbiNodeDominatorTree.h deleted file mode 100755 index 3422b76b..00000000 --- a/win32/include/spidermonkey/js/UbiNodeDominatorTree.h +++ /dev/null @@ -1,677 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeDominatorTree_h -#define js_UbiNodeDominatorTree_h - -#include "mozilla/Attributes.h" -#include "mozilla/DebugOnly.h" -#include "mozilla/Maybe.h" -#include "mozilla/Move.h" -#include "mozilla/UniquePtr.h" - -#include "jsalloc.h" - -#include "js/UbiNode.h" -#include "js/UbiNodePostOrder.h" -#include "js/Utility.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -/** - * In a directed graph with a root node `R`, a node `A` is said to "dominate" a - * node `B` iff every path from `R` to `B` contains `A`. A node `A` is said to - * be the "immediate dominator" of a node `B` iff it dominates `B`, is not `B` - * itself, and does not dominate any other nodes which also dominate `B` in - * turn. - * - * If we take every node from a graph `G` and create a new graph `T` with edges - * to each node from its immediate dominator, then `T` is a tree (each node has - * only one immediate dominator, or none if it is the root). This tree is called - * a "dominator tree". - * - * This class represents a dominator tree constructed from a `JS::ubi::Node` - * heap graph. The domination relationship and dominator trees are useful tools - * for analyzing heap graphs because they tell you: - * - * - Exactly what could be reclaimed by the GC if some node `A` became - * unreachable: those nodes which are dominated by `A`, - * - * - The "retained size" of a node in the heap graph, in contrast to its - * "shallow size". The "shallow size" is the space taken by a node itself, - * not counting anything it references. The "retained size" of a node is its - * shallow size plus the size of all the things that would be collected if - * the original node wasn't (directly or indirectly) referencing them. In - * other words, the retained size is the shallow size of a node plus the - * shallow sizes of every other node it dominates. For example, the root - * node in a binary tree might have a small shallow size that does not take - * up much space itself, but it dominates the rest of the binary tree and - * its retained size is therefore significant (assuming no external - * references into the tree). - * - * The simple, engineered algorithm presented in "A Simple, Fast Dominance - * Algorithm" by Cooper el al[0] is used to find dominators and construct the - * dominator tree. This algorithm runs in O(n^2) time, but is faster in practice - * than alternative algorithms with better theoretical running times, such as - * Lengauer-Tarjan which runs in O(e * log(n)). The big caveat to that statement - * is that Cooper et al found it is faster in practice *on control flow graphs* - * and I'm not convinced that this property also holds on *heap* graphs. That - * said, the implementation of this algorithm is *much* simpler than - * Lengauer-Tarjan and has been found to be fast enough at least for the time - * being. - * - * [0]: http://www.cs.rice.edu/~keith/EMBED/dom.pdf - */ -class JS_PUBLIC_API(DominatorTree) -{ - private: - // Types. - - using PredecessorSets = js::HashMap, - js::SystemAllocPolicy>; - using NodeToIndexMap = js::HashMap, - js::SystemAllocPolicy>; - class DominatedSets; - - public: - class DominatedSetRange; - - /** - * A pointer to an immediately dominated node. - * - * Don't use this type directly; it is no safer than regular pointers. This - * is only for use indirectly with range-based for loops and - * `DominatedSetRange`. - * - * @see JS::ubi::DominatorTree::getDominatedSet - */ - class DominatedNodePtr - { - friend class DominatedSetRange; - - const JS::ubi::Vector& postOrder; - const uint32_t* ptr; - - DominatedNodePtr(const JS::ubi::Vector& postOrder, const uint32_t* ptr) - : postOrder(postOrder) - , ptr(ptr) - { } - - public: - bool operator!=(const DominatedNodePtr& rhs) const { return ptr != rhs.ptr; } - void operator++() { ptr++; } - const Node& operator*() const { return postOrder[*ptr]; } - }; - - /** - * A range of immediately dominated `JS::ubi::Node`s for use with - * range-based for loops. - * - * @see JS::ubi::DominatorTree::getDominatedSet - */ - class DominatedSetRange - { - friend class DominatedSets; - - const JS::ubi::Vector& postOrder; - const uint32_t* beginPtr; - const uint32_t* endPtr; - - DominatedSetRange(JS::ubi::Vector& postOrder, const uint32_t* begin, const uint32_t* end) - : postOrder(postOrder) - , beginPtr(begin) - , endPtr(end) - { - MOZ_ASSERT(begin <= end); - } - - public: - DominatedNodePtr begin() const { - MOZ_ASSERT(beginPtr <= endPtr); - return DominatedNodePtr(postOrder, beginPtr); - } - - DominatedNodePtr end() const { - return DominatedNodePtr(postOrder, endPtr); - } - - size_t length() const { - MOZ_ASSERT(beginPtr <= endPtr); - return endPtr - beginPtr; - } - - /** - * Safely skip ahead `n` dominators in the range, in O(1) time. - * - * Example usage: - * - * mozilla::Maybe range = myDominatorTree.getDominatedSet(myNode); - * if (range.isNothing()) { - * // Handle unknown nodes however you see fit... - * return false; - * } - * - * // Don't care about the first ten, for whatever reason. - * range->skip(10); - * for (const JS::ubi::Node& dominatedNode : *range) { - * // ... - * } - */ - void skip(size_t n) { - beginPtr += n; - if (beginPtr > endPtr) - beginPtr = endPtr; - } - }; - - private: - /** - * The set of all dominated sets in a dominator tree. - * - * Internally stores the sets in a contiguous array, with a side table of - * indices into that contiguous array to denote the start index of each - * individual set. - */ - class DominatedSets - { - JS::ubi::Vector dominated; - JS::ubi::Vector indices; - - DominatedSets(JS::ubi::Vector&& dominated, JS::ubi::Vector&& indices) - : dominated(mozilla::Move(dominated)) - , indices(mozilla::Move(indices)) - { } - - public: - // DominatedSets is not copy-able. - DominatedSets(const DominatedSets& rhs) = delete; - DominatedSets& operator=(const DominatedSets& rhs) = delete; - - // DominatedSets is move-able. - DominatedSets(DominatedSets&& rhs) - : dominated(mozilla::Move(rhs.dominated)) - , indices(mozilla::Move(rhs.indices)) - { - MOZ_ASSERT(this != &rhs, "self-move not allowed"); - } - DominatedSets& operator=(DominatedSets&& rhs) { - this->~DominatedSets(); - new (this) DominatedSets(mozilla::Move(rhs)); - return *this; - } - - /** - * Create the DominatedSets given the mapping of a node index to its - * immediate dominator. Returns `Some` on success, `Nothing` on OOM - * failure. - */ - static mozilla::Maybe Create(const JS::ubi::Vector& doms) { - auto length = doms.length(); - MOZ_ASSERT(length < UINT32_MAX); - - // Create a vector `dominated` holding a flattened set of buckets of - // immediately dominated children nodes, with a lookup table - // `indices` mapping from each node to the beginning of its bucket. - // - // This has three phases: - // - // 1. Iterate over the full set of nodes and count up the size of - // each bucket. These bucket sizes are temporarily stored in the - // `indices` vector. - // - // 2. Convert the `indices` vector to store the cumulative sum of - // the sizes of all buckets before each index, resulting in a - // mapping from node index to one past the end of that node's - // bucket. - // - // 3. Iterate over the full set of nodes again, filling in bucket - // entries from the end of the bucket's range to its - // beginning. This decrements each index as a bucket entry is - // filled in. After having filled in all of a bucket's entries, - // the index points to the start of the bucket. - - JS::ubi::Vector dominated; - JS::ubi::Vector indices; - if (!dominated.growBy(length) || !indices.growBy(length)) - return mozilla::Nothing(); - - // 1 - memset(indices.begin(), 0, length * sizeof(uint32_t)); - for (uint32_t i = 0; i < length; i++) - indices[doms[i]]++; - - // 2 - uint32_t sumOfSizes = 0; - for (uint32_t i = 0; i < length; i++) { - sumOfSizes += indices[i]; - MOZ_ASSERT(sumOfSizes <= length); - indices[i] = sumOfSizes; - } - - // 3 - for (uint32_t i = 0; i < length; i++) { - auto idxOfDom = doms[i]; - indices[idxOfDom]--; - dominated[indices[idxOfDom]] = i; - } - -#ifdef DEBUG - // Assert that our buckets are non-overlapping and don't run off the - // end of the vector. - uint32_t lastIndex = 0; - for (uint32_t i = 0; i < length; i++) { - MOZ_ASSERT(indices[i] >= lastIndex); - MOZ_ASSERT(indices[i] < length); - lastIndex = indices[i]; - } -#endif - - return mozilla::Some(DominatedSets(mozilla::Move(dominated), mozilla::Move(indices))); - } - - /** - * Get the set of nodes immediately dominated by the node at - * `postOrder[nodeIndex]`. - */ - DominatedSetRange dominatedSet(JS::ubi::Vector& postOrder, uint32_t nodeIndex) const { - MOZ_ASSERT(postOrder.length() == indices.length()); - MOZ_ASSERT(nodeIndex < indices.length()); - auto end = nodeIndex == indices.length() - 1 - ? dominated.end() - : &dominated[indices[nodeIndex + 1]]; - return DominatedSetRange(postOrder, &dominated[indices[nodeIndex]], end); - } - }; - - private: - // Data members. - JS::ubi::Vector postOrder; - NodeToIndexMap nodeToPostOrderIndex; - JS::ubi::Vector doms; - DominatedSets dominatedSets; - mozilla::Maybe> retainedSizes; - - private: - // We use `UNDEFINED` as a sentinel value in the `doms` vector to signal - // that we haven't found any dominators for the node at the corresponding - // index in `postOrder` yet. - static const uint32_t UNDEFINED = UINT32_MAX; - - DominatorTree(JS::ubi::Vector&& postOrder, NodeToIndexMap&& nodeToPostOrderIndex, - JS::ubi::Vector&& doms, DominatedSets&& dominatedSets) - : postOrder(mozilla::Move(postOrder)) - , nodeToPostOrderIndex(mozilla::Move(nodeToPostOrderIndex)) - , doms(mozilla::Move(doms)) - , dominatedSets(mozilla::Move(dominatedSets)) - , retainedSizes(mozilla::Nothing()) - { } - - static uint32_t intersect(JS::ubi::Vector& doms, uint32_t finger1, uint32_t finger2) { - while (finger1 != finger2) { - if (finger1 < finger2) - finger1 = doms[finger1]; - else if (finger2 < finger1) - finger2 = doms[finger2]; - } - return finger1; - } - - // Do the post order traversal of the heap graph and populate our - // predecessor sets. - static MOZ_MUST_USE bool doTraversal(JSContext* cx, AutoCheckCannotGC& noGC, const Node& root, - JS::ubi::Vector& postOrder, - PredecessorSets& predecessorSets) { - uint32_t nodeCount = 0; - auto onNode = [&](const Node& node) { - nodeCount++; - if (MOZ_UNLIKELY(nodeCount == UINT32_MAX)) - return false; - return postOrder.append(node); - }; - - auto onEdge = [&](const Node& origin, const Edge& edge) { - auto p = predecessorSets.lookupForAdd(edge.referent); - if (!p) { - mozilla::UniquePtr> set(js_new()); - if (!set || - !set->init() || - !predecessorSets.add(p, edge.referent, mozilla::Move(set))) - { - return false; - } - } - MOZ_ASSERT(p && p->value()); - return p->value()->put(origin); - }; - - PostOrder traversal(cx, noGC); - return traversal.init() && - traversal.addStart(root) && - traversal.traverse(onNode, onEdge); - } - - // Populates the given `map` with an entry for each node to its index in - // `postOrder`. - static MOZ_MUST_USE bool mapNodesToTheirIndices(JS::ubi::Vector& postOrder, - NodeToIndexMap& map) { - MOZ_ASSERT(!map.initialized()); - MOZ_ASSERT(postOrder.length() < UINT32_MAX); - uint32_t length = postOrder.length(); - if (!map.init(length)) - return false; - for (uint32_t i = 0; i < length; i++) - map.putNewInfallible(postOrder[i], i); - return true; - } - - // Convert the Node -> NodeSet predecessorSets to a index -> Vector - // form. - static MOZ_MUST_USE bool convertPredecessorSetsToVectors( - const Node& root, - JS::ubi::Vector& postOrder, - PredecessorSets& predecessorSets, - NodeToIndexMap& nodeToPostOrderIndex, - JS::ubi::Vector>& predecessorVectors) - { - MOZ_ASSERT(postOrder.length() < UINT32_MAX); - uint32_t length = postOrder.length(); - - MOZ_ASSERT(predecessorVectors.length() == 0); - if (!predecessorVectors.growBy(length)) - return false; - - for (uint32_t i = 0; i < length - 1; i++) { - auto& node = postOrder[i]; - MOZ_ASSERT(node != root, - "Only the last node should be root, since this was a post order traversal."); - - auto ptr = predecessorSets.lookup(node); - MOZ_ASSERT(ptr, - "Because this isn't the root, it had better have predecessors, or else how " - "did we even find it."); - - auto& predecessors = ptr->value(); - if (!predecessorVectors[i].reserve(predecessors->count())) - return false; - for (auto range = predecessors->all(); !range.empty(); range.popFront()) { - auto ptr = nodeToPostOrderIndex.lookup(range.front()); - MOZ_ASSERT(ptr); - predecessorVectors[i].infallibleAppend(ptr->value()); - } - } - predecessorSets.finish(); - return true; - } - - // Initialize `doms` such that the immediate dominator of the `root` is the - // `root` itself and all others are `UNDEFINED`. - static MOZ_MUST_USE bool initializeDominators(JS::ubi::Vector& doms, - uint32_t length) { - MOZ_ASSERT(doms.length() == 0); - if (!doms.growByUninitialized(length)) - return false; - doms[length - 1] = length - 1; - for (uint32_t i = 0; i < length - 1; i++) - doms[i] = UNDEFINED; - return true; - } - - void assertSanity() const { - MOZ_ASSERT(postOrder.length() == doms.length()); - MOZ_ASSERT(postOrder.length() == nodeToPostOrderIndex.count()); - MOZ_ASSERT_IF(retainedSizes.isSome(), postOrder.length() == retainedSizes->length()); - } - - MOZ_MUST_USE bool computeRetainedSizes(mozilla::MallocSizeOf mallocSizeOf) { - MOZ_ASSERT(retainedSizes.isNothing()); - auto length = postOrder.length(); - - retainedSizes.emplace(); - if (!retainedSizes->growBy(length)) { - retainedSizes = mozilla::Nothing(); - return false; - } - - // Iterate in forward order so that we know all of a node's children in - // the dominator tree have already had their retained size - // computed. Then we can simply say that the retained size of a node is - // its shallow size (JS::ubi::Node::size) plus the retained sizes of its - // immediate children in the tree. - - for (uint32_t i = 0; i < length; i++) { - auto size = postOrder[i].size(mallocSizeOf); - - for (const auto& dominated : dominatedSets.dominatedSet(postOrder, i)) { - // The root node dominates itself, but shouldn't contribute to - // its own retained size. - if (dominated == postOrder[length - 1]) { - MOZ_ASSERT(i == length - 1); - continue; - } - - auto ptr = nodeToPostOrderIndex.lookup(dominated); - MOZ_ASSERT(ptr); - auto idxOfDominated = ptr->value(); - MOZ_ASSERT(idxOfDominated < i); - size += retainedSizes.ref()[idxOfDominated]; - } - - retainedSizes.ref()[i] = size; - } - - return true; - } - - public: - // DominatorTree is not copy-able. - DominatorTree(const DominatorTree&) = delete; - DominatorTree& operator=(const DominatorTree&) = delete; - - // DominatorTree is move-able. - DominatorTree(DominatorTree&& rhs) - : postOrder(mozilla::Move(rhs.postOrder)) - , nodeToPostOrderIndex(mozilla::Move(rhs.nodeToPostOrderIndex)) - , doms(mozilla::Move(rhs.doms)) - , dominatedSets(mozilla::Move(rhs.dominatedSets)) - , retainedSizes(mozilla::Move(rhs.retainedSizes)) - { - MOZ_ASSERT(this != &rhs, "self-move is not allowed"); - } - DominatorTree& operator=(DominatorTree&& rhs) { - this->~DominatorTree(); - new (this) DominatorTree(mozilla::Move(rhs)); - return *this; - } - - /** - * Construct a `DominatorTree` of the heap graph visible from `root`. The - * `root` is also used as the root of the resulting dominator tree. - * - * The resulting `DominatorTree` instance must not outlive the - * `JS::ubi::Node` graph it was constructed from. - * - * - For `JS::ubi::Node` graphs backed by the live heap graph, this means - * that the `DominatorTree`'s lifetime _must_ be contained within the - * scope of the provided `AutoCheckCannotGC` reference because a GC will - * invalidate the nodes. - * - * - For `JS::ubi::Node` graphs backed by some other offline structure - * provided by the embedder, the resulting `DominatorTree`'s lifetime is - * bounded by that offline structure's lifetime. - * - * In practice, this means that within SpiderMonkey we must treat - * `DominatorTree` as if it were backed by the live heap graph and trust - * that embedders with knowledge of the graph's implementation will do the - * Right Thing. - * - * Returns `mozilla::Nothing()` on OOM failure. It is the caller's - * responsibility to handle and report the OOM. - */ - static mozilla::Maybe - Create(JSContext* cx, AutoCheckCannotGC& noGC, const Node& root) { - JS::ubi::Vector postOrder; - PredecessorSets predecessorSets; - if (!predecessorSets.init() || !doTraversal(cx, noGC, root, postOrder, predecessorSets)) - return mozilla::Nothing(); - - MOZ_ASSERT(postOrder.length() < UINT32_MAX); - uint32_t length = postOrder.length(); - MOZ_ASSERT(postOrder[length - 1] == root); - - // From here on out we wish to avoid hash table lookups, and we use - // indices into `postOrder` instead of actual nodes wherever - // possible. This greatly improves the performance of this - // implementation, but we have to pay a little bit of upfront cost to - // convert our data structures to play along first. - - NodeToIndexMap nodeToPostOrderIndex; - if (!mapNodesToTheirIndices(postOrder, nodeToPostOrderIndex)) - return mozilla::Nothing(); - - JS::ubi::Vector> predecessorVectors; - if (!convertPredecessorSetsToVectors(root, postOrder, predecessorSets, nodeToPostOrderIndex, - predecessorVectors)) - return mozilla::Nothing(); - - JS::ubi::Vector doms; - if (!initializeDominators(doms, length)) - return mozilla::Nothing(); - - bool changed = true; - while (changed) { - changed = false; - - // Iterate over the non-root nodes in reverse post order. - for (uint32_t indexPlusOne = length - 1; indexPlusOne > 0; indexPlusOne--) { - MOZ_ASSERT(postOrder[indexPlusOne - 1] != root); - - // Take the intersection of every predecessor's dominator set; - // that is the current best guess at the immediate dominator for - // this node. - - uint32_t newIDomIdx = UNDEFINED; - - auto& predecessors = predecessorVectors[indexPlusOne - 1]; - auto range = predecessors.all(); - for ( ; !range.empty(); range.popFront()) { - auto idx = range.front(); - if (doms[idx] != UNDEFINED) { - newIDomIdx = idx; - break; - } - } - - MOZ_ASSERT(newIDomIdx != UNDEFINED, - "Because the root is initialized to dominate itself and is the first " - "node in every path, there must exist a predecessor to this node that " - "also has a dominator."); - - for ( ; !range.empty(); range.popFront()) { - auto idx = range.front(); - if (doms[idx] != UNDEFINED) - newIDomIdx = intersect(doms, newIDomIdx, idx); - } - - // If the immediate dominator changed, we will have to do - // another pass of the outer while loop to continue the forward - // dataflow. - if (newIDomIdx != doms[indexPlusOne - 1]) { - doms[indexPlusOne - 1] = newIDomIdx; - changed = true; - } - } - } - - auto maybeDominatedSets = DominatedSets::Create(doms); - if (maybeDominatedSets.isNothing()) - return mozilla::Nothing(); - - return mozilla::Some(DominatorTree(mozilla::Move(postOrder), - mozilla::Move(nodeToPostOrderIndex), - mozilla::Move(doms), - mozilla::Move(*maybeDominatedSets))); - } - - /** - * Get the root node for this dominator tree. - */ - const Node& root() const { - return postOrder[postOrder.length() - 1]; - } - - /** - * Return the immediate dominator of the given `node`. If `node` was not - * reachable from the `root` that this dominator tree was constructed from, - * then return the null `JS::ubi::Node`. - */ - Node getImmediateDominator(const Node& node) const { - assertSanity(); - auto ptr = nodeToPostOrderIndex.lookup(node); - if (!ptr) - return Node(); - - auto idx = ptr->value(); - MOZ_ASSERT(idx < postOrder.length()); - return postOrder[doms[idx]]; - } - - /** - * Get the set of nodes immediately dominated by the given `node`. If `node` - * is not a member of this dominator tree, return `Nothing`. - * - * Example usage: - * - * mozilla::Maybe range = myDominatorTree.getDominatedSet(myNode); - * if (range.isNothing()) { - * // Handle unknown node however you see fit... - * return false; - * } - * - * for (const JS::ubi::Node& dominatedNode : *range) { - * // Do something with each immediately dominated node... - * } - */ - mozilla::Maybe getDominatedSet(const Node& node) { - assertSanity(); - auto ptr = nodeToPostOrderIndex.lookup(node); - if (!ptr) - return mozilla::Nothing(); - - auto idx = ptr->value(); - MOZ_ASSERT(idx < postOrder.length()); - return mozilla::Some(dominatedSets.dominatedSet(postOrder, idx)); - } - - /** - * Get the retained size of the given `node`. The size is placed in - * `outSize`, or 0 if `node` is not a member of the dominator tree. Returns - * false on OOM failure, leaving `outSize` unchanged. - */ - MOZ_MUST_USE bool getRetainedSize(const Node& node, mozilla::MallocSizeOf mallocSizeOf, - Node::Size& outSize) { - assertSanity(); - auto ptr = nodeToPostOrderIndex.lookup(node); - if (!ptr) { - outSize = 0; - return true; - } - - if (retainedSizes.isNothing() && !computeRetainedSizes(mallocSizeOf)) - return false; - - auto idx = ptr->value(); - MOZ_ASSERT(idx < postOrder.length()); - outSize = retainedSizes.ref()[idx]; - return true; - } -}; - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeDominatorTree_h diff --git a/win32/include/spidermonkey/js/UbiNodePostOrder.h b/win32/include/spidermonkey/js/UbiNodePostOrder.h deleted file mode 100755 index a5042677..00000000 --- a/win32/include/spidermonkey/js/UbiNodePostOrder.h +++ /dev/null @@ -1,191 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodePostOrder_h -#define js_UbiNodePostOrder_h - -#include "mozilla/Attributes.h" -#include "mozilla/Maybe.h" -#include "mozilla/Move.h" - -#include "jsalloc.h" - -#include "js/UbiNode.h" -#include "js/Utility.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -/** - * A post-order depth-first traversal of `ubi::Node` graphs. - * - * No GC may occur while an instance of `PostOrder` is live. - * - * The `NodeVisitor` type provided to `PostOrder::traverse` must have the - * following member: - * - * bool operator()(Node& node) - * - * The node visitor method. This method is called once for each `node` - * reachable from the start set in post-order. - * - * This visitor function should return true on success, or false if an error - * occurs. A false return value terminates the traversal immediately, and - * causes `PostOrder::traverse` to return false. - * - * The `EdgeVisitor` type provided to `PostOrder::traverse` must have the - * following member: - * - * bool operator()(Node& origin, Edge& edge) - * - * The edge visitor method. This method is called once for each outgoing - * `edge` from `origin` that is reachable from the start set. - * - * NB: UNLIKE NODES, THERE IS NO GUARANTEED ORDER IN WHICH EDGES AND THEIR - * ORIGINS ARE VISITED! - * - * This visitor function should return true on success, or false if an error - * occurs. A false return value terminates the traversal immediately, and - * causes `PostOrder::traverse` to return false. - */ -struct PostOrder { - private: - struct OriginAndEdges { - Node origin; - EdgeVector edges; - - OriginAndEdges(const Node& node, EdgeVector&& edges) - : origin(node) - , edges(mozilla::Move(edges)) - { } - - OriginAndEdges(const OriginAndEdges& rhs) = delete; - OriginAndEdges& operator=(const OriginAndEdges& rhs) = delete; - - OriginAndEdges(OriginAndEdges&& rhs) - : origin(rhs.origin) - , edges(mozilla::Move(rhs.edges)) - { - MOZ_ASSERT(&rhs != this, "self-move disallowed"); - } - - OriginAndEdges& operator=(OriginAndEdges&& rhs) { - this->~OriginAndEdges(); - new (this) OriginAndEdges(mozilla::Move(rhs)); - return *this; - } - }; - - using Stack = js::Vector; - using Set = js::HashSet, js::SystemAllocPolicy>; - - JSContext* cx; - Set seen; - Stack stack; -#ifdef DEBUG - bool traversed; -#endif - - private: - MOZ_MUST_USE bool fillEdgesFromRange(EdgeVector& edges, js::UniquePtr& range) { - MOZ_ASSERT(range); - for ( ; !range->empty(); range->popFront()) { - if (!edges.append(mozilla::Move(range->front()))) - return false; - } - return true; - } - - MOZ_MUST_USE bool pushForTraversing(const Node& node) { - EdgeVector edges; - auto range = node.edges(cx, /* wantNames */ false); - return range && - fillEdgesFromRange(edges, range) && - stack.append(OriginAndEdges(node, mozilla::Move(edges))); - } - - - public: - // Construct a post-order traversal object. - // - // The traversal asserts that no GC happens in its runtime during its - // lifetime via the `AutoCheckCannotGC&` parameter. We do nothing with it, - // other than require it to exist with a lifetime that encloses our own. - PostOrder(JSContext* cx, AutoCheckCannotGC&) - : cx(cx) - , seen() - , stack() -#ifdef DEBUG - , traversed(false) -#endif - { } - - // Initialize this traversal object. Return false on OOM. - MOZ_MUST_USE bool init() { return seen.init(); } - - // Add `node` as a starting point for the traversal. You may add - // as many starting points as you like. Returns false on OOM. - MOZ_MUST_USE bool addStart(const Node& node) { - if (!seen.put(node)) - return false; - return pushForTraversing(node); - } - - // Traverse the graph in post-order, starting with the set of nodes passed - // to `addStart` and applying `onNode::operator()` for each node in the - // graph and `onEdge::operator()` for each edge in the graph, as described - // above. - // - // This should be called only once per instance of this class. - // - // Return false on OOM or error return from `onNode::operator()` or - // `onEdge::operator()`. - template - MOZ_MUST_USE bool traverse(NodeVisitor onNode, EdgeVisitor onEdge) { -#ifdef DEBUG - MOZ_ASSERT(!traversed, "Can only traverse() once!"); - traversed = true; -#endif - - while (!stack.empty()) { - auto& origin = stack.back().origin; - auto& edges = stack.back().edges; - - if (edges.empty()) { - if (!onNode(origin)) - return false; - stack.popBack(); - continue; - } - - Edge edge = mozilla::Move(edges.back()); - edges.popBack(); - - if (!onEdge(origin, edge)) - return false; - - auto ptr = seen.lookupForAdd(edge.referent); - // We've already seen this node, don't follow its edges. - if (ptr) - continue; - - // Mark the referent as seen and follow its edges. - if (!seen.add(ptr, edge.referent) || - !pushForTraversing(edge.referent)) - { - return false; - } - } - - return true; - } -}; - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodePostOrder_h diff --git a/win32/include/spidermonkey/js/UbiNodeShortestPaths.h b/win32/include/spidermonkey/js/UbiNodeShortestPaths.h deleted file mode 100755 index edd5aebb..00000000 --- a/win32/include/spidermonkey/js/UbiNodeShortestPaths.h +++ /dev/null @@ -1,350 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UbiNodeShortestPaths_h -#define js_UbiNodeShortestPaths_h - -#include "mozilla/Attributes.h" -#include "mozilla/Maybe.h" -#include "mozilla/Move.h" - -#include "jsalloc.h" - -#include "js/UbiNodeBreadthFirst.h" -#include "js/Vector.h" - -namespace JS { -namespace ubi { - -/** - * A back edge along a path in the heap graph. - */ -struct JS_PUBLIC_API(BackEdge) -{ - private: - Node predecessor_; - EdgeName name_; - - public: - using Ptr = mozilla::UniquePtr>; - - BackEdge() : predecessor_(), name_(nullptr) { } - - MOZ_MUST_USE bool init(const Node& predecessor, Edge& edge) { - MOZ_ASSERT(!predecessor_); - MOZ_ASSERT(!name_); - - predecessor_ = predecessor; - name_ = mozilla::Move(edge.name); - return true; - } - - BackEdge(const BackEdge&) = delete; - BackEdge& operator=(const BackEdge&) = delete; - - BackEdge(BackEdge&& rhs) - : predecessor_(rhs.predecessor_) - , name_(mozilla::Move(rhs.name_)) - { - MOZ_ASSERT(&rhs != this); - } - - BackEdge& operator=(BackEdge&& rhs) { - this->~BackEdge(); - new(this) BackEdge(Move(rhs)); - return *this; - } - - Ptr clone() const; - - const EdgeName& name() const { return name_; } - EdgeName& name() { return name_; } - - const JS::ubi::Node& predecessor() const { return predecessor_; } -}; - -/** - * A path is a series of back edges from which we discovered a target node. - */ -using Path = JS::ubi::Vector; - -/** - * The `JS::ubi::ShortestPaths` type represents a collection of up to N shortest - * retaining paths for each of a target set of nodes, starting from the same - * root node. - */ -struct JS_PUBLIC_API(ShortestPaths) -{ - private: - // Types, type aliases, and data members. - - using BackEdgeVector = JS::ubi::Vector; - using NodeToBackEdgeVectorMap = js::HashMap, - js::SystemAllocPolicy>; - - struct Handler; - using Traversal = BreadthFirst; - - /** - * A `JS::ubi::BreadthFirst` traversal handler that records back edges for - * how we reached each node, allowing us to reconstruct the shortest - * retaining paths after the traversal. - */ - struct Handler - { - using NodeData = BackEdge; - - ShortestPaths& shortestPaths; - size_t totalMaxPathsToRecord; - size_t totalPathsRecorded; - - explicit Handler(ShortestPaths& shortestPaths) - : shortestPaths(shortestPaths) - , totalMaxPathsToRecord(shortestPaths.targets_.count() * shortestPaths.maxNumPaths_) - , totalPathsRecorded(0) - { - } - - bool - operator()(Traversal& traversal, JS::ubi::Node origin, JS::ubi::Edge& edge, - BackEdge* back, bool first) - { - MOZ_ASSERT(back); - MOZ_ASSERT(origin == shortestPaths.root_ || traversal.visited.has(origin)); - MOZ_ASSERT(totalPathsRecorded < totalMaxPathsToRecord); - - if (first && !back->init(origin, edge)) - return false; - - if (!shortestPaths.targets_.has(edge.referent)) - return true; - - // If `first` is true, then we moved the edge's name into `back` in - // the above call to `init`. So clone that back edge to get the - // correct edge name. If `first` is not true, then our edge name is - // still in `edge`. This accounts for the asymmetry between - // `back->clone()` in the first branch, and the `init` call in the - // second branch. - - if (first) { - BackEdgeVector paths; - if (!paths.reserve(shortestPaths.maxNumPaths_)) - return false; - auto cloned = back->clone(); - if (!cloned) - return false; - paths.infallibleAppend(mozilla::Move(cloned)); - if (!shortestPaths.paths_.putNew(edge.referent, mozilla::Move(paths))) - return false; - totalPathsRecorded++; - } else { - auto ptr = shortestPaths.paths_.lookup(edge.referent); - MOZ_ASSERT(ptr, - "This isn't the first time we have seen the target node `edge.referent`. " - "We should have inserted it into shortestPaths.paths_ the first time we " - "saw it."); - - if (ptr->value().length() < shortestPaths.maxNumPaths_) { - BackEdge::Ptr thisBackEdge(js_new()); - if (!thisBackEdge || !thisBackEdge->init(origin, edge)) - return false; - ptr->value().infallibleAppend(mozilla::Move(thisBackEdge)); - totalPathsRecorded++; - } - } - - MOZ_ASSERT(totalPathsRecorded <= totalMaxPathsToRecord); - if (totalPathsRecorded == totalMaxPathsToRecord) - traversal.stop(); - - return true; - } - - }; - - // The maximum number of paths to record for each node. - uint32_t maxNumPaths_; - - // The root node we are starting the search from. - Node root_; - - // The set of nodes we are searching for paths to. - NodeSet targets_; - - // The resulting paths. - NodeToBackEdgeVectorMap paths_; - - // Need to keep alive the traversal's back edges so we can walk them later - // when the traversal is over when recreating the shortest paths. - Traversal::NodeMap backEdges_; - - private: - // Private methods. - - ShortestPaths(uint32_t maxNumPaths, const Node& root, NodeSet&& targets) - : maxNumPaths_(maxNumPaths) - , root_(root) - , targets_(mozilla::Move(targets)) - , paths_() - , backEdges_() - { - MOZ_ASSERT(maxNumPaths_ > 0); - MOZ_ASSERT(root_); - MOZ_ASSERT(targets_.initialized()); - } - - bool initialized() const { - return targets_.initialized() && - paths_.initialized() && - backEdges_.initialized(); - } - - public: - // Public methods. - - ShortestPaths(ShortestPaths&& rhs) - : maxNumPaths_(rhs.maxNumPaths_) - , root_(rhs.root_) - , targets_(mozilla::Move(rhs.targets_)) - , paths_(mozilla::Move(rhs.paths_)) - , backEdges_(mozilla::Move(rhs.backEdges_)) - { - MOZ_ASSERT(this != &rhs, "self-move is not allowed"); - } - - ShortestPaths& operator=(ShortestPaths&& rhs) { - this->~ShortestPaths(); - new (this) ShortestPaths(mozilla::Move(rhs)); - return *this; - } - - ShortestPaths(const ShortestPaths&) = delete; - ShortestPaths& operator=(const ShortestPaths&) = delete; - - /** - * Construct a new `JS::ubi::ShortestPaths`, finding up to `maxNumPaths` - * shortest retaining paths for each target node in `targets` starting from - * `root`. - * - * The resulting `ShortestPaths` instance must not outlive the - * `JS::ubi::Node` graph it was constructed from. - * - * - For `JS::ubi::Node` graphs backed by the live heap graph, this means - * that the `ShortestPaths`'s lifetime _must_ be contained within the - * scope of the provided `AutoCheckCannotGC` reference because a GC will - * invalidate the nodes. - * - * - For `JS::ubi::Node` graphs backed by some other offline structure - * provided by the embedder, the resulting `ShortestPaths`'s lifetime is - * bounded by that offline structure's lifetime. - * - * Returns `mozilla::Nothing()` on OOM failure. It is the caller's - * responsibility to handle and report the OOM. - */ - static mozilla::Maybe - Create(JSContext* cx, AutoCheckCannotGC& noGC, uint32_t maxNumPaths, const Node& root, NodeSet&& targets) { - MOZ_ASSERT(targets.count() > 0); - MOZ_ASSERT(maxNumPaths > 0); - - size_t count = targets.count(); - ShortestPaths paths(maxNumPaths, root, mozilla::Move(targets)); - if (!paths.paths_.init(count)) - return mozilla::Nothing(); - - Handler handler(paths); - Traversal traversal(cx, handler, noGC); - traversal.wantNames = true; - if (!traversal.init() || !traversal.addStart(root) || !traversal.traverse()) - return mozilla::Nothing(); - - // Take ownership of the back edges we created while traversing the - // graph so that we can follow them from `paths_` and don't - // use-after-free. - paths.backEdges_ = mozilla::Move(traversal.visited); - - MOZ_ASSERT(paths.initialized()); - return mozilla::Some(mozilla::Move(paths)); - } - - /** - * Get a range that iterates over each target node we searched for retaining - * paths for. The returned range must not outlive the `ShortestPaths` - * instance. - */ - NodeSet::Range eachTarget() const { - MOZ_ASSERT(initialized()); - return targets_.all(); - } - - /** - * Invoke the provided functor/lambda/callable once for each retaining path - * discovered for `target`. The `func` is passed a single `JS::ubi::Path&` - * argument, which contains each edge along the path ordered starting from - * the root and ending at the target, and must not outlive the scope of the - * call. - * - * Note that it is possible that we did not find any paths from the root to - * the given target, in which case `func` will not be invoked. - */ - template - MOZ_MUST_USE bool forEachPath(const Node& target, Func func) { - MOZ_ASSERT(initialized()); - MOZ_ASSERT(targets_.has(target)); - - auto ptr = paths_.lookup(target); - - // We didn't find any paths to this target, so nothing to do here. - if (!ptr) - return true; - - MOZ_ASSERT(ptr->value().length() <= maxNumPaths_); - - Path path; - for (const auto& backEdge : ptr->value()) { - path.clear(); - - if (!path.append(backEdge.get())) - return false; - - Node here = backEdge->predecessor(); - MOZ_ASSERT(here); - - while (here != root_) { - auto p = backEdges_.lookup(here); - MOZ_ASSERT(p); - if (!path.append(&p->value())) - return false; - here = p->value().predecessor(); - MOZ_ASSERT(here); - } - - path.reverse(); - - if (!func(path)) - return false; - } - - return true; - } -}; - -#ifdef DEBUG -// A helper function to dump the first `maxNumPaths` shortest retaining paths to -// `node` from the GC roots. Useful when GC things you expect to have been -// reclaimed by the collector haven't been! -// -// Usage: -// -// JSObject* foo = ...; -// JS::ubi::dumpPaths(rt, JS::ubi::Node(foo)); -JS_PUBLIC_API(void) -dumpPaths(JSRuntime* rt, Node node, uint32_t maxNumPaths = 10); -#endif - -} // namespace ubi -} // namespace JS - -#endif // js_UbiNodeShortestPaths_h diff --git a/win32/include/spidermonkey/js/UniquePtr.h b/win32/include/spidermonkey/js/UniquePtr.h deleted file mode 100755 index 0236bab4..00000000 --- a/win32/include/spidermonkey/js/UniquePtr.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_UniquePtr_h -#define js_UniquePtr_h - -#include "mozilla/UniquePtr.h" - -#include "js/Utility.h" - -namespace js { - -// Replacement for mozilla::UniquePtr that defaults to js::DefaultDelete. -template > -using UniquePtr = mozilla::UniquePtr; - -namespace detail { - -template -struct UniqueSelector -{ - typedef UniquePtr SingleObject; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr UnknownBound; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr KnownBound; -}; - -} // namespace detail - -// Replacement for mozilla::MakeUnique that correctly calls js_new and produces -// a js::UniquePtr. -template -typename detail::UniqueSelector::SingleObject -MakeUnique(Args&&... aArgs) -{ - return UniquePtr(js_new(mozilla::Forward(aArgs)...)); -} - -template -typename detail::UniqueSelector::UnknownBound -MakeUnique(decltype(sizeof(int)) aN) = delete; - -template -typename detail::UniqueSelector::KnownBound -MakeUnique(Args&&... aArgs) = delete; - -} // namespace js - -#endif /* js_UniquePtr_h */ diff --git a/win32/include/spidermonkey/js/Utility.h b/win32/include/spidermonkey/js/Utility.h deleted file mode 100755 index e95e8ecc..00000000 --- a/win32/include/spidermonkey/js/Utility.h +++ /dev/null @@ -1,577 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Utility_h -#define js_Utility_h - -#include "mozilla/Assertions.h" -#include "mozilla/Atomics.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/Move.h" -#include "mozilla/Scoped.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/UniquePtr.h" - -#include -#include - -#ifdef JS_OOM_DO_BACKTRACES -#include -#include -#endif - -#include "jstypes.h" - -/* The public JS engine namespace. */ -namespace JS {} - -/* The mozilla-shared reusable template/utility namespace. */ -namespace mozilla {} - -/* The private JS engine namespace. */ -namespace js {} - -#define JS_STATIC_ASSERT(cond) static_assert(cond, "JS_STATIC_ASSERT") -#define JS_STATIC_ASSERT_IF(cond, expr) MOZ_STATIC_ASSERT_IF(cond, expr, "JS_STATIC_ASSERT_IF") - -extern MOZ_NORETURN MOZ_COLD JS_PUBLIC_API(void) -JS_Assert(const char* s, const char* file, int ln); - -/* - * Custom allocator support for SpiderMonkey - */ -#if defined JS_USE_CUSTOM_ALLOCATOR -# include "jscustomallocator.h" -#else - -namespace js { -namespace oom { - -/* - * To make testing OOM in certain helper threads more effective, - * allow restricting the OOM testing to a certain helper thread - * type. This allows us to fail e.g. in off-thread script parsing - * without causing an OOM in the main thread first. - */ -enum ThreadType { - THREAD_TYPE_NONE = 0, // 0 - THREAD_TYPE_MAIN, // 1 - THREAD_TYPE_ASMJS, // 2 - THREAD_TYPE_ION, // 3 - THREAD_TYPE_PARSE, // 4 - THREAD_TYPE_COMPRESS, // 5 - THREAD_TYPE_GCHELPER, // 6 - THREAD_TYPE_GCPARALLEL, // 7 - THREAD_TYPE_PROMISE_TASK, // 8 - THREAD_TYPE_MAX // Used to check shell function arguments -}; - -/* - * Getter/Setter functions to encapsulate mozilla::ThreadLocal, - * implementation is in jsutil.cpp. - */ -# if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) -extern bool InitThreadType(void); -extern void SetThreadType(ThreadType); -extern JS_PUBLIC_API(uint32_t) GetThreadType(void); -# else -inline bool InitThreadType(void) { return true; } -inline void SetThreadType(ThreadType t) {}; -inline JS_PUBLIC_API(uint32_t) GetThreadType(void) { return 0; } -# endif - -} /* namespace oom */ -} /* namespace js */ - -# if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) - -#ifdef JS_OOM_BREAKPOINT -static MOZ_NEVER_INLINE void js_failedAllocBreakpoint() { asm(""); } -#define JS_OOM_CALL_BP_FUNC() js_failedAllocBreakpoint() -#else -#define JS_OOM_CALL_BP_FUNC() do {} while(0) -#endif - -namespace js { -namespace oom { - -/* - * Out of memory testing support. We provide various testing functions to - * simulate OOM conditions and so we can test that they are handled correctly. - */ - -extern JS_PUBLIC_DATA(uint32_t) targetThread; -extern JS_PUBLIC_DATA(uint64_t) maxAllocations; -extern JS_PUBLIC_DATA(uint64_t) counter; -extern JS_PUBLIC_DATA(bool) failAlways; - -extern void -SimulateOOMAfter(uint64_t allocations, uint32_t thread, bool always); - -extern void -ResetSimulatedOOM(); - -inline bool -IsThreadSimulatingOOM() -{ - return js::oom::targetThread && js::oom::targetThread == js::oom::GetThreadType(); -} - -inline bool -IsSimulatedOOMAllocation() -{ - return IsThreadSimulatingOOM() && - (counter == maxAllocations || (counter > maxAllocations && failAlways)); -} - -inline bool -ShouldFailWithOOM() -{ - if (!IsThreadSimulatingOOM()) - return false; - - counter++; - if (IsSimulatedOOMAllocation()) { - JS_OOM_CALL_BP_FUNC(); - return true; - } - return false; -} - -inline bool -HadSimulatedOOM() { - return counter >= maxAllocations; -} - -} /* namespace oom */ -} /* namespace js */ - -# define JS_OOM_POSSIBLY_FAIL() \ - do { \ - if (js::oom::ShouldFailWithOOM()) \ - return nullptr; \ - } while (0) - -# define JS_OOM_POSSIBLY_FAIL_BOOL() \ - do { \ - if (js::oom::ShouldFailWithOOM()) \ - return false; \ - } while (0) - -# else - -# define JS_OOM_POSSIBLY_FAIL() do {} while(0) -# define JS_OOM_POSSIBLY_FAIL_BOOL() do {} while(0) -namespace js { -namespace oom { -static inline bool IsSimulatedOOMAllocation() { return false; } -static inline bool ShouldFailWithOOM() { return false; } -} /* namespace oom */ -} /* namespace js */ - -# endif /* DEBUG || JS_OOM_BREAKPOINT */ - -namespace js { - -/* Disable OOM testing in sections which are not OOM safe. */ -struct MOZ_RAII AutoEnterOOMUnsafeRegion -{ - MOZ_NORETURN MOZ_COLD void crash(const char* reason); - MOZ_NORETURN MOZ_COLD void crash(size_t size, const char* reason); - - using AnnotateOOMAllocationSizeCallback = void(*)(size_t); - static AnnotateOOMAllocationSizeCallback annotateOOMSizeCallback; - static void setAnnotateOOMAllocationSizeCallback(AnnotateOOMAllocationSizeCallback callback) { - annotateOOMSizeCallback = callback; - } - -#if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) - AutoEnterOOMUnsafeRegion() - : oomEnabled_(oom::IsThreadSimulatingOOM() && oom::maxAllocations != UINT64_MAX), - oomAfter_(0) - { - if (oomEnabled_) { - MOZ_ALWAYS_TRUE(owner_.compareExchange(nullptr, this)); - oomAfter_ = int64_t(oom::maxAllocations) - int64_t(oom::counter); - oom::maxAllocations = UINT64_MAX; - } - } - - ~AutoEnterOOMUnsafeRegion() { - if (oomEnabled_) { - MOZ_ASSERT(oom::maxAllocations == UINT64_MAX); - int64_t maxAllocations = int64_t(oom::counter) + oomAfter_; - MOZ_ASSERT(maxAllocations >= 0, - "alloc count + oom limit exceeds range, your oom limit is probably too large"); - oom::maxAllocations = uint64_t(maxAllocations); - MOZ_ALWAYS_TRUE(owner_.compareExchange(this, nullptr)); - } - } - - private: - // Used to catch concurrent use from other threads. - static mozilla::Atomic owner_; - - bool oomEnabled_; - int64_t oomAfter_; -#endif -}; - -} /* namespace js */ - -static inline void* js_malloc(size_t bytes) -{ - JS_OOM_POSSIBLY_FAIL(); - return malloc(bytes); -} - -static inline void* js_calloc(size_t bytes) -{ - JS_OOM_POSSIBLY_FAIL(); - return calloc(bytes, 1); -} - -static inline void* js_calloc(size_t nmemb, size_t size) -{ - JS_OOM_POSSIBLY_FAIL(); - return calloc(nmemb, size); -} - -static inline void* js_realloc(void* p, size_t bytes) -{ - // realloc() with zero size is not portable, as some implementations may - // return nullptr on success and free |p| for this. We assume nullptr - // indicates failure and that |p| is still valid. - MOZ_ASSERT(bytes != 0); - - JS_OOM_POSSIBLY_FAIL(); - return realloc(p, bytes); -} - -static inline void js_free(void* p) -{ - free(p); -} - -static inline char* js_strdup(const char* s) -{ - JS_OOM_POSSIBLY_FAIL(); - return strdup(s); -} -#endif/* JS_USE_CUSTOM_ALLOCATOR */ - -#include - -/* - * Low-level memory management in SpiderMonkey: - * - * ** Do not use the standard malloc/free/realloc: SpiderMonkey allows these - * to be redefined (via JS_USE_CUSTOM_ALLOCATOR) and Gecko even #define's - * these symbols. - * - * ** Do not use the builtin C++ operator new and delete: these throw on - * error and we cannot override them not to. - * - * Allocation: - * - * - If the lifetime of the allocation is tied to the lifetime of a GC-thing - * (that is, finalizing the GC-thing will free the allocation), call one of - * the following functions: - * - * JSContext::{malloc_,realloc_,calloc_,new_} - * JSRuntime::{malloc_,realloc_,calloc_,new_} - * - * These functions accumulate the number of bytes allocated which is used as - * part of the GC-triggering heuristic. - * - * The difference between the JSContext and JSRuntime versions is that the - * cx version reports an out-of-memory error on OOM. (This follows from the - * general SpiderMonkey idiom that a JSContext-taking function reports its - * own errors.) - * - * - Otherwise, use js_malloc/js_realloc/js_calloc/js_new - * - * Deallocation: - * - * - Ordinarily, use js_free/js_delete. - * - * - For deallocations during GC finalization, use one of the following - * operations on the FreeOp provided to the finalizer: - * - * FreeOp::{free_,delete_} - * - * The advantage of these operations is that the memory is batched and freed - * on another thread. - */ - -/* - * Given a class which should provide a 'new' method, add - * JS_DECLARE_NEW_METHODS (see js::MallocProvider for an example). - * - * Note: Do not add a ; at the end of a use of JS_DECLARE_NEW_METHODS, - * or the build will break. - */ -#define JS_DECLARE_NEW_METHODS(NEWNAME, ALLOCATOR, QUALIFIERS) \ - template \ - QUALIFIERS T * \ - NEWNAME(Args&&... args) MOZ_HEAP_ALLOCATOR { \ - void* memory = ALLOCATOR(sizeof(T)); \ - return MOZ_LIKELY(memory) \ - ? new(memory) T(mozilla::Forward(args)...) \ - : nullptr; \ - } - -/* - * Given a class which should provide 'make' methods, add - * JS_DECLARE_MAKE_METHODS (see js::MallocProvider for an example). This - * method is functionally the same as JS_DECLARE_NEW_METHODS: it just declares - * methods that return mozilla::UniquePtr instances that will singly-manage - * ownership of the created object. - * - * Note: Do not add a ; at the end of a use of JS_DECLARE_MAKE_METHODS, - * or the build will break. - */ -#define JS_DECLARE_MAKE_METHODS(MAKENAME, NEWNAME, QUALIFIERS)\ - template \ - QUALIFIERS mozilla::UniquePtr> \ - MAKENAME(Args&&... args) MOZ_HEAP_ALLOCATOR { \ - T* ptr = NEWNAME(mozilla::Forward(args)...); \ - return mozilla::UniquePtr>(ptr); \ - } - -JS_DECLARE_NEW_METHODS(js_new, js_malloc, static MOZ_ALWAYS_INLINE) - -namespace js { - -/* - * Calculate the number of bytes needed to allocate |numElems| contiguous - * instances of type |T|. Return false if the calculation overflowed. - */ -template -MOZ_MUST_USE inline bool -CalculateAllocSize(size_t numElems, size_t* bytesOut) -{ - *bytesOut = numElems * sizeof(T); - return (numElems & mozilla::tl::MulOverflowMask::value) == 0; -} - -/* - * Calculate the number of bytes needed to allocate a single instance of type - * |T| followed by |numExtra| contiguous instances of type |Extra|. Return - * false if the calculation overflowed. - */ -template -MOZ_MUST_USE inline bool -CalculateAllocSizeWithExtra(size_t numExtra, size_t* bytesOut) -{ - *bytesOut = sizeof(T) + numExtra * sizeof(Extra); - return (numExtra & mozilla::tl::MulOverflowMask::value) == 0 && - *bytesOut >= sizeof(T); -} - -} /* namespace js */ - -template -static MOZ_ALWAYS_INLINE void -js_delete(const T* p) -{ - if (p) { - p->~T(); - js_free(const_cast(p)); - } -} - -template -static MOZ_ALWAYS_INLINE void -js_delete_poison(const T* p) -{ - if (p) { - p->~T(); - memset(const_cast(p), 0x3B, sizeof(T)); - js_free(const_cast(p)); - } -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_malloc() -{ - return static_cast(js_malloc(sizeof(T))); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_calloc() -{ - return static_cast(js_calloc(sizeof(T))); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_malloc(size_t numElems) -{ - size_t bytes; - if (MOZ_UNLIKELY(!js::CalculateAllocSize(numElems, &bytes))) - return nullptr; - return static_cast(js_malloc(bytes)); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_calloc(size_t numElems) -{ - size_t bytes; - if (MOZ_UNLIKELY(!js::CalculateAllocSize(numElems, &bytes))) - return nullptr; - return static_cast(js_calloc(bytes)); -} - -template -static MOZ_ALWAYS_INLINE T* -js_pod_realloc(T* prior, size_t oldSize, size_t newSize) -{ - MOZ_ASSERT(!(oldSize & mozilla::tl::MulOverflowMask::value)); - size_t bytes; - if (MOZ_UNLIKELY(!js::CalculateAllocSize(newSize, &bytes))) - return nullptr; - return static_cast(js_realloc(prior, bytes)); -} - -namespace js { - -template -struct ScopedFreePtrTraits -{ - typedef T* type; - static T* empty() { return nullptr; } - static void release(T* ptr) { js_free(ptr); } -}; -SCOPED_TEMPLATE(ScopedJSFreePtr, ScopedFreePtrTraits) - -template -struct ScopedDeletePtrTraits : public ScopedFreePtrTraits -{ - static void release(T* ptr) { js_delete(ptr); } -}; -SCOPED_TEMPLATE(ScopedJSDeletePtr, ScopedDeletePtrTraits) - -template -struct ScopedReleasePtrTraits : public ScopedFreePtrTraits -{ - static void release(T* ptr) { if (ptr) ptr->release(); } -}; -SCOPED_TEMPLATE(ScopedReleasePtr, ScopedReleasePtrTraits) - -} /* namespace js */ - -namespace JS { - -template -struct DeletePolicy -{ - constexpr DeletePolicy() {} - - template - MOZ_IMPLICIT DeletePolicy(DeletePolicy other, - typename mozilla::EnableIf::value, - int>::Type dummy = 0) - {} - - void operator()(const T* ptr) { - js_delete(const_cast(ptr)); - } -}; - -struct FreePolicy -{ - void operator()(const void* ptr) { - js_free(const_cast(ptr)); - } -}; - -typedef mozilla::UniquePtr UniqueChars; -typedef mozilla::UniquePtr UniqueTwoByteChars; - -} // namespace JS - -namespace js { - -/* Integral types for all hash functions. */ -typedef uint32_t HashNumber; -const unsigned HashNumberSizeBits = 32; - -namespace detail { - -/* - * Given a raw hash code, h, return a number that can be used to select a hash - * bucket. - * - * This function aims to produce as uniform an output distribution as possible, - * especially in the most significant (leftmost) bits, even though the input - * distribution may be highly nonrandom, given the constraints that this must - * be deterministic and quick to compute. - * - * Since the leftmost bits of the result are best, the hash bucket index is - * computed by doing ScrambleHashCode(h) / (2^32/N) or the equivalent - * right-shift, not ScrambleHashCode(h) % N or the equivalent bit-mask. - * - * FIXME: OrderedHashTable uses a bit-mask; see bug 775896. - */ -inline HashNumber -ScrambleHashCode(HashNumber h) -{ - /* - * Simply returning h would not cause any hash tables to produce wrong - * answers. But it can produce pathologically bad performance: The caller - * right-shifts the result, keeping only the highest bits. The high bits of - * hash codes are very often completely entropy-free. (So are the lowest - * bits.) - * - * So we use Fibonacci hashing, as described in Knuth, The Art of Computer - * Programming, 6.4. This mixes all the bits of the input hash code h. - * - * The value of goldenRatio is taken from the hex - * expansion of the golden ratio, which starts 1.9E3779B9.... - * This value is especially good if values with consecutive hash codes - * are stored in a hash table; see Knuth for details. - */ - static const HashNumber goldenRatio = 0x9E3779B9U; - return h * goldenRatio; -} - -} /* namespace detail */ - -} /* namespace js */ - -/* sixgill annotation defines */ -#ifndef HAVE_STATIC_ANNOTATIONS -# define HAVE_STATIC_ANNOTATIONS -# ifdef XGILL_PLUGIN -# define STATIC_PRECONDITION(COND) __attribute__((precondition(#COND))) -# define STATIC_PRECONDITION_ASSUME(COND) __attribute__((precondition_assume(#COND))) -# define STATIC_POSTCONDITION(COND) __attribute__((postcondition(#COND))) -# define STATIC_POSTCONDITION_ASSUME(COND) __attribute__((postcondition_assume(#COND))) -# define STATIC_INVARIANT(COND) __attribute__((invariant(#COND))) -# define STATIC_INVARIANT_ASSUME(COND) __attribute__((invariant_assume(#COND))) -# define STATIC_ASSUME(COND) \ - JS_BEGIN_MACRO \ - __attribute__((assume_static(#COND), unused)) \ - int STATIC_PASTE1(assume_static_, __COUNTER__); \ - JS_END_MACRO -# else /* XGILL_PLUGIN */ -# define STATIC_PRECONDITION(COND) /* nothing */ -# define STATIC_PRECONDITION_ASSUME(COND) /* nothing */ -# define STATIC_POSTCONDITION(COND) /* nothing */ -# define STATIC_POSTCONDITION_ASSUME(COND) /* nothing */ -# define STATIC_INVARIANT(COND) /* nothing */ -# define STATIC_INVARIANT_ASSUME(COND) /* nothing */ -# define STATIC_ASSUME(COND) JS_BEGIN_MACRO /* nothing */ JS_END_MACRO -# endif /* XGILL_PLUGIN */ -# define STATIC_SKIP_INFERENCE STATIC_INVARIANT(skip_inference()) -#endif /* HAVE_STATIC_ANNOTATIONS */ - -#endif /* js_Utility_h */ diff --git a/win32/include/spidermonkey/js/Value.h b/win32/include/spidermonkey/js/Value.h deleted file mode 100755 index 00fdad58..00000000 --- a/win32/include/spidermonkey/js/Value.h +++ /dev/null @@ -1,1509 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JS::Value implementation. */ - -#ifndef js_Value_h -#define js_Value_h - -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/Likely.h" - -#include /* for std::numeric_limits */ - -#include "js-config.h" -#include "jstypes.h" - -#include "js/GCAPI.h" -#include "js/RootingAPI.h" -#include "js/Utility.h" - -namespace JS { class Value; } - -/* JS::Value can store a full int32_t. */ -#define JSVAL_INT_BITS 32 -#define JSVAL_INT_MIN ((int32_t)0x80000000) -#define JSVAL_INT_MAX ((int32_t)0x7fffffff) - -#if defined(JS_PUNBOX64) -# define JSVAL_TAG_SHIFT 47 -#endif - -// Use enums so that printing a JS::Value in the debugger shows nice -// symbolic type tags. - -#if defined(_MSC_VER) -# define JS_ENUM_HEADER(id, type) enum id : type -# define JS_ENUM_FOOTER(id) -#else -# define JS_ENUM_HEADER(id, type) enum id -# define JS_ENUM_FOOTER(id) __attribute__((packed)) -#endif - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueType, uint8_t) -{ - JSVAL_TYPE_DOUBLE = 0x00, - JSVAL_TYPE_INT32 = 0x01, - JSVAL_TYPE_UNDEFINED = 0x02, - JSVAL_TYPE_BOOLEAN = 0x03, - JSVAL_TYPE_MAGIC = 0x04, - JSVAL_TYPE_STRING = 0x05, - JSVAL_TYPE_SYMBOL = 0x06, - JSVAL_TYPE_PRIVATE_GCTHING = 0x07, - JSVAL_TYPE_NULL = 0x08, - JSVAL_TYPE_OBJECT = 0x0c, - - /* These never appear in a jsval; they are only provided as an out-of-band value. */ - JSVAL_TYPE_UNKNOWN = 0x20, - JSVAL_TYPE_MISSING = 0x21 -} JS_ENUM_FOOTER(JSValueType); - -static_assert(sizeof(JSValueType) == 1, - "compiler typed enum support is apparently buggy"); - -#if defined(JS_NUNBOX32) - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueTag, uint32_t) -{ - JSVAL_TAG_CLEAR = 0xFFFFFF80, - JSVAL_TAG_INT32 = JSVAL_TAG_CLEAR | JSVAL_TYPE_INT32, - JSVAL_TAG_UNDEFINED = JSVAL_TAG_CLEAR | JSVAL_TYPE_UNDEFINED, - JSVAL_TAG_STRING = JSVAL_TAG_CLEAR | JSVAL_TYPE_STRING, - JSVAL_TAG_SYMBOL = JSVAL_TAG_CLEAR | JSVAL_TYPE_SYMBOL, - JSVAL_TAG_BOOLEAN = JSVAL_TAG_CLEAR | JSVAL_TYPE_BOOLEAN, - JSVAL_TAG_MAGIC = JSVAL_TAG_CLEAR | JSVAL_TYPE_MAGIC, - JSVAL_TAG_NULL = JSVAL_TAG_CLEAR | JSVAL_TYPE_NULL, - JSVAL_TAG_OBJECT = JSVAL_TAG_CLEAR | JSVAL_TYPE_OBJECT, - JSVAL_TAG_PRIVATE_GCTHING = JSVAL_TAG_CLEAR | JSVAL_TYPE_PRIVATE_GCTHING -} JS_ENUM_FOOTER(JSValueTag); - -static_assert(sizeof(JSValueTag) == sizeof(uint32_t), - "compiler typed enum support is apparently buggy"); - -#elif defined(JS_PUNBOX64) - -/* Remember to propagate changes to the C defines below. */ -JS_ENUM_HEADER(JSValueTag, uint32_t) -{ - JSVAL_TAG_MAX_DOUBLE = 0x1FFF0, - JSVAL_TAG_INT32 = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_INT32, - JSVAL_TAG_UNDEFINED = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_UNDEFINED, - JSVAL_TAG_STRING = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_STRING, - JSVAL_TAG_SYMBOL = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_SYMBOL, - JSVAL_TAG_BOOLEAN = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_BOOLEAN, - JSVAL_TAG_MAGIC = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_MAGIC, - JSVAL_TAG_NULL = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_NULL, - JSVAL_TAG_OBJECT = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_OBJECT, - JSVAL_TAG_PRIVATE_GCTHING = JSVAL_TAG_MAX_DOUBLE | JSVAL_TYPE_PRIVATE_GCTHING -} JS_ENUM_FOOTER(JSValueTag); - -static_assert(sizeof(JSValueTag) == sizeof(uint32_t), - "compiler typed enum support is apparently buggy"); - -JS_ENUM_HEADER(JSValueShiftedTag, uint64_t) -{ - JSVAL_SHIFTED_TAG_MAX_DOUBLE = ((((uint64_t)JSVAL_TAG_MAX_DOUBLE) << JSVAL_TAG_SHIFT) | 0xFFFFFFFF), - JSVAL_SHIFTED_TAG_INT32 = (((uint64_t)JSVAL_TAG_INT32) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_UNDEFINED = (((uint64_t)JSVAL_TAG_UNDEFINED) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_STRING = (((uint64_t)JSVAL_TAG_STRING) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_SYMBOL = (((uint64_t)JSVAL_TAG_SYMBOL) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_BOOLEAN = (((uint64_t)JSVAL_TAG_BOOLEAN) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_MAGIC = (((uint64_t)JSVAL_TAG_MAGIC) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_NULL = (((uint64_t)JSVAL_TAG_NULL) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_OBJECT = (((uint64_t)JSVAL_TAG_OBJECT) << JSVAL_TAG_SHIFT), - JSVAL_SHIFTED_TAG_PRIVATE_GCTHING = (((uint64_t)JSVAL_TAG_PRIVATE_GCTHING) << JSVAL_TAG_SHIFT) -} JS_ENUM_FOOTER(JSValueShiftedTag); - -static_assert(sizeof(JSValueShiftedTag) == sizeof(uint64_t), - "compiler typed enum support is apparently buggy"); - -#endif - -/* - * All our supported compilers implement C++11 |enum Foo : T| syntax, so don't - * expose these macros. (This macro exists *only* because gcc bug 51242 - * makes bit-fields of - * typed enums trigger a warning that can't be turned off. Don't expose it - * beyond this file!) - */ -#undef JS_ENUM_HEADER -#undef JS_ENUM_FOOTER - -#if defined(JS_NUNBOX32) - -#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_CLEAR | (type))) - -#define JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET JSVAL_TAG_NULL -#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT -#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32 -#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING - -#elif defined(JS_PUNBOX64) - -#define JSVAL_PAYLOAD_MASK 0x00007FFFFFFFFFFFLL -#define JSVAL_TAG_MASK 0xFFFF800000000000LL -#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_MAX_DOUBLE | (type))) -#define JSVAL_TYPE_TO_SHIFTED_TAG(type) (((uint64_t)JSVAL_TYPE_TO_TAG(type)) << JSVAL_TAG_SHIFT) - -#define JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET JSVAL_TAG_NULL -#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT -#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32 -#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING - -#define JSVAL_LOWER_INCL_SHIFTED_TAG_OF_OBJ_OR_NULL_SET JSVAL_SHIFTED_TAG_NULL -#define JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET JSVAL_SHIFTED_TAG_OBJECT -#define JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET JSVAL_SHIFTED_TAG_UNDEFINED -#define JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET JSVAL_SHIFTED_TAG_STRING - -#endif /* JS_PUNBOX64 */ - -typedef enum JSWhyMagic -{ - /** a hole in a native object's elements */ - JS_ELEMENTS_HOLE, - - /** there is not a pending iterator value */ - JS_NO_ITER_VALUE, - - /** exception value thrown when closing a generator */ - JS_GENERATOR_CLOSING, - - /** compiler sentinel value */ - JS_NO_CONSTANT, - - /** used in debug builds to catch tracing errors */ - JS_THIS_POISON, - - /** used in debug builds to catch tracing errors */ - JS_ARG_POISON, - - /** an empty subnode in the AST serializer */ - JS_SERIALIZE_NO_NODE, - - /** lazy arguments value on the stack */ - JS_LAZY_ARGUMENTS, - - /** optimized-away 'arguments' value */ - JS_OPTIMIZED_ARGUMENTS, - - /** magic value passed to natives to indicate construction */ - JS_IS_CONSTRUCTING, - - /** value of static block object slot */ - JS_BLOCK_NEEDS_CLONE, - - /** see class js::HashableValue */ - JS_HASH_KEY_EMPTY, - - /** error while running Ion code */ - JS_ION_ERROR, - - /** missing recover instruction result */ - JS_ION_BAILOUT, - - /** optimized out slot */ - JS_OPTIMIZED_OUT, - - /** uninitialized lexical bindings that produce ReferenceError on touch. */ - JS_UNINITIALIZED_LEXICAL, - - /** for local use */ - JS_GENERIC_MAGIC, - - JS_WHY_MAGIC_COUNT -} JSWhyMagic; - -namespace JS { - -static inline constexpr JS::Value UndefinedValue(); -static inline JS::Value PoisonedObjectValue(JSObject* obj); - -namespace detail { - -constexpr int CanonicalizedNaNSignBit = 0; -constexpr uint64_t CanonicalizedNaNSignificand = 0x8000000000000ULL; - -constexpr uint64_t CanonicalizedNaNBits = - mozilla::SpecificNaNBits::value; - -} // namespace detail - -/** - * Returns a generic quiet NaN value, with all payload bits set to zero. - * - * Among other properties, this NaN's bit pattern conforms to JS::Value's - * bit pattern restrictions. - */ -static MOZ_ALWAYS_INLINE double -GenericNaN() -{ - return mozilla::SpecificNaN(detail::CanonicalizedNaNSignBit, - detail::CanonicalizedNaNSignificand); -} - -/* MSVC with PGO miscompiles this function. */ -#if defined(_MSC_VER) -# pragma optimize("g", off) -#endif -static inline double -CanonicalizeNaN(double d) -{ - if (MOZ_UNLIKELY(mozilla::IsNaN(d))) - return GenericNaN(); - return d; -} -#if defined(_MSC_VER) -# pragma optimize("", on) -#endif - -/** - * JS::Value is the interface for a single JavaScript Engine value. A few - * general notes on JS::Value: - * - * - JS::Value has setX() and isX() members for X in - * - * { Int32, Double, String, Symbol, Boolean, Undefined, Null, Object, Magic } - * - * JS::Value also contains toX() for each of the non-singleton types. - * - * - Magic is a singleton type whose payload contains either a JSWhyMagic "reason" for - * the magic value or a uint32_t value. By providing JSWhyMagic values when - * creating and checking for magic values, it is possible to assert, at - * runtime, that only magic values with the expected reason flow through a - * particular value. For example, if cx->exception has a magic value, the - * reason must be JS_GENERATOR_CLOSING. - * - * - The JS::Value operations are preferred. The JSVAL_* operations remain for - * compatibility; they may be removed at some point. These operations mostly - * provide similar functionality. But there are a few key differences. One - * is that JS::Value gives null a separate type. - * Also, to help prevent mistakenly boxing a nullable JSObject* as an object, - * Value::setObject takes a JSObject&. (Conversely, Value::toObject returns a - * JSObject&.) A convenience member Value::setObjectOrNull is provided. - * - * - JSVAL_VOID is the same as the singleton value of the Undefined type. - * - * - Note that JS::Value is 8 bytes on 32 and 64-bit architectures. Thus, on - * 32-bit user code should avoid copying jsval/JS::Value as much as possible, - * preferring to pass by const Value&. - */ -class MOZ_NON_PARAM alignas(8) Value -{ - public: -#if defined(JS_NUNBOX32) - using PayloadType = uint32_t; -#elif defined(JS_PUNBOX64) - using PayloadType = uint64_t; -#endif - - /* - * N.B. the default constructor leaves Value unitialized. Adding a default - * constructor prevents Value from being stored in a union. - */ - Value() = default; - Value(const Value& v) = default; - - /** - * Returns false if creating a NumberValue containing the given type would - * be lossy, true otherwise. - */ - template - static bool isNumberRepresentable(const T t) { - return T(double(t)) == t; - } - - /*** Mutators ***/ - - void setNull() { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_NULL, 0); - } - - void setUndefined() { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_UNDEFINED, 0); - } - - void setInt32(int32_t i) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_INT32, uint32_t(i)); - } - - int32_t& getInt32Ref() { - MOZ_ASSERT(isInt32()); - return data.s.payload.i32; - } - - void setDouble(double d) { - // Don't assign to data.asDouble to fix a miscompilation with - // GCC 5.2.1 and 5.3.1. See bug 1312488. - data = layout(d); - MOZ_ASSERT(isDouble()); - } - - void setNaN() { - setDouble(GenericNaN()); - } - - double& getDoubleRef() { - MOZ_ASSERT(isDouble()); - return data.asDouble; - } - - void setString(JSString* str) { - MOZ_ASSERT(uintptr_t(str) > 0x1000); - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_STRING, PayloadType(str)); - } - - void setSymbol(JS::Symbol* sym) { - MOZ_ASSERT(uintptr_t(sym) > 0x1000); - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_SYMBOL, PayloadType(sym)); - } - - void setObject(JSObject& obj) { - MOZ_ASSERT(uintptr_t(&obj) > 0x1000 || uintptr_t(&obj) == 0x48); -#if defined(JS_PUNBOX64) - // VisualStudio cannot contain parenthesized C++ style cast and shift - // inside decltype in template parameter: - // AssertionConditionType> 1))> - // It throws syntax error. - MOZ_ASSERT((((uintptr_t)&obj) >> JSVAL_TAG_SHIFT) == 0); -#endif - setObjectNoCheck(&obj); - } - - private: - void setObjectNoCheck(JSObject* obj) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_OBJECT, PayloadType(obj)); - } - - friend inline Value PoisonedObjectValue(JSObject* obj); - - public: - void setBoolean(bool b) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_BOOLEAN, uint32_t(b)); - } - - void setMagic(JSWhyMagic why) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_MAGIC, uint32_t(why)); - } - - void setMagicUint32(uint32_t payload) { - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_MAGIC, payload); - } - - bool setNumber(uint32_t ui) { - if (ui > JSVAL_INT_MAX) { - setDouble((double)ui); - return false; - } else { - setInt32((int32_t)ui); - return true; - } - } - - bool setNumber(double d) { - int32_t i; - if (mozilla::NumberIsInt32(d, &i)) { - setInt32(i); - return true; - } - - setDouble(d); - return false; - } - - void setObjectOrNull(JSObject* arg) { - if (arg) - setObject(*arg); - else - setNull(); - } - - void swap(Value& rhs) { - uint64_t tmp = rhs.data.asBits; - rhs.data.asBits = data.asBits; - data.asBits = tmp; - } - - private: - JSValueTag toTag() const { -#if defined(JS_NUNBOX32) - return data.s.tag; -#elif defined(JS_PUNBOX64) - return JSValueTag(data.asBits >> JSVAL_TAG_SHIFT); -#endif - } - - public: - /*** JIT-only interfaces to interact with and create raw Values ***/ -#if defined(JS_NUNBOX32) - PayloadType toNunboxPayload() const { - return data.s.payload.i32; - } - - JSValueTag toNunboxTag() const { - return data.s.tag; - } -#elif defined(JS_PUNBOX64) - const void* bitsAsPunboxPointer() const { - return reinterpret_cast(data.asBits); - } -#endif - - /*** Value type queries ***/ - - /* - * N.B. GCC, in some but not all cases, chooses to emit signed comparison - * of JSValueTag even though its underlying type has been forced to be - * uint32_t. Thus, all comparisons should explicitly cast operands to - * uint32_t. - */ - - bool isUndefined() const { -#if defined(JS_NUNBOX32) - return toTag() == JSVAL_TAG_UNDEFINED; -#elif defined(JS_PUNBOX64) - return data.asBits == JSVAL_SHIFTED_TAG_UNDEFINED; -#endif - } - - bool isNull() const { -#if defined(JS_NUNBOX32) - return toTag() == JSVAL_TAG_NULL; -#elif defined(JS_PUNBOX64) - return data.asBits == JSVAL_SHIFTED_TAG_NULL; -#endif - } - - bool isNullOrUndefined() const { - return isNull() || isUndefined(); - } - - bool isInt32() const { - return toTag() == JSVAL_TAG_INT32; - } - - bool isInt32(int32_t i32) const { - return data.asBits == bitsFromTagAndPayload(JSVAL_TAG_INT32, uint32_t(i32)); - } - - bool isDouble() const { -#if defined(JS_NUNBOX32) - return uint32_t(toTag()) <= uint32_t(JSVAL_TAG_CLEAR); -#elif defined(JS_PUNBOX64) - return (data.asBits | mozilla::DoubleTypeTraits::kSignBit) <= JSVAL_SHIFTED_TAG_MAX_DOUBLE; -#endif - } - - bool isNumber() const { -#if defined(JS_NUNBOX32) - MOZ_ASSERT(toTag() != JSVAL_TAG_CLEAR); - return uint32_t(toTag()) <= uint32_t(JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET); -#elif defined(JS_PUNBOX64) - return data.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET; -#endif - } - - bool isString() const { - return toTag() == JSVAL_TAG_STRING; - } - - bool isSymbol() const { - return toTag() == JSVAL_TAG_SYMBOL; - } - - bool isObject() const { -#if defined(JS_NUNBOX32) - return toTag() == JSVAL_TAG_OBJECT; -#elif defined(JS_PUNBOX64) - MOZ_ASSERT((data.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_TAG_OBJECT); - return data.asBits >= JSVAL_SHIFTED_TAG_OBJECT; -#endif - } - - bool isPrimitive() const { -#if defined(JS_NUNBOX32) - return uint32_t(toTag()) < uint32_t(JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET); -#elif defined(JS_PUNBOX64) - return data.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET; -#endif - } - - bool isObjectOrNull() const { - MOZ_ASSERT(uint32_t(toTag()) <= uint32_t(JSVAL_TAG_OBJECT)); -#if defined(JS_NUNBOX32) - return uint32_t(toTag()) >= uint32_t(JSVAL_LOWER_INCL_TAG_OF_OBJ_OR_NULL_SET); -#elif defined(JS_PUNBOX64) - return data.asBits >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_OBJ_OR_NULL_SET; -#endif - } - - bool isGCThing() const { -#if defined(JS_NUNBOX32) - /* gcc sometimes generates signed < without explicit casts. */ - return uint32_t(toTag()) >= uint32_t(JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET); -#elif defined(JS_PUNBOX64) - return data.asBits >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET; -#endif - } - - bool isBoolean() const { - return toTag() == JSVAL_TAG_BOOLEAN; - } - - bool isTrue() const { - return data.asBits == bitsFromTagAndPayload(JSVAL_TAG_BOOLEAN, uint32_t(true)); - } - - bool isFalse() const { - return data.asBits == bitsFromTagAndPayload(JSVAL_TAG_BOOLEAN, uint32_t(false)); - } - - bool isMagic() const { - return toTag() == JSVAL_TAG_MAGIC; - } - - bool isMagic(JSWhyMagic why) const { - MOZ_ASSERT_IF(isMagic(), data.s.payload.why == why); - return isMagic(); - } - - bool isMarkable() const { - return isGCThing() && !isNull(); - } - - JS::TraceKind traceKind() const { - MOZ_ASSERT(isMarkable()); - static_assert((JSVAL_TAG_STRING & 0x03) == size_t(JS::TraceKind::String), - "Value type tags must correspond with JS::TraceKinds."); - static_assert((JSVAL_TAG_SYMBOL & 0x03) == size_t(JS::TraceKind::Symbol), - "Value type tags must correspond with JS::TraceKinds."); - static_assert((JSVAL_TAG_OBJECT & 0x03) == size_t(JS::TraceKind::Object), - "Value type tags must correspond with JS::TraceKinds."); - if (MOZ_UNLIKELY(isPrivateGCThing())) - return JS::GCThingTraceKind(toGCThing()); - return JS::TraceKind(toTag() & 0x03); - } - - JSWhyMagic whyMagic() const { - MOZ_ASSERT(isMagic()); - return data.s.payload.why; - } - - uint32_t magicUint32() const { - MOZ_ASSERT(isMagic()); - return data.s.payload.u32; - } - - /*** Comparison ***/ - - bool operator==(const Value& rhs) const { - return data.asBits == rhs.data.asBits; - } - - bool operator!=(const Value& rhs) const { - return data.asBits != rhs.data.asBits; - } - - friend inline bool SameType(const Value& lhs, const Value& rhs); - - /*** Extract the value's typed payload ***/ - - int32_t toInt32() const { - MOZ_ASSERT(isInt32()); -#if defined(JS_NUNBOX32) - return data.s.payload.i32; -#elif defined(JS_PUNBOX64) - return int32_t(data.asBits); -#endif - } - - double toDouble() const { - MOZ_ASSERT(isDouble()); - return data.asDouble; - } - - double toNumber() const { - MOZ_ASSERT(isNumber()); - return isDouble() ? toDouble() : double(toInt32()); - } - - JSString* toString() const { - MOZ_ASSERT(isString()); -#if defined(JS_NUNBOX32) - return data.s.payload.str; -#elif defined(JS_PUNBOX64) - return reinterpret_cast(data.asBits & JSVAL_PAYLOAD_MASK); -#endif - } - - JS::Symbol* toSymbol() const { - MOZ_ASSERT(isSymbol()); -#if defined(JS_NUNBOX32) - return data.s.payload.sym; -#elif defined(JS_PUNBOX64) - return reinterpret_cast(data.asBits & JSVAL_PAYLOAD_MASK); -#endif - } - - JSObject& toObject() const { - MOZ_ASSERT(isObject()); -#if defined(JS_NUNBOX32) - return *data.s.payload.obj; -#elif defined(JS_PUNBOX64) - return *toObjectOrNull(); -#endif - } - - JSObject* toObjectOrNull() const { - MOZ_ASSERT(isObjectOrNull()); -#if defined(JS_NUNBOX32) - return data.s.payload.obj; -#elif defined(JS_PUNBOX64) - uint64_t ptrBits = data.asBits & JSVAL_PAYLOAD_MASK; - MOZ_ASSERT((ptrBits & 0x7) == 0); - return reinterpret_cast(ptrBits); -#endif - } - - js::gc::Cell* toGCThing() const { - MOZ_ASSERT(isGCThing()); -#if defined(JS_NUNBOX32) - return data.s.payload.cell; -#elif defined(JS_PUNBOX64) - uint64_t ptrBits = data.asBits & JSVAL_PAYLOAD_MASK; - MOZ_ASSERT((ptrBits & 0x7) == 0); - return reinterpret_cast(ptrBits); -#endif - } - - js::gc::Cell* toMarkablePointer() const { - MOZ_ASSERT(isMarkable()); - return toGCThing(); - } - - GCCellPtr toGCCellPtr() const { - return GCCellPtr(toGCThing(), traceKind()); - } - - bool toBoolean() const { - MOZ_ASSERT(isBoolean()); -#if defined(JS_NUNBOX32) - return bool(data.s.payload.boo); -#elif defined(JS_PUNBOX64) - return bool(data.asBits & JSVAL_PAYLOAD_MASK); -#endif - } - - uint32_t payloadAsRawUint32() const { - MOZ_ASSERT(!isDouble()); - return data.s.payload.u32; - } - - uint64_t asRawBits() const { - return data.asBits; - } - - JSValueType extractNonDoubleType() const { - uint32_t type = toTag() & 0xF; - MOZ_ASSERT(type > JSVAL_TYPE_DOUBLE); - return JSValueType(type); - } - - /* - * Private API - * - * Private setters/getters allow the caller to read/write arbitrary types - * that fit in the 64-bit payload. It is the caller's responsibility, after - * storing to a value with setPrivateX to read only using getPrivateX. - * Privates values are given a type which ensures they are not marked. - */ - - void setPrivate(void* ptr) { - MOZ_ASSERT((uintptr_t(ptr) & 1) == 0); -#if defined(JS_NUNBOX32) - data.s.tag = JSValueTag(0); - data.s.payload.ptr = ptr; -#elif defined(JS_PUNBOX64) - data.asBits = uintptr_t(ptr) >> 1; -#endif - MOZ_ASSERT(isDouble()); - } - - void* toPrivate() const { - MOZ_ASSERT(isDouble()); -#if defined(JS_NUNBOX32) - return data.s.payload.ptr; -#elif defined(JS_PUNBOX64) - MOZ_ASSERT((data.asBits & 0x8000000000000000ULL) == 0); - return reinterpret_cast(data.asBits << 1); -#endif - } - - void setPrivateUint32(uint32_t ui) { - MOZ_ASSERT(uint32_t(int32_t(ui)) == ui); - setInt32(int32_t(ui)); - } - - uint32_t toPrivateUint32() const { - return uint32_t(toInt32()); - } - - /* - * Private GC Thing API - * - * Non-JSObject, JSString, and JS::Symbol cells may be put into the 64-bit - * payload as private GC things. Such Values are considered isMarkable() - * and isGCThing(), and as such, automatically marked. Their traceKind() - * is gotten via their cells. - */ - - void setPrivateGCThing(js::gc::Cell* cell) { - MOZ_ASSERT(JS::GCThingTraceKind(cell) != JS::TraceKind::String, - "Private GC thing Values must not be strings. Make a StringValue instead."); - MOZ_ASSERT(JS::GCThingTraceKind(cell) != JS::TraceKind::Symbol, - "Private GC thing Values must not be symbols. Make a SymbolValue instead."); - MOZ_ASSERT(JS::GCThingTraceKind(cell) != JS::TraceKind::Object, - "Private GC thing Values must not be objects. Make an ObjectValue instead."); - - MOZ_ASSERT(uintptr_t(cell) > 0x1000); -#if defined(JS_PUNBOX64) - // VisualStudio cannot contain parenthesized C++ style cast and shift - // inside decltype in template parameter: - // AssertionConditionType> 1))> - // It throws syntax error. - MOZ_ASSERT((((uintptr_t)cell) >> JSVAL_TAG_SHIFT) == 0); -#endif - data.asBits = bitsFromTagAndPayload(JSVAL_TAG_PRIVATE_GCTHING, PayloadType(cell)); - } - - bool isPrivateGCThing() const { - return toTag() == JSVAL_TAG_PRIVATE_GCTHING; - } - - const size_t* payloadWord() const { -#if defined(JS_NUNBOX32) - return &data.s.payload.word; -#elif defined(JS_PUNBOX64) - return &data.asWord; -#endif - } - - const uintptr_t* payloadUIntPtr() const { -#if defined(JS_NUNBOX32) - return &data.s.payload.uintptr; -#elif defined(JS_PUNBOX64) - return &data.asUIntPtr; -#endif - } - -#if !defined(_MSC_VER) && !defined(__sparc) - // Value must be POD so that MSVC will pass it by value and not in memory - // (bug 689101); the same is true for SPARC as well (bug 737344). More - // precisely, we don't want Value return values compiled as out params. - private: -#endif - -#if MOZ_LITTLE_ENDIAN -# if defined(JS_NUNBOX32) - union layout { - uint64_t asBits; - struct { - union { - int32_t i32; - uint32_t u32; - uint32_t boo; // Don't use |bool| -- it must be four bytes. - JSString* str; - JS::Symbol* sym; - JSObject* obj; - js::gc::Cell* cell; - void* ptr; - JSWhyMagic why; - size_t word; - uintptr_t uintptr; - } payload; - JSValueTag tag; - } s; - double asDouble; - void* asPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# elif defined(JS_PUNBOX64) - union layout { - uint64_t asBits; -#if !defined(_WIN64) - /* MSVC does not pack these correctly :-( */ - struct { - uint64_t payload47 : 47; - JSValueTag tag : 17; - } debugView; -#endif - struct { - union { - int32_t i32; - uint32_t u32; - JSWhyMagic why; - } payload; - } s; - double asDouble; - void* asPtr; - size_t asWord; - uintptr_t asUIntPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# endif /* JS_PUNBOX64 */ -#else /* MOZ_LITTLE_ENDIAN */ -# if defined(JS_NUNBOX32) - union layout { - uint64_t asBits; - struct { - JSValueTag tag; - union { - int32_t i32; - uint32_t u32; - uint32_t boo; // Don't use |bool| -- it must be four bytes. - JSString* str; - JS::Symbol* sym; - JSObject* obj; - js::gc::Cell* cell; - void* ptr; - JSWhyMagic why; - size_t word; - uintptr_t uintptr; - } payload; - } s; - double asDouble; - void* asPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# elif defined(JS_PUNBOX64) - union layout { - uint64_t asBits; - struct { - JSValueTag tag : 17; - uint64_t payload47 : 47; - } debugView; - struct { - uint32_t padding; - union { - int32_t i32; - uint32_t u32; - JSWhyMagic why; - } payload; - } s; - double asDouble; - void* asPtr; - size_t asWord; - uintptr_t asUIntPtr; - - layout() = default; - explicit constexpr layout(uint64_t bits) : asBits(bits) {} - explicit constexpr layout(double d) : asDouble(d) {} - } data; -# endif /* JS_PUNBOX64 */ -#endif /* MOZ_LITTLE_ENDIAN */ - - private: - explicit constexpr Value(uint64_t asBits) : data(asBits) {} - explicit constexpr Value(double d) : data(d) {} - - void staticAssertions() { - JS_STATIC_ASSERT(sizeof(JSValueType) == 1); - JS_STATIC_ASSERT(sizeof(JSValueTag) == 4); - JS_STATIC_ASSERT(sizeof(JSWhyMagic) <= 4); - JS_STATIC_ASSERT(sizeof(Value) == 8); - } - - friend constexpr Value JS::UndefinedValue(); - - public: - static constexpr uint64_t - bitsFromTagAndPayload(JSValueTag tag, PayloadType payload) - { -#if defined(JS_NUNBOX32) - return (uint64_t(uint32_t(tag)) << 32) | payload; -#elif defined(JS_PUNBOX64) - return (uint64_t(uint32_t(tag)) << JSVAL_TAG_SHIFT) | payload; -#endif - } - - static constexpr Value - fromTagAndPayload(JSValueTag tag, PayloadType payload) - { - return fromRawBits(bitsFromTagAndPayload(tag, payload)); - } - - static constexpr Value - fromRawBits(uint64_t asBits) { - return Value(asBits); - } - - static constexpr Value - fromInt32(int32_t i) { - return fromTagAndPayload(JSVAL_TAG_INT32, uint32_t(i)); - } - - static constexpr Value - fromDouble(double d) { - return Value(d); - } -} JS_HAZ_GC_POINTER; - -static_assert(sizeof(Value) == 8, "Value size must leave three tag bits, be a binary power, and is ubiquitously depended upon everywhere"); - -inline bool -IsOptimizedPlaceholderMagicValue(const Value& v) -{ - if (v.isMagic()) { - MOZ_ASSERT(v.whyMagic() == JS_OPTIMIZED_ARGUMENTS || v.whyMagic() == JS_OPTIMIZED_OUT); - return true; - } - return false; -} - -static MOZ_ALWAYS_INLINE void -ExposeValueToActiveJS(const Value& v) -{ - if (v.isMarkable()) - js::gc::ExposeGCThingToActiveJS(GCCellPtr(v)); -} - -/************************************************************************/ - -static inline Value -NullValue() -{ - Value v; - v.setNull(); - return v; -} - -static inline constexpr Value -UndefinedValue() -{ - return Value::fromTagAndPayload(JSVAL_TAG_UNDEFINED, 0); -} - -static inline constexpr Value -Int32Value(int32_t i32) -{ - return Value::fromInt32(i32); -} - -static inline Value -DoubleValue(double dbl) -{ - Value v; - v.setDouble(dbl); - return v; -} - -static inline Value -CanonicalizedDoubleValue(double d) -{ - return MOZ_UNLIKELY(mozilla::IsNaN(d)) - ? Value::fromRawBits(detail::CanonicalizedNaNBits) - : Value::fromDouble(d); -} - -static inline bool -IsCanonicalized(double d) -{ - if (mozilla::IsInfinite(d) || mozilla::IsFinite(d)) - return true; - - uint64_t bits; - mozilla::BitwiseCast(d, &bits); - return (bits & ~mozilla::DoubleTypeTraits::kSignBit) == detail::CanonicalizedNaNBits; -} - -static inline Value -DoubleNaNValue() -{ - Value v; - v.setNaN(); - return v; -} - -static inline Value -Float32Value(float f) -{ - Value v; - v.setDouble(f); - return v; -} - -static inline Value -StringValue(JSString* str) -{ - Value v; - v.setString(str); - return v; -} - -static inline Value -SymbolValue(JS::Symbol* sym) -{ - Value v; - v.setSymbol(sym); - return v; -} - -static inline Value -BooleanValue(bool boo) -{ - Value v; - v.setBoolean(boo); - return v; -} - -static inline Value -TrueValue() -{ - Value v; - v.setBoolean(true); - return v; -} - -static inline Value -FalseValue() -{ - Value v; - v.setBoolean(false); - return v; -} - -static inline Value -ObjectValue(JSObject& obj) -{ - Value v; - v.setObject(obj); - return v; -} - -static inline Value -ObjectValueCrashOnTouch() -{ - Value v; - v.setObject(*reinterpret_cast(0x48)); - return v; -} - -static inline Value -MagicValue(JSWhyMagic why) -{ - Value v; - v.setMagic(why); - return v; -} - -static inline Value -MagicValueUint32(uint32_t payload) -{ - Value v; - v.setMagicUint32(payload); - return v; -} - -static inline Value -NumberValue(float f) -{ - Value v; - v.setNumber(f); - return v; -} - -static inline Value -NumberValue(double dbl) -{ - Value v; - v.setNumber(dbl); - return v; -} - -static inline Value -NumberValue(int8_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(uint8_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(int16_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(uint16_t i) -{ - return Int32Value(i); -} - -static inline Value -NumberValue(int32_t i) -{ - return Int32Value(i); -} - -static inline constexpr Value -NumberValue(uint32_t i) -{ - return i <= JSVAL_INT_MAX - ? Int32Value(int32_t(i)) - : Value::fromDouble(double(i)); -} - -namespace detail { - -template -class MakeNumberValue -{ - public: - template - static inline Value create(const T t) - { - Value v; - if (JSVAL_INT_MIN <= t && t <= JSVAL_INT_MAX) - v.setInt32(int32_t(t)); - else - v.setDouble(double(t)); - return v; - } -}; - -template <> -class MakeNumberValue -{ - public: - template - static inline Value create(const T t) - { - Value v; - if (t <= JSVAL_INT_MAX) - v.setInt32(int32_t(t)); - else - v.setDouble(double(t)); - return v; - } -}; - -} // namespace detail - -template -static inline Value -NumberValue(const T t) -{ - MOZ_ASSERT(Value::isNumberRepresentable(t), "value creation would be lossy"); - return detail::MakeNumberValue::is_signed>::create(t); -} - -static inline Value -ObjectOrNullValue(JSObject* obj) -{ - Value v; - v.setObjectOrNull(obj); - return v; -} - -static inline Value -PrivateValue(void* ptr) -{ - Value v; - v.setPrivate(ptr); - return v; -} - -static inline Value -PrivateUint32Value(uint32_t ui) -{ - Value v; - v.setPrivateUint32(ui); - return v; -} - -static inline Value -PrivateGCThingValue(js::gc::Cell* cell) -{ - Value v; - v.setPrivateGCThing(cell); - return v; -} - -static inline Value -PoisonedObjectValue(JSObject* obj) -{ - Value v; - v.setObjectNoCheck(obj); - return v; -} - -inline bool -SameType(const Value& lhs, const Value& rhs) -{ -#if defined(JS_NUNBOX32) - JSValueTag ltag = lhs.toTag(), rtag = rhs.toTag(); - return ltag == rtag || (ltag < JSVAL_TAG_CLEAR && rtag < JSVAL_TAG_CLEAR); -#elif defined(JS_PUNBOX64) - return (lhs.isDouble() && rhs.isDouble()) || - (((lhs.data.asBits ^ rhs.data.asBits) & 0xFFFF800000000000ULL) == 0); -#endif -} - -} // namespace JS - -/************************************************************************/ - -namespace JS { -JS_PUBLIC_API(void) HeapValuePostBarrier(Value* valuep, const Value& prev, const Value& next); - -template <> -struct GCPolicy -{ - static Value initial() { return UndefinedValue(); } - static void trace(JSTracer* trc, Value* v, const char* name) { - js::UnsafeTraceManuallyBarrieredEdge(trc, v, name); - } - static bool isTenured(const Value& thing) { - return !thing.isGCThing() || !IsInsideNursery(thing.toGCThing()); - } -}; - -} // namespace JS - -namespace js { - -template <> -struct BarrierMethods -{ - static gc::Cell* asGCThingOrNull(const JS::Value& v) { - return v.isMarkable() ? v.toGCThing() : nullptr; - } - static void postBarrier(JS::Value* v, const JS::Value& prev, const JS::Value& next) { - JS::HeapValuePostBarrier(v, prev, next); - } - static void exposeToJS(const JS::Value& v) { - JS::ExposeValueToActiveJS(v); - } -}; - -template class MutableValueOperations; - -/** - * A class designed for CRTP use in implementing the non-mutating parts of the - * Value interface in Value-like classes. Outer must be a class inheriting - * ValueOperations with a visible get() method returning a const - * reference to the Value abstracted by Outer. - */ -template -class ValueOperations -{ - friend class MutableValueOperations; - - const JS::Value& value() const { return static_cast(this)->get(); } - - public: - bool isUndefined() const { return value().isUndefined(); } - bool isNull() const { return value().isNull(); } - bool isBoolean() const { return value().isBoolean(); } - bool isTrue() const { return value().isTrue(); } - bool isFalse() const { return value().isFalse(); } - bool isNumber() const { return value().isNumber(); } - bool isInt32() const { return value().isInt32(); } - bool isInt32(int32_t i32) const { return value().isInt32(i32); } - bool isDouble() const { return value().isDouble(); } - bool isString() const { return value().isString(); } - bool isSymbol() const { return value().isSymbol(); } - bool isObject() const { return value().isObject(); } - bool isMagic() const { return value().isMagic(); } - bool isMagic(JSWhyMagic why) const { return value().isMagic(why); } - bool isMarkable() const { return value().isMarkable(); } - bool isPrimitive() const { return value().isPrimitive(); } - bool isGCThing() const { return value().isGCThing(); } - - bool isNullOrUndefined() const { return value().isNullOrUndefined(); } - bool isObjectOrNull() const { return value().isObjectOrNull(); } - - bool toBoolean() const { return value().toBoolean(); } - double toNumber() const { return value().toNumber(); } - int32_t toInt32() const { return value().toInt32(); } - double toDouble() const { return value().toDouble(); } - JSString* toString() const { return value().toString(); } - JS::Symbol* toSymbol() const { return value().toSymbol(); } - JSObject& toObject() const { return value().toObject(); } - JSObject* toObjectOrNull() const { return value().toObjectOrNull(); } - gc::Cell* toGCThing() const { return value().toGCThing(); } - JS::TraceKind traceKind() const { return value().traceKind(); } - void* toPrivate() const { return value().toPrivate(); } - uint32_t toPrivateUint32() const { return value().toPrivateUint32(); } - - uint64_t asRawBits() const { return value().asRawBits(); } - JSValueType extractNonDoubleType() const { return value().extractNonDoubleType(); } - - JSWhyMagic whyMagic() const { return value().whyMagic(); } - uint32_t magicUint32() const { return value().magicUint32(); } -}; - -/** - * A class designed for CRTP use in implementing all the mutating parts of the - * Value interface in Value-like classes. Outer must be a class inheriting - * MutableValueOperations with visible get() methods returning const and - * non-const references to the Value abstracted by Outer. - */ -template -class MutableValueOperations : public ValueOperations -{ - JS::Value& value() { return static_cast(this)->get(); } - - public: - void setNull() { value().setNull(); } - void setUndefined() { value().setUndefined(); } - void setInt32(int32_t i) { value().setInt32(i); } - void setDouble(double d) { value().setDouble(d); } - void setNaN() { setDouble(JS::GenericNaN()); } - void setBoolean(bool b) { value().setBoolean(b); } - void setMagic(JSWhyMagic why) { value().setMagic(why); } - bool setNumber(uint32_t ui) { return value().setNumber(ui); } - bool setNumber(double d) { return value().setNumber(d); } - void setString(JSString* str) { this->value().setString(str); } - void setSymbol(JS::Symbol* sym) { this->value().setSymbol(sym); } - void setObject(JSObject& obj) { this->value().setObject(obj); } - void setObjectOrNull(JSObject* arg) { this->value().setObjectOrNull(arg); } - void setPrivate(void* ptr) { this->value().setPrivate(ptr); } - void setPrivateUint32(uint32_t ui) { this->value().setPrivateUint32(ui); } - void setPrivateGCThing(js::gc::Cell* cell) { this->value().setPrivateGCThing(cell); } -}; - -/* - * Augment the generic Heap interface when T = Value with - * type-querying, value-extracting, and mutating operations. - */ -template <> -class HeapBase : public ValueOperations > -{ - typedef JS::Heap Outer; - - friend class ValueOperations; - - void setBarriered(const JS::Value& v) { - *static_cast*>(this) = v; - } - - public: - void setNull() { setBarriered(JS::NullValue()); } - void setUndefined() { setBarriered(JS::UndefinedValue()); } - void setInt32(int32_t i) { setBarriered(JS::Int32Value(i)); } - void setDouble(double d) { setBarriered(JS::DoubleValue(d)); } - void setNaN() { setDouble(JS::GenericNaN()); } - void setBoolean(bool b) { setBarriered(JS::BooleanValue(b)); } - void setMagic(JSWhyMagic why) { setBarriered(JS::MagicValue(why)); } - void setString(JSString* str) { setBarriered(JS::StringValue(str)); } - void setSymbol(JS::Symbol* sym) { setBarriered(JS::SymbolValue(sym)); } - void setObject(JSObject& obj) { setBarriered(JS::ObjectValue(obj)); } - void setPrivateGCThing(js::gc::Cell* cell) { setBarriered(JS::PrivateGCThingValue(cell)); } - - bool setNumber(uint32_t ui) { - if (ui > JSVAL_INT_MAX) { - setDouble((double)ui); - return false; - } else { - setInt32((int32_t)ui); - return true; - } - } - - bool setNumber(double d) { - int32_t i; - if (mozilla::NumberIsInt32(d, &i)) { - setInt32(i); - return true; - } - - setDouble(d); - return false; - } - - void setObjectOrNull(JSObject* arg) { - if (arg) - setObject(*arg); - else - setNull(); - } -}; - -template <> -class HandleBase : public ValueOperations > -{}; - -template <> -class MutableHandleBase : public MutableValueOperations > -{}; - -template <> -class RootedBase : public MutableValueOperations > -{}; - -template <> -class PersistentRootedBase : public MutableValueOperations> -{}; - -/* - * If the Value is a GC pointer type, convert to that type and call |f| with - * the pointer. If the Value is not a GC type, calls F::defaultValue. - */ -template -auto -DispatchTyped(F f, const JS::Value& val, Args&&... args) - -> decltype(f(static_cast(nullptr), mozilla::Forward(args)...)) -{ - if (val.isString()) - return f(val.toString(), mozilla::Forward(args)...); - if (val.isObject()) - return f(&val.toObject(), mozilla::Forward(args)...); - if (val.isSymbol()) - return f(val.toSymbol(), mozilla::Forward(args)...); - if (MOZ_UNLIKELY(val.isPrivateGCThing())) - return DispatchTyped(f, val.toGCCellPtr(), mozilla::Forward(args)...); - MOZ_ASSERT(!val.isMarkable()); - return F::defaultValue(val); -} - -template struct VoidDefaultAdaptor { static void defaultValue(const S&) {} }; -template struct IdentityDefaultAdaptor { static S defaultValue(const S& v) {return v;} }; -template struct BoolDefaultAdaptor { static bool defaultValue(const S&) { return v; } }; - -} // namespace js - -/************************************************************************/ - -namespace JS { - -extern JS_PUBLIC_DATA(const HandleValue) NullHandleValue; -extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; -extern JS_PUBLIC_DATA(const HandleValue) TrueHandleValue; -extern JS_PUBLIC_DATA(const HandleValue) FalseHandleValue; - -} // namespace JS - -#endif /* js_Value_h */ diff --git a/win32/include/spidermonkey/js/Vector.h b/win32/include/spidermonkey/js/Vector.h deleted file mode 100755 index 6fa63e93..00000000 --- a/win32/include/spidermonkey/js/Vector.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_Vector_h -#define js_Vector_h - -#include "mozilla/Vector.h" - -/* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4345) -#endif - -namespace js { - -class TempAllocPolicy; - -namespace detail { - -template -struct TypeIsGCThing : mozilla::FalseType -{}; - -// Uncomment this once we actually can assert it: -//template <> -//struct TypeIsGCThing : mozilla::TrueType -//{}; - -} // namespace detail - -template ::value>::Type - > -using Vector = mozilla::Vector; - -} // namespace js - -#endif /* js_Vector_h */ diff --git a/win32/include/spidermonkey/js/WeakMapPtr.h b/win32/include/spidermonkey/js/WeakMapPtr.h deleted file mode 100755 index 41860551..00000000 --- a/win32/include/spidermonkey/js/WeakMapPtr.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef js_WeakMapPtr_h -#define js_WeakMapPtr_h - -#include "jspubtd.h" - -#include "js/TypeDecls.h" - -namespace JS { - -// A wrapper around the internal C++ representation of SpiderMonkey WeakMaps, -// usable outside the engine. -// -// The supported template specializations are enumerated in WeakMapPtr.cpp. If -// you want to use this class for a different key/value combination, add it to -// the list and the compiler will generate the relevant machinery. -template -class JS_PUBLIC_API(WeakMapPtr) -{ - public: - WeakMapPtr() : ptr(nullptr) {} - bool init(JSContext* cx); - bool initialized() { return ptr != nullptr; } - void destroy(); - virtual ~WeakMapPtr() { MOZ_ASSERT(!initialized()); } - void trace(JSTracer* tracer); - - V lookup(const K& key); - bool put(JSContext* cx, const K& key, const V& value); - - private: - void* ptr; - - // WeakMapPtr is neither copyable nor assignable. - WeakMapPtr(const WeakMapPtr& wmp) = delete; - WeakMapPtr& operator=(const WeakMapPtr& wmp) = delete; -}; - -} /* namespace JS */ - -#endif /* js_WeakMapPtr_h */ diff --git a/win32/include/spidermonkey/jsalloc.h b/win32/include/spidermonkey/jsalloc.h deleted file mode 100755 index 6660b71d..00000000 --- a/win32/include/spidermonkey/jsalloc.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * JS allocation policies. - * - * The allocators here are for system memory with lifetimes which are not - * managed by the GC. See the comment at the top of vm/MallocProvider.h. - */ - -#ifndef jsalloc_h -#define jsalloc_h - -#include "js/TypeDecls.h" -#include "js/Utility.h" - -namespace js { - -enum class AllocFunction { - Malloc, - Calloc, - Realloc -}; - -struct ContextFriendFields; - -/* Policy for using system memory functions and doing no error reporting. */ -class SystemAllocPolicy -{ - public: - template T* maybe_pod_malloc(size_t numElems) { return js_pod_malloc(numElems); } - template T* maybe_pod_calloc(size_t numElems) { return js_pod_calloc(numElems); } - template T* maybe_pod_realloc(T* p, size_t oldSize, size_t newSize) { - return js_pod_realloc(p, oldSize, newSize); - } - template T* pod_malloc(size_t numElems) { return maybe_pod_malloc(numElems); } - template T* pod_calloc(size_t numElems) { return maybe_pod_calloc(numElems); } - template T* pod_realloc(T* p, size_t oldSize, size_t newSize) { - return maybe_pod_realloc(p, oldSize, newSize); - } - void free_(void* p) { js_free(p); } - void reportAllocOverflow() const {} - bool checkSimulatedOOM() const { - return !js::oom::ShouldFailWithOOM(); - } -}; - -class ExclusiveContext; -JS_PUBLIC_API(void) ReportOutOfMemory(ExclusiveContext* cxArg); - -/* - * Allocation policy that calls the system memory functions and reports errors - * to the context. Since the JSContext given on construction is stored for - * the lifetime of the container, this policy may only be used for containers - * whose lifetime is a shorter than the given JSContext. - * - * FIXME bug 647103 - rewrite this in terms of temporary allocation functions, - * not the system ones. - */ -class TempAllocPolicy -{ - ContextFriendFields* const cx_; - - /* - * Non-inline helper to call JSRuntime::onOutOfMemory with minimal - * code bloat. - */ - JS_FRIEND_API(void*) onOutOfMemory(AllocFunction allocFunc, size_t nbytes, - void* reallocPtr = nullptr); - - template - T* onOutOfMemoryTyped(AllocFunction allocFunc, size_t numElems, void* reallocPtr = nullptr) { - size_t bytes; - if (MOZ_UNLIKELY(!CalculateAllocSize(numElems, &bytes))) - return nullptr; - return static_cast(onOutOfMemory(allocFunc, bytes, reallocPtr)); - } - - public: - MOZ_IMPLICIT TempAllocPolicy(JSContext* cx) : cx_((ContextFriendFields*) cx) {} // :( - MOZ_IMPLICIT TempAllocPolicy(ContextFriendFields* cx) : cx_(cx) {} - - template - T* maybe_pod_malloc(size_t numElems) { - return js_pod_malloc(numElems); - } - - template - T* maybe_pod_calloc(size_t numElems) { - return js_pod_calloc(numElems); - } - - template - T* maybe_pod_realloc(T* prior, size_t oldSize, size_t newSize) { - return js_pod_realloc(prior, oldSize, newSize); - } - - template - T* pod_malloc(size_t numElems) { - T* p = maybe_pod_malloc(numElems); - if (MOZ_UNLIKELY(!p)) - p = onOutOfMemoryTyped(AllocFunction::Malloc, numElems); - return p; - } - - template - T* pod_calloc(size_t numElems) { - T* p = maybe_pod_calloc(numElems); - if (MOZ_UNLIKELY(!p)) - p = onOutOfMemoryTyped(AllocFunction::Calloc, numElems); - return p; - } - - template - T* pod_realloc(T* prior, size_t oldSize, size_t newSize) { - T* p2 = maybe_pod_realloc(prior, oldSize, newSize); - if (MOZ_UNLIKELY(!p2)) - p2 = onOutOfMemoryTyped(AllocFunction::Realloc, newSize, prior); - return p2; - } - - void free_(void* p) { - js_free(p); - } - - JS_FRIEND_API(void) reportAllocOverflow() const; - - bool checkSimulatedOOM() const { - if (js::oom::ShouldFailWithOOM()) { - js::ReportOutOfMemory(reinterpret_cast(cx_)); - return false; - } - - return true; - } -}; - -} /* namespace js */ - -#endif /* jsalloc_h */ diff --git a/win32/include/spidermonkey/jsapi.h b/win32/include/spidermonkey/jsapi.h deleted file mode 100755 index 84d639a0..00000000 --- a/win32/include/spidermonkey/jsapi.h +++ /dev/null @@ -1,6630 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* JavaScript API. */ - -#ifndef jsapi_h -#define jsapi_h - -#include "mozilla/AlreadyAddRefed.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Range.h" -#include "mozilla/RangedPtr.h" -#include "mozilla/RefCounted.h" -#include "mozilla/RefPtr.h" -#include "mozilla/Variant.h" - -#include -#include -#include -#include - -#include "jsalloc.h" -#include "jspubtd.h" - -#include "js/CallArgs.h" -#include "js/CharacterEncoding.h" -#include "js/Class.h" -#include "js/GCVector.h" -#include "js/HashTable.h" -#include "js/Id.h" -#include "js/Principals.h" -#include "js/Realm.h" -#include "js/RootingAPI.h" -#include "js/TracingAPI.h" -#include "js/Utility.h" -#include "js/Value.h" -#include "js/Vector.h" - -/************************************************************************/ - -namespace JS { - -class TwoByteChars; - -#ifdef JS_DEBUG - -class JS_PUBLIC_API(AutoCheckRequestDepth) -{ - JSContext* cx; - public: - explicit AutoCheckRequestDepth(JSContext* cx); - explicit AutoCheckRequestDepth(js::ContextFriendFields* cx); - ~AutoCheckRequestDepth(); -}; - -# define CHECK_REQUEST(cx) \ - JS::AutoCheckRequestDepth _autoCheckRequestDepth(cx) - -#else - -# define CHECK_REQUEST(cx) \ - ((void) 0) - -#endif /* JS_DEBUG */ - -/** AutoValueArray roots an internal fixed-size array of Values. */ -template -class MOZ_RAII AutoValueArray : public AutoGCRooter -{ - const size_t length_; - Value elements_[N]; - - public: - explicit AutoValueArray(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, VALARRAY), length_(N) - { - /* Always initialize in case we GC before assignment. */ - mozilla::PodArrayZero(elements_); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - unsigned length() const { return length_; } - const Value* begin() const { return elements_; } - Value* begin() { return elements_; } - - HandleValue operator[](unsigned i) const { - MOZ_ASSERT(i < N); - return HandleValue::fromMarkedLocation(&elements_[i]); - } - MutableHandleValue operator[](unsigned i) { - MOZ_ASSERT(i < N); - return MutableHandleValue::fromMarkedLocation(&elements_[i]); - } - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -template -class MOZ_RAII AutoVectorRooterBase : protected AutoGCRooter -{ - typedef js::Vector VectorImpl; - VectorImpl vector; - - public: - explicit AutoVectorRooterBase(JSContext* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), vector(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit AutoVectorRooterBase(js::ContextFriendFields* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), vector(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - typedef T ElementType; - typedef typename VectorImpl::Range Range; - - size_t length() const { return vector.length(); } - bool empty() const { return vector.empty(); } - - MOZ_MUST_USE bool append(const T& v) { return vector.append(v); } - MOZ_MUST_USE bool appendN(const T& v, size_t len) { return vector.appendN(v, len); } - MOZ_MUST_USE bool append(const T* ptr, size_t len) { return vector.append(ptr, len); } - MOZ_MUST_USE bool appendAll(const AutoVectorRooterBase& other) { - return vector.appendAll(other.vector); - } - - MOZ_MUST_USE bool insert(T* p, const T& val) { return vector.insert(p, val); } - - /* For use when space has already been reserved. */ - void infallibleAppend(const T& v) { vector.infallibleAppend(v); } - - void popBack() { vector.popBack(); } - T popCopy() { return vector.popCopy(); } - - MOZ_MUST_USE bool growBy(size_t inc) { - size_t oldLength = vector.length(); - if (!vector.growByUninitialized(inc)) - return false; - makeRangeGCSafe(oldLength); - return true; - } - - MOZ_MUST_USE bool resize(size_t newLength) { - size_t oldLength = vector.length(); - if (newLength <= oldLength) { - vector.shrinkBy(oldLength - newLength); - return true; - } - if (!vector.growByUninitialized(newLength - oldLength)) - return false; - makeRangeGCSafe(oldLength); - return true; - } - - void clear() { vector.clear(); } - - MOZ_MUST_USE bool reserve(size_t newLength) { - return vector.reserve(newLength); - } - - JS::MutableHandle operator[](size_t i) { - return JS::MutableHandle::fromMarkedLocation(&vector[i]); - } - JS::Handle operator[](size_t i) const { - return JS::Handle::fromMarkedLocation(&vector[i]); - } - - const T* begin() const { return vector.begin(); } - T* begin() { return vector.begin(); } - - const T* end() const { return vector.end(); } - T* end() { return vector.end(); } - - Range all() { return vector.all(); } - - const T& back() const { return vector.back(); } - - friend void AutoGCRooter::trace(JSTracer* trc); - - private: - void makeRangeGCSafe(size_t oldLength) { - T* t = vector.begin() + oldLength; - for (size_t i = oldLength; i < vector.length(); ++i, ++t) - memset(t, 0, sizeof(T)); - } - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -template -class MOZ_RAII AutoVectorRooter : public AutoVectorRooterBase -{ - public: - explicit AutoVectorRooter(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoVectorRooterBase(cx, this->GetTag(T())) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit AutoVectorRooter(js::ContextFriendFields* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoVectorRooterBase(cx, this->GetTag(T())) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -class AutoValueVector : public Rooted> { - using Vec = GCVector; - using Base = Rooted; - public: - explicit AutoValueVector(JSContext* cx) : Base(cx, Vec(cx)) {} - explicit AutoValueVector(js::ContextFriendFields* cx) : Base(cx, Vec(cx)) {} -}; - -class AutoIdVector : public Rooted> { - using Vec = GCVector; - using Base = Rooted; - public: - explicit AutoIdVector(JSContext* cx) : Base(cx, Vec(cx)) {} - explicit AutoIdVector(js::ContextFriendFields* cx) : Base(cx, Vec(cx)) {} - - bool appendAll(const AutoIdVector& other) { return this->Base::appendAll(other.get()); } -}; - -class AutoObjectVector : public Rooted> { - using Vec = GCVector; - using Base = Rooted; - public: - explicit AutoObjectVector(JSContext* cx) : Base(cx, Vec(cx)) {} - explicit AutoObjectVector(js::ContextFriendFields* cx) : Base(cx, Vec(cx)) {} -}; - -using ValueVector = JS::GCVector; -using IdVector = JS::GCVector; -using ScriptVector = JS::GCVector; -using StringVector = JS::GCVector; - -template -class MOZ_RAII AutoHashMapRooter : protected AutoGCRooter -{ - private: - typedef js::HashMap HashMapImpl; - - public: - explicit AutoHashMapRooter(JSContext* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), map(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - typedef Key KeyType; - typedef Value ValueType; - typedef typename HashMapImpl::Entry Entry; - typedef typename HashMapImpl::Lookup Lookup; - typedef typename HashMapImpl::Ptr Ptr; - typedef typename HashMapImpl::AddPtr AddPtr; - - bool init(uint32_t len = 16) { - return map.init(len); - } - bool initialized() const { - return map.initialized(); - } - Ptr lookup(const Lookup& l) const { - return map.lookup(l); - } - void remove(Ptr p) { - map.remove(p); - } - AddPtr lookupForAdd(const Lookup& l) const { - return map.lookupForAdd(l); - } - - template - bool add(AddPtr& p, const KeyInput& k, const ValueInput& v) { - return map.add(p, k, v); - } - - bool add(AddPtr& p, const Key& k) { - return map.add(p, k); - } - - template - bool relookupOrAdd(AddPtr& p, const KeyInput& k, const ValueInput& v) { - return map.relookupOrAdd(p, k, v); - } - - typedef typename HashMapImpl::Range Range; - Range all() const { - return map.all(); - } - - typedef typename HashMapImpl::Enum Enum; - - void clear() { - map.clear(); - } - - void finish() { - map.finish(); - } - - bool empty() const { - return map.empty(); - } - - uint32_t count() const { - return map.count(); - } - - size_t capacity() const { - return map.capacity(); - } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return map.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return map.sizeOfIncludingThis(mallocSizeOf); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return map.has(l); - } - - template - bool put(const KeyInput& k, const ValueInput& v) { - return map.put(k, v); - } - - template - bool putNew(const KeyInput& k, const ValueInput& v) { - return map.putNew(k, v); - } - - Ptr lookupWithDefault(const Key& k, const Value& defaultValue) { - return map.lookupWithDefault(k, defaultValue); - } - - void remove(const Lookup& l) { - map.remove(l); - } - - friend void AutoGCRooter::trace(JSTracer* trc); - - private: - AutoHashMapRooter(const AutoHashMapRooter& hmr) = delete; - AutoHashMapRooter& operator=(const AutoHashMapRooter& hmr) = delete; - - HashMapImpl map; - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -template -class MOZ_RAII AutoHashSetRooter : protected AutoGCRooter -{ - private: - typedef js::HashSet HashSetImpl; - - public: - explicit AutoHashSetRooter(JSContext* cx, ptrdiff_t tag - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, tag), set(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - typedef typename HashSetImpl::Lookup Lookup; - typedef typename HashSetImpl::Ptr Ptr; - typedef typename HashSetImpl::AddPtr AddPtr; - - bool init(uint32_t len = 16) { - return set.init(len); - } - bool initialized() const { - return set.initialized(); - } - Ptr lookup(const Lookup& l) const { - return set.lookup(l); - } - void remove(Ptr p) { - set.remove(p); - } - AddPtr lookupForAdd(const Lookup& l) const { - return set.lookupForAdd(l); - } - - bool add(AddPtr& p, const T& t) { - return set.add(p, t); - } - - bool relookupOrAdd(AddPtr& p, const Lookup& l, const T& t) { - return set.relookupOrAdd(p, l, t); - } - - typedef typename HashSetImpl::Range Range; - Range all() const { - return set.all(); - } - - typedef typename HashSetImpl::Enum Enum; - - void clear() { - set.clear(); - } - - void finish() { - set.finish(); - } - - bool empty() const { - return set.empty(); - } - - uint32_t count() const { - return set.count(); - } - - size_t capacity() const { - return set.capacity(); - } - - size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return set.sizeOfExcludingThis(mallocSizeOf); - } - size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const { - return set.sizeOfIncludingThis(mallocSizeOf); - } - - /************************************************** Shorthand operations */ - - bool has(const Lookup& l) const { - return set.has(l); - } - - bool put(const T& t) { - return set.put(t); - } - - bool putNew(const T& t) { - return set.putNew(t); - } - - void remove(const Lookup& l) { - set.remove(l); - } - - friend void AutoGCRooter::trace(JSTracer* trc); - - private: - AutoHashSetRooter(const AutoHashSetRooter& hmr) = delete; - AutoHashSetRooter& operator=(const AutoHashSetRooter& hmr) = delete; - - HashSetImpl set; - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/** - * Custom rooting behavior for internal and external clients. - */ -class MOZ_RAII JS_PUBLIC_API(CustomAutoRooter) : private AutoGCRooter -{ - public: - template - explicit CustomAutoRooter(const CX& cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : AutoGCRooter(cx, CUSTOM) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - friend void AutoGCRooter::trace(JSTracer* trc); - - protected: - virtual ~CustomAutoRooter() {} - - /** Supplied by derived class to trace roots. */ - virtual void trace(JSTracer* trc) = 0; - - private: - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/** A handle to an array of rooted values. */ -class HandleValueArray -{ - const size_t length_; - const Value * const elements_; - - HandleValueArray(size_t len, const Value* elements) : length_(len), elements_(elements) {} - - public: - explicit HandleValueArray(const RootedValue& value) : length_(1), elements_(value.address()) {} - - MOZ_IMPLICIT HandleValueArray(const AutoValueVector& values) - : length_(values.length()), elements_(values.begin()) {} - - template - MOZ_IMPLICIT HandleValueArray(const AutoValueArray& values) : length_(N), elements_(values.begin()) {} - - /** CallArgs must already be rooted somewhere up the stack. */ - MOZ_IMPLICIT HandleValueArray(const JS::CallArgs& args) : length_(args.length()), elements_(args.array()) {} - - /** Use with care! Only call this if the data is guaranteed to be marked. */ - static HandleValueArray fromMarkedLocation(size_t len, const Value* elements) { - return HandleValueArray(len, elements); - } - - static HandleValueArray subarray(const HandleValueArray& values, size_t startIndex, size_t len) { - MOZ_ASSERT(startIndex + len <= values.length()); - return HandleValueArray(len, values.begin() + startIndex); - } - - static HandleValueArray empty() { - return HandleValueArray(0, nullptr); - } - - size_t length() const { return length_; } - const Value* begin() const { return elements_; } - - HandleValue operator[](size_t i) const { - MOZ_ASSERT(i < length_); - return HandleValue::fromMarkedLocation(&elements_[i]); - } -}; - -} /* namespace JS */ - -/************************************************************************/ - -struct JSFreeOp { - protected: - JSRuntime* runtime_; - - explicit JSFreeOp(JSRuntime* rt) - : runtime_(rt) { } - - public: - JSRuntime* runtime() const { - MOZ_ASSERT(runtime_); - return runtime_; - } -}; - -/* Callbacks and their arguments. */ - -/************************************************************************/ - -typedef enum JSGCStatus { - JSGC_BEGIN, - JSGC_END -} JSGCStatus; - -typedef void -(* JSGCCallback)(JSContext* cx, JSGCStatus status, void* data); - -typedef void -(* JSObjectsTenuredCallback)(JSContext* cx, void* data); - -typedef enum JSFinalizeStatus { - /** - * Called when preparing to sweep a group of zones, before anything has been - * swept. The collector will not yield to the mutator before calling the - * callback with JSFINALIZE_GROUP_END status. - */ - JSFINALIZE_GROUP_START, - - /** - * Called when preparing to sweep a group of zones. Weak references to - * unmarked things have been removed and things that are not swept - * incrementally have been finalized at this point. The collector may yield - * to the mutator after this point. - */ - JSFINALIZE_GROUP_END, - - /** - * Called at the end of collection when everything has been swept. - */ - JSFINALIZE_COLLECTION_END -} JSFinalizeStatus; - -typedef void -(* JSFinalizeCallback)(JSFreeOp* fop, JSFinalizeStatus status, bool isZoneGC, void* data); - -typedef void -(* JSWeakPointerZoneGroupCallback)(JSContext* cx, void* data); - -typedef void -(* JSWeakPointerCompartmentCallback)(JSContext* cx, JSCompartment* comp, void* data); - -typedef bool -(* JSInterruptCallback)(JSContext* cx); - -typedef JSObject* -(* JSGetIncumbentGlobalCallback)(JSContext* cx); - -typedef bool -(* JSEnqueuePromiseJobCallback)(JSContext* cx, JS::HandleObject job, - JS::HandleObject allocationSite, JS::HandleObject incumbentGlobal, - void* data); - -enum class PromiseRejectionHandlingState { - Unhandled, - Handled -}; - -typedef void -(* JSPromiseRejectionTrackerCallback)(JSContext* cx, JS::HandleObject promise, - PromiseRejectionHandlingState state, void* data); - -typedef void -(* JSProcessPromiseCallback)(JSContext* cx, JS::HandleObject promise); - -/** - * Possible exception types. These types are part of a JSErrorFormatString - * structure. They define which error to throw in case of a runtime error. - * - * JSEXN_WARN is used for warnings in js.msg files (for instance because we - * don't want to prepend 'Error:' to warning messages). This value can go away - * if we ever decide to use an entirely separate mechanism for warnings. - */ -typedef enum JSExnType { - JSEXN_ERR, - JSEXN_FIRST = JSEXN_ERR, - JSEXN_INTERNALERR, - JSEXN_EVALERR, - JSEXN_RANGEERR, - JSEXN_REFERENCEERR, - JSEXN_SYNTAXERR, - JSEXN_TYPEERR, - JSEXN_URIERR, - JSEXN_DEBUGGEEWOULDRUN, - JSEXN_WASMCOMPILEERROR, - JSEXN_WASMRUNTIMEERROR, - JSEXN_WARN, - JSEXN_LIMIT -} JSExnType; - -typedef struct JSErrorFormatString { - /** The error message name in ASCII. */ - const char* name; - - /** The error format string in ASCII. */ - const char* format; - - /** The number of arguments to expand in the formatted error message. */ - uint16_t argCount; - - /** One of the JSExnType constants above. */ - int16_t exnType; -} JSErrorFormatString; - -typedef const JSErrorFormatString* -(* JSErrorCallback)(void* userRef, const unsigned errorNumber); - -typedef bool -(* JSLocaleToUpperCase)(JSContext* cx, JS::HandleString src, JS::MutableHandleValue rval); - -typedef bool -(* JSLocaleToLowerCase)(JSContext* cx, JS::HandleString src, JS::MutableHandleValue rval); - -typedef bool -(* JSLocaleCompare)(JSContext* cx, JS::HandleString src1, JS::HandleString src2, - JS::MutableHandleValue rval); - -typedef bool -(* JSLocaleToUnicode)(JSContext* cx, const char* src, JS::MutableHandleValue rval); - -/** - * Callback used to ask the embedding for the cross compartment wrapper handler - * that implements the desired prolicy for this kind of object in the - * destination compartment. |obj| is the object to be wrapped. If |existing| is - * non-nullptr, it will point to an existing wrapper object that should be - * re-used if possible. |existing| is guaranteed to be a cross-compartment - * wrapper with a lazily-defined prototype and the correct global. It is - * guaranteed not to wrap a function. - */ -typedef JSObject* -(* JSWrapObjectCallback)(JSContext* cx, JS::HandleObject existing, JS::HandleObject obj); - -/** - * Callback used by the wrap hook to ask the embedding to prepare an object - * for wrapping in a context. This might include unwrapping other wrappers - * or even finding a more suitable object for the new compartment. - */ -typedef void -(* JSPreWrapCallback)(JSContext* cx, JS::HandleObject scope, JS::HandleObject obj, - JS::HandleObject objectPassedToWrap, - JS::MutableHandleObject retObj); - -struct JSWrapObjectCallbacks -{ - JSWrapObjectCallback wrap; - JSPreWrapCallback preWrap; -}; - -typedef void -(* JSDestroyCompartmentCallback)(JSFreeOp* fop, JSCompartment* compartment); - -typedef size_t -(* JSSizeOfIncludingThisCompartmentCallback)(mozilla::MallocSizeOf mallocSizeOf, - JSCompartment* compartment); - -typedef void -(* JSZoneCallback)(JS::Zone* zone); - -typedef void -(* JSCompartmentNameCallback)(JSContext* cx, JSCompartment* compartment, - char* buf, size_t bufsize); - -/************************************************************************/ - -static MOZ_ALWAYS_INLINE JS::Value -JS_NumberValue(double d) -{ - int32_t i; - d = JS::CanonicalizeNaN(d); - if (mozilla::NumberIsInt32(d, &i)) - return JS::Int32Value(i); - return JS::DoubleValue(d); -} - -/************************************************************************/ - -JS_PUBLIC_API(bool) -JS_StringHasBeenPinned(JSContext* cx, JSString* str); - -namespace JS { - -/** - * Container class for passing in script source buffers to the JS engine. This - * not only groups the buffer and length values, it also provides a way to - * optionally pass ownership of the buffer to the JS engine without copying. - * Rules for use: - * - * 1) The data array must be allocated with js_malloc() or js_realloc() if - * ownership is being granted to the SourceBufferHolder. - * 2) If ownership is not given to the SourceBufferHolder, then the memory - * must be kept alive until the JS compilation is complete. - * 3) Any code calling SourceBufferHolder::take() must guarantee to keep the - * memory alive until JS compilation completes. Normally only the JS - * engine should be calling take(). - * - * Example use: - * - * size_t length = 512; - * char16_t* chars = static_cast(js_malloc(sizeof(char16_t) * length)); - * JS::SourceBufferHolder srcBuf(chars, length, JS::SourceBufferHolder::GiveOwnership); - * JS::Compile(cx, options, srcBuf); - */ -class MOZ_STACK_CLASS SourceBufferHolder final -{ - public: - enum Ownership { - NoOwnership, - GiveOwnership - }; - - SourceBufferHolder(const char16_t* data, size_t dataLength, Ownership ownership) - : data_(data), - length_(dataLength), - ownsChars_(ownership == GiveOwnership) - { - // Ensure that null buffers properly return an unowned, empty, - // null-terminated string. - static const char16_t NullChar_ = 0; - if (!get()) { - data_ = &NullChar_; - length_ = 0; - ownsChars_ = false; - } - } - - SourceBufferHolder(SourceBufferHolder&& other) - : data_(other.data_), - length_(other.length_), - ownsChars_(other.ownsChars_) - { - other.data_ = nullptr; - other.length_ = 0; - other.ownsChars_ = false; - } - - ~SourceBufferHolder() { - if (ownsChars_) - js_free(const_cast(data_)); - } - - // Access the underlying source buffer without affecting ownership. - const char16_t* get() const { return data_; } - - // Length of the source buffer in char16_t code units (not bytes) - size_t length() const { return length_; } - - // Returns true if the SourceBufferHolder owns the buffer and will free - // it upon destruction. If true, it is legal to call take(). - bool ownsChars() const { return ownsChars_; } - - // Retrieve and take ownership of the underlying data buffer. The caller - // is now responsible for calling js_free() on the returned value, *but only - // after JS script compilation has completed*. - // - // After the buffer has been taken the SourceBufferHolder functions as if - // it had been constructed on an unowned buffer; get() and length() still - // work. In order for this to be safe the taken buffer must be kept alive - // until after JS script compilation completes as noted above. - // - // Note, it's the caller's responsibility to check ownsChars() before taking - // the buffer. Taking and then free'ing an unowned buffer will have dire - // consequences. - char16_t* take() { - MOZ_ASSERT(ownsChars_); - ownsChars_ = false; - return const_cast(data_); - } - - private: - SourceBufferHolder(SourceBufferHolder&) = delete; - SourceBufferHolder& operator=(SourceBufferHolder&) = delete; - - const char16_t* data_; - size_t length_; - bool ownsChars_; -}; - -} /* namespace JS */ - -/************************************************************************/ - -/* Property attributes, set in JSPropertySpec and passed to API functions. - * - * NB: The data structure in which some of these values are stored only uses - * a uint8_t to store the relevant information. Proceed with caution if - * trying to reorder or change the the first byte worth of flags. - */ -#define JSPROP_ENUMERATE 0x01 /* property is visible to for/in loop */ -#define JSPROP_READONLY 0x02 /* not settable: assignment is no-op. - This flag is only valid when neither - JSPROP_GETTER nor JSPROP_SETTER is - set. */ -#define JSPROP_PERMANENT 0x04 /* property cannot be deleted */ -#define JSPROP_PROPOP_ACCESSORS 0x08 /* Passed to JS_Define(UC)Property* and - JS_DefineElement if getters/setters - are JSGetterOp/JSSetterOp */ -#define JSPROP_GETTER 0x10 /* property holds getter function */ -#define JSPROP_SETTER 0x20 /* property holds setter function */ -#define JSPROP_SHARED 0x40 /* don't allocate a value slot for this - property; don't copy the property on - set of the same-named property in an - object that delegates to a prototype - containing this property */ -#define JSPROP_INTERNAL_USE_BIT 0x80 /* internal JS engine use only */ -#define JSFUN_STUB_GSOPS 0x200 /* use JS_PropertyStub getter/setter - instead of defaulting to class gsops - for property holding function */ - -#define JSFUN_CONSTRUCTOR 0x400 /* native that can be called as a ctor */ - -// 0x800 /* Unused */ - -#define JSFUN_HAS_REST 0x1000 /* function has ...rest parameter. */ - -#define JSFUN_FLAGS_MASK 0x1e00 /* | of all the JSFUN_* flags */ - -/* - * If set, will allow redefining a non-configurable property, but only on a - * non-DOM global. This is a temporary hack that will need to go away in bug - * 1105518. - */ -#define JSPROP_REDEFINE_NONCONFIGURABLE 0x1000 - -/* - * Resolve hooks and enumerate hooks must pass this flag when calling - * JS_Define* APIs to reify lazily-defined properties. - * - * JSPROP_RESOLVING is used only with property-defining APIs. It tells the - * engine to skip the resolve hook when performing the lookup at the beginning - * of property definition. This keeps the resolve hook from accidentally - * triggering itself: unchecked recursion. - * - * For enumerate hooks, triggering the resolve hook would be merely silly, not - * fatal, except in some cases involving non-configurable properties. - */ -#define JSPROP_RESOLVING 0x2000 - -#define JSPROP_IGNORE_ENUMERATE 0x4000 /* ignore the value in JSPROP_ENUMERATE. - This flag only valid when defining over - an existing property. */ -#define JSPROP_IGNORE_READONLY 0x8000 /* ignore the value in JSPROP_READONLY. - This flag only valid when defining over - an existing property. */ -#define JSPROP_IGNORE_PERMANENT 0x10000 /* ignore the value in JSPROP_PERMANENT. - This flag only valid when defining over - an existing property. */ -#define JSPROP_IGNORE_VALUE 0x20000 /* ignore the Value in the descriptor. Nothing was - specified when passed to Object.defineProperty - from script. */ - -/** Microseconds since the epoch, midnight, January 1, 1970 UTC. */ -extern JS_PUBLIC_API(int64_t) -JS_Now(void); - -/** Don't want to export data, so provide accessors for non-inline Values. */ -extern JS_PUBLIC_API(JS::Value) -JS_GetNaNValue(JSContext* cx); - -extern JS_PUBLIC_API(JS::Value) -JS_GetNegativeInfinityValue(JSContext* cx); - -extern JS_PUBLIC_API(JS::Value) -JS_GetPositiveInfinityValue(JSContext* cx); - -extern JS_PUBLIC_API(JS::Value) -JS_GetEmptyStringValue(JSContext* cx); - -extern JS_PUBLIC_API(JSString*) -JS_GetEmptyString(JSContext* cx); - -extern JS_PUBLIC_API(bool) -JS_ValueToObject(JSContext* cx, JS::HandleValue v, JS::MutableHandleObject objp); - -extern JS_PUBLIC_API(JSFunction*) -JS_ValueToFunction(JSContext* cx, JS::HandleValue v); - -extern JS_PUBLIC_API(JSFunction*) -JS_ValueToConstructor(JSContext* cx, JS::HandleValue v); - -extern JS_PUBLIC_API(JSString*) -JS_ValueToSource(JSContext* cx, JS::Handle v); - -extern JS_PUBLIC_API(bool) -JS_DoubleIsInt32(double d, int32_t* ip); - -extern JS_PUBLIC_API(JSType) -JS_TypeOfValue(JSContext* cx, JS::Handle v); - -namespace JS { - -extern JS_PUBLIC_API(const char*) -InformalValueTypeName(const JS::Value& v); - -} /* namespace JS */ - -extern JS_PUBLIC_API(bool) -JS_StrictlyEqual(JSContext* cx, JS::Handle v1, JS::Handle v2, bool* equal); - -extern JS_PUBLIC_API(bool) -JS_LooselyEqual(JSContext* cx, JS::Handle v1, JS::Handle v2, bool* equal); - -extern JS_PUBLIC_API(bool) -JS_SameValue(JSContext* cx, JS::Handle v1, JS::Handle v2, bool* same); - -/** True iff fun is the global eval function. */ -extern JS_PUBLIC_API(bool) -JS_IsBuiltinEvalFunction(JSFunction* fun); - -/** True iff fun is the Function constructor. */ -extern JS_PUBLIC_API(bool) -JS_IsBuiltinFunctionConstructor(JSFunction* fun); - -/************************************************************************/ - -/* - * Locking, contexts, and memory allocation. - * - * It is important that SpiderMonkey be initialized, and the first context - * be created, in a single-threaded fashion. Otherwise the behavior of the - * library is undefined. - * See: http://developer.mozilla.org/en/docs/Category:JSAPI_Reference - */ - -extern JS_PUBLIC_API(JSContext*) -JS_NewContext(uint32_t maxbytes, - uint32_t maxNurseryBytes = JS::DefaultNurseryBytes, - JSContext* parentContext = nullptr); - -extern JS_PUBLIC_API(void) -JS_DestroyContext(JSContext* cx); - -typedef double (*JS_CurrentEmbedderTimeFunction)(); - -/** - * The embedding can specify a time function that will be used in some - * situations. The function can return the time however it likes; but - * the norm is to return times in units of milliseconds since an - * arbitrary, but consistent, epoch. If the time function is not set, - * a built-in default will be used. - */ -JS_PUBLIC_API(void) -JS_SetCurrentEmbedderTimeFunction(JS_CurrentEmbedderTimeFunction timeFn); - -/** - * Return the time as computed using the current time function, or a - * suitable default if one has not been set. - */ -JS_PUBLIC_API(double) -JS_GetCurrentEmbedderTime(); - -JS_PUBLIC_API(void*) -JS_GetContextPrivate(JSContext* cx); - -JS_PUBLIC_API(void) -JS_SetContextPrivate(JSContext* cx, void* data); - -extern JS_PUBLIC_API(JSContext*) -JS_GetParentContext(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_BeginRequest(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_EndRequest(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_SetFutexCanWait(JSContext* cx); - -namespace js { - -void -AssertHeapIsIdle(JSRuntime* rt); - -} /* namespace js */ - -class MOZ_RAII JSAutoRequest -{ - public: - explicit JSAutoRequest(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mContext(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - JS_BeginRequest(mContext); - } - ~JSAutoRequest() { - JS_EndRequest(mContext); - } - - protected: - JSContext* mContext; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - -#if 0 - private: - static void* operator new(size_t) CPP_THROW_NEW { return 0; } - static void operator delete(void*, size_t) { } -#endif -}; - -extern JS_PUBLIC_API(JSVersion) -JS_GetVersion(JSContext* cx); - -/** - * Mutate the version on the compartment. This is generally discouraged, but - * necessary to support the version mutation in the js and xpc shell command - * set. - * - * It would be nice to put this in jsfriendapi, but the linkage requirements - * of the shells make that impossible. - */ -JS_PUBLIC_API(void) -JS_SetVersionForCompartment(JSCompartment* compartment, JSVersion version); - -extern JS_PUBLIC_API(const char*) -JS_VersionToString(JSVersion version); - -extern JS_PUBLIC_API(JSVersion) -JS_StringToVersion(const char* string); - -namespace JS { - -class JS_PUBLIC_API(ContextOptions) { - public: - ContextOptions() - : baseline_(true), - ion_(true), - asmJS_(true), - wasm_(false), - wasmAlwaysBaseline_(false), - throwOnAsmJSValidationFailure_(false), - nativeRegExp_(true), - unboxedArrays_(false), - asyncStack_(true), - throwOnDebuggeeWouldRun_(true), - dumpStackOnDebuggeeWouldRun_(false), - werror_(false), - strictMode_(false), - extraWarnings_(false) - { - } - - bool baseline() const { return baseline_; } - ContextOptions& setBaseline(bool flag) { - baseline_ = flag; - return *this; - } - ContextOptions& toggleBaseline() { - baseline_ = !baseline_; - return *this; - } - - bool ion() const { return ion_; } - ContextOptions& setIon(bool flag) { - ion_ = flag; - return *this; - } - ContextOptions& toggleIon() { - ion_ = !ion_; - return *this; - } - - bool asmJS() const { return asmJS_; } - ContextOptions& setAsmJS(bool flag) { - asmJS_ = flag; - return *this; - } - ContextOptions& toggleAsmJS() { - asmJS_ = !asmJS_; - return *this; - } - - bool wasm() const { return wasm_; } - ContextOptions& setWasm(bool flag) { - wasm_ = flag; - return *this; - } - ContextOptions& toggleWasm() { - wasm_ = !wasm_; - return *this; - } - - bool wasmAlwaysBaseline() const { return wasmAlwaysBaseline_; } - ContextOptions& setWasmAlwaysBaseline(bool flag) { - wasmAlwaysBaseline_ = flag; - return *this; - } - ContextOptions& toggleWasmAlwaysBaseline() { - wasmAlwaysBaseline_ = !wasmAlwaysBaseline_; - return *this; - } - - bool throwOnAsmJSValidationFailure() const { return throwOnAsmJSValidationFailure_; } - ContextOptions& setThrowOnAsmJSValidationFailure(bool flag) { - throwOnAsmJSValidationFailure_ = flag; - return *this; - } - ContextOptions& toggleThrowOnAsmJSValidationFailure() { - throwOnAsmJSValidationFailure_ = !throwOnAsmJSValidationFailure_; - return *this; - } - - bool nativeRegExp() const { return nativeRegExp_; } - ContextOptions& setNativeRegExp(bool flag) { - nativeRegExp_ = flag; - return *this; - } - - bool unboxedArrays() const { return unboxedArrays_; } - ContextOptions& setUnboxedArrays(bool flag) { - unboxedArrays_ = flag; - return *this; - } - - bool asyncStack() const { return asyncStack_; } - ContextOptions& setAsyncStack(bool flag) { - asyncStack_ = flag; - return *this; - } - - bool throwOnDebuggeeWouldRun() const { return throwOnDebuggeeWouldRun_; } - ContextOptions& setThrowOnDebuggeeWouldRun(bool flag) { - throwOnDebuggeeWouldRun_ = flag; - return *this; - } - - bool dumpStackOnDebuggeeWouldRun() const { return dumpStackOnDebuggeeWouldRun_; } - ContextOptions& setDumpStackOnDebuggeeWouldRun(bool flag) { - dumpStackOnDebuggeeWouldRun_ = flag; - return *this; - } - - bool werror() const { return werror_; } - ContextOptions& setWerror(bool flag) { - werror_ = flag; - return *this; - } - ContextOptions& toggleWerror() { - werror_ = !werror_; - return *this; - } - - bool strictMode() const { return strictMode_; } - ContextOptions& setStrictMode(bool flag) { - strictMode_ = flag; - return *this; - } - ContextOptions& toggleStrictMode() { - strictMode_ = !strictMode_; - return *this; - } - - bool extraWarnings() const { return extraWarnings_; } - ContextOptions& setExtraWarnings(bool flag) { - extraWarnings_ = flag; - return *this; - } - ContextOptions& toggleExtraWarnings() { - extraWarnings_ = !extraWarnings_; - return *this; - } - - private: - bool baseline_ : 1; - bool ion_ : 1; - bool asmJS_ : 1; - bool wasm_ : 1; - bool wasmAlwaysBaseline_ : 1; - bool throwOnAsmJSValidationFailure_ : 1; - bool nativeRegExp_ : 1; - bool unboxedArrays_ : 1; - bool asyncStack_ : 1; - bool throwOnDebuggeeWouldRun_ : 1; - bool dumpStackOnDebuggeeWouldRun_ : 1; - bool werror_ : 1; - bool strictMode_ : 1; - bool extraWarnings_ : 1; -}; - -JS_PUBLIC_API(ContextOptions&) -ContextOptionsRef(JSContext* cx); - -/** - * Initialize the runtime's self-hosted code. Embeddings should call this - * exactly once per runtime/context, before the first JS_NewGlobalObject - * call. - */ -JS_PUBLIC_API(bool) -InitSelfHostedCode(JSContext* cx); - -/** - * Asserts (in debug and release builds) that `obj` belongs to the current - * thread's context. - */ -JS_PUBLIC_API(void) -AssertObjectBelongsToCurrentThread(JSObject* obj); - -} /* namespace JS */ - -extern JS_PUBLIC_API(const char*) -JS_GetImplementationVersion(void); - -extern JS_PUBLIC_API(void) -JS_SetDestroyCompartmentCallback(JSContext* cx, JSDestroyCompartmentCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetSizeOfIncludingThisCompartmentCallback(JSContext* cx, - JSSizeOfIncludingThisCompartmentCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetDestroyZoneCallback(JSContext* cx, JSZoneCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetSweepZoneCallback(JSContext* cx, JSZoneCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetCompartmentNameCallback(JSContext* cx, JSCompartmentNameCallback callback); - -extern JS_PUBLIC_API(void) -JS_SetWrapObjectCallbacks(JSContext* cx, const JSWrapObjectCallbacks* callbacks); - -extern JS_PUBLIC_API(void) -JS_SetCompartmentPrivate(JSCompartment* compartment, void* data); - -extern JS_PUBLIC_API(void*) -JS_GetCompartmentPrivate(JSCompartment* compartment); - -extern JS_PUBLIC_API(void) -JS_SetZoneUserData(JS::Zone* zone, void* data); - -extern JS_PUBLIC_API(void*) -JS_GetZoneUserData(JS::Zone* zone); - -extern JS_PUBLIC_API(bool) -JS_WrapObject(JSContext* cx, JS::MutableHandleObject objp); - -extern JS_PUBLIC_API(bool) -JS_WrapValue(JSContext* cx, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(JSObject*) -JS_TransplantObject(JSContext* cx, JS::HandleObject origobj, JS::HandleObject target); - -extern JS_PUBLIC_API(bool) -JS_RefreshCrossCompartmentWrappers(JSContext* cx, JS::Handle obj); - -/* - * At any time, a JSContext has a current (possibly-nullptr) compartment. - * Compartments are described in: - * - * developer.mozilla.org/en-US/docs/SpiderMonkey/SpiderMonkey_compartments - * - * The current compartment of a context may be changed. The preferred way to do - * this is with JSAutoCompartment: - * - * void foo(JSContext* cx, JSObject* obj) { - * // in some compartment 'c' - * { - * JSAutoCompartment ac(cx, obj); // constructor enters - * // in the compartment of 'obj' - * } // destructor leaves - * // back in compartment 'c' - * } - * - * For more complicated uses that don't neatly fit in a C++ stack frame, the - * compartment can entered and left using separate function calls: - * - * void foo(JSContext* cx, JSObject* obj) { - * // in 'oldCompartment' - * JSCompartment* oldCompartment = JS_EnterCompartment(cx, obj); - * // in the compartment of 'obj' - * JS_LeaveCompartment(cx, oldCompartment); - * // back in 'oldCompartment' - * } - * - * Note: these calls must still execute in a LIFO manner w.r.t all other - * enter/leave calls on the context. Furthermore, only the return value of a - * JS_EnterCompartment call may be passed as the 'oldCompartment' argument of - * the corresponding JS_LeaveCompartment call. - */ - -class MOZ_RAII JS_PUBLIC_API(JSAutoCompartment) -{ - JSContext* cx_; - JSCompartment* oldCompartment_; - public: - JSAutoCompartment(JSContext* cx, JSObject* target - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - JSAutoCompartment(JSContext* cx, JSScript* target - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~JSAutoCompartment(); - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -class MOZ_RAII JS_PUBLIC_API(JSAutoNullableCompartment) -{ - JSContext* cx_; - JSCompartment* oldCompartment_; - public: - explicit JSAutoNullableCompartment(JSContext* cx, JSObject* targetOrNull - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~JSAutoNullableCompartment(); - - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/** NB: This API is infallible; a nullptr return value does not indicate error. */ -extern JS_PUBLIC_API(JSCompartment*) -JS_EnterCompartment(JSContext* cx, JSObject* target); - -extern JS_PUBLIC_API(void) -JS_LeaveCompartment(JSContext* cx, JSCompartment* oldCompartment); - -typedef void (*JSIterateCompartmentCallback)(JSContext* cx, void* data, JSCompartment* compartment); - -/** - * This function calls |compartmentCallback| on every compartment. Beware that - * there is no guarantee that the compartment will survive after the callback - * returns. Also, barriers are disabled via the TraceSession. - */ -extern JS_PUBLIC_API(void) -JS_IterateCompartments(JSContext* cx, void* data, - JSIterateCompartmentCallback compartmentCallback); - -/** - * Initialize standard JS class constructors, prototypes, and any top-level - * functions and constants associated with the standard classes (e.g. isNaN - * for Number). - * - * NB: This sets cx's global object to obj if it was null. - */ -extern JS_PUBLIC_API(bool) -JS_InitStandardClasses(JSContext* cx, JS::Handle obj); - -/** - * Resolve id, which must contain either a string or an int, to a standard - * class name in obj if possible, defining the class's constructor and/or - * prototype and storing true in *resolved. If id does not name a standard - * class or a top-level property induced by initializing a standard class, - * store false in *resolved and just return true. Return false on error, - * as usual for bool result-typed API entry points. - * - * This API can be called directly from a global object class's resolve op, - * to define standard classes lazily. The class's enumerate op should call - * JS_EnumerateStandardClasses(cx, obj), to define eagerly during for..in - * loops any classes not yet resolved lazily. - */ -extern JS_PUBLIC_API(bool) -JS_ResolveStandardClass(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* resolved); - -extern JS_PUBLIC_API(bool) -JS_MayResolveStandardClass(const JSAtomState& names, jsid id, JSObject* maybeObj); - -extern JS_PUBLIC_API(bool) -JS_EnumerateStandardClasses(JSContext* cx, JS::HandleObject obj); - -extern JS_PUBLIC_API(bool) -JS_GetClassObject(JSContext* cx, JSProtoKey key, JS::MutableHandle objp); - -extern JS_PUBLIC_API(bool) -JS_GetClassPrototype(JSContext* cx, JSProtoKey key, JS::MutableHandle objp); - -namespace JS { - -/* - * Determine if the given object is an instance/prototype/constructor for a standard - * class. If so, return the associated JSProtoKey. If not, return JSProto_Null. - */ - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardInstance(JSObject* obj); - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardPrototype(JSObject* obj); - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardInstanceOrPrototype(JSObject* obj); - -extern JS_PUBLIC_API(JSProtoKey) -IdentifyStandardConstructor(JSObject* obj); - -extern JS_PUBLIC_API(void) -ProtoKeyToId(JSContext* cx, JSProtoKey key, JS::MutableHandleId idp); - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSProtoKey) -JS_IdToProtoKey(JSContext* cx, JS::HandleId id); - -/** - * Returns the original value of |Function.prototype| from the global object in - * which |forObj| was created. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetFunctionPrototype(JSContext* cx, JS::HandleObject forObj); - -/** - * Returns the original value of |Object.prototype| from the global object in - * which |forObj| was created. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetObjectPrototype(JSContext* cx, JS::HandleObject forObj); - -/** - * Returns the original value of |Array.prototype| from the global object in - * which |forObj| was created. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetArrayPrototype(JSContext* cx, JS::HandleObject forObj); - -/** - * Returns the original value of |Error.prototype| from the global - * object of the current compartment of cx. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetErrorPrototype(JSContext* cx); - -/** - * Returns the %IteratorPrototype% object that all built-in iterator prototype - * chains go through for the global object of the current compartment of cx. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetIteratorPrototype(JSContext* cx); - -extern JS_PUBLIC_API(JSObject*) -JS_GetGlobalForObject(JSContext* cx, JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_IsGlobalObject(JSObject* obj); - -extern JS_PUBLIC_API(JSObject*) -JS_GlobalLexicalEnvironment(JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_HasExtensibleLexicalEnvironment(JSObject* obj); - -extern JS_PUBLIC_API(JSObject*) -JS_ExtensibleLexicalEnvironment(JSObject* obj); - -/** - * May return nullptr, if |c| never had a global (e.g. the atoms compartment), - * or if |c|'s global has been collected. - */ -extern JS_PUBLIC_API(JSObject*) -JS_GetGlobalForCompartmentOrNull(JSContext* cx, JSCompartment* c); - -namespace JS { - -extern JS_PUBLIC_API(JSObject*) -CurrentGlobalOrNull(JSContext* cx); - -} // namespace JS - -/** - * Add 'Reflect.parse', a SpiderMonkey extension, to the Reflect object on the - * given global. - */ -extern JS_PUBLIC_API(bool) -JS_InitReflectParse(JSContext* cx, JS::HandleObject global); - -/** - * Add various profiling-related functions as properties of the given object. - * Defined in builtin/Profilers.cpp. - */ -extern JS_PUBLIC_API(bool) -JS_DefineProfilingFunctions(JSContext* cx, JS::HandleObject obj); - -/* Defined in vm/Debugger.cpp. */ -extern JS_PUBLIC_API(bool) -JS_DefineDebuggerObject(JSContext* cx, JS::HandleObject obj); - -#ifdef JS_HAS_CTYPES -/** - * Initialize the 'ctypes' object on a global variable 'obj'. The 'ctypes' - * object will be sealed. - */ -extern JS_PUBLIC_API(bool) -JS_InitCTypesClass(JSContext* cx, JS::HandleObject global); - -/** - * Convert a unicode string 'source' of length 'slen' to the platform native - * charset, returning a null-terminated string allocated with JS_malloc. On - * failure, this function should report an error. - */ -typedef char* -(* JSCTypesUnicodeToNativeFun)(JSContext* cx, const char16_t* source, size_t slen); - -/** - * Set of function pointers that ctypes can use for various internal functions. - * See JS_SetCTypesCallbacks below. Providing nullptr for a function is safe, - * and will result in the applicable ctypes functionality not being available. - */ -struct JSCTypesCallbacks { - JSCTypesUnicodeToNativeFun unicodeToNative; -}; - -typedef struct JSCTypesCallbacks JSCTypesCallbacks; - -/** - * Set the callbacks on the provided 'ctypesObj' object. 'callbacks' should be a - * pointer to static data that exists for the lifetime of 'ctypesObj', but it - * may safely be altered after calling this function and without having - * to call this function again. - */ -extern JS_PUBLIC_API(void) -JS_SetCTypesCallbacks(JSObject* ctypesObj, const JSCTypesCallbacks* callbacks); -#endif - -extern JS_PUBLIC_API(void*) -JS_malloc(JSContext* cx, size_t nbytes); - -extern JS_PUBLIC_API(void*) -JS_realloc(JSContext* cx, void* p, size_t oldBytes, size_t newBytes); - -/** - * A wrapper for js_free(p) that may delay js_free(p) invocation as a - * performance optimization. - * cx may be nullptr. - */ -extern JS_PUBLIC_API(void) -JS_free(JSContext* cx, void* p); - -/** - * A wrapper for js_free(p) that may delay js_free(p) invocation as a - * performance optimization as specified by the given JSFreeOp instance. - */ -extern JS_PUBLIC_API(void) -JS_freeop(JSFreeOp* fop, void* p); - -extern JS_PUBLIC_API(void) -JS_updateMallocCounter(JSContext* cx, size_t nbytes); - -extern JS_PUBLIC_API(char*) -JS_strdup(JSContext* cx, const char* s); - -/** - * Register externally maintained GC roots. - * - * traceOp: the trace operation. For each root the implementation should call - * JS::TraceEdge whenever the root contains a traceable thing. - * data: the data argument to pass to each invocation of traceOp. - */ -extern JS_PUBLIC_API(bool) -JS_AddExtraGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data); - -/** Undo a call to JS_AddExtraGCRootsTracer. */ -extern JS_PUBLIC_API(void) -JS_RemoveExtraGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data); - -/* - * Garbage collector API. - */ -extern JS_PUBLIC_API(void) -JS_GC(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_MaybeGC(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_SetGCCallback(JSContext* cx, JSGCCallback cb, void* data); - -extern JS_PUBLIC_API(void) -JS_SetObjectsTenuredCallback(JSContext* cx, JSObjectsTenuredCallback cb, - void* data); - -extern JS_PUBLIC_API(bool) -JS_AddFinalizeCallback(JSContext* cx, JSFinalizeCallback cb, void* data); - -extern JS_PUBLIC_API(void) -JS_RemoveFinalizeCallback(JSContext* cx, JSFinalizeCallback cb); - -/* - * Weak pointers and garbage collection - * - * Weak pointers are by their nature not marked as part of garbage collection, - * but they may need to be updated in two cases after a GC: - * - * 1) Their referent was found not to be live and is about to be finalized - * 2) Their referent has been moved by a compacting GC - * - * To handle this, any part of the system that maintain weak pointers to - * JavaScript GC things must register a callback with - * JS_(Add,Remove)WeakPointer{ZoneGroup,Compartment}Callback(). This callback - * must then call JS_UpdateWeakPointerAfterGC() on all weak pointers it knows - * about. - * - * Since sweeping is incremental, we have several callbacks to avoid repeatedly - * having to visit all embedder structures. The WeakPointerZoneGroupCallback is - * called once for each strongly connected group of zones, whereas the - * WeakPointerCompartmentCallback is called once for each compartment that is - * visited while sweeping. Structures that cannot contain references in more - * than one compartment should sweep the relevant per-compartment structures - * using the latter callback to minimizer per-slice overhead. - * - * The argument to JS_UpdateWeakPointerAfterGC() is an in-out param. If the - * referent is about to be finalized the pointer will be set to null. If the - * referent has been moved then the pointer will be updated to point to the new - * location. - * - * Callers of this method are responsible for updating any state that is - * dependent on the object's address. For example, if the object's address is - * used as a key in a hashtable, then the object must be removed and - * re-inserted with the correct hash. - */ - -extern JS_PUBLIC_API(bool) -JS_AddWeakPointerZoneGroupCallback(JSContext* cx, JSWeakPointerZoneGroupCallback cb, void* data); - -extern JS_PUBLIC_API(void) -JS_RemoveWeakPointerZoneGroupCallback(JSContext* cx, JSWeakPointerZoneGroupCallback cb); - -extern JS_PUBLIC_API(bool) -JS_AddWeakPointerCompartmentCallback(JSContext* cx, JSWeakPointerCompartmentCallback cb, - void* data); - -extern JS_PUBLIC_API(void) -JS_RemoveWeakPointerCompartmentCallback(JSContext* cx, JSWeakPointerCompartmentCallback cb); - -extern JS_PUBLIC_API(void) -JS_UpdateWeakPointerAfterGC(JS::Heap* objp); - -extern JS_PUBLIC_API(void) -JS_UpdateWeakPointerAfterGCUnbarriered(JSObject** objp); - -typedef enum JSGCParamKey { - /** Maximum nominal heap before last ditch GC. */ - JSGC_MAX_BYTES = 0, - - /** Number of JS_malloc bytes before last ditch GC. */ - JSGC_MAX_MALLOC_BYTES = 1, - - /** Amount of bytes allocated by the GC. */ - JSGC_BYTES = 3, - - /** Number of times GC has been invoked. Includes both major and minor GC. */ - JSGC_NUMBER = 4, - - /** Select GC mode. */ - JSGC_MODE = 6, - - /** Number of cached empty GC chunks. */ - JSGC_UNUSED_CHUNKS = 7, - - /** Total number of allocated GC chunks. */ - JSGC_TOTAL_CHUNKS = 8, - - /** Max milliseconds to spend in an incremental GC slice. */ - JSGC_SLICE_TIME_BUDGET = 9, - - /** Maximum size the GC mark stack can grow to. */ - JSGC_MARK_STACK_LIMIT = 10, - - /** - * GCs less than this far apart in time will be considered 'high-frequency GCs'. - * See setGCLastBytes in jsgc.cpp. - */ - JSGC_HIGH_FREQUENCY_TIME_LIMIT = 11, - - /** Start of dynamic heap growth. */ - JSGC_HIGH_FREQUENCY_LOW_LIMIT = 12, - - /** End of dynamic heap growth. */ - JSGC_HIGH_FREQUENCY_HIGH_LIMIT = 13, - - /** Upper bound of heap growth. */ - JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX = 14, - - /** Lower bound of heap growth. */ - JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN = 15, - - /** Heap growth for low frequency GCs. */ - JSGC_LOW_FREQUENCY_HEAP_GROWTH = 16, - - /** - * If false, the heap growth factor is fixed at 3. If true, it is determined - * based on whether GCs are high- or low- frequency. - */ - JSGC_DYNAMIC_HEAP_GROWTH = 17, - - /** If true, high-frequency GCs will use a longer mark slice. */ - JSGC_DYNAMIC_MARK_SLICE = 18, - - /** Lower limit after which we limit the heap growth. */ - JSGC_ALLOCATION_THRESHOLD = 19, - - /** - * We try to keep at least this many unused chunks in the free chunk pool at - * all times, even after a shrinking GC. - */ - JSGC_MIN_EMPTY_CHUNK_COUNT = 21, - - /** We never keep more than this many unused chunks in the free chunk pool. */ - JSGC_MAX_EMPTY_CHUNK_COUNT = 22, - - /** Whether compacting GC is enabled. */ - JSGC_COMPACTING_ENABLED = 23, - - /** If true, painting can trigger IGC slices. */ - JSGC_REFRESH_FRAME_SLICES_ENABLED = 24, -} JSGCParamKey; - -extern JS_PUBLIC_API(void) -JS_SetGCParameter(JSContext* cx, JSGCParamKey key, uint32_t value); - -extern JS_PUBLIC_API(uint32_t) -JS_GetGCParameter(JSContext* cx, JSGCParamKey key); - -extern JS_PUBLIC_API(void) -JS_SetGCParametersBasedOnAvailableMemory(JSContext* cx, uint32_t availMem); - -/** - * Create a new JSString whose chars member refers to external memory, i.e., - * memory requiring application-specific finalization. - */ -extern JS_PUBLIC_API(JSString*) -JS_NewExternalString(JSContext* cx, const char16_t* chars, size_t length, - const JSStringFinalizer* fin); - -/** - * Return whether 'str' was created with JS_NewExternalString or - * JS_NewExternalStringWithClosure. - */ -extern JS_PUBLIC_API(bool) -JS_IsExternalString(JSString* str); - -/** - * Return the 'fin' arg passed to JS_NewExternalString. - */ -extern JS_PUBLIC_API(const JSStringFinalizer*) -JS_GetExternalStringFinalizer(JSString* str); - -/** - * Set the size of the native stack that should not be exceed. To disable - * stack size checking pass 0. - * - * SpiderMonkey allows for a distinction between system code (such as GCs, which - * may incidentally be triggered by script but are not strictly performed on - * behalf of such script), trusted script (as determined by JS_SetTrustedPrincipals), - * and untrusted script. Each kind of code may have a different stack quota, - * allowing embedders to keep higher-priority machinery running in the face of - * scripted stack exhaustion by something else. - * - * The stack quotas for each kind of code should be monotonically descending, - * and may be specified with this function. If 0 is passed for a given kind - * of code, it defaults to the value of the next-highest-priority kind. - * - * This function may only be called immediately after the runtime is initialized - * and before any code is executed and/or interrupts requested. - */ -extern JS_PUBLIC_API(void) -JS_SetNativeStackQuota(JSContext* cx, size_t systemCodeStackSize, - size_t trustedScriptStackSize = 0, - size_t untrustedScriptStackSize = 0); - -/************************************************************************/ - -extern JS_PUBLIC_API(bool) -JS_ValueToId(JSContext* cx, JS::HandleValue v, JS::MutableHandleId idp); - -extern JS_PUBLIC_API(bool) -JS_StringToId(JSContext* cx, JS::HandleString s, JS::MutableHandleId idp); - -extern JS_PUBLIC_API(bool) -JS_IdToValue(JSContext* cx, jsid id, JS::MutableHandle vp); - -namespace JS { - -/** - * Convert obj to a primitive value. On success, store the result in vp and - * return true. - * - * The hint argument must be JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_VOID (no - * hint). - * - * Implements: ES6 7.1.1 ToPrimitive(input, [PreferredType]). - */ -extern JS_PUBLIC_API(bool) -ToPrimitive(JSContext* cx, JS::HandleObject obj, JSType hint, JS::MutableHandleValue vp); - -/** - * If args.get(0) is one of the strings "string", "number", or "default", set - * *result to JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_VOID accordingly and - * return true. Otherwise, return false with a TypeError pending. - * - * This can be useful in implementing a @@toPrimitive method. - */ -extern JS_PUBLIC_API(bool) -GetFirstArgumentAsTypeHint(JSContext* cx, CallArgs args, JSType *result); - -} /* namespace JS */ - -extern JS_PUBLIC_API(bool) -JS_PropertyStub(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_StrictPropertyStub(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp, JS::ObjectOpResult& result); - -template -struct JSConstScalarSpec { - const char* name; - T val; -}; - -typedef JSConstScalarSpec JSConstDoubleSpec; -typedef JSConstScalarSpec JSConstIntegerSpec; - -struct JSJitInfo; - -/** - * Wrapper to relace JSNative for JSPropertySpecs and JSFunctionSpecs. This will - * allow us to pass one JSJitInfo per function with the property/function spec, - * without additional field overhead. - */ -typedef struct JSNativeWrapper { - JSNative op; - const JSJitInfo* info; -} JSNativeWrapper; - -/* - * Macro static initializers which make it easy to pass no JSJitInfo as part of a - * JSPropertySpec or JSFunctionSpec. - */ -#define JSNATIVE_WRAPPER(native) { {native, nullptr} } - -/** - * Description of a property. JS_DefineProperties and JS_InitClass take arrays - * of these and define many properties at once. JS_PSG, JS_PSGS and JS_PS_END - * are helper macros for defining such arrays. - */ -struct JSPropertySpec { - struct SelfHostedWrapper { - void* unused; - const char* funname; - }; - - struct ValueWrapper { - uintptr_t type; - union { - const char* string; - int32_t int32; - }; - }; - - const char* name; - uint8_t flags; - union { - struct { - union { - JSNativeWrapper native; - SelfHostedWrapper selfHosted; - } getter; - union { - JSNativeWrapper native; - SelfHostedWrapper selfHosted; - } setter; - } accessors; - ValueWrapper value; - }; - - bool isAccessor() const { - return !(flags & JSPROP_INTERNAL_USE_BIT); - } - bool getValue(JSContext* cx, JS::MutableHandleValue value) const; - - bool isSelfHosted() const { - MOZ_ASSERT(isAccessor()); - -#ifdef DEBUG - // Verify that our accessors match our JSPROP_GETTER flag. - if (flags & JSPROP_GETTER) - checkAccessorsAreSelfHosted(); - else - checkAccessorsAreNative(); -#endif - return (flags & JSPROP_GETTER); - } - - static_assert(sizeof(SelfHostedWrapper) == sizeof(JSNativeWrapper), - "JSPropertySpec::getter/setter must be compact"); - static_assert(offsetof(SelfHostedWrapper, funname) == offsetof(JSNativeWrapper, info), - "JS_SELF_HOSTED* macros below require that " - "SelfHostedWrapper::funname overlay " - "JSNativeWrapper::info"); -private: - void checkAccessorsAreNative() const { - MOZ_ASSERT(accessors.getter.native.op); - // We may not have a setter at all. So all we can assert here, for the - // native case is that if we have a jitinfo for the setter then we have - // a setter op too. This is good enough to make sure we don't have a - // SelfHostedWrapper for the setter. - MOZ_ASSERT_IF(accessors.setter.native.info, accessors.setter.native.op); - } - - void checkAccessorsAreSelfHosted() const { - MOZ_ASSERT(!accessors.getter.selfHosted.unused); - MOZ_ASSERT(!accessors.setter.selfHosted.unused); - } -}; - -namespace JS { -namespace detail { - -/* NEVER DEFINED, DON'T USE. For use by JS_CAST_NATIVE_TO only. */ -inline int CheckIsNative(JSNative native); - -/* NEVER DEFINED, DON'T USE. For use by JS_CAST_STRING_TO only. */ -template -inline int -CheckIsCharacterLiteral(const char (&arr)[N]); - -/* NEVER DEFINED, DON'T USE. For use by JS_CAST_INT32_TO only. */ -inline int CheckIsInt32(int32_t value); - -/* NEVER DEFINED, DON'T USE. For use by JS_PROPERTYOP_GETTER only. */ -inline int CheckIsGetterOp(JSGetterOp op); - -/* NEVER DEFINED, DON'T USE. For use by JS_PROPERTYOP_SETTER only. */ -inline int CheckIsSetterOp(JSSetterOp op); - -} // namespace detail -} // namespace JS - -#define JS_CAST_NATIVE_TO(v, To) \ - (static_cast(sizeof(JS::detail::CheckIsNative(v))), \ - reinterpret_cast(v)) - -#define JS_CAST_STRING_TO(s, To) \ - (static_cast(sizeof(JS::detail::CheckIsCharacterLiteral(s))), \ - reinterpret_cast(s)) - -#define JS_CAST_INT32_TO(s, To) \ - (static_cast(sizeof(JS::detail::CheckIsInt32(s))), \ - reinterpret_cast(s)) - -#define JS_CHECK_ACCESSOR_FLAGS(flags) \ - (static_cast::Type>(0), \ - (flags)) - -#define JS_PROPERTYOP_GETTER(v) \ - (static_cast(sizeof(JS::detail::CheckIsGetterOp(v))), \ - reinterpret_cast(v)) - -#define JS_PROPERTYOP_SETTER(v) \ - (static_cast(sizeof(JS::detail::CheckIsSetterOp(v))), \ - reinterpret_cast(v)) - -#define JS_STUBGETTER JS_PROPERTYOP_GETTER(JS_PropertyStub) - -#define JS_STUBSETTER JS_PROPERTYOP_SETTER(JS_StrictPropertyStub) - -#define JS_PS_ACCESSOR_SPEC(name, getter, setter, flags, extraFlags) \ - { name, uint8_t(JS_CHECK_ACCESSOR_FLAGS(flags) | extraFlags), \ - { { getter, setter } } } -#define JS_PS_VALUE_SPEC(name, value, flags) \ - { name, uint8_t(flags | JSPROP_INTERNAL_USE_BIT), \ - { { value, JSNATIVE_WRAPPER(nullptr) } } } - -#define SELFHOSTED_WRAPPER(name) \ - { { nullptr, JS_CAST_STRING_TO(name, const JSJitInfo*) } } -#define STRINGVALUE_WRAPPER(value) \ - { { reinterpret_cast(JSVAL_TYPE_STRING), JS_CAST_STRING_TO(value, const JSJitInfo*) } } -#define INT32VALUE_WRAPPER(value) \ - { { reinterpret_cast(JSVAL_TYPE_INT32), JS_CAST_INT32_TO(value, const JSJitInfo*) } } - -/* - * JSPropertySpec uses JSNativeWrapper. These macros encapsulate the definition - * of JSNative-backed JSPropertySpecs, by defining the JSNativeWrappers for - * them. - */ -#define JS_PSG(name, getter, flags) \ - JS_PS_ACCESSOR_SPEC(name, JSNATIVE_WRAPPER(getter), JSNATIVE_WRAPPER(nullptr), flags, \ - JSPROP_SHARED) -#define JS_PSGS(name, getter, setter, flags) \ - JS_PS_ACCESSOR_SPEC(name, JSNATIVE_WRAPPER(getter), JSNATIVE_WRAPPER(setter), flags, \ - JSPROP_SHARED) -#define JS_SELF_HOSTED_GET(name, getterName, flags) \ - JS_PS_ACCESSOR_SPEC(name, SELFHOSTED_WRAPPER(getterName), JSNATIVE_WRAPPER(nullptr), flags, \ - JSPROP_SHARED | JSPROP_GETTER) -#define JS_SELF_HOSTED_GETSET(name, getterName, setterName, flags) \ - JS_PS_ACCESSOR_SPEC(name, SELFHOSTED_WRAPPER(getterName), SELFHOSTED_WRAPPER(setterName), \ - flags, JSPROP_SHARED | JSPROP_GETTER | JSPROP_SETTER) -#define JS_SELF_HOSTED_SYM_GET(symbol, getterName, flags) \ - JS_PS_ACCESSOR_SPEC(reinterpret_cast(uint32_t(::JS::SymbolCode::symbol) + 1), \ - SELFHOSTED_WRAPPER(getterName), JSNATIVE_WRAPPER(nullptr), flags, \ - JSPROP_SHARED | JSPROP_GETTER) -#define JS_STRING_PS(name, string, flags) \ - JS_PS_VALUE_SPEC(name, STRINGVALUE_WRAPPER(string), flags) -#define JS_STRING_SYM_PS(symbol, string, flags) \ - JS_PS_VALUE_SPEC(reinterpret_cast(uint32_t(::JS::SymbolCode::symbol) + 1), \ - STRINGVALUE_WRAPPER(string), flags) -#define JS_INT32_PS(name, value, flags) \ - JS_PS_VALUE_SPEC(name, INT32VALUE_WRAPPER(value), flags) -#define JS_PS_END \ - JS_PS_ACCESSOR_SPEC(nullptr, JSNATIVE_WRAPPER(nullptr), JSNATIVE_WRAPPER(nullptr), 0, 0) - -/** - * To define a native function, set call to a JSNativeWrapper. To define a - * self-hosted function, set selfHostedName to the name of a function - * compiled during JSRuntime::initSelfHosting. - */ -struct JSFunctionSpec { - const char* name; - JSNativeWrapper call; - uint16_t nargs; - uint16_t flags; - const char* selfHostedName; -}; - -/* - * Terminating sentinel initializer to put at the end of a JSFunctionSpec array - * that's passed to JS_DefineFunctions or JS_InitClass. - */ -#define JS_FS_END JS_FS(nullptr,nullptr,0,0) - -/* - * Initializer macros for a JSFunctionSpec array element. JS_FN (whose name pays - * homage to the old JSNative/JSFastNative split) simply adds the flag - * JSFUN_STUB_GSOPS. JS_FNINFO allows the simple adding of - * JSJitInfos. JS_SELF_HOSTED_FN declares a self-hosted function. - * JS_INLINABLE_FN allows specifying an InlinableNative enum value for natives - * inlined or specialized by the JIT. Finally JS_FNSPEC has slots for all the - * fields. - * - * The _SYM variants allow defining a function with a symbol key rather than a - * string key. For example, use JS_SYM_FN(iterator, ...) to define an - * @@iterator method. - */ -#define JS_FS(name,call,nargs,flags) \ - JS_FNSPEC(name, call, nullptr, nargs, flags, nullptr) -#define JS_FN(name,call,nargs,flags) \ - JS_FNSPEC(name, call, nullptr, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr) -#define JS_INLINABLE_FN(name,call,nargs,flags,native) \ - JS_FNSPEC(name, call, &js::jit::JitInfo_##native, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr) -#define JS_SYM_FN(symbol,call,nargs,flags) \ - JS_SYM_FNSPEC(symbol, call, nullptr, nargs, (flags) | JSFUN_STUB_GSOPS, nullptr) -#define JS_FNINFO(name,call,info,nargs,flags) \ - JS_FNSPEC(name, call, info, nargs, flags, nullptr) -#define JS_SELF_HOSTED_FN(name,selfHostedName,nargs,flags) \ - JS_FNSPEC(name, nullptr, nullptr, nargs, flags, selfHostedName) -#define JS_SELF_HOSTED_SYM_FN(symbol, selfHostedName, nargs, flags) \ - JS_SYM_FNSPEC(symbol, nullptr, nullptr, nargs, flags, selfHostedName) -#define JS_SYM_FNSPEC(symbol, call, info, nargs, flags, selfHostedName) \ - JS_FNSPEC(reinterpret_cast( \ - uint32_t(::JS::SymbolCode::symbol) + 1), \ - call, info, nargs, flags, selfHostedName) -#define JS_FNSPEC(name,call,info,nargs,flags,selfHostedName) \ - {name, {call, info}, nargs, flags, selfHostedName} - -extern JS_PUBLIC_API(JSObject*) -JS_InitClass(JSContext* cx, JS::HandleObject obj, JS::HandleObject parent_proto, - const JSClass* clasp, JSNative constructor, unsigned nargs, - const JSPropertySpec* ps, const JSFunctionSpec* fs, - const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs); - -/** - * Set up ctor.prototype = proto and proto.constructor = ctor with the - * right property flags. - */ -extern JS_PUBLIC_API(bool) -JS_LinkConstructorAndPrototype(JSContext* cx, JS::Handle ctor, - JS::Handle proto); - -extern JS_PUBLIC_API(const JSClass*) -JS_GetClass(JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_InstanceOf(JSContext* cx, JS::Handle obj, const JSClass* clasp, JS::CallArgs* args); - -extern JS_PUBLIC_API(bool) -JS_HasInstance(JSContext* cx, JS::Handle obj, JS::Handle v, bool* bp); - -namespace JS { - -// Implementation of -// http://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance. If -// you're looking for the equivalent of "instanceof", you want JS_HasInstance, -// not this function. -extern JS_PUBLIC_API(bool) -OrdinaryHasInstance(JSContext* cx, HandleObject objArg, HandleValue v, bool* bp); - -} // namespace JS - -extern JS_PUBLIC_API(void*) -JS_GetPrivate(JSObject* obj); - -extern JS_PUBLIC_API(void) -JS_SetPrivate(JSObject* obj, void* data); - -extern JS_PUBLIC_API(void*) -JS_GetInstancePrivate(JSContext* cx, JS::Handle obj, const JSClass* clasp, - JS::CallArgs* args); - -extern JS_PUBLIC_API(JSObject*) -JS_GetConstructor(JSContext* cx, JS::Handle proto); - -namespace JS { - -enum ZoneSpecifier { - FreshZone = 0, - SystemZone = 1 -}; - -/** - * CompartmentCreationOptions specifies options relevant to creating a new - * compartment, that are either immutable characteristics of that compartment - * or that are discarded after the compartment has been created. - * - * Access to these options on an existing compartment is read-only: if you - * need particular selections, make them before you create the compartment. - */ -class JS_PUBLIC_API(CompartmentCreationOptions) -{ - public: - CompartmentCreationOptions() - : addonId_(nullptr), - traceGlobal_(nullptr), - invisibleToDebugger_(false), - mergeable_(false), - preserveJitCode_(false), - cloneSingletons_(false), - sharedMemoryAndAtomics_(false), - secureContext_(false) - { - zone_.spec = JS::FreshZone; - } - - // A null add-on ID means that the compartment is not associated with an - // add-on. - JSAddonId* addonIdOrNull() const { return addonId_; } - CompartmentCreationOptions& setAddonId(JSAddonId* id) { - addonId_ = id; - return *this; - } - - JSTraceOp getTrace() const { - return traceGlobal_; - } - CompartmentCreationOptions& setTrace(JSTraceOp op) { - traceGlobal_ = op; - return *this; - } - - void* zonePointer() const { - MOZ_ASSERT(uintptr_t(zone_.pointer) > uintptr_t(JS::SystemZone)); - return zone_.pointer; - } - ZoneSpecifier zoneSpecifier() const { return zone_.spec; } - CompartmentCreationOptions& setZone(ZoneSpecifier spec); - CompartmentCreationOptions& setSameZoneAs(JSObject* obj); - - // Certain scopes (i.e. XBL compilation scopes) are implementation details - // of the embedding, and references to them should never leak out to script. - // This flag causes the this compartment to skip firing onNewGlobalObject - // and makes addDebuggee a no-op for this global. - bool invisibleToDebugger() const { return invisibleToDebugger_; } - CompartmentCreationOptions& setInvisibleToDebugger(bool flag) { - invisibleToDebugger_ = flag; - return *this; - } - - // Compartments used for off-thread compilation have their contents merged - // into a target compartment when the compilation is finished. This is only - // allowed if this flag is set. The invisibleToDebugger flag must also be - // set for such compartments. - bool mergeable() const { return mergeable_; } - CompartmentCreationOptions& setMergeable(bool flag) { - mergeable_ = flag; - return *this; - } - - // Determines whether this compartment should preserve JIT code on - // non-shrinking GCs. - bool preserveJitCode() const { return preserveJitCode_; } - CompartmentCreationOptions& setPreserveJitCode(bool flag) { - preserveJitCode_ = flag; - return *this; - } - - bool cloneSingletons() const { return cloneSingletons_; } - CompartmentCreationOptions& setCloneSingletons(bool flag) { - cloneSingletons_ = flag; - return *this; - } - - bool getSharedMemoryAndAtomicsEnabled() const; - CompartmentCreationOptions& setSharedMemoryAndAtomicsEnabled(bool flag); - - // This flag doesn't affect JS engine behavior. It is used by Gecko to - // mark whether content windows and workers are "Secure Context"s. See - // https://w3c.github.io/webappsec-secure-contexts/ - // https://bugzilla.mozilla.org/show_bug.cgi?id=1162772#c34 - bool secureContext() const { return secureContext_; } - CompartmentCreationOptions& setSecureContext(bool flag) { - secureContext_ = flag; - return *this; - } - - private: - JSAddonId* addonId_; - JSTraceOp traceGlobal_; - union { - ZoneSpecifier spec; - void* pointer; // js::Zone* is not exposed in the API. - } zone_; - bool invisibleToDebugger_; - bool mergeable_; - bool preserveJitCode_; - bool cloneSingletons_; - bool sharedMemoryAndAtomics_; - bool secureContext_; -}; - -/** - * CompartmentBehaviors specifies behaviors of a compartment that can be - * changed after the compartment's been created. - */ -class JS_PUBLIC_API(CompartmentBehaviors) -{ - public: - class Override { - public: - Override() : mode_(Default) {} - - bool get(bool defaultValue) const { - if (mode_ == Default) - return defaultValue; - return mode_ == ForceTrue; - } - - void set(bool overrideValue) { - mode_ = overrideValue ? ForceTrue : ForceFalse; - } - - void reset() { - mode_ = Default; - } - - private: - enum Mode { - Default, - ForceTrue, - ForceFalse - }; - - Mode mode_; - }; - - CompartmentBehaviors() - : version_(JSVERSION_UNKNOWN) - , discardSource_(false) - , disableLazyParsing_(false) - , singletonsAsTemplates_(true) - { - } - - JSVersion version() const { return version_; } - CompartmentBehaviors& setVersion(JSVersion aVersion) { - MOZ_ASSERT(aVersion != JSVERSION_UNKNOWN); - version_ = aVersion; - return *this; - } - - // For certain globals, we know enough about the code that will run in them - // that we can discard script source entirely. - bool discardSource() const { return discardSource_; } - CompartmentBehaviors& setDiscardSource(bool flag) { - discardSource_ = flag; - return *this; - } - - bool disableLazyParsing() const { return disableLazyParsing_; } - CompartmentBehaviors& setDisableLazyParsing(bool flag) { - disableLazyParsing_ = flag; - return *this; - } - - bool extraWarnings(JSContext* cx) const; - Override& extraWarningsOverride() { return extraWarningsOverride_; } - - bool getSingletonsAsTemplates() const { - return singletonsAsTemplates_; - } - CompartmentBehaviors& setSingletonsAsValues() { - singletonsAsTemplates_ = false; - return *this; - } - - private: - JSVersion version_; - bool discardSource_; - bool disableLazyParsing_; - Override extraWarningsOverride_; - - // To XDR singletons, we need to ensure that all singletons are all used as - // templates, by making JSOP_OBJECT return a clone of the JSScript - // singleton, instead of returning the value which is baked in the JSScript. - bool singletonsAsTemplates_; -}; - -/** - * CompartmentOptions specifies compartment characteristics: both those that - * can't be changed on a compartment once it's been created - * (CompartmentCreationOptions), and those that can be changed on an existing - * compartment (CompartmentBehaviors). - */ -class JS_PUBLIC_API(CompartmentOptions) -{ - public: - explicit CompartmentOptions() - : creationOptions_(), - behaviors_() - {} - - CompartmentOptions(const CompartmentCreationOptions& compartmentCreation, - const CompartmentBehaviors& compartmentBehaviors) - : creationOptions_(compartmentCreation), - behaviors_(compartmentBehaviors) - {} - - // CompartmentCreationOptions specify fundamental compartment - // characteristics that must be specified when the compartment is created, - // that can't be changed after the compartment is created. - CompartmentCreationOptions& creationOptions() { - return creationOptions_; - } - const CompartmentCreationOptions& creationOptions() const { - return creationOptions_; - } - - // CompartmentBehaviors specify compartment characteristics that can be - // changed after the compartment is created. - CompartmentBehaviors& behaviors() { - return behaviors_; - } - const CompartmentBehaviors& behaviors() const { - return behaviors_; - } - - private: - CompartmentCreationOptions creationOptions_; - CompartmentBehaviors behaviors_; -}; - -JS_PUBLIC_API(const CompartmentCreationOptions&) -CompartmentCreationOptionsRef(JSCompartment* compartment); - -JS_PUBLIC_API(const CompartmentCreationOptions&) -CompartmentCreationOptionsRef(JSObject* obj); - -JS_PUBLIC_API(const CompartmentCreationOptions&) -CompartmentCreationOptionsRef(JSContext* cx); - -JS_PUBLIC_API(CompartmentBehaviors&) -CompartmentBehaviorsRef(JSCompartment* compartment); - -JS_PUBLIC_API(CompartmentBehaviors&) -CompartmentBehaviorsRef(JSObject* obj); - -JS_PUBLIC_API(CompartmentBehaviors&) -CompartmentBehaviorsRef(JSContext* cx); - -/** - * During global creation, we fire notifications to callbacks registered - * via the Debugger API. These callbacks are arbitrary script, and can touch - * the global in arbitrary ways. When that happens, the global should not be - * in a half-baked state. But this creates a problem for consumers that need - * to set slots on the global to put it in a consistent state. - * - * This API provides a way for consumers to set slots atomically (immediately - * after the global is created), before any debugger hooks are fired. It's - * unfortunately on the clunky side, but that's the way the cookie crumbles. - * - * If callers have no additional state on the global to set up, they may pass - * |FireOnNewGlobalHook| to JS_NewGlobalObject, which causes that function to - * fire the hook as its final act before returning. Otherwise, callers should - * pass |DontFireOnNewGlobalHook|, which means that they are responsible for - * invoking JS_FireOnNewGlobalObject upon successfully creating the global. If - * an error occurs and the operation aborts, callers should skip firing the - * hook. But otherwise, callers must take care to fire the hook exactly once - * before compiling any script in the global's scope (we have assertions in - * place to enforce this). This lets us be sure that debugger clients never miss - * breakpoints. - */ -enum OnNewGlobalHookOption { - FireOnNewGlobalHook, - DontFireOnNewGlobalHook -}; - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSObject*) -JS_NewGlobalObject(JSContext* cx, const JSClass* clasp, JSPrincipals* principals, - JS::OnNewGlobalHookOption hookOption, - const JS::CompartmentOptions& options); -/** - * Spidermonkey does not have a good way of keeping track of what compartments should be marked on - * their own. We can mark the roots unconditionally, but marking GC things only relevant in live - * compartments is hard. To mitigate this, we create a static trace hook, installed on each global - * object, from which we can be sure the compartment is relevant, and mark it. - * - * It is still possible to specify custom trace hooks for global object classes. They can be - * provided via the CompartmentOptions passed to JS_NewGlobalObject. - */ -extern JS_PUBLIC_API(void) -JS_GlobalObjectTraceHook(JSTracer* trc, JSObject* global); - -extern JS_PUBLIC_API(void) -JS_FireOnNewGlobalObject(JSContext* cx, JS::HandleObject global); - -extern JS_PUBLIC_API(JSObject*) -JS_NewObject(JSContext* cx, const JSClass* clasp); - -extern JS_PUBLIC_API(bool) -JS_IsNative(JSObject* obj); - -/** - * Unlike JS_NewObject, JS_NewObjectWithGivenProto does not compute a default - * proto. If proto is nullptr, the JS object will have `null` as [[Prototype]]. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewObjectWithGivenProto(JSContext* cx, const JSClass* clasp, JS::Handle proto); - -/** Creates a new plain object, like `new Object()`, with Object.prototype as [[Prototype]]. */ -extern JS_PUBLIC_API(JSObject*) -JS_NewPlainObject(JSContext* cx); - -/** - * Freeze obj, and all objects it refers to, recursively. This will not recurse - * through non-extensible objects, on the assumption that those are already - * deep-frozen. - */ -extern JS_PUBLIC_API(bool) -JS_DeepFreezeObject(JSContext* cx, JS::Handle obj); - -/** - * Freezes an object; see ES5's Object.freeze(obj) method. - */ -extern JS_PUBLIC_API(bool) -JS_FreezeObject(JSContext* cx, JS::Handle obj); - - -/*** Property descriptors ************************************************************************/ - -namespace JS { - -struct JS_PUBLIC_API(PropertyDescriptor) { - JSObject* obj; - unsigned attrs; - JSGetterOp getter; - JSSetterOp setter; - JS::Value value; - - PropertyDescriptor() - : obj(nullptr), attrs(0), getter(nullptr), setter(nullptr), value(JS::UndefinedValue()) - {} - - static void trace(PropertyDescriptor* self, JSTracer* trc) { self->trace(trc); } - void trace(JSTracer* trc); -}; - -template -class PropertyDescriptorOperations -{ - const PropertyDescriptor& desc() const { return static_cast(this)->get(); } - - bool has(unsigned bit) const { - MOZ_ASSERT(bit != 0); - MOZ_ASSERT((bit & (bit - 1)) == 0); // only a single bit - return (desc().attrs & bit) != 0; - } - - bool hasAny(unsigned bits) const { - return (desc().attrs & bits) != 0; - } - - bool hasAll(unsigned bits) const { - return (desc().attrs & bits) == bits; - } - - // Non-API attributes bit used internally for arguments objects. - enum { SHADOWABLE = JSPROP_INTERNAL_USE_BIT }; - - public: - // Descriptors with JSGetterOp/JSSetterOp are considered data - // descriptors. It's complicated. - bool isAccessorDescriptor() const { return hasAny(JSPROP_GETTER | JSPROP_SETTER); } - bool isGenericDescriptor() const { - return (desc().attrs& - (JSPROP_GETTER | JSPROP_SETTER | JSPROP_IGNORE_READONLY | JSPROP_IGNORE_VALUE)) == - (JSPROP_IGNORE_READONLY | JSPROP_IGNORE_VALUE); - } - bool isDataDescriptor() const { return !isAccessorDescriptor() && !isGenericDescriptor(); } - - bool hasConfigurable() const { return !has(JSPROP_IGNORE_PERMANENT); } - bool configurable() const { MOZ_ASSERT(hasConfigurable()); return !has(JSPROP_PERMANENT); } - - bool hasEnumerable() const { return !has(JSPROP_IGNORE_ENUMERATE); } - bool enumerable() const { MOZ_ASSERT(hasEnumerable()); return has(JSPROP_ENUMERATE); } - - bool hasValue() const { return !isAccessorDescriptor() && !has(JSPROP_IGNORE_VALUE); } - JS::HandleValue value() const { - return JS::HandleValue::fromMarkedLocation(&desc().value); - } - - bool hasWritable() const { return !isAccessorDescriptor() && !has(JSPROP_IGNORE_READONLY); } - bool writable() const { MOZ_ASSERT(hasWritable()); return !has(JSPROP_READONLY); } - - bool hasGetterObject() const { return has(JSPROP_GETTER); } - JS::HandleObject getterObject() const { - MOZ_ASSERT(hasGetterObject()); - return JS::HandleObject::fromMarkedLocation( - reinterpret_cast(&desc().getter)); - } - bool hasSetterObject() const { return has(JSPROP_SETTER); } - JS::HandleObject setterObject() const { - MOZ_ASSERT(hasSetterObject()); - return JS::HandleObject::fromMarkedLocation( - reinterpret_cast(&desc().setter)); - } - - bool hasGetterOrSetter() const { return desc().getter || desc().setter; } - bool isShared() const { return has(JSPROP_SHARED); } - - JS::HandleObject object() const { - return JS::HandleObject::fromMarkedLocation(&desc().obj); - } - unsigned attributes() const { return desc().attrs; } - JSGetterOp getter() const { return desc().getter; } - JSSetterOp setter() const { return desc().setter; } - - void assertValid() const { -#ifdef DEBUG - MOZ_ASSERT((attributes() & ~(JSPROP_ENUMERATE | JSPROP_IGNORE_ENUMERATE | - JSPROP_PERMANENT | JSPROP_IGNORE_PERMANENT | - JSPROP_READONLY | JSPROP_IGNORE_READONLY | - JSPROP_IGNORE_VALUE | - JSPROP_GETTER | - JSPROP_SETTER | - JSPROP_SHARED | - JSPROP_REDEFINE_NONCONFIGURABLE | - JSPROP_RESOLVING | - SHADOWABLE)) == 0); - MOZ_ASSERT(!hasAll(JSPROP_IGNORE_ENUMERATE | JSPROP_ENUMERATE)); - MOZ_ASSERT(!hasAll(JSPROP_IGNORE_PERMANENT | JSPROP_PERMANENT)); - if (isAccessorDescriptor()) { - MOZ_ASSERT(has(JSPROP_SHARED)); - MOZ_ASSERT(!has(JSPROP_READONLY)); - MOZ_ASSERT(!has(JSPROP_IGNORE_READONLY)); - MOZ_ASSERT(!has(JSPROP_IGNORE_VALUE)); - MOZ_ASSERT(!has(SHADOWABLE)); - MOZ_ASSERT(value().isUndefined()); - MOZ_ASSERT_IF(!has(JSPROP_GETTER), !getter()); - MOZ_ASSERT_IF(!has(JSPROP_SETTER), !setter()); - } else { - MOZ_ASSERT(!hasAll(JSPROP_IGNORE_READONLY | JSPROP_READONLY)); - MOZ_ASSERT_IF(has(JSPROP_IGNORE_VALUE), value().isUndefined()); - } - MOZ_ASSERT(getter() != JS_PropertyStub); - MOZ_ASSERT(setter() != JS_StrictPropertyStub); - - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_ENUMERATE)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_PERMANENT)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_READONLY)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_IGNORE_VALUE)); - MOZ_ASSERT_IF(has(JSPROP_RESOLVING), !has(JSPROP_REDEFINE_NONCONFIGURABLE)); -#endif - } - - void assertComplete() const { -#ifdef DEBUG - assertValid(); - MOZ_ASSERT((attributes() & ~(JSPROP_ENUMERATE | - JSPROP_PERMANENT | - JSPROP_READONLY | - JSPROP_GETTER | - JSPROP_SETTER | - JSPROP_SHARED | - JSPROP_REDEFINE_NONCONFIGURABLE | - JSPROP_RESOLVING | - SHADOWABLE)) == 0); - MOZ_ASSERT_IF(isAccessorDescriptor(), has(JSPROP_GETTER) && has(JSPROP_SETTER)); -#endif - } - - void assertCompleteIfFound() const { -#ifdef DEBUG - if (object()) - assertComplete(); -#endif - } -}; - -template -class MutablePropertyDescriptorOperations : public PropertyDescriptorOperations -{ - PropertyDescriptor& desc() { return static_cast(this)->get(); } - - public: - void clear() { - object().set(nullptr); - setAttributes(0); - setGetter(nullptr); - setSetter(nullptr); - value().setUndefined(); - } - - void initFields(HandleObject obj, HandleValue v, unsigned attrs, - JSGetterOp getterOp, JSSetterOp setterOp) { - MOZ_ASSERT(getterOp != JS_PropertyStub); - MOZ_ASSERT(setterOp != JS_StrictPropertyStub); - - object().set(obj); - value().set(v); - setAttributes(attrs); - setGetter(getterOp); - setSetter(setterOp); - } - - void assign(PropertyDescriptor& other) { - object().set(other.obj); - setAttributes(other.attrs); - setGetter(other.getter); - setSetter(other.setter); - value().set(other.value); - } - - void setDataDescriptor(HandleValue v, unsigned attrs) { - MOZ_ASSERT((attrs & ~(JSPROP_ENUMERATE | - JSPROP_PERMANENT | - JSPROP_READONLY | - JSPROP_IGNORE_ENUMERATE | - JSPROP_IGNORE_PERMANENT | - JSPROP_IGNORE_READONLY)) == 0); - object().set(nullptr); - setAttributes(attrs); - setGetter(nullptr); - setSetter(nullptr); - value().set(v); - } - - JS::MutableHandleObject object() { - return JS::MutableHandleObject::fromMarkedLocation(&desc().obj); - } - unsigned& attributesRef() { return desc().attrs; } - JSGetterOp& getter() { return desc().getter; } - JSSetterOp& setter() { return desc().setter; } - JS::MutableHandleValue value() { - return JS::MutableHandleValue::fromMarkedLocation(&desc().value); - } - void setValue(JS::HandleValue v) { - MOZ_ASSERT(!(desc().attrs & (JSPROP_GETTER | JSPROP_SETTER))); - attributesRef() &= ~JSPROP_IGNORE_VALUE; - value().set(v); - } - - void setConfigurable(bool configurable) { - setAttributes((desc().attrs & ~(JSPROP_IGNORE_PERMANENT | JSPROP_PERMANENT)) | - (configurable ? 0 : JSPROP_PERMANENT)); - } - void setEnumerable(bool enumerable) { - setAttributes((desc().attrs & ~(JSPROP_IGNORE_ENUMERATE | JSPROP_ENUMERATE)) | - (enumerable ? JSPROP_ENUMERATE : 0)); - } - void setWritable(bool writable) { - MOZ_ASSERT(!(desc().attrs & (JSPROP_GETTER | JSPROP_SETTER))); - setAttributes((desc().attrs & ~(JSPROP_IGNORE_READONLY | JSPROP_READONLY)) | - (writable ? 0 : JSPROP_READONLY)); - } - void setAttributes(unsigned attrs) { desc().attrs = attrs; } - - void setGetter(JSGetterOp op) { - MOZ_ASSERT(op != JS_PropertyStub); - desc().getter = op; - } - void setSetter(JSSetterOp op) { - MOZ_ASSERT(op != JS_StrictPropertyStub); - desc().setter = op; - } - void setGetterObject(JSObject* obj) { - desc().getter = reinterpret_cast(obj); - desc().attrs &= ~(JSPROP_IGNORE_VALUE | JSPROP_IGNORE_READONLY | JSPROP_READONLY); - desc().attrs |= JSPROP_GETTER | JSPROP_SHARED; - } - void setSetterObject(JSObject* obj) { - desc().setter = reinterpret_cast(obj); - desc().attrs &= ~(JSPROP_IGNORE_VALUE | JSPROP_IGNORE_READONLY | JSPROP_READONLY); - desc().attrs |= JSPROP_SETTER | JSPROP_SHARED; - } - - JS::MutableHandleObject getterObject() { - MOZ_ASSERT(this->hasGetterObject()); - return JS::MutableHandleObject::fromMarkedLocation( - reinterpret_cast(&desc().getter)); - } - JS::MutableHandleObject setterObject() { - MOZ_ASSERT(this->hasSetterObject()); - return JS::MutableHandleObject::fromMarkedLocation( - reinterpret_cast(&desc().setter)); - } -}; - -} /* namespace JS */ - -namespace js { - -template <> -class RootedBase - : public JS::MutablePropertyDescriptorOperations> -{}; - -template <> -class HandleBase - : public JS::PropertyDescriptorOperations> -{}; - -template <> -class MutableHandleBase - : public JS::MutablePropertyDescriptorOperations> -{}; - -} /* namespace js */ - -namespace JS { - -extern JS_PUBLIC_API(bool) -ObjectToCompletePropertyDescriptor(JSContext* cx, - JS::HandleObject obj, - JS::HandleValue descriptor, - JS::MutableHandle desc); - -/* - * ES6 draft rev 32 (2015 Feb 2) 6.2.4.4 FromPropertyDescriptor(Desc). - * - * If desc.object() is null, then vp is set to undefined. - */ -extern JS_PUBLIC_API(bool) -FromPropertyDescriptor(JSContext* cx, - JS::Handle desc, - JS::MutableHandleValue vp); - -} // namespace JS - - -/*** Standard internal methods ******************************************************************** - * - * The functions below are the fundamental operations on objects. - * - * ES6 specifies 14 internal methods that define how objects behave. The - * standard is actually quite good on this topic, though you may have to read - * it a few times. See ES6 sections 6.1.7.2 and 6.1.7.3. - * - * When 'obj' is an ordinary object, these functions have boring standard - * behavior as specified by ES6 section 9.1; see the section about internal - * methods in js/src/vm/NativeObject.h. - * - * Proxies override the behavior of internal methods. So when 'obj' is a proxy, - * any one of the functions below could do just about anything. See - * js/public/Proxy.h. - */ - -/** - * Get the prototype of obj, storing it in result. - * - * Implements: ES6 [[GetPrototypeOf]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_GetPrototype(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject result); - -/** - * If |obj| (underneath any functionally-transparent wrapper proxies) has as - * its [[GetPrototypeOf]] trap the ordinary [[GetPrototypeOf]] behavior defined - * for ordinary objects, set |*isOrdinary = true| and store |obj|'s prototype - * in |result|. Otherwise set |*isOrdinary = false|. In case of error, both - * outparams have unspecified value. - */ -extern JS_PUBLIC_API(bool) -JS_GetPrototypeIfOrdinary(JSContext* cx, JS::HandleObject obj, bool* isOrdinary, - JS::MutableHandleObject result); - -/** - * Change the prototype of obj. - * - * Implements: ES6 [[SetPrototypeOf]] internal method. - * - * In cases where ES6 [[SetPrototypeOf]] returns false without an exception, - * JS_SetPrototype throws a TypeError and returns false. - * - * Performance warning: JS_SetPrototype is very bad for performance. It may - * cause compiled jit-code to be invalidated. It also causes not only obj but - * all other objects in the same "group" as obj to be permanently deoptimized. - * It's better to create the object with the right prototype from the start. - */ -extern JS_PUBLIC_API(bool) -JS_SetPrototype(JSContext* cx, JS::HandleObject obj, JS::HandleObject proto); - -/** - * Determine whether obj is extensible. Extensible objects can have new - * properties defined on them. Inextensible objects can't, and their - * [[Prototype]] slot is fixed as well. - * - * Implements: ES6 [[IsExtensible]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_IsExtensible(JSContext* cx, JS::HandleObject obj, bool* extensible); - -/** - * Attempt to make |obj| non-extensible. - * - * Not all failures are treated as errors. See the comment on - * JS::ObjectOpResult in js/public/Class.h. - * - * Implements: ES6 [[PreventExtensions]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_PreventExtensions(JSContext* cx, JS::HandleObject obj, JS::ObjectOpResult& result); - -/** - * Attempt to make the [[Prototype]] of |obj| immutable, such that any attempt - * to modify it will fail. If an error occurs during the attempt, return false - * (with a pending exception set, depending upon the nature of the error). If - * no error occurs, return true with |*succeeded| set to indicate whether the - * attempt successfully made the [[Prototype]] immutable. - * - * This is a nonstandard internal method. - */ -extern JS_PUBLIC_API(bool) -JS_SetImmutablePrototype(JSContext* cx, JS::HandleObject obj, bool* succeeded); - -/** - * Get a description of one of obj's own properties. If no such property exists - * on obj, return true with desc.object() set to null. - * - * Implements: ES6 [[GetOwnProperty]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_GetOwnPropertyDescriptorById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); - -extern JS_PUBLIC_API(bool) -JS_GetOwnPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char* name, - JS::MutableHandle desc); - -extern JS_PUBLIC_API(bool) -JS_GetOwnUCPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char16_t* name, - JS::MutableHandle desc); - -/** - * Like JS_GetOwnPropertyDescriptorById, but also searches the prototype chain - * if no own property is found directly on obj. The object on which the - * property is found is returned in desc.object(). If the property is not found - * on the prototype chain, this returns true with desc.object() set to null. - */ -extern JS_PUBLIC_API(bool) -JS_GetPropertyDescriptorById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); - -extern JS_PUBLIC_API(bool) -JS_GetPropertyDescriptor(JSContext* cx, JS::HandleObject obj, const char* name, - JS::MutableHandle desc); - -/** - * Define a property on obj. - * - * This function uses JS::ObjectOpResult to indicate conditions that ES6 - * specifies as non-error failures. This is inconvenient at best, so use this - * function only if you are implementing a proxy handler's defineProperty() - * method. For all other purposes, use one of the many DefineProperty functions - * below that throw an exception in all failure cases. - * - * Implements: ES6 [[DefineOwnProperty]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc, - JS::ObjectOpResult& result); - -/** - * Define a property on obj, throwing a TypeError if the attempt fails. - * This is the C++ equivalent of `Object.defineProperty(obj, id, desc)`. - */ -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleString value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, int32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, uint32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefinePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, double value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleValue value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleObject value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleString value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, int32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, uint32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineProperty(JSContext* cx, JS::HandleObject obj, const char* name, double value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::Handle desc, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::Handle desc); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleValue value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleObject value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleString value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - int32_t value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - uint32_t value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - double value, unsigned attrs, - JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleValue value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleObject value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleString value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, int32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, uint32_t value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -extern JS_PUBLIC_API(bool) -JS_DefineElement(JSContext* cx, JS::HandleObject obj, uint32_t index, double value, - unsigned attrs, JSNative getter = nullptr, JSNative setter = nullptr); - -/** - * Compute the expression `id in obj`. - * - * If obj has an own or inherited property obj[id], set *foundp = true and - * return true. If not, set *foundp = false and return true. On error, return - * false with an exception pending. - * - * Implements: ES6 [[Has]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_HasPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_HasProperty(JSContext* cx, JS::HandleObject obj, const char* name, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_HasUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - bool* vp); - -extern JS_PUBLIC_API(bool) -JS_HasElement(JSContext* cx, JS::HandleObject obj, uint32_t index, bool* foundp); - -/** - * Determine whether obj has an own property with the key `id`. - * - * Implements: ES6 7.3.11 HasOwnProperty(O, P). - */ -extern JS_PUBLIC_API(bool) -JS_HasOwnPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_HasOwnProperty(JSContext* cx, JS::HandleObject obj, const char* name, bool* foundp); - -/** - * Get the value of the property `obj[id]`, or undefined if no such property - * exists. This is the C++ equivalent of `vp = Reflect.get(obj, id, receiver)`. - * - * Most callers don't need the `receiver` argument. Consider using - * JS_GetProperty instead. (But if you're implementing a proxy handler's set() - * method, it's often correct to call this function and pass the receiver - * through.) - * - * Implements: ES6 [[Get]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_ForwardGetPropertyTo(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::HandleValue receiver, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_ForwardGetElementTo(JSContext* cx, JS::HandleObject obj, uint32_t index, - JS::HandleObject receiver, JS::MutableHandleValue vp); - -/** - * Get the value of the property `obj[id]`, or undefined if no such property - * exists. The result is stored in vp. - * - * Implements: ES6 7.3.1 Get(O, P). - */ -extern JS_PUBLIC_API(bool) -JS_GetPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_GetProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_GetUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(bool) -JS_GetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::MutableHandleValue vp); - -/** - * Perform the same property assignment as `Reflect.set(obj, id, v, receiver)`. - * - * This function has a `receiver` argument that most callers don't need. - * Consider using JS_SetProperty instead. - * - * Implements: ES6 [[Set]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_ForwardSetPropertyTo(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v, - JS::HandleValue receiver, JS::ObjectOpResult& result); - -/** - * Perform the assignment `obj[id] = v`. - * - * This function performs non-strict assignment, so if the property is - * read-only, nothing happens and no error is thrown. - */ -extern JS_PUBLIC_API(bool) -JS_SetPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetProperty(JSContext* cx, JS::HandleObject obj, const char* name, JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleValue v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleObject v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::HandleString v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, int32_t v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, uint32_t v); - -extern JS_PUBLIC_API(bool) -JS_SetElement(JSContext* cx, JS::HandleObject obj, uint32_t index, double v); - -/** - * Delete a property. This is the C++ equivalent of - * `result = Reflect.deleteProperty(obj, id)`. - * - * This function has a `result` out parameter that most callers don't need. - * Unless you can pass through an ObjectOpResult provided by your caller, it's - * probably best to use the JS_DeletePropertyById signature with just 3 - * arguments. - * - * Implements: ES6 [[Delete]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_DeletePropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DeleteProperty(JSContext* cx, JS::HandleObject obj, const char* name, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DeleteUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, size_t namelen, - JS::ObjectOpResult& result); - -extern JS_PUBLIC_API(bool) -JS_DeleteElement(JSContext* cx, JS::HandleObject obj, uint32_t index, JS::ObjectOpResult& result); - -/** - * Delete a property, ignoring strict failures. This is the C++ equivalent of - * the JS `delete obj[id]` in non-strict mode code. - */ -extern JS_PUBLIC_API(bool) -JS_DeletePropertyById(JSContext* cx, JS::HandleObject obj, jsid id); - -extern JS_PUBLIC_API(bool) -JS_DeleteProperty(JSContext* cx, JS::HandleObject obj, const char* name); - -extern JS_PUBLIC_API(bool) -JS_DeleteElement(JSContext* cx, JS::HandleObject obj, uint32_t index); - -/** - * Get an array of the non-symbol enumerable properties of obj. - * This function is roughly equivalent to: - * - * var result = []; - * for (key in obj) - * result.push(key); - * return result; - * - * This is the closest thing we currently have to the ES6 [[Enumerate]] - * internal method. - * - * The array of ids returned by JS_Enumerate must be rooted to protect its - * contents from garbage collection. Use JS::Rooted. - */ -extern JS_PUBLIC_API(bool) -JS_Enumerate(JSContext* cx, JS::HandleObject obj, JS::MutableHandle props); - -/* - * API for determining callability and constructability. [[Call]] and - * [[Construct]] are internal methods that aren't present on all objects, so it - * is useful to ask if they are there or not. The standard itself asks these - * questions routinely. - */ -namespace JS { - -/** - * Return true if the given object is callable. In ES6 terms, an object is - * callable if it has a [[Call]] internal method. - * - * Implements: ES6 7.2.3 IsCallable(argument). - * - * Functions are callable. A scripted proxy or wrapper is callable if its - * target is callable. Most other objects aren't callable. - */ -extern JS_PUBLIC_API(bool) -IsCallable(JSObject* obj); - -/** - * Return true if the given object is a constructor. In ES6 terms, an object is - * a constructor if it has a [[Construct]] internal method. The expression - * `new obj()` throws a TypeError if obj is not a constructor. - * - * Implements: ES6 7.2.4 IsConstructor(argument). - * - * JS functions and classes are constructors. Arrow functions and most builtin - * functions are not. A scripted proxy or wrapper is a constructor if its - * target is a constructor. - */ -extern JS_PUBLIC_API(bool) -IsConstructor(JSObject* obj); - -} /* namespace JS */ - -/** - * Call a function, passing a this-value and arguments. This is the C++ - * equivalent of `rval = Reflect.apply(fun, obj, args)`. - * - * Implements: ES6 7.3.12 Call(F, V, [argumentsList]). - * Use this function to invoke the [[Call]] internal method. - */ -extern JS_PUBLIC_API(bool) -JS_CallFunctionValue(JSContext* cx, JS::HandleObject obj, JS::HandleValue fval, - const JS::HandleValueArray& args, JS::MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -JS_CallFunction(JSContext* cx, JS::HandleObject obj, JS::HandleFunction fun, - const JS::HandleValueArray& args, JS::MutableHandleValue rval); - -/** - * Perform the method call `rval = obj[name](args)`. - */ -extern JS_PUBLIC_API(bool) -JS_CallFunctionName(JSContext* cx, JS::HandleObject obj, const char* name, - const JS::HandleValueArray& args, JS::MutableHandleValue rval); - -namespace JS { - -static inline bool -Call(JSContext* cx, JS::HandleObject thisObj, JS::HandleFunction fun, - const JS::HandleValueArray& args, MutableHandleValue rval) -{ - return !!JS_CallFunction(cx, thisObj, fun, args, rval); -} - -static inline bool -Call(JSContext* cx, JS::HandleObject thisObj, JS::HandleValue fun, const JS::HandleValueArray& args, - MutableHandleValue rval) -{ - return !!JS_CallFunctionValue(cx, thisObj, fun, args, rval); -} - -static inline bool -Call(JSContext* cx, JS::HandleObject thisObj, const char* name, const JS::HandleValueArray& args, - MutableHandleValue rval) -{ - return !!JS_CallFunctionName(cx, thisObj, name, args, rval); -} - -extern JS_PUBLIC_API(bool) -Call(JSContext* cx, JS::HandleValue thisv, JS::HandleValue fun, const JS::HandleValueArray& args, - MutableHandleValue rval); - -static inline bool -Call(JSContext* cx, JS::HandleValue thisv, JS::HandleObject funObj, const JS::HandleValueArray& args, - MutableHandleValue rval) -{ - MOZ_ASSERT(funObj); - JS::RootedValue fun(cx, JS::ObjectValue(*funObj)); - return Call(cx, thisv, fun, args, rval); -} - -/** - * Invoke a constructor. This is the C++ equivalent of - * `rval = Reflect.construct(fun, args, newTarget)`. - * - * JS::Construct() takes a `newTarget` argument that most callers don't need. - * Consider using the four-argument Construct signature instead. (But if you're - * implementing a subclass or a proxy handler's construct() method, this is the - * right function to call.) - * - * Implements: ES6 7.3.13 Construct(F, [argumentsList], [newTarget]). - * Use this function to invoke the [[Construct]] internal method. - */ -extern JS_PUBLIC_API(bool) -Construct(JSContext* cx, JS::HandleValue fun, HandleObject newTarget, - const JS::HandleValueArray &args, MutableHandleObject objp); - -/** - * Invoke a constructor. This is the C++ equivalent of - * `rval = new fun(...args)`. - * - * Implements: ES6 7.3.13 Construct(F, [argumentsList], [newTarget]), when - * newTarget is omitted. - */ -extern JS_PUBLIC_API(bool) -Construct(JSContext* cx, JS::HandleValue fun, const JS::HandleValueArray& args, - MutableHandleObject objp); - -} /* namespace JS */ - -/** - * Invoke a constructor, like the JS expression `new ctor(...args)`. Returns - * the new object, or null on error. - */ -extern JS_PUBLIC_API(JSObject*) -JS_New(JSContext* cx, JS::HandleObject ctor, const JS::HandleValueArray& args); - - -/*** Other property-defining functions ***********************************************************/ - -extern JS_PUBLIC_API(JSObject*) -JS_DefineObject(JSContext* cx, JS::HandleObject obj, const char* name, - const JSClass* clasp = nullptr, unsigned attrs = 0); - -extern JS_PUBLIC_API(bool) -JS_DefineConstDoubles(JSContext* cx, JS::HandleObject obj, const JSConstDoubleSpec* cds); - -extern JS_PUBLIC_API(bool) -JS_DefineConstIntegers(JSContext* cx, JS::HandleObject obj, const JSConstIntegerSpec* cis); - -extern JS_PUBLIC_API(bool) -JS_DefineProperties(JSContext* cx, JS::HandleObject obj, const JSPropertySpec* ps); - - -/* * */ - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnPropertyById(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnProperty(JSContext* cx, JS::HandleObject obj, const char* name, - bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnUCProperty(JSContext* cx, JS::HandleObject obj, const char16_t* name, - size_t namelen, bool* foundp); - -extern JS_PUBLIC_API(bool) -JS_AlreadyHasOwnElement(JSContext* cx, JS::HandleObject obj, uint32_t index, bool* foundp); - -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayObject(JSContext* cx, const JS::HandleValueArray& contents); - -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayObject(JSContext* cx, size_t length); - -/** - * Returns true and sets |*isArray| indicating whether |value| is an Array - * object or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isArray == false| when passed a proxy whose - * target is an Array, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_IsArrayObject(JSContext* cx, JS::HandleValue value, bool* isArray); - -/** - * Returns true and sets |*isArray| indicating whether |obj| is an Array object - * or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isArray == false| when passed a proxy whose - * target is an Array, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_IsArrayObject(JSContext* cx, JS::HandleObject obj, bool* isArray); - -extern JS_PUBLIC_API(bool) -JS_GetArrayLength(JSContext* cx, JS::Handle obj, uint32_t* lengthp); - -extern JS_PUBLIC_API(bool) -JS_SetArrayLength(JSContext* cx, JS::Handle obj, uint32_t length); - -namespace JS { - -/** - * Returns true and sets |*isMap| indicating whether |obj| is an Map object - * or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isMap == false| when passed a proxy whose - * target is an Map, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -IsMapObject(JSContext* cx, JS::HandleObject obj, bool* isMap); - -/** - * Returns true and sets |*isSet| indicating whether |obj| is an Set object - * or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isSet == false| when passed a proxy whose - * target is an Set, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -IsSetObject(JSContext* cx, JS::HandleObject obj, bool* isSet); - -} /* namespace JS */ - -/** - * Assign 'undefined' to all of the object's non-reserved slots. Note: this is - * done for all slots, regardless of the associated property descriptor. - */ -JS_PUBLIC_API(void) -JS_SetAllNonReservedSlotsToUndefined(JSContext* cx, JSObject* objArg); - -/** - * Create a new array buffer with the given contents. It must be legal to pass - * these contents to free(). On success, the ownership is transferred to the - * new array buffer. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayBufferWithContents(JSContext* cx, size_t nbytes, void* contents); - -/** - * Create a new array buffer with the given contents. The array buffer does not take ownership of - * contents, and JS_DetachArrayBuffer must be called before the contents are disposed of. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewArrayBufferWithExternalContents(JSContext* cx, size_t nbytes, void* contents); - -/** - * Steal the contents of the given array buffer. The array buffer has its - * length set to 0 and its contents array cleared. The caller takes ownership - * of the return value and must free it or transfer ownership via - * JS_NewArrayBufferWithContents when done using it. - */ -extern JS_PUBLIC_API(void*) -JS_StealArrayBufferContents(JSContext* cx, JS::HandleObject obj); - -/** - * Returns a pointer to the ArrayBuffer |obj|'s data. |obj| and its views will store and expose - * the data in the returned pointer: assigning into the returned pointer will affect values exposed - * by views of |obj| and vice versa. - * - * The caller must ultimately deallocate the returned pointer to avoid leaking. The memory is - * *not* garbage-collected with |obj|. These steps must be followed to deallocate: - * - * 1. The ArrayBuffer |obj| must be detached using JS_DetachArrayBuffer. - * 2. The returned pointer must be freed using JS_free. - * - * To perform step 1, callers *must* hold a reference to |obj| until they finish using the returned - * pointer. They *must not* attempt to let |obj| be GC'd, then JS_free the pointer. - * - * If |obj| isn't an ArrayBuffer, this function returns null and reports an error. - */ -extern JS_PUBLIC_API(void*) -JS_ExternalizeArrayBufferContents(JSContext* cx, JS::HandleObject obj); - -/** - * Create a new mapped array buffer with the given memory mapped contents. It - * must be legal to free the contents pointer by unmapping it. On success, - * ownership is transferred to the new mapped array buffer. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewMappedArrayBufferWithContents(JSContext* cx, size_t nbytes, void* contents); - -/** - * Create memory mapped array buffer contents. - * Caller must take care of closing fd after calling this function. - */ -extern JS_PUBLIC_API(void*) -JS_CreateMappedArrayBufferContents(int fd, size_t offset, size_t length); - -/** - * Release the allocated resource of mapped array buffer contents before the - * object is created. - * If a new object has been created by JS_NewMappedArrayBufferWithContents() - * with this content, then JS_DetachArrayBuffer() should be used instead to - * release the resource used by the object. - */ -extern JS_PUBLIC_API(void) -JS_ReleaseMappedArrayBufferContents(void* contents, size_t length); - -extern JS_PUBLIC_API(JS::Value) -JS_GetReservedSlot(JSObject* obj, uint32_t index); - -extern JS_PUBLIC_API(void) -JS_SetReservedSlot(JSObject* obj, uint32_t index, const JS::Value& v); - - -/************************************************************************/ - -/* - * Functions and scripts. - */ -extern JS_PUBLIC_API(JSFunction*) -JS_NewFunction(JSContext* cx, JSNative call, unsigned nargs, unsigned flags, - const char* name); - -namespace JS { - -extern JS_PUBLIC_API(JSFunction*) -GetSelfHostedFunction(JSContext* cx, const char* selfHostedName, HandleId id, - unsigned nargs); - -/** - * Create a new function based on the given JSFunctionSpec, *fs. - * id is the result of a successful call to - * `PropertySpecNameToPermanentId(cx, fs->name, &id)`. - * - * Unlike JS_DefineFunctions, this does not treat fs as an array. - * *fs must not be JS_FS_END. - */ -extern JS_PUBLIC_API(JSFunction*) -NewFunctionFromSpec(JSContext* cx, const JSFunctionSpec* fs, HandleId id); - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSObject*) -JS_GetFunctionObject(JSFunction* fun); - -/** - * Return the function's identifier as a JSString, or null if fun is unnamed. - * The returned string lives as long as fun, so you don't need to root a saved - * reference to it if fun is well-connected or rooted, and provided you bound - * the use of the saved reference by fun's lifetime. - */ -extern JS_PUBLIC_API(JSString*) -JS_GetFunctionId(JSFunction* fun); - -/** - * Return a function's display name. This is the defined name if one was given - * where the function was defined, or it could be an inferred name by the JS - * engine in the case that the function was defined to be anonymous. This can - * still return nullptr if a useful display name could not be inferred. The - * same restrictions on rooting as those in JS_GetFunctionId apply. - */ -extern JS_PUBLIC_API(JSString*) -JS_GetFunctionDisplayId(JSFunction* fun); - -/* - * Return the arity (length) of fun. - */ -extern JS_PUBLIC_API(uint16_t) -JS_GetFunctionArity(JSFunction* fun); - -/** - * Infallible predicate to test whether obj is a function object (faster than - * comparing obj's class name to "Function", but equivalent unless someone has - * overwritten the "Function" identifier with a different constructor and then - * created instances using that constructor that might be passed in as obj). - */ -extern JS_PUBLIC_API(bool) -JS_ObjectIsFunction(JSContext* cx, JSObject* obj); - -extern JS_PUBLIC_API(bool) -JS_IsNativeFunction(JSObject* funobj, JSNative call); - -/** Return whether the given function is a valid constructor. */ -extern JS_PUBLIC_API(bool) -JS_IsConstructor(JSFunction* fun); - -extern JS_PUBLIC_API(bool) -JS_DefineFunctions(JSContext* cx, JS::Handle obj, const JSFunctionSpec* fs); - -extern JS_PUBLIC_API(JSFunction*) -JS_DefineFunction(JSContext* cx, JS::Handle obj, const char* name, JSNative call, - unsigned nargs, unsigned attrs); - -extern JS_PUBLIC_API(JSFunction*) -JS_DefineUCFunction(JSContext* cx, JS::Handle obj, - const char16_t* name, size_t namelen, JSNative call, - unsigned nargs, unsigned attrs); - -extern JS_PUBLIC_API(JSFunction*) -JS_DefineFunctionById(JSContext* cx, JS::Handle obj, JS::Handle id, JSNative call, - unsigned nargs, unsigned attrs); - -extern JS_PUBLIC_API(bool) -JS_IsFunctionBound(JSFunction* fun); - -extern JS_PUBLIC_API(JSObject*) -JS_GetBoundFunctionTarget(JSFunction* fun); - -namespace JS { - -/** - * Clone a top-level function into cx's global. This function will dynamically - * fail if funobj was lexically nested inside some other function. - */ -extern JS_PUBLIC_API(JSObject*) -CloneFunctionObject(JSContext* cx, HandleObject funobj); - -/** - * As above, but providing an explicit scope chain. scopeChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the clone's scope chain. - */ -extern JS_PUBLIC_API(JSObject*) -CloneFunctionObject(JSContext* cx, HandleObject funobj, AutoObjectVector& scopeChain); - -} // namespace JS - -/** - * Given a buffer, return false if the buffer might become a valid - * javascript statement with the addition of more lines. Otherwise return - * true. The intent is to support interactive compilation - accumulate - * lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to - * the compiler. - */ -extern JS_PUBLIC_API(bool) -JS_BufferIsCompilableUnit(JSContext* cx, JS::Handle obj, const char* utf8, - size_t length); - -/** - * |script| will always be set. On failure, it will be set to nullptr. - */ -extern JS_PUBLIC_API(bool) -JS_CompileScript(JSContext* cx, const char* ascii, size_t length, - const JS::CompileOptions& options, - JS::MutableHandleScript script); - -/** - * |script| will always be set. On failure, it will be set to nullptr. - */ -extern JS_PUBLIC_API(bool) -JS_CompileUCScript(JSContext* cx, const char16_t* chars, size_t length, - const JS::CompileOptions& options, - JS::MutableHandleScript script); - -extern JS_PUBLIC_API(JSObject*) -JS_GetGlobalFromScript(JSScript* script); - -extern JS_PUBLIC_API(const char*) -JS_GetScriptFilename(JSScript* script); - -extern JS_PUBLIC_API(unsigned) -JS_GetScriptBaseLineNumber(JSContext* cx, JSScript* script); - -extern JS_PUBLIC_API(JSScript*) -JS_GetFunctionScript(JSContext* cx, JS::HandleFunction fun); - -namespace JS { - -/* Options for JavaScript compilation. */ - -/* - * In the most common use case, a CompileOptions instance is allocated on the - * stack, and holds non-owning references to non-POD option values: strings; - * principals; objects; and so on. The code declaring the instance guarantees - * that such option values will outlive the CompileOptions itself: objects are - * otherwise rooted; principals have had their reference counts bumped; strings - * will not be freed until the CompileOptions goes out of scope. In this - * situation, CompileOptions only refers to things others own, so it can be - * lightweight. - * - * In some cases, however, we need to hold compilation options with a - * non-stack-like lifetime. For example, JS::CompileOffThread needs to save - * compilation options where a worker thread can find them, and then return - * immediately. The worker thread will come along at some later point, and use - * the options. - * - * The compiler itself just needs to be able to access a collection of options; - * it doesn't care who owns them, or what's keeping them alive. It does its own - * addrefs/copies/tracing/etc. - * - * Furthermore, in some cases compile options are propagated from one entity to - * another (e.g. from a scriipt to a function defined in that script). This - * involves copying over some, but not all, of the options. - * - * So, we have a class hierarchy that reflects these four use cases: - * - * - TransitiveCompileOptions is the common base class, representing options - * that should get propagated from a script to functions defined in that - * script. This is never instantiated directly. - * - * - ReadOnlyCompileOptions is the only subclass of TransitiveCompileOptions, - * representing a full set of compile options. It can be used by code that - * simply needs to access options set elsewhere, like the compiler. This, - * again, is never instantiated directly. - * - * - The usual CompileOptions class must be stack-allocated, and holds - * non-owning references to the filename, element, and so on. It's derived - * from ReadOnlyCompileOptions, so the compiler can use it. - * - * - OwningCompileOptions roots / copies / reference counts of all its values, - * and unroots / frees / releases them when it is destructed. It too is - * derived from ReadOnlyCompileOptions, so the compiler accepts it. - */ - -enum class AsmJSOption : uint8_t { Enabled, Disabled, DisabledByDebugger }; - -/** - * The common base class for the CompileOptions hierarchy. - * - * Use this in code that needs to propagate compile options from one compilation - * unit to another. - */ -class JS_FRIEND_API(TransitiveCompileOptions) -{ - protected: - // The Web Platform allows scripts to be loaded from arbitrary cross-origin - // sources. This allows an attack by which a malicious website loads a - // sensitive file (say, a bank statement) cross-origin (using the user's - // cookies), and sniffs the generated syntax errors (via a window.onerror - // handler) for juicy morsels of its contents. - // - // To counter this attack, HTML5 specifies that script errors should be - // sanitized ("muted") when the script is not same-origin with the global - // for which it is loaded. Callers should set this flag for cross-origin - // scripts, and it will be propagated appropriately to child scripts and - // passed back in JSErrorReports. - bool mutedErrors_; - const char* filename_; - const char* introducerFilename_; - const char16_t* sourceMapURL_; - - // This constructor leaves 'version' set to JSVERSION_UNKNOWN. The structure - // is unusable until that's set to something more specific; the derived - // classes' constructors take care of that, in ways appropriate to their - // purpose. - TransitiveCompileOptions() - : mutedErrors_(false), - filename_(nullptr), - introducerFilename_(nullptr), - sourceMapURL_(nullptr), - version(JSVERSION_UNKNOWN), - versionSet(false), - utf8(false), - selfHostingMode(false), - canLazilyParse(true), - strictOption(false), - extraWarningsOption(false), - werrorOption(false), - asmJSOption(AsmJSOption::Disabled), - throwOnAsmJSValidationFailureOption(false), - forceAsync(false), - installedFile(false), - sourceIsLazy(false), - introductionType(nullptr), - introductionLineno(0), - introductionOffset(0), - hasIntroductionInfo(false) - { } - - // Set all POD options (those not requiring reference counts, copies, - // rooting, or other hand-holding) to their values in |rhs|. - void copyPODTransitiveOptions(const TransitiveCompileOptions& rhs); - - public: - // Read-only accessors for non-POD options. The proper way to set these - // depends on the derived type. - bool mutedErrors() const { return mutedErrors_; } - const char* filename() const { return filename_; } - const char* introducerFilename() const { return introducerFilename_; } - const char16_t* sourceMapURL() const { return sourceMapURL_; } - virtual JSObject* element() const = 0; - virtual JSString* elementAttributeName() const = 0; - virtual JSScript* introductionScript() const = 0; - - // POD options. - JSVersion version; - bool versionSet; - bool utf8; - bool selfHostingMode; - bool canLazilyParse; - bool strictOption; - bool extraWarningsOption; - bool werrorOption; - AsmJSOption asmJSOption; - bool throwOnAsmJSValidationFailureOption; - bool forceAsync; - bool installedFile; // 'true' iff pre-compiling js file in packaged app - bool sourceIsLazy; - - // |introductionType| is a statically allocated C string: - // one of "eval", "Function", or "GeneratorFunction". - const char* introductionType; - unsigned introductionLineno; - uint32_t introductionOffset; - bool hasIntroductionInfo; - - private: - void operator=(const TransitiveCompileOptions&) = delete; -}; - -/** - * The class representing a full set of compile options. - * - * Use this in code that only needs to access compilation options created - * elsewhere, like the compiler. Don't instantiate this class (the constructor - * is protected anyway); instead, create instances only of the derived classes: - * CompileOptions and OwningCompileOptions. - */ -class JS_FRIEND_API(ReadOnlyCompileOptions) : public TransitiveCompileOptions -{ - friend class CompileOptions; - - protected: - ReadOnlyCompileOptions() - : TransitiveCompileOptions(), - lineno(1), - column(0), - isRunOnce(false), - noScriptRval(false) - { } - - // Set all POD options (those not requiring reference counts, copies, - // rooting, or other hand-holding) to their values in |rhs|. - void copyPODOptions(const ReadOnlyCompileOptions& rhs); - - public: - // Read-only accessors for non-POD options. The proper way to set these - // depends on the derived type. - bool mutedErrors() const { return mutedErrors_; } - const char* filename() const { return filename_; } - const char* introducerFilename() const { return introducerFilename_; } - const char16_t* sourceMapURL() const { return sourceMapURL_; } - virtual JSObject* element() const = 0; - virtual JSString* elementAttributeName() const = 0; - virtual JSScript* introductionScript() const = 0; - - // POD options. - unsigned lineno; - unsigned column; - // isRunOnce only applies to non-function scripts. - bool isRunOnce; - bool noScriptRval; - - private: - void operator=(const ReadOnlyCompileOptions&) = delete; -}; - -/** - * Compilation options, with dynamic lifetime. An instance of this type - * makes a copy of / holds / roots all dynamically allocated resources - * (principals; elements; strings) that it refers to. Its destructor frees - * / drops / unroots them. This is heavier than CompileOptions, below, but - * unlike CompileOptions, it can outlive any given stack frame. - * - * Note that this *roots* any JS values it refers to - they're live - * unconditionally. Thus, instances of this type can't be owned, directly - * or indirectly, by a JavaScript object: if any value that this roots ever - * comes to refer to the object that owns this, then the whole cycle, and - * anything else it entrains, will never be freed. - */ -class JS_FRIEND_API(OwningCompileOptions) : public ReadOnlyCompileOptions -{ - PersistentRootedObject elementRoot; - PersistentRootedString elementAttributeNameRoot; - PersistentRootedScript introductionScriptRoot; - - public: - // A minimal constructor, for use with OwningCompileOptions::copy. This - // leaves |this.version| set to JSVERSION_UNKNOWN; the instance - // shouldn't be used until we've set that to something real (as |copy| - // will). - explicit OwningCompileOptions(JSContext* cx); - ~OwningCompileOptions(); - - JSObject* element() const override { return elementRoot; } - JSString* elementAttributeName() const override { return elementAttributeNameRoot; } - JSScript* introductionScript() const override { return introductionScriptRoot; } - - // Set this to a copy of |rhs|. Return false on OOM. - bool copy(JSContext* cx, const ReadOnlyCompileOptions& rhs); - - /* These setters make copies of their string arguments, and are fallible. */ - bool setFile(JSContext* cx, const char* f); - bool setFileAndLine(JSContext* cx, const char* f, unsigned l); - bool setSourceMapURL(JSContext* cx, const char16_t* s); - bool setIntroducerFilename(JSContext* cx, const char* s); - - /* These setters are infallible, and can be chained. */ - OwningCompileOptions& setLine(unsigned l) { lineno = l; return *this; } - OwningCompileOptions& setElement(JSObject* e) { - elementRoot = e; - return *this; - } - OwningCompileOptions& setElementAttributeName(JSString* p) { - elementAttributeNameRoot = p; - return *this; - } - OwningCompileOptions& setIntroductionScript(JSScript* s) { - introductionScriptRoot = s; - return *this; - } - OwningCompileOptions& setMutedErrors(bool mute) { - mutedErrors_ = mute; - return *this; - } - OwningCompileOptions& setVersion(JSVersion v) { - version = v; - versionSet = true; - return *this; - } - OwningCompileOptions& setUTF8(bool u) { utf8 = u; return *this; } - OwningCompileOptions& setColumn(unsigned c) { column = c; return *this; } - OwningCompileOptions& setIsRunOnce(bool once) { isRunOnce = once; return *this; } - OwningCompileOptions& setNoScriptRval(bool nsr) { noScriptRval = nsr; return *this; } - OwningCompileOptions& setSelfHostingMode(bool shm) { selfHostingMode = shm; return *this; } - OwningCompileOptions& setCanLazilyParse(bool clp) { canLazilyParse = clp; return *this; } - OwningCompileOptions& setSourceIsLazy(bool l) { sourceIsLazy = l; return *this; } - OwningCompileOptions& setIntroductionType(const char* t) { introductionType = t; return *this; } - bool setIntroductionInfo(JSContext* cx, const char* introducerFn, const char* intro, - unsigned line, JSScript* script, uint32_t offset) - { - if (!setIntroducerFilename(cx, introducerFn)) - return false; - introductionType = intro; - introductionLineno = line; - introductionScriptRoot = script; - introductionOffset = offset; - hasIntroductionInfo = true; - return true; - } - - private: - void operator=(const CompileOptions& rhs) = delete; -}; - -/** - * Compilation options stored on the stack. An instance of this type - * simply holds references to dynamically allocated resources (element; - * filename; source map URL) that are owned by something else. If you - * create an instance of this type, it's up to you to guarantee that - * everything you store in it will outlive it. - */ -class MOZ_STACK_CLASS JS_FRIEND_API(CompileOptions) final : public ReadOnlyCompileOptions -{ - RootedObject elementRoot; - RootedString elementAttributeNameRoot; - RootedScript introductionScriptRoot; - - public: - explicit CompileOptions(JSContext* cx, JSVersion version = JSVERSION_UNKNOWN); - CompileOptions(js::ContextFriendFields* cx, const ReadOnlyCompileOptions& rhs) - : ReadOnlyCompileOptions(), elementRoot(cx), elementAttributeNameRoot(cx), - introductionScriptRoot(cx) - { - copyPODOptions(rhs); - - filename_ = rhs.filename(); - introducerFilename_ = rhs.introducerFilename(); - sourceMapURL_ = rhs.sourceMapURL(); - elementRoot = rhs.element(); - elementAttributeNameRoot = rhs.elementAttributeName(); - introductionScriptRoot = rhs.introductionScript(); - } - - CompileOptions(js::ContextFriendFields* cx, const TransitiveCompileOptions& rhs) - : ReadOnlyCompileOptions(), elementRoot(cx), elementAttributeNameRoot(cx), - introductionScriptRoot(cx) - { - copyPODTransitiveOptions(rhs); - - filename_ = rhs.filename(); - introducerFilename_ = rhs.introducerFilename(); - sourceMapURL_ = rhs.sourceMapURL(); - elementRoot = rhs.element(); - elementAttributeNameRoot = rhs.elementAttributeName(); - introductionScriptRoot = rhs.introductionScript(); - } - - JSObject* element() const override { return elementRoot; } - JSString* elementAttributeName() const override { return elementAttributeNameRoot; } - JSScript* introductionScript() const override { return introductionScriptRoot; } - - CompileOptions& setFile(const char* f) { filename_ = f; return *this; } - CompileOptions& setLine(unsigned l) { lineno = l; return *this; } - CompileOptions& setFileAndLine(const char* f, unsigned l) { - filename_ = f; lineno = l; return *this; - } - CompileOptions& setSourceMapURL(const char16_t* s) { sourceMapURL_ = s; return *this; } - CompileOptions& setElement(JSObject* e) { elementRoot = e; return *this; } - CompileOptions& setElementAttributeName(JSString* p) { - elementAttributeNameRoot = p; - return *this; - } - CompileOptions& setIntroductionScript(JSScript* s) { - introductionScriptRoot = s; - return *this; - } - CompileOptions& setMutedErrors(bool mute) { - mutedErrors_ = mute; - return *this; - } - CompileOptions& setVersion(JSVersion v) { - version = v; - versionSet = true; - return *this; - } - CompileOptions& setUTF8(bool u) { utf8 = u; return *this; } - CompileOptions& setColumn(unsigned c) { column = c; return *this; } - CompileOptions& setIsRunOnce(bool once) { isRunOnce = once; return *this; } - CompileOptions& setNoScriptRval(bool nsr) { noScriptRval = nsr; return *this; } - CompileOptions& setSelfHostingMode(bool shm) { selfHostingMode = shm; return *this; } - CompileOptions& setCanLazilyParse(bool clp) { canLazilyParse = clp; return *this; } - CompileOptions& setSourceIsLazy(bool l) { sourceIsLazy = l; return *this; } - CompileOptions& setIntroductionType(const char* t) { introductionType = t; return *this; } - CompileOptions& setIntroductionInfo(const char* introducerFn, const char* intro, - unsigned line, JSScript* script, uint32_t offset) - { - introducerFilename_ = introducerFn; - introductionType = intro; - introductionLineno = line; - introductionScriptRoot = script; - introductionOffset = offset; - hasIntroductionInfo = true; - return *this; - } - CompileOptions& maybeMakeStrictMode(bool strict) { - strictOption = strictOption || strict; - return *this; - } - - private: - void operator=(const CompileOptions& rhs) = delete; -}; - -/** - * |script| will always be set. On failure, it will be set to nullptr. - */ -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* bytes, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - FILE* file, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -Compile(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* filename, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* bytes, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - FILE* file, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* filename, JS::MutableHandleScript script); - -extern JS_PUBLIC_API(bool) -CanCompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options, size_t length); - -/* - * Off thread compilation control flow. - * - * After successfully triggering an off thread compile of a script, the - * callback will eventually be invoked with the specified data and a token - * for the compilation. The callback will be invoked while off the main thread, - * so must ensure that its operations are thread safe. Afterwards, one of the - * following functions must be invoked on the main thread: - * - * - FinishOffThreadScript, to get the result script (or nullptr on failure). - * - CancelOffThreadScript, to free the resources without creating a script. - * - * The characters passed in to CompileOffThread must remain live until the - * callback is invoked, and the resulting script will be rooted until the call - * to FinishOffThreadScript. - */ - -extern JS_PUBLIC_API(bool) -CompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, - OffThreadCompileCallback callback, void* callbackData); - -extern JS_PUBLIC_API(JSScript*) -FinishOffThreadScript(JSContext* cx, void* token); - -extern JS_PUBLIC_API(void) -CancelOffThreadScript(JSContext* cx, void* token); - -extern JS_PUBLIC_API(bool) -CompileOffThreadModule(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, - OffThreadCompileCallback callback, void* callbackData); - -extern JS_PUBLIC_API(JSObject*) -FinishOffThreadModule(JSContext* cx, void* token); - -extern JS_PUBLIC_API(void) -CancelOffThreadModule(JSContext* cx, void* token); - -/** - * Compile a function with envChain plus the global as its scope chain. - * envChain must contain objects in the current compartment of cx. The actual - * scope chain used for the function will consist of With wrappers for those - * objects, followed by the current global of the compartment cx is in. This - * global must not be explicitly included in the scope chain. - */ -extern JS_PUBLIC_API(bool) -CompileFunction(JSContext* cx, AutoObjectVector& envChain, - const ReadOnlyCompileOptions& options, - const char* name, unsigned nargs, const char* const* argnames, - const char16_t* chars, size_t length, JS::MutableHandleFunction fun); - -/** - * Same as above, but taking a SourceBufferHolder for the function body. - */ -extern JS_PUBLIC_API(bool) -CompileFunction(JSContext* cx, AutoObjectVector& envChain, - const ReadOnlyCompileOptions& options, - const char* name, unsigned nargs, const char* const* argnames, - SourceBufferHolder& srcBuf, JS::MutableHandleFunction fun); - -/** - * Same as above, but taking a const char * for the function body. - */ -extern JS_PUBLIC_API(bool) -CompileFunction(JSContext* cx, AutoObjectVector& envChain, - const ReadOnlyCompileOptions& options, - const char* name, unsigned nargs, const char* const* argnames, - const char* bytes, size_t length, JS::MutableHandleFunction fun); - -} /* namespace JS */ - -extern JS_PUBLIC_API(JSString*) -JS_DecompileScript(JSContext* cx, JS::Handle script, const char* name, unsigned indent); - -/* - * API extension: OR this into indent to avoid pretty-printing the decompiled - * source resulting from JS_DecompileFunction. - */ -#define JS_DONT_PRETTY_PRINT ((unsigned)0x8000) - -extern JS_PUBLIC_API(JSString*) -JS_DecompileFunction(JSContext* cx, JS::Handle fun, unsigned indent); - - -/* - * NB: JS_ExecuteScript and the JS::Evaluate APIs come in two flavors: either - * they use the global as the scope, or they take an AutoObjectVector of objects - * to use as the scope chain. In the former case, the global is also used as - * the "this" keyword value and the variables object (ECMA parlance for where - * 'var' and 'function' bind names) of the execution context for script. In the - * latter case, the first object in the provided list is used, unless the list - * is empty, in which case the global is used. - * - * Why a runtime option? The alternative is to add APIs duplicating those - * for the other value of flags, and that doesn't seem worth the code bloat - * cost. Such new entry points would probably have less obvious names, too, so - * would not tend to be used. The ContextOptionsRef adjustment, OTOH, can be - * more easily hacked into existing code that does not depend on the bug; such - * code can continue to use the familiar JS::Evaluate, etc., entry points. - */ - -/** - * Evaluate a script in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::HandleScript script, JS::MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::HandleScript script); - -/** - * As above, but providing an explicit scope chain. envChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the script's scope chain. - */ -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::AutoObjectVector& envChain, - JS::HandleScript script, JS::MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -JS_ExecuteScript(JSContext* cx, JS::AutoObjectVector& envChain, JS::HandleScript script); - -namespace JS { - -/** - * Like the above, but handles a cross-compartment script. If the script is - * cross-compartment, it is cloned into the current compartment before executing. - */ -extern JS_PUBLIC_API(bool) -CloneAndExecuteScript(JSContext* cx, JS::Handle script, - JS::MutableHandleValue rval); - -} /* namespace JS */ - -namespace JS { - -/** - * Evaluate the given source buffer in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleValue rval); - -/** - * As above, but providing an explicit scope chain. envChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the script's scope chain. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, AutoObjectVector& envChain, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleValue rval); - -/** - * Evaluate the given character buffer in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleValue rval); - -/** - * As above, but providing an explicit scope chain. envChain must not include - * the global object on it; that's implicit. It needs to contain the other - * objects that should end up on the script's scope chain. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, AutoObjectVector& envChain, const ReadOnlyCompileOptions& options, - const char16_t* chars, size_t length, JS::MutableHandleValue rval); - -/** - * Evaluate the given byte buffer in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* bytes, size_t length, JS::MutableHandleValue rval); - -/** - * Evaluate the given file in the scope of the current global of cx. - */ -extern JS_PUBLIC_API(bool) -Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options, - const char* filename, JS::MutableHandleValue rval); - -/** - * Get the HostResolveImportedModule hook for a global. - */ -extern JS_PUBLIC_API(JSFunction*) -GetModuleResolveHook(JSContext* cx); - -/** - * Set the HostResolveImportedModule hook for a global to the given function. - */ -extern JS_PUBLIC_API(void) -SetModuleResolveHook(JSContext* cx, JS::HandleFunction func); - -/** - * Parse the given source buffer as a module in the scope of the current global - * of cx and return a source text module record. - */ -extern JS_PUBLIC_API(bool) -CompileModule(JSContext* cx, const ReadOnlyCompileOptions& options, - SourceBufferHolder& srcBuf, JS::MutableHandleObject moduleRecord); - -/** - * Set the [[HostDefined]] field of a source text module record to the given - * value. - */ -extern JS_PUBLIC_API(void) -SetModuleHostDefinedField(JSObject* module, const JS::Value& value); - -/** - * Get the [[HostDefined]] field of a source text module record. - */ -extern JS_PUBLIC_API(JS::Value) -GetModuleHostDefinedField(JSObject* module); - -/* - * Perform the ModuleDeclarationInstantiation operation on on the give source - * text module record. - * - * This transitively resolves all module dependencies (calling the - * HostResolveImportedModule hook) and initializes the environment record for - * the module. - */ -extern JS_PUBLIC_API(bool) -ModuleDeclarationInstantiation(JSContext* cx, JS::HandleObject moduleRecord); - -/* - * Perform the ModuleEvaluation operation on on the give source text module - * record. - * - * This does nothing if this module has already been evaluated. Otherwise, it - * transitively evaluates all dependences of this module and then evaluates this - * module. - * - * ModuleDeclarationInstantiation must have completed prior to calling this. - */ -extern JS_PUBLIC_API(bool) -ModuleEvaluation(JSContext* cx, JS::HandleObject moduleRecord); - -/* - * Get a list of the module specifiers used by a source text module - * record to request importation of modules. - * - * The result is a JavaScript array of string values. To extract the individual - * values use only JS_GetArrayLength and JS_GetElement with indices 0 to - * length - 1. - */ -extern JS_PUBLIC_API(JSObject*) -GetRequestedModules(JSContext* cx, JS::HandleObject moduleRecord); - -/* - * Get the script associated with a module. - */ -extern JS_PUBLIC_API(JSScript*) -GetModuleScript(JSContext* cx, JS::HandleObject moduleRecord); - -} /* namespace JS */ - -extern JS_PUBLIC_API(bool) -JS_CheckForInterrupt(JSContext* cx); - -/* - * These functions allow setting an interrupt callback that will be called - * from the JS thread some time after any thread triggered the callback using - * JS_RequestInterruptCallback(cx). - * - * To schedule the GC and for other activities the engine internally triggers - * interrupt callbacks. The embedding should thus not rely on callbacks being - * triggered through the external API only. - * - * Important note: Additional callbacks can occur inside the callback handler - * if it re-enters the JS engine. The embedding must ensure that the callback - * is disconnected before attempting such re-entry. - */ -extern JS_PUBLIC_API(bool) -JS_AddInterruptCallback(JSContext* cx, JSInterruptCallback callback); - -extern JS_PUBLIC_API(bool) -JS_DisableInterruptCallback(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_ResetInterruptCallback(JSContext* cx, bool enable); - -extern JS_PUBLIC_API(void) -JS_RequestInterruptCallback(JSContext* cx); - -namespace JS { - -/** - * Sets the callback that's invoked whenever an incumbent global is required. - * - * SpiderMonkey doesn't itself have a notion of incumbent globals as defined - * by the html spec, so we need the embedding to provide this. - * See dom/base/ScriptSettings.h for details. - */ -extern JS_PUBLIC_API(void) -SetGetIncumbentGlobalCallback(JSContext* cx, JSGetIncumbentGlobalCallback callback); - -/** - * Sets the callback that's invoked whenever a Promise job should be enqeued. - * - * SpiderMonkey doesn't schedule Promise resolution jobs itself; instead, - * using this function the embedding can provide a callback to do that - * scheduling. The provided `callback` is invoked with the promise job, - * the corresponding Promise's allocation stack, and the `data` pointer - * passed here as arguments. - */ -extern JS_PUBLIC_API(void) -SetEnqueuePromiseJobCallback(JSContext* cx, JSEnqueuePromiseJobCallback callback, - void* data = nullptr); - -/** - * Sets the callback that's invoked whenever a Promise is rejected without - * a rejection handler, and when a Promise that was previously rejected - * without a handler gets a handler attached. - */ -extern JS_PUBLIC_API(void) -SetPromiseRejectionTrackerCallback(JSContext* cx, JSPromiseRejectionTrackerCallback callback, - void* data = nullptr); - -/** - * Returns a new instance of the Promise builtin class in the current - * compartment, with the right slot layout. If a `proto` is passed, that gets - * set as the instance's [[Prototype]] instead of the original value of - * `Promise.prototype`. - */ -extern JS_PUBLIC_API(JSObject*) -NewPromiseObject(JSContext* cx, JS::HandleObject executor, JS::HandleObject proto = nullptr); - -/** - * Returns true if the given object is an unwrapped PromiseObject, false - * otherwise. - */ -extern JS_PUBLIC_API(bool) -IsPromiseObject(JS::HandleObject obj); - -/** - * Returns the current compartment's original Promise constructor. - */ -extern JS_PUBLIC_API(JSObject*) -GetPromiseConstructor(JSContext* cx); - -/** - * Returns the current compartment's original Promise.prototype. - */ -extern JS_PUBLIC_API(JSObject*) -GetPromisePrototype(JSContext* cx); - -// Keep this in sync with the PROMISE_STATE defines in SelfHostingDefines.h. -enum class PromiseState { - Pending, - Fulfilled, - Rejected -}; - -/** - * Returns the given Promise's state as a JS::PromiseState enum value. - */ -extern JS_PUBLIC_API(PromiseState) -GetPromiseState(JS::HandleObject promise); - -/** - * Returns the given Promise's process-unique ID. - */ -JS_PUBLIC_API(uint64_t) -GetPromiseID(JS::HandleObject promise); - -/** - * Returns the given Promise's result: either the resolution value for - * fulfilled promises, or the rejection reason for rejected ones. - */ -extern JS_PUBLIC_API(JS::Value) -GetPromiseResult(JS::HandleObject promise); - -/** - * Returns a js::SavedFrame linked list of the stack that lead to the given - * Promise's allocation. - */ -extern JS_PUBLIC_API(JSObject*) -GetPromiseAllocationSite(JS::HandleObject promise); - -extern JS_PUBLIC_API(JSObject*) -GetPromiseResolutionSite(JS::HandleObject promise); - -#ifdef DEBUG -extern JS_PUBLIC_API(void) -DumpPromiseAllocationSite(JSContext* cx, JS::HandleObject promise); - -extern JS_PUBLIC_API(void) -DumpPromiseResolutionSite(JSContext* cx, JS::HandleObject promise); -#endif - -/** - * Calls the current compartment's original Promise.resolve on the original - * Promise constructor, with `resolutionValue` passed as an argument. - */ -extern JS_PUBLIC_API(JSObject*) -CallOriginalPromiseResolve(JSContext* cx, JS::HandleValue resolutionValue); - -/** - * Calls the current compartment's original Promise.reject on the original - * Promise constructor, with `resolutionValue` passed as an argument. - */ -extern JS_PUBLIC_API(JSObject*) -CallOriginalPromiseReject(JSContext* cx, JS::HandleValue rejectionValue); - -/** - * Resolves the given Promise with the given `resolutionValue`. - * - * Calls the `resolve` function that was passed to the executor function when - * the Promise was created. - */ -extern JS_PUBLIC_API(bool) -ResolvePromise(JSContext* cx, JS::HandleObject promise, JS::HandleValue resolutionValue); - -/** - * Rejects the given `promise` with the given `rejectionValue`. - * - * Calls the `reject` function that was passed to the executor function when - * the Promise was created. - */ -extern JS_PUBLIC_API(bool) -RejectPromise(JSContext* cx, JS::HandleObject promise, JS::HandleValue rejectionValue); - -/** - * Calls the current compartment's original Promise.prototype.then on the - * given `promise`, with `onResolve` and `onReject` passed as arguments. - * - * Asserts if the passed-in `promise` object isn't an unwrapped instance of - * `Promise` or a subclass or `onResolve` and `onReject` aren't both either - * `nullptr` or callable objects. - */ -extern JS_PUBLIC_API(JSObject*) -CallOriginalPromiseThen(JSContext* cx, JS::HandleObject promise, - JS::HandleObject onResolve, JS::HandleObject onReject); - -/** - * Unforgeable, optimized version of the JS builtin Promise.prototype.then. - * - * Takes a Promise instance and `onResolve`, `onReject` callables to enqueue - * as reactions for that promise. In difference to Promise.prototype.then, - * this doesn't create and return a new Promise instance. - * - * Asserts if the passed-in `promise` object isn't an unwrapped instance of - * `Promise` or a subclass or `onResolve` and `onReject` aren't both callable - * objects. - */ -extern JS_PUBLIC_API(bool) -AddPromiseReactions(JSContext* cx, JS::HandleObject promise, - JS::HandleObject onResolve, JS::HandleObject onReject); - -/** - * Unforgeable version of the JS builtin Promise.all. - * - * Takes an AutoObjectVector of Promise objects and returns a promise that's - * resolved with an array of resolution values when all those promises ahve - * been resolved, or rejected with the rejection value of the first rejected - * promise. - * - * Asserts if the array isn't dense or one of the entries isn't an unwrapped - * instance of Promise or a subclass. - */ -extern JS_PUBLIC_API(JSObject*) -GetWaitForAllPromise(JSContext* cx, const JS::AutoObjectVector& promises); - -/** - * An AsyncTask represents a SpiderMonkey-internal operation that starts on a - * JSContext's owner thread, possibly executes on other threads, completes, and - * then needs to be scheduled to run again on the JSContext's owner thread. The - * embedding provides for this final dispatch back to the JSContext's owner - * thread by calling methods on this interface when requested. - */ -struct JS_PUBLIC_API(AsyncTask) -{ - AsyncTask() : user(nullptr) {} - virtual ~AsyncTask() {} - - /** - * After the FinishAsyncTaskCallback is called and succeeds, one of these - * two functions will be called on the original JSContext's owner thread. - */ - virtual void finish(JSContext* cx) = 0; - virtual void cancel(JSContext* cx) = 0; - - /* The embedding may use this field to attach arbitrary data to a task. */ - void* user; -}; - -/** - * A new AsyncTask object, created inside SpiderMonkey on the JSContext's owner - * thread, will be passed to the StartAsyncTaskCallback before it is dispatched - * to another thread. The embedding may use the AsyncTask::user field to attach - * additional task state. - * - * If this function succeeds, SpiderMonkey will call the FinishAsyncTaskCallback - * at some point in the future. Otherwise, FinishAsyncTaskCallback will *not* - * be called. SpiderMonkey assumes that, if StartAsyncTaskCallback fails, it is - * because the JSContext is being shut down. - */ -typedef bool -(*StartAsyncTaskCallback)(JSContext* cx, AsyncTask* task); - -/** - * The FinishAsyncTaskCallback may be called from any thread and will only be - * passed AsyncTasks that have already been started via StartAsyncTaskCallback. - * If the embedding returns 'true', indicating success, the embedding must call - * either task->finish() or task->cancel() on the JSContext's owner thread at - * some point in the future. - */ -typedef bool -(*FinishAsyncTaskCallback)(AsyncTask* task); - -/** - * Set the above callbacks for the given context. - */ -extern JS_PUBLIC_API(void) -SetAsyncTaskCallbacks(JSContext* cx, StartAsyncTaskCallback start, FinishAsyncTaskCallback finish); - -} // namespace JS - -extern JS_PUBLIC_API(bool) -JS_IsRunning(JSContext* cx); - -namespace JS { - -/** - * This class can be used to store a pointer to the youngest frame of a saved - * stack in the specified JSContext. This reference will be picked up by any new - * calls performed until the class is destroyed, with the specified asyncCause, - * that must not be empty. - * - * Any stack capture initiated during these new calls will go through the async - * stack instead of the current stack. - * - * Capturing the stack before a new call is performed will not be affected. - * - * The provided chain of SavedFrame objects can live in any compartment, - * although it will be copied to the compartment where the stack is captured. - * - * See also `js/src/doc/SavedFrame/SavedFrame.md` for documentation on async - * stack frames. - */ -class MOZ_STACK_CLASS JS_PUBLIC_API(AutoSetAsyncStackForNewCalls) -{ - JSContext* cx; - RootedObject oldAsyncStack; - const char* oldAsyncCause; - bool oldAsyncCallIsExplicit; - - public: - enum class AsyncCallKind { - // The ordinary kind of call, where we may apply an async - // parent if there is no ordinary parent. - IMPLICIT, - // An explicit async parent, e.g., callFunctionWithAsyncStack, - // where we always want to override any ordinary parent. - EXPLICIT - }; - - // The stack parameter cannot be null by design, because it would be - // ambiguous whether that would clear any scheduled async stack and make the - // normal stack reappear in the new call, or just keep the async stack - // already scheduled for the new call, if any. - // - // asyncCause is owned by the caller and its lifetime must outlive the - // lifetime of the AutoSetAsyncStackForNewCalls object. It is strongly - // encouraged that asyncCause be a string constant or similar statically - // allocated string. - AutoSetAsyncStackForNewCalls(JSContext* cx, HandleObject stack, - const char* asyncCause, - AsyncCallKind kind = AsyncCallKind::IMPLICIT); - ~AutoSetAsyncStackForNewCalls(); -}; - -} // namespace JS - -/************************************************************************/ - -/* - * Strings. - * - * NB: JS_NewUCString takes ownership of bytes on success, avoiding a copy; - * but on error (signified by null return), it leaves chars owned by the - * caller. So the caller must free bytes in the error case, if it has no use - * for them. In contrast, all the JS_New*StringCopy* functions do not take - * ownership of the character memory passed to them -- they copy it. - */ -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyN(JSContext* cx, const char* s, size_t n); - -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyZ(JSContext* cx, const char* s); - -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyUTF8Z(JSContext* cx, const JS::ConstUTF8CharsZ s); - -extern JS_PUBLIC_API(JSString*) -JS_NewStringCopyUTF8N(JSContext* cx, const JS::UTF8Chars s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinJSString(JSContext* cx, JS::HandleString str); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeStringN(JSContext* cx, const char* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeString(JSContext* cx, const char* s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinStringN(JSContext* cx, const char* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinString(JSContext* cx, const char* s); - -extern JS_PUBLIC_API(JSString*) -JS_NewUCString(JSContext* cx, char16_t* chars, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_NewUCStringCopyN(JSContext* cx, const char16_t* s, size_t n); - -extern JS_PUBLIC_API(JSString*) -JS_NewUCStringCopyZ(JSContext* cx, const char16_t* s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeUCStringN(JSContext* cx, const char16_t* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeUCString(JSContext* cx, const char16_t* s); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinUCStringN(JSContext* cx, const char16_t* s, size_t length); - -extern JS_PUBLIC_API(JSString*) -JS_AtomizeAndPinUCString(JSContext* cx, const char16_t* s); - -extern JS_PUBLIC_API(bool) -JS_CompareStrings(JSContext* cx, JSString* str1, JSString* str2, int32_t* result); - -extern JS_PUBLIC_API(bool) -JS_StringEqualsAscii(JSContext* cx, JSString* str, const char* asciiBytes, bool* match); - -extern JS_PUBLIC_API(size_t) -JS_PutEscapedString(JSContext* cx, char* buffer, size_t size, JSString* str, char quote); - -extern JS_PUBLIC_API(bool) -JS_FileEscapedString(FILE* fp, JSString* str, char quote); - -/* - * Extracting string characters and length. - * - * While getting the length of a string is infallible, getting the chars can - * fail. As indicated by the lack of a JSContext parameter, there are two - * special cases where getting the chars is infallible: - * - * The first case is for strings that have been atomized, e.g. directly by - * JS_AtomizeAndPinString or implicitly because it is stored in a jsid. - * - * The second case is "flat" strings that have been explicitly prepared in a - * fallible context by JS_FlattenString. To catch errors, a separate opaque - * JSFlatString type is returned by JS_FlattenString and expected by - * JS_GetFlatStringChars. Note, though, that this is purely a syntactic - * distinction: the input and output of JS_FlattenString are the same actual - * GC-thing. If a JSString is known to be flat, JS_ASSERT_STRING_IS_FLAT can be - * used to make a debug-checked cast. Example: - * - * // in a fallible context - * JSFlatString* fstr = JS_FlattenString(cx, str); - * if (!fstr) - * return false; - * MOZ_ASSERT(fstr == JS_ASSERT_STRING_IS_FLAT(str)); - * - * // in an infallible context, for the same 'str' - * AutoCheckCannotGC nogc; - * const char16_t* chars = JS_GetTwoByteFlatStringChars(nogc, fstr) - * MOZ_ASSERT(chars); - * - * Flat strings and interned strings are always null-terminated, so - * JS_FlattenString can be used to get a null-terminated string. - * - * Additionally, string characters are stored as either Latin1Char (8-bit) - * or char16_t (16-bit). Clients can use JS_StringHasLatin1Chars and can then - * call either the Latin1* or TwoByte* functions. Some functions like - * JS_CopyStringChars and JS_GetStringCharAt accept both Latin1 and TwoByte - * strings. - */ - -extern JS_PUBLIC_API(size_t) -JS_GetStringLength(JSString* str); - -extern JS_PUBLIC_API(bool) -JS_StringIsFlat(JSString* str); - -/** Returns true iff the string's characters are stored as Latin1. */ -extern JS_PUBLIC_API(bool) -JS_StringHasLatin1Chars(JSString* str); - -extern JS_PUBLIC_API(const JS::Latin1Char*) -JS_GetLatin1StringCharsAndLength(JSContext* cx, const JS::AutoCheckCannotGC& nogc, JSString* str, - size_t* length); - -extern JS_PUBLIC_API(const char16_t*) -JS_GetTwoByteStringCharsAndLength(JSContext* cx, const JS::AutoCheckCannotGC& nogc, JSString* str, - size_t* length); - -extern JS_PUBLIC_API(bool) -JS_GetStringCharAt(JSContext* cx, JSString* str, size_t index, char16_t* res); - -extern JS_PUBLIC_API(char16_t) -JS_GetFlatStringCharAt(JSFlatString* str, size_t index); - -extern JS_PUBLIC_API(const char16_t*) -JS_GetTwoByteExternalStringChars(JSString* str); - -extern JS_PUBLIC_API(bool) -JS_CopyStringChars(JSContext* cx, mozilla::Range dest, JSString* str); - -extern JS_PUBLIC_API(JSFlatString*) -JS_FlattenString(JSContext* cx, JSString* str); - -extern JS_PUBLIC_API(const JS::Latin1Char*) -JS_GetLatin1FlatStringChars(const JS::AutoCheckCannotGC& nogc, JSFlatString* str); - -extern JS_PUBLIC_API(const char16_t*) -JS_GetTwoByteFlatStringChars(const JS::AutoCheckCannotGC& nogc, JSFlatString* str); - -static MOZ_ALWAYS_INLINE JSFlatString* -JSID_TO_FLAT_STRING(jsid id) -{ - MOZ_ASSERT(JSID_IS_STRING(id)); - return (JSFlatString*)(JSID_BITS(id)); -} - -static MOZ_ALWAYS_INLINE JSFlatString* -JS_ASSERT_STRING_IS_FLAT(JSString* str) -{ - MOZ_ASSERT(JS_StringIsFlat(str)); - return (JSFlatString*)str; -} - -static MOZ_ALWAYS_INLINE JSString* -JS_FORGET_STRING_FLATNESS(JSFlatString* fstr) -{ - return (JSString*)fstr; -} - -/* - * Additional APIs that avoid fallibility when given a flat string. - */ - -extern JS_PUBLIC_API(bool) -JS_FlatStringEqualsAscii(JSFlatString* str, const char* asciiBytes); - -extern JS_PUBLIC_API(size_t) -JS_PutEscapedFlatString(char* buffer, size_t size, JSFlatString* str, char quote); - -/** - * Create a dependent string, i.e., a string that owns no character storage, - * but that refers to a slice of another string's chars. Dependent strings - * are mutable by definition, so the thread safety comments above apply. - */ -extern JS_PUBLIC_API(JSString*) -JS_NewDependentString(JSContext* cx, JS::HandleString str, size_t start, - size_t length); - -/** - * Concatenate two strings, possibly resulting in a rope. - * See above for thread safety comments. - */ -extern JS_PUBLIC_API(JSString*) -JS_ConcatStrings(JSContext* cx, JS::HandleString left, JS::HandleString right); - -/** - * For JS_DecodeBytes, set *dstlenp to the size of the destination buffer before - * the call; on return, *dstlenp contains the number of characters actually - * stored. To determine the necessary destination buffer size, make a sizing - * call that passes nullptr for dst. - * - * On errors, the functions report the error. In that case, *dstlenp contains - * the number of characters or bytes transferred so far. If cx is nullptr, no - * error is reported on failure, and the functions simply return false. - * - * NB: This function does not store an additional zero byte or char16_t after the - * transcoded string. - */ -JS_PUBLIC_API(bool) -JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen, char16_t* dst, - size_t* dstlenp); - -/** - * A variation on JS_EncodeCharacters where a null terminated string is - * returned that you are expected to call JS_free on when done. - */ -JS_PUBLIC_API(char*) -JS_EncodeString(JSContext* cx, JSString* str); - -/** - * Same behavior as JS_EncodeString(), but encode into UTF-8 string - */ -JS_PUBLIC_API(char*) -JS_EncodeStringToUTF8(JSContext* cx, JS::HandleString str); - -/** - * Get number of bytes in the string encoding (without accounting for a - * terminating zero bytes. The function returns (size_t) -1 if the string - * can not be encoded into bytes and reports an error using cx accordingly. - */ -JS_PUBLIC_API(size_t) -JS_GetStringEncodingLength(JSContext* cx, JSString* str); - -/** - * Encode string into a buffer. The function does not stores an additional - * zero byte. The function returns (size_t) -1 if the string can not be - * encoded into bytes with no error reported. Otherwise it returns the number - * of bytes that are necessary to encode the string. If that exceeds the - * length parameter, the string will be cut and only length bytes will be - * written into the buffer. - */ -JS_PUBLIC_API(size_t) -JS_EncodeStringToBuffer(JSContext* cx, JSString* str, char* buffer, size_t length); - -class MOZ_RAII JSAutoByteString -{ - public: - JSAutoByteString(JSContext* cx, JSString* str - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mBytes(JS_EncodeString(cx, str)) - { - MOZ_ASSERT(cx); - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit JSAutoByteString(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) - : mBytes(nullptr) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - ~JSAutoByteString() { - JS_free(nullptr, mBytes); - } - - /* Take ownership of the given byte array. */ - void initBytes(char* bytes) { - MOZ_ASSERT(!mBytes); - mBytes = bytes; - } - - char* encodeLatin1(JSContext* cx, JSString* str) { - MOZ_ASSERT(!mBytes); - MOZ_ASSERT(cx); - mBytes = JS_EncodeString(cx, str); - return mBytes; - } - - char* encodeLatin1(js::ExclusiveContext* cx, JSString* str); - - char* encodeUtf8(JSContext* cx, JS::HandleString str) { - MOZ_ASSERT(!mBytes); - MOZ_ASSERT(cx); - mBytes = JS_EncodeStringToUTF8(cx, str); - return mBytes; - } - - void clear() { - js_free(mBytes); - mBytes = nullptr; - } - - char* ptr() const { - return mBytes; - } - - bool operator!() const { - return !mBytes; - } - - size_t length() const { - if (!mBytes) - return 0; - return strlen(mBytes); - } - - private: - char* mBytes; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - - /* Copy and assignment are not supported. */ - JSAutoByteString(const JSAutoByteString& another); - JSAutoByteString& operator=(const JSAutoByteString& another); -}; - -namespace JS { - -extern JS_PUBLIC_API(JSAddonId*) -NewAddonId(JSContext* cx, JS::HandleString str); - -extern JS_PUBLIC_API(JSString*) -StringOfAddonId(JSAddonId* id); - -extern JS_PUBLIC_API(JSAddonId*) -AddonIdOfObject(JSObject* obj); - -} // namespace JS - -/************************************************************************/ -/* - * Symbols - */ - -namespace JS { - -/** - * Create a new Symbol with the given description. This function never returns - * a Symbol that is in the Runtime-wide symbol registry. - * - * If description is null, the new Symbol's [[Description]] attribute is - * undefined. - */ -JS_PUBLIC_API(Symbol*) -NewSymbol(JSContext* cx, HandleString description); - -/** - * Symbol.for as specified in ES6. - * - * Get a Symbol with the description 'key' from the Runtime-wide symbol registry. - * If there is not already a Symbol with that description in the registry, a new - * Symbol is created and registered. 'key' must not be null. - */ -JS_PUBLIC_API(Symbol*) -GetSymbolFor(JSContext* cx, HandleString key); - -/** - * Get the [[Description]] attribute of the given symbol. - * - * This function is infallible. If it returns null, that means the symbol's - * [[Description]] is undefined. - */ -JS_PUBLIC_API(JSString*) -GetSymbolDescription(HandleSymbol symbol); - -/* Well-known symbols. */ -#define JS_FOR_EACH_WELL_KNOWN_SYMBOL(macro) \ - macro(isConcatSpreadable) \ - macro(iterator) \ - macro(match) \ - macro(replace) \ - macro(search) \ - macro(species) \ - macro(hasInstance) \ - macro(split) \ - macro(toPrimitive) \ - macro(toStringTag) \ - macro(unscopables) - -enum class SymbolCode : uint32_t { - // There is one SymbolCode for each well-known symbol. -#define JS_DEFINE_SYMBOL_ENUM(name) name, - JS_FOR_EACH_WELL_KNOWN_SYMBOL(JS_DEFINE_SYMBOL_ENUM) // SymbolCode::iterator, etc. -#undef JS_DEFINE_SYMBOL_ENUM - Limit, - InSymbolRegistry = 0xfffffffe, // created by Symbol.for() or JS::GetSymbolFor() - UniqueSymbol = 0xffffffff // created by Symbol() or JS::NewSymbol() -}; - -/* For use in loops that iterate over the well-known symbols. */ -const size_t WellKnownSymbolLimit = size_t(SymbolCode::Limit); - -/** - * Return the SymbolCode telling what sort of symbol `symbol` is. - * - * A symbol's SymbolCode never changes once it is created. - */ -JS_PUBLIC_API(SymbolCode) -GetSymbolCode(Handle symbol); - -/** - * Get one of the well-known symbols defined by ES6. A single set of well-known - * symbols is shared by all compartments in a JSRuntime. - * - * `which` must be in the range [0, WellKnownSymbolLimit). - */ -JS_PUBLIC_API(Symbol*) -GetWellKnownSymbol(JSContext* cx, SymbolCode which); - -/** - * Return true if the given JSPropertySpec::name or JSFunctionSpec::name value - * is actually a symbol code and not a string. See JS_SYM_FN. - */ -inline bool -PropertySpecNameIsSymbol(const char* name) -{ - uintptr_t u = reinterpret_cast(name); - return u != 0 && u - 1 < WellKnownSymbolLimit; -} - -JS_PUBLIC_API(bool) -PropertySpecNameEqualsId(const char* name, HandleId id); - -/** - * Create a jsid that does not need to be marked for GC. - * - * 'name' is a JSPropertySpec::name or JSFunctionSpec::name value. The - * resulting jsid, on success, is either an interned string or a well-known - * symbol; either way it is immune to GC so there is no need to visit *idp - * during GC marking. - */ -JS_PUBLIC_API(bool) -PropertySpecNameToPermanentId(JSContext* cx, const char* name, jsid* idp); - -} /* namespace JS */ - -/************************************************************************/ -/* - * JSON functions - */ -typedef bool (* JSONWriteCallback)(const char16_t* buf, uint32_t len, void* data); - -/** - * JSON.stringify as specified by ES5. - */ -JS_PUBLIC_API(bool) -JS_Stringify(JSContext* cx, JS::MutableHandleValue value, JS::HandleObject replacer, - JS::HandleValue space, JSONWriteCallback callback, void* data); - -namespace JS { - -/** - * An API akin to JS_Stringify but with the goal of not having observable - * side-effects when the stringification is performed. This means it does not - * allow a replacer or a custom space, and has the following constraints on its - * input: - * - * 1) The input must be a plain object or array, not an abitrary value. - * 2) Every value in the graph reached by the algorithm starting with this - * object must be one of the following: null, undefined, a string (NOT a - * string object!), a boolean, a finite number (i.e. no NaN or Infinity or - * -Infinity), a plain object with no accessor properties, or an Array with - * no holes. - * - * The actual behavior differs from JS_Stringify only in asserting the above and - * NOT attempting to get the "toJSON" property from things, since that could - * clearly have side-effects. - */ -JS_PUBLIC_API(bool) -ToJSONMaybeSafely(JSContext* cx, JS::HandleObject input, - JSONWriteCallback callback, void* data); - -} /* namespace JS */ - -/** - * JSON.parse as specified by ES5. - */ -JS_PUBLIC_API(bool) -JS_ParseJSON(JSContext* cx, const char16_t* chars, uint32_t len, JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_ParseJSON(JSContext* cx, JS::HandleString str, JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_ParseJSONWithReviver(JSContext* cx, const char16_t* chars, uint32_t len, JS::HandleValue reviver, - JS::MutableHandleValue vp); - -JS_PUBLIC_API(bool) -JS_ParseJSONWithReviver(JSContext* cx, JS::HandleString str, JS::HandleValue reviver, - JS::MutableHandleValue vp); - -/************************************************************************/ - -/** - * The default locale for the ECMAScript Internationalization API - * (Intl.Collator, Intl.NumberFormat, Intl.DateTimeFormat). - * Note that the Internationalization API encourages clients to - * specify their own locales. - * The locale string remains owned by the caller. - */ -extern JS_PUBLIC_API(bool) -JS_SetDefaultLocale(JSContext* cx, const char* locale); - -/** - * Look up the default locale for the ECMAScript Internationalization API. - */ -extern JS_PUBLIC_API(JS::UniqueChars) -JS_GetDefaultLocale(JSContext* cx); - -/** - * Reset the default locale to OS defaults. - */ -extern JS_PUBLIC_API(void) -JS_ResetDefaultLocale(JSContext* cx); - -/** - * Locale specific string conversion and error message callbacks. - */ -struct JSLocaleCallbacks { - JSLocaleToUpperCase localeToUpperCase; - JSLocaleToLowerCase localeToLowerCase; - JSLocaleCompare localeCompare; // not used #if EXPOSE_INTL_API - JSLocaleToUnicode localeToUnicode; -}; - -/** - * Establish locale callbacks. The pointer must persist as long as the - * JSContext. Passing nullptr restores the default behaviour. - */ -extern JS_PUBLIC_API(void) -JS_SetLocaleCallbacks(JSContext* cx, const JSLocaleCallbacks* callbacks); - -/** - * Return the address of the current locale callbacks struct, which may - * be nullptr. - */ -extern JS_PUBLIC_API(const JSLocaleCallbacks*) -JS_GetLocaleCallbacks(JSContext* cx); - -/************************************************************************/ - -/* - * Error reporting. - */ - -namespace JS { -const uint16_t MaxNumErrorArguments = 10; -}; - -/** - * Report an exception represented by the sprintf-like conversion of format - * and its arguments. - */ -extern JS_PUBLIC_API(void) -JS_ReportErrorASCII(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(void) -JS_ReportErrorLatin1(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(void) -JS_ReportErrorUTF8(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -/* - * Use an errorNumber to retrieve the format string, args are char* - */ -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberASCII(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberASCIIVA(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, va_list ap); - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberLatin1(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -#ifdef va_start -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberLatin1VA(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, va_list ap); -#endif - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUTF8(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -#ifdef va_start -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUTF8VA(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, va_list ap); -#endif - -/* - * Use an errorNumber to retrieve the format string, args are char16_t* - */ -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUC(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(void) -JS_ReportErrorNumberUCArray(JSContext* cx, JSErrorCallback errorCallback, - void* userRef, const unsigned errorNumber, - const char16_t** args); - -/** - * As above, but report a warning instead (JSREPORT_IS_WARNING(report.flags)). - * Return true if there was no error trying to issue the warning, and if the - * warning was not converted into an error due to the JSOPTION_WERROR option - * being set, false otherwise. - */ -extern JS_PUBLIC_API(bool) -JS_ReportWarningASCII(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(bool) -JS_ReportWarningLatin1(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(bool) -JS_ReportWarningUTF8(JSContext* cx, const char* format, ...) - MOZ_FORMAT_PRINTF(2, 3); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberASCII(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberLatin1(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberUTF8(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -extern JS_PUBLIC_API(bool) -JS_ReportErrorFlagsAndNumberUC(JSContext* cx, unsigned flags, - JSErrorCallback errorCallback, void* userRef, - const unsigned errorNumber, ...); - -/** - * Complain when out of memory. - */ -extern JS_PUBLIC_API(void) -JS_ReportOutOfMemory(JSContext* cx); - -/** - * Complain when an allocation size overflows the maximum supported limit. - */ -extern JS_PUBLIC_API(void) -JS_ReportAllocationOverflow(JSContext* cx); - -class JSErrorReport -{ - // The (default) error message. - // If ownsMessage_ is true, the it is freed in destructor. - JS::ConstUTF8CharsZ message_; - - // Offending source line without final '\n'. - // If ownsLinebuf__ is true, the buffer is freed in destructor. - const char16_t* linebuf_; - - // Number of chars in linebuf_. Does not include trailing '\0'. - size_t linebufLength_; - - // The 0-based offset of error token in linebuf_. - size_t tokenOffset_; - - public: - JSErrorReport() - : linebuf_(nullptr), linebufLength_(0), tokenOffset_(0), - filename(nullptr), lineno(0), column(0), - flags(0), errorNumber(0), - exnType(0), isMuted(false), - ownsLinebuf_(false), ownsMessage_(false) - {} - - ~JSErrorReport() { - freeLinebuf(); - freeMessage(); - } - - const char* filename; /* source file name, URL, etc., or null */ - unsigned lineno; /* source line number */ - unsigned column; /* zero-based column index in line */ - unsigned flags; /* error/warning, etc. */ - unsigned errorNumber; /* the error number, e.g. see js.msg */ - int16_t exnType; /* One of the JSExnType constants */ - bool isMuted : 1; /* See the comment in ReadOnlyCompileOptions. */ - - private: - bool ownsLinebuf_ : 1; - bool ownsMessage_ : 1; - - public: - const char16_t* linebuf() const { - return linebuf_; - } - size_t linebufLength() const { - return linebufLength_; - } - size_t tokenOffset() const { - return tokenOffset_; - } - void initOwnedLinebuf(const char16_t* linebufArg, size_t linebufLengthArg, size_t tokenOffsetArg) { - initBorrowedLinebuf(linebufArg, linebufLengthArg, tokenOffsetArg); - ownsLinebuf_ = true; - } - void initBorrowedLinebuf(const char16_t* linebufArg, size_t linebufLengthArg, size_t tokenOffsetArg); - void freeLinebuf(); - - const JS::ConstUTF8CharsZ message() const { - return message_; - } - - void initOwnedMessage(const char* messageArg) { - initBorrowedMessage(messageArg); - ownsMessage_ = true; - } - void initBorrowedMessage(const char* messageArg) { - MOZ_ASSERT(!message_); - message_ = JS::ConstUTF8CharsZ(messageArg, strlen(messageArg)); - } - - JSString* newMessageString(JSContext* cx); - - void freeMessage(); -}; - -/* - * JSErrorReport flag values. These may be freely composed. - */ -#define JSREPORT_ERROR 0x0 /* pseudo-flag for default case */ -#define JSREPORT_WARNING 0x1 /* reported via JS_ReportWarning */ -#define JSREPORT_EXCEPTION 0x2 /* exception was thrown */ -#define JSREPORT_STRICT 0x4 /* error or warning due to strict option */ - -#define JSREPORT_USER_1 0x8 /* user-defined flag */ - -/* - * If JSREPORT_EXCEPTION is set, then a JavaScript-catchable exception - * has been thrown for this runtime error, and the host should ignore it. - * Exception-aware hosts should also check for JS_IsExceptionPending if - * JS_ExecuteScript returns failure, and signal or propagate the exception, as - * appropriate. - */ -#define JSREPORT_IS_WARNING(flags) (((flags) & JSREPORT_WARNING) != 0) -#define JSREPORT_IS_EXCEPTION(flags) (((flags) & JSREPORT_EXCEPTION) != 0) -#define JSREPORT_IS_STRICT(flags) (((flags) & JSREPORT_STRICT) != 0) - -namespace JS { - -using WarningReporter = void (*)(JSContext* cx, JSErrorReport* report); - -extern JS_PUBLIC_API(WarningReporter) -SetWarningReporter(JSContext* cx, WarningReporter reporter); - -extern JS_PUBLIC_API(WarningReporter) -GetWarningReporter(JSContext* cx); - -extern JS_PUBLIC_API(bool) -CreateError(JSContext* cx, JSExnType type, HandleObject stack, - HandleString fileName, uint32_t lineNumber, uint32_t columnNumber, - JSErrorReport* report, HandleString message, MutableHandleValue rval); - -/************************************************************************/ - -/* - * Weak Maps. - */ - -extern JS_PUBLIC_API(JSObject*) -NewWeakMapObject(JSContext* cx); - -extern JS_PUBLIC_API(bool) -IsWeakMapObject(JSObject* obj); - -extern JS_PUBLIC_API(bool) -GetWeakMapEntry(JSContext* cx, JS::HandleObject mapObj, JS::HandleObject key, - JS::MutableHandleValue val); - -extern JS_PUBLIC_API(bool) -SetWeakMapEntry(JSContext* cx, JS::HandleObject mapObj, JS::HandleObject key, - JS::HandleValue val); - -/* - * Map - */ -extern JS_PUBLIC_API(JSObject*) -NewMapObject(JSContext* cx); - -extern JS_PUBLIC_API(uint32_t) -MapSize(JSContext* cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -MapGet(JSContext* cx, HandleObject obj, - HandleValue key, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapHas(JSContext* cx, HandleObject obj, HandleValue key, bool* rval); - -extern JS_PUBLIC_API(bool) -MapSet(JSContext* cx, HandleObject obj, HandleValue key, HandleValue val); - -extern JS_PUBLIC_API(bool) -MapDelete(JSContext *cx, HandleObject obj, HandleValue key, bool *rval); - -extern JS_PUBLIC_API(bool) -MapClear(JSContext* cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -MapKeys(JSContext* cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapValues(JSContext* cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapEntries(JSContext* cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -MapForEach(JSContext *cx, HandleObject obj, HandleValue callbackFn, HandleValue thisVal); - -/* - * Set - */ -extern JS_PUBLIC_API(JSObject *) -NewSetObject(JSContext *cx); - -extern JS_PUBLIC_API(uint32_t) -SetSize(JSContext *cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -SetHas(JSContext *cx, HandleObject obj, HandleValue key, bool *rval); - -extern JS_PUBLIC_API(bool) -SetDelete(JSContext *cx, HandleObject obj, HandleValue key, bool *rval); - -extern JS_PUBLIC_API(bool) -SetAdd(JSContext *cx, HandleObject obj, HandleValue key); - -extern JS_PUBLIC_API(bool) -SetClear(JSContext *cx, HandleObject obj); - -extern JS_PUBLIC_API(bool) -SetKeys(JSContext *cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -SetValues(JSContext *cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -SetEntries(JSContext *cx, HandleObject obj, MutableHandleValue rval); - -extern JS_PUBLIC_API(bool) -SetForEach(JSContext *cx, HandleObject obj, HandleValue callbackFn, HandleValue thisVal); - -} /* namespace JS */ - -/* - * Dates. - */ - -extern JS_PUBLIC_API(JSObject*) -JS_NewDateObject(JSContext* cx, int year, int mon, int mday, int hour, int min, int sec); - -/** - * Returns true and sets |*isDate| indicating whether |obj| is a Date object or - * a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isDate == false| when passed a proxy whose - * target is a Date, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_ObjectIsDate(JSContext* cx, JS::HandleObject obj, bool* isDate); - -/************************************************************************/ - -/* - * Regular Expressions. - */ -#define JSREG_FOLD 0x01u /* fold uppercase to lowercase */ -#define JSREG_GLOB 0x02u /* global exec, creates array of matches */ -#define JSREG_MULTILINE 0x04u /* treat ^ and $ as begin and end of line */ -#define JSREG_STICKY 0x08u /* only match starting at lastIndex */ -#define JSREG_UNICODE 0x10u /* unicode */ - -extern JS_PUBLIC_API(JSObject*) -JS_NewRegExpObject(JSContext* cx, const char* bytes, size_t length, unsigned flags); - -extern JS_PUBLIC_API(JSObject*) -JS_NewUCRegExpObject(JSContext* cx, const char16_t* chars, size_t length, unsigned flags); - -extern JS_PUBLIC_API(bool) -JS_SetRegExpInput(JSContext* cx, JS::HandleObject obj, JS::HandleString input); - -extern JS_PUBLIC_API(bool) -JS_ClearRegExpStatics(JSContext* cx, JS::HandleObject obj); - -extern JS_PUBLIC_API(bool) -JS_ExecuteRegExp(JSContext* cx, JS::HandleObject obj, JS::HandleObject reobj, - char16_t* chars, size_t length, size_t* indexp, bool test, - JS::MutableHandleValue rval); - -/* RegExp interface for clients without a global object. */ - -extern JS_PUBLIC_API(bool) -JS_ExecuteRegExpNoStatics(JSContext* cx, JS::HandleObject reobj, char16_t* chars, size_t length, - size_t* indexp, bool test, JS::MutableHandleValue rval); - -/** - * Returns true and sets |*isRegExp| indicating whether |obj| is a RegExp - * object or a wrapper around one, otherwise returns false on failure. - * - * This method returns true with |*isRegExp == false| when passed a proxy whose - * target is a RegExp, or when passed a revoked proxy. - */ -extern JS_PUBLIC_API(bool) -JS_ObjectIsRegExp(JSContext* cx, JS::HandleObject obj, bool* isRegExp); - -extern JS_PUBLIC_API(unsigned) -JS_GetRegExpFlags(JSContext* cx, JS::HandleObject obj); - -extern JS_PUBLIC_API(JSString*) -JS_GetRegExpSource(JSContext* cx, JS::HandleObject obj); - -/************************************************************************/ - -extern JS_PUBLIC_API(bool) -JS_IsExceptionPending(JSContext* cx); - -extern JS_PUBLIC_API(bool) -JS_GetPendingException(JSContext* cx, JS::MutableHandleValue vp); - -extern JS_PUBLIC_API(void) -JS_SetPendingException(JSContext* cx, JS::HandleValue v); - -extern JS_PUBLIC_API(void) -JS_ClearPendingException(JSContext* cx); - -namespace JS { - -/** - * Save and later restore the current exception state of a given JSContext. - * This is useful for implementing behavior in C++ that's like try/catch - * or try/finally in JS. - * - * Typical usage: - * - * bool ok = JS::Evaluate(cx, ...); - * AutoSaveExceptionState savedExc(cx); - * ... cleanup that might re-enter JS ... - * return ok; - */ -class JS_PUBLIC_API(AutoSaveExceptionState) -{ - private: - JSContext* context; - bool wasPropagatingForcedReturn; - bool wasOverRecursed; - bool wasThrowing; - RootedValue exceptionValue; - - public: - /* - * Take a snapshot of cx's current exception state. Then clear any current - * pending exception in cx. - */ - explicit AutoSaveExceptionState(JSContext* cx); - - /* - * If neither drop() nor restore() was called, restore the exception - * state only if no exception is currently pending on cx. - */ - ~AutoSaveExceptionState(); - - /* - * Discard any stored exception state. - * If this is called, the destructor is a no-op. - */ - void drop() { - wasPropagatingForcedReturn = false; - wasOverRecursed = false; - wasThrowing = false; - exceptionValue.setUndefined(); - } - - /* - * Replace cx's exception state with the stored exception state. Then - * discard the stored exception state. If this is called, the - * destructor is a no-op. - */ - void restore(); -}; - -} /* namespace JS */ - -/* Deprecated API. Use AutoSaveExceptionState instead. */ -extern JS_PUBLIC_API(JSExceptionState*) -JS_SaveExceptionState(JSContext* cx); - -extern JS_PUBLIC_API(void) -JS_RestoreExceptionState(JSContext* cx, JSExceptionState* state); - -extern JS_PUBLIC_API(void) -JS_DropExceptionState(JSContext* cx, JSExceptionState* state); - -/** - * If the given object is an exception object, the exception will have (or be - * able to lazily create) an error report struct, and this function will return - * the address of that struct. Otherwise, it returns nullptr. The lifetime - * of the error report struct that might be returned is the same as the - * lifetime of the exception object. - */ -extern JS_PUBLIC_API(JSErrorReport*) -JS_ErrorFromException(JSContext* cx, JS::HandleObject obj); - -/** - * If the given object is an exception object (or an unwrappable - * cross-compartment wrapper for one), return the stack for that exception, if - * any. Will return null if the given object is not an exception object - * (including if it's null or a security wrapper that can't be unwrapped) or if - * the exception has no stack. - */ -extern JS_PUBLIC_API(JSObject*) -ExceptionStackOrNull(JS::HandleObject obj); - -/* - * Throws a StopIteration exception on cx. - */ -extern JS_PUBLIC_API(bool) -JS_ThrowStopIteration(JSContext* cx); - -extern JS_PUBLIC_API(bool) -JS_IsStopIteration(const JS::Value& v); - -/** - * A JS context always has an "owner thread". The owner thread is set when the - * context is created (to the current thread) and practically all entry points - * into the JS engine check that a context (or anything contained in the - * context: runtime, compartment, object, etc) is only touched by its owner - * thread. Embeddings may check this invariant outside the JS engine by calling - * JS_AbortIfWrongThread (which will abort if not on the owner thread, even for - * non-debug builds). - */ - -extern JS_PUBLIC_API(void) -JS_AbortIfWrongThread(JSContext* cx); - -/************************************************************************/ - -/** - * A constructor can request that the JS engine create a default new 'this' - * object of the given class, using the callee to determine parentage and - * [[Prototype]]. - */ -extern JS_PUBLIC_API(JSObject*) -JS_NewObjectForConstructor(JSContext* cx, const JSClass* clasp, const JS::CallArgs& args); - -/************************************************************************/ - -#ifdef JS_GC_ZEAL -#define JS_DEFAULT_ZEAL_FREQ 100 - -extern JS_PUBLIC_API(void) -JS_GetGCZealBits(JSContext* cx, uint32_t* zealBits, uint32_t* frequency, uint32_t* nextScheduled); - -extern JS_PUBLIC_API(void) -JS_SetGCZeal(JSContext* cx, uint8_t zeal, uint32_t frequency); - -extern JS_PUBLIC_API(void) -JS_ScheduleGC(JSContext* cx, uint32_t count); -#endif - -extern JS_PUBLIC_API(void) -JS_SetParallelParsingEnabled(JSContext* cx, bool enabled); - -extern JS_PUBLIC_API(void) -JS_SetOffthreadIonCompilationEnabled(JSContext* cx, bool enabled); - -#define JIT_COMPILER_OPTIONS(Register) \ - Register(BASELINE_WARMUP_TRIGGER, "baseline.warmup.trigger") \ - Register(ION_WARMUP_TRIGGER, "ion.warmup.trigger") \ - Register(ION_GVN_ENABLE, "ion.gvn.enable") \ - Register(ION_FORCE_IC, "ion.forceinlineCaches") \ - Register(ION_ENABLE, "ion.enable") \ - Register(ION_INTERRUPT_WITHOUT_SIGNAL, "ion.interrupt-without-signals") \ - Register(ION_CHECK_RANGE_ANALYSIS, "ion.check-range-analysis") \ - Register(BASELINE_ENABLE, "baseline.enable") \ - Register(OFFTHREAD_COMPILATION_ENABLE, "offthread-compilation.enable") \ - Register(JUMP_THRESHOLD, "jump-threshold") \ - Register(ASMJS_ATOMICS_ENABLE, "asmjs.atomics.enable") \ - Register(WASM_TEST_MODE, "wasm.test-mode") \ - Register(WASM_FOLD_OFFSETS, "wasm.fold-offsets") - -typedef enum JSJitCompilerOption { -#define JIT_COMPILER_DECLARE(key, str) \ - JSJITCOMPILER_ ## key, - - JIT_COMPILER_OPTIONS(JIT_COMPILER_DECLARE) -#undef JIT_COMPILER_DECLARE - - JSJITCOMPILER_NOT_AN_OPTION -} JSJitCompilerOption; - -extern JS_PUBLIC_API(void) -JS_SetGlobalJitCompilerOption(JSContext* cx, JSJitCompilerOption opt, uint32_t value); -extern JS_PUBLIC_API(bool) -JS_GetGlobalJitCompilerOption(JSContext* cx, JSJitCompilerOption opt, uint32_t* valueOut); - -/** - * Convert a uint32_t index into a jsid. - */ -extern JS_PUBLIC_API(bool) -JS_IndexToId(JSContext* cx, uint32_t index, JS::MutableHandleId); - -/** - * Convert chars into a jsid. - * - * |chars| may not be an index. - */ -extern JS_PUBLIC_API(bool) -JS_CharsToId(JSContext* cx, JS::TwoByteChars chars, JS::MutableHandleId); - -/** - * Test if the given string is a valid ECMAScript identifier - */ -extern JS_PUBLIC_API(bool) -JS_IsIdentifier(JSContext* cx, JS::HandleString str, bool* isIdentifier); - -/** - * Test whether the given chars + length are a valid ECMAScript identifier. - * This version is infallible, so just returns whether the chars are an - * identifier. - */ -extern JS_PUBLIC_API(bool) -JS_IsIdentifier(const char16_t* chars, size_t length); - -namespace js { -class ScriptSource; -} // namespace js - -namespace JS { - -class MOZ_RAII JS_PUBLIC_API(AutoFilename) -{ - private: - js::ScriptSource* ss_; - mozilla::Variant filename_; - - AutoFilename(const AutoFilename&) = delete; - AutoFilename& operator=(const AutoFilename&) = delete; - - public: - AutoFilename() - : ss_(nullptr), - filename_(mozilla::AsVariant(nullptr)) - {} - - ~AutoFilename() { - reset(); - } - - void reset(); - - void setOwned(UniqueChars&& filename); - void setUnowned(const char* filename); - void setScriptSource(js::ScriptSource* ss); - - const char* get() const; -}; - -/** - * Return the current filename, line number and column number of the most - * currently running frame. Returns true if a scripted frame was found, false - * otherwise. - * - * If a the embedding has hidden the scripted caller for the topmost activation - * record, this will also return false. - */ -extern JS_PUBLIC_API(bool) -DescribeScriptedCaller(JSContext* cx, AutoFilename* filename = nullptr, - unsigned* lineno = nullptr, unsigned* column = nullptr); - -extern JS_PUBLIC_API(JSObject*) -GetScriptedCallerGlobal(JSContext* cx); - -/** - * Informs the JS engine that the scripted caller should be hidden. This can be - * used by the embedding to maintain an override of the scripted caller in its - * calculations, by hiding the scripted caller in the JS engine and pushing data - * onto a separate stack, which it inspects when DescribeScriptedCaller returns - * null. - * - * We maintain a counter on each activation record. Add() increments the counter - * of the topmost activation, and Remove() decrements it. The count may never - * drop below zero, and must always be exactly zero when the activation is - * popped from the stack. - */ -extern JS_PUBLIC_API(void) -HideScriptedCaller(JSContext* cx); - -extern JS_PUBLIC_API(void) -UnhideScriptedCaller(JSContext* cx); - -class MOZ_RAII AutoHideScriptedCaller -{ - public: - explicit AutoHideScriptedCaller(JSContext* cx - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mContext(cx) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - HideScriptedCaller(mContext); - } - ~AutoHideScriptedCaller() { - UnhideScriptedCaller(mContext); - } - - protected: - JSContext* mContext; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/* - * Encode/Decode interpreted scripts and functions to/from memory. - */ - -typedef mozilla::Vector TranscodeBuffer; - -enum TranscodeResult -{ - // Successful encoding / decoding. - TranscodeResult_Ok = 0, - - // A warning message, is set to the message out-param. - TranscodeResult_Failure = 0x100, - TranscodeResult_Failure_BadBuildId = TranscodeResult_Failure | 0x1, - TranscodeResult_Failure_RunOnceNotSupported = TranscodeResult_Failure | 0x2, - TranscodeResult_Failure_AsmJSNotSupported = TranscodeResult_Failure | 0x3, - TranscodeResult_Failure_UnknownClassKind = TranscodeResult_Failure | 0x4, - - // A error, the JSContext has a pending exception. - TranscodeResult_Throw = 0x200 -}; - -extern JS_PUBLIC_API(TranscodeResult) -EncodeScript(JSContext* cx, TranscodeBuffer& buffer, JS::HandleScript script); - -extern JS_PUBLIC_API(TranscodeResult) -EncodeInterpretedFunction(JSContext* cx, TranscodeBuffer& buffer, JS::HandleObject funobj); - -extern JS_PUBLIC_API(TranscodeResult) -DecodeScript(JSContext* cx, TranscodeBuffer& buffer, JS::MutableHandleScript scriptp, - size_t cursorIndex = 0); - -extern JS_PUBLIC_API(TranscodeResult) -DecodeInterpretedFunction(JSContext* cx, TranscodeBuffer& buffer, JS::MutableHandleFunction funp, - size_t cursorIndex = 0); - -} /* namespace JS */ - -namespace js { - -enum class StackFormat { SpiderMonkey, V8, Default }; - -/* - * Sets the format used for stringifying Error stacks. - * - * The default format is StackFormat::SpiderMonkey. Use StackFormat::V8 - * in order to emulate V8's stack formatting. StackFormat::Default can't be - * used here. - */ -extern JS_PUBLIC_API(void) -SetStackFormat(JSContext* cx, StackFormat format); - -extern JS_PUBLIC_API(StackFormat) -GetStackFormat(JSContext* cx); - -} - -namespace JS { - -/* - * This callback represents a request by the JS engine to open for reading the - * existing cache entry for the given global and char range that may contain a - * module. If a cache entry exists, the callback shall return 'true' and return - * the size, base address and an opaque file handle as outparams. If the - * callback returns 'true', the JS engine guarantees a call to - * CloseAsmJSCacheEntryForReadOp, passing the same base address, size and - * handle. - */ -typedef bool -(* OpenAsmJSCacheEntryForReadOp)(HandleObject global, const char16_t* begin, const char16_t* limit, - size_t* size, const uint8_t** memory, intptr_t* handle); -typedef void -(* CloseAsmJSCacheEntryForReadOp)(size_t size, const uint8_t* memory, intptr_t handle); - -/** The list of reasons why an asm.js module may not be stored in the cache. */ -enum AsmJSCacheResult -{ - AsmJSCache_Success, - AsmJSCache_MIN = AsmJSCache_Success, - AsmJSCache_ModuleTooSmall, - AsmJSCache_SynchronousScript, - AsmJSCache_QuotaExceeded, - AsmJSCache_StorageInitFailure, - AsmJSCache_Disabled_Internal, - AsmJSCache_Disabled_ShellFlags, - AsmJSCache_Disabled_JitInspector, - AsmJSCache_InternalError, - AsmJSCache_Disabled_PrivateBrowsing, - AsmJSCache_LIMIT -}; - -/* - * This callback represents a request by the JS engine to open for writing a - * cache entry of the given size for the given global and char range containing - * the just-compiled module. If cache entry space is available, the callback - * shall return 'true' and return the base address and an opaque file handle as - * outparams. If the callback returns 'true', the JS engine guarantees a call - * to CloseAsmJSCacheEntryForWriteOp passing the same base address, size and - * handle. - * - * If 'installed' is true, then the cache entry is associated with a permanently - * installed JS file (e.g., in a packaged webapp). This information allows the - * embedding to store the cache entry in a installed location associated with - * the principal of 'global' where it will not be evicted until the associated - * installed JS file is removed. - */ -typedef AsmJSCacheResult -(* OpenAsmJSCacheEntryForWriteOp)(HandleObject global, bool installed, - const char16_t* begin, const char16_t* end, - size_t size, uint8_t** memory, intptr_t* handle); -typedef void -(* CloseAsmJSCacheEntryForWriteOp)(size_t size, uint8_t* memory, intptr_t handle); - -struct AsmJSCacheOps -{ - OpenAsmJSCacheEntryForReadOp openEntryForRead; - CloseAsmJSCacheEntryForReadOp closeEntryForRead; - OpenAsmJSCacheEntryForWriteOp openEntryForWrite; - CloseAsmJSCacheEntryForWriteOp closeEntryForWrite; -}; - -extern JS_PUBLIC_API(void) -SetAsmJSCacheOps(JSContext* cx, const AsmJSCacheOps* callbacks); - -/** - * Return the buildId (represented as a sequence of characters) associated with - * the currently-executing build. If the JS engine is embedded such that a - * single cache entry can be observed by different compiled versions of the JS - * engine, it is critical that the buildId shall change for each new build of - * the JS engine. - */ -typedef js::Vector BuildIdCharVector; - -typedef bool -(* BuildIdOp)(BuildIdCharVector* buildId); - -extern JS_PUBLIC_API(void) -SetBuildIdOp(JSContext* cx, BuildIdOp buildIdOp); - -/** - * The WasmModule interface allows the embedding to hold a reference to the - * underying C++ implementation of a JS WebAssembly.Module object for purposes - * of (de)serialization off the object's JSRuntime's thread. - * - * - Serialization starts when WebAssembly.Module is passed to the - * structured-clone algorithm. JS::GetWasmModule is called on the JSRuntime - * thread that initiated the structured clone to get the JS::WasmModule. - * This interface is then taken to a background thread where serializedSize() - * and serialize() are called to write the object to two files: a bytecode file - * that always allows successful deserialization and a compiled-code file keyed - * on cpu- and build-id that may become invalid if either of these change between - * serialization and deserialization. After serialization, the reference is - * dropped from the background thread. - * - * - Deserialization starts when the structured clone algorithm encounters a - * serialized WebAssembly.Module. On a background thread, the compiled-code file - * is opened and CompiledWasmModuleAssumptionsMatch is called to see if it is - * still valid (as described above). DeserializeWasmModule is then called to - * construct a JS::WasmModule (also on the background thread), passing the - * bytecode file descriptor and, if valid, the compiled-code file descriptor. - * The JS::WasmObject is then transported to the JSRuntime thread (which - * originated the request) and the wrapping WebAssembly.Module object is created - * by calling createObject(). - */ - -struct WasmModule : mozilla::external::AtomicRefCounted -{ - MOZ_DECLARE_REFCOUNTED_TYPENAME(WasmModule) - virtual ~WasmModule() {} - - virtual void serializedSize(size_t* maybeBytecodeSize, size_t* maybeCompiledSize) const = 0; - virtual void serialize(uint8_t* maybeBytecodeBegin, size_t maybeBytecodeSize, - uint8_t* maybeCompiledBegin, size_t maybeCompiledSize) const = 0; - - virtual JSObject* createObject(JSContext* cx) = 0; -}; - -extern JS_PUBLIC_API(bool) -IsWasmModuleObject(HandleObject obj); - -extern JS_PUBLIC_API(RefPtr) -GetWasmModule(HandleObject obj); - -extern JS_PUBLIC_API(bool) -CompiledWasmModuleAssumptionsMatch(PRFileDesc* compiled, BuildIdCharVector&& buildId); - -extern JS_PUBLIC_API(RefPtr) -DeserializeWasmModule(PRFileDesc* bytecode, PRFileDesc* maybeCompiled, BuildIdCharVector&& buildId, - JS::UniqueChars filename, unsigned line, unsigned column); - -/** - * Convenience class for imitating a JS level for-of loop. Typical usage: - * - * ForOfIterator it(cx); - * if (!it.init(iterable)) - * return false; - * RootedValue val(cx); - * while (true) { - * bool done; - * if (!it.next(&val, &done)) - * return false; - * if (done) - * break; - * if (!DoStuff(cx, val)) - * return false; - * } - */ -class MOZ_STACK_CLASS JS_PUBLIC_API(ForOfIterator) { - protected: - JSContext* cx_; - /* - * Use the ForOfPIC on the global object (see vm/GlobalObject.h) to try - * to optimize iteration across arrays. - * - * Case 1: Regular Iteration - * iterator - pointer to the iterator object. - * index - fixed to NOT_ARRAY (== UINT32_MAX) - * - * Case 2: Optimized Array Iteration - * iterator - pointer to the array object. - * index - current position in array. - * - * The cases are distinguished by whether or not |index| is equal to NOT_ARRAY. - */ - JS::RootedObject iterator; - uint32_t index; - - static const uint32_t NOT_ARRAY = UINT32_MAX; - - ForOfIterator(const ForOfIterator&) = delete; - ForOfIterator& operator=(const ForOfIterator&) = delete; - - public: - explicit ForOfIterator(JSContext* cx) : cx_(cx), iterator(cx_), index(NOT_ARRAY) { } - - enum NonIterableBehavior { - ThrowOnNonIterable, - AllowNonIterable - }; - - /** - * Initialize the iterator. If AllowNonIterable is passed then if getting - * the @@iterator property from iterable returns undefined init() will just - * return true instead of throwing. Callers must then check - * valueIsIterable() before continuing with the iteration. - */ - bool init(JS::HandleValue iterable, - NonIterableBehavior nonIterableBehavior = ThrowOnNonIterable); - - /** - * Get the next value from the iterator. If false *done is true - * after this call, do not examine val. - */ - bool next(JS::MutableHandleValue val, bool* done); - - /** - * If initialized with throwOnNonCallable = false, check whether - * the value is iterable. - */ - bool valueIsIterable() const { - return iterator; - } - - private: - inline bool nextFromOptimizedArray(MutableHandleValue val, bool* done); - bool materializeArrayIterator(); -}; - - -/** - * If a large allocation fails when calling pod_{calloc,realloc}CanGC, the JS - * engine may call the large-allocation- failure callback, if set, to allow the - * embedding to flush caches, possibly perform shrinking GCs, etc. to make some - * room. The allocation will then be retried (and may still fail.) - */ - -typedef void -(* LargeAllocationFailureCallback)(void* data); - -extern JS_PUBLIC_API(void) -SetLargeAllocationFailureCallback(JSContext* cx, LargeAllocationFailureCallback afc, void* data); - -/** - * Unlike the error reporter, which is only called if the exception for an OOM - * bubbles up and is not caught, the OutOfMemoryCallback is called immediately - * at the OOM site to allow the embedding to capture the current state of heap - * allocation before anything is freed. If the large-allocation-failure callback - * is called at all (not all allocation sites call the large-allocation-failure - * callback on failure), it is called before the out-of-memory callback; the - * out-of-memory callback is only called if the allocation still fails after the - * large-allocation-failure callback has returned. - */ - -typedef void -(* OutOfMemoryCallback)(JSContext* cx, void* data); - -extern JS_PUBLIC_API(void) -SetOutOfMemoryCallback(JSContext* cx, OutOfMemoryCallback cb, void* data); - -/** - * Capture all frames. - */ -struct AllFrames { }; - -/** - * Capture at most this many frames. - */ -struct MaxFrames -{ - uint32_t maxFrames; - - explicit MaxFrames(uint32_t max) - : maxFrames(max) - { - MOZ_ASSERT(max > 0); - } -}; - -/** - * Capture the first frame with the given principals. By default, do not - * consider self-hosted frames with the given principals as satisfying the stack - * capture. - */ -struct FirstSubsumedFrame -{ - JSContext* cx; - JSPrincipals* principals; - bool ignoreSelfHosted; - - /** - * Use the cx's current compartment's principals. - */ - explicit FirstSubsumedFrame(JSContext* cx, bool ignoreSelfHostedFrames = true); - - explicit FirstSubsumedFrame(JSContext* ctx, JSPrincipals* p, bool ignoreSelfHostedFrames = true) - : cx(ctx) - , principals(p) - , ignoreSelfHosted(ignoreSelfHostedFrames) - { - if (principals) - JS_HoldPrincipals(principals); - } - - // No copying because we want to avoid holding and dropping principals - // unnecessarily. - FirstSubsumedFrame(const FirstSubsumedFrame&) = delete; - FirstSubsumedFrame& operator=(const FirstSubsumedFrame&) = delete; - - FirstSubsumedFrame(FirstSubsumedFrame&& rhs) - : principals(rhs.principals) - , ignoreSelfHosted(rhs.ignoreSelfHosted) - { - MOZ_ASSERT(this != &rhs, "self move disallowed"); - rhs.principals = nullptr; - } - - FirstSubsumedFrame& operator=(FirstSubsumedFrame&& rhs) { - new (this) FirstSubsumedFrame(mozilla::Move(rhs)); - return *this; - } - - ~FirstSubsumedFrame() { - if (principals) - JS_DropPrincipals(cx, principals); - } -}; - -using StackCapture = mozilla::Variant; - -/** - * Capture the current call stack as a chain of SavedFrame JSObjects, and set - * |stackp| to the SavedFrame for the youngest stack frame, or nullptr if there - * are no JS frames on the stack. - * - * The |capture| parameter describes the portion of the JS stack to capture: - * - * * |JS::AllFrames|: Capture all frames on the stack. - * - * * |JS::MaxFrames|: Capture no more than |JS::MaxFrames::maxFrames| from the - * stack. - * - * * |JS::FirstSubsumedFrame|: Capture the first frame whose principals are - * subsumed by |JS::FirstSubsumedFrame::principals|. By default, do not - * consider self-hosted frames; this can be controlled via the - * |JS::FirstSubsumedFrame::ignoreSelfHosted| flag. Do not capture any async - * stack. - */ -extern JS_PUBLIC_API(bool) -CaptureCurrentStack(JSContext* cx, MutableHandleObject stackp, - StackCapture&& capture = StackCapture(AllFrames())); - -/* - * This is a utility function for preparing an async stack to be used - * by some other object. This may be used when you need to treat a - * given stack trace as an async parent. If you just need to capture - * the current stack, async parents and all, use CaptureCurrentStack - * instead. - * - * Here |asyncStack| is the async stack to prepare. It is copied into - * |cx|'s current compartment, and the newest frame is given - * |asyncCause| as its asynchronous cause. If |maxFrameCount| is - * non-zero, capture at most the youngest |maxFrameCount| frames. The - * new stack object is written to |stackp|. Returns true on success, - * or sets an exception and returns |false| on error. - */ -extern JS_PUBLIC_API(bool) -CopyAsyncStack(JSContext* cx, HandleObject asyncStack, - HandleString asyncCause, MutableHandleObject stackp, - unsigned maxFrameCount); - -/* - * Accessors for working with SavedFrame JSObjects - * - * Each of these functions assert that if their `HandleObject savedFrame` - * argument is non-null, its JSClass is the SavedFrame class (or it is a - * cross-compartment or Xray wrapper around an object with the SavedFrame class) - * and the object is not the SavedFrame.prototype object. - * - * Each of these functions will find the first SavedFrame object in the chain - * whose underlying stack frame principals are subsumed by the cx's current - * compartment's principals, and operate on that SavedFrame object. This - * prevents leaking information about privileged frames to un-privileged - * callers. As a result, the SavedFrame in parameters do _NOT_ need to be in the - * same compartment as the cx, and the various out parameters are _NOT_ - * guaranteed to be in the same compartment as cx. - * - * You may consider or skip over self-hosted frames by passing - * `SavedFrameSelfHosted::Include` or `SavedFrameSelfHosted::Exclude` - * respectively. - * - * Additionally, it may be the case that there is no such SavedFrame object - * whose captured frame's principals are subsumed by the caller's compartment's - * principals! If the `HandleObject savedFrame` argument is null, or the - * caller's principals do not subsume any of the chained SavedFrame object's - * principals, `SavedFrameResult::AccessDenied` is returned and a (hopefully) - * sane default value is chosen for the out param. - * - * See also `js/src/doc/SavedFrame/SavedFrame.md`. - */ - -enum class SavedFrameResult { - Ok, - AccessDenied -}; - -enum class SavedFrameSelfHosted { - Include, - Exclude -}; - -/** - * Given a SavedFrame JSObject, get its source property. Defaults to the empty - * string. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameSource(JSContext* cx, HandleObject savedFrame, MutableHandleString sourcep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its line property. Defaults to 0. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameLine(JSContext* cx, HandleObject savedFrame, uint32_t* linep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its column property. Defaults to 0. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameColumn(JSContext* cx, HandleObject savedFrame, uint32_t* columnp, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its functionDisplayName string, or nullptr - * if SpiderMonkey was unable to infer a name for the captured frame's - * function. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameFunctionDisplayName(JSContext* cx, HandleObject savedFrame, MutableHandleString namep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its asyncCause string. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameAsyncCause(JSContext* cx, HandleObject savedFrame, MutableHandleString asyncCausep, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its asyncParent SavedFrame object or nullptr - * if there is no asyncParent. The `asyncParentp` out parameter is _NOT_ - * guaranteed to be in the cx's compartment. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameAsyncParent(JSContext* cx, HandleObject savedFrame, MutableHandleObject asyncParentp, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject, get its parent SavedFrame object or nullptr if - * it is the oldest frame in the stack. The `parentp` out parameter is _NOT_ - * guaranteed to be in the cx's compartment. Defaults to nullptr. - */ -extern JS_PUBLIC_API(SavedFrameResult) -GetSavedFrameParent(JSContext* cx, HandleObject savedFrame, MutableHandleObject parentp, - SavedFrameSelfHosted selfHosted = SavedFrameSelfHosted::Include); - -/** - * Given a SavedFrame JSObject stack, stringify it in the same format as - * Error.prototype.stack. The stringified stack out parameter is placed in the - * cx's compartment. Defaults to the empty string. - * - * The same notes above about SavedFrame accessors applies here as well: cx - * doesn't need to be in stack's compartment, and stack can be null, a - * SavedFrame object, or a wrapper (CCW or Xray) around a SavedFrame object. - * - * Optional indent parameter specifies the number of white spaces to indent - * each line. - */ -extern JS_PUBLIC_API(bool) -BuildStackString(JSContext* cx, HandleObject stack, MutableHandleString stringp, - size_t indent = 0, js::StackFormat stackFormat = js::StackFormat::Default); - -/** - * Return true iff the given object is either a SavedFrame object or wrapper - * around a SavedFrame object, and it is not the SavedFrame.prototype object. - */ -extern JS_PUBLIC_API(bool) -IsSavedFrame(JSObject* obj); - -} /* namespace JS */ - - -/* Stopwatch-based performance monitoring. */ - -namespace js { - -class AutoStopwatch; - -/** - * Abstract base class for a representation of the performance of a - * component. Embeddings interested in performance monitoring should - * provide a concrete implementation of this class, as well as the - * relevant callbacks (see below). - */ -struct PerformanceGroup { - PerformanceGroup(); - - // The current iteration of the event loop. - uint64_t iteration() const; - - // `true` if an instance of `AutoStopwatch` is already monitoring - // the performance of this performance group for this iteration - // of the event loop, `false` otherwise. - bool isAcquired(uint64_t it) const; - - // `true` if a specific instance of `AutoStopwatch` is already monitoring - // the performance of this performance group for this iteration - // of the event loop, `false` otherwise. - bool isAcquired(uint64_t it, const AutoStopwatch* owner) const; - - // Mark that an instance of `AutoStopwatch` is monitoring - // the performance of this group for a given iteration. - void acquire(uint64_t it, const AutoStopwatch* owner); - - // Mark that no `AutoStopwatch` is monitoring the - // performance of this group for the iteration. - void release(uint64_t it, const AutoStopwatch* owner); - - // The number of cycles spent in this group during this iteration - // of the event loop. Note that cycles are not a reliable measure, - // especially over short intervals. See Stopwatch.* for a more - // complete discussion on the imprecision of cycle measurement. - uint64_t recentCycles(uint64_t iteration) const; - void addRecentCycles(uint64_t iteration, uint64_t cycles); - - // The number of times this group has been activated during this - // iteration of the event loop. - uint64_t recentTicks(uint64_t iteration) const; - void addRecentTicks(uint64_t iteration, uint64_t ticks); - - // The number of microseconds spent doing CPOW during this - // iteration of the event loop. - uint64_t recentCPOW(uint64_t iteration) const; - void addRecentCPOW(uint64_t iteration, uint64_t CPOW); - - // Get rid of any data that pretends to be recent. - void resetRecentData(); - - // `true` if new measures should be added to this group, `false` - // otherwise. - bool isActive() const; - void setIsActive(bool); - - // `true` if this group has been used in the current iteration, - // `false` otherwise. - bool isUsedInThisIteration() const; - void setIsUsedInThisIteration(bool); - protected: - // An implementation of `delete` for this object. Must be provided - // by the embedding. - virtual void Delete() = 0; - - private: - // The number of cycles spent in this group during this iteration - // of the event loop. Note that cycles are not a reliable measure, - // especially over short intervals. See Runtime.cpp for a more - // complete discussion on the imprecision of cycle measurement. - uint64_t recentCycles_; - - // The number of times this group has been activated during this - // iteration of the event loop. - uint64_t recentTicks_; - - // The number of microseconds spent doing CPOW during this - // iteration of the event loop. - uint64_t recentCPOW_; - - // The current iteration of the event loop. If necessary, - // may safely overflow. - uint64_t iteration_; - - // `true` if new measures should be added to this group, `false` - // otherwise. - bool isActive_; - - // `true` if this group has been used in the current iteration, - // `false` otherwise. - bool isUsedInThisIteration_; - - // The stopwatch currently monitoring the group, - // or `nullptr` if none. Used ony for comparison. - const AutoStopwatch* owner_; - - public: - // Compatibility with RefPtr<> - void AddRef(); - void Release(); - uint64_t refCount_; -}; - -using PerformanceGroupVector = mozilla::Vector, 0, SystemAllocPolicy>; - -/** - * Commit any Performance Monitoring data. - * - * Until `FlushMonitoring` has been called, all PerformanceMonitoring data is invisible - * to the outside world and can cancelled with a call to `ResetMonitoring`. - */ -extern JS_PUBLIC_API(bool) -FlushPerformanceMonitoring(JSContext*); - -/** - * Cancel any measurement that hasn't been committed. - */ -extern JS_PUBLIC_API(void) -ResetPerformanceMonitoring(JSContext*); - -/** - * Cleanup any memory used by performance monitoring. - */ -extern JS_PUBLIC_API(void) -DisposePerformanceMonitoring(JSContext*); - -/** - * Turn on/off stopwatch-based CPU monitoring. - * - * `SetStopwatchIsMonitoringCPOW` or `SetStopwatchIsMonitoringJank` - * may return `false` if monitoring could not be activated, which may - * happen if we are out of memory. - */ -extern JS_PUBLIC_API(bool) -SetStopwatchIsMonitoringCPOW(JSContext*, bool); -extern JS_PUBLIC_API(bool) -GetStopwatchIsMonitoringCPOW(JSContext*); -extern JS_PUBLIC_API(bool) -SetStopwatchIsMonitoringJank(JSContext*, bool); -extern JS_PUBLIC_API(bool) -GetStopwatchIsMonitoringJank(JSContext*); - -// Extract the CPU rescheduling data. -extern JS_PUBLIC_API(void) -GetPerfMonitoringTestCpuRescheduling(JSContext*, uint64_t* stayed, uint64_t* moved); - - -/** - * Add a number of microseconds to the time spent waiting on CPOWs - * since process start. - */ -extern JS_PUBLIC_API(void) -AddCPOWPerformanceDelta(JSContext*, uint64_t delta); - -typedef bool -(*StopwatchStartCallback)(uint64_t, void*); -extern JS_PUBLIC_API(bool) -SetStopwatchStartCallback(JSContext*, StopwatchStartCallback, void*); - -typedef bool -(*StopwatchCommitCallback)(uint64_t, PerformanceGroupVector&, void*); -extern JS_PUBLIC_API(bool) -SetStopwatchCommitCallback(JSContext*, StopwatchCommitCallback, void*); - -typedef bool -(*GetGroupsCallback)(JSContext*, PerformanceGroupVector&, void*); -extern JS_PUBLIC_API(bool) -SetGetPerformanceGroupsCallback(JSContext*, GetGroupsCallback, void*); - -} /* namespace js */ - - -#endif /* jsapi_h */ diff --git a/win32/include/spidermonkey/jsbytecode.h b/win32/include/spidermonkey/jsbytecode.h deleted file mode 100755 index 8e4f4cf9..00000000 --- a/win32/include/spidermonkey/jsbytecode.h +++ /dev/null @@ -1,14 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsbytecode_h -#define jsbytecode_h - -#include - -typedef uint8_t jsbytecode; - -#endif /* jsbytecode_h */ diff --git a/win32/include/spidermonkey/jsclist.h b/win32/include/spidermonkey/jsclist.h deleted file mode 100755 index b8455152..00000000 --- a/win32/include/spidermonkey/jsclist.h +++ /dev/null @@ -1,107 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsclist_h -#define jsclist_h - -#include "jstypes.h" - -/* -** Circular linked list -*/ -typedef struct JSCListStr { - struct JSCListStr* next; - struct JSCListStr* prev; -} JSCList; - -/* -** Insert element "_e" into the list, before "_l". -*/ -#define JS_INSERT_BEFORE(_e,_l) \ - JS_BEGIN_MACRO \ - (_e)->next = (_l); \ - (_e)->prev = (_l)->prev; \ - (_l)->prev->next = (_e); \ - (_l)->prev = (_e); \ - JS_END_MACRO - -/* -** Insert element "_e" into the list, after "_l". -*/ -#define JS_INSERT_AFTER(_e,_l) \ - JS_BEGIN_MACRO \ - (_e)->next = (_l)->next; \ - (_e)->prev = (_l); \ - (_l)->next->prev = (_e); \ - (_l)->next = (_e); \ - JS_END_MACRO - -/* -** Return the element following element "_e" -*/ -#define JS_NEXT_LINK(_e) \ - ((_e)->next) -/* -** Return the element preceding element "_e" -*/ -#define JS_PREV_LINK(_e) \ - ((_e)->prev) - -/* -** Append an element "_e" to the end of the list "_l" -*/ -#define JS_APPEND_LINK(_e,_l) JS_INSERT_BEFORE(_e,_l) - -/* -** Insert an element "_e" at the head of the list "_l" -*/ -#define JS_INSERT_LINK(_e,_l) JS_INSERT_AFTER(_e,_l) - -/* Return the head/tail of the list */ -#define JS_LIST_HEAD(_l) (_l)->next -#define JS_LIST_TAIL(_l) (_l)->prev - -/* -** Remove the element "_e" from it's circular list. -*/ -#define JS_REMOVE_LINK(_e) \ - JS_BEGIN_MACRO \ - (_e)->prev->next = (_e)->next; \ - (_e)->next->prev = (_e)->prev; \ - JS_END_MACRO - -/* -** Remove the element "_e" from it's circular list. Also initializes the -** linkage. -*/ -#define JS_REMOVE_AND_INIT_LINK(_e) \ - JS_BEGIN_MACRO \ - (_e)->prev->next = (_e)->next; \ - (_e)->next->prev = (_e)->prev; \ - (_e)->next = (_e); \ - (_e)->prev = (_e); \ - JS_END_MACRO - -/* -** Return non-zero if the given circular list "_l" is empty, zero if the -** circular list is not empty -*/ -#define JS_CLIST_IS_EMPTY(_l) \ - bool((_l)->next == (_l)) - -/* -** Initialize a circular list -*/ -#define JS_INIT_CLIST(_l) \ - JS_BEGIN_MACRO \ - (_l)->next = (_l); \ - (_l)->prev = (_l); \ - JS_END_MACRO - -#define JS_INIT_STATIC_CLIST(_l) \ - {(_l), (_l)} - -#endif /* jsclist_h */ diff --git a/win32/include/spidermonkey/jscpucfg.h b/win32/include/spidermonkey/jscpucfg.h deleted file mode 100755 index 80fdf6bb..00000000 --- a/win32/include/spidermonkey/jscpucfg.h +++ /dev/null @@ -1,20 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jscpucfg_h -#define jscpucfg_h - -#include "mozilla/EndianUtils.h" - -#ifndef JS_STACK_GROWTH_DIRECTION -# ifdef __hppa -# define JS_STACK_GROWTH_DIRECTION (1) -# else -# define JS_STACK_GROWTH_DIRECTION (-1) -# endif -#endif - -#endif /* jscpucfg_h */ diff --git a/win32/include/spidermonkey/jsfriendapi.h b/win32/include/spidermonkey/jsfriendapi.h deleted file mode 100755 index d6463d3d..00000000 --- a/win32/include/spidermonkey/jsfriendapi.h +++ /dev/null @@ -1,3067 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsfriendapi_h -#define jsfriendapi_h - -#include "mozilla/Atomics.h" -#include "mozilla/Casting.h" -#include "mozilla/Maybe.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/UniquePtr.h" - -#include "jsapi.h" // For JSAutoByteString. See bug 1033916. -#include "jsbytecode.h" -#include "jspubtd.h" - -#include "js/CallArgs.h" -#include "js/CallNonGenericMethod.h" -#include "js/Class.h" -#include "js/Utility.h" - -#if JS_STACK_GROWTH_DIRECTION > 0 -# define JS_CHECK_STACK_SIZE(limit, sp) (MOZ_LIKELY((uintptr_t)(sp) < (limit))) -#else -# define JS_CHECK_STACK_SIZE(limit, sp) (MOZ_LIKELY((uintptr_t)(sp) > (limit))) -#endif - -class JSAtom; -struct JSErrorFormatString; -class JSLinearString; -struct JSJitInfo; -class JSErrorReport; - -namespace JS { -template -class Heap; -} /* namespace JS */ - -namespace js { -class JS_FRIEND_API(BaseProxyHandler); -class InterpreterFrame; -} /* namespace js */ - -extern JS_FRIEND_API(void) -JS_SetGrayGCRootsTracer(JSContext* cx, JSTraceDataOp traceOp, void* data); - -extern JS_FRIEND_API(JSObject*) -JS_FindCompilationScope(JSContext* cx, JS::HandleObject obj); - -extern JS_FRIEND_API(JSFunction*) -JS_GetObjectFunction(JSObject* obj); - -extern JS_FRIEND_API(bool) -JS_SplicePrototype(JSContext* cx, JS::HandleObject obj, JS::HandleObject proto); - -extern JS_FRIEND_API(JSObject*) -JS_NewObjectWithUniqueType(JSContext* cx, const JSClass* clasp, JS::HandleObject proto); - -/** - * Allocate an object in exactly the same way as JS_NewObjectWithGivenProto, but - * without invoking the metadata callback on it. This allows creation of - * internal bookkeeping objects that are guaranteed to not have metadata - * attached to them. - */ -extern JS_FRIEND_API(JSObject*) -JS_NewObjectWithoutMetadata(JSContext* cx, const JSClass* clasp, JS::Handle proto); - -extern JS_FRIEND_API(uint32_t) -JS_ObjectCountDynamicSlots(JS::HandleObject obj); - -extern JS_FRIEND_API(size_t) -JS_SetProtoCalled(JSContext* cx); - -extern JS_FRIEND_API(size_t) -JS_GetCustomIteratorCount(JSContext* cx); - -extern JS_FRIEND_API(bool) -JS_NondeterministicGetWeakMapKeys(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject ret); - -extern JS_FRIEND_API(bool) -JS_NondeterministicGetWeakSetKeys(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject ret); - -// Raw JSScript* because this needs to be callable from a signal handler. -extern JS_FRIEND_API(unsigned) -JS_PCToLineNumber(JSScript* script, jsbytecode* pc, unsigned* columnp = nullptr); - -/** - * Determine whether the given object is backed by a DeadObjectProxy. - * - * Such objects hold no other objects (they have no outgoing reference edges) - * and will throw if you touch them (e.g. by reading/writing a property). - */ -extern JS_FRIEND_API(bool) -JS_IsDeadWrapper(JSObject* obj); - -/* - * Used by the cycle collector to trace through a shape or object group and - * all cycle-participating data it reaches, using bounded stack space. - */ -extern JS_FRIEND_API(void) -JS_TraceShapeCycleCollectorChildren(JS::CallbackTracer* trc, JS::GCCellPtr shape); -extern JS_FRIEND_API(void) -JS_TraceObjectGroupCycleCollectorChildren(JS::CallbackTracer* trc, JS::GCCellPtr group); - -enum { - JS_TELEMETRY_GC_REASON, - JS_TELEMETRY_GC_IS_ZONE_GC, - JS_TELEMETRY_GC_MS, - JS_TELEMETRY_GC_BUDGET_MS, - JS_TELEMETRY_GC_ANIMATION_MS, - JS_TELEMETRY_GC_MAX_PAUSE_MS, - JS_TELEMETRY_GC_MARK_MS, - JS_TELEMETRY_GC_SWEEP_MS, - JS_TELEMETRY_GC_COMPACT_MS, - JS_TELEMETRY_GC_MARK_ROOTS_MS, - JS_TELEMETRY_GC_MARK_GRAY_MS, - JS_TELEMETRY_GC_SLICE_MS, - JS_TELEMETRY_GC_SLOW_PHASE, - JS_TELEMETRY_GC_MMU_50, - JS_TELEMETRY_GC_RESET, - JS_TELEMETRY_GC_RESET_REASON, - JS_TELEMETRY_GC_INCREMENTAL_DISABLED, - JS_TELEMETRY_GC_NON_INCREMENTAL, - JS_TELEMETRY_GC_NON_INCREMENTAL_REASON, - JS_TELEMETRY_GC_SCC_SWEEP_TOTAL_MS, - JS_TELEMETRY_GC_SCC_SWEEP_MAX_PAUSE_MS, - JS_TELEMETRY_GC_MINOR_REASON, - JS_TELEMETRY_GC_MINOR_REASON_LONG, - JS_TELEMETRY_GC_MINOR_US, - JS_TELEMETRY_GC_NURSERY_BYTES, - JS_TELEMETRY_GC_PRETENURE_COUNT, - JS_TELEMETRY_DEPRECATED_LANGUAGE_EXTENSIONS_IN_CONTENT, - JS_TELEMETRY_DEPRECATED_LANGUAGE_EXTENSIONS_IN_ADDONS, - JS_TELEMETRY_ADDON_EXCEPTIONS, - JS_TELEMETRY_AOT_USAGE, - JS_TELEMETRY_END -}; - -typedef void -(*JSAccumulateTelemetryDataCallback)(int id, uint32_t sample, const char* key); - -extern JS_FRIEND_API(void) -JS_SetAccumulateTelemetryCallback(JSContext* cx, JSAccumulateTelemetryDataCallback callback); - -extern JS_FRIEND_API(bool) -JS_GetIsSecureContext(JSCompartment* compartment); - -extern JS_FRIEND_API(JSPrincipals*) -JS_GetCompartmentPrincipals(JSCompartment* compartment); - -extern JS_FRIEND_API(void) -JS_SetCompartmentPrincipals(JSCompartment* compartment, JSPrincipals* principals); - -extern JS_FRIEND_API(JSPrincipals*) -JS_GetScriptPrincipals(JSScript* script); - -extern JS_FRIEND_API(bool) -JS_ScriptHasMutedErrors(JSScript* script); - -extern JS_FRIEND_API(JSObject*) -JS_CloneObject(JSContext* cx, JS::HandleObject obj, JS::HandleObject proto); - -/** - * Copy the own properties of src to dst in a fast way. src and dst must both - * be native and must be in the compartment of cx. They must have the same - * class, the same parent, and the same prototype. Class reserved slots will - * NOT be copied. - * - * dst must not have any properties on it before this function is called. - * - * src must have been allocated via JS_NewObjectWithoutMetadata so that we can - * be sure it has no metadata that needs copying to dst. This also means that - * dst needs to have the compartment global as its parent. This function will - * preserve the existing metadata on dst, if any. - */ -extern JS_FRIEND_API(bool) -JS_InitializePropertiesFromCompatibleNativeObject(JSContext* cx, - JS::HandleObject dst, - JS::HandleObject src); - -extern JS_FRIEND_API(JSString*) -JS_BasicObjectToString(JSContext* cx, JS::HandleObject obj); - -namespace js { - -JS_FRIEND_API(bool) -GetBuiltinClass(JSContext* cx, JS::HandleObject obj, ESClass* cls); - -JS_FRIEND_API(const char*) -ObjectClassName(JSContext* cx, JS::HandleObject obj); - -JS_FRIEND_API(void) -ReportOverRecursed(JSContext* maybecx); - -JS_FRIEND_API(bool) -AddRawValueRoot(JSContext* cx, JS::Value* vp, const char* name); - -JS_FRIEND_API(void) -RemoveRawValueRoot(JSContext* cx, JS::Value* vp); - -JS_FRIEND_API(JSAtom*) -GetPropertyNameFromPC(JSScript* script, jsbytecode* pc); - -#ifdef JS_DEBUG - -/* - * Routines to print out values during debugging. These are FRIEND_API to help - * the debugger find them and to support temporarily hacking js::Dump* calls - * into other code. Note that there are overloads that do not require the FILE* - * parameter, which will default to stderr. - */ - -extern JS_FRIEND_API(void) -DumpString(JSString* str, FILE* fp); - -extern JS_FRIEND_API(void) -DumpAtom(JSAtom* atom, FILE* fp); - -extern JS_FRIEND_API(void) -DumpObject(JSObject* obj, FILE* fp); - -extern JS_FRIEND_API(void) -DumpChars(const char16_t* s, size_t n, FILE* fp); - -extern JS_FRIEND_API(void) -DumpValue(const JS::Value& val, FILE* fp); - -extern JS_FRIEND_API(void) -DumpId(jsid id, FILE* fp); - -extern JS_FRIEND_API(void) -DumpInterpreterFrame(JSContext* cx, FILE* fp, InterpreterFrame* start = nullptr); - -extern JS_FRIEND_API(bool) -DumpPC(JSContext* cx, FILE* fp); - -extern JS_FRIEND_API(bool) -DumpScript(JSContext* cx, JSScript* scriptArg, FILE* fp); - -// Versions for use directly in a debugger (default parameters are not handled -// well in gdb; built-in handles like stderr are not handled well in lldb.) -extern JS_FRIEND_API(void) DumpString(JSString* str); -extern JS_FRIEND_API(void) DumpAtom(JSAtom* atom); -extern JS_FRIEND_API(void) DumpObject(JSObject* obj); -extern JS_FRIEND_API(void) DumpChars(const char16_t* s, size_t n); -extern JS_FRIEND_API(void) DumpValue(const JS::Value& val); -extern JS_FRIEND_API(void) DumpId(jsid id); -extern JS_FRIEND_API(void) DumpInterpreterFrame(JSContext* cx, InterpreterFrame* start = nullptr); -extern JS_FRIEND_API(bool) DumpPC(JSContext* cx); -extern JS_FRIEND_API(bool) DumpScript(JSContext* cx, JSScript* scriptArg); - -#endif - -extern JS_FRIEND_API(void) -DumpBacktrace(JSContext* cx, FILE* fp); - -extern JS_FRIEND_API(void) -DumpBacktrace(JSContext* cx); - -} // namespace js - -namespace JS { - -/** Exposed for DumpJSStack */ -extern JS_FRIEND_API(char*) -FormatStackDump(JSContext* cx, char* buf, bool showArgs, bool showLocals, bool showThisProps); - -/** - * Set all of the uninitialized lexicals on an object to undefined. Return - * true if any lexicals were initialized and false otherwise. - * */ -extern JS_FRIEND_API(bool) -ForceLexicalInitialization(JSContext *cx, HandleObject obj); - -} // namespace JS - -/** - * Copies all own properties from |obj| to |target|. |obj| must be a "native" - * object (that is to say, normal-ish - not an Array or a Proxy). - * - * This function immediately enters a compartment, and does not impose any - * restrictions on the compartment of |cx|. - */ -extern JS_FRIEND_API(bool) -JS_CopyPropertiesFrom(JSContext* cx, JS::HandleObject target, JS::HandleObject obj); - -/* - * Single-property version of the above. This function asserts that an |own| - * property of the given name exists on |obj|. - * - * On entry, |cx| must be same-compartment with |obj|. - * - * The copyBehavior argument controls what happens with - * non-configurable properties. - */ -typedef enum { - MakeNonConfigurableIntoConfigurable, - CopyNonConfigurableAsIs -} PropertyCopyBehavior; - -extern JS_FRIEND_API(bool) -JS_CopyPropertyFrom(JSContext* cx, JS::HandleId id, JS::HandleObject target, - JS::HandleObject obj, - PropertyCopyBehavior copyBehavior = CopyNonConfigurableAsIs); - -extern JS_FRIEND_API(bool) -JS_WrapPropertyDescriptor(JSContext* cx, JS::MutableHandle desc); - -struct JSFunctionSpecWithHelp { - const char* name; - JSNative call; - uint16_t nargs; - uint16_t flags; - const JSJitInfo* jitInfo; - const char* usage; - const char* help; -}; - -#define JS_FN_HELP(name,call,nargs,flags,usage,help) \ - {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, nullptr, usage, help} -#define JS_INLINABLE_FN_HELP(name,call,nargs,flags,native,usage,help) \ - {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, &js::jit::JitInfo_##native,\ - usage, help} -#define JS_FS_HELP_END \ - {nullptr, nullptr, 0, 0, nullptr, nullptr} - -extern JS_FRIEND_API(bool) -JS_DefineFunctionsWithHelp(JSContext* cx, JS::HandleObject obj, const JSFunctionSpecWithHelp* fs); - -namespace js { - -extern JS_FRIEND_DATA(const js::ClassOps) ProxyClassOps; -extern JS_FRIEND_DATA(const js::ClassExtension) ProxyClassExtension; -extern JS_FRIEND_DATA(const js::ObjectOps) ProxyObjectOps; - -/* - * Helper Macros for creating JSClasses that function as proxies. - * - * NB: The macro invocation must be surrounded by braces, so as to - * allow for potential JSClass extensions. - */ -#define PROXY_MAKE_EXT(objectMoved) \ - { \ - js::proxy_WeakmapKeyDelegate, \ - objectMoved \ - } - -#define PROXY_CLASS_WITH_EXT(name, flags, extPtr) \ - { \ - name, \ - js::Class::NON_NATIVE | \ - JSCLASS_IS_PROXY | \ - JSCLASS_DELAY_METADATA_BUILDER | \ - flags, \ - &js::ProxyClassOps, \ - JS_NULL_CLASS_SPEC, \ - extPtr, \ - &js::ProxyObjectOps \ - } - -#define PROXY_CLASS_DEF(name, flags) \ - PROXY_CLASS_WITH_EXT(name, flags, &js::ProxyClassExtension) - -/* - * Proxy stubs, similar to JS_*Stub, for embedder proxy class definitions. - * - * NB: Should not be called directly. - */ - -extern JS_FRIEND_API(bool) -proxy_LookupProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleObject objp, - JS::MutableHandle propp); -extern JS_FRIEND_API(bool) -proxy_DefineProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::Handle desc, - JS::ObjectOpResult& result); -extern JS_FRIEND_API(bool) -proxy_HasProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* foundp); -extern JS_FRIEND_API(bool) -proxy_GetProperty(JSContext* cx, JS::HandleObject obj, JS::HandleValue receiver, JS::HandleId id, - JS::MutableHandleValue vp); -extern JS_FRIEND_API(bool) -proxy_SetProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue bp, - JS::HandleValue receiver, JS::ObjectOpResult& result); -extern JS_FRIEND_API(bool) -proxy_GetOwnPropertyDescriptor(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::MutableHandle desc); -extern JS_FRIEND_API(bool) -proxy_DeleteProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::ObjectOpResult& result); - -extern JS_FRIEND_API(void) -proxy_Trace(JSTracer* trc, JSObject* obj); -extern JS_FRIEND_API(JSObject*) -proxy_WeakmapKeyDelegate(JSObject* obj); -extern JS_FRIEND_API(bool) -proxy_Convert(JSContext* cx, JS::HandleObject proxy, JSType hint, JS::MutableHandleValue vp); -extern JS_FRIEND_API(void) -proxy_Finalize(FreeOp* fop, JSObject* obj); -extern JS_FRIEND_API(void) -proxy_ObjectMoved(JSObject* obj, const JSObject* old); -extern JS_FRIEND_API(bool) -proxy_HasInstance(JSContext* cx, JS::HandleObject proxy, JS::MutableHandleValue v, bool* bp); -extern JS_FRIEND_API(bool) -proxy_Call(JSContext* cx, unsigned argc, JS::Value* vp); -extern JS_FRIEND_API(bool) -proxy_Construct(JSContext* cx, unsigned argc, JS::Value* vp); -extern JS_FRIEND_API(JSObject*) -proxy_innerObject(JSObject* obj); -extern JS_FRIEND_API(bool) -proxy_Watch(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); -extern JS_FRIEND_API(bool) -proxy_Unwatch(JSContext* cx, JS::HandleObject obj, JS::HandleId id); -extern JS_FRIEND_API(bool) -proxy_GetElements(JSContext* cx, JS::HandleObject proxy, uint32_t begin, uint32_t end, - ElementAdder* adder); -extern JS_FRIEND_API(JSString*) -proxy_FunToString(JSContext* cx, JS::HandleObject proxy, unsigned indent); - -/** - * A class of objects that return source code on demand. - * - * When code is compiled with setSourceIsLazy(true), SpiderMonkey doesn't - * retain the source code (and doesn't do lazy bytecode generation). If we ever - * need the source code, say, in response to a call to Function.prototype. - * toSource or Debugger.Source.prototype.text, then we call the 'load' member - * function of the instance of this class that has hopefully been registered - * with the runtime, passing the code's URL, and hope that it will be able to - * find the source. - */ -class SourceHook { - public: - virtual ~SourceHook() { } - - /** - * Set |*src| and |*length| to refer to the source code for |filename|. - * On success, the caller owns the buffer to which |*src| points, and - * should use JS_free to free it. - */ - virtual bool load(JSContext* cx, const char* filename, char16_t** src, size_t* length) = 0; -}; - -/** - * Have |cx| use |hook| to retrieve lazily-retrieved source code. See the - * comments for SourceHook. The context takes ownership of the hook, and - * will delete it when the context itself is deleted, or when a new hook is - * set. - */ -extern JS_FRIEND_API(void) -SetSourceHook(JSContext* cx, mozilla::UniquePtr hook); - -/** Remove |cx|'s source hook, and return it. The caller now owns the hook. */ -extern JS_FRIEND_API(mozilla::UniquePtr) -ForgetSourceHook(JSContext* cx); - -extern JS_FRIEND_API(JS::Zone*) -GetCompartmentZone(JSCompartment* comp); - -typedef bool -(* PreserveWrapperCallback)(JSContext* cx, JSObject* obj); - -typedef enum { - CollectNurseryBeforeDump, - IgnoreNurseryObjects -} DumpHeapNurseryBehaviour; - - /** - * Dump the complete object graph of heap-allocated things. - * fp is the file for the dump output. - */ -extern JS_FRIEND_API(void) -DumpHeap(JSContext* cx, FILE* fp, DumpHeapNurseryBehaviour nurseryBehaviour); - -#ifdef JS_OLD_GETTER_SETTER_METHODS -JS_FRIEND_API(bool) obj_defineGetter(JSContext* cx, unsigned argc, JS::Value* vp); -JS_FRIEND_API(bool) obj_defineSetter(JSContext* cx, unsigned argc, JS::Value* vp); -#endif - -extern JS_FRIEND_API(bool) -IsSystemCompartment(JSCompartment* comp); - -extern JS_FRIEND_API(bool) -IsSystemZone(JS::Zone* zone); - -extern JS_FRIEND_API(bool) -IsAtomsCompartment(JSCompartment* comp); - -extern JS_FRIEND_API(bool) -IsAtomsZone(JS::Zone* zone); - -struct WeakMapTracer -{ - JSContext* context; - - explicit WeakMapTracer(JSContext* cx) : context(cx) {} - - // Weak map tracer callback, called once for every binding of every - // weak map that was live at the time of the last garbage collection. - // - // m will be nullptr if the weak map is not contained in a JS Object. - // - // The callback should not GC (and will assert in a debug build if it does so.) - virtual void trace(JSObject* m, JS::GCCellPtr key, JS::GCCellPtr value) = 0; -}; - -extern JS_FRIEND_API(void) -TraceWeakMaps(WeakMapTracer* trc); - -extern JS_FRIEND_API(bool) -AreGCGrayBitsValid(JSContext* cx); - -extern JS_FRIEND_API(bool) -ZoneGlobalsAreAllGray(JS::Zone* zone); - -typedef void -(*GCThingCallback)(void* closure, JS::GCCellPtr thing); - -extern JS_FRIEND_API(void) -VisitGrayWrapperTargets(JS::Zone* zone, GCThingCallback callback, void* closure); - -extern JS_FRIEND_API(JSObject*) -GetWeakmapKeyDelegate(JSObject* key); - -/** - * Invoke cellCallback on every gray JSObject in the given zone. - */ -extern JS_FRIEND_API(void) -IterateGrayObjects(JS::Zone* zone, GCThingCallback cellCallback, void* data); - -/** - * Invoke cellCallback on every gray JSObject in the given zone while cycle - * collection is in progress. - */ -extern JS_FRIEND_API(void) -IterateGrayObjectsUnderCC(JS::Zone* zone, GCThingCallback cellCallback, void* data); - -#ifdef JS_HAS_CTYPES -extern JS_FRIEND_API(size_t) -SizeOfDataIfCDataObject(mozilla::MallocSizeOf mallocSizeOf, JSObject* obj); -#endif - -extern JS_FRIEND_API(JSCompartment*) -GetAnyCompartmentInZone(JS::Zone* zone); - -/* - * Shadow declarations of JS internal structures, for access by inline access - * functions below. Do not use these structures in any other way. When adding - * new fields for access by inline methods, make sure to add static asserts to - * the original header file to ensure that offsets are consistent. - */ -namespace shadow { - -struct ObjectGroup { - const Class* clasp; - JSObject* proto; - JSCompartment* compartment; -}; - -struct BaseShape { - const js::Class* clasp_; - JSObject* parent; -}; - -class Shape { -public: - shadow::BaseShape* base; - jsid _1; - uint32_t slotInfo; - - static const uint32_t FIXED_SLOTS_SHIFT = 27; -}; - -/** - * This layout is shared by all native objects. For non-native objects, the - * group may always be accessed safely, and other members may be as well, - * depending on the object's specific layout. - */ -struct Object { - shadow::ObjectGroup* group; - shadow::Shape* shape; - JS::Value* slots; - void* _1; - - size_t numFixedSlots() const { return shape->slotInfo >> Shape::FIXED_SLOTS_SHIFT; } - JS::Value* fixedSlots() const { - return (JS::Value*)(uintptr_t(this) + sizeof(shadow::Object)); - } - - JS::Value& slotRef(size_t slot) const { - size_t nfixed = numFixedSlots(); - if (slot < nfixed) - return fixedSlots()[slot]; - return slots[slot - nfixed]; - } -}; - -struct Function { - Object base; - uint16_t nargs; - uint16_t flags; - /* Used only for natives */ - JSNative native; - const JSJitInfo* jitinfo; - void* _1; -}; - -struct String -{ - static const uint32_t INLINE_CHARS_BIT = JS_BIT(2); - static const uint32_t LATIN1_CHARS_BIT = JS_BIT(6); - static const uint32_t ROPE_FLAGS = 0; - static const uint32_t TYPE_FLAGS_MASK = JS_BIT(6) - 1; - uint32_t flags; - uint32_t length; - union { - const JS::Latin1Char* nonInlineCharsLatin1; - const char16_t* nonInlineCharsTwoByte; - JS::Latin1Char inlineStorageLatin1[1]; - char16_t inlineStorageTwoByte[1]; - }; -}; - -} /* namespace shadow */ - -// This is equal to |&JSObject::class_|. Use it in places where you don't want -// to #include jsobj.h. -extern JS_FRIEND_DATA(const js::Class* const) ObjectClassPtr; - -inline const js::Class* -GetObjectClass(const JSObject* obj) -{ - return reinterpret_cast(obj)->group->clasp; -} - -inline const JSClass* -GetObjectJSClass(JSObject* obj) -{ - return js::Jsvalify(GetObjectClass(obj)); -} - -JS_FRIEND_API(const Class*) -ProtoKeyToClass(JSProtoKey key); - -// Returns the key for the class inherited by a given standard class (that -// is to say, the prototype of this standard class's prototype). -// -// You must be sure that this corresponds to a standard class with a cached -// JSProtoKey before calling this function. In general |key| will match the -// cached proto key, except in cases where multiple JSProtoKeys share a -// JSClass. -inline JSProtoKey -InheritanceProtoKeyForStandardClass(JSProtoKey key) -{ - // [Object] has nothing to inherit from. - if (key == JSProto_Object) - return JSProto_Null; - - // If we're ClassSpec defined return the proto key from that - if (ProtoKeyToClass(key)->specDefined()) - return ProtoKeyToClass(key)->specInheritanceProtoKey(); - - // Otherwise, we inherit [Object]. - return JSProto_Object; -} - -JS_FRIEND_API(bool) -IsFunctionObject(JSObject* obj); - -static MOZ_ALWAYS_INLINE JSCompartment* -GetObjectCompartment(JSObject* obj) -{ - return reinterpret_cast(obj)->group->compartment; -} - -JS_FRIEND_API(JSObject*) -GetGlobalForObjectCrossCompartment(JSObject* obj); - -JS_FRIEND_API(JSObject*) -GetPrototypeNoProxy(JSObject* obj); - -JS_FRIEND_API(void) -AssertSameCompartment(JSContext* cx, JSObject* obj); - -#ifdef JS_DEBUG -JS_FRIEND_API(void) -AssertSameCompartment(JSObject* objA, JSObject* objB); -#else -inline void AssertSameCompartment(JSObject* objA, JSObject* objB) {} -#endif - -JS_FRIEND_API(void) -NotifyAnimationActivity(JSObject* obj); - -/** - * Return the outermost enclosing function (script) of the scripted caller. - * This function returns nullptr in several cases: - * - no script is running on the context - * - the caller is in global or eval code - * In particular, this function will "stop" its outermost search at eval() and - * thus it will really return the outermost enclosing function *since the - * innermost eval*. - */ -JS_FRIEND_API(JSFunction*) -GetOutermostEnclosingFunctionOfScriptedCaller(JSContext* cx); - -JS_FRIEND_API(JSFunction*) -DefineFunctionWithReserved(JSContext* cx, JSObject* obj, const char* name, JSNative call, - unsigned nargs, unsigned attrs); - -JS_FRIEND_API(JSFunction*) -NewFunctionWithReserved(JSContext* cx, JSNative call, unsigned nargs, unsigned flags, - const char* name); - -JS_FRIEND_API(JSFunction*) -NewFunctionByIdWithReserved(JSContext* cx, JSNative native, unsigned nargs, unsigned flags, - jsid id); - -JS_FRIEND_API(const JS::Value&) -GetFunctionNativeReserved(JSObject* fun, size_t which); - -JS_FRIEND_API(void) -SetFunctionNativeReserved(JSObject* fun, size_t which, const JS::Value& val); - -JS_FRIEND_API(bool) -FunctionHasNativeReserved(JSObject* fun); - -JS_FRIEND_API(bool) -GetObjectProto(JSContext* cx, JS::HandleObject obj, JS::MutableHandleObject proto); - -extern JS_FRIEND_API(JSObject*) -GetStaticPrototype(JSObject* obj); - -JS_FRIEND_API(bool) -GetOriginalEval(JSContext* cx, JS::HandleObject scope, - JS::MutableHandleObject eval); - -inline void* -GetObjectPrivate(JSObject* obj) -{ - MOZ_ASSERT(GetObjectClass(obj)->flags & JSCLASS_HAS_PRIVATE); - const shadow::Object* nobj = reinterpret_cast(obj); - void** addr = reinterpret_cast(&nobj->fixedSlots()[nobj->numFixedSlots()]); - return *addr; -} - -inline const JS::Value& -GetReservedSlot(JSObject* obj, size_t slot) -{ - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); - return reinterpret_cast(obj)->slotRef(slot); -} - -JS_FRIEND_API(void) -SetReservedOrProxyPrivateSlotWithBarrier(JSObject* obj, size_t slot, const JS::Value& value); - -inline void -SetReservedSlot(JSObject* obj, size_t slot, const JS::Value& value) -{ - MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); - shadow::Object* sobj = reinterpret_cast(obj); - if (sobj->slotRef(slot).isMarkable() || value.isMarkable()) - SetReservedOrProxyPrivateSlotWithBarrier(obj, slot, value); - else - sobj->slotRef(slot) = value; -} - -JS_FRIEND_API(uint32_t) -GetObjectSlotSpan(JSObject* obj); - -inline const JS::Value& -GetObjectSlot(JSObject* obj, size_t slot) -{ - MOZ_ASSERT(slot < GetObjectSlotSpan(obj)); - return reinterpret_cast(obj)->slotRef(slot); -} - -MOZ_ALWAYS_INLINE size_t -GetAtomLength(JSAtom* atom) -{ - return reinterpret_cast(atom)->length; -} - -static const uint32_t MaxStringLength = (1 << 28) - 1; - -MOZ_ALWAYS_INLINE size_t -GetStringLength(JSString* s) -{ - return reinterpret_cast(s)->length; -} - -MOZ_ALWAYS_INLINE size_t -GetFlatStringLength(JSFlatString* s) -{ - return reinterpret_cast(s)->length; -} - -MOZ_ALWAYS_INLINE size_t -GetLinearStringLength(JSLinearString* s) -{ - return reinterpret_cast(s)->length; -} - -MOZ_ALWAYS_INLINE bool -LinearStringHasLatin1Chars(JSLinearString* s) -{ - return reinterpret_cast(s)->flags & shadow::String::LATIN1_CHARS_BIT; -} - -MOZ_ALWAYS_INLINE bool -AtomHasLatin1Chars(JSAtom* atom) -{ - return reinterpret_cast(atom)->flags & shadow::String::LATIN1_CHARS_BIT; -} - -MOZ_ALWAYS_INLINE bool -StringHasLatin1Chars(JSString* s) -{ - return reinterpret_cast(s)->flags & shadow::String::LATIN1_CHARS_BIT; -} - -MOZ_ALWAYS_INLINE const JS::Latin1Char* -GetLatin1LinearStringChars(const JS::AutoCheckCannotGC& nogc, JSLinearString* linear) -{ - MOZ_ASSERT(LinearStringHasLatin1Chars(linear)); - - using shadow::String; - String* s = reinterpret_cast(linear); - if (s->flags & String::INLINE_CHARS_BIT) - return s->inlineStorageLatin1; - return s->nonInlineCharsLatin1; -} - -MOZ_ALWAYS_INLINE const char16_t* -GetTwoByteLinearStringChars(const JS::AutoCheckCannotGC& nogc, JSLinearString* linear) -{ - MOZ_ASSERT(!LinearStringHasLatin1Chars(linear)); - - using shadow::String; - String* s = reinterpret_cast(linear); - if (s->flags & String::INLINE_CHARS_BIT) - return s->inlineStorageTwoByte; - return s->nonInlineCharsTwoByte; -} - -MOZ_ALWAYS_INLINE JSLinearString* -AtomToLinearString(JSAtom* atom) -{ - return reinterpret_cast(atom); -} - -MOZ_ALWAYS_INLINE JSFlatString* -AtomToFlatString(JSAtom* atom) -{ - return reinterpret_cast(atom); -} - -MOZ_ALWAYS_INLINE JSLinearString* -FlatStringToLinearString(JSFlatString* s) -{ - return reinterpret_cast(s); -} - -MOZ_ALWAYS_INLINE const JS::Latin1Char* -GetLatin1AtomChars(const JS::AutoCheckCannotGC& nogc, JSAtom* atom) -{ - return GetLatin1LinearStringChars(nogc, AtomToLinearString(atom)); -} - -MOZ_ALWAYS_INLINE const char16_t* -GetTwoByteAtomChars(const JS::AutoCheckCannotGC& nogc, JSAtom* atom) -{ - return GetTwoByteLinearStringChars(nogc, AtomToLinearString(atom)); -} - -JS_FRIEND_API(JSLinearString*) -StringToLinearStringSlow(JSContext* cx, JSString* str); - -MOZ_ALWAYS_INLINE JSLinearString* -StringToLinearString(JSContext* cx, JSString* str) -{ - using shadow::String; - String* s = reinterpret_cast(str); - if (MOZ_UNLIKELY((s->flags & String::TYPE_FLAGS_MASK) == String::ROPE_FLAGS)) - return StringToLinearStringSlow(cx, str); - return reinterpret_cast(str); -} - -template -MOZ_ALWAYS_INLINE void -CopyLinearStringChars(CharType* dest, JSLinearString* s, size_t len, size_t start = 0); - -MOZ_ALWAYS_INLINE void -CopyLinearStringChars(char16_t* dest, JSLinearString* s, size_t len, size_t start = 0) -{ - MOZ_ASSERT(start + len <= GetLinearStringLength(s)); - JS::AutoCheckCannotGC nogc; - if (LinearStringHasLatin1Chars(s)) { - const JS::Latin1Char* src = GetLatin1LinearStringChars(nogc, s); - for (size_t i = 0; i < len; i++) - dest[i] = src[start + i]; - } else { - const char16_t* src = GetTwoByteLinearStringChars(nogc, s); - mozilla::PodCopy(dest, src + start, len); - } -} - -MOZ_ALWAYS_INLINE void -CopyLinearStringChars(char* dest, JSLinearString* s, size_t len, size_t start = 0) -{ - MOZ_ASSERT(start + len <= GetLinearStringLength(s)); - JS::AutoCheckCannotGC nogc; - if (LinearStringHasLatin1Chars(s)) { - const JS::Latin1Char* src = GetLatin1LinearStringChars(nogc, s); - for (size_t i = 0; i < len; i++) - dest[i] = char(src[start + i]); - } else { - const char16_t* src = GetTwoByteLinearStringChars(nogc, s); - for (size_t i = 0; i < len; i++) - dest[i] = char(src[start + i]); - } -} - -template -inline bool -CopyStringChars(JSContext* cx, CharType* dest, JSString* s, size_t len, size_t start = 0) -{ - JSLinearString* linear = StringToLinearString(cx, s); - if (!linear) - return false; - - CopyLinearStringChars(dest, linear, len, start); - return true; -} - -inline void -CopyFlatStringChars(char16_t* dest, JSFlatString* s, size_t len) -{ - CopyLinearStringChars(dest, FlatStringToLinearString(s), len); -} - -/** - * Add some or all property keys of obj to the id vector *props. - * - * The flags parameter controls which property keys are added. Pass a - * combination of the following bits: - * - * JSITER_OWNONLY - Don't also search the prototype chain; only consider - * obj's own properties. - * - * JSITER_HIDDEN - Include nonenumerable properties. - * - * JSITER_SYMBOLS - Include property keys that are symbols. The default - * behavior is to filter out symbols. - * - * JSITER_SYMBOLSONLY - Exclude non-symbol property keys. - * - * This is the closest C++ API we have to `Reflect.ownKeys(obj)`, or - * equivalently, the ES6 [[OwnPropertyKeys]] internal method. Pass - * `JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS` as flags to get - * results that match the output of Reflect.ownKeys. - */ -JS_FRIEND_API(bool) -GetPropertyKeys(JSContext* cx, JS::HandleObject obj, unsigned flags, JS::AutoIdVector* props); - -JS_FRIEND_API(bool) -AppendUnique(JSContext* cx, JS::AutoIdVector& base, JS::AutoIdVector& others); - -JS_FRIEND_API(bool) -StringIsArrayIndex(JSLinearString* str, uint32_t* indexp); - -JS_FRIEND_API(void) -SetPreserveWrapperCallback(JSContext* cx, PreserveWrapperCallback callback); - -JS_FRIEND_API(bool) -IsObjectInContextCompartment(JSObject* obj, const JSContext* cx); - -/* - * NB: keep these in sync with the copy in builtin/SelfHostingDefines.h. - * The first three are omitted because they shouldn't be used in new code. - */ -#define JSITER_ENUMERATE 0x1 /* for-in compatible hidden default iterator */ -#define JSITER_FOREACH 0x2 /* get obj[key] for each property */ -#define JSITER_KEYVALUE 0x4 /* obsolete destructuring for-in wants [key, value] */ -#define JSITER_OWNONLY 0x8 /* iterate over obj's own properties only */ -#define JSITER_HIDDEN 0x10 /* also enumerate non-enumerable properties */ -#define JSITER_SYMBOLS 0x20 /* also include symbol property keys */ -#define JSITER_SYMBOLSONLY 0x40 /* exclude string property keys */ - -JS_FRIEND_API(bool) -RunningWithTrustedPrincipals(JSContext* cx); - -inline uintptr_t -GetNativeStackLimit(JSContext* cx, StackKind kind, int extraAllowance = 0) -{ - uintptr_t limit = ContextFriendFields::get(cx)->nativeStackLimit[kind]; -#if JS_STACK_GROWTH_DIRECTION > 0 - limit += extraAllowance; -#else - limit -= extraAllowance; -#endif - return limit; -} - -inline uintptr_t -GetNativeStackLimit(JSContext* cx, int extraAllowance = 0) -{ - StackKind kind = RunningWithTrustedPrincipals(cx) ? StackForTrustedScript - : StackForUntrustedScript; - return GetNativeStackLimit(cx, kind, extraAllowance); -} - -/* - * These macros report a stack overflow and run |onerror| if we are close to - * using up the C stack. The JS_CHECK_CHROME_RECURSION variant gives us a - * little extra space so that we can ensure that crucial code is able to run. - * JS_CHECK_RECURSION_CONSERVATIVE allows less space than any other check, - * including a safety buffer (as in, it uses the untrusted limit and subtracts - * a little more from it). - */ - -#define JS_CHECK_RECURSION_LIMIT(cx, limit, onerror) \ - JS_BEGIN_MACRO \ - int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(limit, &stackDummy_)) { \ - js::ReportOverRecursed(cx); \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_RECURSION(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT(cx, js::GetNativeStackLimit(cx), onerror) - -#define JS_CHECK_RECURSION_LIMIT_DONT_REPORT(cx, limit, onerror) \ - JS_BEGIN_MACRO \ - int stackDummy_; \ - if (!JS_CHECK_STACK_SIZE(limit, &stackDummy_)) { \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_RECURSION_DONT_REPORT(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT_DONT_REPORT(cx, js::GetNativeStackLimit(cx), onerror) - -#define JS_CHECK_RECURSION_WITH_SP_DONT_REPORT(cx, sp, onerror) \ - JS_BEGIN_MACRO \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_RECURSION_WITH_SP(cx, sp, onerror) \ - JS_BEGIN_MACRO \ - if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ - js::ReportOverRecursed(cx); \ - onerror; \ - } \ - JS_END_MACRO - -#define JS_CHECK_SYSTEM_RECURSION(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT(cx, js::GetNativeStackLimit(cx, js::StackForSystemCode), onerror) - -#define JS_CHECK_RECURSION_CONSERVATIVE(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT(cx, \ - js::GetNativeStackLimit(cx, js::StackForUntrustedScript, -1024 * int(sizeof(size_t))), \ - onerror) - -#define JS_CHECK_RECURSION_CONSERVATIVE_DONT_REPORT(cx, onerror) \ - JS_CHECK_RECURSION_LIMIT_DONT_REPORT(cx, \ - js::GetNativeStackLimit(cx, js::StackForUntrustedScript, -1024 * int(sizeof(size_t))), \ - onerror) - -JS_FRIEND_API(void) -StartPCCountProfiling(JSContext* cx); - -JS_FRIEND_API(void) -StopPCCountProfiling(JSContext* cx); - -JS_FRIEND_API(void) -PurgePCCounts(JSContext* cx); - -JS_FRIEND_API(size_t) -GetPCCountScriptCount(JSContext* cx); - -JS_FRIEND_API(JSString*) -GetPCCountScriptSummary(JSContext* cx, size_t script); - -JS_FRIEND_API(JSString*) -GetPCCountScriptContents(JSContext* cx, size_t script); - -/** - * Generate lcov trace file content for the current compartment, and allocate a - * new buffer and return the content in it, the size of the newly allocated - * content within the buffer would be set to the length out-param. - * - * In case of out-of-memory, this function returns nullptr and does not set any - * value to the length out-param. - */ -JS_FRIEND_API(char*) -GetCodeCoverageSummary(JSContext* cx, size_t* length); - -typedef void -(* ActivityCallback)(void* arg, bool active); - -/** - * Sets a callback that is run whenever the runtime goes idle - the - * last active request ceases - and begins activity - when it was - * idle and a request begins. - */ -JS_FRIEND_API(void) -SetActivityCallback(JSContext* cx, ActivityCallback cb, void* arg); - -typedef bool -(* DOMInstanceClassHasProtoAtDepth)(const Class* instanceClass, - uint32_t protoID, uint32_t depth); -struct JSDOMCallbacks { - DOMInstanceClassHasProtoAtDepth instanceClassMatchesProto; -}; -typedef struct JSDOMCallbacks DOMCallbacks; - -extern JS_FRIEND_API(void) -SetDOMCallbacks(JSContext* cx, const DOMCallbacks* callbacks); - -extern JS_FRIEND_API(const DOMCallbacks*) -GetDOMCallbacks(JSContext* cx); - -extern JS_FRIEND_API(JSObject*) -GetTestingFunctions(JSContext* cx); - -/** - * Helper to convert FreeOp to JSFreeOp when the definition of FreeOp is not - * available and the compiler does not know that FreeOp inherits from - * JSFreeOp. - */ -inline JSFreeOp* -CastToJSFreeOp(FreeOp* fop) -{ - return reinterpret_cast(fop); -} - -/* Implemented in jsexn.cpp. */ - -/** - * Get an error type name from a JSExnType constant. - * Returns nullptr for invalid arguments and JSEXN_INTERNALERR - */ -extern JS_FRIEND_API(JSFlatString*) -GetErrorTypeName(JSContext* cx, int16_t exnType); - -#ifdef JS_DEBUG -extern JS_FRIEND_API(unsigned) -GetEnterCompartmentDepth(JSContext* cx); -#endif - -class RegExpGuard; -extern JS_FRIEND_API(bool) -RegExpToSharedNonInline(JSContext* cx, JS::HandleObject regexp, RegExpGuard* shared); - -/* Implemented in jswrapper.cpp. */ -typedef enum NukeReferencesToWindow { - NukeWindowReferences, - DontNukeWindowReferences -} NukeReferencesToWindow; - -/* - * These filters are designed to be ephemeral stack classes, and thus don't - * do any rooting or holding of their members. - */ -struct CompartmentFilter { - virtual bool match(JSCompartment* c) const = 0; -}; - -struct AllCompartments : public CompartmentFilter { - virtual bool match(JSCompartment* c) const override { return true; } -}; - -struct ContentCompartmentsOnly : public CompartmentFilter { - virtual bool match(JSCompartment* c) const override { - return !IsSystemCompartment(c); - } -}; - -struct ChromeCompartmentsOnly : public CompartmentFilter { - virtual bool match(JSCompartment* c) const override { - return IsSystemCompartment(c); - } -}; - -struct SingleCompartment : public CompartmentFilter { - JSCompartment* ours; - explicit SingleCompartment(JSCompartment* c) : ours(c) {} - virtual bool match(JSCompartment* c) const override { return c == ours; } -}; - -struct CompartmentsWithPrincipals : public CompartmentFilter { - JSPrincipals* principals; - explicit CompartmentsWithPrincipals(JSPrincipals* p) : principals(p) {} - virtual bool match(JSCompartment* c) const override { - return JS_GetCompartmentPrincipals(c) == principals; - } -}; - -extern JS_FRIEND_API(bool) -NukeCrossCompartmentWrappers(JSContext* cx, - const CompartmentFilter& sourceFilter, - const CompartmentFilter& targetFilter, - NukeReferencesToWindow nukeReferencesToWindow); - -/* Specify information about DOMProxy proxies in the DOM, for use by ICs. */ - -/* - * The DOMProxyShadowsCheck function will be called to check if the property for - * id should be gotten from the prototype, or if there is an own property that - * shadows it. - * * If ShadowsViaDirectExpando is returned, then the slot at - * listBaseExpandoSlot contains an expando object which has the property in - * question. - * * If ShadowsViaIndirectExpando is returned, then the slot at - * listBaseExpandoSlot contains a private pointer to an ExpandoAndGeneration - * and the expando object in the ExpandoAndGeneration has the property in - * question. - * * If DoesntShadow is returned then the slot at listBaseExpandoSlot should - * either be undefined or point to an expando object that would contain the - * own property. - * * If DoesntShadowUnique is returned then the slot at listBaseExpandoSlot - * should contain a private pointer to a ExpandoAndGeneration, which contains - * a JS::Value that should either be undefined or point to an expando object, - * and a uint64 value. If that value changes then the IC for getting a - * property will be invalidated. - * * If Shadows is returned, that means the property is an own property of the - * proxy but doesn't live on the expando object. - */ - -struct ExpandoAndGeneration { - ExpandoAndGeneration() - : expando(JS::UndefinedValue()), - generation(0) - {} - - void OwnerUnlinked() - { - ++generation; - } - - static size_t offsetOfExpando() - { - return offsetof(ExpandoAndGeneration, expando); - } - - static size_t offsetOfGeneration() - { - return offsetof(ExpandoAndGeneration, generation); - } - - JS::Heap expando; - uint64_t generation; -}; - -typedef enum DOMProxyShadowsResult { - ShadowCheckFailed, - Shadows, - DoesntShadow, - DoesntShadowUnique, - ShadowsViaDirectExpando, - ShadowsViaIndirectExpando -} DOMProxyShadowsResult; -typedef DOMProxyShadowsResult -(* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); -JS_FRIEND_API(void) -SetDOMProxyInformation(const void* domProxyHandlerFamily, uint32_t domProxyExpandoSlot, - DOMProxyShadowsCheck domProxyShadowsCheck); - -const void* GetDOMProxyHandlerFamily(); -uint32_t GetDOMProxyExpandoSlot(); -DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); -inline bool DOMProxyIsShadowing(DOMProxyShadowsResult result) { - return result == Shadows || - result == ShadowsViaDirectExpando || - result == ShadowsViaIndirectExpando; -} - -/* Implemented in jsdate.cpp. */ - -/** Detect whether the internal date value is NaN. */ -extern JS_FRIEND_API(bool) -DateIsValid(JSContext* cx, JS::HandleObject obj, bool* isValid); - -extern JS_FRIEND_API(bool) -DateGetMsecSinceEpoch(JSContext* cx, JS::HandleObject obj, double* msecSinceEpoch); - -} /* namespace js */ - -/* Implemented in jscntxt.cpp. */ - -/** - * Report an exception, which is currently realized as a printf-style format - * string and its arguments. - */ -typedef enum JSErrNum { -#define MSG_DEF(name, count, exception, format) \ - name, -#include "js.msg" -#undef MSG_DEF - JSErr_Limit -} JSErrNum; - -namespace js { - -extern JS_FRIEND_API(const JSErrorFormatString*) -GetErrorMessage(void* userRef, const unsigned errorNumber); - -// AutoStableStringChars is here so we can use it in ErrorReport. It -// should get moved out of here if we can manage it. See bug 1040316. - -/** - * This class provides safe access to a string's chars across a GC. Once - * we allocate strings and chars in the nursery (bug 903519), this class - * will have to make a copy of the string's chars if they are allocated - * in the nursery, so it's best to avoid using this class unless you really - * need it. It's usually more efficient to use the latin1Chars/twoByteChars - * JSString methods and often the code can be rewritten so that only indexes - * instead of char pointers are used in parts of the code that can GC. - */ -class MOZ_STACK_CLASS AutoStableStringChars -{ - /* - * When copying string char, use this many bytes of inline storage. This is - * chosen to allow the inline string types to be copied without allocating. - * This is asserted in AutoStableStringChars::allocOwnChars. - */ - static const size_t InlineCapacity = 24; - - /* Ensure the string is kept alive while we're using its chars. */ - JS::RootedString s_; - union { - const char16_t* twoByteChars_; - const JS::Latin1Char* latin1Chars_; - }; - mozilla::Maybe> ownChars_; - enum State { Uninitialized, Latin1, TwoByte }; - State state_; - - public: - explicit AutoStableStringChars(JSContext* cx) - : s_(cx), state_(Uninitialized) - {} - - MOZ_MUST_USE - bool init(JSContext* cx, JSString* s); - - /* Like init(), but Latin1 chars are inflated to TwoByte. */ - MOZ_MUST_USE - bool initTwoByte(JSContext* cx, JSString* s); - - bool isLatin1() const { return state_ == Latin1; } - bool isTwoByte() const { return state_ == TwoByte; } - - const char16_t* twoByteChars() const { - MOZ_ASSERT(state_ == TwoByte); - return twoByteChars_; - } - - mozilla::Range latin1Range() const { - MOZ_ASSERT(state_ == Latin1); - return mozilla::Range(latin1Chars_, - GetStringLength(s_)); - } - - mozilla::Range twoByteRange() const { - MOZ_ASSERT(state_ == TwoByte); - return mozilla::Range(twoByteChars_, - GetStringLength(s_)); - } - - /* If we own the chars, transfer ownership to the caller. */ - bool maybeGiveOwnershipToCaller() { - MOZ_ASSERT(state_ != Uninitialized); - if (!ownChars_.isSome() || !ownChars_->extractRawBuffer()) - return false; - state_ = Uninitialized; - ownChars_.reset(); - return true; - } - - private: - AutoStableStringChars(const AutoStableStringChars& other) = delete; - void operator=(const AutoStableStringChars& other) = delete; - - bool baseIsInline(JS::Handle linearString); - template T* allocOwnChars(JSContext* cx, size_t count); - bool copyLatin1Chars(JSContext* cx, JS::Handle linearString); - bool copyTwoByteChars(JSContext* cx, JS::Handle linearString); - bool copyAndInflateLatin1Chars(JSContext*, JS::Handle linearString); -}; - -struct MOZ_STACK_CLASS JS_FRIEND_API(ErrorReport) -{ - explicit ErrorReport(JSContext* cx); - ~ErrorReport(); - - enum SniffingBehavior { - WithSideEffects, - NoSideEffects - }; - - /** - * Generate a JSErrorReport from the provided thrown value. - * - * If the value is a (possibly wrapped) Error object, the JSErrorReport will - * be exactly initialized from the Error object's information, without - * observable side effects. (The Error object's JSErrorReport is reused, if - * it has one.) - * - * Otherwise various attempts are made to derive JSErrorReport information - * from |exn| and from the current execution state. This process is - * *definitely* inconsistent with any standard, and particulars of the - * behavior implemented here generally shouldn't be relied upon. - * - * If the value of |sniffingBehavior| is |WithSideEffects|, some of these - * attempts *may* invoke user-configurable behavior when |exn| is an object: - * converting |exn| to a string, detecting and getting properties on |exn|, - * accessing |exn|'s prototype chain, and others are possible. Users *must* - * tolerate |ErrorReport::init| potentially having arbitrary effects. Any - * exceptions thrown by these operations will be caught and silently - * ignored, and "default" values will be substituted into the JSErrorReport. - * - * But if the value of |sniffingBehavior| is |NoSideEffects|, these attempts - * *will not* invoke any observable side effects. The JSErrorReport will - * simply contain fewer, less precise details. - * - * Unlike some functions involved in error handling, this function adheres - * to the usual JSAPI return value error behavior. - */ - bool init(JSContext* cx, JS::HandleValue exn, - SniffingBehavior sniffingBehavior); - - JSErrorReport* report() - { - return reportp; - } - - const JS::ConstUTF8CharsZ toStringResult() - { - return toStringResult_; - } - - private: - // More or less an equivalent of JS_ReportErrorNumber/js::ReportErrorNumberVA - // but fills in an ErrorReport instead of reporting it. Uses varargs to - // make it simpler to call js::ExpandErrorArgumentsVA. - // - // Returns false if we fail to actually populate the ErrorReport - // for some reason (probably out of memory). - bool populateUncaughtExceptionReportUTF8(JSContext* cx, ...); - bool populateUncaughtExceptionReportUTF8VA(JSContext* cx, va_list ap); - - // Reports exceptions from add-on scopes to telementry. - void ReportAddonExceptionToTelementry(JSContext* cx); - - // We may have a provided JSErrorReport, so need a way to represent that. - JSErrorReport* reportp; - - // Or we may need to synthesize a JSErrorReport one of our own. - JSErrorReport ownedReport; - - // And we have a string to maybe keep alive that has pointers into - // it from ownedReport. - JS::RootedString str; - - // And keep its chars alive too. - AutoStableStringChars strChars; - - // And we need to root our exception value. - JS::RootedObject exnObject; - - // And for our filename. - JSAutoByteString filename; - - // We may have a result of error.toString(). - // FIXME: We should not call error.toString(), since it could have side - // effect (see bug 633623). - JS::ConstUTF8CharsZ toStringResult_; - JSAutoByteString toStringResultBytesStorage; -}; - -/* Implemented in vm/StructuredClone.cpp. */ -extern JS_FRIEND_API(uint64_t) -GetSCOffset(JSStructuredCloneWriter* writer); - -namespace Scalar { - -/** - * Scalar types that can appear in typed arrays and typed objects. The enum - * values must to be kept in sync with the JS_SCALARTYPEREPR_ constants, as - * well as the TypedArrayObject::classes and TypedArrayObject::protoClasses - * definitions. - */ -enum Type { - Int8 = 0, - Uint8, - Int16, - Uint16, - Int32, - Uint32, - Float32, - Float64, - - /** - * Special type that is a uint8_t, but assignments are clamped to [0, 256). - * Treat the raw data type as a uint8_t. - */ - Uint8Clamped, - - /** - * Types that don't have their own TypedArray equivalent, for now. - */ - MaxTypedArrayViewType, - - Int64, - Float32x4, - Int8x16, - Int16x8, - Int32x4 -}; - -static inline size_t -byteSize(Type atype) -{ - switch (atype) { - case Int8: - case Uint8: - case Uint8Clamped: - return 1; - case Int16: - case Uint16: - return 2; - case Int32: - case Uint32: - case Float32: - return 4; - case Int64: - case Float64: - return 8; - case Int8x16: - case Int16x8: - case Int32x4: - case Float32x4: - return 16; - default: - MOZ_CRASH("invalid scalar type"); - } -} - -static inline bool -isSignedIntType(Type atype) { - switch (atype) { - case Int8: - case Int16: - case Int32: - case Int64: - case Int8x16: - case Int16x8: - case Int32x4: - return true; - case Uint8: - case Uint8Clamped: - case Uint16: - case Uint32: - case Float32: - case Float64: - case Float32x4: - return false; - default: - MOZ_CRASH("invalid scalar type"); - } -} - -static inline bool -isSimdType(Type atype) { - switch (atype) { - case Int8: - case Uint8: - case Uint8Clamped: - case Int16: - case Uint16: - case Int32: - case Uint32: - case Int64: - case Float32: - case Float64: - return false; - case Int8x16: - case Int16x8: - case Int32x4: - case Float32x4: - return true; - case MaxTypedArrayViewType: - break; - } - MOZ_CRASH("invalid scalar type"); -} - -static inline size_t -scalarByteSize(Type atype) { - switch (atype) { - case Int8x16: - return 1; - case Int16x8: - return 2; - case Int32x4: - case Float32x4: - return 4; - case Int8: - case Uint8: - case Uint8Clamped: - case Int16: - case Uint16: - case Int32: - case Uint32: - case Int64: - case Float32: - case Float64: - case MaxTypedArrayViewType: - break; - } - MOZ_CRASH("invalid simd type"); -} - -} /* namespace Scalar */ -} /* namespace js */ - -/* - * Create a new typed array with nelements elements. - * - * These functions (except the WithBuffer variants) fill in the array with zeros. - */ - -extern JS_FRIEND_API(JSObject*) -JS_NewInt8Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ClampedArray(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewInt16Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint16Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewInt32Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewUint32Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat32Array(JSContext* cx, uint32_t nelements); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat64Array(JSContext* cx, uint32_t nelements); - -/* - * Create a new typed array and copy in values from the given object. The - * object is used as if it were an array; that is, the new array (if - * successfully created) will have length given by array.length, and its - * elements will be those specified by array[0], array[1], and so on, after - * conversion to the typed array element type. - */ - -extern JS_FRIEND_API(JSObject*) -JS_NewInt8ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ClampedArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewInt16ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint16ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewInt32ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewUint32ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat32ArrayFromArray(JSContext* cx, JS::HandleObject array); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat64ArrayFromArray(JSContext* cx, JS::HandleObject array); - -/* - * Create a new typed array using the given ArrayBuffer or - * SharedArrayBuffer for storage. The length value is optional; if -1 - * is passed, enough elements to use up the remainder of the byte - * array is used as the default value. - */ - -extern JS_FRIEND_API(JSObject*) -JS_NewInt8ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint8ClampedArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewInt16ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint16ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewInt32ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewUint32ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat32ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); -extern JS_FRIEND_API(JSObject*) -JS_NewFloat64ArrayWithBuffer(JSContext* cx, JS::HandleObject arrayBuffer, - uint32_t byteOffset, int32_t length); - -/** - * Create a new SharedArrayBuffer with the given byte length. This - * may only be called if - * JS::CompartmentCreationOptionsRef(cx).getSharedMemoryAndAtomicsEnabled() is - * true. - */ -extern JS_FRIEND_API(JSObject*) -JS_NewSharedArrayBuffer(JSContext* cx, uint32_t nbytes); - -/** - * Create a new ArrayBuffer with the given byte length. - */ -extern JS_FRIEND_API(JSObject*) -JS_NewArrayBuffer(JSContext* cx, uint32_t nbytes); - -/** - * Check whether obj supports JS_GetTypedArray* APIs. Note that this may return - * false if a security wrapper is encountered that denies the unwrapping. If - * this test or one of the JS_Is*Array tests succeeds, then it is safe to call - * the various accessor JSAPI calls defined below. - */ -extern JS_FRIEND_API(bool) -JS_IsTypedArrayObject(JSObject* obj); - -/** - * Check whether obj supports JS_GetArrayBufferView* APIs. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. If this test or one of the more specific tests succeeds, then it - * is safe to call the various ArrayBufferView accessor JSAPI calls defined - * below. - */ -extern JS_FRIEND_API(bool) -JS_IsArrayBufferViewObject(JSObject* obj); - -/* - * Test for specific typed array types (ArrayBufferView subtypes) - */ - -extern JS_FRIEND_API(bool) -JS_IsInt8Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint8Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint8ClampedArray(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsInt16Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint16Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsInt32Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsUint32Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsFloat32Array(JSObject* obj); -extern JS_FRIEND_API(bool) -JS_IsFloat64Array(JSObject* obj); - -/** - * Return the isShared flag of a typed array, which denotes whether - * the underlying buffer is a SharedArrayBuffer. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(bool) -JS_GetTypedArraySharedness(JSObject* obj); - -/* - * Test for specific typed array types (ArrayBufferView subtypes) and return - * the unwrapped object if so, else nullptr. Never throws. - */ - -namespace js { - -extern JS_FRIEND_API(JSObject*) -UnwrapInt8Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint8Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint8ClampedArray(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapInt16Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint16Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapInt32Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapUint32Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapFloat32Array(JSObject* obj); -extern JS_FRIEND_API(JSObject*) -UnwrapFloat64Array(JSObject* obj); - -extern JS_FRIEND_API(JSObject*) -UnwrapArrayBuffer(JSObject* obj); - -extern JS_FRIEND_API(JSObject*) -UnwrapArrayBufferView(JSObject* obj); - -extern JS_FRIEND_API(JSObject*) -UnwrapSharedArrayBuffer(JSObject* obj); - - -namespace detail { - -extern JS_FRIEND_DATA(const Class* const) Int8ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint8ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint8ClampedArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Int16ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint16ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Int32ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Uint32ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Float32ArrayClassPtr; -extern JS_FRIEND_DATA(const Class* const) Float64ArrayClassPtr; - -const size_t TypedArrayLengthSlot = 1; - -} // namespace detail - -#define JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Type, type) \ -inline void \ -Get ## Type ## ArrayLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, type** data) \ -{ \ - MOZ_ASSERT(GetObjectClass(obj) == detail::Type ## ArrayClassPtr); \ - const JS::Value& lenSlot = GetReservedSlot(obj, detail::TypedArrayLengthSlot); \ - *length = mozilla::AssertedCast(lenSlot.toInt32()); \ - *isSharedMemory = JS_GetTypedArraySharedness(obj); \ - *data = static_cast(GetObjectPrivate(obj)); \ -} - -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Int8, int8_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint8, uint8_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint8Clamped, uint8_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Int16, int16_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint16, uint16_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Int32, int32_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Uint32, uint32_t) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Float32, float) -JS_DEFINE_DATA_AND_LENGTH_ACCESSOR(Float64, double) - -#undef JS_DEFINE_DATA_AND_LENGTH_ACCESSOR - -// This one isn't inlined because it's rather tricky (by dint of having to deal -// with a dozen-plus classes and varying slot layouts. -extern JS_FRIEND_API(void) -GetArrayBufferViewLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -// This one isn't inlined because there are a bunch of different ArrayBuffer -// classes that would have to be individually handled here. -// -// There is an isShared out argument for API consistency (eases use from DOM). -// It will always be set to false. -extern JS_FRIEND_API(void) -GetArrayBufferLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -// Ditto for SharedArrayBuffer. -// -// There is an isShared out argument for API consistency (eases use from DOM). -// It will always be set to true. -extern JS_FRIEND_API(void) -GetSharedArrayBufferLengthAndData(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -} // namespace js - -JS_FRIEND_API(uint8_t*) -JS_GetSharedArrayBufferData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/* - * Unwrap Typed arrays all at once. Return nullptr without throwing if the - * object cannot be viewed as the correct typed array, or the typed array - * object on success, filling both outparameters. - */ -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsInt8Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, int8_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint8Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint8ClampedArray(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsInt16Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, int16_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint16Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint16_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsInt32Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, int32_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsUint32Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint32_t** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsFloat32Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, float** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsFloat64Array(JSObject* obj, uint32_t* length, bool* isSharedMemory, double** data); -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsArrayBufferView(JSObject* obj, uint32_t* length, bool* isSharedMemory, uint8_t** data); - -/* - * Unwrap an ArrayBuffer, return nullptr if it's a different type. - */ -extern JS_FRIEND_API(JSObject*) -JS_GetObjectAsArrayBuffer(JSObject* obj, uint32_t* length, uint8_t** data); - -/* - * Get the type of elements in a typed array, or MaxTypedArrayViewType if a DataView. - * - * |obj| must have passed a JS_IsArrayBufferView/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is an ArrayBufferView or a - * wrapper of an ArrayBufferView, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(js::Scalar::Type) -JS_GetArrayBufferViewType(JSObject* obj); - -extern JS_FRIEND_API(js::Scalar::Type) -JS_GetSharedArrayBufferViewType(JSObject* obj); - -/* - * Check whether obj supports the JS_GetArrayBuffer* APIs. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. If this test succeeds, then it is safe to call the various - * accessor JSAPI calls defined below. - */ -extern JS_FRIEND_API(bool) -JS_IsArrayBufferObject(JSObject* obj); - -extern JS_FRIEND_API(bool) -JS_IsSharedArrayBufferObject(JSObject* obj); - -/** - * Return the available byte length of an array buffer. - * - * |obj| must have passed a JS_IsArrayBufferObject test, or somehow be known - * that it would pass such a test: it is an ArrayBuffer or a wrapper of an - * ArrayBuffer, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetArrayBufferByteLength(JSObject* obj); - -extern JS_FRIEND_API(uint32_t) -JS_GetSharedArrayBufferByteLength(JSObject* obj); - -/** - * Return true if the arrayBuffer contains any data. This will return false for - * ArrayBuffer.prototype and detached ArrayBuffers. - * - * |obj| must have passed a JS_IsArrayBufferObject test, or somehow be known - * that it would pass such a test: it is an ArrayBuffer or a wrapper of an - * ArrayBuffer, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(bool) -JS_ArrayBufferHasData(JSObject* obj); - -/** - * Return a pointer to the start of the data referenced by a typed array. The - * data is still owned by the typed array, and should not be modified on - * another thread. Furthermore, the pointer can become invalid on GC (if the - * data is small and fits inside the array's GC header), so callers must take - * care not to hold on across anything that could GC. - * - * |obj| must have passed a JS_IsArrayBufferObject test, or somehow be known - * that it would pass such a test: it is an ArrayBuffer or a wrapper of an - * ArrayBuffer, and the unwrapping will succeed. - * - * *isSharedMemory will be set to false, the argument is present to simplify - * its use from code that also interacts with SharedArrayBuffer. - */ -extern JS_FRIEND_API(uint8_t*) -JS_GetArrayBufferData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/** - * Check whether the obj is ArrayBufferObject and memory mapped. Note that this - * may return false if a security wrapper is encountered that denies the - * unwrapping. - */ -extern JS_FRIEND_API(bool) -JS_IsMappedArrayBufferObject(JSObject* obj); - -/** - * Return the number of elements in a typed array. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetTypedArrayLength(JSObject* obj); - -/** - * Return the byte offset from the start of an array buffer to the start of a - * typed array view. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetTypedArrayByteOffset(JSObject* obj); - -/** - * Return the byte length of a typed array. - * - * |obj| must have passed a JS_IsTypedArrayObject/JS_Is*Array test, or somehow - * be known that it would pass such a test: it is a typed array or a wrapper of - * a typed array, and the unwrapping will succeed. - */ -extern JS_FRIEND_API(uint32_t) -JS_GetTypedArrayByteLength(JSObject* obj); - -/** - * Check whether obj supports JS_ArrayBufferView* APIs. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. - */ -extern JS_FRIEND_API(bool) -JS_IsArrayBufferViewObject(JSObject* obj); - -/** - * More generic name for JS_GetTypedArrayByteLength to cover DataViews as well - */ -extern JS_FRIEND_API(uint32_t) -JS_GetArrayBufferViewByteLength(JSObject* obj); - -/* - * Return a pointer to the start of the data referenced by a typed array. The - * data is still owned by the typed array, and should not be modified on - * another thread. Furthermore, the pointer can become invalid on GC (if the - * data is small and fits inside the array's GC header), so callers must take - * care not to hold on across anything that could GC. - * - * |obj| must have passed a JS_Is*Array test, or somehow be known that it would - * pass such a test: it is a typed array or a wrapper of a typed array, and the - * unwrapping will succeed. - * - * *isSharedMemory will be set to true if the typed array maps a - * SharedArrayBuffer, otherwise to false. - */ - -extern JS_FRIEND_API(int8_t*) -JS_GetInt8ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint8_t*) -JS_GetUint8ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint8_t*) -JS_GetUint8ClampedArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(int16_t*) -JS_GetInt16ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint16_t*) -JS_GetUint16ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(int32_t*) -JS_GetInt32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(uint32_t*) -JS_GetUint32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(float*) -JS_GetFloat32ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); -extern JS_FRIEND_API(double*) -JS_GetFloat64ArrayData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/** - * Same as above, but for any kind of ArrayBufferView. Prefer the type-specific - * versions when possible. - */ -extern JS_FRIEND_API(void*) -JS_GetArrayBufferViewData(JSObject* obj, bool* isSharedMemory, const JS::AutoCheckCannotGC&); - -/** - * Return the ArrayBuffer or SharedArrayBuffer underlying an ArrayBufferView. - * This may return a detached buffer. |obj| must be an object that would - * return true for JS_IsArrayBufferViewObject(). - */ -extern JS_FRIEND_API(JSObject*) -JS_GetArrayBufferViewBuffer(JSContext* cx, JS::HandleObject obj, bool* isSharedMemory); - -/** - * Detach an ArrayBuffer, causing all associated views to no longer refer to - * the ArrayBuffer's original attached memory. - * - * The |changeData| argument is obsolete and ignored. - */ -extern JS_FRIEND_API(bool) -JS_DetachArrayBuffer(JSContext* cx, JS::HandleObject obj); - -/** - * Check whether the obj is a detached ArrayBufferObject. Note that this may - * return false if a security wrapper is encountered that denies the - * unwrapping. - */ -extern JS_FRIEND_API(bool) -JS_IsDetachedArrayBufferObject(JSObject* obj); - -/** - * Check whether obj supports JS_GetDataView* APIs. - */ -JS_FRIEND_API(bool) -JS_IsDataViewObject(JSObject* obj); - -/** - * Create a new DataView using the given ArrayBuffer for storage. The given - * buffer must be an ArrayBuffer (or a cross-compartment wrapper of an - * ArrayBuffer), and the offset and length must fit within the bounds of the - * arrayBuffer. Currently, nullptr will be returned and an exception will be - * thrown if these conditions do not hold, but do not depend on that behavior. - */ -JS_FRIEND_API(JSObject*) -JS_NewDataView(JSContext* cx, JS::HandleObject arrayBuffer, uint32_t byteOffset, int32_t byteLength); - -/** - * Return the byte offset of a data view into its array buffer. |obj| must be a - * DataView. - * - * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that - * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. - */ -JS_FRIEND_API(uint32_t) -JS_GetDataViewByteOffset(JSObject* obj); - -/** - * Return the byte length of a data view. - * - * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that - * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be - * unable to assert when unwrapping should be disallowed. - */ -JS_FRIEND_API(uint32_t) -JS_GetDataViewByteLength(JSObject* obj); - -/** - * Return a pointer to the beginning of the data referenced by a DataView. - * - * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that - * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be - * unable to assert when unwrapping should be disallowed. - */ -JS_FRIEND_API(void*) -JS_GetDataViewData(JSObject* obj, const JS::AutoCheckCannotGC&); - -namespace js { - -/** - * Add a watchpoint -- in the Object.prototype.watch sense -- to |obj| for the - * property |id|, using the callable object |callable| as the function to be - * called for notifications. - * - * This is an internal function exposed -- temporarily -- only so that DOM - * proxies can be watchable. Don't use it! We'll soon kill off the - * Object.prototype.{,un}watch functions, at which point this will go too. - */ -extern JS_FRIEND_API(bool) -WatchGuts(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); - -/** - * Remove a watchpoint -- in the Object.prototype.watch sense -- from |obj| for - * the property |id|. - * - * This is an internal function exposed -- temporarily -- only so that DOM - * proxies can be watchable. Don't use it! We'll soon kill off the - * Object.prototype.{,un}watch functions, at which point this will go too. - */ -extern JS_FRIEND_API(bool) -UnwatchGuts(JSContext* cx, JS::HandleObject obj, JS::HandleId id); - -namespace jit { - -enum class InlinableNative : uint16_t; - -} // namespace jit - -} // namespace js - -/** - * A class, expected to be passed by value, which represents the CallArgs for a - * JSJitGetterOp. - */ -class JSJitGetterCallArgs : protected JS::MutableHandleValue -{ - public: - explicit JSJitGetterCallArgs(const JS::CallArgs& args) - : JS::MutableHandleValue(args.rval()) - {} - - explicit JSJitGetterCallArgs(JS::RootedValue* rooted) - : JS::MutableHandleValue(rooted) - {} - - JS::MutableHandleValue rval() { - return *this; - } -}; - -/** - * A class, expected to be passed by value, which represents the CallArgs for a - * JSJitSetterOp. - */ -class JSJitSetterCallArgs : protected JS::MutableHandleValue -{ - public: - explicit JSJitSetterCallArgs(const JS::CallArgs& args) - : JS::MutableHandleValue(args[0]) - {} - - JS::MutableHandleValue operator[](unsigned i) { - MOZ_ASSERT(i == 0); - return *this; - } - - unsigned length() const { return 1; } - - // Add get() or maybe hasDefined() as needed -}; - -struct JSJitMethodCallArgsTraits; - -/** - * A class, expected to be passed by reference, which represents the CallArgs - * for a JSJitMethodOp. - */ -class JSJitMethodCallArgs : protected JS::detail::CallArgsBase -{ - private: - typedef JS::detail::CallArgsBase Base; - friend struct JSJitMethodCallArgsTraits; - - public: - explicit JSJitMethodCallArgs(const JS::CallArgs& args) { - argv_ = args.array(); - argc_ = args.length(); - } - - JS::MutableHandleValue rval() const { - return Base::rval(); - } - - unsigned length() const { return Base::length(); } - - JS::MutableHandleValue operator[](unsigned i) const { - return Base::operator[](i); - } - - bool hasDefined(unsigned i) const { - return Base::hasDefined(i); - } - - JSObject& callee() const { - // We can't use Base::callee() because that will try to poke at - // this->usedRval_, which we don't have. - return argv_[-2].toObject(); - } - - JS::HandleValue get(unsigned i) const { - return Base::get(i); - } -}; - -struct JSJitMethodCallArgsTraits -{ - static const size_t offsetOfArgv = offsetof(JSJitMethodCallArgs, argv_); - static const size_t offsetOfArgc = offsetof(JSJitMethodCallArgs, argc_); -}; - -typedef bool -(* JSJitGetterOp)(JSContext* cx, JS::HandleObject thisObj, - void* specializedThis, JSJitGetterCallArgs args); -typedef bool -(* JSJitSetterOp)(JSContext* cx, JS::HandleObject thisObj, - void* specializedThis, JSJitSetterCallArgs args); -typedef bool -(* JSJitMethodOp)(JSContext* cx, JS::HandleObject thisObj, - void* specializedThis, const JSJitMethodCallArgs& args); - -/** - * This struct contains metadata passed from the DOM to the JS Engine for JIT - * optimizations on DOM property accessors. Eventually, this should be made - * available to general JSAPI users, but we are not currently ready to do so. - */ -struct JSJitInfo { - enum OpType { - Getter, - Setter, - Method, - StaticMethod, - InlinableNative, - // Must be last - OpTypeCount - }; - - enum ArgType { - // Basic types - String = (1 << 0), - Integer = (1 << 1), // Only 32-bit or less - Double = (1 << 2), // Maybe we want to add Float sometime too - Boolean = (1 << 3), - Object = (1 << 4), - Null = (1 << 5), - - // And derived types - Numeric = Integer | Double, - // Should "Primitive" use the WebIDL definition, which - // excludes string and null, or the typical JS one that includes them? - Primitive = Numeric | Boolean | Null | String, - ObjectOrNull = Object | Null, - Any = ObjectOrNull | Primitive, - - // Our sentinel value. - ArgTypeListEnd = (1 << 31) - }; - - static_assert(Any & String, "Any must include String."); - static_assert(Any & Integer, "Any must include Integer."); - static_assert(Any & Double, "Any must include Double."); - static_assert(Any & Boolean, "Any must include Boolean."); - static_assert(Any & Object, "Any must include Object."); - static_assert(Any & Null, "Any must include Null."); - - /** - * An enum that describes what this getter/setter/method aliases. This - * determines what things can be hoisted past this call, and if this - * call is movable what it can be hoisted past. - */ - enum AliasSet { - /** - * Alias nothing: a constant value, getting it can't affect any other - * values, nothing can affect it. - */ - AliasNone, - - /** - * Alias things that can modify the DOM but nothing else. Doing the - * call can't affect the behavior of any other function. - */ - AliasDOMSets, - - /** - * Alias the world. Calling this can change arbitrary values anywhere - * in the system. Most things fall in this bucket. - */ - AliasEverything, - - /** Must be last. */ - AliasSetCount - }; - - bool needsOuterizedThisObject() const - { - return type() != Getter && type() != Setter; - } - - bool isTypedMethodJitInfo() const - { - return isTypedMethod; - } - - OpType type() const - { - return OpType(type_); - } - - AliasSet aliasSet() const - { - return AliasSet(aliasSet_); - } - - JSValueType returnType() const - { - return JSValueType(returnType_); - } - - union { - JSJitGetterOp getter; - JSJitSetterOp setter; - JSJitMethodOp method; - /** A DOM static method, used for Promise wrappers */ - JSNative staticMethod; - }; - - union { - uint16_t protoID; - js::jit::InlinableNative inlinableNative; - }; - - union { - uint16_t depth; - - // Additional opcode for some InlinableNative functions. - uint16_t nativeOp; - }; - - // These fields are carefully packed to take up 4 bytes. If you need more - // bits for whatever reason, please see if you can steal bits from existing - // fields before adding more members to this structure. - -#define JITINFO_OP_TYPE_BITS 4 -#define JITINFO_ALIAS_SET_BITS 4 -#define JITINFO_RETURN_TYPE_BITS 8 -#define JITINFO_SLOT_INDEX_BITS 10 - - /** The OpType that says what sort of function we are. */ - uint32_t type_ : JITINFO_OP_TYPE_BITS; - - /** - * The alias set for this op. This is a _minimal_ alias set; in - * particular for a method it does not include whatever argument - * conversions might do. That's covered by argTypes and runtime - * analysis of the actual argument types being passed in. - */ - uint32_t aliasSet_ : JITINFO_ALIAS_SET_BITS; - - /** The return type tag. Might be JSVAL_TYPE_UNKNOWN. */ - uint32_t returnType_ : JITINFO_RETURN_TYPE_BITS; - - static_assert(OpTypeCount <= (1 << JITINFO_OP_TYPE_BITS), - "Not enough space for OpType"); - static_assert(AliasSetCount <= (1 << JITINFO_ALIAS_SET_BITS), - "Not enough space for AliasSet"); - static_assert((sizeof(JSValueType) * 8) <= JITINFO_RETURN_TYPE_BITS, - "Not enough space for JSValueType"); - -#undef JITINFO_RETURN_TYPE_BITS -#undef JITINFO_ALIAS_SET_BITS -#undef JITINFO_OP_TYPE_BITS - - /** Is op fallible? False in setters. */ - uint32_t isInfallible : 1; - - /** - * Is op movable? To be movable the op must - * not AliasEverything, but even that might - * not be enough (e.g. in cases when it can - * throw or is explicitly not movable). - */ - uint32_t isMovable : 1; - - /** - * Can op be dead-code eliminated? Again, this - * depends on whether the op can throw, in - * addition to the alias set. - */ - uint32_t isEliminatable : 1; - - // XXXbz should we have a JSValueType for the type of the member? - /** - * True if this is a getter that can always - * get the value from a slot of the "this" object. - */ - uint32_t isAlwaysInSlot : 1; - - /** - * True if this is a getter that can sometimes (if the slot doesn't contain - * UndefinedValue()) get the value from a slot of the "this" object. - */ - uint32_t isLazilyCachedInSlot : 1; - - /** True if this is an instance of JSTypedMethodJitInfo. */ - uint32_t isTypedMethod : 1; - - /** - * If isAlwaysInSlot or isSometimesInSlot is true, - * the index of the slot to get the value from. - * Otherwise 0. - */ - uint32_t slotIndex : JITINFO_SLOT_INDEX_BITS; - - static const size_t maxSlotIndex = (1 << JITINFO_SLOT_INDEX_BITS) - 1; - -#undef JITINFO_SLOT_INDEX_BITS -}; - -static_assert(sizeof(JSJitInfo) == (sizeof(void*) + 2 * sizeof(uint32_t)), - "There are several thousand instances of JSJitInfo stored in " - "a binary. Please don't increase its space requirements without " - "verifying that there is no other way forward (better packing, " - "smaller datatypes for fields, subclassing, etc.)."); - -struct JSTypedMethodJitInfo -{ - // We use C-style inheritance here, rather than C++ style inheritance - // because not all compilers support brace-initialization for non-aggregate - // classes. Using C++ style inheritance and constructors instead of - // brace-initialization would also force the creation of static - // constructors (on some compilers) when JSJitInfo and JSTypedMethodJitInfo - // structures are declared. Since there can be several thousand of these - // structures present and we want to have roughly equivalent performance - // across a range of compilers, we do things manually. - JSJitInfo base; - - const JSJitInfo::ArgType* const argTypes; /* For a method, a list of sets of - types that the function - expects. This can be used, - for example, to figure out - when argument coercions can - have side-effects. */ -}; - -namespace js { - -static MOZ_ALWAYS_INLINE shadow::Function* -FunctionObjectToShadowFunction(JSObject* fun) -{ - MOZ_ASSERT(GetObjectClass(fun) == FunctionClassPtr); - return reinterpret_cast(fun); -} - -/* Statically asserted in jsfun.h. */ -static const unsigned JS_FUNCTION_INTERPRETED_BITS = 0x0201; - -// Return whether the given function object is native. -static MOZ_ALWAYS_INLINE bool -FunctionObjectIsNative(JSObject* fun) -{ - return !(FunctionObjectToShadowFunction(fun)->flags & JS_FUNCTION_INTERPRETED_BITS); -} - -static MOZ_ALWAYS_INLINE JSNative -GetFunctionObjectNative(JSObject* fun) -{ - MOZ_ASSERT(FunctionObjectIsNative(fun)); - return FunctionObjectToShadowFunction(fun)->native; -} - -} // namespace js - -static MOZ_ALWAYS_INLINE const JSJitInfo* -FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) -{ - MOZ_ASSERT(js::FunctionObjectIsNative(&v.toObject())); - return js::FunctionObjectToShadowFunction(&v.toObject())->jitinfo; -} - -static MOZ_ALWAYS_INLINE void -SET_JITINFO(JSFunction * func, const JSJitInfo* info) -{ - js::shadow::Function* fun = reinterpret_cast(func); - MOZ_ASSERT(!(fun->flags & js::JS_FUNCTION_INTERPRETED_BITS)); - fun->jitinfo = info; -} - -/* - * Engine-internal extensions of jsid. This code is here only until we - * eliminate Gecko's dependencies on it! - */ - -static MOZ_ALWAYS_INLINE jsid -JSID_FROM_BITS(size_t bits) -{ - jsid id; - JSID_BITS(id) = bits; - return id; -} - -namespace js { -namespace detail { -bool IdMatchesAtom(jsid id, JSAtom* atom); -} // namespace detail -} // namespace js - -/** - * Must not be used on atoms that are representable as integer jsids. - * Prefer NameToId or AtomToId over this function: - * - * A PropertyName is an atom that does not contain an integer in the range - * [0, UINT32_MAX]. However, jsid can only hold an integer in the range - * [0, JSID_INT_MAX] (where JSID_INT_MAX == 2^31-1). Thus, for the range of - * integers (JSID_INT_MAX, UINT32_MAX], to represent as a jsid 'id', it must be - * the case JSID_IS_ATOM(id) and !JSID_TO_ATOM(id)->isPropertyName(). In most - * cases when creating a jsid, code does not have to care about this corner - * case because: - * - * - When given an arbitrary JSAtom*, AtomToId must be used, which checks for - * integer atoms representable as integer jsids, and does this conversion. - * - * - When given a PropertyName*, NameToId can be used which which does not need - * to do any dynamic checks. - * - * Thus, it is only the rare third case which needs this function, which - * handles any JSAtom* that is known not to be representable with an int jsid. - */ -static MOZ_ALWAYS_INLINE jsid -NON_INTEGER_ATOM_TO_JSID(JSAtom* atom) -{ - MOZ_ASSERT(((size_t)atom & 0x7) == 0); - jsid id = JSID_FROM_BITS((size_t)atom); - MOZ_ASSERT(js::detail::IdMatchesAtom(id, atom)); - return id; -} - -/* All strings stored in jsids are atomized, but are not necessarily property names. */ -static MOZ_ALWAYS_INLINE bool -JSID_IS_ATOM(jsid id) -{ - return JSID_IS_STRING(id); -} - -static MOZ_ALWAYS_INLINE bool -JSID_IS_ATOM(jsid id, JSAtom* atom) -{ - return id == JSID_FROM_BITS((size_t)atom); -} - -static MOZ_ALWAYS_INLINE JSAtom* -JSID_TO_ATOM(jsid id) -{ - return (JSAtom*)JSID_TO_STRING(id); -} - -JS_STATIC_ASSERT(sizeof(jsid) == sizeof(void*)); - -namespace js { - -static MOZ_ALWAYS_INLINE JS::Value -IdToValue(jsid id) -{ - if (JSID_IS_STRING(id)) - return JS::StringValue(JSID_TO_STRING(id)); - if (JSID_IS_INT(id)) - return JS::Int32Value(JSID_TO_INT(id)); - if (JSID_IS_SYMBOL(id)) - return JS::SymbolValue(JSID_TO_SYMBOL(id)); - MOZ_ASSERT(JSID_IS_VOID(id)); - return JS::UndefinedValue(); -} - -/** - * If the embedder has registered a ScriptEnvironmentPreparer, - * PrepareScriptEnvironmentAndInvoke will call the preparer's 'invoke' method - * with the given |closure|, with the assumption that the preparer will set up - * any state necessary to run script in |scope|, invoke |closure| with a valid - * JSContext*, report any exceptions thrown from the closure, and return. - * - * If no preparer is registered, PrepareScriptEnvironmentAndInvoke will assert - * that |rt| has exactly one JSContext associated with it, enter the compartment - * of |scope| on that context, and invoke |closure|. - * - * In both cases, PrepareScriptEnvironmentAndInvoke will report any exceptions - * that are thrown by the closure. Consumers who want to propagate back - * whether the closure succeeded should do so via members of the closure - * itself. - */ - -struct ScriptEnvironmentPreparer { - struct Closure { - virtual bool operator()(JSContext* cx) = 0; - }; - - virtual void invoke(JS::HandleObject scope, Closure& closure) = 0; -}; - -extern JS_FRIEND_API(void) -PrepareScriptEnvironmentAndInvoke(JSContext* cx, JS::HandleObject scope, - ScriptEnvironmentPreparer::Closure& closure); - -JS_FRIEND_API(void) -SetScriptEnvironmentPreparer(JSContext* cx, ScriptEnvironmentPreparer* preparer); - -enum CTypesActivityType { - CTYPES_CALL_BEGIN, - CTYPES_CALL_END, - CTYPES_CALLBACK_BEGIN, - CTYPES_CALLBACK_END -}; - -typedef void -(* CTypesActivityCallback)(JSContext* cx, CTypesActivityType type); - -/** - * Sets a callback that is run whenever js-ctypes is about to be used when - * calling into C. - */ -JS_FRIEND_API(void) -SetCTypesActivityCallback(JSContext* cx, CTypesActivityCallback cb); - -class MOZ_RAII JS_FRIEND_API(AutoCTypesActivityCallback) { - private: - JSContext* cx; - CTypesActivityCallback callback; - CTypesActivityType endType; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - - public: - AutoCTypesActivityCallback(JSContext* cx, CTypesActivityType beginType, - CTypesActivityType endType - MOZ_GUARD_OBJECT_NOTIFIER_PARAM); - ~AutoCTypesActivityCallback() { - DoEndCallback(); - } - void DoEndCallback() { - if (callback) { - callback(cx, endType); - callback = nullptr; - } - } -}; - -// Abstract base class for objects that build allocation metadata for JavaScript -// values. -struct AllocationMetadataBuilder { - AllocationMetadataBuilder() { } - - // Return a metadata object for the newly constructed object |obj|, or - // nullptr if there's no metadata to attach. - // - // Implementations should treat all errors as fatal; there is no way to - // report errors from this callback. In particular, the caller provides an - // oomUnsafe for overriding implementations to use. - virtual JSObject* build(JSContext* cx, JS::HandleObject obj, - AutoEnterOOMUnsafeRegion& oomUnsafe) const - { - return nullptr; - } -}; - -/** - * Specify a callback to invoke when creating each JS object in the current - * compartment, which may return a metadata object to associate with the - * object. - */ -JS_FRIEND_API(void) -SetAllocationMetadataBuilder(JSContext* cx, const AllocationMetadataBuilder *callback); - -/** Get the metadata associated with an object. */ -JS_FRIEND_API(JSObject*) -GetAllocationMetadata(JSObject* obj); - -JS_FRIEND_API(bool) -GetElementsWithAdder(JSContext* cx, JS::HandleObject obj, JS::HandleObject receiver, - uint32_t begin, uint32_t end, js::ElementAdder* adder); - -JS_FRIEND_API(bool) -ForwardToNative(JSContext* cx, JSNative native, const JS::CallArgs& args); - -/** - * Helper function for HTMLDocument and HTMLFormElement. - * - * These are the only two interfaces that have [OverrideBuiltins], a named - * getter, and no named setter. They're implemented as proxies with a custom - * getOwnPropertyDescriptor() method. Unfortunately, overriding - * getOwnPropertyDescriptor() automatically affects the behavior of set(), - * which normally is just common sense but is *not* desired for these two - * interfaces. - * - * The fix is for these two interfaces to override set() to ignore the - * getOwnPropertyDescriptor() override. - * - * SetPropertyIgnoringNamedGetter is exposed to make it easier to override - * set() in this way. It carries out all the steps of BaseProxyHandler::set() - * except the initial getOwnPropertyDescriptor() call. The caller must supply - * that descriptor as the 'ownDesc' parameter. - * - * Implemented in proxy/BaseProxyHandler.cpp. - */ -JS_FRIEND_API(bool) -SetPropertyIgnoringNamedGetter(JSContext* cx, JS::HandleObject obj, JS::HandleId id, - JS::HandleValue v, JS::HandleValue receiver, - JS::Handle ownDesc, - JS::ObjectOpResult& result); - -JS_FRIEND_API(void) -ReportASCIIErrorWithId(JSContext* cx, const char* msg, JS::HandleId id); - -// This function is for one specific use case, please don't use this for anything else! -extern JS_FRIEND_API(bool) -ExecuteInGlobalAndReturnScope(JSContext* cx, JS::HandleObject obj, JS::HandleScript script, - JS::MutableHandleObject scope); - -#if defined(XP_WIN) && defined(_WIN64) -// Parameters use void* types to avoid #including windows.h. The return value of -// this function is returned from the exception handler. -typedef long -(*JitExceptionHandler)(void* exceptionRecord, // PEXECTION_RECORD - void* context); // PCONTEXT - -/** - * Windows uses "structured exception handling" to handle faults. When a fault - * occurs, the stack is searched for a handler (similar to C++ exception - * handling). If the search does not find a handler, the "unhandled exception - * filter" is called. Breakpad uses the unhandled exception filter to do crash - * reporting. Unfortunately, on Win64, JIT code on the stack completely throws - * off this unwinding process and prevents the unhandled exception filter from - * being called. The reason is that Win64 requires unwind information be - * registered for all code regions and JIT code has none. While it is possible - * to register full unwind information for JIT code, this is a lot of work (one - * has to be able to recover the frame pointer at any PC) so instead we register - * a handler for all JIT code that simply calls breakpad's unhandled exception - * filter (which will perform crash reporting and then terminate the process). - * This would be wrong if there was an outer __try block that expected to handle - * the fault, but this is not generally allowed. - * - * Gecko must call SetJitExceptionFilter before any JIT code is compiled and - * only once per process. - */ -extern JS_FRIEND_API(void) -SetJitExceptionHandler(JitExceptionHandler handler); -#endif - -/** - * Get the nearest enclosing with environment object for a given function. If - * the function is not scripted or is not enclosed by a with scope, returns - * the global. - */ -extern JS_FRIEND_API(JSObject*) -GetNearestEnclosingWithEnvironmentObjectForFunction(JSFunction* fun); - -/** - * Get the first SavedFrame object in this SavedFrame stack whose principals are - * subsumed by the cx's principals. If there is no such frame, return nullptr. - * - * Do NOT pass a non-SavedFrame object here. - * - * The savedFrame and cx do not need to be in the same compartment. - */ -extern JS_FRIEND_API(JSObject*) -GetFirstSubsumedSavedFrame(JSContext* cx, JS::HandleObject savedFrame, JS::SavedFrameSelfHosted selfHosted); - -extern JS_FRIEND_API(bool) -ReportIsNotFunction(JSContext* cx, JS::HandleValue v); - -extern JS_FRIEND_API(JSObject*) -ConvertArgsToArray(JSContext* cx, const JS::CallArgs& args); - -/** - * Window and WindowProxy - * - * The functions below have to do with Windows and WindowProxies. There's an - * invariant that actual Window objects (the global objects of web pages) are - * never directly exposed to script. Instead we often substitute a WindowProxy. - * - * The environment chain, on the other hand, contains the Window and never its - * WindowProxy. - * - * As a result, we have calls to these "substitute-this-object-for-that-object" - * functions sprinkled at apparently arbitrary (but actually *very* carefully - * and nervously selected) places throughout the engine and indeed the - * universe. - */ - -/** - * Tell the JS engine which Class is used for WindowProxy objects. Used by the - * functions below. - */ -extern JS_FRIEND_API(void) -SetWindowProxyClass(JSContext* cx, const Class* clasp); - -/** - * Associates a WindowProxy with a Window (global object). `windowProxy` must - * have the Class set by SetWindowProxyClass. - */ -extern JS_FRIEND_API(void) -SetWindowProxy(JSContext* cx, JS::HandleObject global, JS::HandleObject windowProxy); - -namespace detail { - -JS_FRIEND_API(bool) -IsWindowSlow(JSObject* obj); - -} // namespace detail - -/** - * Returns true iff `obj` is a global object with an associated WindowProxy, - * see SetWindowProxy. - */ -inline bool -IsWindow(JSObject* obj) -{ - if (GetObjectClass(obj)->flags & JSCLASS_IS_GLOBAL) - return detail::IsWindowSlow(obj); - return false; -} - -/** - * Returns true iff `obj` has the WindowProxy Class (see SetWindowProxyClass). - */ -JS_FRIEND_API(bool) -IsWindowProxy(JSObject* obj); - -/** - * If `obj` is a Window, get its associated WindowProxy (or a CCW or dead - * wrapper if the page was navigated away from), else return `obj`. This - * function is infallible and never returns nullptr. - */ -extern JS_FRIEND_API(JSObject*) -ToWindowProxyIfWindow(JSObject* obj); - -/** - * If `obj` is a WindowProxy, get its associated Window (the compartment's - * global), else return `obj`. This function is infallible and never returns - * nullptr. - */ -extern JS_FRIEND_API(JSObject*) -ToWindowIfWindowProxy(JSObject* obj); - -} /* namespace js */ - -class NativeProfiler -{ - public: - virtual ~NativeProfiler() {}; - virtual void sampleNative(void* addr, uint32_t size) = 0; - virtual void removeNative(void* addr) = 0; - virtual void reset() = 0; -}; - -class GCHeapProfiler -{ - public: - virtual ~GCHeapProfiler() {}; - virtual void sampleTenured(void* addr, uint32_t size) = 0; - virtual void sampleNursery(void* addr, uint32_t size) = 0; - virtual void markTenuredStart() = 0; - virtual void markTenured(void* addr) = 0; - virtual void sweepTenured() = 0; - virtual void sweepNursery() = 0; - virtual void moveNurseryToTenured(void* addrOld, void* addrNew) = 0; - virtual void reset() = 0; -}; - -class MemProfiler -{ - static mozilla::Atomic sActiveProfilerCount; - static NativeProfiler* sNativeProfiler; - - static GCHeapProfiler* GetGCHeapProfiler(void* addr); - static GCHeapProfiler* GetGCHeapProfiler(JSRuntime* runtime); - - static NativeProfiler* GetNativeProfiler() { - return sNativeProfiler; - } - - GCHeapProfiler* mGCHeapProfiler; - JSRuntime* mRuntime; - - public: - explicit MemProfiler(JSRuntime* aRuntime) : mGCHeapProfiler(nullptr), mRuntime(aRuntime) {} - - void start(GCHeapProfiler* aGCHeapProfiler); - void stop(); - - GCHeapProfiler* getGCHeapProfiler() const { - return mGCHeapProfiler; - } - - static MOZ_ALWAYS_INLINE bool enabled() { - return sActiveProfilerCount > 0; - } - - static MemProfiler* GetMemProfiler(JSContext* context); - - static void SetNativeProfiler(NativeProfiler* aProfiler) { - sNativeProfiler = aProfiler; - } - - static MOZ_ALWAYS_INLINE void SampleNative(void* addr, uint32_t size) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - NativeProfiler* profiler = GetNativeProfiler(); - if (profiler) - profiler->sampleNative(addr, size); - } - - static MOZ_ALWAYS_INLINE void SampleTenured(void* addr, uint32_t size) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addr); - if (profiler) - profiler->sampleTenured(addr, size); - } - - static MOZ_ALWAYS_INLINE void SampleNursery(void* addr, uint32_t size) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addr); - if (profiler) - profiler->sampleNursery(addr, size); - } - - static MOZ_ALWAYS_INLINE void RemoveNative(void* addr) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - NativeProfiler* profiler = GetNativeProfiler(); - if (profiler) - profiler->removeNative(addr); - } - - static MOZ_ALWAYS_INLINE void MarkTenuredStart(JSRuntime* runtime) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(runtime); - if (profiler) - profiler->markTenuredStart(); - } - - static MOZ_ALWAYS_INLINE void MarkTenured(void* addr) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addr); - if (profiler) - profiler->markTenured(addr); - } - - static MOZ_ALWAYS_INLINE void SweepTenured(JSRuntime* runtime) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(runtime); - if (profiler) - profiler->sweepTenured(); - } - - static MOZ_ALWAYS_INLINE void SweepNursery(JSRuntime* runtime) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(runtime); - if (profiler) - profiler->sweepNursery(); - } - - static MOZ_ALWAYS_INLINE void MoveNurseryToTenured(void* addrOld, void* addrNew) { - JS::AutoSuppressGCAnalysis nogc; - - if (MOZ_LIKELY(!enabled())) - return; - - GCHeapProfiler* profiler = GetGCHeapProfiler(addrOld); - if (profiler) - profiler->moveNurseryToTenured(addrOld, addrNew); - } -}; - -#endif /* jsfriendapi_h */ diff --git a/win32/include/spidermonkey/jsperf.h b/win32/include/spidermonkey/jsperf.h deleted file mode 100755 index b8f2909a..00000000 --- a/win32/include/spidermonkey/jsperf.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef perf_jsperf_h -#define perf_jsperf_h - -#include "jstypes.h" - -#include "js/TypeDecls.h" -#include "js/Utility.h" - -namespace JS { - -/* - * JS::PerfMeasurement is a generic way to access detailed performance - * measurement APIs provided by your operating system. The details of - * exactly how this works and what can be measured are highly - * system-specific, but this interface is (one hopes) implementable - * on top of all of them. - * - * To use this API, create a PerfMeasurement object, passing its - * constructor a bitmask indicating which events you are interested - * in. Thereafter, Start() zeroes all counters and starts timing; - * Stop() stops timing again; and the counters for the events you - * requested are available as data values after calling Stop(). The - * object may be reused for many measurements. - */ -class JS_FRIEND_API(PerfMeasurement) -{ - protected: - // Implementation-specific data, if any. - void* impl; - - public: - /* - * Events that may be measured. Taken directly from the list of - * "generalized hardware performance event types" in the Linux - * perf_event API, plus some of the "software events". - */ - enum EventMask { - CPU_CYCLES = 0x00000001, - INSTRUCTIONS = 0x00000002, - CACHE_REFERENCES = 0x00000004, - CACHE_MISSES = 0x00000008, - BRANCH_INSTRUCTIONS = 0x00000010, - BRANCH_MISSES = 0x00000020, - BUS_CYCLES = 0x00000040, - PAGE_FAULTS = 0x00000080, - MAJOR_PAGE_FAULTS = 0x00000100, - CONTEXT_SWITCHES = 0x00000200, - CPU_MIGRATIONS = 0x00000400, - - ALL = 0x000007ff, - NUM_MEASURABLE_EVENTS = 11 - }; - - /* - * Bitmask of events that will be measured when this object is - * active (between Start() and Stop()). This may differ from the - * bitmask passed to the constructor if the platform does not - * support measuring all of the requested events. - */ - const EventMask eventsMeasured; - - /* - * Counters for each measurable event. - * Immediately after one of these objects is created, all of the - * counters for enabled events will be zero, and all of the - * counters for disabled events will be uint64_t(-1). - */ - uint64_t cpu_cycles; - uint64_t instructions; - uint64_t cache_references; - uint64_t cache_misses; - uint64_t branch_instructions; - uint64_t branch_misses; - uint64_t bus_cycles; - uint64_t page_faults; - uint64_t major_page_faults; - uint64_t context_switches; - uint64_t cpu_migrations; - - /* - * Prepare to measure the indicated set of events. If not all of - * the requested events can be measured on the current platform, - * then the eventsMeasured bitmask will only include the subset of - * |toMeasure| corresponding to the events that can be measured. - */ - explicit PerfMeasurement(EventMask toMeasure); - - /* Done with this set of measurements, tear down OS-level state. */ - ~PerfMeasurement(); - - /* Start a measurement cycle. */ - void start(); - - /* - * End a measurement cycle, and for each enabled counter, add the - * number of measured events of that type to the appropriate - * visible variable. - */ - void stop(); - - /* Reset all enabled counters to zero. */ - void reset(); - - /* - * True if this platform supports measuring _something_, i.e. it's - * not using the stub implementation. - */ - static bool canMeasureSomething(); -}; - -/* Inject a Javascript wrapper around the above C++ class into the - * Javascript object passed as an argument (this will normally be a - * global object). The JS-visible API is identical to the C++ API. - */ -extern JS_FRIEND_API(JSObject*) - RegisterPerfMeasurement(JSContext* cx, JS::HandleObject global); - -/* - * Given a Value which contains an instance of the aforementioned - * wrapper class, extract the C++ object. Returns nullptr if the - * Value is not an instance of the wrapper. - */ -extern JS_FRIEND_API(PerfMeasurement*) - ExtractPerfMeasurement(const Value& wrapper); - -} // namespace JS - -#endif /* perf_jsperf_h */ diff --git a/win32/include/spidermonkey/jsprf.h b/win32/include/spidermonkey/jsprf.h deleted file mode 100755 index b84b5a5c..00000000 --- a/win32/include/spidermonkey/jsprf.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsprf_h -#define jsprf_h - -/* -** API for PR printf like routines. Supports the following formats -** %d - decimal -** %u - unsigned decimal -** %x - unsigned hex -** %X - unsigned uppercase hex -** %o - unsigned octal -** %hd, %hu, %hx, %hX, %ho - "short" versions of above -** %ld, %lu, %lx, %lX, %lo - "long" versions of above -** %lld, %llu, %llx, %llX, %llo - "long long" versions of above -** %zd, %zo, %zu, %zx, %zX - size_t versions of above -** %Id, %Io, %Iu, %Ix, %IX - size_t versions of above (for Windows compat) -** You should use PRI*SIZE macros instead -** %s - string -** %c - character -** %p - pointer (deals with machine dependent pointer size) -** %f - float -** %g - float -*/ - -#include "mozilla/IntegerPrintfMacros.h" -#include "mozilla/SizePrintfMacros.h" - -#include - -#include "jstypes.h" - -/* -** sprintf into a malloc'd buffer. Return a pointer to the malloc'd -** buffer on success, nullptr on failure. Call "JS_smprintf_free" to release -** the memory returned. -*/ -extern JS_PUBLIC_API(char*) JS_smprintf(const char* fmt, ...) - MOZ_FORMAT_PRINTF(1, 2); - -/* -** Free the memory allocated, for the caller, by JS_smprintf -*/ -extern JS_PUBLIC_API(void) JS_smprintf_free(char* mem); - -/* -** "append" sprintf into a malloc'd buffer. "last" is the last value of -** the malloc'd buffer. sprintf will append data to the end of last, -** growing it as necessary using realloc. If last is nullptr, JS_sprintf_append -** will allocate the initial string. The return value is the new value of -** last for subsequent calls, or nullptr if there is a malloc failure. -*/ -extern JS_PUBLIC_API(char*) JS_sprintf_append(char* last, const char* fmt, ...) - MOZ_FORMAT_PRINTF(2, 3); - -/* -** va_list forms of the above. -*/ -extern JS_PUBLIC_API(char*) JS_vsmprintf(const char* fmt, va_list ap); -extern JS_PUBLIC_API(char*) JS_vsprintf_append(char* last, const char* fmt, va_list ap); - -#endif /* jsprf_h */ diff --git a/win32/include/spidermonkey/jsprototypes.h b/win32/include/spidermonkey/jsprototypes.h deleted file mode 100755 index f409dce9..00000000 --- a/win32/include/spidermonkey/jsprototypes.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsprototypes_h -#define jsprototypes_h - -/* A higher-order macro for enumerating all JSProtoKey values. */ -/* - * Consumers define macros as follows: - * macro(name, code, init, clasp) - * name: The canonical name of the class. - * code: The enumerator code. There are part of the XDR API, and must not change. - * init: Initialization function. These are |extern "C";|, and clients should use - * |extern "C" {}| as appropriate when using this macro. - * clasp: The JSClass for this object, or "dummy" if it doesn't exist. - * - * - * Consumers wishing to iterate over all the JSProtoKey values, can use - * JS_FOR_EACH_PROTOTYPE. However, there are certain values that don't correspond - * to real constructors, like Null or constructors that are disabled via - * preprocessor directives. We still need to include these in the JSProtoKey list - * in order to maintain binary XDR compatibility, but we need to provide a tool - * to handle them differently. JS_FOR_PROTOTYPES fills this niche. - * - * Consumers pass two macros to JS_FOR_PROTOTYPES - |real| and |imaginary|. The - * former is invoked for entries that have real client-exposed constructors, and - * the latter is called for the rest. Consumers that don't care about this - * distinction can simply pass the same macro to both, which is exactly what - * JS_FOR_EACH_PROTOTYPE does. - */ - -#define CLASP(name) (&name##Class) -#define OCLASP(name) (&name##Object::class_) -#define TYPED_ARRAY_CLASP(type) (&TypedArrayObject::classes[Scalar::type]) -#define ERROR_CLASP(type) (&ErrorObject::classes[type]) - -#ifdef EXPOSE_INTL_API -#define IF_INTL(real,imaginary) real -#else -#define IF_INTL(real,imaginary) imaginary -#endif - -#ifdef ENABLE_BINARYDATA -#define IF_BDATA(real,imaginary) real -#else -#define IF_BDATA(real,imaginary) imaginary -#endif - -#ifdef ENABLE_SIMD -# define IF_SIMD(real,imaginary) real -#else -# define IF_SIMD(real,imaginary) imaginary -#endif - -#ifdef ENABLE_SHARED_ARRAY_BUFFER -#define IF_SAB(real,imaginary) real -#else -#define IF_SAB(real,imaginary) imaginary -#endif - -#ifdef SPIDERMONKEY_PROMISE -#define IF_PROMISE(real,imaginary) real -#else -#define IF_PROMISE(real,imaginary) imaginary -#endif - -#define JS_FOR_PROTOTYPES(real,imaginary) \ - imaginary(Null, 0, InitNullClass, dummy) \ - real(Object, 1, InitViaClassSpec, OCLASP(Plain)) \ - real(Function, 2, InitViaClassSpec, &JSFunction::class_) \ - real(Array, 3, InitViaClassSpec, OCLASP(Array)) \ - real(Boolean, 4, InitBooleanClass, OCLASP(Boolean)) \ - real(JSON, 5, InitJSONClass, CLASP(JSON)) \ - real(Date, 6, InitViaClassSpec, OCLASP(Date)) \ - real(Math, 7, InitMathClass, CLASP(Math)) \ - real(Number, 8, InitNumberClass, OCLASP(Number)) \ - real(String, 9, InitStringClass, OCLASP(String)) \ - real(RegExp, 10, InitViaClassSpec, OCLASP(RegExp)) \ - real(Error, 11, InitViaClassSpec, ERROR_CLASP(JSEXN_ERR)) \ - real(InternalError, 12, InitViaClassSpec, ERROR_CLASP(JSEXN_INTERNALERR)) \ - real(EvalError, 13, InitViaClassSpec, ERROR_CLASP(JSEXN_EVALERR)) \ - real(RangeError, 14, InitViaClassSpec, ERROR_CLASP(JSEXN_RANGEERR)) \ - real(ReferenceError, 15, InitViaClassSpec, ERROR_CLASP(JSEXN_REFERENCEERR)) \ - real(SyntaxError, 16, InitViaClassSpec, ERROR_CLASP(JSEXN_SYNTAXERR)) \ - real(TypeError, 17, InitViaClassSpec, ERROR_CLASP(JSEXN_TYPEERR)) \ - real(URIError, 18, InitViaClassSpec, ERROR_CLASP(JSEXN_URIERR)) \ - real(DebuggeeWouldRun, 19, InitViaClassSpec, ERROR_CLASP(JSEXN_DEBUGGEEWOULDRUN)) \ - real(CompileError, 20, InitViaClassSpec, ERROR_CLASP(JSEXN_WASMCOMPILEERROR)) \ - real(RuntimeError, 21, InitViaClassSpec, ERROR_CLASP(JSEXN_WASMRUNTIMEERROR)) \ - real(Iterator, 22, InitLegacyIteratorClass,OCLASP(PropertyIterator)) \ - real(StopIteration, 23, InitStopIterationClass, OCLASP(StopIteration)) \ - real(ArrayBuffer, 24, InitViaClassSpec, OCLASP(ArrayBuffer)) \ - real(Int8Array, 25, InitViaClassSpec, TYPED_ARRAY_CLASP(Int8)) \ - real(Uint8Array, 26, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint8)) \ - real(Int16Array, 27, InitViaClassSpec, TYPED_ARRAY_CLASP(Int16)) \ - real(Uint16Array, 28, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint16)) \ - real(Int32Array, 29, InitViaClassSpec, TYPED_ARRAY_CLASP(Int32)) \ - real(Uint32Array, 30, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint32)) \ - real(Float32Array, 31, InitViaClassSpec, TYPED_ARRAY_CLASP(Float32)) \ - real(Float64Array, 32, InitViaClassSpec, TYPED_ARRAY_CLASP(Float64)) \ - real(Uint8ClampedArray, 33, InitViaClassSpec, TYPED_ARRAY_CLASP(Uint8Clamped)) \ - real(Proxy, 34, InitProxyClass, js::ProxyClassPtr) \ - real(WeakMap, 35, InitWeakMapClass, OCLASP(WeakMap)) \ - real(Map, 36, InitMapClass, OCLASP(Map)) \ - real(Set, 37, InitSetClass, OCLASP(Set)) \ - real(DataView, 38, InitDataViewClass, OCLASP(DataView)) \ - real(Symbol, 39, InitSymbolClass, OCLASP(Symbol)) \ -IF_SAB(real,imaginary)(SharedArrayBuffer, 40, InitViaClassSpec, OCLASP(SharedArrayBuffer)) \ -IF_INTL(real,imaginary) (Intl, 41, InitIntlClass, CLASP(Intl)) \ -IF_BDATA(real,imaginary)(TypedObject, 42, InitTypedObjectModuleObject, OCLASP(TypedObjectModule)) \ - real(Reflect, 43, InitReflect, nullptr) \ -IF_SIMD(real,imaginary)(SIMD, 44, InitSimdClass, OCLASP(Simd)) \ - real(WeakSet, 45, InitWeakSetClass, OCLASP(WeakSet)) \ - real(TypedArray, 46, InitViaClassSpec, &js::TypedArrayObject::sharedTypedArrayPrototypeClass) \ -IF_SAB(real,imaginary)(Atomics, 47, InitAtomicsClass, OCLASP(Atomics)) \ - real(SavedFrame, 48, InitViaClassSpec, &js::SavedFrame::class_) \ - real(WebAssembly, 49, InitWebAssemblyClass, CLASP(WebAssembly)) \ - imaginary(WasmModule, 50, dummy, dummy) \ - imaginary(WasmInstance, 51, dummy, dummy) \ - imaginary(WasmMemory, 52, dummy, dummy) \ - imaginary(WasmTable, 53, dummy, dummy) \ -IF_PROMISE(real,imaginary)(Promise, 54, InitViaClassSpec, OCLASP(Promise)) \ - -#define JS_FOR_EACH_PROTOTYPE(macro) JS_FOR_PROTOTYPES(macro,macro) - -#endif /* jsprototypes_h */ diff --git a/win32/include/spidermonkey/jspubtd.h b/win32/include/spidermonkey/jspubtd.h deleted file mode 100755 index 309b9d74..00000000 --- a/win32/include/spidermonkey/jspubtd.h +++ /dev/null @@ -1,476 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jspubtd_h -#define jspubtd_h - -/* - * JS public API typedefs. - */ - -#include "mozilla/Assertions.h" -#include "mozilla/EnumeratedArray.h" -#include "mozilla/LinkedList.h" -#include "mozilla/PodOperations.h" - -#include "jsprototypes.h" -#include "jstypes.h" - -#include "js/TraceKind.h" -#include "js/TypeDecls.h" - -#if defined(JS_GC_ZEAL) || defined(DEBUG) -# define JSGC_HASH_TABLE_CHECKS -#endif - -namespace JS { - -class AutoIdVector; -class CallArgs; - -template -class Rooted; - -class JS_FRIEND_API(CompileOptions); -class JS_FRIEND_API(ReadOnlyCompileOptions); -class JS_FRIEND_API(OwningCompileOptions); -class JS_FRIEND_API(TransitiveCompileOptions); -class JS_PUBLIC_API(CompartmentOptions); - -struct RootingContext; -class Value; -struct Zone; - -namespace shadow { -struct Runtime; -} // namespace shadow - -} // namespace JS - -namespace js { -class RootLists; -} // namespace js - -/* - * Run-time version enumeration. For compile-time version checking, please use - * the JS_HAS_* macros in jsversion.h, or use MOZJS_MAJOR_VERSION, - * MOZJS_MINOR_VERSION, MOZJS_PATCH_VERSION, and MOZJS_ALPHA definitions. - */ -enum JSVersion { - JSVERSION_ECMA_3 = 148, - JSVERSION_1_6 = 160, - JSVERSION_1_7 = 170, - JSVERSION_1_8 = 180, - JSVERSION_ECMA_5 = 185, - JSVERSION_DEFAULT = 0, - JSVERSION_UNKNOWN = -1, - JSVERSION_LATEST = JSVERSION_ECMA_5 -}; - -/* Result of typeof operator enumeration. */ -enum JSType { - JSTYPE_VOID, /* undefined */ - JSTYPE_OBJECT, /* object */ - JSTYPE_FUNCTION, /* function */ - JSTYPE_STRING, /* string */ - JSTYPE_NUMBER, /* number */ - JSTYPE_BOOLEAN, /* boolean */ - JSTYPE_NULL, /* null */ - JSTYPE_SYMBOL, /* symbol */ - JSTYPE_LIMIT -}; - -/* Dense index into cached prototypes and class atoms for standard objects. */ -enum JSProtoKey { -#define PROTOKEY_AND_INITIALIZER(name,code,init,clasp) JSProto_##name = code, - JS_FOR_EACH_PROTOTYPE(PROTOKEY_AND_INITIALIZER) -#undef PROTOKEY_AND_INITIALIZER - JSProto_LIMIT -}; - -/* Struct forward declarations. */ -struct JSClass; -struct JSCompartment; -struct JSCrossCompartmentCall; -class JSErrorReport; -struct JSExceptionState; -struct JSFunctionSpec; -struct JSLocaleCallbacks; -struct JSObjectMap; -struct JSPrincipals; -struct JSPropertyName; -struct JSPropertySpec; -struct JSRuntime; -struct JSSecurityCallbacks; -struct JSStructuredCloneCallbacks; -struct JSStructuredCloneReader; -struct JSStructuredCloneWriter; -class JS_PUBLIC_API(JSTracer); - -class JSFlatString; - -typedef bool (*JSInitCallback)(void); - -template struct JSConstScalarSpec; -typedef JSConstScalarSpec JSConstDoubleSpec; -typedef JSConstScalarSpec JSConstIntegerSpec; - -/* - * Generic trace operation that calls JS::TraceEdge on each traceable thing's - * location reachable from data. - */ -typedef void -(* JSTraceDataOp)(JSTracer* trc, void* data); - -namespace js { -namespace gc { -class AutoTraceSession; -class StoreBuffer; -} // namespace gc - -// Whether the current thread is permitted access to any part of the specified -// runtime or zone. -JS_FRIEND_API(bool) -CurrentThreadCanAccessRuntime(const JSRuntime* rt); - -#ifdef DEBUG -JS_FRIEND_API(bool) -CurrentThreadIsPerformingGC(); -#endif - -} // namespace js - -namespace JS { - -class JS_PUBLIC_API(AutoEnterCycleCollection); -class JS_PUBLIC_API(AutoAssertOnBarrier); -struct JS_PUBLIC_API(PropertyDescriptor); - -typedef void (*OffThreadCompileCallback)(void* token, void* callbackData); - -enum class HeapState { - Idle, // doing nothing with the GC heap - Tracing, // tracing the GC heap without collecting, e.g. IterateCompartments() - MajorCollecting, // doing a GC of the major heap - MinorCollecting, // doing a GC of the minor heap (nursery) - CycleCollecting // in the "Unlink" phase of cycle collection -}; - -namespace shadow { - -struct Runtime -{ - private: - JS::HeapState heapState_; - - protected: - void setHeapState(JS::HeapState newState) { - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(asRuntime())); - MOZ_ASSERT(heapState_ != newState); - heapState_ = newState; - } - - JS::HeapState heapState() const { - MOZ_ASSERT(js::CurrentThreadCanAccessRuntime(asRuntime()) || - js::CurrentThreadIsPerformingGC()); - return heapState_; - } - - // In some cases, invoking GC barriers (incremental or otherwise) will break - // things. These barriers assert if this flag is set. - bool allowGCBarriers_; - friend class JS::AutoAssertOnBarrier; - - js::gc::StoreBuffer* gcStoreBufferPtr_; - - // The gray bits can become invalid if UnmarkGray overflows the stack. A - // full GC will reset this bit, since it fills in all the gray bits. - bool gcGrayBitsValid_; - - public: - Runtime() - : heapState_(JS::HeapState::Idle) - , allowGCBarriers_(true) - , gcStoreBufferPtr_(nullptr) - , gcGrayBitsValid_(false) - {} - - bool isHeapBusy() const { return heapState() != JS::HeapState::Idle; } - bool isHeapTracing() const { return heapState() == JS::HeapState::Tracing; } - bool isHeapMajorCollecting() const { return heapState() == JS::HeapState::MajorCollecting; } - bool isHeapMinorCollecting() const { return heapState() == JS::HeapState::MinorCollecting; } - bool isHeapCollecting() const { return isHeapMinorCollecting() || isHeapMajorCollecting(); } - bool isCycleCollecting() const { - return heapState() == JS::HeapState::CycleCollecting; - } - - bool allowGCBarriers() const { return allowGCBarriers_; } - - js::gc::StoreBuffer* gcStoreBufferPtr() { return gcStoreBufferPtr_; } - - bool areGCGrayBitsValid() const { return gcGrayBitsValid_; } - void setGCGrayBitsValid(bool valid) { gcGrayBitsValid_ = valid; } - - const JSRuntime* asRuntime() const { - return reinterpret_cast(this); - } - - static JS::shadow::Runtime* asShadowRuntime(JSRuntime* rt) { - return reinterpret_cast(rt); - } - - protected: - void setGCStoreBufferPtr(js::gc::StoreBuffer* storeBuffer) { - gcStoreBufferPtr_ = storeBuffer; - } -}; - -} /* namespace shadow */ - -// Decorates the Unlinking phase of CycleCollection so that accidental use -// of barriered accessors results in assertions instead of leaks. -class MOZ_STACK_CLASS JS_PUBLIC_API(AutoEnterCycleCollection) -{ -#ifdef DEBUG - JSRuntime* runtime; - - public: - explicit AutoEnterCycleCollection(JSContext* cx); - ~AutoEnterCycleCollection(); -#else - public: - explicit AutoEnterCycleCollection(JSContext* cx) {} - ~AutoEnterCycleCollection() {} -#endif -}; - -class JS_PUBLIC_API(AutoGCRooter) -{ - public: - AutoGCRooter(JSContext* cx, ptrdiff_t tag); - AutoGCRooter(JS::RootingContext* cx, ptrdiff_t tag); - - ~AutoGCRooter() { - MOZ_ASSERT(this == *stackTop); - *stackTop = down; - } - - /* Implemented in gc/RootMarking.cpp. */ - inline void trace(JSTracer* trc); - static void traceAll(JSTracer* trc); - static void traceAllWrappers(JSTracer* trc); - - protected: - AutoGCRooter * const down; - - /* - * Discriminates actual subclass of this being used. If non-negative, the - * subclass roots an array of values of the length stored in this field. - * If negative, meaning is indicated by the corresponding value in the enum - * below. Any other negative value indicates some deeper problem such as - * memory corruption. - */ - ptrdiff_t tag_; - - enum { - VALARRAY = -2, /* js::AutoValueArray */ - PARSER = -3, /* js::frontend::Parser */ - VALVECTOR = -10, /* js::AutoValueVector */ - IDVECTOR = -11, /* js::AutoIdVector */ - OBJVECTOR = -14, /* js::AutoObjectVector */ - IONMASM = -19, /* js::jit::MacroAssembler */ - WRAPVECTOR = -20, /* js::AutoWrapperVector */ - WRAPPER = -21, /* js::AutoWrapperRooter */ - CUSTOM = -26 /* js::CustomAutoRooter */ - }; - - static ptrdiff_t GetTag(const Value& value) { return VALVECTOR; } - static ptrdiff_t GetTag(const jsid& id) { return IDVECTOR; } - static ptrdiff_t GetTag(JSObject* obj) { return OBJVECTOR; } - - private: - AutoGCRooter ** const stackTop; - - /* No copy or assignment semantics. */ - AutoGCRooter(AutoGCRooter& ida) = delete; - void operator=(AutoGCRooter& ida) = delete; -}; - -// Our instantiations of Rooted and PersistentRooted require an -// instantiation of MapTypeToRootKind. -template <> -struct MapTypeToRootKind { - static const RootKind kind = RootKind::Traceable; -}; - -} /* namespace JS */ - -namespace js { - -class ExclusiveContext; - -/* - * This list enumerates the different types of conceptual stacks we have in - * SpiderMonkey. In reality, they all share the C stack, but we allow different - * stack limits depending on the type of code running. - */ -enum StackKind -{ - StackForSystemCode, // C++, such as the GC, running on behalf of the VM. - StackForTrustedScript, // Script running with trusted principals. - StackForUntrustedScript, // Script running with untrusted principals. - StackKindCount -}; - -using RootedListHeads = mozilla::EnumeratedArray*>; - -// Abstracts JS rooting mechanisms so they can be shared between the JSContext -// and JSRuntime. -class RootLists -{ - // Stack GC roots for Rooted GC heap pointers. - RootedListHeads stackRoots_; - template friend class JS::Rooted; - - // Stack GC roots for AutoFooRooter classes. - JS::AutoGCRooter* autoGCRooters_; - friend class JS::AutoGCRooter; - - // Heap GC roots for PersistentRooted pointers. - mozilla::EnumeratedArray>> heapRoots_; - template friend class JS::PersistentRooted; - - public: - RootLists() : autoGCRooters_(nullptr) { - for (auto& stackRootPtr : stackRoots_) - stackRootPtr = nullptr; - } - - ~RootLists() { - // The semantics of PersistentRooted containing pointers and tagged - // pointers are somewhat different from those of PersistentRooted - // containing a structure with a trace method. PersistentRooted - // containing pointers are allowed to outlive the owning RootLists, - // whereas those containing a traceable structure are not. - // - // The purpose of this feature is to support lazy initialization of - // global references for the several places in Gecko that do not have - // access to a tighter context, but that still need to refer to GC - // pointers. For such pointers, FinishPersistentRootedChains ensures - // that the contained references are nulled out when the owning - // RootLists dies to prevent UAF errors. - // - // However, for RootKind::Traceable, we do not know the concrete type - // of the held thing, so we simply cannot do this without accruing - // extra overhead and complexity for all users for a case that is - // unlikely to ever be used in practice. For this reason, the following - // assertion disallows usage of PersistentRooted that - // outlives the RootLists. - MOZ_ASSERT(heapRoots_[JS::RootKind::Traceable].isEmpty()); - } - - void traceStackRoots(JSTracer* trc); - void checkNoGCRooters(); - - void tracePersistentRoots(JSTracer* trc); - void finishPersistentRoots(); -}; - -} // namespace js - -namespace JS { - -/* - * JS::RootingContext is a base class of ContextFriendFields and JSContext. - * This class can be used to let code construct a Rooted<> or PersistentRooted<> - * instance, without giving it full access to the JSContext. - */ -struct RootingContext -{ - js::RootLists roots; - -#ifdef DEBUG - // Whether the derived class is a JSContext or an ExclusiveContext. - bool isJSContext; -#endif - - explicit RootingContext(bool isJSContextArg) -#ifdef DEBUG - : isJSContext(isJSContextArg) -#endif - {} - - static RootingContext* get(JSContext* cx) { - return reinterpret_cast(cx); - } -}; - -} // namespace JS - -namespace js { - -struct ContextFriendFields : public JS::RootingContext -{ - protected: - /* The current compartment. */ - JSCompartment* compartment_; - - /* The current zone. */ - JS::Zone* zone_; - - public: - /* Limit pointer for checking native stack consumption. */ - uintptr_t nativeStackLimit[js::StackKindCount]; - - explicit ContextFriendFields(bool isJSContext); - - static const ContextFriendFields* get(const JSContext* cx) { - return reinterpret_cast(cx); - } - - static ContextFriendFields* get(JSContext* cx) { - return reinterpret_cast(cx); - } - - friend JSCompartment* GetContextCompartment(const JSContext* cx); - friend JS::Zone* GetContextZone(const JSContext* cx); - template friend class JS::Rooted; -}; - -/* - * Inlinable accessors for JSContext. - * - * - These must not be available on the more restricted superclasses of - * JSContext, so we can't simply define them on ContextFriendFields. - * - * - They're perfectly ordinary JSContext functionality, so ought to be - * usable without resorting to jsfriendapi.h, and when JSContext is an - * incomplete type. - */ -inline JSCompartment* -GetContextCompartment(const JSContext* cx) -{ - return ContextFriendFields::get(cx)->compartment_; -} - -inline JS::Zone* -GetContextZone(const JSContext* cx) -{ - return ContextFriendFields::get(cx)->zone_; -} - -} /* namespace js */ - -MOZ_BEGIN_EXTERN_C - -// Defined in NSPR prio.h. -typedef struct PRFileDesc PRFileDesc; - -MOZ_END_EXTERN_C - -#endif /* jspubtd_h */ diff --git a/win32/include/spidermonkey/jstypes.h b/win32/include/spidermonkey/jstypes.h deleted file mode 100755 index 914674ab..00000000 --- a/win32/include/spidermonkey/jstypes.h +++ /dev/null @@ -1,219 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: jstypes.h -** Description: Definitions of NSPR's basic types -** -** Prototypes and macros used to make up for deficiencies in ANSI environments -** that we have found. -** -** Since we do not wrap and all the other standard headers, authors -** of portable code will not know in general that they need these definitions. -** Instead of requiring these authors to find the dependent uses in their code -** and take the following steps only in those C files, we take steps once here -** for all C files. -**/ - -#ifndef jstypes_h -#define jstypes_h - -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/Types.h" - -// jstypes.h is (or should be!) included by every file in SpiderMonkey. -// js-config.h and jsversion.h also should be included by every file. -// So include them here. -// XXX: including them in js/RequiredDefines.h should be a better option, since -// that is by definition the header file that should be included in all -// SpiderMonkey code. However, Gecko doesn't do this! See bug 909576. -#include "js-config.h" -#include "jsversion.h" - -/*********************************************************************** -** MACROS: JS_EXTERN_API -** JS_EXPORT_API -** DESCRIPTION: -** These are only for externally visible routines and globals. For -** internal routines, just use "extern" for type checking and that -** will not export internal cross-file or forward-declared symbols. -** Define a macro for declaring procedures return types. We use this to -** deal with windoze specific type hackery for DLL definitions. Use -** JS_EXTERN_API when the prototype for the method is declared. Use -** JS_EXPORT_API for the implementation of the method. -** -** Example: -** in dowhim.h -** JS_EXTERN_API( void ) DoWhatIMean( void ); -** in dowhim.c -** JS_EXPORT_API( void ) DoWhatIMean( void ) { return; } -** -** -***********************************************************************/ - -#define JS_EXTERN_API(type) extern MOZ_EXPORT type -#define JS_EXPORT_API(type) MOZ_EXPORT type -#define JS_EXPORT_DATA(type) MOZ_EXPORT type -#define JS_IMPORT_API(type) MOZ_IMPORT_API type -#define JS_IMPORT_DATA(type) MOZ_IMPORT_DATA type - -/* - * The linkage of JS API functions differs depending on whether the file is - * used within the JS library or not. Any source file within the JS - * interpreter should define EXPORT_JS_API whereas any client of the library - * should not. STATIC_JS_API is used to build JS as a static library. - */ -#if defined(STATIC_JS_API) -# define JS_PUBLIC_API(t) t -# define JS_PUBLIC_DATA(t) t -# define JS_FRIEND_API(t) t -# define JS_FRIEND_DATA(t) t -#elif defined(EXPORT_JS_API) || defined(STATIC_EXPORTABLE_JS_API) -# define JS_PUBLIC_API(t) MOZ_EXPORT t -# define JS_PUBLIC_DATA(t) MOZ_EXPORT t -# define JS_FRIEND_API(t) MOZ_EXPORT t -# define JS_FRIEND_DATA(t) MOZ_EXPORT t -#else -# define JS_PUBLIC_API(t) MOZ_IMPORT_API t -# define JS_PUBLIC_DATA(t) MOZ_IMPORT_DATA t -# define JS_FRIEND_API(t) MOZ_IMPORT_API t -# define JS_FRIEND_DATA(t) MOZ_IMPORT_DATA t -#endif - -#if defined(_MSC_VER) && defined(_M_IX86) -#define JS_FASTCALL __fastcall -#elif defined(__GNUC__) && defined(__i386__) -#define JS_FASTCALL __attribute__((fastcall)) -#else -#define JS_FASTCALL -#define JS_NO_FASTCALL -#endif - -/*********************************************************************** -** MACROS: JS_BEGIN_MACRO -** JS_END_MACRO -** DESCRIPTION: -** Macro body brackets so that macros with compound statement definitions -** behave syntactically more like functions when called. -***********************************************************************/ -#define JS_BEGIN_MACRO do { - -#if defined(_MSC_VER) -# define JS_END_MACRO \ - } __pragma(warning(push)) __pragma(warning(disable:4127)) \ - while (0) __pragma(warning(pop)) -#else -# define JS_END_MACRO } while (0) -#endif - -/*********************************************************************** -** MACROS: JS_BIT -** JS_BITMASK -** DESCRIPTION: -** Bit masking macros. XXX n must be <= 31 to be portable -***********************************************************************/ -#define JS_BIT(n) ((uint32_t)1 << (n)) -#define JS_BITMASK(n) (JS_BIT(n) - 1) - -/*********************************************************************** -** MACROS: JS_HOWMANY -** JS_ROUNDUP -** DESCRIPTION: -** Commonly used macros for operations on compatible types. -***********************************************************************/ -#define JS_HOWMANY(x,y) (((x)+(y)-1)/(y)) -#define JS_ROUNDUP(x,y) (JS_HOWMANY(x,y)*(y)) - -#include "jscpucfg.h" - -/* - * Define JS_64BIT iff we are building in an environment with 64-bit - * addresses. - */ -#ifdef _MSC_VER -# if defined(_M_X64) || defined(_M_AMD64) -# define JS_64BIT -# endif -#elif defined(__GNUC__) -/* Additional GCC defines are when running on Solaris, AIX, and HPUX */ -# if defined(__x86_64__) || defined(__sparcv9) || \ - defined(__64BIT__) || defined(__LP64__) -# define JS_64BIT -# endif -#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Sun Studio C/C++ */ -# if defined(__x86_64) || defined(__sparcv9) -# define JS_64BIT -# endif -#elif defined(__xlc__) || defined(__xlC__) /* IBM XL C/C++ */ -# if defined(__64BIT__) -# define JS_64BIT -# endif -#elif defined(__HP_cc) || defined(__HP_aCC) /* HP-UX cc/aCC */ -# if defined(__LP64__) -# define JS_64BIT -# endif -#else -# error "Implement me" -#endif - -/*********************************************************************** -** MACROS: JS_ARRAY_LENGTH -** JS_ARRAY_END -** DESCRIPTION: -** Macros to get the number of elements and the pointer to one past the -** last element of a C array. Use them like this: -** -** char16_t buf[10]; -** JSString* str; -** ... -** for (char16_t* s = buf; s != JS_ARRAY_END(buf); ++s) *s = ...; -** ... -** str = JS_NewStringCopyN(cx, buf, JS_ARRAY_LENGTH(buf)); -** ... -** -***********************************************************************/ - -#define JS_ARRAY_LENGTH(array) (sizeof (array) / sizeof (array)[0]) -#define JS_ARRAY_END(array) ((array) + JS_ARRAY_LENGTH(array)) - -#define JS_BITS_PER_BYTE 8 -#define JS_BITS_PER_BYTE_LOG2 3 - -#if defined(JS_64BIT) -# define JS_BITS_PER_WORD 64 -#else -# define JS_BITS_PER_WORD 32 -#endif - -/*********************************************************************** -** MACROS: JS_FUNC_TO_DATA_PTR -** JS_DATA_TO_FUNC_PTR -** DESCRIPTION: -** Macros to convert between function and data pointers of the same -** size. Use them like this: -** -** JSGetterOp nativeGetter; -** JSObject* scriptedGetter; -** ... -** scriptedGetter = JS_FUNC_TO_DATA_PTR(JSObject*, nativeGetter); -** ... -** nativeGetter = JS_DATA_TO_FUNC_PTR(JSGetterOp, scriptedGetter); -** -***********************************************************************/ - -#define JS_FUNC_TO_DATA_PTR(type, fun) (mozilla::BitwiseCast(fun)) -#define JS_DATA_TO_FUNC_PTR(type, ptr) (mozilla::BitwiseCast(ptr)) - -#ifdef __GNUC__ -# define JS_EXTENSION __extension__ -# define JS_EXTENSION_(s) __extension__ ({ s; }) -#else -# define JS_EXTENSION -# define JS_EXTENSION_(s) s -#endif - -#endif /* jstypes_h */ diff --git a/win32/include/spidermonkey/jsversion.h b/win32/include/spidermonkey/jsversion.h deleted file mode 100755 index 8bdfe47b..00000000 --- a/win32/include/spidermonkey/jsversion.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jsversion_h -#define jsversion_h - -/* - * JS Capability Macros. - */ -#define JS_HAS_STR_HTML_HELPERS 1 /* (no longer used) */ -#define JS_HAS_OBJ_PROTO_PROP 1 /* has o.__proto__ etc. */ -#define JS_HAS_OBJ_WATCHPOINT 1 /* has o.watch and o.unwatch */ -#define JS_HAS_TOSOURCE 1 /* has Object/Array toSource method */ -#define JS_HAS_CATCH_GUARD 1 /* has exception handling catch guard */ -#define JS_HAS_UNEVAL 1 /* has uneval() top-level function */ -#define JS_HAS_CONST 1 /* (no longer used) */ -#define JS_HAS_FUN_EXPR_STMT 1 /* (no longer used) */ -#define JS_HAS_FOR_EACH_IN 1 /* has for each (lhs in iterable) */ -#define JS_HAS_GENERATORS 1 /* (no longer used) */ -#define JS_HAS_BLOCK_SCOPE 1 /* (no longer used) */ -#define JS_HAS_DESTRUCTURING 2 /* (no longer used) */ -#define JS_HAS_GENERATOR_EXPRS 1 /* (no longer used) */ -#define JS_HAS_EXPR_CLOSURES 1 /* has function (formals) listexpr */ - -/* (no longer used) */ -#define JS_HAS_NEW_GLOBAL_OBJECT 1 - -/* (no longer used) */ -#define JS_HAS_DESTRUCTURING_SHORTHAND (JS_HAS_DESTRUCTURING == 2) - -/* - * Feature for Object.prototype.__{define,lookup}{G,S}etter__ legacy support; - * support likely to be made opt-in at some future time. - */ -#define JS_OLD_GETTER_SETTER_METHODS 1 - -#endif /* jsversion_h */ diff --git a/win32/include/spidermonkey/jswrapper.h b/win32/include/spidermonkey/jswrapper.h deleted file mode 100755 index 9b14c59e..00000000 --- a/win32/include/spidermonkey/jswrapper.h +++ /dev/null @@ -1,382 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef jswrapper_h -#define jswrapper_h - -#include "mozilla/Attributes.h" - -#include "js/Proxy.h" - -namespace js { - -/* - * Helper for Wrapper::New default options. - * - * Callers of Wrapper::New() who wish to specify a prototype for the created - * Wrapper, *MUST* construct a WrapperOptions with a JSContext. - */ -class MOZ_STACK_CLASS WrapperOptions : public ProxyOptions { - public: - WrapperOptions() : ProxyOptions(false), - proto_() - {} - - explicit WrapperOptions(JSContext* cx) : ProxyOptions(false), - proto_() - { - proto_.emplace(cx); - } - - inline JSObject* proto() const; - WrapperOptions& setProto(JSObject* protoArg) { - MOZ_ASSERT(proto_); - *proto_ = protoArg; - return *this; - } - - private: - mozilla::Maybe proto_; -}; - -/* - * A wrapper is a proxy with a target object to which it generally forwards - * operations, but may restrict access to certain operations or augment those - * operations in various ways. - * - * A wrapper can be "unwrapped" in C++, exposing the underlying object. - * Callers should be careful to avoid unwrapping security wrappers in the wrong - * context. - * - * Important: If you add a method implementation here, you probably also need - * to add an override in CrossCompartmentWrapper. If you don't, you risk - * compartment mismatches. See bug 945826 comment 0. - */ -class JS_FRIEND_API(Wrapper) : public BaseProxyHandler -{ - unsigned mFlags; - - public: - explicit constexpr Wrapper(unsigned aFlags, bool aHasPrototype = false, - bool aHasSecurityPolicy = false) - : BaseProxyHandler(&family, aHasPrototype, aHasSecurityPolicy), - mFlags(aFlags) - { } - - virtual bool finalizeInBackground(const Value& priv) const override; - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const override; - virtual bool defineProperty(JSContext* cx, HandleObject proxy, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const override; - virtual bool delete_(JSContext* cx, HandleObject proxy, HandleId id, - ObjectOpResult& result) const override; - virtual bool enumerate(JSContext* cx, HandleObject proxy, - MutableHandleObject objp) const override; - virtual bool getPrototype(JSContext* cx, HandleObject proxy, - MutableHandleObject protop) const override; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const override; - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, - MutableHandleObject protop) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, - bool* succeeded) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject proxy, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject proxy, bool* extensible) const override; - virtual bool has(JSContext* cx, HandleObject proxy, HandleId id, - bool* bp) const override; - virtual bool get(JSContext* cx, HandleObject proxy, HandleValue receiver, - HandleId id, MutableHandleValue vp) const override; - virtual bool set(JSContext* cx, HandleObject proxy, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const override; - virtual bool call(JSContext* cx, HandleObject proxy, const CallArgs& args) const override; - virtual bool construct(JSContext* cx, HandleObject proxy, const CallArgs& args) const override; - - /* SpiderMonkey extensions. */ - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, - MutableHandle desc) const override; - virtual bool hasOwn(JSContext* cx, HandleObject proxy, HandleId id, - bool* bp) const override; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject proxy, - AutoIdVector& props) const override; - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const override; - virtual bool hasInstance(JSContext* cx, HandleObject proxy, MutableHandleValue v, - bool* bp) const override; - virtual bool getBuiltinClass(JSContext* cx, HandleObject proxy, ESClass* cls) const override; - virtual bool isArray(JSContext* cx, HandleObject proxy, - JS::IsArrayAnswer* answer) const override; - virtual const char* className(JSContext* cx, HandleObject proxy) const override; - virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, - unsigned indent) const override; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, - RegExpGuard* g) const override; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, - MutableHandleValue vp) const override; - virtual bool isCallable(JSObject* obj) const override; - virtual bool isConstructor(JSObject* obj) const override; - virtual JSObject* weakmapKeyDelegate(JSObject* proxy) const override; - - public: - using BaseProxyHandler::Action; - - enum Flags { - CROSS_COMPARTMENT = 1 << 0, - LAST_USED_FLAG = CROSS_COMPARTMENT - }; - - static JSObject* New(JSContext* cx, JSObject* obj, const Wrapper* handler, - const WrapperOptions& options = WrapperOptions()); - - static JSObject* Renew(JSContext* cx, JSObject* existing, JSObject* obj, const Wrapper* handler); - - static const Wrapper* wrapperHandler(JSObject* wrapper); - - static JSObject* wrappedObject(JSObject* wrapper); - - unsigned flags() const { - return mFlags; - } - - static const char family; - static const Wrapper singleton; - static const Wrapper singletonWithPrototype; - - static JSObject* defaultProto; -}; - -inline JSObject* -WrapperOptions::proto() const -{ - return proto_ ? *proto_ : Wrapper::defaultProto; -} - -/* Base class for all cross compartment wrapper handlers. */ -class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper -{ - public: - explicit constexpr CrossCompartmentWrapper(unsigned aFlags, bool aHasPrototype = false, - bool aHasSecurityPolicy = false) - : Wrapper(CROSS_COMPARTMENT | aFlags, aHasPrototype, aHasSecurityPolicy) - { } - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool delete_(JSContext* cx, HandleObject wrapper, HandleId id, - ObjectOpResult& result) const override; - virtual bool enumerate(JSContext* cx, HandleObject wrapper, MutableHandleObject objp) const override; - virtual bool getPrototype(JSContext* cx, HandleObject proxy, - MutableHandleObject protop) const override; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const override; - - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, - MutableHandleObject protop) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, - bool* succeeded) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; - virtual bool has(JSContext* cx, HandleObject wrapper, HandleId id, bool* bp) const override; - virtual bool get(JSContext* cx, HandleObject wrapper, HandleValue receiver, - HandleId id, MutableHandleValue vp) const override; - virtual bool set(JSContext* cx, HandleObject wrapper, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const override; - virtual bool call(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - virtual bool construct(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - - /* SpiderMonkey extensions. */ - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool hasOwn(JSContext* cx, HandleObject wrapper, HandleId id, bool* bp) const override; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const override; - virtual bool hasInstance(JSContext* cx, HandleObject wrapper, MutableHandleValue v, - bool* bp) const override; - virtual const char* className(JSContext* cx, HandleObject proxy) const override; - virtual JSString* fun_toString(JSContext* cx, HandleObject wrapper, - unsigned indent) const override; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const override; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const override; - - // Allocate CrossCompartmentWrappers in the nursery. - virtual bool canNurseryAllocate() const override { return true; } - - static const CrossCompartmentWrapper singleton; - static const CrossCompartmentWrapper singletonWithPrototype; -}; - -class JS_FRIEND_API(OpaqueCrossCompartmentWrapper) : public CrossCompartmentWrapper -{ - public: - explicit constexpr OpaqueCrossCompartmentWrapper() : CrossCompartmentWrapper(0) - { } - - /* Standard internal methods. */ - virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool ownPropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool delete_(JSContext* cx, HandleObject wrapper, HandleId id, - ObjectOpResult& result) const override; - virtual bool enumerate(JSContext* cx, HandleObject wrapper, - MutableHandleObject objp) const override; - virtual bool getPrototype(JSContext* cx, HandleObject wrapper, - MutableHandleObject protop) const override; - virtual bool setPrototype(JSContext* cx, HandleObject wrapper, HandleObject proto, - ObjectOpResult& result) const override; - virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject wrapper, bool* isOrdinary, - MutableHandleObject protop) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject wrapper, - bool* succeeded) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; - virtual bool has(JSContext* cx, HandleObject wrapper, HandleId id, - bool* bp) const override; - virtual bool get(JSContext* cx, HandleObject wrapper, HandleValue receiver, - HandleId id, MutableHandleValue vp) const override; - virtual bool set(JSContext* cx, HandleObject wrapper, HandleId id, HandleValue v, - HandleValue receiver, ObjectOpResult& result) const override; - virtual bool call(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - virtual bool construct(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; - - /* SpiderMonkey extensions. */ - virtual bool getPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, - MutableHandle desc) const override; - virtual bool hasOwn(JSContext* cx, HandleObject wrapper, HandleId id, - bool* bp) const override; - virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject wrapper, - AutoIdVector& props) const override; - virtual bool getBuiltinClass(JSContext* cx, HandleObject wrapper, ESClass* cls) const override; - virtual bool isArray(JSContext* cx, HandleObject obj, - JS::IsArrayAnswer* answer) const override; - virtual const char* className(JSContext* cx, HandleObject wrapper) const override; - virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, unsigned indent) const override; - - static const OpaqueCrossCompartmentWrapper singleton; -}; - -/* - * Base class for security wrappers. A security wrapper is potentially hiding - * all or part of some wrapped object thus SecurityWrapper defaults to denying - * access to the wrappee. This is the opposite of Wrapper which tries to be - * completely transparent. - * - * NB: Currently, only a few ProxyHandler operations are overridden to deny - * access, relying on derived SecurityWrapper to block access when necessary. - */ -template -class JS_FRIEND_API(SecurityWrapper) : public Base -{ - public: - explicit constexpr SecurityWrapper(unsigned flags, bool hasPrototype = false) - : Base(flags, hasPrototype, /* hasSecurityPolicy = */ true) - { } - - virtual bool enter(JSContext* cx, HandleObject wrapper, HandleId id, Wrapper::Action act, - bool* bp) const override; - - virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, - Handle desc, - ObjectOpResult& result) const override; - virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; - virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, - ObjectOpResult& result) const override; - virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, - ObjectOpResult& result) const override; - virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, bool* succeeded) const override; - - virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, - const CallArgs& args) const override; - virtual bool getBuiltinClass(JSContext* cx, HandleObject wrapper, ESClass* cls) const override; - virtual bool isArray(JSContext* cx, HandleObject wrapper, JS::IsArrayAnswer* answer) const override; - virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const override; - virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const override; - - // Allow isCallable and isConstructor. They used to be class-level, and so could not be guarded - // against. - - virtual bool watch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, - JS::HandleObject callable) const override; - virtual bool unwatch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id) const override; - - /* - * Allow our subclasses to select the superclass behavior they want without - * needing to specify an exact superclass. - */ - typedef Base Permissive; - typedef SecurityWrapper Restrictive; -}; - -typedef SecurityWrapper CrossCompartmentSecurityWrapper; - -extern JSObject* -TransparentObjectWrapper(JSContext* cx, HandleObject existing, HandleObject obj); - -inline bool -IsWrapper(JSObject* obj) -{ - return IsProxy(obj) && GetProxyHandler(obj)->family() == &Wrapper::family; -} - -// Given a JSObject, returns that object stripped of wrappers. If -// stopAtWindowProxy is true, then this returns the WindowProxy if it was -// previously wrapped. Otherwise, this returns the first object for -// which JSObject::isWrapper returns false. -JS_FRIEND_API(JSObject*) -UncheckedUnwrap(JSObject* obj, bool stopAtWindowProxy = true, unsigned* flagsp = nullptr); - -// Given a JSObject, returns that object stripped of wrappers. At each stage, -// the security wrapper has the opportunity to veto the unwrap. If -// stopAtWindowProxy is true, then this returns the WindowProxy if it was -// previously wrapped. -JS_FRIEND_API(JSObject*) -CheckedUnwrap(JSObject* obj, bool stopAtWindowProxy = true); - -// Unwrap only the outermost security wrapper, with the same semantics as -// above. This is the checked version of Wrapper::wrappedObject. -JS_FRIEND_API(JSObject*) -UnwrapOneChecked(JSObject* obj, bool stopAtWindowProxy = true); - -JS_FRIEND_API(bool) -IsCrossCompartmentWrapper(JSObject* obj); - -void -NukeCrossCompartmentWrapper(JSContext* cx, JSObject* wrapper); - -void -RemapWrapper(JSContext* cx, JSObject* wobj, JSObject* newTarget); - -JS_FRIEND_API(bool) -RemapAllWrappersForObject(JSContext* cx, JSObject* oldTarget, - JSObject* newTarget); - -// API to recompute all cross-compartment wrappers whose source and target -// match the given filters. -JS_FRIEND_API(bool) -RecomputeWrappers(JSContext* cx, const CompartmentFilter& sourceFilter, - const CompartmentFilter& targetFilter); - -} /* namespace js */ - -#endif /* jswrapper_h */ diff --git a/win32/include/spidermonkey/mozilla/Alignment.h b/win32/include/spidermonkey/mozilla/Alignment.h deleted file mode 100755 index 4fcda4f3..00000000 --- a/win32/include/spidermonkey/mozilla/Alignment.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Functionality related to memory alignment. */ - -#ifndef mozilla_Alignment_h -#define mozilla_Alignment_h - -#include "mozilla/Attributes.h" -#include -#include - -namespace mozilla { - -/* - * This class, and the corresponding macro MOZ_ALIGNOF, figures out how many - * bytes of alignment a given type needs. - */ -template -class AlignmentFinder -{ - struct Aligner - { - char mChar; - T mT; - }; - -public: - static const size_t alignment = sizeof(Aligner) - sizeof(T); -}; - -#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment - -/* - * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. - * - * For instance, - * - * MOZ_ALIGNED_DECL(char arr[2], 8); - * - * will declare a two-character array |arr| aligned to 8 bytes. - */ - -#if defined(__GNUC__) -# define MOZ_ALIGNED_DECL(_type, _align) \ - _type __attribute__((aligned(_align))) -#elif defined(_MSC_VER) -# define MOZ_ALIGNED_DECL(_type, _align) \ - __declspec(align(_align)) _type -#else -# warning "We don't know how to align variables on this compiler." -# define MOZ_ALIGNED_DECL(_type, _align) _type -#endif - -/* - * AlignedElem is a structure whose alignment is guaranteed to be at least N - * bytes. - * - * We support 1, 2, 4, 8, and 16-bit alignment. - */ -template -struct AlignedElem; - -/* - * We have to specialize this template because GCC doesn't like - * __attribute__((aligned(foo))) where foo is a template parameter. - */ - -template<> -struct AlignedElem<1> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 1); -}; - -template<> -struct AlignedElem<2> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 2); -}; - -template<> -struct AlignedElem<4> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 4); -}; - -template<> -struct AlignedElem<8> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 8); -}; - -template<> -struct AlignedElem<16> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 16); -}; - -/* - * This utility pales in comparison to Boost's aligned_storage. The utility - * simply assumes that uint64_t is enough alignment for anyone. This may need - * to be extended one day... - * - * As an important side effect, pulling the storage into this template is - * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving - * false negatives when we cast from the char buffer to whatever type we've - * constructed using the bytes. - */ -template -struct AlignedStorage -{ - union U - { - char mBytes[Nbytes]; - uint64_t mDummy; - } u; - - const void* addr() const { return u.mBytes; } - void* addr() { return u.mBytes; } - - AlignedStorage() = default; - - // AlignedStorage is non-copyable: the default copy constructor violates - // strict aliasing rules, per bug 1269319. - AlignedStorage(const AlignedStorage&) = delete; - void operator=(const AlignedStorage&) = delete; -}; - -template -struct MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS AlignedStorage2 -{ - union U - { - char mBytes[sizeof(T)]; - uint64_t mDummy; - } u; - - const T* addr() const { return reinterpret_cast(u.mBytes); } - T* addr() { return static_cast(static_cast(u.mBytes)); } - - AlignedStorage2() = default; - - // AlignedStorage2 is non-copyable: the default copy constructor violates - // strict aliasing rules, per bug 1269319. - AlignedStorage2(const AlignedStorage2&) = delete; - void operator=(const AlignedStorage2&) = delete; -}; - -} /* namespace mozilla */ - -#endif /* mozilla_Alignment_h */ diff --git a/win32/include/spidermonkey/mozilla/AllocPolicy.h b/win32/include/spidermonkey/mozilla/AllocPolicy.h deleted file mode 100755 index 81f62b03..00000000 --- a/win32/include/spidermonkey/mozilla/AllocPolicy.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * An allocation policy concept, usable for structures and algorithms to - * control how memory is allocated and how failures are handled. - */ - -#ifndef mozilla_AllocPolicy_h -#define mozilla_AllocPolicy_h - -#include "mozilla/Attributes.h" -#include "mozilla/TemplateLib.h" - -#include -#include - -namespace mozilla { - -/* - * Allocation policies are used to implement the standard allocation behaviors - * in a customizable way. Additionally, custom behaviors may be added to these - * behaviors, such as additionally reporting an error through an out-of-band - * mechanism when OOM occurs. The concept modeled here is as follows: - * - * - public copy constructor, assignment, destructor - * - template T* maybe_pod_malloc(size_t) - * Fallible, but doesn't report an error on OOM. - * - template T* maybe_pod_calloc(size_t) - * Fallible, but doesn't report an error on OOM. - * - template T* maybe_pod_realloc(T*, size_t, size_t) - * Fallible, but doesn't report an error on OOM. The old allocation - * size is passed in, in addition to the new allocation size requested. - * - template T* pod_malloc(size_t) - * Responsible for OOM reporting when null is returned. - * - template T* pod_calloc(size_t) - * Responsible for OOM reporting when null is returned. - * - template T* pod_realloc(T*, size_t, size_t) - * Responsible for OOM reporting when null is returned. The old allocation - * size is passed in, in addition to the new allocation size requested. - * - void free_(void*) - * - void reportAllocOverflow() const - * Called on allocation overflow (that is, an allocation implicitly tried - * to allocate more than the available memory space -- think allocating an - * array of large-size objects, where N * size overflows) before null is - * returned. - * - bool checkSimulatedOOM() const - * Some clients generally allocate memory yet in some circumstances won't - * need to do so. For example, appending to a vector with a small amount of - * inline storage generally allocates memory, but no allocation occurs - * unless appending exceeds inline storage. But for testing purposes, it - * can be useful to treat *every* operation as allocating. - * Clients (such as this hypothetical append method implementation) should - * call this method in situations that don't allocate, but could generally, - * to support this. The default behavior should return true; more - * complicated behavior might be to return false only after a certain - * number of allocations-or-check-simulated-OOMs (coordinating with the - * other AllocPolicy methods) have occurred. - * - * mfbt provides (and typically uses by default) only MallocAllocPolicy, which - * does nothing more than delegate to the malloc/alloc/free functions. - */ - -/* - * A policy that straightforwardly uses malloc/calloc/realloc/free and adds no - * extra behaviors. - */ -class MallocAllocPolicy -{ -public: - template - T* maybe_pod_malloc(size_t aNumElems) - { - if (aNumElems & mozilla::tl::MulOverflowMask::value) { - return nullptr; - } - return static_cast(malloc(aNumElems * sizeof(T))); - } - - template - T* maybe_pod_calloc(size_t aNumElems) - { - return static_cast(calloc(aNumElems, sizeof(T))); - } - - template - T* maybe_pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - if (aNewSize & mozilla::tl::MulOverflowMask::value) { - return nullptr; - } - return static_cast(realloc(aPtr, aNewSize * sizeof(T))); - } - - template - T* pod_malloc(size_t aNumElems) - { - return maybe_pod_malloc(aNumElems); - } - - template - T* pod_calloc(size_t aNumElems) - { - return maybe_pod_calloc(aNumElems); - } - - template - T* pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - return maybe_pod_realloc(aPtr, aOldSize, aNewSize); - } - - void free_(void* aPtr) - { - free(aPtr); - } - - void reportAllocOverflow() const - { - } - - MOZ_MUST_USE bool checkSimulatedOOM() const - { - return true; - } -}; - -} // namespace mozilla - -#endif /* mozilla_AllocPolicy_h */ diff --git a/win32/include/spidermonkey/mozilla/AlreadyAddRefed.h b/win32/include/spidermonkey/mozilla/AlreadyAddRefed.h deleted file mode 100755 index 0d7b0cae..00000000 --- a/win32/include/spidermonkey/mozilla/AlreadyAddRefed.h +++ /dev/null @@ -1,147 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Typed temporary pointers for reference-counted smart pointers. */ - -#ifndef AlreadyAddRefed_h -#define AlreadyAddRefed_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" - -namespace mozilla { - -struct unused_t; - -} // namespace mozilla - -/** - * already_AddRefed cooperates with reference counting smart pointers to enable - * you to assign in a pointer _without_ |AddRef|ing it. You might want to use - * this as a return type from a function that returns an already |AddRef|ed - * pointer. - * - * TODO Move already_AddRefed to namespace mozilla. This has not yet been done - * because of the sheer number of usages of already_AddRefed. - */ -template -struct MOZ_MUST_USE_TYPE MOZ_NON_AUTOABLE already_AddRefed -{ - /* - * We want to allow returning nullptr from functions returning - * already_AddRefed, for simplicity. But we also don't want to allow - * returning raw T*, instead preferring creation of already_AddRefed from - * a reference counting smart pointer. - * - * We address the latter requirement by making the (T*) constructor explicit. - * But |return nullptr| won't consider an explicit constructor, so we need - * another constructor to handle it. Plain old (decltype(nullptr)) doesn't - * cut it, because if nullptr is emulated as __null (with type int or long), - * passing nullptr to an int/long parameter triggers compiler warnings. We - * need a type that no one can pass accidentally; a pointer-to-member-function - * (where no such function exists) does the trick nicely. - * - * That handles the return-value case. What about for locals, argument types, - * and so on? |already_AddRefed(nullptr)| considers both overloads (and - * the (already_AddRefed&&) overload as well!), so there's an ambiguity. - * We can target true nullptr using decltype(nullptr), but we can't target - * emulated nullptr the same way, because passing __null to an int/long - * parameter triggers compiler warnings. So just give up on this, and provide - * this behavior through the default constructor. - * - * We can revert to simply explicit (T*) and implicit (decltype(nullptr)) when - * nullptr no longer needs to be emulated to support the ancient b2g compiler. - * (The () overload could also be removed, if desired, if we changed callers.) - */ - already_AddRefed() : mRawPtr(nullptr) {} - - // The return and argument types here are arbitrarily selected so no - // corresponding member function exists. - typedef void (already_AddRefed::* MatchNullptr)(double, float); - MOZ_IMPLICIT already_AddRefed(MatchNullptr aRawPtr) : mRawPtr(nullptr) {} - - explicit already_AddRefed(T* aRawPtr) : mRawPtr(aRawPtr) {} - - // Disallow copy constructor and copy assignment operator: move semantics used instead. - already_AddRefed(const already_AddRefed& aOther) = delete; - already_AddRefed& operator=(const already_AddRefed& aOther) = delete; - - already_AddRefed(already_AddRefed&& aOther) : mRawPtr(aOther.take()) {} - - already_AddRefed& operator=(already_AddRefed&& aOther) - { - mRawPtr = aOther.take(); - return *this; - } - - /** - * This helper is useful in cases like - * - * already_AddRefed - * Foo() - * { - * RefPtr x = ...; - * return x.forget(); - * } - * - * The autoconversion allows one to omit the idiom - * - * RefPtr y = x.forget(); - * return y.forget(); - * - * Note that nsRefPtr is the XPCOM reference counting smart pointer class. - */ - template - MOZ_IMPLICIT already_AddRefed(already_AddRefed&& aOther) : mRawPtr(aOther.take()) {} - - ~already_AddRefed() { MOZ_ASSERT(!mRawPtr); } - - // Specialize the unused operator<< for already_AddRefed, to allow - // nsCOMPtr foo; - // Unused << foo.forget(); - // Note that nsCOMPtr is the XPCOM reference counting smart pointer class. - friend void operator<<(const mozilla::unused_t& aUnused, - const already_AddRefed& aRhs) - { - auto mutableAlreadyAddRefed = const_cast*>(&aRhs); - aUnused << mutableAlreadyAddRefed->take(); - } - - MOZ_MUST_USE T* take() - { - T* rawPtr = mRawPtr; - mRawPtr = nullptr; - return rawPtr; - } - - /** - * This helper provides a static_cast replacement for already_AddRefed, so - * if you have - * - * already_AddRefed F(); - * - * you can write - * - * already_AddRefed - * G() - * { - * return F().downcast(); - * } - */ - template - already_AddRefed downcast() - { - U* tmp = static_cast(mRawPtr); - mRawPtr = nullptr; - return already_AddRefed(tmp); - } - -private: - T* MOZ_OWNING_REF mRawPtr; -}; - -#endif // AlreadyAddRefed_h diff --git a/win32/include/spidermonkey/mozilla/Array.h b/win32/include/spidermonkey/mozilla/Array.h deleted file mode 100755 index 72b89ede..00000000 --- a/win32/include/spidermonkey/mozilla/Array.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A compile-time constant-length array with bounds-checking assertions. */ - -#ifndef mozilla_Array_h -#define mozilla_Array_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/ReverseIterator.h" - -#include - -namespace mozilla { - -template -class Array -{ - T mArr[Length]; - -public: - Array() {} - - template - MOZ_IMPLICIT Array(Args&&... aArgs) - : mArr{mozilla::Forward(aArgs)...} - { - static_assert(sizeof...(aArgs) == Length, - "The number of arguments should be equal to the template parameter Length"); - } - - T& operator[](size_t aIndex) - { - MOZ_ASSERT(aIndex < Length); - return mArr[aIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(aIndex < Length); - return mArr[aIndex]; - } - - typedef T* iterator; - typedef const T* const_iterator; - typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; - - // Methods for range-based for loops. - iterator begin() { return mArr; } - const_iterator begin() const { return mArr; } - const_iterator cbegin() const { return begin(); } - iterator end() { return mArr + Length; } - const_iterator end() const { return mArr + Length; } - const_iterator cend() const { return end(); } - - // Methods for reverse iterating. - reverse_iterator rbegin() { return reverse_iterator(end()); } - const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() { return reverse_iterator(begin()); } - const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } - const_reverse_iterator crend() const { return rend(); } -}; - -template -class Array -{ -public: - T& operator[](size_t aIndex) - { - MOZ_CRASH("indexing into zero-length array"); - } - - const T& operator[](size_t aIndex) const - { - MOZ_CRASH("indexing into zero-length array"); - } -}; - -} /* namespace mozilla */ - -#endif /* mozilla_Array_h */ diff --git a/win32/include/spidermonkey/mozilla/ArrayUtils.h b/win32/include/spidermonkey/mozilla/ArrayUtils.h deleted file mode 100755 index 50236ccb..00000000 --- a/win32/include/spidermonkey/mozilla/ArrayUtils.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements various helper functions related to arrays. - */ - -#ifndef mozilla_ArrayUtils_h -#define mozilla_ArrayUtils_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#include - -#ifdef __cplusplus - -#include "mozilla/Alignment.h" -#include "mozilla/Array.h" -#include "mozilla/EnumeratedArray.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/* - * Safely subtract two pointers when it is known that aEnd >= aBegin, yielding a - * size_t result. - * - * Ordinary pointer subtraction yields a ptrdiff_t result, which, being signed, - * has insufficient range to express the distance between pointers at opposite - * ends of the address space. Furthermore, most compilers use ptrdiff_t to - * represent the intermediate byte address distance, before dividing by - * sizeof(T); if that intermediate result overflows, they'll produce results - * with the wrong sign even when the correct scaled distance would fit in a - * ptrdiff_t. - */ -template -MOZ_ALWAYS_INLINE size_t -PointerRangeSize(T* aBegin, T* aEnd) -{ - MOZ_ASSERT(aEnd >= aBegin); - return (size_t(aEnd) - size_t(aBegin)) / sizeof(T); -} - -/* - * Compute the length of an array with constant length. (Use of this method - * with a non-array pointer will not compile.) - * - * Beware of the implicit trailing '\0' when using this with string constants. - */ -template -constexpr size_t -ArrayLength(T (&aArr)[N]) -{ - return N; -} - -template -constexpr size_t -ArrayLength(const Array& aArr) -{ - return N; -} - -template -constexpr size_t -ArrayLength(const EnumeratedArray& aArr) -{ - return size_t(N); -} - -/* - * Compute the address one past the last element of a constant-length array. - * - * Beware of the implicit trailing '\0' when using this with string constants. - */ -template -constexpr T* -ArrayEnd(T (&aArr)[N]) -{ - return aArr + ArrayLength(aArr); -} - -template -constexpr T* -ArrayEnd(Array& aArr) -{ - return &aArr[0] + ArrayLength(aArr); -} - -template -constexpr const T* -ArrayEnd(const Array& aArr) -{ - return &aArr[0] + ArrayLength(aArr); -} - -namespace detail { - -template::value>> -struct AlignedChecker -{ - static void - test(const Pointee* aPtr) - { - MOZ_ASSERT((uintptr_t(aPtr) % MOZ_ALIGNOF(AlignType)) == 0, - "performing a range-check with a misaligned pointer"); - } -}; - -template -struct AlignedChecker -{ - static void - test(const Pointee* aPtr) - { - } -}; - -} // namespace detail - -/** - * Determines whether |aPtr| points at an object in the range [aBegin, aEnd). - * - * |aPtr| must have the same alignment as |aBegin| and |aEnd|. This usually - * should be achieved by ensuring |aPtr| points at a |U|, not just that it - * points at a |T|. - * - * It is a usage error for any argument to be misaligned. - * - * It's okay for T* to be void*, and if so U* may also be void*. In the latter - * case no argument is required to be aligned (obviously, as void* implies no - * particular alignment). - */ -template -inline typename EnableIf::value || - IsBaseOf::value || - IsVoid::value, - bool>::Type -IsInRange(const T* aPtr, const U* aBegin, const U* aEnd) -{ - MOZ_ASSERT(aBegin <= aEnd); - detail::AlignedChecker::test(aPtr); - detail::AlignedChecker::test(aBegin); - detail::AlignedChecker::test(aEnd); - return aBegin <= reinterpret_cast(aPtr) && - reinterpret_cast(aPtr) < aEnd; -} - -/** - * Convenience version of the above method when the valid range is specified as - * uintptr_t values. As above, |aPtr| must be aligned, and |aBegin| and |aEnd| - * must be aligned with respect to |T|. - */ -template -inline bool -IsInRange(const T* aPtr, uintptr_t aBegin, uintptr_t aEnd) -{ - return IsInRange(aPtr, - reinterpret_cast(aBegin), - reinterpret_cast(aEnd)); -} - -namespace detail { - -/* - * Helper for the MOZ_ARRAY_LENGTH() macro to make the length a typesafe - * compile-time constant even on compilers lacking constexpr support. - */ -template -char (&ArrayLengthHelper(T (&array)[N]))[N]; - -} /* namespace detail */ - -} /* namespace mozilla */ - -#endif /* __cplusplus */ - -/* - * MOZ_ARRAY_LENGTH() is an alternative to mozilla::ArrayLength() for C files - * that can't use C++ template functions and for static_assert() calls that - * can't call ArrayLength() when it is not a C++11 constexpr function. - */ -#ifdef __cplusplus -# define MOZ_ARRAY_LENGTH(array) sizeof(mozilla::detail::ArrayLengthHelper(array)) -#else -# define MOZ_ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0])) -#endif - -#endif /* mozilla_ArrayUtils_h */ diff --git a/win32/include/spidermonkey/mozilla/Assertions.h b/win32/include/spidermonkey/mozilla/Assertions.h deleted file mode 100755 index e978af3d..00000000 --- a/win32/include/spidermonkey/mozilla/Assertions.h +++ /dev/null @@ -1,585 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implementations of runtime and static assertion macros for C and C++. */ - -#ifndef mozilla_Assertions_h -#define mozilla_Assertions_h - -#if defined(MOZILLA_INTERNAL_API) && defined(__cplusplus) -#define MOZ_DUMP_ASSERTION_STACK -#endif - -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/Likely.h" -#include "mozilla/MacroArgs.h" -#include "mozilla/StaticAnalysisFunctions.h" -#include "mozilla/Types.h" -#ifdef MOZ_DUMP_ASSERTION_STACK -#include "nsTraceRefcnt.h" -#endif - -#if defined(MOZ_HAS_MOZGLUE) || defined(MOZILLA_INTERNAL_API) -/* - * The crash reason set by MOZ_CRASH_ANNOTATE is consumed by the crash reporter - * if present. It is declared here (and defined in Assertions.cpp) to make it - * available to all code, even libraries that don't link with the crash reporter - * directly. - */ -MOZ_BEGIN_EXTERN_C -extern MFBT_DATA const char* gMozCrashReason; -MOZ_END_EXTERN_C - -static inline void -AnnotateMozCrashReason(const char* reason) -{ - gMozCrashReason = reason; -} -# define MOZ_CRASH_ANNOTATE(...) AnnotateMozCrashReason(__VA_ARGS__) -#else -# define MOZ_CRASH_ANNOTATE(...) do { /* nothing */ } while (0) -#endif - -#include -#include -#include -#ifdef WIN32 - /* - * TerminateProcess and GetCurrentProcess are defined in , which - * further depends on . We hardcode these few definitions manually - * because those headers clutter the global namespace with a significant - * number of undesired macros and symbols. - */ -# ifdef __cplusplus -extern "C" { -# endif -__declspec(dllimport) int __stdcall -TerminateProcess(void* hProcess, unsigned int uExitCode); -__declspec(dllimport) void* __stdcall GetCurrentProcess(void); -# ifdef __cplusplus -} -# endif -#else -# include -#endif -#ifdef ANDROID -# include -#endif - -/* - * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time* in C. - * In C++11, static_assert is provided by the compiler to the same effect. - * This can be useful when you make certain assumptions about what must hold for - * optimal, or even correct, behavior. For example, you might assert that the - * size of a struct is a multiple of the target architecture's word size: - * - * struct S { ... }; - * // C - * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0, - * "S should be a multiple of word size for efficiency"); - * // C++11 - * static_assert(sizeof(S) % sizeof(size_t) == 0, - * "S should be a multiple of word size for efficiency"); - * - * This macro can be used in any location where both an extern declaration and a - * typedef could be used. - */ -#ifndef __cplusplus - /* - * Some of the definitions below create an otherwise-unused typedef. This - * triggers compiler warnings with some versions of gcc, so mark the typedefs - * as permissibly-unused to disable the warnings. - */ -# if defined(__GNUC__) -# define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused)) -# else -# define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */ -# endif -# define MOZ_STATIC_ASSERT_GLUE1(x, y) x##y -# define MOZ_STATIC_ASSERT_GLUE(x, y) MOZ_STATIC_ASSERT_GLUE1(x, y) -# if defined(__SUNPRO_CC) - /* - * The Sun Studio C++ compiler is buggy when declaring, inside a function, - * another extern'd function with an array argument whose length contains a - * sizeof, triggering the error message "sizeof expression not accepted as - * size of array parameter". This bug (6688515, not public yet) would hit - * defining moz_static_assert as a function, so we always define an extern - * array for Sun Studio. - * - * We include the line number in the symbol name in a best-effort attempt - * to avoid conflicts (see below). - */ -# define MOZ_STATIC_ASSERT(cond, reason) \ - extern char MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)[(cond) ? 1 : -1] -# elif defined(__COUNTER__) - /* - * If there was no preferred alternative, use a compiler-agnostic version. - * - * Note that the non-__COUNTER__ version has a bug in C++: it can't be used - * in both |extern "C"| and normal C++ in the same translation unit. (Alas - * |extern "C"| isn't allowed in a function.) The only affected compiler - * we really care about is gcc 4.2. For that compiler and others like it, - * we include the line number in the function name to do the best we can to - * avoid conflicts. These should be rare: a conflict would require use of - * MOZ_STATIC_ASSERT on the same line in separate files in the same - * translation unit, *and* the uses would have to be in code with - * different linkage, *and* the first observed use must be in C++-linkage - * code. - */ -# define MOZ_STATIC_ASSERT(cond, reason) \ - typedef int MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __COUNTER__)[(cond) ? 1 : -1] MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE -# else -# define MOZ_STATIC_ASSERT(cond, reason) \ - extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE -# endif - -#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason) -#else -#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) static_assert(!(cond) || (expr), reason) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Prints |aStr| as an assertion failure (using aFilename and aLine as the - * location of the assertion) to the standard debug-output channel. - * - * Usually you should use MOZ_ASSERT or MOZ_CRASH instead of this method. This - * method is primarily for internal use in this header, and only secondarily - * for use in implementing release-build assertions. - */ -static MOZ_COLD MOZ_ALWAYS_INLINE void -MOZ_ReportAssertionFailure(const char* aStr, const char* aFilename, int aLine) - MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS -{ -#ifdef ANDROID - __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert", - "Assertion failure: %s, at %s:%d\n", - aStr, aFilename, aLine); -#else - fprintf(stderr, "Assertion failure: %s, at %s:%d\n", aStr, aFilename, aLine); -#if defined (MOZ_DUMP_ASSERTION_STACK) - nsTraceRefcnt::WalkTheStack(stderr); -#endif - fflush(stderr); -#endif -} - -static MOZ_COLD MOZ_ALWAYS_INLINE void -MOZ_ReportCrash(const char* aStr, const char* aFilename, int aLine) - MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS -{ -#ifdef ANDROID - __android_log_print(ANDROID_LOG_FATAL, "MOZ_CRASH", - "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine); -#else - fprintf(stderr, "Hit MOZ_CRASH(%s) at %s:%d\n", aStr, aFilename, aLine); -#if defined(MOZ_DUMP_ASSERTION_STACK) - nsTraceRefcnt::WalkTheStack(stderr); -#endif - fflush(stderr); -#endif -} - -/** - * MOZ_REALLY_CRASH is used in the implementation of MOZ_CRASH(). You should - * call MOZ_CRASH instead. - */ -#if defined(_MSC_VER) - /* - * On MSVC use the __debugbreak compiler intrinsic, which produces an inline - * (not nested in a system function) breakpoint. This distinctively invokes - * Breakpad without requiring system library symbols on all stack-processing - * machines, as a nested breakpoint would require. - * - * We use TerminateProcess with the exit code aborting would generate - * because we don't want to invoke atexit handlers, destructors, library - * unload handlers, and so on when our process might be in a compromised - * state. - * - * We don't use abort() because it'd cause Windows to annoyingly pop up the - * process error dialog multiple times. See bug 345118 and bug 426163. - * - * We follow TerminateProcess() with a call to MOZ_NoReturn() so that the - * compiler doesn't hassle us to provide a return statement after a - * MOZ_REALLY_CRASH() call. - * - * (Technically these are Windows requirements, not MSVC requirements. But - * practically you need MSVC for debugging, and we only ship builds created - * by MSVC, so doing it this way reduces complexity.) - */ - -__declspec(noreturn) __inline void MOZ_NoReturn() {} - -# ifdef __cplusplus -# define MOZ_REALLY_CRASH() \ - do { \ - ::__debugbreak(); \ - *((volatile int*) NULL) = __LINE__; \ - ::TerminateProcess(::GetCurrentProcess(), 3); \ - ::MOZ_NoReturn(); \ - } while (0) -# else -# define MOZ_REALLY_CRASH() \ - do { \ - __debugbreak(); \ - *((volatile int*) NULL) = __LINE__; \ - TerminateProcess(GetCurrentProcess(), 3); \ - MOZ_NoReturn(); \ - } while (0) -# endif -#else -# ifdef __cplusplus -# define MOZ_REALLY_CRASH() \ - do { \ - *((volatile int*) NULL) = __LINE__; \ - ::abort(); \ - } while (0) -# else -# define MOZ_REALLY_CRASH() \ - do { \ - *((volatile int*) NULL) = __LINE__; \ - abort(); \ - } while (0) -# endif -#endif - -/* - * MOZ_CRASH([explanation-string]) crashes the program, plain and simple, in a - * Breakpad-compatible way, in both debug and release builds. - * - * MOZ_CRASH is a good solution for "handling" failure cases when you're - * unwilling or unable to handle them more cleanly -- for OOM, for likely memory - * corruption, and so on. It's also a good solution if you need safe behavior - * in release builds as well as debug builds. But if the failure is one that - * should be debugged and fixed, MOZ_ASSERT is generally preferable. - * - * The optional explanation-string, if provided, must be a string literal - * explaining why we're crashing. This argument is intended for use with - * MOZ_CRASH() calls whose rationale is non-obvious; don't use it if it's - * obvious why we're crashing. - * - * If we're a DEBUG build and we crash at a MOZ_CRASH which provides an - * explanation-string, we print the string to stderr. Otherwise, we don't - * print anything; this is because we want MOZ_CRASH to be 100% safe in release - * builds, and it's hard to print to stderr safely when memory might have been - * corrupted. - */ -#ifndef DEBUG -# define MOZ_CRASH(...) \ - do { \ - MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \ - MOZ_REALLY_CRASH(); \ - } while (0) -#else -# define MOZ_CRASH(...) \ - do { \ - MOZ_ReportCrash("" __VA_ARGS__, __FILE__, __LINE__); \ - MOZ_CRASH_ANNOTATE("MOZ_CRASH(" __VA_ARGS__ ")"); \ - MOZ_REALLY_CRASH(); \ - } while (0) -#endif - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -/* - * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in - * debug builds. If it is, execution continues. Otherwise, an error message - * including the expression and the explanation-string (if provided) is printed, - * an attempt is made to invoke any existing debugger, and execution halts. - * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition - * which can correctly be falsy. - * - * The optional explanation-string, if provided, must be a string literal - * explaining the assertion. It is intended for use with assertions whose - * correctness or rationale is non-obvious, and for assertions where the "real" - * condition being tested is best described prosaically. Don't provide an - * explanation if it's not actually helpful. - * - * // No explanation needed: pointer arguments often must not be NULL. - * MOZ_ASSERT(arg); - * - * // An explanation can be helpful to explain exactly how we know an - * // assertion is valid. - * MOZ_ASSERT(state == WAITING_FOR_RESPONSE, - * "given that and , we must have..."); - * - * // Or it might disambiguate multiple identical (save for their location) - * // assertions of the same expression. - * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(), - * "we already set [[PrimitiveThis]] for this Boolean object"); - * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(), - * "we already set [[PrimitiveThis]] for this String object"); - * - * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs - * *only* during debugging, not "in the field". If you want the latter, use - * MOZ_RELEASE_ASSERT, which applies to non-debug builds as well. - * - * MOZ_DIAGNOSTIC_ASSERT works like MOZ_RELEASE_ASSERT in Nightly/Aurora and - * MOZ_ASSERT in Beta/Release - use this when a condition is potentially rare - * enough to require real user testing to hit, but is not security-sensitive. - * This can cause user pain, so use it sparingly. If a MOZ_DIAGNOSTIC_ASSERT - * is firing, it should promptly be converted to a MOZ_ASSERT while the failure - * is being investigated, rather than letting users suffer. - */ - -/* - * Implement MOZ_VALIDATE_ASSERT_CONDITION_TYPE, which is used to guard against - * accidentally passing something unintended in lieu of an assertion condition. - */ - -#ifdef __cplusplus -# include "mozilla/TypeTraits.h" -namespace mozilla { -namespace detail { - -template -struct AssertionConditionType -{ - typedef typename RemoveReference::Type ValueT; - static_assert(!IsArray::value, - "Expected boolean assertion condition, got an array or a " - "string!"); - static_assert(!IsFunction::value, - "Expected boolean assertion condition, got a function! Did " - "you intend to call that function?"); - static_assert(!IsFloatingPoint::value, - "It's often a bad idea to assert that a floating-point number " - "is nonzero, because such assertions tend to intermittently " - "fail. Shouldn't your code gracefully handle this case instead " - "of asserting? Anyway, if you really want to do that, write an " - "explicit boolean condition, like !!x or x!=0."); - - static const bool isValid = true; -}; - -} // namespace detail -} // namespace mozilla -# define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) \ - static_assert(mozilla::detail::AssertionConditionType::isValid, \ - "invalid assertion condition") -#else -# define MOZ_VALIDATE_ASSERT_CONDITION_TYPE(x) -#endif - -/* First the single-argument form. */ -#define MOZ_ASSERT_HELPER1(expr) \ - do { \ - MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \ - if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \ - MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \ - MOZ_CRASH_ANNOTATE("MOZ_RELEASE_ASSERT(" #expr ")"); \ - MOZ_REALLY_CRASH(); \ - } \ - } while (0) -/* Now the two-argument form. */ -#define MOZ_ASSERT_HELPER2(expr, explain) \ - do { \ - MOZ_VALIDATE_ASSERT_CONDITION_TYPE(expr); \ - if (MOZ_UNLIKELY(!MOZ_CHECK_ASSERT_ASSIGNMENT(expr))) { \ - MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \ - MOZ_CRASH_ANNOTATE("MOZ_RELEASE_ASSERT(" #expr ") (" explain ")"); \ - MOZ_REALLY_CRASH(); \ - } \ - } while (0) - -#define MOZ_RELEASE_ASSERT_GLUE(a, b) a b -#define MOZ_RELEASE_ASSERT(...) \ - MOZ_RELEASE_ASSERT_GLUE( \ - MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_ASSERT_HELPER, __VA_ARGS__), \ - (__VA_ARGS__)) - -#ifdef DEBUG -# define MOZ_ASSERT(...) MOZ_RELEASE_ASSERT(__VA_ARGS__) -#else -# define MOZ_ASSERT(...) do { } while (0) -#endif /* DEBUG */ - -#ifdef RELEASE_OR_BETA -# define MOZ_DIAGNOSTIC_ASSERT MOZ_ASSERT -#else -# define MOZ_DIAGNOSTIC_ASSERT MOZ_RELEASE_ASSERT -#endif - -/* - * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is - * true. - * - * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num)); - * - * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is - * designed to catch bugs during debugging, not "in the field". - */ -#ifdef DEBUG -# define MOZ_ASSERT_IF(cond, expr) \ - do { \ - if (cond) { \ - MOZ_ASSERT(expr); \ - } \ - } while (0) -#else -# define MOZ_ASSERT_IF(cond, expr) do { } while (0) -#endif - -/* - * MOZ_ASSUME_UNREACHABLE_MARKER() expands to an expression which states that - * it is undefined behavior for execution to reach this point. No guarantees - * are made about what will happen if this is reached at runtime. Most code - * should use MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE because it has extra - * asserts. - */ -#if defined(__clang__) || defined(__GNUC__) -# define MOZ_ASSUME_UNREACHABLE_MARKER() __builtin_unreachable() -#elif defined(_MSC_VER) -# define MOZ_ASSUME_UNREACHABLE_MARKER() __assume(0) -#else -# ifdef __cplusplus -# define MOZ_ASSUME_UNREACHABLE_MARKER() ::abort() -# else -# define MOZ_ASSUME_UNREACHABLE_MARKER() abort() -# endif -#endif - -/* - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE([reason]) tells the compiler that it - * can assume that the macro call cannot be reached during execution. This lets - * the compiler generate better-optimized code under some circumstances, at the - * expense of the program's behavior being undefined if control reaches the - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE. - * - * In Gecko, you probably should not use this macro outside of performance- or - * size-critical code, because it's unsafe. If you don't care about code size - * or performance, you should probably use MOZ_ASSERT or MOZ_CRASH. - * - * SpiderMonkey is a different beast, and there it's acceptable to use - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE more widely. - * - * Note that MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE is noreturn, so it's valid - * not to return a value following a MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE - * call. - * - * Example usage: - * - * enum ValueType { - * VALUE_STRING, - * VALUE_INT, - * VALUE_FLOAT - * }; - * - * int ptrToInt(ValueType type, void* value) { - * { - * // We know for sure that type is either INT or FLOAT, and we want this - * // code to run as quickly as possible. - * switch (type) { - * case VALUE_INT: - * return *(int*) value; - * case VALUE_FLOAT: - * return (int) *(float*) value; - * default: - * MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected ValueType"); - * } - * } - */ - -/* - * Unconditional assert in debug builds for (assumed) unreachable code paths - * that have a safe return without crashing in release builds. - */ -#define MOZ_ASSERT_UNREACHABLE(reason) \ - MOZ_ASSERT(false, "MOZ_ASSERT_UNREACHABLE: " reason) - -#define MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(reason) \ - do { \ - MOZ_ASSERT_UNREACHABLE(reason); \ - MOZ_ASSUME_UNREACHABLE_MARKER(); \ - } while (0) - -/** - * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about - * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in - * debug builds, but intentionally fall through in release builds to handle - * unexpected values. - * - * Why do we need MOZ_FALLTHROUGH_ASSERT in addition to MOZ_FALLTHROUGH? In - * release builds, the MOZ_ASSERT(false) will expand to `do { } while (0)`, - * requiring a MOZ_FALLTHROUGH annotation to suppress a -Wimplicit-fallthrough - * warning. In debug builds, the MOZ_ASSERT(false) will expand to something like - * `if (true) { MOZ_CRASH(); }` and the MOZ_FALLTHROUGH annotation will cause - * a -Wunreachable-code warning. The MOZ_FALLTHROUGH_ASSERT macro breaks this - * warning stalemate. - * - * // Example before MOZ_FALLTHROUGH_ASSERT: - * switch (foo) { - * default: - * // This case wants to assert in debug builds, fall through in release. - * MOZ_ASSERT(false); // -Wimplicit-fallthrough warning in release builds! - * MOZ_FALLTHROUGH; // but -Wunreachable-code warning in debug builds! - * case 5: - * return 5; - * } - * - * // Example with MOZ_FALLTHROUGH_ASSERT: - * switch (foo) { - * default: - * // This case asserts in debug builds, falls through in release. - * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!"); - * case 5: - * return 5; - * } - */ -#ifdef DEBUG -# define MOZ_FALLTHROUGH_ASSERT(reason) MOZ_CRASH("MOZ_FALLTHROUGH_ASSERT: " reason) -#else -# define MOZ_FALLTHROUGH_ASSERT(...) MOZ_FALLTHROUGH -#endif - -/* - * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided - * expression, in debug builds and in release builds both. Then, in debug - * builds only, the value of the expression is asserted either true or false - * using MOZ_ASSERT. - */ -#ifdef DEBUG -# define MOZ_ALWAYS_TRUE(expr) \ - do { \ - if ((expr)) { \ - /* Do nothing. */ \ - } else { \ - MOZ_ASSERT(false, #expr); \ - } \ - } while (0) -# define MOZ_ALWAYS_FALSE(expr) \ - do { \ - if ((expr)) { \ - MOZ_ASSERT(false, #expr); \ - } else { \ - /* Do nothing. */ \ - } \ - } while (0) -#else -# define MOZ_ALWAYS_TRUE(expr) \ - do { \ - if ((expr)) { \ - /* Silence MOZ_MUST_USE. */ \ - } \ - } while (0) -# define MOZ_ALWAYS_FALSE(expr) \ - do { \ - if ((expr)) { \ - /* Silence MOZ_MUST_USE. */ \ - } \ - } while (0) -#endif - -#undef MOZ_DUMP_ASSERTION_STACK -#undef MOZ_CRASH_CRASHREPORT - -#endif /* mozilla_Assertions_h */ diff --git a/win32/include/spidermonkey/mozilla/Atomics.h b/win32/include/spidermonkey/mozilla/Atomics.h deleted file mode 100755 index 213d1b9f..00000000 --- a/win32/include/spidermonkey/mozilla/Atomics.h +++ /dev/null @@ -1,800 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements (almost always) lock-free atomic operations. The operations here - * are a subset of that which can be found in C++11's header, with a - * different API to enforce consistent memory ordering constraints. - * - * Anyone caught using |volatile| for inter-thread memory safety needs to be - * sent a copy of this header and the C++11 standard. - */ - -#ifndef mozilla_Atomics_h -#define mozilla_Atomics_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/TypeTraits.h" - -#include - -/* - * Our minimum deployment target on clang/OS X is OS X 10.6, whose SDK - * does not have . So be sure to check for support - * along with C++0x support. - */ -#if defined(_MSC_VER) -# define MOZ_HAVE_CXX11_ATOMICS -#elif defined(__clang__) || defined(__GNUC__) - /* - * Clang doesn't like from libstdc++ before 4.7 due to the - * loose typing of the atomic builtins. GCC 4.5 and 4.6 lacks inline - * definitions for unspecialized std::atomic and causes linking errors. - * Therefore, we require at least 4.7.0 for using libstdc++. - * - * libc++ is only functional with clang. - */ -# if MOZ_USING_LIBSTDCXX && MOZ_LIBSTDCXX_VERSION_AT_LEAST(4, 7, 0) -# define MOZ_HAVE_CXX11_ATOMICS -# elif MOZ_USING_LIBCXX && defined(__clang__) -# define MOZ_HAVE_CXX11_ATOMICS -# endif -#endif - -namespace mozilla { - -/** - * An enum of memory ordering possibilities for atomics. - * - * Memory ordering is the observable state of distinct values in memory. - * (It's a separate concept from atomicity, which concerns whether an - * operation can ever be observed in an intermediate state. Don't - * conflate the two!) Given a sequence of operations in source code on - * memory, it is *not* always the case that, at all times and on all - * cores, those operations will appear to have occurred in that exact - * sequence. First, the compiler might reorder that sequence, if it - * thinks another ordering will be more efficient. Second, the CPU may - * not expose so consistent a view of memory. CPUs will often perform - * their own instruction reordering, above and beyond that performed by - * the compiler. And each core has its own memory caches, and accesses - * (reads and writes both) to "memory" may only resolve to out-of-date - * cache entries -- not to the "most recently" performed operation in - * some global sense. Any access to a value that may be used by - * multiple threads, potentially across multiple cores, must therefore - * have a memory ordering imposed on it, for all code on all - * threads/cores to have a sufficiently coherent worldview. - * - * http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync and - * http://en.cppreference.com/w/cpp/atomic/memory_order go into more - * detail on all this, including examples of how each mode works. - * - * Note that for simplicity and practicality, not all of the modes in - * C++11 are supported. The missing C++11 modes are either subsumed by - * the modes we provide below, or not relevant for the CPUs we support - * in Gecko. These three modes are confusing enough as it is! - */ -enum MemoryOrdering { - /* - * Relaxed ordering is the simplest memory ordering: none at all. - * When the result of a write is observed, nothing may be inferred - * about other memory. Writes ostensibly performed "before" on the - * writing thread may not yet be visible. Writes performed "after" on - * the writing thread may already be visible, if the compiler or CPU - * reordered them. (The latter can happen if reads and/or writes get - * held up in per-processor caches.) Relaxed ordering means - * operations can always use cached values (as long as the actual - * updates to atomic values actually occur, correctly, eventually), so - * it's usually the fastest sort of atomic access. For this reason, - * *it's also the most dangerous kind of access*. - * - * Relaxed ordering is good for things like process-wide statistics - * counters that don't need to be consistent with anything else, so - * long as updates themselves are atomic. (And so long as any - * observations of that value can tolerate being out-of-date -- if you - * need some sort of up-to-date value, you need some sort of other - * synchronizing operation.) It's *not* good for locks, mutexes, - * reference counts, etc. that mediate access to other memory, or must - * be observably consistent with other memory. - * - * x86 architectures don't take advantage of the optimization - * opportunities that relaxed ordering permits. Thus it's possible - * that using relaxed ordering will "work" on x86 but fail elsewhere - * (ARM, say, which *does* implement non-sequentially-consistent - * relaxed ordering semantics). Be extra-careful using relaxed - * ordering if you can't easily test non-x86 architectures! - */ - Relaxed, - - /* - * When an atomic value is updated with ReleaseAcquire ordering, and - * that new value is observed with ReleaseAcquire ordering, prior - * writes (atomic or not) are also observable. What ReleaseAcquire - * *doesn't* give you is any observable ordering guarantees for - * ReleaseAcquire-ordered operations on different objects. For - * example, if there are two cores that each perform ReleaseAcquire - * operations on separate objects, each core may or may not observe - * the operations made by the other core. The only way the cores can - * be synchronized with ReleaseAcquire is if they both - * ReleaseAcquire-access the same object. This implies that you can't - * necessarily describe some global total ordering of ReleaseAcquire - * operations. - * - * ReleaseAcquire ordering is good for (as the name implies) atomic - * operations on values controlling ownership of things: reference - * counts, mutexes, and the like. However, if you are thinking about - * using these to implement your own locks or mutexes, you should take - * a good, hard look at actual lock or mutex primitives first. - */ - ReleaseAcquire, - - /* - * When an atomic value is updated with SequentiallyConsistent - * ordering, all writes observable when the update is observed, just - * as with ReleaseAcquire ordering. But, furthermore, a global total - * ordering of SequentiallyConsistent operations *can* be described. - * For example, if two cores perform SequentiallyConsistent operations - * on separate objects, one core will observably perform its update - * (and all previous operations will have completed), then the other - * core will observably perform its update (and all previous - * operations will have completed). (Although those previous - * operations aren't themselves ordered -- they could be intermixed, - * or ordered if they occur on atomic values with ordering - * requirements.) SequentiallyConsistent is the *simplest and safest* - * ordering of atomic operations -- it's always as if one operation - * happens, then another, then another, in some order -- and every - * core observes updates to happen in that single order. Because it - * has the most synchronization requirements, operations ordered this - * way also tend to be slowest. - * - * SequentiallyConsistent ordering can be desirable when multiple - * threads observe objects, and they all have to agree on the - * observable order of changes to them. People expect - * SequentiallyConsistent ordering, even if they shouldn't, when - * writing code, atomic or otherwise. SequentiallyConsistent is also - * the ordering of choice when designing lockless data structures. If - * you don't know what order to use, use this one. - */ - SequentiallyConsistent, -}; - -} // namespace mozilla - -// Build up the underlying intrinsics. -#ifdef MOZ_HAVE_CXX11_ATOMICS - -# include - -namespace mozilla { -namespace detail { - -/* - * We provide CompareExchangeFailureOrder to work around a bug in some - * versions of GCC's header. See bug 898491. - */ -template struct AtomicOrderConstraints; - -template<> -struct AtomicOrderConstraints -{ - static const std::memory_order AtomicRMWOrder = std::memory_order_relaxed; - static const std::memory_order LoadOrder = std::memory_order_relaxed; - static const std::memory_order StoreOrder = std::memory_order_relaxed; - static const std::memory_order CompareExchangeFailureOrder = - std::memory_order_relaxed; -}; - -template<> -struct AtomicOrderConstraints -{ - static const std::memory_order AtomicRMWOrder = std::memory_order_acq_rel; - static const std::memory_order LoadOrder = std::memory_order_acquire; - static const std::memory_order StoreOrder = std::memory_order_release; - static const std::memory_order CompareExchangeFailureOrder = - std::memory_order_acquire; -}; - -template<> -struct AtomicOrderConstraints -{ - static const std::memory_order AtomicRMWOrder = std::memory_order_seq_cst; - static const std::memory_order LoadOrder = std::memory_order_seq_cst; - static const std::memory_order StoreOrder = std::memory_order_seq_cst; - static const std::memory_order CompareExchangeFailureOrder = - std::memory_order_seq_cst; -}; - -template -struct IntrinsicBase -{ - typedef std::atomic ValueType; - typedef AtomicOrderConstraints OrderedOp; -}; - -template -struct IntrinsicMemoryOps : public IntrinsicBase -{ - typedef IntrinsicBase Base; - - static T load(const typename Base::ValueType& aPtr) - { - return aPtr.load(Base::OrderedOp::LoadOrder); - } - - static void store(typename Base::ValueType& aPtr, T aVal) - { - aPtr.store(aVal, Base::OrderedOp::StoreOrder); - } - - static T exchange(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.exchange(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static bool compareExchange(typename Base::ValueType& aPtr, - T aOldVal, T aNewVal) - { - return aPtr.compare_exchange_strong(aOldVal, aNewVal, - Base::OrderedOp::AtomicRMWOrder, - Base::OrderedOp::CompareExchangeFailureOrder); - } -}; - -template -struct IntrinsicAddSub : public IntrinsicBase -{ - typedef IntrinsicBase Base; - - static T add(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_add(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T sub(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_sub(aVal, Base::OrderedOp::AtomicRMWOrder); - } -}; - -template -struct IntrinsicAddSub : public IntrinsicBase -{ - typedef IntrinsicBase Base; - - static T* add(typename Base::ValueType& aPtr, ptrdiff_t aVal) - { - return aPtr.fetch_add(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T* sub(typename Base::ValueType& aPtr, ptrdiff_t aVal) - { - return aPtr.fetch_sub(aVal, Base::OrderedOp::AtomicRMWOrder); - } -}; - -template -struct IntrinsicIncDec : public IntrinsicAddSub -{ - typedef IntrinsicBase Base; - - static T inc(typename Base::ValueType& aPtr) - { - return IntrinsicAddSub::add(aPtr, 1); - } - - static T dec(typename Base::ValueType& aPtr) - { - return IntrinsicAddSub::sub(aPtr, 1); - } -}; - -template -struct AtomicIntrinsics : public IntrinsicMemoryOps, - public IntrinsicIncDec -{ - typedef IntrinsicBase Base; - - static T or_(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_or(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T xor_(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_xor(aVal, Base::OrderedOp::AtomicRMWOrder); - } - - static T and_(typename Base::ValueType& aPtr, T aVal) - { - return aPtr.fetch_and(aVal, Base::OrderedOp::AtomicRMWOrder); - } -}; - -template -struct AtomicIntrinsics - : public IntrinsicMemoryOps, public IntrinsicIncDec -{ -}; - -template -struct ToStorageTypeArgument -{ - static constexpr T convert (T aT) { return aT; } -}; - -} // namespace detail -} // namespace mozilla - -#elif defined(__GNUC__) - -namespace mozilla { -namespace detail { - -/* - * The __sync_* family of intrinsics is documented here: - * - * http://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Atomic-Builtins.html - * - * While these intrinsics are deprecated in favor of the newer __atomic_* - * family of intrincs: - * - * http://gcc.gnu.org/onlinedocs/gcc-4.7.3/gcc/_005f_005fatomic-Builtins.html - * - * any GCC version that supports the __atomic_* intrinsics will also support - * the header and so will be handled above. We provide a version of - * atomics using the __sync_* intrinsics to support older versions of GCC. - * - * All __sync_* intrinsics that we use below act as full memory barriers, for - * both compiler and hardware reordering, except for __sync_lock_test_and_set, - * which is a only an acquire barrier. When we call __sync_lock_test_and_set, - * we add a barrier above it as appropriate. - */ - -template struct Barrier; - -/* - * Some processors (in particular, x86) don't require quite so many calls to - * __sync_sychronize as our specializations of Barrier produce. If - * performance turns out to be an issue, defining these specializations - * on a per-processor basis would be a good first tuning step. - */ - -template<> -struct Barrier -{ - static void beforeLoad() {} - static void afterLoad() {} - static void beforeStore() {} - static void afterStore() {} -}; - -template<> -struct Barrier -{ - static void beforeLoad() {} - static void afterLoad() { __sync_synchronize(); } - static void beforeStore() { __sync_synchronize(); } - static void afterStore() {} -}; - -template<> -struct Barrier -{ - static void beforeLoad() { __sync_synchronize(); } - static void afterLoad() { __sync_synchronize(); } - static void beforeStore() { __sync_synchronize(); } - static void afterStore() { __sync_synchronize(); } -}; - -template::value> -struct AtomicStorageType -{ - // For non-enums, just use the type directly. - typedef T Type; -}; - -template -struct AtomicStorageType - : Conditional -{ - static_assert(sizeof(T) == 4 || sizeof(T) == 8, - "wrong type computed in conditional above"); -}; - -template -struct IntrinsicMemoryOps -{ - typedef typename AtomicStorageType::Type ValueType; - - static T load(const ValueType& aPtr) - { - Barrier::beforeLoad(); - T val = T(aPtr); - Barrier::afterLoad(); - return val; - } - - static void store(ValueType& aPtr, T aVal) - { - Barrier::beforeStore(); - aPtr = ValueType(aVal); - Barrier::afterStore(); - } - - static T exchange(ValueType& aPtr, T aVal) - { - // __sync_lock_test_and_set is only an acquire barrier; loads and stores - // can't be moved up from after to before it, but they can be moved down - // from before to after it. We may want a stricter ordering, so we need - // an explicit barrier. - Barrier::beforeStore(); - return T(__sync_lock_test_and_set(&aPtr, ValueType(aVal))); - } - - static bool compareExchange(ValueType& aPtr, T aOldVal, T aNewVal) - { - return __sync_bool_compare_and_swap(&aPtr, ValueType(aOldVal), ValueType(aNewVal)); - } -}; - -template -struct IntrinsicAddSub - : public IntrinsicMemoryOps -{ - typedef IntrinsicMemoryOps Base; - typedef typename Base::ValueType ValueType; - - static T add(ValueType& aPtr, T aVal) - { - return T(__sync_fetch_and_add(&aPtr, ValueType(aVal))); - } - - static T sub(ValueType& aPtr, T aVal) - { - return T(__sync_fetch_and_sub(&aPtr, ValueType(aVal))); - } -}; - -template -struct IntrinsicAddSub - : public IntrinsicMemoryOps -{ - typedef IntrinsicMemoryOps Base; - typedef typename Base::ValueType ValueType; - - /* - * The reinterpret_casts are needed so that - * __sync_fetch_and_{add,sub} will properly type-check. - * - * Also, these functions do not provide standard semantics for - * pointer types, so we need to adjust the addend. - */ - static ValueType add(ValueType& aPtr, ptrdiff_t aVal) - { - ValueType amount = reinterpret_cast(aVal * sizeof(T)); - return __sync_fetch_and_add(&aPtr, amount); - } - - static ValueType sub(ValueType& aPtr, ptrdiff_t aVal) - { - ValueType amount = reinterpret_cast(aVal * sizeof(T)); - return __sync_fetch_and_sub(&aPtr, amount); - } -}; - -template -struct IntrinsicIncDec : public IntrinsicAddSub -{ - typedef IntrinsicAddSub Base; - typedef typename Base::ValueType ValueType; - - static T inc(ValueType& aPtr) { return Base::add(aPtr, 1); } - static T dec(ValueType& aPtr) { return Base::sub(aPtr, 1); } -}; - -template -struct AtomicIntrinsics : public IntrinsicIncDec -{ - static T or_( T& aPtr, T aVal) { return __sync_fetch_and_or(&aPtr, aVal); } - static T xor_(T& aPtr, T aVal) { return __sync_fetch_and_xor(&aPtr, aVal); } - static T and_(T& aPtr, T aVal) { return __sync_fetch_and_and(&aPtr, aVal); } -}; - -template -struct AtomicIntrinsics : public IntrinsicIncDec -{ -}; - -template::value> -struct ToStorageTypeArgument -{ - typedef typename AtomicStorageType::Type ResultType; - - static constexpr ResultType convert (T aT) { return ResultType(aT); } -}; - -template -struct ToStorageTypeArgument -{ - static constexpr T convert (T aT) { return aT; } -}; - -} // namespace detail -} // namespace mozilla - -#else -# error "Atomic compiler intrinsics are not supported on your platform" -#endif - -namespace mozilla { - -namespace detail { - -template -class AtomicBase -{ - static_assert(sizeof(T) == 4 || sizeof(T) == 8, - "mozilla/Atomics.h only supports 32-bit and 64-bit types"); - -protected: - typedef typename detail::AtomicIntrinsics Intrinsics; - typedef typename Intrinsics::ValueType ValueType; - ValueType mValue; - -public: - constexpr AtomicBase() : mValue() {} - explicit constexpr AtomicBase(T aInit) - : mValue(ToStorageTypeArgument::convert(aInit)) - {} - - // Note: we can't provide operator T() here because Atomic inherits - // from AtomcBase with T=uint32_t and not T=bool. If we implemented - // operator T() here, it would cause errors when comparing Atomic with - // a regular bool. - - T operator=(T aVal) - { - Intrinsics::store(mValue, aVal); - return aVal; - } - - /** - * Performs an atomic swap operation. aVal is stored and the previous - * value of this variable is returned. - */ - T exchange(T aVal) - { - return Intrinsics::exchange(mValue, aVal); - } - - /** - * Performs an atomic compare-and-swap operation and returns true if it - * succeeded. This is equivalent to atomically doing - * - * if (mValue == aOldValue) { - * mValue = aNewValue; - * return true; - * } else { - * return false; - * } - */ - bool compareExchange(T aOldValue, T aNewValue) - { - return Intrinsics::compareExchange(mValue, aOldValue, aNewValue); - } - -private: - template - AtomicBase(const AtomicBase& aCopy) = delete; -}; - -template -class AtomicBaseIncDec : public AtomicBase -{ - typedef typename detail::AtomicBase Base; - -public: - constexpr AtomicBaseIncDec() : Base() {} - explicit constexpr AtomicBaseIncDec(T aInit) : Base(aInit) {} - - using Base::operator=; - - operator T() const { return Base::Intrinsics::load(Base::mValue); } - T operator++(int) { return Base::Intrinsics::inc(Base::mValue); } - T operator--(int) { return Base::Intrinsics::dec(Base::mValue); } - T operator++() { return Base::Intrinsics::inc(Base::mValue) + 1; } - T operator--() { return Base::Intrinsics::dec(Base::mValue) - 1; } - -private: - template - AtomicBaseIncDec(const AtomicBaseIncDec& aCopy) = delete; -}; - -} // namespace detail - -/** - * A wrapper for a type that enforces that all memory accesses are atomic. - * - * In general, where a variable |T foo| exists, |Atomic foo| can be used in - * its place. Implementations for integral and pointer types are provided - * below. - * - * Atomic accesses are sequentially consistent by default. You should - * use the default unless you are tall enough to ride the - * memory-ordering roller coaster (if you're not sure, you aren't) and - * you have a compelling reason to do otherwise. - * - * There is one exception to the case of atomic memory accesses: providing an - * initial value of the atomic value is not guaranteed to be atomic. This is a - * deliberate design choice that enables static atomic variables to be declared - * without introducing extra static constructors. - */ -template -class Atomic; - -/** - * Atomic implementation for integral types. - * - * In addition to atomic store and load operations, compound assignment and - * increment/decrement operators are implemented which perform the - * corresponding read-modify-write operation atomically. Finally, an atomic - * swap method is provided. - */ -template -class Atomic::value && - !IsSame::value>::Type> - : public detail::AtomicBaseIncDec -{ - typedef typename detail::AtomicBaseIncDec Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(T aInit) : Base(aInit) {} - - using Base::operator=; - - T operator+=(T aDelta) - { - return Base::Intrinsics::add(Base::mValue, aDelta) + aDelta; - } - - T operator-=(T aDelta) - { - return Base::Intrinsics::sub(Base::mValue, aDelta) - aDelta; - } - - T operator|=(T aVal) - { - return Base::Intrinsics::or_(Base::mValue, aVal) | aVal; - } - - T operator^=(T aVal) - { - return Base::Intrinsics::xor_(Base::mValue, aVal) ^ aVal; - } - - T operator&=(T aVal) - { - return Base::Intrinsics::and_(Base::mValue, aVal) & aVal; - } - -private: - Atomic(Atomic& aOther) = delete; -}; - -/** - * Atomic implementation for pointer types. - * - * An atomic compare-and-swap primitive for pointer variables is provided, as - * are atomic increment and decement operators. Also provided are the compound - * assignment operators for addition and subtraction. Atomic swap (via - * exchange()) is included as well. - */ -template -class Atomic : public detail::AtomicBaseIncDec -{ - typedef typename detail::AtomicBaseIncDec Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(T* aInit) : Base(aInit) {} - - using Base::operator=; - - T* operator+=(ptrdiff_t aDelta) - { - return Base::Intrinsics::add(Base::mValue, aDelta) + aDelta; - } - - T* operator-=(ptrdiff_t aDelta) - { - return Base::Intrinsics::sub(Base::mValue, aDelta) - aDelta; - } - -private: - Atomic(Atomic& aOther) = delete; -}; - -/** - * Atomic implementation for enum types. - * - * The atomic store and load operations and the atomic swap method is provided. - */ -template -class Atomic::value>::Type> - : public detail::AtomicBase -{ - typedef typename detail::AtomicBase Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(T aInit) : Base(aInit) {} - - operator T() const { return T(Base::Intrinsics::load(Base::mValue)); } - - using Base::operator=; - -private: - Atomic(Atomic& aOther) = delete; -}; - -/** - * Atomic implementation for boolean types. - * - * The atomic store and load operations and the atomic swap method is provided. - * - * Note: - * - * - sizeof(Atomic) != sizeof(bool) for some implementations of - * bool and/or some implementations of std::atomic. This is allowed in - * [atomic.types.generic]p9. - * - * - It's not obvious whether the 8-bit atomic functions on Windows are always - * inlined or not. If they are not inlined, the corresponding functions in the - * runtime library are not available on Windows XP. This is why we implement - * Atomic with an underlying type of uint32_t. - */ -template -class Atomic - : protected detail::AtomicBase -{ - typedef typename detail::AtomicBase Base; - -public: - constexpr Atomic() : Base() {} - explicit constexpr Atomic(bool aInit) : Base(aInit) {} - - // We provide boolean wrappers for the underlying AtomicBase methods. - MOZ_IMPLICIT operator bool() const - { - return Base::Intrinsics::load(Base::mValue); - } - - bool operator=(bool aVal) - { - return Base::operator=(aVal); - } - - bool exchange(bool aVal) - { - return Base::exchange(aVal); - } - - bool compareExchange(bool aOldValue, bool aNewValue) - { - return Base::compareExchange(aOldValue, aNewValue); - } - -private: - Atomic(Atomic& aOther) = delete; -}; - -} // namespace mozilla - -#endif /* mozilla_Atomics_h */ diff --git a/win32/include/spidermonkey/mozilla/Attributes.h b/win32/include/spidermonkey/mozilla/Attributes.h deleted file mode 100755 index df6172f3..00000000 --- a/win32/include/spidermonkey/mozilla/Attributes.h +++ /dev/null @@ -1,604 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implementations of various class and method modifier attributes. */ - -#ifndef mozilla_Attributes_h -#define mozilla_Attributes_h - -#include "mozilla/Compiler.h" - -/* - * MOZ_ALWAYS_INLINE is a macro which expands to tell the compiler that the - * method decorated with it must be inlined, even if the compiler thinks - * otherwise. This is only a (much) stronger version of the inline hint: - * compilers are not guaranteed to respect it (although they're much more likely - * to do so). - * - * The MOZ_ALWAYS_INLINE_EVEN_DEBUG macro is yet stronger. It tells the - * compiler to inline even in DEBUG builds. It should be used very rarely. - */ -#if defined(_MSC_VER) -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __forceinline -#elif defined(__GNUC__) -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) inline -#else -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG inline -#endif - -#if !defined(DEBUG) -# define MOZ_ALWAYS_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG -#elif defined(_MSC_VER) && !defined(__cplusplus) -# define MOZ_ALWAYS_INLINE __inline -#else -# define MOZ_ALWAYS_INLINE inline -#endif - -#if defined(_MSC_VER) -/* - * g++ requires -std=c++0x or -std=gnu++0x to support C++11 functionality - * without warnings (functionality used by the macros below). These modes are - * detectable by checking whether __GXX_EXPERIMENTAL_CXX0X__ is defined or, more - * standardly, by checking whether __cplusplus has a C++11 or greater value. - * Current versions of g++ do not correctly set __cplusplus, so we check both - * for forward compatibility. - */ -# define MOZ_HAVE_NEVER_INLINE __declspec(noinline) -# define MOZ_HAVE_NORETURN __declspec(noreturn) -#elif defined(__clang__) - /* - * Per Clang documentation, "Note that marketing version numbers should not - * be used to check for language features, as different vendors use different - * numbering schemes. Instead, use the feature checking macros." - */ -# ifndef __has_extension -# define __has_extension __has_feature /* compatibility, for older versions of clang */ -# endif -# if __has_attribute(noinline) -# define MOZ_HAVE_NEVER_INLINE __attribute__((noinline)) -# endif -# if __has_attribute(noreturn) -# define MOZ_HAVE_NORETURN __attribute__((noreturn)) -# endif -#elif defined(__GNUC__) -# define MOZ_HAVE_NEVER_INLINE __attribute__((noinline)) -# define MOZ_HAVE_NORETURN __attribute__((noreturn)) -#endif - -/* - * When built with clang analyzer (a.k.a scan-build), define MOZ_HAVE_NORETURN - * to mark some false positives - */ -#ifdef __clang_analyzer__ -# if __has_extension(attribute_analyzer_noreturn) -# define MOZ_HAVE_ANALYZER_NORETURN __attribute__((analyzer_noreturn)) -# endif -#endif - -/* - * MOZ_NEVER_INLINE is a macro which expands to tell the compiler that the - * method decorated with it must never be inlined, even if the compiler would - * otherwise choose to inline the method. Compilers aren't absolutely - * guaranteed to support this, but most do. - */ -#if defined(MOZ_HAVE_NEVER_INLINE) -# define MOZ_NEVER_INLINE MOZ_HAVE_NEVER_INLINE -#else -# define MOZ_NEVER_INLINE /* no support */ -#endif - -/* - * MOZ_NORETURN, specified at the start of a function declaration, indicates - * that the given function does not return. (The function definition does not - * need to be annotated.) - * - * MOZ_NORETURN void abort(const char* msg); - * - * This modifier permits the compiler to optimize code assuming a call to such a - * function will never return. It also enables the compiler to avoid spurious - * warnings about not initializing variables, or about any other seemingly-dodgy - * operations performed after the function returns. - * - * This modifier does not affect the corresponding function's linking behavior. - */ -#if defined(MOZ_HAVE_NORETURN) -# define MOZ_NORETURN MOZ_HAVE_NORETURN -#else -# define MOZ_NORETURN /* no support */ -#endif - -/** - * MOZ_COLD tells the compiler that a function is "cold", meaning infrequently - * executed. This may lead it to optimize for size more aggressively than speed, - * or to allocate the body of the function in a distant part of the text segment - * to help keep it from taking up unnecessary icache when it isn't in use. - * - * Place this attribute at the very beginning of a function definition. For - * example, write - * - * MOZ_COLD int foo(); - * - * or - * - * MOZ_COLD int foo() { return 42; } - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_COLD __attribute__ ((cold)) -#else -# define MOZ_COLD -#endif - -/** - * MOZ_NONNULL tells the compiler that some of the arguments to a function are - * known to be non-null. The arguments are a list of 1-based argument indexes - * identifying arguments which are known to be non-null. - * - * Place this attribute at the very beginning of a function definition. For - * example, write - * - * MOZ_NONNULL(1, 2) int foo(char *p, char *q); - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_NONNULL(...) __attribute__ ((nonnull(__VA_ARGS__))) -#else -# define MOZ_NONNULL(...) -#endif - -/* - * MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS, specified at the end of a function - * declaration, indicates that for the purposes of static analysis, this - * function does not return. (The function definition does not need to be - * annotated.) - * - * MOZ_ReportCrash(const char* s, const char* file, int ln) - * MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS - * - * Some static analyzers, like scan-build from clang, can use this information - * to eliminate false positives. From the upstream documentation of scan-build: - * "This attribute is useful for annotating assertion handlers that actually - * can return, but for the purpose of using the analyzer we want to pretend - * that such functions do not return." - * - */ -#if defined(MOZ_HAVE_ANALYZER_NORETURN) -# define MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS MOZ_HAVE_ANALYZER_NORETURN -#else -# define MOZ_PRETEND_NORETURN_FOR_STATIC_ANALYSIS /* no support */ -#endif - -/* - * MOZ_ASAN_BLACKLIST is a macro to tell AddressSanitizer (a compile-time - * instrumentation shipped with Clang and GCC) to not instrument the annotated - * function. Furthermore, it will prevent the compiler from inlining the - * function because inlining currently breaks the blacklisting mechanism of - * AddressSanitizer. - */ -#if defined(__has_feature) -# if __has_feature(address_sanitizer) -# define MOZ_HAVE_ASAN_BLACKLIST -# endif -#elif defined(__GNUC__) -# if defined(__SANITIZE_ADDRESS__) -# define MOZ_HAVE_ASAN_BLACKLIST -# endif -#endif - -#if defined(MOZ_HAVE_ASAN_BLACKLIST) -# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_address)) -#else -# define MOZ_ASAN_BLACKLIST /* nothing */ -#endif - -/* - * MOZ_TSAN_BLACKLIST is a macro to tell ThreadSanitizer (a compile-time - * instrumentation shipped with Clang) to not instrument the annotated function. - * Furthermore, it will prevent the compiler from inlining the function because - * inlining currently breaks the blacklisting mechanism of ThreadSanitizer. - */ -#if defined(__has_feature) -# if __has_feature(thread_sanitizer) -# define MOZ_TSAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_thread)) -# else -# define MOZ_TSAN_BLACKLIST /* nothing */ -# endif -#else -# define MOZ_TSAN_BLACKLIST /* nothing */ -#endif - -/** - * MOZ_ALLOCATOR tells the compiler that the function it marks returns either a - * "fresh", "pointer-free" block of memory, or nullptr. "Fresh" means that the - * block is not pointed to by any other reachable pointer in the program. - * "Pointer-free" means that the block contains no pointers to any valid object - * in the program. It may be initialized with other (non-pointer) values. - * - * Placing this attribute on appropriate functions helps GCC analyze pointer - * aliasing more accurately in their callers. - * - * GCC warns if a caller ignores the value returned by a function marked with - * MOZ_ALLOCATOR: it is hard to imagine cases where dropping the value returned - * by a function that meets the criteria above would be intentional. - * - * Place this attribute after the argument list and 'this' qualifiers of a - * function definition. For example, write - * - * void *my_allocator(size_t) MOZ_ALLOCATOR; - * - * or - * - * void *my_allocator(size_t bytes) MOZ_ALLOCATOR { ... } - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_ALLOCATOR __attribute__ ((malloc, warn_unused_result)) -#else -# define MOZ_ALLOCATOR -#endif - -/** - * MOZ_MUST_USE tells the compiler to emit a warning if a function's - * return value is not used by the caller. - * - * Place this attribute at the very beginning of a function declaration. For - * example, write - * - * MOZ_MUST_USE int foo(); - * - * or - * - * MOZ_MUST_USE int foo() { return 42; } - */ -#if defined(__GNUC__) || defined(__clang__) -# define MOZ_MUST_USE __attribute__ ((warn_unused_result)) -#else -# define MOZ_MUST_USE -#endif - -/** - * MOZ_FALLTHROUGH is an annotation to suppress compiler warnings about switch - * cases that fall through without a break or return statement. MOZ_FALLTHROUGH - * is only needed on cases that have code. - * - * MOZ_FALLTHROUGH_ASSERT is an annotation to suppress compiler warnings about - * switch cases that MOZ_ASSERT(false) (or its alias MOZ_ASSERT_UNREACHABLE) in - * debug builds, but intentionally fall through in release builds. See comment - * in Assertions.h for more details. - * - * switch (foo) { - * case 1: // These cases have no code. No fallthrough annotations are needed. - * case 2: - * case 3: // This case has code, so a fallthrough annotation is needed! - * foo++; - * MOZ_FALLTHROUGH; - * case 4: - * return foo; - * - * default: - * // This case asserts in debug builds, falls through in release. - * MOZ_FALLTHROUGH_ASSERT("Unexpected foo value?!"); - * case 5: - * return 5; - * } - */ -#if defined(__clang__) && __cplusplus >= 201103L - /* clang's fallthrough annotations are only available starting in C++11. */ -# define MOZ_FALLTHROUGH [[clang::fallthrough]] -#elif defined(_MSC_VER) - /* - * MSVC's __fallthrough annotations are checked by /analyze (Code Analysis): - * https://msdn.microsoft.com/en-us/library/ms235402%28VS.80%29.aspx - */ -# include -# define MOZ_FALLTHROUGH __fallthrough -#else -# define MOZ_FALLTHROUGH /* FALLTHROUGH */ -#endif - -#ifdef __cplusplus - -/* - * The following macros are attributes that support the static analysis plugin - * included with Mozilla, and will be implemented (when such support is enabled) - * as C++11 attributes. Since such attributes are legal pretty much everywhere - * and have subtly different semantics depending on their placement, the - * following is a guide on where to place the attributes. - * - * Attributes that apply to a struct or class precede the name of the class: - * (Note that this is different from the placement of final for classes!) - * - * class MOZ_CLASS_ATTRIBUTE SomeClass {}; - * - * Attributes that apply to functions follow the parentheses and const - * qualifiers but precede final, override and the function body: - * - * void DeclaredFunction() MOZ_FUNCTION_ATTRIBUTE; - * void SomeFunction() MOZ_FUNCTION_ATTRIBUTE {} - * void PureFunction() const MOZ_FUNCTION_ATTRIBUTE = 0; - * void OverriddenFunction() MOZ_FUNCTION_ATTIRBUTE override; - * - * Attributes that apply to variables or parameters follow the variable's name: - * - * int variable MOZ_VARIABLE_ATTRIBUTE; - * - * Attributes that apply to types follow the type name: - * - * typedef int MOZ_TYPE_ATTRIBUTE MagicInt; - * int MOZ_TYPE_ATTRIBUTE someVariable; - * int* MOZ_TYPE_ATTRIBUTE magicPtrInt; - * int MOZ_TYPE_ATTRIBUTE* ptrToMagicInt; - * - * Attributes that apply to statements precede the statement: - * - * MOZ_IF_ATTRIBUTE if (x == 0) - * MOZ_DO_ATTRIBUTE do { } while (0); - * - * Attributes that apply to labels precede the label: - * - * MOZ_LABEL_ATTRIBUTE target: - * goto target; - * MOZ_CASE_ATTRIBUTE case 5: - * MOZ_DEFAULT_ATTRIBUTE default: - * - * The static analyses that are performed by the plugin are as follows: - * - * MOZ_MUST_OVERRIDE: Applies to all C++ member functions. All immediate - * subclasses must provide an exact override of this method; if a subclass - * does not override this method, the compiler will emit an error. This - * attribute is not limited to virtual methods, so if it is applied to a - * nonvirtual method and the subclass does not provide an equivalent - * definition, the compiler will emit an error. - * MOZ_STACK_CLASS: Applies to all classes. Any class with this annotation is - * expected to live on the stack, so it is a compile-time error to use it, or - * an array of such objects, as a global or static variable, or as the type of - * a new expression (unless placement new is being used). If a member of - * another class uses this class, or if another class inherits from this - * class, then it is considered to be a stack class as well, although this - * attribute need not be provided in such cases. - * MOZ_NONHEAP_CLASS: Applies to all classes. Any class with this annotation is - * expected to live on the stack or in static storage, so it is a compile-time - * error to use it, or an array of such objects, as the type of a new - * expression. If a member of another class uses this class, or if another - * class inherits from this class, then it is considered to be a non-heap class - * as well, although this attribute need not be provided in such cases. - * MOZ_HEAP_CLASS: Applies to all classes. Any class with this annotation is - * expected to live on the heap, so it is a compile-time error to use it, or - * an array of such objects, as the type of a variable declaration, or as a - * temporary object. If a member of another class uses this class, or if - * another class inherits from this class, then it is considered to be a heap - * class as well, although this attribute need not be provided in such cases. - * MOZ_NON_TEMPORARY_CLASS: Applies to all classes. Any class with this - * annotation is expected not to live in a temporary. If a member of another - * class uses this class or if another class inherits from this class, then it - * is considered to be a non-temporary class as well, although this attribute - * need not be provided in such cases. - * MOZ_RAII: Applies to all classes. Any class with this annotation is assumed - * to be a RAII guard, which is expected to live on the stack in an automatic - * allocation. It is prohibited from being allocated in a temporary, static - * storage, or on the heap. This is a combination of MOZ_STACK_CLASS and - * MOZ_NON_TEMPORARY_CLASS. - * MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS: Applies to all classes that are - * intended to prevent introducing static initializers. This attribute - * currently makes it a compile-time error to instantiate these classes - * anywhere other than at the global scope, or as a static member of a class. - * In non-debug mode, it also prohibits non-trivial constructors and - * destructors. - * MOZ_TRIVIAL_CTOR_DTOR: Applies to all classes that must have both a trivial - * or constexpr constructor and a trivial destructor. Setting this attribute - * on a class makes it a compile-time error for that class to get a - * non-trivial constructor or destructor for any reason. - * MOZ_HEAP_ALLOCATOR: Applies to any function. This indicates that the return - * value is allocated on the heap, and will as a result check such allocations - * during MOZ_STACK_CLASS and MOZ_NONHEAP_CLASS annotation checking. - * MOZ_IMPLICIT: Applies to constructors. Implicit conversion constructors - * are disallowed by default unless they are marked as MOZ_IMPLICIT. This - * attribute must be used for constructors which intend to provide implicit - * conversions. - * MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT: Applies to functions. Makes it a compile - * time error to pass arithmetic expressions on variables to the function. - * MOZ_OWNING_REF: Applies to declarations of pointers to reference counted - * types. This attribute tells the compiler that the raw pointer is a strong - * reference, where ownership through methods such as AddRef and Release is - * managed manually. This can make the compiler ignore these pointers when - * validating the usage of pointers otherwise. - * - * Example uses include owned pointers inside of unions, and pointers stored - * in POD types where a using a smart pointer class would make the object - * non-POD. - * MOZ_NON_OWNING_REF: Applies to declarations of pointers to reference counted - * types. This attribute tells the compiler that the raw pointer is a weak - * reference, which is ensured to be valid by a guarantee that the reference - * will be nulled before the pointer becomes invalid. This can make the compiler - * ignore these pointers when validating the usage of pointers otherwise. - * - * Examples include an mOwner pointer, which is nulled by the owning class's - * destructor, and is null-checked before dereferencing. - * MOZ_UNSAFE_REF: Applies to declarations of pointers to reference counted types. - * Occasionally there are non-owning references which are valid, but do not take - * the form of a MOZ_NON_OWNING_REF. Their safety may be dependent on the behaviour - * of API consumers. The string argument passed to this macro documents the safety - * conditions. This can make the compiler ignore these pointers when validating - * the usage of pointers elsewhere. - * - * Examples include an nsIAtom* member which is known at compile time to point to a - * static atom which is valid throughout the lifetime of the program, or an API which - * stores a pointer, but doesn't take ownership over it, instead requiring the API - * consumer to correctly null the value before it becomes invalid. - * - * Use of this annotation is discouraged when a strong reference or one of the above - * two annotations can be used instead. - * MOZ_NO_ADDREF_RELEASE_ON_RETURN: Applies to function declarations. Makes it - * a compile time error to call AddRef or Release on the return value of a - * function. This is intended to be used with operator->() of our smart - * pointer classes to ensure that the refcount of an object wrapped in a - * smart pointer is not manipulated directly. - * MOZ_MUST_USE_TYPE: Applies to type declarations. Makes it a compile time - * error to not use the return value of a function which has this type. This - * is intended to be used with types which it is an error to not use. - * MOZ_NEEDS_NO_VTABLE_TYPE: Applies to template class declarations. Makes it - * a compile time error to instantiate this template with a type parameter which - * has a VTable. - * MOZ_NON_MEMMOVABLE: Applies to class declarations for types that are not safe - * to be moved in memory using memmove(). - * MOZ_NEEDS_MEMMOVABLE_TYPE: Applies to template class declarations where the - * template arguments are required to be safe to move in memory using - * memmove(). Passing MOZ_NON_MEMMOVABLE types to these templates is a - * compile time error. - * MOZ_NEEDS_MEMMOVABLE_MEMBERS: Applies to class declarations where each member - * must be safe to move in memory using memmove(). MOZ_NON_MEMMOVABLE types - * used in members of these classes are compile time errors. - * MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS: Applies to template class - * declarations where an instance of the template should be considered, for - * static analysis purposes, to inherit any type annotations (such as - * MOZ_MUST_USE_TYPE and MOZ_STACK_CLASS) from its template arguments. - * MOZ_INIT_OUTSIDE_CTOR: Applies to class member declarations. Occasionally - * there are class members that are not initialized in the constructor, - * but logic elsewhere in the class ensures they are initialized prior to use. - * Using this attribute on a member disables the check that this member must be - * initialized in constructors via list-initialization, in the constructor body, - * or via functions called from the constructor body. - * MOZ_IS_CLASS_INIT: Applies to class method declarations. Occasionally the - * constructor doesn't initialize all of the member variables and another function - * is used to initialize the rest. This marker is used to make the static analysis - * tool aware that the marked function is part of the initialization process - * and to include the marked function in the scan mechanism that determines witch - * member variables still remain uninitialized. - * MOZ_NON_PARAM: Applies to types. Makes it compile time error to use the type - * in parameter without pointer or reference. - * MOZ_NON_AUTOABLE: Applies to class declarations. Makes it a compile time error to - * use `auto` in place of this type in variable declarations. This is intended to - * be used with types which are intended to be implicitly constructed into other - * other types before being assigned to variables. - * MOZ_REQUIRED_BASE_METHOD: Applies to virtual class method declarations. - * Sometimes derived classes override methods that need to be called by their - * overridden counterparts. This marker indicates that the marked method must - * be called by the method that it overrides. - */ -#ifdef MOZ_CLANG_PLUGIN -# define MOZ_MUST_OVERRIDE __attribute__((annotate("moz_must_override"))) -# define MOZ_STACK_CLASS __attribute__((annotate("moz_stack_class"))) -# define MOZ_NONHEAP_CLASS __attribute__((annotate("moz_nonheap_class"))) -# define MOZ_HEAP_CLASS __attribute__((annotate("moz_heap_class"))) -# define MOZ_NON_TEMPORARY_CLASS __attribute__((annotate("moz_non_temporary_class"))) -# define MOZ_TRIVIAL_CTOR_DTOR __attribute__((annotate("moz_trivial_ctor_dtor"))) -# ifdef DEBUG - /* in debug builds, these classes do have non-trivial constructors. */ -# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS __attribute__((annotate("moz_global_class"))) -# else -# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS __attribute__((annotate("moz_global_class"))) \ - MOZ_TRIVIAL_CTOR_DTOR -# endif -# define MOZ_IMPLICIT __attribute__((annotate("moz_implicit"))) -# define MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT __attribute__((annotate("moz_no_arith_expr_in_arg"))) -# define MOZ_OWNING_REF __attribute__((annotate("moz_strong_ref"))) -# define MOZ_NON_OWNING_REF __attribute__((annotate("moz_weak_ref"))) -# define MOZ_UNSAFE_REF(reason) __attribute__((annotate("moz_weak_ref"))) -# define MOZ_NO_ADDREF_RELEASE_ON_RETURN __attribute__((annotate("moz_no_addref_release_on_return"))) -# define MOZ_MUST_USE_TYPE __attribute__((annotate("moz_must_use_type"))) -# define MOZ_NEEDS_NO_VTABLE_TYPE __attribute__((annotate("moz_needs_no_vtable_type"))) -# define MOZ_NON_MEMMOVABLE __attribute__((annotate("moz_non_memmovable"))) -# define MOZ_NEEDS_MEMMOVABLE_TYPE __attribute__((annotate("moz_needs_memmovable_type"))) -# define MOZ_NEEDS_MEMMOVABLE_MEMBERS __attribute__((annotate("moz_needs_memmovable_members"))) -# define MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS \ - __attribute__((annotate("moz_inherit_type_annotations_from_template_args"))) -# define MOZ_NON_AUTOABLE __attribute__((annotate("moz_non_autoable"))) -# define MOZ_INIT_OUTSIDE_CTOR \ - __attribute__((annotate("moz_ignore_ctor_initialization"))) -# define MOZ_IS_CLASS_INIT \ - __attribute__((annotate("moz_is_class_init"))) -# define MOZ_NON_PARAM \ - __attribute__((annotate("moz_non_param"))) -# define MOZ_REQUIRED_BASE_METHOD \ - __attribute__((annotate("moz_required_base_method"))) -/* - * It turns out that clang doesn't like void func() __attribute__ {} without a - * warning, so use pragmas to disable the warning. This code won't work on GCC - * anyways, so the warning is safe to ignore. - */ -# define MOZ_HEAP_ALLOCATOR \ - _Pragma("clang diagnostic push") \ - _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ - __attribute__((annotate("moz_heap_allocator"))) \ - _Pragma("clang diagnostic pop") -#else -# define MOZ_MUST_OVERRIDE /* nothing */ -# define MOZ_STACK_CLASS /* nothing */ -# define MOZ_NONHEAP_CLASS /* nothing */ -# define MOZ_HEAP_CLASS /* nothing */ -# define MOZ_NON_TEMPORARY_CLASS /* nothing */ -# define MOZ_TRIVIAL_CTOR_DTOR /* nothing */ -# define MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS /* nothing */ -# define MOZ_IMPLICIT /* nothing */ -# define MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT /* nothing */ -# define MOZ_HEAP_ALLOCATOR /* nothing */ -# define MOZ_OWNING_REF /* nothing */ -# define MOZ_NON_OWNING_REF /* nothing */ -# define MOZ_UNSAFE_REF(reason) /* nothing */ -# define MOZ_NO_ADDREF_RELEASE_ON_RETURN /* nothing */ -# define MOZ_MUST_USE_TYPE /* nothing */ -# define MOZ_NEEDS_NO_VTABLE_TYPE /* nothing */ -# define MOZ_NON_MEMMOVABLE /* nothing */ -# define MOZ_NEEDS_MEMMOVABLE_TYPE /* nothing */ -# define MOZ_NEEDS_MEMMOVABLE_MEMBERS /* nothing */ -# define MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS /* nothing */ -# define MOZ_INIT_OUTSIDE_CTOR /* nothing */ -# define MOZ_IS_CLASS_INIT /* nothing */ -# define MOZ_NON_PARAM /* nothing */ -# define MOZ_NON_AUTOABLE /* nothing */ -# define MOZ_REQUIRED_BASE_METHOD /* nothing */ -#endif /* MOZ_CLANG_PLUGIN */ - -#define MOZ_RAII MOZ_NON_TEMPORARY_CLASS MOZ_STACK_CLASS - -/* - * MOZ_HAVE_REF_QUALIFIERS is defined for compilers that support C++11's rvalue - * qualifier, "&&". - */ -#if defined(_MSC_VER) && _MSC_VER >= 1900 -# define MOZ_HAVE_REF_QUALIFIERS -#elif defined(__clang__) -// All supported Clang versions -# define MOZ_HAVE_REF_QUALIFIERS -#elif defined(__GNUC__) -# include "mozilla/Compiler.h" -# if MOZ_GCC_VERSION_AT_LEAST(4, 8, 1) -# define MOZ_HAVE_REF_QUALIFIERS -# endif -#endif - -#endif /* __cplusplus */ - -/** - * Printf style formats. MOZ_FORMAT_PRINTF can be used to annotate a - * function or method that is "printf-like"; this will let (some) - * compilers check that the arguments match the template string. - * - * This macro takes two arguments. The first argument is the argument - * number of the template string. The second argument is the argument - * number of the '...' argument holding the arguments. - * - * Argument numbers start at 1. Note that the implicit "this" - * argument of a non-static member function counts as an argument. - * - * So, for a simple case like: - * void print_something (int whatever, const char *fmt, ...); - * The corresponding annotation would be - * MOZ_FORMAT_PRINTF(2, 3) - * However, if "print_something" were a non-static member function, - * then the annotation would be: - * MOZ_FORMAT_PRINTF(3, 4) - * - * Note that the checking is limited to standards-conforming - * printf-likes, and in particular this should not be used for - * PR_snprintf and friends, which are "printf-like" but which assign - * different meanings to the various formats. - */ -#ifdef __GNUC__ -#define MOZ_FORMAT_PRINTF(stringIndex, firstToCheck) \ - __attribute__ ((format (printf, stringIndex, firstToCheck))) -#else -#define MOZ_FORMAT_PRINTF(stringIndex, firstToCheck) -#endif - -#endif /* mozilla_Attributes_h */ diff --git a/win32/include/spidermonkey/mozilla/BinarySearch.h b/win32/include/spidermonkey/mozilla/BinarySearch.h deleted file mode 100755 index 1bbe0566..00000000 --- a/win32/include/spidermonkey/mozilla/BinarySearch.h +++ /dev/null @@ -1,139 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_BinarySearch_h -#define mozilla_BinarySearch_h - -#include "mozilla/Assertions.h" - -#include - -namespace mozilla { - -/* - * The BinarySearch() algorithm searches the given container |aContainer| over - * the sorted index range [aBegin, aEnd) for an index |i| where - * |aContainer[i] == aTarget|. - * If such an index |i| is found, BinarySearch returns |true| and the index is - * returned via the outparam |aMatchOrInsertionPoint|. If no index is found, - * BinarySearch returns |false| and the outparam returns the first index in - * [aBegin, aEnd] where |aTarget| can be inserted to maintain sorted order. - * - * Example: - * - * Vector sortedInts = ... - * - * size_t match; - * if (BinarySearch(sortedInts, 0, sortedInts.length(), 13, &match)) { - * printf("found 13 at %lu\n", match); - * } - * - * The BinarySearchIf() version behaves similarly, but takes |aComparator|, a - * functor to compare the values with, instead of a value to find. - * That functor should take one argument - the value to compare - and return an - * |int| with the comparison result: - * - * * 0, if the argument is equal to, - * * less than 0, if the argument is greater than, - * * greater than 0, if the argument is less than - * - * the value. - * - * Example: - * - * struct Comparator { - * int operator()(int aVal) const { - * if (mTarget < aVal) { return -1; } - * if (mTarget > aVal) { return 1; } - * return 0; - * } - * explicit Comparator(int aTarget) : mTarget(aTarget) {} - * const int mTarget; - * }; - * - * Vector sortedInts = ... - * - * size_t match; - * if (BinarySearchIf(sortedInts, 0, sortedInts.length(), Comparator(13), &match)) { - * printf("found 13 at %lu\n", match); - * } - * - */ - -template -bool -BinarySearchIf(const Container& aContainer, size_t aBegin, size_t aEnd, - const Comparator& aCompare, size_t* aMatchOrInsertionPoint) -{ - MOZ_ASSERT(aBegin <= aEnd); - - size_t low = aBegin; - size_t high = aEnd; - while (high != low) { - size_t middle = low + (high - low) / 2; - - // Allow any intermediate type so long as it provides a suitable ordering - // relation. - const int result = aCompare(aContainer[middle]); - - if (result == 0) { - *aMatchOrInsertionPoint = middle; - return true; - } - - if (result < 0) { - high = middle; - } else { - low = middle + 1; - } - } - - *aMatchOrInsertionPoint = low; - return false; -} - -namespace detail { - -template -class BinarySearchDefaultComparator -{ -public: - explicit BinarySearchDefaultComparator(const T& aTarget) - : mTarget(aTarget) - {} - - template - int operator()(const U& aVal) const { - if (mTarget == aVal) { - return 0; - } - - if (mTarget < aVal) { - return -1; - } - - return 1; - } - -private: - const T& mTarget; -}; - -} // namespace detail - -template -bool -BinarySearch(const Container& aContainer, size_t aBegin, size_t aEnd, - T aTarget, size_t* aMatchOrInsertionPoint) -{ - return BinarySearchIf(aContainer, aBegin, aEnd, - detail::BinarySearchDefaultComparator(aTarget), - aMatchOrInsertionPoint); -} - -} // namespace mozilla - -#endif // mozilla_BinarySearch_h diff --git a/win32/include/spidermonkey/mozilla/BloomFilter.h b/win32/include/spidermonkey/mozilla/BloomFilter.h deleted file mode 100755 index 6757e411..00000000 --- a/win32/include/spidermonkey/mozilla/BloomFilter.h +++ /dev/null @@ -1,256 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * A counting Bloom filter implementation. This allows consumers to - * do fast probabilistic "is item X in set Y?" testing which will - * never answer "no" when the correct answer is "yes" (but might - * incorrectly answer "yes" when the correct answer is "no"). - */ - -#ifndef mozilla_BloomFilter_h -#define mozilla_BloomFilter_h - -#include "mozilla/Assertions.h" -#include "mozilla/Likely.h" - -#include -#include - -namespace mozilla { - -/* - * This class implements a counting Bloom filter as described at - * , with - * 8-bit counters. This allows quick probabilistic answers to the - * question "is object X in set Y?" where the contents of Y might not - * be time-invariant. The probabilistic nature of the test means that - * sometimes the answer will be "yes" when it should be "no". If the - * answer is "no", then X is guaranteed not to be in Y. - * - * The filter is parametrized on KeySize, which is the size of the key - * generated by each of hash functions used by the filter, in bits, - * and the type of object T being added and removed. T must implement - * a |uint32_t hash() const| method which returns a uint32_t hash key - * that will be used to generate the two separate hash functions for - * the Bloom filter. This hash key MUST be well-distributed for good - * results! KeySize is not allowed to be larger than 16. - * - * The filter uses exactly 2**KeySize bytes of memory. From now on we - * will refer to the memory used by the filter as M. - * - * The expected rate of incorrect "yes" answers depends on M and on - * the number N of objects in set Y. As long as N is small compared - * to M, the rate of such answers is expected to be approximately - * 4*(N/M)**2 for this filter. In practice, if Y has a few hundred - * elements then using a KeySize of 12 gives a reasonably low - * incorrect answer rate. A KeySize of 12 has the additional benefit - * of using exactly one page for the filter in typical hardware - * configurations. - */ - -template -class BloomFilter -{ - /* - * A counting Bloom filter with 8-bit counters. For now we assume - * that having two hash functions is enough, but we may revisit that - * decision later. - * - * The filter uses an array with 2**KeySize entries. - * - * Assuming a well-distributed hash function, a Bloom filter with - * array size M containing N elements and - * using k hash function has expected false positive rate exactly - * - * $ (1 - (1 - 1/M)^{kN})^k $ - * - * because each array slot has a - * - * $ (1 - 1/M)^{kN} $ - * - * chance of being 0, and the expected false positive rate is the - * probability that all of the k hash functions will hit a nonzero - * slot. - * - * For reasonable assumptions (M large, kN large, which should both - * hold if we're worried about false positives) about M and kN this - * becomes approximately - * - * $$ (1 - \exp(-kN/M))^k $$ - * - * For our special case of k == 2, that's $(1 - \exp(-2N/M))^2$, - * or in other words - * - * $$ N/M = -0.5 * \ln(1 - \sqrt(r)) $$ - * - * where r is the false positive rate. This can be used to compute - * the desired KeySize for a given load N and false positive rate r. - * - * If N/M is assumed small, then the false positive rate can - * further be approximated as 4*N^2/M^2. So increasing KeySize by - * 1, which doubles M, reduces the false positive rate by about a - * factor of 4, and a false positive rate of 1% corresponds to - * about M/N == 20. - * - * What this means in practice is that for a few hundred keys using a - * KeySize of 12 gives false positive rates on the order of 0.25-4%. - * - * Similarly, using a KeySize of 10 would lead to a 4% false - * positive rate for N == 100 and to quite bad false positive - * rates for larger N. - */ -public: - BloomFilter() - { - static_assert(KeySize <= kKeyShift, "KeySize too big"); - - // Should we have a custom operator new using calloc instead and - // require that we're allocated via the operator? - clear(); - } - - /* - * Clear the filter. This should be done before reusing it, because - * just removing all items doesn't clear counters that hit the upper - * bound. - */ - void clear(); - - /* - * Add an item to the filter. - */ - void add(const T* aValue); - - /* - * Remove an item from the filter. - */ - void remove(const T* aValue); - - /* - * Check whether the filter might contain an item. This can - * sometimes return true even if the item is not in the filter, - * but will never return false for items that are actually in the - * filter. - */ - bool mightContain(const T* aValue) const; - - /* - * Methods for add/remove/contain when we already have a hash computed - */ - void add(uint32_t aHash); - void remove(uint32_t aHash); - bool mightContain(uint32_t aHash) const; - -private: - static const size_t kArraySize = (1 << KeySize); - static const uint32_t kKeyMask = (1 << KeySize) - 1; - static const uint32_t kKeyShift = 16; - - static uint32_t hash1(uint32_t aHash) - { - return aHash & kKeyMask; - } - static uint32_t hash2(uint32_t aHash) - { - return (aHash >> kKeyShift) & kKeyMask; - } - - uint8_t& firstSlot(uint32_t aHash) - { - return mCounters[hash1(aHash)]; - } - uint8_t& secondSlot(uint32_t aHash) - { - return mCounters[hash2(aHash)]; - } - - const uint8_t& firstSlot(uint32_t aHash) const - { - return mCounters[hash1(aHash)]; - } - const uint8_t& secondSlot(uint32_t aHash) const - { - return mCounters[hash2(aHash)]; - } - - static bool full(const uint8_t& aSlot) { return aSlot == UINT8_MAX; } - - uint8_t mCounters[kArraySize]; -}; - -template -inline void -BloomFilter::clear() -{ - memset(mCounters, 0, kArraySize); -} - -template -inline void -BloomFilter::add(uint32_t aHash) -{ - uint8_t& slot1 = firstSlot(aHash); - if (MOZ_LIKELY(!full(slot1))) { - ++slot1; - } - uint8_t& slot2 = secondSlot(aHash); - if (MOZ_LIKELY(!full(slot2))) { - ++slot2; - } -} - -template -MOZ_ALWAYS_INLINE void -BloomFilter::add(const T* aValue) -{ - uint32_t hash = aValue->hash(); - return add(hash); -} - -template -inline void -BloomFilter::remove(uint32_t aHash) -{ - // If the slots are full, we don't know whether we bumped them to be - // there when we added or not, so just leave them full. - uint8_t& slot1 = firstSlot(aHash); - if (MOZ_LIKELY(!full(slot1))) { - --slot1; - } - uint8_t& slot2 = secondSlot(aHash); - if (MOZ_LIKELY(!full(slot2))) { - --slot2; - } -} - -template -MOZ_ALWAYS_INLINE void -BloomFilter::remove(const T* aValue) -{ - uint32_t hash = aValue->hash(); - remove(hash); -} - -template -MOZ_ALWAYS_INLINE bool -BloomFilter::mightContain(uint32_t aHash) const -{ - // Check that all the slots for this hash contain something - return firstSlot(aHash) && secondSlot(aHash); -} - -template -MOZ_ALWAYS_INLINE bool -BloomFilter::mightContain(const T* aValue) const -{ - uint32_t hash = aValue->hash(); - return mightContain(hash); -} - -} // namespace mozilla - -#endif /* mozilla_BloomFilter_h */ diff --git a/win32/include/spidermonkey/mozilla/BufferList.h b/win32/include/spidermonkey/mozilla/BufferList.h deleted file mode 100755 index 42aea12d..00000000 --- a/win32/include/spidermonkey/mozilla/BufferList.h +++ /dev/null @@ -1,517 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_BufferList_h -#define mozilla_BufferList_h - -#include -#include "mozilla/AllocPolicy.h" -#include "mozilla/Move.h" -#include "mozilla/ScopeExit.h" -#include "mozilla/Types.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Vector.h" -#include - -// BufferList represents a sequence of buffers of data. A BufferList can choose -// to own its buffers or not. The class handles writing to the buffers, -// iterating over them, and reading data out. Unlike SegmentedVector, the -// buffers may be of unequal size. Like SegmentedVector, BufferList is a nice -// way to avoid large contiguous allocations (which can trigger OOMs). - -namespace mozilla { - -template -class BufferList : private AllocPolicy -{ - // Each buffer in a BufferList has a size and a capacity. The first mSize - // bytes are initialized and the remaining |mCapacity - mSize| bytes are free. - struct Segment - { - char* mData; - size_t mSize; - size_t mCapacity; - - Segment(char* aData, size_t aSize, size_t aCapacity) - : mData(aData), - mSize(aSize), - mCapacity(aCapacity) - { - } - - Segment(const Segment&) = delete; - Segment& operator=(const Segment&) = delete; - - Segment(Segment&&) = default; - Segment& operator=(Segment&&) = default; - - char* Start() const { return mData; } - char* End() const { return mData + mSize; } - }; - - template - friend class BufferList; - - public: - // For the convenience of callers, all segments are required to be a multiple - // of 8 bytes in capacity. Also, every buffer except the last one is required - // to be full (i.e., size == capacity). Therefore, a byte at offset N within - // the BufferList and stored in memory at an address A will satisfy - // (N % Align == A % Align) if Align == 2, 4, or 8. - static const size_t kSegmentAlignment = 8; - - // Allocate a BufferList. The BufferList will free all its buffers when it is - // destroyed. An initial buffer of size aInitialSize and capacity - // aInitialCapacity is allocated automatically. This data will be contiguous - // an can be accessed via |Start()|. Subsequent buffers will be allocated with - // capacity aStandardCapacity. - BufferList(size_t aInitialSize, - size_t aInitialCapacity, - size_t aStandardCapacity, - AllocPolicy aAP = AllocPolicy()) - : AllocPolicy(aAP), - mOwning(true), - mSegments(aAP), - mSize(0), - mStandardCapacity(aStandardCapacity) - { - MOZ_ASSERT(aInitialCapacity % kSegmentAlignment == 0); - MOZ_ASSERT(aStandardCapacity % kSegmentAlignment == 0); - - if (aInitialCapacity) { - AllocateSegment(aInitialSize, aInitialCapacity); - } - } - - BufferList(const BufferList& aOther) = delete; - - BufferList(BufferList&& aOther) - : mOwning(aOther.mOwning), - mSegments(Move(aOther.mSegments)), - mSize(aOther.mSize), - mStandardCapacity(aOther.mStandardCapacity) - { - aOther.mSegments.clear(); - aOther.mSize = 0; - } - - BufferList& operator=(const BufferList& aOther) = delete; - - BufferList& operator=(BufferList&& aOther) - { - Clear(); - - mOwning = aOther.mOwning; - mSegments = Move(aOther.mSegments); - mSize = aOther.mSize; - aOther.mSegments.clear(); - aOther.mSize = 0; - return *this; - } - - ~BufferList() { Clear(); } - - // Returns the sum of the sizes of all the buffers. - size_t Size() const { return mSize; } - - void Clear() - { - if (mOwning) { - for (Segment& segment : mSegments) { - this->free_(segment.mData); - } - } - mSegments.clear(); - - mSize = 0; - } - - // Iterates over bytes in the segments. You can advance it by as many bytes as - // you choose. - class IterImpl - { - // Invariants: - // (0) mSegment <= bufferList.mSegments.size() - // (1) mData <= mDataEnd - // (2) If mSegment is not the last segment, mData < mDataEnd - uintptr_t mSegment; - char* mData; - char* mDataEnd; - - friend class BufferList; - - public: - explicit IterImpl(const BufferList& aBuffers) - : mSegment(0), - mData(nullptr), - mDataEnd(nullptr) - { - if (!aBuffers.mSegments.empty()) { - mData = aBuffers.mSegments[0].Start(); - mDataEnd = aBuffers.mSegments[0].End(); - } - } - - // Returns a pointer to the raw data. It is valid to access up to - // RemainingInSegment bytes of this buffer. - char* Data() const - { - MOZ_RELEASE_ASSERT(!Done()); - return mData; - } - - // Returns true if the memory in the range [Data(), Data() + aBytes) is all - // part of one contiguous buffer. - bool HasRoomFor(size_t aBytes) const - { - MOZ_RELEASE_ASSERT(mData <= mDataEnd); - return size_t(mDataEnd - mData) >= aBytes; - } - - // Returns the maximum value aBytes for which HasRoomFor(aBytes) will be - // true. - size_t RemainingInSegment() const - { - MOZ_RELEASE_ASSERT(mData <= mDataEnd); - return mDataEnd - mData; - } - - // Advances the iterator by aBytes bytes. aBytes must be less than - // RemainingInSegment(). If advancing by aBytes takes the iterator to the - // end of a buffer, it will be moved to the beginning of the next buffer - // unless it is the last buffer. - void Advance(const BufferList& aBuffers, size_t aBytes) - { - const Segment& segment = aBuffers.mSegments[mSegment]; - MOZ_RELEASE_ASSERT(segment.Start() <= mData); - MOZ_RELEASE_ASSERT(mData <= mDataEnd); - MOZ_RELEASE_ASSERT(mDataEnd == segment.End()); - - MOZ_RELEASE_ASSERT(HasRoomFor(aBytes)); - mData += aBytes; - - if (mData == mDataEnd && mSegment + 1 < aBuffers.mSegments.length()) { - mSegment++; - const Segment& nextSegment = aBuffers.mSegments[mSegment]; - mData = nextSegment.Start(); - mDataEnd = nextSegment.End(); - MOZ_RELEASE_ASSERT(mData < mDataEnd); - } - } - - // Advance the iterator by aBytes, possibly crossing segments. This function - // returns false if it runs out of buffers to advance through. Otherwise it - // returns true. - bool AdvanceAcrossSegments(const BufferList& aBuffers, size_t aBytes) - { - size_t bytes = aBytes; - while (bytes) { - size_t toAdvance = std::min(bytes, RemainingInSegment()); - if (!toAdvance) { - return false; - } - Advance(aBuffers, toAdvance); - bytes -= toAdvance; - } - return true; - } - - // Returns true when the iterator reaches the end of the BufferList. - bool Done() const - { - return mData == mDataEnd; - } - - private: - - // Count the bytes we would need to advance in order to reach aTarget. - size_t BytesUntil(const BufferList& aBuffers, const IterImpl& aTarget) const { - size_t offset = 0; - - MOZ_ASSERT(aTarget.IsIn(aBuffers)); - - char* data = mData; - for (uintptr_t segment = mSegment; segment < aTarget.mSegment; segment++) { - offset += aBuffers.mSegments[segment].End() - data; - data = aBuffers.mSegments[segment].mData; - } - - MOZ_RELEASE_ASSERT(IsIn(aBuffers)); - MOZ_RELEASE_ASSERT(aTarget.mData >= data); - - offset += aTarget.mData - data; - return offset; - } - - bool IsIn(const BufferList& aBuffers) const { - return mSegment < aBuffers.mSegments.length() && - mData >= aBuffers.mSegments[mSegment].mData && - mData < aBuffers.mSegments[mSegment].End(); - } - }; - - // Special convenience method that returns Iter().Data(). - char* Start() { return mSegments[0].mData; } - const char* Start() const { return mSegments[0].mData; } - - IterImpl Iter() const { return IterImpl(*this); } - - // Copies aSize bytes from aData into the BufferList. The storage for these - // bytes may be split across multiple buffers. Size() is increased by aSize. - inline bool WriteBytes(const char* aData, size_t aSize); - - // Copies possibly non-contiguous byte range starting at aIter into - // aData. aIter is advanced by aSize bytes. Returns false if it runs out of - // data before aSize. - inline bool ReadBytes(IterImpl& aIter, char* aData, size_t aSize) const; - - // Return a new BufferList that shares storage with this BufferList. The new - // BufferList is read-only. It allows iteration over aSize bytes starting at - // aIter. Borrow can fail, in which case *aSuccess will be false upon - // return. The borrowed BufferList can use a different AllocPolicy than the - // original one. However, it is not responsible for freeing buffers, so the - // AllocPolicy is only used for the buffer vector. - template - BufferList Borrow(IterImpl& aIter, size_t aSize, bool* aSuccess, - BorrowingAllocPolicy aAP = BorrowingAllocPolicy()) const; - - // Return a new BufferList and move storage from this BufferList to it. The - // new BufferList owns the buffers. Move can fail, in which case *aSuccess - // will be false upon return. The new BufferList can use a different - // AllocPolicy than the original one. The new OtherAllocPolicy is responsible - // for freeing buffers, so the OtherAllocPolicy must use freeing method - // compatible to the original one. - template - BufferList MoveFallible(bool* aSuccess, OtherAllocPolicy aAP = OtherAllocPolicy()); - - // Return a new BufferList that adopts the byte range starting at Iter so that - // range [aIter, aIter + aSize) is transplanted to the returned BufferList. - // Contents of the buffer before aIter + aSize is left undefined. - // Extract can fail, in which case *aSuccess will be false upon return. The - // moved buffers are erased from the original BufferList. In case of extract - // fails, the original BufferList is intact. All other iterators except aIter - // are invalidated. - // This method requires aIter and aSize to be 8-byte aligned. - BufferList Extract(IterImpl& aIter, size_t aSize, bool* aSuccess); - - // Return the number of bytes from 'start' to 'end', two iterators within - // this BufferList. - size_t RangeLength(const IterImpl& start, const IterImpl& end) const { - MOZ_ASSERT(start.IsIn(*this) && end.IsIn(*this)); - return start.BytesUntil(*this, end); - } - -private: - explicit BufferList(AllocPolicy aAP) - : AllocPolicy(aAP), - mOwning(false), - mSize(0), - mStandardCapacity(0) - { - } - - void* AllocateSegment(size_t aSize, size_t aCapacity) - { - MOZ_RELEASE_ASSERT(mOwning); - - char* data = this->template pod_malloc(aCapacity); - if (!data) { - return nullptr; - } - if (!mSegments.append(Segment(data, aSize, aCapacity))) { - this->free_(data); - return nullptr; - } - mSize += aSize; - return data; - } - - bool mOwning; - Vector mSegments; - size_t mSize; - size_t mStandardCapacity; -}; - -template -bool -BufferList::WriteBytes(const char* aData, size_t aSize) -{ - MOZ_RELEASE_ASSERT(mOwning); - MOZ_RELEASE_ASSERT(mStandardCapacity); - - size_t copied = 0; - size_t remaining = aSize; - - if (!mSegments.empty()) { - Segment& lastSegment = mSegments.back(); - - size_t toCopy = std::min(aSize, lastSegment.mCapacity - lastSegment.mSize); - memcpy(lastSegment.mData + lastSegment.mSize, aData, toCopy); - lastSegment.mSize += toCopy; - mSize += toCopy; - - copied += toCopy; - remaining -= toCopy; - } - - while (remaining) { - size_t toCopy = std::min(remaining, mStandardCapacity); - - void* data = AllocateSegment(toCopy, mStandardCapacity); - if (!data) { - return false; - } - memcpy(data, aData + copied, toCopy); - - copied += toCopy; - remaining -= toCopy; - } - - return true; -} - -template -bool -BufferList::ReadBytes(IterImpl& aIter, char* aData, size_t aSize) const -{ - size_t copied = 0; - size_t remaining = aSize; - while (remaining) { - size_t toCopy = std::min(aIter.RemainingInSegment(), remaining); - if (!toCopy) { - // We've run out of data in the last segment. - return false; - } - memcpy(aData + copied, aIter.Data(), toCopy); - copied += toCopy; - remaining -= toCopy; - - aIter.Advance(*this, toCopy); - } - - return true; -} - -template template -BufferList -BufferList::Borrow(IterImpl& aIter, size_t aSize, bool* aSuccess, - BorrowingAllocPolicy aAP) const -{ - BufferList result(aAP); - - size_t size = aSize; - while (size) { - size_t toAdvance = std::min(size, aIter.RemainingInSegment()); - - if (!toAdvance || !result.mSegments.append(typename BufferList::Segment(aIter.mData, toAdvance, toAdvance))) { - *aSuccess = false; - return result; - } - aIter.Advance(*this, toAdvance); - size -= toAdvance; - } - - result.mSize = aSize; - *aSuccess = true; - return result; -} - -template template -BufferList -BufferList::MoveFallible(bool* aSuccess, OtherAllocPolicy aAP) -{ - BufferList result(0, 0, mStandardCapacity, aAP); - - IterImpl iter = Iter(); - while (!iter.Done()) { - size_t toAdvance = iter.RemainingInSegment(); - - if (!toAdvance || !result.mSegments.append(typename BufferList::Segment(iter.mData, toAdvance, toAdvance))) { - *aSuccess = false; - result.mSegments.clear(); - return result; - } - iter.Advance(*this, toAdvance); - } - - result.mSize = mSize; - mSegments.clear(); - mSize = 0; - *aSuccess = true; - return result; -} - -template -BufferList -BufferList::Extract(IterImpl& aIter, size_t aSize, bool* aSuccess) -{ - MOZ_RELEASE_ASSERT(aSize); - MOZ_RELEASE_ASSERT(mOwning); - MOZ_ASSERT(aSize % kSegmentAlignment == 0); - MOZ_ASSERT(intptr_t(aIter.mData) % kSegmentAlignment == 0); - - IterImpl iter = aIter; - size_t size = aSize; - size_t toCopy = std::min(size, aIter.RemainingInSegment()); - MOZ_ASSERT(toCopy % kSegmentAlignment == 0); - - BufferList result(0, toCopy, mStandardCapacity); - BufferList error(0, 0, mStandardCapacity); - - // Copy the head - if (!result.WriteBytes(aIter.mData, toCopy)) { - *aSuccess = false; - return error; - } - iter.Advance(*this, toCopy); - size -= toCopy; - - // Move segments to result - auto resultGuard = MakeScopeExit([&] { - *aSuccess = false; - result.mSegments.erase(result.mSegments.begin()+1, result.mSegments.end()); - }); - - size_t movedSize = 0; - uintptr_t toRemoveStart = iter.mSegment; - uintptr_t toRemoveEnd = iter.mSegment; - while (!iter.Done() && - !iter.HasRoomFor(size)) { - if (!result.mSegments.append(Segment(mSegments[iter.mSegment].mData, - mSegments[iter.mSegment].mSize, - mSegments[iter.mSegment].mCapacity))) { - return error; - } - movedSize += iter.RemainingInSegment(); - size -= iter.RemainingInSegment(); - toRemoveEnd++; - iter.Advance(*this, iter.RemainingInSegment()); - } - - if (size) { - if (!iter.HasRoomFor(size) || - !result.WriteBytes(iter.Data(), size)) { - return error; - } - iter.Advance(*this, size); - } - - mSegments.erase(mSegments.begin() + toRemoveStart, mSegments.begin() + toRemoveEnd); - mSize -= movedSize; - aIter.mSegment = iter.mSegment - (toRemoveEnd - toRemoveStart); - aIter.mData = iter.mData; - aIter.mDataEnd = iter.mDataEnd; - MOZ_ASSERT(aIter.mDataEnd == mSegments[aIter.mSegment].End()); - result.mSize = aSize; - - resultGuard.release(); - *aSuccess = true; - return result; -} - -} // namespace mozilla - -#endif /* mozilla_BufferList_h */ diff --git a/win32/include/spidermonkey/mozilla/Casting.h b/win32/include/spidermonkey/mozilla/Casting.h deleted file mode 100755 index a7d0fb50..00000000 --- a/win32/include/spidermonkey/mozilla/Casting.h +++ /dev/null @@ -1,243 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Cast operations to supplement the built-in casting operations. */ - -#ifndef mozilla_Casting_h -#define mozilla_Casting_h - -#include "mozilla/Assertions.h" -#include "mozilla/TypeTraits.h" - -#include - -namespace mozilla { - -/** - * Sets the outparam value of type |To| with the same underlying bit pattern of - * |aFrom|. - * - * |To| and |From| must be types of the same size; be careful of cross-platform - * size differences, or this might fail to compile on some but not all - * platforms. - * - * There is also a variant that returns the value directly. In most cases, the - * two variants should be identical. However, in the specific case of x86 - * chips, the behavior differs: returning floating-point values directly is done - * through the x87 stack, and x87 loads and stores turn signaling NaNs into - * quiet NaNs... silently. Returning floating-point values via outparam, - * however, is done entirely within the SSE registers when SSE2 floating-point - * is enabled in the compiler, which has semantics-preserving behavior you would - * expect. - * - * If preserving the distinction between signaling NaNs and quiet NaNs is - * important to you, you should use the outparam version. In all other cases, - * you should use the direct return version. - */ -template -inline void -BitwiseCast(const From aFrom, To* aResult) -{ - static_assert(sizeof(From) == sizeof(To), - "To and From must have the same size"); - union - { - From mFrom; - To mTo; - } u; - u.mFrom = aFrom; - *aResult = u.mTo; -} - -template -inline To -BitwiseCast(const From aFrom) -{ - To temp; - BitwiseCast(aFrom, &temp); - return temp; -} - -namespace detail { - -enum ToSignedness { ToIsSigned, ToIsUnsigned }; -enum FromSignedness { FromIsSigned, FromIsUnsigned }; - -template::value ? FromIsSigned : FromIsUnsigned, - ToSignedness = IsSigned::value ? ToIsSigned : ToIsUnsigned> -struct BoundsCheckImpl; - -// Implicit conversions on operands to binary operations make this all a bit -// hard to verify. Attempt to ease the pain below by *only* comparing values -// that are obviously the same type (and will undergo no further conversions), -// even when it's not strictly necessary, for explicitness. - -enum UUComparison { FromIsBigger, FromIsNotBigger }; - -// Unsigned-to-unsigned range check - -template sizeof(To)) - ? FromIsBigger - : FromIsNotBigger> -struct UnsignedUnsignedCheck; - -template -struct UnsignedUnsignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - return aFrom <= From(To(-1)); - } -}; - -template -struct UnsignedUnsignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - return true; - } -}; - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - return UnsignedUnsignedCheck::checkBounds(aFrom); - } -}; - -// Signed-to-unsigned range check - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - if (aFrom < 0) { - return false; - } - if (sizeof(To) >= sizeof(From)) { - return true; - } - return aFrom <= From(To(-1)); - } -}; - -// Unsigned-to-signed range check - -enum USComparison { FromIsSmaller, FromIsNotSmaller }; - -template -struct UnsignedSignedCheck; - -template -struct UnsignedSignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - return true; - } -}; - -template -struct UnsignedSignedCheck -{ -public: - static bool checkBounds(const From aFrom) - { - const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); - return aFrom <= From(MaxValue); - } -}; - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - return UnsignedSignedCheck::checkBounds(aFrom); - } -}; - -// Signed-to-signed range check - -template -struct BoundsCheckImpl -{ -public: - static bool checkBounds(const From aFrom) - { - if (sizeof(From) <= sizeof(To)) { - return true; - } - const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1); - const To MinValue = -MaxValue - To(1); - return From(MinValue) <= aFrom && - From(aFrom) <= From(MaxValue); - } -}; - -template::value && - IsIntegral::value> -class BoundsChecker; - -template -class BoundsChecker -{ -public: - static bool checkBounds(const From aFrom) { return true; } -}; - -template -class BoundsChecker -{ -public: - static bool checkBounds(const From aFrom) - { - return BoundsCheckImpl::checkBounds(aFrom); - } -}; - -template -inline bool -IsInBounds(const From aFrom) -{ - return BoundsChecker::checkBounds(aFrom); -} - -} // namespace detail - -/** - * Cast a value of integral type |From| to a value of integral type |To|, - * asserting that the cast will be a safe cast per C++ (that is, that |to| is in - * the range of values permitted for the type |From|). - */ -template -inline To -AssertedCast(const From aFrom) -{ - MOZ_ASSERT((detail::IsInBounds(aFrom))); - return static_cast(aFrom); -} - -} // namespace mozilla - -#endif /* mozilla_Casting_h */ diff --git a/win32/include/spidermonkey/mozilla/ChaosMode.h b/win32/include/spidermonkey/mozilla/ChaosMode.h deleted file mode 100755 index 94833c39..00000000 --- a/win32/include/spidermonkey/mozilla/ChaosMode.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_ChaosMode_h -#define mozilla_ChaosMode_h - -#include "mozilla/Atomics.h" -#include "mozilla/EnumSet.h" - -#include -#include - -namespace mozilla { - -enum ChaosFeature { - None = 0x0, - // Altering thread scheduling. - ThreadScheduling = 0x1, - // Altering network request scheduling. - NetworkScheduling = 0x2, - // Altering timer scheduling. - TimerScheduling = 0x4, - // Read and write less-than-requested amounts. - IOAmounts = 0x8, - // Iterate over hash tables in random order. - HashTableIteration = 0x10, - // Randomly refuse to use cached version of image (when allowed by spec). - ImageCache = 0x20, - Any = 0xffffffff, -}; - -namespace detail { -extern MFBT_DATA Atomic gChaosModeCounter; -extern MFBT_DATA ChaosFeature gChaosFeatures; -} // namespace detail - -/** - * When "chaos mode" is activated, code that makes implicitly nondeterministic - * choices is encouraged to make random and extreme choices, to test more - * code paths and uncover bugs. - */ -class ChaosMode -{ -public: - static void SetChaosFeature(ChaosFeature aChaosFeature) - { - detail::gChaosFeatures = aChaosFeature; - } - - static bool isActive(ChaosFeature aFeature) - { - if (detail::gChaosModeCounter > 0) { - return true; - } - return detail::gChaosFeatures & aFeature; - } - - /** - * Increase the chaos mode activation level. An equivalent number of - * calls to leaveChaosMode must be made in order to restore the original - * chaos mode state. If the activation level is nonzero all chaos mode - * features are activated. - */ - static void enterChaosMode() - { - detail::gChaosModeCounter++; - } - - /** - * Decrease the chaos mode activation level. See enterChaosMode(). - */ - static void leaveChaosMode() - { - MOZ_ASSERT(detail::gChaosModeCounter > 0); - detail::gChaosModeCounter--; - } - - /** - * Returns a somewhat (but not uniformly) random uint32_t < aBound. - * Not to be used for anything except ChaosMode, since it's not very random. - */ - static uint32_t randomUint32LessThan(uint32_t aBound) - { - MOZ_ASSERT(aBound != 0); - return uint32_t(rand()) % aBound; - } -}; - -} /* namespace mozilla */ - -#endif /* mozilla_ChaosMode_h */ diff --git a/win32/include/spidermonkey/mozilla/Char16.h b/win32/include/spidermonkey/mozilla/Char16.h deleted file mode 100755 index 3c2f254a..00000000 --- a/win32/include/spidermonkey/mozilla/Char16.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements a UTF-16 character type. */ - -#ifndef mozilla_Char16_h -#define mozilla_Char16_h - -#ifdef __cplusplus - -/* - * C++11 introduces a char16_t type and support for UTF-16 string and character - * literals. C++11's char16_t is a distinct builtin type. Technically, char16_t - * is a 16-bit code unit of a Unicode code point, not a "character". - */ - -#ifdef WIN32 -# define MOZ_USE_CHAR16_WRAPPER -# include - /** - * Win32 API extensively uses wchar_t, which is represented by a separated - * builtin type than char16_t per spec. It's not the case for MSVC prior to - * MSVC 2015, but other compilers follow the spec. We want to mix wchar_t and - * char16_t on Windows builds. This class is supposed to make it easier. It - * stores char16_t const pointer, but provides implicit casts for wchar_t as - * well. On other platforms, we simply use - * |typedef const char16_t* char16ptr_t|. Here, we want to make the class as - * similar to this typedef, including providing some casts that are allowed - * by the typedef. - */ -class char16ptr_t -{ -private: - const char16_t* mPtr; - static_assert(sizeof(char16_t) == sizeof(wchar_t), - "char16_t and wchar_t sizes differ"); - -public: - char16ptr_t(const char16_t* aPtr) : mPtr(aPtr) {} - char16ptr_t(const wchar_t* aPtr) : - mPtr(reinterpret_cast(aPtr)) - {} - - /* Without this, nullptr assignment would be ambiguous. */ - constexpr char16ptr_t(decltype(nullptr)) : mPtr(nullptr) {} - - operator const char16_t*() const - { - return mPtr; - } - operator const wchar_t*() const - { - return reinterpret_cast(mPtr); - } - operator const void*() const - { - return mPtr; - } - operator bool() const - { - return mPtr != nullptr; - } - - /* Explicit cast operators to allow things like (char16_t*)str. */ - explicit operator char16_t*() const - { - return const_cast(mPtr); - } - explicit operator wchar_t*() const - { - return const_cast(static_cast(*this)); - } - explicit operator int() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned int() const - { - return reinterpret_cast(mPtr); - } - explicit operator long() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned long() const - { - return reinterpret_cast(mPtr); - } - explicit operator long long() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned long long() const - { - return reinterpret_cast(mPtr); - } - - /** - * Some Windows API calls accept BYTE* but require that data actually be - * WCHAR*. Supporting this requires explicit operators to support the - * requisite explicit casts. - */ - explicit operator const char*() const - { - return reinterpret_cast(mPtr); - } - explicit operator const unsigned char*() const - { - return reinterpret_cast(mPtr); - } - explicit operator unsigned char*() const - { - return - const_cast(reinterpret_cast(mPtr)); - } - explicit operator void*() const - { - return const_cast(mPtr); - } - - /* Some operators used on pointers. */ - char16_t operator[](size_t aIndex) const - { - return mPtr[aIndex]; - } - bool operator==(const char16ptr_t& aOther) const - { - return mPtr == aOther.mPtr; - } - bool operator==(decltype(nullptr)) const - { - return mPtr == nullptr; - } - bool operator!=(const char16ptr_t& aOther) const - { - return mPtr != aOther.mPtr; - } - bool operator!=(decltype(nullptr)) const - { - return mPtr != nullptr; - } - char16ptr_t operator+(int aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(unsigned int aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(unsigned long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(long long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - char16ptr_t operator+(unsigned long long aValue) const - { - return char16ptr_t(mPtr + aValue); - } - ptrdiff_t operator-(const char16ptr_t& aOther) const - { - return mPtr - aOther.mPtr; - } -}; - -inline decltype((char*)0-(char*)0) -operator-(const char16_t* aX, const char16ptr_t aY) -{ - return aX - static_cast(aY); -} - -#else - -typedef const char16_t* char16ptr_t; - -#endif - -static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); -static_assert(char16_t(-1) > char16_t(0), "Is char16_t type unsigned?"); -static_assert(sizeof(u'A') == 2, "Is unicode char literal 16 bits?"); -static_assert(sizeof(u""[0]) == 2, "Is unicode string char 16 bits?"); - -#endif - -#endif /* mozilla_Char16_h */ diff --git a/win32/include/spidermonkey/mozilla/CheckedInt.h b/win32/include/spidermonkey/mozilla/CheckedInt.h deleted file mode 100755 index 02ef8d5b..00000000 --- a/win32/include/spidermonkey/mozilla/CheckedInt.h +++ /dev/null @@ -1,791 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Provides checked integers, detecting integer overflow and divide-by-0. */ - -#ifndef mozilla_CheckedInt_h -#define mozilla_CheckedInt_h - -#include -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/IntegerTypeTraits.h" - -namespace mozilla { - -template class CheckedInt; - -namespace detail { - -/* - * Step 1: manually record supported types - * - * What's nontrivial here is that there are different families of integer - * types: basic integer types and stdint types. It is merrily undefined which - * types from one family may be just typedefs for a type from another family. - * - * For example, on GCC 4.6, aside from the basic integer types, the only other - * type that isn't just a typedef for some of them, is int8_t. - */ - -struct UnsupportedType {}; - -template -struct IsSupportedPass2 -{ - static const bool value = false; -}; - -template -struct IsSupported -{ - static const bool value = IsSupportedPass2::value; -}; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - -template<> -struct IsSupported -{ static const bool value = true; }; - - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -template<> -struct IsSupportedPass2 -{ static const bool value = true; }; - -/* - * Step 2: Implement the actual validity checks. - * - * Ideas taken from IntegerLib, code different. - */ - -template -struct TwiceBiggerType -{ - typedef typename detail::StdintTypeForSizeAndSignedness< - sizeof(IntegerType) * 2, - IsSigned::value - >::Type Type; -}; - -template -struct TwiceBiggerType -{ - typedef UnsupportedType Type; -}; - -template -inline bool -HasSignBit(T aX) -{ - // In C++, right bit shifts on negative values is undefined by the standard. - // Notice that signed-to-unsigned conversions are always well-defined in the - // standard, as the value congruent modulo 2**n as expected. By contrast, - // unsigned-to-signed is only well-defined if the value is representable. - return bool(typename MakeUnsigned::Type(aX) >> - PositionOfSignBit::value); -} - -// Bitwise ops may return a larger type, so it's good to use this inline -// helper guaranteeing that the result is really of type T. -template -inline T -BinaryComplement(T aX) -{ - return ~aX; -} - -template::value, - bool IsUSigned = IsSigned::value> -struct DoesRangeContainRange -{ -}; - -template -struct DoesRangeContainRange -{ - static const bool value = sizeof(T) >= sizeof(U); -}; - -template -struct DoesRangeContainRange -{ - static const bool value = sizeof(T) > sizeof(U); -}; - -template -struct DoesRangeContainRange -{ - static const bool value = false; -}; - -template::value, - bool IsUSigned = IsSigned::value, - bool DoesTRangeContainURange = DoesRangeContainRange::value> -struct IsInRangeImpl {}; - -template -struct IsInRangeImpl -{ - static bool run(U) - { - return true; - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return aX <= MaxValue::value && aX >= MinValue::value; - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return aX <= MaxValue::value; - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return sizeof(T) > sizeof(U) || aX <= U(MaxValue::value); - } -}; - -template -struct IsInRangeImpl -{ - static bool run(U aX) - { - return sizeof(T) >= sizeof(U) - ? aX >= 0 - : aX >= 0 && aX <= U(MaxValue::value); - } -}; - -template -inline bool -IsInRange(U aX) -{ - return IsInRangeImpl::run(aX); -} - -template -inline bool -IsAddValid(T aX, T aY) -{ - // Addition is valid if the sign of aX+aY is equal to either that of aX or - // that of aY. Since the value of aX+aY is undefined if we have a signed - // type, we compute it using the unsigned type of the same size. Beware! - // These bitwise operations can return a larger integer type, if T was a - // small type like int8_t, so we explicitly cast to T. - - typename MakeUnsigned::Type ux = aX; - typename MakeUnsigned::Type uy = aY; - typename MakeUnsigned::Type result = ux + uy; - return IsSigned::value - ? HasSignBit(BinaryComplement(T((result ^ aX) & (result ^ aY)))) - : BinaryComplement(aX) >= aY; -} - -template -inline bool -IsSubValid(T aX, T aY) -{ - // Subtraction is valid if either aX and aY have same sign, or aX-aY and aX - // have same sign. Since the value of aX-aY is undefined if we have a signed - // type, we compute it using the unsigned type of the same size. - typename MakeUnsigned::Type ux = aX; - typename MakeUnsigned::Type uy = aY; - typename MakeUnsigned::Type result = ux - uy; - - return IsSigned::value - ? HasSignBit(BinaryComplement(T((result ^ aX) & (aX ^ aY)))) - : aX >= aY; -} - -template::value, - bool TwiceBiggerTypeIsSupported = - IsSupported::Type>::value> -struct IsMulValidImpl {}; - -template -struct IsMulValidImpl -{ - static bool run(T aX, T aY) - { - typedef typename TwiceBiggerType::Type TwiceBiggerType; - TwiceBiggerType product = TwiceBiggerType(aX) * TwiceBiggerType(aY); - return IsInRange(product); - } -}; - -template -struct IsMulValidImpl -{ - static bool run(T aX, T aY) - { - const T max = MaxValue::value; - const T min = MinValue::value; - - if (aX == 0 || aY == 0) { - return true; - } - if (aX > 0) { - return aY > 0 - ? aX <= max / aY - : aY >= min / aX; - } - - // If we reach this point, we know that aX < 0. - return aY > 0 - ? aX >= min / aY - : aY >= max / aX; - } -}; - -template -struct IsMulValidImpl -{ - static bool run(T aX, T aY) - { - return aY == 0 || aX <= MaxValue::value / aY; - } -}; - -template -inline bool -IsMulValid(T aX, T aY) -{ - return IsMulValidImpl::run(aX, aY); -} - -template -inline bool -IsDivValid(T aX, T aY) -{ - // Keep in mind that in the signed case, min/-1 is invalid because - // abs(min)>max. - return aY != 0 && - !(IsSigned::value && aX == MinValue::value && aY == T(-1)); -} - -template::value> -struct IsModValidImpl; - -template -inline bool -IsModValid(T aX, T aY) -{ - return IsModValidImpl::run(aX, aY); -} - -/* - * Mod is pretty simple. - * For now, let's just use the ANSI C definition: - * If aX or aY are negative, the results are implementation defined. - * Consider these invalid. - * Undefined for aY=0. - * The result will never exceed either aX or aY. - * - * Checking that aX>=0 is a warning when T is unsigned. - */ - -template -struct IsModValidImpl -{ - static inline bool run(T aX, T aY) - { - return aY >= 1; - } -}; - -template -struct IsModValidImpl -{ - static inline bool run(T aX, T aY) - { - if (aX < 0) { - return false; - } - return aY >= 1; - } -}; - -template::value> -struct NegateImpl; - -template -struct NegateImpl -{ - static CheckedInt negate(const CheckedInt& aVal) - { - // Handle negation separately for signed/unsigned, for simpler code and to - // avoid an MSVC warning negating an unsigned value. - return CheckedInt(0, aVal.isValid() && aVal.mValue == 0); - } -}; - -template -struct NegateImpl -{ - static CheckedInt negate(const CheckedInt& aVal) - { - // Watch out for the min-value, which (with twos-complement) can't be - // negated as -min-value is then (max-value + 1). - if (!aVal.isValid() || aVal.mValue == MinValue::value) { - return CheckedInt(aVal.mValue, false); - } - return CheckedInt(-aVal.mValue, true); - } -}; - -} // namespace detail - - -/* - * Step 3: Now define the CheckedInt class. - */ - -/** - * @class CheckedInt - * @brief Integer wrapper class checking for integer overflow and other errors - * @param T the integer type to wrap. Can be any type among the following: - * - any basic integer type such as |int| - * - any stdint type such as |int8_t| - * - * This class implements guarded integer arithmetic. Do a computation, check - * that isValid() returns true, you then have a guarantee that no problem, such - * as integer overflow, happened during this computation, and you can call - * value() to get the plain integer value. - * - * The arithmetic operators in this class are guaranteed not to raise a signal - * (e.g. in case of a division by zero). - * - * For example, suppose that you want to implement a function that computes - * (aX+aY)/aZ, that doesn't crash if aZ==0, and that reports on error (divide by - * zero or integer overflow). You could code it as follows: - @code - bool computeXPlusYOverZ(int aX, int aY, int aZ, int* aResult) - { - CheckedInt checkedResult = (CheckedInt(aX) + aY) / aZ; - if (checkedResult.isValid()) { - *aResult = checkedResult.value(); - return true; - } else { - return false; - } - } - @endcode - * - * Implicit conversion from plain integers to checked integers is allowed. The - * plain integer is checked to be in range before being casted to the - * destination type. This means that the following lines all compile, and the - * resulting CheckedInts are correctly detected as valid or invalid: - * @code - // 1 is of type int, is found to be in range for uint8_t, x is valid - CheckedInt x(1); - // -1 is of type int, is found not to be in range for uint8_t, x is invalid - CheckedInt x(-1); - // -1 is of type int, is found to be in range for int8_t, x is valid - CheckedInt x(-1); - // 1000 is of type int16_t, is found not to be in range for int8_t, - // x is invalid - CheckedInt x(int16_t(1000)); - // 3123456789 is of type uint32_t, is found not to be in range for int32_t, - // x is invalid - CheckedInt x(uint32_t(3123456789)); - * @endcode - * Implicit conversion from - * checked integers to plain integers is not allowed. As shown in the - * above example, to get the value of a checked integer as a normal integer, - * call value(). - * - * Arithmetic operations between checked and plain integers is allowed; the - * result type is the type of the checked integer. - * - * Checked integers of different types cannot be used in the same arithmetic - * expression. - * - * There are convenience typedefs for all stdint types, of the following form - * (these are just 2 examples): - @code - typedef CheckedInt CheckedInt32; - typedef CheckedInt CheckedUint16; - @endcode - */ -template -class CheckedInt -{ -protected: - T mValue; - bool mIsValid; - - template - CheckedInt(U aValue, bool aIsValid) : mValue(aValue), mIsValid(aIsValid) - { - static_assert(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); - } - - friend struct detail::NegateImpl; - -public: - /** - * Constructs a checked integer with given @a value. The checked integer is - * initialized as valid or invalid depending on whether the @a value - * is in range. - * - * This constructor is not explicit. Instead, the type of its argument is a - * separate template parameter, ensuring that no conversion is performed - * before this constructor is actually called. As explained in the above - * documentation for class CheckedInt, this constructor checks that its - * argument is valid. - */ - template - MOZ_IMPLICIT CheckedInt(U aValue) MOZ_NO_ARITHMETIC_EXPR_IN_ARGUMENT - : mValue(T(aValue)), - mIsValid(detail::IsInRange(aValue)) - { - static_assert(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); - } - - template - friend class CheckedInt; - - template - CheckedInt toChecked() const - { - CheckedInt ret(mValue); - ret.mIsValid = ret.mIsValid && mIsValid; - return ret; - } - - /** Constructs a valid checked integer with initial value 0 */ - CheckedInt() : mValue(0), mIsValid(true) - { - static_assert(detail::IsSupported::value, - "This type is not supported by CheckedInt"); - } - - /** @returns the actual value */ - T value() const - { - MOZ_ASSERT(mIsValid, "Invalid checked integer (division by zero or integer overflow)"); - return mValue; - } - - /** - * @returns true if the checked integer is valid, i.e. is not the result - * of an invalid operation or of an operation involving an invalid checked - * integer - */ - bool isValid() const - { - return mIsValid; - } - - template - friend CheckedInt operator +(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator +=(U aRhs); - CheckedInt& operator +=(const CheckedInt& aRhs); - - template - friend CheckedInt operator -(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator -=(U aRhs); - CheckedInt& operator -=(const CheckedInt& aRhs); - - template - friend CheckedInt operator *(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator *=(U aRhs); - CheckedInt& operator *=(const CheckedInt& aRhs); - - template - friend CheckedInt operator /(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator /=(U aRhs); - CheckedInt& operator /=(const CheckedInt& aRhs); - - template - friend CheckedInt operator %(const CheckedInt& aLhs, - const CheckedInt& aRhs); - template - CheckedInt& operator %=(U aRhs); - CheckedInt& operator %=(const CheckedInt& aRhs); - - CheckedInt operator -() const - { - return detail::NegateImpl::negate(*this); - } - - /** - * @returns true if the left and right hand sides are valid - * and have the same value. - * - * Note that these semantics are the reason why we don't offer - * a operator!=. Indeed, we'd want to have a!=b be equivalent to !(a==b) - * but that would mean that whenever a or b is invalid, a!=b - * is always true, which would be very confusing. - * - * For similar reasons, operators <, >, <=, >= would be very tricky to - * specify, so we just avoid offering them. - * - * Notice that these == semantics are made more reasonable by these facts: - * 1. a==b implies equality at the raw data level - * (the converse is false, as a==b is never true among invalids) - * 2. This is similar to the behavior of IEEE floats, where a==b - * means that a and b have the same value *and* neither is NaN. - */ - bool operator ==(const CheckedInt& aOther) const - { - return mIsValid && aOther.mIsValid && mValue == aOther.mValue; - } - - /** prefix ++ */ - CheckedInt& operator++() - { - *this += 1; - return *this; - } - - /** postfix ++ */ - CheckedInt operator++(int) - { - CheckedInt tmp = *this; - *this += 1; - return tmp; - } - - /** prefix -- */ - CheckedInt& operator--() - { - *this -= 1; - return *this; - } - - /** postfix -- */ - CheckedInt operator--(int) - { - CheckedInt tmp = *this; - *this -= 1; - return tmp; - } - -private: - /** - * The !=, <, <=, >, >= operators are disabled: - * see the comment on operator==. - */ - template bool operator !=(U aOther) const = delete; - template bool operator < (U aOther) const = delete; - template bool operator <=(U aOther) const = delete; - template bool operator > (U aOther) const = delete; - template bool operator >=(U aOther) const = delete; -}; - -#define MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(NAME, OP) \ - template \ - inline CheckedInt \ - operator OP(const CheckedInt& aLhs, const CheckedInt& aRhs) \ - { \ - if (!detail::Is##NAME##Valid(aLhs.mValue, aRhs.mValue)) { \ - return CheckedInt(0, false); \ - } \ - return CheckedInt(aLhs.mValue OP aRhs.mValue, \ - aLhs.mIsValid && aRhs.mIsValid); \ - } - -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Add, +) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Sub, -) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mul, *) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Div, /) -MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mod, %) - -#undef MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR - -// Implement castToCheckedInt(x), making sure that -// - it allows x to be either a CheckedInt or any integer type -// that can be casted to T -// - if x is already a CheckedInt, we just return a reference to it, -// instead of copying it (optimization) - -namespace detail { - -template -struct CastToCheckedIntImpl -{ - typedef CheckedInt ReturnType; - static CheckedInt run(U aU) { return aU; } -}; - -template -struct CastToCheckedIntImpl > -{ - typedef const CheckedInt& ReturnType; - static const CheckedInt& run(const CheckedInt& aU) { return aU; } -}; - -} // namespace detail - -template -inline typename detail::CastToCheckedIntImpl::ReturnType -castToCheckedInt(U aU) -{ - static_assert(detail::IsSupported::value && - detail::IsSupported::value, - "This type is not supported by CheckedInt"); - return detail::CastToCheckedIntImpl::run(aU); -} - -#define MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(OP, COMPOUND_OP) \ - template \ - template \ - CheckedInt& CheckedInt::operator COMPOUND_OP(U aRhs) \ - { \ - *this = *this OP castToCheckedInt(aRhs); \ - return *this; \ - } \ - template \ - CheckedInt& CheckedInt::operator COMPOUND_OP(const CheckedInt& aRhs) \ - { \ - *this = *this OP aRhs; \ - return *this; \ - } \ - template \ - inline CheckedInt operator OP(const CheckedInt& aLhs, U aRhs) \ - { \ - return aLhs OP castToCheckedInt(aRhs); \ - } \ - template \ - inline CheckedInt operator OP(U aLhs, const CheckedInt& aRhs) \ - { \ - return castToCheckedInt(aLhs) OP aRhs; \ - } - -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(+, +=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(*, *=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(-, -=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(/, /=) -MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(%, %=) - -#undef MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS - -template -inline bool -operator ==(const CheckedInt& aLhs, U aRhs) -{ - return aLhs == castToCheckedInt(aRhs); -} - -template -inline bool -operator ==(U aLhs, const CheckedInt& aRhs) -{ - return castToCheckedInt(aLhs) == aRhs; -} - -// Convenience typedefs. -typedef CheckedInt CheckedInt8; -typedef CheckedInt CheckedUint8; -typedef CheckedInt CheckedInt16; -typedef CheckedInt CheckedUint16; -typedef CheckedInt CheckedInt32; -typedef CheckedInt CheckedUint32; -typedef CheckedInt CheckedInt64; -typedef CheckedInt CheckedUint64; - -} // namespace mozilla - -#endif /* mozilla_CheckedInt_h */ diff --git a/win32/include/spidermonkey/mozilla/Compiler.h b/win32/include/spidermonkey/mozilla/Compiler.h deleted file mode 100755 index 1bd34d32..00000000 --- a/win32/include/spidermonkey/mozilla/Compiler.h +++ /dev/null @@ -1,113 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Various compiler checks. */ - -#ifndef mozilla_Compiler_h -#define mozilla_Compiler_h - -#define MOZ_IS_GCC 0 -#define MOZ_IS_MSVC 0 - -#if !defined(__clang__) && defined(__GNUC__) - -# undef MOZ_IS_GCC -# define MOZ_IS_GCC 1 - /* - * These macros should simplify gcc version checking. For example, to check - * for gcc 4.7.1 or later, check `#if MOZ_GCC_VERSION_AT_LEAST(4, 7, 1)`. - */ -# define MOZ_GCC_VERSION_AT_LEAST(major, minor, patchlevel) \ - ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \ - >= ((major) * 10000 + (minor) * 100 + (patchlevel))) -# define MOZ_GCC_VERSION_AT_MOST(major, minor, patchlevel) \ - ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \ - <= ((major) * 10000 + (minor) * 100 + (patchlevel))) -# if !MOZ_GCC_VERSION_AT_LEAST(4, 8, 0) -# error "mfbt (and Gecko) require at least gcc 4.8 to build." -# endif - -#elif defined(_MSC_VER) - -# undef MOZ_IS_MSVC -# define MOZ_IS_MSVC 1 - -#endif - -/* - * The situation with standard libraries is a lot worse than with compilers, - * particularly as clang and gcc could end up using one of three or so standard - * libraries, and they may not be up-to-snuff with newer C++11 versions. To - * detect the library, we're going to include cstddef (which is a small header - * which will be transitively included by everybody else at some point) to grab - * the version macros and deduce macros from there. - */ -#ifdef __cplusplus -# include -# ifdef _STLPORT_MAJOR -# define MOZ_USING_STLPORT 1 -# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) \ - (_STLPORT_VERSION >= ((major) << 8 | (minor) << 4 | (patch))) -# elif defined(_LIBCPP_VERSION) - /* - * libc++, unfortunately, doesn't appear to have useful versioning macros. - * Hopefully, the recommendations of N3694 with respect to standard libraries - * will get applied instead and we won't need to worry about version numbers - * here. - */ -# define MOZ_USING_LIBCXX 1 -# elif defined(__GLIBCXX__) -# define MOZ_USING_LIBSTDCXX 1 - /* - * libstdc++ is also annoying and doesn't give us useful versioning macros - * for the library. If we're using gcc, then assume that libstdc++ matches - * the compiler version. If we're using clang, we're going to have to fake - * major/minor combinations by looking for newly-defined config macros. - */ -# if MOZ_IS_GCC -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - MOZ_GCC_VERSION_AT_LEAST(major, minor, patch) -# elif defined(_GLIBCXX_THROW_OR_ABORT) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 8)) -# elif defined(_GLIBCXX_NOEXCEPT) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 7)) -# elif defined(_GLIBCXX_USE_DEPRECATED) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 6)) -# elif defined(_GLIBCXX_PSEUDO_VISIBILITY) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 5)) -# elif defined(_GLIBCXX_BEGIN_EXTERN_C) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 4)) -# elif defined(_GLIBCXX_VISIBILITY_ATTR) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 3)) -# elif defined(_GLIBCXX_VISIBILITY) -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ - ((major) < 4 || ((major) == 4 && (minor) <= 2)) -# else -# error "Your version of libstdc++ is unknown to us and is likely too old." -# endif -# endif - - // Flesh out the defines for everyone else -# ifndef MOZ_USING_STLPORT -# define MOZ_USING_STLPORT 0 -# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) 0 -# endif -# ifndef MOZ_USING_LIBCXX -# define MOZ_USING_LIBCXX 0 -# endif -# ifndef MOZ_USING_LIBSTDCXX -# define MOZ_USING_LIBSTDCXX 0 -# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) 0 -# endif -#endif /* __cplusplus */ - -#endif /* mozilla_Compiler_h */ diff --git a/win32/include/spidermonkey/mozilla/Compression.h b/win32/include/spidermonkey/mozilla/Compression.h deleted file mode 100755 index aa50211b..00000000 --- a/win32/include/spidermonkey/mozilla/Compression.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Various simple compression/decompression functions. */ - -#ifndef mozilla_Compression_h_ -#define mozilla_Compression_h_ - -#include "mozilla/Assertions.h" -#include "mozilla/Types.h" - -namespace mozilla { -namespace Compression { - -/** - * LZ4 is a very fast byte-wise compression algorithm. - * - * Compared to Google's Snappy it is faster to compress and decompress and - * generally produces output of about the same size. - * - * Compared to zlib it compresses at about 10x the speed, decompresses at about - * 4x the speed and produces output of about 1.5x the size. - */ - -class LZ4 -{ -public: - /** - * Compresses |aInputSize| bytes from |aSource| into |aDest|. Destination - * buffer must be already allocated, and must be sized to handle worst cases - * situations (input data not compressible). Worst case size evaluation is - * provided by function maxCompressedSize() - * - * @param aInputSize is the input size. Max supported value is ~1.9GB - * @return the number of bytes written in buffer |aDest| - */ - static MFBT_API size_t - compress(const char* aSource, size_t aInputSize, char* aDest); - - /** - * Compress |aInputSize| bytes from |aSource| into an output buffer - * |aDest| of maximum size |aMaxOutputSize|. If it cannot achieve it, - * compression will stop, and result of the function will be zero, - * |aDest| will still be written to, but since the number of input - * bytes consumed is not returned the result is not usable. - * - * This function never writes outside of provided output buffer. - * - * @param aInputSize is the input size. Max supported value is ~1.9GB - * @param aMaxOutputSize is the size of the destination buffer (which must - * be already allocated) - * @return the number of bytes written in buffer |aDest| or 0 if the - * compression fails - */ - static MFBT_API size_t - compressLimitedOutput(const char* aSource, size_t aInputSize, char* aDest, - size_t aMaxOutputSize); - - /** - * If the source stream is malformed, the function will stop decoding - * and return false. - * - * This function never writes outside of provided buffers, and never - * modifies input buffer. - * - * Note: destination buffer must be already allocated, and its size must be a - * minimum of |aOutputSize| bytes. - * - * @param aOutputSize is the output size, therefore the original size - * @return true on success, false on failure - */ - static MFBT_API MOZ_MUST_USE bool - decompress(const char* aSource, char* aDest, size_t aOutputSize); - - /** - * If the source stream is malformed, the function will stop decoding - * and return false. - * - * This function never writes beyond aDest + aMaxOutputSize, and is - * therefore protected against malicious data packets. - * - * Note: Destination buffer must be already allocated. This version is - * slightly slower than the decompress without the aMaxOutputSize. - * - * @param aInputSize is the length of the input compressed data - * @param aMaxOutputSize is the size of the destination buffer (which must be - * already allocated) - * @param aOutputSize the actual number of bytes decoded in the destination - * buffer (necessarily <= aMaxOutputSize) - * @return true on success, false on failure - */ - static MFBT_API MOZ_MUST_USE bool - decompress(const char* aSource, size_t aInputSize, char* aDest, - size_t aMaxOutputSize, size_t* aOutputSize); - - /* - * Provides the maximum size that LZ4 may output in a "worst case" - * scenario (input data not compressible) primarily useful for memory - * allocation of output buffer. - * note : this function is limited by "int" range (2^31-1) - * - * @param aInputSize is the input size. Max supported value is ~1.9GB - * @return maximum output size in a "worst case" scenario - */ - static inline size_t maxCompressedSize(size_t aInputSize) - { - size_t max = (aInputSize + (aInputSize / 255) + 16); - MOZ_ASSERT(max > aInputSize); - return max; - } -}; - -} /* namespace Compression */ -} /* namespace mozilla */ - -#endif /* mozilla_Compression_h_ */ diff --git a/win32/include/spidermonkey/mozilla/DebugOnly.h b/win32/include/spidermonkey/mozilla/DebugOnly.h deleted file mode 100755 index a1a669db..00000000 --- a/win32/include/spidermonkey/mozilla/DebugOnly.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Provides DebugOnly, a type for variables used only in debug builds (i.e. by - * assertions). - */ - -#ifndef mozilla_DebugOnly_h -#define mozilla_DebugOnly_h - -#include "mozilla/Attributes.h" - -namespace mozilla { - -/** - * DebugOnly contains a value of type T, but only in debug builds. In release - * builds, it does not contain a value. This helper is intended to be used with - * MOZ_ASSERT()-style macros, allowing one to write: - * - * DebugOnly check = func(); - * MOZ_ASSERT(check); - * - * more concisely than declaring |check| conditional on #ifdef DEBUG. - * - * DebugOnly instances can only be coerced to T in debug builds. In release - * builds they don't have a value, so type coercion is not well defined. - * - * NOTE: DebugOnly instances still take up one byte of space, plus padding, even - * in optimized, non-DEBUG builds (see bug 1253094 comment 37 for more info). - * For this reason the class is MOZ_STACK_CLASS to prevent consumers using - * DebugOnly for struct/class members and unwittingly inflating the size of - * their objects in release builds. - */ -template -class MOZ_STACK_CLASS DebugOnly -{ -public: -#ifdef DEBUG - T value; - - DebugOnly() { } - MOZ_IMPLICIT DebugOnly(const T& aOther) : value(aOther) { } - DebugOnly(const DebugOnly& aOther) : value(aOther.value) { } - DebugOnly& operator=(const T& aRhs) { - value = aRhs; - return *this; - } - - void operator++(int) { value++; } - void operator--(int) { value--; } - - // Do not define operator+=(), etc. here. These will coerce via the - // implicit cast and built-in operators. Defining explicit methods here - // will create ambiguity the compiler can't deal with. - - T* operator&() { return &value; } - - operator T&() { return value; } - operator const T&() const { return value; } - - T& operator->() { return value; } - const T& operator->() const { return value; } - -#else - DebugOnly() { } - MOZ_IMPLICIT DebugOnly(const T&) { } - DebugOnly(const DebugOnly&) { } - DebugOnly& operator=(const T&) { return *this; } - void operator++(int) { } - void operator--(int) { } - DebugOnly& operator+=(const T&) { return *this; } - DebugOnly& operator-=(const T&) { return *this; } - DebugOnly& operator&=(const T&) { return *this; } - DebugOnly& operator|=(const T&) { return *this; } - DebugOnly& operator^=(const T&) { return *this; } -#endif - - /* - * DebugOnly must always have a destructor or else it will - * generate "unused variable" warnings, exactly what it's intended - * to avoid! - */ - ~DebugOnly() {} -}; - -} // namespace mozilla - -#endif /* mozilla_DebugOnly_h */ diff --git a/win32/include/spidermonkey/mozilla/Decimal.h b/win32/include/spidermonkey/mozilla/Decimal.h deleted file mode 100755 index 10d0e2c7..00000000 --- a/win32/include/spidermonkey/mozilla/Decimal.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * Imported from: - * https://chromium.googlesource.com/chromium/src.git/+/master/third_party/WebKit/Source/platform/Decimal.h - * Check UPSTREAM-GIT-SHA for the commit ID of the last update from Blink core. - */ - -#ifndef Decimal_h -#define Decimal_h - -#include "mozilla/Assertions.h" -#include -#include "mozilla/Types.h" - -#include - -#ifndef ASSERT -#define DEFINED_ASSERT_FOR_DECIMAL_H 1 -#define ASSERT MOZ_ASSERT -#endif - -#define PLATFORM_EXPORT - -// To use USING_FAST_MALLOC we'd need: -// https://chromium.googlesource.com/chromium/src.git/+/master/third_party/WebKit/Source/wtf/Allocator.h -// Since we don't allocate Decimal objects, no need. -#define USING_FAST_MALLOC(type) \ - void ignore_this_dummy_method() = delete - -#define DISALLOW_NEW() \ - private: \ - void* operator new(size_t) = delete; \ - void* operator new(size_t, void*) = delete; \ - public: - -namespace blink { - -namespace DecimalPrivate { -class SpecialValueHandler; -} - -// This class represents decimal base floating point number. -// -// FIXME: Once all C++ compiler support decimal type, we should replace this -// class to compiler supported one. See below URI for current status of decimal -// type for C++: // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1977.html -class PLATFORM_EXPORT Decimal { - USING_FAST_MALLOC(Decimal); -public: - enum Sign { - Positive, - Negative, - }; - - // You should not use EncodedData other than unit testing. - class EncodedData { - DISALLOW_NEW(); - // For accessing FormatClass. - friend class Decimal; - friend class DecimalPrivate::SpecialValueHandler; - public: - EncodedData(Sign, int exponent, uint64_t coefficient); - - bool operator==(const EncodedData&) const; - bool operator!=(const EncodedData& another) const { return !operator==(another); } - - uint64_t coefficient() const { return m_coefficient; } - int countDigits() const; - int exponent() const { return m_exponent; } - bool isFinite() const { return !isSpecial(); } - bool isInfinity() const { return m_formatClass == ClassInfinity; } - bool isNaN() const { return m_formatClass == ClassNaN; } - bool isSpecial() const { return m_formatClass == ClassInfinity || m_formatClass == ClassNaN; } - bool isZero() const { return m_formatClass == ClassZero; } - Sign sign() const { return m_sign; } - void setSign(Sign sign) { m_sign = sign; } - - private: - enum FormatClass { - ClassInfinity, - ClassNormal, - ClassNaN, - ClassZero, - }; - - EncodedData(Sign, FormatClass); - FormatClass formatClass() const { return m_formatClass; } - - uint64_t m_coefficient; - int16_t m_exponent; - FormatClass m_formatClass; - Sign m_sign; - }; - - MFBT_API explicit Decimal(int32_t = 0); - MFBT_API Decimal(Sign, int exponent, uint64_t coefficient); - MFBT_API Decimal(const Decimal&); - - MFBT_API Decimal& operator=(const Decimal&); - MFBT_API Decimal& operator+=(const Decimal&); - MFBT_API Decimal& operator-=(const Decimal&); - MFBT_API Decimal& operator*=(const Decimal&); - MFBT_API Decimal& operator/=(const Decimal&); - - MFBT_API Decimal operator-() const; - - MFBT_API bool operator==(const Decimal&) const; - MFBT_API bool operator!=(const Decimal&) const; - MFBT_API bool operator<(const Decimal&) const; - MFBT_API bool operator<=(const Decimal&) const; - MFBT_API bool operator>(const Decimal&) const; - MFBT_API bool operator>=(const Decimal&) const; - - MFBT_API Decimal operator+(const Decimal&) const; - MFBT_API Decimal operator-(const Decimal&) const; - MFBT_API Decimal operator*(const Decimal&) const; - MFBT_API Decimal operator/(const Decimal&) const; - - int exponent() const - { - ASSERT(isFinite()); - return m_data.exponent(); - } - - bool isFinite() const { return m_data.isFinite(); } - bool isInfinity() const { return m_data.isInfinity(); } - bool isNaN() const { return m_data.isNaN(); } - bool isNegative() const { return sign() == Negative; } - bool isPositive() const { return sign() == Positive; } - bool isSpecial() const { return m_data.isSpecial(); } - bool isZero() const { return m_data.isZero(); } - - MFBT_API Decimal abs() const; - MFBT_API Decimal ceil() const; - MFBT_API Decimal floor() const; - MFBT_API Decimal remainder(const Decimal&) const; - MFBT_API Decimal round() const; - - MFBT_API double toDouble() const; - // Note: toString method supports infinity and nan but fromString not. - MFBT_API std::string toString() const; - MFBT_API bool toString(char* strBuf, size_t bufLength) const; - - static MFBT_API Decimal fromDouble(double); - // fromString supports following syntax EBNF: - // number ::= sign? digit+ ('.' digit*) (exponent-marker sign? digit+)? - // | sign? '.' digit+ (exponent-marker sign? digit+)? - // sign ::= '+' | '-' - // exponent-marker ::= 'e' | 'E' - // digit ::= '0' | '1' | ... | '9' - // Note: fromString doesn't support "infinity" and "nan". - static MFBT_API Decimal fromString(const std::string& aValue); - static MFBT_API Decimal infinity(Sign); - static MFBT_API Decimal nan(); - static MFBT_API Decimal zero(Sign); - - // You should not use below methods. We expose them for unit testing. - MFBT_API explicit Decimal(const EncodedData&); - const EncodedData& value() const { return m_data; } - -private: - struct AlignedOperands { - uint64_t lhsCoefficient; - uint64_t rhsCoefficient; - int exponent; - }; - - MFBT_API explicit Decimal(double); - MFBT_API Decimal compareTo(const Decimal&) const; - - static MFBT_API AlignedOperands alignOperands(const Decimal& lhs, const Decimal& rhs); - static inline Sign invertSign(Sign sign) { return sign == Negative ? Positive : Negative; } - - Sign sign() const { return m_data.sign(); } - - EncodedData m_data; -}; - -} // namespace blink - -namespace mozilla { -typedef blink::Decimal Decimal; -} // namespace mozilla - -#undef USING_FAST_MALLOC - -#ifdef DEFINED_ASSERT_FOR_DECIMAL_H -#undef DEFINED_ASSERT_FOR_DECIMAL_H -#undef ASSERT -#endif - -#endif // Decimal_h diff --git a/win32/include/spidermonkey/mozilla/EndianUtils.h b/win32/include/spidermonkey/mozilla/EndianUtils.h deleted file mode 100755 index 00815580..00000000 --- a/win32/include/spidermonkey/mozilla/EndianUtils.h +++ /dev/null @@ -1,695 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Functions for reading and writing integers in various endiannesses. */ - -/* - * The classes LittleEndian and BigEndian expose static methods for - * reading and writing 16-, 32-, and 64-bit signed and unsigned integers - * in their respective endianness. The naming scheme is: - * - * {Little,Big}Endian::{read,write}{Uint,Int} - * - * For instance, LittleEndian::readInt32 will read a 32-bit signed - * integer from memory in little endian format. Similarly, - * BigEndian::writeUint16 will write a 16-bit unsigned integer to memory - * in big-endian format. - * - * The class NativeEndian exposes methods for conversion of existing - * data to and from the native endianness. These methods are intended - * for cases where data needs to be transferred, serialized, etc. - * swap{To,From}{Little,Big}Endian byteswap a single value if necessary. - * Bulk conversion functions are also provided which optimize the - * no-conversion-needed case: - * - * - copyAndSwap{To,From}{Little,Big}Endian; - * - swap{To,From}{Little,Big}EndianInPlace. - * - * The *From* variants are intended to be used for reading data and the - * *To* variants for writing data. - * - * Methods on NativeEndian work with integer data of any type. - * Floating-point data is not supported. - * - * For clarity in networking code, "Network" may be used as a synonym - * for "Big" in any of the above methods or class names. - * - * As an example, reading a file format header whose fields are stored - * in big-endian format might look like: - * - * class ExampleHeader - * { - * private: - * uint32_t mMagic; - * uint32_t mLength; - * uint32_t mTotalRecords; - * uint64_t mChecksum; - * - * public: - * ExampleHeader(const void* data) - * { - * const uint8_t* ptr = static_cast(data); - * mMagic = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t); - * mLength = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t); - * mTotalRecords = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t); - * mChecksum = BigEndian::readUint64(ptr); - * } - * ... - * }; - */ - -#ifndef mozilla_EndianUtils_h -#define mozilla_EndianUtils_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/DebugOnly.h" -#include "mozilla/TypeTraits.h" - -#include -#include - -#if defined(_MSC_VER) -# include -# pragma intrinsic(_byteswap_ushort) -# pragma intrinsic(_byteswap_ulong) -# pragma intrinsic(_byteswap_uint64) -#endif - -#if defined(_WIN64) -# if defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_) -# define MOZ_LITTLE_ENDIAN 1 -# else -# error "CPU type is unknown" -# endif -#elif defined(_WIN32) -# if defined(_M_IX86) -# define MOZ_LITTLE_ENDIAN 1 -# elif defined(_M_ARM) -# define MOZ_LITTLE_ENDIAN 1 -# else -# error "CPU type is unknown" -# endif -#elif defined(__APPLE__) || defined(__powerpc__) || defined(__ppc__) -# if __LITTLE_ENDIAN__ -# define MOZ_LITTLE_ENDIAN 1 -# elif __BIG_ENDIAN__ -# define MOZ_BIG_ENDIAN 1 -# endif -#elif defined(__GNUC__) && \ - defined(__BYTE_ORDER__) && \ - defined(__ORDER_LITTLE_ENDIAN__) && \ - defined(__ORDER_BIG_ENDIAN__) - /* - * Some versions of GCC provide architecture-independent macros for - * this. Yes, there are more than two values for __BYTE_ORDER__. - */ -# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -# define MOZ_LITTLE_ENDIAN 1 -# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ -# define MOZ_BIG_ENDIAN 1 -# else -# error "Can't handle mixed-endian architectures" -# endif -/* - * We can't include useful headers like or - * here because they're not present on all platforms. Instead we have - * this big conditional that ideally will catch all the interesting - * cases. - */ -#elif defined(__sparc) || defined(__sparc__) || \ - defined(_POWER) || defined(__hppa) || \ - defined(_MIPSEB) || defined(__ARMEB__) || \ - defined(__s390__) || defined(__AARCH64EB__) || \ - (defined(__sh__) && defined(__LITTLE_ENDIAN__)) || \ - (defined(__ia64) && defined(__BIG_ENDIAN__)) -# define MOZ_BIG_ENDIAN 1 -#elif defined(__i386) || defined(__i386__) || \ - defined(__x86_64) || defined(__x86_64__) || \ - defined(_MIPSEL) || defined(__ARMEL__) || \ - defined(__alpha__) || defined(__AARCH64EL__) || \ - (defined(__sh__) && defined(__BIG_ENDIAN__)) || \ - (defined(__ia64) && !defined(__BIG_ENDIAN__)) -# define MOZ_LITTLE_ENDIAN 1 -#endif - -#if MOZ_BIG_ENDIAN -# define MOZ_LITTLE_ENDIAN 0 -#elif MOZ_LITTLE_ENDIAN -# define MOZ_BIG_ENDIAN 0 -#else -# error "Cannot determine endianness" -#endif - -#if defined(__clang__) -# if __has_builtin(__builtin_bswap16) -# define MOZ_HAVE_BUILTIN_BYTESWAP16 __builtin_bswap16 -# endif -#elif defined(__GNUC__) -# define MOZ_HAVE_BUILTIN_BYTESWAP16 __builtin_bswap16 -#elif defined(_MSC_VER) -# define MOZ_HAVE_BUILTIN_BYTESWAP16 _byteswap_ushort -#endif - -namespace mozilla { - -namespace detail { - -/* - * We need wrappers here because free functions with default template - * arguments and/or partial specialization of function templates are not - * supported by all the compilers we use. - */ -template -struct Swapper; - -template -struct Swapper -{ - static T swap(T aValue) - { -#if defined(MOZ_HAVE_BUILTIN_BYTESWAP16) - return MOZ_HAVE_BUILTIN_BYTESWAP16(aValue); -#else - return T(((aValue & 0x00ff) << 8) | ((aValue & 0xff00) >> 8)); -#endif - } -}; - -template -struct Swapper -{ - static T swap(T aValue) - { -#if defined(__clang__) || defined(__GNUC__) - return T(__builtin_bswap32(aValue)); -#elif defined(_MSC_VER) - return T(_byteswap_ulong(aValue)); -#else - return T(((aValue & 0x000000ffU) << 24) | - ((aValue & 0x0000ff00U) << 8) | - ((aValue & 0x00ff0000U) >> 8) | - ((aValue & 0xff000000U) >> 24)); -#endif - } -}; - -template -struct Swapper -{ - static inline T swap(T aValue) - { -#if defined(__clang__) || defined(__GNUC__) - return T(__builtin_bswap64(aValue)); -#elif defined(_MSC_VER) - return T(_byteswap_uint64(aValue)); -#else - return T(((aValue & 0x00000000000000ffULL) << 56) | - ((aValue & 0x000000000000ff00ULL) << 40) | - ((aValue & 0x0000000000ff0000ULL) << 24) | - ((aValue & 0x00000000ff000000ULL) << 8) | - ((aValue & 0x000000ff00000000ULL) >> 8) | - ((aValue & 0x0000ff0000000000ULL) >> 24) | - ((aValue & 0x00ff000000000000ULL) >> 40) | - ((aValue & 0xff00000000000000ULL) >> 56)); -#endif - } -}; - -enum Endianness { Little, Big }; - -#if MOZ_BIG_ENDIAN -# define MOZ_NATIVE_ENDIANNESS detail::Big -#else -# define MOZ_NATIVE_ENDIANNESS detail::Little -#endif - -class EndianUtils -{ - /** - * Assert that the memory regions [aDest, aDest+aCount) and - * [aSrc, aSrc+aCount] do not overlap. aCount is given in bytes. - */ - static void assertNoOverlap(const void* aDest, const void* aSrc, - size_t aCount) - { - DebugOnly byteDestPtr = static_cast(aDest); - DebugOnly byteSrcPtr = static_cast(aSrc); - MOZ_ASSERT((byteDestPtr <= byteSrcPtr && - byteDestPtr + aCount <= byteSrcPtr) || - (byteSrcPtr <= byteDestPtr && - byteSrcPtr + aCount <= byteDestPtr)); - } - - template - static void assertAligned(T* aPtr) - { - MOZ_ASSERT((uintptr_t(aPtr) % sizeof(T)) == 0, "Unaligned pointer!"); - } - -protected: - /** - * Return |aValue| converted from SourceEndian encoding to DestEndian - * encoding. - */ - template - static inline T maybeSwap(T aValue) - { - if (SourceEndian == DestEndian) { - return aValue; - } - return Swapper::swap(aValue); - } - - /** - * Convert |aCount| elements at |aPtr| from SourceEndian encoding to - * DestEndian encoding. - */ - template - static inline void maybeSwapInPlace(T* aPtr, size_t aCount) - { - assertAligned(aPtr); - - if (SourceEndian == DestEndian) { - return; - } - for (size_t i = 0; i < aCount; i++) { - aPtr[i] = Swapper::swap(aPtr[i]); - } - } - - /** - * Write |aCount| elements to the unaligned address |aDest| in DestEndian - * format, using elements found at |aSrc| in SourceEndian format. - */ - template - static void copyAndSwapTo(void* aDest, const T* aSrc, size_t aCount) - { - assertNoOverlap(aDest, aSrc, aCount * sizeof(T)); - assertAligned(aSrc); - - if (SourceEndian == DestEndian) { - memcpy(aDest, aSrc, aCount * sizeof(T)); - return; - } - - uint8_t* byteDestPtr = static_cast(aDest); - for (size_t i = 0; i < aCount; ++i) { - union - { - T mVal; - uint8_t mBuffer[sizeof(T)]; - } u; - u.mVal = maybeSwap(aSrc[i]); - memcpy(byteDestPtr, u.mBuffer, sizeof(T)); - byteDestPtr += sizeof(T); - } - } - - /** - * Write |aCount| elements to |aDest| in DestEndian format, using elements - * found at the unaligned address |aSrc| in SourceEndian format. - */ - template - static void copyAndSwapFrom(T* aDest, const void* aSrc, size_t aCount) - { - assertNoOverlap(aDest, aSrc, aCount * sizeof(T)); - assertAligned(aDest); - - if (SourceEndian == DestEndian) { - memcpy(aDest, aSrc, aCount * sizeof(T)); - return; - } - - const uint8_t* byteSrcPtr = static_cast(aSrc); - for (size_t i = 0; i < aCount; ++i) { - union - { - T mVal; - uint8_t mBuffer[sizeof(T)]; - } u; - memcpy(u.mBuffer, byteSrcPtr, sizeof(T)); - aDest[i] = maybeSwap(u.mVal); - byteSrcPtr += sizeof(T); - } - } -}; - -template -class Endian : private EndianUtils -{ -protected: - /** Read a uint16_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE uint16_t readUint16(const void* aPtr) - { - return read(aPtr); - } - - /** Read a uint32_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE uint32_t readUint32(const void* aPtr) - { - return read(aPtr); - } - - /** Read a uint64_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE uint64_t readUint64(const void* aPtr) - { - return read(aPtr); - } - - /** Read an int16_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE int16_t readInt16(const void* aPtr) - { - return read(aPtr); - } - - /** Read an int32_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE int32_t readInt32(const void* aPtr) - { - return read(aPtr); - } - - /** Read an int64_t in ThisEndian endianness from |aPtr| and return it. */ - static MOZ_MUST_USE int64_t readInt64(const void* aPtr) - { - return read(aPtr); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeUint16(void* aPtr, uint16_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeUint32(void* aPtr, uint32_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeUint64(void* aPtr, uint64_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeInt16(void* aPtr, int16_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeInt32(void* aPtr, int32_t aValue) - { - write(aPtr, aValue); - } - - /** Write |aValue| to |aPtr| using ThisEndian endianness. */ - static void writeInt64(void* aPtr, int64_t aValue) - { - write(aPtr, aValue); - } - - /* - * Converts a value of type T to little-endian format. - * - * This function is intended for cases where you have data in your - * native-endian format and you need it to appear in little-endian - * format for transmission. - */ - template - MOZ_MUST_USE static T swapToLittleEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to little-endian format if ThisEndian is Big. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapToLittleEndian(void* aDest, const T* aSrc, - size_t aCount) - { - copyAndSwapTo(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapToLittleEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Converts a value of type T to big-endian format. - */ - template - MOZ_MUST_USE static T swapToBigEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to big-endian format if ThisEndian is Little. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapToBigEndian(void* aDest, const T* aSrc, - size_t aCount) - { - copyAndSwapTo(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapToBigEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Synonyms for the big-endian functions, for better readability - * in network code. - */ - - template - MOZ_MUST_USE static T swapToNetworkOrder(T aValue) - { - return swapToBigEndian(aValue); - } - - template - static void - copyAndSwapToNetworkOrder(void* aDest, const T* aSrc, size_t aCount) - { - copyAndSwapToBigEndian(aDest, aSrc, aCount); - } - - template - static void - swapToNetworkOrderInPlace(T* aPtr, size_t aCount) - { - swapToBigEndianInPlace(aPtr, aCount); - } - - /* - * Converts a value of type T from little-endian format. - */ - template - MOZ_MUST_USE static T swapFromLittleEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to little-endian format if ThisEndian is Big. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapFromLittleEndian(T* aDest, const void* aSrc, - size_t aCount) - { - copyAndSwapFrom(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapFromLittleEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Converts a value of type T from big-endian format. - */ - template - MOZ_MUST_USE static T swapFromBigEndian(T aValue) - { - return maybeSwap(aValue); - } - - /* - * Copies |aCount| values of type T starting at |aSrc| to |aDest|, converting - * them to big-endian format if ThisEndian is Little. - * As with memcpy, |aDest| and |aSrc| must not overlap. - */ - template - static void copyAndSwapFromBigEndian(T* aDest, const void* aSrc, - size_t aCount) - { - copyAndSwapFrom(aDest, aSrc, aCount); - } - - /* - * Likewise, but converts values in place. - */ - template - static void swapFromBigEndianInPlace(T* aPtr, size_t aCount) - { - maybeSwapInPlace(aPtr, aCount); - } - - /* - * Synonyms for the big-endian functions, for better readability - * in network code. - */ - template - MOZ_MUST_USE static T swapFromNetworkOrder(T aValue) - { - return swapFromBigEndian(aValue); - } - - template - static void copyAndSwapFromNetworkOrder(T* aDest, const void* aSrc, - size_t aCount) - { - copyAndSwapFromBigEndian(aDest, aSrc, aCount); - } - - template - static void swapFromNetworkOrderInPlace(T* aPtr, size_t aCount) - { - swapFromBigEndianInPlace(aPtr, aCount); - } - -private: - /** - * Read a value of type T, encoded in endianness ThisEndian from |aPtr|. - * Return that value encoded in native endianness. - */ - template - static T read(const void* aPtr) - { - union - { - T mVal; - uint8_t mBuffer[sizeof(T)]; - } u; - memcpy(u.mBuffer, aPtr, sizeof(T)); - return maybeSwap(u.mVal); - } - - /** - * Write a value of type T, in native endianness, to |aPtr|, in ThisEndian - * endianness. - */ - template - static void write(void* aPtr, T aValue) - { - T tmp = maybeSwap(aValue); - memcpy(aPtr, &tmp, sizeof(T)); - } - - Endian() = delete; - Endian(const Endian& aTther) = delete; - void operator=(const Endian& aOther) = delete; -}; - -template -class EndianReadWrite : public Endian -{ -private: - typedef Endian super; - -public: - using super::readUint16; - using super::readUint32; - using super::readUint64; - using super::readInt16; - using super::readInt32; - using super::readInt64; - using super::writeUint16; - using super::writeUint32; - using super::writeUint64; - using super::writeInt16; - using super::writeInt32; - using super::writeInt64; -}; - -} /* namespace detail */ - -class LittleEndian final : public detail::EndianReadWrite -{}; - -class BigEndian final : public detail::EndianReadWrite -{}; - -typedef BigEndian NetworkEndian; - -class NativeEndian final : public detail::Endian -{ -private: - typedef detail::Endian super; - -public: - /* - * These functions are intended for cases where you have data in your - * native-endian format and you need the data to appear in the appropriate - * endianness for transmission, serialization, etc. - */ - using super::swapToLittleEndian; - using super::copyAndSwapToLittleEndian; - using super::swapToLittleEndianInPlace; - using super::swapToBigEndian; - using super::copyAndSwapToBigEndian; - using super::swapToBigEndianInPlace; - using super::swapToNetworkOrder; - using super::copyAndSwapToNetworkOrder; - using super::swapToNetworkOrderInPlace; - - /* - * These functions are intended for cases where you have data in the - * given endianness (e.g. reading from disk or a file-format) and you - * need the data to appear in native-endian format for processing. - */ - using super::swapFromLittleEndian; - using super::copyAndSwapFromLittleEndian; - using super::swapFromLittleEndianInPlace; - using super::swapFromBigEndian; - using super::copyAndSwapFromBigEndian; - using super::swapFromBigEndianInPlace; - using super::swapFromNetworkOrder; - using super::copyAndSwapFromNetworkOrder; - using super::swapFromNetworkOrderInPlace; -}; - -#undef MOZ_NATIVE_ENDIANNESS - -} /* namespace mozilla */ - -#endif /* mozilla_EndianUtils_h */ diff --git a/win32/include/spidermonkey/mozilla/EnumSet.h b/win32/include/spidermonkey/mozilla/EnumSet.h deleted file mode 100755 index 5282ab30..00000000 --- a/win32/include/spidermonkey/mozilla/EnumSet.h +++ /dev/null @@ -1,344 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A set abstraction for enumeration values. */ - -#ifndef mozilla_EnumSet_h -#define mozilla_EnumSet_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#include - -#include - -namespace mozilla { - -/** - * EnumSet is a set of values defined by an enumeration. It is implemented - * using a 32 bit mask for each value so it will only work for enums with an int - * representation less than 32. It works both for enum and enum class types. - */ -template -class EnumSet -{ -public: - EnumSet() - : mBitField(0) - { - initVersion(); - } - - MOZ_IMPLICIT EnumSet(T aEnum) - : mBitField(bitFor(aEnum)) - { } - - EnumSet(T aEnum1, T aEnum2) - : mBitField(bitFor(aEnum1) | - bitFor(aEnum2)) - { - initVersion(); - } - - EnumSet(T aEnum1, T aEnum2, T aEnum3) - : mBitField(bitFor(aEnum1) | - bitFor(aEnum2) | - bitFor(aEnum3)) - { - initVersion(); - } - - EnumSet(T aEnum1, T aEnum2, T aEnum3, T aEnum4) - : mBitField(bitFor(aEnum1) | - bitFor(aEnum2) | - bitFor(aEnum3) | - bitFor(aEnum4)) - { - initVersion(); - } - - MOZ_IMPLICIT EnumSet(std::initializer_list list) - : mBitField(0) - { - for (auto value : list) { - (*this) += value; - } - initVersion(); - } - - EnumSet(const EnumSet& aEnumSet) - : mBitField(aEnumSet.mBitField) - { - initVersion(); - } - - /** - * Add an element - */ - void operator+=(T aEnum) - { - incVersion(); - mBitField |= bitFor(aEnum); - } - - /** - * Add an element - */ - EnumSet operator+(T aEnum) const - { - EnumSet result(*this); - result += aEnum; - return result; - } - - /** - * Union - */ - void operator+=(const EnumSet aEnumSet) - { - incVersion(); - mBitField |= aEnumSet.mBitField; - } - - /** - * Union - */ - EnumSet operator+(const EnumSet aEnumSet) const - { - EnumSet result(*this); - result += aEnumSet; - return result; - } - - /** - * Remove an element - */ - void operator-=(T aEnum) - { - incVersion(); - mBitField &= ~(bitFor(aEnum)); - } - - /** - * Remove an element - */ - EnumSet operator-(T aEnum) const - { - EnumSet result(*this); - result -= aEnum; - return result; - } - - /** - * Remove a set of elements - */ - void operator-=(const EnumSet aEnumSet) - { - incVersion(); - mBitField &= ~(aEnumSet.mBitField); - } - - /** - * Remove a set of elements - */ - EnumSet operator-(const EnumSet aEnumSet) const - { - EnumSet result(*this); - result -= aEnumSet; - return result; - } - - /** - * Clear - */ - void clear() - { - incVersion(); - mBitField = 0; - } - - /** - * Intersection - */ - void operator&=(const EnumSet aEnumSet) - { - incVersion(); - mBitField &= aEnumSet.mBitField; - } - - /** - * Intersection - */ - EnumSet operator&(const EnumSet aEnumSet) const - { - EnumSet result(*this); - result &= aEnumSet; - return result; - } - - /** - * Equality - */ - bool operator==(const EnumSet aEnumSet) const - { - return mBitField == aEnumSet.mBitField; - } - - /** - * Test is an element is contained in the set. - */ - bool contains(T aEnum) const - { - return mBitField & bitFor(aEnum); - } - - /** - * Return the number of elements in the set. - */ - uint8_t size() const - { - uint8_t count = 0; - for (uint32_t bitField = mBitField; bitField; bitField >>= 1) { - if (bitField & 1) { - count++; - } - } - return count; - } - - bool isEmpty() const - { - return mBitField == 0; - } - - uint32_t serialize() const - { - return mBitField; - } - - void deserialize(uint32_t aValue) - { - incVersion(); - mBitField = aValue; - } - - class ConstIterator - { - const EnumSet* mSet; - uint32_t mPos; -#ifdef DEBUG - uint64_t mVersion; -#endif - - void checkVersion() { - // Check that the set has not been modified while being iterated. - MOZ_ASSERT_IF(mSet, mSet->mVersion == mVersion); - } - - public: - ConstIterator(const EnumSet& aSet, uint32_t aPos) - : mSet(&aSet), mPos(aPos) - { -#ifdef DEBUG - mVersion = mSet->mVersion; -#endif - MOZ_ASSERT(aPos <= kMaxBits); - if (aPos != kMaxBits && !mSet->contains(T(mPos))) - ++*this; - } - - ConstIterator(const ConstIterator& aOther) - : mSet(aOther.mSet), mPos(aOther.mPos) - { -#ifdef DEBUG - mVersion = aOther.mVersion; - checkVersion(); -#endif - } - - ConstIterator(ConstIterator&& aOther) - : mSet(aOther.mSet), mPos(aOther.mPos) - { -#ifdef DEBUG - mVersion = aOther.mVersion; - checkVersion(); -#endif - aOther.mSet = nullptr; - } - - ~ConstIterator() { - checkVersion(); - } - - bool operator==(const ConstIterator& other) { - MOZ_ASSERT(mSet == other.mSet); - checkVersion(); - return mPos == other.mPos; - } - - bool operator!=(const ConstIterator& other) { - return !(*this == other); - } - - T operator*() { - MOZ_ASSERT(mSet); - MOZ_ASSERT(mPos < kMaxBits); - MOZ_ASSERT(mSet->contains(T(mPos))); - checkVersion(); - return T(mPos); - } - - ConstIterator& operator++() { - MOZ_ASSERT(mSet); - MOZ_ASSERT(mPos < kMaxBits); - checkVersion(); - do { - mPos++; - } while (mPos < kMaxBits && !mSet->contains(T(mPos))); - return *this; - } - }; - - ConstIterator begin() const { - return ConstIterator(*this, 0); - } - - ConstIterator end() const { - return ConstIterator(*this, kMaxBits); - } - -private: - static uint32_t bitFor(T aEnum) - { - uint32_t bitNumber = (uint32_t)aEnum; - MOZ_ASSERT(bitNumber < kMaxBits); - return 1U << bitNumber; - } - - void initVersion() { -#ifdef DEBUG - mVersion = 0; -#endif - } - - void incVersion() { -#ifdef DEBUG - mVersion++; -#endif - } - - static const size_t kMaxBits = 32; - uint32_t mBitField; - -#ifdef DEBUG - uint64_t mVersion; -#endif -}; - -} // namespace mozilla - -#endif /* mozilla_EnumSet_h_*/ diff --git a/win32/include/spidermonkey/mozilla/EnumTypeTraits.h b/win32/include/spidermonkey/mozilla/EnumTypeTraits.h deleted file mode 100755 index 223eaf8c..00000000 --- a/win32/include/spidermonkey/mozilla/EnumTypeTraits.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Type traits for enums. */ - -#ifndef mozilla_EnumTypeTraits_h -#define mozilla_EnumTypeTraits_h - -#include - -namespace mozilla { - -namespace detail { - -template -struct EnumFitsWithinHelper; - -// Signed enum, signed storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -// Signed enum, unsigned storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -// Unsigned enum, signed storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -// Unsigned enum, unsigned storage. -template -struct EnumFitsWithinHelper - : public std::integral_constant -{}; - -} // namespace detail - -/* - * Type trait that determines whether the enum type T can fit within the - * integral type Storage without data loss. This trait should be used with - * caution with an enum type whose underlying type has not been explicitly - * specified: for such enums, the C++ implementation is free to choose a type - * no smaller than int whose range encompasses all possible values of the enum. - * So for an enum with only small non-negative values, the underlying type may - * be either int or unsigned int, depending on the whims of the implementation. - */ -template -struct EnumTypeFitsWithin - : public detail::EnumFitsWithinHelper< - sizeof(T), - std::is_signed::type>::value, - sizeof(Storage), - std::is_signed::value - > -{ - static_assert(std::is_enum::value, "must provide an enum type"); - static_assert(std::is_integral::value, "must provide an integral type"); -}; - -} // namespace mozilla - -#endif /* mozilla_EnumTypeTraits_h */ diff --git a/win32/include/spidermonkey/mozilla/EnumeratedArray.h b/win32/include/spidermonkey/mozilla/EnumeratedArray.h deleted file mode 100755 index 9e74b772..00000000 --- a/win32/include/spidermonkey/mozilla/EnumeratedArray.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* EnumeratedArray is like Array, but indexed by a typed enum. */ - -#ifndef mozilla_EnumeratedArray_h -#define mozilla_EnumeratedArray_h - -#include "mozilla/Array.h" -#include "mozilla/Move.h" - -namespace mozilla { - -/** - * EnumeratedArray is a fixed-size array container for use when an - * array is indexed by a specific enum class. - * - * This provides type safety by guarding at compile time against accidentally - * indexing such arrays with unrelated values. This also removes the need - * for manual casting when using a typed enum value to index arrays. - * - * Aside from the typing of indices, EnumeratedArray is similar to Array. - * - * Example: - * - * enum class AnimalSpecies { - * Cow, - * Sheep, - * Count - * }; - * - * EnumeratedArray headCount; - * - * headCount[AnimalSpecies::Cow] = 17; - * headCount[AnimalSpecies::Sheep] = 30; - * - */ -template -class EnumeratedArray -{ -public: - static const size_t kSize = size_t(SizeAsEnumValue); - -private: - typedef Array ArrayType; - - ArrayType mArray; - -public: - EnumeratedArray() {} - - template - MOZ_IMPLICIT EnumeratedArray(Args&&... aArgs) - : mArray{mozilla::Forward(aArgs)...} - {} - - explicit EnumeratedArray(const EnumeratedArray& aOther) - { - for (size_t i = 0; i < kSize; i++) { - mArray[i] = aOther.mArray[i]; - } - } - - EnumeratedArray(EnumeratedArray&& aOther) - { - for (size_t i = 0; i < kSize; i++) { - mArray[i] = Move(aOther.mArray[i]); - } - } - - ValueType& operator[](IndexType aIndex) - { - return mArray[size_t(aIndex)]; - } - - const ValueType& operator[](IndexType aIndex) const - { - return mArray[size_t(aIndex)]; - } - - typedef typename ArrayType::iterator iterator; - typedef typename ArrayType::const_iterator const_iterator; - typedef typename ArrayType::reverse_iterator reverse_iterator; - typedef typename ArrayType::const_reverse_iterator const_reverse_iterator; - - // Methods for range-based for loops. - iterator begin() { return mArray.begin(); } - const_iterator begin() const { return mArray.begin(); } - const_iterator cbegin() const { return mArray.cbegin(); } - iterator end() { return mArray.end(); } - const_iterator end() const { return mArray.end(); } - const_iterator cend() const { return mArray.cend(); } - - // Methods for reverse iterating. - reverse_iterator rbegin() { return mArray.rbegin(); } - const_reverse_iterator rbegin() const { return mArray.rbegin(); } - const_reverse_iterator crbegin() const { return mArray.crbegin(); } - reverse_iterator rend() { return mArray.rend(); } - const_reverse_iterator rend() const { return mArray.rend(); } - const_reverse_iterator crend() const { return mArray.crend(); } -}; - -} // namespace mozilla - -#endif // mozilla_EnumeratedArray_h diff --git a/win32/include/spidermonkey/mozilla/EnumeratedRange.h b/win32/include/spidermonkey/mozilla/EnumeratedRange.h deleted file mode 100755 index b158f8a3..00000000 --- a/win32/include/spidermonkey/mozilla/EnumeratedRange.h +++ /dev/null @@ -1,201 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Iterator over contiguous enum values */ - -/* - * Implements generator functions that create a range to iterate over the values - * of a scoped or unscoped enum. Unlike IntegerRange, which can only function on - * the underlying integral type, the elements of the generated sequence will - * have the type of the enum in question. - * - * Note that the enum values should be contiguous in the iterated range; - * unfortunately there exists no way for EnumeratedRange to enforce this - * either dynamically or at compile time. - */ - -#ifndef mozilla_EnumeratedRange_h -#define mozilla_EnumeratedRange_h - -#include - -#include "mozilla/ReverseIterator.h" - -namespace mozilla { - -namespace detail { - -template -class EnumeratedIterator -{ -public: - typedef typename std::underlying_type::type IntTypeT; - - template - explicit EnumeratedIterator(EnumType aCurrent) - : mCurrent(aCurrent) { } - - template - explicit EnumeratedIterator(const EnumeratedIterator& aOther) - : mCurrent(aOther.mCurrent) { } - - EnumTypeT operator*() const { return mCurrent; } - - /* Increment and decrement operators */ - - EnumeratedIterator& operator++() - { - mCurrent = EnumTypeT(IntTypeT(mCurrent) + IntTypeT(1)); - return *this; - } - EnumeratedIterator& operator--() - { - mCurrent = EnumTypeT(IntTypeT(mCurrent) - IntTypeT(1)); - return *this; - } - EnumeratedIterator operator++(int) - { - auto ret = *this; - mCurrent = EnumTypeT(IntTypeT(mCurrent) + IntTypeT(1)); - return ret; - } - EnumeratedIterator operator--(int) - { - auto ret = *this; - mCurrent = EnumTypeT(IntTypeT(mCurrent) - IntTypeT(1)); - return ret; - } - - /* Comparison operators */ - - template - friend bool operator==(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator!=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator<(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator<=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator>(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - template - friend bool operator>=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2); - -private: - EnumTypeT mCurrent; -}; - -template -bool operator==(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent == aIter2.mCurrent; -} - -template -bool operator!=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent != aIter2.mCurrent; -} - -template -bool operator<(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent < aIter2.mCurrent; -} - -template -bool operator<=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent <= aIter2.mCurrent; -} - -template -bool operator>(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent > aIter2.mCurrent; -} - -template -bool operator>=(const EnumeratedIterator& aIter1, - const EnumeratedIterator& aIter2) -{ - return aIter1.mCurrent >= aIter2.mCurrent; -} - -template -class EnumeratedRange -{ -public: - typedef EnumeratedIterator iterator; - typedef EnumeratedIterator const_iterator; - typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; - - template - EnumeratedRange(EnumType aBegin, EnumType aEnd) - : mBegin(aBegin), mEnd(aEnd) { } - - iterator begin() const { return iterator(mBegin); } - const_iterator cbegin() const { return begin(); } - iterator end() const { return iterator(mEnd); } - const_iterator cend() const { return end(); } - reverse_iterator rbegin() const { return reverse_iterator(mEnd); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() const { return reverse_iterator(mBegin); } - const_reverse_iterator crend() const { return rend(); } - -private: - EnumTypeT mBegin; - EnumTypeT mEnd; -}; - -} // namespace detail - -#ifdef __GNUC__ -// Enums can have an unsigned underlying type, which makes some of the -// comparisons below always true or always false. Temporarily disable -// -Wtype-limits to avoid breaking -Werror builds. -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wtype-limits" -#endif - -// Create a range to iterate from aBegin to aEnd, exclusive. -template -inline detail::EnumeratedRange -MakeEnumeratedRange(EnumType aBegin, EnumType aEnd) -{ - MOZ_ASSERT(aBegin <= aEnd, "Cannot generate invalid, unbounded range!"); - return detail::EnumeratedRange(aBegin, aEnd); -} - -// Create a range to iterate from EnumType(0) to aEnd, exclusive. EnumType(0) -// should exist, but note that there is no way for us to ensure that it does! -template -inline detail::EnumeratedRange -MakeEnumeratedRange(EnumType aEnd) -{ - return MakeEnumeratedRange(EnumType(0), aEnd); -} - -#ifdef __GNUC__ -# pragma GCC diagnostic pop -#endif - -} // namespace mozilla - -#endif // mozilla_EnumeratedRange_h - diff --git a/win32/include/spidermonkey/mozilla/FastBernoulliTrial.h b/win32/include/spidermonkey/mozilla/FastBernoulliTrial.h deleted file mode 100755 index 7e38b70a..00000000 --- a/win32/include/spidermonkey/mozilla/FastBernoulliTrial.h +++ /dev/null @@ -1,379 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_FastBernoulliTrial_h -#define mozilla_FastBernoulliTrial_h - -#include "mozilla/Assertions.h" -#include "mozilla/XorShift128PlusRNG.h" - -#include -#include - -namespace mozilla { - -/** - * class FastBernoulliTrial: Efficient sampling with uniform probability - * - * When gathering statistics about a program's behavior, we may be observing - * events that occur very frequently (e.g., function calls or memory - * allocations) and we may be gathering information that is somewhat expensive - * to produce (e.g., call stacks). Sampling all the events could have a - * significant impact on the program's performance. - * - * Why not just sample every N'th event? This technique is called "systematic - * sampling"; it's simple and efficient, and it's fine if we imagine a - * patternless stream of events. But what if we're sampling allocations, and the - * program happens to have a loop where each iteration does exactly N - * allocations? You would end up sampling the same allocation every time through - * the loop; the entire rest of the loop becomes invisible to your measurements! - * More generally, if each iteration does M allocations, and M and N have any - * common divisor at all, most allocation sites will never be sampled. If - * they're both even, say, the odd-numbered allocations disappear from your - * results. - * - * Ideally, we'd like each event to have some probability P of being sampled, - * independent of its neighbors and of its position in the sequence. This is - * called "Bernoulli sampling", and it doesn't suffer from any of the problems - * mentioned above. - * - * One disadvantage of Bernoulli sampling is that you can't be sure exactly how - * many samples you'll get: technically, it's possible that you might sample - * none of them, or all of them. But if the number of events N is large, these - * aren't likely outcomes; you can generally expect somewhere around P * N - * events to be sampled. - * - * The other disadvantage of Bernoulli sampling is that you have to generate a - * random number for every event, which can be slow. - * - * [significant pause] - * - * BUT NOT WITH THIS CLASS! FastBernoulliTrial lets you do true Bernoulli - * sampling, while generating a fresh random number only when we do decide to - * sample an event, not on every trial. When it decides not to sample, a call to - * |FastBernoulliTrial::trial| is nothing but decrementing a counter and - * comparing it to zero. So the lower your sampling probability is, the less - * overhead FastBernoulliTrial imposes. - * - * Probabilities of 0 and 1 are handled efficiently. (In neither case need we - * ever generate a random number at all.) - * - * The essential API: - * - * - FastBernoulliTrial(double P) - * Construct an instance that selects events with probability P. - * - * - FastBernoulliTrial::trial() - * Return true with probability P. Call this each time an event occurs, to - * decide whether to sample it or not. - * - * - FastBernoulliTrial::trial(size_t n) - * Equivalent to calling trial() |n| times, and returning true if any of those - * calls do. However, like trial, this runs in fast constant time. - * - * What is this good for? In some applications, some events are "bigger" than - * others. For example, large allocations are more significant than small - * allocations. Perhaps we'd like to imagine that we're drawing allocations - * from a stream of bytes, and performing a separate Bernoulli trial on every - * byte from the stream. We can accomplish this by calling |t.trial(S)| for - * the number of bytes S, and sampling the event if that returns true. - * - * Of course, this style of sampling needs to be paired with analysis and - * presentation that makes the size of the event apparent, lest trials with - * large values for |n| appear to be indistinguishable from those with small - * values for |n|. - */ -class FastBernoulliTrial { - /* - * This comment should just read, "Generate skip counts with a geometric - * distribution", and leave everyone to go look that up and see why it's the - * right thing to do, if they don't know already. - * - * BUT IF YOU'RE CURIOUS, COMMENTS ARE FREE... - * - * Instead of generating a fresh random number for every trial, we can - * randomly generate a count of how many times we should return false before - * the next time we return true. We call this a "skip count". Once we've - * returned true, we generate a fresh skip count, and begin counting down - * again. - * - * Here's an awesome fact: by exercising a little care in the way we generate - * skip counts, we can produce results indistinguishable from those we would - * get "rolling the dice" afresh for every trial. - * - * In short, skip counts in Bernoulli trials of probability P obey a geometric - * distribution. If a random variable X is uniformly distributed from [0..1), - * then std::floor(std::log(X) / std::log(1-P)) has the appropriate geometric - * distribution for the skip counts. - * - * Why that formula? - * - * Suppose we're to return |true| with some probability P, say, 0.3. Spread - * all possible futures along a line segment of length 1. In portion P of - * those cases, we'll return true on the next call to |trial|; the skip count - * is 0. For the remaining portion 1-P of cases, the skip count is 1 or more. - * - * skip: 0 1 or more - * |------------------^-----------------------------------------| - * portion: 0.3 0.7 - * P 1-P - * - * But the "1 or more" section of the line is subdivided the same way: *within - * that section*, in portion P the second call to |trial()| returns true, and in - * portion 1-P it returns false a second time; the skip count is two or more. - * So we return true on the second call in proportion 0.7 * 0.3, and skip at - * least the first two in proportion 0.7 * 0.7. - * - * skip: 0 1 2 or more - * |------------------^------------^----------------------------| - * portion: 0.3 0.7 * 0.3 0.7 * 0.7 - * P (1-P)*P (1-P)^2 - * - * We can continue to subdivide: - * - * skip >= 0: |------------------------------------------------- (1-P)^0 --| - * skip >= 1: | ------------------------------- (1-P)^1 --| - * skip >= 2: | ------------------ (1-P)^2 --| - * skip >= 3: | ^ ---------- (1-P)^3 --| - * skip >= 4: | . --- (1-P)^4 --| - * . - * ^X, see below - * - * In other words, the likelihood of the next n calls to |trial| returning - * false is (1-P)^n. The longer a run we require, the more the likelihood - * drops. Further calls may return false too, but this is the probability - * we'll skip at least n. - * - * This is interesting, because we can pick a point along this line segment - * and see which skip count's range it falls within; the point X above, for - * example, is within the ">= 2" range, but not within the ">= 3" range, so it - * designates a skip count of 2. So if we pick points on the line at random - * and use the skip counts they fall under, that will be indistinguishable - * from generating a fresh random number between 0 and 1 for each trial and - * comparing it to P. - * - * So to find the skip count for a point X, we must ask: To what whole power - * must we raise 1-P such that we include X, but the next power would exclude - * it? This is exactly std::floor(std::log(X) / std::log(1-P)). - * - * Our algorithm is then, simply: When constructed, compute an initial skip - * count. Return false from |trial| that many times, and then compute a new skip - * count. - * - * For a call to |trial(n)|, if the skip count is greater than n, return false - * and subtract n from the skip count. If the skip count is less than n, - * return true and compute a new skip count. Since each trial is independent, - * it doesn't matter by how much n overshoots the skip count; we can actually - * compute a new skip count at *any* time without affecting the distribution. - * This is really beautiful. - */ - public: - /** - * Construct a fast Bernoulli trial generator. Calls to |trial()| return true - * with probability |aProbability|. Use |aState0| and |aState1| to seed the - * random number generator; both may not be zero. - */ - FastBernoulliTrial(double aProbability, uint64_t aState0, uint64_t aState1) - : mProbability(0) - , mInvLogNotProbability(0) - , mGenerator(aState0, aState1) - , mSkipCount(0) - { - setProbability(aProbability); - } - - /** - * Return true with probability |mProbability|. Call this each time an event - * occurs, to decide whether to sample it or not. The lower |mProbability| is, - * the faster this function runs. - */ - bool trial() { - if (mSkipCount) { - mSkipCount--; - return false; - } - - return chooseSkipCount(); - } - - /** - * Equivalent to calling trial() |n| times, and returning true if any of those - * calls do. However, like trial, this runs in fast constant time. - * - * What is this good for? In some applications, some events are "bigger" than - * others. For example, large allocations are more significant than small - * allocations. Perhaps we'd like to imagine that we're drawing allocations - * from a stream of bytes, and performing a separate Bernoulli trial on every - * byte from the stream. We can accomplish this by calling |t.trial(S)| for - * the number of bytes S, and sampling the event if that returns true. - * - * Of course, this style of sampling needs to be paired with analysis and - * presentation that makes the "size" of the event apparent, lest trials with - * large values for |n| appear to be indistinguishable from those with small - * values for |n|, despite being potentially much more likely to be sampled. - */ - bool trial(size_t aCount) { - if (mSkipCount > aCount) { - mSkipCount -= aCount; - return false; - } - - return chooseSkipCount(); - } - - void setRandomState(uint64_t aState0, uint64_t aState1) { - mGenerator.setState(aState0, aState1); - } - - void setProbability(double aProbability) { - MOZ_ASSERT(0 <= aProbability && aProbability <= 1); - mProbability = aProbability; - if (0 < mProbability && mProbability < 1) { - /* - * Let's look carefully at how this calculation plays out in floating- - * point arithmetic. We'll assume IEEE, but the final C++ code we arrive - * at would still be fine if our numbers were mathematically perfect. So, - * while we've considered IEEE's edge cases, we haven't done anything that - * should be actively bad when using other representations. - * - * (In the below, read comparisons as exact mathematical comparisons: when - * we say something "equals 1", that means it's exactly equal to 1. We - * treat approximation using intervals with open boundaries: saying a - * value is in (0,1) doesn't specify how close to 0 or 1 the value gets. - * When we use closed boundaries like [2**-53, 1], we're careful to ensure - * the boundary values are actually representable.) - * - * - After the comparison above, we know mProbability is in (0,1). - * - * - The gaps below 1 are 2**-53, so that interval is (0, 1-2**-53]. - * - * - Because the floating-point gaps near 1 are wider than those near - * zero, there are many small positive doubles ε such that 1-ε rounds to - * exactly 1. However, 2**-53 can be represented exactly. So - * 1-mProbability is in [2**-53, 1]. - * - * - log(1 - mProbability) is thus in (-37, 0]. - * - * That range includes zero, but when we use mInvLogNotProbability, it - * would be helpful if we could trust that it's negative. So when log(1 - * - mProbability) is 0, we'll just set mProbability to 0, so that - * mInvLogNotProbability is not used in chooseSkipCount. - * - * - How much of the range of mProbability does this cause us to ignore? - * The only value for which log returns 0 is exactly 1; the slope of log - * at 1 is 1, so for small ε such that 1 - ε != 1, log(1 - ε) is -ε, - * never 0. The gaps near one are larger than the gaps near zero, so if - * 1 - ε wasn't 1, then -ε is representable. So if log(1 - mProbability) - * isn't 0, then 1 - mProbability isn't 1, which means that mProbability - * is at least 2**-53, as discussed earlier. This is a sampling - * likelihood of roughly one in ten trillion, which is unlikely to be - * distinguishable from zero in practice. - * - * So by forbidding zero, we've tightened our range to (-37, -2**-53]. - * - * - Finally, 1 / log(1 - mProbability) is in [-2**53, -1/37). This all - * falls readily within the range of an IEEE double. - * - * ALL THAT HAVING BEEN SAID: here are the five lines of actual code: - */ - double logNotProbability = std::log(1 - mProbability); - if (logNotProbability == 0.0) - mProbability = 0.0; - else - mInvLogNotProbability = 1 / logNotProbability; - } - - chooseSkipCount(); - } - - private: - /* The likelihood that any given call to |trial| should return true. */ - double mProbability; - - /* - * The value of 1/std::log(1 - mProbability), cached for repeated use. - * - * If mProbability is exactly 0 or exactly 1, we don't use this value. - * Otherwise, we guarantee this value is in the range [-2**53, -1/37), i.e. - * definitely negative, as required by chooseSkipCount. See setProbability for - * the details. - */ - double mInvLogNotProbability; - - /* Our random number generator. */ - non_crypto::XorShift128PlusRNG mGenerator; - - /* The number of times |trial| should return false before next returning true. */ - size_t mSkipCount; - - /* - * Choose the next skip count. This also returns the value that |trial| should - * return, since we have to check for the extreme values for mProbability - * anyway, and |trial| should never return true at all when mProbability is 0. - */ - bool chooseSkipCount() { - /* - * If the probability is 1.0, every call to |trial| returns true. Make sure - * mSkipCount is 0. - */ - if (mProbability == 1.0) { - mSkipCount = 0; - return true; - } - - /* - * If the probabilility is zero, |trial| never returns true. Don't bother us - * for a while. - */ - if (mProbability == 0.0) { - mSkipCount = SIZE_MAX; - return false; - } - - /* - * What sorts of values can this call to std::floor produce? - * - * Since mGenerator.nextDouble returns a value in [0, 1-2**-53], std::log - * returns a value in the range [-infinity, -2**-53], all negative. Since - * mInvLogNotProbability is negative (see its comments), the product is - * positive and possibly infinite. std::floor returns +infinity unchanged. - * So the result will always be positive. - * - * Converting a double to an integer that is out of range for that integer - * is undefined behavior, so we must clamp our result to SIZE_MAX, to ensure - * we get an acceptable value for mSkipCount. - * - * The clamp is written carefully. Note that if we had said: - * - * if (skipCount > SIZE_MAX) - * skipCount = SIZE_MAX; - * - * that leads to undefined behavior 64-bit machines: SIZE_MAX coerced to - * double is 2^64, not 2^64-1, so this doesn't actually set skipCount to a - * value that can be safely assigned to mSkipCount. - * - * Jakub Oleson cleverly suggested flipping the sense of the comparison: if - * we require that skipCount < SIZE_MAX, then because of the gaps (2048) - * between doubles at that magnitude, the highest double less than 2^64 is - * 2^64 - 2048, which is fine to store in a size_t. - * - * (On 32-bit machines, all size_t values can be represented exactly in - * double, so all is well.) - */ - double skipCount = std::floor(std::log(mGenerator.nextDouble()) - * mInvLogNotProbability); - if (skipCount < SIZE_MAX) - mSkipCount = skipCount; - else - mSkipCount = SIZE_MAX; - - return true; - } -}; - -} /* namespace mozilla */ - -#endif /* mozilla_FastBernoulliTrial_h */ diff --git a/win32/include/spidermonkey/mozilla/FloatingPoint.h b/win32/include/spidermonkey/mozilla/FloatingPoint.h deleted file mode 100755 index 59afccd1..00000000 --- a/win32/include/spidermonkey/mozilla/FloatingPoint.h +++ /dev/null @@ -1,479 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Various predicates and operations on IEEE-754 floating point types. */ - -#ifndef mozilla_FloatingPoint_h -#define mozilla_FloatingPoint_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Casting.h" -#include "mozilla/MathAlgorithms.h" -#include "mozilla/Types.h" - -#include - -namespace mozilla { - -/* - * It's reasonable to ask why we have this header at all. Don't isnan, - * copysign, the built-in comparison operators, and the like solve these - * problems? Unfortunately, they don't. We've found that various compilers - * (MSVC, MSVC when compiling with PGO, and GCC on OS X, at least) miscompile - * the standard methods in various situations, so we can't use them. Some of - * these compilers even have problems compiling seemingly reasonable bitwise - * algorithms! But with some care we've found algorithms that seem to not - * trigger those compiler bugs. - * - * For the aforementioned reasons, be very wary of making changes to any of - * these algorithms. If you must make changes, keep a careful eye out for - * compiler bustage, particularly PGO-specific bustage. - */ - -struct FloatTypeTraits -{ - typedef uint32_t Bits; - - static const unsigned kExponentBias = 127; - static const unsigned kExponentShift = 23; - - static const Bits kSignBit = 0x80000000UL; - static const Bits kExponentBits = 0x7F800000UL; - static const Bits kSignificandBits = 0x007FFFFFUL; -}; - -struct DoubleTypeTraits -{ - typedef uint64_t Bits; - - static const unsigned kExponentBias = 1023; - static const unsigned kExponentShift = 52; - - static const Bits kSignBit = 0x8000000000000000ULL; - static const Bits kExponentBits = 0x7ff0000000000000ULL; - static const Bits kSignificandBits = 0x000fffffffffffffULL; -}; - -template struct SelectTrait; -template<> struct SelectTrait : public FloatTypeTraits {}; -template<> struct SelectTrait : public DoubleTypeTraits {}; - -/* - * This struct contains details regarding the encoding of floating-point - * numbers that can be useful for direct bit manipulation. As of now, the - * template parameter has to be float or double. - * - * The nested typedef |Bits| is the unsigned integral type with the same size - * as T: uint32_t for float and uint64_t for double (static assertions - * double-check these assumptions). - * - * kExponentBias is the offset that is subtracted from the exponent when - * computing the value, i.e. one plus the opposite of the mininum possible - * exponent. - * kExponentShift is the shift that one needs to apply to retrieve the - * exponent component of the value. - * - * kSignBit contains a bits mask. Bit-and-ing with this mask will result in - * obtaining the sign bit. - * kExponentBits contains the mask needed for obtaining the exponent bits and - * kSignificandBits contains the mask needed for obtaining the significand - * bits. - * - * Full details of how floating point number formats are encoded are beyond - * the scope of this comment. For more information, see - * http://en.wikipedia.org/wiki/IEEE_floating_point - * http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers - */ -template -struct FloatingPoint : public SelectTrait -{ - typedef SelectTrait Base; - typedef typename Base::Bits Bits; - - static_assert((Base::kSignBit & Base::kExponentBits) == 0, - "sign bit shouldn't overlap exponent bits"); - static_assert((Base::kSignBit & Base::kSignificandBits) == 0, - "sign bit shouldn't overlap significand bits"); - static_assert((Base::kExponentBits & Base::kSignificandBits) == 0, - "exponent bits shouldn't overlap significand bits"); - - static_assert((Base::kSignBit | Base::kExponentBits | Base::kSignificandBits) == - ~Bits(0), - "all bits accounted for"); - - /* - * These implementations assume float/double are 32/64-bit single/double - * format number types compatible with the IEEE-754 standard. C++ don't - * require this to be the case. But we required this in implementations of - * these algorithms that preceded this header, so we shouldn't break anything - * if we keep doing so. - */ - static_assert(sizeof(T) == sizeof(Bits), "Bits must be same size as T"); -}; - -/** Determines whether a float/double is NaN. */ -template -static MOZ_ALWAYS_INLINE bool -IsNaN(T aValue) -{ - /* - * A float/double is NaN if all exponent bits are 1 and the significand - * contains at least one non-zero bit. - */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - return (BitwiseCast(aValue) & Traits::kExponentBits) == Traits::kExponentBits && - (BitwiseCast(aValue) & Traits::kSignificandBits) != 0; -} - -/** Determines whether a float/double is +Infinity or -Infinity. */ -template -static MOZ_ALWAYS_INLINE bool -IsInfinite(T aValue) -{ - /* Infinities have all exponent bits set to 1 and an all-0 significand. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return (bits & ~Traits::kSignBit) == Traits::kExponentBits; -} - -/** Determines whether a float/double is not NaN or infinite. */ -template -static MOZ_ALWAYS_INLINE bool -IsFinite(T aValue) -{ - /* - * NaN and Infinities are the only non-finite floats/doubles, and both have - * all exponent bits set to 1. - */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return (bits & Traits::kExponentBits) != Traits::kExponentBits; -} - -/** - * Determines whether a float/double is negative or -0. It is an error - * to call this method on a float/double which is NaN. - */ -template -static MOZ_ALWAYS_INLINE bool -IsNegative(T aValue) -{ - MOZ_ASSERT(!IsNaN(aValue), "NaN does not have a sign"); - - /* The sign bit is set if the double is negative. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return (bits & Traits::kSignBit) != 0; -} - -/** Determines whether a float/double represents -0. */ -template -static MOZ_ALWAYS_INLINE bool -IsNegativeZero(T aValue) -{ - /* Only the sign bit is set if the value is -0. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return bits == Traits::kSignBit; -} - -/** Determines wether a float/double represents +0. */ -template -static MOZ_ALWAYS_INLINE bool -IsPositiveZero(T aValue) -{ - /* All bits are zero if the value is +0. */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return bits == 0; -} - -/** - * Returns 0 if a float/double is NaN or infinite; - * otherwise, the float/double is returned. - */ -template -static MOZ_ALWAYS_INLINE T -ToZeroIfNonfinite(T aValue) -{ - return IsFinite(aValue) ? aValue : 0; -} - -/** - * Returns the exponent portion of the float/double. - * - * Zero is not special-cased, so ExponentComponent(0.0) is - * -int_fast16_t(Traits::kExponentBias). - */ -template -static MOZ_ALWAYS_INLINE int_fast16_t -ExponentComponent(T aValue) -{ - /* - * The exponent component of a float/double is an unsigned number, biased - * from its actual value. Subtract the bias to retrieve the actual exponent. - */ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - Bits bits = BitwiseCast(aValue); - return int_fast16_t((bits & Traits::kExponentBits) >> Traits::kExponentShift) - - int_fast16_t(Traits::kExponentBias); -} - -/** Returns +Infinity. */ -template -static MOZ_ALWAYS_INLINE T -PositiveInfinity() -{ - /* - * Positive infinity has all exponent bits set, sign bit set to 0, and no - * significand. - */ - typedef FloatingPoint Traits; - return BitwiseCast(Traits::kExponentBits); -} - -/** Returns -Infinity. */ -template -static MOZ_ALWAYS_INLINE T -NegativeInfinity() -{ - /* - * Negative infinity has all exponent bits set, sign bit set to 1, and no - * significand. - */ - typedef FloatingPoint Traits; - return BitwiseCast(Traits::kSignBit | Traits::kExponentBits); -} - -/** - * Computes the bit pattern for a NaN with the specified sign bit and - * significand bits. - */ -template::Bits Significand> -struct SpecificNaNBits -{ - using Traits = FloatingPoint; - - static_assert(SignBit == 0 || SignBit == 1, "bad sign bit"); - static_assert((Significand & ~Traits::kSignificandBits) == 0, - "significand must only have significand bits set"); - static_assert(Significand & Traits::kSignificandBits, - "significand must be nonzero"); - - static constexpr typename Traits::Bits value = - (SignBit * Traits::kSignBit) | Traits::kExponentBits | Significand; -}; - -/** - * Constructs a NaN value with the specified sign bit and significand bits. - * - * There is also a variant that returns the value directly. In most cases, the - * two variants should be identical. However, in the specific case of x86 - * chips, the behavior differs: returning floating-point values directly is done - * through the x87 stack, and x87 loads and stores turn signaling NaNs into - * quiet NaNs... silently. Returning floating-point values via outparam, - * however, is done entirely within the SSE registers when SSE2 floating-point - * is enabled in the compiler, which has semantics-preserving behavior you would - * expect. - * - * If preserving the distinction between signaling NaNs and quiet NaNs is - * important to you, you should use the outparam version. In all other cases, - * you should use the direct return version. - */ -template -static MOZ_ALWAYS_INLINE void -SpecificNaN(int signbit, typename FloatingPoint::Bits significand, T* result) -{ - typedef FloatingPoint Traits; - MOZ_ASSERT(signbit == 0 || signbit == 1); - MOZ_ASSERT((significand & ~Traits::kSignificandBits) == 0); - MOZ_ASSERT(significand & Traits::kSignificandBits); - - BitwiseCast((signbit ? Traits::kSignBit : 0) | - Traits::kExponentBits | - significand, - result); - MOZ_ASSERT(IsNaN(*result)); -} - -template -static MOZ_ALWAYS_INLINE T -SpecificNaN(int signbit, typename FloatingPoint::Bits significand) -{ - T t; - SpecificNaN(signbit, significand, &t); - return t; -} - -/** Computes the smallest non-zero positive float/double value. */ -template -static MOZ_ALWAYS_INLINE T -MinNumberValue() -{ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - return BitwiseCast(Bits(1)); -} - -/** - * If aValue is equal to some int32_t value, set *aInt32 to that value and - * return true; otherwise return false. - * - * Note that negative zero is "equal" to zero here. To test whether a value can - * be losslessly converted to int32_t and back, use NumberIsInt32 instead. - */ -template -static MOZ_ALWAYS_INLINE bool -NumberEqualsInt32(T aValue, int32_t* aInt32) -{ - /* - * XXX Casting a floating-point value that doesn't truncate to int32_t, to - * int32_t, induces undefined behavior. We should definitely fix this - * (bug 744965), but as apparently it "works" in practice, it's not a - * pressing concern now. - */ - return aValue == (*aInt32 = int32_t(aValue)); -} - -/** - * If d can be converted to int32_t and back to an identical double value, - * set *aInt32 to that value and return true; otherwise return false. - * - * The difference between this and NumberEqualsInt32 is that this method returns - * false for negative zero. - */ -template -static MOZ_ALWAYS_INLINE bool -NumberIsInt32(T aValue, int32_t* aInt32) -{ - return !IsNegativeZero(aValue) && NumberEqualsInt32(aValue, aInt32); -} - -/** - * Computes a NaN value. Do not use this method if you depend upon a particular - * NaN value being returned. - */ -template -static MOZ_ALWAYS_INLINE T -UnspecifiedNaN() -{ - /* - * If we can use any quiet NaN, we might as well use the all-ones NaN, - * since it's cheap to materialize on common platforms (such as x64, where - * this value can be represented in a 32-bit signed immediate field, allowing - * it to be stored to memory in a single instruction). - */ - typedef FloatingPoint Traits; - return SpecificNaN(1, Traits::kSignificandBits); -} - -/** - * Compare two doubles for equality, *without* equating -0 to +0, and equating - * any NaN value to any other NaN value. (The normal equality operators equate - * -0 with +0, and they equate NaN to no other value.) - */ -template -static inline bool -NumbersAreIdentical(T aValue1, T aValue2) -{ - typedef FloatingPoint Traits; - typedef typename Traits::Bits Bits; - if (IsNaN(aValue1)) { - return IsNaN(aValue2); - } - return BitwiseCast(aValue1) == BitwiseCast(aValue2); -} - -namespace detail { - -template -struct FuzzyEqualsEpsilon; - -template<> -struct FuzzyEqualsEpsilon -{ - // A number near 1e-5 that is exactly representable in a float. - static float value() { return 1.0f / (1 << 17); } -}; - -template<> -struct FuzzyEqualsEpsilon -{ - // A number near 1e-12 that is exactly representable in a double. - static double value() { return 1.0 / (1LL << 40); } -}; - -} // namespace detail - -/** - * Compare two floating point values for equality, modulo rounding error. That - * is, the two values are considered equal if they are both not NaN and if they - * are less than or equal to aEpsilon apart. The default value of aEpsilon is - * near 1e-5. - * - * For most scenarios you will want to use FuzzyEqualsMultiplicative instead, - * as it is more reasonable over the entire range of floating point numbers. - * This additive version should only be used if you know the range of the - * numbers you are dealing with is bounded and stays around the same order of - * magnitude. - */ -template -static MOZ_ALWAYS_INLINE bool -FuzzyEqualsAdditive(T aValue1, T aValue2, - T aEpsilon = detail::FuzzyEqualsEpsilon::value()) -{ - static_assert(IsFloatingPoint::value, "floating point type required"); - return Abs(aValue1 - aValue2) <= aEpsilon; -} - -/** - * Compare two floating point values for equality, allowing for rounding error - * relative to the magnitude of the values. That is, the two values are - * considered equal if they are both not NaN and they are less than or equal to - * some aEpsilon apart, where the aEpsilon is scaled by the smaller of the two - * argument values. - * - * In most cases you will want to use this rather than FuzzyEqualsAdditive, as - * this function effectively masks out differences in the bottom few bits of - * the floating point numbers being compared, regardless of what order of - * magnitude those numbers are at. - */ -template -static MOZ_ALWAYS_INLINE bool -FuzzyEqualsMultiplicative(T aValue1, T aValue2, - T aEpsilon = detail::FuzzyEqualsEpsilon::value()) -{ - static_assert(IsFloatingPoint::value, "floating point type required"); - // can't use std::min because of bug 965340 - T smaller = Abs(aValue1) < Abs(aValue2) ? Abs(aValue1) : Abs(aValue2); - return Abs(aValue1 - aValue2) <= aEpsilon * smaller; -} - -/** - * Returns true if the given value can be losslessly represented as an IEEE-754 - * single format number, false otherwise. All NaN values are considered - * representable (notwithstanding that the exact bit pattern of a double format - * NaN value can't be exactly represented in single format). - * - * This function isn't inlined to avoid buggy optimizations by MSVC. - */ -MOZ_MUST_USE -extern MFBT_API bool -IsFloat32Representable(double aFloat32); - -} /* namespace mozilla */ - -#endif /* mozilla_FloatingPoint_h */ diff --git a/win32/include/spidermonkey/mozilla/Function.h b/win32/include/spidermonkey/mozilla/Function.h deleted file mode 100755 index d6de9c83..00000000 --- a/win32/include/spidermonkey/mozilla/Function.h +++ /dev/null @@ -1,223 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A type-erased callable wrapper. */ - -#ifndef mozilla_Function_h -#define mozilla_Function_h - -#include "mozilla/Attributes.h" // for MOZ_IMPLICIT -#include "mozilla/Move.h" -#include "mozilla/RefCounted.h" -#include "mozilla/RefPtr.h" - -// |function| is a wrapper that can hold any type of callable -// object that can be invoked in a way that's compatible with |Signature|. -// The standard "type erasure" technique is used to avoid the type of the -// wrapper depending on the concrete type of the wrapped callable. -// -// Supported callable types include non-member functions, static member -// functions, and function objects (that is to say, objects with an overloaded -// call operator; this includes C++11 lambdas). Member functions aren't -// directly supported; they first need to be wrapped into a function object -// using |std::mem_fn()| or an equivalent. -// -// |Signature| is a type of the form |ReturnType(Arguments...)|. Syntactically, -// this is a function type; it's not used in any way other than serving as a -// vehicle to encode the return and argument types into a single type. -// -// |function| is default-constructible. A default-constructed instance is -// considered "empty". Invoking an empty instance is undefined behaviour. -// An empty instance can be populated with a callable by assigning to it. -// -// This class is intended to provide functionality similar to the C++11 -// standard library class |std::function|. - -namespace mozilla { - -namespace detail { - -template -class FunctionImplBase : public mozilla::RefCounted> -{ -public: - MOZ_DECLARE_REFCOUNTED_TYPENAME(FunctionImplBase) - - virtual ~FunctionImplBase() {} - virtual ReturnType call(Arguments... aArguments) = 0; -}; - -// Normal Callable Object. -template -class FunctionImpl : public FunctionImplBase -{ - public: - explicit FunctionImpl(const Callable& aCallable) - : mCallable(aCallable) {} - - ReturnType call(Arguments... aArguments) override - { - return mCallable(Forward(aArguments)...); - } - private: - Callable mCallable; -}; - -// Base class for passing pointer to member function. -template -class MemberFunctionImplBase : public FunctionImplBase -{ -public: - explicit MemberFunctionImplBase(const Callable& aCallable) - : mCallable(aCallable) {} - - ReturnType call(Arguments... aArguments) override - { - return callInternal(Forward(aArguments)...); - } -private: - template - ReturnType callInternal(ThisType* aThis, Args&&... aArguments) - { - return (aThis->*mCallable)(Forward(aArguments)...); - } - - template - ReturnType callInternal(ThisType&& aThis, Args&&... aArguments) - { - return (aThis.*mCallable)(Forward(aArguments)...); - } - Callable mCallable; -}; - -// For non-const member function specialization of FunctionImpl. -template -class FunctionImpl - : public MemberFunctionImplBase -{ -public: - explicit FunctionImpl(ReturnType(ThisType::*aMemberFunc)(Args...)) - : MemberFunctionImplBase(aMemberFunc) - {} -}; - -// For const member function specialization of FunctionImpl. -template -class FunctionImpl - : public MemberFunctionImplBase -{ -public: - explicit FunctionImpl(ReturnType(ThisType::*aConstMemberFunc)(Args...) const) - : MemberFunctionImplBase(aConstMemberFunc) - {} -}; - -} // namespace detail - -// The primary template is never defined. As |Signature| is required to be -// of the form |ReturnType(Arguments...)|, we only define a partial -// specialization that matches this form. This allows us to use |ReturnType| -// and |Arguments| in the definition of the specialization without having to -// introspect |Signature|. -template -class function; - -template -class function -{ -public: - function() {} - - // This constructor is implicit to match the interface of |std::function|. - template - MOZ_IMPLICIT function(const Callable& aCallable) - : mImpl(new detail::FunctionImpl(aCallable)) - {} - MOZ_IMPLICIT function(const function& aFunction) - : mImpl(aFunction.mImpl) - {} - MOZ_IMPLICIT function(decltype(nullptr)) - {} - - // Move constructor and move assingment operator. - // These should be generated automatically, but MSVC doesn't do that yet. - function(function&& aOther) : mImpl(Move(aOther.mImpl)) {} - function& operator=(function&& aOther) { - mImpl = Move(aOther.mImpl); - return *this; - } - - template - function& operator=(const Callable& aCallable) - { - mImpl = new detail::FunctionImpl(aCallable); - return *this; - } - function& operator=(const function& aFunction) - { - mImpl = aFunction.mImpl; - return *this; - } - function& operator=(decltype(nullptr)) - { - mImpl = nullptr; - return *this; - } - - template - ReturnType operator()(Args&&... aArguments) const - { - MOZ_ASSERT(mImpl); - return mImpl->call(Forward(aArguments)...); - } - - explicit operator bool() const - { - return bool(mImpl); - } - -private: - // TODO: Consider implementing a small object optimization. - RefPtr> mImpl; -}; - -template -bool -operator==(const function& aX, decltype(nullptr)) -{ - return !aX; -} - -template -bool -operator==(decltype(nullptr), const function& aX) -{ - return !aX; -} - -template -bool -operator!=(const function& aX, decltype(nullptr)) -{ - return bool(aX); -} - -template -bool -operator!=(decltype(nullptr), const function& aX) -{ - return bool(aX); -} - -} // namespace mozilla - -#endif /* mozilla_Function_h */ diff --git a/win32/include/spidermonkey/mozilla/GuardObjects.h b/win32/include/spidermonkey/mozilla/GuardObjects.h deleted file mode 100755 index 9440c71c..00000000 --- a/win32/include/spidermonkey/mozilla/GuardObjects.h +++ /dev/null @@ -1,167 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implementation of macros to ensure correct use of RAII Auto* objects. */ - -#ifndef mozilla_GuardObjects_h -#define mozilla_GuardObjects_h - -#include "mozilla/Assertions.h" -#include "mozilla/Move.h" -#include "mozilla/Types.h" - -#ifdef __cplusplus - -#ifdef DEBUG - -/** - * A custom define is used rather than |mozPoisonValue()| due to cascading - * build failures relating to how mfbt is linked on different operating - * systems. See bug 1160253. - */ -#define MOZ_POISON uintptr_t(-1) - -namespace mozilla { -namespace detail { - -/* - * The following classes are designed to cause assertions to detect - * inadvertent use of guard objects as temporaries. In other words, - * when we have a guard object whose only purpose is its constructor and - * destructor (and is never otherwise referenced), the intended use - * might be: - * - * AutoRestore savePainting(mIsPainting); - * - * but is is easy to accidentally write: - * - * AutoRestore(mIsPainting); - * - * which compiles just fine, but runs the destructor well before the - * intended time. - * - * They work by adding (#ifdef DEBUG) an additional parameter to the - * guard object's constructor, with a default value, so that users of - * the guard object's API do not need to do anything. The default value - * of this parameter is a temporary object. C++ (ISO/IEC 14882:1998), - * section 12.2 [class.temporary], clauses 4 and 5 seem to assume a - * guarantee that temporaries are destroyed in the reverse of their - * construction order, but I actually can't find a statement that that - * is true in the general case (beyond the two specific cases mentioned - * there). However, it seems to be true. - * - * These classes are intended to be used only via the macros immediately - * below them: - * - * MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER declares (ifdef DEBUG) a member - * variable, and should be put where a declaration of a private - * member variable would be placed. - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM should be placed at the end of the - * parameters to each constructor of the guard object; it declares - * (ifdef DEBUG) an additional parameter. (But use the *_ONLY_PARAM - * variant for constructors that take no other parameters.) - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL should likewise be used in - * the implementation of such constructors when they are not inline. - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT should be used in - * the implementation of such constructors to pass the parameter to - * a base class that also uses these macros - * MOZ_GUARD_OBJECT_NOTIFIER_INIT is a statement that belongs in each - * constructor. It uses the parameter declared by - * MOZ_GUARD_OBJECT_NOTIFIER_PARAM. - * - * For more details, and examples of using these macros, see - * https://developer.mozilla.org/en/Using_RAII_classes_in_Mozilla - */ -class GuardObjectNotifier -{ -private: - bool* mStatementDone; - -public: - GuardObjectNotifier() - : mStatementDone(reinterpret_cast(MOZ_POISON)) - { - } - - ~GuardObjectNotifier() - { - // Assert that the GuardObjectNotifier has been properly initialized by - // using the |MOZ_GUARD_OBJECT_NOTIFIER_INIT| macro. A poison value is - // used rather than a null check to appease static analyzers that were - // (incorrectly) detecting null pointer dereferences. - MOZ_ASSERT(mStatementDone != reinterpret_cast(MOZ_POISON)); - *mStatementDone = true; - } - - void setStatementDone(bool* aStatementIsDone) - { - mStatementDone = aStatementIsDone; - } -}; - -class GuardObjectNotificationReceiver -{ -private: - bool mStatementDone; - -public: - GuardObjectNotificationReceiver() : mStatementDone(false) { } - - ~GuardObjectNotificationReceiver() { - /* - * Assert that the guard object was not used as a temporary. (Note that - * this assert might also fire if init is not called because the guard - * object's implementation is not using the above macros correctly.) - */ - MOZ_ASSERT(mStatementDone); - } - - void init(GuardObjectNotifier& aNotifier) - { - aNotifier.setStatementDone(&mStatementDone); - } -}; - -} /* namespace detail */ -} /* namespace mozilla */ - -#undef MOZ_POISON - -#endif /* DEBUG */ - -#ifdef DEBUG -# define MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER \ - mozilla::detail::GuardObjectNotificationReceiver _mCheckNotUsedAsTemporary; -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM \ - , mozilla::detail::GuardObjectNotifier&& _notifier = \ - mozilla::detail::GuardObjectNotifier() -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM \ - mozilla::detail::GuardObjectNotifier&& _notifier = \ - mozilla::detail::GuardObjectNotifier() -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL \ - , mozilla::detail::GuardObjectNotifier&& _notifier -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_IN_IMPL \ - mozilla::detail::GuardObjectNotifier&& _notifier -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT \ - , mozilla::Move(_notifier) -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT \ - mozilla::Move(_notifier) -# define MOZ_GUARD_OBJECT_NOTIFIER_INIT \ - do { _mCheckNotUsedAsTemporary.init(_notifier); } while (0) -#else -# define MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_IN_IMPL -# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT -# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT -# define MOZ_GUARD_OBJECT_NOTIFIER_INIT do { } while (0) -#endif - -#endif /* __cplusplus */ - -#endif /* mozilla_GuardObjects_h */ diff --git a/win32/include/spidermonkey/mozilla/HashFunctions.h b/win32/include/spidermonkey/mozilla/HashFunctions.h deleted file mode 100755 index eeb192c3..00000000 --- a/win32/include/spidermonkey/mozilla/HashFunctions.h +++ /dev/null @@ -1,389 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Utilities for hashing. */ - -/* - * This file exports functions for hashing data down to a 32-bit value, - * including: - * - * - HashString Hash a char* or char16_t/wchar_t* of known or unknown - * length. - * - * - HashBytes Hash a byte array of known length. - * - * - HashGeneric Hash one or more values. Currently, we support uint32_t, - * types which can be implicitly cast to uint32_t, data - * pointers, and function pointers. - * - * - AddToHash Add one or more values to the given hash. This supports the - * same list of types as HashGeneric. - * - * - * You can chain these functions together to hash complex objects. For example: - * - * class ComplexObject - * { - * char* mStr; - * uint32_t mUint1, mUint2; - * void (*mCallbackFn)(); - * - * public: - * uint32_t hash() - * { - * uint32_t hash = HashString(mStr); - * hash = AddToHash(hash, mUint1, mUint2); - * return AddToHash(hash, mCallbackFn); - * } - * }; - * - * If you want to hash an nsAString or nsACString, use the HashString functions - * in nsHashKeys.h. - */ - -#ifndef mozilla_HashFunctions_h -#define mozilla_HashFunctions_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Char16.h" -#include "mozilla/MathAlgorithms.h" -#include "mozilla/Types.h" - -#include - -#ifdef __cplusplus -namespace mozilla { - -/** - * The golden ratio as a 32-bit fixed-point value. - */ -static const uint32_t kGoldenRatioU32 = 0x9E3779B9U; - -inline uint32_t -RotateBitsLeft32(uint32_t aValue, uint8_t aBits) -{ - MOZ_ASSERT(aBits < 32); - return (aValue << aBits) | (aValue >> (32 - aBits)); -} - -namespace detail { - -inline uint32_t -AddU32ToHash(uint32_t aHash, uint32_t aValue) -{ - /* - * This is the meat of all our hash routines. This hash function is not - * particularly sophisticated, but it seems to work well for our mostly - * plain-text inputs. Implementation notes follow. - * - * Our use of the golden ratio here is arbitrary; we could pick almost any - * number which: - * - * * is odd (because otherwise, all our hash values will be even) - * - * * has a reasonably-even mix of 1's and 0's (consider the extreme case - * where we multiply by 0x3 or 0xeffffff -- this will not produce good - * mixing across all bits of the hash). - * - * The rotation length of 5 is also arbitrary, although an odd number is again - * preferable so our hash explores the whole universe of possible rotations. - * - * Finally, we multiply by the golden ratio *after* xor'ing, not before. - * Otherwise, if |aHash| is 0 (as it often is for the beginning of a - * message), the expression - * - * (kGoldenRatioU32 * RotateBitsLeft(aHash, 5)) |xor| aValue - * - * evaluates to |aValue|. - * - * (Number-theoretic aside: Because any odd number |m| is relatively prime to - * our modulus (2^32), the list - * - * [x * m (mod 2^32) for 0 <= x < 2^32] - * - * has no duplicate elements. This means that multiplying by |m| does not - * cause us to skip any possible hash values. - * - * It's also nice if |m| has large-ish order mod 2^32 -- that is, if the - * smallest k such that m^k == 1 (mod 2^32) is large -- so we can safely - * multiply our hash value by |m| a few times without negating the - * multiplicative effect. Our golden ratio constant has order 2^29, which is - * more than enough for our purposes.) - */ - return kGoldenRatioU32 * (RotateBitsLeft32(aHash, 5) ^ aValue); -} - -/** - * AddUintptrToHash takes sizeof(uintptr_t) as a template parameter. - */ -template -inline uint32_t -AddUintptrToHash(uint32_t aHash, uintptr_t aValue); - -template<> -inline uint32_t -AddUintptrToHash<4>(uint32_t aHash, uintptr_t aValue) -{ - return AddU32ToHash(aHash, static_cast(aValue)); -} - -template<> -inline uint32_t -AddUintptrToHash<8>(uint32_t aHash, uintptr_t aValue) -{ - /* - * The static cast to uint64_t below is necessary because this function - * sometimes gets compiled on 32-bit platforms (yes, even though it's a - * template and we never call this particular override in a 32-bit build). If - * we do aValue >> 32 on a 32-bit machine, we're shifting a 32-bit uintptr_t - * right 32 bits, and the compiler throws an error. - */ - uint32_t v1 = static_cast(aValue); - uint32_t v2 = static_cast(static_cast(aValue) >> 32); - return AddU32ToHash(AddU32ToHash(aHash, v1), v2); -} - -} /* namespace detail */ - -/** - * AddToHash takes a hash and some values and returns a new hash based on the - * inputs. - * - * Currently, we support hashing uint32_t's, values which we can implicitly - * convert to uint32_t, data pointers, and function pointers. - */ -template -MOZ_MUST_USE inline uint32_t -AddToHash(uint32_t aHash, A aA) -{ - /* - * Try to convert |A| to uint32_t implicitly. If this works, great. If not, - * we'll error out. - */ - return detail::AddU32ToHash(aHash, aA); -} - -template -MOZ_MUST_USE inline uint32_t -AddToHash(uint32_t aHash, A* aA) -{ - /* - * You might think this function should just take a void*. But then we'd only - * catch data pointers and couldn't handle function pointers. - */ - - static_assert(sizeof(aA) == sizeof(uintptr_t), "Strange pointer!"); - - return detail::AddUintptrToHash(aHash, uintptr_t(aA)); -} - -template<> -MOZ_MUST_USE inline uint32_t -AddToHash(uint32_t aHash, uintptr_t aA) -{ - return detail::AddUintptrToHash(aHash, aA); -} - -template -MOZ_MUST_USE uint32_t -AddToHash(uint32_t aHash, A aArg, Args... aArgs) -{ - return AddToHash(AddToHash(aHash, aArg), aArgs...); -} - -/** - * The HashGeneric class of functions let you hash one or more values. - * - * If you want to hash together two values x and y, calling HashGeneric(x, y) is - * much better than calling AddToHash(x, y), because AddToHash(x, y) assumes - * that x has already been hashed. - */ -template -MOZ_MUST_USE inline uint32_t -HashGeneric(Args... aArgs) -{ - return AddToHash(0, aArgs...); -} - -namespace detail { - -template -uint32_t -HashUntilZero(const T* aStr) -{ - uint32_t hash = 0; - for (T c; (c = *aStr); aStr++) { - hash = AddToHash(hash, c); - } - return hash; -} - -template -uint32_t -HashKnownLength(const T* aStr, size_t aLength) -{ - uint32_t hash = 0; - for (size_t i = 0; i < aLength; i++) { - hash = AddToHash(hash, aStr[i]); - } - return hash; -} - -} /* namespace detail */ - -/** - * The HashString overloads below do just what you'd expect. - * - * If you have the string's length, you might as well call the overload which - * includes the length. It may be marginally faster. - */ -MOZ_MUST_USE inline uint32_t -HashString(const char* aStr) -{ - return detail::HashUntilZero(reinterpret_cast(aStr)); -} - -MOZ_MUST_USE inline uint32_t -HashString(const char* aStr, size_t aLength) -{ - return detail::HashKnownLength(reinterpret_cast(aStr), aLength); -} - -MOZ_MUST_USE -inline uint32_t -HashString(const unsigned char* aStr, size_t aLength) -{ - return detail::HashKnownLength(aStr, aLength); -} - -MOZ_MUST_USE inline uint32_t -HashString(const char16_t* aStr) -{ - return detail::HashUntilZero(aStr); -} - -MOZ_MUST_USE inline uint32_t -HashString(const char16_t* aStr, size_t aLength) -{ - return detail::HashKnownLength(aStr, aLength); -} - -/* - * On Windows, wchar_t is not the same as char16_t, even though it's - * the same width! - */ -#ifdef WIN32 -MOZ_MUST_USE inline uint32_t -HashString(const wchar_t* aStr) -{ - return detail::HashUntilZero(aStr); -} - -MOZ_MUST_USE inline uint32_t -HashString(const wchar_t* aStr, size_t aLength) -{ - return detail::HashKnownLength(aStr, aLength); -} -#endif - -/** - * Hash some number of bytes. - * - * This hash walks word-by-word, rather than byte-by-byte, so you won't get the - * same result out of HashBytes as you would out of HashString. - */ -MOZ_MUST_USE extern MFBT_API uint32_t -HashBytes(const void* bytes, size_t aLength); - -/** - * A pseudorandom function mapping 32-bit integers to 32-bit integers. - * - * This is for when you're feeding private data (like pointer values or credit - * card numbers) to a non-crypto hash function (like HashBytes) and then using - * the hash code for something that untrusted parties could observe (like a JS - * Map). Plug in a HashCodeScrambler before that last step to avoid leaking the - * private data. - * - * By itself, this does not prevent hash-flooding DoS attacks, because an - * attacker can still generate many values with exactly equal hash codes by - * attacking the non-crypto hash function alone. Equal hash codes will, of - * course, still be equal however much you scramble them. - * - * The algorithm is SipHash-1-3. See . - */ -class HashCodeScrambler -{ - struct SipHasher; - - uint64_t mK0, mK1; - -public: - /** Creates a new scrambler with the given 128-bit key. */ - constexpr HashCodeScrambler(uint64_t aK0, uint64_t aK1) : mK0(aK0), mK1(aK1) {} - - /** - * Scramble a hash code. Always produces the same result for the same - * combination of key and hash code. - */ - uint32_t scramble(uint32_t aHashCode) const - { - SipHasher hasher(mK0, mK1); - return uint32_t(hasher.sipHash(aHashCode)); - } - -private: - struct SipHasher - { - SipHasher(uint64_t aK0, uint64_t aK1) - { - // 1. Initialization. - mV0 = aK0 ^ UINT64_C(0x736f6d6570736575); - mV1 = aK1 ^ UINT64_C(0x646f72616e646f6d); - mV2 = aK0 ^ UINT64_C(0x6c7967656e657261); - mV3 = aK1 ^ UINT64_C(0x7465646279746573); - } - - uint64_t sipHash(uint64_t aM) - { - // 2. Compression. - mV3 ^= aM; - sipRound(); - mV0 ^= aM; - - // 3. Finalization. - mV2 ^= 0xff; - for (int i = 0; i < 3; i++) - sipRound(); - return mV0 ^ mV1 ^ mV2 ^ mV3; - } - - void sipRound() - { - mV0 += mV1; - mV1 = RotateLeft(mV1, 13); - mV1 ^= mV0; - mV0 = RotateLeft(mV0, 32); - mV2 += mV3; - mV3 = RotateLeft(mV3, 16); - mV3 ^= mV2; - mV0 += mV3; - mV3 = RotateLeft(mV3, 21); - mV3 ^= mV0; - mV2 += mV1; - mV1 = RotateLeft(mV1, 17); - mV1 ^= mV2; - mV2 = RotateLeft(mV2, 32); - } - - uint64_t mV0, mV1, mV2, mV3; - }; -}; - -} /* namespace mozilla */ -#endif /* __cplusplus */ - -#endif /* mozilla_HashFunctions_h */ diff --git a/win32/include/spidermonkey/mozilla/IndexSequence.h b/win32/include/spidermonkey/mozilla/IndexSequence.h deleted file mode 100755 index 1ccace02..00000000 --- a/win32/include/spidermonkey/mozilla/IndexSequence.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A utility for expanding a tuple into a variadic argument list. - * Based on std::index_sequence. */ - -/** - * Example usage: - * - * Problem: - * - * You have a variadic function Foo: - * - * template void Foo(Args...); - * - * And a variadic function Bar, which contains a tuple: - * - * template - * void Bar() { - * // ... - * Tuple t; - * } - * - * And inside Bar, you want to call Foo with the elements of the tuple as - * arguments to Foo. - * - * You want to write: - * - * Foo(Get<0>(t), Get<1>(t), ..., Get(t)) - * - * but you can't literally write that, because N is different for different - * instantiations of Bar. - * - * Solution: - * - * Write a helper function which takes the tuple, and an index sequence - * containing indices corresponding to the tuple indices. - * - * template - * void Helper(const Tuple& t, IndexSequence) - * { - * Foo(Get(t)...); - * } - * - * Assuming 'Indices...' are 0, 1, ..., N - 1, where N is the size of the - * tuple, pack expansion will expand the pack 'Get(t)...' to - * 'Get<0>(t), Get<1>(t), ..., Get(t)'. - * - * Finally, call the helper, creating the index sequence to pass in like so: - * - * template - * void Bar() { - * // ... - * Tuple t; - * Helper(t, typename IndexSequenceFor::Type()); - * } - */ - -#ifndef mozilla_IndexSequence_h -#define mozilla_IndexSequence_h - -#include "mozilla/Attributes.h" - -#include - -namespace mozilla { - -/** - * Represents a compile-time sequence of integer indices. - */ -template -struct IndexSequence -{ - static constexpr size_t Size() { return sizeof...(Indices); } -}; - -namespace detail { - -// Helpers used by MakeIndexSequence. - -template -struct IndexTuple -{ - typedef IndexTuple Next; -}; - -// Builds IndexTuple<0, 1, ..., N - 1>. -template -struct BuildIndexTuple -{ - typedef typename BuildIndexTuple::Type::Next Type; -}; - -template<> -struct BuildIndexTuple<0> -{ - typedef IndexTuple<> Type; -}; - -template -struct MakeIndexSequenceImpl; - -template -struct MakeIndexSequenceImpl> -{ - typedef IndexSequence Type; -}; - -} // namespace detail - -/** - * A utility for building an IndexSequence of consecutive indices. - * MakeIndexSequence::Type evaluates to IndexSequence<0, 1, .., N - 1>. - * Note: unlike std::make_index_sequence, this is not an alias template - * to work around bugs in MSVC 2013. - */ -template -struct MakeIndexSequence -{ - typedef typename detail::MakeIndexSequenceImpl::Type>::Type Type; -}; - -/** - * A utility for building an IndexSequence of consecutive indices - * corresponding to a variadic argument list. - * IndexSequenceFor evaluates to IndexSequence<0, 1, ..., N - 1> - * where N is the number of types in Types. - * Note: unlike std::index_sequence_for, this is not an alias template - * to work around bugs in MSVC 2013. - */ -template -struct IndexSequenceFor -{ - typedef typename MakeIndexSequence::Type Type; -}; - -} // namespace mozilla - -#endif /* mozilla_IndexSequence_h */ diff --git a/win32/include/spidermonkey/mozilla/IntegerPrintfMacros.h b/win32/include/spidermonkey/mozilla/IntegerPrintfMacros.h deleted file mode 100755 index c534a0ba..00000000 --- a/win32/include/spidermonkey/mozilla/IntegerPrintfMacros.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements the C99 interface. */ - -#ifndef mozilla_IntegerPrintfMacros_h_ -#define mozilla_IntegerPrintfMacros_h_ - -/* - * These macros should not be used with the NSPR printf-like functions or their - * users, e.g. mozilla/Logging.h. If you need to use NSPR's facilities, see the - * comment on supported formats at the top of nsprpub/pr/include/prprf.h. - */ - -/* - * scanf is a footgun: if the input number exceeds the bounds of the target - * type, behavior is undefined (in the compiler sense: that is, this code - * could overwrite your hard drive with zeroes): - * - * uint8_t u; - * sscanf("256", "%" SCNu8, &u); // BAD - * - * For this reason, *never* use the SCN* macros provided by this header! - */ - -#include - -/* - * Fix up Android's broken [u]intptr_t inttype macros. Android's PRI*PTR - * macros are defined as "ld", but sizeof(long) is 8 and sizeof(intptr_t) - * is 4 on 32-bit Android. TestTypeTraits.cpp asserts that these new macro - * definitions match the actual type sizes seen at compile time. - */ -#if defined(ANDROID) && !defined(__LP64__) -# undef PRIdPTR /* intptr_t */ -# define PRIdPTR "d" /* intptr_t */ -# undef PRIiPTR /* intptr_t */ -# define PRIiPTR "i" /* intptr_t */ -# undef PRIoPTR /* uintptr_t */ -# define PRIoPTR "o" /* uintptr_t */ -# undef PRIuPTR /* uintptr_t */ -# define PRIuPTR "u" /* uintptr_t */ -# undef PRIxPTR /* uintptr_t */ -# define PRIxPTR "x" /* uintptr_t */ -# undef PRIXPTR /* uintptr_t */ -# define PRIXPTR "X" /* uintptr_t */ -#endif - -#endif /* mozilla_IntegerPrintfMacros_h_ */ diff --git a/win32/include/spidermonkey/mozilla/IntegerRange.h b/win32/include/spidermonkey/mozilla/IntegerRange.h deleted file mode 100755 index 8d5d2e4d..00000000 --- a/win32/include/spidermonkey/mozilla/IntegerRange.h +++ /dev/null @@ -1,181 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Iterator over ranges of integers */ - -#ifndef mozilla_IntegerRange_h -#define mozilla_IntegerRange_h - -#include "mozilla/Assertions.h" -#include "mozilla/ReverseIterator.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -namespace detail { - -template -class IntegerIterator -{ -public: - template - explicit IntegerIterator(IntType aCurrent) - : mCurrent(aCurrent) { } - - template - explicit IntegerIterator(const IntegerIterator& aOther) - : mCurrent(aOther.mCurrent) { } - - IntTypeT operator*() const { return mCurrent; } - - /* Increment and decrement operators */ - - IntegerIterator& operator++() { ++mCurrent; return *this; } - IntegerIterator& operator--() { --mCurrent; return *this; } - IntegerIterator operator++(int) { auto ret = *this; ++mCurrent; return ret; } - IntegerIterator operator--(int) { auto ret = *this; --mCurrent; return ret; } - - /* Comparison operators */ - - template - friend bool operator==(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator!=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator<(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator<=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator>(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - template - friend bool operator>=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2); - -private: - IntTypeT mCurrent; -}; - -template -bool operator==(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent == aIter2.mCurrent; -} - -template -bool operator!=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent != aIter2.mCurrent; -} - -template -bool operator<(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent < aIter2.mCurrent; -} - -template -bool operator<=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent <= aIter2.mCurrent; -} - -template -bool operator>(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent > aIter2.mCurrent; -} - -template -bool operator>=(const IntegerIterator& aIter1, - const IntegerIterator& aIter2) -{ - return aIter1.mCurrent >= aIter2.mCurrent; -} - -template -class IntegerRange -{ -public: - typedef IntegerIterator iterator; - typedef IntegerIterator const_iterator; - typedef ReverseIterator> reverse_iterator; - typedef ReverseIterator> const_reverse_iterator; - - template - explicit IntegerRange(IntType aEnd) - : mBegin(0), mEnd(aEnd) { } - - template - IntegerRange(IntType1 aBegin, IntType2 aEnd) - : mBegin(aBegin), mEnd(aEnd) { } - - iterator begin() const { return iterator(mBegin); } - const_iterator cbegin() const { return begin(); } - iterator end() const { return iterator(mEnd); } - const_iterator cend() const { return end(); } - reverse_iterator rbegin() const { return reverse_iterator(mEnd); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() const { return reverse_iterator(mBegin); } - const_reverse_iterator crend() const { return rend(); } - -private: - IntTypeT mBegin; - IntTypeT mEnd; -}; - -template::value> -struct GeqZero -{ - static bool check(T t) { - return t >= 0; - } -}; - -template -struct GeqZero -{ - static bool check(T t) { - return true; - } -}; - -} // namespace detail - -template -detail::IntegerRange -MakeRange(IntType aEnd) -{ - static_assert(IsIntegral::value, "value must be integral"); - MOZ_ASSERT(detail::GeqZero::check(aEnd), - "Should never have negative value here"); - return detail::IntegerRange(aEnd); -} - -template -detail::IntegerRange -MakeRange(IntType1 aBegin, IntType2 aEnd) -{ - static_assert(IsIntegral::value && IsIntegral::value, - "values must both be integral"); - static_assert(IsSigned::value == IsSigned::value, - "signed/unsigned mismatch"); - MOZ_ASSERT(aEnd >= aBegin, "End value should be larger than begin value"); - return detail::IntegerRange(aBegin, aEnd); -} - -} // namespace mozilla - -#endif // mozilla_IntegerRange_h diff --git a/win32/include/spidermonkey/mozilla/IntegerTypeTraits.h b/win32/include/spidermonkey/mozilla/IntegerTypeTraits.h deleted file mode 100755 index 6144d208..00000000 --- a/win32/include/spidermonkey/mozilla/IntegerTypeTraits.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Helpers to manipulate integer types that don't fit in TypeTraits.h */ - -#ifndef mozilla_IntegerTypeTraits_h -#define mozilla_IntegerTypeTraits_h - -#include "mozilla/TypeTraits.h" -#include - -namespace mozilla { - -namespace detail { - -/** - * StdintTypeForSizeAndSignedness returns the stdint integer type - * of given size (can be 1, 2, 4 or 8) and given signedness - * (false means unsigned, true means signed). - */ -template -struct StdintTypeForSizeAndSignedness; - -template<> -struct StdintTypeForSizeAndSignedness<1, true> -{ - typedef int8_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<1, false> -{ - typedef uint8_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<2, true> -{ - typedef int16_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<2, false> -{ - typedef uint16_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<4, true> -{ - typedef int32_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<4, false> -{ - typedef uint32_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<8, true> -{ - typedef int64_t Type; -}; - -template<> -struct StdintTypeForSizeAndSignedness<8, false> -{ - typedef uint64_t Type; -}; - -} // namespace detail - -template -struct UnsignedStdintTypeForSize - : detail::StdintTypeForSizeAndSignedness -{}; - -template -struct SignedStdintTypeForSize - : detail::StdintTypeForSizeAndSignedness -{}; - -template -struct PositionOfSignBit -{ - static_assert(IsIntegral::value, - "PositionOfSignBit is only for integral types"); - // 8 here should be CHAR_BIT from limits.h, but the world has moved on. - static const size_t value = 8 * sizeof(IntegerType) - 1; -}; - -/** - * MinValue returns the minimum value of the given integer type as a - * compile-time constant, which std::numeric_limits::min() - * cannot do in c++98. - */ -template -struct MinValue -{ -private: - static_assert(IsIntegral::value, - "MinValue is only for integral types"); - - typedef typename MakeUnsigned::Type UnsignedIntegerType; - static const size_t PosOfSignBit = PositionOfSignBit::value; - -public: - // Bitwise ops may return a larger type, that's why we cast explicitly. - // In C++, left bit shifts on signed values is undefined by the standard - // unless the shifted value is representable. - // Notice that signed-to-unsigned conversions are always well-defined in - // the standard as the value congruent to 2**n, as expected. By contrast, - // unsigned-to-signed is only well-defined if the value is representable. - static const IntegerType value = - IsSigned::value - ? IntegerType(UnsignedIntegerType(1) << PosOfSignBit) - : IntegerType(0); -}; - -/** - * MaxValue returns the maximum value of the given integer type as a - * compile-time constant, which std::numeric_limits::max() - * cannot do in c++98. - */ -template -struct MaxValue -{ - static_assert(IsIntegral::value, - "MaxValue is only for integral types"); - - // Tricksy, but covered by the CheckedInt unit test. - // Relies on the type of MinValue::value - // being IntegerType. - static const IntegerType value = ~MinValue::value; -}; - -} // namespace mozilla - -#endif // mozilla_IntegerTypeTraits_h diff --git a/win32/include/spidermonkey/mozilla/JSONWriter.h b/win32/include/spidermonkey/mozilla/JSONWriter.h deleted file mode 100755 index 7d44dc7f..00000000 --- a/win32/include/spidermonkey/mozilla/JSONWriter.h +++ /dev/null @@ -1,460 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A JSON pretty-printer class. */ - -// A typical JSON-writing library requires you to first build up a data -// structure that represents a JSON object and then serialize it (to file, or -// somewhere else). This approach makes for a clean API, but building the data -// structure takes up memory. Sometimes that isn't desirable, such as when the -// JSON data is produced for memory reporting. -// -// The JSONWriter class instead allows JSON data to be written out -// incrementally without building up large data structures. -// -// The API is slightly uglier than you would see in a typical JSON-writing -// library, but still fairly easy to use. It's possible to generate invalid -// JSON with JSONWriter, but typically the most basic testing will identify any -// such problems. -// -// Similarly, there are no RAII facilities for automatically closing objects -// and arrays. These would be nice if you are generating all your code within -// nested functions, but in other cases you'd have to maintain an explicit -// stack of RAII objects and manually unwind it, which is no better than just -// calling "end" functions. Furthermore, the consequences of forgetting to -// close an object or array are obvious and, again, will be identified via -// basic testing, unlike other cases where RAII is typically used (e.g. smart -// pointers) and the consequences of defects are more subtle. -// -// Importantly, the class does solve the two hard problems of JSON -// pretty-printing, which are (a) correctly escaping strings, and (b) adding -// appropriate indentation and commas between items. -// -// By default, every property is placed on its own line. However, it is -// possible to request that objects and arrays be placed entirely on a single -// line, which can reduce output size significantly in some cases. -// -// Strings used (for property names and string property values) are |const -// char*| throughout, and can be ASCII or UTF-8. -// -// EXAMPLE -// ------- -// Assume that |MyWriteFunc| is a class that implements |JSONWriteFunc|. The -// following code: -// -// JSONWriter w(MakeUnique()); -// w.Start(); -// { -// w.NullProperty("null"); -// w.BoolProperty("bool", true); -// w.IntProperty("int", 1); -// w.StartArrayProperty("array"); -// { -// w.StringElement("string"); -// w.StartObjectElement(); -// { -// w.DoubleProperty("double", 3.4); -// w.StartArrayProperty("single-line array", w.SingleLineStyle); -// { -// w.IntElement(1); -// w.StartObjectElement(); // SingleLineStyle is inherited from -// w.EndObjectElement(); // above for this collection -// } -// w.EndArray(); -// } -// w.EndObjectElement(); -// } -// w.EndArrayProperty(); -// } -// w.End(); -// -// will produce pretty-printed output for the following JSON object: -// -// { -// "null": null, -// "bool": true, -// "int": 1, -// "array": [ -// "string", -// { -// "double": 3.4, -// "single-line array": [1, {}] -// } -// ] -// } -// -// The nesting in the example code is obviously optional, but can aid -// readability. - -#ifndef mozilla_JSONWriter_h -#define mozilla_JSONWriter_h - -#include "mozilla/double-conversion.h" -#include "mozilla/IntegerPrintfMacros.h" -#include "mozilla/PodOperations.h" -#include "mozilla/Sprintf.h" -#include "mozilla/UniquePtr.h" -#include "mozilla/Vector.h" - -#include - -namespace mozilla { - -// A quasi-functor for JSONWriter. We don't use a true functor because that -// requires templatizing JSONWriter, and the templatization seeps to lots of -// places we don't want it to. -class JSONWriteFunc -{ -public: - virtual void Write(const char* aStr) = 0; - virtual ~JSONWriteFunc() {} -}; - -// Ideally this would be within |EscapedString| but when compiling with GCC -// on Linux that caused link errors, whereas this formulation didn't. -namespace detail { -extern MFBT_DATA const char gTwoCharEscapes[256]; -} // namespace detail - -class JSONWriter -{ - // From http://www.ietf.org/rfc/rfc4627.txt: - // - // "All Unicode characters may be placed within the quotation marks except - // for the characters that must be escaped: quotation mark, reverse - // solidus, and the control characters (U+0000 through U+001F)." - // - // This implementation uses two-char escape sequences where possible, namely: - // - // \", \\, \b, \f, \n, \r, \t - // - // All control characters not in the above list are represented with a - // six-char escape sequence, e.g. '\u000b' (a.k.a. '\v'). - // - class EscapedString - { - // Only one of |mUnownedStr| and |mOwnedStr| are ever non-null. |mIsOwned| - // indicates which one is in use. They're not within a union because that - // wouldn't work with UniquePtr. - bool mIsOwned; - const char* mUnownedStr; - UniquePtr mOwnedStr; - - void SanityCheck() const - { - MOZ_ASSERT_IF( mIsOwned, mOwnedStr.get() && !mUnownedStr); - MOZ_ASSERT_IF(!mIsOwned, !mOwnedStr.get() && mUnownedStr); - } - - static char hexDigitToAsciiChar(uint8_t u) - { - u = u & 0xf; - return u < 10 ? '0' + u : 'a' + (u - 10); - } - - public: - explicit EscapedString(const char* aStr) - : mUnownedStr(nullptr) - , mOwnedStr(nullptr) - { - const char* p; - - // First, see if we need to modify the string. - size_t nExtra = 0; - p = aStr; - while (true) { - uint8_t u = *p; // ensure it can't be interpreted as negative - if (u == 0) { - break; - } - if (detail::gTwoCharEscapes[u]) { - nExtra += 1; - } else if (u <= 0x1f) { - nExtra += 5; - } - p++; - } - - if (nExtra == 0) { - // No escapes needed. Easy. - mIsOwned = false; - mUnownedStr = aStr; - return; - } - - // Escapes are needed. We'll create a new string. - mIsOwned = true; - size_t len = (p - aStr) + nExtra; - mOwnedStr = MakeUnique(len + 1); - - p = aStr; - size_t i = 0; - - while (true) { - uint8_t u = *p; // ensure it can't be interpreted as negative - if (u == 0) { - mOwnedStr[i] = 0; - break; - } - if (detail::gTwoCharEscapes[u]) { - mOwnedStr[i++] = '\\'; - mOwnedStr[i++] = detail::gTwoCharEscapes[u]; - } else if (u <= 0x1f) { - mOwnedStr[i++] = '\\'; - mOwnedStr[i++] = 'u'; - mOwnedStr[i++] = '0'; - mOwnedStr[i++] = '0'; - mOwnedStr[i++] = hexDigitToAsciiChar((u & 0x00f0) >> 4); - mOwnedStr[i++] = hexDigitToAsciiChar(u & 0x000f); - } else { - mOwnedStr[i++] = u; - } - p++; - } - } - - ~EscapedString() - { - SanityCheck(); - } - - const char* get() const - { - SanityCheck(); - return mIsOwned ? mOwnedStr.get() : mUnownedStr; - } - }; - -public: - // Collections (objects and arrays) are printed in a multi-line style by - // default. This can be changed to a single-line style if SingleLineStyle is - // specified. If a collection is printed in single-line style, every nested - // collection within it is also printed in single-line style, even if - // multi-line style is requested. - enum CollectionStyle { - MultiLineStyle, // the default - SingleLineStyle - }; - -protected: - const UniquePtr mWriter; - Vector mNeedComma; // do we need a comma at depth N? - Vector mNeedNewlines; // do we need newlines at depth N? - size_t mDepth; // the current nesting depth - - void Indent() - { - for (size_t i = 0; i < mDepth; i++) { - mWriter->Write(" "); - } - } - - // Adds whatever is necessary (maybe a comma, and then a newline and - // whitespace) to separate an item (property or element) from what's come - // before. - void Separator() - { - if (mNeedComma[mDepth]) { - mWriter->Write(","); - } - if (mDepth > 0 && mNeedNewlines[mDepth]) { - mWriter->Write("\n"); - Indent(); - } else if (mNeedComma[mDepth]) { - mWriter->Write(" "); - } - } - - void PropertyNameAndColon(const char* aName) - { - EscapedString escapedName(aName); - mWriter->Write("\""); - mWriter->Write(escapedName.get()); - mWriter->Write("\": "); - } - - void Scalar(const char* aMaybePropertyName, const char* aStringValue) - { - Separator(); - if (aMaybePropertyName) { - PropertyNameAndColon(aMaybePropertyName); - } - mWriter->Write(aStringValue); - mNeedComma[mDepth] = true; - } - - void QuotedScalar(const char* aMaybePropertyName, const char* aStringValue) - { - Separator(); - if (aMaybePropertyName) { - PropertyNameAndColon(aMaybePropertyName); - } - mWriter->Write("\""); - mWriter->Write(aStringValue); - mWriter->Write("\""); - mNeedComma[mDepth] = true; - } - - void NewVectorEntries() - { - // If these tiny allocations OOM we might as well just crash because we - // must be in serious memory trouble. - MOZ_RELEASE_ASSERT(mNeedComma.resizeUninitialized(mDepth + 1)); - MOZ_RELEASE_ASSERT(mNeedNewlines.resizeUninitialized(mDepth + 1)); - mNeedComma[mDepth] = false; - mNeedNewlines[mDepth] = true; - } - - void StartCollection(const char* aMaybePropertyName, const char* aStartChar, - CollectionStyle aStyle = MultiLineStyle) - { - Separator(); - if (aMaybePropertyName) { - mWriter->Write("\""); - mWriter->Write(aMaybePropertyName); - mWriter->Write("\": "); - } - mWriter->Write(aStartChar); - mNeedComma[mDepth] = true; - mDepth++; - NewVectorEntries(); - mNeedNewlines[mDepth] = - mNeedNewlines[mDepth - 1] && aStyle == MultiLineStyle; - } - - // Adds the whitespace and closing char necessary to end a collection. - void EndCollection(const char* aEndChar) - { - if (mNeedNewlines[mDepth]) { - mWriter->Write("\n"); - mDepth--; - Indent(); - } else { - mDepth--; - } - mWriter->Write(aEndChar); - } - -public: - explicit JSONWriter(UniquePtr aWriter) - : mWriter(Move(aWriter)) - , mNeedComma() - , mNeedNewlines() - , mDepth(0) - { - NewVectorEntries(); - } - - // Returns the JSONWriteFunc passed in at creation, for temporary use. The - // JSONWriter object still owns the JSONWriteFunc. - JSONWriteFunc* WriteFunc() const { return mWriter.get(); } - - // For all the following functions, the "Prints:" comment indicates what the - // basic output looks like. However, it doesn't indicate the whitespace and - // trailing commas, which are automatically added as required. - // - // All property names and string properties are escaped as necessary. - - // Prints: { - void Start(CollectionStyle aStyle = MultiLineStyle) - { - StartCollection(nullptr, "{", aStyle); - } - - // Prints: } - void End() { EndCollection("}\n"); } - - // Prints: "": null - void NullProperty(const char* aName) - { - Scalar(aName, "null"); - } - - // Prints: null - void NullElement() { NullProperty(nullptr); } - - // Prints: "": - void BoolProperty(const char* aName, bool aBool) - { - Scalar(aName, aBool ? "true" : "false"); - } - - // Prints: - void BoolElement(bool aBool) { BoolProperty(nullptr, aBool); } - - // Prints: "": - void IntProperty(const char* aName, int64_t aInt) - { - char buf[64]; - SprintfLiteral(buf, "%" PRId64, aInt); - Scalar(aName, buf); - } - - // Prints: - void IntElement(int64_t aInt) { IntProperty(nullptr, aInt); } - - // Prints: "": - void DoubleProperty(const char* aName, double aDouble) - { - static const size_t buflen = 64; - char buf[buflen]; - const double_conversion::DoubleToStringConverter &converter = - double_conversion::DoubleToStringConverter::EcmaScriptConverter(); - double_conversion::StringBuilder builder(buf, buflen); - converter.ToShortest(aDouble, &builder); - Scalar(aName, builder.Finalize()); - } - - // Prints: - void DoubleElement(double aDouble) { DoubleProperty(nullptr, aDouble); } - - // Prints: "": "" - void StringProperty(const char* aName, const char* aStr) - { - EscapedString escapedStr(aStr); - QuotedScalar(aName, escapedStr.get()); - } - - // Prints: "" - void StringElement(const char* aStr) { StringProperty(nullptr, aStr); } - - // Prints: "": [ - void StartArrayProperty(const char* aName, - CollectionStyle aStyle = MultiLineStyle) - { - StartCollection(aName, "[", aStyle); - } - - // Prints: [ - void StartArrayElement(CollectionStyle aStyle = MultiLineStyle) - { - StartArrayProperty(nullptr, aStyle); - } - - // Prints: ] - void EndArray() { EndCollection("]"); } - - // Prints: "": { - void StartObjectProperty(const char* aName, - CollectionStyle aStyle = MultiLineStyle) - { - StartCollection(aName, "{", aStyle); - } - - // Prints: { - void StartObjectElement(CollectionStyle aStyle = MultiLineStyle) - { - StartObjectProperty(nullptr, aStyle); - } - - // Prints: } - void EndObject() { EndCollection("}"); } -}; - -} // namespace mozilla - -#endif /* mozilla_JSONWriter_h */ - diff --git a/win32/include/spidermonkey/mozilla/Likely.h b/win32/include/spidermonkey/mozilla/Likely.h deleted file mode 100755 index 4f216092..00000000 --- a/win32/include/spidermonkey/mozilla/Likely.h +++ /dev/null @@ -1,23 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * MOZ_LIKELY and MOZ_UNLIKELY macros to hint to the compiler how a - * boolean predicate should be branch-predicted. - */ - -#ifndef mozilla_Likely_h -#define mozilla_Likely_h - -#if defined(__clang__) || defined(__GNUC__) -# define MOZ_LIKELY(x) (__builtin_expect(!!(x), 1)) -# define MOZ_UNLIKELY(x) (__builtin_expect(!!(x), 0)) -#else -# define MOZ_LIKELY(x) (!!(x)) -# define MOZ_UNLIKELY(x) (!!(x)) -#endif - -#endif /* mozilla_Likely_h */ diff --git a/win32/include/spidermonkey/mozilla/LinkedList.h b/win32/include/spidermonkey/mozilla/LinkedList.h deleted file mode 100755 index 6e14aa16..00000000 --- a/win32/include/spidermonkey/mozilla/LinkedList.h +++ /dev/null @@ -1,659 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A type-safe doubly-linked list class. */ - -/* - * The classes LinkedList and LinkedListElement together form a - * convenient, type-safe doubly-linked list implementation. - * - * The class T which will be inserted into the linked list must inherit from - * LinkedListElement. A given object may be in only one linked list at a - * time. - * - * A LinkedListElement automatically removes itself from the list upon - * destruction, and a LinkedList will fatally assert in debug builds if it's - * non-empty when it's destructed. - * - * For example, you might use LinkedList in a simple observer list class as - * follows. - * - * class Observer : public LinkedListElement - * { - * public: - * void observe(char* aTopic) { ... } - * }; - * - * class ObserverContainer - * { - * private: - * LinkedList list; - * - * public: - * void addObserver(Observer* aObserver) - * { - * // Will assert if |aObserver| is part of another list. - * list.insertBack(aObserver); - * } - * - * void removeObserver(Observer* aObserver) - * { - * // Will assert if |aObserver| is not part of some list. - * aObserver.remove(); - * // Or, will assert if |aObserver| is not part of |list| specifically. - * // aObserver.removeFrom(list); - * } - * - * void notifyObservers(char* aTopic) - * { - * for (Observer* o = list.getFirst(); o != nullptr; o = o->getNext()) { - * o->observe(aTopic); - * } - * } - * }; - * - * Additionally, the class AutoCleanLinkedList is a LinkedList that will - * remove and delete each element still within itself upon destruction. Note - * that because each element is deleted, elements must have been allocated - * using |new|. - */ - -#ifndef mozilla_LinkedList_h -#define mozilla_LinkedList_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/RefPtr.h" - -#ifdef __cplusplus - -namespace mozilla { - -template -class LinkedListElement; - -namespace detail { - -/** - * LinkedList supports refcounted elements using this adapter class. Clients - * using LinkedList> will get a data structure that holds a strong - * reference to T as long as T is in the list. - */ -template -struct LinkedListElementTraits -{ - typedef T* RawType; - typedef const T* ConstRawType; - typedef T* ClientType; - typedef const T* ConstClientType; - - // These static methods are called when an element is added to or removed from - // a linked list. It can be used to keep track ownership in lists that are - // supposed to own their elements. If elements are transferred from one list - // to another, no enter or exit calls happen since the elements still belong - // to a list. - static void enterList(LinkedListElement* elt) {} - static void exitList(LinkedListElement* elt) {} -}; - -template -struct LinkedListElementTraits> -{ - typedef T* RawType; - typedef const T* ConstRawType; - typedef RefPtr ClientType; - typedef RefPtr ConstClientType; - - static void enterList(LinkedListElement>* elt) { elt->asT()->AddRef(); } - static void exitList(LinkedListElement>* elt) { elt->asT()->Release(); } -}; - -} /* namespace detail */ - -template -class LinkedList; - -template -class LinkedListElement -{ - typedef typename detail::LinkedListElementTraits Traits; - typedef typename Traits::RawType RawType; - typedef typename Traits::ConstRawType ConstRawType; - typedef typename Traits::ClientType ClientType; - typedef typename Traits::ConstClientType ConstClientType; - - /* - * It's convenient that we return nullptr when getNext() or getPrevious() - * hits the end of the list, but doing so costs an extra word of storage in - * each linked list node (to keep track of whether |this| is the sentinel - * node) and a branch on this value in getNext/getPrevious. - * - * We could get rid of the extra word of storage by shoving the "is - * sentinel" bit into one of the pointers, although this would, of course, - * have performance implications of its own. - * - * But the goal here isn't to win an award for the fastest or slimmest - * linked list; rather, we want a *convenient* linked list. So we won't - * waste time guessing which micro-optimization strategy is best. - * - * - * Speaking of unnecessary work, it's worth addressing here why we wrote - * mozilla::LinkedList in the first place, instead of using stl::list. - * - * The key difference between mozilla::LinkedList and stl::list is that - * mozilla::LinkedList stores the mPrev/mNext pointers in the object itself, - * while stl::list stores the mPrev/mNext pointers in a list element which - * itself points to the object being stored. - * - * mozilla::LinkedList's approach makes it harder to store an object in more - * than one list. But the upside is that you can call next() / prev() / - * remove() directly on the object. With stl::list, you'd need to store a - * pointer to its iterator in the object in order to accomplish this. Not - * only would this waste space, but you'd have to remember to update that - * pointer every time you added or removed the object from a list. - * - * In-place, constant-time removal is a killer feature of doubly-linked - * lists, and supporting this painlessly was a key design criterion. - */ - -private: - LinkedListElement* mNext; - LinkedListElement* mPrev; - const bool mIsSentinel; - -public: - LinkedListElement() - : mNext(this), - mPrev(this), - mIsSentinel(false) - { } - - /* - * Moves |aOther| into |*this|. If |aOther| is already in a list, then - * |aOther| is removed from the list and replaced by |*this|. - */ - LinkedListElement(LinkedListElement&& aOther) - : mIsSentinel(aOther.mIsSentinel) - { - adjustLinkForMove(Move(aOther)); - } - - LinkedListElement& operator=(LinkedListElement&& aOther) - { - MOZ_ASSERT(mIsSentinel == aOther.mIsSentinel, "Mismatch NodeKind!"); - MOZ_ASSERT(!isInList(), - "Assigning to an element in a list messes up that list!"); - adjustLinkForMove(Move(aOther)); - return *this; - } - - ~LinkedListElement() - { - if (!mIsSentinel && isInList()) { - remove(); - } - } - - /* - * Get the next element in the list, or nullptr if this is the last element - * in the list. - */ - RawType getNext() { return mNext->asT(); } - ConstRawType getNext() const { return mNext->asT(); } - - /* - * Get the previous element in the list, or nullptr if this is the first - * element in the list. - */ - RawType getPrevious() { return mPrev->asT(); } - ConstRawType getPrevious() const { return mPrev->asT(); } - - /* - * Insert aElem after this element in the list. |this| must be part of a - * linked list when you call setNext(); otherwise, this method will assert. - */ - void setNext(RawType aElem) - { - MOZ_ASSERT(isInList()); - setNextUnsafe(aElem); - } - - /* - * Insert aElem before this element in the list. |this| must be part of a - * linked list when you call setPrevious(); otherwise, this method will - * assert. - */ - void setPrevious(RawType aElem) - { - MOZ_ASSERT(isInList()); - setPreviousUnsafe(aElem); - } - - /* - * Remove this element from the list which contains it. If this element is - * not currently part of a linked list, this method asserts. - */ - void remove() - { - MOZ_ASSERT(isInList()); - - mPrev->mNext = mNext; - mNext->mPrev = mPrev; - mNext = this; - mPrev = this; - - Traits::exitList(this); - } - - /* - * Remove this element from the list containing it. Returns a pointer to the - * element that follows this element (before it was removed). This method - * asserts if the element does not belong to a list. - */ - ClientType removeAndGetNext() - { - ClientType r = getNext(); - remove(); - return r; - } - - /* - * Remove this element from the list containing it. Returns a pointer to the - * previous element in the containing list (before the removal). This method - * asserts if the element does not belong to a list. - */ - ClientType removeAndGetPrevious() - { - ClientType r = getPrevious(); - remove(); - return r; - } - - /* - * Identical to remove(), but also asserts in debug builds that this element - * is in aList. - */ - void removeFrom(const LinkedList& aList) - { - aList.assertContains(asT()); - remove(); - } - - /* - * Return true if |this| part is of a linked list, and false otherwise. - */ - bool isInList() const - { - MOZ_ASSERT((mNext == this) == (mPrev == this)); - return mNext != this; - } - -private: - friend class LinkedList; - friend struct detail::LinkedListElementTraits; - - enum class NodeKind { - Normal, - Sentinel - }; - - explicit LinkedListElement(NodeKind nodeKind) - : mNext(this), - mPrev(this), - mIsSentinel(nodeKind == NodeKind::Sentinel) - { } - - /* - * Return |this| cast to T* if we're a normal node, or return nullptr if - * we're a sentinel node. - */ - RawType asT() - { - return mIsSentinel ? nullptr : static_cast(this); - } - ConstRawType asT() const - { - return mIsSentinel ? nullptr : static_cast(this); - } - - /* - * Insert aElem after this element, but don't check that this element is in - * the list. This is called by LinkedList::insertFront(). - */ - void setNextUnsafe(RawType aElem) - { - LinkedListElement *listElem = static_cast(aElem); - MOZ_ASSERT(!listElem->isInList()); - - listElem->mNext = this->mNext; - listElem->mPrev = this; - this->mNext->mPrev = listElem; - this->mNext = listElem; - - Traits::enterList(aElem); - } - - /* - * Insert aElem before this element, but don't check that this element is in - * the list. This is called by LinkedList::insertBack(). - */ - void setPreviousUnsafe(RawType aElem) - { - LinkedListElement* listElem = static_cast*>(aElem); - MOZ_ASSERT(!listElem->isInList()); - - listElem->mNext = this; - listElem->mPrev = this->mPrev; - this->mPrev->mNext = listElem; - this->mPrev = listElem; - - Traits::enterList(aElem); - } - - /* - * Adjust mNext and mPrev for implementing move constructor and move - * assignment. - */ - void adjustLinkForMove(LinkedListElement&& aOther) - { - if (!aOther.isInList()) { - mNext = this; - mPrev = this; - return; - } - - if (!mIsSentinel) { - Traits::enterList(this); - } - - MOZ_ASSERT(aOther.mNext->mPrev == &aOther); - MOZ_ASSERT(aOther.mPrev->mNext == &aOther); - - /* - * Initialize |this| with |aOther|'s mPrev/mNext pointers, and adjust those - * element to point to this one. - */ - mNext = aOther.mNext; - mPrev = aOther.mPrev; - - mNext->mPrev = this; - mPrev->mNext = this; - - /* - * Adjust |aOther| so it doesn't think it's in a list. This makes it - * safely destructable. - */ - aOther.mNext = &aOther; - aOther.mPrev = &aOther; - - if (!mIsSentinel) { - Traits::exitList(&aOther); - } - } - - LinkedListElement& operator=(const LinkedListElement& aOther) = delete; - LinkedListElement(const LinkedListElement& aOther) = delete; -}; - -template -class LinkedList -{ -private: - typedef typename detail::LinkedListElementTraits Traits; - typedef typename Traits::RawType RawType; - typedef typename Traits::ConstRawType ConstRawType; - typedef typename Traits::ClientType ClientType; - typedef typename Traits::ConstClientType ConstClientType; - - LinkedListElement sentinel; - -public: - class Iterator { - RawType mCurrent; - - public: - explicit Iterator(RawType aCurrent) : mCurrent(aCurrent) {} - - RawType operator *() const { - return mCurrent; - } - - const Iterator& operator++() { - mCurrent = mCurrent->getNext(); - return *this; - } - - bool operator!=(Iterator& aOther) const { - return mCurrent != aOther.mCurrent; - } - }; - - LinkedList() : sentinel(LinkedListElement::NodeKind::Sentinel) { } - - LinkedList(LinkedList&& aOther) - : sentinel(mozilla::Move(aOther.sentinel)) - { } - - LinkedList& operator=(LinkedList&& aOther) - { - MOZ_ASSERT(isEmpty(), "Assigning to a non-empty list leaks elements in that list!"); - sentinel = mozilla::Move(aOther.sentinel); - return *this; - } - - ~LinkedList() { - MOZ_ASSERT(isEmpty(), - "failing this assertion means this LinkedList's creator is " - "buggy: it should have removed all this list's elements before " - "the list's destruction"); - } - - /* - * Add aElem to the front of the list. - */ - void insertFront(RawType aElem) - { - /* Bypass setNext()'s this->isInList() assertion. */ - sentinel.setNextUnsafe(aElem); - } - - /* - * Add aElem to the back of the list. - */ - void insertBack(RawType aElem) - { - sentinel.setPreviousUnsafe(aElem); - } - - /* - * Get the first element of the list, or nullptr if the list is empty. - */ - RawType getFirst() { return sentinel.getNext(); } - ConstRawType getFirst() const { return sentinel.getNext(); } - - /* - * Get the last element of the list, or nullptr if the list is empty. - */ - RawType getLast() { return sentinel.getPrevious(); } - ConstRawType getLast() const { return sentinel.getPrevious(); } - - /* - * Get and remove the first element of the list. If the list is empty, - * return nullptr. - */ - ClientType popFirst() - { - ClientType ret = sentinel.getNext(); - if (ret) { - static_cast*>(RawType(ret))->remove(); - } - return ret; - } - - /* - * Get and remove the last element of the list. If the list is empty, - * return nullptr. - */ - ClientType popLast() - { - ClientType ret = sentinel.getPrevious(); - if (ret) { - static_cast*>(RawType(ret))->remove(); - } - return ret; - } - - /* - * Return true if the list is empty, or false otherwise. - */ - bool isEmpty() const - { - return !sentinel.isInList(); - } - - /* - * Remove all the elements from the list. - * - * This runs in time linear to the list's length, because we have to mark - * each element as not in the list. - */ - void clear() - { - while (popFirst()) { - continue; - } - } - - /* - * Allow range-based iteration: - * - * for (MyElementType* elt : myList) { ... } - */ - Iterator begin() { - return Iterator(getFirst()); - } - Iterator end() { - return Iterator(nullptr); - } - - /* - * Measures the memory consumption of the list excluding |this|. Note that - * it only measures the list elements themselves. If the list elements - * contain pointers to other memory blocks, those blocks must be measured - * separately during a subsequent iteration over the list. - */ - size_t sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const - { - size_t n = 0; - for (const T* t = getFirst(); t; t = t->getNext()) { - n += aMallocSizeOf(t); - } - return n; - } - - /* - * Like sizeOfExcludingThis(), but measures |this| as well. - */ - size_t sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const - { - return aMallocSizeOf(this) + sizeOfExcludingThis(aMallocSizeOf); - } - - /* - * In a debug build, make sure that the list is sane (no cycles, consistent - * mNext/mPrev pointers, only one sentinel). Has no effect in release builds. - */ - void debugAssertIsSane() const - { -#ifdef DEBUG - const LinkedListElement* slow; - const LinkedListElement* fast1; - const LinkedListElement* fast2; - - /* - * Check for cycles in the forward singly-linked list using the - * tortoise/hare algorithm. - */ - for (slow = sentinel.mNext, - fast1 = sentinel.mNext->mNext, - fast2 = sentinel.mNext->mNext->mNext; - slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; - slow = slow->mNext, fast1 = fast2->mNext, fast2 = fast1->mNext) { - MOZ_ASSERT(slow != fast1); - MOZ_ASSERT(slow != fast2); - } - - /* Check for cycles in the backward singly-linked list. */ - for (slow = sentinel.mPrev, - fast1 = sentinel.mPrev->mPrev, - fast2 = sentinel.mPrev->mPrev->mPrev; - slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; - slow = slow->mPrev, fast1 = fast2->mPrev, fast2 = fast1->mPrev) { - MOZ_ASSERT(slow != fast1); - MOZ_ASSERT(slow != fast2); - } - - /* - * Check that |sentinel| is the only node in the list with - * mIsSentinel == true. - */ - for (const LinkedListElement* elem = sentinel.mNext; - elem != &sentinel; - elem = elem->mNext) { - MOZ_ASSERT(!elem->mIsSentinel); - } - - /* Check that the mNext/mPrev pointers match up. */ - const LinkedListElement* prev = &sentinel; - const LinkedListElement* cur = sentinel.mNext; - do { - MOZ_ASSERT(cur->mPrev == prev); - MOZ_ASSERT(prev->mNext == cur); - - prev = cur; - cur = cur->mNext; - } while (cur != &sentinel); -#endif /* ifdef DEBUG */ - } - -private: - friend class LinkedListElement; - - void assertContains(const RawType aValue) const - { -#ifdef DEBUG - for (ConstRawType elem = getFirst(); elem; elem = elem->getNext()) { - if (elem == aValue) { - return; - } - } - MOZ_CRASH("element wasn't found in this list!"); -#endif - } - - LinkedList& operator=(const LinkedList& aOther) = delete; - LinkedList(const LinkedList& aOther) = delete; -}; - -template -class AutoCleanLinkedList : public LinkedList -{ -public: - ~AutoCleanLinkedList() - { - while (T* element = this->popFirst()) { - delete element; - } - } -}; - -} /* namespace mozilla */ - -#endif /* __cplusplus */ - -#endif /* mozilla_LinkedList_h */ diff --git a/win32/include/spidermonkey/mozilla/MacroArgs.h b/win32/include/spidermonkey/mozilla/MacroArgs.h deleted file mode 100755 index 52ed1e82..00000000 --- a/win32/include/spidermonkey/mozilla/MacroArgs.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements various macros meant to ease the use of variadic macros. - */ - -#ifndef mozilla_MacroArgs_h -#define mozilla_MacroArgs_h - -// Concatenates pre-processor tokens in a way that can be used with __LINE__. -#define MOZ_CONCAT2(x, y) x ## y -#define MOZ_CONCAT(x, y) MOZ_CONCAT2(x, y) - -/* - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(aPrefix, ...) counts the number of variadic - * arguments and prefixes it with |aPrefix|. For example: - * - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(, foo, 42) expands to 2 - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(A, foo, 42, bar) expands to A3 - * - * You must pass in between 1 and 50 (inclusive) variadic arguments, past - * |aPrefix|. It is not legal to do - * - * MOZ_PASTE_PREFIX_AND_ARG_COUNT(prefix) - * - * (that is, pass in 0 variadic arguments). To ensure that a compile-time - * error occurs when these constraints are violated, use the - * MOZ_STATIC_ASSERT_VALID_ARG_COUNT macro with the same variaidc arguments - * wherever this macro is used. - * - * Passing (__VA_ARGS__, ) rather than simply calling - * MOZ_MACROARGS_ARG_COUNT_HELPER2(__VA_ARGS__, ) very - * carefully tiptoes around a MSVC bug where it improperly expands __VA_ARGS__ - * as a single token in argument lists. For details, see: - * - * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement - * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644 - */ -#define MOZ_PASTE_PREFIX_AND_ARG_COUNT(aPrefix, ...) \ - MOZ_MACROARGS_ARG_COUNT_HELPER((__VA_ARGS__, \ - aPrefix##50, aPrefix##49, aPrefix##48, aPrefix##47, aPrefix##46, \ - aPrefix##45, aPrefix##44, aPrefix##43, aPrefix##42, aPrefix##41, \ - aPrefix##40, aPrefix##39, aPrefix##38, aPrefix##37, aPrefix##36, \ - aPrefix##35, aPrefix##34, aPrefix##33, aPrefix##32, aPrefix##31, \ - aPrefix##30, aPrefix##29, aPrefix##28, aPrefix##27, aPrefix##26, \ - aPrefix##25, aPrefix##24, aPrefix##23, aPrefix##22, aPrefix##21, \ - aPrefix##20, aPrefix##19, aPrefix##18, aPrefix##17, aPrefix##16, \ - aPrefix##15, aPrefix##14, aPrefix##13, aPrefix##12, aPrefix##11, \ - aPrefix##10, aPrefix##9, aPrefix##8, aPrefix##7, aPrefix##6, \ - aPrefix##5, aPrefix##4, aPrefix##3, aPrefix##2, aPrefix##1, aPrefix##0)) - -#define MOZ_MACROARGS_ARG_COUNT_HELPER(aArgs) \ - MOZ_MACROARGS_ARG_COUNT_HELPER2 aArgs - -#define MOZ_MACROARGS_ARG_COUNT_HELPER2( \ - a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, \ - a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, \ - a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, \ - a31, a32, a33, a34, a35, a36, a37, a38, a39, a40, \ - a41, a42, a43, a44, a45, a46, a47, a48, a49, a50, \ - a51, ...) a51 - -/* - * MOZ_STATIC_ASSERT_VALID_ARG_COUNT ensures that a compile-time error occurs - * when the argument count constraints of MOZ_PASTE_PREFIX_AND_ARG_COUNT are - * violated. Use this macro wherever MOZ_PASTE_PREFIX_AND_ARG_COUNT is used - * and pass it the same variadic arguments. - * - * This macro employs a few dirty tricks to function. To detect the zero - * argument case, |(__VA_ARGS__)| is stringified, sizeof-ed, and compared to - * what it should be in the absence of arguments. - * - * Detecting too many arguments is a little trickier. With a valid argument - * count and a prefix of 1, MOZ_PASTE_PREFIX_AND_ARG_COUNT expands to e.g. 14. - * With a prefix of 0.0, it expands to e.g. 0.04. If there are too many - * arguments, it expands to the first argument over the limit. If this - * exceeding argument is a number, the assertion will fail as there is no - * number than can simultaneously be both > 10 and == 0. If the exceeding - * argument is not a number, a compile-time error should still occur due to - * the operations performed on it. - */ -#define MOZ_MACROARGS_STRINGIFY_HELPER(x) #x -#define MOZ_STATIC_ASSERT_VALID_ARG_COUNT(...) \ - static_assert( \ - sizeof(MOZ_MACROARGS_STRINGIFY_HELPER((__VA_ARGS__))) != sizeof("()") && \ - (MOZ_PASTE_PREFIX_AND_ARG_COUNT(1, __VA_ARGS__)) > 10 && \ - (int)(MOZ_PASTE_PREFIX_AND_ARG_COUNT(0.0, __VA_ARGS__)) == 0, \ - "MOZ_STATIC_ASSERT_VALID_ARG_COUNT requires 1 to 50 arguments") /* ; */ - -/* - * MOZ_ARGS_AFTER_N expands to its arguments excluding the first |N| - * arguments. For example: - * - * MOZ_ARGS_AFTER_2(a, b, c, d) expands to: c, d - */ -#define MOZ_ARGS_AFTER_1(a1, ...) __VA_ARGS__ -#define MOZ_ARGS_AFTER_2(a1, a2, ...) __VA_ARGS__ - -/* - * MOZ_ARG_N expands to its |N|th argument. - */ -#define MOZ_ARG_1(a1, ...) a1 -#define MOZ_ARG_2(a1, a2, ...) a2 - -#endif /* mozilla_MacroArgs_h */ diff --git a/win32/include/spidermonkey/mozilla/MacroForEach.h b/win32/include/spidermonkey/mozilla/MacroForEach.h deleted file mode 100755 index 7c0e3cfb..00000000 --- a/win32/include/spidermonkey/mozilla/MacroForEach.h +++ /dev/null @@ -1,158 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements a higher-order macro for iteratively calling another macro with - * fixed leading arguments, plus a trailing element picked from a second list - * of arguments. - */ - -#ifndef mozilla_MacroForEach_h -#define mozilla_MacroForEach_h - -#include "mozilla/MacroArgs.h" - -/* - * MOZ_FOR_EACH(aMacro, aFixedArgs, aArgs) expands to N calls to the macro - * |aMacro| where N is equal the number of items in the list |aArgs|. The - * arguments for each |aMacro| call are composed of *all* arguments in the list - * |aFixedArgs| as well as a single argument in the list |aArgs|. For example: - * - * #define MACRO_A(x) x + - * int a = MOZ_FOR_EACH(MACRO_A, (), (1, 2, 3)) 0; - * // Expands to: MACRO_A(1) MACRO_A(2) MACRO_A(3) 0; - * // And further to: 1 + 2 + 3 + 0; - * - * #define MACRO_B(k, x) (k + x) + - * int b = MOZ_FOR_EACH(MACRO_B, (5,), (1, 2)) 0; - * // Expands to: MACRO_B(5, 1) MACRO_B(5, 2) 0; - * - * #define MACRO_C(k1, k2, x) (k1 + k2 + x) + - * int c = MOZ_FOR_EACH(MACRO_C, (5, 8,), (1, 2)) 0; - * // Expands to: MACRO_B(5, 8, 1) MACRO_B(5, 8, 2) 0; - * - * If the |aFixedArgs| list is not empty, a trailing comma must be included. - * - * The |aArgs| list must be not be empty and may be up to 50 items long. Use - * MOZ_STATIC_ASSERT_VALID_ARG_COUNT to ensure that violating this constraint - * results in a compile-time error. - */ -#define MOZ_FOR_EACH_EXPAND_HELPER(...) __VA_ARGS__ -#define MOZ_FOR_EACH_GLUE(a, b) a b -#define MOZ_FOR_EACH(aMacro, aFixedArgs, aArgs) \ - MOZ_FOR_EACH_GLUE( \ - MOZ_PASTE_PREFIX_AND_ARG_COUNT(MOZ_FOR_EACH_, \ - MOZ_FOR_EACH_EXPAND_HELPER aArgs), \ - (aMacro, aFixedArgs, aArgs)) - -#define MOZ_FOR_EACH_HELPER_GLUE(a, b) a b -#define MOZ_FOR_EACH_HELPER(aMacro, aFixedArgs, aArgs) \ - MOZ_FOR_EACH_HELPER_GLUE( \ - aMacro, \ - (MOZ_FOR_EACH_EXPAND_HELPER aFixedArgs MOZ_ARG_1 aArgs)) - -#define MOZ_FOR_EACH_1(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) -#define MOZ_FOR_EACH_2(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_1(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_3(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_2(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_4(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_3(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_5(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_4(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_6(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_5(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_7(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_6(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_8(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_7(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_9(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_8(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_10(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_9(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_11(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_10(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_12(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_11(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_13(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_12(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_14(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_13(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_15(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_14(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_16(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_15(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_17(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_16(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_18(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_17(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_19(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_18(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_20(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_19(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_21(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_20(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_22(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_21(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_23(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_22(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_24(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_23(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_25(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_24(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_26(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_25(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_27(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_26(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_28(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_27(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_29(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_28(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_30(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_29(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_31(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_30(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_32(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_31(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_33(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_32(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_34(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_33(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_35(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_34(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_36(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_35(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_37(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_36(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_38(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_37(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_39(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_38(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_40(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_39(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_41(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_40(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_42(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_41(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_43(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_42(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_44(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_43(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_45(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_44(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_46(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_45(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_47(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_46(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_48(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_47(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_49(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_48(m, fa, (MOZ_ARGS_AFTER_1 a)) -#define MOZ_FOR_EACH_50(m, fa, a) \ - MOZ_FOR_EACH_HELPER(m, fa, a) MOZ_FOR_EACH_49(m, fa, (MOZ_ARGS_AFTER_1 a)) - -#endif /* mozilla_MacroForEach_h */ diff --git a/win32/include/spidermonkey/mozilla/MathAlgorithms.h b/win32/include/spidermonkey/mozilla/MathAlgorithms.h deleted file mode 100755 index 4db6de49..00000000 --- a/win32/include/spidermonkey/mozilla/MathAlgorithms.h +++ /dev/null @@ -1,547 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* mfbt maths algorithms. */ - -#ifndef mozilla_MathAlgorithms_h -#define mozilla_MathAlgorithms_h - -#include "mozilla/Assertions.h" -#include "mozilla/TypeTraits.h" - -#include -#include -#include - -namespace mozilla { - -// Greatest Common Divisor -template -MOZ_ALWAYS_INLINE IntegerType -EuclidGCD(IntegerType aA, IntegerType aB) -{ - // Euclid's algorithm; O(N) in the worst case. (There are better - // ways, but we don't need them for the current use of this algo.) - MOZ_ASSERT(aA > IntegerType(0)); - MOZ_ASSERT(aB > IntegerType(0)); - - while (aA != aB) { - if (aA > aB) { - aA = aA - aB; - } else { - aB = aB - aA; - } - } - - return aA; -} - -// Least Common Multiple -template -MOZ_ALWAYS_INLINE IntegerType -EuclidLCM(IntegerType aA, IntegerType aB) -{ - // Divide first to reduce overflow risk. - return (aA / EuclidGCD(aA, aB)) * aB; -} - -namespace detail { - -template -struct AllowDeprecatedAbsFixed : FalseType {}; - -template<> struct AllowDeprecatedAbsFixed : TrueType {}; -template<> struct AllowDeprecatedAbsFixed : TrueType {}; - -template -struct AllowDeprecatedAbs : AllowDeprecatedAbsFixed {}; - -template<> struct AllowDeprecatedAbs : TrueType {}; -template<> struct AllowDeprecatedAbs : TrueType {}; - -} // namespace detail - -// DO NOT USE DeprecatedAbs. It exists only until its callers can be converted -// to Abs below, and it will be removed when all callers have been changed. -template -inline typename mozilla::EnableIf::value, T>::Type -DeprecatedAbs(const T aValue) -{ - // The absolute value of the smallest possible value of a signed-integer type - // won't fit in that type (on twos-complement systems -- and we're blithely - // assuming we're on such systems, for the non- types listed above), - // so assert that the input isn't that value. - // - // This is the case if: the value is non-negative; or if adding one (giving a - // value in the range [-maxvalue, 0]), then negating (giving a value in the - // range [0, maxvalue]), doesn't produce maxvalue (because in twos-complement, - // (minvalue + 1) == -maxvalue). - MOZ_ASSERT(aValue >= 0 || - -(aValue + 1) != T((1ULL << (CHAR_BIT * sizeof(T) - 1)) - 1), - "You can't negate the smallest possible negative integer!"); - return aValue >= 0 ? aValue : -aValue; -} - -namespace detail { - -// For now mozilla::Abs only takes intN_T, the signed natural types, and -// float/double/long double. Feel free to add overloads for other standard, -// signed types if you need them. - -template -struct AbsReturnTypeFixed; - -template<> struct AbsReturnTypeFixed { typedef uint8_t Type; }; -template<> struct AbsReturnTypeFixed { typedef uint16_t Type; }; -template<> struct AbsReturnTypeFixed { typedef uint32_t Type; }; -template<> struct AbsReturnTypeFixed { typedef uint64_t Type; }; - -template -struct AbsReturnType : AbsReturnTypeFixed {}; - -template<> struct AbsReturnType : - EnableIf {}; -template<> struct AbsReturnType { typedef unsigned char Type; }; -template<> struct AbsReturnType { typedef unsigned short Type; }; -template<> struct AbsReturnType { typedef unsigned int Type; }; -template<> struct AbsReturnType { typedef unsigned long Type; }; -template<> struct AbsReturnType { typedef unsigned long long Type; }; -template<> struct AbsReturnType { typedef float Type; }; -template<> struct AbsReturnType { typedef double Type; }; -template<> struct AbsReturnType { typedef long double Type; }; - -} // namespace detail - -template -inline typename detail::AbsReturnType::Type -Abs(const T aValue) -{ - typedef typename detail::AbsReturnType::Type ReturnType; - return aValue >= 0 ? ReturnType(aValue) : ~ReturnType(aValue) + 1; -} - -template<> -inline float -Abs(const float aFloat) -{ - return std::fabs(aFloat); -} - -template<> -inline double -Abs(const double aDouble) -{ - return std::fabs(aDouble); -} - -template<> -inline long double -Abs(const long double aLongDouble) -{ - return std::fabs(aLongDouble); -} - -} // namespace mozilla - -#if defined(_MSC_VER) && \ - (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) -# define MOZ_BITSCAN_WINDOWS - -# include -# pragma intrinsic(_BitScanForward, _BitScanReverse) - -# if defined(_M_AMD64) || defined(_M_X64) -# define MOZ_BITSCAN_WINDOWS64 -# pragma intrinsic(_BitScanForward64, _BitScanReverse64) -# endif - -#endif - -namespace mozilla { - -namespace detail { - -#if defined(MOZ_BITSCAN_WINDOWS) - -inline uint_fast8_t -CountLeadingZeroes32(uint32_t aValue) -{ - unsigned long index; - if (!_BitScanReverse(&index, static_cast(aValue))) - return 32; - return uint_fast8_t(31 - index); -} - - -inline uint_fast8_t -CountTrailingZeroes32(uint32_t aValue) -{ - unsigned long index; - if (!_BitScanForward(&index, static_cast(aValue))) - return 32; - return uint_fast8_t(index); -} - -inline uint_fast8_t -CountPopulation32(uint32_t aValue) -{ - uint32_t x = aValue - ((aValue >> 1) & 0x55555555); - x = (x & 0x33333333) + ((x >> 2) & 0x33333333); - return (((x + (x >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24; -} -inline uint_fast8_t -CountPopulation64(uint64_t aValue) -{ - return uint_fast8_t(CountPopulation32(aValue & 0xffffffff) + - CountPopulation32(aValue >> 32)); -} - -inline uint_fast8_t -CountLeadingZeroes64(uint64_t aValue) -{ -#if defined(MOZ_BITSCAN_WINDOWS64) - unsigned long index; - if (!_BitScanReverse64(&index, static_cast(aValue))) - return 64; - return uint_fast8_t(63 - index); -#else - uint32_t hi = uint32_t(aValue >> 32); - if (hi != 0) { - return CountLeadingZeroes32(hi); - } - return 32u + CountLeadingZeroes32(uint32_t(aValue)); -#endif -} - -inline uint_fast8_t -CountTrailingZeroes64(uint64_t aValue) -{ -#if defined(MOZ_BITSCAN_WINDOWS64) - unsigned long index; - if (!_BitScanForward64(&index, static_cast(aValue))) - return 64; - return uint_fast8_t(index); -#else - uint32_t lo = uint32_t(aValue); - if (lo != 0) { - return CountTrailingZeroes32(lo); - } - return 32u + CountTrailingZeroes32(uint32_t(aValue >> 32)); -#endif -} - -# ifdef MOZ_HAVE_BITSCAN64 -# undef MOZ_HAVE_BITSCAN64 -# endif - -#elif defined(__clang__) || defined(__GNUC__) - -# if defined(__clang__) -# if !__has_builtin(__builtin_ctz) || !__has_builtin(__builtin_clz) -# error "A clang providing __builtin_c[lt]z is required to build" -# endif -# else - // gcc has had __builtin_clz and friends since 3.4: no need to check. -# endif - -inline uint_fast8_t -CountLeadingZeroes32(uint32_t aValue) -{ - return __builtin_clz(aValue); -} - -inline uint_fast8_t -CountTrailingZeroes32(uint32_t aValue) -{ - return __builtin_ctz(aValue); -} - -inline uint_fast8_t -CountPopulation32(uint32_t aValue) -{ - return __builtin_popcount(aValue); -} - -inline uint_fast8_t -CountPopulation64(uint64_t aValue) -{ - return __builtin_popcountll(aValue); -} - -inline uint_fast8_t -CountLeadingZeroes64(uint64_t aValue) -{ - return __builtin_clzll(aValue); -} - -inline uint_fast8_t -CountTrailingZeroes64(uint64_t aValue) -{ - return __builtin_ctzll(aValue); -} - -#else -# error "Implement these!" -inline uint_fast8_t CountLeadingZeroes32(uint32_t aValue) = delete; -inline uint_fast8_t CountTrailingZeroes32(uint32_t aValue) = delete; -inline uint_fast8_t CountPopulation32(uint32_t aValue) = delete; -inline uint_fast8_t CountPopulation64(uint64_t aValue) = delete; -inline uint_fast8_t CountLeadingZeroes64(uint64_t aValue) = delete; -inline uint_fast8_t CountTrailingZeroes64(uint64_t aValue) = delete; -#endif - -} // namespace detail - -/** - * Compute the number of high-order zero bits in the NON-ZERO number |aValue|. - * That is, looking at the bitwise representation of the number, with the - * highest- valued bits at the start, return the number of zeroes before the - * first one is observed. - * - * CountLeadingZeroes32(0xF0FF1000) is 0; - * CountLeadingZeroes32(0x7F8F0001) is 1; - * CountLeadingZeroes32(0x3FFF0100) is 2; - * CountLeadingZeroes32(0x1FF50010) is 3; and so on. - */ -inline uint_fast8_t -CountLeadingZeroes32(uint32_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountLeadingZeroes32(aValue); -} - -/** - * Compute the number of low-order zero bits in the NON-ZERO number |aValue|. - * That is, looking at the bitwise representation of the number, with the - * lowest- valued bits at the start, return the number of zeroes before the - * first one is observed. - * - * CountTrailingZeroes32(0x0100FFFF) is 0; - * CountTrailingZeroes32(0x7000FFFE) is 1; - * CountTrailingZeroes32(0x0080FFFC) is 2; - * CountTrailingZeroes32(0x0080FFF8) is 3; and so on. - */ -inline uint_fast8_t -CountTrailingZeroes32(uint32_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountTrailingZeroes32(aValue); -} - -/** - * Compute the number of one bits in the number |aValue|, - */ -inline uint_fast8_t -CountPopulation32(uint32_t aValue) -{ - return detail::CountPopulation32(aValue); -} - -/** Analogous to CountPopulation32, but for 64-bit numbers */ -inline uint_fast8_t -CountPopulation64(uint64_t aValue) -{ - return detail::CountPopulation64(aValue); -} - -/** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ -inline uint_fast8_t -CountLeadingZeroes64(uint64_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountLeadingZeroes64(aValue); -} - -/** Analogous to CountTrailingZeroes32, but for 64-bit numbers. */ -inline uint_fast8_t -CountTrailingZeroes64(uint64_t aValue) -{ - MOZ_ASSERT(aValue != 0); - return detail::CountTrailingZeroes64(aValue); -} - -namespace detail { - -template -class CeilingLog2; - -template -class CeilingLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - // Check for <= 1 to avoid the == 0 undefined case. - return aValue <= 1 ? 0u : 32u - CountLeadingZeroes32(aValue - 1); - } -}; - -template -class CeilingLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - // Check for <= 1 to avoid the == 0 undefined case. - return aValue <= 1 ? 0u : 64u - CountLeadingZeroes64(aValue - 1); - } -}; - -} // namespace detail - -/** - * Compute the log of the least power of 2 greater than or equal to |aValue|. - * - * CeilingLog2(0..1) is 0; - * CeilingLog2(2) is 1; - * CeilingLog2(3..4) is 2; - * CeilingLog2(5..8) is 3; - * CeilingLog2(9..16) is 4; and so on. - */ -template -inline uint_fast8_t -CeilingLog2(const T aValue) -{ - return detail::CeilingLog2::compute(aValue); -} - -/** A CeilingLog2 variant that accepts only size_t. */ -inline uint_fast8_t -CeilingLog2Size(size_t aValue) -{ - return CeilingLog2(aValue); -} - -namespace detail { - -template -class FloorLog2; - -template -class FloorLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - return 31u - CountLeadingZeroes32(aValue | 1); - } -}; - -template -class FloorLog2 -{ -public: - static uint_fast8_t compute(const T aValue) - { - return 63u - CountLeadingZeroes64(aValue | 1); - } -}; - -} // namespace detail - -/** - * Compute the log of the greatest power of 2 less than or equal to |aValue|. - * - * FloorLog2(0..1) is 0; - * FloorLog2(2..3) is 1; - * FloorLog2(4..7) is 2; - * FloorLog2(8..15) is 3; and so on. - */ -template -inline uint_fast8_t -FloorLog2(const T aValue) -{ - return detail::FloorLog2::compute(aValue); -} - -/** A FloorLog2 variant that accepts only size_t. */ -inline uint_fast8_t -FloorLog2Size(size_t aValue) -{ - return FloorLog2(aValue); -} - -/* - * Compute the smallest power of 2 greater than or equal to |x|. |x| must not - * be so great that the computed value would overflow |size_t|. - */ -inline size_t -RoundUpPow2(size_t aValue) -{ - MOZ_ASSERT(aValue <= (size_t(1) << (sizeof(size_t) * CHAR_BIT - 1)), - "can't round up -- will overflow!"); - return size_t(1) << CeilingLog2(aValue); -} - -/** - * Rotates the bits of the given value left by the amount of the shift width. - */ -template -inline T -RotateLeft(const T aValue, uint_fast8_t aShift) -{ - MOZ_ASSERT(aShift < sizeof(T) * CHAR_BIT, "Shift value is too large!"); - MOZ_ASSERT(aShift > 0, - "Rotation by value length is undefined behavior, but compilers " - "do not currently fold a test into the rotate instruction. " - "Please remove this restriction when compilers optimize the " - "zero case (http://blog.regehr.org/archives/1063)."); - static_assert(IsUnsigned::value, "Rotates require unsigned values"); - return (aValue << aShift) | (aValue >> (sizeof(T) * CHAR_BIT - aShift)); -} - -/** - * Rotates the bits of the given value right by the amount of the shift width. - */ -template -inline T -RotateRight(const T aValue, uint_fast8_t aShift) -{ - MOZ_ASSERT(aShift < sizeof(T) * CHAR_BIT, "Shift value is too large!"); - MOZ_ASSERT(aShift > 0, - "Rotation by value length is undefined behavior, but compilers " - "do not currently fold a test into the rotate instruction. " - "Please remove this restriction when compilers optimize the " - "zero case (http://blog.regehr.org/archives/1063)."); - static_assert(IsUnsigned::value, "Rotates require unsigned values"); - return (aValue >> aShift) | (aValue << (sizeof(T) * CHAR_BIT - aShift)); -} - -/** - * Returns true if |x| is a power of two. - * Zero is not an integer power of two. (-Inf is not an integer) - */ -template -constexpr bool -IsPowerOfTwo(T x) -{ - static_assert(IsUnsigned::value, - "IsPowerOfTwo requires unsigned values"); - return x && (x & (x - 1)) == 0; -} - -template -inline T -Clamp(const T aValue, const T aMin, const T aMax) -{ - static_assert(IsIntegral::value, - "Clamp accepts only integral types, so that it doesn't have" - " to distinguish differently-signed zeroes (which users may" - " or may not care to distinguish, likely at a perf cost) or" - " to decide how to clamp NaN or a range with a NaN" - " endpoint."); - MOZ_ASSERT(aMin <= aMax); - - if (aValue <= aMin) - return aMin; - if (aValue >= aMax) - return aMax; - return aValue; -} - -} /* namespace mozilla */ - -#endif /* mozilla_MathAlgorithms_h */ diff --git a/win32/include/spidermonkey/mozilla/Maybe.h b/win32/include/spidermonkey/mozilla/Maybe.h deleted file mode 100755 index 2a601ac4..00000000 --- a/win32/include/spidermonkey/mozilla/Maybe.h +++ /dev/null @@ -1,551 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A class for optional values and in-place lazy construction. */ - -#ifndef mozilla_Maybe_h -#define mozilla_Maybe_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include // for placement new -#include - -namespace mozilla { - -struct Nothing { }; - -/* - * Maybe is a container class which contains either zero or one elements. It - * serves two roles. It can represent values which are *semantically* optional, - * augmenting a type with an explicit 'Nothing' value. In this role, it provides - * methods that make it easy to work with values that may be missing, along with - * equality and comparison operators so that Maybe values can be stored in - * containers. Maybe values can be constructed conveniently in expressions using - * type inference, as follows: - * - * void doSomething(Maybe aFoo) { - * if (aFoo) // Make sure that aFoo contains a value... - * aFoo->takeAction(); // and then use |aFoo->| to access it. - * } // |*aFoo| also works! - * - * doSomething(Nothing()); // Passes a Maybe containing no value. - * doSomething(Some(Foo(100))); // Passes a Maybe containing |Foo(100)|. - * - * You'll note that it's important to check whether a Maybe contains a value - * before using it, using conversion to bool, |isSome()|, or |isNothing()|. You - * can avoid these checks, and sometimes write more readable code, using - * |valueOr()|, |ptrOr()|, and |refOr()|, which allow you to retrieve the value - * in the Maybe and provide a default for the 'Nothing' case. You can also use - * |apply()| to call a function only if the Maybe holds a value, and |map()| to - * transform the value in the Maybe, returning another Maybe with a possibly - * different type. - * - * Maybe's other role is to support lazily constructing objects without using - * dynamic storage. A Maybe directly contains storage for a value, but it's - * empty by default. |emplace()|, as mentioned above, can be used to construct a - * value in Maybe's storage. The value a Maybe contains can be destroyed by - * calling |reset()|; this will happen automatically if a Maybe is destroyed - * while holding a value. - * - * It's a common idiom in C++ to use a pointer as a 'Maybe' type, with a null - * value meaning 'Nothing' and any other value meaning 'Some'. You can convert - * from such a pointer to a Maybe value using 'ToMaybe()'. - * - * Maybe is inspired by similar types in the standard library of many other - * languages (e.g. Haskell's Maybe and Rust's Option). In the C++ world it's - * very similar to std::optional, which was proposed for C++14 and originated in - * Boost. The most important differences between Maybe and std::optional are: - * - * - std::optional may be compared with T. We deliberately forbid that. - * - std::optional allows in-place construction without a separate call to - * |emplace()| by using a dummy |in_place_t| value to tag the appropriate - * constructor. - * - std::optional has |valueOr()|, equivalent to Maybe's |valueOr()|, but - * lacks corresponding methods for |refOr()| and |ptrOr()|. - * - std::optional lacks |map()| and |apply()|, making it less suitable for - * functional-style code. - * - std::optional lacks many convenience functions that Maybe has. Most - * unfortunately, it lacks equivalents of the type-inferred constructor - * functions |Some()| and |Nothing()|. - * - * N.B. GCC has missed optimizations with Maybe in the past and may generate - * extra branches/loads/stores. Use with caution on hot paths; it's not known - * whether or not this is still a problem. - */ -template -class Maybe -{ - bool mIsSome; - AlignedStorage2 mStorage; - -public: - typedef T ValueType; - - Maybe() : mIsSome(false) { } - ~Maybe() { reset(); } - - MOZ_IMPLICIT Maybe(Nothing) : mIsSome(false) { } - - Maybe(const Maybe& aOther) - : mIsSome(false) - { - if (aOther.mIsSome) { - emplace(*aOther); - } - } - - /** - * Maybe can be copy-constructed from a Maybe if U* and T* are - * compatible, or from Maybe. - */ - template::value && - (std::is_same::value || - (std::is_pointer::value && - std::is_base_of::type, - typename std::remove_pointer::type>::value))>::type> - MOZ_IMPLICIT - Maybe(const Maybe& aOther) - : mIsSome(false) - { - if (aOther.isSome()) { - emplace(*aOther); - } - } - - Maybe(Maybe&& aOther) - : mIsSome(false) - { - if (aOther.mIsSome) { - emplace(Move(*aOther)); - aOther.reset(); - } - } - - /** - * Maybe can be move-constructed from a Maybe if U* and T* are - * compatible, or from Maybe. - */ - template::value && - (std::is_same::value || - (std::is_pointer::value && - std::is_base_of::type, - typename std::remove_pointer::type>::value))>::type> - MOZ_IMPLICIT - Maybe(Maybe&& aOther) - : mIsSome(false) - { - if (aOther.isSome()) { - emplace(Move(*aOther)); - aOther.reset(); - } - } - - Maybe& operator=(const Maybe& aOther) - { - if (&aOther != this) { - if (aOther.mIsSome) { - if (mIsSome) { - // XXX(seth): The correct code for this branch, below, can't be used - // due to a bug in Visual Studio 2010. See bug 1052940. - /* - ref() = aOther.ref(); - */ - reset(); - emplace(*aOther); - } else { - emplace(*aOther); - } - } else { - reset(); - } - } - return *this; - } - - Maybe& operator=(Maybe&& aOther) - { - MOZ_ASSERT(this != &aOther, "Self-moves are prohibited"); - - if (aOther.mIsSome) { - if (mIsSome) { - ref() = Move(aOther.ref()); - } else { - emplace(Move(*aOther)); - } - aOther.reset(); - } else { - reset(); - } - - return *this; - } - - /* Methods that check whether this Maybe contains a value */ - explicit operator bool() const { return isSome(); } - bool isSome() const { return mIsSome; } - bool isNothing() const { return !mIsSome; } - - /* Returns the contents of this Maybe by value. Unsafe unless |isSome()|. */ - T value() const - { - MOZ_ASSERT(mIsSome); - return ref(); - } - - /* - * Returns the contents of this Maybe by value. If |isNothing()|, returns - * the default value provided. - */ - template - T valueOr(V&& aDefault) const - { - if (isSome()) { - return ref(); - } - return Forward(aDefault); - } - - /* - * Returns the contents of this Maybe by value. If |isNothing()|, returns - * the value returned from the function or functor provided. - */ - template - T valueOrFrom(F&& aFunc) const - { - if (isSome()) { - return ref(); - } - return aFunc(); - } - - /* Returns the contents of this Maybe by pointer. Unsafe unless |isSome()|. */ - T* ptr() - { - MOZ_ASSERT(mIsSome); - return &ref(); - } - - const T* ptr() const - { - MOZ_ASSERT(mIsSome); - return &ref(); - } - - /* - * Returns the contents of this Maybe by pointer. If |isNothing()|, - * returns the default value provided. - */ - T* ptrOr(T* aDefault) - { - if (isSome()) { - return ptr(); - } - return aDefault; - } - - const T* ptrOr(const T* aDefault) const - { - if (isSome()) { - return ptr(); - } - return aDefault; - } - - /* - * Returns the contents of this Maybe by pointer. If |isNothing()|, - * returns the value returned from the function or functor provided. - */ - template - T* ptrOrFrom(F&& aFunc) - { - if (isSome()) { - return ptr(); - } - return aFunc(); - } - - template - const T* ptrOrFrom(F&& aFunc) const - { - if (isSome()) { - return ptr(); - } - return aFunc(); - } - - T* operator->() - { - MOZ_ASSERT(mIsSome); - return ptr(); - } - - const T* operator->() const - { - MOZ_ASSERT(mIsSome); - return ptr(); - } - - /* Returns the contents of this Maybe by ref. Unsafe unless |isSome()|. */ - T& ref() - { - MOZ_ASSERT(mIsSome); - return *mStorage.addr(); - } - - const T& ref() const - { - MOZ_ASSERT(mIsSome); - return *mStorage.addr(); - } - - /* - * Returns the contents of this Maybe by ref. If |isNothing()|, returns - * the default value provided. - */ - T& refOr(T& aDefault) - { - if (isSome()) { - return ref(); - } - return aDefault; - } - - const T& refOr(const T& aDefault) const - { - if (isSome()) { - return ref(); - } - return aDefault; - } - - /* - * Returns the contents of this Maybe by ref. If |isNothing()|, returns the - * value returned from the function or functor provided. - */ - template - T& refOrFrom(F&& aFunc) - { - if (isSome()) { - return ref(); - } - return aFunc(); - } - - template - const T& refOrFrom(F&& aFunc) const - { - if (isSome()) { - return ref(); - } - return aFunc(); - } - - T& operator*() - { - MOZ_ASSERT(mIsSome); - return ref(); - } - - const T& operator*() const - { - MOZ_ASSERT(mIsSome); - return ref(); - } - - /* If |isSome()|, runs the provided function or functor on the contents of - * this Maybe. */ - template - Maybe& apply(Func aFunc) - { - if (isSome()) { - aFunc(ref()); - } - return *this; - } - - template - const Maybe& apply(Func aFunc) const - { - if (isSome()) { - aFunc(ref()); - } - return *this; - } - - /* - * If |isSome()|, runs the provided function and returns the result wrapped - * in a Maybe. If |isNothing()|, returns an empty Maybe value. - */ - template - auto map(Func aFunc) -> Maybe>().ref()))> - { - using ReturnType = decltype(aFunc(ref())); - if (isSome()) { - Maybe val; - val.emplace(aFunc(ref())); - return val; - } - return Maybe(); - } - - template - auto map(Func aFunc) const -> Maybe>().ref()))> - { - using ReturnType = decltype(aFunc(ref())); - if (isSome()) { - Maybe val; - val.emplace(aFunc(ref())); - return val; - } - return Maybe(); - } - - /* If |isSome()|, empties this Maybe and destroys its contents. */ - void reset() - { - if (isSome()) { - ref().T::~T(); - mIsSome = false; - } - } - - /* - * Constructs a T value in-place in this empty Maybe's storage. The - * arguments to |emplace()| are the parameters to T's constructor. - */ - template - void emplace(Args&&... aArgs) - { - MOZ_ASSERT(!mIsSome); - ::new (mStorage.addr()) T(Forward(aArgs)...); - mIsSome = true; - } -}; - -/* - * Some() creates a Maybe value containing the provided T value. If T has a - * move constructor, it's used to make this as efficient as possible. - * - * Some() selects the type of Maybe it returns by removing any const, volatile, - * or reference qualifiers from the type of the value you pass to it. This gives - * it more intuitive behavior when used in expressions, but it also means that - * if you need to construct a Maybe value that holds a const, volatile, or - * reference value, you need to use emplace() instead. - */ -template -Maybe::Type>::Type> -Some(T&& aValue) -{ - typedef typename RemoveCV::Type>::Type U; - Maybe value; - value.emplace(Forward(aValue)); - return value; -} - -template -Maybe::Type>::Type> -ToMaybe(T* aPtr) -{ - if (aPtr) { - return Some(*aPtr); - } - return Nothing(); -} - -/* - * Two Maybe values are equal if - * - both are Nothing, or - * - both are Some, and the values they contain are equal. - */ -template bool -operator==(const Maybe& aLHS, const Maybe& aRHS) -{ - if (aLHS.isNothing() != aRHS.isNothing()) { - return false; - } - return aLHS.isNothing() || *aLHS == *aRHS; -} - -template bool -operator!=(const Maybe& aLHS, const Maybe& aRHS) -{ - return !(aLHS == aRHS); -} - -/* - * We support comparison to Nothing to allow reasonable expressions like: - * if (maybeValue == Nothing()) { ... } - */ -template bool -operator==(const Maybe& aLHS, const Nothing& aRHS) -{ - return aLHS.isNothing(); -} - -template bool -operator!=(const Maybe& aLHS, const Nothing& aRHS) -{ - return !(aLHS == aRHS); -} - -template bool -operator==(const Nothing& aLHS, const Maybe& aRHS) -{ - return aRHS.isNothing(); -} - -template bool -operator!=(const Nothing& aLHS, const Maybe& aRHS) -{ - return !(aLHS == aRHS); -} - -/* - * Maybe values are ordered in the same way T values are ordered, except that - * Nothing comes before anything else. - */ -template bool -operator<(const Maybe& aLHS, const Maybe& aRHS) -{ - if (aLHS.isNothing()) { - return aRHS.isSome(); - } - if (aRHS.isNothing()) { - return false; - } - return *aLHS < *aRHS; -} - -template bool -operator>(const Maybe& aLHS, const Maybe& aRHS) -{ - return !(aLHS < aRHS || aLHS == aRHS); -} - -template bool -operator<=(const Maybe& aLHS, const Maybe& aRHS) -{ - return aLHS < aRHS || aLHS == aRHS; -} - -template bool -operator>=(const Maybe& aLHS, const Maybe& aRHS) -{ - return !(aLHS < aRHS); -} - -} // namespace mozilla - -#endif /* mozilla_Maybe_h */ diff --git a/win32/include/spidermonkey/mozilla/MaybeOneOf.h b/win32/include/spidermonkey/mozilla/MaybeOneOf.h deleted file mode 100755 index 9c38ff8b..00000000 --- a/win32/include/spidermonkey/mozilla/MaybeOneOf.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_MaybeOneOf_h -#define mozilla_MaybeOneOf_h - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Move.h" -#include "mozilla/TemplateLib.h" - -#include // For placement new - -namespace mozilla { - -/* - * MaybeOneOf is like Maybe, but it supports constructing either T1 - * or T2. When a MaybeOneOf is constructed, it is |empty()|, i.e., - * no value has been constructed and no destructor will be called when the - * MaybeOneOf is destroyed. Upon calling |construct()| or - * |construct()|, a T1 or T2 object will be constructed with the given - * arguments and that object will be destroyed when the owning MaybeOneOf is - * destroyed. - */ -template -class MaybeOneOf -{ - AlignedStorage::value> storage; - - enum State { None, SomeT1, SomeT2 } state; - template struct Type2State {}; - - template - T& as() - { - MOZ_ASSERT(state == Type2State::result); - return *(T*)storage.addr(); - } - - template - const T& as() const - { - MOZ_ASSERT(state == Type2State::result); - return *(T*)storage.addr(); - } - -public: - MaybeOneOf() : state(None) {} - ~MaybeOneOf() { destroyIfConstructed(); } - - MaybeOneOf(MaybeOneOf&& rhs) - : state(None) - { - if (!rhs.empty()) { - if (rhs.constructed()) { - construct(Move(rhs.as())); - rhs.as().~T1(); - } else { - construct(Move(rhs.as())); - rhs.as().~T2(); - } - rhs.state = None; - } - } - - MaybeOneOf &operator=(MaybeOneOf&& rhs) - { - MOZ_ASSERT(this != &rhs, "Self-move is prohibited"); - this->~MaybeOneOf(); - new(this) MaybeOneOf(Move(rhs)); - return *this; - } - - bool empty() const { return state == None; } - - template - bool constructed() const { return state == Type2State::result; } - - template - void construct(Args&&... aArgs) - { - MOZ_ASSERT(state == None); - state = Type2State::result; - ::new (storage.addr()) T(Forward(aArgs)...); - } - - template - T& ref() - { - return as(); - } - - template - const T& ref() const - { - return as(); - } - - void destroy() - { - MOZ_ASSERT(state == SomeT1 || state == SomeT2); - if (state == SomeT1) { - as().~T1(); - } else if (state == SomeT2) { - as().~T2(); - } - state = None; - } - - void destroyIfConstructed() - { - if (!empty()) { - destroy(); - } - } - -private: - MaybeOneOf(const MaybeOneOf& aOther) = delete; - const MaybeOneOf& operator=(const MaybeOneOf& aOther) = delete; -}; - -template -template -struct MaybeOneOf::Type2State -{ - typedef MaybeOneOf Enclosing; - static const typename Enclosing::State result = Enclosing::SomeT1; -}; - -template -template -struct MaybeOneOf::Type2State -{ - typedef MaybeOneOf Enclosing; - static const typename Enclosing::State result = Enclosing::SomeT2; -}; - -} // namespace mozilla - -#endif /* mozilla_MaybeOneOf_h */ diff --git a/win32/include/spidermonkey/mozilla/MemoryChecking.h b/win32/include/spidermonkey/mozilla/MemoryChecking.h deleted file mode 100755 index ff42d7f1..00000000 --- a/win32/include/spidermonkey/mozilla/MemoryChecking.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Provides a common interface to the ASan (AddressSanitizer) and Valgrind - * functions used to mark memory in certain ways. In detail, the following - * three macros are provided: - * - * MOZ_MAKE_MEM_NOACCESS - Mark memory as unsafe to access (e.g. freed) - * MOZ_MAKE_MEM_UNDEFINED - Mark memory as accessible, with content undefined - * MOZ_MAKE_MEM_DEFINED - Mark memory as accessible, with content defined - * - * With Valgrind in use, these directly map to the three respective Valgrind - * macros. With ASan in use, the NOACCESS macro maps to poisoning the memory, - * while the UNDEFINED/DEFINED macros unpoison memory. - * - * With no memory checker available, all macros expand to the empty statement. - */ - -#ifndef mozilla_MemoryChecking_h -#define mozilla_MemoryChecking_h - -#if defined(MOZ_VALGRIND) -#include "valgrind/memcheck.h" -#endif - -#if defined(MOZ_ASAN) || defined(MOZ_VALGRIND) -#define MOZ_HAVE_MEM_CHECKS 1 -#endif - -#if defined(MOZ_ASAN) -#include - -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" - -#ifdef _MSC_VER -// In clang-cl based ASAN, we link against the memory poisoning functions -// statically. -#define MOZ_ASAN_VISIBILITY -#else -#define MOZ_ASAN_VISIBILITY MOZ_EXPORT -#endif - -extern "C" { -/* These definitions are usually provided through the - * sanitizer/asan_interface.h header installed by ASan. - */ -void MOZ_ASAN_VISIBILITY -__asan_poison_memory_region(void const volatile *addr, size_t size); -void MOZ_ASAN_VISIBILITY -__asan_unpoison_memory_region(void const volatile *addr, size_t size); - -#define MOZ_MAKE_MEM_NOACCESS(addr, size) \ - __asan_poison_memory_region((addr), (size)) - -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \ - __asan_unpoison_memory_region((addr), (size)) - -#define MOZ_MAKE_MEM_DEFINED(addr, size) \ - __asan_unpoison_memory_region((addr), (size)) - -/* - * These definitions are usually provided through the - * sanitizer/lsan_interface.h header installed by LSan. - */ -void MOZ_EXPORT -__lsan_ignore_object(const void *p); - -} -#elif defined(MOZ_MSAN) -#include - -#include "mozilla/Types.h" - -extern "C" { -/* These definitions are usually provided through the - * sanitizer/msan_interface.h header installed by MSan. - */ -void MOZ_EXPORT -__msan_poison(void const volatile *addr, size_t size); -void MOZ_EXPORT -__msan_unpoison(void const volatile *addr, size_t size); - -#define MOZ_MAKE_MEM_NOACCESS(addr, size) \ - __msan_poison((addr), (size)) - -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \ - __msan_poison((addr), (size)) - -#define MOZ_MAKE_MEM_DEFINED(addr, size) \ - __msan_unpoison((addr), (size)) -} -#elif defined(MOZ_VALGRIND) -#define MOZ_MAKE_MEM_NOACCESS(addr, size) \ - VALGRIND_MAKE_MEM_NOACCESS((addr), (size)) - -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \ - VALGRIND_MAKE_MEM_UNDEFINED((addr), (size)) - -#define MOZ_MAKE_MEM_DEFINED(addr, size) \ - VALGRIND_MAKE_MEM_DEFINED((addr), (size)) -#else - -#define MOZ_MAKE_MEM_NOACCESS(addr, size) do {} while (0) -#define MOZ_MAKE_MEM_UNDEFINED(addr, size) do {} while (0) -#define MOZ_MAKE_MEM_DEFINED(addr, size) do {} while (0) - -#endif - -/* - * MOZ_LSAN_INTENTIONAL_LEAK(X) is a macro to tell LeakSanitizer that X - * points to a value that will intentionally never be deallocated during - * the execution of the process. - * - * Additional uses of this macro should be reviewed by people - * conversant in leak-checking and/or MFBT peers. - */ -#if defined(MOZ_ASAN) -# define MOZ_LSAN_INTENTIONALLY_LEAK_OBJECT(X) __lsan_ignore_object(X) -#else -# define MOZ_LSAN_INTENTIONALLY_LEAK_OBJECT(X) /* nothing */ -#endif // defined(MOZ_ASAN) - - -#endif /* mozilla_MemoryChecking_h */ diff --git a/win32/include/spidermonkey/mozilla/MemoryReporting.h b/win32/include/spidermonkey/mozilla/MemoryReporting.h deleted file mode 100755 index d2340ecf..00000000 --- a/win32/include/spidermonkey/mozilla/MemoryReporting.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Memory reporting infrastructure. */ - -#ifndef mozilla_MemoryReporting_h -#define mozilla_MemoryReporting_h - -#include - -#ifdef __cplusplus - -namespace mozilla { - -/* - * This is for functions that are like malloc_usable_size. Such functions are - * used for measuring the size of data structures. - */ -typedef size_t (*MallocSizeOf)(const void* p); - -} /* namespace mozilla */ - -#endif /* __cplusplus */ - -typedef size_t (*MozMallocSizeOf)(const void* p); - -#endif /* mozilla_MemoryReporting_h */ diff --git a/win32/include/spidermonkey/mozilla/Move.h b/win32/include/spidermonkey/mozilla/Move.h deleted file mode 100755 index f6d0bfc1..00000000 --- a/win32/include/spidermonkey/mozilla/Move.h +++ /dev/null @@ -1,238 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* C++11-style, but C++98-usable, "move references" implementation. */ - -#ifndef mozilla_Move_h -#define mozilla_Move_h - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/* - * "Move" References - * - * Some types can be copied much more efficiently if we know the original's - * value need not be preserved --- that is, if we are doing a "move", not a - * "copy". For example, if we have: - * - * Vector u; - * Vector v(u); - * - * the constructor for v must apply a copy constructor to each element of u --- - * taking time linear in the length of u. However, if we know we will not need u - * any more once v has been initialized, then we could initialize v very - * efficiently simply by stealing u's dynamically allocated buffer and giving it - * to v --- a constant-time operation, regardless of the size of u. - * - * Moves often appear in container implementations. For example, when we append - * to a vector, we may need to resize its buffer. This entails moving each of - * its extant elements from the old, smaller buffer to the new, larger buffer. - * But once the elements have been migrated, we're just going to throw away the - * old buffer; we don't care if they still have their values. So if the vector's - * element type can implement "move" more efficiently than "copy", the vector - * resizing should by all means use a "move" operation. Hash tables should also - * use moves when resizing their internal array as entries are added and - * removed. - * - * The details of the optimization, and whether it's worth applying, vary - * from one type to the next: copying an 'int' is as cheap as moving it, so - * there's no benefit in distinguishing 'int' moves from copies. And while - * some constructor calls for complex types are moves, many really have to - * be copies, and can't be optimized this way. So we need: - * - * 1) a way for a type (like Vector) to announce that it can be moved more - * efficiently than it can be copied, and provide an implementation of that - * move operation; and - * - * 2) a way for a particular invocation of a copy constructor to say that it's - * really a move, not a copy, and that the value of the original isn't - * important afterwards (although it must still be safe to destroy). - * - * If a constructor has a single argument of type 'T&&' (an 'rvalue reference - * to T'), that indicates that it is a 'move constructor'. That's 1). It should - * move, not copy, its argument into the object being constructed. It may leave - * the original in any safely-destructible state. - * - * If a constructor's argument is an rvalue, as in 'C(f(x))' or 'C(x + y)', as - * opposed to an lvalue, as in 'C(x)', then overload resolution will prefer the - * move constructor, if there is one. The 'mozilla::Move' function, defined in - * this file, is an identity function you can use in a constructor invocation to - * make any argument into an rvalue, like this: C(Move(x)). That's 2). (You - * could use any function that works, but 'Move' indicates your intention - * clearly.) - * - * Where we might define a copy constructor for a class C like this: - * - * C(const C& rhs) { ... copy rhs to this ... } - * - * we would declare a move constructor like this: - * - * C(C&& rhs) { .. move rhs to this ... } - * - * And where we might perform a copy like this: - * - * C c2(c1); - * - * we would perform a move like this: - * - * C c2(Move(c1)); - * - * Note that 'T&&' implicitly converts to 'T&'. So you can pass a 'T&&' to an - * ordinary copy constructor for a type that doesn't support a special move - * constructor, and you'll just get a copy. This means that templates can use - * Move whenever they know they won't use the original value any more, even if - * they're not sure whether the type at hand has a specialized move constructor. - * If it doesn't, the 'T&&' will just convert to a 'T&', and the ordinary copy - * constructor will apply. - * - * A class with a move constructor can also provide a move assignment operator. - * A generic definition would run this's destructor, and then apply the move - * constructor to *this's memory. A typical definition: - * - * C& operator=(C&& rhs) { - * MOZ_ASSERT(&rhs != this, "self-moves are prohibited"); - * this->~C(); - * new(this) C(Move(rhs)); - * return *this; - * } - * - * With that in place, one can write move assignments like this: - * - * c2 = Move(c1); - * - * This destroys c2, moves c1's value to c2, and leaves c1 in an undefined but - * destructible state. - * - * As we say, a move must leave the original in a "destructible" state. The - * original's destructor will still be called, so if a move doesn't - * actually steal all its resources, that's fine. We require only that the - * move destination must take on the original's value; and that destructing - * the original must not break the move destination. - * - * (Opinions differ on whether move assignment operators should deal with move - * assignment of an object onto itself. It seems wise to either handle that - * case, or assert that it does not occur.) - * - * Forwarding: - * - * Sometimes we want copy construction or assignment if we're passed an ordinary - * value, but move construction if passed an rvalue reference. For example, if - * our constructor takes two arguments and either could usefully be a move, it - * seems silly to write out all four combinations: - * - * C::C(X& x, Y& y) : x(x), y(y) { } - * C::C(X& x, Y&& y) : x(x), y(Move(y)) { } - * C::C(X&& x, Y& y) : x(Move(x)), y(y) { } - * C::C(X&& x, Y&& y) : x(Move(x)), y(Move(y)) { } - * - * To avoid this, C++11 has tweaks to make it possible to write what you mean. - * The four constructor overloads above can be written as one constructor - * template like so[0]: - * - * template - * C::C(XArg&& x, YArg&& y) : x(Forward(x)), y(Forward(y)) { } - * - * ("'Don't Repeat Yourself'? What's that?") - * - * This takes advantage of two new rules in C++11: - * - * - First, when a function template takes an argument that is an rvalue - * reference to a template argument (like 'XArg&& x' and 'YArg&& y' above), - * then when the argument is applied to an lvalue, the template argument - * resolves to 'T&'; and when it is applied to an rvalue, the template - * argument resolves to 'T'. Thus, in a call to C::C like: - * - * X foo(int); - * Y yy; - * - * C(foo(5), yy) - * - * XArg would resolve to 'X', and YArg would resolve to 'Y&'. - * - * - Second, Whereas C++ used to forbid references to references, C++11 defines - * 'collapsing rules': 'T& &', 'T&& &', and 'T& &&' (that is, any combination - * involving an lvalue reference) now collapse to simply 'T&'; and 'T&& &&' - * collapses to 'T&&'. - * - * Thus, in the call above, 'XArg&&' is 'X&&'; and 'YArg&&' is 'Y& &&', which - * collapses to 'Y&'. Because the arguments are declared as rvalue references - * to template arguments, the lvalue-ness "shines through" where present. - * - * Then, the 'Forward' function --- you must invoke 'Forward' with its type - * argument --- returns an lvalue reference or an rvalue reference to its - * argument, depending on what T is. In our unified constructor definition, that - * means that we'll invoke either the copy or move constructors for x and y, - * depending on what we gave C's constructor. In our call, we'll move 'foo()' - * into 'x', but copy 'yy' into 'y'. - * - * This header file defines Move and Forward in the mozilla namespace. It's up - * to individual containers to annotate moves as such, by calling Move; and it's - * up to individual types to define move constructors and assignment operators - * when valuable. - * - * (C++11 says that the header file should define 'std::move' and - * 'std::forward', which are just like our 'Move' and 'Forward'; but those - * definitions aren't available in that header on all our platforms, so we - * define them ourselves here.) - * - * 0. This pattern is known as "perfect forwarding". Interestingly, it is not - * actually perfect, and it can't forward all possible argument expressions! - * There is a C++11 issue: you can't form a reference to a bit-field. As a - * workaround, assign the bit-field to a local variable and use that: - * - * // C is as above - * struct S { int x : 1; } s; - * C(s.x, 0); // BAD: s.x is a reference to a bit-field, can't form those - * int tmp = s.x; - * C(tmp, 0); // OK: tmp not a bit-field - */ - -/** - * Identical to std::Move(); this is necessary until our stlport supports - * std::move(). - */ -template -inline typename RemoveReference::Type&& -Move(T&& aX) -{ - return static_cast::Type&&>(aX); -} - -/** - * These two overloads are identical to std::forward(); they are necessary until - * our stlport supports std::forward(). - */ -template -inline T&& -Forward(typename RemoveReference::Type& aX) -{ - return static_cast(aX); -} - -template -inline T&& -Forward(typename RemoveReference::Type&& aX) -{ - static_assert(!IsLvalueReference::value, - "misuse of Forward detected! try the other overload"); - return static_cast(aX); -} - -/** Swap |aX| and |aY| using move-construction if possible. */ -template -inline void -Swap(T& aX, T& aY) -{ - T tmp(Move(aX)); - aX = Move(aY); - aY = Move(tmp); -} - -} // namespace mozilla - -#endif /* mozilla_Move_h */ diff --git a/win32/include/spidermonkey/mozilla/NotNull.h b/win32/include/spidermonkey/mozilla/NotNull.h deleted file mode 100755 index 0c3c333e..00000000 --- a/win32/include/spidermonkey/mozilla/NotNull.h +++ /dev/null @@ -1,209 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_NotNull_h -#define mozilla_NotNull_h - -// It's often unclear if a particular pointer, be it raw (T*) or smart -// (RefPtr, nsCOMPtr, etc.) can be null. This leads to missing null -// checks (which can cause crashes) and unnecessary null checks (which clutter -// the code). -// -// C++ has a built-in alternative that avoids these problems: references. This -// module defines another alternative, NotNull, which can be used in cases -// where references are not suitable. -// -// In the comments below we use the word "handle" to cover all varieties of -// pointers and references. -// -// References -// ---------- -// References are always non-null. (You can do |T& r = *p;| where |p| is null, -// but that's undefined behaviour. C++ doesn't provide any built-in, ironclad -// guarantee of non-nullness.) -// -// A reference works well when you need a temporary handle to an existing -// single object, e.g. for passing a handle to a function, or as a local handle -// within another object. (In Rust parlance, this is a "borrow".) -// -// A reference is less appropriate in the following cases. -// -// - As a primary handle to an object. E.g. code such as this is possible but -// strange: |T& t = *new T(); ...; delete &t;| -// -// - As a handle to an array. It's common for |T*| to refer to either a single -// |T| or an array of |T|, but |T&| cannot refer to an array of |T| because -// you can't index off a reference (at least, not without first converting it -// to a pointer). -// -// - When the handle identity is meaningful, e.g. if you have a hashtable of -// handles, because you have to use |&| on the reference to convert it to a -// pointer. -// -// - Some people don't like using non-const references as function parameters, -// because it is not clear at the call site that the argument might be -// modified. -// -// - When you need "smart" behaviour. E.g. we lack reference equivalents to -// RefPtr and nsCOMPtr. -// -// - When interfacing with code that uses pointers a lot, sometimes using a -// reference just feels like an odd fit. -// -// Furthermore, a reference is impossible in the following cases. -// -// - When the handle is rebound to another object. References don't allow this. -// -// - When the handle has type |void|. |void&| is not allowed. -// -// NotNull is an alternative that can be used in any of the above cases except -// for the last one, where the handle type is |void|. See below. - -#include "mozilla/Assertions.h" - -namespace mozilla { - -// NotNull can be used to wrap a "base" pointer (raw or smart) to indicate it -// is not null. Some examples: -// -// - NotNull -// - NotNull> -// - NotNull> -// -// NotNull has the following notable properties. -// -// - It has zero space overhead. -// -// - It must be initialized explicitly. There is no default initialization. -// -// - It auto-converts to the base pointer type. -// -// - It does not auto-convert from a base pointer. Implicit conversion from a -// less-constrained type (e.g. T*) to a more-constrained type (e.g. -// NotNull) is dangerous. Creation and assignment from a base pointer can -// only be done with WrapNotNull(), which makes them impossible to overlook, -// both when writing and reading code. -// -// - When initialized (or assigned) it is checked, and if it is null we abort. -// This guarantees that it cannot be null. -// -// - |operator bool()| is deleted. This means you cannot check a NotNull in a -// boolean context, which eliminates the possibility of unnecessary null -// checks. -// -// NotNull currently doesn't work with UniquePtr. See -// https://github.com/Microsoft/GSL/issues/89 for some discussion. -// -template -class NotNull -{ - template friend NotNull WrapNotNull(U aBasePtr); - - T mBasePtr; - - // This constructor is only used by WrapNotNull(). - template - explicit NotNull(U aBasePtr) : mBasePtr(aBasePtr) {} - -public: - // Disallow default construction. - NotNull() = delete; - - // Construct/assign from another NotNull with a compatible base pointer type. - template - MOZ_IMPLICIT NotNull(const NotNull& aOther) : mBasePtr(aOther.get()) {} - - // Default copy/move construction and assignment. - NotNull(const NotNull&) = default; - NotNull& operator=(const NotNull&) = default; - NotNull(NotNull&&) = default; - NotNull& operator=(NotNull&&) = default; - - // Disallow null checks, which are unnecessary for this type. - explicit operator bool() const = delete; - - // Explicit conversion to a base pointer. Use only to resolve ambiguity or to - // get a castable pointer. - const T& get() const { return mBasePtr; } - - // Implicit conversion to a base pointer. Preferable to get(). - operator const T&() const { return get(); } - - // Dereference operators. - const T& operator->() const { return get(); } - decltype(*mBasePtr) operator*() const { return *mBasePtr; } -}; - -template -NotNull -WrapNotNull(const T aBasePtr) -{ - NotNull notNull(aBasePtr); - MOZ_RELEASE_ASSERT(aBasePtr); - return notNull; -} - -// Compare two NotNulls. -template -inline bool -operator==(const NotNull& aLhs, const NotNull& aRhs) -{ - return aLhs.get() == aRhs.get(); -} -template -inline bool -operator!=(const NotNull& aLhs, const NotNull& aRhs) -{ - return aLhs.get() != aRhs.get(); -} - -// Compare a NotNull to a base pointer. -template -inline bool -operator==(const NotNull& aLhs, const U& aRhs) -{ - return aLhs.get() == aRhs; -} -template -inline bool -operator!=(const NotNull& aLhs, const U& aRhs) -{ - return aLhs.get() != aRhs; -} - -// Compare a base pointer to a NotNull. -template -inline bool -operator==(const T& aLhs, const NotNull& aRhs) -{ - return aLhs == aRhs.get(); -} -template -inline bool -operator!=(const T& aLhs, const NotNull& aRhs) -{ - return aLhs != aRhs.get(); -} - -// Disallow comparing a NotNull to a nullptr. -template -bool -operator==(const NotNull&, decltype(nullptr)) = delete; -template -bool -operator!=(const NotNull&, decltype(nullptr)) = delete; - -// Disallow comparing a nullptr to a NotNull. -template -bool -operator==(decltype(nullptr), const NotNull&) = delete; -template -bool -operator!=(decltype(nullptr), const NotNull&) = delete; - -} // namespace mozilla - -#endif /* mozilla_NotNull_h */ diff --git a/win32/include/spidermonkey/mozilla/NullPtr.h b/win32/include/spidermonkey/mozilla/NullPtr.h deleted file mode 100755 index d2248f4b..00000000 --- a/win32/include/spidermonkey/mozilla/NullPtr.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements a mozilla::IsNullPointer type trait. */ - -#ifndef mozilla_NullPtr_h -#define mozilla_NullPtr_h - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/** - * IsNullPointer::value is true iff T is decltype(nullptr). - * - * Ideally this would be in TypeTraits.h, but C++11 omitted std::is_null_pointer - * (fixed in C++14), so in the interests of easing a switch to , - * this trait lives elsewhere. - */ -template -struct IsNullPointer : FalseType {}; - -template<> -struct IsNullPointer : TrueType {}; - -} // namespace mozilla - -#endif /* mozilla_NullPtr_h */ diff --git a/win32/include/spidermonkey/mozilla/Opaque.h b/win32/include/spidermonkey/mozilla/Opaque.h deleted file mode 100755 index d7239ee7..00000000 --- a/win32/include/spidermonkey/mozilla/Opaque.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* An opaque integral type supporting only comparison operators. */ - -#ifndef mozilla_Opaque_h -#define mozilla_Opaque_h - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -/** - * Opaque is a replacement for integral T in cases where only comparisons - * must be supported, and it's desirable to prevent accidental dependency on - * exact values. - */ -template -class Opaque final -{ - static_assert(mozilla::IsIntegral::value, - "mozilla::Opaque only supports integral types"); - - T mValue; - -public: - Opaque() {} - explicit Opaque(T aValue) : mValue(aValue) {} - - bool operator==(const Opaque& aOther) const { - return mValue == aOther.mValue; - } - - bool operator!=(const Opaque& aOther) const { - return !(*this == aOther); - } -}; - -} // namespace mozilla - -#endif /* mozilla_Opaque_h */ diff --git a/win32/include/spidermonkey/mozilla/OperatorNewExtensions.h b/win32/include/spidermonkey/mozilla/OperatorNewExtensions.h deleted file mode 100755 index 52fd88a6..00000000 --- a/win32/include/spidermonkey/mozilla/OperatorNewExtensions.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A version of |operator new| that eschews mandatory null-checks. */ - -#ifndef mozilla_OperatorNewExtensions_h -#define mozilla_OperatorNewExtensions_h - -#include "mozilla/Assertions.h" - -// Credit goes to WebKit for this implementation, cf. -// https://bugs.webkit.org/show_bug.cgi?id=74676 -namespace mozilla { -enum NotNullTag { - KnownNotNull, -}; -} // namespace mozilla - -/* - * The logic here is a little subtle. [expr.new] states that if the allocation - * function being called returns null, then object initialization must not be - * done, and the entirety of the new expression must return null. Non-throwing - * (noexcept) functions are defined to return null to indicate failure. The - * standard placement operator new is defined in such a way, and so it requires - * a null check, even when that null check would be extraneous. Functions - * declared without such a specification are defined to throw std::bad_alloc if - * they fail, and return a non-null pointer otherwise. We compile without - * exceptions, so any placement new overload we define that doesn't declare - * itself as noexcept must therefore avoid generating a null check. Below is - * just such an overload. - * - * You might think that MOZ_NONNULL might perform the same function, but - * MOZ_NONNULL isn't supported on all of our compilers, and even when it is - * supported, doesn't work on all the versions we support. And even keeping - * those limitations in mind, we can't put MOZ_NONNULL on the global, - * standardized placement new function in any event. - * - * We deliberately don't add MOZ_NONNULL(3) to tag |p| as non-null, to benefit - * hypothetical static analyzers. Doing so makes |MOZ_ASSERT(p)|'s internal - * test vacuous, and some compilers warn about such vacuous tests. - */ -inline void* -operator new(size_t, mozilla::NotNullTag, void* p) -{ - MOZ_ASSERT(p); - return p; -} - -#endif // mozilla_OperatorNewExtensions_h diff --git a/win32/include/spidermonkey/mozilla/Pair.h b/win32/include/spidermonkey/mozilla/Pair.h deleted file mode 100755 index ad7b86a2..00000000 --- a/win32/include/spidermonkey/mozilla/Pair.h +++ /dev/null @@ -1,219 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A class holding a pair of objects that tries to conserve storage space. */ - -#ifndef mozilla_Pair_h -#define mozilla_Pair_h - -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -namespace detail { - -enum StorageType { AsBase, AsMember }; - -// Optimize storage using the Empty Base Optimization -- that empty base classes -// don't take up space -- to optimize size when one or the other class is -// stateless and can be used as a base class. -// -// The extra conditions on storage for B are necessary so that PairHelper won't -// ambiguously inherit from either A or B, such that one or the other base class -// would be inaccessible. -template::value ? detail::AsBase : detail::AsMember, - detail::StorageType = - IsEmpty::value && !IsBaseOf::value && !IsBaseOf::value - ? detail::AsBase - : detail::AsMember> -struct PairHelper; - -template -struct PairHelper -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : mFirstA(Forward(aA)), - mSecondB(Forward(aB)) - {} - - A& first() { return mFirstA; } - const A& first() const { return mFirstA; } - B& second() { return mSecondB; } - const B& second() const { return mSecondB; } - - void swap(PairHelper& aOther) - { - Swap(mFirstA, aOther.mFirstA); - Swap(mSecondB, aOther.mSecondB); - } - -private: - A mFirstA; - B mSecondB; -}; - -template -struct PairHelper : private B -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : B(Forward(aB)), - mFirstA(Forward(aA)) - {} - - A& first() { return mFirstA; } - const A& first() const { return mFirstA; } - B& second() { return *this; } - const B& second() const { return *this; } - - void swap(PairHelper& aOther) - { - Swap(mFirstA, aOther.mFirstA); - Swap(static_cast(*this), static_cast(aOther)); - } - -private: - A mFirstA; -}; - -template -struct PairHelper : private A -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : A(Forward(aA)), - mSecondB(Forward(aB)) - {} - - A& first() { return *this; } - const A& first() const { return *this; } - B& second() { return mSecondB; } - const B& second() const { return mSecondB; } - - void swap(PairHelper& aOther) - { - Swap(static_cast(*this), static_cast(aOther)); - Swap(mSecondB, aOther.mSecondB); - } - -private: - B mSecondB; -}; - -template -struct PairHelper : private A, private B -{ -protected: - template - PairHelper(AArg&& aA, BArg&& aB) - : A(Forward(aA)), - B(Forward(aB)) - {} - - A& first() { return static_cast(*this); } - const A& first() const { return static_cast(*this); } - B& second() { return static_cast(*this); } - const B& second() const { return static_cast(*this); } - - void swap(PairHelper& aOther) - { - Swap(static_cast(*this), static_cast(aOther)); - Swap(static_cast(*this), static_cast(aOther)); - } -}; - -} // namespace detail - -/** - * Pair is the logical concatenation of an instance of A with an instance B. - * Space is conserved when possible. Neither A nor B may be a final class. - * - * It's typically clearer to have individual A and B member fields. Except if - * you want the space-conserving qualities of Pair, you're probably better off - * not using this! - * - * No guarantees are provided about the memory layout of A and B, the order of - * initialization or destruction of A and B, and so on. (This is approximately - * required to optimize space usage.) The first/second names are merely - * conceptual! - */ -template -struct Pair - : private detail::PairHelper -{ - typedef typename detail::PairHelper Base; - -public: - template - Pair(AArg&& aA, BArg&& aB) - : Base(Forward(aA), Forward(aB)) - {} - - Pair(Pair&& aOther) - : Base(Move(aOther.first()), Move(aOther.second())) - { } - - Pair(const Pair& aOther) = default; - - Pair& operator=(Pair&& aOther) - { - MOZ_ASSERT(this != &aOther, "Self-moves are prohibited"); - - first() = Move(aOther.first()); - second() = Move(aOther.second()); - - return *this; - } - - Pair& operator=(const Pair& aOther) = default; - - /** The A instance. */ - using Base::first; - /** The B instance. */ - using Base::second; - - /** Swap this pair with another pair. */ - void swap(Pair& aOther) { Base::swap(aOther); } -}; - -template -void -Swap(Pair& aX, Pair& aY) -{ - aX.swap(aY); -} - -/** - * MakePair allows you to construct a Pair instance using type inference. A call - * like this: - * - * MakePair(Foo(), Bar()) - * - * will return a Pair. - */ -template -Pair::Type>::Type, - typename RemoveCV::Type>::Type> -MakePair(A&& aA, B&& aB) -{ - return - Pair::Type>::Type, - typename RemoveCV::Type>::Type>( - Forward(aA), - Forward(aB)); -} - -} // namespace mozilla - -#endif /* mozilla_Pair_h */ diff --git a/win32/include/spidermonkey/mozilla/PodOperations.h b/win32/include/spidermonkey/mozilla/PodOperations.h deleted file mode 100755 index e6f4df21..00000000 --- a/win32/include/spidermonkey/mozilla/PodOperations.h +++ /dev/null @@ -1,196 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Operations for zeroing POD types, arrays, and so on. - * - * These operations are preferable to memset, memcmp, and the like because they - * don't require remembering to multiply by sizeof(T), array lengths, and so on - * everywhere. - */ - -#ifndef mozilla_PodOperations_h -#define mozilla_PodOperations_h - -#include "mozilla/Array.h" -#include "mozilla/ArrayUtils.h" -#include "mozilla/Attributes.h" - -#include -#include - -namespace mozilla { - -/** Set the contents of |aT| to 0. */ -template -static MOZ_ALWAYS_INLINE void -PodZero(T* aT) -{ - memset(aT, 0, sizeof(T)); -} - -/** Set the contents of |aNElem| elements starting at |aT| to 0. */ -template -static MOZ_ALWAYS_INLINE void -PodZero(T* aT, size_t aNElem) -{ - /* - * This function is often called with 'aNElem' small; we use an inline loop - * instead of calling 'memset' with a non-constant length. The compiler - * should inline the memset call with constant size, though. - */ - for (T* end = aT + aNElem; aT < end; aT++) { - memset(aT, 0, sizeof(T)); - } -} - -/* - * Arrays implicitly convert to pointers to their first element, which is - * dangerous when combined with the above PodZero definitions. Adding an - * overload for arrays is ambiguous, so we need another identifier. The - * ambiguous overload is left to catch mistaken uses of PodZero; if you get a - * compile error involving PodZero and array types, use PodArrayZero instead. - */ -template -static void PodZero(T (&aT)[N]) = delete; -template -static void PodZero(T (&aT)[N], size_t aNElem) = delete; - -/** Set the contents of the array |aT| to zero. */ -template -static MOZ_ALWAYS_INLINE void -PodArrayZero(T (&aT)[N]) -{ - memset(aT, 0, N * sizeof(T)); -} - -template -static MOZ_ALWAYS_INLINE void -PodArrayZero(Array& aArr) -{ - memset(&aArr[0], 0, N * sizeof(T)); -} - -/** - * Assign |*aSrc| to |*aDst|. The locations must not be the same and must not - * overlap. - */ -template -static MOZ_ALWAYS_INLINE void -PodAssign(T* aDst, const T* aSrc) -{ - MOZ_ASSERT(aDst + 1 <= aSrc || aSrc + 1 <= aDst, - "destination and source must not overlap"); - memcpy(reinterpret_cast(aDst), reinterpret_cast(aSrc), - sizeof(T)); -} - -/** - * Copy |aNElem| T elements from |aSrc| to |aDst|. The two memory ranges must - * not overlap! - */ -template -static MOZ_ALWAYS_INLINE void -PodCopy(T* aDst, const T* aSrc, size_t aNElem) -{ - MOZ_ASSERT(aDst + aNElem <= aSrc || aSrc + aNElem <= aDst, - "destination and source must not overlap"); - if (aNElem < 128) { - /* - * Avoid using operator= in this loop, as it may have been - * intentionally deleted by the POD type. - */ - for (const T* srcend = aSrc + aNElem; aSrc < srcend; aSrc++, aDst++) { - PodAssign(aDst, aSrc); - } - } else { - memcpy(aDst, aSrc, aNElem * sizeof(T)); - } -} - -template -static MOZ_ALWAYS_INLINE void -PodCopy(volatile T* aDst, const volatile T* aSrc, size_t aNElem) -{ - MOZ_ASSERT(aDst + aNElem <= aSrc || aSrc + aNElem <= aDst, - "destination and source must not overlap"); - - /* - * Volatile |aDst| requires extra work, because it's undefined behavior to - * modify volatile objects using the mem* functions. Just write out the - * loops manually, using operator= rather than memcpy for the same reason, - * and let the compiler optimize to the extent it can. - */ - for (const volatile T* srcend = aSrc + aNElem; - aSrc < srcend; - aSrc++, aDst++) { - *aDst = *aSrc; - } -} - -/* - * Copy the contents of the array |aSrc| into the array |aDst|, both of size N. - * The arrays must not overlap! - */ -template -static MOZ_ALWAYS_INLINE void -PodArrayCopy(T (&aDst)[N], const T (&aSrc)[N]) -{ - PodCopy(aDst, aSrc, N); -} - -/** - * Copy the memory for |aNElem| T elements from |aSrc| to |aDst|. If the two - * memory ranges overlap, then the effect is as if the |aNElem| elements are - * first copied from |aSrc| to a temporary array, and then from the temporary - * array to |aDst|. - */ -template -static MOZ_ALWAYS_INLINE void -PodMove(T* aDst, const T* aSrc, size_t aNElem) -{ - MOZ_ASSERT(aNElem <= SIZE_MAX / sizeof(T), - "trying to move an impossible number of elements"); - memmove(aDst, aSrc, aNElem * sizeof(T)); -} - -/** - * Determine whether the |len| elements at |one| are memory-identical to the - * |len| elements at |two|. - */ -template -static MOZ_ALWAYS_INLINE bool -PodEqual(const T* one, const T* two, size_t len) -{ - if (len < 128) { - const T* p1end = one + len; - const T* p1 = one; - const T* p2 = two; - for (; p1 < p1end; p1++, p2++) { - if (*p1 != *p2) { - return false; - } - } - return true; - } - - return !memcmp(one, two, len * sizeof(T)); -} - -/* - * Determine whether the |N| elements at |one| are memory-identical to the - * |N| elements at |two|. - */ -template -static MOZ_ALWAYS_INLINE bool -PodEqual(const T (&one)[N], const T (&two)[N]) -{ - return PodEqual(one, two, N); -} - -} // namespace mozilla - -#endif /* mozilla_PodOperations_h */ diff --git a/win32/include/spidermonkey/mozilla/Poison.h b/win32/include/spidermonkey/mozilla/Poison.h deleted file mode 100755 index aae56765..00000000 --- a/win32/include/spidermonkey/mozilla/Poison.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * A poison value that can be used to fill a memory space with - * an address that leads to a safe crash when dereferenced. - */ - -#ifndef mozilla_Poison_h -#define mozilla_Poison_h - -#include "mozilla/Assertions.h" -#include "mozilla/Types.h" - -#include - -MOZ_BEGIN_EXTERN_C - -extern MFBT_DATA uintptr_t gMozillaPoisonValue; - -/** - * @return the poison value. - */ -inline uintptr_t mozPoisonValue() -{ - return gMozillaPoisonValue; -} - -/** - * Overwrite the memory block of aSize bytes at aPtr with the poison value. - * aPtr MUST be aligned at a sizeof(uintptr_t) boundary. - * Only an even number of sizeof(uintptr_t) bytes are overwritten, the last - * few bytes (if any) is not overwritten. - */ -inline void mozWritePoison(void* aPtr, size_t aSize) -{ - const uintptr_t POISON = mozPoisonValue(); - char* p = (char*)aPtr; - char* limit = p + aSize; - MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment"); - MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect"); - for (; p < limit; p += sizeof(uintptr_t)) { - *((uintptr_t*)p) = POISON; - } -} - -/** - * Initialize the poison value. - * This should only be called once. - */ -extern MFBT_API void mozPoisonValueInit(); - -/* Values annotated by CrashReporter */ -extern MFBT_DATA uintptr_t gMozillaPoisonBase; -extern MFBT_DATA uintptr_t gMozillaPoisonSize; - -MOZ_END_EXTERN_C - -#if defined(__cplusplus) - -namespace mozilla { - -/** - * This class is designed to cause crashes when various kinds of memory - * corruption are observed. For instance, let's say we have a class C where we - * suspect out-of-bounds writes to some members. We can insert a member of type - * Poison near the members we suspect are being corrupted by out-of-bounds - * writes. Or perhaps we have a class K we suspect is subject to use-after-free - * violations, in which case it doesn't particularly matter where in the class - * we add the member of type Poison. - * - * In either case, we then insert calls to Check() throughout the code. Doing - * so enables us to narrow down the location where the corruption is occurring. - * A pleasant side-effect of these additional Check() calls is that crash - * signatures may become more regular, as crashes will ideally occur - * consolidated at the point of a Check(), rather than scattered about at - * various uses of the corrupted memory. - */ -class CorruptionCanary { -public: - CorruptionCanary() { - mValue = kCanarySet; - } - - ~CorruptionCanary() { - Check(); - mValue = mozPoisonValue(); - } - - void Check() const { - if (mValue != kCanarySet) { - MOZ_CRASH("Canary check failed, check lifetime"); - } - } - -private: - static const uintptr_t kCanarySet = 0x0f0b0f0b; - uintptr_t mValue; -}; - -} // mozilla - -#endif - -#endif /* mozilla_Poison_h */ diff --git a/win32/include/spidermonkey/mozilla/Range.h b/win32/include/spidermonkey/mozilla/Range.h deleted file mode 100755 index 47d91bb0..00000000 --- a/win32/include/spidermonkey/mozilla/Range.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_Range_h -#define mozilla_Range_h - -#include "mozilla/RangedPtr.h" -#include "mozilla/TypeTraits.h" - -#include - -namespace mozilla { - -// Range is a tuple containing a pointer and a length. -template -class Range -{ - const RangedPtr mStart; - const RangedPtr mEnd; - -public: - Range() : mStart(nullptr, 0), mEnd(nullptr, 0) {} - Range(T* aPtr, size_t aLength) - : mStart(aPtr, aPtr, aPtr + aLength), - mEnd(aPtr + aLength, aPtr, aPtr + aLength) - {} - Range(const RangedPtr& aStart, const RangedPtr& aEnd) - : mStart(aStart.get(), aStart.get(), aEnd.get()), - mEnd(aEnd.get(), aStart.get(), aEnd.get()) - { - // Only accept two RangedPtrs within the same range. - aStart.checkIdenticalRange(aEnd); - MOZ_ASSERT(aStart <= aEnd); - } - - template::value, - int>::Type> - MOZ_IMPLICIT Range(const Range& aOther) - : mStart(aOther.mStart), - mEnd(aOther.mEnd) - {} - - RangedPtr begin() const { return mStart; } - RangedPtr end() const { return mEnd; } - size_t length() const { return mEnd - mStart; } - - T& operator[](size_t aOffset) const { return mStart[aOffset]; } - - explicit operator bool() const { return mStart != nullptr; } -}; - -} // namespace mozilla - -#endif /* mozilla_Range_h */ diff --git a/win32/include/spidermonkey/mozilla/RangedArray.h b/win32/include/spidermonkey/mozilla/RangedArray.h deleted file mode 100755 index afe6267f..00000000 --- a/win32/include/spidermonkey/mozilla/RangedArray.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * A compile-time constant-length array, with bounds-checking assertions -- but - * unlike mozilla::Array, with indexes biased by a constant. - * - * Thus where mozilla::Array is a three-element array indexed by [0, 3), - * mozilla::RangedArray is a three-element array indexed by [8, 11). - */ - -#ifndef mozilla_RangedArray_h -#define mozilla_RangedArray_h - -#include "mozilla/Array.h" - -namespace mozilla { - -template -class RangedArray -{ -private: - typedef Array ArrayType; - ArrayType mArr; - -public: - T& operator[](size_t aIndex) - { - MOZ_ASSERT(aIndex == MinIndex || aIndex > MinIndex); - return mArr[aIndex - MinIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(aIndex == MinIndex || aIndex > MinIndex); - return mArr[aIndex - MinIndex]; - } - - typedef typename ArrayType::iterator iterator; - typedef typename ArrayType::const_iterator const_iterator; - typedef typename ArrayType::reverse_iterator reverse_iterator; - typedef typename ArrayType::const_reverse_iterator const_reverse_iterator; - - // Methods for range-based for loops. - iterator begin() { return mArr.begin(); } - const_iterator begin() const { return mArr.begin(); } - const_iterator cbegin() const { return mArr.cbegin(); } - iterator end() { return mArr.end(); } - const_iterator end() const { return mArr.end(); } - const_iterator cend() const { return mArr.cend(); } - - // Methods for reverse iterating. - reverse_iterator rbegin() { return mArr.rbegin(); } - const_reverse_iterator rbegin() const { return mArr.rbegin(); } - const_reverse_iterator crbegin() const { return mArr.crbegin(); } - reverse_iterator rend() { return mArr.rend(); } - const_reverse_iterator rend() const { return mArr.rend(); } - const_reverse_iterator crend() const { return mArr.crend(); } -}; - -} // namespace mozilla - -#endif // mozilla_RangedArray_h diff --git a/win32/include/spidermonkey/mozilla/RangedPtr.h b/win32/include/spidermonkey/mozilla/RangedPtr.h deleted file mode 100755 index a07c1f4f..00000000 --- a/win32/include/spidermonkey/mozilla/RangedPtr.h +++ /dev/null @@ -1,292 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Implements a smart pointer asserted to remain within a range specified at - * construction. - */ - -#ifndef mozilla_RangedPtr_h -#define mozilla_RangedPtr_h - -#include "mozilla/ArrayUtils.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#include - -namespace mozilla { - -/* - * RangedPtr is a smart pointer restricted to an address range specified at - * creation. The pointer (and any smart pointers derived from it) must remain - * within the range [start, end] (inclusive of end to facilitate use as - * sentinels). Dereferencing or indexing into the pointer (or pointers derived - * from it) must remain within the range [start, end). All the standard pointer - * operators are defined on it; in debug builds these operations assert that the - * range specified at construction is respected. - * - * In theory passing a smart pointer instance as an argument can be slightly - * slower than passing a T* (due to ABI requirements for passing structs versus - * passing pointers), if the method being called isn't inlined. If you are in - * extremely performance-critical code, you may want to be careful using this - * smart pointer as an argument type. - * - * RangedPtr intentionally does not implicitly convert to T*. Use get() to - * explicitly convert to T*. Keep in mind that the raw pointer of course won't - * implement bounds checking in debug builds. - */ -template -class RangedPtr -{ - T* mPtr; - -#ifdef DEBUG - T* const mRangeStart; - T* const mRangeEnd; -#endif - - void checkSanity() - { - MOZ_ASSERT(mRangeStart <= mPtr); - MOZ_ASSERT(mPtr <= mRangeEnd); - } - - /* Creates a new pointer for |aPtr|, restricted to this pointer's range. */ - RangedPtr create(T* aPtr) const - { -#ifdef DEBUG - return RangedPtr(aPtr, mRangeStart, mRangeEnd); -#else - return RangedPtr(aPtr, nullptr, size_t(0)); -#endif - } - - uintptr_t asUintptr() const { return reinterpret_cast(mPtr); } - -public: - RangedPtr(T* aPtr, T* aStart, T* aEnd) - : mPtr(aPtr) -#ifdef DEBUG - , mRangeStart(aStart), mRangeEnd(aEnd) -#endif - { - MOZ_ASSERT(mRangeStart <= mRangeEnd); - checkSanity(); - } - RangedPtr(T* aPtr, T* aStart, size_t aLength) - : mPtr(aPtr) -#ifdef DEBUG - , mRangeStart(aStart), mRangeEnd(aStart + aLength) -#endif - { - MOZ_ASSERT(aLength <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(reinterpret_cast(mRangeStart) + aLength * sizeof(T) >= - reinterpret_cast(mRangeStart)); - checkSanity(); - } - - /* Equivalent to RangedPtr(aPtr, aPtr, aLength). */ - RangedPtr(T* aPtr, size_t aLength) - : mPtr(aPtr) -#ifdef DEBUG - , mRangeStart(aPtr), mRangeEnd(aPtr + aLength) -#endif - { - MOZ_ASSERT(aLength <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(reinterpret_cast(mRangeStart) + aLength * sizeof(T) >= - reinterpret_cast(mRangeStart)); - checkSanity(); - } - - /* Equivalent to RangedPtr(aArr, aArr, N). */ - template - explicit RangedPtr(T (&aArr)[N]) - : mPtr(aArr) -#ifdef DEBUG - , mRangeStart(aArr), mRangeEnd(aArr + N) -#endif - { - checkSanity(); - } - - T* get() const { return mPtr; } - - explicit operator bool() const { return mPtr != nullptr; } - - void checkIdenticalRange(const RangedPtr& aOther) const - { - MOZ_ASSERT(mRangeStart == aOther.mRangeStart); - MOZ_ASSERT(mRangeEnd == aOther.mRangeEnd); - } - - /* - * You can only assign one RangedPtr into another if the two pointers have - * the same valid range: - * - * char arr1[] = "hi"; - * char arr2[] = "bye"; - * RangedPtr p1(arr1, 2); - * p1 = RangedPtr(arr1 + 1, arr1, arr1 + 2); // works - * p1 = RangedPtr(arr2, 3); // asserts - */ - RangedPtr& operator=(const RangedPtr& aOther) - { - checkIdenticalRange(aOther); - mPtr = aOther.mPtr; - checkSanity(); - return *this; - } - - RangedPtr operator+(size_t aInc) const - { - MOZ_ASSERT(aInc <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(asUintptr() + aInc * sizeof(T) >= asUintptr()); - return create(mPtr + aInc); - } - - RangedPtr operator-(size_t aDec) const - { - MOZ_ASSERT(aDec <= size_t(-1) / sizeof(T)); - MOZ_ASSERT(asUintptr() - aDec * sizeof(T) <= asUintptr()); - return create(mPtr - aDec); - } - - /* - * You can assign a raw pointer into a RangedPtr if the raw pointer is - * within the range specified at creation. - */ - template - RangedPtr& operator=(U* aPtr) - { - *this = create(aPtr); - return *this; - } - - template - RangedPtr& operator=(const RangedPtr& aPtr) - { - MOZ_ASSERT(mRangeStart <= aPtr.mPtr); - MOZ_ASSERT(aPtr.mPtr <= mRangeEnd); - mPtr = aPtr.mPtr; - checkSanity(); - return *this; - } - - RangedPtr& operator++() - { - return (*this += 1); - } - - RangedPtr operator++(int) - { - RangedPtr rcp = *this; - ++*this; - return rcp; - } - - RangedPtr& operator--() - { - return (*this -= 1); - } - - RangedPtr operator--(int) - { - RangedPtr rcp = *this; - --*this; - return rcp; - } - - RangedPtr& operator+=(size_t aInc) - { - *this = *this + aInc; - return *this; - } - - RangedPtr& operator-=(size_t aDec) - { - *this = *this - aDec; - return *this; - } - - T& operator[](int aIndex) const - { - MOZ_ASSERT(size_t(aIndex > 0 ? aIndex : -aIndex) <= size_t(-1) / sizeof(T)); - return *create(mPtr + aIndex); - } - - T& operator*() const - { - MOZ_ASSERT(mPtr >= mRangeStart); - MOZ_ASSERT(mPtr < mRangeEnd); - return *mPtr; - } - - T* operator->() const - { - MOZ_ASSERT(mPtr >= mRangeStart); - MOZ_ASSERT(mPtr < mRangeEnd); - return mPtr; - } - - template - bool operator==(const RangedPtr& aOther) const - { - return mPtr == aOther.mPtr; - } - template - bool operator!=(const RangedPtr& aOther) const - { - return !(*this == aOther); - } - - template - bool operator==(const U* u) const - { - return mPtr == u; - } - template - bool operator!=(const U* u) const - { - return !(*this == u); - } - - template - bool operator<(const RangedPtr& aOther) const - { - return mPtr < aOther.mPtr; - } - template - bool operator<=(const RangedPtr& aOther) const - { - return mPtr <= aOther.mPtr; - } - - template - bool operator>(const RangedPtr& aOther) const - { - return mPtr > aOther.mPtr; - } - template - bool operator>=(const RangedPtr& aOther) const - { - return mPtr >= aOther.mPtr; - } - - size_t operator-(const RangedPtr& aOther) const - { - MOZ_ASSERT(mPtr >= aOther.mPtr); - return PointerRangeSize(aOther.mPtr, mPtr); - } - -private: - RangedPtr() = delete; - T* operator&() = delete; -}; - -} /* namespace mozilla */ - -#endif /* mozilla_RangedPtr_h */ diff --git a/win32/include/spidermonkey/mozilla/ReentrancyGuard.h b/win32/include/spidermonkey/mozilla/ReentrancyGuard.h deleted file mode 100755 index 9963974e..00000000 --- a/win32/include/spidermonkey/mozilla/ReentrancyGuard.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Small helper class for asserting uses of a class are non-reentrant. */ - -#ifndef mozilla_ReentrancyGuard_h -#define mozilla_ReentrancyGuard_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/GuardObjects.h" - -namespace mozilla { - -/* Useful for implementing containers that assert non-reentrancy */ -class MOZ_RAII ReentrancyGuard -{ - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -#ifdef DEBUG - bool& mEntered; -#endif - -public: - template -#ifdef DEBUG - explicit ReentrancyGuard(T& aObj - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mEntered(aObj.mEntered) -#else - explicit ReentrancyGuard(T& - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) -#endif - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; -#ifdef DEBUG - MOZ_ASSERT(!mEntered); - mEntered = true; -#endif - } - ~ReentrancyGuard() - { -#ifdef DEBUG - mEntered = false; -#endif - } - -private: - ReentrancyGuard(const ReentrancyGuard&) = delete; - void operator=(const ReentrancyGuard&) = delete; -}; - -} // namespace mozilla - -#endif /* mozilla_ReentrancyGuard_h */ diff --git a/win32/include/spidermonkey/mozilla/RefCountType.h b/win32/include/spidermonkey/mozilla/RefCountType.h deleted file mode 100755 index e95a22a0..00000000 --- a/win32/include/spidermonkey/mozilla/RefCountType.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_RefCountType_h -#define mozilla_RefCountType_h - -#include - -/** - * MozRefCountType is Mozilla's reference count type. - * - * We use the same type to represent the refcount of RefCounted objects - * as well, in order to be able to use the leak detection facilities - * that are implemented by XPCOM. - * - * Note that this type is not in the mozilla namespace so that it is - * usable for both C and C++ code. - */ -typedef uintptr_t MozRefCountType; - -/* - * This is the return type for AddRef() and Release() in nsISupports. - * IUnknown of COM returns an unsigned long from equivalent functions. - * - * The following ifdef exists to maintain binary compatibility with - * IUnknown, the base interface in Microsoft COM. - */ -#ifdef XP_WIN -typedef unsigned long MozExternalRefCountType; -#else -typedef uint32_t MozExternalRefCountType; -#endif - -#endif diff --git a/win32/include/spidermonkey/mozilla/RefCounted.h b/win32/include/spidermonkey/mozilla/RefCounted.h deleted file mode 100755 index ae05f1e0..00000000 --- a/win32/include/spidermonkey/mozilla/RefCounted.h +++ /dev/null @@ -1,210 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* CRTP refcounting templates. Do not use unless you are an Expert. */ - -#ifndef mozilla_RefCounted_h -#define mozilla_RefCounted_h - -#include "mozilla/AlreadyAddRefed.h" -#include "mozilla/Assertions.h" -#include "mozilla/Atomics.h" -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/RefCountType.h" -#include "mozilla/TypeTraits.h" - -#if defined(MOZILLA_INTERNAL_API) -#include "nsXPCOM.h" -#endif - -#if defined(MOZILLA_INTERNAL_API) && \ - (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING)) -#define MOZ_REFCOUNTED_LEAK_CHECKING -#endif - -namespace mozilla { - -/** - * RefCounted is a sort of a "mixin" for a class T. RefCounted - * manages, well, refcounting for T, and because RefCounted is - * parameterized on T, RefCounted can call T's destructor directly. - * This means T doesn't need to have a virtual dtor and so doesn't - * need a vtable. - * - * RefCounted is created with refcount == 0. Newly-allocated - * RefCounted must immediately be assigned to a RefPtr to make the - * refcount > 0. It's an error to allocate and free a bare - * RefCounted, i.e. outside of the RefPtr machinery. Attempts to - * do so will abort DEBUG builds. - * - * Live RefCounted have refcount > 0. The lifetime (refcounts) of - * live RefCounted are controlled by RefPtr and - * RefPtr. Upon a transition from refcounted==1 - * to 0, the RefCounted "dies" and is destroyed. The "destroyed" - * state is represented in DEBUG builds by refcount==0xffffdead. This - * state distinguishes use-before-ref (refcount==0) from - * use-after-destroy (refcount==0xffffdead). - * - * Note that when deriving from RefCounted or AtomicRefCounted, you - * should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public - * section of your class, where ClassName is the name of your class. - */ -namespace detail { -const MozRefCountType DEAD = 0xffffdead; - -// When building code that gets compiled into Gecko, try to use the -// trace-refcount leak logging facilities. -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING -class RefCountLogger -{ -public: - static void logAddRef(const void* aPointer, MozRefCountType aRefCount, - const char* aTypeName, uint32_t aInstanceSize) - { - MOZ_ASSERT(aRefCount != DEAD); - NS_LogAddRef(const_cast(aPointer), aRefCount, aTypeName, - aInstanceSize); - } - - static void logRelease(const void* aPointer, MozRefCountType aRefCount, - const char* aTypeName) - { - MOZ_ASSERT(aRefCount != DEAD); - NS_LogRelease(const_cast(aPointer), aRefCount, aTypeName); - } -}; -#endif - -// This is used WeakPtr.h as well as this file. -enum RefCountAtomicity -{ - AtomicRefCount, - NonAtomicRefCount -}; - -template -class RefCounted -{ -protected: - RefCounted() : mRefCnt(0) {} - ~RefCounted() { MOZ_ASSERT(mRefCnt == detail::DEAD); } - -public: - // Compatibility with nsRefPtr. - void AddRef() const - { - // Note: this method must be thread safe for AtomicRefCounted. - MOZ_ASSERT(int32_t(mRefCnt) >= 0); -#ifndef MOZ_REFCOUNTED_LEAK_CHECKING - ++mRefCnt; -#else - const char* type = static_cast(this)->typeName(); - uint32_t size = static_cast(this)->typeSize(); - const void* ptr = static_cast(this); - MozRefCountType cnt = ++mRefCnt; - detail::RefCountLogger::logAddRef(ptr, cnt, type, size); -#endif - } - - void Release() const - { - // Note: this method must be thread safe for AtomicRefCounted. - MOZ_ASSERT(int32_t(mRefCnt) > 0); -#ifndef MOZ_REFCOUNTED_LEAK_CHECKING - MozRefCountType cnt = --mRefCnt; -#else - const char* type = static_cast(this)->typeName(); - const void* ptr = static_cast(this); - MozRefCountType cnt = --mRefCnt; - // Note: it's not safe to touch |this| after decrementing the refcount, - // except for below. - detail::RefCountLogger::logRelease(ptr, cnt, type); -#endif - if (0 == cnt) { - // Because we have atomically decremented the refcount above, only - // one thread can get a 0 count here, so as long as we can assume that - // everything else in the system is accessing this object through - // RefPtrs, it's safe to access |this| here. -#ifdef DEBUG - mRefCnt = detail::DEAD; -#endif - delete static_cast(this); - } - } - - // Compatibility with wtf::RefPtr. - void ref() { AddRef(); } - void deref() { Release(); } - MozRefCountType refCount() const { return mRefCnt; } - bool hasOneRef() const - { - MOZ_ASSERT(mRefCnt > 0); - return mRefCnt == 1; - } - -private: - mutable typename Conditional, - MozRefCountType>::Type mRefCnt; -}; - -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING -// Passing override for the optional argument marks the typeName and -// typeSize functions defined by this macro as overrides. -#define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \ - virtual const char* typeName() const __VA_ARGS__ { return #T; } \ - virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); } -#else -#define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) -#endif - -// Note that this macro is expanded unconditionally because it declares only -// two small inline functions which will hopefully get eliminated by the linker -// in non-leak-checking builds. -#define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \ - const char* typeName() const { return #T; } \ - size_t typeSize() const { return sizeof(*this); } - -} // namespace detail - -template -class RefCounted : public detail::RefCounted -{ -public: - ~RefCounted() - { - static_assert(IsBaseOf::value, - "T must derive from RefCounted"); - } -}; - -namespace external { - -/** - * AtomicRefCounted is like RefCounted, with an atomically updated - * reference counter. - * - * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING - * instead. - */ -template -class AtomicRefCounted : - public mozilla::detail::RefCounted -{ -public: - ~AtomicRefCounted() - { - static_assert(IsBaseOf::value, - "T must derive from AtomicRefCounted"); - } -}; - -} // namespace external - -} // namespace mozilla - -#endif // mozilla_RefCounted_h diff --git a/win32/include/spidermonkey/mozilla/RefPtr.h b/win32/include/spidermonkey/mozilla/RefPtr.h deleted file mode 100755 index bfa8f6e0..00000000 --- a/win32/include/spidermonkey/mozilla/RefPtr.h +++ /dev/null @@ -1,656 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_RefPtr_h -#define mozilla_RefPtr_h - -#include "mozilla/AlreadyAddRefed.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -/*****************************************************************************/ - -// template class RefPtrGetterAddRefs; - -class nsCOMPtr_helper; - -namespace mozilla { -template class OwningNonNull; -template class StaticRefPtr; - -// Traditionally, RefPtr supports automatic refcounting of any pointer type -// with AddRef() and Release() methods that follow the traditional semantics. -// -// This traits class can be specialized to operate on other pointer types. For -// example, we specialize this trait for opaque FFI types that represent -// refcounted objects in Rust. -// -// Given the use of ConstRemovingRefPtrTraits below, U should not be a const- -// qualified type. -template -struct RefPtrTraits -{ - static void AddRef(U* aPtr) { - aPtr->AddRef(); - } - static void Release(U* aPtr) { - aPtr->Release(); - } -}; - -} // namespace mozilla - -template -class RefPtr -{ -private: - void - assign_with_AddRef(T* aRawPtr) - { - if (aRawPtr) { - ConstRemovingRefPtrTraits::AddRef(aRawPtr); - } - assign_assuming_AddRef(aRawPtr); - } - - void - assign_assuming_AddRef(T* aNewPtr) - { - T* oldPtr = mRawPtr; - mRawPtr = aNewPtr; - if (oldPtr) { - ConstRemovingRefPtrTraits::Release(oldPtr); - } - } - -private: - T* MOZ_OWNING_REF mRawPtr; - -public: - typedef T element_type; - - ~RefPtr() - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::Release(mRawPtr); - } - } - - // Constructors - - RefPtr() - : mRawPtr(nullptr) - // default constructor - { - } - - RefPtr(const RefPtr& aSmartPtr) - : mRawPtr(aSmartPtr.mRawPtr) - // copy-constructor - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::AddRef(mRawPtr); - } - } - - RefPtr(RefPtr&& aRefPtr) - : mRawPtr(aRefPtr.mRawPtr) - { - aRefPtr.mRawPtr = nullptr; - } - - // construct from a raw pointer (of the right type) - - MOZ_IMPLICIT RefPtr(T* aRawPtr) - : mRawPtr(aRawPtr) - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::AddRef(mRawPtr); - } - } - - MOZ_IMPLICIT RefPtr(decltype(nullptr)) - : mRawPtr(nullptr) - { - } - - template - MOZ_IMPLICIT RefPtr(already_AddRefed& aSmartPtr) - : mRawPtr(aSmartPtr.take()) - // construct from |already_AddRefed| - { - } - - template - MOZ_IMPLICIT RefPtr(already_AddRefed&& aSmartPtr) - : mRawPtr(aSmartPtr.take()) - // construct from |otherRefPtr.forget()| - { - } - - template - MOZ_IMPLICIT RefPtr(const RefPtr& aSmartPtr) - : mRawPtr(aSmartPtr.get()) - // copy-construct from a smart pointer with a related pointer type - { - if (mRawPtr) { - ConstRemovingRefPtrTraits::AddRef(mRawPtr); - } - } - - template - MOZ_IMPLICIT RefPtr(RefPtr&& aSmartPtr) - : mRawPtr(aSmartPtr.forget().take()) - // construct from |Move(RefPtr)|. - { - } - - MOZ_IMPLICIT RefPtr(const nsCOMPtr_helper& aHelper); - - // Defined in OwningNonNull.h - template - MOZ_IMPLICIT RefPtr(const mozilla::OwningNonNull& aOther); - - // Defined in StaticPtr.h - template - MOZ_IMPLICIT RefPtr(const mozilla::StaticRefPtr& aOther); - - // Assignment operators - - RefPtr& - operator=(decltype(nullptr)) - { - assign_assuming_AddRef(nullptr); - return *this; - } - - RefPtr& - operator=(const RefPtr& aRhs) - // copy assignment operator - { - assign_with_AddRef(aRhs.mRawPtr); - return *this; - } - - template - RefPtr& - operator=(const RefPtr& aRhs) - // assign from an RefPtr of a related pointer type - { - assign_with_AddRef(aRhs.get()); - return *this; - } - - RefPtr& - operator=(T* aRhs) - // assign from a raw pointer (of the right type) - { - assign_with_AddRef(aRhs); - return *this; - } - - template - RefPtr& - operator=(already_AddRefed& aRhs) - // assign from |already_AddRefed| - { - assign_assuming_AddRef(aRhs.take()); - return *this; - } - - template - RefPtr& - operator=(already_AddRefed && aRhs) - // assign from |otherRefPtr.forget()| - { - assign_assuming_AddRef(aRhs.take()); - return *this; - } - - RefPtr& operator=(const nsCOMPtr_helper& aHelper); - - RefPtr& - operator=(RefPtr && aRefPtr) - { - assign_assuming_AddRef(aRefPtr.mRawPtr); - aRefPtr.mRawPtr = nullptr; - return *this; - } - - // Defined in OwningNonNull.h - template - RefPtr& - operator=(const mozilla::OwningNonNull& aOther); - - // Defined in StaticPtr.h - template - RefPtr& - operator=(const mozilla::StaticRefPtr& aOther); - - // Other pointer operators - - void - swap(RefPtr& aRhs) - // ...exchange ownership with |aRhs|; can save a pair of refcount operations - { - T* temp = aRhs.mRawPtr; - aRhs.mRawPtr = mRawPtr; - mRawPtr = temp; - } - - void - swap(T*& aRhs) - // ...exchange ownership with |aRhs|; can save a pair of refcount operations - { - T* temp = aRhs; - aRhs = mRawPtr; - mRawPtr = temp; - } - - already_AddRefed - forget() - // return the value of mRawPtr and null out mRawPtr. Useful for - // already_AddRefed return values. - { - T* temp = nullptr; - swap(temp); - return already_AddRefed(temp); - } - - template - void - forget(I** aRhs) - // Set the target of aRhs to the value of mRawPtr and null out mRawPtr. - // Useful to avoid unnecessary AddRef/Release pairs with "out" - // parameters where aRhs bay be a T** or an I** where I is a base class - // of T. - { - MOZ_ASSERT(aRhs, "Null pointer passed to forget!"); - *aRhs = mRawPtr; - mRawPtr = nullptr; - } - - T* - get() const - /* - Prefer the implicit conversion provided automatically by |operator T*() const|. - Use |get()| to resolve ambiguity or to get a castable pointer. - */ - { - return const_cast(mRawPtr); - } - - operator T*() const -#ifdef MOZ_HAVE_REF_QUALIFIERS - & -#endif - /* - ...makes an |RefPtr| act like its underlying raw pointer type whenever it - is used in a context where a raw pointer is expected. It is this operator - that makes an |RefPtr| substitutable for a raw pointer. - - Prefer the implicit use of this operator to calling |get()|, except where - necessary to resolve ambiguity. - */ - { - return get(); - } - -#ifdef MOZ_HAVE_REF_QUALIFIERS - // Don't allow implicit conversion of temporary RefPtr to raw pointer, - // because the refcount might be one and the pointer will immediately become - // invalid. - operator T*() const && = delete; - - // These are needed to avoid the deleted operator above. XXX Why is operator! - // needed separately? Shouldn't the compiler prefer using the non-deleted - // operator bool instead of the deleted operator T*? - explicit operator bool() const { return !!mRawPtr; } - bool operator!() const { return !mRawPtr; } -#endif - - T* - operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN - { - MOZ_ASSERT(mRawPtr != nullptr, - "You can't dereference a NULL RefPtr with operator->()."); - return get(); - } - - template - class Proxy - { - typedef R (T::*member_function)(Args...); - T* mRawPtr; - member_function mFunction; - public: - Proxy(T* aRawPtr, member_function aFunction) - : mRawPtr(aRawPtr), - mFunction(aFunction) - { - } - template - R operator()(ActualArgs&&... aArgs) - { - return ((*mRawPtr).*mFunction)(mozilla::Forward(aArgs)...); - } - }; - - template - Proxy operator->*(R (T::*aFptr)(Args...)) const - { - MOZ_ASSERT(mRawPtr != nullptr, - "You can't dereference a NULL RefPtr with operator->*()."); - return Proxy(get(), aFptr); - } - - RefPtr* - get_address() - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } - - const RefPtr* - get_address() const - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } - -public: - T& - operator*() const - { - MOZ_ASSERT(mRawPtr != nullptr, - "You can't dereference a NULL RefPtr with operator*()."); - return *get(); - } - - T** - StartAssignment() - { - assign_assuming_AddRef(nullptr); - return reinterpret_cast(&mRawPtr); - } -private: - // This helper class makes |RefPtr| possible by casting away - // the constness from the pointer when calling AddRef() and Release(). - // - // This is necessary because AddRef() and Release() implementations can't - // generally expected to be const themselves (without heavy use of |mutable| - // and |const_cast| in their own implementations). - // - // This should be sound because while |RefPtr| provides a - // const view of an object, the object itself should not be const (it - // would have to be allocated as |new const T| or similar to be const). - template - struct ConstRemovingRefPtrTraits - { - static void AddRef(U* aPtr) { - mozilla::RefPtrTraits::AddRef(aPtr); - } - static void Release(U* aPtr) { - mozilla::RefPtrTraits::Release(aPtr); - } - }; - template - struct ConstRemovingRefPtrTraits - { - static void AddRef(const U* aPtr) { - mozilla::RefPtrTraits::AddRef(const_cast(aPtr)); - } - static void Release(const U* aPtr) { - mozilla::RefPtrTraits::Release(const_cast(aPtr)); - } - }; -}; - -class nsCycleCollectionTraversalCallback; -template -void -CycleCollectionNoteChild(nsCycleCollectionTraversalCallback& aCallback, - T* aChild, const char* aName, uint32_t aFlags); - -template -inline void -ImplCycleCollectionUnlink(RefPtr& aField) -{ - aField = nullptr; -} - -template -inline void -ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback, - RefPtr& aField, - const char* aName, - uint32_t aFlags = 0) -{ - CycleCollectionNoteChild(aCallback, aField.get(), aName, aFlags); -} - -template -inline RefPtr* -address_of(RefPtr& aPtr) -{ - return aPtr.get_address(); -} - -template -inline const RefPtr* -address_of(const RefPtr& aPtr) -{ - return aPtr.get_address(); -} - -template -class RefPtrGetterAddRefs -/* - ... - - This class is designed to be used for anonymous temporary objects in the - argument list of calls that return COM interface pointers, e.g., - - RefPtr fooP; - ...->GetAddRefedPointer(getter_AddRefs(fooP)) - - DO NOT USE THIS TYPE DIRECTLY IN YOUR CODE. Use |getter_AddRefs()| instead. - - When initialized with a |RefPtr|, as in the example above, it returns - a |void**|, a |T**|, or an |nsISupports**| as needed, that the - outer call (|GetAddRefedPointer| in this case) can fill in. - - This type should be a nested class inside |RefPtr|. -*/ -{ -public: - explicit - RefPtrGetterAddRefs(RefPtr& aSmartPtr) - : mTargetSmartPtr(aSmartPtr) - { - // nothing else to do - } - - operator void**() - { - return reinterpret_cast(mTargetSmartPtr.StartAssignment()); - } - - operator T**() - { - return mTargetSmartPtr.StartAssignment(); - } - - T*& - operator*() - { - return *(mTargetSmartPtr.StartAssignment()); - } - -private: - RefPtr& mTargetSmartPtr; -}; - -template -inline RefPtrGetterAddRefs -getter_AddRefs(RefPtr& aSmartPtr) -/* - Used around a |RefPtr| when - ...makes the class |RefPtrGetterAddRefs| invisible. -*/ -{ - return RefPtrGetterAddRefs(aSmartPtr); -} - - -// Comparing two |RefPtr|s - -template -inline bool -operator==(const RefPtr& aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs.get()) == static_cast(aRhs.get()); -} - - -template -inline bool -operator!=(const RefPtr& aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs.get()) != static_cast(aRhs.get()); -} - - -// Comparing an |RefPtr| to a raw pointer - -template -inline bool -operator==(const RefPtr& aLhs, const U* aRhs) -{ - return static_cast(aLhs.get()) == static_cast(aRhs); -} - -template -inline bool -operator==(const U* aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs) == static_cast(aRhs.get()); -} - -template -inline bool -operator!=(const RefPtr& aLhs, const U* aRhs) -{ - return static_cast(aLhs.get()) != static_cast(aRhs); -} - -template -inline bool -operator!=(const U* aLhs, const RefPtr& aRhs) -{ - return static_cast(aLhs) != static_cast(aRhs.get()); -} - -template -inline bool -operator==(const RefPtr& aLhs, U* aRhs) -{ - return static_cast(aLhs.get()) == const_cast(aRhs); -} - -template -inline bool -operator==(U* aLhs, const RefPtr& aRhs) -{ - return const_cast(aLhs) == static_cast(aRhs.get()); -} - -template -inline bool -operator!=(const RefPtr& aLhs, U* aRhs) -{ - return static_cast(aLhs.get()) != const_cast(aRhs); -} - -template -inline bool -operator!=(U* aLhs, const RefPtr& aRhs) -{ - return const_cast(aLhs) != static_cast(aRhs.get()); -} - -// Comparing an |RefPtr| to |nullptr| - -template -inline bool -operator==(const RefPtr& aLhs, decltype(nullptr)) -{ - return aLhs.get() == nullptr; -} - -template -inline bool -operator==(decltype(nullptr), const RefPtr& aRhs) -{ - return nullptr == aRhs.get(); -} - -template -inline bool -operator!=(const RefPtr& aLhs, decltype(nullptr)) -{ - return aLhs.get() != nullptr; -} - -template -inline bool -operator!=(decltype(nullptr), const RefPtr& aRhs) -{ - return nullptr != aRhs.get(); -} - -/*****************************************************************************/ - -template -inline already_AddRefed -do_AddRef(T* aObj) -{ - RefPtr ref(aObj); - return ref.forget(); -} - -template -inline already_AddRefed -do_AddRef(const RefPtr& aObj) -{ - RefPtr ref(aObj); - return ref.forget(); -} - -namespace mozilla { - -/** - * Helper function to be able to conveniently write things like: - * - * already_AddRefed - * f(...) - * { - * return MakeAndAddRef(...); - * } - */ -template -already_AddRefed -MakeAndAddRef(Args&&... aArgs) -{ - RefPtr p(new T(Forward(aArgs)...)); - return p.forget(); -} - -} // namespace mozilla - -#endif /* mozilla_RefPtr_h */ diff --git a/win32/include/spidermonkey/mozilla/ReverseIterator.h b/win32/include/spidermonkey/mozilla/ReverseIterator.h deleted file mode 100755 index 49c2e279..00000000 --- a/win32/include/spidermonkey/mozilla/ReverseIterator.h +++ /dev/null @@ -1,168 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* An iterator that acts like another iterator, but iterating in - * the negative direction. (Note that not all iterators can iterate - * in the negative direction.) */ - -#ifndef mozilla_ReverseIterator_h -#define mozilla_ReverseIterator_h - -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -template -class ReverseIterator -{ -public: - template - explicit ReverseIterator(Iterator aIter) - : mCurrent(aIter) { } - - template - MOZ_IMPLICIT ReverseIterator(const ReverseIterator& aOther) - : mCurrent(aOther.mCurrent) { } - - decltype(*DeclVal()) operator*() const - { - IteratorT tmp = mCurrent; - return *--tmp; - } - - /* Increments and decrements operators */ - - ReverseIterator& operator++() { --mCurrent; return *this; } - ReverseIterator& operator--() { ++mCurrent; return *this; } - ReverseIterator operator++(int) { auto ret = *this; mCurrent--; return ret; } - ReverseIterator operator--(int) { auto ret = *this; mCurrent++; return ret; } - - /* Comparison operators */ - - template - friend bool operator==(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator!=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator<(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator<=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator>(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - template - friend bool operator>=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2); - -private: - IteratorT mCurrent; -}; - -template -bool -operator==(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent == aIter2.mCurrent; -} - -template -bool -operator!=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent != aIter2.mCurrent; -} - -template -bool -operator<(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent > aIter2.mCurrent; -} - -template -bool -operator<=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent >= aIter2.mCurrent; -} - -template -bool -operator>(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent < aIter2.mCurrent; -} - -template -bool -operator>=(const ReverseIterator& aIter1, - const ReverseIterator& aIter2) -{ - return aIter1.mCurrent <= aIter2.mCurrent; -} - -namespace detail { - -template -class IteratorRange -{ -public: - typedef IteratorT iterator; - typedef IteratorT const_iterator; - typedef ReverseIterator reverse_iterator; - typedef ReverseIterator const_reverse_iterator; - - template - MOZ_IMPLICIT IteratorRange(Iterator1 aIterBegin, Iterator2 aIterEnd) - : mIterBegin(aIterBegin), mIterEnd(aIterEnd) { } - - template - MOZ_IMPLICIT IteratorRange(const IteratorRange& aOther) - : mIterBegin(aOther.mIterBegin), mIterEnd(aOther.mIterEnd) { } - - iterator begin() const { return mIterBegin; } - const_iterator cbegin() const { return begin(); } - iterator end() const { return mIterEnd; } - const_iterator cend() const { return end(); } - reverse_iterator rbegin() const { return reverse_iterator(mIterEnd); } - const_reverse_iterator crbegin() const { return rbegin(); } - reverse_iterator rend() const { return reverse_iterator(mIterBegin); } - const_reverse_iterator crend() const { return rend(); } - -private: - IteratorT mIterBegin; - IteratorT mIterEnd; -}; - -} // namespace detail - -template -detail::IteratorRange -Reversed(Range& aRange) -{ - return {aRange.rbegin(), aRange.rend()}; -} - -template -detail::IteratorRange -Reversed(const Range& aRange) -{ - return {aRange.rbegin(), aRange.rend()}; -} - -} // namespace mozilla - -#endif // mozilla_ReverseIterator_h diff --git a/win32/include/spidermonkey/mozilla/RollingMean.h b/win32/include/spidermonkey/mozilla/RollingMean.h deleted file mode 100755 index 8cc3148e..00000000 --- a/win32/include/spidermonkey/mozilla/RollingMean.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A set abstraction for enumeration values. */ - -#ifndef mozilla_RollingMean_h_ -#define mozilla_RollingMean_h_ - -#include "mozilla/Assertions.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Vector.h" - -#include - -namespace mozilla { - -/** - * RollingMean calculates a rolling mean of the values it is given. It - * accumulates the total as values are added and removed. The second type - * argument S specifies the type of the total. This may need to be a bigger - * type in order to maintain that the sum of all values in the average doesn't - * exceed the maximum input value. - * - * WARNING: Float types are not supported due to rounding errors. - */ -template -class RollingMean -{ -private: - size_t mInsertIndex; - size_t mMaxValues; - Vector mValues; - S mTotal; - -public: - static_assert(!IsFloatingPoint::value, - "floating-point types are unsupported due to rounding " - "errors"); - - explicit RollingMean(size_t aMaxValues) - : mInsertIndex(0), - mMaxValues(aMaxValues), - mTotal(0) - { - MOZ_ASSERT(aMaxValues > 0); - } - - RollingMean& operator=(RollingMean&& aOther) - { - MOZ_ASSERT(this != &aOther, "self-assignment is forbidden"); - this->~RollingMean(); - new(this) RollingMean(aOther.mMaxValues); - mInsertIndex = aOther.mInsertIndex; - mTotal = aOther.mTotal; - mValues.swap(aOther.mValues); - return *this; - } - - /** - * Insert a value into the rolling mean. - */ - bool insert(T aValue) - { - MOZ_ASSERT(mValues.length() <= mMaxValues); - - if (mValues.length() == mMaxValues) { - mTotal = mTotal - mValues[mInsertIndex] + aValue; - mValues[mInsertIndex] = aValue; - } else { - if (!mValues.append(aValue)) { - return false; - } - mTotal = mTotal + aValue; - } - - mInsertIndex = (mInsertIndex + 1) % mMaxValues; - return true; - } - - /** - * Calculate the rolling mean. - */ - T mean() - { - MOZ_ASSERT(!empty()); - return T(mTotal / int64_t(mValues.length())); - } - - bool empty() - { - return mValues.empty(); - } - - /** - * Remove all values from the rolling mean. - */ - void clear() - { - mValues.clear(); - mInsertIndex = 0; - mTotal = T(0); - } - - size_t maxValues() - { - return mMaxValues; - } -}; - -} // namespace mozilla - -#endif // mozilla_RollingMean_h_ diff --git a/win32/include/spidermonkey/mozilla/SHA1.h b/win32/include/spidermonkey/mozilla/SHA1.h deleted file mode 100755 index ddccaa67..00000000 --- a/win32/include/spidermonkey/mozilla/SHA1.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Simple class for computing SHA1. */ - -#ifndef mozilla_SHA1_h -#define mozilla_SHA1_h - -#include "mozilla/Types.h" - -#include -#include - -namespace mozilla { - -/** - * This class computes the SHA1 hash of a byte sequence, or of the concatenation - * of multiple sequences. For example, computing the SHA1 of two sequences of - * bytes could be done as follows: - * - * void SHA1(const uint8_t* buf1, uint32_t size1, - * const uint8_t* buf2, uint32_t size2, - * SHA1Sum::Hash& hash) - * { - * SHA1Sum s; - * s.update(buf1, size1); - * s.update(buf2, size2); - * s.finish(hash); - * } - * - * The finish method may only be called once and cannot be followed by calls - * to update. - */ -class SHA1Sum -{ - union - { - uint32_t mW[16]; /* input buffer */ - uint8_t mB[64]; - } mU; - uint64_t mSize; /* count of hashed bytes. */ - unsigned mH[22]; /* 5 state variables, 16 tmp values, 1 extra */ - bool mDone; - -public: - MFBT_API SHA1Sum(); - - static const size_t kHashSize = 20; - typedef uint8_t Hash[kHashSize]; - - /* Add len bytes of dataIn to the data sequence being hashed. */ - MFBT_API void update(const void* aData, uint32_t aLength); - - /* Compute the final hash of all data into hashOut. */ - MFBT_API void finish(SHA1Sum::Hash& aHashOut); -}; - -} /* namespace mozilla */ - -#endif /* mozilla_SHA1_h */ diff --git a/win32/include/spidermonkey/mozilla/Saturate.h b/win32/include/spidermonkey/mozilla/Saturate.h deleted file mode 100755 index b79364d2..00000000 --- a/win32/include/spidermonkey/mozilla/Saturate.h +++ /dev/null @@ -1,288 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Provides saturation arithmetics for scalar types. */ - -#ifndef mozilla_Saturate_h -#define mozilla_Saturate_h - -#include "mozilla/Attributes.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include - -namespace mozilla { -namespace detail { - -/** - * |SaturateOp| wraps scalar values for saturation arithmetics. Usage: - * - * uint32_t value = 1; - * - * ++SaturateOp(value); // value is 2 - * --SaturateOp(value); // value is 1 - * --SaturateOp(value); // value is 0 - * --SaturateOp(value); // value is still 0 - * - * Please add new operators when required. - * - * |SaturateOp| will saturate at the minimum and maximum values of - * type T. If you need other bounds, implement a clamped-type class and - * specialize the type traits accordingly. - */ -template -class SaturateOp -{ -public: - explicit SaturateOp(T& aValue) - : mValue(aValue) - { - // We should actually check for |std::is_scalar::value| to be - // true, but this type trait is not available everywhere. Relax - // this assertion if you want to use floating point values as well. - static_assert(IsIntegral::value, - "Integral type required in instantiation"); - } - - // Add and subtract operators - - T operator+(const T& aRhs) const - { - return T(mValue) += aRhs; - } - - T operator-(const T& aRhs) const - { - return T(mValue) -= aRhs; - } - - // Compound operators - - const T& operator+=(const T& aRhs) const - { - const T min = std::numeric_limits::min(); - const T max = std::numeric_limits::max(); - - if (aRhs > static_cast(0)) { - mValue = (max - aRhs) < mValue ? max : mValue + aRhs; - } else { - mValue = (min - aRhs) > mValue ? min : mValue + aRhs; - } - return mValue; - } - - const T& operator-=(const T& aRhs) const - { - const T min = std::numeric_limits::min(); - const T max = std::numeric_limits::max(); - - if (aRhs > static_cast(0)) { - mValue = (min + aRhs) > mValue ? min : mValue - aRhs; - } else { - mValue = (max + aRhs) < mValue ? max : mValue - aRhs; - } - return mValue; - } - - // Increment and decrement operators - - const T& operator++() const // prefix - { - return operator+=(static_cast(1)); - } - - T operator++(int) const // postfix - { - const T value(mValue); - operator++(); - return value; - } - - const T& operator--() const // prefix - { - return operator-=(static_cast(1)); - } - - T operator--(int) const // postfix - { - const T value(mValue); - operator--(); - return value; - } - -private: - SaturateOp(const SaturateOp&) = delete; - SaturateOp(SaturateOp&&) = delete; - SaturateOp& operator=(const SaturateOp&) = delete; - SaturateOp& operator=(SaturateOp&&) = delete; - - T& mValue; -}; - -/** - * |Saturate| is a value type for saturation arithmetics. It's - * build on top of |SaturateOp|. - */ -template -class Saturate -{ -public: - Saturate() = default; - MOZ_IMPLICIT Saturate(const Saturate&) = default; - - MOZ_IMPLICIT Saturate(Saturate&& aValue) - { - mValue = Move(aValue.mValue); - } - - explicit Saturate(const T& aValue) - : mValue(aValue) - { } - - const T& value() const - { - return mValue; - } - - // Compare operators - - bool operator==(const Saturate& aRhs) const - { - return mValue == aRhs.mValue; - } - - bool operator!=(const Saturate& aRhs) const - { - return !operator==(aRhs); - } - - bool operator==(const T& aRhs) const - { - return mValue == aRhs; - } - - bool operator!=(const T& aRhs) const - { - return !operator==(aRhs); - } - - // Assignment operators - - Saturate& operator=(const Saturate&) = default; - - Saturate& operator=(Saturate&& aRhs) - { - mValue = Move(aRhs.mValue); - return *this; - } - - // Add and subtract operators - - Saturate operator+(const Saturate& aRhs) const - { - Saturate lhs(mValue); - return lhs += aRhs.mValue; - } - - Saturate operator+(const T& aRhs) const - { - Saturate lhs(mValue); - return lhs += aRhs; - } - - Saturate operator-(const Saturate& aRhs) const - { - Saturate lhs(mValue); - return lhs -= aRhs.mValue; - } - - Saturate operator-(const T& aRhs) const - { - Saturate lhs(mValue); - return lhs -= aRhs; - } - - // Compound operators - - Saturate& operator+=(const Saturate& aRhs) - { - SaturateOp(mValue) += aRhs.mValue; - return *this; - } - - Saturate& operator+=(const T& aRhs) - { - SaturateOp(mValue) += aRhs; - return *this; - } - - Saturate& operator-=(const Saturate& aRhs) - { - SaturateOp(mValue) -= aRhs.mValue; - return *this; - } - - Saturate& operator-=(const T& aRhs) - { - SaturateOp(mValue) -= aRhs; - return *this; - } - - // Increment and decrement operators - - Saturate& operator++() // prefix - { - ++SaturateOp(mValue); - return *this; - } - - Saturate operator++(int) // postfix - { - return Saturate(SaturateOp(mValue)++); - } - - Saturate& operator--() // prefix - { - --SaturateOp(mValue); - return *this; - } - - Saturate operator--(int) // postfix - { - return Saturate(SaturateOp(mValue)--); - } - -private: - T mValue; -}; - -} // namespace detail - -typedef detail::Saturate SaturateInt8; -typedef detail::Saturate SaturateInt16; -typedef detail::Saturate SaturateInt32; -typedef detail::Saturate SaturateUint8; -typedef detail::Saturate SaturateUint16; -typedef detail::Saturate SaturateUint32; - -} // namespace mozilla - -template -bool -operator==(LhsT aLhs, const mozilla::detail::Saturate& aRhs) -{ - return aRhs.operator==(static_cast(aLhs)); -} - -template -bool -operator!=(LhsT aLhs, const mozilla::detail::Saturate& aRhs) -{ - return !(aLhs == aRhs); -} - -#endif // mozilla_Saturate_h diff --git a/win32/include/spidermonkey/mozilla/ScopeExit.h b/win32/include/spidermonkey/mozilla/ScopeExit.h deleted file mode 100755 index 7aff82d8..00000000 --- a/win32/include/spidermonkey/mozilla/ScopeExit.h +++ /dev/null @@ -1,135 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* RAII class for executing arbitrary actions at scope end. */ - -#ifndef mozilla_ScopeExit_h -#define mozilla_ScopeExit_h - -/* - * See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189.pdf for a - * standards-track version of this. - * - * Error handling can be complex when various actions need to be performed that - * need to be undone if an error occurs midway. This can be handled with a - * collection of boolean state variables and gotos, which can get clunky and - * error-prone: - * - * { - * if (!a.setup()) - * goto fail; - * isASetup = true; - * - * if (!b.setup()) - * goto fail; - * isBSetup = true; - * - * ... - * return true; - * - * fail: - * if (isASetup) - * a.teardown(); - * if (isBSetup) - * b.teardown(); - * return false; - * } - * - * ScopeExit is a mechanism to simplify this pattern by keeping an RAII guard - * class that will perform the teardown on destruction, unless released. So the - * above would become: - * - * { - * if (!a.setup()) { - * return false; - * } - * auto guardA = MakeScopeExit([&] { - * a.teardown(); - * }); - * - * if (!b.setup()) { - * return false; - * } - * auto guardB = MakeScopeExit([&] { - * b.teardown(); - * }); - * - * ... - * guardA.release(); - * guardB.release(); - * return true; - * } - * - * This header provides: - * - * - |ScopeExit| - a container for a cleanup call, automically called at the - * end of the scope; - * - |MakeScopeExit| - a convenience function for constructing a |ScopeExit| - * with a given cleanup routine, commonly used with a lambda function. - * - * Note that the RAII classes defined in this header do _not_ perform any form - * of reference-counting or garbage-collection. These classes have exactly two - * behaviors: - * - * - if |release()| has not been called, the cleanup is always performed at - * the end of the scope; - * - if |release()| has been called, nothing will happen at the end of the - * scope. - */ - -#include "mozilla/GuardObjects.h" -#include "mozilla/Move.h" - -namespace mozilla { - -template -class MOZ_STACK_CLASS ScopeExit { - ExitFunction mExitFunction; - bool mExecuteOnDestruction; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - -public: - explicit ScopeExit(ExitFunction&& cleanup - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mExitFunction(cleanup) - , mExecuteOnDestruction(true) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - ScopeExit(ScopeExit&& rhs) - : mExitFunction(mozilla::Move(rhs.mExitFunction)) - , mExecuteOnDestruction(rhs.mExecuteOnDestruction) - { - rhs.release(); - } - - ~ScopeExit() { - if (mExecuteOnDestruction) { - mExitFunction(); - } - } - - void release() { - mExecuteOnDestruction = false; - } - -private: - explicit ScopeExit(const ScopeExit&) = delete; - ScopeExit& operator=(const ScopeExit&) = delete; - ScopeExit& operator=(ScopeExit&&) = delete; -}; - -template -ScopeExit -MakeScopeExit(ExitFunction&& exitFunction) -{ - return ScopeExit(mozilla::Move(exitFunction)); -} - -} /* namespace mozilla */ - -#endif /* mozilla_ScopeExit_h */ diff --git a/win32/include/spidermonkey/mozilla/Scoped.h b/win32/include/spidermonkey/mozilla/Scoped.h deleted file mode 100755 index c935434a..00000000 --- a/win32/include/spidermonkey/mozilla/Scoped.h +++ /dev/null @@ -1,255 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* DEPRECATED: Use UniquePtr.h instead. */ - -#ifndef mozilla_Scoped_h -#define mozilla_Scoped_h - -/* - * DEPRECATED: Use UniquePtr.h instead. - * - * Resource Acquisition Is Initialization is a programming idiom used - * to write robust code that is able to deallocate resources properly, - * even in presence of execution errors or exceptions that need to be - * propagated. The Scoped* classes defined via the |SCOPED_TEMPLATE| - * and |MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLTE| macros perform the - * deallocation of the resource they hold once program execution - * reaches the end of the scope for which they have been defined. - * These macros have been used to automatically close file - * descriptors/file handles when reaching the end of the scope, - * graphics contexts, etc. - * - * The general scenario for RAII classes created by the above macros - * is the following: - * - * ScopedClass foo(create_value()); - * // ... In this scope, |foo| is defined. Use |foo.get()| or |foo.rwget()| - * to access the value. - * // ... In case of |return| or |throw|, |foo| is deallocated automatically. - * // ... If |foo| needs to be returned or stored, use |foo.forget()| - * - * Note that the RAII classes defined in this header do _not_ perform any form - * of reference-counting or garbage-collection. These classes have exactly two - * behaviors: - * - * - if |forget()| has not been called, the resource is always deallocated at - * the end of the scope; - * - if |forget()| has been called, any control on the resource is unbound - * and the resource is not deallocated by the class. - */ - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/GuardObjects.h" -#include "mozilla/Move.h" - -namespace mozilla { - -/* - * Scoped is a helper to create RAII wrappers - * Type argument |Traits| is expected to have the following structure: - * - * struct Traits - * { - * // Define the type of the value stored in the wrapper - * typedef value_type type; - * // Returns the value corresponding to the uninitialized or freed state - * const static type empty(); - * // Release resources corresponding to the wrapped value - * // This function is responsible for not releasing an |empty| value - * const static void release(type); - * } - */ -template -class MOZ_NON_TEMPORARY_CLASS Scoped -{ -public: - typedef typename Traits::type Resource; - - explicit Scoped(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) - : mValue(Traits::empty()) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - explicit Scoped(const Resource& aValue - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mValue(aValue) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - } - - /* Move constructor. */ - Scoped(Scoped&& aOther - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : mValue(Move(aOther.mValue)) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - aOther.mValue = Traits::empty(); - } - - ~Scoped() { Traits::release(mValue); } - - // Constant getter - operator const Resource&() const { return mValue; } - const Resource& operator->() const { return mValue; } - const Resource& get() const { return mValue; } - // Non-constant getter. - Resource& rwget() { return mValue; } - - /* - * Forget the resource. - * - * Once |forget| has been called, the |Scoped| is neutralized, i.e. it will - * have no effect at destruction (unless it is reset to another resource by - * |operator=|). - * - * @return The original resource. - */ - Resource forget() - { - Resource tmp = mValue; - mValue = Traits::empty(); - return tmp; - } - - /* - * Perform immediate clean-up of this |Scoped|. - * - * If this |Scoped| is currently empty, this method has no effect. - */ - void dispose() - { - Traits::release(mValue); - mValue = Traits::empty(); - } - - bool operator==(const Resource& aOther) const { return mValue == aOther; } - - /* - * Replace the resource with another resource. - * - * Calling |operator=| has the side-effect of triggering clean-up. If you do - * not want to trigger clean-up, you should first invoke |forget|. - * - * @return this - */ - Scoped& operator=(const Resource& aOther) { return reset(aOther); } - - Scoped& reset(const Resource& aOther) - { - Traits::release(mValue); - mValue = aOther; - return *this; - } - - /* Move assignment operator. */ - Scoped& operator=(Scoped&& aRhs) - { - MOZ_ASSERT(&aRhs != this, "self-move-assignment not allowed"); - this->~Scoped(); - new(this) Scoped(Move(aRhs)); - return *this; - } - -private: - explicit Scoped(const Scoped& aValue) = delete; - Scoped& operator=(const Scoped& aValue) = delete; - -private: - Resource mValue; - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER -}; - -/* - * SCOPED_TEMPLATE defines a templated class derived from Scoped - * This allows to implement templates such as ScopedFreePtr. - * - * @param name The name of the class to define. - * @param Traits A struct implementing clean-up. See the implementations - * for more details. - */ -#define SCOPED_TEMPLATE(name, Traits) \ -template \ -struct MOZ_NON_TEMPORARY_CLASS name : public mozilla::Scoped > \ -{ \ - typedef mozilla::Scoped > Super; \ - typedef typename Super::Resource Resource; \ - name& operator=(Resource aRhs) \ - { \ - Super::operator=(aRhs); \ - return *this; \ - } \ - name& operator=(name&& aRhs) \ - { \ - Super::operator=(Move(aRhs)); \ - return *this; \ - } \ - explicit name(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) \ - : Super(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT) \ - {} \ - explicit name(Resource aRhs \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) \ - : Super(aRhs \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT) \ - {} \ - name(name&& aRhs \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) \ - : Super(Move(aRhs) \ - MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT) \ - {} \ -private: \ - explicit name(name&) = delete; \ - name& operator=(name&) = delete; \ -}; - -/* - * MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE makes it easy to create scoped - * pointers for types with custom deleters; just overload - * TypeSpecificDelete(T*) in the same namespace as T to call the deleter for - * type T. - * - * @param name The name of the class to define. - * @param Type A struct implementing clean-up. See the implementations - * for more details. - * *param Deleter The function that is used to delete/destroy/free a - * non-null value of Type*. - * - * Example: - * - * MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPRFileDesc, PRFileDesc, \ - * PR_Close) - * ... - * { - * ScopedPRFileDesc file(PR_OpenFile(...)); - * ... - * } // file is closed with PR_Close here - */ -#define MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(name, Type, Deleter) \ -template <> inline void TypeSpecificDelete(Type* aValue) { Deleter(aValue); } \ -typedef ::mozilla::TypeSpecificScopedPointer name; - -template void TypeSpecificDelete(T* aValue); - -template -struct TypeSpecificScopedPointerTraits -{ - typedef T* type; - static type empty() { return nullptr; } - static void release(type aValue) - { - if (aValue) { - TypeSpecificDelete(aValue); - } - } -}; - -SCOPED_TEMPLATE(TypeSpecificScopedPointer, TypeSpecificScopedPointerTraits) - -} /* namespace mozilla */ - -#endif /* mozilla_Scoped_h */ diff --git a/win32/include/spidermonkey/mozilla/SegmentedVector.h b/win32/include/spidermonkey/mozilla/SegmentedVector.h deleted file mode 100755 index 1bf60e46..00000000 --- a/win32/include/spidermonkey/mozilla/SegmentedVector.h +++ /dev/null @@ -1,339 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// A simple segmented vector class. -// -// This class should be used in preference to mozilla::Vector or nsTArray when -// you are simply gathering items in order to later iterate over them. -// -// - In the case where you don't know the final size in advance, using -// SegmentedVector avoids the need to repeatedly allocate increasingly large -// buffers and copy the data into them. -// -// - In the case where you know the final size in advance and so can set the -// capacity appropriately, using SegmentedVector still avoids the need for -// large allocations (which can trigger OOMs). - -#ifndef mozilla_SegmentedVector_h -#define mozilla_SegmentedVector_h - -#include "mozilla/Alignment.h" -#include "mozilla/AllocPolicy.h" -#include "mozilla/Array.h" -#include "mozilla/LinkedList.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#include // for placement new - -namespace mozilla { - -// |IdealSegmentSize| specifies how big each segment will be in bytes (or as -// close as is possible). Use the following guidelines to choose a size. -// -// - It should be a power-of-two, to avoid slop. -// -// - It should not be too small, so that segment allocations are infrequent, -// and so that per-segment bookkeeping overhead is low. Typically each -// segment should be able to hold hundreds of elements, at least. -// -// - It should not be too large, so that OOMs are unlikely when allocating -// segments, and so that not too much space is wasted when the final segment -// is not full. -// -// The ideal size depends on how the SegmentedVector is used and the size of -// |T|, but reasonable sizes include 1024, 4096 (the default), 8192, and 16384. -// -template -class SegmentedVector : private AllocPolicy -{ - template - struct SegmentImpl - : public mozilla::LinkedListElement> - { - SegmentImpl() : mLength(0) {} - - ~SegmentImpl() - { - for (uint32_t i = 0; i < mLength; i++) { - (*this)[i].~T(); - } - } - - uint32_t Length() const { return mLength; } - - T* Elems() { return reinterpret_cast(&mStorage.mBuf); } - - T& operator[](size_t aIndex) - { - MOZ_ASSERT(aIndex < mLength); - return Elems()[aIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(aIndex < mLength); - return Elems()[aIndex]; - } - - template - void Append(U&& aU) - { - MOZ_ASSERT(mLength < SegmentCapacity); - // Pre-increment mLength so that the bounds-check in operator[] passes. - mLength++; - T* elem = &(*this)[mLength - 1]; - new (elem) T(mozilla::Forward(aU)); - } - - void PopLast() - { - MOZ_ASSERT(mLength > 0); - (*this)[mLength - 1].~T(); - mLength--; - } - - uint32_t mLength; - - // The union ensures that the elements are appropriately aligned. - union Storage - { - char mBuf[sizeof(T) * SegmentCapacity]; - mozilla::AlignedElem mAlign; - } mStorage; - - static_assert(MOZ_ALIGNOF(T) == MOZ_ALIGNOF(Storage), - "SegmentedVector provides incorrect alignment"); - }; - - // See how many we elements we can fit in a segment of IdealSegmentSize. If - // IdealSegmentSize is too small, it'll be just one. The +1 is because - // kSingleElementSegmentSize already accounts for one element. - static const size_t kSingleElementSegmentSize = sizeof(SegmentImpl<1>); - static const size_t kSegmentCapacity = - kSingleElementSegmentSize <= IdealSegmentSize - ? (IdealSegmentSize - kSingleElementSegmentSize) / sizeof(T) + 1 - : 1; - - typedef SegmentImpl Segment; - -public: - // The |aIdealSegmentSize| is only for sanity checking. If it's specified, we - // check that the actual segment size is as close as possible to it. This - // serves as a sanity check for SegmentedVectorCapacity's capacity - // computation. - explicit SegmentedVector(size_t aIdealSegmentSize = 0) - { - // The difference between the actual segment size and the ideal segment - // size should be less than the size of a single element... unless the - // ideal size was too small, in which case the capacity should be one. - MOZ_ASSERT_IF( - aIdealSegmentSize != 0, - (sizeof(Segment) > aIdealSegmentSize && kSegmentCapacity == 1) || - aIdealSegmentSize - sizeof(Segment) < sizeof(T)); - } - - ~SegmentedVector() { Clear(); } - - bool IsEmpty() const { return !mSegments.getFirst(); } - - // Note that this is O(n) rather than O(1), but the constant factor is very - // small because it only has to do one addition per segment. - size_t Length() const - { - size_t n = 0; - for (auto segment = mSegments.getFirst(); - segment; - segment = segment->getNext()) { - n += segment->Length(); - } - return n; - } - - // Returns false if the allocation failed. (If you are using an infallible - // allocation policy, use InfallibleAppend() instead.) - template - MOZ_MUST_USE bool Append(U&& aU) - { - Segment* last = mSegments.getLast(); - if (!last || last->Length() == kSegmentCapacity) { - last = this->template pod_malloc(1); - if (!last) { - return false; - } - new (last) Segment(); - mSegments.insertBack(last); - } - last->Append(mozilla::Forward(aU)); - return true; - } - - // You should probably only use this instead of Append() if you are using an - // infallible allocation policy. It will crash if the allocation fails. - template - void InfallibleAppend(U&& aU) - { - bool ok = Append(mozilla::Forward(aU)); - MOZ_RELEASE_ASSERT(ok); - } - - void Clear() - { - Segment* segment; - while ((segment = mSegments.popFirst())) { - segment->~Segment(); - this->free_(segment); - } - } - - T& GetLast() - { - MOZ_ASSERT(!IsEmpty()); - Segment* last = mSegments.getLast(); - return (*last)[last->Length() - 1]; - } - - const T& GetLast() const - { - MOZ_ASSERT(!IsEmpty()); - Segment* last = mSegments.getLast(); - return (*last)[last->Length() - 1]; - } - - void PopLast() - { - MOZ_ASSERT(!IsEmpty()); - Segment* last = mSegments.getLast(); - last->PopLast(); - if (!last->Length()) { - mSegments.popLast(); - last->~Segment(); - this->free_(last); - } - } - - // Equivalent to calling |PopLast| |aNumElements| times, but potentially - // more efficient. - void PopLastN(uint32_t aNumElements) - { - MOZ_ASSERT(aNumElements <= Length()); - - Segment* last; - - // Pop full segments for as long as we can. Note that this loop - // cleanly handles the case when the initial last segment is not - // full and we are popping more elements than said segment contains. - do { - last = mSegments.getLast(); - - // The list is empty. We're all done. - if (!last) { - return; - } - - // Check to see if the list contains too many elements. Handle - // that in the epilogue. - uint32_t segmentLen = last->Length(); - if (segmentLen > aNumElements) { - break; - } - - // Destroying the segment destroys all elements contained therein. - mSegments.popLast(); - last->~Segment(); - this->free_(last); - - MOZ_ASSERT(aNumElements >= segmentLen); - aNumElements -= segmentLen; - if (aNumElements == 0) { - return; - } - } while (true); - - // Handle the case where the last segment contains more elements - // than we want to pop. - MOZ_ASSERT(last); - MOZ_ASSERT(last == mSegments.getLast()); - MOZ_ASSERT(aNumElements != 0); - MOZ_ASSERT(aNumElements < last->Length()); - for (uint32_t i = 0; i < aNumElements; ++i) { - last->PopLast(); - } - MOZ_ASSERT(last->Length() != 0); - } - - // Use this class to iterate over a SegmentedVector, like so: - // - // for (auto iter = v.Iter(); !iter.Done(); iter.Next()) { - // MyElem& elem = iter.Get(); - // f(elem); - // } - // - class IterImpl - { - friend class SegmentedVector; - - Segment* mSegment; - size_t mIndex; - - explicit IterImpl(SegmentedVector* aVector) - : mSegment(aVector->mSegments.getFirst()) - , mIndex(0) - {} - - public: - bool Done() const { return !mSegment; } - - T& Get() - { - MOZ_ASSERT(!Done()); - return (*mSegment)[mIndex]; - } - - const T& Get() const - { - MOZ_ASSERT(!Done()); - return (*mSegment)[mIndex]; - } - - void Next() - { - MOZ_ASSERT(!Done()); - mIndex++; - if (mIndex == mSegment->Length()) { - mSegment = mSegment->getNext(); - mIndex = 0; - } - } - }; - - IterImpl Iter() { return IterImpl(this); } - - // Measure the memory consumption of the vector excluding |this|. Note that - // it only measures the vector itself. If the vector elements contain - // pointers to other memory blocks, those blocks must be measured separately - // during a subsequent iteration over the vector. - size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const - { - return mSegments.sizeOfExcludingThis(aMallocSizeOf); - } - - // Like sizeOfExcludingThis(), but measures |this| as well. - size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const - { - return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf); - } - -private: - mozilla::LinkedList mSegments; -}; - -} // namespace mozilla - -#endif /* mozilla_SegmentedVector_h */ diff --git a/win32/include/spidermonkey/mozilla/SizePrintfMacros.h b/win32/include/spidermonkey/mozilla/SizePrintfMacros.h deleted file mode 100755 index ec55c62c..00000000 --- a/win32/include/spidermonkey/mozilla/SizePrintfMacros.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Implements (nonstandard) PRI{ouxX}SIZE format macros for size_t types. */ - -#ifndef mozilla_SizePrintfMacros_h_ -#define mozilla_SizePrintfMacros_h_ - -/* - * MSVC's libc does not support C99's %z format length modifier for size_t - * types. Instead, we use Microsoft's nonstandard %I modifier for size_t, which - * is unsigned __int32 on 32-bit platforms and unsigned __int64 on 64-bit - * platforms: - * - * http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx - */ - -#if defined(XP_WIN) -# define PRIoSIZE "Io" -# define PRIuSIZE "Iu" -# define PRIxSIZE "Ix" -# define PRIXSIZE "IX" -#else -# define PRIoSIZE "zo" -# define PRIuSIZE "zu" -# define PRIxSIZE "zx" -# define PRIXSIZE "zX" -#endif - -#endif /* mozilla_SizePrintfMacros_h_ */ diff --git a/win32/include/spidermonkey/mozilla/SplayTree.h b/win32/include/spidermonkey/mozilla/SplayTree.h deleted file mode 100755 index 2b3b838b..00000000 --- a/win32/include/spidermonkey/mozilla/SplayTree.h +++ /dev/null @@ -1,330 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/** - * A sorted tree with optimal access times, where recently-accessed elements - * are faster to access again. - */ - -#ifndef mozilla_SplayTree_h -#define mozilla_SplayTree_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -namespace mozilla { - -template -class SplayTree; - -template -class SplayTreeNode -{ -public: - template - friend class SplayTree; - - SplayTreeNode() - : mLeft(nullptr) - , mRight(nullptr) - , mParent(nullptr) - {} - -private: - T* mLeft; - T* mRight; - T* mParent; -}; - - -/** - * Class which represents a splay tree. - * Splay trees are balanced binary search trees for which search, insert and - * remove are all amortized O(log n), but where accessing a node makes it - * faster to access that node in the future. - * - * T indicates the type of tree elements, Comparator must have a static - * compare(const T&, const T&) method ordering the elements. The compare - * method must be free from side effects. - */ -template -class SplayTree -{ - T* mRoot; - -public: - constexpr SplayTree() - : mRoot(nullptr) - {} - - bool empty() const - { - return !mRoot; - } - - T* find(const T& aValue) - { - if (empty()) { - return nullptr; - } - - T* last = lookup(aValue); - splay(last); - return Comparator::compare(aValue, *last) == 0 ? last : nullptr; - } - - void insert(T* aValue) - { - MOZ_ASSERT(!find(*aValue), "Duplicate elements are not allowed."); - - if (!mRoot) { - mRoot = aValue; - return; - } - T* last = lookup(*aValue); - int cmp = Comparator::compare(*aValue, *last); - - finishInsertion(last, cmp, aValue); - return; - } - - T* findOrInsert(const T& aValue); - - T* remove(const T& aValue) - { - T* last = lookup(aValue); - MOZ_ASSERT(last, "This tree must contain the element being removed."); - MOZ_ASSERT(Comparator::compare(aValue, *last) == 0); - - // Splay the tree so that the item to remove is the root. - splay(last); - MOZ_ASSERT(last == mRoot); - - // Find another node which can be swapped in for the root: either the - // rightmost child of the root's left, or the leftmost child of the - // root's right. - T* swap; - T* swapChild; - if (mRoot->mLeft) { - swap = mRoot->mLeft; - while (swap->mRight) { - swap = swap->mRight; - } - swapChild = swap->mLeft; - } else if (mRoot->mRight) { - swap = mRoot->mRight; - while (swap->mLeft) { - swap = swap->mLeft; - } - swapChild = swap->mRight; - } else { - T* result = mRoot; - mRoot = nullptr; - return result; - } - - // The selected node has at most one child, in swapChild. Detach it - // from the subtree by replacing it with that child. - if (swap == swap->mParent->mLeft) { - swap->mParent->mLeft = swapChild; - } else { - swap->mParent->mRight = swapChild; - } - if (swapChild) { - swapChild->mParent = swap->mParent; - } - - // Make the selected node the new root. - mRoot = swap; - mRoot->mParent = nullptr; - mRoot->mLeft = last->mLeft; - mRoot->mRight = last->mRight; - if (mRoot->mLeft) { - mRoot->mLeft->mParent = mRoot; - } - if (mRoot->mRight) { - mRoot->mRight->mParent = mRoot; - } - - return last; - } - - T* removeMin() - { - MOZ_ASSERT(mRoot, "No min to remove!"); - - T* min = mRoot; - while (min->mLeft) { - min = min->mLeft; - } - return remove(*min); - } - - // For testing purposes only. - void checkCoherency() - { - checkCoherency(mRoot, nullptr); - } - -private: - /** - * Returns the node in this comparing equal to |aValue|, or a node just - * greater or just less than |aValue| if there is no such node. - */ - T* lookup(const T& aValue) - { - MOZ_ASSERT(!empty()); - - T* node = mRoot; - T* parent; - do { - parent = node; - int c = Comparator::compare(aValue, *node); - if (c == 0) { - return node; - } else if (c < 0) { - node = node->mLeft; - } else { - node = node->mRight; - } - } while (node); - return parent; - } - - void finishInsertion(T* aLast, int32_t aCmp, T* aNew) - { - MOZ_ASSERT(aCmp, "Nodes shouldn't be equal!"); - - T** parentPointer = (aCmp < 0) ? &aLast->mLeft : &aLast->mRight; - MOZ_ASSERT(!*parentPointer); - *parentPointer = aNew; - aNew->mParent = aLast; - - splay(aNew); - } - - /** - * Rotate the tree until |node| is at the root of the tree. Performing - * the rotations in this fashion preserves the amortized balancing of - * the tree. - */ - void splay(T* aNode) - { - MOZ_ASSERT(aNode); - - while (aNode != mRoot) { - T* parent = aNode->mParent; - if (parent == mRoot) { - // Zig rotation. - rotate(aNode); - MOZ_ASSERT(aNode == mRoot); - return; - } - T* grandparent = parent->mParent; - if ((parent->mLeft == aNode) == (grandparent->mLeft == parent)) { - // Zig-zig rotation. - rotate(parent); - rotate(aNode); - } else { - // Zig-zag rotation. - rotate(aNode); - rotate(aNode); - } - } - } - - void rotate(T* aNode) - { - // Rearrange nodes so that aNode becomes the parent of its current - // parent, while preserving the sortedness of the tree. - T* parent = aNode->mParent; - if (parent->mLeft == aNode) { - // x y - // y c ==> a x - // a b b c - parent->mLeft = aNode->mRight; - if (aNode->mRight) { - aNode->mRight->mParent = parent; - } - aNode->mRight = parent; - } else { - MOZ_ASSERT(parent->mRight == aNode); - // x y - // a y ==> x c - // b c a b - parent->mRight = aNode->mLeft; - if (aNode->mLeft) { - aNode->mLeft->mParent = parent; - } - aNode->mLeft = parent; - } - aNode->mParent = parent->mParent; - parent->mParent = aNode; - if (T* grandparent = aNode->mParent) { - if (grandparent->mLeft == parent) { - grandparent->mLeft = aNode; - } else { - grandparent->mRight = aNode; - } - } else { - mRoot = aNode; - } - } - - T* checkCoherency(T* aNode, T* aMinimum) - { - if (mRoot) { - MOZ_RELEASE_ASSERT(!mRoot->mParent); - } - if (!aNode) { - MOZ_RELEASE_ASSERT(!mRoot); - return nullptr; - } - if (!aNode->mParent) { - MOZ_RELEASE_ASSERT(aNode == mRoot); - } - if (aMinimum) { - MOZ_RELEASE_ASSERT(Comparator::compare(*aMinimum, *aNode) < 0); - } - if (aNode->mLeft) { - MOZ_RELEASE_ASSERT(aNode->mLeft->mParent == aNode); - T* leftMaximum = checkCoherency(aNode->mLeft, aMinimum); - MOZ_RELEASE_ASSERT(Comparator::compare(*leftMaximum, *aNode) < 0); - } - if (aNode->mRight) { - MOZ_RELEASE_ASSERT(aNode->mRight->mParent == aNode); - return checkCoherency(aNode->mRight, aNode); - } - return aNode; - } - - SplayTree(const SplayTree&) = delete; - void operator=(const SplayTree&) = delete; -}; - -template -T* -SplayTree::findOrInsert(const T& aValue) -{ - if (!mRoot) { - mRoot = new T(aValue); - return mRoot; - } - - T* last = lookup(aValue); - int cmp = Comparator::compare(aValue, *last); - if (!cmp) { - return last; - } - - T* t = new T(aValue); - finishInsertion(last, cmp, t); - return t; -} - -} /* namespace mozilla */ - -#endif /* mozilla_SplayTree_h */ diff --git a/win32/include/spidermonkey/mozilla/Sprintf.h b/win32/include/spidermonkey/mozilla/Sprintf.h deleted file mode 100755 index e0be271e..00000000 --- a/win32/include/spidermonkey/mozilla/Sprintf.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Provides a safer sprintf for printing to fixed-size character arrays. */ - -#ifndef mozilla_Sprintf_h_ -#define mozilla_Sprintf_h_ - -#include -#include - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" - -#ifdef __cplusplus - -template -int VsprintfLiteral(char (&buffer)[N], const char* format, va_list args) -{ - MOZ_ASSERT(format != buffer); - int result = vsnprintf(buffer, N, format, args); - buffer[N - 1] = '\0'; - return result; -} - -template -MOZ_FORMAT_PRINTF(2, 3) -int SprintfLiteral(char (&buffer)[N], const char* format, ...) -{ - va_list args; - va_start(args, format); - int result = VsprintfLiteral(buffer, format, args); - va_end(args); - return result; -} - -#endif -#endif /* mozilla_Sprintf_h_ */ diff --git a/win32/include/spidermonkey/mozilla/StackWalk.h b/win32/include/spidermonkey/mozilla/StackWalk.h deleted file mode 100755 index 534c0bd8..00000000 --- a/win32/include/spidermonkey/mozilla/StackWalk.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* API for getting a stack trace of the C/C++ stack on the current thread */ - -#ifndef mozilla_StackWalk_h -#define mozilla_StackWalk_h - -/* WARNING: This file is intended to be included from C or C++ files. */ - -#include "mozilla/Types.h" -#include - -/** - * The callback for MozStackWalk. - * - * @param aFrameNumber The frame number (starts at 1, not 0). - * @param aPC The program counter value. - * @param aSP The best approximation possible of what the stack - * pointer will be pointing to when the execution returns - * to executing that at aPC. If no approximation can - * be made it will be nullptr. - * @param aClosure Extra data passed in via MozStackWalk(). - */ -typedef void -(*MozWalkStackCallback)(uint32_t aFrameNumber, void* aPC, void* aSP, - void* aClosure); - -/** - * Call aCallback for the C/C++ stack frames on the current thread, from - * the caller of MozStackWalk to main (or above). - * - * @param aCallback Callback function, called once per frame. - * @param aSkipFrames Number of initial frames to skip. 0 means that - * the first callback will be for the caller of - * MozStackWalk. - * @param aMaxFrames Maximum number of frames to trace. 0 means no limit. - * @param aClosure Caller-supplied data passed through to aCallback. - * @param aThread The thread for which the stack is to be retrieved. - * Passing null causes us to walk the stack of the - * current thread. On Windows, this is a thread HANDLE. - * It is currently not supported on any other platform. - * @param aPlatformData Platform specific data that can help in walking the - * stack, this should be nullptr unless you really know - * what you're doing! This needs to be a pointer to a - * CONTEXT on Windows and should not be passed on other - * platforms. - * - * May skip some stack frames due to compiler optimizations or code - * generation. - * - */ -MFBT_API bool -MozStackWalk(MozWalkStackCallback aCallback, uint32_t aSkipFrames, - uint32_t aMaxFrames, void* aClosure, uintptr_t aThread, - void* aPlatformData); - -typedef struct -{ - /* - * The name of the shared library or executable containing an - * address and the address's offset within that library, or empty - * string and zero if unknown. - */ - char library[256]; - ptrdiff_t loffset; - /* - * The name of the file name and line number of the code - * corresponding to the address, or empty string and zero if - * unknown. - */ - char filename[256]; - unsigned long lineno; - /* - * The name of the function containing an address and the address's - * offset within that function, or empty string and zero if unknown. - */ - char function[256]; - ptrdiff_t foffset; -} MozCodeAddressDetails; - -/** - * For a given pointer to code, fill in the pieces of information used - * when printing a stack trace. - * - * @param aPC The code address. - * @param aDetails A structure to be filled in with the result. - */ -MFBT_API bool -MozDescribeCodeAddress(void* aPC, MozCodeAddressDetails* aDetails); - -/** - * Format the information about a code address in a format suitable for - * stack traces on the current platform. When available, this string - * should contain the function name, source file, and line number. When - * these are not available, library and offset should be reported, if - * possible. - * - * Note that this output is parsed by several scripts including the fix*.py and - * make-tree.pl scripts in tools/rb/. It should only be change with care, and - * in conjunction with those scripts. - * - * @param aBuffer A string to be filled in with the description. - * The string will always be null-terminated. - * @param aBufferSize The size, in bytes, of aBuffer, including - * room for the terminating null. If the information - * to be printed would be larger than aBuffer, it - * will be truncated so that aBuffer[aBufferSize-1] - * is the terminating null. - * @param aFrameNumber The frame number. - * @param aPC The code address. - * @param aFunction The function name. Possibly null or the empty string. - * @param aLibrary The library name. Possibly null or the empty string. - * @param aLOffset The library offset. - * @param aFileName The filename. Possibly null or the empty string. - * @param aLineNo The line number. Possibly zero. - */ -MFBT_API void -MozFormatCodeAddress(char* aBuffer, uint32_t aBufferSize, uint32_t aFrameNumber, - const void* aPC, const char* aFunction, - const char* aLibrary, ptrdiff_t aLOffset, - const char* aFileName, uint32_t aLineNo); - -/** - * Format the information about a code address in the same fashion as - * MozFormatCodeAddress. - * - * @param aBuffer A string to be filled in with the description. - * The string will always be null-terminated. - * @param aBufferSize The size, in bytes, of aBuffer, including - * room for the terminating null. If the information - * to be printed would be larger than aBuffer, it - * will be truncated so that aBuffer[aBufferSize-1] - * is the terminating null. - * @param aFrameNumber The frame number. - * @param aPC The code address. - * @param aDetails The value filled in by MozDescribeCodeAddress(aPC). - */ -MFBT_API void -MozFormatCodeAddressDetails(char* aBuffer, uint32_t aBufferSize, - uint32_t aFrameNumber, void* aPC, - const MozCodeAddressDetails* aDetails); - -namespace mozilla { - -MFBT_API bool -FramePointerStackWalk(MozWalkStackCallback aCallback, uint32_t aSkipFrames, - uint32_t aMaxFrames, void* aClosure, void** aBp, - void* aStackEnd); - -} // namespace mozilla - -/** - * Initialize the critical sections for this platform so that we can - * abort stack walks when needed. - */ -MFBT_API void -StackWalkInitCriticalAddress(void); - -#endif diff --git a/win32/include/spidermonkey/mozilla/StackWalk_windows.h b/win32/include/spidermonkey/mozilla/StackWalk_windows.h deleted file mode 100755 index 5ffdd206..00000000 --- a/win32/include/spidermonkey/mozilla/StackWalk_windows.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef mozilla_StackWalk_windows_h -#define mozilla_StackWalk_windows_h - -#include "mozilla/Types.h" - -/** - * Allow stack walkers to work around the egregious win64 dynamic lookup table - * list API by locking around SuspendThread to avoid deadlock. - * - * See comment in StackWalk.cpp - */ -MFBT_API void -AcquireStackWalkWorkaroundLock(); - -MFBT_API bool -TryAcquireStackWalkWorkaroundLock(); - -MFBT_API void -ReleaseStackWalkWorkaroundLock(); - -#endif // mozilla_StackWalk_windows_h diff --git a/win32/include/spidermonkey/mozilla/StaticAnalysisFunctions.h b/win32/include/spidermonkey/mozilla/StaticAnalysisFunctions.h deleted file mode 100755 index a06809dc..00000000 --- a/win32/include/spidermonkey/mozilla/StaticAnalysisFunctions.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_StaticAnalysisFunctions_h -#define mozilla_StaticAnalysisFunctions_h - -#ifndef __cplusplus -#ifndef bool -#include -#endif -#endif -/* - * Functions that are used as markers in Gecko code for static analysis. Their - * purpose is to have different AST nodes generated during compile time and to - * match them based on different checkers implemented in build/clang-plugin - */ - -#ifdef MOZ_CLANG_PLUGIN - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * MOZ_AssertAssignmentTest - used in MOZ_ASSERT in order to test the possible - * presence of assignment instead of logical comparisons. - * - * Example: - * MOZ_ASSERT(retVal = true); - */ -static MOZ_ALWAYS_INLINE bool MOZ_AssertAssignmentTest(bool exprResult) { - return exprResult; -} - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#define MOZ_CHECK_ASSERT_ASSIGNMENT(expr) MOZ_AssertAssignmentTest(!!(expr)) - -#else - -#define MOZ_CHECK_ASSERT_ASSIGNMENT(expr) (!!(expr)) - -#endif /* MOZ_CLANG_PLUGIN */ -#endif /* StaticAnalysisFunctions_h */ \ No newline at end of file diff --git a/win32/include/spidermonkey/mozilla/TaggedAnonymousMemory.h b/win32/include/spidermonkey/mozilla/TaggedAnonymousMemory.h deleted file mode 100755 index d26b06df..00000000 --- a/win32/include/spidermonkey/mozilla/TaggedAnonymousMemory.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// Some Linux kernels -- specifically, newer versions of Android and -// some B2G devices -- have a feature for assigning names to ranges of -// anonymous memory (i.e., memory that doesn't have a "name" in the -// form of an underlying mapped file). These names are reported in -// /proc//smaps alongside system-level memory usage information -// such as Proportional Set Size (memory usage adjusted for sharing -// between processes), which allows reporting this information at a -// finer granularity than would otherwise be possible (e.g., -// separating malloc() heap from JS heap). -// -// Existing memory can be tagged with MozTagAnonymousMemory(); it will -// tag the range of complete pages containing the given interval, so -// the results may be inexact if the range isn't page-aligned. -// MozTaggedAnonymousMmap() can be used like mmap() with an extra -// parameter, and will tag the returned memory if the mapping was -// successful (and if it was in fact anonymous). -// -// NOTE: The pointer given as the "tag" argument MUST remain valid as -// long as the mapping exists. The referenced string is read when -// /proc//smaps or /proc//maps is read, not when the tag is -// established, so freeing it or changing its contents will have -// unexpected results. Using a static string is probably best. -// -// Also note that this header can be used by both C and C++ code. - -#ifndef mozilla_TaggedAnonymousMemory_h -#define mozilla_TaggedAnonymousMemory_h - -#ifndef XP_WIN - -#include -#include - -#include "mozilla/Types.h" - -#ifdef ANDROID - -#ifdef __cplusplus -extern "C" { -#endif - -MFBT_API void -MozTagAnonymousMemory(const void* aPtr, size_t aLength, const char* aTag); - -MFBT_API void* -MozTaggedAnonymousMmap(void* aAddr, size_t aLength, int aProt, int aFlags, - int aFd, off_t aOffset, const char* aTag); - -MFBT_API int -MozTaggedMemoryIsSupported(void); - -#ifdef __cplusplus -} // extern "C" -#endif - -#else // ANDROID - -static inline void -MozTagAnonymousMemory(const void* aPtr, size_t aLength, const char* aTag) -{ -} - -static inline void* -MozTaggedAnonymousMmap(void* aAddr, size_t aLength, int aProt, int aFlags, - int aFd, off_t aOffset, const char* aTag) -{ - return mmap(aAddr, aLength, aProt, aFlags, aFd, aOffset); -} - -static inline int -MozTaggedMemoryIsSupported(void) -{ - return 0; -} - -#endif // ANDROID - -#endif // !XP_WIN - -#endif // mozilla_TaggedAnonymousMemory_h diff --git a/win32/include/spidermonkey/mozilla/TemplateLib.h b/win32/include/spidermonkey/mozilla/TemplateLib.h deleted file mode 100755 index 6286452d..00000000 --- a/win32/include/spidermonkey/mozilla/TemplateLib.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * Reusable template meta-functions on types and compile-time values. Meta- - * functions are placed inside the 'tl' namespace to avoid conflict with non- - * meta functions of the same name (e.g., mozilla::tl::FloorLog2 vs. - * mozilla::FloorLog2). - * - * When constexpr support becomes universal, we should probably use that instead - * of some of these templates, for simplicity. - */ - -#ifndef mozilla_TemplateLib_h -#define mozilla_TemplateLib_h - -#include -#include - -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -namespace tl { - -/** Compute min/max. */ -template -struct Min -{ - static const size_t value = I < J ? I : J; -}; -template -struct Max -{ - static const size_t value = I > J ? I : J; -}; - -/** Compute floor(log2(i)). */ -template -struct FloorLog2 -{ - static const size_t value = 1 + FloorLog2::value; -}; -template<> struct FloorLog2<0> { /* Error */ }; -template<> struct FloorLog2<1> { static const size_t value = 0; }; - -/** Compute ceiling(log2(i)). */ -template -struct CeilingLog2 -{ - static const size_t value = FloorLog2<2 * I - 1>::value; -}; - -/** Round up to the nearest power of 2. */ -template -struct RoundUpPow2 -{ - static const size_t value = size_t(1) << CeilingLog2::value; -}; -template<> -struct RoundUpPow2<0> -{ - static const size_t value = 1; -}; - -/** Compute the number of bits in the given unsigned type. */ -template -struct BitSize -{ - static const size_t value = sizeof(T) * CHAR_BIT; -}; - -/** - * Produce an N-bit mask, where N <= BitSize::value. Handle the - * language-undefined edge case when N = BitSize::value. - */ -template -struct NBitMask -{ - // Assert the precondition. On success this evaluates to 0. Otherwise it - // triggers divide-by-zero at compile time: a guaranteed compile error in - // C++11, and usually one in C++98. Add this value to |value| to assure - // its computation. - static const size_t checkPrecondition = - 0 / size_t(N < BitSize::value); - static const size_t value = (size_t(1) << N) - 1 + checkPrecondition; -}; -template<> -struct NBitMask::value> -{ - static const size_t value = size_t(-1); -}; - -/** - * For the unsigned integral type size_t, compute a mask M for N such that - * for all X, !(X & M) implies X * N will not overflow (w.r.t size_t) - */ -template -struct MulOverflowMask -{ - static const size_t value = - ~NBitMask::value - CeilingLog2::value>::value; -}; -template<> struct MulOverflowMask<0> { /* Error */ }; -template<> struct MulOverflowMask<1> { static const size_t value = 0; }; - -/** - * And computes the logical 'and' of its argument booleans. - * - * Examples: - * mozilla::t1::And::value is true. - * mozilla::t1::And::value is false. - * mozilla::t1::And<>::value is true. - */ - -template -struct And; - -template<> -struct And<> : public TrueType { }; - -template -struct And - : public Conditional, FalseType>::Type { }; - -} // namespace tl - -} // namespace mozilla - -#endif /* mozilla_TemplateLib_h */ diff --git a/win32/include/spidermonkey/mozilla/ThreadLocal.h b/win32/include/spidermonkey/mozilla/ThreadLocal.h deleted file mode 100755 index 880e6773..00000000 --- a/win32/include/spidermonkey/mozilla/ThreadLocal.h +++ /dev/null @@ -1,222 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Cross-platform lightweight thread local data wrappers. */ - -#ifndef mozilla_ThreadLocal_h -#define mozilla_ThreadLocal_h - -#if defined(XP_WIN) -// This file will get included in any file that wants to add a profiler mark. -// In order to not bring together we could include windef.h and -// winbase.h which are sufficient to get the prototypes for the Tls* functions. -// # include -// # include -// Unfortunately, even including these headers causes us to add a bunch of ugly -// stuff to our namespace e.g #define CreateEvent CreateEventW -extern "C" { -__declspec(dllimport) void* __stdcall TlsGetValue(unsigned long); -__declspec(dllimport) int __stdcall TlsSetValue(unsigned long, void*); -__declspec(dllimport) unsigned long __stdcall TlsAlloc(); -} -#else -# include -# include -#endif - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -// sig_safe_t denotes an atomic type which can be read or stored in a single -// instruction. This means that data of this type is safe to be manipulated -// from a signal handler, or other similar asynchronous execution contexts. -#if defined(XP_WIN) -typedef unsigned long sig_safe_t; -#else -typedef sig_atomic_t sig_safe_t; -#endif - -namespace detail { - -#if defined(HAVE_THREAD_TLS_KEYWORD) -#define MOZ_HAS_THREAD_LOCAL -#endif - -/* - * Thread Local Storage helpers. - * - * Usage: - * - * Do not directly instantiate this class. Instead, use the - * MOZ_THREAD_LOCAL macro to declare or define instances. The macro - * takes a type name as its argument. - * - * Declare like this: - * extern MOZ_THREAD_LOCAL(int) tlsInt; - * Define like this: - * MOZ_THREAD_LOCAL(int) tlsInt; - * or: - * static MOZ_THREAD_LOCAL(int) tlsInt; - * - * Only static-storage-duration (e.g. global variables, or static class members) - * objects of this class should be instantiated. This class relies on - * zero-initialization, which is implicit for static-storage-duration objects. - * It doesn't have a custom default constructor, to avoid static initializers. - * - * API usage: - * - * // Create a TLS item. - * // - * // Note that init() should be invoked before the first use of set() - * // or get(). It is ok to call it multiple times. This must be - * // called in a way that avoids possible races with other threads. - * MOZ_THREAD_LOCAL(int) tlsKey; - * if (!tlsKey.init()) { - * // deal with the error - * } - * - * // Set the TLS value - * tlsKey.set(123); - * - * // Get the TLS value - * int value = tlsKey.get(); - */ -template -class ThreadLocal -{ -#ifndef MOZ_HAS_THREAD_LOCAL -#if defined(XP_WIN) - typedef unsigned long key_t; -#else - typedef pthread_key_t key_t; -#endif - - // Integral types narrower than void* must be extended to avoid - // warnings from valgrind on some platforms. This helper type - // achieves that without penalizing the common case of ThreadLocals - // instantiated using a pointer type. - template - struct Helper - { - typedef uintptr_t Type; - }; - - template - struct Helper - { - typedef S *Type; - }; -#endif - - bool initialized() const { -#ifdef MOZ_HAS_THREAD_LOCAL - return true; -#else - return mInited; -#endif - } - -public: - // __thread does not allow non-trivial constructors, but we can - // instead rely on zero-initialization. -#ifndef MOZ_HAS_THREAD_LOCAL - ThreadLocal() - : mKey(0), mInited(false) - {} -#endif - - MOZ_MUST_USE inline bool init(); - - inline T get() const; - - inline void set(const T aValue); - -private: -#ifdef MOZ_HAS_THREAD_LOCAL - T mValue; -#else - key_t mKey; - bool mInited; -#endif -}; - -template -inline bool -ThreadLocal::init() -{ - static_assert(mozilla::IsPointer::value || mozilla::IsIntegral::value, - "mozilla::ThreadLocal must be used with a pointer or " - "integral type"); - static_assert(sizeof(T) <= sizeof(void*), - "mozilla::ThreadLocal can't be used for types larger than " - "a pointer"); - -#ifdef MOZ_HAS_THREAD_LOCAL - return true; -#else - if (!initialized()) { -#ifdef XP_WIN - mKey = TlsAlloc(); - mInited = mKey != 0xFFFFFFFFUL; // TLS_OUT_OF_INDEXES -#else - mInited = !pthread_key_create(&mKey, nullptr); -#endif - } - return mInited; -#endif -} - -template -inline T -ThreadLocal::get() const -{ -#ifdef MOZ_HAS_THREAD_LOCAL - return mValue; -#else - MOZ_ASSERT(initialized()); - void* h; -#ifdef XP_WIN - h = TlsGetValue(mKey); -#else - h = pthread_getspecific(mKey); -#endif - return static_cast(reinterpret_cast::Type>(h)); -#endif -} - -template -inline void -ThreadLocal::set(const T aValue) -{ -#ifdef MOZ_HAS_THREAD_LOCAL - mValue = aValue; -#else - MOZ_ASSERT(initialized()); - void* h = reinterpret_cast(static_cast::Type>(aValue)); -#ifdef XP_WIN - bool succeeded = TlsSetValue(mKey, h); -#else - bool succeeded = !pthread_setspecific(mKey, h); -#endif - if (!succeeded) { - MOZ_CRASH(); - } -#endif -} - -#ifdef MOZ_HAS_THREAD_LOCAL -#define MOZ_THREAD_LOCAL(TYPE) __thread mozilla::detail::ThreadLocal -#else -#define MOZ_THREAD_LOCAL(TYPE) mozilla::detail::ThreadLocal -#endif - -} // namespace detail -} // namespace mozilla - -#endif /* mozilla_ThreadLocal_h */ diff --git a/win32/include/spidermonkey/mozilla/TimeStamp.h b/win32/include/spidermonkey/mozilla/TimeStamp.h deleted file mode 100755 index a1a0eb36..00000000 --- a/win32/include/spidermonkey/mozilla/TimeStamp.h +++ /dev/null @@ -1,609 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_TimeStamp_h -#define mozilla_TimeStamp_h - -#include -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/FloatingPoint.h" -#include "mozilla/TypeTraits.h" -#include "mozilla/Types.h" - -namespace IPC { -template struct ParamTraits; -} // namespace IPC - -#ifdef XP_WIN -// defines TimeStampValue as a complex value keeping both -// GetTickCount and QueryPerformanceCounter values -#include "TimeStamp_windows.h" -#endif - -namespace mozilla { - -#ifndef XP_WIN -typedef uint64_t TimeStampValue; -#endif - -class TimeStamp; - -/** - * Platform-specific implementation details of BaseTimeDuration. - */ -class BaseTimeDurationPlatformUtils -{ -public: - static MFBT_API double ToSeconds(int64_t aTicks); - static MFBT_API double ToSecondsSigDigits(int64_t aTicks); - static MFBT_API int64_t TicksFromMilliseconds(double aMilliseconds); - static MFBT_API int64_t ResolutionInTicks(); -}; - -/** - * Instances of this class represent the length of an interval of time. - * Negative durations are allowed, meaning the end is before the start. - * - * Internally the duration is stored as a int64_t in units of - * PR_TicksPerSecond() when building with NSPR interval timers, or a - * system-dependent unit when building with system clocks. The - * system-dependent unit must be constant, otherwise the semantics of - * this class would be broken. - * - * The ValueCalculator template parameter determines how arithmetic - * operations are performed on the integer count of ticks (mValue). - */ -template -class BaseTimeDuration -{ -public: - // The default duration is 0. - constexpr BaseTimeDuration() : mValue(0) {} - // Allow construction using '0' as the initial value, for readability, - // but no other numbers (so we don't have any implicit unit conversions). - struct _SomethingVeryRandomHere; - MOZ_IMPLICIT BaseTimeDuration(_SomethingVeryRandomHere* aZero) : mValue(0) - { - MOZ_ASSERT(!aZero, "Who's playing funny games here?"); - } - // Default copy-constructor and assignment are OK - - // Converting copy-constructor and assignment operator - template - explicit BaseTimeDuration(const BaseTimeDuration& aOther) - : mValue(aOther.mValue) - { } - - template - BaseTimeDuration& operator=(const BaseTimeDuration& aOther) - { - mValue = aOther.mValue; - return *this; - } - - double ToSeconds() const - { - if (mValue == INT64_MAX) { - return PositiveInfinity(); - } - if (mValue == INT64_MIN) { - return NegativeInfinity(); - } - return BaseTimeDurationPlatformUtils::ToSeconds(mValue); - } - // Return a duration value that includes digits of time we think to - // be significant. This method should be used when displaying a - // time to humans. - double ToSecondsSigDigits() const - { - if (mValue == INT64_MAX) { - return PositiveInfinity(); - } - if (mValue == INT64_MIN) { - return NegativeInfinity(); - } - return BaseTimeDurationPlatformUtils::ToSecondsSigDigits(mValue); - } - double ToMilliseconds() const { return ToSeconds() * 1000.0; } - double ToMicroseconds() const { return ToMilliseconds() * 1000.0; } - - // Using a double here is safe enough; with 53 bits we can represent - // durations up to over 280,000 years exactly. If the units of - // mValue do not allow us to represent durations of that length, - // long durations are clamped to the max/min representable value - // instead of overflowing. - static inline BaseTimeDuration FromSeconds(double aSeconds) - { - return FromMilliseconds(aSeconds * 1000.0); - } - static BaseTimeDuration FromMilliseconds(double aMilliseconds) - { - if (aMilliseconds == PositiveInfinity()) { - return Forever(); - } - if (aMilliseconds == NegativeInfinity()) { - return FromTicks(INT64_MIN); - } - return FromTicks( - BaseTimeDurationPlatformUtils::TicksFromMilliseconds(aMilliseconds)); - } - static inline BaseTimeDuration FromMicroseconds(double aMicroseconds) - { - return FromMilliseconds(aMicroseconds / 1000.0); - } - - static BaseTimeDuration Forever() - { - return FromTicks(INT64_MAX); - } - - BaseTimeDuration operator+(const BaseTimeDuration& aOther) const - { - return FromTicks(ValueCalculator::Add(mValue, aOther.mValue)); - } - BaseTimeDuration operator-(const BaseTimeDuration& aOther) const - { - return FromTicks(ValueCalculator::Subtract(mValue, aOther.mValue)); - } - BaseTimeDuration& operator+=(const BaseTimeDuration& aOther) - { - mValue = ValueCalculator::Add(mValue, aOther.mValue); - return *this; - } - BaseTimeDuration& operator-=(const BaseTimeDuration& aOther) - { - mValue = ValueCalculator::Subtract(mValue, aOther.mValue); - return *this; - } - BaseTimeDuration operator-() const - { - // We don't just use FromTicks(ValueCalculator::Subtract(0, mValue)) - // since that won't give the correct result for -TimeDuration::Forever(). - int64_t ticks; - if (mValue == INT64_MAX) { - ticks = INT64_MIN; - } else if (mValue == INT64_MIN) { - ticks = INT64_MAX; - } else { - ticks = -mValue; - } - - return FromTicks(ticks); - } - -private: - // Block double multiplier (slower, imprecise if long duration) - Bug 853398. - // If required, use MultDouble explicitly and with care. - BaseTimeDuration operator*(const double aMultiplier) const = delete; - - // Block double divisor (for the same reason, and because dividing by - // fractional values would otherwise invoke the int64_t variant, and rounding - // the passed argument can then cause divide-by-zero) - Bug 1147491. - BaseTimeDuration operator/(const double aDivisor) const = delete; - -public: - BaseTimeDuration MultDouble(double aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const int32_t aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const uint32_t aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const int64_t aMultiplier) const - { - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator*(const uint64_t aMultiplier) const - { - if (aMultiplier > INT64_MAX) { - return Forever(); - } - return FromTicks(ValueCalculator::Multiply(mValue, aMultiplier)); - } - BaseTimeDuration operator/(const int64_t aDivisor) const - { - MOZ_ASSERT(aDivisor != 0, "Division by zero"); - return FromTicks(ValueCalculator::Divide(mValue, aDivisor)); - } - double operator/(const BaseTimeDuration& aOther) const - { -#ifndef MOZ_B2G - // Bug 1066388 - This fails on B2G ICS Emulator - MOZ_ASSERT(aOther.mValue != 0, "Division by zero"); -#endif - return ValueCalculator::DivideDouble(mValue, aOther.mValue); - } - BaseTimeDuration operator%(const BaseTimeDuration& aOther) const - { - MOZ_ASSERT(aOther.mValue != 0, "Division by zero"); - return FromTicks(ValueCalculator::Modulo(mValue, aOther.mValue)); - } - - template - bool operator<(const BaseTimeDuration& aOther) const - { - return mValue < aOther.mValue; - } - template - bool operator<=(const BaseTimeDuration& aOther) const - { - return mValue <= aOther.mValue; - } - template - bool operator>=(const BaseTimeDuration& aOther) const - { - return mValue >= aOther.mValue; - } - template - bool operator>(const BaseTimeDuration& aOther) const - { - return mValue > aOther.mValue; - } - template - bool operator==(const BaseTimeDuration& aOther) const - { - return mValue == aOther.mValue; - } - template - bool operator!=(const BaseTimeDuration& aOther) const - { - return mValue != aOther.mValue; - } - bool IsZero() const - { - return mValue == 0; - } - explicit operator bool() const - { - return mValue != 0; - } - - // Return a best guess at the system's current timing resolution, - // which might be variable. BaseTimeDurations below this order of - // magnitude are meaningless, and those at the same order of - // magnitude or just above are suspect. - static BaseTimeDuration Resolution() { - return FromTicks(BaseTimeDurationPlatformUtils::ResolutionInTicks()); - } - - // We could define additional operators here: - // -- convert to/from other time units - // -- scale duration by a float - // but let's do that on demand. - // Comparing durations for equality will only lead to bugs on - // platforms with high-resolution timers. - -private: - friend class TimeStamp; - friend struct IPC::ParamTraits>; - template - friend class BaseTimeDuration; - - static BaseTimeDuration FromTicks(int64_t aTicks) - { - BaseTimeDuration t; - t.mValue = aTicks; - return t; - } - - static BaseTimeDuration FromTicks(double aTicks) - { - // NOTE: this MUST be a >= test, because int64_t(double(INT64_MAX)) - // overflows and gives INT64_MIN. - if (aTicks >= double(INT64_MAX)) { - return FromTicks(INT64_MAX); - } - - // This MUST be a <= test. - if (aTicks <= double(INT64_MIN)) { - return FromTicks(INT64_MIN); - } - - return FromTicks(int64_t(aTicks)); - } - - // Duration, result is implementation-specific difference of two TimeStamps - int64_t mValue; -}; - -/** - * Perform arithmetic operations on the value of a BaseTimeDuration without - * doing strict checks on the range of values. - */ -class TimeDurationValueCalculator -{ -public: - static int64_t Add(int64_t aA, int64_t aB) { return aA + aB; } - static int64_t Subtract(int64_t aA, int64_t aB) { return aA - aB; } - - template - static int64_t Multiply(int64_t aA, T aB) - { - static_assert(IsIntegral::value, - "Using integer multiplication routine with non-integer type." - " Further specialization required"); - return aA * static_cast(aB); - } - - static int64_t Divide(int64_t aA, int64_t aB) { return aA / aB; } - static double DivideDouble(int64_t aA, int64_t aB) - { - return static_cast(aA) / aB; - } - static int64_t Modulo(int64_t aA, int64_t aB) { return aA % aB; } -}; - -template <> -inline int64_t -TimeDurationValueCalculator::Multiply(int64_t aA, double aB) -{ - return static_cast(aA * aB); -} - -/** - * Specialization of BaseTimeDuration that uses TimeDurationValueCalculator for - * arithmetic on the mValue member. - * - * Use this class for time durations that are *not* expected to hold values of - * Forever (or the negative equivalent) or when such time duration are *not* - * expected to be used in arithmetic operations. - */ -typedef BaseTimeDuration TimeDuration; - -/** - * Instances of this class represent moments in time, or a special - * "null" moment. We do not use the non-monotonic system clock or - * local time, since they can be reset, causing apparent backward - * travel in time, which can confuse algorithms. Instead we measure - * elapsed time according to the system. This time can never go - * backwards (i.e. it never wraps around, at least not in less than - * five million years of system elapsed time). It might not advance - * while the system is sleeping. If TimeStamp::SetNow() is not called - * at all for hours or days, we might not notice the passage of some - * of that time. - * - * We deliberately do not expose a way to convert TimeStamps to some - * particular unit. All you can do is compute a difference between two - * TimeStamps to get a TimeDuration. You can also add a TimeDuration - * to a TimeStamp to get a new TimeStamp. You can't do something - * meaningless like add two TimeStamps. - * - * Internally this is implemented as either a wrapper around - * - high-resolution, monotonic, system clocks if they exist on this - * platform - * - PRIntervalTime otherwise. We detect wraparounds of - * PRIntervalTime and work around them. - * - * This class is similar to C++11's time_point, however it is - * explicitly nullable and provides an IsNull() method. time_point - * is initialized to the clock's epoch and provides a - * time_since_epoch() method that functions similiarly. i.e. - * t.IsNull() is equivalent to t.time_since_epoch() == decltype(t)::duration::zero(); - */ -class TimeStamp -{ -public: - /** - * Initialize to the "null" moment - */ - constexpr TimeStamp() : mValue(0) {} - // Default copy-constructor and assignment are OK - - /** - * The system timestamps are the same as the TimeStamp - * retrieved by mozilla::TimeStamp. Since we need this for - * vsync timestamps, we enable the creation of mozilla::TimeStamps - * on platforms that support vsync aligned refresh drivers / compositors - * Verified true as of Jan 31, 2015: B2G and OS X - * False on Windows 7 - * UNTESTED ON OTHER PLATFORMS - */ -#if defined(MOZ_WIDGET_GONK) || defined(XP_DARWIN) - static TimeStamp FromSystemTime(int64_t aSystemTime) - { - static_assert(sizeof(aSystemTime) == sizeof(TimeStampValue), - "System timestamp should be same units as TimeStampValue"); - return TimeStamp(aSystemTime); - } -#endif - - /** - * Return true if this is the "null" moment - */ - bool IsNull() const { return mValue == 0; } - - /** - * Return true if this is not the "null" moment, may be used in tests, e.g.: - * |if (timestamp) { ... }| - */ - explicit operator bool() const - { - return mValue != 0; - } - - /** - * Return a timestamp reflecting the current elapsed system time. This - * is monotonically increasing (i.e., does not decrease) over the - * lifetime of this process' XPCOM session. - * - * Now() is trying to ensure the best possible precision on each platform, - * at least one millisecond. - * - * NowLoRes() has been introduced to workaround performance problems of - * QueryPerformanceCounter on the Windows platform. NowLoRes() is giving - * lower precision, usually 15.6 ms, but with very good performance benefit. - * Use it for measurements of longer times, like >200ms timeouts. - */ - static TimeStamp Now() { return Now(true); } - static TimeStamp NowLoRes() { return Now(false); } - - /** - * Return a timestamp representing the time when the current process was - * created which will be comparable with other timestamps taken with this - * class. If the actual process creation time is detected to be inconsistent - * the @a aIsInconsistent parameter will be set to true, the returned - * timestamp however will still be valid though inaccurate. - * - * @param aIsInconsistent Set to true if an inconsistency was detected in the - * process creation time - * @returns A timestamp representing the time when the process was created, - * this timestamp is always valid even when errors are reported - */ - static MFBT_API TimeStamp ProcessCreation(bool& aIsInconsistent); - - /** - * Records a process restart. After this call ProcessCreation() will return - * the time when the browser was restarted instead of the actual time when - * the process was created. - */ - static MFBT_API void RecordProcessRestart(); - - /** - * Compute the difference between two timestamps. Both must be non-null. - */ - TimeDuration operator-(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - static_assert(-INT64_MAX > INT64_MIN, "int64_t sanity check"); - int64_t ticks = int64_t(mValue - aOther.mValue); - // Check for overflow. - if (mValue > aOther.mValue) { - if (ticks < 0) { - ticks = INT64_MAX; - } - } else { - if (ticks > 0) { - ticks = INT64_MIN; - } - } - return TimeDuration::FromTicks(ticks); - } - - TimeStamp operator+(const TimeDuration& aOther) const - { - TimeStamp result = *this; - result += aOther; - return result; - } - TimeStamp operator-(const TimeDuration& aOther) const - { - TimeStamp result = *this; - result -= aOther; - return result; - } - TimeStamp& operator+=(const TimeDuration& aOther) - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - TimeStampValue value = mValue + aOther.mValue; - // Check for underflow. - // (We don't check for overflow because it's not obvious what the error - // behavior should be in that case.) - if (aOther.mValue < 0 && value > mValue) { - value = 0; - } - mValue = value; - return *this; - } - TimeStamp& operator-=(const TimeDuration& aOther) - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - TimeStampValue value = mValue - aOther.mValue; - // Check for underflow. - // (We don't check for overflow because it's not obvious what the error - // behavior should be in that case.) - if (aOther.mValue > 0 && value > mValue) { - value = 0; - } - mValue = value; - return *this; - } - - bool operator<(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue < aOther.mValue; - } - bool operator<=(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue <= aOther.mValue; - } - bool operator>=(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue >= aOther.mValue; - } - bool operator>(const TimeStamp& aOther) const - { - MOZ_ASSERT(!IsNull(), "Cannot compute with a null value"); - MOZ_ASSERT(!aOther.IsNull(), "Cannot compute with aOther null value"); - return mValue > aOther.mValue; - } - bool operator==(const TimeStamp& aOther) const - { - return IsNull() - ? aOther.IsNull() - : !aOther.IsNull() && mValue == aOther.mValue; - } - bool operator!=(const TimeStamp& aOther) const - { - return !(*this == aOther); - } - - // Comparing TimeStamps for equality should be discouraged. Adding - // two TimeStamps, or scaling TimeStamps, is nonsense and must never - // be allowed. - - static MFBT_API void Startup(); - static MFBT_API void Shutdown(); - -private: - friend struct IPC::ParamTraits; - friend void StartupTimelineRecordExternal(int, uint64_t); - - MOZ_IMPLICIT TimeStamp(TimeStampValue aValue) : mValue(aValue) {} - - static MFBT_API TimeStamp Now(bool aHighResolution); - - /** - * Computes the uptime of the current process in microseconds. The result - * is platform-dependent and needs to be checked against existing timestamps - * for consistency. - * - * @returns The number of microseconds since the calling process was started - * or 0 if an error was encountered while computing the uptime - */ - static MFBT_API uint64_t ComputeProcessUptime(); - - /** - * When built with PRIntervalTime, a value of 0 means this instance - * is "null". Otherwise, the low 32 bits represent a PRIntervalTime, - * and the high 32 bits represent a counter of the number of - * rollovers of PRIntervalTime that we've seen. This counter starts - * at 1 to avoid a real time colliding with the "null" value. - * - * PR_INTERVAL_MAX is set at 100,000 ticks per second. So the minimum - * time to wrap around is about 2^64/100000 seconds, i.e. about - * 5,849,424 years. - * - * When using a system clock, a value is system dependent. - */ - TimeStampValue mValue; -}; - -} // namespace mozilla - -#endif /* mozilla_TimeStamp_h */ diff --git a/win32/include/spidermonkey/mozilla/TimeStamp_windows.h b/win32/include/spidermonkey/mozilla/TimeStamp_windows.h deleted file mode 100755 index c87d34ef..00000000 --- a/win32/include/spidermonkey/mozilla/TimeStamp_windows.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_TimeStamp_windows_h -#define mozilla_TimeStamp_windows_h - -#include "mozilla/Types.h" - -namespace mozilla { - -class TimeStamp; - -class TimeStampValue -{ - friend struct IPC::ParamTraits; - friend class TimeStamp; - friend void StartupTimelineRecordExternal(int, uint64_t); - - // Both QPC and GTC are kept in [mt] units. - uint64_t mGTC; - uint64_t mQPC; - bool mHasQPC; - bool mIsNull; - - MFBT_API TimeStampValue(uint64_t aGTC, uint64_t aQPC, bool aHasQPC); - - MFBT_API uint64_t CheckQPC(const TimeStampValue& aOther) const; - - struct _SomethingVeryRandomHere; - constexpr TimeStampValue(_SomethingVeryRandomHere* aNullValue) - : mGTC(0) - , mQPC(0) - , mHasQPC(false) - , mIsNull(true) - { - } - -public: - MFBT_API uint64_t operator-(const TimeStampValue& aOther) const; - - TimeStampValue operator+(const int64_t aOther) const - { - return TimeStampValue(mGTC + aOther, mQPC + aOther, mHasQPC); - } - TimeStampValue operator-(const int64_t aOther) const - { - return TimeStampValue(mGTC - aOther, mQPC - aOther, mHasQPC); - } - MFBT_API TimeStampValue& operator+=(const int64_t aOther); - MFBT_API TimeStampValue& operator-=(const int64_t aOther); - - bool operator<(const TimeStampValue& aOther) const - { - return int64_t(*this - aOther) < 0; - } - bool operator>(const TimeStampValue& aOther) const - { - return int64_t(*this - aOther) > 0; - } - bool operator<=(const TimeStampValue& aOther) const - { - return int64_t(*this - aOther) <= 0; - } - bool operator>=(const TimeStampValue& aOther) const - { - return int64_t(*this - aOther) >= 0; - } - bool operator==(const TimeStampValue& aOther) const - { - return int64_t(*this - aOther) == 0; - } - bool operator!=(const TimeStampValue& aOther) const - { - return int64_t(*this - aOther) != 0; - } -}; - -} - -#endif /* mozilla_TimeStamp_h */ diff --git a/win32/include/spidermonkey/mozilla/ToString.h b/win32/include/spidermonkey/mozilla/ToString.h deleted file mode 100755 index f11cad5c..00000000 --- a/win32/include/spidermonkey/mozilla/ToString.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Utilities for converting an object to a string representation. */ - -#ifndef mozilla_ToString_h -#define mozilla_ToString_h - -#include -#include - -namespace mozilla { - -/** - * A convenience function for converting an object to a string representation. - * Supports any object which can be streamed to an std::ostream. - */ -template -std::string -ToString(const T& aValue) -{ - std::ostringstream stream; - stream << aValue; - return stream.str(); -} - -} // namespace mozilla - -#endif /* mozilla_ToString_h */ diff --git a/win32/include/spidermonkey/mozilla/Tuple.h b/win32/include/spidermonkey/mozilla/Tuple.h deleted file mode 100755 index a7f9bee6..00000000 --- a/win32/include/spidermonkey/mozilla/Tuple.h +++ /dev/null @@ -1,461 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A variadic tuple class. */ - -#ifndef mozilla_Tuple_h -#define mozilla_Tuple_h - -#include "mozilla/Move.h" -#include "mozilla/Pair.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/TypeTraits.h" - -#include -#include - -namespace mozilla { - -namespace detail { - -/* - * A helper class that allows passing around multiple variadic argument lists - * by grouping them. - */ -template -struct Group; - -/* - * CheckConvertibility checks whether each type in a source pack of types - * is convertible to the corresponding type in a target pack of types. - * - * It is intended to be invoked like this: - * CheckConvertibility, Group> - * 'Group' is used to separate types in the two packs (otherwise if we just - * wrote 'CheckConvertibility -struct CheckConvertibilityImpl; - -template -struct CheckConvertibilityImpl - : FalseType {}; - -template -struct CheckConvertibilityImpl, Group, true> - : IntegralConstant::value...>::value> { }; - -template -struct CheckConvertibility; - -template -struct CheckConvertibility, Group> - : CheckConvertibilityImpl, Group, - sizeof...(SourceTypes) == sizeof...(TargetTypes)> { }; - -/* - * TupleImpl is a helper class used to implement mozilla::Tuple. - * It represents one node in a recursive inheritance hierarchy. - * 'Index' is the 0-based index of the tuple element stored in this node; - * 'Elements...' are the types of the elements stored in this node and its - * base classes. - * - * Example: - * Tuple inherits from - * TupleImpl<0, int, float, char>, which stores the 'int' and inherits from - * TupleImpl<1, float, char>, which stores the 'float' and inherits from - * TupleImpl<2, char>, which stores the 'char' and inherits from - * TupleImpl<3>, which stores nothing and terminates the recursion. - * - * The purpose of the 'Index' parameter is to allow efficient index-based - * access to a tuple element: given a tuple, and an index 'I' that we wish to - * access, we can cast the tuple to the base which stores the I'th element - * by performing template argument deduction against 'TupleImpl', - * where 'I' is specified explicitly and 'E...' is deduced (this is what the - * non-member 'Get(t)' function does). - * - * This implementation strategy is borrowed from libstdc++'s std::tuple - * implementation. - */ -template -struct TupleImpl; - -/* - * The base case of the inheritance recursion (and also the implementation - * of an empty tuple). - */ -template -struct TupleImpl { - bool operator==(const TupleImpl& aOther) const - { - return true; - } -}; - -/* - * One node of the recursive inheritance hierarchy. It stores the element at - * index 'Index' of a tuple, of type 'HeadT', and inherits from the nodes - * that store the remaining elements, of types 'TailT...'. - */ -template -struct TupleImpl - : public TupleImpl -{ - typedef TupleImpl Base; - - // Accessors for the head and the tail. - // These are static, because the intended usage is for the caller to, - // given a tuple, obtain the type B of the base class which stores the - // element of interest, and then call B::Head(tuple) to access it. - // (Tail() is mostly for internal use, but is exposed for consistency.) - static HeadT& Head(TupleImpl& aTuple) { return aTuple.mHead; } - static const HeadT& Head(const TupleImpl& aTuple) { return aTuple.mHead; } - static Base& Tail(TupleImpl& aTuple) { return aTuple; } - static const Base& Tail(const TupleImpl& aTuple) { return aTuple; } - - TupleImpl() : Base(), mHead() { } - - // Construct from const references to the elements. - explicit TupleImpl(const HeadT& aHead, const TailT&... aTail) - : Base(aTail...), mHead(aHead) { } - - // Construct from objects that are convertible to the elements. - // This constructor is enabled only when the argument types are actually - // convertible to the element types, otherwise it could become a better - // match for certain invocations than the copy constructor. - template , - Group>::value>::Type> - explicit TupleImpl(OtherHeadT&& aHead, OtherTailT&&... aTail) - : Base(Forward(aTail)...), mHead(Forward(aHead)) { } - - // Copy and move constructors. - // We'd like to use '= default' to implement these, but MSVC 2013's support - // for '= default' is incomplete and this doesn't work. - TupleImpl(const TupleImpl& aOther) - : Base(Tail(aOther)) - , mHead(Head(aOther)) {} - TupleImpl(TupleImpl&& aOther) - : Base(Move(Tail(aOther))) - , mHead(Forward(Head(aOther))) {} - - // Assign from a tuple whose elements are convertible to the elements - // of this tuple. - template ::Type> - TupleImpl& operator=(const TupleImpl& aOther) - { - typedef TupleImpl OtherT; - Head(*this) = OtherT::Head(aOther); - Tail(*this) = OtherT::Tail(aOther); - return *this; - } - template ::Type> - TupleImpl& operator=(TupleImpl&& aOther) - { - typedef TupleImpl OtherT; - Head(*this) = Move(OtherT::Head(aOther)); - Tail(*this) = Move(OtherT::Tail(aOther)); - return *this; - } - - // Copy and move assignment operators. - TupleImpl& operator=(const TupleImpl& aOther) - { - Head(*this) = Head(aOther); - Tail(*this) = Tail(aOther); - return *this; - } - TupleImpl& operator=(TupleImpl&& aOther) - { - Head(*this) = Move(Head(aOther)); - Tail(*this) = Move(Tail(aOther)); - return *this; - } - bool operator==(const TupleImpl& aOther) const - { - return Head(*this) == Head(aOther) && Tail(*this) == Tail(aOther); - } -private: - HeadT mHead; // The element stored at this index in the tuple. -}; - -} // namespace detail - -/** - * Tuple is a class that stores zero or more objects, whose types are specified - * as template parameters. It can be thought of as a generalization of Pair, - * (which can be thought of as a 2-tuple). - * - * Tuple allows index-based access to its elements (with the index having to be - * known at compile time) via the non-member function 'Get(tuple)'. - */ -template -class Tuple : public detail::TupleImpl<0, Elements...> -{ - typedef detail::TupleImpl<0, Elements...> Impl; -public: - // The constructors and assignment operators here are simple wrappers - // around those in TupleImpl. - - Tuple() : Impl() { } - explicit Tuple(const Elements&... aElements) : Impl(aElements...) { } - // Here, we can't just use 'typename... OtherElements' because MSVC will give - // a warning "C4520: multiple default constructors specified" (even if no one - // actually instantiates the constructor with an empty parameter pack - - // that's probably a bug) and we compile with warnings-as-errors. - template , - detail::Group>::value>::Type> - explicit Tuple(OtherHead&& aHead, OtherTail&&... aTail) - : Impl(Forward(aHead), Forward(aTail)...) { } - Tuple(const Tuple& aOther) : Impl(aOther) { } - Tuple(Tuple&& aOther) : Impl(Move(aOther)) { } - - template ::Type> - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - template ::Type> - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - bool operator==(const Tuple& aOther) const - { - return static_cast(*this) == static_cast(aOther); - } -}; - -/** - * Specialization of Tuple for two elements. - * This is created to support construction and assignment from a Pair or std::pair. - */ -template -class Tuple : public detail::TupleImpl<0, A, B> -{ - typedef detail::TupleImpl<0, A, B> Impl; - -public: - // The constructors and assignment operators here are simple wrappers - // around those in TupleImpl. - - Tuple() : Impl() { } - explicit Tuple(const A& aA, const B& aB) : Impl(aA, aB) { } - template , - detail::Group>::value>::Type> - explicit Tuple(AArg&& aA, BArg&& aB) - : Impl(Forward(aA), Forward(aB)) { } - Tuple(const Tuple& aOther) : Impl(aOther) { } - Tuple(Tuple&& aOther) : Impl(Move(aOther)) { } - explicit Tuple(const Pair& aOther) - : Impl(aOther.first(), aOther.second()) { } - explicit Tuple(Pair&& aOther) : Impl(Forward(aOther.first()), - Forward(aOther.second())) { } - explicit Tuple(const std::pair& aOther) - : Impl(aOther.first, aOther.second) { } - explicit Tuple(std::pair&& aOther) : Impl(Forward(aOther.first), - Forward(aOther.second)) { } - - template - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - template - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - Tuple& operator=(const Tuple& aOther) - { - static_cast(*this) = aOther; - return *this; - } - Tuple& operator=(Tuple&& aOther) - { - static_cast(*this) = Move(aOther); - return *this; - } - template - Tuple& operator=(const Pair& aOther) - { - Impl::Head(*this) = aOther.first(); - Impl::Tail(*this).Head(*this) = aOther.second(); - return *this; - } - template - Tuple& operator=(Pair&& aOther) - { - Impl::Head(*this) = Forward(aOther.first()); - Impl::Tail(*this).Head(*this) = Forward(aOther.second()); - return *this; - } - template - Tuple& operator=(const std::pair& aOther) - { - Impl::Head(*this) = aOther.first; - Impl::Tail(*this).Head(*this) = aOther.second; - return *this; - } - template - Tuple& operator=(std::pair&& aOther) - { - Impl::Head(*this) = Forward(aOther.first); - Impl::Tail(*this).Head(*this) = Forward(aOther.second); - return *this; - } -}; - -/** - * Specialization of Tuple for zero arguments. - * This is necessary because if the primary template were instantiated with - * an empty parameter pack, the 'Tuple(Elements...)' constructors would - * become illegal overloads of the default constructor. - */ -template <> -class Tuple<> {}; - -namespace detail { - -/* - * Helper functions for implementing Get(tuple). - * These functions take a TupleImpl, with Index being - * explicitly specified, and Elements being deduced. By passing a Tuple - * object as argument, template argument deduction will do its magic and - * cast the tuple to the base class which stores the element at Index. - */ - -// Const reference version. -template -auto TupleGetHelper(TupleImpl& aTuple) - -> decltype(TupleImpl::Head(aTuple)) -{ - return TupleImpl::Head(aTuple); -} - -// Non-const reference version. -template -auto TupleGetHelper(const TupleImpl& aTuple) - -> decltype(TupleImpl::Head(aTuple)) -{ - return TupleImpl::Head(aTuple); -} - -} // namespace detail - -/** - * Index-based access to an element of a tuple. - * The syntax is Get(tuple). The index is zero-based. - * - * Example: - * - * Tuple t; - * ... - * float f = Get<1>(t); - */ - -// Non-const reference version. -template -auto Get(Tuple& aTuple) - -> decltype(detail::TupleGetHelper(aTuple)) -{ - return detail::TupleGetHelper(aTuple); -} - -// Const reference version. -template -auto Get(const Tuple& aTuple) - -> decltype(detail::TupleGetHelper(aTuple)) -{ - return detail::TupleGetHelper(aTuple); -} - -// Rvalue reference version. -template -auto Get(Tuple&& aTuple) - -> decltype(Move(mozilla::Get(aTuple))) -{ - // We need a 'mozilla::' qualification here to avoid - // name lookup only finding the current function. - return Move(mozilla::Get(aTuple)); -} - -/** - * A convenience function for constructing a tuple out of a sequence of - * values without specifying the type of the tuple. - * The type of the tuple is deduced from the types of its elements. - * - * Example: - * - * auto tuple = MakeTuple(42, 0.5f, 'c'); // has type Tuple - */ -template -inline Tuple::Type...> -MakeTuple(Elements&&... aElements) -{ - return Tuple::Type...>(Forward(aElements)...); -} - -/** - * A convenience function for constructing a tuple of references to a - * sequence of variables. Since assignments to the elements of the tuple - * "go through" to the referenced variables, this can be used to "unpack" - * a tuple into individual variables. - * - * Example: - * - * int i; - * float f; - * char c; - * Tie(i, f, c) = FunctionThatReturnsATuple(); - */ -template -inline Tuple -Tie(Elements&... aVariables) -{ - return Tuple(aVariables...); -} - -} // namespace mozilla - -#endif /* mozilla_Tuple_h */ diff --git a/win32/include/spidermonkey/mozilla/TypeTraits.h b/win32/include/spidermonkey/mozilla/TypeTraits.h deleted file mode 100755 index 084f608c..00000000 --- a/win32/include/spidermonkey/mozilla/TypeTraits.h +++ /dev/null @@ -1,1262 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Template-based metaprogramming and type-testing facilities. */ - -#ifndef mozilla_TypeTraits_h -#define mozilla_TypeTraits_h - -#include "mozilla/Types.h" - -/* - * These traits are approximate copies of the traits and semantics from C++11's - * header. Don't add traits not in that header! When all - * platforms provide that header, we can convert all users and remove this one. - */ - -#include - -namespace mozilla { - -/* Forward declarations. */ - -template struct RemoveCV; -template struct AddRvalueReference; - -/* 20.2.4 Function template declval [declval] */ - -/** - * DeclVal simplifies the definition of expressions which occur as unevaluated - * operands. It converts T to a reference type, making it possible to use in - * decltype expressions even if T does not have a default constructor, e.g.: - * decltype(DeclVal().foo()) - */ -template -typename AddRvalueReference::Type DeclVal(); - -/* 20.9.3 Helper classes [meta.help] */ - -/** - * Helper class used as a base for various type traits, exposed publicly - * because exposes it as well. - */ -template -struct IntegralConstant -{ - static const T value = Value; - typedef T ValueType; - typedef IntegralConstant Type; -}; - -/** Convenient aliases. */ -typedef IntegralConstant TrueType; -typedef IntegralConstant FalseType; - -/* 20.9.4 Unary type traits [meta.unary] */ - -/* 20.9.4.1 Primary type categories [meta.unary.cat] */ - -namespace detail { - -template -struct IsVoidHelper : FalseType {}; - -template<> -struct IsVoidHelper : TrueType {}; - -} // namespace detail - -/** - * IsVoid determines whether a type is void. - * - * mozilla::IsVoid::value is false; - * mozilla::IsVoid::value is true; - * mozilla::IsVoid::value is false; - * mozilla::IsVoid::value is true. - */ -template -struct IsVoid : detail::IsVoidHelper::Type> {}; - -namespace detail { - -template -struct IsIntegralHelper : FalseType {}; - -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; -template<> struct IsIntegralHelper : TrueType {}; - -} /* namespace detail */ - -/** - * IsIntegral determines whether a type is an integral type. - * - * mozilla::IsIntegral::value is true; - * mozilla::IsIntegral::value is true; - * mozilla::IsIntegral::value is true; - * mozilla::IsIntegral::value is false; - * mozilla::IsIntegral::value is false; - */ -template -struct IsIntegral : detail::IsIntegralHelper::Type> -{}; - -template -struct IsSame; - -namespace detail { - -template -struct IsFloatingPointHelper - : IntegralConstant::value || - IsSame::value || - IsSame::value> -{}; - -} // namespace detail - -/** - * IsFloatingPoint determines whether a type is a floating point type (float, - * double, long double). - * - * mozilla::IsFloatingPoint::value is false; - * mozilla::IsFloatingPoint::value is true; - * mozilla::IsFloatingPoint::value is true; - * mozilla::IsFloatingPoint::value is false. - */ -template -struct IsFloatingPoint - : detail::IsFloatingPointHelper::Type> -{}; - -namespace detail { - -template -struct IsArrayHelper : FalseType {}; - -template -struct IsArrayHelper : TrueType {}; - -template -struct IsArrayHelper : TrueType {}; - -} // namespace detail - -/** - * IsArray determines whether a type is an array type, of known or unknown - * length. - * - * mozilla::IsArray::value is false; - * mozilla::IsArray::value is true; - * mozilla::IsArray::value is true. - */ -template -struct IsArray : detail::IsArrayHelper::Type> -{}; - -namespace detail { - -template -struct IsFunPtr; - -template -struct IsFunPtr - : public FalseType -{}; - -template -struct IsFunPtr - : public TrueType -{}; - -}; // namespace detail - -/** - * IsFunction determines whether a type is a function type. Function pointers - * don't qualify here--only the type of an actual function symbol. We do not - * correctly handle varags function types because of a bug in MSVC. - * - * Given the function: - * void f(int) {} - * - * mozilla::IsFunction is true; - * mozilla::IsFunction is false; - * mozilla::IsFunction is true. - */ -template -struct IsFunction - : public detail::IsFunPtr::Type *> -{}; - -namespace detail { - -template -struct IsPointerHelper : FalseType {}; - -template -struct IsPointerHelper : TrueType {}; - -} // namespace detail - -/** - * IsPointer determines whether a type is a possibly-CV-qualified pointer type - * (but not a pointer-to-member type). - * - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is true; - * mozilla::IsPointer::value is false; - * mozilla::IsPointer::value is false. - * mozilla::IsPointer::value is false - */ -template -struct IsPointer : detail::IsPointerHelper::Type> -{}; - -/** - * IsLvalueReference determines whether a type is an lvalue reference. - * - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is false; - * mozilla::IsLvalueReference::value is true; - * mozilla::IsLvalueReference::value is false. - */ -template -struct IsLvalueReference : FalseType {}; - -template -struct IsLvalueReference : TrueType {}; - -/** - * IsRvalueReference determines whether a type is an rvalue reference. - * - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is false; - * mozilla::IsRvalueReference::value is true. - */ -template -struct IsRvalueReference : FalseType {}; - -template -struct IsRvalueReference : TrueType {}; - -namespace detail { - -// __is_enum is a supported extension across all of our supported compilers. -template -struct IsEnumHelper - : IntegralConstant -{}; - -} // namespace detail - -/** - * IsEnum determines whether a type is an enum type. - * - * mozilla::IsEnum::value is true; - * mozilla::IsEnum::value is false; - * mozilla::IsEnum::value is false; - */ -template -struct IsEnum - : detail::IsEnumHelper::Type> -{}; - -namespace detail { - -// __is_class is a supported extension across all of our supported compilers: -// http://llvm.org/releases/3.0/docs/ClangReleaseNotes.html -// http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Type-Traits.html#Type-Traits -// http://msdn.microsoft.com/en-us/library/ms177194%28v=vs.100%29.aspx -template -struct IsClassHelper - : IntegralConstant -{}; - -} // namespace detail - -/** - * IsClass determines whether a type is a class type (but not a union). - * - * struct S {}; - * union U {}; - * mozilla::IsClass::value is false; - * mozilla::IsClass::value is true; - * mozilla::IsClass::value is false; - */ -template -struct IsClass - : detail::IsClassHelper::Type> -{}; - -/* 20.9.4.2 Composite type traits [meta.unary.comp] */ - -/** - * IsReference determines whether a type is an lvalue or rvalue reference. - * - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is false; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is true; - * mozilla::IsReference::value is true. - */ -template -struct IsReference - : IntegralConstant::value || IsRvalueReference::value> -{}; - -/** - * IsArithmetic determines whether a type is arithmetic. A type is arithmetic - * iff it is an integral type or a floating point type. - * - * mozilla::IsArithmetic::value is true; - * mozilla::IsArithmetic::value is true; - * mozilla::IsArithmetic::value is false. - */ -template -struct IsArithmetic - : IntegralConstant::value || IsFloatingPoint::value> -{}; - -namespace detail { - -template -struct IsMemberPointerHelper : FalseType {}; - -template -struct IsMemberPointerHelper : TrueType {}; - -} // namespace detail - -/** - * IsMemberPointer determines whether a type is pointer to non-static member - * object or a pointer to non-static member function. - * - * mozilla::IsMemberPointer::value is true - * mozilla::IsMemberPointer::value is false - */ -template -struct IsMemberPointer - : detail::IsMemberPointerHelper::Type> -{}; - -/** - * IsScalar determines whether a type is a scalar type. - * - * mozilla::IsScalar::value is true - * mozilla::IsScalar::value is true - * mozilla::IsScalar::value is false - */ -template -struct IsScalar - : IntegralConstant::value || IsEnum::value || - IsPointer::value || IsMemberPointer::value> -{}; - -/* 20.9.4.3 Type properties [meta.unary.prop] */ - -/** - * IsConst determines whether a type is const or not. - * - * mozilla::IsConst::value is false; - * mozilla::IsConst::value is true; - * mozilla::IsConst::value is false. - */ -template -struct IsConst : FalseType {}; - -template -struct IsConst : TrueType {}; - -/** - * IsVolatile determines whether a type is volatile or not. - * - * mozilla::IsVolatile::value is false; - * mozilla::IsVolatile::value is true; - * mozilla::IsVolatile::value is false. - */ -template -struct IsVolatile : FalseType {}; - -template -struct IsVolatile : TrueType {}; - -/** - * Traits class for identifying POD types. Until C++11 there's no automatic - * way to detect PODs, so for the moment this is done manually. Users may - * define specializations of this class that inherit from mozilla::TrueType and - * mozilla::FalseType (or equivalently mozilla::IntegralConstant, or conveniently from mozilla::IsPod for composite types) as needed to - * ensure correct IsPod behavior. - */ -template -struct IsPod : public FalseType {}; - -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template<> struct IsPod : TrueType {}; -template struct IsPod : TrueType {}; - -namespace detail { - -// __is_empty is a supported extension across all of our supported compilers: -// http://llvm.org/releases/3.0/docs/ClangReleaseNotes.html -// http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Type-Traits.html#Type-Traits -// http://msdn.microsoft.com/en-us/library/ms177194%28v=vs.100%29.aspx -template -struct IsEmptyHelper - : IntegralConstant::value && __is_empty(T)> -{}; - -} // namespace detail - -/** - * IsEmpty determines whether a type is a class (but not a union) that is empty. - * - * A class is empty iff it and all its base classes have no non-static data - * members (except bit-fields of length 0) and no virtual member functions, and - * no base class is empty or a virtual base class. - * - * Intuitively, empty classes don't have any data that has to be stored in - * instances of those classes. (The size of the class must still be non-zero, - * because distinct array elements of any type must have different addresses. - * However, if the Empty Base Optimization is implemented by the compiler [most - * compilers implement it, and in certain cases C++11 requires it], the size of - * a class inheriting from an empty |Base| class need not be inflated by - * |sizeof(Base)|.) And intuitively, non-empty classes have data members and/or - * vtable pointers that must be stored in each instance for proper behavior. - * - * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); - * union U1 { int x; }; - * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); - * struct E1 {}; - * struct E2 { int : 0 }; - * struct E3 : E1 {}; - * struct E4 : E2 {}; - * static_assert(mozilla::IsEmpty::value && - * mozilla::IsEmpty::value && - * mozilla::IsEmpty::value && - * mozilla::IsEmpty::value, - * "all empty"); - * union U2 { E1 e1; }; - * static_assert(!mozilla::IsEmpty::value, "not a class => not empty"); - * struct NE1 { int x; }; - * struct NE2 : virtual E1 {}; - * struct NE3 : E2 { virtual ~NE3() {} }; - * struct NE4 { virtual void f() {} }; - * static_assert(!mozilla::IsEmpty::value && - * !mozilla::IsEmpty::value && - * !mozilla::IsEmpty::value && - * !mozilla::IsEmpty::value, - * "all empty"); - */ -template -struct IsEmpty : detail::IsEmptyHelper::Type> -{}; - - -namespace detail { - -template::value, - bool = IsIntegral::value, - typename NoCV = typename RemoveCV::Type> -struct IsSignedHelper; - -// Floating point is signed. -template -struct IsSignedHelper : TrueType {}; - -// Integral is conditionally signed. -template -struct IsSignedHelper - : IntegralConstant -{}; - -// Non-floating point, non-integral is not signed. -template -struct IsSignedHelper : FalseType {}; - -} // namespace detail - -/** - * IsSigned determines whether a type is a signed arithmetic type. |char| is - * considered a signed type if it has the same representation as |signed char|. - * - * mozilla::IsSigned::value is true; - * mozilla::IsSigned::value is false; - * mozilla::IsSigned::value is false; - * mozilla::IsSigned::value is true. - */ -template -struct IsSigned : detail::IsSignedHelper {}; - -namespace detail { - -template::value, - bool = IsIntegral::value, - typename NoCV = typename RemoveCV::Type> -struct IsUnsignedHelper; - -// Floating point is not unsigned. -template -struct IsUnsignedHelper : FalseType {}; - -// Integral is conditionally unsigned. -template -struct IsUnsignedHelper - : IntegralConstant::value || bool(NoCV(1) < NoCV(-1)))> -{}; - -// Non-floating point, non-integral is not unsigned. -template -struct IsUnsignedHelper : FalseType {}; - -} // namespace detail - -/** - * IsUnsigned determines whether a type is an unsigned arithmetic type. - * - * mozilla::IsUnsigned::value is false; - * mozilla::IsUnsigned::value is true; - * mozilla::IsUnsigned::value is true; - * mozilla::IsUnsigned::value is false. - */ -template -struct IsUnsigned : detail::IsUnsignedHelper {}; - -namespace detail { - -struct DoIsDestructibleImpl -{ - template().~T())> - static TrueType test(int); - template - static FalseType test(...); -}; - -template -struct IsDestructibleImpl : public DoIsDestructibleImpl -{ - typedef decltype(test(0)) Type; -}; - -} // namespace detail - -template -struct IsDestructible : public detail::IsDestructibleImpl::Type {}; - -/* 20.9.5 Type property queries [meta.unary.prop.query] */ - -/* 20.9.6 Relationships between types [meta.rel] */ - -/** - * IsSame tests whether two types are the same type. - * - * mozilla::IsSame::value is true; - * mozilla::IsSame::value is true; - * mozilla::IsSame::value is false; - * mozilla::IsSame::value is true; - * mozilla::IsSame::value is false; - * mozilla::IsSame::value is true. - */ -template -struct IsSame : FalseType {}; - -template -struct IsSame : TrueType {}; - -namespace detail { - -#if defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) - -template -struct BaseOfTester : IntegralConstant {}; - -#else - -// The trickery used to implement IsBaseOf here makes it possible to use it for -// the cases of private and multiple inheritance. This code was inspired by the -// sample code here: -// -// http://stackoverflow.com/questions/2910979/how-is-base-of-works -template -struct BaseOfHelper -{ -public: - operator Base*() const; - operator Derived*(); -}; - -template -struct BaseOfTester -{ -private: - template - static char test(Derived*, T); - static int test(Base*, int); - -public: - static const bool value = - sizeof(test(BaseOfHelper(), int())) == sizeof(char); -}; - -template -struct BaseOfTester -{ -private: - template - static char test(Derived*, T); - static int test(Base*, int); - -public: - static const bool value = - sizeof(test(BaseOfHelper(), int())) == sizeof(char); -}; - -template -struct BaseOfTester : FalseType {}; - -template -struct BaseOfTester : TrueType {}; - -template -struct BaseOfTester : TrueType {}; - -#endif - -} /* namespace detail */ - -/* - * IsBaseOf allows to know whether a given class is derived from another. - * - * Consider the following class definitions: - * - * class A {}; - * class B : public A {}; - * class C {}; - * - * mozilla::IsBaseOf::value is true; - * mozilla::IsBaseOf::value is false; - */ -template -struct IsBaseOf - : IntegralConstant::value> -{}; - -namespace detail { - -template -struct ConvertibleTester -{ -private: - template - static char test_helper(To1); - - template - static decltype(test_helper(DeclVal())) test(int); - - template - static int test(...); - -public: - static const bool value = - sizeof(test(0)) == sizeof(char); -}; - -} // namespace detail - -/** - * IsConvertible determines whether a value of type From will implicitly convert - * to a value of type To. For example: - * - * struct A {}; - * struct B : public A {}; - * struct C {}; - * - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is true; - * mozilla::IsConvertible::value is false; - * mozilla::IsConvertible::value is false; - * mozilla::IsConvertible::value is false; - * mozilla::IsConvertible::value is false. - * - * For obscure reasons, you can't use IsConvertible when the types being tested - * are related through private inheritance, and you'll get a compile error if - * you try. Just don't do it! - * - * Note - we need special handling for void, which ConvertibleTester doesn't - * handle. The void handling here doesn't handle const/volatile void correctly, - * which could be easily fixed if the need arises. - */ -template -struct IsConvertible - : IntegralConstant::value> -{}; - -template -struct IsConvertible - : IntegralConstant::value> -{}; - -template -struct IsConvertible - : IntegralConstant::value> -{}; - -template<> -struct IsConvertible - : TrueType -{}; - -/* 20.9.7 Transformations between types [meta.trans] */ - -/* 20.9.7.1 Const-volatile modifications [meta.trans.cv] */ - -/** - * RemoveConst removes top-level const qualifications on a type. - * - * mozilla::RemoveConst::Type is int; - * mozilla::RemoveConst::Type is int; - * mozilla::RemoveConst::Type is const int*; - * mozilla::RemoveConst::Type is int*. - */ -template -struct RemoveConst -{ - typedef T Type; -}; - -template -struct RemoveConst -{ - typedef T Type; -}; - -/** - * RemoveVolatile removes top-level volatile qualifications on a type. - * - * mozilla::RemoveVolatile::Type is int; - * mozilla::RemoveVolatile::Type is int; - * mozilla::RemoveVolatile::Type is volatile int*; - * mozilla::RemoveVolatile::Type is int*. - */ -template -struct RemoveVolatile -{ - typedef T Type; -}; - -template -struct RemoveVolatile -{ - typedef T Type; -}; - -/** - * RemoveCV removes top-level const and volatile qualifications on a type. - * - * mozilla::RemoveCV::Type is int; - * mozilla::RemoveCV::Type is int; - * mozilla::RemoveCV::Type is int; - * mozilla::RemoveCV::Type is int*. - */ -template -struct RemoveCV -{ - typedef typename RemoveConst::Type>::Type Type; -}; - -/* 20.9.7.2 Reference modifications [meta.trans.ref] */ - -/** - * Converts reference types to the underlying types. - * - * mozilla::RemoveReference::Type is T; - * mozilla::RemoveReference::Type is T; - * mozilla::RemoveReference::Type is T; - */ - -template -struct RemoveReference -{ - typedef T Type; -}; - -template -struct RemoveReference -{ - typedef T Type; -}; - -template -struct RemoveReference -{ - typedef T Type; -}; - -template -struct Conditional; - -namespace detail { - -enum Voidness { TIsVoid, TIsNotVoid }; - -template::value ? TIsVoid : TIsNotVoid> -struct AddLvalueReferenceHelper; - -template -struct AddLvalueReferenceHelper -{ - typedef void Type; -}; - -template -struct AddLvalueReferenceHelper -{ - typedef T& Type; -}; - -} // namespace detail - -/** - * AddLvalueReference adds an lvalue & reference to T if one isn't already - * present. (Note: adding an lvalue reference to an rvalue && reference in - * essence replaces the && with a &&, per C+11 reference collapsing rules. For - * example, int&& would become int&.) - * - * The final computed type will only *not* be an lvalue reference if T is void. - * - * mozilla::AddLvalueReference::Type is int&; - * mozilla::AddLvalueRference::Type is volatile int&; - * mozilla::AddLvalueReference::Type is void*&; - * mozilla::AddLvalueReference::Type is void; - * mozilla::AddLvalueReference::Type is struct S&. - */ -template -struct AddLvalueReference - : detail::AddLvalueReferenceHelper -{}; - -namespace detail { - -template::value ? TIsVoid : TIsNotVoid> -struct AddRvalueReferenceHelper; - -template -struct AddRvalueReferenceHelper -{ - typedef void Type; -}; - -template -struct AddRvalueReferenceHelper -{ - typedef T&& Type; -}; - -} // namespace detail - -/** - * AddRvalueReference adds an rvalue && reference to T if one isn't already - * present. (Note: adding an rvalue reference to an lvalue & reference in - * essence keeps the &, per C+11 reference collapsing rules. For example, - * int& would remain int&.) - * - * The final computed type will only *not* be a reference if T is void. - * - * mozilla::AddRvalueReference::Type is int&&; - * mozilla::AddRvalueRference::Type is volatile int&; - * mozilla::AddRvalueRference::Type is const int&&; - * mozilla::AddRvalueReference::Type is void*&&; - * mozilla::AddRvalueReference::Type is void; - * mozilla::AddRvalueReference::Type is struct S&. - */ -template -struct AddRvalueReference - : detail::AddRvalueReferenceHelper -{}; - -/* 20.9.7.3 Sign modifications [meta.trans.sign] */ - -template -struct EnableIf; - -namespace detail { - -template -struct WithC : Conditional -{}; - -template -struct WithV : Conditional -{}; - - -template -struct WithCV : WithC::Type> -{}; - -template -struct CorrespondingSigned; - -template<> -struct CorrespondingSigned { typedef signed char Type; }; -template<> -struct CorrespondingSigned { typedef signed char Type; }; -template<> -struct CorrespondingSigned { typedef short Type; }; -template<> -struct CorrespondingSigned { typedef int Type; }; -template<> -struct CorrespondingSigned { typedef long Type; }; -template<> -struct CorrespondingSigned { typedef long long Type; }; - -template::Type, - bool IsSignedIntegerType = IsSigned::value && - !IsSame::value> -struct MakeSigned; - -template -struct MakeSigned -{ - typedef T Type; -}; - -template -struct MakeSigned - : WithCV::value, IsVolatile::value, - typename CorrespondingSigned::Type> -{}; - -} // namespace detail - -/** - * MakeSigned produces the corresponding signed integer type for a given - * integral type T, with the const/volatile qualifiers of T. T must be a - * possibly-const/volatile-qualified integral type that isn't bool. - * - * If T is already a signed integer type (not including char!), then T is - * produced. - * - * Otherwise, if T is an unsigned integer type, the signed variety of T, with - * T's const/volatile qualifiers, is produced. - * - * Otherwise, the integral type of the same size as T, with the lowest rank, - * with T's const/volatile qualifiers, is produced. (This basically only acts - * to produce signed char when T = char.) - * - * mozilla::MakeSigned::Type is signed long; - * mozilla::MakeSigned::Type is volatile int; - * mozilla::MakeSigned::Type is const signed short; - * mozilla::MakeSigned::Type is const signed char; - * mozilla::MakeSigned is an error; - * mozilla::MakeSigned is an error. - */ -template -struct MakeSigned - : EnableIf::value && - !IsSame::Type>::value, - typename detail::MakeSigned - >::Type -{}; - -namespace detail { - -template -struct CorrespondingUnsigned; - -template<> -struct CorrespondingUnsigned { typedef unsigned char Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned char Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned short Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned int Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned long Type; }; -template<> -struct CorrespondingUnsigned { typedef unsigned long long Type; }; - - -template::Type, - bool IsUnsignedIntegerType = IsUnsigned::value && - !IsSame::value> -struct MakeUnsigned; - -template -struct MakeUnsigned -{ - typedef T Type; -}; - -template -struct MakeUnsigned - : WithCV::value, IsVolatile::value, - typename CorrespondingUnsigned::Type> -{}; - -} // namespace detail - -/** - * MakeUnsigned produces the corresponding unsigned integer type for a given - * integral type T, with the const/volatile qualifiers of T. T must be a - * possibly-const/volatile-qualified integral type that isn't bool. - * - * If T is already an unsigned integer type (not including char!), then T is - * produced. - * - * Otherwise, if T is an signed integer type, the unsigned variety of T, with - * T's const/volatile qualifiers, is produced. - * - * Otherwise, the unsigned integral type of the same size as T, with the lowest - * rank, with T's const/volatile qualifiers, is produced. (This basically only - * acts to produce unsigned char when T = char.) - * - * mozilla::MakeUnsigned::Type is unsigned long; - * mozilla::MakeUnsigned::Type is volatile unsigned int; - * mozilla::MakeUnsigned::Type is const unsigned short; - * mozilla::MakeUnsigned::Type is const unsigned char; - * mozilla::MakeUnsigned is an error; - * mozilla::MakeUnsigned is an error. - */ -template -struct MakeUnsigned - : EnableIf::value && - !IsSame::Type>::value, - typename detail::MakeUnsigned - >::Type -{}; - -/* 20.9.7.4 Array modifications [meta.trans.arr] */ - -/** - * RemoveExtent produces either the type of the elements of the array T, or T - * itself. - * - * mozilla::RemoveExtent::Type is int; - * mozilla::RemoveExtent::Type is const int; - * mozilla::RemoveExtent::Type is volatile int; - * mozilla::RemoveExtent::Type is long[17]. - */ -template -struct RemoveExtent -{ - typedef T Type; -}; - -template -struct RemoveExtent -{ - typedef T Type; -}; - -template -struct RemoveExtent -{ - typedef T Type; -}; - -/* 20.9.7.5 Pointer modifications [meta.trans.ptr] */ - -namespace detail { - -template -struct RemovePointerHelper -{ - typedef T Type; -}; - -template -struct RemovePointerHelper -{ - typedef Pointee Type; -}; - -} // namespace detail - -/** - * Produces the pointed-to type if a pointer is provided, else returns the input - * type. Note that this does not dereference pointer-to-member pointers. - * - * struct S { bool m; void f(); }; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is int; - * mozilla::RemovePointer::Type is const long; - * mozilla::RemovePointer::Type is void; - * mozilla::RemovePointer::Type is void (S::*)(); - * mozilla::RemovePointer::Type is void(); - * mozilla::RemovePointer::Type is bool S::*. - */ -template -struct RemovePointer - : detail::RemovePointerHelper::Type> -{}; - -/** - * Converts T& to T*. Otherwise returns T* given T. Note that C++17 wants - * std::add_pointer to work differently for function types. We don't implement - * that behavior here. - * - * mozilla::AddPointer is int*; - * mozilla::AddPointer is int**; - * mozilla::AddPointer is int*; - * mozilla::AddPointer is int** const. - */ -template -struct AddPointer -{ - typedef typename RemoveReference::Type* Type; -}; - -/* 20.9.7.6 Other transformations [meta.trans.other] */ - -/** - * EnableIf is a struct containing a typedef of T if and only if B is true. - * - * mozilla::EnableIf::Type is int; - * mozilla::EnableIf::Type is a compile-time error. - * - * Use this template to implement SFINAE-style (Substitution Failure Is not An - * Error) requirements. For example, you might use it to impose a restriction - * on a template parameter: - * - * template - * class PodVector // vector optimized to store POD (memcpy-able) types - * { - * EnableIf::value, T>::Type* vector; - * size_t length; - * ... - * }; - */ -template -struct EnableIf -{}; - -template -struct EnableIf -{ - typedef T Type; -}; - -/** - * Conditional selects a class between two, depending on a given boolean value. - * - * mozilla::Conditional::Type is A; - * mozilla::Conditional::Type is B; - */ -template -struct Conditional -{ - typedef A Type; -}; - -template -struct Conditional -{ - typedef B Type; -}; - -namespace detail { - -template::value, - bool IsFunction = IsFunction::value> -struct DecaySelector; - -template -struct DecaySelector -{ - typedef typename RemoveCV::Type Type; -}; - -template -struct DecaySelector -{ - typedef typename RemoveExtent::Type* Type; -}; - -template -struct DecaySelector -{ - typedef typename AddPointer::Type Type; -}; - -}; // namespace detail - -/** - * Strips const/volatile off a type and decays it from an lvalue to an - * rvalue. So function types are converted to function pointers, arrays to - * pointers, and references are removed. - * - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int - * mozilla::Decay::Type is int* - * mozilla::Decay::Type is int(*)(int) - */ -template -class Decay - : public detail::DecaySelector::Type> -{ -}; - -} /* namespace mozilla */ - -#endif /* mozilla_TypeTraits_h */ diff --git a/win32/include/spidermonkey/mozilla/TypedEnumBits.h b/win32/include/spidermonkey/mozilla/TypedEnumBits.h deleted file mode 100755 index 5ee6315c..00000000 --- a/win32/include/spidermonkey/mozilla/TypedEnumBits.h +++ /dev/null @@ -1,156 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS allows using a typed enum as bit flags. - */ - -#ifndef mozilla_TypedEnumBits_h -#define mozilla_TypedEnumBits_h - -#include "mozilla/Attributes.h" -#include "mozilla/IntegerTypeTraits.h" - -namespace mozilla { - -/* - * The problem that CastableTypedEnumResult aims to solve is that - * typed enums are not convertible to bool, and there is no way to make them - * be, yet user code wants to be able to write - * - * if (myFlags & Flags::SOME_PARTICULAR_FLAG) (1) - * - * There are different approaches to solving this. Most of them require - * adapting user code. For example, we could implement operator! and have - * the user write - * - * if (!!(myFlags & Flags::SOME_PARTICULAR_FLAG)) (2) - * - * Or we could supply a IsNonZero() or Any() function returning whether - * an enum value is nonzero, and have the user write - * - * if (Any(Flags & Flags::SOME_PARTICULAR_FLAG)) (3) - * - * But instead, we choose to preserve the original user syntax (1) as it - * is inherently more readable, and to ease porting existing code to typed - * enums. We achieve this by having operator& and other binary bitwise - * operators have as return type a class, CastableTypedEnumResult, - * that wraps a typed enum but adds bool convertibility. - */ -template -class CastableTypedEnumResult -{ -private: - const E mValue; - -public: - explicit constexpr CastableTypedEnumResult(E aValue) - : mValue(aValue) - {} - - constexpr operator E() const { return mValue; } - - template - explicit constexpr - operator DestinationType() const { return DestinationType(mValue); } - - constexpr bool operator !() const { return !bool(mValue); } -}; - -#define MOZ_CASTABLETYPEDENUMRESULT_BINOP(Op, OtherType, ReturnType) \ -template \ -constexpr ReturnType \ -operator Op(const OtherType& aE, const CastableTypedEnumResult& aR) \ -{ \ - return ReturnType(aE Op OtherType(aR)); \ -} \ -template \ -constexpr ReturnType \ -operator Op(const CastableTypedEnumResult& aR, const OtherType& aE) \ -{ \ - return ReturnType(OtherType(aR) Op aE); \ -} \ -template \ -constexpr ReturnType \ -operator Op(const CastableTypedEnumResult& aR1, \ - const CastableTypedEnumResult& aR2) \ -{ \ - return ReturnType(OtherType(aR1) Op OtherType(aR2)); \ -} - -MOZ_CASTABLETYPEDENUMRESULT_BINOP(|, E, CastableTypedEnumResult) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(&, E, CastableTypedEnumResult) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(^, E, CastableTypedEnumResult) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(==, E, bool) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(!=, E, bool) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(||, bool, bool) -MOZ_CASTABLETYPEDENUMRESULT_BINOP(&&, bool, bool) - -template -constexpr CastableTypedEnumResult -operator ~(const CastableTypedEnumResult& aR) -{ - return CastableTypedEnumResult(~(E(aR))); -} - -#define MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(Op) \ -template \ -E& \ -operator Op(E& aR1, \ - const CastableTypedEnumResult& aR2) \ -{ \ - return aR1 Op E(aR2); \ -} - -MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(&=) -MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(|=) -MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP(^=) - -#undef MOZ_CASTABLETYPEDENUMRESULT_COMPOUND_ASSIGN_OP - -#undef MOZ_CASTABLETYPEDENUMRESULT_BINOP - -namespace detail { -template -struct UnsignedIntegerTypeForEnum - : UnsignedStdintTypeForSize -{}; -} // namespace detail - -} // namespace mozilla - -#define MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, Op) \ - inline constexpr mozilla::CastableTypedEnumResult \ - operator Op(Name a, Name b) \ - { \ - typedef mozilla::CastableTypedEnumResult Result; \ - typedef mozilla::detail::UnsignedIntegerTypeForEnum::Type U; \ - return Result(Name(U(a) Op U(b))); \ - } \ - \ - inline Name& \ - operator Op##=(Name& a, Name b) \ - { \ - return a = a Op b; \ - } - -/** - * MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS generates standard bitwise operators - * for the given enum type. Use this to enable using an enum type as bit-field. - */ -#define MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(Name) \ - MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, |) \ - MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, &) \ - MOZ_MAKE_ENUM_CLASS_BINOP_IMPL(Name, ^) \ - inline constexpr mozilla::CastableTypedEnumResult \ - operator~(Name a) \ - { \ - typedef mozilla::CastableTypedEnumResult Result; \ - typedef mozilla::detail::UnsignedIntegerTypeForEnum::Type U; \ - return Result(Name(~(U(a)))); \ - } - -#endif // mozilla_TypedEnumBits_h diff --git a/win32/include/spidermonkey/mozilla/Types.h b/win32/include/spidermonkey/mozilla/Types.h deleted file mode 100755 index e7e18abb..00000000 --- a/win32/include/spidermonkey/mozilla/Types.h +++ /dev/null @@ -1,134 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* mfbt foundational types and macros. */ - -#ifndef mozilla_Types_h -#define mozilla_Types_h - -/* - * This header must be valid C and C++, includable by code embedding either - * SpiderMonkey or Gecko. - */ - -/* Expose all types and size_t. */ -#include -#include - -/* Implement compiler and linker macros needed for APIs. */ - -/* - * MOZ_EXPORT is used to declare and define a symbol or type which is externally - * visible to users of the current library. It encapsulates various decorations - * needed to properly export the method's symbol. - * - * api.h: - * extern MOZ_EXPORT int MeaningOfLife(void); - * extern MOZ_EXPORT int LuggageCombination; - * - * api.c: - * int MeaningOfLife(void) { return 42; } - * int LuggageCombination = 12345; - * - * If you are merely sharing a method across files, just use plain |extern|. - * These macros are designed for use by library interfaces -- not for normal - * methods or data used cross-file. - */ -#if defined(WIN32) -# define MOZ_EXPORT __declspec(dllexport) -#else /* Unix */ -# ifdef HAVE_VISIBILITY_ATTRIBUTE -# define MOZ_EXPORT __attribute__((visibility("default"))) -# elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) -# define MOZ_EXPORT __global -# else -# define MOZ_EXPORT /* nothing */ -# endif -#endif - - -/* - * Whereas implementers use MOZ_EXPORT to declare and define library symbols, - * users use MOZ_IMPORT_API and MOZ_IMPORT_DATA to access them. Most often the - * implementer of the library will expose an API macro which expands to either - * the export or import version of the macro, depending upon the compilation - * mode. - */ -#ifdef _WIN32 -# if defined(__MWERKS__) -# define MOZ_IMPORT_API /* nothing */ -# else -# define MOZ_IMPORT_API __declspec(dllimport) -# endif -#else -# define MOZ_IMPORT_API MOZ_EXPORT -#endif - -#if defined(_WIN32) && !defined(__MWERKS__) -# define MOZ_IMPORT_DATA __declspec(dllimport) -#else -# define MOZ_IMPORT_DATA MOZ_EXPORT -#endif - -/* - * Consistent with the above comment, the MFBT_API and MFBT_DATA macros expose - * export mfbt declarations when building mfbt, and they expose import mfbt - * declarations when using mfbt. - */ -#if defined(IMPL_MFBT) -# define MFBT_API MOZ_EXPORT -# define MFBT_DATA MOZ_EXPORT -#else - /* - * On linux mozglue is linked in the program and we link libxul.so with - * -z,defs. Normally that causes the linker to reject undefined references in - * libxul.so, but as a loophole it allows undefined references to weak - * symbols. We add the weak attribute to the import version of the MFBT API - * macros to exploit this. - */ -# if defined(MOZ_GLUE_IN_PROGRAM) -# define MFBT_API __attribute__((weak)) MOZ_IMPORT_API -# define MFBT_DATA __attribute__((weak)) MOZ_IMPORT_DATA -# else -# define MFBT_API MOZ_IMPORT_API -# define MFBT_DATA MOZ_IMPORT_DATA -# endif -#endif - -/* - * C symbols in C++ code must be declared immediately within |extern "C"| - * blocks. However, in C code, they need not be declared specially. This - * difference is abstracted behind the MOZ_BEGIN_EXTERN_C and MOZ_END_EXTERN_C - * macros, so that the user need not know whether he is being used in C or C++ - * code. - * - * MOZ_BEGIN_EXTERN_C - * - * extern MOZ_EXPORT int MostRandomNumber(void); - * ...other declarations... - * - * MOZ_END_EXTERN_C - * - * This said, it is preferable to just use |extern "C"| in C++ header files for - * its greater clarity. - */ -#ifdef __cplusplus -# define MOZ_BEGIN_EXTERN_C extern "C" { -# define MOZ_END_EXTERN_C } -#else -# define MOZ_BEGIN_EXTERN_C -# define MOZ_END_EXTERN_C -#endif - -/* - * GCC's typeof is available when decltype is not. - */ -#if defined(__GNUC__) && defined(__cplusplus) && \ - !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L -# define decltype __typeof__ -#endif - -#endif /* mozilla_Types_h */ diff --git a/win32/include/spidermonkey/mozilla/UniquePtr.h b/win32/include/spidermonkey/mozilla/UniquePtr.h deleted file mode 100755 index 7e1035bc..00000000 --- a/win32/include/spidermonkey/mozilla/UniquePtr.h +++ /dev/null @@ -1,697 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Smart pointer managing sole ownership of a resource. */ - -#ifndef mozilla_UniquePtr_h -#define mozilla_UniquePtr_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/Move.h" -#include "mozilla/Pair.h" -#include "mozilla/TypeTraits.h" - -namespace mozilla { - -template class DefaultDelete; -template> class UniquePtr; - -} // namespace mozilla - -namespace mozilla { - -namespace detail { - -struct HasPointerTypeHelper -{ - template static double Test(...); - template static char Test(typename U::pointer* = 0); -}; - -template -class HasPointerType : public IntegralConstant(0)) == 1> -{ -}; - -template ::value> -struct PointerTypeImpl -{ - typedef typename D::pointer Type; -}; - -template -struct PointerTypeImpl -{ - typedef T* Type; -}; - -template -struct PointerType -{ - typedef typename PointerTypeImpl::Type>::Type Type; -}; - -} // namespace detail - -/** - * UniquePtr is a smart pointer that wholly owns a resource. Ownership may be - * transferred out of a UniquePtr through explicit action, but otherwise the - * resource is destroyed when the UniquePtr is destroyed. - * - * UniquePtr is similar to C++98's std::auto_ptr, but it improves upon auto_ptr - * in one crucial way: it's impossible to copy a UniquePtr. Copying an auto_ptr - * obviously *can't* copy ownership of its singly-owned resource. So what - * happens if you try to copy one? Bizarrely, ownership is implicitly - * *transferred*, preserving single ownership but breaking code that assumes a - * copy of an object is identical to the original. (This is why auto_ptr is - * prohibited in STL containers.) - * - * UniquePtr solves this problem by being *movable* rather than copyable. - * Instead of passing a |UniquePtr u| directly to the constructor or assignment - * operator, you pass |Move(u)|. In doing so you indicate that you're *moving* - * ownership out of |u|, into the target of the construction/assignment. After - * the transfer completes, |u| contains |nullptr| and may be safely destroyed. - * This preserves single ownership but also allows UniquePtr to be moved by - * algorithms that have been made move-safe. (Note: if |u| is instead a - * temporary expression, don't use |Move()|: just pass the expression, because - * it's already move-ready. For more information see Move.h.) - * - * UniquePtr is also better than std::auto_ptr in that the deletion operation is - * customizable. An optional second template parameter specifies a class that - * (through its operator()(T*)) implements the desired deletion policy. If no - * policy is specified, mozilla::DefaultDelete is used -- which will either - * |delete| or |delete[]| the resource, depending whether the resource is an - * array. Custom deletion policies ideally should be empty classes (no member - * fields, no member fields in base classes, no virtual methods/inheritance), - * because then UniquePtr can be just as efficient as a raw pointer. - * - * Use of UniquePtr proceeds like so: - * - * UniquePtr g1; // initializes to nullptr - * g1.reset(new int); // switch resources using reset() - * g1 = nullptr; // clears g1, deletes the int - * - * UniquePtr g2(new int); // owns that int - * int* p = g2.release(); // g2 leaks its int -- still requires deletion - * delete p; // now freed - * - * struct S { int x; S(int x) : x(x) {} }; - * UniquePtr g3, g4(new S(5)); - * g3 = Move(g4); // g3 owns the S, g4 cleared - * S* p = g3.get(); // g3 still owns |p| - * assert(g3->x == 5); // operator-> works (if .get() != nullptr) - * assert((*g3).x == 5); // also operator* (again, if not cleared) - * Swap(g3, g4); // g4 now owns the S, g3 cleared - * g3.swap(g4); // g3 now owns the S, g4 cleared - * UniquePtr g5(Move(g3)); // g5 owns the S, g3 cleared - * g5.reset(); // deletes the S, g5 cleared - * - * struct FreePolicy { void operator()(void* p) { free(p); } }; - * UniquePtr g6(static_cast(malloc(sizeof(int)))); - * int* ptr = g6.get(); - * g6 = nullptr; // calls free(ptr) - * - * Now, carefully note a few things you *can't* do: - * - * UniquePtr b1; - * b1 = new int; // BAD: can only assign another UniquePtr - * int* ptr = b1; // BAD: no auto-conversion to pointer, use get() - * - * UniquePtr b2(b1); // BAD: can't copy a UniquePtr - * UniquePtr b3 = b1; // BAD: can't copy-assign a UniquePtr - * - * (Note that changing a UniquePtr to store a direct |new| expression is - * permitted, but usually you should use MakeUnique, defined at the end of this - * header.) - * - * A few miscellaneous notes: - * - * UniquePtr, when not instantiated for an array type, can be move-constructed - * and move-assigned, not only from itself but from "derived" UniquePtr - * instantiations where U converts to T and E converts to D. If you want to use - * this, you're going to have to specify a deletion policy for both UniquePtr - * instantations, and T pretty much has to have a virtual destructor. In other - * words, this doesn't work: - * - * struct Base { virtual ~Base() {} }; - * struct Derived : Base {}; - * - * UniquePtr b1; - * // BAD: DefaultDelete and DefaultDelete don't interconvert - * UniquePtr d1(Move(b)); - * - * UniquePtr b2; - * UniquePtr> d2(Move(b2)); // okay - * - * UniquePtr is specialized for array types. Specializing with an array type - * creates a smart-pointer version of that array -- not a pointer to such an - * array. - * - * UniquePtr arr(new int[5]); - * arr[0] = 4; - * - * What else is different? Deletion of course uses |delete[]|. An operator[] - * is provided. Functionality that doesn't make sense for arrays is removed. - * The constructors and mutating methods only accept array pointers (not T*, U* - * that converts to T*, or UniquePtr or UniquePtr) or |nullptr|. - * - * It's perfectly okay for a function to return a UniquePtr. This transfers - * the UniquePtr's sole ownership of the data, to the fresh UniquePtr created - * in the calling function, that will then solely own that data. Such functions - * can return a local variable UniquePtr, |nullptr|, |UniquePtr(ptr)| where - * |ptr| is a |T*|, or a UniquePtr |Move()|'d from elsewhere. - * - * UniquePtr will commonly be a member of a class, with lifetime equivalent to - * that of that class. If you want to expose the related resource, you could - * expose a raw pointer via |get()|, but ownership of a raw pointer is - * inherently unclear. So it's better to expose a |const UniquePtr&| instead. - * This prohibits mutation but still allows use of |get()| when needed (but - * operator-> is preferred). Of course, you can only use this smart pointer as - * long as the enclosing class instance remains live -- no different than if you - * exposed the |get()| raw pointer. - * - * To pass a UniquePtr-managed resource as a pointer, use a |const UniquePtr&| - * argument. To specify an inout parameter (where the method may or may not - * take ownership of the resource, or reset it), or to specify an out parameter - * (where simply returning a |UniquePtr| isn't possible), use a |UniquePtr&| - * argument. To unconditionally transfer ownership of a UniquePtr - * into a method, use a |UniquePtr| argument. To conditionally transfer - * ownership of a resource into a method, should the method want it, use a - * |UniquePtr&&| argument. - */ -template -class UniquePtr -{ -public: - typedef T ElementType; - typedef D DeleterType; - typedef typename detail::PointerType::Type Pointer; - -private: - Pair mTuple; - - Pointer& ptr() { return mTuple.first(); } - const Pointer& ptr() const { return mTuple.first(); } - - DeleterType& del() { return mTuple.second(); } - const DeleterType& del() const { return mTuple.second(); } - -public: - /** - * Construct a UniquePtr containing |nullptr|. - */ - constexpr UniquePtr() - : mTuple(static_cast(nullptr), DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - /** - * Construct a UniquePtr containing |aPtr|. - */ - explicit UniquePtr(Pointer aPtr) - : mTuple(aPtr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - UniquePtr(Pointer aPtr, - typename Conditional::value, - D, - const D&>::Type aD1) - : mTuple(aPtr, aD1) - {} - - // If you encounter an error with MSVC10 about RemoveReference below, along - // the lines that "more than one partial specialization matches the template - // argument list": don't use UniquePtr! Ideally - // you should make deletion use the same function every time, using a - // deleter policy: - // - // // BAD, won't compile with MSVC10, deleter doesn't need to be a - // // variable at all - // typedef void (&FreeSignature)(void*); - // UniquePtr ptr((int*) malloc(sizeof(int)), free); - // - // // GOOD, compiles with MSVC10, deletion behavior statically known and - // // optimizable - // struct DeleteByFreeing - // { - // void operator()(void* aPtr) { free(aPtr); } - // }; - // - // If deletion really, truly, must be a variable: you might be able to work - // around this with a deleter class that contains the function reference. - // But this workaround is untried and untested, because variable deletion - // behavior really isn't something you should use. - UniquePtr(Pointer aPtr, - typename RemoveReference::Type&& aD2) - : mTuple(aPtr, Move(aD2)) - { - static_assert(!IsReference::value, - "rvalue deleter can't be stored by reference"); - } - - UniquePtr(UniquePtr&& aOther) - : mTuple(aOther.release(), Forward(aOther.get_deleter())) - {} - - MOZ_IMPLICIT - UniquePtr(decltype(nullptr)) - : mTuple(nullptr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - template - MOZ_IMPLICIT - UniquePtr(UniquePtr&& aOther, - typename EnableIf::Pointer, - Pointer>::value && - !IsArray::value && - (IsReference::value - ? IsSame::value - : IsConvertible::value), - int>::Type aDummy = 0) - : mTuple(aOther.release(), Forward(aOther.get_deleter())) - { - } - - ~UniquePtr() { reset(nullptr); } - - UniquePtr& operator=(UniquePtr&& aOther) - { - reset(aOther.release()); - get_deleter() = Forward(aOther.get_deleter()); - return *this; - } - - template - UniquePtr& operator=(UniquePtr&& aOther) - { - static_assert(IsConvertible::Pointer, - Pointer>::value, - "incompatible UniquePtr pointees"); - static_assert(!IsArray::value, - "can't assign from UniquePtr holding an array"); - - reset(aOther.release()); - get_deleter() = Forward(aOther.get_deleter()); - return *this; - } - - UniquePtr& operator=(decltype(nullptr)) - { - reset(nullptr); - return *this; - } - - T& operator*() const { return *get(); } - Pointer operator->() const - { - MOZ_ASSERT(get(), "dereferencing a UniquePtr containing nullptr"); - return get(); - } - - explicit operator bool() const { return get() != nullptr; } - - Pointer get() const { return ptr(); } - - DeleterType& get_deleter() { return del(); } - const DeleterType& get_deleter() const { return del(); } - - MOZ_MUST_USE Pointer release() - { - Pointer p = ptr(); - ptr() = nullptr; - return p; - } - - void reset(Pointer aPtr = Pointer()) - { - Pointer old = ptr(); - ptr() = aPtr; - if (old != nullptr) { - get_deleter()(old); - } - } - - void swap(UniquePtr& aOther) - { - mTuple.swap(aOther.mTuple); - } - - UniquePtr(const UniquePtr& aOther) = delete; // construct using Move()! - void operator=(const UniquePtr& aOther) = delete; // assign using Move()! -}; - -// In case you didn't read the comment by the main definition (you should!): the -// UniquePtr specialization exists to manage array pointers. It deletes -// such pointers using delete[], it will reject construction and modification -// attempts using U* or U[]. Otherwise it works like the normal UniquePtr. -template -class UniquePtr -{ -public: - typedef T* Pointer; - typedef T ElementType; - typedef D DeleterType; - -private: - Pair mTuple; - -public: - /** - * Construct a UniquePtr containing nullptr. - */ - constexpr UniquePtr() - : mTuple(static_cast(nullptr), DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - /** - * Construct a UniquePtr containing |aPtr|. - */ - explicit UniquePtr(Pointer aPtr) - : mTuple(aPtr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - // delete[] knows how to handle *only* an array of a single class type. For - // delete[] to work correctly, it must know the size of each element, the - // fields and base classes of each element requiring destruction, and so on. - // So forbid all overloads which would end up invoking delete[] on a pointer - // of the wrong type. - template - UniquePtr(U&& aU, - typename EnableIf::value && - IsConvertible::value, - int>::Type aDummy = 0) - = delete; - - UniquePtr(Pointer aPtr, - typename Conditional::value, - D, - const D&>::Type aD1) - : mTuple(aPtr, aD1) - {} - - // If you encounter an error with MSVC10 about RemoveReference below, along - // the lines that "more than one partial specialization matches the template - // argument list": don't use UniquePtr! See the - // comment by this constructor in the non-T[] specialization above. - UniquePtr(Pointer aPtr, - typename RemoveReference::Type&& aD2) - : mTuple(aPtr, Move(aD2)) - { - static_assert(!IsReference::value, - "rvalue deleter can't be stored by reference"); - } - - // Forbidden for the same reasons as stated above. - template - UniquePtr(U&& aU, V&& aV, - typename EnableIf::value && - IsConvertible::value, - int>::Type aDummy = 0) - = delete; - - UniquePtr(UniquePtr&& aOther) - : mTuple(aOther.release(), Forward(aOther.get_deleter())) - {} - - MOZ_IMPLICIT - UniquePtr(decltype(nullptr)) - : mTuple(nullptr, DeleterType()) - { - static_assert(!IsPointer::value, "must provide a deleter instance"); - static_assert(!IsReference::value, "must provide a deleter instance"); - } - - ~UniquePtr() { reset(nullptr); } - - UniquePtr& operator=(UniquePtr&& aOther) - { - reset(aOther.release()); - get_deleter() = Forward(aOther.get_deleter()); - return *this; - } - - UniquePtr& operator=(decltype(nullptr)) - { - reset(); - return *this; - } - - explicit operator bool() const { return get() != nullptr; } - - T& operator[](decltype(sizeof(int)) aIndex) const { return get()[aIndex]; } - Pointer get() const { return mTuple.first(); } - - DeleterType& get_deleter() { return mTuple.second(); } - const DeleterType& get_deleter() const { return mTuple.second(); } - - MOZ_MUST_USE Pointer release() - { - Pointer p = mTuple.first(); - mTuple.first() = nullptr; - return p; - } - - void reset(Pointer aPtr = Pointer()) - { - Pointer old = mTuple.first(); - mTuple.first() = aPtr; - if (old != nullptr) { - mTuple.second()(old); - } - } - - void reset(decltype(nullptr)) - { - Pointer old = mTuple.first(); - mTuple.first() = nullptr; - if (old != nullptr) { - mTuple.second()(old); - } - } - - template - void reset(U) = delete; - - void swap(UniquePtr& aOther) { mTuple.swap(aOther.mTuple); } - - UniquePtr(const UniquePtr& aOther) = delete; // construct using Move()! - void operator=(const UniquePtr& aOther) = delete; // assign using Move()! -}; - -/** - * A default deletion policy using plain old operator delete. - * - * Note that this type can be specialized, but authors should beware of the risk - * that the specialization may at some point cease to match (either because it - * gets moved to a different compilation unit or the signature changes). If the - * non-specialized (|delete|-based) version compiles for that type but does the - * wrong thing, bad things could happen. - * - * This is a non-issue for types which are always incomplete (i.e. opaque handle - * types), since |delete|-ing such a type will always trigger a compilation - * error. - */ -template -class DefaultDelete -{ -public: - constexpr DefaultDelete() {} - - template - MOZ_IMPLICIT DefaultDelete(const DefaultDelete& aOther, - typename EnableIf::value, - int>::Type aDummy = 0) - {} - - void operator()(T* aPtr) const - { - static_assert(sizeof(T) > 0, "T must be complete"); - delete aPtr; - } -}; - -/** A default deletion policy using operator delete[]. */ -template -class DefaultDelete -{ -public: - constexpr DefaultDelete() {} - - void operator()(T* aPtr) const - { - static_assert(sizeof(T) > 0, "T must be complete"); - delete[] aPtr; - } - - template - void operator()(U* aPtr) const = delete; -}; - -template -void -Swap(UniquePtr& aX, UniquePtr& aY) -{ - aX.swap(aY); -} - -template -bool -operator==(const UniquePtr& aX, const UniquePtr& aY) -{ - return aX.get() == aY.get(); -} - -template -bool -operator!=(const UniquePtr& aX, const UniquePtr& aY) -{ - return aX.get() != aY.get(); -} - -template -bool -operator==(const UniquePtr& aX, decltype(nullptr)) -{ - return !aX; -} - -template -bool -operator==(decltype(nullptr), const UniquePtr& aX) -{ - return !aX; -} - -template -bool -operator!=(const UniquePtr& aX, decltype(nullptr)) -{ - return bool(aX); -} - -template -bool -operator!=(decltype(nullptr), const UniquePtr& aX) -{ - return bool(aX); -} - -// No operator<, operator>, operator<=, operator>= for now because simplicity. - -namespace detail { - -template -struct UniqueSelector -{ - typedef UniquePtr SingleObject; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr UnknownBound; -}; - -template -struct UniqueSelector -{ - typedef UniquePtr KnownBound; -}; - -} // namespace detail - -/** - * MakeUnique is a helper function for allocating new'd objects and arrays, - * returning a UniquePtr containing the resulting pointer. The semantics of - * MakeUnique(...) are as follows. - * - * If Type is an array T[n]: - * Disallowed, deleted, no overload for you! - * If Type is an array T[]: - * MakeUnique(size_t) is the only valid overload. The pointer returned - * is as if by |new T[n]()|, which value-initializes each element. (If T - * isn't a class type, this will zero each element. If T is a class type, - * then roughly speaking, each element will be constructed using its default - * constructor. See C++11 [dcl.init]p7 for the full gory details.) - * If Type is non-array T: - * The arguments passed to MakeUnique(...) are forwarded into a - * |new T(...)| call, initializing the T as would happen if executing - * |T(...)|. - * - * There are various benefits to using MakeUnique instead of |new| expressions. - * - * First, MakeUnique eliminates use of |new| from code entirely. If objects are - * only created through UniquePtr, then (assuming all explicit release() calls - * are safe, including transitively, and no type-safety casting funniness) - * correctly maintained ownership of the UniquePtr guarantees no leaks are - * possible. (This pays off best if a class is only ever created through a - * factory method on the class, using a private constructor.) - * - * Second, initializing a UniquePtr using a |new| expression requires repeating - * the name of the new'd type, whereas MakeUnique in concert with the |auto| - * keyword names it only once: - * - * UniquePtr ptr1(new char()); // repetitive - * auto ptr2 = MakeUnique(); // shorter - * - * Of course this assumes the reader understands the operation MakeUnique - * performs. In the long run this is probably a reasonable assumption. In the - * short run you'll have to use your judgment about what readers can be expected - * to know, or to quickly look up. - * - * Third, a call to MakeUnique can be assigned directly to a UniquePtr. In - * contrast you can't assign a pointer into a UniquePtr without using the - * cumbersome reset(). - * - * UniquePtr p; - * p = new char; // ERROR - * p.reset(new char); // works, but fugly - * p = MakeUnique(); // preferred - * - * (And third, although not relevant to Mozilla: MakeUnique is exception-safe. - * An exception thrown after |new T| succeeds will leak that memory, unless the - * pointer is assigned to an object that will manage its ownership. UniquePtr - * ably serves this function.) - */ - -template -typename detail::UniqueSelector::SingleObject -MakeUnique(Args&&... aArgs) -{ - return UniquePtr(new T(Forward(aArgs)...)); -} - -template -typename detail::UniqueSelector::UnknownBound -MakeUnique(decltype(sizeof(int)) aN) -{ - typedef typename RemoveExtent::Type ArrayType; - return UniquePtr(new ArrayType[aN]()); -} - -template -typename detail::UniqueSelector::KnownBound -MakeUnique(Args&&... aArgs) = delete; - -} // namespace mozilla - -#endif /* mozilla_UniquePtr_h */ diff --git a/win32/include/spidermonkey/mozilla/UniquePtrExtensions.h b/win32/include/spidermonkey/mozilla/UniquePtrExtensions.h deleted file mode 100755 index d94f33ee..00000000 --- a/win32/include/spidermonkey/mozilla/UniquePtrExtensions.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Useful extensions to UniquePtr. */ - -#ifndef mozilla_UniquePtrExtensions_h -#define mozilla_UniquePtrExtensions_h - -#include "mozilla/fallible.h" -#include "mozilla/UniquePtr.h" - -namespace mozilla { - -/** - * MakeUniqueFallible works exactly like MakeUnique, except that the memory - * allocation performed is done fallibly, i.e. it can return nullptr. - */ -template -typename detail::UniqueSelector::SingleObject -MakeUniqueFallible(Args&&... aArgs) -{ - return UniquePtr(new (fallible) T(Forward(aArgs)...)); -} - -template -typename detail::UniqueSelector::UnknownBound -MakeUniqueFallible(decltype(sizeof(int)) aN) -{ - typedef typename RemoveExtent::Type ArrayType; - return UniquePtr(new (fallible) ArrayType[aN]()); -} - -template -typename detail::UniqueSelector::KnownBound -MakeUniqueFallible(Args&&... aArgs) = delete; - -namespace detail { - -template -struct FreePolicy -{ - void operator()(const void* ptr) { - free(const_cast(ptr)); - } -}; - -} // namespace detail - -template -using UniqueFreePtr = UniquePtr>; - -} // namespace mozilla - -#endif // mozilla_UniquePtrExtensions_h diff --git a/win32/include/spidermonkey/mozilla/Unused.h b/win32/include/spidermonkey/mozilla/Unused.h deleted file mode 100755 index e693e32a..00000000 --- a/win32/include/spidermonkey/mozilla/Unused.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_unused_h -#define mozilla_unused_h - -#include "mozilla/Types.h" - -#ifdef __cplusplus - -namespace mozilla { - -// -// Suppress GCC warnings about unused return values with -// Unused << SomeFuncDeclaredWarnUnusedReturnValue(); -// -struct unused_t -{ - template - inline void - operator<<(const T& /*unused*/) const {} -}; - -extern MFBT_DATA const unused_t Unused; - -} // namespace mozilla - -#endif // __cplusplus - -// An alternative to mozilla::Unused for use in (a) C code and (b) code where -// linking with unused.o is difficult. -#define MOZ_UNUSED(expr) \ - do { if (expr) { (void)0; } } while (0) - -#endif // mozilla_unused_h diff --git a/win32/include/spidermonkey/mozilla/Variant.h b/win32/include/spidermonkey/mozilla/Variant.h deleted file mode 100755 index 8a33286e..00000000 --- a/win32/include/spidermonkey/mozilla/Variant.h +++ /dev/null @@ -1,625 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A template class for tagged unions. */ - -#include -#include - -#include "mozilla/Alignment.h" -#include "mozilla/Assertions.h" -#include "mozilla/Move.h" -#include "mozilla/TypeTraits.h" - -#ifndef mozilla_Variant_h -#define mozilla_Variant_h - -namespace mozilla { - -template -class Variant; - -namespace detail { - -// MaxSizeOf computes the maximum sizeof(T) for each T in Ts. - -template -struct MaxSizeOf -{ - static const size_t size = sizeof(T) > MaxSizeOf::size - ? sizeof(T) - : MaxSizeOf::size; -}; - -template -struct MaxSizeOf -{ - static const size_t size = sizeof(T); -}; - -// The `IsVariant` helper is used in conjunction with static_assert and -// `mozilla::EnableIf` to catch passing non-variant types to `Variant::is()` -// and friends at compile time, rather than at runtime. It ensures that the -// given type `Needle` is one of the types in the set of types `Haystack`. - -template -struct IsVariant; - -template -struct IsVariant -{ - static const bool value = false; -}; - -template -struct IsVariant -{ - static const bool value = true; -}; - -template -struct IsVariant : public IsVariant { }; - -/// SelectVariantTypeHelper is used in the implementation of SelectVariantType. -template -struct SelectVariantTypeHelper; - -template -struct SelectVariantTypeHelper -{ }; - -template -struct SelectVariantTypeHelper -{ - typedef T Type; -}; - -template -struct SelectVariantTypeHelper -{ - typedef const T Type; -}; - -template -struct SelectVariantTypeHelper -{ - typedef const T& Type; -}; - -template -struct SelectVariantTypeHelper -{ - typedef T&& Type; -}; - -template -struct SelectVariantTypeHelper - : public SelectVariantTypeHelper -{ }; - -/** - * SelectVariantType takes a type T and a list of variant types Variants and - * yields a type Type, selected from Variants, that can store a value of type T - * or a reference to type T. If no such type was found, Type is not defined. - */ -template -struct SelectVariantType - : public SelectVariantTypeHelper::Type>::Type, - Variants...> -{ }; - -// Compute a fast, compact type that can be used to hold integral values that -// distinctly map to every type in Ts. -template -struct VariantTag -{ -private: - static const size_t TypeCount = sizeof...(Ts); - -public: - using Type = - typename Conditional::Type - >::Type; -}; - -// TagHelper gets the given sentinel tag value for the given type T. This has to -// be split out from VariantImplementation because you can't nest a partial -// template specialization within a template class. - -template -struct TagHelper; - -// In the case where T != U, we continue recursion. -template -struct TagHelper -{ - static Tag tag() { return Next::template tag(); } -}; - -// In the case where T == U, return the tag number. -template -struct TagHelper -{ - static Tag tag() { return Tag(N); } -}; - -// The VariantImplementation template provides the guts of mozilla::Variant. We -// create a VariantImplementation for each T in Ts... which handles -// construction, destruction, etc for when the Variant's type is T. If the -// Variant's type isn't T, it punts the request on to the next -// VariantImplementation. - -template -struct VariantImplementation; - -// The singly typed Variant / recursion base case. -template -struct VariantImplementation -{ - template - static Tag tag() { - static_assert(mozilla::IsSame::value, - "mozilla::Variant: tag: bad type!"); - return Tag(N); - } - - template - static void copyConstruct(void* aLhs, const Variant& aRhs) { - new (aLhs) T(aRhs.template as()); - } - - template - static void moveConstruct(void* aLhs, Variant&& aRhs) { - new (aLhs) T(aRhs.template extract()); - } - - template - static void destroy(Variant& aV) { - aV.template as().~T(); - } - - template - static bool - equal(const Variant& aLhs, const Variant& aRhs) { - return aLhs.template as() == aRhs.template as(); - } - - template - static auto - match(Matcher&& aMatcher, ConcreteVariant& aV) - -> decltype(aMatcher.match(aV.template as())) - { - return aMatcher.match(aV.template as()); - } -}; - -// VariantImplementation for some variant type T. -template -struct VariantImplementation -{ - // The next recursive VariantImplementation. - using Next = VariantImplementation; - - template - static Tag tag() { - return TagHelper::value>::tag(); - } - - template - static void copyConstruct(void* aLhs, const Variant& aRhs) { - if (aRhs.template is()) { - new (aLhs) T(aRhs.template as()); - } else { - Next::copyConstruct(aLhs, aRhs); - } - } - - template - static void moveConstruct(void* aLhs, Variant&& aRhs) { - if (aRhs.template is()) { - new (aLhs) T(aRhs.template extract()); - } else { - Next::moveConstruct(aLhs, aRhs); - } - } - - template - static void destroy(Variant& aV) { - if (aV.template is()) { - aV.template as().~T(); - } else { - Next::destroy(aV); - } - } - - template - static bool equal(const Variant& aLhs, const Variant& aRhs) { - if (aLhs.template is()) { - MOZ_ASSERT(aRhs.template is()); - return aLhs.template as() == aRhs.template as(); - } else { - return Next::equal(aLhs, aRhs); - } - } - - template - static auto - match(Matcher&& aMatcher, ConcreteVariant& aV) - -> decltype(aMatcher.match(aV.template as())) - { - if (aV.template is()) { - return aMatcher.match(aV.template as()); - } else { - // If you're seeing compilation errors here like "no matching - // function for call to 'match'" then that means that the - // Matcher doesn't exhaust all variant types. There must exist a - // Matcher::match(T&) for every variant type T. - // - // If you're seeing compilation errors here like "cannot - // initialize return object of type <...> with an rvalue of type - // <...>" then that means that the Matcher::match(T&) overloads - // are returning different types. They must all return the same - // Matcher::ReturnType type. - return Next::match(aMatcher, aV); - } - } -}; - -/** - * AsVariantTemporary stores a value of type T to allow construction of a - * Variant value via type inference. Because T is copied and there's no - * guarantee that the copy can be elided, AsVariantTemporary is best used with - * primitive or very small types. - */ -template -struct AsVariantTemporary -{ - explicit AsVariantTemporary(const T& aValue) - : mValue(aValue) - {} - - template - explicit AsVariantTemporary(U&& aValue) - : mValue(Forward(aValue)) - {} - - AsVariantTemporary(const AsVariantTemporary& aOther) - : mValue(aOther.mValue) - {} - - AsVariantTemporary(AsVariantTemporary&& aOther) - : mValue(Move(aOther.mValue)) - {} - - AsVariantTemporary() = delete; - void operator=(const AsVariantTemporary&) = delete; - void operator=(AsVariantTemporary&&) = delete; - - typename RemoveConst::Type>::Type mValue; -}; - -} // namespace detail - -/** - * # mozilla::Variant - * - * A variant / tagged union / heterogenous disjoint union / sum-type template - * class. Similar in concept to (but not derived from) `boost::variant`. - * - * Sometimes, you may wish to use a C union with non-POD types. However, this is - * forbidden in C++ because it is not clear which type in the union should have - * its constructor and destructor run on creation and deletion - * respectively. This is the problem that `mozilla::Variant` solves. - * - * ## Usage - * - * A `mozilla::Variant` instance is constructed (via move or copy) from one of - * its variant types (ignoring const and references). It does *not* support - * construction from subclasses of variant types or types that coerce to one of - * the variant types. - * - * Variant v1('a'); - * Variant, B, C> v2(MakeUnique()); - * - * Because specifying the full type of a Variant value is often verbose, - * AsVariant() can be used to construct a Variant value using type inference in - * contexts such as expressions or when returning values from functions. Because - * AsVariant() must copy or move the value into a temporary and this cannot - * necessarily be elided by the compiler, it's mostly appropriate only for use - * with primitive or very small types. - * - * - * Variant Foo() { return AsVariant('x'); } - * // ... - * Variant v1 = Foo(); // v1 holds char('x'). - * - * All access to the contained value goes through type-safe accessors. - * - * void - * Foo(Variant v) - * { - * if (v.is()) { - * A& ref = v.as(); - * ... - * } else { - * ... - * } - * } - * - * Attempting to use the contained value as type `T1` when the `Variant` - * instance contains a value of type `T2` causes an assertion failure. - * - * A a; - * Variant v(a); - * v.as(); // <--- Assertion failure! - * - * Trying to use a `Variant` instance as some type `U` that is not a - * member of the set of `Ts...` is a compiler error. - * - * A a; - * Variant v(a); - * v.as(); // <--- Compiler error! - * - * Additionally, you can turn a `Variant` that `is` into a `T` by moving it - * out of the containing `Variant` instance with the `extract` method: - * - * Variant, B, C> v(MakeUnique()); - * auto ptr = v.extract>(); - * - * Finally, you can exhaustively match on the contained variant and branch into - * different code paths depending which type is contained. This is preferred to - * manually checking every variant type T with is() because it provides - * compile-time checking that you handled every type, rather than runtime - * assertion failures. - * - * // Bad! - * char* foo(Variant& v) { - * if (v.is()) { - * return ...; - * } else if (v.is()) { - * return ...; - * } else { - * return doSomething(v.as()); // Forgot about case D! - * } - * } - * - * // Good! - * struct FooMatcher - * { - * // The return type of all matchers must be identical. - * char* match(A& a) { ... } - * char* match(B& b) { ... } - * char* match(C& c) { ... } - * char* match(D& d) { ... } // Compile-time error to forget D! - * } - * char* foo(Variant& v) { - * return v.match(FooMatcher()); - * } - * - * ## Examples - * - * A tree is either an empty leaf, or a node with a value and two children: - * - * struct Leaf { }; - * - * template - * struct Node - * { - * T value; - * Tree* left; - * Tree* right; - * }; - * - * template - * using Tree = Variant>; - * - * A copy-on-write string is either a non-owning reference to some existing - * string, or an owning reference to our copy: - * - * class CopyOnWriteString - * { - * Variant> string; - * - * ... - * }; - */ -template -class MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS Variant -{ - using Tag = typename detail::VariantTag::Type; - using Impl = detail::VariantImplementation; - using RawData = AlignedStorage::size>; - - // Raw storage for the contained variant value. - RawData raw; - - // Each type is given a unique tag value that lets us keep track of the - // contained variant value's type. - Tag tag; - - void* ptr() { - return reinterpret_cast(&raw); - } - -public: - /** Perfect forwarding construction for some variant type T. */ - template::Type> - explicit Variant(RefT&& aT) - : tag(Impl::template tag()) - { - new (ptr()) T(Forward(aT)); - } - - /** - * Constructs this Variant from an AsVariantTemporary such that T can be - * stored in one of the types allowable in this Variant. This is used in the - * implementation of AsVariant(). - */ - template::Type> - MOZ_IMPLICIT Variant(detail::AsVariantTemporary&& aValue) - : tag(Impl::template tag()) - { - new (ptr()) T(Move(aValue.mValue)); - } - - /** Copy construction. */ - Variant(const Variant& aRhs) - : tag(aRhs.tag) - { - Impl::copyConstruct(ptr(), aRhs); - } - - /** Move construction. */ - Variant(Variant&& aRhs) - : tag(aRhs.tag) - { - Impl::moveConstruct(ptr(), Move(aRhs)); - } - - /** Copy assignment. */ - Variant& operator=(const Variant& aRhs) { - MOZ_ASSERT(&aRhs != this, "self-assign disallowed"); - this->~Variant(); - new (this) Variant(aRhs); - return *this; - } - - /** Move assignment. */ - Variant& operator=(Variant&& aRhs) { - MOZ_ASSERT(&aRhs != this, "self-assign disallowed"); - this->~Variant(); - new (this) Variant(Move(aRhs)); - return *this; - } - - /** Move assignment from AsVariant(). */ - template - Variant& operator=(detail::AsVariantTemporary&& aValue) - { - this->~Variant(); - new (this) Variant(Move(aValue)); - return *this; - } - - ~Variant() - { - Impl::destroy(*this); - } - - /** Check which variant type is currently contained. */ - template - bool is() const { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - return Impl::template tag() == tag; - } - - /** - * Operator == overload that defers to the variant type's operator== - * implementation if the rhs is tagged as the same type as this one. - */ - bool operator==(const Variant& aRhs) const { - return tag == aRhs.tag && Impl::equal(*this, aRhs); - } - - /** - * Operator != overload that defers to the negation of the variant type's - * operator== implementation if the rhs is tagged as the same type as this - * one. - */ - bool operator!=(const Variant& aRhs) const { - return !(*this == aRhs); - } - - // Accessors for working with the contained variant value. - - /** Mutable reference. */ - template - T& as() { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - MOZ_ASSERT(is()); - return *reinterpret_cast(&raw); - } - - /** Immutable const reference. */ - template - const T& as() const { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - MOZ_ASSERT(is()); - return *reinterpret_cast(&raw); - } - - /** - * Extract the contained variant value from this container into a temporary - * value. On completion, the value in the variant will be in a - * safely-destructible state, as determined by the behavior of T's move - * constructor when provided the variant's internal value. - */ - template - T extract() { - static_assert(detail::IsVariant::value, - "provided a type not found in this Variant's type list"); - MOZ_ASSERT(is()); - return T(Move(as())); - } - - // Exhaustive matching of all variant types on the contained value. - - /** Match on an immutable const reference. */ - template - auto - match(Matcher&& aMatcher) const - -> decltype(Impl::match(aMatcher, *this)) - { - return Impl::match(aMatcher, *this); - } - - /** Match on a mutable non-const reference. */ - template - auto - match(Matcher&& aMatcher) - -> decltype(Impl::match(aMatcher, *this)) - { - return Impl::match(aMatcher, *this); - } -}; - -/* - * AsVariant() is used to construct a Variant value containing the - * provided T value using type inference. It can be used to construct Variant - * values in expressions or return them from functions without specifying the - * entire Variant type. - * - * Because AsVariant() must copy or move the value into a temporary and this - * cannot necessarily be elided by the compiler, it's mostly appropriate only - * for use with primitive or very small types. - * - * AsVariant() returns a AsVariantTemporary value which is implicitly - * convertible to any Variant that can hold a value of type T. - */ -template -detail::AsVariantTemporary -AsVariant(T&& aValue) -{ - return detail::AsVariantTemporary(Forward(aValue)); -} - -} // namespace mozilla - -#endif /* mozilla_Variant_h */ diff --git a/win32/include/spidermonkey/mozilla/Vector.h b/win32/include/spidermonkey/mozilla/Vector.h deleted file mode 100755 index fc43afcf..00000000 --- a/win32/include/spidermonkey/mozilla/Vector.h +++ /dev/null @@ -1,1491 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* A type/length-parametrized vector class. */ - -#ifndef mozilla_Vector_h -#define mozilla_Vector_h - -#include "mozilla/Alignment.h" -#include "mozilla/AllocPolicy.h" -#include "mozilla/ArrayUtils.h" // for PointerRangeSize -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/MathAlgorithms.h" -#include "mozilla/MemoryReporting.h" -#include "mozilla/Move.h" -#include "mozilla/OperatorNewExtensions.h" -#include "mozilla/ReentrancyGuard.h" -#include "mozilla/TemplateLib.h" -#include "mozilla/TypeTraits.h" - -#include // for placement new - -/* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4345) -#endif - -namespace mozilla { - -template -class Vector; - -namespace detail { - -/* - * Check that the given capacity wastes the minimal amount of space if - * allocated on the heap. This means that aCapacity*sizeof(T) is as close to a - * power-of-two as possible. growStorageBy() is responsible for ensuring this. - */ -template -static bool CapacityHasExcessSpace(size_t aCapacity) -{ - size_t size = aCapacity * sizeof(T); - return RoundUpPow2(size) - size >= sizeof(T); -} - -/* - * This template class provides a default implementation for vector operations - * when the element type is not known to be a POD, as judged by IsPod. - */ -template -struct VectorImpl -{ - /* - * Constructs an object in the uninitialized memory at *aDst with aArgs. - */ - template - MOZ_NONNULL(1) - static inline void new_(T* aDst, Args&&... aArgs) - { - new(KnownNotNull, aDst) T(Forward(aArgs)...); - } - - /* Destroys constructed objects in the range [aBegin, aEnd). */ - static inline void destroy(T* aBegin, T* aEnd) - { - MOZ_ASSERT(aBegin <= aEnd); - for (T* p = aBegin; p < aEnd; ++p) { - p->~T(); - } - } - - /* Constructs objects in the uninitialized range [aBegin, aEnd). */ - static inline void initialize(T* aBegin, T* aEnd) - { - MOZ_ASSERT(aBegin <= aEnd); - for (T* p = aBegin; p < aEnd; ++p) { - new_(p); - } - } - - /* - * Copy-constructs objects in the uninitialized range - * [aDst, aDst+(aSrcEnd-aSrcStart)) from the range [aSrcStart, aSrcEnd). - */ - template - static inline void copyConstruct(T* aDst, - const U* aSrcStart, const U* aSrcEnd) - { - MOZ_ASSERT(aSrcStart <= aSrcEnd); - for (const U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) { - new_(aDst, *p); - } - } - - /* - * Move-constructs objects in the uninitialized range - * [aDst, aDst+(aSrcEnd-aSrcStart)) from the range [aSrcStart, aSrcEnd). - */ - template - static inline void moveConstruct(T* aDst, U* aSrcStart, U* aSrcEnd) - { - MOZ_ASSERT(aSrcStart <= aSrcEnd); - for (U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) { - new_(aDst, Move(*p)); - } - } - - /* - * Copy-constructs objects in the uninitialized range [aDst, aDst+aN) from - * the same object aU. - */ - template - static inline void copyConstructN(T* aDst, size_t aN, const U& aU) - { - for (T* end = aDst + aN; aDst < end; ++aDst) { - new_(aDst, aU); - } - } - - /* - * Grows the given buffer to have capacity aNewCap, preserving the objects - * constructed in the range [begin, end) and updating aV. Assumes that (1) - * aNewCap has not overflowed, and (2) multiplying aNewCap by sizeof(T) will - * not overflow. - */ - static inline MOZ_MUST_USE bool - growTo(Vector& aV, size_t aNewCap) - { - MOZ_ASSERT(!aV.usingInlineStorage()); - MOZ_ASSERT(!CapacityHasExcessSpace(aNewCap)); - T* newbuf = aV.template pod_malloc(aNewCap); - if (MOZ_UNLIKELY(!newbuf)) { - return false; - } - T* dst = newbuf; - T* src = aV.beginNoCheck(); - for (; src < aV.endNoCheck(); ++dst, ++src) { - new_(dst, Move(*src)); - } - VectorImpl::destroy(aV.beginNoCheck(), aV.endNoCheck()); - aV.free_(aV.mBegin); - aV.mBegin = newbuf; - /* aV.mLength is unchanged. */ - aV.mCapacity = aNewCap; - return true; - } -}; - -/* - * This partial template specialization provides a default implementation for - * vector operations when the element type is known to be a POD, as judged by - * IsPod. - */ -template -struct VectorImpl -{ - template - MOZ_NONNULL(1) - static inline void new_(T* aDst, Args&&... aArgs) - { - // Explicitly construct a local object instead of using a temporary since - // T(args...) will be treated like a C-style cast in the unary case and - // allow unsafe conversions. Both forms should be equivalent to an - // optimizing compiler. - T temp(Forward(aArgs)...); - *aDst = temp; - } - - static inline void destroy(T*, T*) {} - - static inline void initialize(T* aBegin, T* aEnd) - { - /* - * You would think that memset would be a big win (or even break even) - * when we know T is a POD. But currently it's not. This is probably - * because |append| tends to be given small ranges and memset requires - * a function call that doesn't get inlined. - * - * memset(aBegin, 0, sizeof(T) * (aEnd - aBegin)); - */ - MOZ_ASSERT(aBegin <= aEnd); - for (T* p = aBegin; p < aEnd; ++p) { - new_(p); - } - } - - template - static inline void copyConstruct(T* aDst, - const U* aSrcStart, const U* aSrcEnd) - { - /* - * See above memset comment. Also, notice that copyConstruct is - * currently templated (T != U), so memcpy won't work without - * requiring T == U. - * - * memcpy(aDst, aSrcStart, sizeof(T) * (aSrcEnd - aSrcStart)); - */ - MOZ_ASSERT(aSrcStart <= aSrcEnd); - for (const U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) { - new_(aDst, *p); - } - } - - template - static inline void moveConstruct(T* aDst, - const U* aSrcStart, const U* aSrcEnd) - { - copyConstruct(aDst, aSrcStart, aSrcEnd); - } - - static inline void copyConstructN(T* aDst, size_t aN, const T& aT) - { - for (T* end = aDst + aN; aDst < end; ++aDst) { - new_(aDst, aT); - } - } - - static inline MOZ_MUST_USE bool - growTo(Vector& aV, size_t aNewCap) - { - MOZ_ASSERT(!aV.usingInlineStorage()); - MOZ_ASSERT(!CapacityHasExcessSpace(aNewCap)); - T* newbuf = aV.template pod_realloc(aV.mBegin, aV.mCapacity, aNewCap); - if (MOZ_UNLIKELY(!newbuf)) { - return false; - } - aV.mBegin = newbuf; - /* aV.mLength is unchanged. */ - aV.mCapacity = aNewCap; - return true; - } - - static inline void - podResizeToFit(Vector& aV) - { - if (aV.usingInlineStorage() || aV.mLength == aV.mCapacity) { - return; - } - T* newbuf = aV.template pod_realloc(aV.mBegin, aV.mCapacity, aV.mLength); - if (MOZ_UNLIKELY(!newbuf)) { - return; - } - aV.mBegin = newbuf; - aV.mCapacity = aV.mLength; - } -}; - -// A struct for TestVector.cpp to access private internal fields. -// DO NOT DEFINE IN YOUR OWN CODE. -struct VectorTesting; - -} // namespace detail - -/* - * STL-like container providing a short-lived, dynamic buffer. Vector calls the - * constructors/destructors of all elements stored in its internal buffer, so - * non-PODs may be safely used. Additionally, Vector will store the first N - * elements in-place before resorting to dynamic allocation. - * - * T requirements: - * - default and copy constructible, assignable, destructible - * - operations do not throw - * MinInlineCapacity requirements: - * - any value, however, MinInlineCapacity is clamped to min/max values - * AllocPolicy: - * - see "Allocation policies" in AllocPolicy.h (defaults to - * mozilla::MallocAllocPolicy) - * - * Vector is not reentrant: T member functions called during Vector member - * functions must not call back into the same object! - */ -template -class Vector final : private AllocPolicy -{ - /* utilities */ - - static const bool kElemIsPod = IsPod::value; - typedef detail::VectorImpl Impl; - friend struct detail::VectorImpl; - - friend struct detail::VectorTesting; - - MOZ_MUST_USE bool growStorageBy(size_t aIncr); - MOZ_MUST_USE bool convertToHeapStorage(size_t aNewCap); - MOZ_MUST_USE bool maybeCheckSimulatedOOM(size_t aRequestedSize); - - /* magic constants */ - - static const int kMaxInlineBytes = 1024; - - /* compute constants */ - - /* - * Consider element size to be 1 for buffer sizing if there are 0 inline - * elements. This allows us to compile when the definition of the element - * type is not visible here. - * - * Explicit specialization is only allowed at namespace scope, so in order - * to keep everything here, we use a dummy template parameter with partial - * specialization. - */ - template - struct ElemSize - { - static const size_t value = sizeof(T); - }; - template - struct ElemSize<0, Dummy> - { - static const size_t value = 1; - }; - - static const size_t kInlineCapacity = - tl::Min::value>::value; - - /* Calculate inline buffer size; avoid 0-sized array. */ - static const size_t kInlineBytes = - tl::Max<1, kInlineCapacity * ElemSize::value>::value; - - /* member data */ - - /* - * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin, - * mBegin + mLength) hold valid constructed T objects. The range [mBegin + - * mLength, mBegin + mCapacity) holds uninitialized memory. The range - * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory - * previously allocated by a call to reserve(). - */ - T* mBegin; - - /* Number of elements in the vector. */ - size_t mLength; - - /* Max number of elements storable in the vector without resizing. */ - size_t mCapacity; - -#ifdef DEBUG - /* Max elements of reserved or used space in this vector. */ - size_t mReserved; -#endif - - /* Memory used for inline storage. */ - AlignedStorage mStorage; - -#ifdef DEBUG - friend class ReentrancyGuard; - bool mEntered; -#endif - - /* private accessors */ - - bool usingInlineStorage() const - { - return mBegin == const_cast(this)->inlineStorage(); - } - - T* inlineStorage() - { - return static_cast(mStorage.addr()); - } - - T* beginNoCheck() const - { - return mBegin; - } - - T* endNoCheck() - { - return mBegin + mLength; - } - - const T* endNoCheck() const - { - return mBegin + mLength; - } - -#ifdef DEBUG - /** - * The amount of explicitly allocated space in this vector that is immediately - * available to be filled by appending additional elements. This value is - * always greater than or equal to |length()| -- the vector's actual elements - * are implicitly reserved. This value is always less than or equal to - * |capacity()|. It may be explicitly increased using the |reserve()| method. - */ - size_t reserved() const - { - MOZ_ASSERT(mLength <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - return mReserved; - } -#endif - - /* Append operations guaranteed to succeed due to pre-reserved space. */ - template void internalAppend(U&& aU); - template - void internalAppendAll(const Vector& aU); - void internalAppendN(const T& aT, size_t aN); - template void internalAppend(const U* aBegin, size_t aLength); - -public: - static const size_t sMaxInlineStorage = MinInlineCapacity; - - typedef T ElementType; - - explicit Vector(AllocPolicy = AllocPolicy()); - Vector(Vector&&); /* Move constructor. */ - Vector& operator=(Vector&&); /* Move assignment. */ - ~Vector(); - - /* accessors */ - - const AllocPolicy& allocPolicy() const { return *this; } - - AllocPolicy& allocPolicy() { return *this; } - - enum { InlineLength = MinInlineCapacity }; - - size_t length() const { return mLength; } - - bool empty() const { return mLength == 0; } - - size_t capacity() const { return mCapacity; } - - T* begin() - { - MOZ_ASSERT(!mEntered); - return mBegin; - } - - const T* begin() const - { - MOZ_ASSERT(!mEntered); - return mBegin; - } - - T* end() - { - MOZ_ASSERT(!mEntered); - return mBegin + mLength; - } - - const T* end() const - { - MOZ_ASSERT(!mEntered); - return mBegin + mLength; - } - - T& operator[](size_t aIndex) - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(aIndex < mLength); - return begin()[aIndex]; - } - - const T& operator[](size_t aIndex) const - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(aIndex < mLength); - return begin()[aIndex]; - } - - T& back() - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(!empty()); - return *(end() - 1); - } - - const T& back() const - { - MOZ_ASSERT(!mEntered); - MOZ_ASSERT(!empty()); - return *(end() - 1); - } - - class Range - { - friend class Vector; - T* mCur; - T* mEnd; - Range(T* aCur, T* aEnd) - : mCur(aCur) - , mEnd(aEnd) - { - MOZ_ASSERT(aCur <= aEnd); - } - - public: - bool empty() const { return mCur == mEnd; } - size_t remain() const { return PointerRangeSize(mCur, mEnd); } - T& front() const { MOZ_ASSERT(!empty()); return *mCur; } - void popFront() { MOZ_ASSERT(!empty()); ++mCur; } - T popCopyFront() { MOZ_ASSERT(!empty()); return *mCur++; } - }; - - class ConstRange - { - friend class Vector; - const T* mCur; - const T* mEnd; - ConstRange(const T* aCur, const T* aEnd) - : mCur(aCur) - , mEnd(aEnd) - { - MOZ_ASSERT(aCur <= aEnd); - } - - public: - bool empty() const { return mCur == mEnd; } - size_t remain() const { return PointerRangeSize(mCur, mEnd); } - const T& front() const { MOZ_ASSERT(!empty()); return *mCur; } - void popFront() { MOZ_ASSERT(!empty()); ++mCur; } - T popCopyFront() { MOZ_ASSERT(!empty()); return *mCur++; } - }; - - Range all() { return Range(begin(), end()); } - ConstRange all() const { return ConstRange(begin(), end()); } - - /* mutators */ - - /** - * Reverse the order of the elements in the vector in place. - */ - void reverse(); - - /** - * Given that the vector is empty, grow the internal capacity to |aRequest|, - * keeping the length 0. - */ - MOZ_MUST_USE bool initCapacity(size_t aRequest); - - /** - * Given that the vector is empty, grow the internal capacity and length to - * |aRequest| leaving the elements' memory completely uninitialized (with all - * the associated hazards and caveats). This avoids the usual allocation-size - * rounding that happens in resize and overhead of initialization for elements - * that are about to be overwritten. - */ - MOZ_MUST_USE bool initLengthUninitialized(size_t aRequest); - - /** - * If reserve(aRequest) succeeds and |aRequest >= length()|, then appending - * |aRequest - length()| elements, in any sequence of append/appendAll calls, - * is guaranteed to succeed. - * - * A request to reserve an amount less than the current length does not affect - * reserved space. - */ - MOZ_MUST_USE bool reserve(size_t aRequest); - - /** - * Destroy elements in the range [end() - aIncr, end()). Does not deallocate - * or unreserve storage for those elements. - */ - void shrinkBy(size_t aIncr); - - /** - * Destroy elements in the range [aNewLength, end()). Does not deallocate - * or unreserve storage for those elements. - */ - void shrinkTo(size_t aNewLength); - - /** Grow the vector by aIncr elements. */ - MOZ_MUST_USE bool growBy(size_t aIncr); - - /** Call shrinkBy or growBy based on whether newSize > length(). */ - MOZ_MUST_USE bool resize(size_t aNewLength); - - /** - * Increase the length of the vector, but don't initialize the new elements - * -- leave them as uninitialized memory. - */ - MOZ_MUST_USE bool growByUninitialized(size_t aIncr); - void infallibleGrowByUninitialized(size_t aIncr); - MOZ_MUST_USE bool resizeUninitialized(size_t aNewLength); - - /** Shorthand for shrinkBy(length()). */ - void clear(); - - /** Clears and releases any heap-allocated storage. */ - void clearAndFree(); - - /** - * Calls the AllocPolicy's pod_realloc to release excess capacity. Since - * realloc is only safe on PODs, this method fails to compile if IsPod - * is false. - */ - void podResizeToFit(); - - /** - * If true, appending |aNeeded| elements won't reallocate elements storage. - * This *doesn't* mean that infallibleAppend may be used! You still must - * reserve the extra space, even if this method indicates that appends won't - * need to reallocate elements storage. - */ - bool canAppendWithoutRealloc(size_t aNeeded) const; - - /** Potentially fallible append operations. */ - - /** - * This can take either a T& or a T&&. Given a T&&, it moves |aU| into the - * vector, instead of copying it. If it fails, |aU| is left unmoved. ("We are - * not amused.") - */ - template MOZ_MUST_USE bool append(U&& aU); - - /** - * Construct a T in-place as a new entry at the end of this vector. - */ - template - MOZ_MUST_USE bool emplaceBack(Args&&... aArgs) - { - if (!growByUninitialized(1)) - return false; - Impl::new_(&back(), Forward(aArgs)...); - return true; - } - - template - MOZ_MUST_USE bool appendAll(const Vector& aU); - MOZ_MUST_USE bool appendN(const T& aT, size_t aN); - template MOZ_MUST_USE bool append(const U* aBegin, const U* aEnd); - template MOZ_MUST_USE bool append(const U* aBegin, size_t aLength); - - /* - * Guaranteed-infallible append operations for use upon vectors whose - * memory has been pre-reserved. Don't use this if you haven't reserved the - * memory! - */ - template void infallibleAppend(U&& aU) - { - internalAppend(Forward(aU)); - } - void infallibleAppendN(const T& aT, size_t aN) - { - internalAppendN(aT, aN); - } - template void infallibleAppend(const U* aBegin, const U* aEnd) - { - internalAppend(aBegin, PointerRangeSize(aBegin, aEnd)); - } - template void infallibleAppend(const U* aBegin, size_t aLength) - { - internalAppend(aBegin, aLength); - } - template - void infallibleEmplaceBack(Args&&... aArgs) - { - infallibleGrowByUninitialized(1); - Impl::new_(&back(), Forward(aArgs)...); - } - - void popBack(); - - T popCopy(); - - /** - * If elements are stored in-place, return nullptr and leave this vector - * unmodified. - * - * Otherwise return this vector's elements buffer, and clear this vector as if - * by clearAndFree(). The caller now owns the buffer and is responsible for - * deallocating it consistent with this vector's AllocPolicy. - * - * N.B. Although a T*, only the range [0, length()) is constructed. - */ - MOZ_MUST_USE T* extractRawBuffer(); - - /** - * If elements are stored in-place, allocate a new buffer, move this vector's - * elements into it, and return that buffer. - * - * Otherwise return this vector's elements buffer. The caller now owns the - * buffer and is responsible for deallocating it consistent with this vector's - * AllocPolicy. - * - * This vector is cleared, as if by clearAndFree(), when this method - * succeeds. This method fails and returns nullptr only if new elements buffer - * allocation fails. - * - * N.B. Only the range [0, length()) of the returned buffer is constructed. - * If any of these elements are uninitialized (as growByUninitialized - * enables), behavior is undefined. - */ - MOZ_MUST_USE T* extractOrCopyRawBuffer(); - - /** - * Transfer ownership of an array of objects into the vector. The caller - * must have allocated the array in accordance with this vector's - * AllocPolicy. - * - * N.B. This call assumes that there are no uninitialized elements in the - * passed array. - */ - void replaceRawBuffer(T* aP, size_t aLength); - - /** - * Places |aVal| at position |aP|, shifting existing elements from |aP| onward - * one position higher. On success, |aP| should not be reused because it'll - * be a dangling pointer if reallocation of the vector storage occurred; the - * return value should be used instead. On failure, nullptr is returned. - * - * Example usage: - * - * if (!(p = vec.insert(p, val))) { - * - * } - * - * - * This is inherently a linear-time operation. Be careful! - */ - template - MOZ_MUST_USE T* insert(T* aP, U&& aVal); - - /** - * Removes the element |aT|, which must fall in the bounds [begin, end), - * shifting existing elements from |aT + 1| onward one position lower. - */ - void erase(T* aT); - - /** - * Removes the elements [|aBegin|, |aEnd|), which must fall in the bounds - * [begin, end), shifting existing elements from |aEnd + 1| onward to aBegin's - * old position. - */ - void erase(T* aBegin, T* aEnd); - - /** - * Measure the size of the vector's heap-allocated storage. - */ - size_t sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const; - - /** - * Like sizeOfExcludingThis, but also measures the size of the vector - * object (which must be heap-allocated) itself. - */ - size_t sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const; - - void swap(Vector& aOther); - -private: - Vector(const Vector&) = delete; - void operator=(const Vector&) = delete; -}; - -/* This does the re-entrancy check plus several other sanity checks. */ -#define MOZ_REENTRANCY_GUARD_ET_AL \ - ReentrancyGuard g(*this); \ - MOZ_ASSERT_IF(usingInlineStorage(), mCapacity == kInlineCapacity); \ - MOZ_ASSERT(reserved() <= mCapacity); \ - MOZ_ASSERT(mLength <= reserved()); \ - MOZ_ASSERT(mLength <= mCapacity) - -/* Vector Implementation */ - -template -MOZ_ALWAYS_INLINE -Vector::Vector(AP aAP) - : AP(aAP) - , mLength(0) - , mCapacity(kInlineCapacity) -#ifdef DEBUG - , mReserved(0) - , mEntered(false) -#endif -{ - mBegin = static_cast(mStorage.addr()); -} - -/* Move constructor. */ -template -MOZ_ALWAYS_INLINE -Vector::Vector(Vector&& aRhs) - : AllocPolicy(Move(aRhs)) -#ifdef DEBUG - , mEntered(false) -#endif -{ - mLength = aRhs.mLength; - mCapacity = aRhs.mCapacity; -#ifdef DEBUG - mReserved = aRhs.mReserved; -#endif - - if (aRhs.usingInlineStorage()) { - /* We can't move the buffer over in this case, so copy elements. */ - mBegin = static_cast(mStorage.addr()); - Impl::moveConstruct(mBegin, aRhs.beginNoCheck(), aRhs.endNoCheck()); - /* - * Leave aRhs's mLength, mBegin, mCapacity, and mReserved as they are. - * The elements in its in-line storage still need to be destroyed. - */ - } else { - /* - * Take src's buffer, and turn src into an empty vector using - * in-line storage. - */ - mBegin = aRhs.mBegin; - aRhs.mBegin = static_cast(aRhs.mStorage.addr()); - aRhs.mCapacity = kInlineCapacity; - aRhs.mLength = 0; -#ifdef DEBUG - aRhs.mReserved = 0; -#endif - } -} - -/* Move assignment. */ -template -MOZ_ALWAYS_INLINE Vector& -Vector::operator=(Vector&& aRhs) -{ - MOZ_ASSERT(this != &aRhs, "self-move assignment is prohibited"); - this->~Vector(); - new(KnownNotNull, this) Vector(Move(aRhs)); - return *this; -} - -template -MOZ_ALWAYS_INLINE -Vector::~Vector() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) { - this->free_(beginNoCheck()); - } -} - -template -MOZ_ALWAYS_INLINE void -Vector::reverse() { - MOZ_REENTRANCY_GUARD_ET_AL; - T* elems = mBegin; - size_t len = mLength; - size_t mid = len / 2; - for (size_t i = 0; i < mid; i++) { - Swap(elems[i], elems[len - i - 1]); - } -} - -/* - * This function will create a new heap buffer with capacity aNewCap, - * move all elements in the inline buffer to this new buffer, - * and fail on OOM. - */ -template -inline bool -Vector::convertToHeapStorage(size_t aNewCap) -{ - MOZ_ASSERT(usingInlineStorage()); - - /* Allocate buffer. */ - MOZ_ASSERT(!detail::CapacityHasExcessSpace(aNewCap)); - T* newBuf = this->template pod_malloc(aNewCap); - if (MOZ_UNLIKELY(!newBuf)) { - return false; - } - - /* Copy inline elements into heap buffer. */ - Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - - /* Switch in heap buffer. */ - mBegin = newBuf; - /* mLength is unchanged. */ - mCapacity = aNewCap; - return true; -} - -template -MOZ_NEVER_INLINE bool -Vector::growStorageBy(size_t aIncr) -{ - MOZ_ASSERT(mLength + aIncr > mCapacity); - - /* - * When choosing a new capacity, its size should is as close to 2**N bytes - * as possible. 2**N-sized requests are best because they are unlikely to - * be rounded up by the allocator. Asking for a 2**N number of elements - * isn't as good, because if sizeof(T) is not a power-of-two that would - * result in a non-2**N request size. - */ - - size_t newCap; - - if (aIncr == 1) { - if (usingInlineStorage()) { - /* This case occurs in ~70--80% of the calls to this function. */ - size_t newSize = - tl::RoundUpPow2<(kInlineCapacity + 1) * sizeof(T)>::value; - newCap = newSize / sizeof(T); - goto convert; - } - - if (mLength == 0) { - /* This case occurs in ~0--10% of the calls to this function. */ - newCap = 1; - goto grow; - } - - /* This case occurs in ~15--20% of the calls to this function. */ - - /* - * Will mLength * 4 *sizeof(T) overflow? This condition limits a vector - * to 1GB of memory on a 32-bit system, which is a reasonable limit. It - * also ensures that - * - * static_cast(end()) - static_cast(begin()) - * - * doesn't overflow ptrdiff_t (see bug 510319). - */ - if (MOZ_UNLIKELY(mLength & tl::MulOverflowMask<4 * sizeof(T)>::value)) { - this->reportAllocOverflow(); - return false; - } - - /* - * If we reach here, the existing capacity will have a size that is already - * as close to 2^N as sizeof(T) will allow. Just double the capacity, and - * then there might be space for one more element. - */ - newCap = mLength * 2; - if (detail::CapacityHasExcessSpace(newCap)) { - newCap += 1; - } - } else { - /* This case occurs in ~2% of the calls to this function. */ - size_t newMinCap = mLength + aIncr; - - /* Did mLength + aIncr overflow? Will newCap * sizeof(T) overflow? */ - if (MOZ_UNLIKELY(newMinCap < mLength || - newMinCap & tl::MulOverflowMask<2 * sizeof(T)>::value)) - { - this->reportAllocOverflow(); - return false; - } - - size_t newMinSize = newMinCap * sizeof(T); - size_t newSize = RoundUpPow2(newMinSize); - newCap = newSize / sizeof(T); - } - - if (usingInlineStorage()) { -convert: - return convertToHeapStorage(newCap); - } - -grow: - return Impl::growTo(*this, newCap); -} - -template -inline bool -Vector::initCapacity(size_t aRequest) -{ - MOZ_ASSERT(empty()); - MOZ_ASSERT(usingInlineStorage()); - if (aRequest == 0) { - return true; - } - T* newbuf = this->template pod_malloc(aRequest); - if (MOZ_UNLIKELY(!newbuf)) { - return false; - } - mBegin = newbuf; - mCapacity = aRequest; -#ifdef DEBUG - mReserved = aRequest; -#endif - return true; -} - -template -inline bool -Vector::initLengthUninitialized(size_t aRequest) -{ - if (!initCapacity(aRequest)) { - return false; - } - infallibleGrowByUninitialized(aRequest); - return true; -} - -template -inline bool -Vector::maybeCheckSimulatedOOM(size_t aRequestedSize) -{ - if (aRequestedSize <= N) { - return true; - } - -#ifdef DEBUG - if (aRequestedSize <= mReserved) { - return true; - } -#endif - - return allocPolicy().checkSimulatedOOM(); -} - -template -inline bool -Vector::reserve(size_t aRequest) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (aRequest > mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(aRequest - mLength))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(aRequest)) { - return false; - } -#ifdef DEBUG - if (aRequest > mReserved) { - mReserved = aRequest; - } - MOZ_ASSERT(mLength <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); -#endif - return true; -} - -template -inline void -Vector::shrinkBy(size_t aIncr) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - MOZ_ASSERT(aIncr <= mLength); - Impl::destroy(endNoCheck() - aIncr, endNoCheck()); - mLength -= aIncr; -} - -template -MOZ_ALWAYS_INLINE void -Vector::shrinkTo(size_t aNewLength) -{ - MOZ_ASSERT(aNewLength <= mLength); - shrinkBy(mLength - aNewLength); -} - -template -MOZ_ALWAYS_INLINE bool -Vector::growBy(size_t aIncr) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (aIncr > mCapacity - mLength) { - if (MOZ_UNLIKELY(!growStorageBy(aIncr))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aIncr)) { - return false; - } - MOZ_ASSERT(mLength + aIncr <= mCapacity); - T* newend = endNoCheck() + aIncr; - Impl::initialize(endNoCheck(), newend); - mLength += aIncr; -#ifdef DEBUG - if (mLength > mReserved) { - mReserved = mLength; - } -#endif - return true; -} - -template -MOZ_ALWAYS_INLINE bool -Vector::growByUninitialized(size_t aIncr) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (aIncr > mCapacity - mLength) { - if (MOZ_UNLIKELY(!growStorageBy(aIncr))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aIncr)) { - return false; - } -#ifdef DEBUG - if (mLength + aIncr > mReserved) { - mReserved = mLength + aIncr; - } -#endif - infallibleGrowByUninitialized(aIncr); - return true; -} - -template -MOZ_ALWAYS_INLINE void -Vector::infallibleGrowByUninitialized(size_t aIncr) -{ - MOZ_ASSERT(mLength + aIncr <= reserved()); - mLength += aIncr; -} - -template -inline bool -Vector::resize(size_t aNewLength) -{ - size_t curLength = mLength; - if (aNewLength > curLength) { - return growBy(aNewLength - curLength); - } - shrinkBy(curLength - aNewLength); - return true; -} - -template -MOZ_ALWAYS_INLINE bool -Vector::resizeUninitialized(size_t aNewLength) -{ - size_t curLength = mLength; - if (aNewLength > curLength) { - return growByUninitialized(aNewLength - curLength); - } - shrinkBy(curLength - aNewLength); - return true; -} - -template -inline void -Vector::clear() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - Impl::destroy(beginNoCheck(), endNoCheck()); - mLength = 0; -} - -template -inline void -Vector::clearAndFree() -{ - clear(); - - if (usingInlineStorage()) { - return; - } - this->free_(beginNoCheck()); - mBegin = static_cast(mStorage.addr()); - mCapacity = kInlineCapacity; -#ifdef DEBUG - mReserved = 0; -#endif -} - -template -inline void -Vector::podResizeToFit() -{ - // This function is only defined if IsPod is true and will fail to compile - // otherwise. - Impl::podResizeToFit(*this); -} - -template -inline bool -Vector::canAppendWithoutRealloc(size_t aNeeded) const -{ - return mLength + aNeeded <= mCapacity; -} - -template -template -MOZ_ALWAYS_INLINE void -Vector::internalAppendAll(const Vector& aOther) -{ - internalAppend(aOther.begin(), aOther.length()); -} - -template -template -MOZ_ALWAYS_INLINE void -Vector::internalAppend(U&& aU) -{ - MOZ_ASSERT(mLength + 1 <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - Impl::new_(endNoCheck(), Forward(aU)); - ++mLength; -} - -template -MOZ_ALWAYS_INLINE bool -Vector::appendN(const T& aT, size_t aNeeded) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (mLength + aNeeded > mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(aNeeded))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aNeeded)) { - return false; - } -#ifdef DEBUG - if (mLength + aNeeded > mReserved) { - mReserved = mLength + aNeeded; - } -#endif - internalAppendN(aT, aNeeded); - return true; -} - -template -MOZ_ALWAYS_INLINE void -Vector::internalAppendN(const T& aT, size_t aNeeded) -{ - MOZ_ASSERT(mLength + aNeeded <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - Impl::copyConstructN(endNoCheck(), aNeeded, aT); - mLength += aNeeded; -} - -template -template -inline T* -Vector::insert(T* aP, U&& aVal) -{ - MOZ_ASSERT(begin() <= aP); - MOZ_ASSERT(aP <= end()); - size_t pos = aP - begin(); - MOZ_ASSERT(pos <= mLength); - size_t oldLength = mLength; - if (pos == oldLength) { - if (!append(Forward(aVal))) { - return nullptr; - } - } else { - T oldBack = Move(back()); - if (!append(Move(oldBack))) { /* Dup the last element. */ - return nullptr; - } - for (size_t i = oldLength; i > pos; --i) { - (*this)[i] = Move((*this)[i - 1]); - } - (*this)[pos] = Forward(aVal); - } - return begin() + pos; -} - -template -inline void -Vector::erase(T* aIt) -{ - MOZ_ASSERT(begin() <= aIt); - MOZ_ASSERT(aIt < end()); - while (aIt + 1 < end()) { - *aIt = Move(*(aIt + 1)); - ++aIt; - } - popBack(); -} - -template -inline void -Vector::erase(T* aBegin, T* aEnd) -{ - MOZ_ASSERT(begin() <= aBegin); - MOZ_ASSERT(aBegin <= aEnd); - MOZ_ASSERT(aEnd <= end()); - while (aEnd < end()) { - *aBegin++ = Move(*aEnd++); - } - shrinkBy(aEnd - aBegin); -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::append(const U* aInsBegin, const U* aInsEnd) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - size_t aNeeded = PointerRangeSize(aInsBegin, aInsEnd); - if (mLength + aNeeded > mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(aNeeded))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + aNeeded)) { - return false; - } -#ifdef DEBUG - if (mLength + aNeeded > mReserved) { - mReserved = mLength + aNeeded; - } -#endif - internalAppend(aInsBegin, aNeeded); - return true; -} - -template -template -MOZ_ALWAYS_INLINE void -Vector::internalAppend(const U* aInsBegin, size_t aInsLength) -{ - MOZ_ASSERT(mLength + aInsLength <= mReserved); - MOZ_ASSERT(mReserved <= mCapacity); - Impl::copyConstruct(endNoCheck(), aInsBegin, aInsBegin + aInsLength); - mLength += aInsLength; -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::append(U&& aU) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - if (mLength == mCapacity) { - if (MOZ_UNLIKELY(!growStorageBy(1))) { - return false; - } - } else if (!maybeCheckSimulatedOOM(mLength + 1)) { - return false; - } -#ifdef DEBUG - if (mLength + 1 > mReserved) { - mReserved = mLength + 1; - } -#endif - internalAppend(Forward(aU)); - return true; -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::appendAll(const Vector& aOther) -{ - return append(aOther.begin(), aOther.length()); -} - -template -template -MOZ_ALWAYS_INLINE bool -Vector::append(const U* aInsBegin, size_t aInsLength) -{ - return append(aInsBegin, aInsBegin + aInsLength); -} - -template -MOZ_ALWAYS_INLINE void -Vector::popBack() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - MOZ_ASSERT(!empty()); - --mLength; - endNoCheck()->~T(); -} - -template -MOZ_ALWAYS_INLINE T -Vector::popCopy() -{ - T ret = back(); - popBack(); - return ret; -} - -template -inline T* -Vector::extractRawBuffer() -{ - MOZ_REENTRANCY_GUARD_ET_AL; - - if (usingInlineStorage()) { - return nullptr; - } - - T* ret = mBegin; - mBegin = static_cast(mStorage.addr()); - mLength = 0; - mCapacity = kInlineCapacity; -#ifdef DEBUG - mReserved = 0; -#endif - return ret; -} - -template -inline T* -Vector::extractOrCopyRawBuffer() -{ - if (T* ret = extractRawBuffer()) { - return ret; - } - - MOZ_REENTRANCY_GUARD_ET_AL; - - T* copy = this->template pod_malloc(mLength); - if (!copy) { - return nullptr; - } - - Impl::moveConstruct(copy, beginNoCheck(), endNoCheck()); - Impl::destroy(beginNoCheck(), endNoCheck()); - mBegin = static_cast(mStorage.addr()); - mLength = 0; - mCapacity = kInlineCapacity; -#ifdef DEBUG - mReserved = 0; -#endif - return copy; -} - -template -inline void -Vector::replaceRawBuffer(T* aP, size_t aLength) -{ - MOZ_REENTRANCY_GUARD_ET_AL; - - /* Destroy what we have. */ - Impl::destroy(beginNoCheck(), endNoCheck()); - if (!usingInlineStorage()) { - this->free_(beginNoCheck()); - } - - /* Take in the new buffer. */ - if (aLength <= kInlineCapacity) { - /* - * We convert to inline storage if possible, even though aP might - * otherwise be acceptable. Maybe this behaviour should be - * specifiable with an argument to this function. - */ - mBegin = static_cast(mStorage.addr()); - mLength = aLength; - mCapacity = kInlineCapacity; - Impl::moveConstruct(mBegin, aP, aP + aLength); - Impl::destroy(aP, aP + aLength); - this->free_(aP); - } else { - mBegin = aP; - mLength = aLength; - mCapacity = aLength; - } -#ifdef DEBUG - mReserved = aLength; -#endif -} - -template -inline size_t -Vector::sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const -{ - return usingInlineStorage() ? 0 : aMallocSizeOf(beginNoCheck()); -} - -template -inline size_t -Vector::sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const -{ - return aMallocSizeOf(this) + sizeOfExcludingThis(aMallocSizeOf); -} - -template -inline void -Vector::swap(Vector& aOther) -{ - static_assert(N == 0, - "still need to implement this for N != 0"); - - // This only works when inline storage is always empty. - if (!usingInlineStorage() && aOther.usingInlineStorage()) { - aOther.mBegin = mBegin; - mBegin = inlineStorage(); - } else if (usingInlineStorage() && !aOther.usingInlineStorage()) { - mBegin = aOther.mBegin; - aOther.mBegin = aOther.inlineStorage(); - } else if (!usingInlineStorage() && !aOther.usingInlineStorage()) { - Swap(mBegin, aOther.mBegin); - } else { - // This case is a no-op, since we'd set both to use their inline storage. - } - - Swap(mLength, aOther.mLength); - Swap(mCapacity, aOther.mCapacity); -#ifdef DEBUG - Swap(mReserved, aOther.mReserved); -#endif -} - -} // namespace mozilla - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif /* mozilla_Vector_h */ diff --git a/win32/include/spidermonkey/mozilla/WeakPtr.h b/win32/include/spidermonkey/mozilla/WeakPtr.h deleted file mode 100755 index ef0c19f4..00000000 --- a/win32/include/spidermonkey/mozilla/WeakPtr.h +++ /dev/null @@ -1,283 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* Weak pointer functionality, implemented as a mixin for use with any class. */ - -/** - * SupportsWeakPtr lets you have a pointer to an object 'Foo' without affecting - * its lifetime. It works by creating a single shared reference counted object - * (WeakReference) that each WeakPtr will access 'Foo' through. This lets 'Foo' - * clear the pointer in the WeakReference without having to know about all of - * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime - * of 'Foo'. - * - * PLEASE NOTE: This weak pointer implementation is not thread-safe. - * - * Note that when deriving from SupportsWeakPtr you should add - * MOZ_DECLARE_WEAKREFERENCE_TYPENAME(ClassName) to the public section of your - * class, where ClassName is the name of your class. - * - * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional - * dereference, and an additional heap allocated pointer sized object shared - * between all of the WeakPtrs. - * - * Example of usage: - * - * // To have a class C support weak pointers, inherit from - * // SupportsWeakPtr. - * class C : public SupportsWeakPtr - * { - * public: - * MOZ_DECLARE_WEAKREFERENCE_TYPENAME(C) - * int mNum; - * void act(); - * }; - * - * C* ptr = new C(); - * - * // Get weak pointers to ptr. The first time a weak pointer - * // is obtained, a reference counted WeakReference object is created that - * // can live beyond the lifetime of 'ptr'. The WeakReference - * // object will be notified of 'ptr's destruction. - * WeakPtr weak = ptr; - * WeakPtr other = ptr; - * - * // Test a weak pointer for validity before using it. - * if (weak) { - * weak->mNum = 17; - * weak->act(); - * } - * - * // Destroying the underlying object clears weak pointers to it. - * delete ptr; - * - * MOZ_ASSERT(!weak, "Deleting |ptr| clears weak pointers to it."); - * MOZ_ASSERT(!other, "Deleting |ptr| clears all weak pointers to it."); - * - * WeakPtr is typesafe and may be used with any class. It is not required that - * the class be reference-counted or allocated in any particular way. - * - * The API was loosely inspired by Chromium's weak_ptr.h: - * http://src.chromium.org/svn/trunk/src/base/memory/weak_ptr.h - */ - -#ifndef mozilla_WeakPtr_h -#define mozilla_WeakPtr_h - -#include "mozilla/ArrayUtils.h" -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/RefCounted.h" -#include "mozilla/RefPtr.h" -#include "mozilla/TypeTraits.h" - -#include - -// Weak referencing is not implemeted as thread safe. When a WeakPtr -// is created or dereferenced on thread A but the real object is just -// being Released() on thread B, there is a possibility of a race -// when the proxy object (detail::WeakReference) is notified about -// the real object destruction just between when thread A is storing -// the object pointer locally and is about to add a reference to it. -// -// Hence, a non-null weak proxy object is considered to have a single -// "owning thread". It means that each query for a weak reference, -// its dereference, and destruction of the real object must all happen -// on a single thread. The following macros implement assertions for -// checking these conditions. -// -// We disable this on MinGW. MinGW has two threading models: win32 -// API based, which disables std::thread; and POSIX based which -// enables it but requires an emulation library (winpthreads). -// Rather than attempting to switch to pthread emulation at this point, -// we are disabling the std::thread based assertion checking. -// -// In the future, to enable it we could -// a. have libgcc/stdc++ support win32 threads natively -// b. switch to POSIX-based threading in MinGW with pthread emulation -// c. refactor it to not use std::thread - -#if !defined(__MINGW32__) && (defined(DEBUG) || (defined(NIGHTLY_BUILD) && !defined(MOZ_PROFILING))) - -#include -#define MOZ_WEAKPTR_DECLARE_THREAD_SAFETY_CHECK \ - std::thread::id _owningThread; \ - bool _empty; // If it was initialized as a placeholder with mPtr = nullptr. -#define MOZ_WEAKPTR_INIT_THREAD_SAFETY_CHECK() \ - do { \ - _owningThread = std::this_thread::get_id(); \ - _empty = !p; \ - } while (false) -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY() \ - MOZ_DIAGNOSTIC_ASSERT(_empty || _owningThread == std::this_thread::get_id(), \ - "WeakPtr used on multiple threads") -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(that) \ - (that)->AssertThreadSafety(); - -#define MOZ_WEAKPTR_THREAD_SAFETY_CHECKING 1 - -#else - -#define MOZ_WEAKPTR_DECLARE_THREAD_SAFETY_CHECK -#define MOZ_WEAKPTR_INIT_THREAD_SAFETY_CHECK() do { } while (false) -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY() do { } while (false) -#define MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(that) do { } while (false) - -#endif - -namespace mozilla { - -template class WeakPtr; -template class SupportsWeakPtr; - -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING -#define MOZ_DECLARE_WEAKREFERENCE_TYPENAME(T) \ - static const char* weakReferenceTypeName() { return "WeakReference<" #T ">"; } -#else -#define MOZ_DECLARE_WEAKREFERENCE_TYPENAME(T) -#endif - -namespace detail { - -// This can live beyond the lifetime of the class derived from -// SupportsWeakPtr. -template -class WeakReference : public ::mozilla::RefCounted > -{ -public: - explicit WeakReference(T* p) : mPtr(p) - { - MOZ_WEAKPTR_INIT_THREAD_SAFETY_CHECK(); - } - - T* get() const { - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY(); - return mPtr; - } - -#ifdef MOZ_REFCOUNTED_LEAK_CHECKING - const char* typeName() const - { - // The first time this is called mPtr is null, so don't - // invoke any methods on mPtr. - return T::weakReferenceTypeName(); - } - size_t typeSize() const { return sizeof(*this); } -#endif - -#ifdef MOZ_WEAKPTR_THREAD_SAFETY_CHECKING - void AssertThreadSafety() { MOZ_WEAKPTR_ASSERT_THREAD_SAFETY(); } -#endif - -private: - friend class mozilla::SupportsWeakPtr; - - void detach() { - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY(); - mPtr = nullptr; - } - - T* MOZ_NON_OWNING_REF mPtr; - MOZ_WEAKPTR_DECLARE_THREAD_SAFETY_CHECK -}; - -} // namespace detail - -template -class SupportsWeakPtr -{ -protected: - ~SupportsWeakPtr() - { - static_assert(IsBaseOf, T>::value, - "T must derive from SupportsWeakPtr"); - if (mSelfReferencingWeakPtr) { - mSelfReferencingWeakPtr.mRef->detach(); - } - } - -private: - const WeakPtr& SelfReferencingWeakPtr() - { - if (!mSelfReferencingWeakPtr) { - mSelfReferencingWeakPtr.mRef = new detail::WeakReference(static_cast(this)); - } else { - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(mSelfReferencingWeakPtr.mRef); - } - return mSelfReferencingWeakPtr; - } - - const WeakPtr& SelfReferencingWeakPtr() const - { - const WeakPtr& p = const_cast(this)->SelfReferencingWeakPtr(); - return reinterpret_cast&>(p); - } - - friend class WeakPtr; - friend class WeakPtr; - - WeakPtr mSelfReferencingWeakPtr; -}; - -template -class WeakPtr -{ - typedef detail::WeakReference WeakReference; - -public: - WeakPtr& operator=(const WeakPtr& aOther) - { - mRef = aOther.mRef; - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(mRef); - return *this; - } - - WeakPtr(const WeakPtr& aOther) - { - // The thread safety check is performed inside of the operator= method. - *this = aOther; - } - - WeakPtr& operator=(T* aOther) - { - if (aOther) { - *this = aOther->SelfReferencingWeakPtr(); - } else if (!mRef || mRef->get()) { - // Ensure that mRef is dereferenceable in the uninitialized state. - mRef = new WeakReference(nullptr); - } - // The thread safety check happens inside SelfReferencingWeakPtr - // or is initialized in the WeakReference constructor. - return *this; - } - - MOZ_IMPLICIT WeakPtr(T* aOther) - { - *this = aOther; - MOZ_WEAKPTR_ASSERT_THREAD_SAFETY_DELEGATED(mRef); - } - - // Ensure that mRef is dereferenceable in the uninitialized state. - WeakPtr() : mRef(new WeakReference(nullptr)) {} - - operator T*() const { return mRef->get(); } - T& operator*() const { return *mRef->get(); } - - T* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN { return mRef->get(); } - - T* get() const { return mRef->get(); } - -private: - friend class SupportsWeakPtr; - - explicit WeakPtr(const RefPtr& aOther) : mRef(aOther) {} - - RefPtr mRef; -}; - -} // namespace mozilla - -#endif /* mozilla_WeakPtr_h */ diff --git a/win32/include/spidermonkey/mozilla/WindowsVersion.h b/win32/include/spidermonkey/mozilla/WindowsVersion.h deleted file mode 100755 index 4156f4f6..00000000 --- a/win32/include/spidermonkey/mozilla/WindowsVersion.h +++ /dev/null @@ -1,195 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_WindowsVersion_h -#define mozilla_WindowsVersion_h - -#include "mozilla/Attributes.h" -#include -#include - -namespace mozilla { - -inline bool -IsWindowsVersionOrLater(uint32_t aVersion) -{ - static uint32_t minVersion = 0; - static uint32_t maxVersion = UINT32_MAX; - - if (minVersion >= aVersion) { - return true; - } - - if (aVersion >= maxVersion) { - return false; - } - - OSVERSIONINFOEX info; - ZeroMemory(&info, sizeof(OSVERSIONINFOEX)); - info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); - info.dwMajorVersion = aVersion >> 24; - info.dwMinorVersion = (aVersion >> 16) & 0xFF; - info.wServicePackMajor = (aVersion >> 8) & 0xFF; - info.wServicePackMinor = aVersion & 0xFF; - - DWORDLONG conditionMask = 0; - VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); - VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); - VER_SET_CONDITION(conditionMask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); - VER_SET_CONDITION(conditionMask, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL); - - if (VerifyVersionInfo(&info, - VER_MAJORVERSION | VER_MINORVERSION | - VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR, - conditionMask)) { - minVersion = aVersion; - return true; - } - - maxVersion = aVersion; - return false; -} - -inline bool -IsWindowsBuildOrLater(uint32_t aBuild) -{ - static uint32_t minBuild = 0; - static uint32_t maxBuild = UINT32_MAX; - - if (minBuild >= aBuild) { - return true; - } - - if (aBuild >= maxBuild) { - return false; - } - - OSVERSIONINFOEX info; - ZeroMemory(&info, sizeof(OSVERSIONINFOEX)); - info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); - info.dwBuildNumber = aBuild; - - DWORDLONG conditionMask = 0; - VER_SET_CONDITION(conditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL); - - if (VerifyVersionInfo(&info, VER_BUILDNUMBER, conditionMask)) { - minBuild = aBuild; - return true; - } - - maxBuild = aBuild; - return false; -} - -#if defined(_M_X64) || defined(_M_AMD64) -// We support only Win7 or later on Win64. -MOZ_ALWAYS_INLINE bool -IsXPSP3OrLater() -{ - return true; -} - -MOZ_ALWAYS_INLINE bool -IsWin2003OrLater() -{ - return true; -} - -MOZ_ALWAYS_INLINE bool -IsWin2003SP2OrLater() -{ - return true; -} - -MOZ_ALWAYS_INLINE bool -IsVistaOrLater() -{ - return true; -} - -MOZ_ALWAYS_INLINE bool -IsVistaSP1OrLater() -{ - return true; -} - -MOZ_ALWAYS_INLINE bool -IsWin7OrLater() -{ - return true; -} -#else -MOZ_ALWAYS_INLINE bool -IsXPSP3OrLater() -{ - return IsWindowsVersionOrLater(0x05010300ul); -} - -MOZ_ALWAYS_INLINE bool -IsWin2003OrLater() -{ - return IsWindowsVersionOrLater(0x05020000ul); -} - -MOZ_ALWAYS_INLINE bool -IsWin2003SP2OrLater() -{ - return IsWindowsVersionOrLater(0x05020200ul); -} - -MOZ_ALWAYS_INLINE bool -IsVistaOrLater() -{ - return IsWindowsVersionOrLater(0x06000000ul); -} - -MOZ_ALWAYS_INLINE bool -IsVistaSP1OrLater() -{ - return IsWindowsVersionOrLater(0x06000100ul); -} - -MOZ_ALWAYS_INLINE bool -IsWin7OrLater() -{ - return IsWindowsVersionOrLater(0x06010000ul); -} -#endif - -MOZ_ALWAYS_INLINE bool -IsWin7SP1OrLater() -{ - return IsWindowsVersionOrLater(0x06010100ul); -} - -MOZ_ALWAYS_INLINE bool -IsWin8OrLater() -{ - return IsWindowsVersionOrLater(0x06020000ul); -} - -MOZ_ALWAYS_INLINE bool -IsWin8Point1OrLater() -{ - return IsWindowsVersionOrLater(0x06030000ul); -} - -MOZ_ALWAYS_INLINE bool -IsWin10OrLater() -{ - return IsWindowsVersionOrLater(0x0a000000ul); -} - -MOZ_ALWAYS_INLINE bool -IsNotWin7PreRTM() -{ - return IsWin7SP1OrLater() || !IsWin7OrLater() || - IsWindowsBuildOrLater(7600); -} - -} // namespace mozilla - -#endif /* mozilla_WindowsVersion_h */ diff --git a/win32/include/spidermonkey/mozilla/XorShift128PlusRNG.h b/win32/include/spidermonkey/mozilla/XorShift128PlusRNG.h deleted file mode 100755 index 2f182f0f..00000000 --- a/win32/include/spidermonkey/mozilla/XorShift128PlusRNG.h +++ /dev/null @@ -1,121 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* The xorshift128+ pseudo-random number generator. */ - -#ifndef mozilla_XorShift128Plus_h -#define mozilla_XorShift128Plus_h - -#include "mozilla/Assertions.h" -#include "mozilla/Attributes.h" -#include "mozilla/FloatingPoint.h" - -#include - -namespace mozilla { -namespace non_crypto { - -/* - * A stream of pseudo-random numbers generated using the xorshift+ technique - * described here: - * - * Vigna, Sebastiano (2014). "Further scramblings of Marsaglia's xorshift - * generators". arXiv:1404.0390 (http://arxiv.org/abs/1404.0390) - * - * That paper says: - * - * In particular, we propose a tightly coded xorshift128+ generator that - * does not fail systematically any test from the BigCrush suite of TestU01 - * (even reversed) and generates 64 pseudorandom bits in 1.10 ns on an - * Intel(R) Core(TM) i7-4770 CPU @3.40GHz (Haswell). It is the fastest - * generator we are aware of with such empirical statistical properties. - * - * The stream of numbers produced by this method repeats every 2**128 - 1 calls - * (i.e. never, for all practical purposes). Zero appears 2**64 - 1 times in - * this period; all other numbers appear 2**64 times. Additionally, each *bit* - * in the produced numbers repeats every 2**128 - 1 calls. - * - * This generator is not suitable as a cryptographically secure random number - * generator. - */ -class XorShift128PlusRNG { - uint64_t mState[2]; - - public: - /* - * Construct a xorshift128+ pseudo-random number stream using |aInitial0| and - * |aInitial1| as the initial state. These MUST NOT both be zero. - * - * If the initial states contain many zeros, for a few iterations you'll see - * many zeroes in the generated numbers. It's suggested to seed a SplitMix64 - * generator and use its first two - * outputs to seed xorshift128+. - */ - XorShift128PlusRNG(uint64_t aInitial0, uint64_t aInitial1) { - setState(aInitial0, aInitial1); - } - - /** - * Return a pseudo-random 64-bit number. - */ - uint64_t next() { - /* - * The offsetOfState*() methods below are provided so that exceedingly-rare - * callers that want to observe or poke at RNG state in C++ type-system- - * ignoring means can do so. Don't change the next() or nextDouble() - * algorithms without altering code that uses offsetOfState*()! - */ - uint64_t s1 = mState[0]; - const uint64_t s0 = mState[1]; - mState[0] = s0; - s1 ^= s1 << 23; - mState[1] = s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26); - return mState[1] + s0; - } - - /* - * Return a pseudo-random floating-point value in the range [0, 1). More - * precisely, choose an integer in the range [0, 2**53) and divide it by - * 2**53. Given the 2**128 - 1 period noted above, the produced doubles are - * all but uniformly distributed in this range. - */ - double nextDouble() { - /* - * Because the IEEE 64-bit floating point format stores the leading '1' bit - * of the mantissa implicitly, it effectively represents a mantissa in the - * range [0, 2**53) in only 52 bits. FloatingPoint::kExponentShift - * is the width of the bitfield in the in-memory format, so we must add one - * to get the mantissa's range. - */ - static constexpr int kMantissaBits = - mozilla::FloatingPoint::kExponentShift + 1; - uint64_t mantissa = next() & ((UINT64_C(1) << kMantissaBits) - 1); - return double(mantissa) / (UINT64_C(1) << kMantissaBits); - } - - /* - * Set the stream's current state to |aState0| and |aState1|. These must not - * both be zero; ideally, they should have an almost even mix of zero and one - * bits. - */ - void setState(uint64_t aState0, uint64_t aState1) { - MOZ_ASSERT(aState0 || aState1); - mState[0] = aState0; - mState[1] = aState1; - } - - static size_t offsetOfState0() { - return offsetof(XorShift128PlusRNG, mState[0]); - } - static size_t offsetOfState1() { - return offsetof(XorShift128PlusRNG, mState[1]); - } -}; - -} // namespace non_crypto -} // namespace mozilla - -#endif // mozilla_XorShift128Plus_h diff --git a/win32/include/spidermonkey/mozilla/double-conversion.h b/win32/include/spidermonkey/mozilla/double-conversion.h deleted file mode 100755 index 957575cf..00000000 --- a/win32/include/spidermonkey/mozilla/double-conversion.h +++ /dev/null @@ -1,538 +0,0 @@ -// Copyright 2012 the V8 project authors. All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following -// disclaimer in the documentation and/or other materials provided -// with the distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ -#define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ - -#include "mozilla/Types.h" -#include "utils.h" - -namespace double_conversion { - -class DoubleToStringConverter { - public: - // When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint - // or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the - // function returns false. - static const int kMaxFixedDigitsBeforePoint = 60; - static const int kMaxFixedDigitsAfterPoint = 60; - - // When calling ToExponential with a requested_digits - // parameter > kMaxExponentialDigits then the function returns false. - static const int kMaxExponentialDigits = 120; - - // When calling ToPrecision with a requested_digits - // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits - // then the function returns false. - static const int kMinPrecisionDigits = 1; - static const int kMaxPrecisionDigits = 120; - - enum Flags { - NO_FLAGS = 0, - EMIT_POSITIVE_EXPONENT_SIGN = 1, - EMIT_TRAILING_DECIMAL_POINT = 2, - EMIT_TRAILING_ZERO_AFTER_POINT = 4, - UNIQUE_ZERO = 8 - }; - - // Flags should be a bit-or combination of the possible Flags-enum. - // - NO_FLAGS: no special flags. - // - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent - // form, emits a '+' for positive exponents. Example: 1.2e+2. - // - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is - // converted into decimal format then a trailing decimal point is appended. - // Example: 2345.0 is converted to "2345.". - // - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point - // emits a trailing '0'-character. This flag requires the - // EXMIT_TRAILING_DECIMAL_POINT flag. - // Example: 2345.0 is converted to "2345.0". - // - UNIQUE_ZERO: "-0.0" is converted to "0.0". - // - // Infinity symbol and nan_symbol provide the string representation for these - // special values. If the string is NULL and the special value is encountered - // then the conversion functions return false. - // - // The exponent_character is used in exponential representations. It is - // usually 'e' or 'E'. - // - // When converting to the shortest representation the converter will - // represent input numbers in decimal format if they are in the interval - // [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[ - // (lower boundary included, greater boundary excluded). - // Example: with decimal_in_shortest_low = -6 and - // decimal_in_shortest_high = 21: - // ToShortest(0.000001) -> "0.000001" - // ToShortest(0.0000001) -> "1e-7" - // ToShortest(111111111111111111111.0) -> "111111111111111110000" - // ToShortest(100000000000000000000.0) -> "100000000000000000000" - // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21" - // - // When converting to precision mode the converter may add - // max_leading_padding_zeroes before returning the number in exponential - // format. - // Example with max_leading_padding_zeroes_in_precision_mode = 6. - // ToPrecision(0.0000012345, 2) -> "0.0000012" - // ToPrecision(0.00000012345, 2) -> "1.2e-7" - // Similarily the converter may add up to - // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid - // returning an exponential representation. A zero added by the - // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit. - // Examples for max_trailing_padding_zeroes_in_precision_mode = 1: - // ToPrecision(230.0, 2) -> "230" - // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT. - // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT. - DoubleToStringConverter(int flags, - const char* infinity_symbol, - const char* nan_symbol, - char exponent_character, - int decimal_in_shortest_low, - int decimal_in_shortest_high, - int max_leading_padding_zeroes_in_precision_mode, - int max_trailing_padding_zeroes_in_precision_mode) - : flags_(flags), - infinity_symbol_(infinity_symbol), - nan_symbol_(nan_symbol), - exponent_character_(exponent_character), - decimal_in_shortest_low_(decimal_in_shortest_low), - decimal_in_shortest_high_(decimal_in_shortest_high), - max_leading_padding_zeroes_in_precision_mode_( - max_leading_padding_zeroes_in_precision_mode), - max_trailing_padding_zeroes_in_precision_mode_( - max_trailing_padding_zeroes_in_precision_mode) { - // When 'trailing zero after the point' is set, then 'trailing point' - // must be set too. - ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) || - !((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0)); - } - - // Returns a converter following the EcmaScript specification. - static MFBT_API const DoubleToStringConverter& EcmaScriptConverter(); - - // Computes the shortest string of digits that correctly represent the input - // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high - // (see constructor) it then either returns a decimal representation, or an - // exponential representation. - // Example with decimal_in_shortest_low = -6, - // decimal_in_shortest_high = 21, - // EMIT_POSITIVE_EXPONENT_SIGN activated, and - // EMIT_TRAILING_DECIMAL_POINT deactived: - // ToShortest(0.000001) -> "0.000001" - // ToShortest(0.0000001) -> "1e-7" - // ToShortest(111111111111111111111.0) -> "111111111111111110000" - // ToShortest(100000000000000000000.0) -> "100000000000000000000" - // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21" - // - // Note: the conversion may round the output if the returned string - // is accurate enough to uniquely identify the input-number. - // For example the most precise representation of the double 9e59 equals - // "899999999999999918767229449717619953810131273674690656206848", but - // the converter will return the shorter (but still correct) "9e59". - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except when the input value is special and no infinity_symbol or - // nan_symbol has been given to the constructor. - bool ToShortest(double value, StringBuilder* result_builder) const { - return ToShortestIeeeNumber(value, result_builder, SHORTEST); - } - - // Same as ToShortest, but for single-precision floats. - bool ToShortestSingle(float value, StringBuilder* result_builder) const { - return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE); - } - - - // Computes a decimal representation with a fixed number of digits after the - // decimal point. The last emitted digit is rounded. - // - // Examples: - // ToFixed(3.12, 1) -> "3.1" - // ToFixed(3.1415, 3) -> "3.142" - // ToFixed(1234.56789, 4) -> "1234.5679" - // ToFixed(1.23, 5) -> "1.23000" - // ToFixed(0.1, 4) -> "0.1000" - // ToFixed(1e30, 2) -> "1000000000000000019884624838656.00" - // ToFixed(0.1, 30) -> "0.100000000000000005551115123126" - // ToFixed(0.1, 17) -> "0.10000000000000001" - // - // If requested_digits equals 0, then the tail of the result depends on - // the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT. - // Examples, for requested_digits == 0, - // let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be - // - false and false: then 123.45 -> 123 - // 0.678 -> 1 - // - true and false: then 123.45 -> 123. - // 0.678 -> 1. - // - true and true: then 123.45 -> 123.0 - // 0.678 -> 1.0 - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except for the following cases: - // - the input value is special and no infinity_symbol or nan_symbol has - // been provided to the constructor, - // - 'value' > 10^kMaxFixedDigitsBeforePoint, or - // - 'requested_digits' > kMaxFixedDigitsAfterPoint. - // The last two conditions imply that the result will never contain more than - // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters - // (one additional character for the sign, and one for the decimal point). - MFBT_API bool ToFixed(double value, - int requested_digits, - StringBuilder* result_builder) const; - - // Computes a representation in exponential format with requested_digits - // after the decimal point. The last emitted digit is rounded. - // If requested_digits equals -1, then the shortest exponential representation - // is computed. - // - // Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and - // exponent_character set to 'e'. - // ToExponential(3.12, 1) -> "3.1e0" - // ToExponential(5.0, 3) -> "5.000e0" - // ToExponential(0.001, 2) -> "1.00e-3" - // ToExponential(3.1415, -1) -> "3.1415e0" - // ToExponential(3.1415, 4) -> "3.1415e0" - // ToExponential(3.1415, 3) -> "3.142e0" - // ToExponential(123456789000000, 3) -> "1.235e14" - // ToExponential(1000000000000000019884624838656.0, -1) -> "1e30" - // ToExponential(1000000000000000019884624838656.0, 32) -> - // "1.00000000000000001988462483865600e30" - // ToExponential(1234, 0) -> "1e3" - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except for the following cases: - // - the input value is special and no infinity_symbol or nan_symbol has - // been provided to the constructor, - // - 'requested_digits' > kMaxExponentialDigits. - // The last condition implies that the result will never contain more than - // kMaxExponentialDigits + 8 characters (the sign, the digit before the - // decimal point, the decimal point, the exponent character, the - // exponent's sign, and at most 3 exponent digits). - MFBT_API bool ToExponential(double value, - int requested_digits, - StringBuilder* result_builder) const; - - // Computes 'precision' leading digits of the given 'value' and returns them - // either in exponential or decimal format, depending on - // max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the - // constructor). - // The last computed digit is rounded. - // - // Example with max_leading_padding_zeroes_in_precision_mode = 6. - // ToPrecision(0.0000012345, 2) -> "0.0000012" - // ToPrecision(0.00000012345, 2) -> "1.2e-7" - // Similarily the converter may add up to - // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid - // returning an exponential representation. A zero added by the - // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit. - // Examples for max_trailing_padding_zeroes_in_precision_mode = 1: - // ToPrecision(230.0, 2) -> "230" - // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT. - // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT. - // Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no - // EMIT_TRAILING_ZERO_AFTER_POINT: - // ToPrecision(123450.0, 6) -> "123450" - // ToPrecision(123450.0, 5) -> "123450" - // ToPrecision(123450.0, 4) -> "123500" - // ToPrecision(123450.0, 3) -> "123000" - // ToPrecision(123450.0, 2) -> "1.2e5" - // - // Returns true if the conversion succeeds. The conversion always succeeds - // except for the following cases: - // - the input value is special and no infinity_symbol or nan_symbol has - // been provided to the constructor, - // - precision < kMinPericisionDigits - // - precision > kMaxPrecisionDigits - // The last condition implies that the result will never contain more than - // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the - // exponent character, the exponent's sign, and at most 3 exponent digits). - MFBT_API bool ToPrecision(double value, - int precision, - bool* used_exponential_notation, - StringBuilder* result_builder) const; - - enum DtoaMode { - // Produce the shortest correct representation. - // For example the output of 0.299999999999999988897 is (the less accurate - // but correct) 0.3. - SHORTEST, - // Same as SHORTEST, but for single-precision floats. - SHORTEST_SINGLE, - // Produce a fixed number of digits after the decimal point. - // For instance fixed(0.1, 4) becomes 0.1000 - // If the input number is big, the output will be big. - FIXED, - // Fixed number of digits (independent of the decimal point). - PRECISION - }; - - // The maximal number of digits that are needed to emit a double in base 10. - // A higher precision can be achieved by using more digits, but the shortest - // accurate representation of any double will never use more digits than - // kBase10MaximalLength. - // Note that DoubleToAscii null-terminates its input. So the given buffer - // should be at least kBase10MaximalLength + 1 characters long. - static const MFBT_DATA int kBase10MaximalLength = 17; - - // Converts the given double 'v' to ascii. 'v' must not be NaN, +Infinity, or - // -Infinity. In SHORTEST_SINGLE-mode this restriction also applies to 'v' - // after it has been casted to a single-precision float. That is, in this - // mode static_cast(v) must not be NaN, +Infinity or -Infinity. - // - // The result should be interpreted as buffer * 10^(point-length). - // - // The output depends on the given mode: - // - SHORTEST: produce the least amount of digits for which the internal - // identity requirement is still satisfied. If the digits are printed - // (together with the correct exponent) then reading this number will give - // 'v' again. The buffer will choose the representation that is closest to - // 'v'. If there are two at the same distance, than the one farther away - // from 0 is chosen (halfway cases - ending with 5 - are rounded up). - // In this mode the 'requested_digits' parameter is ignored. - // - SHORTEST_SINGLE: same as SHORTEST but with single-precision. - // - FIXED: produces digits necessary to print a given number with - // 'requested_digits' digits after the decimal point. The produced digits - // might be too short in which case the caller has to fill the remainder - // with '0's. - // Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2. - // Halfway cases are rounded towards +/-Infinity (away from 0). The call - // toFixed(0.15, 2) thus returns buffer="2", point=0. - // The returned buffer may contain digits that would be truncated from the - // shortest representation of the input. - // - PRECISION: produces 'requested_digits' where the first digit is not '0'. - // Even though the length of produced digits usually equals - // 'requested_digits', the function is allowed to return fewer digits, in - // which case the caller has to fill the missing digits with '0's. - // Halfway cases are again rounded away from 0. - // DoubleToAscii expects the given buffer to be big enough to hold all - // digits and a terminating null-character. In SHORTEST-mode it expects a - // buffer of at least kBase10MaximalLength + 1. In all other modes the - // requested_digits parameter and the padding-zeroes limit the size of the - // output. Don't forget the decimal point, the exponent character and the - // terminating null-character when computing the maximal output size. - // The given length is only used in debug mode to ensure the buffer is big - // enough. - static MFBT_API void DoubleToAscii(double v, - DtoaMode mode, - int requested_digits, - char* buffer, - int buffer_length, - bool* sign, - int* length, - int* point); - - private: - // Implementation for ToShortest and ToShortestSingle. - MFBT_API bool ToShortestIeeeNumber(double value, - StringBuilder* result_builder, - DtoaMode mode) const; - - // If the value is a special value (NaN or Infinity) constructs the - // corresponding string using the configured infinity/nan-symbol. - // If either of them is NULL or the value is not special then the - // function returns false. - MFBT_API bool HandleSpecialValues(double value, StringBuilder* result_builder) const; - // Constructs an exponential representation (i.e. 1.234e56). - // The given exponent assumes a decimal point after the first decimal digit. - MFBT_API void CreateExponentialRepresentation(const char* decimal_digits, - int length, - int exponent, - StringBuilder* result_builder) const; - // Creates a decimal representation (i.e 1234.5678). - MFBT_API void CreateDecimalRepresentation(const char* decimal_digits, - int length, - int decimal_point, - int digits_after_point, - StringBuilder* result_builder) const; - - const int flags_; - const char* const infinity_symbol_; - const char* const nan_symbol_; - const char exponent_character_; - const int decimal_in_shortest_low_; - const int decimal_in_shortest_high_; - const int max_leading_padding_zeroes_in_precision_mode_; - const int max_trailing_padding_zeroes_in_precision_mode_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter); -}; - - -class StringToDoubleConverter { - public: - // Enumeration for allowing octals and ignoring junk when converting - // strings to numbers. - enum Flags { - NO_FLAGS = 0, - ALLOW_HEX = 1, - ALLOW_OCTALS = 2, - ALLOW_TRAILING_JUNK = 4, - ALLOW_LEADING_SPACES = 8, - ALLOW_TRAILING_SPACES = 16, - ALLOW_SPACES_AFTER_SIGN = 32 - }; - - // Flags should be a bit-or combination of the possible Flags-enum. - // - NO_FLAGS: no special flags. - // - ALLOW_HEX: recognizes the prefix "0x". Hex numbers may only be integers. - // Ex: StringToDouble("0x1234") -> 4660.0 - // In StringToDouble("0x1234.56") the characters ".56" are trailing - // junk. The result of the call is hence dependent on - // the ALLOW_TRAILING_JUNK flag and/or the junk value. - // With this flag "0x" is a junk-string. Even with ALLOW_TRAILING_JUNK, - // the string will not be parsed as "0" followed by junk. - // - // - ALLOW_OCTALS: recognizes the prefix "0" for octals: - // If a sequence of octal digits starts with '0', then the number is - // read as octal integer. Octal numbers may only be integers. - // Ex: StringToDouble("01234") -> 668.0 - // StringToDouble("012349") -> 12349.0 // Not a sequence of octal - // // digits. - // In StringToDouble("01234.56") the characters ".56" are trailing - // junk. The result of the call is hence dependent on - // the ALLOW_TRAILING_JUNK flag and/or the junk value. - // In StringToDouble("01234e56") the characters "e56" are trailing - // junk, too. - // - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of - // a double literal. - // - ALLOW_LEADING_SPACES: skip over leading spaces. - // - ALLOW_TRAILING_SPACES: ignore trailing spaces. - // - ALLOW_SPACES_AFTER_SIGN: ignore spaces after the sign. - // Ex: StringToDouble("- 123.2") -> -123.2. - // StringToDouble("+ 123.2") -> 123.2 - // - // empty_string_value is returned when an empty string is given as input. - // If ALLOW_LEADING_SPACES or ALLOW_TRAILING_SPACES are set, then a string - // containing only spaces is converted to the 'empty_string_value', too. - // - // junk_string_value is returned when - // a) ALLOW_TRAILING_JUNK is not set, and a junk character (a character not - // part of a double-literal) is found. - // b) ALLOW_TRAILING_JUNK is set, but the string does not start with a - // double literal. - // - // infinity_symbol and nan_symbol are strings that are used to detect - // inputs that represent infinity and NaN. They can be null, in which case - // they are ignored. - // The conversion routine first reads any possible signs. Then it compares the - // following character of the input-string with the first character of - // the infinity, and nan-symbol. If either matches, the function assumes, that - // a match has been found, and expects the following input characters to match - // the remaining characters of the special-value symbol. - // This means that the following restrictions apply to special-value symbols: - // - they must not start with signs ('+', or '-'), - // - they must not have the same first character. - // - they must not start with digits. - // - // Examples: - // flags = ALLOW_HEX | ALLOW_TRAILING_JUNK, - // empty_string_value = 0.0, - // junk_string_value = NaN, - // infinity_symbol = "infinity", - // nan_symbol = "nan": - // StringToDouble("0x1234") -> 4660.0. - // StringToDouble("0x1234K") -> 4660.0. - // StringToDouble("") -> 0.0 // empty_string_value. - // StringToDouble(" ") -> NaN // junk_string_value. - // StringToDouble(" 1") -> NaN // junk_string_value. - // StringToDouble("0x") -> NaN // junk_string_value. - // StringToDouble("-123.45") -> -123.45. - // StringToDouble("--123.45") -> NaN // junk_string_value. - // StringToDouble("123e45") -> 123e45. - // StringToDouble("123E45") -> 123e45. - // StringToDouble("123e+45") -> 123e45. - // StringToDouble("123E-45") -> 123e-45. - // StringToDouble("123e") -> 123.0 // trailing junk ignored. - // StringToDouble("123e-") -> 123.0 // trailing junk ignored. - // StringToDouble("+NaN") -> NaN // NaN string literal. - // StringToDouble("-infinity") -> -inf. // infinity literal. - // StringToDouble("Infinity") -> NaN // junk_string_value. - // - // flags = ALLOW_OCTAL | ALLOW_LEADING_SPACES, - // empty_string_value = 0.0, - // junk_string_value = NaN, - // infinity_symbol = NULL, - // nan_symbol = NULL: - // StringToDouble("0x1234") -> NaN // junk_string_value. - // StringToDouble("01234") -> 668.0. - // StringToDouble("") -> 0.0 // empty_string_value. - // StringToDouble(" ") -> 0.0 // empty_string_value. - // StringToDouble(" 1") -> 1.0 - // StringToDouble("0x") -> NaN // junk_string_value. - // StringToDouble("0123e45") -> NaN // junk_string_value. - // StringToDouble("01239E45") -> 1239e45. - // StringToDouble("-infinity") -> NaN // junk_string_value. - // StringToDouble("NaN") -> NaN // junk_string_value. - StringToDoubleConverter(int flags, - double empty_string_value, - double junk_string_value, - const char* infinity_symbol, - const char* nan_symbol) - : flags_(flags), - empty_string_value_(empty_string_value), - junk_string_value_(junk_string_value), - infinity_symbol_(infinity_symbol), - nan_symbol_(nan_symbol) { - } - - // Performs the conversion. - // The output parameter 'processed_characters_count' is set to the number - // of characters that have been processed to read the number. - // Spaces than are processed with ALLOW_{LEADING|TRAILING}_SPACES are included - // in the 'processed_characters_count'. Trailing junk is never included. - double StringToDouble(const char* buffer, - int length, - int* processed_characters_count) const { - return StringToIeee(buffer, length, processed_characters_count, true); - } - - // Same as StringToDouble but reads a float. - // Note that this is not equivalent to static_cast(StringToDouble(...)) - // due to potential double-rounding. - float StringToFloat(const char* buffer, - int length, - int* processed_characters_count) const { - return static_cast(StringToIeee(buffer, length, - processed_characters_count, false)); - } - - private: - const int flags_; - const double empty_string_value_; - const double junk_string_value_; - const char* const infinity_symbol_; - const char* const nan_symbol_; - - double StringToIeee(const char* buffer, - int length, - int* processed_characters_count, - bool read_as_double) const; - - DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter); -}; - -} // namespace double_conversion - -#endif // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_ diff --git a/win32/include/spidermonkey/mozilla/fallible.h b/win32/include/spidermonkey/mozilla/fallible.h deleted file mode 100755 index c028360b..00000000 --- a/win32/include/spidermonkey/mozilla/fallible.h +++ /dev/null @@ -1,68 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_fallible_h -#define mozilla_fallible_h - -#if defined(__cplusplus) - -/* Explicit fallible allocation - * - * Memory allocation (normally) defaults to abort in case of failed - * allocation. That is, it never returns NULL, and crashes instead. - * - * Code can explicitely request for fallible memory allocation thanks - * to the declarations below. - * - * The typical use of the mozilla::fallible const is with placement new, - * like the following: - * - * foo = new (mozilla::fallible) Foo(); - * - * The following forms, or derivatives, are also possible but deprecated: - * - * foo = new ((mozilla::fallible_t())) Foo(); - * - * const mozilla::fallible_t fallible = mozilla::fallible_t(); - * bar = new (f) Bar(); - * - * It is also possible to declare method overloads with fallible allocation - * alternatives, like so: - * - * class Foo { - * public: - * void Method(void *); - * void Method(void *, const mozilla::fallible_t&); - * }; - * - * Foo foo; - * foo.Method(nullptr, mozilla::fallible); - * - * If that last method call is in a method that itself takes a const - * fallible_t& argument, it is recommended to propagate that argument - * instead of using mozilla::fallible: - * - * void Func(Foo &foo, const mozilla::fallible_t& aFallible) { - * foo.Method(nullptr, aFallible); - * } - * - */ -namespace mozilla { - -struct fallible_t { }; - -/* This symbol is kept unexported, such that in corner cases where the - * compiler can't remove its use (essentially, cross compilation-unit - * calls), the smallest machine code is used. - * Depending how the linker packs symbols, it will consume between 1 and - * 8 bytes of read-only data in each executable or shared library, but - * only in those where it's actually not optimized out by the compiler. - */ -extern const fallible_t fallible; - -} // namespace mozilla - -#endif - -#endif // mozilla_fallible_h diff --git a/win32/include/spidermonkey/mozilla/mozalloc.h b/win32/include/spidermonkey/mozilla/mozalloc.h deleted file mode 100755 index f7ddb7e6..00000000 --- a/win32/include/spidermonkey/mozilla/mozalloc.h +++ /dev/null @@ -1,361 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: sw=4 ts=4 et : - */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_mozalloc_h -#define mozilla_mozalloc_h - -/* - * https://bugzilla.mozilla.org/show_bug.cgi?id=427099 - */ - -#if defined(__cplusplus) -# include -// Since libstdc++ 6, including the C headers (e.g. stdlib.h) instead of the -// corresponding C++ header (e.g. cstdlib) can cause confusion in C++ code -// using things defined there. Specifically, with stdlib.h, the use of abs() -// in gfx/graphite2/src/inc/UtfCodec.h somehow ends up picking the wrong abs() -# include -# include -#else -# include -# include -#endif - -#if defined(__cplusplus) -#include "mozilla/fallible.h" -#include "mozilla/mozalloc_abort.h" -#include "mozilla/TemplateLib.h" -#endif -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" - -#define MOZALLOC_HAVE_XMALLOC - -#if defined(MOZ_ALWAYS_INLINE_EVEN_DEBUG) -# define MOZALLOC_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG -#elif defined(HAVE_FORCEINLINE) -# define MOZALLOC_INLINE __forceinline -#else -# define MOZALLOC_INLINE inline -#endif - -/* Workaround build problem with Sun Studio 12 */ -#if defined(__SUNPRO_C) || defined(__SUNPRO_CC) -# undef MOZ_MUST_USE -# define MOZ_MUST_USE -# undef MOZ_ALLOCATOR -# define MOZ_ALLOCATOR -#endif - -#if defined(__cplusplus) -extern "C" { -#endif /* ifdef __cplusplus */ - -/* - * We need to use malloc_impl and free_impl in this file when they are - * defined, because of how mozglue.dll is linked on Windows, where using - * malloc/free would end up using the symbols from the MSVCRT instead of - * ours. - */ -#ifndef free_impl -#define free_impl free -#define free_impl_ -#endif -#ifndef malloc_impl -#define malloc_impl malloc -#define malloc_impl_ -#endif - -/* - * Each declaration below is analogous to a "standard" allocation - * function, except that the out-of-memory handling is made explicit. - * The |moz_x| versions will never return a NULL pointer; if memory - * is exhausted, they abort. The |moz_| versions may return NULL - * pointers if memory is exhausted: their return value must be checked. - * - * All these allocation functions are *guaranteed* to return a pointer - * to memory allocated in such a way that that memory can be freed by - * passing that pointer to |free()|. - */ - -MFBT_API void* moz_xmalloc(size_t size) - MOZ_ALLOCATOR; - -MFBT_API void* moz_xcalloc(size_t nmemb, size_t size) - MOZ_ALLOCATOR; - -MFBT_API void* moz_xrealloc(void* ptr, size_t size) - MOZ_ALLOCATOR; - -MFBT_API char* moz_xstrdup(const char* str) - MOZ_ALLOCATOR; - -MFBT_API size_t moz_malloc_usable_size(void *ptr); - -MFBT_API size_t moz_malloc_size_of(const void *ptr); - -#if defined(HAVE_STRNDUP) -MFBT_API char* moz_xstrndup(const char* str, size_t strsize) - MOZ_ALLOCATOR; -#endif /* if defined(HAVE_STRNDUP) */ - - -#if defined(HAVE_POSIX_MEMALIGN) -MFBT_API MOZ_MUST_USE -int moz_xposix_memalign(void **ptr, size_t alignment, size_t size); - -MFBT_API MOZ_MUST_USE -int moz_posix_memalign(void **ptr, size_t alignment, size_t size); -#endif /* if defined(HAVE_POSIX_MEMALIGN) */ - - -#if defined(HAVE_MEMALIGN) -MFBT_API void* moz_xmemalign(size_t boundary, size_t size) - MOZ_ALLOCATOR; -#endif /* if defined(HAVE_MEMALIGN) */ - - -#if defined(HAVE_VALLOC) -MFBT_API void* moz_xvalloc(size_t size) - MOZ_ALLOCATOR; -#endif /* if defined(HAVE_VALLOC) */ - - -#ifdef __cplusplus -} /* extern "C" */ -#endif /* ifdef __cplusplus */ - - -#ifdef __cplusplus - -/* - * We implement the default operators new/delete as part of - * libmozalloc, replacing their definitions in libstdc++. The - * operator new* definitions in libmozalloc will never return a NULL - * pointer. - * - * Each operator new immediately below returns a pointer to memory - * that can be delete'd by any of - * - * (1) the matching infallible operator delete immediately below - * (2) the matching "fallible" operator delete further below - * (3) the matching system |operator delete(void*, std::nothrow)| - * (4) the matching system |operator delete(void*) throw(std::bad_alloc)| - * - * NB: these are declared |throw(std::bad_alloc)|, though they will never - * throw that exception. This declaration is consistent with the rule - * that |::operator new() throw(std::bad_alloc)| will never return NULL. - */ - -/* NB: This is defined just to silence vacuous warnings about symbol - * visibility on OS X/gcc. These symbols are force-inline and not - * exported. */ -#if defined(XP_MACOSX) -# define MOZALLOC_EXPORT_NEW MFBT_API -#else -# define MOZALLOC_EXPORT_NEW -#endif - -#if defined(ANDROID) -/* - * It's important to always specify 'throw()' in GCC because it's used to tell - * GCC that 'new' may return null. That makes GCC null-check the result before - * potentially initializing the memory to zero. - * Also, the Android minimalistic headers don't include std::bad_alloc. - */ -#define MOZALLOC_THROW_IF_HAS_EXCEPTIONS throw() -#define MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS -#elif defined(_MSC_VER) -/* - * Suppress build warning spam (bug 578546). - */ -#define MOZALLOC_THROW_IF_HAS_EXCEPTIONS -#define MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS -#else -#define MOZALLOC_THROW_IF_HAS_EXCEPTIONS throw() -#define MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS throw(std::bad_alloc) -#endif - -#define MOZALLOC_THROW_BAD_ALLOC MOZALLOC_THROW_BAD_ALLOC_IF_HAS_EXCEPTIONS - -MOZALLOC_EXPORT_NEW -#if defined(__GNUC__) && !defined(__clang__) && defined(__SANITIZE_ADDRESS__) -/* gcc's asan somehow doesn't like always_inline on this function. */ -__attribute__((gnu_inline)) inline -#else -MOZALLOC_INLINE -#endif -void* operator new(size_t size) MOZALLOC_THROW_BAD_ALLOC -{ - return moz_xmalloc(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void* operator new(size_t size, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void* operator new[](size_t size) MOZALLOC_THROW_BAD_ALLOC -{ - return moz_xmalloc(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void* operator new[](size_t size, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete(void* ptr) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete(void* ptr, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete[](void* ptr) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - -MOZALLOC_EXPORT_NEW MOZALLOC_INLINE -void operator delete[](void* ptr, const std::nothrow_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return free_impl(ptr); -} - - -/* - * We also add a new allocator variant: "fallible operator new." - * Unlike libmozalloc's implementations of the standard nofail - * allocators, this allocator is allowed to return NULL. It can be used - * as follows - * - * Foo* f = new (mozilla::fallible) Foo(...); - * - * operator delete(fallible) is defined for completeness only. - * - * Each operator new below returns a pointer to memory that can be - * delete'd by any of - * - * (1) the matching "fallible" operator delete below - * (2) the matching infallible operator delete above - * (3) the matching system |operator delete(void*, std::nothrow)| - * (4) the matching system |operator delete(void*) throw(std::bad_alloc)| - */ - -MOZALLOC_INLINE -void* operator new(size_t size, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_INLINE -void* operator new[](size_t size, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - return malloc_impl(size); -} - -MOZALLOC_INLINE -void operator delete(void* ptr, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - free_impl(ptr); -} - -MOZALLOC_INLINE -void operator delete[](void* ptr, const mozilla::fallible_t&) MOZALLOC_THROW_IF_HAS_EXCEPTIONS -{ - free_impl(ptr); -} - - -/* - * This policy is identical to MallocAllocPolicy, except it uses - * moz_xmalloc/moz_xcalloc/moz_xrealloc instead of - * malloc/calloc/realloc. - */ -class InfallibleAllocPolicy -{ -public: - template - T* maybe_pod_malloc(size_t aNumElems) - { - return pod_malloc(aNumElems); - } - - template - T* maybe_pod_calloc(size_t aNumElems) - { - return pod_calloc(aNumElems); - } - - template - T* maybe_pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - return pod_realloc(aPtr, aOldSize, aNewSize); - } - - template - T* pod_malloc(size_t aNumElems) - { - if (aNumElems & mozilla::tl::MulOverflowMask::value) { - reportAllocOverflow(); - } - return static_cast(moz_xmalloc(aNumElems * sizeof(T))); - } - - template - T* pod_calloc(size_t aNumElems) - { - return static_cast(moz_xcalloc(aNumElems, sizeof(T))); - } - - template - T* pod_realloc(T* aPtr, size_t aOldSize, size_t aNewSize) - { - if (aNewSize & mozilla::tl::MulOverflowMask::value) { - reportAllocOverflow(); - } - return static_cast(moz_xrealloc(aPtr, aNewSize * sizeof(T))); - } - - void free_(void* aPtr) - { - free_impl(aPtr); - } - - void reportAllocOverflow() const - { - mozalloc_abort("alloc overflow"); - } - - bool checkSimulatedOOM() const - { - return true; - } -}; - -#endif /* ifdef __cplusplus */ - -#ifdef malloc_impl_ -#undef malloc_impl_ -#undef malloc_impl -#endif -#ifdef free_impl_ -#undef free_impl_ -#undef free_impl -#endif - -#endif /* ifndef mozilla_mozalloc_h */ diff --git a/win32/include/spidermonkey/mozilla/mozalloc_abort.h b/win32/include/spidermonkey/mozilla/mozalloc_abort.h deleted file mode 100755 index 065cebcb..00000000 --- a/win32/include/spidermonkey/mozilla/mozalloc_abort.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: sw=4 ts=4 et : - */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_mozalloc_abort_h -#define mozilla_mozalloc_abort_h - -#include "mozilla/Attributes.h" -#include "mozilla/Types.h" - -/** - * Terminate this process in such a way that breakpad is triggered, if - * at all possible. - * - * Note: MOZ_NORETURN seems to break crash stacks on ARM, so we don't - * use that annotation there. - */ -MFBT_API -#if !defined(__arm__) - MOZ_NORETURN -#endif - void mozalloc_abort(const char* const msg); - - -#endif /* ifndef mozilla_mozalloc_abort_h */ diff --git a/win32/include/spidermonkey/mozilla/mozalloc_oom.h b/win32/include/spidermonkey/mozilla/mozalloc_oom.h deleted file mode 100755 index 35bb9acc..00000000 --- a/win32/include/spidermonkey/mozilla/mozalloc_oom.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: sw=4 ts=4 et : - */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_mozalloc_oom_h -#define mozilla_mozalloc_oom_h - -#include "mozalloc.h" - -/** - * Called when memory is critically low. Returns iff it was able to - * remedy the critical memory situation; if not, it will abort(). - */ -MFBT_API void mozalloc_handle_oom(size_t requestedSize); - -/** - * Called by embedders (specifically Mozilla breakpad) which wants to be - * notified of an intentional abort, to annotate any crash report with - * the size of the allocation on which we aborted. - */ -typedef void (*mozalloc_oom_abort_handler)(size_t size); -MFBT_API void mozalloc_set_oom_abort_handler(mozalloc_oom_abort_handler handler); - -/* TODO: functions to query system memory usage and register - * critical-memory handlers. */ - - -#endif /* ifndef mozilla_mozalloc_oom_h */ diff --git a/win32/include/spidermonkey/mozilla/utils.h b/win32/include/spidermonkey/mozilla/utils.h deleted file mode 100755 index 15dd4bfb..00000000 --- a/win32/include/spidermonkey/mozilla/utils.h +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright 2010 the V8 project authors. All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following -// disclaimer in the documentation and/or other materials provided -// with the distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef DOUBLE_CONVERSION_UTILS_H_ -#define DOUBLE_CONVERSION_UTILS_H_ - -#include -#include - -#include "mozilla/Assertions.h" -#ifndef ASSERT -#define ASSERT(condition) MOZ_ASSERT(condition) -#endif -#ifndef UNIMPLEMENTED -#define UNIMPLEMENTED() MOZ_CRASH() -#endif -#ifndef UNREACHABLE -#define UNREACHABLE() MOZ_CRASH() -#endif - -// Double operations detection based on target architecture. -// Linux uses a 80bit wide floating point stack on x86. This induces double -// rounding, which in turn leads to wrong results. -// An easy way to test if the floating-point operations are correct is to -// evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then -// the result is equal to 89255e-22. -// The best way to test this, is to create a division-function and to compare -// the output of the division with the expected result. (Inlining must be -// disabled.) -// On Linux,x86 89255e-22 != Div_double(89255.0/1e22) -#if defined(_M_X64) || defined(__x86_64__) || \ - defined(__ARMEL__) || defined(__avr32__) || \ - defined(__hppa__) || defined(__ia64__) || \ - defined(__mips__) || \ - defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \ - defined(__sparc__) || defined(__sparc) || defined(__s390__) || \ - defined(__SH4__) || defined(__alpha__) || \ - defined(_MIPS_ARCH_MIPS32R2) || \ - defined(__AARCH64EL__) || defined(__aarch64__) -#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 -#elif defined(_M_IX86) || defined(__i386__) || defined(__i386) -#if defined(_WIN32) -// Windows uses a 64bit wide floating point stack. -#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 -#else -#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS -#endif // _WIN32 -#else -#error Target architecture was not detected as supported by Double-Conversion. -#endif - - -#include - -// The following macro works on both 32 and 64-bit platforms. -// Usage: instead of writing 0x1234567890123456 -// write UINT64_2PART_C(0x12345678,90123456); -#define UINT64_2PART_C(a, b) (((static_cast(a) << 32) + 0x##b##u)) - - -// The expression ARRAY_SIZE(a) is a compile-time constant of type -// size_t which represents the number of elements of the given -// array. You should only use ARRAY_SIZE on statically allocated -// arrays. -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(a) \ - ((sizeof(a) / sizeof(*(a))) / \ - static_cast(!(sizeof(a) % sizeof(*(a))))) -#endif - -// A macro to disallow the evil copy constructor and operator= functions -// This should be used in the private: declarations for a class -#ifndef DISALLOW_COPY_AND_ASSIGN -#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&); \ - void operator=(const TypeName&) -#endif - -// A macro to disallow all the implicit constructors, namely the -// default constructor, copy constructor and operator= functions. -// -// This should be used in the private: declarations for a class -// that wants to prevent anyone from instantiating it. This is -// especially useful for classes containing only static methods. -#ifndef DISALLOW_IMPLICIT_CONSTRUCTORS -#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ - TypeName(); \ - DISALLOW_COPY_AND_ASSIGN(TypeName) -#endif - -namespace double_conversion { - -static const int kCharSize = sizeof(char); - -// Returns the maximum of the two parameters. -template -static T Max(T a, T b) { - return a < b ? b : a; -} - - -// Returns the minimum of the two parameters. -template -static T Min(T a, T b) { - return a < b ? a : b; -} - - -inline int StrLength(const char* string) { - size_t length = strlen(string); - ASSERT(length == static_cast(static_cast(length))); - return static_cast(length); -} - -// This is a simplified version of V8's Vector class. -template -class Vector { - public: - Vector() : start_(NULL), length_(0) {} - Vector(T* data, int len) : start_(data), length_(len) { - ASSERT(len == 0 || (len > 0 && data != NULL)); - } - - // Returns a vector using the same backing storage as this one, - // spanning from and including 'from', to but not including 'to'. - Vector SubVector(int from, int to) { - ASSERT(to <= length_); - ASSERT(from < to); - ASSERT(0 <= from); - return Vector(start() + from, to - from); - } - - // Returns the length of the vector. - int length() const { return length_; } - - // Returns whether or not the vector is empty. - bool is_empty() const { return length_ == 0; } - - // Returns the pointer to the start of the data in the vector. - T* start() const { return start_; } - - // Access individual vector elements - checks bounds in debug mode. - T& operator[](int index) const { - ASSERT(0 <= index && index < length_); - return start_[index]; - } - - T& first() { return start_[0]; } - - T& last() { return start_[length_ - 1]; } - - private: - T* start_; - int length_; -}; - - -// Helper class for building result strings in a character buffer. The -// purpose of the class is to use safe operations that checks the -// buffer bounds on all operations in debug mode. -class StringBuilder { - public: - StringBuilder(char* buffer, int buffer_size) - : buffer_(buffer, buffer_size), position_(0) { } - - ~StringBuilder() { if (!is_finalized()) Finalize(); } - - int size() const { return buffer_.length(); } - - // Get the current position in the builder. - int position() const { - ASSERT(!is_finalized()); - return position_; - } - - // Reset the position. - void Reset() { position_ = 0; } - - // Add a single character to the builder. It is not allowed to add - // 0-characters; use the Finalize() method to terminate the string - // instead. - void AddCharacter(char c) { - ASSERT(c != '\0'); - ASSERT(!is_finalized() && position_ < buffer_.length()); - buffer_[position_++] = c; - } - - // Add an entire string to the builder. Uses strlen() internally to - // compute the length of the input string. - void AddString(const char* s) { - AddSubstring(s, StrLength(s)); - } - - // Add the first 'n' characters of the given string 's' to the - // builder. The input string must have enough characters. - void AddSubstring(const char* s, int n) { - ASSERT(!is_finalized() && position_ + n < buffer_.length()); - ASSERT(static_cast(n) <= strlen(s)); - memmove(&buffer_[position_], s, n * kCharSize); - position_ += n; - } - - - // Add character padding to the builder. If count is non-positive, - // nothing is added to the builder. - void AddPadding(char c, int count) { - for (int i = 0; i < count; i++) { - AddCharacter(c); - } - } - - // Finalize the string by 0-terminating it and returning the buffer. - char* Finalize() { - ASSERT(!is_finalized() && position_ < buffer_.length()); - buffer_[position_] = '\0'; - // Make sure nobody managed to add a 0-character to the - // buffer while building the string. - ASSERT(strlen(buffer_.start()) == static_cast(position_)); - position_ = -1; - ASSERT(is_finalized()); - return buffer_.start(); - } - - private: - Vector buffer_; - int position_; - - bool is_finalized() const { return position_ < 0; } - - DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder); -}; - -// The type-based aliasing rule allows the compiler to assume that pointers of -// different types (for some definition of different) never alias each other. -// Thus the following code does not work: -// -// float f = foo(); -// int fbits = *(int*)(&f); -// -// The compiler 'knows' that the int pointer can't refer to f since the types -// don't match, so the compiler may cache f in a register, leaving random data -// in fbits. Using C++ style casts makes no difference, however a pointer to -// char data is assumed to alias any other pointer. This is the 'memcpy -// exception'. -// -// Bit_cast uses the memcpy exception to move the bits from a variable of one -// type of a variable of another type. Of course the end result is likely to -// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005) -// will completely optimize BitCast away. -// -// There is an additional use for BitCast. -// Recent gccs will warn when they see casts that may result in breakage due to -// the type-based aliasing rule. If you have checked that there is no breakage -// you can use BitCast to cast one pointer type to another. This confuses gcc -// enough that it can no longer see that you have cast one pointer type to -// another thus avoiding the warning. -template -inline Dest BitCast(const Source& source) { - static_assert(sizeof(Dest) == sizeof(Source), - "BitCast's source and destination types must be the same size"); - - Dest dest; - memmove(&dest, &source, sizeof(dest)); - return dest; -} - -template -inline Dest BitCast(Source* source) { - return BitCast(reinterpret_cast(source)); -} - -} // namespace double_conversion - -#endif // DOUBLE_CONVERSION_UTILS_H_ diff --git a/win32/include/spidermonkey/mozzconf.h b/win32/include/spidermonkey/mozzconf.h deleted file mode 100755 index f1da5ae2..00000000 --- a/win32/include/spidermonkey/mozzconf.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef MOZZCONF_H -#define MOZZCONF_H - -#include "mozilla/Types.h" - -#if defined(ZLIB_IN_MOZGLUE) -#define ZEXTERN MFBT_API -#endif - -/* Exported Symbols */ -#define zlibVersion MOZ_Z_zlibVersion -#define deflate MOZ_Z_deflate -#define deflateEnd MOZ_Z_deflateEnd -#define inflate MOZ_Z_inflate -#define inflateEnd MOZ_Z_inflateEnd -#define deflateSetDictionary MOZ_Z_deflateSetDictionary -#define deflateCopy MOZ_Z_deflateCopy -#define deflateReset MOZ_Z_deflateReset -#define deflateParams MOZ_Z_deflateParams -#define deflateBound MOZ_Z_deflateBound -#define deflatePrime MOZ_Z_deflatePrime -#define inflateSetDictionary MOZ_Z_inflateSetDictionary -#define inflateSync MOZ_Z_inflateSync -#define inflateCopy MOZ_Z_inflateCopy -#define inflateReset MOZ_Z_inflateReset -#define inflateBack MOZ_Z_inflateBack -#define inflateBackEnd MOZ_Z_inflateBackEnd -#define zlibCompileFlags MOZ_Z_zlibCompileFlags -#define compress MOZ_Z_compress -#define compress2 MOZ_Z_compress2 -#define compressBound MOZ_Z_compressBound -#define uncompress MOZ_Z_uncompress -#define gzopen MOZ_Z_gzopen -#define gzdopen MOZ_Z_gzdopen -#define gzsetparams MOZ_Z_gzsetparams -#define gzread MOZ_Z_gzread -#define gzwrite MOZ_Z_gzwrite -#define gzprintf MOZ_Z_gzprintf -#define gzputs MOZ_Z_gzputs -#define gzgets MOZ_Z_gzgets -#define gzputc MOZ_Z_gzputc -#define gzgetc MOZ_Z_gzgetc -#define gzungetc MOZ_Z_gzungetc -#define gzflush MOZ_Z_gzflush -#define gzseek MOZ_Z_gzseek -#define gzrewind MOZ_Z_gzrewind -#define gztell MOZ_Z_gztell -#define gzeof MOZ_Z_gzeof -#define gzclose MOZ_Z_gzclose -#define gzerror MOZ_Z_gzerror -#define gzclearerr MOZ_Z_gzclearerr -#define adler32 MOZ_Z_adler32 -#define crc32 MOZ_Z_crc32 -#define deflateInit_ MOZ_Z_deflateInit_ -#define deflateInit2_ MOZ_Z_deflateInit2_ -#define inflateInit_ MOZ_Z_inflateInit_ -#define inflateInit2_ MOZ_Z_inflateInit2_ -#define inflateBackInit_ MOZ_Z_inflateBackInit_ -#define inflateSyncPoint MOZ_Z_inflateSyncPoint -#define get_crc_table MOZ_Z_get_crc_table -#define zError MOZ_Z_zError - -/* Extra global symbols */ -#define _dist_code MOZ_Z__dist_code -#define _length_code MOZ_Z__length_code -#define _tr_align MOZ_Z__tr_align -#define _tr_flush_block MOZ_Z__tr_flush_block -#define _tr_init MOZ_Z__tr_init -#define _tr_stored_block MOZ_Z__tr_stored_block -#define _tr_tally MOZ_Z__tr_tally -#define deflate_copyright MOZ_Z_deflate_copyright -#define inflate_copyright MOZ_Z_inflate_copyright -#define inflate_fast MOZ_Z_inflate_fast -#define inflate_table MOZ_Z_inflate_table -#define z_errmsg MOZ_Z_z_errmsg -#define zcalloc MOZ_Z_zcalloc -#define zcfree MOZ_Z_zcfree -#define alloc_func MOZ_Z_alloc_func -#define free_func MOZ_Z_free_func -#define in_func MOZ_Z_in_func -#define out_func MOZ_Z_out_func - -/* New as of zlib-1.2.3 */ -#define adler32_combine MOZ_Z_adler32_combine -#define crc32_combine MOZ_Z_crc32_combine -#define deflateSetHeader MOZ_Z_deflateSetHeader -#define deflateTune MOZ_Z_deflateTune -#define gzdirect MOZ_Z_gzdirect -#define inflatePrime MOZ_Z_inflatePrime -#define inflateGetHeader MOZ_Z_inflateGetHeader - -/* New as of zlib-1.2.4 */ -#define adler32_combine64 MOZ_Z_adler32_combine64 -#define crc32_combine64 MOZ_Z_crc32_combine64 -#define gz_error MOZ_Z_gz_error -#define gz_intmax MOZ_Z_gz_intmax -#define gz_strwinerror MOZ_Z_gz_strwinerror -#define gzbuffer MOZ_Z_gzbuffer -#define gzclose_r MOZ_Z_gzclose_r -#define gzclose_w MOZ_Z_gzclose_w -#define gzoffset MOZ_Z_gzoffset -#define gzoffset64 MOZ_Z_gzoffset64 -#define gzopen64 MOZ_Z_gzopen64 -#define gzseek64 MOZ_Z_gzseek64 -#define gztell64 MOZ_Z_gztell64 -#define inflateMark MOZ_Z_inflateMark -#define inflateReset2 MOZ_Z_inflateReset2 -#define inflateUndermine MOZ_Z_inflateUndermine - -/* New as of zlib-1.2.6 */ -#define deflatePending MOZ_Z_deflatePending -#define deflateResetKeep MOZ_Z_deflateResetKeep -#define inflateResetKeep MOZ_Z_inflateResetKeep -#define gzgetc_ MOZ_Z_gzgetc_ - -/* New as of zlib-1.2.7 */ -#define gzopen_w MOZ_Z_gzopen_w - -/* New as of zlib-1.2.8 */ -#define _tr_flush_bits MOZ_Z__tr_flush_bits -#define gzvprintf MOZ_Z_gzvprintf -#define inflateGetDictionary MOZ_Z_inflateGetDictionary - -#endif diff --git a/win32/include/spidermonkey/nspr/md/_darwin.cfg b/win32/include/spidermonkey/nspr/md/_darwin.cfg deleted file mode 100755 index 5e118933..00000000 --- a/win32/include/spidermonkey/nspr/md/_darwin.cfg +++ /dev/null @@ -1,165 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef nspr_cpucfg___ -#define nspr_cpucfg___ - -#ifndef XP_UNIX -#define XP_UNIX -#endif - -#define PR_AF_INET6 30 /* same as AF_INET6 */ - -#ifdef __LITTLE_ENDIAN__ -#undef IS_BIG_ENDIAN -#define IS_LITTLE_ENDIAN 1 -#else -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#endif - -#ifdef __LP64__ -#define IS_64 -#endif - -#ifndef HAVE_LONG_LONG -#define HAVE_LONG_LONG -#endif -#undef HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS 1 - -#ifdef IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 -#define PR_BITS_PER_DWORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 -#define PR_BITS_PER_DWORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 -#define PR_ALIGN_OF_DWORD 8 - -#else /* IS_64 */ - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 -#define PR_BITS_PER_DWORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#endif /* IS_64 */ - -#ifndef NO_NSPR_10_SUPPORT - -#define BYTES_PER_BYTE PR_BYTES_PER_BYTE -#define BYTES_PER_SHORT PR_BYTES_PER_SHORT -#define BYTES_PER_INT PR_BYTES_PER_INT -#define BYTES_PER_INT64 PR_BYTES_PER_INT64 -#define BYTES_PER_LONG PR_BYTES_PER_LONG -#define BYTES_PER_FLOAT PR_BYTES_PER_FLOAT -#define BYTES_PER_DOUBLE PR_BYTES_PER_DOUBLE -#define BYTES_PER_WORD PR_BYTES_PER_WORD -#define BYTES_PER_DWORD PR_BYTES_PER_DWORD - -#define BITS_PER_BYTE PR_BITS_PER_BYTE -#define BITS_PER_SHORT PR_BITS_PER_SHORT -#define BITS_PER_INT PR_BITS_PER_INT -#define BITS_PER_INT64 PR_BITS_PER_INT64 -#define BITS_PER_LONG PR_BITS_PER_LONG -#define BITS_PER_FLOAT PR_BITS_PER_FLOAT -#define BITS_PER_DOUBLE PR_BITS_PER_DOUBLE -#define BITS_PER_WORD PR_BITS_PER_WORD - -#define BITS_PER_BYTE_LOG2 PR_BITS_PER_BYTE_LOG2 -#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2 -#define BITS_PER_INT_LOG2 PR_BITS_PER_INT_LOG2 -#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2 -#define BITS_PER_LONG_LOG2 PR_BITS_PER_LONG_LOG2 -#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2 -#define BITS_PER_DOUBLE_LOG2 PR_BITS_PER_DOUBLE_LOG2 -#define BITS_PER_WORD_LOG2 PR_BITS_PER_WORD_LOG2 - -#define ALIGN_OF_SHORT PR_ALIGN_OF_SHORT -#define ALIGN_OF_INT PR_ALIGN_OF_INT -#define ALIGN_OF_LONG PR_ALIGN_OF_LONG -#define ALIGN_OF_INT64 PR_ALIGN_OF_INT64 -#define ALIGN_OF_FLOAT PR_ALIGN_OF_FLOAT -#define ALIGN_OF_DOUBLE PR_ALIGN_OF_DOUBLE -#define ALIGN_OF_POINTER PR_ALIGN_OF_POINTER -#define ALIGN_OF_WORD PR_ALIGN_OF_WORD - -#define BYTES_PER_WORD_LOG2 PR_BYTES_PER_WORD_LOG2 -#define BYTES_PER_DWORD_LOG2 PR_BYTES_PER_DWORD_LOG2 -#define WORDS_PER_DWORD_LOG2 PR_WORDS_PER_DWORD_LOG2 - -#endif /* NO_NSPR_10_SUPPORT */ - -#endif /* nspr_cpucfg___ */ - diff --git a/win32/include/spidermonkey/nspr/md/_freebsd.cfg b/win32/include/spidermonkey/nspr/md/_freebsd.cfg deleted file mode 100755 index 1d1039a5..00000000 --- a/win32/include/spidermonkey/nspr/md/_freebsd.cfg +++ /dev/null @@ -1,594 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef nspr_cpucfg___ -#define nspr_cpucfg___ - -#ifndef XP_UNIX -#define XP_UNIX -#endif - -#ifndef FREEBSD -#define FREEBSD -#endif - -#define PR_AF_INET6 28 /* same as AF_INET6 */ - -#ifndef HAVE_LONG_LONG -#define HAVE_LONG_LONG -#endif - -#if defined(__i386__) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#undef HAVE_ALIGNED_DOUBLES -#undef HAVE_ALIGNED_LONGLONGS - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 - -#elif defined(__alpha__) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 - -#elif defined(__sparc__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 - -#elif defined(__ia64__) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#elif defined(__amd64__) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#elif defined(__powerpc64__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__powerpc__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__aarch64__) - -#undef IS_BIG_ENDIAN -#define IS_LITTLE_ENDIAN 1 -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__arm__) - -#if defined(__ARMEB__) || defined(__ARM_BIG_ENDIAN__) -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#else -#undef IS_BIG_ENDIAN -#define IS_LITTLE_ENDIAN 1 -#endif - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__mips64__) - -#if defined(__MIPSEB__) || defined(_MIPSEB) -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#else -#undef IS_BIG_ENDIAN -#define IS_LITTLE_ENDIAN 1 -#endif - -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__mips__) - -#if defined(__MIPSEB__) || defined(_MIPSEB) -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#else -#undef IS_BIG_ENDIAN -#define IS_LITTLE_ENDIAN 1 -#endif - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#else - -#error "Unknown CPU architecture" - -#endif - -#ifndef NO_NSPR_10_SUPPORT - -#define BYTES_PER_BYTE PR_BYTES_PER_BYTE -#define BYTES_PER_SHORT PR_BYTES_PER_SHORT -#define BYTES_PER_INT PR_BYTES_PER_INT -#define BYTES_PER_INT64 PR_BYTES_PER_INT64 -#define BYTES_PER_LONG PR_BYTES_PER_LONG -#define BYTES_PER_FLOAT PR_BYTES_PER_FLOAT -#define BYTES_PER_DOUBLE PR_BYTES_PER_DOUBLE -#define BYTES_PER_WORD PR_BYTES_PER_WORD -#define BYTES_PER_DWORD PR_BYTES_PER_DWORD - -#define BITS_PER_BYTE PR_BITS_PER_BYTE -#define BITS_PER_SHORT PR_BITS_PER_SHORT -#define BITS_PER_INT PR_BITS_PER_INT -#define BITS_PER_INT64 PR_BITS_PER_INT64 -#define BITS_PER_LONG PR_BITS_PER_LONG -#define BITS_PER_FLOAT PR_BITS_PER_FLOAT -#define BITS_PER_DOUBLE PR_BITS_PER_DOUBLE -#define BITS_PER_WORD PR_BITS_PER_WORD - -#define BITS_PER_BYTE_LOG2 PR_BITS_PER_BYTE_LOG2 -#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2 -#define BITS_PER_INT_LOG2 PR_BITS_PER_INT_LOG2 -#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2 -#define BITS_PER_LONG_LOG2 PR_BITS_PER_LONG_LOG2 -#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2 -#define BITS_PER_DOUBLE_LOG2 PR_BITS_PER_DOUBLE_LOG2 -#define BITS_PER_WORD_LOG2 PR_BITS_PER_WORD_LOG2 - -#define ALIGN_OF_SHORT PR_ALIGN_OF_SHORT -#define ALIGN_OF_INT PR_ALIGN_OF_INT -#define ALIGN_OF_LONG PR_ALIGN_OF_LONG -#define ALIGN_OF_INT64 PR_ALIGN_OF_INT64 -#define ALIGN_OF_FLOAT PR_ALIGN_OF_FLOAT -#define ALIGN_OF_DOUBLE PR_ALIGN_OF_DOUBLE -#define ALIGN_OF_POINTER PR_ALIGN_OF_POINTER -#define ALIGN_OF_WORD PR_ALIGN_OF_WORD - -#define BYTES_PER_WORD_LOG2 PR_BYTES_PER_WORD_LOG2 -#define BYTES_PER_DWORD_LOG2 PR_BYTES_PER_DWORD_LOG2 -#define WORDS_PER_DWORD_LOG2 PR_WORDS_PER_DWORD_LOG2 - -#endif /* NO_NSPR_10_SUPPORT */ - -#endif /* nspr_cpucfg___ */ diff --git a/win32/include/spidermonkey/nspr/md/_linux.cfg b/win32/include/spidermonkey/nspr/md/_linux.cfg deleted file mode 100755 index 8cbf0cb9..00000000 --- a/win32/include/spidermonkey/nspr/md/_linux.cfg +++ /dev/null @@ -1,1081 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * This file is used by not only Linux but also other glibc systems - * such as GNU/Hurd and GNU/k*BSD. - */ - -#ifndef nspr_cpucfg___ -#define nspr_cpucfg___ - -#ifndef XP_UNIX -#define XP_UNIX -#endif - -#if !defined(LINUX) && defined(__linux__) -#define LINUX -#endif - -#ifdef __FreeBSD_kernel__ -#define PR_AF_INET6 28 /* same as AF_INET6 */ -#elif defined(__GNU__) -#define PR_AF_INET6 26 /* same as AF_INET6 */ -#else -#define PR_AF_INET6 10 /* same as AF_INET6 */ -#endif - -#ifdef __powerpc64__ - -#ifdef __LITTLE_ENDIAN__ -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#else -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#endif -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__powerpc__) - -#ifdef __LITTLE_ENDIAN__ -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#else -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#endif - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__alpha) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__ia64__) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__x86_64__) - -#ifdef __ILP32__ - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#else - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#endif - -#elif defined(__mc68000__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 2 -#define PR_ALIGN_OF_LONG 2 -#define PR_ALIGN_OF_INT64 2 -#define PR_ALIGN_OF_FLOAT 2 -#define PR_ALIGN_OF_DOUBLE 2 -#define PR_ALIGN_OF_POINTER 2 -#define PR_ALIGN_OF_WORD 2 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__sparc__) && defined (__arch64__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__sparc__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__i386__) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__mips__) - -#ifdef __MIPSEB__ -#define IS_BIG_ENDIAN 1 -#undef IS_LITTLE_ENDIAN -#elif defined(__MIPSEL__) -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#else -#error "Unknown MIPS endianness." -#endif - -#if _MIPS_SIM == _ABI64 - -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#else /* _ABI64 */ - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#endif /* _ABI64 */ - -#elif defined(__arm__) - -#ifdef __ARMEB__ -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#elif defined(__ARMEL__) -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#else -#error "Unknown ARM endianness." -#endif - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__aarch64__) - -#ifdef __AARCH64EB__ -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#elif defined(__AARCH64EL__) -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#else -#error "Unknown Aarch64 endianness." -#endif -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__hppa__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__s390x__) - -#define IS_BIG_ENDIAN 1 -#undef IS_LITTLE_ENDIAN -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__s390__) - -#define IS_BIG_ENDIAN 1 -#undef IS_LITTLE_ENDIAN - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__sh__) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__avr32__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__m32r__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__or1k__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#else - -#error "Unknown CPU architecture" - -#endif - -#ifndef HAVE_LONG_LONG -#define HAVE_LONG_LONG -#endif -#if PR_ALIGN_OF_DOUBLE == 8 -#define HAVE_ALIGNED_DOUBLES -#endif -#if PR_ALIGN_OF_INT64 == 8 -#define HAVE_ALIGNED_LONGLONGS -#endif - -#ifndef NO_NSPR_10_SUPPORT - -#define BYTES_PER_BYTE PR_BYTES_PER_BYTE -#define BYTES_PER_SHORT PR_BYTES_PER_SHORT -#define BYTES_PER_INT PR_BYTES_PER_INT -#define BYTES_PER_INT64 PR_BYTES_PER_INT64 -#define BYTES_PER_LONG PR_BYTES_PER_LONG -#define BYTES_PER_FLOAT PR_BYTES_PER_FLOAT -#define BYTES_PER_DOUBLE PR_BYTES_PER_DOUBLE -#define BYTES_PER_WORD PR_BYTES_PER_WORD -#define BYTES_PER_DWORD PR_BYTES_PER_DWORD - -#define BITS_PER_BYTE PR_BITS_PER_BYTE -#define BITS_PER_SHORT PR_BITS_PER_SHORT -#define BITS_PER_INT PR_BITS_PER_INT -#define BITS_PER_INT64 PR_BITS_PER_INT64 -#define BITS_PER_LONG PR_BITS_PER_LONG -#define BITS_PER_FLOAT PR_BITS_PER_FLOAT -#define BITS_PER_DOUBLE PR_BITS_PER_DOUBLE -#define BITS_PER_WORD PR_BITS_PER_WORD - -#define BITS_PER_BYTE_LOG2 PR_BITS_PER_BYTE_LOG2 -#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2 -#define BITS_PER_INT_LOG2 PR_BITS_PER_INT_LOG2 -#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2 -#define BITS_PER_LONG_LOG2 PR_BITS_PER_LONG_LOG2 -#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2 -#define BITS_PER_DOUBLE_LOG2 PR_BITS_PER_DOUBLE_LOG2 -#define BITS_PER_WORD_LOG2 PR_BITS_PER_WORD_LOG2 - -#define ALIGN_OF_SHORT PR_ALIGN_OF_SHORT -#define ALIGN_OF_INT PR_ALIGN_OF_INT -#define ALIGN_OF_LONG PR_ALIGN_OF_LONG -#define ALIGN_OF_INT64 PR_ALIGN_OF_INT64 -#define ALIGN_OF_FLOAT PR_ALIGN_OF_FLOAT -#define ALIGN_OF_DOUBLE PR_ALIGN_OF_DOUBLE -#define ALIGN_OF_POINTER PR_ALIGN_OF_POINTER -#define ALIGN_OF_WORD PR_ALIGN_OF_WORD - -#define BYTES_PER_WORD_LOG2 PR_BYTES_PER_WORD_LOG2 -#define BYTES_PER_DWORD_LOG2 PR_BYTES_PER_DWORD_LOG2 -#define WORDS_PER_DWORD_LOG2 PR_WORDS_PER_DWORD_LOG2 - -#endif /* NO_NSPR_10_SUPPORT */ - -#endif /* nspr_cpucfg___ */ diff --git a/win32/include/spidermonkey/nspr/md/_netbsd.cfg b/win32/include/spidermonkey/nspr/md/_netbsd.cfg deleted file mode 100755 index 1326556e..00000000 --- a/win32/include/spidermonkey/nspr/md/_netbsd.cfg +++ /dev/null @@ -1,351 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef nspr_cpucfg___ -#define nspr_cpucfg___ - -#ifndef XP_UNIX -#define XP_UNIX -#endif - -#ifndef NETBSD -#define NETBSD -#endif - -#define PR_AF_INET6 24 /* same as AF_INET6 */ - -#ifndef HAVE_LONG_LONG -#define HAVE_LONG_LONG -#endif - -#if defined(__i386__) || defined(__arm32__) || defined(__ARMEL__) || \ - defined(__MIPSEL__) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#undef HAVE_ALIGNED_DOUBLES -#undef HAVE_ALIGNED_LONGLONGS - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 - -#elif defined(__sparc_v9__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 - -#elif defined(__sparc__) || defined(__MIPSEB__) || defined(__ARMEB__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 - -#elif defined(__alpha__) -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__amd64__) -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__powerpc__) || defined(__m68k__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#undef HAVE_ALIGNED_DOUBLES -#undef HAVE_ALIGNED_LONGLONGS - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#else - -#error Must define constants for type sizes here. - -#endif - - -#ifndef NO_NSPR_10_SUPPORT - -#define BYTES_PER_BYTE PR_BYTES_PER_BYTE -#define BYTES_PER_SHORT PR_BYTES_PER_SHORT -#define BYTES_PER_INT PR_BYTES_PER_INT -#define BYTES_PER_INT64 PR_BYTES_PER_INT64 -#define BYTES_PER_LONG PR_BYTES_PER_LONG -#define BYTES_PER_FLOAT PR_BYTES_PER_FLOAT -#define BYTES_PER_DOUBLE PR_BYTES_PER_DOUBLE -#define BYTES_PER_WORD PR_BYTES_PER_WORD -#define BYTES_PER_DWORD PR_BYTES_PER_DWORD - -#define BITS_PER_BYTE PR_BITS_PER_BYTE -#define BITS_PER_SHORT PR_BITS_PER_SHORT -#define BITS_PER_INT PR_BITS_PER_INT -#define BITS_PER_INT64 PR_BITS_PER_INT64 -#define BITS_PER_LONG PR_BITS_PER_LONG -#define BITS_PER_FLOAT PR_BITS_PER_FLOAT -#define BITS_PER_DOUBLE PR_BITS_PER_DOUBLE -#define BITS_PER_WORD PR_BITS_PER_WORD - -#define BITS_PER_BYTE_LOG2 PR_BITS_PER_BYTE_LOG2 -#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2 -#define BITS_PER_INT_LOG2 PR_BITS_PER_INT_LOG2 -#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2 -#define BITS_PER_LONG_LOG2 PR_BITS_PER_LONG_LOG2 -#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2 -#define BITS_PER_DOUBLE_LOG2 PR_BITS_PER_DOUBLE_LOG2 -#define BITS_PER_WORD_LOG2 PR_BITS_PER_WORD_LOG2 - -#define ALIGN_OF_SHORT PR_ALIGN_OF_SHORT -#define ALIGN_OF_INT PR_ALIGN_OF_INT -#define ALIGN_OF_LONG PR_ALIGN_OF_LONG -#define ALIGN_OF_INT64 PR_ALIGN_OF_INT64 -#define ALIGN_OF_FLOAT PR_ALIGN_OF_FLOAT -#define ALIGN_OF_DOUBLE PR_ALIGN_OF_DOUBLE -#define ALIGN_OF_POINTER PR_ALIGN_OF_POINTER -#define ALIGN_OF_WORD PR_ALIGN_OF_WORD - -#define BYTES_PER_WORD_LOG2 PR_BYTES_PER_WORD_LOG2 -#define BYTES_PER_DWORD_LOG2 PR_BYTES_PER_DWORD_LOG2 -#define WORDS_PER_DWORD_LOG2 PR_WORDS_PER_DWORD_LOG2 - -#endif /* NO_NSPR_10_SUPPORT */ - -#endif /* nspr_cpucfg___ */ diff --git a/win32/include/spidermonkey/nspr/md/_openbsd.cfg b/win32/include/spidermonkey/nspr/md/_openbsd.cfg deleted file mode 100755 index b68d6e9c..00000000 --- a/win32/include/spidermonkey/nspr/md/_openbsd.cfg +++ /dev/null @@ -1,353 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef nspr_cpucfg___ -#define nspr_cpucfg___ - -#ifndef XP_UNIX -#define XP_UNIX -#endif - -#ifndef OPENBSD -#define OPENBSD -#endif - -#define PR_AF_INET6 24 /* same as AF_INET6 */ - -#ifndef HAVE_LONG_LONG -#define HAVE_LONG_LONG -#endif - -#if defined(__i386__) || defined(__arm__) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#undef HAVE_ALIGNED_DOUBLES -#undef HAVE_ALIGNED_LONGLONGS - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 - -#elif defined(__amd64__) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS - -#elif defined(__sparc_v9__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__sparc__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 - -#elif defined(__alpha__) -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(__powerpc__) || defined(__m68k__) - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 -#undef HAVE_ALIGNED_DOUBLES -#undef HAVE_ALIGNED_LONGLONGS - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#else - -#error Must define constants for type sizes here. - -#endif - - -#ifndef NO_NSPR_10_SUPPORT - -#define BYTES_PER_BYTE PR_BYTES_PER_BYTE -#define BYTES_PER_SHORT PR_BYTES_PER_SHORT -#define BYTES_PER_INT PR_BYTES_PER_INT -#define BYTES_PER_INT64 PR_BYTES_PER_INT64 -#define BYTES_PER_LONG PR_BYTES_PER_LONG -#define BYTES_PER_FLOAT PR_BYTES_PER_FLOAT -#define BYTES_PER_DOUBLE PR_BYTES_PER_DOUBLE -#define BYTES_PER_WORD PR_BYTES_PER_WORD -#define BYTES_PER_DWORD PR_BYTES_PER_DWORD - -#define BITS_PER_BYTE PR_BITS_PER_BYTE -#define BITS_PER_SHORT PR_BITS_PER_SHORT -#define BITS_PER_INT PR_BITS_PER_INT -#define BITS_PER_INT64 PR_BITS_PER_INT64 -#define BITS_PER_LONG PR_BITS_PER_LONG -#define BITS_PER_FLOAT PR_BITS_PER_FLOAT -#define BITS_PER_DOUBLE PR_BITS_PER_DOUBLE -#define BITS_PER_WORD PR_BITS_PER_WORD - -#define BITS_PER_BYTE_LOG2 PR_BITS_PER_BYTE_LOG2 -#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2 -#define BITS_PER_INT_LOG2 PR_BITS_PER_INT_LOG2 -#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2 -#define BITS_PER_LONG_LOG2 PR_BITS_PER_LONG_LOG2 -#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2 -#define BITS_PER_DOUBLE_LOG2 PR_BITS_PER_DOUBLE_LOG2 -#define BITS_PER_WORD_LOG2 PR_BITS_PER_WORD_LOG2 - -#define ALIGN_OF_SHORT PR_ALIGN_OF_SHORT -#define ALIGN_OF_INT PR_ALIGN_OF_INT -#define ALIGN_OF_LONG PR_ALIGN_OF_LONG -#define ALIGN_OF_INT64 PR_ALIGN_OF_INT64 -#define ALIGN_OF_FLOAT PR_ALIGN_OF_FLOAT -#define ALIGN_OF_DOUBLE PR_ALIGN_OF_DOUBLE -#define ALIGN_OF_POINTER PR_ALIGN_OF_POINTER -#define ALIGN_OF_WORD PR_ALIGN_OF_WORD - -#define BYTES_PER_WORD_LOG2 PR_BYTES_PER_WORD_LOG2 -#define BYTES_PER_DWORD_LOG2 PR_BYTES_PER_DWORD_LOG2 -#define WORDS_PER_DWORD_LOG2 PR_WORDS_PER_DWORD_LOG2 - -#endif /* NO_NSPR_10_SUPPORT */ - -#endif /* nspr_cpucfg___ */ diff --git a/win32/include/spidermonkey/nspr/md/_win95.cfg b/win32/include/spidermonkey/nspr/md/_win95.cfg deleted file mode 100755 index 1e693cc6..00000000 --- a/win32/include/spidermonkey/nspr/md/_win95.cfg +++ /dev/null @@ -1,272 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef nspr_cpucfg___ -#define nspr_cpucfg___ - -#ifndef XP_PC -#define XP_PC -#endif - -#ifndef WIN32 -#define WIN32 -#endif - -#ifndef WIN95 -#define WIN95 -#endif - -#define PR_AF_INET6 23 /* same as AF_INET6 */ - -#if defined(_M_IX86) || defined(_X86_) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_DOUBLE 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_WORD 32 -#define PR_BITS_PER_DWORD 64 -#define PR_BITS_PER_DOUBLE 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_WORD_LOG2 5 -#define PR_BITS_PER_DWORD_LOG2 6 -#define PR_BITS_PER_DOUBLE_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_WORD 4 -#define PR_ALIGN_OF_DWORD 8 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_DOUBLE 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_WORD 64 -#define PR_BITS_PER_DWORD 64 -#define PR_BITS_PER_DOUBLE 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_WORD_LOG2 6 -#define PR_BITS_PER_DWORD_LOG2 6 -#define PR_BITS_PER_DOUBLE_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_WORD 8 -#define PR_ALIGN_OF_DWORD 8 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(_M_IA64) || defined(_IA64_) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN -#define IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_DOUBLE 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_WORD 64 -#define PR_BITS_PER_DWORD 64 -#define PR_BITS_PER_DOUBLE 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_WORD_LOG2 6 -#define PR_BITS_PER_DWORD_LOG2 6 -#define PR_BITS_PER_DOUBLE_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_WORD 8 -#define PR_ALIGN_OF_DWORD 8 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 - -#define PR_BYTES_PER_WORD_LOG2 3 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#elif defined(_M_ARM) || defined(_ARM_) - -#define IS_LITTLE_ENDIAN 1 -#undef IS_BIG_ENDIAN - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_DOUBLE 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_WORD 32 -#define PR_BITS_PER_DWORD 64 -#define PR_BITS_PER_DOUBLE 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_WORD_LOG2 5 -#define PR_BITS_PER_DWORD_LOG2 6 -#define PR_BITS_PER_DOUBLE_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_WORD 4 -#define PR_ALIGN_OF_DWORD 8 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 4 - -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#else /* defined(_M_IX86) || defined(_X86_) */ - -#error unknown processor architecture - -#endif /* defined(_M_IX86) || defined(_X86_) */ - -#ifndef HAVE_LONG_LONG -#define HAVE_LONG_LONG -#endif - -#ifndef NO_NSPR_10_SUPPORT - -#define BYTES_PER_BYTE PR_BYTES_PER_BYTE -#define BYTES_PER_SHORT PR_BYTES_PER_SHORT -#define BYTES_PER_INT PR_BYTES_PER_INT -#define BYTES_PER_INT64 PR_BYTES_PER_INT64 -#define BYTES_PER_LONG PR_BYTES_PER_LONG -#define BYTES_PER_FLOAT PR_BYTES_PER_FLOAT -#define BYTES_PER_DOUBLE PR_BYTES_PER_DOUBLE -#define BYTES_PER_WORD PR_BYTES_PER_WORD -#define BYTES_PER_DWORD PR_BYTES_PER_DWORD - -#define BITS_PER_BYTE PR_BITS_PER_BYTE -#define BITS_PER_SHORT PR_BITS_PER_SHORT -#define BITS_PER_INT PR_BITS_PER_INT -#define BITS_PER_INT64 PR_BITS_PER_INT64 -#define BITS_PER_LONG PR_BITS_PER_LONG -#define BITS_PER_FLOAT PR_BITS_PER_FLOAT -#define BITS_PER_DOUBLE PR_BITS_PER_DOUBLE -#define BITS_PER_WORD PR_BITS_PER_WORD - -#define BITS_PER_BYTE_LOG2 PR_BITS_PER_BYTE_LOG2 -#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2 -#define BITS_PER_INT_LOG2 PR_BITS_PER_INT_LOG2 -#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2 -#define BITS_PER_LONG_LOG2 PR_BITS_PER_LONG_LOG2 -#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2 -#define BITS_PER_DOUBLE_LOG2 PR_BITS_PER_DOUBLE_LOG2 -#define BITS_PER_WORD_LOG2 PR_BITS_PER_WORD_LOG2 - -#define ALIGN_OF_SHORT PR_ALIGN_OF_SHORT -#define ALIGN_OF_INT PR_ALIGN_OF_INT -#define ALIGN_OF_LONG PR_ALIGN_OF_LONG -#define ALIGN_OF_INT64 PR_ALIGN_OF_INT64 -#define ALIGN_OF_FLOAT PR_ALIGN_OF_FLOAT -#define ALIGN_OF_DOUBLE PR_ALIGN_OF_DOUBLE -#define ALIGN_OF_POINTER PR_ALIGN_OF_POINTER -#define ALIGN_OF_WORD PR_ALIGN_OF_WORD - -#define BYTES_PER_WORD_LOG2 PR_BYTES_PER_WORD_LOG2 -#define BYTES_PER_DWORD_LOG2 PR_BYTES_PER_DWORD_LOG2 -#define WORDS_PER_DWORD_LOG2 PR_WORDS_PER_DWORD_LOG2 - -#endif /* NO_NSPR_10_SUPPORT */ - -#endif /* nspr_cpucfg___ */ diff --git a/win32/include/spidermonkey/nspr/nspr.h b/win32/include/spidermonkey/nspr/nspr.h deleted file mode 100755 index 0cbc71c1..00000000 --- a/win32/include/spidermonkey/nspr/nspr.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef nspr_h___ -#define nspr_h___ - -#include "pratom.h" -#include "prbit.h" -#include "prclist.h" -#include "prcmon.h" -#include "prcvar.h" -#include "prdtoa.h" -#include "prenv.h" -#include "prerror.h" -#include "prinet.h" -#include "prinit.h" -#include "prinrval.h" -#include "prio.h" -#include "pripcsem.h" -#include "prlink.h" -#include "prlock.h" -#include "prlog.h" -#include "prlong.h" -#include "prmem.h" -#include "prmon.h" -#include "prmwait.h" -#include "prnetdb.h" -#include "prprf.h" -#include "prproces.h" -#include "prrng.h" -#include "prrwlock.h" -#include "prshm.h" -#include "prshma.h" -#include "prsystem.h" -#include "prthread.h" -#include "prtime.h" -#include "prtpool.h" -#include "prtrace.h" -#include "prtypes.h" - -#endif /* nspr_h___ */ diff --git a/win32/include/spidermonkey/nspr/plarena.h b/win32/include/spidermonkey/nspr/plarena.h deleted file mode 100755 index 5336a0e4..00000000 --- a/win32/include/spidermonkey/nspr/plarena.h +++ /dev/null @@ -1,327 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef plarena_h___ -#define plarena_h___ -/* - * Lifetime-based fast allocation, inspired by much prior art, including - * "Fast Allocation and Deallocation of Memory Based on Object Lifetimes" - * David R. Hanson, Software -- Practice and Experience, Vol. 20(1). - * - * Also supports LIFO allocation (PL_ARENA_MARK/PL_ARENA_RELEASE). - */ -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -typedef struct PLArena PLArena; - -struct PLArena { - PLArena *next; /* next arena for this lifetime */ - PRUword base; /* aligned base address, follows this header */ - PRUword limit; /* one beyond last byte in arena */ - PRUword avail; /* points to next available byte */ -}; - -#ifdef PL_ARENAMETER -typedef struct PLArenaStats PLArenaStats; - -struct PLArenaStats { - PLArenaStats *next; /* next in arenaStats list */ - char *name; /* name for debugging */ - PRUint32 narenas; /* number of arenas in pool */ - PRUint32 nallocs; /* number of PL_ARENA_ALLOCATE() calls */ - PRUint32 nreclaims; /* number of reclaims from freeArenas */ - PRUint32 nmallocs; /* number of malloc() calls */ - PRUint32 ndeallocs; /* number of lifetime deallocations */ - PRUint32 ngrows; /* number of PL_ARENA_GROW() calls */ - PRUint32 ninplace; /* number of in-place growths */ - PRUint32 nreleases; /* number of PL_ARENA_RELEASE() calls */ - PRUint32 nfastrels; /* number of "fast path" releases */ - PRUint32 nbytes; /* total bytes allocated */ - PRUint32 maxalloc; /* maximum allocation size in bytes */ - PRFloat64 variance; /* size variance accumulator */ -}; -#endif - -typedef struct PLArenaPool PLArenaPool; - -struct PLArenaPool { - PLArena first; /* first arena in pool list */ - PLArena *current; /* arena from which to allocate space */ - PRUint32 arenasize; /* net exact size of a new arena */ - PRUword mask; /* alignment mask (power-of-2 - 1) */ -#ifdef PL_ARENAMETER - PLArenaStats stats; -#endif -}; - -/* - * WARNING: The PL_MAKE_MEM_ macros are for internal use by NSPR. Do NOT use - * them in your code. - * - * NOTE: Valgrind support to be added. - * - * The PL_MAKE_MEM_ macros are modeled after the MOZ_MAKE_MEM_ macros in - * Mozilla's mfbt/MemoryChecking.h. Only AddressSanitizer is supported now. - * - * Provides a common interface to the ASan (AddressSanitizer) and Valgrind - * functions used to mark memory in certain ways. In detail, the following - * three macros are provided: - * - * PL_MAKE_MEM_NOACCESS - Mark memory as unsafe to access (e.g. freed) - * PL_MAKE_MEM_UNDEFINED - Mark memory as accessible, with content undefined - * PL_MAKE_MEM_DEFINED - Mark memory as accessible, with content defined - * - * With Valgrind in use, these directly map to the three respective Valgrind - * macros. With ASan in use, the NOACCESS macro maps to poisoning the memory, - * while the UNDEFINED/DEFINED macros unpoison memory. - * - * With no memory checker available, all macros expand to the empty statement. - */ - -/* WARNING: PL_SANITIZE_ADDRESS is for internal use by this header. Do NOT - * define or test this macro in your code. - */ -#if defined(__has_feature) -#if __has_feature(address_sanitizer) -#define PL_SANITIZE_ADDRESS 1 -#endif -#elif defined(__SANITIZE_ADDRESS__) -#define PL_SANITIZE_ADDRESS 1 -#endif - -#if defined(PL_SANITIZE_ADDRESS) - -/* These definitions are usually provided through the - * sanitizer/asan_interface.h header installed by ASan. - * See https://github.com/google/sanitizers/wiki/AddressSanitizerManualPoisoning - */ - -PR_IMPORT(void) __asan_poison_memory_region(void const volatile *addr, size_t size); -PR_IMPORT(void) __asan_unpoison_memory_region(void const volatile *addr, size_t size); - -#define PL_MAKE_MEM_NOACCESS(addr, size) \ - __asan_poison_memory_region((addr), (size)) - -#define PL_MAKE_MEM_UNDEFINED(addr, size) \ - __asan_unpoison_memory_region((addr), (size)) - -#define PL_MAKE_MEM_DEFINED(addr, size) \ - __asan_unpoison_memory_region((addr), (size)) - -#else - -#define PL_MAKE_MEM_NOACCESS(addr, size) -#define PL_MAKE_MEM_UNDEFINED(addr, size) -#define PL_MAKE_MEM_DEFINED(addr, size) - -#endif - -/* - * If the including .c file uses only one power-of-2 alignment, it may define - * PL_ARENA_CONST_ALIGN_MASK to the alignment mask and save a few instructions - * per ALLOCATE and GROW. - */ -#ifdef PL_ARENA_CONST_ALIGN_MASK -#define PL_ARENA_ALIGN(pool, n) (((PRUword)(n) + PL_ARENA_CONST_ALIGN_MASK) \ - & ~PL_ARENA_CONST_ALIGN_MASK) - -#define PL_INIT_ARENA_POOL(pool, name, size) \ - PL_InitArenaPool(pool, name, size, PL_ARENA_CONST_ALIGN_MASK + 1) -#else -#define PL_ARENA_ALIGN(pool, n) (((PRUword)(n) + (pool)->mask) & ~(pool)->mask) -#endif - -#define PL_ARENA_ALLOCATE(p, pool, nb) \ - PR_BEGIN_MACRO \ - PLArena *_a = (pool)->current; \ - PRUint32 _nb = PL_ARENA_ALIGN(pool, (PRUint32)nb); \ - PRUword _p = _a->avail; \ - if (_nb < (PRUint32)nb) { \ - _p = 0; \ - } else if (_nb > (_a->limit - _a->avail)) { \ - _p = (PRUword)PL_ArenaAllocate(pool, _nb); \ - } else { \ - _a->avail += _nb; \ - } \ - p = (void *)_p; \ - if (p) { \ - PL_MAKE_MEM_UNDEFINED(p, (PRUint32)nb); \ - PL_ArenaCountAllocation(pool, (PRUint32)nb); \ - } \ - PR_END_MACRO - -#define PL_ARENA_GROW(p, pool, size, incr) \ - PR_BEGIN_MACRO \ - PLArena *_a = (pool)->current; \ - PRUint32 _incr = PL_ARENA_ALIGN(pool, (PRUint32)incr); \ - if (_incr < (PRUint32)incr) { \ - p = NULL; \ - } else if (_a->avail == (PRUword)(p) + PL_ARENA_ALIGN(pool, size) && \ - _incr <= (_a->limit - _a->avail)) { \ - PL_MAKE_MEM_UNDEFINED((unsigned char *)(p) + size, (PRUint32)incr); \ - _a->avail += _incr; \ - PL_ArenaCountInplaceGrowth(pool, size, (PRUint32)incr); \ - } else { \ - p = PL_ArenaGrow(pool, p, size, (PRUint32)incr); \ - } \ - if (p) {\ - PL_ArenaCountGrowth(pool, size, (PRUint32)incr); \ - } \ - PR_END_MACRO - -#define PL_ARENA_MARK(pool) ((void *) (pool)->current->avail) -#define PR_UPTRDIFF(p,q) ((PRUword)(p) - (PRUword)(q)) - -#define PL_CLEAR_UNUSED_PATTERN(a, pattern) \ - PR_BEGIN_MACRO \ - PR_ASSERT((a)->avail <= (a)->limit); \ - PL_MAKE_MEM_UNDEFINED((void*)(a)->avail, (a)->limit - (a)->avail); \ - memset((void*)(a)->avail, (pattern), (a)->limit - (a)->avail); \ - PR_END_MACRO -#ifdef DEBUG -#define PL_FREE_PATTERN 0xDA -#define PL_CLEAR_UNUSED(a) PL_CLEAR_UNUSED_PATTERN((a), PL_FREE_PATTERN) -#define PL_CLEAR_ARENA(a) \ - PR_BEGIN_MACRO \ - PL_MAKE_MEM_UNDEFINED((void*)(a), (a)->limit - (PRUword)(a)); \ - memset((void*)(a), PL_FREE_PATTERN, (a)->limit - (PRUword)(a)); \ - PR_END_MACRO -#else -#define PL_CLEAR_UNUSED(a) -#define PL_CLEAR_ARENA(a) -#endif - -#define PL_ARENA_RELEASE(pool, mark) \ - PR_BEGIN_MACRO \ - char *_m = (char *)(mark); \ - PLArena *_a = (pool)->current; \ - if (PR_UPTRDIFF(_m, _a->base) <= PR_UPTRDIFF(_a->avail, _a->base)) { \ - _a->avail = (PRUword)PL_ARENA_ALIGN(pool, _m); \ - PL_CLEAR_UNUSED(_a); \ - PL_MAKE_MEM_NOACCESS((void*)_a->avail, _a->limit - _a->avail); \ - PL_ArenaCountRetract(pool, _m); \ - } else { \ - PL_ArenaRelease(pool, _m); \ - } \ - PL_ArenaCountRelease(pool, _m); \ - PR_END_MACRO - -#ifdef PL_ARENAMETER -#define PL_COUNT_ARENA(pool,op) ((pool)->stats.narenas op) -#else -#define PL_COUNT_ARENA(pool,op) -#endif - -#define PL_ARENA_DESTROY(pool, a, pnext) \ - PR_BEGIN_MACRO \ - PL_COUNT_ARENA(pool,--); \ - if ((pool)->current == (a)) (pool)->current = &(pool)->first; \ - *(pnext) = (a)->next; \ - PL_CLEAR_ARENA(a); \ - free(a); \ - (a) = 0; \ - PR_END_MACRO - -/* -** Initialize an arena pool with the given name for debugging and metering, -** with a minimum gross size per arena of size bytes. The net size per arena -** is smaller than the gross size by a header of four pointers plus any -** necessary padding for alignment. -** -** Note: choose a gross size that's a power of two to avoid the heap allocator -** rounding the size up. -**/ -PR_EXTERN(void) PL_InitArenaPool( - PLArenaPool *pool, const char *name, PRUint32 size, PRUint32 align); - -/* -** Finish using arenas, freeing all memory associated with them. -** NOTE: this function is now a no-op. If you want to free a single -** PLArenaPoolUse use PL_FreeArenaPool() or PL_FinishArenaPool(). -**/ -PR_EXTERN(void) PL_ArenaFinish(void); - -/* -** Free the arenas in pool. The user may continue to allocate from pool -** after calling this function. There is no need to call PL_InitArenaPool() -** again unless PL_FinishArenaPool(pool) has been called. -**/ -PR_EXTERN(void) PL_FreeArenaPool(PLArenaPool *pool); - -/* -** Free the arenas in pool and finish using it altogether. -**/ -PR_EXTERN(void) PL_FinishArenaPool(PLArenaPool *pool); - -/* -** Compact all of the arenas in a pool so that no space is wasted. -** NOT IMPLEMENTED. Do not use. -**/ -PR_EXTERN(void) PL_CompactArenaPool(PLArenaPool *pool); - -/* -** Friend functions used by the PL_ARENA_*() macros. -** -** WARNING: do not call these functions directly. Always use the -** PL_ARENA_*() macros. -**/ -PR_EXTERN(void *) PL_ArenaAllocate(PLArenaPool *pool, PRUint32 nb); - -PR_EXTERN(void *) PL_ArenaGrow( - PLArenaPool *pool, void *p, PRUint32 size, PRUint32 incr); - -PR_EXTERN(void) PL_ArenaRelease(PLArenaPool *pool, char *mark); - -/* -** memset contents of all arenas in pool to pattern -*/ -PR_EXTERN(void) PL_ClearArenaPool(PLArenaPool *pool, PRInt32 pattern); - -/* -** A function like malloc_size() or malloc_usable_size() that measures the -** size of a heap block. -*/ -typedef size_t (*PLMallocSizeFn)(const void *ptr); - -/* -** Measure all memory used by a PLArenaPool, excluding the PLArenaPool -** structure. -*/ -PR_EXTERN(size_t) PL_SizeOfArenaPoolExcludingPool( - const PLArenaPool *pool, PLMallocSizeFn mallocSizeOf); - -#ifdef PL_ARENAMETER - -#include - -PR_EXTERN(void) PL_ArenaCountAllocation(PLArenaPool *pool, PRUint32 nb); - -PR_EXTERN(void) PL_ArenaCountInplaceGrowth( - PLArenaPool *pool, PRUint32 size, PRUint32 incr); - -PR_EXTERN(void) PL_ArenaCountGrowth( - PLArenaPool *pool, PRUint32 size, PRUint32 incr); - -PR_EXTERN(void) PL_ArenaCountRelease(PLArenaPool *pool, char *mark); - -PR_EXTERN(void) PL_ArenaCountRetract(PLArenaPool *pool, char *mark); - -PR_EXTERN(void) PL_DumpArenaStats(FILE *fp); - -#else /* !PL_ARENAMETER */ - -#define PL_ArenaCountAllocation(ap, nb) /* nothing */ -#define PL_ArenaCountInplaceGrowth(ap, size, incr) /* nothing */ -#define PL_ArenaCountGrowth(ap, size, incr) /* nothing */ -#define PL_ArenaCountRelease(ap, mark) /* nothing */ -#define PL_ArenaCountRetract(ap, mark) /* nothing */ - -#endif /* !PL_ARENAMETER */ - -PR_END_EXTERN_C - -#endif /* plarena_h___ */ diff --git a/win32/include/spidermonkey/nspr/plarenas.h b/win32/include/spidermonkey/nspr/plarenas.h deleted file mode 100755 index 4a0f5a8d..00000000 --- a/win32/include/spidermonkey/nspr/plarenas.h +++ /dev/null @@ -1,12 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** PLArena-related declarations used to be split between plarenas.h and -** plarena.h. That split wasn't useful, so now all the declarations are in -** plarena.h. However, this file still exists so that any old code that -** includes it will still work. -**/ -#include "plarena.h" diff --git a/win32/include/spidermonkey/nspr/plbase64.h b/win32/include/spidermonkey/nspr/plbase64.h deleted file mode 100755 index 7d17ea78..00000000 --- a/win32/include/spidermonkey/nspr/plbase64.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef _plbase64_h -#define _plbase64_h - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/* - * PL_Base64Encode - * - * This routine encodes the data pointed to by the "src" parameter using the - * base64 algorithm, and returns a pointer to the result. If the "srclen" - * parameter is not zero, it specifies the length of the source data. If it - * is zero, the source data is assumed to be null-terminated, and PL_strlen - * is used to determine the source length. If the "dest" parameter is not - * null, it is assumed to point to a buffer of sufficient size (which may be - * calculated: ((srclen + 2)/3)*4) into which the encoded data is placed - * (without any termination). If the "dest" parameter is null, a buffer is - * allocated from the heap to hold the encoded data, and the result *will* - * be terminated with an extra null character. It is the caller's - * responsibility to free the result when it is allocated. A null is returned - * if the allocation fails. - * - * NOTE: when calculating ((srclen + 2)/3)*4), first ensure that - * srclen <= (PR_UINT32_MAX/4) * 3 - * to avoid PRUint32 overflow. - */ - -PR_EXTERN(char *) -PL_Base64Encode -( - const char *src, - PRUint32 srclen, - char *dest -); - -/* - * PL_Base64Decode - * - * This routine decodes the data pointed to by the "src" parameter using - * the base64 algorithm, and returns a pointer to the result. The source - * may either include or exclude any trailing '=' characters. If the - * "srclen" parameter is not zero, it specifies the length of the source - * data. If it is zero, PL_strlen will be used to determine the source - * length. If the "dest" parameter is not null, it is assumed to point to - * a buffer of sufficient size (which may be calculated: (srclen * 3)/4 - * when srclen includes the '=' characters) into which the decoded data - * is placed (without any termination). If the "dest" parameter is null, - * a buffer is allocated from the heap to hold the decoded data, and the - * result *will* be terminated with an extra null character. It is the - * caller's responsibility to free the result when it is allocated. A null - * is retuned if the allocation fails, or if the source is not well-coded. - * - * NOTE: when calculating (srclen * 3)/4, first ensure that - * srclen <= PR_UINT32_MAX/3 - * to avoid PRUint32 overflow. Alternatively, calculate - * (srclen/4) * 3 + ((srclen%4) * 3)/4 - * which is equivalent but doesn't overflow for any value of srclen. - */ - -PR_EXTERN(char *) -PL_Base64Decode -( - const char *src, - PRUint32 srclen, - char *dest -); - -PR_END_EXTERN_C - -#endif /* _plbase64_h */ diff --git a/win32/include/spidermonkey/nspr/plerror.h b/win32/include/spidermonkey/nspr/plerror.h deleted file mode 100755 index cd85dd3f..00000000 --- a/win32/include/spidermonkey/nspr/plerror.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: plerror.h -** Description: Simple routine to print translate the calling thread's -** error numbers and print them. -*/ - -#if defined(PLERROR_H) -#else -#define PLERROR_H - -#include "prio.h" -#include "prtypes.h" - -PR_BEGIN_EXTERN_C -/* -** Print the messages to "syserr" prepending 'msg' if not NULL. -*/ -PR_EXTERN(void) PL_PrintError(const char *msg); - -/* -** Print the messages to specified output file prepending 'msg' if not NULL. -*/ -PR_EXTERN(void) PL_FPrintError(PRFileDesc *output, const char *msg); - -PR_END_EXTERN_C - -#endif /* defined(PLERROR_H) */ - -/* plerror.h */ diff --git a/win32/include/spidermonkey/nspr/plgetopt.h b/win32/include/spidermonkey/nspr/plgetopt.h deleted file mode 100755 index 19cafa60..00000000 --- a/win32/include/spidermonkey/nspr/plgetopt.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: plgetopt.h -** Description: utilities to parse argc/argv -*/ - -#if defined(PLGETOPT_H_) -#else -#define PLGETOPT_H_ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -typedef struct PLOptionInternal PLOptionInternal; - -typedef enum -{ - PL_OPT_OK, /* all's well with the option */ - PL_OPT_EOL, /* end of options list */ - PL_OPT_BAD /* invalid option (and value) */ -} PLOptStatus; - -typedef struct PLLongOpt -{ - const char * longOptName; /* long option name string */ - PRIntn longOption; /* value put in PLOptState for this option. */ - PRBool valueRequired; /* If option name not followed by '=', */ - /* value is the next argument from argv. */ -} PLLongOpt; - -typedef struct PLOptState -{ - char option; /* the name of the option */ - const char *value; /* the value of that option | NULL */ - - PLOptionInternal *internal; /* private processing state */ - - PRIntn longOption; /* value from PLLongOpt put here */ - PRIntn longOptIndex; /* index into caller's array of PLLongOpts */ -} PLOptState; - -/* - * PL_CreateOptState - * - * The argument "options" points to a string of single-character option - * names. Option names that may have an option argument value must be - * followed immediately by a ':' character. - */ -PR_EXTERN(PLOptState*) PL_CreateOptState( - PRIntn argc, char **argv, const char *options); - -/* - * PL_CreateLongOptState - * - * Alternative to PL_CreateOptState. - * Allows caller to specify BOTH a string of single-character option names, - * AND an array of structures describing "long" (keyword) option names. - * The array is terminated by a structure in which longOptName is NULL. - * Long option values (arguments) may always be given as "--name=value". - * If PLLongOpt.valueRequired is not PR_FALSE, and the option name was not - * followed by '=' then the next argument from argv is taken as the value. - */ -PR_EXTERN(PLOptState*) PL_CreateLongOptState( - PRIntn argc, char **argv, const char *options, - const PLLongOpt *longOpts); -/* - * PL_DestroyOptState - * - * Call this to destroy the PLOptState returned from PL_CreateOptState or - * PL_CreateLongOptState. - */ -PR_EXTERN(void) PL_DestroyOptState(PLOptState *opt); - -/* - * PL_GetNextOpt - * - * When this function returns PL_OPT_OK, - * - opt->option will hold the single-character option name that was parsed, - * or zero. - * When opt->option is zero, the token parsed was either a "long" (keyword) - * option or a positional parameter. - * For a positional parameter, - * - opt->longOptIndex will contain -1, and - * - opt->value will point to the positional parameter string. - * For a long option name, - * - opt->longOptIndex will contain the non-negative index of the - * PLLongOpt structure in the caller's array of PLLongOpt structures - * corresponding to the long option name, and - * For a single-character or long option, - * - opt->longOption will contain the value of the single-character option - * name, or the value of the longOption from the PLLongOpt structure - * for that long option. See notes below. - * - opt->value will point to the argument option string, or will - * be NULL if option does not require argument. If option requires - * argument but it is not provided, PL_OPT_BAD is returned. - * When opt->option is non-zero, - * - opt->longOptIndex will be -1 - * When this function returns PL_OPT_EOL, or PL_OPT_BAD, the contents of - * opt are undefined. - * - * Notes: It is possible to ignore opt->option, and always look at - * opt->longOption instead. opt->longOption will contain the same value - * as opt->option for single-character option names, and will contain the - * value of longOption from the PLLongOpt structure for long option names. - * This means that it is possible to equivalence long option names to - * single character names by giving the longOption in the PLLongOpt struct - * the same value as the single-character option name. - * For long options that are NOT intended to be equivalent to any single- - * character option, the longOption value should be chosen to not match - * any possible single character name. It might be advisable to choose - * longOption values greater than 0xff for such long options. - */ -PR_EXTERN(PLOptStatus) PL_GetNextOpt(PLOptState *opt); - -PR_END_EXTERN_C - -#endif /* defined(PLGETOPT_H_) */ - -/* plgetopt.h */ - diff --git a/win32/include/spidermonkey/nspr/plhash.h b/win32/include/spidermonkey/nspr/plhash.h deleted file mode 100755 index 2c221aed..00000000 --- a/win32/include/spidermonkey/nspr/plhash.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef plhash_h___ -#define plhash_h___ -/* - * API to portable hash table code. - */ -#include -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -typedef struct PLHashEntry PLHashEntry; -typedef struct PLHashTable PLHashTable; -typedef PRUint32 PLHashNumber; -#define PL_HASH_BITS 32 /* Number of bits in PLHashNumber */ -typedef PLHashNumber (PR_CALLBACK *PLHashFunction)(const void *key); -typedef PRIntn (PR_CALLBACK *PLHashComparator)(const void *v1, const void *v2); - -typedef PRIntn (PR_CALLBACK *PLHashEnumerator)(PLHashEntry *he, PRIntn i, void *arg); - -/* Flag bits in PLHashEnumerator's return value */ -#define HT_ENUMERATE_NEXT 0 /* continue enumerating entries */ -#define HT_ENUMERATE_STOP 1 /* stop enumerating entries */ -#define HT_ENUMERATE_REMOVE 2 /* remove and free the current entry */ -#define HT_ENUMERATE_UNHASH 4 /* just unhash the current entry */ - -typedef struct PLHashAllocOps { - void * (PR_CALLBACK *allocTable)(void *pool, PRSize size); - void (PR_CALLBACK *freeTable)(void *pool, void *item); - PLHashEntry * (PR_CALLBACK *allocEntry)(void *pool, const void *key); - void (PR_CALLBACK *freeEntry)(void *pool, PLHashEntry *he, PRUintn flag); -} PLHashAllocOps; - -#define HT_FREE_VALUE 0 /* just free the entry's value */ -#define HT_FREE_ENTRY 1 /* free value and entire entry */ - -struct PLHashEntry { - PLHashEntry *next; /* hash chain linkage */ - PLHashNumber keyHash; /* key hash function result */ - const void *key; /* ptr to opaque key */ - void *value; /* ptr to opaque value */ -}; - -struct PLHashTable { - PLHashEntry **buckets; /* vector of hash buckets */ - PRUint32 nentries; /* number of entries in table */ - PRUint32 shift; /* multiplicative hash shift */ - PLHashFunction keyHash; /* key hash function */ - PLHashComparator keyCompare; /* key comparison function */ - PLHashComparator valueCompare; /* value comparison function */ - const PLHashAllocOps *allocOps; /* allocation operations */ - void *allocPriv; /* allocation private data */ -#ifdef HASHMETER - PRUint32 nlookups; /* total number of lookups */ - PRUint32 nsteps; /* number of hash chains traversed */ - PRUint32 ngrows; /* number of table expansions */ - PRUint32 nshrinks; /* number of table contractions */ -#endif -}; - -/* - * Create a new hash table. - * If allocOps is null, use default allocator ops built on top of malloc(). - */ -PR_EXTERN(PLHashTable *) -PL_NewHashTable(PRUint32 numBuckets, PLHashFunction keyHash, - PLHashComparator keyCompare, PLHashComparator valueCompare, - const PLHashAllocOps *allocOps, void *allocPriv); - -PR_EXTERN(void) -PL_HashTableDestroy(PLHashTable *ht); - -/* Higher level access methods */ -PR_EXTERN(PLHashEntry *) -PL_HashTableAdd(PLHashTable *ht, const void *key, void *value); - -PR_EXTERN(PRBool) -PL_HashTableRemove(PLHashTable *ht, const void *key); - -PR_EXTERN(void *) -PL_HashTableLookup(PLHashTable *ht, const void *key); - -PR_EXTERN(void *) -PL_HashTableLookupConst(PLHashTable *ht, const void *key); - -PR_EXTERN(PRIntn) -PL_HashTableEnumerateEntries(PLHashTable *ht, PLHashEnumerator f, void *arg); - -/* General-purpose C string hash function. */ -PR_EXTERN(PLHashNumber) -PL_HashString(const void *key); - -/* Compare strings using strcmp(), return true if equal. */ -PR_EXTERN(PRIntn) -PL_CompareStrings(const void *v1, const void *v2); - -/* Stub function just returns v1 == v2 */ -PR_EXTERN(PRIntn) -PL_CompareValues(const void *v1, const void *v2); - -/* Low level access methods */ -PR_EXTERN(PLHashEntry **) -PL_HashTableRawLookup(PLHashTable *ht, PLHashNumber keyHash, const void *key); - -PR_EXTERN(PLHashEntry **) -PL_HashTableRawLookupConst(PLHashTable *ht, PLHashNumber keyHash, - const void *key); - -PR_EXTERN(PLHashEntry *) -PL_HashTableRawAdd(PLHashTable *ht, PLHashEntry **hep, PLHashNumber keyHash, - const void *key, void *value); - -PR_EXTERN(void) -PL_HashTableRawRemove(PLHashTable *ht, PLHashEntry **hep, PLHashEntry *he); - -/* This can be trivially implemented using PL_HashTableEnumerateEntries. */ -PR_EXTERN(PRIntn) -PL_HashTableDump(PLHashTable *ht, PLHashEnumerator dump, FILE *fp); - -PR_END_EXTERN_C - -#endif /* plhash_h___ */ diff --git a/win32/include/spidermonkey/nspr/plstr.h b/win32/include/spidermonkey/nspr/plstr.h deleted file mode 100755 index 57814c70..00000000 --- a/win32/include/spidermonkey/nspr/plstr.h +++ /dev/null @@ -1,437 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef _plstr_h -#define _plstr_h - -/* - * plstr.h - * - * This header file exports the API to the NSPR portable library or string- - * handling functions. - * - * This API was not designed as an "optimal" or "ideal" string library; it - * was based on the good ol' unix string.3 functions, and was written to - * - * 1) replace the libc functions, for cross-platform consistency, - * 2) complete the API on platforms lacking common functions (e.g., - * strcase*), and - * 3) to implement some obvious "closure" functions that I've seen - * people hacking around in our code. - * - * Point number three largely means that most functions have an "strn" - * limited-length version, and all comparison routines have a non-case- - * sensitive version available. - */ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C -/* - * PL_strlen - * - * Returns the length of the provided string, not including the trailing '\0'. - */ - -PR_EXTERN(PRUint32) -PL_strlen(const char *str); - -/* - * PL_strnlen - * - * Returns the length of the provided string, not including the trailing '\0', - * up to the indicated maximum. The string will not be examined beyond the - * maximum; if no terminating '\0' is found, the maximum will be returned. - */ - -PR_EXTERN(PRUint32) -PL_strnlen(const char *str, PRUint32 max); - -/* - * PL_strcpy - * - * Copies the source string, up to and including the trailing '\0', into the - * destination buffer. It does not (can not) verify that the destination - * buffer is large enough. It returns the "dest" argument. - */ - -PR_EXTERN(char *) -PL_strcpy(char *dest, const char *src); - -/* - * PL_strncpy - * - * Copies the source string into the destination buffer, up to and including - * the trailing '\0' or up to and including the max'th character, whichever - * comes first. It does not (can not) verify that the destination buffer is - * large enough. If the source string is longer than the maximum length, - * the result will *not* be null-terminated (JLRU). - */ - -PR_EXTERN(char *) -PL_strncpy(char *dest, const char *src, PRUint32 max); - -/* - * PL_strncpyz - * - * Copies the source string into the destination buffer, up to and including - * the trailing '\0' or up but not including the max'th character, whichever - * comes first. It does not (can not) verify that the destination buffer is - * large enough. The destination string is always terminated with a '\0', - * unlike the traditional libc implementation. It returns the "dest" argument. - * - * NOTE: If you call this with a source "abcdefg" and a max of 5, the - * destination will end up with "abcd\0" (i.e., its strlen length will be 4)! - * - * This means you can do this: - * - * char buffer[ SOME_SIZE ]; - * PL_strncpyz(buffer, src, sizeof(buffer)); - * - * and the result will be properly terminated. - */ - -PR_EXTERN(char *) -PL_strncpyz(char *dest, const char *src, PRUint32 max); - -/* - * PL_strdup - * - * Returns a pointer to a malloc'd extent of memory containing a duplicate - * of the argument string. The size of the allocated extent is one greater - * than the length of the argument string, because of the terminator. A - * null argument, like a zero-length argument, will result in a pointer to - * a one-byte extent containing the null value. This routine returns null - * upon malloc failure. - */ - -PR_EXTERN(char *) -PL_strdup(const char *s); - -/* - * PL_strfree - * - * Free memory allocated by PL_strdup - */ - -PR_EXTERN(void) -PL_strfree(char *s); - -/* - * PL_strndup - * - * Returns a pointer to a malloc'd extent of memory containing a duplicate - * of the argument string, up to the maximum specified. If the argument - * string has a length greater than the value of the specified maximum, the - * return value will be a pointer to an extent of memory of length one - * greater than the maximum specified. A null string, a zero-length string, - * or a zero maximum will all result in a pointer to a one-byte extent - * containing the null value. This routine returns null upon malloc failure. - */ - -PR_EXTERN(char *) -PL_strndup(const char *s, PRUint32 max); - -/* - * PL_strcat - * - * Appends a copy of the string pointed to by the second argument to the - * end of the string pointed to by the first. The destination buffer is - * not (can not be) checked for sufficient size. A null destination - * argument returns null; otherwise, the first argument is returned. - */ - -PR_EXTERN(char *) -PL_strcat(char *dst, const char *src); - -/* - * PL_strncat - * - * Appends a copy of the string pointed to by the second argument, up to - * the maximum size specified, to the end of the string pointed to by the - * first. The destination buffer is not (can not be) checked for sufficient - * size. A null destination argument returns null; otherwise, the first - * argument is returned. If the maximum size limits the copy, then the - * result will *not* be null-terminated (JLRU). A null destination - * returns null; otherwise, the destination argument is returned. - */ - -PR_EXTERN(char *) -PL_strncat(char *dst, const char *src, PRUint32 max); - -/* - * PL_strcatn - * - * Appends a copy of the string pointed to by the third argument, to the - * end of the string pointed to by the first. The second argument specifies - * the maximum size of the destination buffer, including the null termination. - * If the existing string in dst is longer than the max, no action is taken. - * The resulting string will be null-terminated. A null destination returns - * null; otherwise, the destination argument is returned. - */ - -PR_EXTERN(char *) -PL_strcatn(char *dst, PRUint32 max, const char *src); - -/* - * PL_strcmp - * - * Returns an integer, the sign of which -- positive, zero, or negative -- - * reflects the lexical sorting order of the two strings indicated. The - * result is positive if the first string comes after the second. The - * NSPR implementation is not i18n. - */ - -PR_EXTERN(PRIntn) -PL_strcmp(const char *a, const char *b); - -/* - * PL_strncmp - * - * Returns an integer, the sign of which -- positive, zero, or negative -- - * reflects the lexical sorting order of the two strings indicated, up to - * the maximum specified. The result is positive if the first string comes - * after the second. The NSPR implementation is not i18n. If the maximum - * is zero, only the existance or non-existance (pointer is null) of the - * strings is compared. - */ - -PR_EXTERN(PRIntn) -PL_strncmp(const char *a, const char *b, PRUint32 max); - -/* - * PL_strcasecmp - * - * Returns an integer, the sign of which -- positive, zero or negative -- - * reflects the case-insensitive lexical sorting order of the two strings - * indicated. The result is positive if the first string comes after the - * second. The NSPR implementation is not i18n. - */ - -PR_EXTERN(PRIntn) -PL_strcasecmp(const char *a, const char *b); - -/* - * PL_strncasecmp - * - * Returns an integer, the sign of which -- positive, zero or negative -- - * reflects the case-insensitive lexical sorting order of the first n characters - * of the two strings indicated. The result is positive if the first string comes - * after the second. The NSPR implementation is not i18n. - */ - -PR_EXTERN(PRIntn) -PL_strncasecmp(const char *a, const char *b, PRUint32 max); - -/* - * PL_strchr - * - * Returns a pointer to the first instance of the specified character in the - * provided string. It returns null if the character is not found, or if the - * provided string is null. The character may be the null character. - */ - -PR_EXTERN(char *) -PL_strchr(const char *s, char c); - -/* - * PL_strrchr - * - * Returns a pointer to the last instance of the specified character in the - * provided string. It returns null if the character is not found, or if the - * provided string is null. The character may be the null character. - */ - -PR_EXTERN(char *) -PL_strrchr(const char *s, char c); - -/* - * PL_strnchr - * - * Returns a pointer to the first instance of the specified character within the - * first n characters of the provided string. It returns null if the character - * is not found, or if the provided string is null. The character may be the - * null character. - */ - -PR_EXTERN(char *) -PL_strnchr(const char *s, char c, PRUint32 n); - -/* - * PL_strnrchr - * - * Returns a pointer to the last instance of the specified character within the - * first n characters of the provided string. It returns null if the character is - * not found, or if the provided string is null. The character may be the null - * character. - */ - -PR_EXTERN(char *) -PL_strnrchr(const char *s, char c, PRUint32 n); - -/* - * NOTE: Looking for strcasechr, strcaserchr, strncasechr, or strncaserchr? - * Use strpbrk, strprbrk, strnpbrk or strnprbrk. - */ - -/* - * PL_strpbrk - * - * Returns a pointer to the first instance in the first string of any character - * (not including the terminating null character) of the second string. It returns - * null if either string is null. - */ - -PR_EXTERN(char *) -PL_strpbrk(const char *s, const char *list); - -/* - * PL_strprbrk - * - * Returns a pointer to the last instance in the first string of any character - * (not including the terminating null character) of the second string. It returns - * null if either string is null. - */ - -PR_EXTERN(char *) -PL_strprbrk(const char *s, const char *list); - -/* - * PL_strnpbrk - * - * Returns a pointer to the first instance (within the first n characters) of any - * character (not including the terminating null character) of the second string. - * It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strnpbrk(const char *s, const char *list, PRUint32 n); - -/* - * PL_strnprbrk - * - * Returns a pointer to the last instance (within the first n characters) of any - * character (not including the terminating null character) of the second string. - * It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strnprbrk(const char *s, const char *list, PRUint32 n); - -/* - * PL_strstr - * - * Returns a pointer to the first instance of the little string within the - * big one. It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strstr(const char *big, const char *little); - -/* - * PL_strrstr - * - * Returns a pointer to the last instance of the little string within the big one. - * It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strrstr(const char *big, const char *little); - -/* - * PL_strnstr - * - * Returns a pointer to the first instance of the little string within the first - * n characters of the big one. It returns null if either string is null. It - * returns null if the length of the little string is greater than n. - */ - -PR_EXTERN(char *) -PL_strnstr(const char *big, const char *little, PRUint32 n); - -/* - * PL_strnrstr - * - * Returns a pointer to the last instance of the little string within the first - * n characters of the big one. It returns null if either string is null. It - * returns null if the length of the little string is greater than n. - */ - -PR_EXTERN(char *) -PL_strnrstr(const char *big, const char *little, PRUint32 max); - -/* - * PL_strcasestr - * - * Returns a pointer to the first instance of the little string within the big one, - * ignoring case. It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strcasestr(const char *big, const char *little); - -/* - * PL_strcaserstr - * - * Returns a pointer to the last instance of the little string within the big one, - * ignoring case. It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strcaserstr(const char *big, const char *little); - -/* - * PL_strncasestr - * - * Returns a pointer to the first instance of the little string within the first - * n characters of the big one, ignoring case. It returns null if either string is - * null. It returns null if the length of the little string is greater than n. - */ - -PR_EXTERN(char *) -PL_strncasestr(const char *big, const char *little, PRUint32 max); - -/* - * PL_strncaserstr - * - * Returns a pointer to the last instance of the little string within the first - * n characters of the big one, ignoring case. It returns null if either string is - * null. It returns null if the length of the little string is greater than n. - */ - -PR_EXTERN(char *) -PL_strncaserstr(const char *big, const char *little, PRUint32 max); - -/* - * PL_strtok_r - * - * Splits the string s1 into tokens, separated by one or more characters - * from the separator string s2. The argument lasts points to a - * user-supplied char * pointer in which PL_strtok_r stores information - * for it to continue scanning the same string. - * - * In the first call to PL_strtok_r, s1 points to a string and the value - * of *lasts is ignored. PL_strtok_r returns a pointer to the first - * token, writes '\0' into the character following the first token, and - * updates *lasts. - * - * In subsequent calls, s1 is null and lasts must stay unchanged from the - * previous call. The separator string s2 may be different from call to - * call. PL_strtok_r returns a pointer to the next token in s1. When no - * token remains in s1, PL_strtok_r returns null. - */ - -PR_EXTERN(char *) -PL_strtok_r(char *s1, const char *s2, char **lasts); - -/* - * Things not (yet?) included: strspn/strcspn, strsep. - * memchr, memcmp, memcpy, memccpy, index, rindex, bcmp, bcopy, bzero. - * Any and all i18n/l10n stuff. - */ - -PR_END_EXTERN_C - -#endif /* _plstr_h */ diff --git a/win32/include/spidermonkey/nspr/pratom.h b/win32/include/spidermonkey/nspr/pratom.h deleted file mode 100755 index dff9d6c0..00000000 --- a/win32/include/spidermonkey/nspr/pratom.h +++ /dev/null @@ -1,198 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* GLOBAL FUNCTIONS: -** DESCRIPTION: -** PR Atomic operations -*/ - -#ifndef pratom_h___ -#define pratom_h___ - -#include "prtypes.h" -#include "prlock.h" - -PR_BEGIN_EXTERN_C - -/* -** FUNCTION: PR_AtomicIncrement -** DESCRIPTION: -** Atomically increment a 32 bit value. -** INPUTS: -** val: a pointer to the value to increment -** RETURN: -** the returned value is the result of the increment -*/ -NSPR_API(PRInt32) PR_AtomicIncrement(PRInt32 *val); - -/* -** FUNCTION: PR_AtomicDecrement -** DESCRIPTION: -** Atomically decrement a 32 bit value. -** INPUTS: -** val: a pointer to the value to decrement -** RETURN: -** the returned value is the result of the decrement -*/ -NSPR_API(PRInt32) PR_AtomicDecrement(PRInt32 *val); - -/* -** FUNCTION: PR_AtomicSet -** DESCRIPTION: -** Atomically set a 32 bit value. -** INPUTS: -** val: A pointer to a 32 bit value to be set -** newval: The newvalue to assign to val -** RETURN: -** Returns the prior value -*/ -NSPR_API(PRInt32) PR_AtomicSet(PRInt32 *val, PRInt32 newval); - -/* -** FUNCTION: PR_AtomicAdd -** DESCRIPTION: -** Atomically add a 32 bit value. -** INPUTS: -** ptr: a pointer to the value to increment -** val: value to be added -** RETURN: -** the returned value is the result of the addition -*/ -NSPR_API(PRInt32) PR_AtomicAdd(PRInt32 *ptr, PRInt32 val); - -/* -** MACRO: PR_ATOMIC_INCREMENT -** MACRO: PR_ATOMIC_DECREMENT -** MACRO: PR_ATOMIC_SET -** MACRO: PR_ATOMIC_ADD -** DESCRIPTION: -** Macro versions of the atomic operations. They may be implemented -** as compiler intrinsics. -** -** IMPORTANT NOTE TO NSPR MAINTAINERS: -** Implement these macros with compiler intrinsics only on platforms -** where the PR_AtomicXXX functions are truly atomic (i.e., where the -** configuration macro _PR_HAVE_ATOMIC_OPS is defined). Otherwise, -** the macros and functions won't be compatible and can't be used -** interchangeably. -*/ -#if defined(_WIN32) && !defined(_WIN32_WCE) && \ - (!defined(_MSC_VER) || (_MSC_VER >= 1310)) - -#include - -#ifdef _MSC_VER -#pragma intrinsic(_InterlockedIncrement) -#pragma intrinsic(_InterlockedDecrement) -#pragma intrinsic(_InterlockedExchange) -#pragma intrinsic(_InterlockedExchangeAdd) -#endif - -#define PR_ATOMIC_INCREMENT(val) _InterlockedIncrement((long volatile *)(val)) -#define PR_ATOMIC_DECREMENT(val) _InterlockedDecrement((long volatile *)(val)) -#define PR_ATOMIC_SET(val, newval) \ - _InterlockedExchange((long volatile *)(val), (long)(newval)) -#define PR_ATOMIC_ADD(ptr, val) \ - (_InterlockedExchangeAdd((long volatile *)(ptr), (long)(val)) + (val)) - -#elif ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) && \ - ((defined(__APPLE__) && \ - (defined(__ppc__) || defined(__i386__) || defined(__x86_64__))) || \ - (defined(__linux__) && \ - ((defined(__i386__) && \ - defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) || \ - defined(__ia64__) || defined(__x86_64__) || \ - defined(__powerpc__) || \ - (defined(__arm__) && \ - defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) || \ - defined(__aarch64__) || defined(__alpha) || \ - (defined(__mips__) && \ - defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4))))) - -/* - * Because the GCC manual warns that some processors may support - * reduced functionality of __sync_lock_test_and_set, we test for the - * processors that we believe support a full atomic exchange operation. - */ - -#define PR_ATOMIC_INCREMENT(val) __sync_add_and_fetch(val, 1) -#define PR_ATOMIC_DECREMENT(val) __sync_sub_and_fetch(val, 1) -#define PR_ATOMIC_SET(val, newval) __sync_lock_test_and_set(val, newval) -#define PR_ATOMIC_ADD(ptr, val) __sync_add_and_fetch(ptr, val) - -#else - -#define PR_ATOMIC_INCREMENT(val) PR_AtomicIncrement(val) -#define PR_ATOMIC_DECREMENT(val) PR_AtomicDecrement(val) -#define PR_ATOMIC_SET(val, newval) PR_AtomicSet(val, newval) -#define PR_ATOMIC_ADD(ptr, val) PR_AtomicAdd(ptr, val) - -#endif - -/* -** LIFO linked-list (stack) -*/ -typedef struct PRStackElemStr PRStackElem; - -struct PRStackElemStr { - PRStackElem *prstk_elem_next; /* next pointer MUST be at offset 0; - assembly language code relies on this */ -}; - -typedef struct PRStackStr PRStack; - -/* -** FUNCTION: PR_CreateStack -** DESCRIPTION: -** Create a stack, a LIFO linked list -** INPUTS: -** stack_name: a pointer to string containing the name of the stack -** RETURN: -** A pointer to the created stack, if successful, else NULL. -*/ -NSPR_API(PRStack *) PR_CreateStack(const char *stack_name); - -/* -** FUNCTION: PR_StackPush -** DESCRIPTION: -** Push an element on the top of the stack -** INPUTS: -** stack: pointer to the stack -** stack_elem: pointer to the stack element -** RETURN: -** None -*/ -NSPR_API(void) PR_StackPush(PRStack *stack, PRStackElem *stack_elem); - -/* -** FUNCTION: PR_StackPop -** DESCRIPTION: -** Remove the element on the top of the stack -** INPUTS: -** stack: pointer to the stack -** RETURN: -** A pointer to the stack element removed from the top of the stack, -** if non-empty, -** else NULL -*/ -NSPR_API(PRStackElem *) PR_StackPop(PRStack *stack); - -/* -** FUNCTION: PR_DestroyStack -** DESCRIPTION: -** Destroy the stack -** INPUTS: -** stack: pointer to the stack -** RETURN: -** PR_SUCCESS - if successfully deleted -** PR_FAILURE - if the stack is not empty -** PR_GetError will return -** PR_INVALID_STATE_ERROR - stack is not empty -*/ -NSPR_API(PRStatus) PR_DestroyStack(PRStack *stack); - -PR_END_EXTERN_C - -#endif /* pratom_h___ */ diff --git a/win32/include/spidermonkey/nspr/prbit.h b/win32/include/spidermonkey/nspr/prbit.h deleted file mode 100755 index 0434fc68..00000000 --- a/win32/include/spidermonkey/nspr/prbit.h +++ /dev/null @@ -1,150 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prbit_h___ -#define prbit_h___ - -#include "prtypes.h" -PR_BEGIN_EXTERN_C - -/* -** Replace compare/jump/add/shift sequence with compiler built-in/intrinsic -** functions. -*/ -#if defined(_WIN32) && (_MSC_VER >= 1300) && \ - (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_ARM)) -# include -# pragma intrinsic(_BitScanForward,_BitScanReverse) - __forceinline static int __prBitScanForward32(unsigned int val) - { - unsigned long idx; - _BitScanForward(&idx, (unsigned long)val); - return( (int)idx ); - } - __forceinline static int __prBitScanReverse32(unsigned int val) - { - unsigned long idx; - _BitScanReverse(&idx, (unsigned long)val); - return( (int)(31-idx) ); - } -# define pr_bitscan_ctz32(val) __prBitScanForward32(val) -# define pr_bitscan_clz32(val) __prBitScanReverse32(val) -# define PR_HAVE_BUILTIN_BITSCAN32 -#elif ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) && \ - (defined(__i386__) || defined(__x86_64__) || defined(__arm__)) -# define pr_bitscan_ctz32(val) __builtin_ctz(val) -# define pr_bitscan_clz32(val) __builtin_clz(val) -# define PR_HAVE_BUILTIN_BITSCAN32 -#endif /* MSVC || GCC */ - -/* -** A prbitmap_t is a long integer that can be used for bitmaps -*/ -typedef unsigned long prbitmap_t; - -#define PR_TEST_BIT(_map,_bit) \ - ((_map)[(_bit)>>PR_BITS_PER_LONG_LOG2] & (1L << ((_bit) & (PR_BITS_PER_LONG-1)))) -#define PR_SET_BIT(_map,_bit) \ - ((_map)[(_bit)>>PR_BITS_PER_LONG_LOG2] |= (1L << ((_bit) & (PR_BITS_PER_LONG-1)))) -#define PR_CLEAR_BIT(_map,_bit) \ - ((_map)[(_bit)>>PR_BITS_PER_LONG_LOG2] &= ~(1L << ((_bit) & (PR_BITS_PER_LONG-1)))) - -/* -** Compute the log of the least power of 2 greater than or equal to n -*/ -NSPR_API(PRIntn) PR_CeilingLog2(PRUint32 i); - -/* -** Compute the log of the greatest power of 2 less than or equal to n -*/ -NSPR_API(PRIntn) PR_FloorLog2(PRUint32 i); - -/* -** Macro version of PR_CeilingLog2: Compute the log of the least power of -** 2 greater than or equal to _n. The result is returned in _log2. -*/ -#ifdef PR_HAVE_BUILTIN_BITSCAN32 -#define PR_CEILING_LOG2(_log2,_n) \ - PR_BEGIN_MACRO \ - PRUint32 j_ = (PRUint32)(_n); \ - (_log2) = (j_ <= 1 ? 0 : 32 - pr_bitscan_clz32(j_ - 1)); \ - PR_END_MACRO -#else -#define PR_CEILING_LOG2(_log2,_n) \ - PR_BEGIN_MACRO \ - PRUint32 j_ = (PRUint32)(_n); \ - (_log2) = 0; \ - if ((j_) & ((j_)-1)) \ - (_log2) += 1; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - PR_END_MACRO -#endif /* PR_HAVE_BUILTIN_BITSCAN32 */ - -/* -** Macro version of PR_FloorLog2: Compute the log of the greatest power of -** 2 less than or equal to _n. The result is returned in _log2. -** -** This is equivalent to finding the highest set bit in the word. -*/ -#ifdef PR_HAVE_BUILTIN_BITSCAN32 -#define PR_FLOOR_LOG2(_log2,_n) \ - PR_BEGIN_MACRO \ - PRUint32 j_ = (PRUint32)(_n); \ - (_log2) = 31 - pr_bitscan_clz32((j_) | 1); \ - PR_END_MACRO -#else -#define PR_FLOOR_LOG2(_log2,_n) \ - PR_BEGIN_MACRO \ - PRUint32 j_ = (PRUint32)(_n); \ - (_log2) = 0; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - PR_END_MACRO -#endif /* PR_HAVE_BUILTIN_BITSCAN32 */ - -/* -** Macros for rotate left and right. The argument 'a' must be an unsigned -** 32-bit integer type such as PRUint32. -** -** There is no rotate operation in the C Language, so the construct -** (a << 4) | (a >> 28) is frequently used instead. Most compilers convert -** this to a rotate instruction, but MSVC doesn't without a little help. -** To get MSVC to generate a rotate instruction, we have to use the _rotl -** or _rotr intrinsic and use a pragma to make it inline. -** -** Note: MSVC in VS2005 will do an inline rotate instruction on the above -** construct. -*/ - -#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_AMD64) || \ - defined(_M_X64) || defined(_M_ARM)) -#include -#pragma intrinsic(_rotl, _rotr) -#define PR_ROTATE_LEFT32(a, bits) _rotl(a, bits) -#define PR_ROTATE_RIGHT32(a, bits) _rotr(a, bits) -#else -#define PR_ROTATE_LEFT32(a, bits) (((a) << (bits)) | ((a) >> (32 - (bits)))) -#define PR_ROTATE_RIGHT32(a, bits) (((a) >> (bits)) | ((a) << (32 - (bits)))) -#endif - -PR_END_EXTERN_C -#endif /* prbit_h___ */ diff --git a/win32/include/spidermonkey/nspr/prclist.h b/win32/include/spidermonkey/nspr/prclist.h deleted file mode 100755 index 23247228..00000000 --- a/win32/include/spidermonkey/nspr/prclist.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prclist_h___ -#define prclist_h___ - -#include "prtypes.h" - -typedef struct PRCListStr PRCList; - -/* -** Circular linked list -*/ -struct PRCListStr { - PRCList *next; - PRCList *prev; -}; - -/* -** Insert element "_e" into the list, before "_l". -*/ -#define PR_INSERT_BEFORE(_e,_l) \ - PR_BEGIN_MACRO \ - (_e)->next = (_l); \ - (_e)->prev = (_l)->prev; \ - (_l)->prev->next = (_e); \ - (_l)->prev = (_e); \ - PR_END_MACRO - -/* -** Insert element "_e" into the list, after "_l". -*/ -#define PR_INSERT_AFTER(_e,_l) \ - PR_BEGIN_MACRO \ - (_e)->next = (_l)->next; \ - (_e)->prev = (_l); \ - (_l)->next->prev = (_e); \ - (_l)->next = (_e); \ - PR_END_MACRO - -/* -** Return the element following element "_e" -*/ -#define PR_NEXT_LINK(_e) \ - ((_e)->next) -/* -** Return the element preceding element "_e" -*/ -#define PR_PREV_LINK(_e) \ - ((_e)->prev) - -/* -** Append an element "_e" to the end of the list "_l" -*/ -#define PR_APPEND_LINK(_e,_l) PR_INSERT_BEFORE(_e,_l) - -/* -** Insert an element "_e" at the head of the list "_l" -*/ -#define PR_INSERT_LINK(_e,_l) PR_INSERT_AFTER(_e,_l) - -/* Return the head/tail of the list */ -#define PR_LIST_HEAD(_l) (_l)->next -#define PR_LIST_TAIL(_l) (_l)->prev - -/* -** Remove the element "_e" from it's circular list. -*/ -#define PR_REMOVE_LINK(_e) \ - PR_BEGIN_MACRO \ - (_e)->prev->next = (_e)->next; \ - (_e)->next->prev = (_e)->prev; \ - PR_END_MACRO - -/* -** Remove the element "_e" from it's circular list. Also initializes the -** linkage. -*/ -#define PR_REMOVE_AND_INIT_LINK(_e) \ - PR_BEGIN_MACRO \ - (_e)->prev->next = (_e)->next; \ - (_e)->next->prev = (_e)->prev; \ - (_e)->next = (_e); \ - (_e)->prev = (_e); \ - PR_END_MACRO - -/* -** Return non-zero if the given circular list "_l" is empty, zero if the -** circular list is not empty -*/ -#define PR_CLIST_IS_EMPTY(_l) \ - ((_l)->next == (_l)) - -/* -** Initialize a circular list -*/ -#define PR_INIT_CLIST(_l) \ - PR_BEGIN_MACRO \ - (_l)->next = (_l); \ - (_l)->prev = (_l); \ - PR_END_MACRO - -#define PR_INIT_STATIC_CLIST(_l) \ - {(_l), (_l)} - -#endif /* prclist_h___ */ diff --git a/win32/include/spidermonkey/nspr/prcmon.h b/win32/include/spidermonkey/nspr/prcmon.h deleted file mode 100755 index 69171138..00000000 --- a/win32/include/spidermonkey/nspr/prcmon.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prcmon_h___ -#define prcmon_h___ - -/* -** Interface to cached monitors. Cached monitors use an address to find a -** given PR monitor. In this way a monitor can be associated with another -** object without preallocating a monitor for all objects. -** -** A hash table is used to quickly map addresses to individual monitors -** and the system automatically grows the hash table as needed. -** -** Cache monitors are about 5 times slower to use than uncached monitors. -*/ -#include "prmon.h" -#include "prinrval.h" - -PR_BEGIN_EXTERN_C - -/** -** Like PR_EnterMonitor except use the "address" to find a monitor in the -** monitor cache. If successful, returns the PRMonitor now associated -** with "address". Note that you must PR_CExitMonitor the address to -** release the monitor cache entry (otherwise the monitor cache will fill -** up). This call will return NULL if the monitor cache needs to be -** expanded and the system is out of memory. -*/ -NSPR_API(PRMonitor*) PR_CEnterMonitor(void *address); - -/* -** Like PR_ExitMonitor except use the "address" to find a monitor in the -** monitor cache. -*/ -NSPR_API(PRStatus) PR_CExitMonitor(void *address); - -/* -** Like PR_Wait except use the "address" to find a monitor in the -** monitor cache. -*/ -NSPR_API(PRStatus) PR_CWait(void *address, PRIntervalTime timeout); - -/* -** Like PR_Notify except use the "address" to find a monitor in the -** monitor cache. -*/ -NSPR_API(PRStatus) PR_CNotify(void *address); - -/* -** Like PR_NotifyAll except use the "address" to find a monitor in the -** monitor cache. -*/ -NSPR_API(PRStatus) PR_CNotifyAll(void *address); - -/* -** Set a callback to be invoked each time a monitor is recycled from the cache -** freelist, with the monitor's cache-key passed in address. -*/ -NSPR_API(void) PR_CSetOnMonitorRecycle(void (PR_CALLBACK *callback)(void *address)); - -PR_END_EXTERN_C - -#endif /* prcmon_h___ */ diff --git a/win32/include/spidermonkey/nspr/prcountr.h b/win32/include/spidermonkey/nspr/prcountr.h deleted file mode 100755 index 53b6176b..00000000 --- a/win32/include/spidermonkey/nspr/prcountr.h +++ /dev/null @@ -1,525 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prcountr_h___ -#define prcountr_h___ - -/*---------------------------------------------------------------------------- -** prcountr.h -- NSPR Instrumentation counters -** -** The NSPR Counter Feature provides a means to "count -** something." Counters can be dynamically defined, incremented, -** decremented, set, and deleted under application program -** control. -** -** The Counter Feature is intended to be used as instrumentation, -** not as operational data. If you need a counter for operational -** data, use native integral types. -** -** Counters are 32bit unsigned intergers. On overflow, a counter -** will wrap. No exception is recognized or reported. -** -** A counter can be dynamically created using a two level naming -** convention. A "handle" is returned when the counter is -** created. The counter can subsequently be addressed by its -** handle. An API is provided to get an existing counter's handle -** given the names with which it was originally created. -** Similarly, a counter's name can be retrieved given its handle. -** -** The counter naming convention is a two-level hierarchy. The -** QName is the higher level of the hierarchy; RName is the -** lower level. RNames can be thought of as existing within a -** QName. The same RName can exist within multiple QNames. QNames -** are unique. The NSPR Counter is not a near-zero overhead -** feature. Application designers should be aware of -** serialization issues when using the Counter API. Creating a -** counter locks a large asset, potentially causing a stall. This -** suggest that applications should create counters at component -** initialization, for example, and not create and destroy them -** willy-nilly. ... You have been warned. -** -** Incrementing and Adding to counters uses atomic operations. -** The performance of these operations will vary from platform -** to platform. On platforms where atomic operations are not -** supported the overhead may be substantial. -** -** When traversing the counter database with FindNext functions, -** the instantaneous values of any given counter is that at the -** moment of extraction. The state of the entire counter database -** may not be viewed as atomic. -** -** The counter interface may be disabled (No-Op'd) at compile -** time. When DEBUG is defined at compile time, the Counter -** Feature is compiled into NSPR and applications invoking it. -** When DEBUG is not defined, the counter macros compile to -** nothing. To force the Counter Feature to be compiled into an -** optimized build, define FORCE_NSPR_COUNTERS at compile time -** for both NSPR and the application intending to use it. -** -** Application designers should use the macro form of the Counter -** Feature methods to minimize performance impact in optimized -** builds. The macros normally compile to nothing on optimized -** builds. -** -** Application designers should be aware of the effects of -** debug and optimized build differences when using result of the -** Counter Feature macros in expressions. -** -** The Counter Feature is thread-safe and SMP safe. -** -** /lth. 09-Jun-1998. -*/ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/* -** Opaque counter handle type. -** ... don't even think of looking in here. -** -*/ -typedef void * PRCounterHandle; - -#define PRCOUNTER_NAME_MAX 31 -#define PRCOUNTER_DESC_MAX 255 - - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_DEFINE_COUNTER() -- Define a PRCounterHandle -** -** DESCRIPTION: PR_DEFINE_COUNTER() is used to define a counter -** handle. -** -*/ -#define PR_DEFINE_COUNTER(name) PRCounterHandle name - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_INIT_COUNTER_HANDLE() -- Set the value of a PRCounterHandle -** -** DESCRIPTION: -** PR_INIT_COUNTER_HANDLE() sets the value of a PRCounterHandle -** to value. -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_INIT_COUNTER_HANDLE(handle,value)\ - (handle) = (PRCounterHandle)(value) -#else -#define PR_INIT_COUNTER_HANDLE(handle,value) -#endif - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_CreateCounter() -- Create a counter -** -** DESCRIPTION: PR_CreateCounter() creates a counter object and -** initializes it to zero. -** -** The macro form takes as its first argument the name of the -** PRCounterHandle to receive the handle returned from -** PR_CreateCounter(). -** -** INPUTS: -** qName: The QName for the counter object. The maximum length -** of qName is defined by PRCOUNTER_NAME_MAX -** -** rName: The RName for the counter object. The maximum length -** of qName is defined by PRCOUNTER_NAME_MAX -** -** descrioption: The description of the counter object. The -** maximum length of description is defined by -** PRCOUNTER_DESC_MAX. -** -** OUTPUTS: -** -** RETURNS: -** PRCounterHandle. -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_CREATE_COUNTER(handle,qName,rName,description)\ - (handle) = PR_CreateCounter((qName),(rName),(description)) -#else -#define PR_CREATE_COUNTER(handle,qName,rName,description) -#endif - -NSPR_API(PRCounterHandle) - PR_CreateCounter( - const char *qName, - const char *rName, - const char *description -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_DestroyCounter() -- Destroy a counter object. -** -** DESCRIPTION: PR_DestroyCounter() removes a counter and -** unregisters its handle from the counter database. -** -** INPUTS: -** handle: the PRCounterHandle of the counter to be destroyed. -** -** OUTPUTS: -** The counter is destroyed. -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_DESTROY_COUNTER(handle) PR_DestroyCounter((handle)) -#else -#define PR_DESTROY_COUNTER(handle) -#endif - -NSPR_API(void) - PR_DestroyCounter( - PRCounterHandle handle -); - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_GetCounterHandleFromName() -- Retreive a -** counter's handle give its name. -** -** DESCRIPTION: PR_GetCounterHandleFromName() retreives a -** counter's handle from the counter database, given the name -** the counter was originally created with. -** -** INPUTS: -** qName: Counter's original QName. -** rName: Counter's original RName. -** -** OUTPUTS: -** -** RETURNS: -** PRCounterHandle or PRCounterError. -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_GET_COUNTER_HANDLE_FROM_NAME(handle,qName,rName)\ - (handle) = PR_GetCounterHandleFromName((qName),(rName)) -#else -#define PR_GET_COUNTER_HANDLE_FROM_NAME(handle,qName,rName) -#endif - -NSPR_API(PRCounterHandle) - PR_GetCounterHandleFromName( - const char *qName, - const char *rName -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_GetCounterNameFromHandle() -- Retreive a -** counter's name, given its handle. -** -** DESCRIPTION: PR_GetCounterNameFromHandle() retreives a -** counter's name given its handle. -** -** INPUTS: -** qName: Where to store a pointer to qName. -** rName: Where to store a pointer to rName. -** description: Where to store a pointer to description. -** -** OUTPUTS: Pointers to the Counter Feature's copies of the names -** used when the counters were created. -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_GET_COUNTER_NAME_FROM_HANDLE(handle,qName,rName,description)\ - PR_GetCounterNameFromHandle((handle),(qName),(rName),(description)) -#else -#define PR_GET_COUNTER_NAME_FROM_HANDLE(handle,qName,rName,description ) -#endif - -NSPR_API(void) - PR_GetCounterNameFromHandle( - PRCounterHandle handle, - const char **qName, - const char **rName, - const char **description -); - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_IncrementCounter() -- Add one to the referenced -** counter. -** -** DESCRIPTION: Add one to the referenced counter. -** -** INPUTS: -** handle: The PRCounterHandle of the counter to be incremented -** -** OUTPUTS: The counter is incrementd. -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_INCREMENT_COUNTER(handle) PR_IncrementCounter(handle) -#else -#define PR_INCREMENT_COUNTER(handle) -#endif - -NSPR_API(void) - PR_IncrementCounter( - PRCounterHandle handle -); - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_DecrementCounter() -- Subtract one from the -** referenced counter -** -** DESCRIPTION: Subtract one from the referenced counter. -** -** INPUTS: -** handle: The PRCounterHandle of the coutner to be -** decremented. -** -** OUTPUTS: the counter is decremented. -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_DECREMENT_COUNTER(handle) PR_DecrementCounter(handle) -#else -#define PR_DECREMENT_COUNTER(handle) -#endif - -NSPR_API(void) - PR_DecrementCounter( - PRCounterHandle handle -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_AddToCounter() -- Add a value to a counter. -** -** DESCRIPTION: Add value to the counter referenced by handle. -** -** INPUTS: -** handle: the PRCounterHandle of the counter to be added to. -** -** value: the value to be added to the counter. -** -** OUTPUTS: new value for counter. -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_ADD_TO_COUNTER(handle,value)\ - PR_AddToCounter((handle),(value)) -#else -#define PR_ADD_TO_COUNTER(handle,value) -#endif - -NSPR_API(void) - PR_AddToCounter( - PRCounterHandle handle, - PRUint32 value -); - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_SubtractFromCounter() -- A value is subtracted -** from a counter. -** -** DESCRIPTION: -** Subtract a value from a counter. -** -** INPUTS: -** handle: the PRCounterHandle of the counter to be subtracted -** from. -** -** value: the value to be subtracted from the counter. -** -** OUTPUTS: new value for counter -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_SUBTRACT_FROM_COUNTER(handle,value)\ - PR_SubtractFromCounter((handle),(value)) -#else -#define PR_SUBTRACT_FROM_COUNTER(handle,value) -#endif - -NSPR_API(void) - PR_SubtractFromCounter( - PRCounterHandle handle, - PRUint32 value -); - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_GetCounter() -- Retreive the value of a counter -** -** DESCRIPTION: -** Retreive the value of a counter. -** -** INPUTS: -** handle: the PR_CounterHandle of the counter to be retreived -** -** OUTPUTS: -** -** RETURNS: The value of the referenced counter -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_GET_COUNTER(counter,handle)\ - (counter) = PR_GetCounter((handle)) -#else -#define PR_GET_COUNTER(counter,handle) 0 -#endif - -NSPR_API(PRUint32) - PR_GetCounter( - PRCounterHandle handle -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_SetCounter() -- Replace the content of counter -** with value. -** -** DESCRIPTION: The contents of the referenced counter are -** replaced by value. -** -** INPUTS: -** handle: the PRCounterHandle of the counter whose contents -** are to be replaced. -** -** value: the new value of the counter. -** -** OUTPUTS: -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_SET_COUNTER(handle,value) PR_SetCounter((handle),(value)) -#else -#define PR_SET_COUNTER(handle,value) -#endif - -NSPR_API(void) - PR_SetCounter( - PRCounterHandle handle, - PRUint32 value -); - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_FindNextCounterQname() -- Retreive the next QName counter -** handle iterator -** -** DESCRIPTION: -** PR_FindNextCounterQname() retreives the first or next Qname -** the counter data base, depending on the value of handle. When -** handle is NULL, the function attempts to retreive the first -** QName handle in the database. When handle is a handle previosly -** retreived QName handle, then the function attempts to retreive -** the next QName handle. -** -** INPUTS: -** handle: PRCounterHandle or NULL. -** -** OUTPUTS: returned -** -** RETURNS: PRCounterHandle or NULL when no more QName counter -** handles are present. -** -** RESTRICTIONS: -** A concurrent PR_CreateCounter() or PR_DestroyCounter() may -** cause unpredictable results. -** -** A PRCounterHandle returned from this function may only be used -** in another PR_FindNextCounterQname() function call; other -** operations may cause unpredictable results. -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_FIND_NEXT_COUNTER_QNAME(next,handle)\ - (next) = PR_FindNextCounterQname((handle)) -#else -#define PR_FIND_NEXT_COUNTER_QNAME(next,handle) NULL -#endif - -NSPR_API(PRCounterHandle) - PR_FindNextCounterQname( - PRCounterHandle handle -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_FindNextCounterRname() -- Retreive the next RName counter -** handle iterator -** -** DESCRIPTION: -** PR_FindNextCounterRname() retreives the first or next RNname -** handle from the counter data base, depending on the -** value of handle. When handle is NULL, the function attempts to -** retreive the first RName handle in the database. When handle is -** a handle previosly retreived RName handle, then the function -** attempts to retreive the next RName handle. -** -** INPUTS: -** handle: PRCounterHandle or NULL. -** qhandle: PRCounterHandle of a previously aquired via -** PR_FIND_NEXT_QNAME_HANDLE() -** -** OUTPUTS: returned -** -** RETURNS: PRCounterHandle or NULL when no more RName counter -** handles are present. -** -** RESTRICTIONS: -** A concurrent PR_CreateCounter() or PR_DestroyCounter() may -** cause unpredictable results. -** -** A PRCounterHandle returned from this function may only be used -** in another PR_FindNextCounterRname() function call; other -** operations may cause unpredictable results. -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_COUNTERS) -#define PR_FIND_NEXT_COUNTER_RNAME(next,rhandle,qhandle)\ - (next) = PR_FindNextCounterRname((rhandle),(qhandle)) -#else -#define PR_FIND_NEXT_COUNTER_RNAME(next,rhandle,qhandle) -#endif - -NSPR_API(PRCounterHandle) - PR_FindNextCounterRname( - PRCounterHandle rhandle, - PRCounterHandle qhandle -); - -PR_END_EXTERN_C - -#endif /* prcountr_h___ */ diff --git a/win32/include/spidermonkey/nspr/prcpucfg.h b/win32/include/spidermonkey/nspr/prcpucfg.h deleted file mode 100755 index 5f796273..00000000 --- a/win32/include/spidermonkey/nspr/prcpucfg.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef NSPR_PRCPUCFG_H_ -#define NSPR_PRCPUCFG_H_ - -/* - * Need to support conditionals that are defined in both the top-level build - * system as well as NSS' build system for now. - */ -#if defined(XP_DARWIN) || defined(DARWIN) -#include "md/_darwin.cfg" -#elif defined(XP_WIN) || defined(_WINDOWS) -#include "md/_win95.cfg" -#elif defined(__FreeBSD__) -#include "md/_freebsd.cfg" -#elif defined(__NetBSD__) -#include "md/_netbsd.cfg" -#elif defined(__OpenBSD__) -#include "md/_openbsd.cfg" -#elif defined(__linux__) -#include "md/_linux.cfg" -#else -#error "Unsupported platform!" -#endif - -#endif /* NSPR_PRCPUCFG_H_ */ diff --git a/win32/include/spidermonkey/nspr/prcvar.h b/win32/include/spidermonkey/nspr/prcvar.h deleted file mode 100755 index 3e30ce1f..00000000 --- a/win32/include/spidermonkey/nspr/prcvar.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prcvar_h___ -#define prcvar_h___ - -#include "prlock.h" -#include "prinrval.h" - -PR_BEGIN_EXTERN_C - -typedef struct PRCondVar PRCondVar; - -/* -** Create a new condition variable. -** -** "lock" is the lock used to protect the condition variable. -** -** Condition variables are synchronization objects that threads can use -** to wait for some condition to occur. -** -** This may fail if memory is tight or if some operating system resource -** is low. In such cases, a NULL will be returned. -*/ -NSPR_API(PRCondVar*) PR_NewCondVar(PRLock *lock); - -/* -** Destroy a condition variable. There must be no thread -** waiting on the condvar. The caller is responsible for guaranteeing -** that the condvar is no longer in use. -** -*/ -NSPR_API(void) PR_DestroyCondVar(PRCondVar *cvar); - -/* -** The thread that waits on a condition is blocked in a "waiting on -** condition" state until another thread notifies the condition or a -** caller specified amount of time expires. The lock associated with -** the condition variable will be released, which must have be held -** prior to the call to wait. -** -** Logically a notified thread is moved from the "waiting on condition" -** state and made "ready." When scheduled, it will attempt to reacquire -** the lock that it held when wait was called. -** -** The timeout has two well known values, PR_INTERVAL_NO_TIMEOUT and -** PR_INTERVAL_NO_WAIT. The former value requires that a condition be -** notified (or the thread interrupted) before it will resume from the -** wait. If the timeout has a value of PR_INTERVAL_NO_WAIT, the effect -** is to release the lock, possibly causing a rescheduling within the -** runtime, then immediately attempting to reacquire the lock and resume. -** -** Any other value for timeout will cause the thread to be rescheduled -** either due to explicit notification or an expired interval. The latter -** must be determined by treating time as one part of the monitored data -** being protected by the lock and tested explicitly for an expired -** interval. -** -** Returns PR_FAILURE if the caller has not locked the lock associated -** with the condition variable or the thread was interrupted (PR_Interrupt()). -** The particular reason can be extracted with PR_GetError(). -*/ -NSPR_API(PRStatus) PR_WaitCondVar(PRCondVar *cvar, PRIntervalTime timeout); - -/* -** Notify ONE thread that is currently waiting on 'cvar'. Which thread is -** dependent on the implementation of the runtime. Common sense would dictate -** that all threads waiting on a single condition have identical semantics, -** therefore which one gets notified is not significant. -** -** The calling thead must hold the lock that protects the condition, as -** well as the invariants that are tightly bound to the condition, when -** notify is called. -** -** Returns PR_FAILURE if the caller has not locked the lock associated -** with the condition variable. -*/ -NSPR_API(PRStatus) PR_NotifyCondVar(PRCondVar *cvar); - -/* -** Notify all of the threads waiting on the condition variable. The order -** that the threads are notified is indeterminant. The lock that protects -** the condition must be held. -** -** Returns PR_FAILURE if the caller has not locked the lock associated -** with the condition variable. -*/ -NSPR_API(PRStatus) PR_NotifyAllCondVar(PRCondVar *cvar); - -PR_END_EXTERN_C - -#endif /* prcvar_h___ */ diff --git a/win32/include/spidermonkey/nspr/prdtoa.h b/win32/include/spidermonkey/nspr/prdtoa.h deleted file mode 100755 index 191b6c75..00000000 --- a/win32/include/spidermonkey/nspr/prdtoa.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prdtoa_h___ -#define prdtoa_h___ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/* -** PR_strtod() returns as a double-precision floating-point number -** the value represented by the character string pointed to by -** s00. The string is scanned up to the first unrecognized -** character. -**a -** If the value of se is not (char **)NULL, a pointer to -** the character terminating the scan is returned in the location pointed -** to by se. If no number can be formed, se is set to s00, and -** zero is returned. -*/ -NSPR_API(PRFloat64) -PR_strtod(const char *s00, char **se); - -/* -** PR_cnvtf() -** conversion routines for floating point -** prcsn - number of digits of precision to generate floating -** point value. -*/ -NSPR_API(void) PR_cnvtf(char *buf, PRIntn bufsz, PRIntn prcsn, PRFloat64 fval); - -/* -** PR_dtoa() converts double to a string. -** -** ARGUMENTS: -** If rve is not null, *rve is set to point to the end of the return value. -** If d is +-Infinity or NaN, then *decpt is set to 9999. -** -** mode: -** 0 ==> shortest string that yields d when read in -** and rounded to nearest. -*/ -NSPR_API(PRStatus) PR_dtoa(PRFloat64 d, PRIntn mode, PRIntn ndigits, - PRIntn *decpt, PRIntn *sign, char **rve, char *buf, PRSize bufsize); - -PR_END_EXTERN_C - -#endif /* prdtoa_h___ */ diff --git a/win32/include/spidermonkey/nspr/prenv.h b/win32/include/spidermonkey/nspr/prenv.h deleted file mode 100755 index 468c7d59..00000000 --- a/win32/include/spidermonkey/nspr/prenv.h +++ /dev/null @@ -1,162 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prenv_h___ -#define prenv_h___ - -#include "prtypes.h" - -/*******************************************************************************/ -/*******************************************************************************/ -/****************** THESE FUNCTIONS MAY NOT BE THREAD SAFE *********************/ -/*******************************************************************************/ -/*******************************************************************************/ - -PR_BEGIN_EXTERN_C - -/* -** PR_GetEnv() -- Retrieve value of environment variable -** -** Description: -** PR_GetEnv() is modeled on Unix getenv(). -** -** -** Inputs: -** var -- The name of the environment variable -** -** Returns: -** The value of the environment variable 'var' or NULL if -** the variable is undefined. -** -** Restrictions: -** You'd think that a POSIX getenv(), putenv() would be -** consistently implemented everywhere. Surprise! It is not. On -** some platforms, a putenv() where the argument is of -** the form "name" causes the named environment variable to -** be un-set; that is: a subsequent getenv() returns NULL. On -** other platforms, the putenv() fails, on others, it is a -** no-op. Similarly, a putenv() where the argument is of the -** form "name=" causes the named environment variable to be -** un-set; a subsequent call to getenv() returns NULL. On -** other platforms, a subsequent call to getenv() returns a -** pointer to a null-string (a byte of zero). -** -** PR_GetEnv(), PR_SetEnv() provide a consistent behavior -** across all supported platforms. There are, however, some -** restrictions and some practices you must use to achieve -** consistent results everywhere. -** -** When manipulating the environment there is no way to un-set -** an environment variable across all platforms. We suggest -** you interpret the return of a pointer to null-string to -** mean the same as a return of NULL from PR_GetEnv(). -** -** A call to PR_SetEnv() where the parameter is of the form -** "name" will return PR_FAILURE; the environment remains -** unchanged. A call to PR_SetEnv() where the parameter is -** of the form "name=" may un-set the envrionment variable on -** some platforms; on others it may set the value of the -** environment variable to the null-string. -** -** For example, to test for NULL return or return of the -** null-string from PR_GetEnv(), use the following code -** fragment: -** -** char *val = PR_GetEnv("foo"); -** if ((NULL == val) || ('\0' == *val)) { -** ... interpret this as un-set ... -** } -** -** The caller must ensure that the string passed -** to PR_SetEnv() is persistent. That is: The string should -** not be on the stack, where it can be overwritten -** on return from the function calling PR_SetEnv(). -** Similarly, the string passed to PR_SetEnv() must not be -** overwritten by other actions of the process. ... Some -** platforms use the string by reference rather than copying -** it into the environment space. ... You have been warned! -** -** Use of platform-native functions that manipulate the -** environment (getenv(), putenv(), -** SetEnvironmentVariable(), etc.) must not be used with -** NSPR's similar functions. The platform-native functions -** may not be thread safe and/or may operate on different -** conceptual environment space than that operated upon by -** NSPR's functions or other environment manipulating -** functions on the same platform. (!) -** -*/ -NSPR_API(char*) PR_GetEnv(const char *var); - -/* -** PR_GetEnvSecure() -- get a security-sensitive environment variable -** -** Description: -** -** PR_GetEnvSecure() is similar to PR_GetEnv(), but it returns NULL if -** the program was run with elevated privilege (e.g., setuid or setgid -** on Unix). This can be used for cases like log file paths which -** could otherwise be used for privilege escalation. Note that some -** platforms may have platform-specific privilege elevation mechanisms -** not recognized by this function; see the implementation for details. -*/ -NSPR_API(char*) PR_GetEnvSecure(const char *var); - -/* -** PR_SetEnv() -- set, unset or change an environment variable -** -** Description: -** PR_SetEnv() is modeled on the Unix putenv() function. -** -** Inputs: -** string -- pointer to a caller supplied -** constant, persistent string of the form name=value. Where -** name is the name of the environment variable to be set or -** changed; value is the value assigned to the variable. -** -** Returns: -** PRStatus. -** -** Restrictions: -** See the Restrictions documented in the description of -** PR_GetEnv() in this header file. -** -** -*/ -NSPR_API(PRStatus) PR_SetEnv(const char *string); - -/* -** PR_DuplicateEnvironment() -- Obtain a copy of the environment. -** -** Description: -** PR_DuplicateEnvironment() copies the environment so that it can be -** modified without changing the current process's environment, and -** then passed to interfaces such as POSIX execve(). In particular, -** this avoids needing to allocate memory or take locks in the child -** after a fork(); neither of these is allowed by POSIX after a -** multithreaded process calls fork(), and PR_SetEnv does both. -** -** Inputs: -** none -** -** Returns: -** A pointer to a null-terminated array of null-terminated strings, -** like the traditional global variable "environ". The array and -** the strings are allocated with PR_Malloc(), and it is the -** caller's responsibility to free them. -** -** In case of memory allocation failure, or if the operating system -** doesn't support reading the entire environment through the global -** variable "environ" or similar, returns NULL instead. -** -** Restrictions: -** Similarly to PR_GetEnv(), this function may not interoperate as -** expected with the operating system's native environment accessors. -*/ -NSPR_API(char **) PR_DuplicateEnvironment(void); - -PR_END_EXTERN_C - -#endif /* prenv_h___ */ diff --git a/win32/include/spidermonkey/nspr/prerr.h b/win32/include/spidermonkey/nspr/prerr.h deleted file mode 100755 index 8512329e..00000000 --- a/win32/include/spidermonkey/nspr/prerr.h +++ /dev/null @@ -1,249 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prerr_h___ -#define prerr_h___ - -/* - * - * prerr.h - * This file is automatically generated; please do not edit it. - */ - -/* Memory allocation attempt failed */ -#define PR_OUT_OF_MEMORY_ERROR (-6000L) - -/* Invalid file descriptor */ -#define PR_BAD_DESCRIPTOR_ERROR (-5999L) - -/* The operation would have blocked */ -#define PR_WOULD_BLOCK_ERROR (-5998L) - -/* Invalid memory address argument */ -#define PR_ACCESS_FAULT_ERROR (-5997L) - -/* Invalid function for file type */ -#define PR_INVALID_METHOD_ERROR (-5996L) - -/* Invalid memory address argument */ -#define PR_ILLEGAL_ACCESS_ERROR (-5995L) - -/* Some unknown error has occurred */ -#define PR_UNKNOWN_ERROR (-5994L) - -/* Operation interrupted by another thread */ -#define PR_PENDING_INTERRUPT_ERROR (-5993L) - -/* function not implemented */ -#define PR_NOT_IMPLEMENTED_ERROR (-5992L) - -/* I/O function error */ -#define PR_IO_ERROR (-5991L) - -/* I/O operation timed out */ -#define PR_IO_TIMEOUT_ERROR (-5990L) - -/* I/O operation on busy file descriptor */ -#define PR_IO_PENDING_ERROR (-5989L) - -/* The directory could not be opened */ -#define PR_DIRECTORY_OPEN_ERROR (-5988L) - -/* Invalid function argument */ -#define PR_INVALID_ARGUMENT_ERROR (-5987L) - -/* Network address not available (in use?) */ -#define PR_ADDRESS_NOT_AVAILABLE_ERROR (-5986L) - -/* Network address type not supported */ -#define PR_ADDRESS_NOT_SUPPORTED_ERROR (-5985L) - -/* Already connected */ -#define PR_IS_CONNECTED_ERROR (-5984L) - -/* Network address is invalid */ -#define PR_BAD_ADDRESS_ERROR (-5983L) - -/* Local Network address is in use */ -#define PR_ADDRESS_IN_USE_ERROR (-5982L) - -/* Connection refused by peer */ -#define PR_CONNECT_REFUSED_ERROR (-5981L) - -/* Network address is presently unreachable */ -#define PR_NETWORK_UNREACHABLE_ERROR (-5980L) - -/* Connection attempt timed out */ -#define PR_CONNECT_TIMEOUT_ERROR (-5979L) - -/* Network file descriptor is not connected */ -#define PR_NOT_CONNECTED_ERROR (-5978L) - -/* Failure to load dynamic library */ -#define PR_LOAD_LIBRARY_ERROR (-5977L) - -/* Failure to unload dynamic library */ -#define PR_UNLOAD_LIBRARY_ERROR (-5976L) - -/* Symbol not found in any of the loaded dynamic libraries */ -#define PR_FIND_SYMBOL_ERROR (-5975L) - -/* Insufficient system resources */ -#define PR_INSUFFICIENT_RESOURCES_ERROR (-5974L) - -/* A directory lookup on a network address has failed */ -#define PR_DIRECTORY_LOOKUP_ERROR (-5973L) - -/* Attempt to access a TPD key that is out of range */ -#define PR_TPD_RANGE_ERROR (-5972L) - -/* Process open FD table is full */ -#define PR_PROC_DESC_TABLE_FULL_ERROR (-5971L) - -/* System open FD table is full */ -#define PR_SYS_DESC_TABLE_FULL_ERROR (-5970L) - -/* Network operation attempted on non-network file descriptor */ -#define PR_NOT_SOCKET_ERROR (-5969L) - -/* TCP-specific function attempted on a non-TCP file descriptor */ -#define PR_NOT_TCP_SOCKET_ERROR (-5968L) - -/* TCP file descriptor is already bound */ -#define PR_SOCKET_ADDRESS_IS_BOUND_ERROR (-5967L) - -/* Access Denied */ -#define PR_NO_ACCESS_RIGHTS_ERROR (-5966L) - -/* The requested operation is not supported by the platform */ -#define PR_OPERATION_NOT_SUPPORTED_ERROR (-5965L) - -/* The host operating system does not support the protocol requested */ -#define PR_PROTOCOL_NOT_SUPPORTED_ERROR (-5964L) - -/* Access to the remote file has been severed */ -#define PR_REMOTE_FILE_ERROR (-5963L) - -/* The value requested is too large to be stored in the data buffer provided */ -#define PR_BUFFER_OVERFLOW_ERROR (-5962L) - -/* TCP connection reset by peer */ -#define PR_CONNECT_RESET_ERROR (-5961L) - -/* Unused */ -#define PR_RANGE_ERROR (-5960L) - -/* The operation would have deadlocked */ -#define PR_DEADLOCK_ERROR (-5959L) - -/* The file is already locked */ -#define PR_FILE_IS_LOCKED_ERROR (-5958L) - -/* Write would result in file larger than the system allows */ -#define PR_FILE_TOO_BIG_ERROR (-5957L) - -/* The device for storing the file is full */ -#define PR_NO_DEVICE_SPACE_ERROR (-5956L) - -/* Unused */ -#define PR_PIPE_ERROR (-5955L) - -/* Unused */ -#define PR_NO_SEEK_DEVICE_ERROR (-5954L) - -/* Cannot perform a normal file operation on a directory */ -#define PR_IS_DIRECTORY_ERROR (-5953L) - -/* Symbolic link loop */ -#define PR_LOOP_ERROR (-5952L) - -/* File name is too long */ -#define PR_NAME_TOO_LONG_ERROR (-5951L) - -/* File not found */ -#define PR_FILE_NOT_FOUND_ERROR (-5950L) - -/* Cannot perform directory operation on a normal file */ -#define PR_NOT_DIRECTORY_ERROR (-5949L) - -/* Cannot write to a read-only file system */ -#define PR_READ_ONLY_FILESYSTEM_ERROR (-5948L) - -/* Cannot delete a directory that is not empty */ -#define PR_DIRECTORY_NOT_EMPTY_ERROR (-5947L) - -/* Cannot delete or rename a file object while the file system is busy */ -#define PR_FILESYSTEM_MOUNTED_ERROR (-5946L) - -/* Cannot rename a file to a file system on another device */ -#define PR_NOT_SAME_DEVICE_ERROR (-5945L) - -/* The directory object in the file system is corrupted */ -#define PR_DIRECTORY_CORRUPTED_ERROR (-5944L) - -/* Cannot create or rename a filename that already exists */ -#define PR_FILE_EXISTS_ERROR (-5943L) - -/* Directory is full. No additional filenames may be added */ -#define PR_MAX_DIRECTORY_ENTRIES_ERROR (-5942L) - -/* The required device was in an invalid state */ -#define PR_INVALID_DEVICE_STATE_ERROR (-5941L) - -/* The device is locked */ -#define PR_DEVICE_IS_LOCKED_ERROR (-5940L) - -/* No more entries in the directory */ -#define PR_NO_MORE_FILES_ERROR (-5939L) - -/* Encountered end of file */ -#define PR_END_OF_FILE_ERROR (-5938L) - -/* Seek error */ -#define PR_FILE_SEEK_ERROR (-5937L) - -/* The file is busy */ -#define PR_FILE_IS_BUSY_ERROR (-5936L) - -/* The I/O operation was aborted */ -#define PR_OPERATION_ABORTED_ERROR (-5935L) - -/* Operation is still in progress (probably a non-blocking connect) */ -#define PR_IN_PROGRESS_ERROR (-5934L) - -/* Operation has already been initiated (probably a non-blocking connect) */ -#define PR_ALREADY_INITIATED_ERROR (-5933L) - -/* The wait group is empty */ -#define PR_GROUP_EMPTY_ERROR (-5932L) - -/* Object state improper for request */ -#define PR_INVALID_STATE_ERROR (-5931L) - -/* Network is down */ -#define PR_NETWORK_DOWN_ERROR (-5930L) - -/* Socket shutdown */ -#define PR_SOCKET_SHUTDOWN_ERROR (-5929L) - -/* Connection aborted */ -#define PR_CONNECT_ABORTED_ERROR (-5928L) - -/* Host is unreachable */ -#define PR_HOST_UNREACHABLE_ERROR (-5927L) - -/* The library is not loaded */ -#define PR_LIBRARY_NOT_LOADED_ERROR (-5926L) - -/* The one-time function was previously called and failed. Its error code is no longer available */ -#define PR_CALL_ONCE_ERROR (-5925L) - -/* Placeholder for the end of the list */ -#define PR_MAX_ERROR (-5924L) - -extern void nspr_InitializePRErrorTable(void); -#define ERROR_TABLE_BASE_nspr (-6000L) - -#endif /* prerr_h___ */ diff --git a/win32/include/spidermonkey/nspr/prerror.h b/win32/include/spidermonkey/nspr/prerror.h deleted file mode 100755 index 3d6baf6e..00000000 --- a/win32/include/spidermonkey/nspr/prerror.h +++ /dev/null @@ -1,294 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prerror_h___ -#define prerror_h___ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -typedef PRInt32 PRErrorCode; - -#define PR_NSPR_ERROR_BASE -6000 - -#include "prerr.h" - -/* -** Set error will preserve an error condition within a thread context. -** The values stored are the NSPR (platform independent) translation of -** the error. Also, if available, the platform specific oserror is stored. -** If there is no appropriate OS error number, a zero my be supplied. -*/ -NSPR_API(void) PR_SetError(PRErrorCode errorCode, PRInt32 oserr); - -/* -** The text value specified may be NULL. If it is not NULL and the text length -** is zero, the string is assumed to be a null terminated C string. Otherwise -** the text is assumed to be the length specified and possibly include NULL -** characters (e.g., a multi-national string). -** -** The text will be copied into to thread structure and remain there -** until the next call to PR_SetError. -*/ -NSPR_API(void) PR_SetErrorText( - PRIntn textLength, const char *text); - -/* -** Return the current threads last set error code. -*/ -NSPR_API(PRErrorCode) PR_GetError(void); - -/* -** Return the current threads last set os error code. This is used for -** machine specific code that desires the underlying os error. -*/ -NSPR_API(PRInt32) PR_GetOSError(void); - -/* -** Get the length of the error text. If a zero is returned, then there -** is no text. Otherwise, the value returned is sufficient to contain -** the error text currently available. -*/ -NSPR_API(PRInt32) PR_GetErrorTextLength(void); - -/* -** Copy the current threads current error text. Then actual number of bytes -** copied is returned as the result. If the result is zero, the 'text' area -** is unaffected. -*/ -NSPR_API(PRInt32) PR_GetErrorText(char *text); - - -/* -Copyright (C) 1987, 1988 Student Information Processing Board of the -Massachusetts Institute of Technology. - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, provided -that the above copyright notice appear in all copies and that both that -copyright notice and this permission notice appear in supporting -documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be -used in advertising or publicity pertaining to distribution of the software -without specific, written prior permission. M.I.T. and the M.I.T. S.I.P.B. -make no representations about the suitability of this software for any -purpose. It is provided "as is" without express or implied warranty. -*/ - - -/* - * NOTE: - * The interfaces for error-code-translation described in the rest of - * this file are preliminary in the 3.1 release of nspr and are subject - * to change in future releases. - */ - -/* -** Description: Localizable error code to string function. -** -** -** NSPR provides a mechanism for converting an error code to a -** descriptive string, in a caller-specified language. -** -** Error codes themselves are 32 bit (signed) integers. Typically, -** the high order 24 bits are an identifier of which error table the -** error code is from, and the low order 8 bits are a sequential error -** number within the table. NSPR supports error tables whose first -** error code is not a multiple of 256, such error code assignments -** should be avoided when possible. -** -** Error table 0 is defined to match the UNIX system call error table -** (sys_errlist); this allows errno values to be used directly in the -** library. Other error table numbers are typically formed by -** compacting together the first four characters of the error table -** name. The mapping between characters in the name and numeric -** values in the error code are defined in a system-independent -** fashion, so that two systems that can pass integral values between -** them can reliably pass error codes without loss of meaning; this -** should work even if the character sets used are not the -** same. (However, if this is to be done, error table 0 should be -** avoided, since the local system call error tables may differ.) -** -** Libraries defining error codes need only provide a table mapping -** error code numbers to names and default English descriptions, -** calling a routine to install the table, making it ``known'' to NSPR -** library. Once installed, a table may not be removed. Any error -** code the library generates can be converted to the corresponding -** error message. There is also a default format for error codes -** accidentally returned before making the table known, which is of -** the form "unknown code foo 32", where "foo" would be the name of -** the table. -** -** Normally, the error code conversion routine only supports the -** languages "i-default" and "en", returning the error-table-provided -** English description for both languages. The application may -** provide a localization plugin, allowing support for additional -** languages. -** -**/ - -/**********************************************************************/ -/************************* TYPES AND CONSTANTS ************************/ -/**********************************************************************/ - -/* - * PRLanguageCode -- - * - * NSPR represents a language code as a non-negative integer. - * Languages 0 is always "i-default" the language you get without - * explicit negotiation. Language 1 is always "en", English - * which has been explicitly negotiated. Additional language - * codes are defined by an application-provided localization plugin. - */ -typedef PRUint32 PRLanguageCode; -#define PR_LANGUAGE_I_DEFAULT 0 /* i-default, the default language */ -#define PR_LANGUAGE_EN 1 /* English, explicitly negotiated */ - -/* - * struct PRErrorMessage -- - * - * An error message in an error table. - */ -struct PRErrorMessage { - const char * name; /* Macro name for error */ - const char * en_text; /* Default English text */ -}; - -/* - * struct PRErrorTable -- - * - * An error table, provided by a library. - */ -struct PRErrorTable { - const struct PRErrorMessage * msgs; /* Array of error information */ - const char *name; /* Name of error table source */ - PRErrorCode base; /* Error code for first error in table */ - int n_msgs; /* Number of codes in table */ -}; - -/* - * struct PRErrorCallbackPrivate -- - * - * A private structure for the localization plugin - */ -struct PRErrorCallbackPrivate; - -/* - * struct PRErrorCallbackTablePrivate -- - * - * A data structure under which the localization plugin may store information, - * associated with an error table, that is private to itself. - */ -struct PRErrorCallbackTablePrivate; - -/* - * PRErrorCallbackLookupFn -- - * - * A function of PRErrorCallbackLookupFn type is a localization - * plugin callback which converts an error code into a description - * in the requested language. The callback is provided the - * appropriate error table, private data for the plugin and the table. - * The callback returns the appropriate UTF-8 encoded description, or NULL - * if no description can be found. - */ -typedef const char * -PRErrorCallbackLookupFn(PRErrorCode code, PRLanguageCode language, - const struct PRErrorTable *table, - struct PRErrorCallbackPrivate *cb_private, - struct PRErrorCallbackTablePrivate *table_private); - -/* - * PRErrorCallbackNewTableFn -- - * - * A function PRErrorCallbackNewTableFn type is a localization plugin - * callback which is called once with each error table registered - * with NSPR. The callback is provided with the error table and - * the plugin's private structure. The callback returns any table private - * data it wishes to associate with the error table. Does not need to be thread - * safe. - */ -typedef struct PRErrorCallbackTablePrivate * -PRErrorCallbackNewTableFn(const struct PRErrorTable *table, - struct PRErrorCallbackPrivate *cb_private); - -/**********************************************************************/ -/****************************** FUNCTIONS *****************************/ -/**********************************************************************/ - -/*********************************************************************** -** FUNCTION: PR_ErrorToString -** DESCRIPTION: -** Returns the UTF-8 message for an error code in -** the requested language. May return the message -** in the default language if a translation in the requested -** language is not available. The returned string is -** valid for the duration of the process. Never returns NULL. -** -***********************************************************************/ -NSPR_API(const char *) PR_ErrorToString(PRErrorCode code, - PRLanguageCode language); - - -/*********************************************************************** -** FUNCTION: PR_ErrorToName -** DESCRIPTION: -** Returns the macro name for an error code, or NULL -** if the error code is not known. The returned string is -** valid for the duration of the process. -** -** Does not work for error table 0, the system error codes. -** -***********************************************************************/ -NSPR_API(const char *) PR_ErrorToName(PRErrorCode code); - - -/*********************************************************************** -** FUNCTION: PR_ErrorLanguages -** DESCRIPTION: -** Returns the RFC 1766 language tags for the language -** codes PR_ErrorToString() supports. The returned array is valid -** for the duration of the process. Never returns NULL. The first -** item in the returned array is the language tag for PRLanguageCode 0, -** the second is for PRLanguageCode 1, and so on. The array is terminated -** with a null pointer. -** -***********************************************************************/ -NSPR_API(const char * const *) PR_ErrorLanguages(void); - - -/*********************************************************************** -** FUNCTION: PR_ErrorInstallTable -** DESCRIPTION: -** Registers an error table with NSPR. Must be done exactly once per -** table. Memory pointed to by `table' must remain valid for the life -** of the process. -** -** NOT THREAD SAFE! -** -***********************************************************************/ -NSPR_API(PRErrorCode) PR_ErrorInstallTable(const struct PRErrorTable *table); - - -/*********************************************************************** -** FUNCTION: PR_ErrorInstallCallback -** DESCRIPTION: -** Registers an error localization plugin with NSPR. May be called -** at most one time. `languages' contains the language codes supported -** by this plugin. Languages 0 and 1 must be "i-default" and "en" -** respectively. `lookup' and `newtable' contain pointers to -** the plugin callback functions. `cb_private' contains any information -** private to the plugin functions. -** -** NOT THREAD SAFE! -** -***********************************************************************/ -NSPR_API(void) PR_ErrorInstallCallback(const char * const * languages, - PRErrorCallbackLookupFn *lookup, - PRErrorCallbackNewTableFn *newtable, - struct PRErrorCallbackPrivate *cb_private); - -PR_END_EXTERN_C - -#endif /* prerror_h___ */ diff --git a/win32/include/spidermonkey/nspr/prinet.h b/win32/include/spidermonkey/nspr/prinet.h deleted file mode 100755 index 15d229fe..00000000 --- a/win32/include/spidermonkey/nspr/prinet.h +++ /dev/null @@ -1,99 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * File: prinet.h - * Description: - * Header file used to find the system header files for socket support[1]. - * This file serves the following purposes: - * - A cross-platform, "get-everything" socket header file. On - * Unix, socket support is scattered in several header files, - * while Windows has a "get-everything" socket header file[2]. - * - NSPR needs the following macro definitions and function - * prototype declarations from these header files: - * AF_INET - * INADDR_ANY, INADDR_LOOPBACK, INADDR_BROADCAST - * ntohl(), ntohs(), htonl(), ntons(). - * NSPR does not define its own versions of these macros and - * functions. It simply uses the native versions, which have - * the same names on all supported platforms. - * This file is intended to be included by NSPR public header - * files, such as prio.h. One should not include this file directly. - * - * Notes: - * 1. This file should have been an internal header. Please do not - * depend on it to pull in the system header files you need. - * 2. WARNING: This file is no longer cross-platform as it is a no-op - * for WIN32! See the comment in the WIN32 section for details. - */ - -#ifndef prinet_h__ -#define prinet_h__ - -#if defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS) -#include -#include /* AF_INET */ -#include /* INADDR_ANY, ..., ntohl(), ... */ -#ifdef XP_OS2 -#include -#endif -#ifdef XP_UNIX -#ifdef AIX -/* - * On AIX 4.3, the header refers to struct - * ether_addr and struct sockaddr_dl that are not declared. - * The following struct declarations eliminate the compiler - * warnings. - */ -struct ether_addr; -struct sockaddr_dl; -#endif /* AIX */ -#include -#endif /* XP_UNIX */ -#include - -#if defined(FREEBSD) || defined(BSDI) || defined(QNX) -#include /* the only place that defines INADDR_LOOPBACK */ -#endif - -/* - * OS/2 hack. For some reason INADDR_LOOPBACK is not defined in the - * socket headers. - */ -#if defined(OS2) && !defined(INADDR_LOOPBACK) -#define INADDR_LOOPBACK 0x7f000001 -#endif - -/* - * Prototypes of ntohl() etc. are declared in - * on these platforms. - */ -#if defined(BSDI) || defined(OSF1) -#include -#endif - -/* On Android, ntohl() etc. are declared in . */ -#ifdef __ANDROID__ -#include -#endif - -#elif defined(WIN32) - -/* - * Do not include any system header files. - * - * Originally we were including . It slowed down the - * compilation of files that included NSPR headers, so we removed - * the inclusion at customer's request, which created - * an unfortunate inconsistency with other platforms. - */ - -#else - -#error Unknown platform - -#endif - -#endif /* prinet_h__ */ diff --git a/win32/include/spidermonkey/nspr/prinit.h b/win32/include/spidermonkey/nspr/prinit.h deleted file mode 100755 index e27fc34d..00000000 --- a/win32/include/spidermonkey/nspr/prinit.h +++ /dev/null @@ -1,215 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prinit_h___ -#define prinit_h___ - -#include "prthread.h" -#include "prtypes.h" -#include "prwin16.h" -#include - -PR_BEGIN_EXTERN_C - -/************************************************************************/ -/**************************IDENTITY AND VERSIONING***********************/ -/************************************************************************/ - -/* -** NSPR's name, this should persist until at least the turn of the -** century. -*/ -#define PR_NAME "NSPR" - -/* -** NSPR's version is used to determine the likelihood that the version you -** used to build your component is anywhere close to being compatible with -** what is in the underlying library. -** -** The format of the version string is -** ".[.] []" -*/ -#define PR_VERSION "4.13.1" -#define PR_VMAJOR 4 -#define PR_VMINOR 13 -#define PR_VPATCH 1 -#define PR_BETA PR_FALSE - -/* -** PRVersionCheck -** -** The basic signature of the function that is called to provide version -** checking. The result will be a boolean that indicates the likelihood -** that the underling library will perform as the caller expects. -** -** The only argument is a string, which should be the verson identifier -** of the library in question. That string will be compared against an -** equivalent string that represents the actual build version of the -** exporting library. -** -** The result will be the logical union of the directly called library -** and all dependent libraries. -*/ - -typedef PRBool (*PRVersionCheck)(const char*); - -/* -** PR_VersionCheck -** -** NSPR's existance proof of the version check function. -** -** Note that NSPR has no cooperating dependencies. -*/ - -NSPR_API(PRBool) PR_VersionCheck(const char *importedVersion); - -/* - * Returns a const string of the NSPR library version. - */ -NSPR_API(const char*) PR_GetVersion(void); - - -/************************************************************************/ -/*******************************INITIALIZATION***************************/ -/************************************************************************/ - -/* -** Initialize the runtime. Attach a thread object to the currently -** executing native thread of type "type". -** -** The specificaiton of 'maxPTDs' is ignored. -*/ -NSPR_API(void) PR_Init( - PRThreadType type, PRThreadPriority priority, PRUintn maxPTDs); - -/* -** And alternate form of initialization, one that may become the default if -** not the only mechanism, provides a method to get the NSPR runtime init- -** ialized and place NSPR between the caller and the runtime library. This -** allows main() to be treated as any other thread root function, signalling -** its compeletion by returning and allowing the runtime to coordinate the -** completion of the other threads of the runtime. -** -** The priority of the main (or primordial) thread will be PR_PRIORITY_NORMAL. -** The thread may adjust its own priority by using PR_SetPriority(), though -** at this time the support for priorities is somewhat weak. -** -** The specificaiton of 'maxPTDs' is ignored. -** -** The value returned by PR_Initialize is the value returned from the root -** function, 'prmain'. -*/ - -typedef PRIntn (PR_CALLBACK *PRPrimordialFn)(PRIntn argc, char **argv); - -NSPR_API(PRIntn) PR_Initialize( - PRPrimordialFn prmain, PRIntn argc, char **argv, PRUintn maxPTDs); - -/* -** Return PR_TRUE if PR_Init has already been called. -*/ -NSPR_API(PRBool) PR_Initialized(void); - -/* - * Perform a graceful shutdown of NSPR. PR_Cleanup() may be called by - * the primordial thread near the end of the main() function. - * - * PR_Cleanup() attempts to synchronize the natural termination of - * process. It does that by blocking the caller, if and only if it is - * the primordial thread, until the number of user threads has dropped - * to zero. When the primordial thread returns from main(), the process - * will immediately and silently exit. That is, it will (if necessary) - * forcibly terminate any existing threads and exit without significant - * blocking and there will be no error messages or core files. - * - * PR_Cleanup() returns PR_SUCCESS if NSPR is successfully shutdown, - * or PR_FAILURE if the calling thread of this function is not the - * primordial thread. - */ -NSPR_API(PRStatus) PR_Cleanup(void); - -/* -** Disable Interrupts -** Disables timer signals used for pre-emptive scheduling. -*/ -NSPR_API(void) PR_DisableClockInterrupts(void); - -/* -** Enables Interrupts -** Enables timer signals used for pre-emptive scheduling. -*/ -NSPR_API(void) PR_EnableClockInterrupts(void); - -/* -** Block Interrupts -** Blocks the timer signal used for pre-emptive scheduling -*/ -NSPR_API(void) PR_BlockClockInterrupts(void); - -/* -** Unblock Interrupts -** Unblocks the timer signal used for pre-emptive scheduling -*/ -NSPR_API(void) PR_UnblockClockInterrupts(void); - -/* -** Create extra virtual processor threads. Generally used with MP systems. -*/ -NSPR_API(void) PR_SetConcurrency(PRUintn numCPUs); - -/* -** Control the method and size of the file descriptor (PRFileDesc*) -** cache used by the runtime. Setting 'high' to zero is for performance, -** any other value probably for debugging (see memo on FD caching). -*/ -NSPR_API(PRStatus) PR_SetFDCacheSize(PRIntn low, PRIntn high); - -/* - * Cause an immediate, nongraceful, forced termination of the process. - * It takes a PRIntn argument, which is the exit status code of the - * process. - */ -NSPR_API(void) PR_ProcessExit(PRIntn status); - -/* -** Abort the process in a non-graceful manner. This will cause a core file, -** call to the debugger or other moral equivalent as well as causing the -** entire process to stop. -*/ -NSPR_API(void) PR_Abort(void); - -/* - **************************************************************** - * - * Module initialization: - * - **************************************************************** - */ - -typedef struct PRCallOnceType { - PRIntn initialized; - PRInt32 inProgress; - PRStatus status; -} PRCallOnceType; - -typedef PRStatus (PR_CALLBACK *PRCallOnceFN)(void); - -typedef PRStatus (PR_CALLBACK *PRCallOnceWithArgFN)(void *arg); - -NSPR_API(PRStatus) PR_CallOnce( - PRCallOnceType *once, - PRCallOnceFN func -); - -NSPR_API(PRStatus) PR_CallOnceWithArg( - PRCallOnceType *once, - PRCallOnceWithArgFN func, - void *arg -); - - -PR_END_EXTERN_C - -#endif /* prinit_h___ */ diff --git a/win32/include/spidermonkey/nspr/prinrval.h b/win32/include/spidermonkey/nspr/prinrval.h deleted file mode 100755 index 14cd39b6..00000000 --- a/win32/include/spidermonkey/nspr/prinrval.h +++ /dev/null @@ -1,146 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: prinrval.h -** Description: API to interval timing functions of NSPR. -** -** -** NSPR provides interval times that are independent of network time -** of day values. Interval times are (in theory) accurate regardless -** of host processing requirements and also very cheap to acquire. It -** is expected that getting an interval time while in a synchronized -** function (holding one's lock). -**/ - -#if !defined(prinrval_h) -#define prinrval_h - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/**********************************************************************/ -/************************* TYPES AND CONSTANTS ************************/ -/**********************************************************************/ - -typedef PRUint32 PRIntervalTime; - -/*********************************************************************** -** DEFINES: PR_INTERVAL_MIN -** PR_INTERVAL_MAX -** DESCRIPTION: -** These two constants define the range (in ticks / second) of the -** platform dependent type, PRIntervalTime. These constants bound both -** the period and the resolution of a PRIntervalTime. -***********************************************************************/ -#define PR_INTERVAL_MIN 1000UL -#define PR_INTERVAL_MAX 100000UL - -/*********************************************************************** -** DEFINES: PR_INTERVAL_NO_WAIT -** PR_INTERVAL_NO_TIMEOUT -** DESCRIPTION: -** Two reserved constants are defined in the PRIntervalTime namespace. -** They are used to indicate that the process should wait no time (return -** immediately) or wait forever (never time out), respectively. -** Note: PR_INTERVAL_NO_TIMEOUT passed as input to PR_Connect is -** interpreted as use the OS's connect timeout. -** -***********************************************************************/ -#define PR_INTERVAL_NO_WAIT 0UL -#define PR_INTERVAL_NO_TIMEOUT 0xffffffffUL - -/**********************************************************************/ -/****************************** FUNCTIONS *****************************/ -/**********************************************************************/ - -/*********************************************************************** -** FUNCTION: PR_IntervalNow -** DESCRIPTION: -** Return the value of NSPR's free running interval timer. That timer -** can be used to establish epochs and determine intervals (be computing -** the difference between two times). -** INPUTS: void -** OUTPUTS: void -** RETURN: PRIntervalTime -** -** SIDE EFFECTS: -** None -** RESTRICTIONS: -** The units of PRIntervalTime are platform dependent. They are chosen -** such that they are appropriate for the host OS, yet provide sufficient -** resolution and period to be useful to clients. -** MEMORY: N/A -** ALGORITHM: Platform dependent -***********************************************************************/ -NSPR_API(PRIntervalTime) PR_IntervalNow(void); - -/*********************************************************************** -** FUNCTION: PR_TicksPerSecond -** DESCRIPTION: -** Return the number of ticks per second for PR_IntervalNow's clock. -** The value will be in the range [PR_INTERVAL_MIN..PR_INTERVAL_MAX]. -** INPUTS: void -** OUTPUTS: void -** RETURN: PRUint32 -** -** SIDE EFFECTS: -** None -** RESTRICTIONS: -** None -** MEMORY: N/A -** ALGORITHM: N/A -***********************************************************************/ -NSPR_API(PRUint32) PR_TicksPerSecond(void); - -/*********************************************************************** -** FUNCTION: PR_SecondsToInterval -** PR_MillisecondsToInterval -** PR_MicrosecondsToInterval -** DESCRIPTION: -** Convert standard clock units to platform dependent intervals. -** INPUTS: PRUint32 -** OUTPUTS: void -** RETURN: PRIntervalTime -** -** SIDE EFFECTS: -** None -** RESTRICTIONS: -** Conversion may cause overflow, which is not reported. -** MEMORY: N/A -** ALGORITHM: N/A -***********************************************************************/ -NSPR_API(PRIntervalTime) PR_SecondsToInterval(PRUint32 seconds); -NSPR_API(PRIntervalTime) PR_MillisecondsToInterval(PRUint32 milli); -NSPR_API(PRIntervalTime) PR_MicrosecondsToInterval(PRUint32 micro); - -/*********************************************************************** -** FUNCTION: PR_IntervalToSeconds -** PR_IntervalToMilliseconds -** PR_IntervalToMicroseconds -** DESCRIPTION: -** Convert platform dependent intervals to standard clock units. -** INPUTS: PRIntervalTime -** OUTPUTS: void -** RETURN: PRUint32 -** -** SIDE EFFECTS: -** None -** RESTRICTIONS: -** Conversion may cause overflow, which is not reported. -** MEMORY: N/A -** ALGORITHM: N/A -***********************************************************************/ -NSPR_API(PRUint32) PR_IntervalToSeconds(PRIntervalTime ticks); -NSPR_API(PRUint32) PR_IntervalToMilliseconds(PRIntervalTime ticks); -NSPR_API(PRUint32) PR_IntervalToMicroseconds(PRIntervalTime ticks); - -PR_END_EXTERN_C - - -#endif /* !defined(prinrval_h) */ - -/* prinrval.h */ diff --git a/win32/include/spidermonkey/nspr/prio.h b/win32/include/spidermonkey/nspr/prio.h deleted file mode 100755 index 18504e5c..00000000 --- a/win32/include/spidermonkey/nspr/prio.h +++ /dev/null @@ -1,2022 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * File: prio.h - * - * Description: PR i/o related stuff, such as file system access, file - * i/o, socket i/o, etc. - */ - -#ifndef prio_h___ -#define prio_h___ - -#include "prlong.h" -#include "prtime.h" -#include "prinrval.h" -#include "prinet.h" - -PR_BEGIN_EXTERN_C - -/* Typedefs */ -typedef struct PRDir PRDir; -typedef struct PRDirEntry PRDirEntry; -#ifdef MOZ_UNICODE -typedef struct PRDirUTF16 PRDirUTF16; -typedef struct PRDirEntryUTF16 PRDirEntryUTF16; -#endif /* MOZ_UNICODE */ -typedef struct PRFileDesc PRFileDesc; -typedef struct PRFileInfo PRFileInfo; -typedef struct PRFileInfo64 PRFileInfo64; -typedef union PRNetAddr PRNetAddr; -typedef struct PRIOMethods PRIOMethods; -typedef struct PRPollDesc PRPollDesc; -typedef struct PRFilePrivate PRFilePrivate; -typedef struct PRSendFileData PRSendFileData; - -/* -*************************************************************************** -** The file descriptor. -** This is the primary structure to represent any active open socket, -** whether it be a normal file or a network connection. Such objects -** are stackable (or layerable). Each layer may have its own set of -** method pointers and context private to that layer. All each layer -** knows about its neighbors is how to get to their method table. -*************************************************************************** -*/ - -typedef PRIntn PRDescIdentity; /* see: Layering file descriptors */ - -struct PRFileDesc { - const PRIOMethods *methods; /* the I/O methods table */ - PRFilePrivate *secret; /* layer dependent data */ - PRFileDesc *lower, *higher; /* pointers to adjacent layers */ - void (PR_CALLBACK *dtor)(PRFileDesc *fd); - /* A destructor function for layer */ - PRDescIdentity identity; /* Identity of this particular layer */ -}; - -/* -*************************************************************************** -** PRTransmitFileFlags -** -** Flags for PR_TransmitFile. Pass PR_TRANSMITFILE_CLOSE_SOCKET to -** PR_TransmitFile if the connection should be closed after the file -** is transmitted. -*************************************************************************** -*/ -typedef enum PRTransmitFileFlags { - PR_TRANSMITFILE_KEEP_OPEN = 0, /* socket is left open after file - * is transmitted. */ - PR_TRANSMITFILE_CLOSE_SOCKET = 1 /* socket is closed after file - * is transmitted. */ -} PRTransmitFileFlags; - -/* -************************************************************************** -** Macros for PRNetAddr -** -** Address families: PR_AF_INET, PR_AF_INET6, PR_AF_LOCAL -** IP addresses: PR_INADDR_ANY, PR_INADDR_LOOPBACK, PR_INADDR_BROADCAST -************************************************************************** -*/ - -#ifdef WIN32 - -#define PR_AF_INET 2 -#define PR_AF_LOCAL 1 -#define PR_INADDR_ANY (unsigned long)0x00000000 -#define PR_INADDR_LOOPBACK 0x7f000001 -#define PR_INADDR_BROADCAST (unsigned long)0xffffffff - -#else /* WIN32 */ - -#define PR_AF_INET AF_INET -#define PR_AF_LOCAL AF_UNIX -#define PR_INADDR_ANY INADDR_ANY -#define PR_INADDR_LOOPBACK INADDR_LOOPBACK -#define PR_INADDR_BROADCAST INADDR_BROADCAST - -#endif /* WIN32 */ - -/* -** Define PR_AF_INET6 in prcpucfg.h with the same -** value as AF_INET6 on platforms with IPv6 support. -** Otherwise define it here. -*/ -#ifndef PR_AF_INET6 -#define PR_AF_INET6 100 -#endif - -#define PR_AF_INET_SDP 101 -#define PR_AF_INET6_SDP 102 - -#ifndef PR_AF_UNSPEC -#define PR_AF_UNSPEC 0 -#endif - -/* -************************************************************************** -** A network address -** -** Only Internet Protocol (IPv4 and IPv6) addresses are supported. -** The address family must always represent IPv4 (AF_INET, probably == 2) -** or IPv6 (AF_INET6). -************************************************************************** -*************************************************************************/ - -struct PRIPv6Addr { - union { - PRUint8 _S6_u8[16]; - PRUint16 _S6_u16[8]; - PRUint32 _S6_u32[4]; - PRUint64 _S6_u64[2]; - } _S6_un; -}; -#define pr_s6_addr _S6_un._S6_u8 -#define pr_s6_addr16 _S6_un._S6_u16 -#define pr_s6_addr32 _S6_un._S6_u32 -#define pr_s6_addr64 _S6_un._S6_u64 - -typedef struct PRIPv6Addr PRIPv6Addr; - -union PRNetAddr { - struct { - PRUint16 family; /* address family (0x00ff maskable) */ -#ifdef XP_BEOS - char data[10]; /* Be has a smaller structure */ -#else - char data[14]; /* raw address data */ -#endif - } raw; - struct { - PRUint16 family; /* address family (AF_INET) */ - PRUint16 port; /* port number */ - PRUint32 ip; /* The actual 32 bits of address */ -#ifdef XP_BEOS - char pad[4]; /* Be has a smaller structure */ -#else - char pad[8]; -#endif - } inet; - struct { - PRUint16 family; /* address family (AF_INET6) */ - PRUint16 port; /* port number */ - PRUint32 flowinfo; /* routing information */ - PRIPv6Addr ip; /* the actual 128 bits of address */ - PRUint32 scope_id; /* set of interfaces for a scope */ - } ipv6; -#if defined(XP_UNIX) || defined(XP_OS2) || defined(XP_WIN) - struct { /* Unix domain socket address */ - PRUint16 family; /* address family (AF_UNIX) */ -#ifdef XP_OS2 - char path[108]; /* null-terminated pathname */ - /* bind fails if size is not 108. */ -#else - char path[104]; /* null-terminated pathname */ -#endif - } local; -#endif -}; - -/* -*************************************************************************** -** PRSockOption -** -** The file descriptors can have predefined options set after they file -** descriptor is created to change their behavior. Only the options in -** the following enumeration are supported. -*************************************************************************** -*/ -typedef enum PRSockOption -{ - PR_SockOpt_Nonblocking, /* nonblocking io */ - PR_SockOpt_Linger, /* linger on close if data present */ - PR_SockOpt_Reuseaddr, /* allow local address reuse */ - PR_SockOpt_Keepalive, /* keep connections alive */ - PR_SockOpt_RecvBufferSize, /* receive buffer size */ - PR_SockOpt_SendBufferSize, /* send buffer size */ - - PR_SockOpt_IpTimeToLive, /* time to live */ - PR_SockOpt_IpTypeOfService, /* type of service and precedence */ - - PR_SockOpt_AddMember, /* add an IP group membership */ - PR_SockOpt_DropMember, /* drop an IP group membership */ - PR_SockOpt_McastInterface, /* multicast interface address */ - PR_SockOpt_McastTimeToLive, /* multicast timetolive */ - PR_SockOpt_McastLoopback, /* multicast loopback */ - - PR_SockOpt_NoDelay, /* don't delay send to coalesce packets */ - PR_SockOpt_MaxSegment, /* maximum segment size */ - PR_SockOpt_Broadcast, /* enable broadcast */ - PR_SockOpt_Reuseport, /* allow local address & port reuse on - * platforms that support it */ - PR_SockOpt_Last -} PRSockOption; - -typedef struct PRLinger { - PRBool polarity; /* Polarity of the option's setting */ - PRIntervalTime linger; /* Time to linger before closing */ -} PRLinger; - -typedef struct PRMcastRequest { - PRNetAddr mcaddr; /* IP multicast address of group */ - PRNetAddr ifaddr; /* local IP address of interface */ -} PRMcastRequest; - -typedef struct PRSocketOptionData -{ - PRSockOption option; - union - { - PRUintn ip_ttl; /* IP time to live */ - PRUintn mcast_ttl; /* IP multicast time to live */ - PRUintn tos; /* IP type of service and precedence */ - PRBool non_blocking; /* Non-blocking (network) I/O */ - PRBool reuse_addr; /* Allow local address reuse */ - PRBool reuse_port; /* Allow local address & port reuse on - * platforms that support it */ - PRBool keep_alive; /* Keep connections alive */ - PRBool mcast_loopback; /* IP multicast loopback */ - PRBool no_delay; /* Don't delay send to coalesce packets */ - PRBool broadcast; /* Enable broadcast */ - PRSize max_segment; /* Maximum segment size */ - PRSize recv_buffer_size; /* Receive buffer size */ - PRSize send_buffer_size; /* Send buffer size */ - PRLinger linger; /* Time to linger on close if data present */ - PRMcastRequest add_member; /* add an IP group membership */ - PRMcastRequest drop_member; /* Drop an IP group membership */ - PRNetAddr mcast_if; /* multicast interface address */ - } value; -} PRSocketOptionData; - -/* -*************************************************************************** -** PRIOVec -** -** The I/O vector is used by the write vector method to describe the areas -** that are affected by the ouput operation. -*************************************************************************** -*/ -typedef struct PRIOVec { - char *iov_base; - int iov_len; -} PRIOVec; - -/* -*************************************************************************** -** Discover what type of socket is being described by the file descriptor. -*************************************************************************** -*/ -typedef enum PRDescType -{ - PR_DESC_FILE = 1, - PR_DESC_SOCKET_TCP = 2, - PR_DESC_SOCKET_UDP = 3, - PR_DESC_LAYERED = 4, - PR_DESC_PIPE = 5 -} PRDescType; - -typedef enum PRSeekWhence { - PR_SEEK_SET = 0, - PR_SEEK_CUR = 1, - PR_SEEK_END = 2 -} PRSeekWhence; - -NSPR_API(PRDescType) PR_GetDescType(PRFileDesc *file); - -/* -*************************************************************************** -** PRIOMethods -** -** The I/O methods table provides procedural access to the functions of -** the file descriptor. It is the responsibility of a layer implementor -** to provide suitable functions at every entry point. If a layer provides -** no functionality, it should call the next lower(higher) function of the -** same name (e.g., return fd->lower->method->close(fd->lower)); -** -** Not all functions are implemented for all types of files. In cases where -** that is true, the function will return a error indication with an error -** code of PR_INVALID_METHOD_ERROR. -*************************************************************************** -*/ - -typedef PRStatus (PR_CALLBACK *PRCloseFN)(PRFileDesc *fd); -typedef PRInt32 (PR_CALLBACK *PRReadFN)(PRFileDesc *fd, void *buf, PRInt32 amount); -typedef PRInt32 (PR_CALLBACK *PRWriteFN)(PRFileDesc *fd, const void *buf, PRInt32 amount); -typedef PRInt32 (PR_CALLBACK *PRAvailableFN)(PRFileDesc *fd); -typedef PRInt64 (PR_CALLBACK *PRAvailable64FN)(PRFileDesc *fd); -typedef PRStatus (PR_CALLBACK *PRFsyncFN)(PRFileDesc *fd); -typedef PROffset32 (PR_CALLBACK *PRSeekFN)(PRFileDesc *fd, PROffset32 offset, PRSeekWhence how); -typedef PROffset64 (PR_CALLBACK *PRSeek64FN)(PRFileDesc *fd, PROffset64 offset, PRSeekWhence how); -typedef PRStatus (PR_CALLBACK *PRFileInfoFN)(PRFileDesc *fd, PRFileInfo *info); -typedef PRStatus (PR_CALLBACK *PRFileInfo64FN)(PRFileDesc *fd, PRFileInfo64 *info); -typedef PRInt32 (PR_CALLBACK *PRWritevFN)( - PRFileDesc *fd, const PRIOVec *iov, PRInt32 iov_size, - PRIntervalTime timeout); -typedef PRStatus (PR_CALLBACK *PRConnectFN)( - PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout); -typedef PRFileDesc* (PR_CALLBACK *PRAcceptFN) ( - PRFileDesc *fd, PRNetAddr *addr, PRIntervalTime timeout); -typedef PRStatus (PR_CALLBACK *PRBindFN)(PRFileDesc *fd, const PRNetAddr *addr); -typedef PRStatus (PR_CALLBACK *PRListenFN)(PRFileDesc *fd, PRIntn backlog); -typedef PRStatus (PR_CALLBACK *PRShutdownFN)(PRFileDesc *fd, PRIntn how); -typedef PRInt32 (PR_CALLBACK *PRRecvFN)( - PRFileDesc *fd, void *buf, PRInt32 amount, - PRIntn flags, PRIntervalTime timeout); -typedef PRInt32 (PR_CALLBACK *PRSendFN) ( - PRFileDesc *fd, const void *buf, PRInt32 amount, - PRIntn flags, PRIntervalTime timeout); -typedef PRInt32 (PR_CALLBACK *PRRecvfromFN)( - PRFileDesc *fd, void *buf, PRInt32 amount, - PRIntn flags, PRNetAddr *addr, PRIntervalTime timeout); -typedef PRInt32 (PR_CALLBACK *PRSendtoFN)( - PRFileDesc *fd, const void *buf, PRInt32 amount, - PRIntn flags, const PRNetAddr *addr, PRIntervalTime timeout); -typedef PRInt16 (PR_CALLBACK *PRPollFN)( - PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags); -typedef PRInt32 (PR_CALLBACK *PRAcceptreadFN)( - PRFileDesc *sd, PRFileDesc **nd, PRNetAddr **raddr, - void *buf, PRInt32 amount, PRIntervalTime t); -typedef PRInt32 (PR_CALLBACK *PRTransmitfileFN)( - PRFileDesc *sd, PRFileDesc *fd, const void *headers, - PRInt32 hlen, PRTransmitFileFlags flags, PRIntervalTime t); -typedef PRStatus (PR_CALLBACK *PRGetsocknameFN)(PRFileDesc *fd, PRNetAddr *addr); -typedef PRStatus (PR_CALLBACK *PRGetpeernameFN)(PRFileDesc *fd, PRNetAddr *addr); -typedef PRStatus (PR_CALLBACK *PRGetsocketoptionFN)( - PRFileDesc *fd, PRSocketOptionData *data); -typedef PRStatus (PR_CALLBACK *PRSetsocketoptionFN)( - PRFileDesc *fd, const PRSocketOptionData *data); -typedef PRInt32 (PR_CALLBACK *PRSendfileFN)( - PRFileDesc *networkSocket, PRSendFileData *sendData, - PRTransmitFileFlags flags, PRIntervalTime timeout); -typedef PRStatus (PR_CALLBACK *PRConnectcontinueFN)( - PRFileDesc *fd, PRInt16 out_flags); -typedef PRIntn (PR_CALLBACK *PRReservedFN)(PRFileDesc *fd); - -struct PRIOMethods { - PRDescType file_type; /* Type of file represented (tos) */ - PRCloseFN close; /* close file and destroy descriptor */ - PRReadFN read; /* read up to specified bytes into buffer */ - PRWriteFN write; /* write specified bytes from buffer */ - PRAvailableFN available; /* determine number of bytes available */ - PRAvailable64FN available64; /* ditto, 64 bit */ - PRFsyncFN fsync; /* flush all buffers to permanent store */ - PRSeekFN seek; /* position the file to the desired place */ - PRSeek64FN seek64; /* ditto, 64 bit */ - PRFileInfoFN fileInfo; /* Get information about an open file */ - PRFileInfo64FN fileInfo64; /* ditto, 64 bit */ - PRWritevFN writev; /* Write segments as described by iovector */ - PRConnectFN connect; /* Connect to the specified (net) address */ - PRAcceptFN accept; /* Accept a connection for a (net) peer */ - PRBindFN bind; /* Associate a (net) address with the fd */ - PRListenFN listen; /* Prepare to listen for (net) connections */ - PRShutdownFN shutdown; /* Shutdown a (net) connection */ - PRRecvFN recv; /* Solicit up the the specified bytes */ - PRSendFN send; /* Send all the bytes specified */ - PRRecvfromFN recvfrom; /* Solicit (net) bytes and report source */ - PRSendtoFN sendto; /* Send bytes to (net) address specified */ - PRPollFN poll; /* Test the fd to see if it is ready */ - PRAcceptreadFN acceptread; /* Accept and read on a new (net) fd */ - PRTransmitfileFN transmitfile; /* Transmit at entire file */ - PRGetsocknameFN getsockname; /* Get (net) address associated with fd */ - PRGetpeernameFN getpeername; /* Get peer's (net) address */ - PRReservedFN reserved_fn_6; /* reserved for future use */ - PRReservedFN reserved_fn_5; /* reserved for future use */ - PRGetsocketoptionFN getsocketoption; - /* Get current setting of specified option */ - PRSetsocketoptionFN setsocketoption; - /* Set value of specified option */ - PRSendfileFN sendfile; /* Send a (partial) file with header/trailer*/ - PRConnectcontinueFN connectcontinue; - /* Continue a nonblocking connect */ - PRReservedFN reserved_fn_3; /* reserved for future use */ - PRReservedFN reserved_fn_2; /* reserved for future use */ - PRReservedFN reserved_fn_1; /* reserved for future use */ - PRReservedFN reserved_fn_0; /* reserved for future use */ -}; - -/* - ************************************************************************** - * FUNCTION: PR_GetSpecialFD - * DESCRIPTION: Get the file descriptor that represents the standard input, - * output, or error stream. - * INPUTS: - * PRSpecialFD id - * A value indicating the type of stream desired: - * PR_StandardInput: standard input - * PR_StandardOuput: standard output - * PR_StandardError: standard error - * OUTPUTS: none - * RETURNS: PRFileDesc * - * If the argument is valid, PR_GetSpecialFD returns a file descriptor - * that represents the corresponding standard I/O stream. Otherwise, - * PR_GetSpecialFD returns NULL and sets error PR_INVALID_ARGUMENT_ERROR. - ************************************************************************** - */ - -typedef enum PRSpecialFD -{ - PR_StandardInput, /* standard input */ - PR_StandardOutput, /* standard output */ - PR_StandardError /* standard error */ -} PRSpecialFD; - -NSPR_API(PRFileDesc*) PR_GetSpecialFD(PRSpecialFD id); - -#define PR_STDIN PR_GetSpecialFD(PR_StandardInput) -#define PR_STDOUT PR_GetSpecialFD(PR_StandardOutput) -#define PR_STDERR PR_GetSpecialFD(PR_StandardError) - -/* - ************************************************************************** - * Layering file descriptors - * - * File descriptors may be layered. Each layer has it's own identity. - * Identities are allocated by the runtime and are to be associated - * (by the layer implementor) with all layers that are of that type. - * It is then possible to scan the chain of layers and find a layer - * that one recongizes and therefore predict that it will implement - * a desired protocol. - * - * There are three well-known identities: - * PR_INVALID_IO_LAYER => an invalid layer identity, for error return - * PR_TOP_IO_LAYER => the identity of the top of the stack - * PR_NSPR_IO_LAYER => the identity used by NSPR proper - * PR_TOP_IO_LAYER may be used as a shorthand for identifying the topmost - * layer of an existing stack. Ie., the following two constructs are - * equivalent. - * - * rv = PR_PushIOLayer(stack, PR_TOP_IO_LAYER, my_layer); - * rv = PR_PushIOLayer(stack, PR_GetLayersIdentity(stack), my_layer) - * - * A string may be associated with the creation of the identity. It - * will be copied by the runtime. If queried the runtime will return - * a reference to that copied string (not yet another copy). There - * is no facility for deleting an identity. - ************************************************************************** - */ - -#define PR_IO_LAYER_HEAD (PRDescIdentity)-3 -#define PR_INVALID_IO_LAYER (PRDescIdentity)-1 -#define PR_TOP_IO_LAYER (PRDescIdentity)-2 -#define PR_NSPR_IO_LAYER (PRDescIdentity)0 - -NSPR_API(PRDescIdentity) PR_GetUniqueIdentity(const char *layer_name); -NSPR_API(const char*) PR_GetNameForIdentity(PRDescIdentity ident); -NSPR_API(PRDescIdentity) PR_GetLayersIdentity(PRFileDesc* fd); -NSPR_API(PRFileDesc*) PR_GetIdentitiesLayer(PRFileDesc* fd_stack, PRDescIdentity id); - -/* - ************************************************************************** - * PR_GetDefaultIOMethods: Accessing the default methods table. - * You may get a pointer to the default methods table by calling this function. - * You may then select any elements from that table with which to build your - * layer's methods table. You may NOT modify the table directly. - ************************************************************************** - */ -NSPR_API(const PRIOMethods *) PR_GetDefaultIOMethods(void); - -/* - ************************************************************************** - * Creating a layer - * - * A new layer may be allocated by calling PR_CreateIOLayerStub(). The - * file descriptor returned will contain the pointer to the methods table - * provided. The runtime will not modify the table nor test its correctness. - ************************************************************************** - */ -NSPR_API(PRFileDesc*) PR_CreateIOLayerStub( - PRDescIdentity ident, const PRIOMethods *methods); - -/* - ************************************************************************** - * Creating a layer - * - * A new stack may be created by calling PR_CreateIOLayer(). The - * file descriptor returned will point to the top of the stack, which has - * the layer 'fd' as the topmost layer. - * - * NOTE: This function creates a new style stack, which has a fixed, dummy - * header. The old style stack, created by a call to PR_PushIOLayer, - * results in modifying contents of the top layer of the stack, when - * pushing and popping layers of the stack. - ************************************************************************** - */ -NSPR_API(PRFileDesc*) PR_CreateIOLayer(PRFileDesc* fd); - -/* - ************************************************************************** - * Pushing a layer - * - * A file descriptor (perhaps allocated using PR_CreateIOLayerStub()) may - * be pushed into an existing stack of file descriptors at any point the - * caller deems appropriate. The new layer will be inserted into the stack - * just above the layer with the indicated identity. - * - * Note: Even if the identity parameter indicates the top-most layer of - * the stack, the value of the file descriptor describing the original - * stack will not change. - ************************************************************************** - */ -NSPR_API(PRStatus) PR_PushIOLayer( - PRFileDesc *fd_stack, PRDescIdentity id, PRFileDesc *layer); - -/* - ************************************************************************** - * Popping a layer - * - * A layer may be popped from a stack by indicating the identity of the - * layer to be removed. If found, a pointer to the removed object will - * be returned to the caller. The object then becomes the responsibility - * of the caller. - * - * Note: Even if the identity indicates the top layer of the stack, the - * reference returned will not be the file descriptor for the stack and - * that file descriptor will remain valid. - ************************************************************************** - */ -NSPR_API(PRFileDesc*) PR_PopIOLayer(PRFileDesc *fd_stack, PRDescIdentity id); - -/* - ************************************************************************** - * FUNCTION: PR_Open - * DESCRIPTION: Open a file for reading, writing, or both. - * INPUTS: - * const char *name - * The path name of the file to be opened - * PRIntn flags - * The file status flags. - * It is a bitwise OR of the following bit flags (only one of - * the first three flags below may be used): - * PR_RDONLY Open for reading only. - * PR_WRONLY Open for writing only. - * PR_RDWR Open for reading and writing. - * PR_CREATE_FILE If the file does not exist, the file is created - * If the file exists, this flag has no effect. - * PR_SYNC If set, each write will wait for both the file data - * and file status to be physically updated. - * PR_APPEND The file pointer is set to the end of - * the file prior to each write. - * PR_TRUNCATE If the file exists, its length is truncated to 0. - * PR_EXCL With PR_CREATE_FILE, if the file does not exist, - * the file is created. If the file already - * exists, no action and NULL is returned - * - * PRIntn mode - * The access permission bits of the file mode, if the file is - * created when PR_CREATE_FILE is on. - * OUTPUTS: None - * RETURNS: PRFileDesc * - * If the file is successfully opened, - * returns a pointer to the PRFileDesc - * created for the newly opened file. - * Returns a NULL pointer if the open - * failed. - * SIDE EFFECTS: - * RESTRICTIONS: - * MEMORY: - * The return value, if not NULL, points to a dynamically allocated - * PRFileDesc object. - * ALGORITHM: - ************************************************************************** - */ - -/* Open flags */ -#define PR_RDONLY 0x01 -#define PR_WRONLY 0x02 -#define PR_RDWR 0x04 -#define PR_CREATE_FILE 0x08 -#define PR_APPEND 0x10 -#define PR_TRUNCATE 0x20 -#define PR_SYNC 0x40 -#define PR_EXCL 0x80 - -/* -** File modes .... -** -** CAVEAT: 'mode' is currently only applicable on UNIX platforms. -** The 'mode' argument may be ignored by PR_Open on other platforms. -** -** 00400 Read by owner. -** 00200 Write by owner. -** 00100 Execute (search if a directory) by owner. -** 00040 Read by group. -** 00020 Write by group. -** 00010 Execute by group. -** 00004 Read by others. -** 00002 Write by others -** 00001 Execute by others. -** -*/ - -NSPR_API(PRFileDesc*) PR_Open(const char *name, PRIntn flags, PRIntn mode); - -/* - ************************************************************************** - * FUNCTION: PR_OpenFile - * DESCRIPTION: - * Open a file for reading, writing, or both. - * PR_OpenFile has the same prototype as PR_Open but implements - * the specified file mode where possible. - ************************************************************************** - */ - -/* File mode bits */ -#define PR_IRWXU 00700 /* read, write, execute/search by owner */ -#define PR_IRUSR 00400 /* read permission, owner */ -#define PR_IWUSR 00200 /* write permission, owner */ -#define PR_IXUSR 00100 /* execute/search permission, owner */ -#define PR_IRWXG 00070 /* read, write, execute/search by group */ -#define PR_IRGRP 00040 /* read permission, group */ -#define PR_IWGRP 00020 /* write permission, group */ -#define PR_IXGRP 00010 /* execute/search permission, group */ -#define PR_IRWXO 00007 /* read, write, execute/search by others */ -#define PR_IROTH 00004 /* read permission, others */ -#define PR_IWOTH 00002 /* write permission, others */ -#define PR_IXOTH 00001 /* execute/search permission, others */ - -NSPR_API(PRFileDesc*) PR_OpenFile( - const char *name, PRIntn flags, PRIntn mode); - -#ifdef MOZ_UNICODE -/* - * EXPERIMENTAL: This function may be removed in a future release. - */ -NSPR_API(PRFileDesc*) PR_OpenFileUTF16( - const PRUnichar *name, PRIntn flags, PRIntn mode); -#endif /* MOZ_UNICODE */ - -/* - ************************************************************************** - * FUNCTION: PR_Close - * DESCRIPTION: - * Close a file or socket. - * INPUTS: - * PRFileDesc *fd - * a pointer to a PRFileDesc. - * OUTPUTS: - * None. - * RETURN: - * PRStatus - * SIDE EFFECTS: - * RESTRICTIONS: - * None. - * MEMORY: - * The dynamic memory pointed to by the argument fd is freed. - ************************************************************************** - */ - -NSPR_API(PRStatus) PR_Close(PRFileDesc *fd); - -/* - ************************************************************************** - * FUNCTION: PR_Read - * DESCRIPTION: - * Read bytes from a file or socket. - * The operation will block until either an end of stream indication is - * encountered, some positive number of bytes are transferred, or there - * is an error. No more than 'amount' bytes will be transferred. - * INPUTS: - * PRFileDesc *fd - * pointer to the PRFileDesc object for the file or socket - * void *buf - * pointer to a buffer to hold the data read in. - * PRInt32 amount - * the size of 'buf' (in bytes) - * OUTPUTS: - * RETURN: - * PRInt32 - * a positive number indicates the number of bytes actually read in. - * 0 means end of file is reached or the network connection is closed. - * -1 indicates a failure. The reason for the failure is obtained - * by calling PR_GetError(). - * SIDE EFFECTS: - * data is written into the buffer pointed to by 'buf'. - * RESTRICTIONS: - * None. - * MEMORY: - * N/A - * ALGORITHM: - * N/A - ************************************************************************** - */ - -NSPR_API(PRInt32) PR_Read(PRFileDesc *fd, void *buf, PRInt32 amount); - -/* - *************************************************************************** - * FUNCTION: PR_Write - * DESCRIPTION: - * Write a specified number of bytes to a file or socket. The thread - * invoking this function blocks until all the data is written. - * INPUTS: - * PRFileDesc *fd - * pointer to a PRFileDesc object that refers to a file or socket - * const void *buf - * pointer to the buffer holding the data - * PRInt32 amount - * amount of data in bytes to be written from the buffer - * OUTPUTS: - * None. - * RETURN: PRInt32 - * A positive number indicates the number of bytes successfully written. - * A -1 is an indication that the operation failed. The reason - * for the failure is obtained by calling PR_GetError(). - *************************************************************************** - */ - -NSPR_API(PRInt32) PR_Write(PRFileDesc *fd,const void *buf,PRInt32 amount); - -/* - *************************************************************************** - * FUNCTION: PR_Writev - * DESCRIPTION: - * Write data to a socket. The data is organized in a PRIOVec array. The - * operation will block until all the data is written or the operation - * fails. - * INPUTS: - * PRFileDesc *fd - * Pointer that points to a PRFileDesc object for a socket. - * const PRIOVec *iov - * An array of PRIOVec. PRIOVec is a struct with the following - * two fields: - * char *iov_base; - * int iov_len; - * PRInt32 iov_size - * Number of elements in the iov array. The value of this - * argument must not be greater than PR_MAX_IOVECTOR_SIZE. - * If it is, the method will fail (PR_BUFFER_OVERFLOW_ERROR). - * PRIntervalTime timeout - * Time limit for completion of the entire write operation. - * OUTPUTS: - * None - * RETURN: - * A positive number indicates the number of bytes successfully written. - * A -1 is an indication that the operation failed. The reason - * for the failure is obtained by calling PR_GetError(). - *************************************************************************** - */ - -#define PR_MAX_IOVECTOR_SIZE 16 /* 'iov_size' must be <= */ - -NSPR_API(PRInt32) PR_Writev( - PRFileDesc *fd, const PRIOVec *iov, PRInt32 iov_size, - PRIntervalTime timeout); - -/* - *************************************************************************** - * FUNCTION: PR_Delete - * DESCRIPTION: - * Delete a file from the filesystem. The operation may fail if the - * file is open. - * INPUTS: - * const char *name - * Path name of the file to be deleted. - * OUTPUTS: - * None. - * RETURN: PRStatus - * The function returns PR_SUCCESS if the file is successfully - * deleted, otherwise it returns PR_FAILURE. - *************************************************************************** - */ - -NSPR_API(PRStatus) PR_Delete(const char *name); - -/**************************************************************************/ - -typedef enum PRFileType -{ - PR_FILE_FILE = 1, - PR_FILE_DIRECTORY = 2, - PR_FILE_OTHER = 3 -} PRFileType; - -struct PRFileInfo { - PRFileType type; /* Type of file */ - PROffset32 size; /* Size, in bytes, of file's contents */ - PRTime creationTime; /* Creation time per definition of PRTime */ - PRTime modifyTime; /* Last modification time per definition of PRTime */ -}; - -struct PRFileInfo64 { - PRFileType type; /* Type of file */ - PROffset64 size; /* Size, in bytes, of file's contents */ - PRTime creationTime; /* Creation time per definition of PRTime */ - PRTime modifyTime; /* Last modification time per definition of PRTime */ -}; - -/**************************************************************************** - * FUNCTION: PR_GetFileInfo, PR_GetFileInfo64 - * DESCRIPTION: - * Get the information about the file with the given path name. This is - * applicable only to NSFileDesc describing 'file' types (see - * INPUTS: - * const char *fn - * path name of the file - * OUTPUTS: - * PRFileInfo *info - * Information about the given file is written into the file - * information object pointer to by 'info'. - * RETURN: PRStatus - * PR_GetFileInfo returns PR_SUCCESS if file information is successfully - * obtained, otherwise it returns PR_FAILURE. - *************************************************************************** - */ - -NSPR_API(PRStatus) PR_GetFileInfo(const char *fn, PRFileInfo *info); -NSPR_API(PRStatus) PR_GetFileInfo64(const char *fn, PRFileInfo64 *info); - -#ifdef MOZ_UNICODE -/* - * EXPERIMENTAL: This function may be removed in a future release. - */ -NSPR_API(PRStatus) PR_GetFileInfo64UTF16(const PRUnichar *fn, PRFileInfo64 *info); -#endif /* MOZ_UNICODE */ - -/* - ************************************************************************** - * FUNCTION: PR_GetOpenFileInfo, PR_GetOpenFileInfo64 - * DESCRIPTION: - * Get information about an open file referred to by the - * given PRFileDesc object. - * INPUTS: - * const PRFileDesc *fd - * A reference to a valid, open file. - * OUTPUTS: - * Same as PR_GetFileInfo, PR_GetFileInfo64 - * RETURN: PRStatus - * PR_GetFileInfo returns PR_SUCCESS if file information is successfully - * obtained, otherwise it returns PR_FAILURE. - *************************************************************************** - */ - -NSPR_API(PRStatus) PR_GetOpenFileInfo(PRFileDesc *fd, PRFileInfo *info); -NSPR_API(PRStatus) PR_GetOpenFileInfo64(PRFileDesc *fd, PRFileInfo64 *info); - -/* - ************************************************************************** - * FUNCTION: PR_Rename - * DESCRIPTION: - * Rename a file from the old name 'from' to the new name 'to'. - * INPUTS: - * const char *from - * The old name of the file to be renamed. - * const char *to - * The new name of the file. - * OUTPUTS: - * None. - * RETURN: PRStatus - ************************************************************************** - */ - -NSPR_API(PRStatus) PR_Rename(const char *from, const char *to); - -/* - ************************************************************************* - * FUNCTION: PR_Access - * DESCRIPTION: - * Determine accessibility of a file. - * INPUTS: - * const char *name - * path name of the file - * PRAccessHow how - * specifies which access permission to check for. - * It can be one of the following values: - * PR_ACCESS_READ_OK Test for read permission - * PR_ACCESS_WRITE_OK Test for write permission - * PR_ACCESS_EXISTS Check existence of file - * OUTPUTS: - * None. - * RETURN: PRStatus - * PR_SUCCESS is returned if the requested access is permitted. - * Otherwise, PR_FAILURE is returned. Additional information - * regarding the reason for the failure may be retrieved from - * PR_GetError(). - ************************************************************************* - */ - -typedef enum PRAccessHow { - PR_ACCESS_EXISTS = 1, - PR_ACCESS_WRITE_OK = 2, - PR_ACCESS_READ_OK = 3 -} PRAccessHow; - -NSPR_API(PRStatus) PR_Access(const char *name, PRAccessHow how); - -/* - ************************************************************************* - * FUNCTION: PR_Seek, PR_Seek64 - * DESCRIPTION: - * Moves read-write file offset - * INPUTS: - * PRFileDesc *fd - * Pointer to a PRFileDesc object. - * PROffset32, PROffset64 offset - * Specifies a value, in bytes, that is used in conjunction - * with the 'whence' parameter to set the file pointer. A - * negative value causes seeking in the reverse direction. - * PRSeekWhence whence - * Specifies how to interpret the 'offset' parameter in setting - * the file pointer associated with the 'fd' parameter. - * Values for the 'whence' parameter are: - * PR_SEEK_SET Sets the file pointer to the value of the - * 'offset' parameter - * PR_SEEK_CUR Sets the file pointer to its current location - * plus the value of the offset parameter. - * PR_SEEK_END Sets the file pointer to the size of the - * file plus the value of the offset parameter. - * OUTPUTS: - * None. - * RETURN: PROffset32, PROffset64 - * Upon successful completion, the resulting pointer location, - * measured in bytes from the beginning of the file, is returned. - * If the PR_Seek() function fails, the file offset remains - * unchanged, and the returned value is -1. The error code can - * then be retrieved via PR_GetError(). - ************************************************************************* - */ - -NSPR_API(PROffset32) PR_Seek(PRFileDesc *fd, PROffset32 offset, PRSeekWhence whence); -NSPR_API(PROffset64) PR_Seek64(PRFileDesc *fd, PROffset64 offset, PRSeekWhence whence); - -/* - ************************************************************************ - * FUNCTION: PR_Available - * DESCRIPTION: - * Determine the amount of data in bytes available for reading - * in the given file or socket. - * INPUTS: - * PRFileDesc *fd - * Pointer to a PRFileDesc object that refers to a file or - * socket. - * OUTPUTS: - * None - * RETURN: PRInt32, PRInt64 - * Upon successful completion, PR_Available returns the number of - * bytes beyond the current read pointer that is available for - * reading. Otherwise, it returns a -1 and the reason for the - * failure can be retrieved via PR_GetError(). - ************************************************************************ - */ - -NSPR_API(PRInt32) PR_Available(PRFileDesc *fd); -NSPR_API(PRInt64) PR_Available64(PRFileDesc *fd); - -/* - ************************************************************************ - * FUNCTION: PR_Sync - * DESCRIPTION: - * Sync any buffered data for a fd to its backing device (disk). - * INPUTS: - * PRFileDesc *fd - * Pointer to a PRFileDesc object that refers to a file or - * socket - * OUTPUTS: - * None - * RETURN: PRStatus - * PR_SUCCESS is returned if the requested access is permitted. - * Otherwise, PR_FAILURE is returned. - ************************************************************************ - */ - -NSPR_API(PRStatus) PR_Sync(PRFileDesc *fd); - -/************************************************************************/ - -struct PRDirEntry { - const char *name; /* name of entry, relative to directory name */ -}; - -#ifdef MOZ_UNICODE -struct PRDirEntryUTF16 { - const PRUnichar *name; /* name of entry in UTF16, relative to - * directory name */ -}; -#endif /* MOZ_UNICODE */ - -#if !defined(NO_NSPR_10_SUPPORT) -#define PR_DirName(dirEntry) (dirEntry->name) -#endif - -/* - ************************************************************************* - * FUNCTION: PR_OpenDir - * DESCRIPTION: - * Open the directory by the given name - * INPUTS: - * const char *name - * path name of the directory to be opened - * OUTPUTS: - * None - * RETURN: PRDir * - * If the directory is sucessfully opened, a PRDir object is - * dynamically allocated and a pointer to it is returned. - * If the directory cannot be opened, a NULL pointer is returned. - * MEMORY: - * Upon successful completion, the return value points to - * dynamically allocated memory. - ************************************************************************* - */ - -NSPR_API(PRDir*) PR_OpenDir(const char *name); - -#ifdef MOZ_UNICODE -/* - * EXPERIMENTAL: This function may be removed in a future release. - */ -NSPR_API(PRDirUTF16*) PR_OpenDirUTF16(const PRUnichar *name); -#endif /* MOZ_UNICODE */ - -/* - ************************************************************************* - * FUNCTION: PR_ReadDir - * DESCRIPTION: - * INPUTS: - * PRDir *dir - * pointer to a PRDir object that designates an open directory - * PRDirFlags flags - * PR_SKIP_NONE Do not skip any files - * PR_SKIP_DOT Skip the directory entry "." that - * represents the current directory - * PR_SKIP_DOT_DOT Skip the directory entry ".." that - * represents the parent directory. - * PR_SKIP_BOTH Skip both '.' and '..' - * PR_SKIP_HIDDEN Skip hidden files - * OUTPUTS: - * RETURN: PRDirEntry* - * Returns a pointer to the next entry in the directory. Returns - * a NULL pointer upon reaching the end of the directory or when an - * error occurs. The actual reason can be retrieved via PR_GetError(). - ************************************************************************* - */ - -typedef enum PRDirFlags { - PR_SKIP_NONE = 0x0, - PR_SKIP_DOT = 0x1, - PR_SKIP_DOT_DOT = 0x2, - PR_SKIP_BOTH = 0x3, - PR_SKIP_HIDDEN = 0x4 -} PRDirFlags; - -NSPR_API(PRDirEntry*) PR_ReadDir(PRDir *dir, PRDirFlags flags); - -#ifdef MOZ_UNICODE -/* - * EXPERIMENTAL: This function may be removed in a future release. - */ -NSPR_API(PRDirEntryUTF16*) PR_ReadDirUTF16(PRDirUTF16 *dir, PRDirFlags flags); -#endif /* MOZ_UNICODE */ - -/* - ************************************************************************* - * FUNCTION: PR_CloseDir - * DESCRIPTION: - * Close the specified directory. - * INPUTS: - * PRDir *dir - * The directory to be closed. - * OUTPUTS: - * None - * RETURN: PRStatus - * If successful, will return a status of PR_SUCCESS. Otherwise - * a value of PR_FAILURE. The reason for the failure may be re- - * trieved using PR_GetError(). - ************************************************************************* - */ - -NSPR_API(PRStatus) PR_CloseDir(PRDir *dir); - -#ifdef MOZ_UNICODE -/* - * EXPERIMENTAL: This function may be removed in a future release. - */ -NSPR_API(PRStatus) PR_CloseDirUTF16(PRDirUTF16 *dir); -#endif /* MOZ_UNICODE */ - -/* - ************************************************************************* - * FUNCTION: PR_MkDir - * DESCRIPTION: - * Create a new directory with the given name and access mode. - * INPUTS: - * const char *name - * The name of the directory to be created. All the path components - * up to but not including the leaf component must already exist. - * PRIntn mode - * See 'mode' definiton in PR_Open(). - * OUTPUTS: - * None - * RETURN: PRStatus - * If successful, will return a status of PR_SUCCESS. Otherwise - * a value of PR_FAILURE. The reason for the failure may be re- - * trieved using PR_GetError(). - ************************************************************************* - */ - -NSPR_API(PRStatus) PR_MkDir(const char *name, PRIntn mode); - -/* - ************************************************************************* - * FUNCTION: PR_MakeDir - * DESCRIPTION: - * Create a new directory with the given name and access mode. - * PR_MakeDir has the same prototype as PR_MkDir but implements - * the specified access mode where possible. - ************************************************************************* - */ - -NSPR_API(PRStatus) PR_MakeDir(const char *name, PRIntn mode); - -/* - ************************************************************************* - * FUNCTION: PR_RmDir - * DESCRIPTION: - * Remove a directory by the given name. - * INPUTS: - * const char *name - * The name of the directory to be removed. All the path components - * must already exist. Only the leaf component will be removed. - * OUTPUTS: - * None - * RETURN: PRStatus - * If successful, will return a status of PR_SUCCESS. Otherwise - * a value of PR_FAILURE. The reason for the failure may be re- - * trieved using PR_GetError(). - ************************************************************************** - */ - -NSPR_API(PRStatus) PR_RmDir(const char *name); - -/* - ************************************************************************* - * FUNCTION: PR_NewUDPSocket - * DESCRIPTION: - * Create a new UDP socket. - * INPUTS: - * None - * OUTPUTS: - * None - * RETURN: PRFileDesc* - * Upon successful completion, PR_NewUDPSocket returns a pointer - * to the PRFileDesc created for the newly opened UDP socket. - * Returns a NULL pointer if the creation of a new UDP socket failed. - * - ************************************************************************** - */ - -NSPR_API(PRFileDesc*) PR_NewUDPSocket(void); - -/* - ************************************************************************* - * FUNCTION: PR_NewTCPSocket - * DESCRIPTION: - * Create a new TCP socket. - * INPUTS: - * None - * OUTPUTS: - * None - * RETURN: PRFileDesc* - * Upon successful completion, PR_NewTCPSocket returns a pointer - * to the PRFileDesc created for the newly opened TCP socket. - * Returns a NULL pointer if the creation of a new TCP socket failed. - * - ************************************************************************** - */ - -NSPR_API(PRFileDesc*) PR_NewTCPSocket(void); - -/* - ************************************************************************* - * FUNCTION: PR_OpenUDPSocket - * DESCRIPTION: - * Create a new UDP socket of the specified address family. - * INPUTS: - * PRIntn af - * Address family - * OUTPUTS: - * None - * RETURN: PRFileDesc* - * Upon successful completion, PR_OpenUDPSocket returns a pointer - * to the PRFileDesc created for the newly opened UDP socket. - * Returns a NULL pointer if the creation of a new UDP socket failed. - * - ************************************************************************** - */ - -NSPR_API(PRFileDesc*) PR_OpenUDPSocket(PRIntn af); - -/* - ************************************************************************* - * FUNCTION: PR_OpenTCPSocket - * DESCRIPTION: - * Create a new TCP socket of the specified address family. - * INPUTS: - * PRIntn af - * Address family - * OUTPUTS: - * None - * RETURN: PRFileDesc* - * Upon successful completion, PR_NewTCPSocket returns a pointer - * to the PRFileDesc created for the newly opened TCP socket. - * Returns a NULL pointer if the creation of a new TCP socket failed. - * - ************************************************************************** - */ - -NSPR_API(PRFileDesc*) PR_OpenTCPSocket(PRIntn af); - -/* - ************************************************************************* - * FUNCTION: PR_Connect - * DESCRIPTION: - * Initiate a connection on a socket. - * INPUTS: - * PRFileDesc *fd - * Points to a PRFileDesc object representing a socket - * PRNetAddr *addr - * Specifies the address of the socket in its own communication - * space. - * PRIntervalTime timeout - * The function uses the lesser of the provided timeout and - * the OS's connect timeout. In particular, if you specify - * PR_INTERVAL_NO_TIMEOUT as the timeout, the OS's connection - * time limit will be used. - * - * OUTPUTS: - * None - * RETURN: PRStatus - * Upon successful completion of connection initiation, PR_Connect - * returns PR_SUCCESS. Otherwise, it returns PR_FAILURE. Further - * failure information can be obtained by calling PR_GetError(). - ************************************************************************** - */ - -NSPR_API(PRStatus) PR_Connect( - PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout); - -/* - ************************************************************************* - * FUNCTION: PR_ConnectContinue - * DESCRIPTION: - * Continue a nonblocking connect. After a nonblocking connect - * is initiated with PR_Connect() (which fails with - * PR_IN_PROGRESS_ERROR), one should call PR_Poll() on the socket, - * with the in_flags PR_POLL_WRITE | PR_POLL_EXCEPT. When - * PR_Poll() returns, one calls PR_ConnectContinue() on the - * socket to determine whether the nonblocking connect has - * completed or is still in progress. Repeat the PR_Poll(), - * PR_ConnectContinue() sequence until the nonblocking connect - * has completed. - * INPUTS: - * PRFileDesc *fd - * the file descriptor representing a socket - * PRInt16 out_flags - * the out_flags field of the poll descriptor returned by - * PR_Poll() - * RETURN: PRStatus - * If the nonblocking connect has successfully completed, - * PR_ConnectContinue returns PR_SUCCESS. If PR_ConnectContinue() - * returns PR_FAILURE, call PR_GetError(): - * - PR_IN_PROGRESS_ERROR: the nonblocking connect is still in - * progress and has not completed yet. The caller should poll - * on the file descriptor for the in_flags - * PR_POLL_WRITE|PR_POLL_EXCEPT and retry PR_ConnectContinue - * later when PR_Poll() returns. - * - Other errors: the nonblocking connect has failed with this - * error code. - */ - -NSPR_API(PRStatus) PR_ConnectContinue(PRFileDesc *fd, PRInt16 out_flags); - -/* - ************************************************************************* - * THIS FUNCTION IS DEPRECATED. USE PR_ConnectContinue INSTEAD. - * - * FUNCTION: PR_GetConnectStatus - * DESCRIPTION: - * Get the completion status of a nonblocking connect. After - * a nonblocking connect is initiated with PR_Connect() (which - * fails with PR_IN_PROGRESS_ERROR), one should call PR_Poll() - * on the socket, with the in_flags PR_POLL_WRITE | PR_POLL_EXCEPT. - * When PR_Poll() returns, one calls PR_GetConnectStatus on the - * PRPollDesc structure to determine whether the nonblocking - * connect has succeeded or failed. - * INPUTS: - * const PRPollDesc *pd - * Pointer to a PRPollDesc whose fd member is the socket, - * and in_flags must contain PR_POLL_WRITE and PR_POLL_EXCEPT. - * PR_Poll() should have been called and set the out_flags. - * RETURN: PRStatus - * If the nonblocking connect has successfully completed, - * PR_GetConnectStatus returns PR_SUCCESS. If PR_GetConnectStatus() - * returns PR_FAILURE, call PR_GetError(): - * - PR_IN_PROGRESS_ERROR: the nonblocking connect is still in - * progress and has not completed yet. - * - Other errors: the nonblocking connect has failed with this - * error code. - */ - -NSPR_API(PRStatus) PR_GetConnectStatus(const PRPollDesc *pd); - -/* - ************************************************************************* - * FUNCTION: PR_Accept - * DESCRIPTION: - * Accept a connection on a socket. - * INPUTS: - * PRFileDesc *fd - * Points to a PRFileDesc object representing the rendezvous socket - * on which the caller is willing to accept new connections. - * PRIntervalTime timeout - * Time limit for completion of the accept operation. - * OUTPUTS: - * PRNetAddr *addr - * Returns the address of the connecting entity in its own - * communication space. It may be NULL. - * RETURN: PRFileDesc* - * Upon successful acceptance of a connection, PR_Accept - * returns a valid file descriptor. Otherwise, it returns NULL. - * Further failure information can be obtained by calling PR_GetError(). - ************************************************************************** - */ - -NSPR_API(PRFileDesc*) PR_Accept( - PRFileDesc *fd, PRNetAddr *addr, PRIntervalTime timeout); - -/* - ************************************************************************* - * FUNCTION: PR_Bind - * DESCRIPTION: - * Bind an address to a socket. - * INPUTS: - * PRFileDesc *fd - * Points to a PRFileDesc object representing a socket. - * PRNetAddr *addr - * Specifies the address to which the socket will be bound. - * OUTPUTS: - * None - * RETURN: PRStatus - * Upon successful binding of an address to a socket, PR_Bind - * returns PR_SUCCESS. Otherwise, it returns PR_FAILURE. Further - * failure information can be obtained by calling PR_GetError(). - ************************************************************************** - */ - -NSPR_API(PRStatus) PR_Bind(PRFileDesc *fd, const PRNetAddr *addr); - -/* - ************************************************************************* - * FUNCTION: PR_Listen - * DESCRIPTION: - * Listen for connections on a socket. - * INPUTS: - * PRFileDesc *fd - * Points to a PRFileDesc object representing a socket that will be - * used to listen for new connections. - * PRIntn backlog - * Specifies the maximum length of the queue of pending connections. - * OUTPUTS: - * None - * RETURN: PRStatus - * Upon successful completion of listen request, PR_Listen - * returns PR_SUCCESS. Otherwise, it returns PR_FAILURE. Further - * failure information can be obtained by calling PR_GetError(). - ************************************************************************** - */ - -NSPR_API(PRStatus) PR_Listen(PRFileDesc *fd, PRIntn backlog); - -/* - ************************************************************************* - * FUNCTION: PR_Shutdown - * DESCRIPTION: - * Shut down part of a full-duplex connection on a socket. - * INPUTS: - * PRFileDesc *fd - * Points to a PRFileDesc object representing a connected socket. - * PRIntn how - * Specifies the kind of disallowed operations on the socket. - * PR_SHUTDOWN_RCV - Further receives will be disallowed - * PR_SHUTDOWN_SEND - Further sends will be disallowed - * PR_SHUTDOWN_BOTH - Further sends and receives will be disallowed - * OUTPUTS: - * None - * RETURN: PRStatus - * Upon successful completion of shutdown request, PR_Shutdown - * returns PR_SUCCESS. Otherwise, it returns PR_FAILURE. Further - * failure information can be obtained by calling PR_GetError(). - ************************************************************************** - */ - -typedef enum PRShutdownHow -{ - PR_SHUTDOWN_RCV = 0, /* disallow further receives */ - PR_SHUTDOWN_SEND = 1, /* disallow further sends */ - PR_SHUTDOWN_BOTH = 2 /* disallow further receives and sends */ -} PRShutdownHow; - -NSPR_API(PRStatus) PR_Shutdown(PRFileDesc *fd, PRShutdownHow how); - -/* - ************************************************************************* - * FUNCTION: PR_Recv - * DESCRIPTION: - * Receive a specified number of bytes from a connected socket. - * The operation will block until some positive number of bytes are - * transferred, a time out has occurred, or there is an error. - * No more than 'amount' bytes will be transferred. - * INPUTS: - * PRFileDesc *fd - * points to a PRFileDesc object representing a socket. - * void *buf - * pointer to a buffer to hold the data received. - * PRInt32 amount - * the size of 'buf' (in bytes) - * PRIntn flags - * must be zero or PR_MSG_PEEK. - * PRIntervalTime timeout - * Time limit for completion of the receive operation. - * OUTPUTS: - * None - * RETURN: PRInt32 - * a positive number indicates the number of bytes actually received. - * 0 means the network connection is closed. - * -1 indicates a failure. The reason for the failure is obtained - * by calling PR_GetError(). - ************************************************************************** - */ - -#define PR_MSG_PEEK 0x2 - -NSPR_API(PRInt32) PR_Recv(PRFileDesc *fd, void *buf, PRInt32 amount, - PRIntn flags, PRIntervalTime timeout); - -/* - ************************************************************************* - * FUNCTION: PR_Send - * DESCRIPTION: - * Send a specified number of bytes from a connected socket. - * The operation will block until all bytes are - * processed, a time out has occurred, or there is an error. - * INPUTS: - * PRFileDesc *fd - * points to a PRFileDesc object representing a socket. - * void *buf - * pointer to a buffer from where the data is sent. - * PRInt32 amount - * the size of 'buf' (in bytes) - * PRIntn flags - * (OBSOLETE - must always be zero) - * PRIntervalTime timeout - * Time limit for completion of the send operation. - * OUTPUTS: - * None - * RETURN: PRInt32 - * A positive number indicates the number of bytes successfully processed. - * This number must always equal 'amount'. A -1 is an indication that the - * operation failed. The reason for the failure is obtained by calling - * PR_GetError(). - ************************************************************************** - */ - -NSPR_API(PRInt32) PR_Send(PRFileDesc *fd, const void *buf, PRInt32 amount, - PRIntn flags, PRIntervalTime timeout); - -/* - ************************************************************************* - * FUNCTION: PR_RecvFrom - * DESCRIPTION: - * Receive up to a specified number of bytes from socket which may - * or may not be connected. - * The operation will block until one or more bytes are - * transferred, a time out has occurred, or there is an error. - * No more than 'amount' bytes will be transferred. - * INPUTS: - * PRFileDesc *fd - * points to a PRFileDesc object representing a socket. - * void *buf - * pointer to a buffer to hold the data received. - * PRInt32 amount - * the size of 'buf' (in bytes) - * PRIntn flags - * (OBSOLETE - must always be zero) - * PRNetAddr *addr - * Specifies the address of the sending peer. It may be NULL. - * PRIntervalTime timeout - * Time limit for completion of the receive operation. - * OUTPUTS: - * None - * RETURN: PRInt32 - * a positive number indicates the number of bytes actually received. - * 0 means the network connection is closed. - * -1 indicates a failure. The reason for the failure is obtained - * by calling PR_GetError(). - ************************************************************************** - */ - -NSPR_API(PRInt32) PR_RecvFrom( - PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags, - PRNetAddr *addr, PRIntervalTime timeout); - -/* - ************************************************************************* - * FUNCTION: PR_SendTo - * DESCRIPTION: - * Send a specified number of bytes from an unconnected socket. - * The operation will block until all bytes are - * sent, a time out has occurred, or there is an error. - * INPUTS: - * PRFileDesc *fd - * points to a PRFileDesc object representing an unconnected socket. - * void *buf - * pointer to a buffer from where the data is sent. - * PRInt32 amount - * the size of 'buf' (in bytes) - * PRIntn flags - * (OBSOLETE - must always be zero) - * PRNetAddr *addr - * Specifies the address of the peer. -.* PRIntervalTime timeout - * Time limit for completion of the send operation. - * OUTPUTS: - * None - * RETURN: PRInt32 - * A positive number indicates the number of bytes successfully sent. - * -1 indicates a failure. The reason for the failure is obtained - * by calling PR_GetError(). - ************************************************************************** - */ - -NSPR_API(PRInt32) PR_SendTo( - PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags, - const PRNetAddr *addr, PRIntervalTime timeout); - -/* -************************************************************************* -** FUNCTION: PR_TransmitFile -** DESCRIPTION: -** Transmitfile sends a complete file (sourceFile) across a socket -** (networkSocket). If headers is non-NULL, the headers will be sent across -** the socket prior to sending the file. -** -** Optionally, the PR_TRANSMITFILE_CLOSE_SOCKET flag may be passed to -** transmitfile. This flag specifies that transmitfile should close the -** socket after sending the data. -** -** INPUTS: -** PRFileDesc *networkSocket -** The socket to send data over -** PRFileDesc *sourceFile -** The file to send -** const void *headers -** A pointer to headers to be sent before sending data -** PRInt32 hlen -** length of header buffers in bytes. -** PRTransmitFileFlags flags -** If the flags indicate that the connection should be closed, -** it will be done immediately after transferring the file, unless -** the operation is unsuccessful. -.* PRIntervalTime timeout - * Time limit for completion of the transmit operation. -** -** RETURNS: -** Returns the number of bytes written or -1 if the operation failed. -** If an error occurs while sending the file, the PR_TRANSMITFILE_CLOSE_ -** SOCKET flag is ignored. The reason for the failure is obtained -** by calling PR_GetError(). -************************************************************************** -*/ - -NSPR_API(PRInt32) PR_TransmitFile( - PRFileDesc *networkSocket, PRFileDesc *sourceFile, - const void *headers, PRInt32 hlen, PRTransmitFileFlags flags, - PRIntervalTime timeout); - -/* -************************************************************************* -** FUNCTION: PR_SendFile -** DESCRIPTION: -** PR_SendFile sends data from a file (sendData->fd) across a socket -** (networkSocket). If specified, a header and/or trailer buffer are sent -** before and after the file, respectively. The file offset, number of bytes -** of file data to send, the header and trailer buffers are specified in the -** sendData argument. -** -** Optionally, if the PR_TRANSMITFILE_CLOSE_SOCKET flag is passed, the -** socket is closed after successfully sending the data. -** -** INPUTS: -** PRFileDesc *networkSocket -** The socket to send data over -** PRSendFileData *sendData -** Contains the FD, file offset and length, header and trailer -** buffer specifications. -** PRTransmitFileFlags flags -** If the flags indicate that the connection should be closed, -** it will be done immediately after transferring the file, unless -** the operation is unsuccessful. -.* PRIntervalTime timeout - * Time limit for completion of the send operation. -** -** RETURNS: -** Returns the number of bytes written or -1 if the operation failed. -** If an error occurs while sending the file, the PR_TRANSMITFILE_CLOSE_ -** SOCKET flag is ignored. The reason for the failure is obtained -** by calling PR_GetError(). -************************************************************************** -*/ - -struct PRSendFileData { - PRFileDesc *fd; /* file to send */ - PRUint32 file_offset; /* file offset */ - PRSize file_nbytes; /* number of bytes of file data to send */ - /* if 0, send data from file_offset to */ - /* end-of-file. */ - const void *header; /* header buffer */ - PRInt32 hlen; /* header len */ - const void *trailer; /* trailer buffer */ - PRInt32 tlen; /* trailer len */ -}; - - -NSPR_API(PRInt32) PR_SendFile( - PRFileDesc *networkSocket, PRSendFileData *sendData, - PRTransmitFileFlags flags, PRIntervalTime timeout); - -/* -************************************************************************* -** FUNCTION: PR_AcceptRead -** DESCRIPTION: -** AcceptRead accepts a new connection, returns the newly created -** socket's descriptor and also returns the connecting peer's address. -** AcceptRead, as its name suggests, also receives the first block of data -** sent by the peer. -** -** INPUTS: -** PRFileDesc *listenSock -** A socket descriptor that has been called with the PR_Listen() -** function, also known as the rendezvous socket. -** void *buf -** A pointer to a buffer to receive data sent by the client. This -** buffer must be large enough to receive bytes of data -** and two PRNetAddr structures, plus an extra 32 bytes. See: -** PR_ACCEPT_READ_BUF_OVERHEAD. -** PRInt32 amount -** The number of bytes of client data to receive. Does not include -** the size of the PRNetAddr structures. If 0, no data will be read -** from the client. -** PRIntervalTime timeout -** The timeout interval only applies to the read portion of the -** operation. PR_AcceptRead will block indefinitely until the -** connection is accepted; the read will timeout after the timeout -** interval elapses. -** OUTPUTS: -** PRFileDesc **acceptedSock -** The file descriptor for the newly connected socket. This parameter -** will only be valid if the function return does not indicate failure. -** PRNetAddr **peerAddr, -** The address of the remote socket. This parameter will only be -** valid if the function return does not indicate failure. The -** returned address is not guaranteed to be properly aligned. -** -** RETURNS: -** The number of bytes read from the client or -1 on failure. The reason -** for the failure is obtained by calling PR_GetError(). -************************************************************************** -**/ -/* define buffer overhead constant. Add this value to the user's -** data length when allocating a buffer to accept data. -** Example: -** #define USER_DATA_SIZE 10 -** char buf[USER_DATA_SIZE + PR_ACCEPT_READ_BUF_OVERHEAD]; -** bytesRead = PR_AcceptRead( s, fd, &a, &p, USER_DATA_SIZE, ...); -*/ -#define PR_ACCEPT_READ_BUF_OVERHEAD (32+(2*sizeof(PRNetAddr))) - -NSPR_API(PRInt32) PR_AcceptRead( - PRFileDesc *listenSock, PRFileDesc **acceptedSock, - PRNetAddr **peerAddr, void *buf, PRInt32 amount, PRIntervalTime timeout); - -/* -************************************************************************* -** FUNCTION: PR_NewTCPSocketPair -** DESCRIPTION: -** Create a new TCP socket pair. The returned descriptors can be used -** interchangeably; they are interconnected full-duplex descriptors: data -** written to one can be read from the other and vice-versa. -** -** INPUTS: -** None -** OUTPUTS: -** PRFileDesc *fds[2] -** The file descriptor pair for the newly created TCP sockets. -** RETURN: PRStatus -** Upon successful completion of TCP socket pair, PR_NewTCPSocketPair -** returns PR_SUCCESS. Otherwise, it returns PR_FAILURE. Further -** failure information can be obtained by calling PR_GetError(). -** XXX can we implement this on windoze and mac? -************************************************************************** -**/ -NSPR_API(PRStatus) PR_NewTCPSocketPair(PRFileDesc *fds[2]); - -/* -************************************************************************* -** FUNCTION: PR_GetSockName -** DESCRIPTION: -** Get socket name. Return the network address for this socket. -** -** INPUTS: -** PRFileDesc *fd -** Points to a PRFileDesc object representing the socket. -** OUTPUTS: -** PRNetAddr *addr -** Returns the address of the socket in its own communication space. -** RETURN: PRStatus -** Upon successful completion, PR_GetSockName returns PR_SUCCESS. -** Otherwise, it returns PR_FAILURE. Further failure information can -** be obtained by calling PR_GetError(). -************************************************************************** -**/ -NSPR_API(PRStatus) PR_GetSockName(PRFileDesc *fd, PRNetAddr *addr); - -/* -************************************************************************* -** FUNCTION: PR_GetPeerName -** DESCRIPTION: -** Get name of the connected peer. Return the network address for the -** connected peer socket. -** -** INPUTS: -** PRFileDesc *fd -** Points to a PRFileDesc object representing the connected peer. -** OUTPUTS: -** PRNetAddr *addr -** Returns the address of the connected peer in its own communication -** space. -** RETURN: PRStatus -** Upon successful completion, PR_GetPeerName returns PR_SUCCESS. -** Otherwise, it returns PR_FAILURE. Further failure information can -** be obtained by calling PR_GetError(). -************************************************************************** -**/ -NSPR_API(PRStatus) PR_GetPeerName(PRFileDesc *fd, PRNetAddr *addr); - -NSPR_API(PRStatus) PR_GetSocketOption( - PRFileDesc *fd, PRSocketOptionData *data); - -NSPR_API(PRStatus) PR_SetSocketOption( - PRFileDesc *fd, const PRSocketOptionData *data); - -/* - ********************************************************************* - * - * File descriptor inheritance - * - ********************************************************************* - */ - -/* - ************************************************************************ - * FUNCTION: PR_SetFDInheritable - * DESCRIPTION: - * Set the inheritance attribute of a file descriptor. - * - * INPUTS: - * PRFileDesc *fd - * Points to a PRFileDesc object. - * PRBool inheritable - * If PR_TRUE, the file descriptor fd is set to be inheritable - * by a child process. If PR_FALSE, the file descriptor is set - * to be not inheritable by a child process. - * RETURN: PRStatus - * Upon successful completion, PR_SetFDInheritable returns PR_SUCCESS. - * Otherwise, it returns PR_FAILURE. Further failure information can - * be obtained by calling PR_GetError(). - ************************************************************************* - */ -NSPR_API(PRStatus) PR_SetFDInheritable( - PRFileDesc *fd, - PRBool inheritable); - -/* - ************************************************************************ - * FUNCTION: PR_GetInheritedFD - * DESCRIPTION: - * Get an inherited file descriptor with the specified name. - * - * INPUTS: - * const char *name - * The name of the inherited file descriptor. - * RETURN: PRFileDesc * - * Upon successful completion, PR_GetInheritedFD returns the - * inherited file descriptor with the specified name. Otherwise, - * it returns NULL. Further failure information can be obtained - * by calling PR_GetError(). - ************************************************************************* - */ -NSPR_API(PRFileDesc *) PR_GetInheritedFD(const char *name); - -/* - ********************************************************************* - * - * Memory-mapped files - * - ********************************************************************* - */ - -typedef struct PRFileMap PRFileMap; - -/* - * protection options for read and write accesses of a file mapping - */ -typedef enum PRFileMapProtect { - PR_PROT_READONLY, /* read only */ - PR_PROT_READWRITE, /* readable, and write is shared */ - PR_PROT_WRITECOPY /* readable, and write is private (copy-on-write) */ -} PRFileMapProtect; - -NSPR_API(PRFileMap *) PR_CreateFileMap( - PRFileDesc *fd, - PRInt64 size, - PRFileMapProtect prot); - -/* - * return the alignment (in bytes) of the offset argument to PR_MemMap - */ -NSPR_API(PRInt32) PR_GetMemMapAlignment(void); - -NSPR_API(void *) PR_MemMap( - PRFileMap *fmap, - PROffset64 offset, /* must be aligned and sized according to the - * return value of PR_GetMemMapAlignment() */ - PRUint32 len); - -NSPR_API(PRStatus) PR_MemUnmap(void *addr, PRUint32 len); - -NSPR_API(PRStatus) PR_CloseFileMap(PRFileMap *fmap); - -/* - * Synchronously flush the given memory-mapped address range of the given open - * file to disk. The function does not return until all modified data have - * been written to disk. - * - * On some platforms, the function will call PR_Sync(fd) internally if it is - * necessary for flushing modified data to disk synchronously. - */ -NSPR_API(PRStatus) PR_SyncMemMap( - PRFileDesc *fd, - void *addr, - PRUint32 len); - -/* - ****************************************************************** - * - * Interprocess communication - * - ****************************************************************** - */ - -/* - * Creates an anonymous pipe and returns file descriptors for the - * read and write ends of the pipe. - */ - -NSPR_API(PRStatus) PR_CreatePipe( - PRFileDesc **readPipe, - PRFileDesc **writePipe -); - -/************************************************************************/ -/************** The following definitions are for poll ******************/ -/************************************************************************/ - -struct PRPollDesc { - PRFileDesc* fd; - PRInt16 in_flags; - PRInt16 out_flags; -}; - -/* -** Bit values for PRPollDesc.in_flags or PRPollDesc.out_flags. Binary-or -** these together to produce the desired poll request. -*/ - -#if defined(_PR_POLL_BACKCOMPAT) - -#include -#define PR_POLL_READ POLLIN -#define PR_POLL_WRITE POLLOUT -#define PR_POLL_EXCEPT POLLPRI -#define PR_POLL_ERR POLLERR /* only in out_flags */ -#define PR_POLL_NVAL POLLNVAL /* only in out_flags when fd is bad */ -#define PR_POLL_HUP POLLHUP /* only in out_flags */ - -#else /* _PR_POLL_BACKCOMPAT */ - -#define PR_POLL_READ 0x1 -#define PR_POLL_WRITE 0x2 -#define PR_POLL_EXCEPT 0x4 -#define PR_POLL_ERR 0x8 /* only in out_flags */ -#define PR_POLL_NVAL 0x10 /* only in out_flags when fd is bad */ -#define PR_POLL_HUP 0x20 /* only in out_flags */ - -#endif /* _PR_POLL_BACKCOMPAT */ - -/* -************************************************************************* -** FUNCTION: PR_Poll -** DESCRIPTION: -** -** The call returns as soon as I/O is ready on one or more of the underlying -** socket objects. A count of the number of ready descriptors is -** returned unless a timeout occurs in which case zero is returned. -** -** PRPollDesc.fd should be set to a pointer to a PRFileDesc object -** representing a socket. This field can be set to NULL to indicate to -** PR_Poll that this PRFileDesc object should be ignored. -** PRPollDesc.in_flags should be set to the desired request -** (read/write/except or some combination). Upon successful return from -** this call PRPollDesc.out_flags will be set to indicate what kind of -** i/o can be performed on the respective descriptor. PR_Poll() uses the -** out_flags fields as scratch variables during the call. If PR_Poll() -** returns 0 or -1, the out_flags fields do not contain meaningful values -** and must not be used. -** -** INPUTS: -** PRPollDesc *pds A pointer to an array of PRPollDesc -** -** PRIntn npds The number of elements in the array -** If this argument is zero PR_Poll is -** equivalent to a PR_Sleep(timeout). -** -** PRIntervalTime timeout Amount of time the call will block waiting -** for I/O to become ready. If this time expires -** w/o any I/O becoming ready, the result will -** be zero. -** -** OUTPUTS: None -** RETURN: -** PRInt32 Number of PRPollDesc's with events or zero -** if the function timed out or -1 on failure. -** The reason for the failure is obtained by -** calling PR_GetError(). -************************************************************************** -*/ -NSPR_API(PRInt32) PR_Poll( - PRPollDesc *pds, PRIntn npds, PRIntervalTime timeout); - -/* -************************************************************************** -** -** Pollable events -** -** A pollable event is a special kind of file descriptor. -** The only I/O operation you can perform on a pollable event -** is to poll it with the PR_POLL_READ flag. You can't -** read from or write to a pollable event. -** -** The purpose of a pollable event is to combine event waiting -** with I/O waiting in a single PR_Poll call. Pollable events -** are implemented using a pipe or a pair of TCP sockets -** connected via the loopback address, therefore setting and -** waiting for pollable events are expensive operating system -** calls. Do not use pollable events for general thread -** synchronization. Use condition variables instead. -** -** A pollable event has two states: set and unset. Events -** are not queued, so there is no notion of an event count. -** A pollable event is either set or unset. -** -** A new pollable event is created by a PR_NewPollableEvent -** call and is initially in the unset state. -** -** PR_WaitForPollableEvent blocks the calling thread until -** the pollable event is set, and then it atomically unsets -** the pollable event before it returns. -** -** To set a pollable event, call PR_SetPollableEvent. -** -** One can call PR_Poll with the PR_POLL_READ flag on a pollable -** event. When the pollable event is set, PR_Poll returns with -** the PR_POLL_READ flag set in the out_flags. -** -** To close a pollable event, call PR_DestroyPollableEvent -** (not PR_Close). -** -************************************************************************** -*/ - -NSPR_API(PRFileDesc *) PR_NewPollableEvent(void); - -NSPR_API(PRStatus) PR_DestroyPollableEvent(PRFileDesc *event); - -NSPR_API(PRStatus) PR_SetPollableEvent(PRFileDesc *event); - -NSPR_API(PRStatus) PR_WaitForPollableEvent(PRFileDesc *event); - -PR_END_EXTERN_C - -#endif /* prio_h___ */ diff --git a/win32/include/spidermonkey/nspr/pripcsem.h b/win32/include/spidermonkey/nspr/pripcsem.h deleted file mode 100755 index f5a524da..00000000 --- a/win32/include/spidermonkey/nspr/pripcsem.h +++ /dev/null @@ -1,101 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * File: pripcsem.h - * - * Description: named semaphores for interprocess - * synchronization - * - * Unrelated processes obtain access to a shared semaphore - * by specifying its name. - * - * Our goal is to support named semaphores on at least - * Unix and Win32 platforms. The implementation will use - * one of the three native semaphore APIs: POSIX, System V, - * and Win32. - * - * Because POSIX named semaphores have kernel persistence, - * we are forced to have a delete function in this API. - */ - -#ifndef pripcsem_h___ -#define pripcsem_h___ - -#include "prtypes.h" -#include "prio.h" - -PR_BEGIN_EXTERN_C - -/* - * PRSem is an opaque structure that represents a named - * semaphore. - */ -typedef struct PRSem PRSem; - -/* - * PR_OpenSemaphore -- - * - * Create or open a named semaphore with the specified name. - * A handle to the semaphore is returned. - * - * If the named semaphore doesn't exist and the PR_SEM_CREATE - * flag is specified, the named semaphore is created. The - * created semaphore needs to be removed from the system with - * a PR_DeleteSemaphore call. - * - * If PR_SEM_CREATE is specified, the third argument is the - * access permission bits of the new semaphore (same - * interpretation as the mode argument to PR_Open) and the - * fourth argument is the initial value of the new semaphore. - * If PR_SEM_CREATE is not specified, the third and fourth - * arguments are ignored. - */ - -#define PR_SEM_CREATE 0x1 /* create if not exist */ -#define PR_SEM_EXCL 0x2 /* fail if already exists */ - -NSPR_API(PRSem *) PR_OpenSemaphore( - const char *name, PRIntn flags, PRIntn mode, PRUintn value); - -/* - * PR_WaitSemaphore -- - * - * If the value of the semaphore is > 0, decrement the value and return. - * If the value is 0, sleep until the value becomes > 0, then decrement - * the value and return. - * - * The "test and decrement" operation is performed atomically. - */ - -NSPR_API(PRStatus) PR_WaitSemaphore(PRSem *sem); - -/* - * PR_PostSemaphore -- - * - * Increment the value of the named semaphore by 1. - */ - -NSPR_API(PRStatus) PR_PostSemaphore(PRSem *sem); - -/* - * PR_CloseSemaphore -- - * - * Close a named semaphore handle. - */ - -NSPR_API(PRStatus) PR_CloseSemaphore(PRSem *sem); - -/* - * PR_DeleteSemaphore -- - * - * Remove a named semaphore from the system. - */ - -NSPR_API(PRStatus) PR_DeleteSemaphore(const char *name); - -PR_END_EXTERN_C - -#endif /* pripcsem_h___ */ diff --git a/win32/include/spidermonkey/nspr/private/pprio.h b/win32/include/spidermonkey/nspr/private/pprio.h deleted file mode 100755 index 26bcd0d0..00000000 --- a/win32/include/spidermonkey/nspr/private/pprio.h +++ /dev/null @@ -1,242 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: pprio.h -** -** Description: Private definitions for I/O related structures -*/ - -#ifndef pprio_h___ -#define pprio_h___ - -#include "prtypes.h" -#include "prio.h" - -PR_BEGIN_EXTERN_C - -/************************************************************************/ -/************************************************************************/ - -#ifdef _WIN64 -typedef __int64 PROsfd; -#else -typedef PRInt32 PROsfd; -#endif - -/* Return the method tables for files, tcp sockets and udp sockets */ -NSPR_API(const PRIOMethods*) PR_GetFileMethods(void); -NSPR_API(const PRIOMethods*) PR_GetTCPMethods(void); -NSPR_API(const PRIOMethods*) PR_GetUDPMethods(void); -NSPR_API(const PRIOMethods*) PR_GetPipeMethods(void); - -/* -** Convert a NSPR socket handle to a native socket handle. -** -** Using this function makes your code depend on the properties of the -** current NSPR implementation, which may change (although extremely -** unlikely because of NSPR's backward compatibility requirement). Avoid -** using it if you can. -** -** If you use this function, you need to understand what NSPR does to -** the native handle. For example, NSPR puts native socket handles in -** non-blocking mode or associates them with an I/O completion port (the -** WINNT build configuration only). Your use of the native handle should -** not interfere with NSPR's use of the native handle. If your code -** changes the configuration of the native handle, (e.g., changes it to -** blocking or closes it), NSPR will not work correctly. -*/ -NSPR_API(PROsfd) PR_FileDesc2NativeHandle(PRFileDesc *); -NSPR_API(void) PR_ChangeFileDescNativeHandle(PRFileDesc *, PROsfd); -NSPR_API(PRFileDesc*) PR_AllocFileDesc(PROsfd osfd, - const PRIOMethods *methods); -NSPR_API(void) PR_FreeFileDesc(PRFileDesc *fd); -/* -** Import an existing OS file to NSPR. -*/ -NSPR_API(PRFileDesc*) PR_ImportFile(PROsfd osfd); -NSPR_API(PRFileDesc*) PR_ImportPipe(PROsfd osfd); -NSPR_API(PRFileDesc*) PR_ImportTCPSocket(PROsfd osfd); -NSPR_API(PRFileDesc*) PR_ImportUDPSocket(PROsfd osfd); - - -/* - ************************************************************************* - * FUNCTION: PR_CreateSocketPollFd - * DESCRIPTION: - * Create a PRFileDesc wrapper for a native socket handle, for use with - * PR_Poll only - * INPUTS: - * None - * OUTPUTS: - * None - * RETURN: PRFileDesc* - * Upon successful completion, PR_CreateSocketPollFd returns a pointer - * to the PRFileDesc created for the native socket handle - * Returns a NULL pointer if the create of a new PRFileDesc failed - * - ************************************************************************** - */ - -NSPR_API(PRFileDesc*) PR_CreateSocketPollFd(PROsfd osfd); - -/* - ************************************************************************* - * FUNCTION: PR_DestroySocketPollFd - * DESCRIPTION: - * Destroy the PRFileDesc wrapper created by PR_CreateSocketPollFd - * INPUTS: - * None - * OUTPUTS: - * None - * RETURN: PRFileDesc* - * Upon successful completion, PR_DestroySocketPollFd returns - * PR_SUCCESS, else PR_FAILURE - * - ************************************************************************** - */ - -NSPR_API(PRStatus) PR_DestroySocketPollFd(PRFileDesc *fd); - - -/* -** Macros for PR_Socket -** -** Socket types: PR_SOCK_STREAM, PR_SOCK_DGRAM -*/ - -#ifdef WIN32 - -#define PR_SOCK_STREAM 1 -#define PR_SOCK_DGRAM 2 - -#else /* WIN32 */ - -#define PR_SOCK_STREAM SOCK_STREAM -#define PR_SOCK_DGRAM SOCK_DGRAM - -#endif /* WIN32 */ - -/* -** Create a new Socket; this function is obsolete. -*/ -NSPR_API(PRFileDesc*) PR_Socket(PRInt32 domain, PRInt32 type, PRInt32 proto); - -/* FUNCTION: PR_LockFile -** DESCRIPTION: -** Lock a file for exclusive access. -** RETURNS: -** PR_SUCCESS when the lock is held -** PR_FAILURE otherwise -*/ -NSPR_API(PRStatus) PR_LockFile(PRFileDesc *fd); - -/* FUNCTION: PR_TLockFile -** DESCRIPTION: -** Test and Lock a file for exclusive access. Do not block if the -** file cannot be locked immediately. -** RETURNS: -** PR_SUCCESS when the lock is held -** PR_FAILURE otherwise -*/ -NSPR_API(PRStatus) PR_TLockFile(PRFileDesc *fd); - -/* FUNCTION: PR_UnlockFile -** DESCRIPTION: -** Unlock a file which has been previously locked successfully by this -** process. -** RETURNS: -** PR_SUCCESS when the lock is released -** PR_FAILURE otherwise -*/ -NSPR_API(PRStatus) PR_UnlockFile(PRFileDesc *fd); - -/* -** Emulate acceptread by accept and recv. -*/ -NSPR_API(PRInt32) PR_EmulateAcceptRead(PRFileDesc *sd, PRFileDesc **nd, - PRNetAddr **raddr, void *buf, PRInt32 amount, PRIntervalTime timeout); - -/* -** Emulate sendfile by reading from the file and writing to the socket. -** The file is memory-mapped if memory-mapped files are supported. -*/ -NSPR_API(PRInt32) PR_EmulateSendFile( - PRFileDesc *networkSocket, PRSendFileData *sendData, - PRTransmitFileFlags flags, PRIntervalTime timeout); - -#ifdef WIN32 -/* FUNCTION: PR_NTFast_AcceptRead -** DESCRIPTION: -** NT has the notion of an "accept context", which is only needed in -** order to make certain calls. By default, a socket connected via -** AcceptEx can only do a limited number of things without updating -** the acceptcontext. The generic version of PR_AcceptRead always -** updates the accept context. This version does not. -**/ -NSPR_API(PRInt32) PR_NTFast_AcceptRead(PRFileDesc *sd, PRFileDesc **nd, - PRNetAddr **raddr, void *buf, PRInt32 amount, PRIntervalTime t); - -typedef void (*_PR_AcceptTimeoutCallback)(void *); - -/* FUNCTION: PR_NTFast_AcceptRead_WithTimeoutCallback -** DESCRIPTION: -** The AcceptEx call combines the accept with the read function. However, -** our daemon threads need to be able to wakeup and reliably flush their -** log buffers if the Accept times out. However, with the current blocking -** interface to AcceptRead, there is no way for us to timeout the Accept; -** this is because when we timeout the Read, we can close the newly -** socket and continue; but when we timeout the accept itself, there is no -** new socket to timeout. So instead, this version of the function is -** provided. After the initial timeout period elapses on the accept() -** portion of the function, it will call the callback routine and then -** continue the accept. If the timeout occurs on the read, it will -** close the connection and return error. -*/ -NSPR_API(PRInt32) PR_NTFast_AcceptRead_WithTimeoutCallback( - PRFileDesc *sd, - PRFileDesc **nd, - PRNetAddr **raddr, - void *buf, - PRInt32 amount, - PRIntervalTime t, - _PR_AcceptTimeoutCallback callback, - void *callback_arg); - -/* FUNCTION: PR_NTFast_Accept -** DESCRIPTION: -** NT has the notion of an "accept context", which is only needed in -** order to make certain calls. By default, a socket connected via -** AcceptEx can only do a limited number of things without updating -** the acceptcontext. The generic version of PR_Accept always -** updates the accept context. This version does not. -**/ -NSPR_API(PRFileDesc*) PR_NTFast_Accept(PRFileDesc *fd, PRNetAddr *addr, - PRIntervalTime timeout); - -/* FUNCTION: PR_NTFast_Update -** DESCRIPTION: -** For sockets accepted with PR_NTFast_Accept or PR_NTFastAcceptRead, -** this function will update the accept context for those sockets, -** so that the socket can make general purpose socket calls. -** Without calling this, the only operations supported on the socket -** Are PR_Read, PR_Write, PR_Transmitfile, and PR_Close. -*/ -NSPR_API(void) PR_NTFast_UpdateAcceptContext(PRFileDesc *acceptSock, - PRFileDesc *listenSock); - - -/* FUNCTION: PR_NT_CancelIo -** DESCRIPTION: -** Cancel IO operations on fd. -*/ -NSPR_API(PRStatus) PR_NT_CancelIo(PRFileDesc *fd); - - -#endif /* WIN32 */ - -PR_END_EXTERN_C - -#endif /* pprio_h___ */ diff --git a/win32/include/spidermonkey/nspr/private/pprthred.h b/win32/include/spidermonkey/nspr/private/pprthred.h deleted file mode 100755 index eb60baed..00000000 --- a/win32/include/spidermonkey/nspr/private/pprthred.h +++ /dev/null @@ -1,331 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef pprthred_h___ -#define pprthred_h___ - -/* -** API for PR private functions. These calls are to be used by internal -** developers only. -*/ -#include "nspr.h" - -#if defined(XP_OS2) -#define INCL_DOS -#define INCL_DOSERRORS -#define INCL_WIN -#include -#endif - -PR_BEGIN_EXTERN_C - -/*--------------------------------------------------------------------------- -** THREAD PRIVATE FUNCTIONS ----------------------------------------------------------------------------*/ - -/* -** Associate a thread object with an existing native thread. -** "type" is the type of thread object to attach -** "priority" is the priority to assign to the thread -** "stack" defines the shape of the threads stack -** -** This can return NULL if some kind of error occurs, or if memory is -** tight. This call invokes "start(obj,arg)" and returns when the -** function returns. The thread object is automatically destroyed. -** -** This call is not normally needed unless you create your own native -** thread. PR_Init does this automatically for the primordial thread. -*/ -NSPR_API(PRThread*) PR_AttachThread(PRThreadType type, - PRThreadPriority priority, - PRThreadStack *stack); - -/* -** Detach the nspr thread from the currently executing native thread. -** The thread object will be destroyed and all related data attached -** to it. The exit procs will be invoked. -** -** This call is not normally needed unless you create your own native -** thread. PR_Exit will automatially detach the nspr thread object -** created by PR_Init for the primordial thread. -** -** This call returns after the nspr thread object is destroyed. -*/ -NSPR_API(void) PR_DetachThread(void); - -/* -** Get the id of the named thread. Each thread is assigned a unique id -** when it is created or attached. -*/ -NSPR_API(PRUint32) PR_GetThreadID(PRThread *thread); - -/* -** Set the procedure that is called when a thread is dumped. The procedure -** will be applied to the argument, arg, when called. Setting the procedure -** to NULL effectively removes it. -*/ -typedef void (*PRThreadDumpProc)(PRFileDesc *fd, PRThread *t, void *arg); -NSPR_API(void) PR_SetThreadDumpProc( - PRThread* thread, PRThreadDumpProc dump, void *arg); - -/* -** Get this thread's affinity mask. The affinity mask is a 32 bit quantity -** marking a bit for each processor this process is allowed to run on. -** The processor mask is returned in the mask argument. -** The least-significant-bit represents processor 0. -** -** Returns 0 on success, -1 on failure. -*/ -NSPR_API(PRInt32) PR_GetThreadAffinityMask(PRThread *thread, PRUint32 *mask); - -/* -** Set this thread's affinity mask. -** -** Returns 0 on success, -1 on failure. -*/ -NSPR_API(PRInt32) PR_SetThreadAffinityMask(PRThread *thread, PRUint32 mask ); - -/* -** Set the default CPU Affinity mask. -** -*/ -NSPR_API(PRInt32) PR_SetCPUAffinityMask(PRUint32 mask); - -/* -** Show status of all threads to standard error output. -*/ -NSPR_API(void) PR_ShowStatus(void); - -/* -** Set thread recycle mode to on (1) or off (0) -*/ -NSPR_API(void) PR_SetThreadRecycleMode(PRUint32 flag); - - -/*--------------------------------------------------------------------------- -** THREAD PRIVATE FUNCTIONS FOR GARBAGE COLLECTIBLE THREADS ----------------------------------------------------------------------------*/ - -/* -** Only Garbage collectible threads participate in resume all, suspend all and -** enumeration operations. They are also different during creation when -** platform specific action may be needed (For example, all Solaris GC able -** threads are bound threads). -*/ - -/* -** Same as PR_CreateThread except that the thread is marked as garbage -** collectible. -*/ -NSPR_API(PRThread*) PR_CreateThreadGCAble(PRThreadType type, - void (*start)(void *arg), - void *arg, - PRThreadPriority priority, - PRThreadScope scope, - PRThreadState state, - PRUint32 stackSize); - -/* -** Same as PR_AttachThread except that the thread being attached is marked as -** garbage collectible. -*/ -NSPR_API(PRThread*) PR_AttachThreadGCAble(PRThreadType type, - PRThreadPriority priority, - PRThreadStack *stack); - -/* -** Mark the thread as garbage collectible. -*/ -NSPR_API(void) PR_SetThreadGCAble(void); - -/* -** Unmark the thread as garbage collectible. -*/ -NSPR_API(void) PR_ClearThreadGCAble(void); - -/* -** This routine prevents all other GC able threads from running. This call is needed by -** the garbage collector. -*/ -NSPR_API(void) PR_SuspendAll(void); - -/* -** This routine unblocks all other GC able threads that were suspended from running by -** PR_SuspendAll(). This call is needed by the garbage collector. -*/ -NSPR_API(void) PR_ResumeAll(void); - -/* -** Return the thread stack pointer of the given thread. -** Needed by the garbage collector. -*/ -NSPR_API(void *) PR_GetSP(PRThread *thread); - -/* -** Save the registers that the GC would find interesting into the thread -** "t". isCurrent will be non-zero if the thread state that is being -** saved is the currently executing thread. Return the address of the -** first register to be scanned as well as the number of registers to -** scan in "np". -** -** If "isCurrent" is non-zero then it is allowed for the thread context -** area to be used as scratch storage to hold just the registers -** necessary for scanning. -** -** This function simply calls the internal function _MD_HomeGCRegisters(). -*/ -NSPR_API(PRWord *) PR_GetGCRegisters(PRThread *t, int isCurrent, int *np); - -/* -** (Get|Set)ExecutionEnvironent -** -** Used by Java to associate it's execution environment so garbage collector -** can find it. If return is NULL, then it's probably not a collectable thread. -** -** There's no locking required around these calls. -*/ -NSPR_API(void*) GetExecutionEnvironment(PRThread *thread); -NSPR_API(void) SetExecutionEnvironment(PRThread* thread, void *environment); - -/* -** Enumeration function that applies "func(thread,i,arg)" to each active -** thread in the process. The enumerator returns PR_SUCCESS if the enumeration -** should continue, any other value is considered failure, and enumeration -** stops, returning the failure value from PR_EnumerateThreads. -** Needed by the garbage collector. -*/ -typedef PRStatus (PR_CALLBACK *PREnumerator)(PRThread *t, int i, void *arg); -NSPR_API(PRStatus) PR_EnumerateThreads(PREnumerator func, void *arg); - -/* -** Signature of a thread stack scanning function. It is applied to every -** contiguous group of potential pointers within a thread. Count denotes the -** number of pointers. -*/ -typedef PRStatus -(PR_CALLBACK *PRScanStackFun)(PRThread* t, - void** baseAddr, PRUword count, void* closure); - -/* -** Applies scanFun to all contiguous groups of potential pointers -** within a thread. This includes the stack, registers, and thread-local -** data. If scanFun returns a status value other than PR_SUCCESS the scan -** is aborted, and the status value is returned. -*/ -NSPR_API(PRStatus) -PR_ThreadScanStackPointers(PRThread* t, - PRScanStackFun scanFun, void* scanClosure); - -/* -** Calls PR_ThreadScanStackPointers for every thread. -*/ -NSPR_API(PRStatus) -PR_ScanStackPointers(PRScanStackFun scanFun, void* scanClosure); - -/* -** Returns a conservative estimate on the amount of stack space left -** on a thread in bytes, sufficient for making decisions about whether -** to continue recursing or not. -*/ -NSPR_API(PRUword) -PR_GetStackSpaceLeft(PRThread* t); - -/*--------------------------------------------------------------------------- -** THREAD CPU PRIVATE FUNCTIONS ----------------------------------------------------------------------------*/ - -/* -** Get a pointer to the primordial CPU. -*/ -NSPR_API(struct _PRCPU *) _PR_GetPrimordialCPU(void); - -/*--------------------------------------------------------------------------- -** THREAD SYNCHRONIZATION PRIVATE FUNCTIONS ----------------------------------------------------------------------------*/ - -/* -** Create a new named monitor (named for debugging purposes). -** Monitors are re-entrant locks with a built-in condition variable. -** -** This may fail if memory is tight or if some operating system resource -** is low. -*/ -NSPR_API(PRMonitor*) PR_NewNamedMonitor(const char* name); - -/* -** Test and then lock the lock if it's not already locked by some other -** thread. Return PR_FALSE if some other thread owned the lock at the -** time of the call. -*/ -NSPR_API(PRBool) PR_TestAndLock(PRLock *lock); - -/* -** Test and then enter the mutex associated with the monitor if it's not -** already entered by some other thread. Return PR_FALSE if some other -** thread owned the mutex at the time of the call. -*/ -NSPR_API(PRBool) PR_TestAndEnterMonitor(PRMonitor *mon); - -/* -** Return the number of times that the current thread has entered the -** mutex. Returns zero if the current thread has not entered the mutex. -*/ -NSPR_API(PRIntn) PR_GetMonitorEntryCount(PRMonitor *mon); - -/* -** Just like PR_CEnterMonitor except that if the monitor is owned by -** another thread NULL is returned. -*/ -NSPR_API(PRMonitor*) PR_CTestAndEnterMonitor(void *address); - -/*--------------------------------------------------------------------------- -** PLATFORM-SPECIFIC INITIALIZATION FUNCTIONS ----------------------------------------------------------------------------*/ -#if defined(IRIX) -/* -** Irix specific initialization funtion to be called before PR_Init -** is called by the application. Sets the CONF_INITUSERS and CONF_INITSIZE -** attributes of the shared arena set up by nspr. -** -** The environment variables _NSPR_IRIX_INITUSERS and _NSPR_IRIX_INITSIZE -** can also be used to set these arena attributes. If _NSPR_IRIX_INITUSERS -** is set, but not _NSPR_IRIX_INITSIZE, the value of the CONF_INITSIZE -** attribute of the nspr arena is scaled as a function of the -** _NSPR_IRIX_INITUSERS value. -** -** If the _PR_Irix_Set_Arena_Params() is called in addition to setting the -** environment variables, the values of the environment variables are used. -** -*/ -NSPR_API(void) _PR_Irix_Set_Arena_Params(PRInt32 initusers, PRInt32 initsize); - -#endif /* IRIX */ - -#if defined(XP_OS2) -/* -** These functions need to be called at the start and end of a thread. -** An EXCEPTIONREGISTRATIONRECORD must be declared on the stack and its -** address passed to the two functions. -*/ -NSPR_API(void) PR_OS2_SetFloatExcpHandler(EXCEPTIONREGISTRATIONRECORD* e); -NSPR_API(void) PR_OS2_UnsetFloatExcpHandler(EXCEPTIONREGISTRATIONRECORD* e); -#endif /* XP_OS2 */ - -/* I think PR_GetMonitorEntryCount is useless. All you really want is this... */ -#define PR_InMonitor(m) (PR_GetMonitorEntryCount(m) > 0) - -/*--------------------------------------------------------------------------- -** Special X-Lock hack for client ----------------------------------------------------------------------------*/ - -#ifdef XP_UNIX -extern void PR_XLock(void); -extern void PR_XUnlock(void); -extern PRBool PR_XIsLocked(void); -#endif /* XP_UNIX */ - -PR_END_EXTERN_C - -#endif /* pprthred_h___ */ diff --git a/win32/include/spidermonkey/nspr/private/prpriv.h b/win32/include/spidermonkey/nspr/private/prpriv.h deleted file mode 100755 index f45eee47..00000000 --- a/win32/include/spidermonkey/nspr/private/prpriv.h +++ /dev/null @@ -1,16 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prpriv_h___ -#define prpriv_h___ - -/* - * NSPR 2.0 Private API - */ - -#include "private/pprio.h" -#include "private/pprthred.h" - -#endif /* prpriv_h___ */ diff --git a/win32/include/spidermonkey/nspr/prlink.h b/win32/include/spidermonkey/nspr/prlink.h deleted file mode 100755 index ea45ef8e..00000000 --- a/win32/include/spidermonkey/nspr/prlink.h +++ /dev/null @@ -1,230 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prlink_h___ -#define prlink_h___ - -/* -** API to static and dynamic linking. -*/ -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -typedef struct PRLibrary PRLibrary; - -typedef struct PRStaticLinkTable { - const char *name; - void (*fp)(void); -} PRStaticLinkTable; - -/* -** Change the default library path to the given string. The string is -** copied. This call will fail if it runs out of memory. -** -** The string provided as 'path' is copied. The caller can do whatever is -** convenient with the argument when the function is complete. -*/ -NSPR_API(PRStatus) PR_SetLibraryPath(const char *path); - -/* -** Return a character string which contains the path used to search for -** dynamically loadable libraries. -** -** The returned value is basically a copy of a PR_SetLibraryPath(). -** The storage is allocated by the runtime and becomes the responsibilty -** of the caller. -*/ -NSPR_API(char*) PR_GetLibraryPath(void); - -/* -** Given a directory name "dir" and a library name "lib" construct a full -** path name that will refer to the actual dynamically loaded -** library. This does not test for existance of said file, it just -** constructs the full filename. The name constructed is system dependent -** and prepared for PR_LoadLibrary. The result must be free'd when the -** caller is done with it. -** -** The storage for the result is allocated by the runtime and becomes the -** responsibility of the caller. -*/ -NSPR_API(char*) PR_GetLibraryName(const char *dir, const char *lib); - -/* -** -** Free the memory allocated, for the caller, by PR_GetLibraryName -*/ -NSPR_API(void) PR_FreeLibraryName(char *mem); - -/* -** Given a library "name" try to load the library. The argument "name" -** is a machine-dependent name for the library, such as the full pathname -** returned by PR_GetLibraryName. If the library is already loaded, -** this function will avoid loading the library twice. -** -** If the library is loaded successfully, then a pointer to the PRLibrary -** structure representing the library is returned. Otherwise, NULL is -** returned. -** -** This increments the reference count of the library. -*/ -NSPR_API(PRLibrary*) PR_LoadLibrary(const char *name); - -/* -** Each operating system has its preferred way of specifying -** a file in the file system. Most operating systems use -** a pathname. Mac OS Classic, on the other hand, uses the FSSpec -** structure to specify a file. PRLibSpec allows NSPR clients -** to use the type of file specification that is most efficient -** for a particular platform. -** -** On some operating systems such as Mac OS Classic, a shared library -** may contain code fragments that can be individually loaded. -** PRLibSpec also allows NSPR clients to identify a code fragment -** in a library, if code fragments are supported by the OS. -** A code fragment can be specified by name or by an integer index. -** -** Right now PRLibSpec supports four types of library specification: -** a pathname in the native character encoding, a Mac code fragment -** by name, a Mac code fragment by index, and a UTF-16 pathname. -*/ - -typedef enum PRLibSpecType { - PR_LibSpec_Pathname, - PR_LibSpec_MacNamedFragment, /* obsolete (for Mac OS Classic) */ - PR_LibSpec_MacIndexedFragment, /* obsolete (for Mac OS Classic) */ - PR_LibSpec_PathnameU /* supported only on Win32 */ -} PRLibSpecType; - -struct FSSpec; /* Mac OS Classic FSSpec */ - -typedef struct PRLibSpec { - PRLibSpecType type; - union { - /* if type is PR_LibSpec_Pathname */ - const char *pathname; - - /* if type is PR_LibSpec_MacNamedFragment */ - struct { - const struct FSSpec *fsspec; - const char *name; - } mac_named_fragment; /* obsolete (for Mac OS Classic) */ - - /* if type is PR_LibSpec_MacIndexedFragment */ - struct { - const struct FSSpec *fsspec; - PRUint32 index; - } mac_indexed_fragment; /* obsolete (for Mac OS Classic) */ - - /* if type is PR_LibSpec_PathnameU */ - const PRUnichar *pathname_u; /* supported only on Win32 */ - } value; -} PRLibSpec; - -/* -** The following bit flags may be or'd together and passed -** as the 'flags' argument to PR_LoadLibraryWithFlags. -** Flags not supported by the underlying OS are ignored. -*/ - -#define PR_LD_LAZY 0x1 /* equivalent to RTLD_LAZY on Unix */ -#define PR_LD_NOW 0x2 /* equivalent to RTLD_NOW on Unix */ -#define PR_LD_GLOBAL 0x4 /* equivalent to RTLD_GLOBAL on Unix */ -#define PR_LD_LOCAL 0x8 /* equivalent to RTLD_LOCAL on Unix */ -/* The following is equivalent to LOAD_WITH_ALTERED_SEARCH_PATH on Windows */ -#define PR_LD_ALT_SEARCH_PATH 0x10 -/* 0x8000 reserved for NSPR internal use */ - -/* -** Load the specified library, in the manner specified by 'flags'. -*/ - -NSPR_API(PRLibrary *) -PR_LoadLibraryWithFlags( - PRLibSpec libSpec, /* the shared library */ - PRIntn flags /* flags that affect the loading */ -); - -/* -** Unload a previously loaded library. If the library was a static -** library then the static link table will no longer be referenced. The -** associated PRLibrary object is freed. -** -** PR_FAILURE is returned if the library cannot be unloaded. -** -** This function decrements the reference count of the library. -*/ -NSPR_API(PRStatus) PR_UnloadLibrary(PRLibrary *lib); - -/* -** Given the name of a procedure, return the address of the function that -** implements the procedure, or NULL if no such function can be -** found. This does not find symbols in the main program (the ".exe"); -** use PR_LoadStaticLibrary to register symbols in the main program. -** -** This function does not modify the reference count of the library. -*/ -NSPR_API(void*) PR_FindSymbol(PRLibrary *lib, const char *name); - -/* -** Similar to PR_FindSymbol, except that the return value is a pointer to -** a function, and not a pointer to void. Casting between a data pointer -** and a function pointer is not portable according to the C standard. -** Any function pointer can be cast to any other function pointer. -** -** This function does not modify the reference count of the library. -*/ -typedef void (*PRFuncPtr)(void); -NSPR_API(PRFuncPtr) PR_FindFunctionSymbol(PRLibrary *lib, const char *name); - -/* -** Finds a symbol in one of the currently loaded libraries. Given the -** name of a procedure, return the address of the function that -** implements the procedure, and return the library that contains that -** symbol, or NULL if no such function can be found. This does not find -** symbols in the main program (the ".exe"); use PR_AddStaticLibrary to -** register symbols in the main program. -** -** This increments the reference count of the library. -*/ -NSPR_API(void*) PR_FindSymbolAndLibrary(const char *name, - PRLibrary* *lib); - -/* -** Similar to PR_FindSymbolAndLibrary, except that the return value is -** a pointer to a function, and not a pointer to void. Casting between a -** data pointer and a function pointer is not portable according to the C -** standard. Any function pointer can be cast to any other function pointer. -** -** This increments the reference count of the library. -*/ -NSPR_API(PRFuncPtr) PR_FindFunctionSymbolAndLibrary(const char *name, - PRLibrary* *lib); - -/* -** Register a static link table with the runtime under the name -** "name". The symbols present in the static link table will be made -** available to PR_FindSymbol. If "name" is null then the symbols will be -** made available to the library which represents the executable. The -** tables are not copied. -** -** Returns the library object if successful, null otherwise. -** -** This increments the reference count of the library. -*/ -NSPR_API(PRLibrary*) PR_LoadStaticLibrary( - const char *name, const PRStaticLinkTable *table); - -/* -** Return the pathname of the file that the library "name" was loaded -** from. "addr" is the address of a function defined in the library. -** -** The caller is responsible for freeing the result with PR_Free. -*/ -NSPR_API(char *) PR_GetLibraryFilePathname(const char *name, PRFuncPtr addr); - -PR_END_EXTERN_C - -#endif /* prlink_h___ */ diff --git a/win32/include/spidermonkey/nspr/prlock.h b/win32/include/spidermonkey/nspr/prlock.h deleted file mode 100755 index bc76a0e1..00000000 --- a/win32/include/spidermonkey/nspr/prlock.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: prlock.h -** Description: API to basic locking functions of NSPR. -** -** -** NSPR provides basic locking mechanisms for thread synchronization. Locks -** are lightweight resource contention controls that prevent multiple threads -** from accessing something (code/data) simultaneously. -**/ - -#ifndef prlock_h___ -#define prlock_h___ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/**********************************************************************/ -/************************* TYPES AND CONSTANTS ************************/ -/**********************************************************************/ - -/* - * PRLock -- - * - * NSPR represents the lock as an opaque entity to the client of the - * API. All routines operate on a pointer to this opaque entity. - */ - -typedef struct PRLock PRLock; - -/**********************************************************************/ -/****************************** FUNCTIONS *****************************/ -/**********************************************************************/ - -/*********************************************************************** -** FUNCTION: PR_NewLock -** DESCRIPTION: -** Returns a pointer to a newly created opaque lock object. -** INPUTS: void -** OUTPUTS: void -** RETURN: PRLock* -** If the lock can not be created because of resource constraints, NULL -** is returned. -** -***********************************************************************/ -NSPR_API(PRLock*) PR_NewLock(void); - -/*********************************************************************** -** FUNCTION: PR_DestroyLock -** DESCRIPTION: -** Destroys a given opaque lock object. -** INPUTS: PRLock *lock -** Lock to be freed. -** OUTPUTS: void -** RETURN: None -***********************************************************************/ -NSPR_API(void) PR_DestroyLock(PRLock *lock); - -/*********************************************************************** -** FUNCTION: PR_Lock -** DESCRIPTION: -** Lock a lock. -** INPUTS: PRLock *lock -** Lock to locked. -** OUTPUTS: void -** RETURN: None -***********************************************************************/ -NSPR_API(void) PR_Lock(PRLock *lock); - -/*********************************************************************** -** FUNCTION: PR_Unlock -** DESCRIPTION: -** Unlock a lock. Unlocking an unlocked lock has undefined results. -** INPUTS: PRLock *lock -** Lock to unlocked. -** OUTPUTS: void -** RETURN: PR_STATUS -** Returns PR_FAILURE if the caller does not own the lock. -***********************************************************************/ -NSPR_API(PRStatus) PR_Unlock(PRLock *lock); - -/*********************************************************************** -** MACRO: PR_ASSERT_CURRENT_THREAD_OWNS_LOCK -** DESCRIPTION: -** If the current thread owns |lock|, this assertion is guaranteed to -** succeed. Otherwise, the behavior of this function is undefined. -** INPUTS: PRLock *lock -** Lock to assert ownership of. -** OUTPUTS: void -** RETURN: None -***********************************************************************/ -#if defined(DEBUG) || defined(FORCE_PR_ASSERT) -#define PR_ASSERT_CURRENT_THREAD_OWNS_LOCK(/* PrLock* */ lock) \ - PR_AssertCurrentThreadOwnsLock(lock) -#else -#define PR_ASSERT_CURRENT_THREAD_OWNS_LOCK(/* PrLock* */ lock) -#endif - -/* Don't call this function directly. */ -NSPR_API(void) PR_AssertCurrentThreadOwnsLock(PRLock *lock); - -PR_END_EXTERN_C - -#endif /* prlock_h___ */ diff --git a/win32/include/spidermonkey/nspr/prlog.h b/win32/include/spidermonkey/nspr/prlog.h deleted file mode 100755 index 4a291dc1..00000000 --- a/win32/include/spidermonkey/nspr/prlog.h +++ /dev/null @@ -1,222 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prlog_h___ -#define prlog_h___ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/* -** prlog.h -- Declare interfaces to NSPR's Logging service -** -** NSPR provides a logging service that is used by NSPR itself and is -** available to client programs. -** -** To use the service from a client program, you should create a -** PRLogModuleInfo structure by calling PR_NewLogModule(). After -** creating the LogModule, you can write to the log using the PR_LOG() -** macro. -** -** Initialization of the log service is handled by NSPR initialization. -** -** At execution time, you must enable the log service. To enable the -** log service, set the environment variable: NSPR_LOG_MODULES -** variable. -** -** NSPR_LOG_MODULES variable has the form: -** -** :[, :]* -** -** Where: -** is the name passed to PR_NewLogModule(). -** is a numeric constant, e.g. 5. This value is the maximum -** value of a log event, enumerated by PRLogModuleLevel, that you want -** written to the log. -** -** For example: to record all events of greater value than or equal to -** PR_LOG_ERROR for a LogModule names "gizmo", say: -** -** set NSPR_LOG_MODULES=gizmo:2 -** -** Note that you must specify the numeric value of PR_LOG_ERROR. -** -** Special LogModule names are provided for controlling NSPR's log -** service at execution time. These controls should be set in the -** NSPR_LOG_MODULES environment variable at execution time to affect -** NSPR's log service for your application. -** -** The special LogModule "all" enables all LogModules. To enable all -** LogModule calls to PR_LOG(), say: -** -** set NSPR_LOG_MODULES=all:5 -** -** The special LogModule name "sync" tells the NSPR log service to do -** unbuffered logging. -** -** The special LogModule name "bufsize:" tells NSPR to set the -** log buffer to . -** -** The environment variable NSPR_LOG_FILE specifies the log file to use -** unless the default of "stderr" is acceptable. For MS Windows -** systems, NSPR_LOG_FILE can be set to a special value: "WinDebug" -** (case sensitive). This value causes PR_LOG() output to be written -** using the Windows API OutputDebugString(). OutputDebugString() -** writes to the debugger window; some people find this helpful. -** -** -** To put log messages in your programs, use the PR_LOG macro: -** -** PR_LOG(, , (, *)); -** -** Where is the address of a PRLogModuleInfo structure, and -** is one of the levels defined by the enumeration: -** PRLogModuleLevel. is a printf() style of argument list. That -** is: (fmtstring, ...). -** -** Example: -** -** main() { -** PRIntn one = 1; -** PRLogModuleInfo * myLm = PR_NewLogModule("gizmo"); -** PR_LOG( myLm, PR_LOG_ALWAYS, ("Log this! %d\n", one)); -** return; -** } -** -** Note the use of printf() style arguments as the third agrument(s) to -** PR_LOG(). -** -** After compiling and linking you application, set the environment: -** -** set NSPR_LOG_MODULES=gizmo:5 -** set NSPR_LOG_FILE=logfile.txt -** -** When you execute your application, the string "Log this! 1" will be -** written to the file "logfile.txt". -** -** Note to NSPR engineers: a number of PRLogModuleInfo structures are -** defined and initialized in prinit.c. See this module for ideas on -** what to log where. -** -*/ - -typedef enum PRLogModuleLevel { - PR_LOG_NONE = 0, /* nothing */ - PR_LOG_ALWAYS = 1, /* always printed */ - PR_LOG_ERROR = 2, /* error messages */ - PR_LOG_WARNING = 3, /* warning messages */ - PR_LOG_DEBUG = 4, /* debug messages */ - - PR_LOG_NOTICE = PR_LOG_DEBUG, /* notice messages */ - PR_LOG_WARN = PR_LOG_WARNING, /* warning messages */ - PR_LOG_MIN = PR_LOG_DEBUG, /* minimal debugging messages */ - PR_LOG_MAX = PR_LOG_DEBUG /* maximal debugging messages */ -} PRLogModuleLevel; - -/* -** One of these structures is created for each module that uses logging. -** "name" is the name of the module -** "level" is the debugging level selected for that module -*/ -typedef struct PRLogModuleInfo { - const char *name; - PRLogModuleLevel level; - struct PRLogModuleInfo *next; -} PRLogModuleInfo; - -/* -** Create a new log module. -*/ -NSPR_API(PRLogModuleInfo*) PR_NewLogModule(const char *name); - -/* -** Set the file to use for logging. Returns PR_FALSE if the file cannot -** be created -*/ -NSPR_API(PRBool) PR_SetLogFile(const char *name); - -/* -** Set the size of the logging buffer. If "buffer_size" is zero then the -** logging becomes "synchronous" (or unbuffered). -*/ -NSPR_API(void) PR_SetLogBuffering(PRIntn buffer_size); - -/* -** Print a string to the log. "fmt" is a PR_snprintf format type. All -** messages printed to the log are preceeded by the name of the thread -** and a time stamp. Also, the routine provides a missing newline if one -** is not provided. -*/ -NSPR_API(void) PR_LogPrint(const char *fmt, ...); - -/* -** Flush the log to its file. -*/ -NSPR_API(void) PR_LogFlush(void); - -NSPR_API(void) PR_Assert(const char *s, const char *file, PRIntn ln) - PR_PRETEND_NORETURN; - -#if defined(DEBUG) || defined(FORCE_PR_LOG) -#define PR_LOGGING 1 - -#define PR_LOG_TEST(_module,_level) \ - ((_module)->level >= (_level)) - -/* -** Log something. -** "module" is the address of a PRLogModuleInfo structure -** "level" is the desired logging level -** "args" is a variable length list of arguments to print, in the following -** format: ("printf style format string", ...) -*/ -#define PR_LOG(_module,_level,_args) \ - PR_BEGIN_MACRO \ - if (PR_LOG_TEST(_module,_level)) { \ - PR_LogPrint _args; \ - } \ - PR_END_MACRO - -#else /* defined(DEBUG) || defined(FORCE_PR_LOG) */ - -#undef PR_LOGGING -#define PR_LOG_TEST(module,level) 0 -#define PR_LOG(module,level,args) - -#endif /* defined(DEBUG) || defined(FORCE_PR_LOG) */ - -#ifndef NO_NSPR_10_SUPPORT - -#ifdef PR_LOGGING -#define PR_LOG_BEGIN PR_LOG -#define PR_LOG_END PR_LOG -#define PR_LOG_DEFINE PR_NewLogModule -#else -#define PR_LOG_BEGIN(module,level,args) -#define PR_LOG_END(module,level,args) -#define PR_LOG_DEFINE(_name) NULL -#endif /* PR_LOGGING */ - -#endif /* NO_NSPR_10_SUPPORT */ - -#if defined(DEBUG) || defined(FORCE_PR_ASSERT) - -#define PR_ASSERT(_expr) \ - ((_expr)?((void)0):PR_Assert(# _expr,__FILE__,__LINE__)) - -#define PR_NOT_REACHED(_reasonStr) \ - PR_Assert(_reasonStr,__FILE__,__LINE__) - -#else - -#define PR_ASSERT(expr) ((void) 0) -#define PR_NOT_REACHED(reasonStr) - -#endif /* defined(DEBUG) || defined(FORCE_PR_ASSERT) */ - -PR_END_EXTERN_C - -#endif /* prlog_h___ */ diff --git a/win32/include/spidermonkey/nspr/prlong.h b/win32/include/spidermonkey/nspr/prlong.h deleted file mode 100755 index df1f30b0..00000000 --- a/win32/include/spidermonkey/nspr/prlong.h +++ /dev/null @@ -1,403 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: prlong.h -** Description: Portable access to 64 bit numerics -** -** Long-long (64-bit signed integer type) support. Some C compilers -** don't support 64 bit integers yet, so we use these macros to -** support both machines that do and don't. -**/ -#ifndef prlong_h___ -#define prlong_h___ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/*********************************************************************** -** DEFINES: LL_MaxInt -** LL_MinInt -** LL_Zero -** LL_MaxUint -** DESCRIPTION: -** Various interesting constants and static variable -** initializer -***********************************************************************/ -NSPR_API(PRInt64) LL_MaxInt(void); -NSPR_API(PRInt64) LL_MinInt(void); -NSPR_API(PRInt64) LL_Zero(void); -NSPR_API(PRUint64) LL_MaxUint(void); - -#if defined(HAVE_LONG_LONG) - -/* Keep this in sync with prtypes.h. */ -#if PR_BYTES_PER_LONG == 8 && !defined(PR_ALTERNATE_INT64_TYPEDEF) -#define LL_MAXINT 9223372036854775807L -#define LL_MININT (-LL_MAXINT - 1L) -#define LL_ZERO 0L -#define LL_MAXUINT 18446744073709551615UL -#define LL_INIT(hi, lo) ((hi ## L << 32) + lo ## L) -#elif defined(WIN32) && !defined(__GNUC__) -#define LL_MAXINT 9223372036854775807i64 -#define LL_MININT (-LL_MAXINT - 1i64) -#define LL_ZERO 0i64 -#define LL_MAXUINT 18446744073709551615ui64 -#define LL_INIT(hi, lo) ((hi ## i64 << 32) + lo ## i64) -#else -#define LL_MAXINT 9223372036854775807LL -#define LL_MININT (-LL_MAXINT - 1LL) -#define LL_ZERO 0LL -#define LL_MAXUINT 18446744073709551615ULL -#define LL_INIT(hi, lo) ((hi ## LL << 32) + lo ## LL) -#endif - -/*********************************************************************** -** MACROS: LL_* -** DESCRIPTION: -** The following macros define portable access to the 64 bit -** math facilities. -** -***********************************************************************/ - -/*********************************************************************** -** MACROS: LL_ -** -** LL_IS_ZERO Test for zero -** LL_EQ Test for equality -** LL_NE Test for inequality -** LL_GE_ZERO Test for zero or positive -** LL_CMP Compare two values -***********************************************************************/ -#define LL_IS_ZERO(a) ((a) == 0) -#define LL_EQ(a, b) ((a) == (b)) -#define LL_NE(a, b) ((a) != (b)) -#define LL_GE_ZERO(a) ((a) >= 0) -#define LL_CMP(a, op, b) ((PRInt64)(a) op (PRInt64)(b)) -#define LL_UCMP(a, op, b) ((PRUint64)(a) op (PRUint64)(b)) - -/*********************************************************************** -** MACROS: LL_ -** -** LL_AND Logical and -** LL_OR Logical or -** LL_XOR Logical exclusion -** LL_OR2 A disgusting deviation -** LL_NOT Negation (one's complement) -***********************************************************************/ -#define LL_AND(r, a, b) ((r) = (a) & (b)) -#define LL_OR(r, a, b) ((r) = (a) | (b)) -#define LL_XOR(r, a, b) ((r) = (a) ^ (b)) -#define LL_OR2(r, a) ((r) = (r) | (a)) -#define LL_NOT(r, a) ((r) = ~(a)) - -/*********************************************************************** -** MACROS: LL_ -** -** LL_NEG Negation (two's complement) -** LL_ADD Summation (two's complement) -** LL_SUB Difference (two's complement) -***********************************************************************/ -#define LL_NEG(r, a) ((r) = -(a)) -#define LL_ADD(r, a, b) ((r) = (a) + (b)) -#define LL_SUB(r, a, b) ((r) = (a) - (b)) - -/*********************************************************************** -** MACROS: LL_ -** -** LL_MUL Product (two's complement) -** LL_DIV Quotient (two's complement) -** LL_MOD Modulus (two's complement) -***********************************************************************/ -#define LL_MUL(r, a, b) ((r) = (a) * (b)) -#define LL_DIV(r, a, b) ((r) = (a) / (b)) -#define LL_MOD(r, a, b) ((r) = (a) % (b)) - -/*********************************************************************** -** MACROS: LL_ -** -** LL_SHL Shift left [0..64] bits -** LL_SHR Shift right [0..64] bits with sign extension -** LL_USHR Unsigned shift right [0..64] bits -** LL_ISHL Signed shift left [0..64] bits -***********************************************************************/ -#define LL_SHL(r, a, b) ((r) = (PRInt64)(a) << (b)) -#define LL_SHR(r, a, b) ((r) = (PRInt64)(a) >> (b)) -#define LL_USHR(r, a, b) ((r) = (PRUint64)(a) >> (b)) -#define LL_ISHL(r, a, b) ((r) = (PRInt64)(a) << (b)) - -/*********************************************************************** -** MACROS: LL_ -** -** LL_L2I Convert to signed 32 bit -** LL_L2UI Convert to unsigned 32 bit -** LL_L2F Convert to floating point -** LL_L2D Convert to floating point -** LL_I2L Convert signed to 64 bit -** LL_UI2L Convert unsigned to 64 bit -** LL_F2L Convert float to 64 bit -** LL_D2L Convert float to 64 bit -***********************************************************************/ -#define LL_L2I(i, l) ((i) = (PRInt32)(l)) -#define LL_L2UI(ui, l) ((ui) = (PRUint32)(l)) -#define LL_L2F(f, l) ((f) = (PRFloat64)(l)) -#define LL_L2D(d, l) ((d) = (PRFloat64)(l)) - -#define LL_I2L(l, i) ((l) = (PRInt64)(i)) -#define LL_UI2L(l, ui) ((l) = (PRInt64)(ui)) -#define LL_F2L(l, f) ((l) = (PRInt64)(f)) -#define LL_D2L(l, d) ((l) = (PRInt64)(d)) - -/*********************************************************************** -** MACROS: LL_UDIVMOD -** DESCRIPTION: -** Produce both a quotient and a remainder given an unsigned -** INPUTS: PRUint64 a: The dividend of the operation -** PRUint64 b: The quotient of the operation -** OUTPUTS: PRUint64 *qp: pointer to quotient -** PRUint64 *rp: pointer to remainder -***********************************************************************/ -#define LL_UDIVMOD(qp, rp, a, b) \ - (*(qp) = ((PRUint64)(a) / (b)), \ - *(rp) = ((PRUint64)(a) % (b))) - -#else /* !HAVE_LONG_LONG */ - -#define LL_MAXINT LL_MaxInt() -#define LL_MININT LL_MinInt() -#define LL_ZERO LL_Zero() -#define LL_MAXUINT LL_MaxUint() - -#ifdef IS_LITTLE_ENDIAN -#define LL_INIT(hi, lo) {PR_UINT32(lo), PR_UINT32(hi)} -#else -#define LL_INIT(hi, lo) {PR_UINT32(hi), PR_UINT32(lo)} -#endif - -#define LL_IS_ZERO(a) (((a).hi == 0) && ((a).lo == 0)) -#define LL_EQ(a, b) (((a).hi == (b).hi) && ((a).lo == (b).lo)) -#define LL_NE(a, b) (((a).hi != (b).hi) || ((a).lo != (b).lo)) -#define LL_GE_ZERO(a) (((a).hi >> 31) == 0) - -#define LL_CMP(a, op, b) (((a).hi == (b).hi) ? ((a).lo op (b).lo) : \ - ((PRInt32)(a).hi op (PRInt32)(b).hi)) -#define LL_UCMP(a, op, b) (((a).hi == (b).hi) ? ((a).lo op (b).lo) : \ - ((a).hi op (b).hi)) - -#define LL_AND(r, a, b) ((r).lo = (a).lo & (b).lo, \ - (r).hi = (a).hi & (b).hi) -#define LL_OR(r, a, b) ((r).lo = (a).lo | (b).lo, \ - (r).hi = (a).hi | (b).hi) -#define LL_XOR(r, a, b) ((r).lo = (a).lo ^ (b).lo, \ - (r).hi = (a).hi ^ (b).hi) -#define LL_OR2(r, a) ((r).lo = (r).lo | (a).lo, \ - (r).hi = (r).hi | (a).hi) -#define LL_NOT(r, a) ((r).lo = ~(a).lo, \ - (r).hi = ~(a).hi) - -#define LL_NEG(r, a) ((r).lo = -(PRInt32)(a).lo, \ - (r).hi = -(PRInt32)(a).hi - ((r).lo != 0)) -#define LL_ADD(r, a, b) { \ - PRInt64 _a, _b; \ - _a = a; _b = b; \ - (r).lo = _a.lo + _b.lo; \ - (r).hi = _a.hi + _b.hi + ((r).lo < _b.lo); \ -} - -#define LL_SUB(r, a, b) { \ - PRInt64 _a, _b; \ - _a = a; _b = b; \ - (r).lo = _a.lo - _b.lo; \ - (r).hi = _a.hi - _b.hi - (_a.lo < _b.lo); \ -} - -#define LL_MUL(r, a, b) { \ - PRInt64 _a, _b; \ - _a = a; _b = b; \ - LL_MUL32(r, _a.lo, _b.lo); \ - (r).hi += _a.hi * _b.lo + _a.lo * _b.hi; \ -} - -#define _lo16(a) ((a) & PR_BITMASK(16)) -#define _hi16(a) ((a) >> 16) - -#define LL_MUL32(r, a, b) { \ - PRUint32 _a1, _a0, _b1, _b0, _y0, _y1, _y2, _y3; \ - _a1 = _hi16(a), _a0 = _lo16(a); \ - _b1 = _hi16(b), _b0 = _lo16(b); \ - _y0 = _a0 * _b0; \ - _y1 = _a0 * _b1; \ - _y2 = _a1 * _b0; \ - _y3 = _a1 * _b1; \ - _y1 += _hi16(_y0); /* can't carry */ \ - _y1 += _y2; /* might carry */ \ - if (_y1 < _y2) \ - _y3 += (PRUint32)(PR_BIT(16)); /* propagate */ \ - (r).lo = (_lo16(_y1) << 16) + _lo16(_y0); \ - (r).hi = _y3 + _hi16(_y1); \ -} - -#define LL_UDIVMOD(qp, rp, a, b) ll_udivmod(qp, rp, a, b) - -NSPR_API(void) ll_udivmod(PRUint64 *qp, PRUint64 *rp, PRUint64 a, PRUint64 b); - -#define LL_DIV(r, a, b) { \ - PRInt64 _a, _b; \ - PRUint32 _negative = (PRInt32)(a).hi < 0; \ - if (_negative) { \ - LL_NEG(_a, a); \ - } else { \ - _a = a; \ - } \ - if ((PRInt32)(b).hi < 0) { \ - _negative ^= 1; \ - LL_NEG(_b, b); \ - } else { \ - _b = b; \ - } \ - LL_UDIVMOD(&(r), 0, _a, _b); \ - if (_negative) \ - LL_NEG(r, r); \ -} - -#define LL_MOD(r, a, b) { \ - PRInt64 _a, _b; \ - PRUint32 _negative = (PRInt32)(a).hi < 0; \ - if (_negative) { \ - LL_NEG(_a, a); \ - } else { \ - _a = a; \ - } \ - if ((PRInt32)(b).hi < 0) { \ - LL_NEG(_b, b); \ - } else { \ - _b = b; \ - } \ - LL_UDIVMOD(0, &(r), _a, _b); \ - if (_negative) \ - LL_NEG(r, r); \ -} - -#define LL_SHL(r, a, b) { \ - if (b) { \ - PRInt64 _a; \ - _a = a; \ - if ((b) < 32) { \ - (r).lo = _a.lo << ((b) & 31); \ - (r).hi = (_a.hi << ((b) & 31)) | (_a.lo >> (32 - (b))); \ - } else { \ - (r).lo = 0; \ - (r).hi = _a.lo << ((b) & 31); \ - } \ - } else { \ - (r) = (a); \ - } \ -} - -/* a is an PRInt32, b is PRInt32, r is PRInt64 */ -#define LL_ISHL(r, a, b) { \ - if (b) { \ - PRInt64 _a; \ - _a.lo = (a); \ - _a.hi = 0; \ - if ((b) < 32) { \ - (r).lo = (a) << ((b) & 31); \ - (r).hi = ((a) >> (32 - (b))); \ - } else { \ - (r).lo = 0; \ - (r).hi = (a) << ((b) & 31); \ - } \ - } else { \ - (r).lo = (a); \ - (r).hi = 0; \ - } \ -} - -#define LL_SHR(r, a, b) { \ - if (b) { \ - PRInt64 _a; \ - _a = a; \ - if ((b) < 32) { \ - (r).lo = (_a.hi << (32 - (b))) | (_a.lo >> ((b) & 31)); \ - (r).hi = (PRInt32)_a.hi >> ((b) & 31); \ - } else { \ - (r).lo = (PRInt32)_a.hi >> ((b) & 31); \ - (r).hi = (PRInt32)_a.hi >> 31; \ - } \ - } else { \ - (r) = (a); \ - } \ -} - -#define LL_USHR(r, a, b) { \ - if (b) { \ - PRInt64 _a; \ - _a = a; \ - if ((b) < 32) { \ - (r).lo = (_a.hi << (32 - (b))) | (_a.lo >> ((b) & 31)); \ - (r).hi = _a.hi >> ((b) & 31); \ - } else { \ - (r).lo = _a.hi >> ((b) & 31); \ - (r).hi = 0; \ - } \ - } else { \ - (r) = (a); \ - } \ -} - -#define LL_L2I(i, l) ((i) = (l).lo) -#define LL_L2UI(ui, l) ((ui) = (l).lo) -#define LL_L2F(f, l) { double _d; LL_L2D(_d, l); (f) = (PRFloat64)_d; } - -#define LL_L2D(d, l) { \ - int _negative; \ - PRInt64 _absval; \ - \ - _negative = (l).hi >> 31; \ - if (_negative) { \ - LL_NEG(_absval, l); \ - } else { \ - _absval = l; \ - } \ - (d) = (double)_absval.hi * 4.294967296e9 + _absval.lo; \ - if (_negative) \ - (d) = -(d); \ -} - -#define LL_I2L(l, i) { PRInt32 _i = ((PRInt32)(i)) >> 31; (l).lo = (i); (l).hi = _i; } -#define LL_UI2L(l, ui) ((l).lo = (ui), (l).hi = 0) -#define LL_F2L(l, f) { double _d = (double)f; LL_D2L(l, _d); } - -#define LL_D2L(l, d) { \ - int _negative; \ - double _absval, _d_hi; \ - PRInt64 _lo_d; \ - \ - _negative = ((d) < 0); \ - _absval = _negative ? -(d) : (d); \ - \ - (l).hi = _absval / 4.294967296e9; \ - (l).lo = 0; \ - LL_L2D(_d_hi, l); \ - _absval -= _d_hi; \ - _lo_d.hi = 0; \ - if (_absval < 0) { \ - _lo_d.lo = -_absval; \ - LL_SUB(l, l, _lo_d); \ - } else { \ - _lo_d.lo = _absval; \ - LL_ADD(l, l, _lo_d); \ - } \ - \ - if (_negative) \ - LL_NEG(l, l); \ -} - -#endif /* !HAVE_LONG_LONG */ - -PR_END_EXTERN_C - -#endif /* prlong_h___ */ diff --git a/win32/include/spidermonkey/nspr/prmem.h b/win32/include/spidermonkey/nspr/prmem.h deleted file mode 100755 index c7cb5fbf..00000000 --- a/win32/include/spidermonkey/nspr/prmem.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: prmem.h -** Description: API to NSPR memory management functions -** -*/ -#ifndef prmem_h___ -#define prmem_h___ - -#include "prtypes.h" -#include - -PR_BEGIN_EXTERN_C - -/* -** Thread safe memory allocation. -** -** NOTE: pr wraps up malloc, free, calloc, realloc so they are already -** thread safe (and are not declared here - look in stdlib.h). -*/ - -/* -** PR_Malloc, PR_Calloc, PR_Realloc, and PR_Free have the same signatures -** as their libc equivalent malloc, calloc, realloc, and free, and have -** the same semantics. (Note that the argument type size_t is replaced -** by PRUint32.) Memory allocated by PR_Malloc, PR_Calloc, or PR_Realloc -** must be freed by PR_Free. -*/ - -NSPR_API(void *) PR_Malloc(PRUint32 size); - -NSPR_API(void *) PR_Calloc(PRUint32 nelem, PRUint32 elsize); - -NSPR_API(void *) PR_Realloc(void *ptr, PRUint32 size); - -NSPR_API(void) PR_Free(void *ptr); - -/* -** The following are some convenience macros defined in terms of -** PR_Malloc, PR_Calloc, PR_Realloc, and PR_Free. -*/ - -/*********************************************************************** -** FUNCTION: PR_MALLOC() -** DESCRIPTION: -** PR_NEW() allocates an untyped item of size _size from the heap. -** INPUTS: _size: size in bytes of item to be allocated -** OUTPUTS: untyped pointer to the node allocated -** RETURN: pointer to node or error returned from malloc(). -***********************************************************************/ -#define PR_MALLOC(_bytes) (PR_Malloc((_bytes))) - -/*********************************************************************** -** FUNCTION: PR_NEW() -** DESCRIPTION: -** PR_NEW() allocates an item of type _struct from the heap. -** INPUTS: _struct: a data type -** OUTPUTS: pointer to _struct -** RETURN: pointer to _struct or error returns from malloc(). -***********************************************************************/ -#define PR_NEW(_struct) ((_struct *) PR_MALLOC(sizeof(_struct))) - -/*********************************************************************** -** FUNCTION: PR_REALLOC() -** DESCRIPTION: -** PR_REALLOC() re-allocates _ptr bytes from the heap as a _size -** untyped item. -** INPUTS: _ptr: pointer to node to reallocate -** _size: size of node to allocate -** OUTPUTS: pointer to node allocated -** RETURN: pointer to node allocated -***********************************************************************/ -#define PR_REALLOC(_ptr, _size) (PR_Realloc((_ptr), (_size))) - -/*********************************************************************** -** FUNCTION: PR_CALLOC() -** DESCRIPTION: -** PR_CALLOC() allocates a _size bytes untyped item from the heap -** and sets the allocated memory to all 0x00. -** INPUTS: _size: size of node to allocate -** OUTPUTS: pointer to node allocated -** RETURN: pointer to node allocated -***********************************************************************/ -#define PR_CALLOC(_size) (PR_Calloc(1, (_size))) - -/*********************************************************************** -** FUNCTION: PR_NEWZAP() -** DESCRIPTION: -** PR_NEWZAP() allocates an item of type _struct from the heap -** and sets the allocated memory to all 0x00. -** INPUTS: _struct: a data type -** OUTPUTS: pointer to _struct -** RETURN: pointer to _struct -***********************************************************************/ -#define PR_NEWZAP(_struct) ((_struct*)PR_Calloc(1, sizeof(_struct))) - -/*********************************************************************** -** FUNCTION: PR_DELETE() -** DESCRIPTION: -** PR_DELETE() unallocates an object previosly allocated via PR_NEW() -** or PR_NEWZAP() to the heap. -** INPUTS: pointer to previously allocated object -** OUTPUTS: the referenced object is returned to the heap -** RETURN: void -***********************************************************************/ -#define PR_DELETE(_ptr) { PR_Free(_ptr); (_ptr) = NULL; } - -/*********************************************************************** -** FUNCTION: PR_FREEIF() -** DESCRIPTION: -** PR_FREEIF() conditionally unallocates an object previously allocated -** vial PR_NEW() or PR_NEWZAP(). If the pointer to the object is -** equal to zero (0), the object is not released. -** INPUTS: pointer to previously allocated object -** OUTPUTS: the referenced object is conditionally returned to the heap -** RETURN: void -***********************************************************************/ -#define PR_FREEIF(_ptr) if (_ptr) PR_DELETE(_ptr) - -PR_END_EXTERN_C - -#endif /* prmem_h___ */ diff --git a/win32/include/spidermonkey/nspr/prmon.h b/win32/include/spidermonkey/nspr/prmon.h deleted file mode 100755 index 374e2982..00000000 --- a/win32/include/spidermonkey/nspr/prmon.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prmon_h___ -#define prmon_h___ - -#include "prtypes.h" -#include "prinrval.h" - -PR_BEGIN_EXTERN_C - -typedef struct PRMonitor PRMonitor; - -/* -** Create a new monitor. Monitors are re-entrant locks with a single built-in -** condition variable. -** -** This may fail if memory is tight or if some operating system resource -** is low. -*/ -NSPR_API(PRMonitor*) PR_NewMonitor(void); - -/* -** Destroy a monitor. The caller is responsible for guaranteeing that the -** monitor is no longer in use. There must be no thread waiting on the monitor's -** condition variable and that the lock is not held. -** -*/ -NSPR_API(void) PR_DestroyMonitor(PRMonitor *mon); - -/* -** Enter the lock associated with the monitor. If the calling thread currently -** is in the monitor, the call to enter will silently succeed. In either case, -** it will increment the entry count by one. -*/ -NSPR_API(void) PR_EnterMonitor(PRMonitor *mon); - -/* -** Decrement the entry count associated with the monitor. If the decremented -** entry count is zero, the monitor is exited. Returns PR_FAILURE if the -** calling thread has not entered the monitor. -*/ -NSPR_API(PRStatus) PR_ExitMonitor(PRMonitor *mon); - -/* -** Wait for a notify on the monitor's condition variable. Sleep for "ticks" -** amount of time (if "ticks" is PR_INTERVAL_NO_TIMEOUT then the sleep is -** indefinite). -** -** While the thread is waiting it exits the monitor (as if it called -** PR_ExitMonitor as many times as it had called PR_EnterMonitor). When -** the wait has finished the thread regains control of the monitors lock -** with the same entry count as before the wait began. -** -** The thread waiting on the monitor will be resumed when the monitor is -** notified (assuming the thread is the next in line to receive the -** notify) or when the "ticks" timeout elapses. -** -** Returns PR_FAILURE if the caller has not entered the monitor. -*/ -NSPR_API(PRStatus) PR_Wait(PRMonitor *mon, PRIntervalTime ticks); - -/* -** Notify a thread waiting on the monitor's condition variable. If a thread -** is waiting on the condition variable (using PR_Wait) then it is awakened -** and attempts to reenter the monitor. -*/ -NSPR_API(PRStatus) PR_Notify(PRMonitor *mon); - -/* -** Notify all of the threads waiting on the monitor's condition variable. -** All of threads waiting on the condition are scheduled to reenter the -** monitor. -*/ -NSPR_API(PRStatus) PR_NotifyAll(PRMonitor *mon); - -/* -** PR_ASSERT_CURRENT_THREAD_IN_MONITOR -** If the current thread is in |mon|, this assertion is guaranteed to -** succeed. Otherwise, the behavior of this function is undefined. -*/ -#if defined(DEBUG) || defined(FORCE_PR_ASSERT) -#define PR_ASSERT_CURRENT_THREAD_IN_MONITOR(/* PRMonitor* */ mon) \ - PR_AssertCurrentThreadInMonitor(mon) -#else -#define PR_ASSERT_CURRENT_THREAD_IN_MONITOR(/* PRMonitor* */ mon) -#endif - -/* Don't call this function directly. */ -NSPR_API(void) PR_AssertCurrentThreadInMonitor(PRMonitor *mon); - -PR_END_EXTERN_C - -#endif /* prmon_h___ */ diff --git a/win32/include/spidermonkey/nspr/prmwait.h b/win32/include/spidermonkey/nspr/prmwait.h deleted file mode 100755 index a902d90e..00000000 --- a/win32/include/spidermonkey/nspr/prmwait.h +++ /dev/null @@ -1,380 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if defined(_PRMWAIT_H) -#else -#define _PRMWAIT_H - -#include "prio.h" -#include "prtypes.h" -#include "prclist.h" - -PR_BEGIN_EXTERN_C - -/********************************************************************************/ -/********************************************************************************/ -/********************************************************************************/ -/****************************** WARNING ****************************/ -/********************************************************************************/ -/**************************** This is work in progress. *************************/ -/************************** Do not make any assumptions *************************/ -/************************** about the stability of this *************************/ -/************************** API or the underlying imple- ************************/ -/************************** mentation. ************************/ -/********************************************************************************/ -/********************************************************************************/ - -/* -** STRUCTURE: PRWaitGroup -** DESCRIPTION: -** The client may define several wait groups in order to semantically -** tie a collection of file descriptors for a single purpose. This allows -** easier dispatching of threads that returned with active file descriptors -** from the wait function. -*/ -typedef struct PRWaitGroup PRWaitGroup; - -/* -** ENUMERATION: PRMWStatus -** DESCRIPTION: -** This enumeration is used to indicate the completion status of -** a receive wait object. Generally stated, a positive value indicates -** that the operation is not yet complete. A zero value indicates -** success (similar to PR_SUCCESS) and any negative value is an -** indication of failure. The reason for the failure can be retrieved -** by calling PR_GetError(). -** -** PR_MW_PENDING The operation is still pending. None of the other -** fields of the object are currently valid. -** PR_MW_SUCCESS The operation is complete and it was successful. -** PR_MW_FAILURE The operation failed. The reason for the failure -** can be retrieved by calling PR_GetError(). -** PR_MW_TIMEOUT The amount of time allowed for by the object's -** 'timeout' field has expired w/o the operation -** otherwise coming to closure. -** PR_MW_INTERRUPT The operation was cancelled, either by the client -** calling PR_CancelWaitFileDesc() or destroying the -** entire wait group (PR_DestroyWaitGroup()). -*/ -typedef enum PRMWStatus -{ - PR_MW_PENDING = 1, - PR_MW_SUCCESS = 0, - PR_MW_FAILURE = -1, - PR_MW_TIMEOUT = -2, - PR_MW_INTERRUPT = -3 -} PRMWStatus; - -/* -** STRUCTURE: PRMemoryDescriptor -** DESCRIPTION: -** THis is a descriptor for an interval of memory. It contains a -** pointer to the first byte of that memory and the length (in -** bytes) of the interval. -*/ -typedef struct PRMemoryDescriptor -{ - void *start; /* pointer to first byte of memory */ - PRSize length; /* length (in bytes) of memory interval */ -} PRMemoryDescriptor; - -/* -** STRUCTURE: PRMWaitClientData -** DESCRIPTION: -** An opague stucture for which a client MAY give provide a concrete -** definition and associate with a receive descriptor. The NSPR runtime -** does not manage this field. It is completely up to the client. -*/ -typedef struct PRMWaitClientData PRMWaitClientData; - -/* -** STRUCTURE: PRRecvWait -** DESCRIPTION: -** A receive wait object contains the file descriptor that is subject -** to the wait and the amount of time (beginning epoch established -** when the object is presented to the runtime) the the channel should -** block before abandoning the process. -** -** The success of the wait operation will be noted in the object's -** 'outcome' field. The fields are not valid when the NSPR runtime -** is in possession of the object. -** -** The memory descriptor describes an interval of writable memory -** in the caller's address space where data from an initial read -** can be placed. The description may indicate a null interval. -*/ -typedef struct PRRecvWait -{ - PRCList internal; /* internal runtime linkages */ - - PRFileDesc *fd; /* file descriptor associated w/ object */ - PRMWStatus outcome; /* outcome of the current/last operation */ - PRIntervalTime timeout; /* time allowed for entire operation */ - - PRInt32 bytesRecv; /* number of bytes transferred into buffer */ - PRMemoryDescriptor buffer; /* where to store first segment of input data */ - PRMWaitClientData *client; /* pointer to arbitrary client defined data */ -} PRRecvWait; - -/* -** STRUCTURE: PRMWaitEnumerator -** DESCRIPTION: -** An enumeration object is used to store the state of an existing -** enumeration over a wait group. The opaque object must be allocated -** by the client and the reference presented on each call to the -** pseudo-stateless enumerator. The enumeration objects are sharable -** only in serial fashion. -*/ -typedef struct PRMWaitEnumerator PRMWaitEnumerator; - - -/* -** FUNCTION: PR_AddWaitFileDesc -** DESCRIPTION: -** This function will effectively add a file descriptor to the -** list of those waiting for network receive. The new descriptor -** will be semantically tied to the wait group specified. -** -** The ownership for the storage pointed to by 'desc' is temporarily -** passed over the the NSPR runtime. It will be handed back by the -** function PR_WaitRecvReady(). -** -** INPUTS -** group A reference to a PRWaitGroup or NULL. Wait groups are -** created by calling PR_CreateWaitGroup() and are used -** to semantically group various file descriptors by the -** client's application. -** desc A reference to a valid PRRecvWait. The object of the -** reference must be preserved and not be modified -** until its ownership is returned to the client. -** RETURN -** PRStatus An indication of success. If equal to PR_FAILUE details -** of the failure are avaiable via PR_GetError(). -** -** ERRORS -** PR_INVALID_ARGUMENT_ERROR -** Invalid 'group' identifier or duplicate 'desc' object. -** PR_OUT_OF_MEMORY_ERROR -** Insuffient memory for internal data structures. -** PR_INVALID_STATE_ERROR -** The group is being destroyed. -*/ -NSPR_API(PRStatus) PR_AddWaitFileDesc(PRWaitGroup *group, PRRecvWait *desc); - -/* -** FUNCTION: PR_WaitRecvReady -** DESCRIPTION: -** PR_WaitRecvReady will block the calling thread until one of the -** file descriptors that have been added via PR_AddWaitFileDesc is -** available for input I/O. -** INPUT -** group A pointer to a valid PRWaitGroup or NULL (the null -** group. The function will block the caller until a -** channel from the wait group becomes ready for receive -** or there is some sort of error. -** RETURN -** PRReciveWait -** When the caller is resumed it is either returned a -** valid pointer to a previously added receive wait or -** a NULL. If the latter, the function has terminated -** for a reason that can be determined by calling -** PR_GetError(). -** If a valid pointer is returned, the reference is to the -** file descriptor contained in the receive wait object. -** The outcome of the wait operation may still fail, and -** if it has, that fact will be noted in the object's -** outcome field. Details can be retrieved from PR_GetError(). -** -** ERRORS -** PR_INVALID_ARGUMENT_ERROR -** The 'group' is not known by the runtime. -** PR_PENDING_INTERRUPT_ERROR - The thread was interrupted. -** PR_INVALID_STATE_ERROR -** The group is being destroyed. -*/ -NSPR_API(PRRecvWait*) PR_WaitRecvReady(PRWaitGroup *group); - -/* -** FUNCTION: PR_CancelWaitFileDesc -** DESCRIPTION: -** PR_CancelWaitFileDesc is provided as a means for cancelling operations -** on objects previously submitted by use of PR_AddWaitFileDesc(). If -** the runtime knows of the object, it will be marked as having failed -** because it was interrupted (similar to PR_Interrupt()). The first -** available thread waiting on the group will be made to return the -** PRRecvWait object with the outcome noted. -** -** INPUTS -** group The wait group under which the wait receive object was -** added. -** desc A pointer to the wait receive object that is to be -** cancelled. -** RETURN -** PRStatus If the wait receive object was located and associated -** with the specified wait group, the status returned will -** be PR_SUCCESS. There is still a race condition that would -** permit the offected object to complete normally, but it -** is assured that it will complete in the near future. -** If the receive object or wait group are invalid, the -** function will return with a status of PR_FAILURE. -** -** ERRORS -** PR_INVALID_ARGUMENT_ERROR -** The 'group' argument is not recognized as a valid group. -** PR_COLLECTION_EMPTY_ERROR -** There are no more receive wait objects in the group's -** collection. -** PR_INVALID_STATE_ERROR -** The group is being destroyed. -*/ -NSPR_API(PRStatus) PR_CancelWaitFileDesc(PRWaitGroup *group, PRRecvWait *desc); - -/* -** FUNCTION: PR_CancelWaitGroup -** DESCRIPTION: -** PR_CancelWaitGroup is provided as a means for cancelling operations -** on objects previously submitted by use of PR_AddWaitFileDesc(). Each -** successive call will return a pointer to a PRRecvWait object that -** was previously registered via PR_AddWaitFileDesc(). If no wait -** objects are associated with the wait group, a NULL will be returned. -** This function should be called in a loop until a NULL is returned -** to reclaim all the wait objects prior to calling PR_DestroyWaitGroup(). -** -** INPUTS -** group The wait group under which the wait receive object was -** added. -** RETURN -** PRRecvWait* If the wait group is valid and at least one receive wait -** object is present in the group, that object will be -** marked as PR_MW_INTERRUPT'd and removed from the group's -** queues. Otherwise a NULL will be returned and the reason -** for the NULL may be retrieved by calling PR_GetError(). -** -** ERRORS -** PR_INVALID_ARGUMENT_ERROR -** PR_GROUP_EMPTY_ERROR -*/ -NSPR_API(PRRecvWait*) PR_CancelWaitGroup(PRWaitGroup *group); - -/* -** FUNCTION: PR_CreateWaitGroup -** DESCRIPTION: -** A wait group is an opaque object that a client may create in order -** to semantically group various wait requests. Each wait group is -** unique, including the default wait group (NULL). A wait request -** that was added under a wait group will only be serviced by a caller -** that specified the same wait group. -** -** INPUT -** size The size of the hash table to be used to contain the -** receive wait objects. This is just the initial size. -** It will grow as it needs to, but to avoid that hassle -** one can suggest a suitable size initially. It should -** be ~30% larger than the maximum number of receive wait -** objects expected. -** RETURN -** PRWaitGroup If successful, the function will return a pointer to an -** object that was allocated by and owned by the runtime. -** The reference remains valid until it is explicitly destroyed -** by calling PR_DestroyWaitGroup(). -** -** ERRORS -** PR_OUT_OF_MEMORY_ERROR -*/ -NSPR_API(PRWaitGroup*) PR_CreateWaitGroup(PRInt32 size); - -/* -** FUNCTION: PR_DestroyWaitGroup -** DESCRIPTION: -** Undo the effects of PR_CreateWaitGroup(). Any receive wait operations -** on the group will be treated as if the each had been the target of a -** PR_CancelWaitFileDesc(). -** -** INPUT -** group Reference to a wait group previously allocated using -** PR_CreateWaitGroup(). -** RETURN -** PRStatus Will be PR_SUCCESS if the wait group was valid and there -** are no receive wait objects in that group. Otherwise -** will indicate PR_FAILURE. -** -** ERRORS -** PR_INVALID_ARGUMENT_ERROR -** The 'group' argument does not reference a known object. -** PR_INVALID_STATE_ERROR -** The group still contains receive wait objects. -*/ -NSPR_API(PRStatus) PR_DestroyWaitGroup(PRWaitGroup *group); - -/* -** FUNCTION: PR_CreateMWaitEnumerator -** DESCRIPTION: -** The PR_CreateMWaitEnumerator() function returns a reference to an -** opaque PRMWaitEnumerator object. The enumerator object is required -** as an argument for each successive call in the stateless enumeration -** of the indicated wait group. -** -** group The wait group that the enumeration is intended to -** process. It may be be the default wait group (NULL). -** RETURN -** PRMWaitEnumerator* group -** A reference to an object that will be used to store -** intermediate state of enumerations. -** ERRORS -** Errors are indicated by the function returning a NULL. -** PR_INVALID_ARGUMENT_ERROR -** The 'group' argument does not reference a known object. -** PR_OUT_OF_MEMORY_ERROR -*/ -NSPR_API(PRMWaitEnumerator*) PR_CreateMWaitEnumerator(PRWaitGroup *group); - -/* -** FUNCTION: PR_DestroyMWaitEnumerator -** DESCRIPTION: -** Destroys the object created by PR_CreateMWaitEnumerator(). The reference -** used as an argument becomes invalid. -** -** INPUT -** PRMWaitEnumerator* enumerator -** The PRMWaitEnumerator object to destroy. -** RETURN -** PRStatus -** PR_SUCCESS if successful, PR_FAILURE otherwise. -** ERRORS -** PR_INVALID_ARGUMENT_ERROR -** The enumerator is invalid. -*/ -NSPR_API(PRStatus) PR_DestroyMWaitEnumerator(PRMWaitEnumerator* enumerator); - -/* -** FUNCTION: PR_EnumerateWaitGroup -** DESCRIPTION: -** PR_EnumerateWaitGroup is a thread safe enumerator over a wait group. -** Each call to the enumerator must present a valid PRMWaitEnumerator -** rererence and a pointer to the "previous" element returned from the -** enumeration process or a NULL. -** -** An enumeration is started by passing a NULL as the "previous" value. -** Subsequent calls to the enumerator must pass in the result of the -** previous call. The enumeration end is signaled by the runtime returning -** a NULL as the result. -** -** Modifications to the content of the wait group are allowed during -** an enumeration. The effect is that the enumeration may have to be -** "reset" and that may result in duplicates being returned from the -** enumeration. -** -** An enumeration may be abandoned at any time. The runtime is not -** keeping any state, so there are no issues in that regard. -*/ -NSPR_API(PRRecvWait*) PR_EnumerateWaitGroup( - PRMWaitEnumerator *enumerator, const PRRecvWait *previous); - -PR_END_EXTERN_C - -#endif /* defined(_PRMWAIT_H) */ - -/* prmwait.h */ diff --git a/win32/include/spidermonkey/nspr/prnetdb.h b/win32/include/spidermonkey/nspr/prnetdb.h deleted file mode 100755 index 49b77b14..00000000 --- a/win32/include/spidermonkey/nspr/prnetdb.h +++ /dev/null @@ -1,467 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prnetdb_h___ -#define prnetdb_h___ - -#include "prtypes.h" -#include "prio.h" - -PR_BEGIN_EXTERN_C - - -/* - ********************************************************************* - * Translate an Internet address to/from a character string - ********************************************************************* - */ -NSPR_API(PRStatus) PR_StringToNetAddr( - const char *string, PRNetAddr *addr); - -NSPR_API(PRStatus) PR_NetAddrToString( - const PRNetAddr *addr, char *string, PRUint32 size); - -/* -** Structures returned by network data base library. All addresses are -** supplied in host order, and returned in network order (suitable for -** use in system calls). -*/ -/* -** Beware that WINSOCK.H defines h_addrtype and h_length as short. -** Client code does direct struct copies of hostent to PRHostEnt and -** hence the ifdef. -*/ -typedef struct PRHostEnt { - char *h_name; /* official name of host */ - char **h_aliases; /* alias list */ -#ifdef WIN32 - PRInt16 h_addrtype; /* host address type */ - PRInt16 h_length; /* length of address */ -#else - PRInt32 h_addrtype; /* host address type */ - PRInt32 h_length; /* length of address */ -#endif - char **h_addr_list; /* list of addresses from name server */ -} PRHostEnt; - -/* A safe size to use that will mostly work... */ -#if (defined(AIX) && defined(_THREAD_SAFE)) || defined(OSF1) -#define PR_NETDB_BUF_SIZE sizeof(struct protoent_data) -#else -#define PR_NETDB_BUF_SIZE 1024 -#endif - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_GetHostByName() -** Lookup a host by name. -** -** INPUTS: -** char *hostname Character string defining the host name of interest -** char *buf A scratch buffer for the runtime to return result. -** This buffer is allocated by the caller. -** PRIntn bufsize Number of bytes in 'buf'. A recommnded value to -** use is PR_NETDB_BUF_SIZE. -** OUTPUTS: -** PRHostEnt *hostentry -** This structure is filled in by the runtime if -** the function returns PR_SUCCESS. This structure -** is allocated by the caller. -** RETURN: -** PRStatus PR_SUCCESS if the lookup succeeds. If it fails -** the result will be PR_FAILURE and the reason -** for the failure can be retrieved by PR_GetError(). -***********************************************************************/ -NSPR_API(PRStatus) PR_GetHostByName( - const char *hostname, char *buf, PRIntn bufsize, PRHostEnt *hostentry); - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_GetIPNodeByName() -** Lookup a host by name. Equivalent to getipnodebyname(AI_DEFAULT) -** of RFC 2553. -** -** INPUTS: -** char *hostname Character string defining the host name of interest -** PRUint16 af Address family (either PR_AF_INET or PR_AF_INET6) -** PRIntn flags Specifies the types of addresses that are searched -** for and the types of addresses that are returned. -** The only supported flag is PR_AI_DEFAULT. -** char *buf A scratch buffer for the runtime to return result. -** This buffer is allocated by the caller. -** PRIntn bufsize Number of bytes in 'buf'. A recommnded value to -** use is PR_NETDB_BUF_SIZE. -** OUTPUTS: -** PRHostEnt *hostentry -** This structure is filled in by the runtime if -** the function returns PR_SUCCESS. This structure -** is allocated by the caller. -** RETURN: -** PRStatus PR_SUCCESS if the lookup succeeds. If it fails -** the result will be PR_FAILURE and the reason -** for the failure can be retrieved by PR_GetError(). -***********************************************************************/ - - -#define PR_AI_ALL 0x08 -#define PR_AI_V4MAPPED 0x10 -#define PR_AI_ADDRCONFIG 0x20 -#define PR_AI_NOCANONNAME 0x8000 -#define PR_AI_DEFAULT (PR_AI_V4MAPPED | PR_AI_ADDRCONFIG) - -NSPR_API(PRStatus) PR_GetIPNodeByName( - const char *hostname, - PRUint16 af, - PRIntn flags, - char *buf, - PRIntn bufsize, - PRHostEnt *hostentry); - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_GetHostByAddr() -** Lookup a host entry by its network address. -** -** INPUTS: -** char *hostaddr IP address of host in question -** char *buf A scratch buffer for the runtime to return result. -** This buffer is allocated by the caller. -** PRIntn bufsize Number of bytes in 'buf'. A recommnded value to -** use is PR_NETDB_BUF_SIZE. -** OUTPUTS: -** PRHostEnt *hostentry -** This structure is filled in by the runtime if -** the function returns PR_SUCCESS. This structure -** is allocated by the caller. -** RETURN: -** PRStatus PR_SUCCESS if the lookup succeeds. If it fails -** the result will be PR_FAILURE and the reason -** for the failure can be retrieved by PR_GetError(). -***********************************************************************/ -NSPR_API(PRStatus) PR_GetHostByAddr( - const PRNetAddr *hostaddr, char *buf, PRIntn bufsize, PRHostEnt *hostentry); - -/*********************************************************************** -** FUNCTION: PR_EnumerateHostEnt() -** DESCRIPTION: -** A stateless enumerator over a PRHostEnt structure acquired from -** PR_GetHostByName() PR_GetHostByAddr() to evaluate the possible -** network addresses. -** -** INPUTS: -** PRIntn enumIndex Index of the enumeration. The enumeration starts -** and ends with a value of zero. -** -** PRHostEnt *hostEnt A pointer to a host entry struct that was -** previously returned by PR_GetHostByName() or -** PR_GetHostByAddr(). -** -** PRUint16 port The port number to be assigned as part of the -** PRNetAddr. -** -** OUTPUTS: -** PRNetAddr *address A pointer to an address structure that will be -** filled in by the call to the enumeration if the -** result of the call is greater than zero. -** -** RETURN: -** PRIntn The value that should be used for the next call -** of the enumerator ('enumIndex'). The enumeration -** is ended if this value is returned zero. -** If a value of -1 is returned, the enumeration -** has failed. The reason for the failure can be -** retrieved by calling PR_GetError(). -***********************************************************************/ -NSPR_API(PRIntn) PR_EnumerateHostEnt( - PRIntn enumIndex, const PRHostEnt *hostEnt, PRUint16 port, PRNetAddr *address); - -/*********************************************************************** -** FUNCTION: PR_InitializeNetAddr(), -** DESCRIPTION: -** Initialize the fields of a PRNetAddr, assigning well known values as -** appropriate. -** -** INPUTS -** PRNetAddrValue val The value to be assigned to the IP Address portion -** of the network address. This can only specify the -** special well known values that are equivalent to -** INADDR_ANY and INADDR_LOOPBACK. -** -** PRUint16 port The port number to be assigned in the structure. -** -** OUTPUTS: -** PRNetAddr *addr The address to be manipulated. -** -** RETURN: -** PRStatus To indicate success or failure. If the latter, the -** reason for the failure can be retrieved by calling -** PR_GetError(); -***********************************************************************/ -typedef enum PRNetAddrValue -{ - PR_IpAddrNull, /* do NOT overwrite the IP address */ - PR_IpAddrAny, /* assign logical INADDR_ANY to IP address */ - PR_IpAddrLoopback, /* assign logical INADDR_LOOPBACK */ - PR_IpAddrV4Mapped /* IPv4 mapped address */ -} PRNetAddrValue; - -NSPR_API(PRStatus) PR_InitializeNetAddr( - PRNetAddrValue val, PRUint16 port, PRNetAddr *addr); - -/*********************************************************************** -** FUNCTION: PR_SetNetAddr(), -** DESCRIPTION: -** Set the fields of a PRNetAddr, assigning well known values as -** appropriate. This function is similar to PR_InitializeNetAddr -** but differs in that the address family is specified. -** -** INPUTS -** PRNetAddrValue val The value to be assigned to the IP Address portion -** of the network address. This can only specify the -** special well known values that are equivalent to -** INADDR_ANY and INADDR_LOOPBACK. -** -** PRUint16 af The address family (either PR_AF_INET or PR_AF_INET6) -** -** PRUint16 port The port number to be assigned in the structure. -** -** OUTPUTS: -** PRNetAddr *addr The address to be manipulated. -** -** RETURN: -** PRStatus To indicate success or failure. If the latter, the -** reason for the failure can be retrieved by calling -** PR_GetError(); -***********************************************************************/ -NSPR_API(PRStatus) PR_SetNetAddr( - PRNetAddrValue val, PRUint16 af, PRUint16 port, PRNetAddr *addr); - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_IsNetAddrType() -** Determine if the network address is of the specified type. -** -** INPUTS: -** const PRNetAddr *addr A network address. -** PRNetAddrValue The type of network address -** -** RETURN: -** PRBool PR_TRUE if the network address is of the -** specified type, else PR_FALSE. -***********************************************************************/ -NSPR_API(PRBool) PR_IsNetAddrType(const PRNetAddr *addr, PRNetAddrValue val); - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_ConvertIPv4AddrToIPv6() -** Convert an IPv4 addr to an (IPv4-mapped) IPv6 addr -** -** INPUTS: -** PRUint32 v4addr IPv4 address -** -** OUTPUTS: -** PRIPv6Addr *v6addr The converted IPv6 address -** -** RETURN: -** void -** -***********************************************************************/ -NSPR_API(void) PR_ConvertIPv4AddrToIPv6(PRUint32 v4addr, PRIPv6Addr *v6addr); - -/*********************************************************************** -** MACRO: -** DESCRIPTION: PR_NetAddrFamily() -** Get the 'family' field of a PRNetAddr union. -** -** INPUTS: -** const PRNetAddr *addr A network address. -** -** RETURN: -** PRUint16 The 'family' field of 'addr'. -***********************************************************************/ -#define PR_NetAddrFamily(addr) ((addr)->raw.family) - -/*********************************************************************** -** MACRO: -** DESCRIPTION: PR_NetAddrInetPort() -** Get the 'port' field of a PRNetAddr union. -** -** INPUTS: -** const PRNetAddr *addr A network address. -** -** RETURN: -** PRUint16 The 'port' field of 'addr'. -***********************************************************************/ -#define PR_NetAddrInetPort(addr) \ - ((addr)->raw.family == PR_AF_INET6 ? (addr)->ipv6.port : (addr)->inet.port) - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_GetProtoByName() -** Lookup a protocol entry based on protocol's name -** -** INPUTS: -** char *protocolname Character string of the protocol's name. -** char *buf A scratch buffer for the runtime to return result. -** This buffer is allocated by the caller. -** PRIntn bufsize Number of bytes in 'buf'. A recommnded value to -** use is PR_NETDB_BUF_SIZE. -** OUTPUTS: -** PRHostEnt *PRProtoEnt -** This structure is filled in by the runtime if -** the function returns PR_SUCCESS. This structure -** is allocated by the caller. -** RETURN: -** PRStatus PR_SUCCESS if the lookup succeeds. If it fails -** the result will be PR_FAILURE and the reason -** for the failure can be retrieved by PR_GetError(). -***********************************************************************/ - -typedef struct PRProtoEnt { - char *p_name; /* official protocol name */ - char **p_aliases; /* alias list */ -#ifdef WIN32 - PRInt16 p_num; /* protocol # */ -#else - PRInt32 p_num; /* protocol # */ -#endif -} PRProtoEnt; - -NSPR_API(PRStatus) PR_GetProtoByName( - const char* protocolname, char* buffer, PRInt32 bufsize, PRProtoEnt* result); - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_GetProtoByNumber() -** Lookup a protocol entry based on protocol's number -** -** INPUTS: -** PRInt32 protocolnumber -** Number assigned to the protocol. -** char *buf A scratch buffer for the runtime to return result. -** This buffer is allocated by the caller. -** PRIntn bufsize Number of bytes in 'buf'. A recommnded value to -** use is PR_NETDB_BUF_SIZE. -** OUTPUTS: -** PRHostEnt *PRProtoEnt -** This structure is filled in by the runtime if -** the function returns PR_SUCCESS. This structure -** is allocated by the caller. -** RETURN: -** PRStatus PR_SUCCESS if the lookup succeeds. If it fails -** the result will be PR_FAILURE and the reason -** for the failure can be retrieved by PR_GetError(). -***********************************************************************/ -NSPR_API(PRStatus) PR_GetProtoByNumber( - PRInt32 protocolnumber, char* buffer, PRInt32 bufsize, PRProtoEnt* result); - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_GetAddrInfoByName() -** Look up a host by name. Equivalent to getaddrinfo(host, NULL, ...) of -** RFC 3493. -** -** INPUTS: -** char *hostname Character string defining the host name of interest -** PRUint16 af May be PR_AF_UNSPEC or PR_AF_INET. -** PRIntn flags May be either PR_AI_ADDRCONFIG or -** PR_AI_ADDRCONFIG | PR_AI_NOCANONNAME. Include -** PR_AI_NOCANONNAME to suppress the determination of -** the canonical name corresponding to hostname. -** RETURN: -** PRAddrInfo* Handle to a data structure containing the results -** of the host lookup. Use PR_EnumerateAddrInfo to -** inspect the PRNetAddr values stored in this object. -** When no longer needed, this handle must be destroyed -** with a call to PR_FreeAddrInfo. If a lookup error -** occurs, then NULL will be returned. -***********************************************************************/ -typedef struct PRAddrInfo PRAddrInfo; - -NSPR_API(PRAddrInfo*) PR_GetAddrInfoByName( - const char *hostname, PRUint16 af, PRIntn flags); - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_FreeAddrInfo() -** Destroy the PRAddrInfo handle allocated by PR_GetAddrInfoByName(). -** -** INPUTS: -** PRAddrInfo *addrInfo -** The handle resulting from a successful call to -** PR_GetAddrInfoByName(). -** RETURN: -** void -***********************************************************************/ -NSPR_API(void) PR_FreeAddrInfo(PRAddrInfo *addrInfo); - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_EnumerateAddrInfo() -** A stateless enumerator over a PRAddrInfo handle acquired from -** PR_GetAddrInfoByName() to inspect the possible network addresses. -** -** INPUTS: -** void *enumPtr Index pointer of the enumeration. The enumeration -** starts and ends with a value of NULL. -** const PRAddrInfo *addrInfo -** The PRAddrInfo handle returned by a successful -** call to PR_GetAddrInfoByName(). -** PRUint16 port The port number to be assigned as part of the -** PRNetAddr. -** OUTPUTS: -** PRNetAddr *result A pointer to an address structure that will be -** filled in by the call to the enumeration if the -** result of the call is not NULL. -** RETURN: -** void* The value that should be used for the next call -** of the enumerator ('enumPtr'). The enumeration -** is ended if this value is NULL. -***********************************************************************/ -NSPR_API(void *) PR_EnumerateAddrInfo( - void *enumPtr, const PRAddrInfo *addrInfo, PRUint16 port, PRNetAddr *result); - -/*********************************************************************** -** FUNCTION: -** DESCRIPTION: PR_GetCanonNameFromAddrInfo() -** Extracts the canonical name of the hostname passed to -** PR_GetAddrInfoByName(). -** -** INPUTS: -** const PRAddrInfo *addrInfo -** The PRAddrInfo handle returned by a successful -** call to PR_GetAddrInfoByName(). -** RETURN: -** const char * A const pointer to the canonical hostname stored -** in the given PRAddrInfo handle. This pointer is -** invalidated once the PRAddrInfo handle is destroyed -** by a call to PR_FreeAddrInfo(). -***********************************************************************/ -NSPR_API(const char *) PR_GetCanonNameFromAddrInfo( - const PRAddrInfo *addrInfo); - -/*********************************************************************** -** FUNCTIONS: PR_ntohs, PR_ntohl, PR_ntohll, PR_htons, PR_htonl, PR_htonll -** -** DESCRIPTION: API entries for the common byte ordering routines. -** -** PR_ntohs 16 bit conversion from network to host -** PR_ntohl 32 bit conversion from network to host -** PR_ntohll 64 bit conversion from network to host -** PR_htons 16 bit conversion from host to network -** PR_htonl 32 bit conversion from host to network -** PR_ntonll 64 bit conversion from host to network -** -***********************************************************************/ -NSPR_API(PRUint16) PR_ntohs(PRUint16); -NSPR_API(PRUint32) PR_ntohl(PRUint32); -NSPR_API(PRUint64) PR_ntohll(PRUint64); -NSPR_API(PRUint16) PR_htons(PRUint16); -NSPR_API(PRUint32) PR_htonl(PRUint32); -NSPR_API(PRUint64) PR_htonll(PRUint64); - -PR_END_EXTERN_C - -#endif /* prnetdb_h___ */ diff --git a/win32/include/spidermonkey/nspr/prolock.h b/win32/include/spidermonkey/nspr/prolock.h deleted file mode 100755 index 5e5a4093..00000000 --- a/win32/include/spidermonkey/nspr/prolock.h +++ /dev/null @@ -1,178 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prolock_h___ -#define prolock_h___ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/* -** A locking mechanism, built on the existing PRLock definition, -** is provided that will permit applications to define a Lock -** Hierarchy (or Lock Ordering) schema. An application designed -** using the Ordered Lock functions will terminate with a -** diagnostic message when a lock inversion condition is -** detected. -** -** The lock ordering detection is compile-time enabled only. In -** optimized builds of NSPR, the Ordered Lock functions map -** directly to PRLock functions, providing no lock order -** detection. -** -** The Ordered Lock Facility is compiled in when DEBUG is defined at -** compile-time. Ordered Lock can be forced on in optimized builds by -** defining FORCE_NSPR_ORDERED_LOCK at compile-time. Both the -** application using Ordered Lock and NSPR must be compiled with the -** facility enabled to achieve the desired results. -** -** Application designers should use the macro interfaces to the Ordered -** Lock facility to ensure that it is compiled out in optimized builds. -** -** Application designers are responsible for defining their own -** lock hierarchy. -** -** Ordered Lock is thread-safe and SMP safe. -** -** See Also: prlock.h -** -** /lth. 10-Jun-1998. -** -*/ - -/* -** Opaque type for ordered lock. -** ... Don't even think of looking in here. -** -*/ - -#if defined(DEBUG) || defined(FORCE_NSPR_ORDERED_LOCKS) -typedef void * PROrderedLock; -#else -/* -** Map PROrderedLock and methods onto PRLock when ordered locking -** is not compiled in. -** -*/ -#include "prlock.h" - -typedef PRLock PROrderedLock; -#endif - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_CreateOrderedLock() -- Create an Ordered Lock -** -** DESCRIPTION: PR_CreateOrderedLock() creates an ordered lock. -** -** INPUTS: -** order: user defined order of this lock. -** name: name of the lock. For debugging purposes. -** -** OUTPUTS: returned -** -** RETURNS: PR_OrderedLock pointer -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_ORDERED_LOCKS) -#define PR_CREATE_ORDERED_LOCK(order,name)\ - PR_CreateOrderedLock((order),(name)) -#else -#define PR_CREATE_ORDERED_LOCK(order) PR_NewLock() -#endif - -NSPR_API(PROrderedLock *) - PR_CreateOrderedLock( - PRInt32 order, - const char *name -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_DestroyOrderedLock() -- Destroy an Ordered Lock -** -** DESCRIPTION: PR_DestroyOrderedLock() destroys the ordered lock -** referenced by lock. -** -** INPUTS: lock: pointer to a PROrderedLock -** -** OUTPUTS: the lock is destroyed -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_ORDERED_LOCKS) -#define PR_DESTROY_ORDERED_LOCK(lock) PR_DestroyOrderedLock((lock)) -#else -#define PR_DESTROY_ORDERED_LOCK(lock) PR_DestroyLock((lock)) -#endif - -NSPR_API(void) - PR_DestroyOrderedLock( - PROrderedLock *lock -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_LockOrderedLock() -- Lock an ordered lock -** -** DESCRIPTION: PR_LockOrderedLock() locks the ordered lock -** referenced by lock. If the order of lock is less than or equal -** to the order of the highest lock held by the locking thread, -** the function asserts. -** -** INPUTS: lock: a pointer to a PROrderedLock -** -** OUTPUTS: The lock is held or the function asserts. -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_ORDERED_LOCKS) -#define PR_LOCK_ORDERED_LOCK(lock) PR_LockOrderedLock((lock)) -#else -#define PR_LOCK_ORDERED_LOCK(lock) PR_Lock((lock)) -#endif - -NSPR_API(void) - PR_LockOrderedLock( - PROrderedLock *lock -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_UnlockOrderedLock() -- unlock and Ordered Lock -** -** DESCRIPTION: PR_UnlockOrderedLock() unlocks the lock referenced -** by lock. -** -** INPUTS: lock: a pointer to a PROrderedLock -** -** OUTPUTS: the lock is unlocked -** -** RETURNS: -** PR_SUCCESS -** PR_FAILURE -** -** RESTRICTIONS: -** -*/ -#if defined(DEBUG) || defined(FORCE_NSPR_ORDERED_LOCKS) -#define PR_UNLOCK_ORDERED_LOCK(lock) PR_UnlockOrderedLock((lock)) -#else -#define PR_UNLOCK_ORDERED_LOCK(lock) PR_Unlock((lock)) -#endif - -NSPR_API(PRStatus) - PR_UnlockOrderedLock( - PROrderedLock *lock -); - -PR_END_EXTERN_C - -#endif /* prolock_h___ */ diff --git a/win32/include/spidermonkey/nspr/prpdce.h b/win32/include/spidermonkey/nspr/prpdce.h deleted file mode 100755 index b681795f..00000000 --- a/win32/include/spidermonkey/nspr/prpdce.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - * File: prpdce.h - * Description: This file is the API defined to allow for DCE (aka POSIX) - * thread emulation in an NSPR environment. It is not the - * intent that this be a fully supported API. - */ - -#if !defined(PRPDCE_H) -#define PRPDCE_H - -#include "prlock.h" -#include "prcvar.h" -#include "prtypes.h" -#include "prinrval.h" - -PR_BEGIN_EXTERN_C - -#define _PR_NAKED_CV_LOCK (PRLock*)0xdce1dce1 - -/* -** Test and acquire a lock. -** -** If the lock is acquired by the calling thread, the -** return value will be PR_SUCCESS. If the lock is -** already held, by another thread or this thread, the -** result will be PR_FAILURE. -*/ -NSPR_API(PRStatus) PRP_TryLock(PRLock *lock); - -/* -** Create a naked condition variable -** -** A "naked" condition variable is one that is not created bound -** to a lock. The CV created with this function is the only type -** that may be used in the subsequent "naked" condition variable -** operations (see PRP_NakedWait, PRP_NakedNotify, PRP_NakedBroadcast); -*/ -NSPR_API(PRCondVar*) PRP_NewNakedCondVar(void); - -/* -** Destroy a naked condition variable -** -** Destroy the condition variable created by PR_NewNakedCondVar. -*/ -NSPR_API(void) PRP_DestroyNakedCondVar(PRCondVar *cvar); - -/* -** Wait on a condition -** -** Wait on the condition variable 'cvar'. It is asserted that -** the lock protecting the condition 'lock' is held by the -** calling thread. If more time expires than that declared in -** 'timeout' the condition will be notified. Waits can be -** interrupted by another thread. -** -** NB: The CV ('cvar') must be one created using PR_NewNakedCondVar. -*/ -NSPR_API(PRStatus) PRP_NakedWait( - PRCondVar *cvar, PRLock *lock, PRIntervalTime timeout); - -/* -** Notify a thread waiting on a condition -** -** Notify the condition specified 'cvar'. -** -** NB: The CV ('cvar') must be one created using PR_NewNakedCondVar. -*/ -NSPR_API(PRStatus) PRP_NakedNotify(PRCondVar *cvar); - -/* -** Notify all threads waiting on a condition -** -** Notify the condition specified 'cvar'. -** -** NB: The CV ('cvar') must be one created using PR_NewNakedCondVar. -*/ -NSPR_API(PRStatus) PRP_NakedBroadcast(PRCondVar *cvar); - -PR_END_EXTERN_C - -#endif /* PRPDCE_H */ diff --git a/win32/include/spidermonkey/nspr/prprf.h b/win32/include/spidermonkey/nspr/prprf.h deleted file mode 100755 index 440be888..00000000 --- a/win32/include/spidermonkey/nspr/prprf.h +++ /dev/null @@ -1,122 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prprf_h___ -#define prprf_h___ - -/* -** API for PR printf like routines. Supports the following formats -** %d - decimal -** %u - unsigned decimal -** %x - unsigned hex -** %X - unsigned uppercase hex -** %o - unsigned octal -** %hd, %hu, %hx, %hX, %ho - 16-bit versions of above -** %ld, %lu, %lx, %lX, %lo - 32-bit versions of above -** %lld, %llu, %llx, %llX, %llo - 64 bit versions of above -** %s - string -** %c - character -** %p - pointer (deals with machine dependent pointer size) -** %f - float -** %g - float -*/ -#include "prtypes.h" -#include "prio.h" -#include -#include - -PR_BEGIN_EXTERN_C - -/* -** sprintf into a fixed size buffer. Guarantees that a NUL is at the end -** of the buffer. Returns the length of the written output, NOT including -** the NUL, or (PRUint32)-1 if an error occurs. -*/ -NSPR_API(PRUint32) PR_snprintf(char *out, PRUint32 outlen, const char *fmt, ...); - -/* -** sprintf into a PR_MALLOC'd buffer. Return a pointer to the malloc'd -** buffer on success, NULL on failure. Call "PR_smprintf_free" to release -** the memory returned. -*/ -NSPR_API(char*) PR_smprintf(const char *fmt, ...); - -/* -** Free the memory allocated, for the caller, by PR_smprintf -*/ -NSPR_API(void) PR_smprintf_free(char *mem); - -/* -** "append" sprintf into a PR_MALLOC'd buffer. "last" is the last value of -** the PR_MALLOC'd buffer. sprintf will append data to the end of last, -** growing it as necessary using realloc. If last is NULL, PR_sprintf_append -** will allocate the initial string. The return value is the new value of -** last for subsequent calls, or NULL if there is a malloc failure. -*/ -NSPR_API(char*) PR_sprintf_append(char *last, const char *fmt, ...); - -/* -** sprintf into a function. The function "f" is called with a string to -** place into the output. "arg" is an opaque pointer used by the stuff -** function to hold any state needed to do the storage of the output -** data. The return value is a count of the number of characters fed to -** the stuff function, or (PRUint32)-1 if an error occurs. -*/ -typedef PRIntn (*PRStuffFunc)(void *arg, const char *s, PRUint32 slen); - -NSPR_API(PRUint32) PR_sxprintf(PRStuffFunc f, void *arg, const char *fmt, ...); - -/* -** fprintf to a PRFileDesc -*/ -NSPR_API(PRUint32) PR_fprintf(struct PRFileDesc* fd, const char *fmt, ...); - -/* -** va_list forms of the above. -*/ -NSPR_API(PRUint32) PR_vsnprintf(char *out, PRUint32 outlen, const char *fmt, va_list ap); -NSPR_API(char*) PR_vsmprintf(const char *fmt, va_list ap); -NSPR_API(char*) PR_vsprintf_append(char *last, const char *fmt, va_list ap); -NSPR_API(PRUint32) PR_vsxprintf(PRStuffFunc f, void *arg, const char *fmt, va_list ap); -NSPR_API(PRUint32) PR_vfprintf(struct PRFileDesc* fd, const char *fmt, va_list ap); - -/* -*************************************************************************** -** FUNCTION: PR_sscanf -** DESCRIPTION: -** PR_sscanf() scans the input character string, performs data -** conversions, and stores the converted values in the data objects -** pointed to by its arguments according to the format control -** string. -** -** PR_sscanf() behaves the same way as the sscanf() function in the -** Standard C Library (stdio.h), with the following exceptions: -** - PR_sscanf() handles the NSPR integer and floating point types, -** such as PRInt16, PRInt32, PRInt64, and PRFloat64, whereas -** sscanf() handles the standard C types like short, int, long, -** and double. -** - PR_sscanf() has no multibyte character support, while sscanf() -** does. -** INPUTS: -** const char *buf -** a character string holding the input to scan -** const char *fmt -** the format control string for the conversions -** ... -** variable number of arguments, each of them is a pointer to -** a data object in which the converted value will be stored -** OUTPUTS: none -** RETURNS: PRInt32 -** The number of values converted and stored. -** RESTRICTIONS: -** Multibyte characters in 'buf' or 'fmt' are not allowed. -*************************************************************************** -*/ - -NSPR_API(PRInt32) PR_sscanf(const char *buf, const char *fmt, ...); - -PR_END_EXTERN_C - -#endif /* prprf_h___ */ diff --git a/win32/include/spidermonkey/nspr/prproces.h b/win32/include/spidermonkey/nspr/prproces.h deleted file mode 100755 index 97825422..00000000 --- a/win32/include/spidermonkey/nspr/prproces.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prproces_h___ -#define prproces_h___ - -#include "prtypes.h" -#include "prio.h" - -PR_BEGIN_EXTERN_C - -/************************************************************************/ -/*****************************PROCESS OPERATIONS*************************/ -/************************************************************************/ - -typedef struct PRProcess PRProcess; -typedef struct PRProcessAttr PRProcessAttr; - -NSPR_API(PRProcessAttr *) PR_NewProcessAttr(void); - -NSPR_API(void) PR_ResetProcessAttr(PRProcessAttr *attr); - -NSPR_API(void) PR_DestroyProcessAttr(PRProcessAttr *attr); - -NSPR_API(void) PR_ProcessAttrSetStdioRedirect( - PRProcessAttr *attr, - PRSpecialFD stdioFd, - PRFileDesc *redirectFd -); - -/* - * OBSOLETE -- use PR_ProcessAttrSetStdioRedirect instead. - */ -NSPR_API(void) PR_SetStdioRedirect( - PRProcessAttr *attr, - PRSpecialFD stdioFd, - PRFileDesc *redirectFd -); - -NSPR_API(PRStatus) PR_ProcessAttrSetCurrentDirectory( - PRProcessAttr *attr, - const char *dir -); - -NSPR_API(PRStatus) PR_ProcessAttrSetInheritableFD( - PRProcessAttr *attr, - PRFileDesc *fd, - const char *name -); - -/* -** Create a new process -** -** Create a new process executing the file specified as 'path' and with -** the supplied arguments and environment. -** -** This function may fail because of illegal access (permissions), -** invalid arguments or insufficient resources. -** -** A process may be created such that the creator can later synchronize its -** termination using PR_WaitProcess(). -*/ - -NSPR_API(PRProcess*) PR_CreateProcess( - const char *path, - char *const *argv, - char *const *envp, - const PRProcessAttr *attr); - -NSPR_API(PRStatus) PR_CreateProcessDetached( - const char *path, - char *const *argv, - char *const *envp, - const PRProcessAttr *attr); - -NSPR_API(PRStatus) PR_DetachProcess(PRProcess *process); - -NSPR_API(PRStatus) PR_WaitProcess(PRProcess *process, PRInt32 *exitCode); - -NSPR_API(PRStatus) PR_KillProcess(PRProcess *process); - -PR_END_EXTERN_C - -#endif /* prproces_h___ */ diff --git a/win32/include/spidermonkey/nspr/prrng.h b/win32/include/spidermonkey/nspr/prrng.h deleted file mode 100755 index 3b5a4433..00000000 --- a/win32/include/spidermonkey/nspr/prrng.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - - -/* -** prrng.h -- NSPR Random Number Generator -** -** -** lth. 29-Oct-1999. -*/ - -#ifndef prrng_h___ -#define prrng_h___ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/* -** PR_GetRandomNoise() -- Get random noise from the host platform -** -** Description: -** PR_GetRandomNoise() provides, depending on platform, a random value. -** The length of the random value is dependent on platform and the -** platform's ability to provide a random value at that moment. -** -** The intent of PR_GetRandomNoise() is to provide a "seed" value for a -** another random number generator that may be suitable for -** cryptographic operations. This implies that the random value -** provided may not be, by itself, cryptographically secure. The value -** generated by PR_GetRandomNoise() is at best, extremely difficult to -** predict and is as non-deterministic as the underlying platfrom can -** provide. -** -** Inputs: -** buf -- pointer to a caller supplied buffer to contain the -** generated random number. buf must be at least as large as -** is specified in the 'size' argument. -** -** size -- the requested size of the generated random number -** -** Outputs: -** a random number provided in 'buf'. -** -** Returns: -** PRSize value equal to the size of the random number actually -** generated, or zero. The generated size may be less than the size -** requested. A return value of zero means that PR_GetRandomNoise() is -** not implemented on this platform, or there is no available noise -** available to be returned at the time of the call. -** -** Restrictions: -** Calls to PR_GetRandomNoise() may use a lot of CPU on some platforms. -** Some platforms may block for up to a few seconds while they -** accumulate some noise. Busy machines generate lots of noise, but -** care is advised when using PR_GetRandomNoise() frequently in your -** application. -** -** History: -** Parts of the model dependent implementation for PR_GetRandomNoise() -** were taken in whole or part from code previously in Netscape's NSS -** component. -** -*/ -NSPR_API(PRSize) PR_GetRandomNoise( - void *buf, - PRSize size -); - -PR_END_EXTERN_C - -#endif /* prrng_h___ */ -/* end prrng.h */ diff --git a/win32/include/spidermonkey/nspr/prrwlock.h b/win32/include/spidermonkey/nspr/prrwlock.h deleted file mode 100755 index 65d052dd..00000000 --- a/win32/include/spidermonkey/nspr/prrwlock.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: prrwlock.h -** Description: API to basic reader-writer lock functions of NSPR. -** -**/ - -#ifndef prrwlock_h___ -#define prrwlock_h___ - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/* - * PRRWLock -- - * - * The reader writer lock, PRRWLock, is an opaque object to the clients - * of NSPR. All routines operate on a pointer to this opaque entity. - */ - - -typedef struct PRRWLock PRRWLock; - -#define PR_RWLOCK_RANK_NONE 0 - - -/*********************************************************************** -** FUNCTION: PR_NewRWLock -** DESCRIPTION: -** Returns a pointer to a newly created reader-writer lock object. -** INPUTS: Lock rank -** Lock name -** OUTPUTS: void -** RETURN: PRRWLock* -** If the lock cannot be created because of resource constraints, NULL -** is returned. -** -***********************************************************************/ -NSPR_API(PRRWLock*) PR_NewRWLock(PRUint32 lock_rank, const char *lock_name); - -/*********************************************************************** -** FUNCTION: PR_DestroyRWLock -** DESCRIPTION: -** Destroys a given RW lock object. -** INPUTS: PRRWLock *lock - Lock to be freed. -** OUTPUTS: void -** RETURN: None -***********************************************************************/ -NSPR_API(void) PR_DestroyRWLock(PRRWLock *lock); - -/*********************************************************************** -** FUNCTION: PR_RWLock_Rlock -** DESCRIPTION: -** Apply a read lock (non-exclusive) on a RWLock -** INPUTS: PRRWLock *lock - Lock to be read-locked. -** OUTPUTS: void -** RETURN: None -***********************************************************************/ -NSPR_API(void) PR_RWLock_Rlock(PRRWLock *lock); - -/*********************************************************************** -** FUNCTION: PR_RWLock_Wlock -** DESCRIPTION: -** Apply a write lock (exclusive) on a RWLock -** INPUTS: PRRWLock *lock - Lock to write-locked. -** OUTPUTS: void -** RETURN: None -***********************************************************************/ -NSPR_API(void) PR_RWLock_Wlock(PRRWLock *lock); - -/*********************************************************************** -** FUNCTION: PR_RWLock_Unlock -** DESCRIPTION: -** Release a RW lock. Unlocking an unlocked lock has undefined results. -** INPUTS: PRRWLock *lock - Lock to unlocked. -** OUTPUTS: void -** RETURN: void -***********************************************************************/ -NSPR_API(void) PR_RWLock_Unlock(PRRWLock *lock); - -PR_END_EXTERN_C - -#endif /* prrwlock_h___ */ diff --git a/win32/include/spidermonkey/nspr/prshm.h b/win32/include/spidermonkey/nspr/prshm.h deleted file mode 100755 index f821a58e..00000000 --- a/win32/include/spidermonkey/nspr/prshm.h +++ /dev/null @@ -1,257 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** prshm.h -- NSPR Shared Memory -** -** NSPR Named Shared Memory API provides a cross-platform named -** shared-memory interface. NSPR Named Shared Memory is modeled on -** similar constructs in Unix and Windows operating systems. Shared -** memory allows multiple processes to access one or more common shared -** memory regions, using it as an inter-process communication channel. -** -** Notes on Platform Independence: -** NSPR Named Shared Memory is built on the native services offered -** by most platforms. The NSPR Named Shared Memory API tries to -** provide a least common denominator interface so that it works -** across all supported platforms. To ensure that it works everywhere, -** some platform considerations must be accomodated and the protocol -** for using NSPR Shared Memory API must be observed. -** -** Protocol: -** Multiple shared memories can be created using NSPR's Shared Memory -** feature. For each named shared memory, as defined by the name -** given in the PR_OpenSharedMemory() call, a protocol for using the -** shared memory API is required to ensure desired behavior. Failing -** to follow the protocol may yield unpredictable results. -** -** PR_OpenSharedMemory() will create the shared memory segment, if it -** does not already exist, or open a connection that the existing -** shared memory segment if it already exists. -** -** PR_AttachSharedMemory() should be called following -** PR_OpenSharedMemory() to map the memory segment to an address in -** the application's address space. -** -** PR_AttachSharedMemory() may be called to re-map a shared memory -** segment after detaching the same PRSharedMemory object. Be -** sure to detach it when done. -** -** PR_DetachSharedMemory() should be called to un-map the shared -** memory segment from the application's address space. -** -** PR_CloseSharedMemory() should be called when no further use of the -** PRSharedMemory object is required within a process. Following a -** call to PR_CloseSharedMemory() the PRSharedMemory object is -** invalid and cannot be reused. -** -** PR_DeleteSharedMemory() should be called before process -** termination. After calling PR_DeleteSharedMemory() any further use -** of the shared memory associated with the name may cause -** unpredictable results. -** -** Files: -** The name passed to PR_OpenSharedMemory() should be a valid filename -** for a unix platform. PR_OpenSharedMemory() creates file using the -** name passed in. Some platforms may mangle the name before creating -** the file and the shared memory. -** -** The unix implementation may use SysV IPC shared memory, Posix -** shared memory, or memory mapped files; the filename may used to -** define the namespace. On Windows, the name is significant, but -** there is no file associated with name. -** -** No assumptions about the persistence of data in the named file -** should be made. Depending on platform, the shared memory may be -** mapped onto system paging space and be discarded at process -** termination. -** -** All names provided to PR_OpenSharedMemory() should be valid -** filename syntax or name syntax for shared memory for the target -** platform. Referenced directories should have permissions -** appropriate for writing. -** -** Limits: -** Different platforms have limits on both the number and size of -** shared memory resources. The default system limits on some -** platforms may be smaller than your requirements. These limits may -** be adjusted on some platforms either via boot-time options or by -** setting the size of the system paging space to accomodate more -** and/or larger shared memory segment(s). -** -** Security: -** On unix platforms, depending on implementation, contents of the -** backing store for the shared memory can be exposed via the file -** system. Set permissions and or access controls at create and attach -** time to ensure you get the desired security. -** -** On windows platforms, no special security measures are provided. -** -** Example: -** The test case pr/tests/nameshm1.c provides an example of use as -** well as testing the operation of NSPR's Named Shared Memory. -** -** lth. 18-Aug-1999. -*/ - -#ifndef prshm_h___ -#define prshm_h___ - -#include "prtypes.h" -#include "prio.h" - -PR_BEGIN_EXTERN_C - -/* -** Declare opaque type PRSharedMemory. -*/ -typedef struct PRSharedMemory PRSharedMemory; - -/* -** FUNCTION: PR_OpenSharedMemory() -** -** DESCRIPTION: -** PR_OpenSharedMemory() creates a new shared-memory segment or -** associates a previously created memory segment with name. -** -** When parameter create is (PR_SHM_EXCL | PR_SHM_CREATE) and the -** shared memory already exists, the function returns NULL with the -** error set to PR_FILE_EXISTS_ERROR. -** -** When parameter create is PR_SHM_CREATE and the shared memory -** already exists, a handle to that memory segment is returned. If -** the segment does not exist, it is created and a pointer to the -** related PRSharedMemory structure is returned. -** -** When parameter create is 0, and the shared memory exists, a -** pointer to a PRSharedMemory is returned. If the shared memory does -** not exist, NULL is returned with the error set to -** PR_FILE_NOT_FOUND_ERROR. -** -** INPUTS: -** name -- the name the shared-memory segment is known as. -** size -- the size of the shared memory segment. -** flags -- Options for creating the shared memory -** mode -- Same as is passed to PR_Open() -** -** OUTPUTS: -** The shared memory is allocated. -** -** RETURNS: Pointer to opaque structure PRSharedMemory or NULL. -** NULL is returned on error. The reason for the error can be -** retrieved via PR_GetError() and PR_GetOSError(); -** -*/ -NSPR_API( PRSharedMemory * ) - PR_OpenSharedMemory( - const char *name, - PRSize size, - PRIntn flags, - PRIntn mode -); -/* Define values for PR_OpenShareMemory(...,create) */ -#define PR_SHM_CREATE 0x1 /* create if not exist */ -#define PR_SHM_EXCL 0x2 /* fail if already exists */ - -/* -** FUNCTION: PR_AttachSharedMemory() -** -** DESCRIPTION: -** PR_AttachSharedMemory() maps the shared-memory described by -** shm to the current process. -** -** INPUTS: -** shm -- The handle returned from PR_OpenSharedMemory(). -** flags -- options for mapping the shared memory. -** PR_SHM_READONLY causes the memory to be attached -** read-only. -** -** OUTPUTS: -** On success, the shared memory segment represented by shm is mapped -** into the process' address space. -** -** RETURNS: Address where shared memory is mapped, or NULL. -** NULL is returned on error. The reason for the error can be -** retrieved via PR_GetError() and PR_GetOSError(); -** -** -*/ -NSPR_API( void * ) - PR_AttachSharedMemory( - PRSharedMemory *shm, - PRIntn flags -); -/* Define values for PR_AttachSharedMemory(...,flags) */ -#define PR_SHM_READONLY 0x01 - -/* -** FUNCTION: PR_DetachSharedMemory() -** -** DESCRIPTION: -** PR_DetachSharedMemory() detaches the shared-memory described -** by shm. -** -** INPUTS: -** shm -- The handle returned from PR_OpenSharedMemory(). -** addr -- The address at which the memory was attached. -** -** OUTPUTS: -** The shared memory mapped to an address via a previous call to -** PR_AttachSharedMemory() is unmapped. -** -** RETURNS: PRStatus -** -*/ -NSPR_API( PRStatus ) - PR_DetachSharedMemory( - PRSharedMemory *shm, - void *addr -); - -/* -** FUNCTION: PR_CloseSharedMemory() -** -** DESCRIPTION: -** PR_CloseSharedMemory() closes the shared-memory described by -** shm. -** -** INPUTS: -** shm -- The handle returned from PR_OpenSharedMemory(). -** -** OUTPUTS: -** the shared memory represented by shm is closed -** -** RETURNS: PRStatus -** -*/ -NSPR_API( PRStatus ) - PR_CloseSharedMemory( - PRSharedMemory *shm -); - -/* -** FUNCTION: PR_DeleteSharedMemory() -** -** DESCRIPTION: -** The shared memory resource represented by name is released. -** -** INPUTS: -** name -- the name the shared-memory segment -** -** OUTPUTS: -** depending on platform, resources may be returned to the underlying -** operating system. -** -** RETURNS: PRStatus -** -*/ -NSPR_API( PRStatus ) - PR_DeleteSharedMemory( - const char *name -); - -PR_END_EXTERN_C - -#endif /* prshm_h___ */ diff --git a/win32/include/spidermonkey/nspr/prshma.h b/win32/include/spidermonkey/nspr/prshma.h deleted file mode 100755 index 2abc4aeb..00000000 --- a/win32/include/spidermonkey/nspr/prshma.h +++ /dev/null @@ -1,239 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** prshma.h -- NSPR Anonymous Shared Memory -** -** NSPR provides an anonymous shared memory based on NSPR's PRFileMap -** type. The anonymous file-mapped shared memory provides an inheritable -** shared memory, as in: the child process inherits the shared memory. -** Compare the file-mapped anonymous shared memory to to a named shared -** memory described in prshm.h. The intent is to provide a shared -** memory that is accessable only by parent and child processes. ... -** It's a security thing. -** -** Depending on the underlying platform, the file-mapped shared memory -** may be backed by a file. ... surprise! ... On some platforms, no -** real file backs the shared memory. On platforms where the shared -** memory is backed by a file, the file's name in the filesystem is -** visible to other processes for only the duration of the creation of -** the file, hopefully a very short time. This restricts processess -** that do not inherit the shared memory from opening the file and -** reading or writing its contents. Further, when all processes -** using an anonymous shared memory terminate, the backing file is -** deleted. ... If you are not paranoid, you're not paying attention. -** -** The file-mapped shared memory requires a protocol for the parent -** process and child process to share the memory. NSPR provides two -** protocols. Use one or the other; don't mix and match. -** -** In the first protocol, the job of passing the inheritable shared -** memory is done via helper-functions with PR_CreateProcess(). In the -** second protocol, the parent process is responsible for creating the -** child process; the parent and child are mutually responsible for -** passing a FileMap string. NSPR provides helper functions for -** extracting data from the PRFileMap object. ... See the examples -** below. -** -** Both sides should adhere strictly to the protocol for proper -** operation. The pseudo-code below shows the use of a file-mapped -** shared memory by a parent and child processes. In the examples, the -** server creates the file-mapped shared memory, the client attaches to -** it. -** -** First protocol. -** Server: -** -** fm = PR_OpenAnonFileMap(dirName, size, FilemapProt); -** addr = PR_MemMap(fm); -** attr = PR_NewProcessAttr(); -** PR_ProcessAttrSetInheritableFileMap( attr, fm, shmname ); -** PR_CreateProcess(Client); -** PR_DestroyProcessAttr(attr); -** ... yadda ... -** PR_MemUnmap( addr ); -** PR_CloseFileMap(fm); -** -** -** Client: -** ... started by server via PR_CreateProcess() -** fm = PR_GetInheritedFileMap( shmname ); -** addr = PR_MemMap(fm); -** ... yadda ... -** PR_MemUnmap(addr); -** PR_CloseFileMap(fm); -** -** -** Second Protocol: -** Server: -** -** fm = PR_OpenAnonFileMap(dirName, size, FilemapProt); -** fmstring = PR_ExportFileMapAsString( fm ); -** addr = PR_MemMap(fm); -** ... application specific technique to pass fmstring to child -** ... yadda ... Server uses his own magic to create child -** PR_MemUnmap( addr ); -** PR_CloseFileMap(fm); -** -** -** Client: -** ... started by server via his own magic -** ... application specific technique to find fmstring from parent -** fm = PR_ImportFileMapFromString( fmstring ) -** addr = PR_MemMap(fm); -** ... yadda ... -** PR_MemUnmap(addr); -** PR_CloseFileMap(fm); -** -** -** lth. 2-Jul-1999. -** -** Note: The second protocol was requested by NelsonB (7/1999); this is -** to accomodate servers which already create their own child processes -** using platform native methods. -** -*/ - -#ifndef prshma_h___ -#define prshma_h___ - -#include "prtypes.h" -#include "prio.h" -#include "prproces.h" - -PR_BEGIN_EXTERN_C - -/* -** PR_OpenAnonFileMap() -- Creates an anonymous file-mapped shared memory -** -** Description: -** PR_OpenAnonFileMap() creates an anonymous shared memory. If the -** shared memory already exists, a handle is returned to that shared -** memory object. -** -** On Unix platforms, PR_OpenAnonFileMap() uses 'dirName' as a -** directory name, without the trailing '/', to contain the anonymous -** file. A filename is generated for the name. -** -** On Windows platforms, dirName is ignored. -** -** Inputs: -** dirName -- A directory name to contain the anonymous file. -** size -- The size of the shared memory -** prot -- How the shared memory is mapped. See prio.h -** -** Outputs: -** PRFileMap * -** -** Returns: -** Pointer to PRFileMap or NULL on error. -** -*/ -NSPR_API( PRFileMap *) -PR_OpenAnonFileMap( - const char *dirName, - PRSize size, - PRFileMapProtect prot -); - -/* -** PR_ProcessAttrSetInheritableFileMap() -- Prepare FileMap for export -** to my children processes via PR_CreateProcess() -** -** Description: -** PR_ProcessAttrSetInheritableFileMap() connects the PRFileMap to -** PRProcessAttr with shmname. A subsequent call to PR_CreateProcess() -** makes the PRFileMap importable by the child process. -** -** Inputs: -** attr -- PRProcessAttr, used to pass data to PR_CreateProcess() -** fm -- PRFileMap structure to be passed to the child process -** shmname -- The name for the PRFileMap; used by child. -** -** Outputs: -** PRFileMap * -** -** Returns: -** PRStatus -** -*/ -NSPR_API(PRStatus) -PR_ProcessAttrSetInheritableFileMap( - PRProcessAttr *attr, - PRFileMap *fm, - const char *shmname -); - -/* -** PR_GetInheritedFileMap() -- Import a PRFileMap previously exported -** by my parent process via PR_CreateProcess() -** -** Description: -** PR_GetInheritedFileMap() retrieves a PRFileMap object exported from -** its parent process via PR_CreateProcess(). -** -** Inputs: -** shmname -- The name provided to PR_ProcessAttrSetInheritableFileMap() -** -** Outputs: -** PRFileMap * -** -** Returns: -** PRFileMap pointer or NULL. -** -*/ -NSPR_API( PRFileMap *) -PR_GetInheritedFileMap( - const char *shmname -); - -/* -** PR_ExportFileMapAsString() -- Creates a string identifying a PRFileMap -** -** Description: -** Creates an identifier, as a string, from a PRFileMap object -** previously created with PR_OpenAnonFileMap(). -** -** Inputs: -** fm -- PRFileMap pointer to be represented as a string. -** bufsize -- sizeof(buf) -** buf -- a buffer of length PR_FILEMAP_STRING_BUFSIZE -** -** Outputs: -** buf contains the stringized PRFileMap identifier -** -** Returns: -** PRStatus -** -*/ -NSPR_API( PRStatus ) -PR_ExportFileMapAsString( - PRFileMap *fm, - PRSize bufsize, - char *buf -); -#define PR_FILEMAP_STRING_BUFSIZE 128 - -/* -** PR_ImportFileMapFromString() -- Creates a PRFileMap from the identifying string -** -** Description: -** PR_ImportFileMapFromString() creates a PRFileMap object from a -** string previously created by PR_ExportFileMapAsString(). -** -** Inputs: -** fmstring -- string created by PR_ExportFileMapAsString() -** -** Returns: -** PRFileMap pointer or NULL. -** -*/ -NSPR_API( PRFileMap * ) -PR_ImportFileMapFromString( - const char *fmstring -); - -PR_END_EXTERN_C -#endif /* prshma_h___ */ diff --git a/win32/include/spidermonkey/nspr/prsystem.h b/win32/include/spidermonkey/nspr/prsystem.h deleted file mode 100755 index b3e14e7f..00000000 --- a/win32/include/spidermonkey/nspr/prsystem.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prsystem_h___ -#define prsystem_h___ - -/* -** API to NSPR functions returning system info. -*/ -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/* -** Get the host' directory separator. -** Pathnames are then assumed to be of the form: -** []*() -*/ - -NSPR_API(char) PR_GetDirectorySeparator(void); - -/* -** OBSOLETE -- the function name is misspelled. -** Use PR_GetDirectorySeparator instead. -*/ - -NSPR_API(char) PR_GetDirectorySepartor(void); - -/* -** Get the host' path separator. -** Paths are assumed to be of the form: -** []* -*/ - -NSPR_API(char) PR_GetPathSeparator(void); - -/* Types of information available via PR_GetSystemInfo(...) */ -typedef enum { - PR_SI_HOSTNAME, /* the hostname with the domain name (if any) - * removed */ - PR_SI_SYSNAME, - PR_SI_RELEASE, - PR_SI_ARCHITECTURE, - PR_SI_HOSTNAME_UNTRUNCATED /* the hostname exactly as configured - * on the system */ -} PRSysInfo; - - -/* -** If successful returns a null termintated string in 'buf' for -** the information indicated in 'cmd'. If unseccussful the reason for -** the failure can be retrieved from PR_GetError(). -** -** The buffer is allocated by the caller and should be at least -** SYS_INFO_BUFFER_LENGTH bytes in length. -*/ - -#define SYS_INFO_BUFFER_LENGTH 256 - -NSPR_API(PRStatus) PR_GetSystemInfo(PRSysInfo cmd, char *buf, PRUint32 buflen); - -/* -** Return the number of bytes in a page -*/ -NSPR_API(PRInt32) PR_GetPageSize(void); - -/* -** Return log2 of the size of a page -*/ -NSPR_API(PRInt32) PR_GetPageShift(void); - -/* -** PR_GetNumberOfProcessors() -- returns the number of CPUs -** -** Description: -** PR_GetNumberOfProcessors() extracts the number of processors -** (CPUs available in an SMP system) and returns the number. -** -** Parameters: -** none -** -** Returns: -** The number of available processors or -1 on error -** -*/ -NSPR_API(PRInt32) PR_GetNumberOfProcessors( void ); - -/* -** PR_GetPhysicalMemorySize() -- returns the amount of system RAM -** -** Description: -** PR_GetPhysicalMemorySize() determines the amount of physical RAM -** in the system and returns the size in bytes. -** -** Parameters: -** none -** -** Returns: -** The amount of system RAM, or 0 on failure. -** -*/ -NSPR_API(PRUint64) PR_GetPhysicalMemorySize(void); - -PR_END_EXTERN_C - -#endif /* prsystem_h___ */ diff --git a/win32/include/spidermonkey/nspr/prthread.h b/win32/include/spidermonkey/nspr/prthread.h deleted file mode 100755 index f8b28a62..00000000 --- a/win32/include/spidermonkey/nspr/prthread.h +++ /dev/null @@ -1,272 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prthread_h___ -#define prthread_h___ - -/* -** API for NSPR threads. On some architectures (Mac OS Classic -** notably) pre-emptibility is not guaranteed. Hard priority scheduling -** is not guaranteed, so programming using priority based synchronization -** is a no-no. -** -** NSPR threads are scheduled based loosely on their client set priority. -** In general, a thread of a higher priority has a statistically better -** chance of running relative to threads of lower priority. However, -** NSPR uses multiple strategies to provide execution vehicles for thread -** abstraction of various host platforms. As it turns out, there is little -** NSPR can do to affect the scheduling attributes of "GLOBAL" threads. -** However, a semblance of GLOBAL threads is used to implement "LOCAL" -** threads. An arbitrary number of such LOCAL threads can be assigned to -** a single GLOBAL thread. -** -** For scheduling, NSPR will attempt to run the highest priority LOCAL -** thread associated with a given GLOBAL thread. It is further assumed -** that the host OS will apply some form of "fair" scheduling on the -** GLOBAL threads. -** -** Threads have a "system flag" which when set indicates the thread -** doesn't count for determining when the process should exit (the -** process exits when the last user thread exits). -** -** Threads also have a "scope flag" which controls whether the threads -** are scheduled in the local scope or scheduled by the OS globally. This -** indicates whether a thread is permanently bound to a native OS thread. -** An unbound thread competes for scheduling resources in the same process. -** -** Another flag is "state flag" which control whether the thread is joinable. -** It allows other threads to wait for the created thread to reach completion. -** -** Threads can have "per-thread-data" attached to them. Each thread has a -** per-thread error number and error string which are updated when NSPR -** operations fail. -*/ -#include "prtypes.h" -#include "prinrval.h" - -PR_BEGIN_EXTERN_C - -typedef struct PRThread PRThread; -typedef struct PRThreadStack PRThreadStack; - -typedef enum PRThreadType { - PR_USER_THREAD, - PR_SYSTEM_THREAD -} PRThreadType; - -typedef enum PRThreadScope { - PR_LOCAL_THREAD, - PR_GLOBAL_THREAD, - PR_GLOBAL_BOUND_THREAD -} PRThreadScope; - -typedef enum PRThreadState { - PR_JOINABLE_THREAD, - PR_UNJOINABLE_THREAD -} PRThreadState; - -typedef enum PRThreadPriority -{ - PR_PRIORITY_FIRST = 0, /* just a placeholder */ - PR_PRIORITY_LOW = 0, /* the lowest possible priority */ - PR_PRIORITY_NORMAL = 1, /* most common expected priority */ - PR_PRIORITY_HIGH = 2, /* slightly more aggressive scheduling */ - PR_PRIORITY_URGENT = 3, /* it does little good to have more than one */ - PR_PRIORITY_LAST = 3 /* this is just a placeholder */ -} PRThreadPriority; - -/* -** Create a new thread: -** "type" is the type of thread to create -** "start(arg)" will be invoked as the threads "main" -** "priority" will be created thread's priority -** "scope" will specify whether the thread is local or global -** "state" will specify whether the thread is joinable or not -** "stackSize" the size of the stack, in bytes. The value can be zero -** and then a machine specific stack size will be chosen. -** -** This can return NULL if some kind of error occurs, such as if memory is -** tight. -** -** If you want the thread to start up waiting for the creator to do -** something, enter a lock before creating the thread and then have the -** threads start routine enter and exit the same lock. When you are ready -** for the thread to run, exit the lock. -** -** If you want to detect the completion of the created thread, the thread -** should be created joinable. Then, use PR_JoinThread to synchrnoize the -** termination of another thread. -** -** When the start function returns the thread exits. If it is the last -** PR_USER_THREAD to exit then the process exits. -*/ -NSPR_API(PRThread*) PR_CreateThread(PRThreadType type, - void (PR_CALLBACK *start)(void *arg), - void *arg, - PRThreadPriority priority, - PRThreadScope scope, - PRThreadState state, - PRUint32 stackSize); - -/* -** Wait for thread termination: -** "thread" is the target thread -** -** This can return PR_FAILURE if no joinable thread could be found -** corresponding to the specified target thread. -** -** The calling thread is blocked until the target thread completes. -** Several threads cannot wait for the same thread to complete; one thread -** will operate successfully and others will terminate with an error PR_FAILURE. -** The calling thread will not be blocked if the target thread has already -** terminated. -*/ -NSPR_API(PRStatus) PR_JoinThread(PRThread *thread); - -/* -** Return the current thread object for the currently running code. -** Never returns NULL. -*/ -NSPR_API(PRThread*) PR_GetCurrentThread(void); -#ifndef NO_NSPR_10_SUPPORT -#define PR_CurrentThread() PR_GetCurrentThread() /* for nspr1.0 compat. */ -#endif /* NO_NSPR_10_SUPPORT */ - -/* -** Get the priority of "thread". -*/ -NSPR_API(PRThreadPriority) PR_GetThreadPriority(const PRThread *thread); - -/* -** Change the priority of the "thread" to "priority". -** -** PR_SetThreadPriority works in a best-effort manner. On some platforms a -** special privilege, such as root access, is required to change thread -** priorities, especially to raise thread priorities. If the caller doesn't -** have enough privileges to change thread priorites, the function has no -** effect except causing a future PR_GetThreadPriority call to return -** |priority|. -*/ -NSPR_API(void) PR_SetThreadPriority(PRThread *thread, PRThreadPriority priority); - -/* -** Set the name of the current thread, which will be visible in a debugger -** and accessible via a call to PR_GetThreadName(). -*/ -NSPR_API(PRStatus) PR_SetCurrentThreadName(const char *name); - -/* -** Return the name of "thread", if set. Otherwise return NULL. -*/ -NSPR_API(const char *) PR_GetThreadName(const PRThread *thread); - -/* -** This routine returns a new index for per-thread-private data table. -** The index is visible to all threads within a process. This index can -** be used with the PR_SetThreadPrivate() and PR_GetThreadPrivate() routines -** to save and retrieve data associated with the index for a thread. -** -** Each index is associationed with a destructor function ('dtor'). The function -** may be specified as NULL when the index is created. If it is not NULL, the -** function will be called when: -** - the thread exits and the private data for the associated index -** is not NULL, -** - new thread private data is set and the current private data is -** not NULL. -** -** The index independently maintains specific values for each binding thread. -** A thread can only get access to its own thread-specific-data. -** -** Upon a new index return the value associated with the index for all threads -** is NULL, and upon thread creation the value associated with all indices for -** that thread is NULL. -** -** Returns PR_FAILURE if the total number of indices will exceed the maximun -** allowed. -*/ -typedef void (PR_CALLBACK *PRThreadPrivateDTOR)(void *priv); - -NSPR_API(PRStatus) PR_NewThreadPrivateIndex( - PRUintn *newIndex, PRThreadPrivateDTOR destructor); - -/* -** Define some per-thread-private data. -** "tpdIndex" is an index into the per-thread private data table -** "priv" is the per-thread-private data -** -** If the per-thread private data table has a previously registered -** destructor function and a non-NULL per-thread-private data value, -** the destructor function is invoked. -** -** This can return PR_FAILURE if the index is invalid. -*/ -NSPR_API(PRStatus) PR_SetThreadPrivate(PRUintn tpdIndex, void *priv); - -/* -** Recover the per-thread-private data for the current thread. "tpdIndex" is -** the index into the per-thread private data table. -** -** The returned value may be NULL which is indistinguishable from an error -** condition. -** -** A thread can only get access to its own thread-specific-data. -*/ -NSPR_API(void*) PR_GetThreadPrivate(PRUintn tpdIndex); - -/* -** This routine sets the interrupt request for a target thread. The interrupt -** request remains in the thread's state until it is delivered exactly once -** or explicitly canceled. -** -** A thread that has been interrupted will fail all NSPR blocking operations -** that return a PRStatus (I/O, waiting on a condition, etc). -** -** PR_Interrupt may itself fail if the target thread is invalid. -*/ -NSPR_API(PRStatus) PR_Interrupt(PRThread *thread); - -/* -** Clear the interrupt request for the calling thread. If no such request -** is pending, this operation is a noop. -*/ -NSPR_API(void) PR_ClearInterrupt(void); - -/* -** Block the interrupt for the calling thread. -*/ -NSPR_API(void) PR_BlockInterrupt(void); - -/* -** Unblock the interrupt for the calling thread. -*/ -NSPR_API(void) PR_UnblockInterrupt(void); - -/* -** Make the current thread sleep until "ticks" time amount of time -** has expired. If "ticks" is PR_INTERVAL_NO_WAIT then the call is -** equivalent to calling PR_Yield. Calling PR_Sleep with an argument -** equivalent to PR_INTERVAL_NO_TIMEOUT is an error and will result -** in a PR_FAILURE error return. -*/ -NSPR_API(PRStatus) PR_Sleep(PRIntervalTime ticks); - -/* -** Get the scoping of this thread. -*/ -NSPR_API(PRThreadScope) PR_GetThreadScope(const PRThread *thread); - -/* -** Get the type of this thread. -*/ -NSPR_API(PRThreadType) PR_GetThreadType(const PRThread *thread); - -/* -** Get the join state of this thread. -*/ -NSPR_API(PRThreadState) PR_GetThreadState(const PRThread *thread); - -PR_END_EXTERN_C - -#endif /* prthread_h___ */ diff --git a/win32/include/spidermonkey/nspr/prtime.h b/win32/include/spidermonkey/nspr/prtime.h deleted file mode 100755 index caaee14f..00000000 --- a/win32/include/spidermonkey/nspr/prtime.h +++ /dev/null @@ -1,262 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* - *---------------------------------------------------------------------- - * - * prtime.h -- - * - * NSPR date and time functions - * - *----------------------------------------------------------------------- - */ - -#ifndef prtime_h___ -#define prtime_h___ - -#include "prlong.h" - -PR_BEGIN_EXTERN_C - -/**********************************************************************/ -/************************* TYPES AND CONSTANTS ************************/ -/**********************************************************************/ - -#define PR_MSEC_PER_SEC 1000L -#define PR_USEC_PER_SEC 1000000L -#define PR_NSEC_PER_SEC 1000000000L -#define PR_USEC_PER_MSEC 1000L -#define PR_NSEC_PER_MSEC 1000000L - -/* - * PRTime -- - * - * NSPR represents basic time as 64-bit signed integers relative - * to midnight (00:00:00), January 1, 1970 Greenwich Mean Time (GMT). - * (GMT is also known as Coordinated Universal Time, UTC.) - * The units of time are in microseconds. Negative times are allowed - * to represent times prior to the January 1970 epoch. Such values are - * intended to be exported to other systems or converted to human - * readable form. - * - * Notes on porting: PRTime corresponds to time_t in ANSI C. NSPR 1.0 - * simply uses PRInt64. - */ - -typedef PRInt64 PRTime; - -/* - * Time zone and daylight saving time corrections applied to GMT to - * obtain the local time of some geographic location - */ - -typedef struct PRTimeParameters { - PRInt32 tp_gmt_offset; /* the offset from GMT in seconds */ - PRInt32 tp_dst_offset; /* contribution of DST in seconds */ -} PRTimeParameters; - -/* - * PRExplodedTime -- - * - * Time broken down into human-readable components such as year, month, - * day, hour, minute, second, and microsecond. Time zone and daylight - * saving time corrections may be applied. If they are applied, the - * offsets from the GMT must be saved in the 'tm_params' field so that - * all the information is available to reconstruct GMT. - * - * Notes on porting: PRExplodedTime corrresponds to struct tm in - * ANSI C, with the following differences: - * - an additional field tm_usec; - * - replacing tm_isdst by tm_params; - * - the month field is spelled tm_month, not tm_mon; - * - we use absolute year, AD, not the year since 1900. - * The corresponding type in NSPR 1.0 is called PRTime. Below is - * a table of date/time type correspondence in the three APIs: - * API time since epoch time in components - * ANSI C time_t struct tm - * NSPR 1.0 PRInt64 PRTime - * NSPR 2.0 PRTime PRExplodedTime - */ - -typedef struct PRExplodedTime { - PRInt32 tm_usec; /* microseconds past tm_sec (0-99999) */ - PRInt32 tm_sec; /* seconds past tm_min (0-61, accomodating - up to two leap seconds) */ - PRInt32 tm_min; /* minutes past tm_hour (0-59) */ - PRInt32 tm_hour; /* hours past tm_day (0-23) */ - PRInt32 tm_mday; /* days past tm_mon (1-31, note that it - starts from 1) */ - PRInt32 tm_month; /* months past tm_year (0-11, Jan = 0) */ - PRInt16 tm_year; /* absolute year, AD (note that we do not - count from 1900) */ - - PRInt8 tm_wday; /* calculated day of the week - (0-6, Sun = 0) */ - PRInt16 tm_yday; /* calculated day of the year - (0-365, Jan 1 = 0) */ - - PRTimeParameters tm_params; /* time parameters used by conversion */ -} PRExplodedTime; - -/* - * PRTimeParamFn -- - * - * A function of PRTimeParamFn type returns the time zone and - * daylight saving time corrections for some geographic location, - * given the current time in GMT. The input argument gmt should - * point to a PRExplodedTime that is in GMT, i.e., whose - * tm_params contains all 0's. - * - * For any time zone other than GMT, the computation is intended to - * consist of two steps: - * - Figure out the time zone correction, tp_gmt_offset. This number - * usually depends on the geographic location only. But it may - * also depend on the current time. For example, all of China - * is one time zone right now. But this situation may change - * in the future. - * - Figure out the daylight saving time correction, tp_dst_offset. - * This number depends on both the geographic location and the - * current time. Most of the DST rules are expressed in local - * current time. If so, one should apply the time zone correction - * to GMT before applying the DST rules. - */ - -typedef PRTimeParameters (PR_CALLBACK *PRTimeParamFn)(const PRExplodedTime *gmt); - -/**********************************************************************/ -/****************************** FUNCTIONS *****************************/ -/**********************************************************************/ - -/* - * The PR_Now routine returns the current time relative to the - * epoch, midnight, January 1, 1970 UTC. The units of the returned - * value are microseconds since the epoch. - * - * The values returned are not guaranteed to advance in a linear fashion - * due to the application of time correction protocols which synchronize - * computer clocks to some external time source. Consequently it should - * not be depended on for interval timing. - * - * The implementation is machine dependent. - * Cf. time_t time(time_t *tp) in ANSI C. - */ -NSPR_API(PRTime) -PR_Now(void); - -/* - * Expand time binding it to time parameters provided by PRTimeParamFn. - * The calculation is envisoned to proceed in the following steps: - * - From given PRTime, calculate PRExplodedTime in GMT - * - Apply the given PRTimeParamFn to the GMT that we just calculated - * to obtain PRTimeParameters. - * - Add the PRTimeParameters offsets to GMT to get the local time - * as PRExplodedTime. - */ - -NSPR_API(void) PR_ExplodeTime( - PRTime usecs, PRTimeParamFn params, PRExplodedTime *exploded); - -/* Reverse operation of PR_ExplodeTime */ -NSPR_API(PRTime) -PR_ImplodeTime(const PRExplodedTime *exploded); - -/* - * Adjust exploded time to normalize field overflows after manipulation. - * Note that the following fields of PRExplodedTime should not be - * manipulated: - * - tm_month and tm_year: because the number of days in a month and - * number of days in a year are not constant, it is ambiguous to - * manipulate the month and year fields, although one may be tempted - * to. For example, what does "a month from January 31st" mean? - * - tm_wday and tm_yday: these fields are calculated by NSPR. Users - * should treat them as "read-only". - */ - -NSPR_API(void) PR_NormalizeTime( - PRExplodedTime *exploded, PRTimeParamFn params); - -/**********************************************************************/ -/*********************** TIME PARAMETER FUNCTIONS *********************/ -/**********************************************************************/ - -/* Time parameters that suit current host machine */ -NSPR_API(PRTimeParameters) PR_LocalTimeParameters(const PRExplodedTime *gmt); - -/* Time parameters that represent Greenwich Mean Time */ -NSPR_API(PRTimeParameters) PR_GMTParameters(const PRExplodedTime *gmt); - -/* - * Time parameters that represent the US Pacific Time Zone, with the - * current daylight saving time rules (for testing only) - */ -NSPR_API(PRTimeParameters) PR_USPacificTimeParameters(const PRExplodedTime *gmt); - -/* - * This parses a time/date string into a PRExplodedTime - * struct. It populates all fields but it can't split - * the offset from UTC into tp_gmt_offset and tp_dst_offset in - * most cases (exceptions: PST/PDT, MST/MDT, CST/CDT, EST/EDT, GMT/BST). - * In those cases tp_gmt_offset will be the sum of these two and - * tp_dst_offset will be 0. - * It returns PR_SUCCESS on success, and PR_FAILURE - * if the time/date string can't be parsed. - * - * Many formats are handled, including: - * - * 14 Apr 89 03:20:12 - * 14 Apr 89 03:20 GMT - * Fri, 17 Mar 89 4:01:33 - * Fri, 17 Mar 89 4:01 GMT - * Mon Jan 16 16:12 PDT 1989 - * Mon Jan 16 16:12 +0130 1989 - * 6 May 1992 16:41-JST (Wednesday) - * 22-AUG-1993 10:59:12.82 - * 22-AUG-1993 10:59pm - * 22-AUG-1993 12:59am - * 22-AUG-1993 12:59 PM - * Friday, August 04, 1995 3:54 PM - * 06/21/95 04:24:34 PM - * 20/06/95 21:07 - * 95-06-08 19:32:48 EDT - * - * If the input string doesn't contain a description of the timezone, - * we consult the `default_to_gmt' to decide whether the string should - * be interpreted relative to the local time zone (PR_FALSE) or GMT (PR_TRUE). - * The correct value for this argument depends on what standard specified - * the time string which you are parsing. - */ - -NSPR_API(PRStatus) PR_ParseTimeStringToExplodedTime ( - const char *string, - PRBool default_to_gmt, - PRExplodedTime *result); - -/* - * This uses PR_ParseTimeStringToExplodedTime to parse - * a time/date string and PR_ImplodeTime to transform it into - * a PRTime (microseconds after "1-Jan-1970 00:00:00 GMT"). - * It returns PR_SUCCESS on success, and PR_FAILURE - * if the time/date string can't be parsed. - */ - -NSPR_API(PRStatus) PR_ParseTimeString ( - const char *string, - PRBool default_to_gmt, - PRTime *result); - -/* Format a time value into a buffer. Same semantics as strftime() */ -NSPR_API(PRUint32) PR_FormatTime(char *buf, int buflen, const char *fmt, - const PRExplodedTime *time); - -/* Format a time value into a buffer. Time is always in US English format, - * regardless of locale setting. - */ -NSPR_API(PRUint32) -PR_FormatTimeUSEnglish(char *buf, PRUint32 bufSize, - const char *format, const PRExplodedTime *time); - -PR_END_EXTERN_C - -#endif /* prtime_h___ */ diff --git a/win32/include/spidermonkey/nspr/prtpool.h b/win32/include/spidermonkey/nspr/prtpool.h deleted file mode 100755 index 6a434dd1..00000000 --- a/win32/include/spidermonkey/nspr/prtpool.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prtpool_h___ -#define prtpool_h___ - -#include "prtypes.h" -#include "prthread.h" -#include "prio.h" -#include "prerror.h" - -/* - * NOTE: - * THIS API IS A PRELIMINARY VERSION IN NSPR 4.0 AND IS SUBJECT TO - * CHANGE - */ - -PR_BEGIN_EXTERN_C - -typedef struct PRJobIoDesc { - PRFileDesc *socket; - PRErrorCode error; - PRIntervalTime timeout; -} PRJobIoDesc; - -typedef struct PRThreadPool PRThreadPool; -typedef struct PRJob PRJob; -typedef void (PR_CALLBACK *PRJobFn) (void *arg); - -/* Create thread pool */ -NSPR_API(PRThreadPool *) -PR_CreateThreadPool(PRInt32 initial_threads, PRInt32 max_threads, - PRUint32 stacksize); - -/* queue a job */ -NSPR_API(PRJob *) -PR_QueueJob(PRThreadPool *tpool, PRJobFn fn, void *arg, PRBool joinable); - -/* queue a job, when a socket is readable */ -NSPR_API(PRJob *) -PR_QueueJob_Read(PRThreadPool *tpool, PRJobIoDesc *iod, - PRJobFn fn, void * arg, PRBool joinable); - -/* queue a job, when a socket is writeable */ -NSPR_API(PRJob *) -PR_QueueJob_Write(PRThreadPool *tpool, PRJobIoDesc *iod, - PRJobFn fn, void * arg, PRBool joinable); - -/* queue a job, when a socket has a pending connection */ -NSPR_API(PRJob *) -PR_QueueJob_Accept(PRThreadPool *tpool, PRJobIoDesc *iod, - PRJobFn fn, void * arg, PRBool joinable); - -/* queue a job, when the socket connection to addr succeeds or fails */ -NSPR_API(PRJob *) -PR_QueueJob_Connect(PRThreadPool *tpool, PRJobIoDesc *iod, - const PRNetAddr *addr, PRJobFn fn, void * arg, PRBool joinable); - -/* queue a job, when a timer exipres */ -NSPR_API(PRJob *) -PR_QueueJob_Timer(PRThreadPool *tpool, PRIntervalTime timeout, - PRJobFn fn, void * arg, PRBool joinable); -/* cancel a job */ -NSPR_API(PRStatus) -PR_CancelJob(PRJob *job); - -/* join a job */ -NSPR_API(PRStatus) -PR_JoinJob(PRJob *job); - -/* shutdown pool */ -NSPR_API(PRStatus) -PR_ShutdownThreadPool(PRThreadPool *tpool); - -/* join pool, wait for exit of all threads */ -NSPR_API(PRStatus) -PR_JoinThreadPool(PRThreadPool *tpool); - -PR_END_EXTERN_C - -#endif /* prtpool_h___ */ diff --git a/win32/include/spidermonkey/nspr/prtrace.h b/win32/include/spidermonkey/nspr/prtrace.h deleted file mode 100755 index 12a5fbfb..00000000 --- a/win32/include/spidermonkey/nspr/prtrace.h +++ /dev/null @@ -1,646 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prtrace_h___ -#define prtrace_h___ -/* -** prtrace.h -- NSPR's Trace Facility. -** -** The Trace Facility provides a means to trace application -** program events within a process. When implementing an -** application program an engineer may insert a "Trace" function -** call, passing arguments to be traced. The "Trace" function -** combines the user trace data with identifying data and -** writes this data in time ordered sequence into a circular -** in-memory buffer; when the buffer fills, it wraps. -** -** Functions are provided to set and/or re-configure the size of -** the trace buffer, control what events are recorded in the -** buffer, enable and disable tracing based on specific user -** supplied data and other control functions. Methods are provided -** to record the trace entries in the in-memory trace buffer to -** a file. -** -** Tracing may cause a performance degredation to the application -** depending on the number and placement of calls to the tracing -** facility. When tracing is compiled in and all tracing is -** disabled via the runtime controls, the overhead should be -** minimal. ... Famous last words, eh? -** -** When DEBUG is defined at compile time, the Trace Facility is -** compiled as part of NSPR and any application using NSPR's -** header files will have tracing compiled in. When DEBUG is not -** defined, the Trace Facility is not compiled into NSPR nor -** exported in its header files. If the Trace Facility is -** desired in a non-debug build, then FORCE_NSPR_TRACE may be -** defined at compile time for both the optimized build of NSPR -** and the application. NSPR and any application using NSPR's -** Trace Facility must be compiled with the same level of trace -** conditioning or unresolved references may be realized at link -** time. -** -** For any of the Trace Facility methods that requires a trace -** handle as an input argument, the caller must ensure that the -** trace handle argument is valid. An invalid trace handle -** argument may cause unpredictable results. -** -** Trace Facility methods are thread-safe and SMP safe. -** -** Users of the Trace Facility should use the defined macros to -** invoke trace methods, not the function calls directly. e.g. -** PR_TRACE( h1,0,1,2, ...); not PR_Trace(h1,0,1,2, ...); -** -** Application designers should be aware of the effects of -** debug and optimized build differences when using result of the -** Trace Facility macros in expressions. -** -** See Also: prcountr.h -** -** /lth. 08-Jun-1998. -*/ - -#include "prtypes.h" -#include "prthread.h" -#include "prtime.h" - -PR_BEGIN_EXTERN_C - -/* -** Opaque type for the trace handle -** ... Don't even think about looking in here. -** -*/ -typedef void * PRTraceHandle; - -/* -** PRTraceEntry -- A trace entry in the in-memory trace buffer -** looks like this. -** -*/ -typedef struct PRTraceEntry -{ - PRThread *thread; /* The thread creating the trace entry */ - PRTraceHandle handle; /* PRTraceHandle creating the trace entry */ - PRTime time; /* Value of PR_Now() at time of trace entry */ - PRUint32 userData[8]; /* user supplied trace data */ -} PRTraceEntry; - -/* -** PRTraceOption -- command operands to -** PR_[Set|Get]TraceOption(). See descriptive meanings there. -** -*/ -typedef enum PRTraceOption -{ - PRTraceBufSize, - PRTraceEnable, - PRTraceDisable, - PRTraceSuspend, - PRTraceResume, - PRTraceSuspendRecording, - PRTraceResumeRecording, - PRTraceLockHandles, - PRTraceUnLockHandles, - PRTraceStopRecording -} PRTraceOption; - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_DEFINE_TRACE() -- Define a PRTraceHandle -** -** DESCRIPTION: PR_DEFINE_TRACE() is used to define a trace -** handle. -** -*/ -#define PR_DEFINE_TRACE(name) PRTraceHandle name - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_INIT_TRACE_HANDLE() -- Set the value of a PRTraceHandle -** -** DESCRIPTION: -** PR_INIT_TRACE_HANDLE() sets the value of a PRTraceHandle -** to value. e.g. PR_INIT_TRACE_HANDLE( myHandle, NULL ); -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_INIT_TRACE_HANDLE(handle,value)\ - (handle) = (PRCounterHandle)(value) -#else -#define PR_INIT_TRACE_HANDLE(handle,value) -#endif - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_CreateTrace() -- Create a trace handle -** -** DESCRIPTION: -** PR_CreateTrace() creates a new trace handle. Tracing is -** enabled for this handle when it is created. The trace handle -** is intended for use in other Trace Facility calls. -** -** PR_CreateTrace() registers the QName, RName and description -** data so that this data can be retrieved later. -** -** INPUTS: -** qName: pointer to string. QName for this trace handle. -** -** rName: pointer to string. RName for this trace handle. -** -** description: pointer to string. Descriptive data about this -** trace handle. -** -** OUTPUTS: -** Creates the trace handle. -** Registers the QName and RName with the trace facility. -** -** RETURNS: -** PRTraceHandle -** -** RESTRICTIONS: -** qName is limited to 31 characters. -** rName is limited to 31 characters. -** description is limited to 255 characters. -** -*/ -#define PRTRACE_NAME_MAX 31 -#define PRTRACE_DESC_MAX 255 - -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_CREATE_TRACE(handle,qName,rName,description)\ - (handle) = PR_CreateTrace((qName),(rName),(description)) -#else -#define PR_CREATE_TRACE(handle,qName,rName,description) -#endif - -NSPR_API(PRTraceHandle) - PR_CreateTrace( - const char *qName, /* QName for this trace handle */ - const char *rName, /* RName for this trace handle */ - const char *description /* description for this trace handle */ -); - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_DestroyTrace() -- Destroy a trace handle -** -** DESCRIPTION: -** PR_DestroyTrace() removes the referenced trace handle and -** associated QName, RName and description data from the Trace -** Facility. -** -** INPUTS: handle. A PRTraceHandle -** -** OUTPUTS: -** The trace handle is unregistered. -** The QName, RName and description are removed. -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_DESTROY_TRACE(handle)\ - PR_DestroyTrace((handle)) -#else -#define PR_DESTROY_TRACE(handle) -#endif - -NSPR_API(void) - PR_DestroyTrace( - PRTraceHandle handle /* Handle to be destroyed */ -); - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_Trace() -- Make a trace entry in the in-memory trace -** -** DESCRIPTION: -** PR_Trace() makes an entry in the in-memory trace buffer for -** the referenced trace handle. The next logically available -** PRTraceEntry is used; when the next trace entry would overflow -** the trace table, the table wraps. -** -** PR_Trace() for a specific trace handle may be disabled by -** calling PR_SetTraceOption() specifying PRTraceDisable for the -** trace handle to be disabled. -** -** INPUTS: -** handle: PRTraceHandle. The trace handle for this trace. -** -** userData[0..7]: unsigned 32bit integers. user supplied data -** that is copied into the PRTraceEntry -** -** OUTPUTS: -** A PRTraceEntry is (conditionally) formatted in the in-memory -** trace buffer. -** -** RETURNS: void. -** -** RESTRICTIONS: -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_TRACE(handle,ud0,ud1,ud2,ud3,ud4,ud5,ud6,ud7)\ - PR_Trace((handle),(ud0),(ud1),(ud2),(ud3),(ud4),(ud5),(ud6),(ud7)) -#else -#define PR_TRACE(handle,ud0,ud1,ud2,ud3,ud4,ud5,ud6,ud7) -#endif - -NSPR_API(void) - PR_Trace( - PRTraceHandle handle, /* use this trace handle */ - PRUint32 userData0, /* User supplied data word 0 */ - PRUint32 userData1, /* User supplied data word 1 */ - PRUint32 userData2, /* User supplied data word 2 */ - PRUint32 userData3, /* User supplied data word 3 */ - PRUint32 userData4, /* User supplied data word 4 */ - PRUint32 userData5, /* User supplied data word 5 */ - PRUint32 userData6, /* User supplied data word 6 */ - PRUint32 userData7 /* User supplied data word 7 */ -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_SetTraceOption() -- Control the Trace Facility -** -** DESCRIPTION: -** PR_SetTraceOption() controls the Trace Facility. Depending on -** command and value, attributes of the Trace Facility may be -** changed. -** -** INPUTS: -** command: An enumerated value in the set of PRTraceOption. -** value: pointer to the data to be set. Type of the data is -** dependent on command; for each value of command, the type -** and meaning of dereferenced value is shown. -** -** PRTraceBufSize: unsigned long: the size of the trace buffer, -** in bytes. -** -** PRTraceEnable: PRTraceHandle. The trace handle to be -** enabled. -** -** PRTraceDisable: PRTraceHandle. The trace handle to be -** disabled. -** -** PRTraceSuspend: void. value must be NULL. All tracing is -** suspended. -** -** PRTraceResume: void. value must be NULL. Tracing for all -** previously enabled, prior to a PRTraceSuspend, is resumed. -** -** PRTraceStopRecording: void. value must be NULL. If recording -** (see: ** PR_RecordTraceEntries()) is being done, -** PRTraceStopRecording causes PR_RecordTraceEntries() to return -** to its caller. If recording is not being done, this function -** has no effect. -** -** PRTraceSuspendRecording: void. Must be NULL. If recording is -** being done, PRTraceSuspendRecording causes further writes to -** the trace file to be suspended. Data in the in-memory -** trace buffer that would ordinarily be written to the -** trace file will not be written. Trace entries will continue -** to be entered in the in-memory buffer. If the Trace Facility -** recording is already in a suspended state, the call has no -** effect. -** -** PRTraceResumeRecording: void. value must be NULL. If -** recording for the Trace Facility has been previously been -** suspended, this causes recording to resume. Recording resumes -** with the next in-memory buffer segment that would be written -** if trace recording had not been suspended. If recording is -** not currently suspended, the call has no effect. -** -** PRTraceLockHandles: void. value must be NULL. Locks the -** trace handle lock. While the trace handle lock is held, -** calls to PR_CreateTrace() will block until the lock is -** released. -** -** PRTraceUnlockHandles: void. value must be NULL. Unlocks the -** trace handle lock. -** -** OUTPUTS: -** The operation of the Trace Facility may be changed. -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_SET_TRACE_OPTION(command,value)\ - PR_SetTraceOption((command),(value)) -#else -#define PR_SET_TRACE_OPTION(command,value) -#endif - -NSPR_API(void) - PR_SetTraceOption( - PRTraceOption command, /* One of the enumerated values */ - void *value /* command value or NULL */ -); - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_GetTraceOption() -- Retrieve settings from the Trace Facility -** -** DESCRIPTION: -** PR_GetTraceOption() retrieves the current setting of the -** Trace Facility control depending on command. -** -** -** PRTraceBufSize: unsigned long: the size of the trace buffer, -** in bytes. -** -** -** INPUTS: -** command: one of the enumerated values in PRTraceOptions -** valid for PR_GetTraceOption(). -** -** OUTPUTS: -** dependent on command. -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_GET_TRACE_OPTION(command,value)\ - PR_GetTraceOption((command),(value)) -#else -#define PR_GET_TRACE_OPTION(command,value) -#endif - -NSPR_API(void) - PR_GetTraceOption( - PRTraceOption command, /* One of the enumerated values */ - void *value /* command value or NULL */ -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_GetTraceHandleFromName() -- Retrieve an existing -** handle by name. -** -** DESCRIPTION: -** PR_GetTraceHandleFromName() retreives an existing tracehandle -** using the name specified by qName and rName. -** -** INPUTS: -** qName: pointer to string. QName for this trace handle. -** -** rName: pointer to string. RName for this trace handle. -** -** -** OUTPUTS: returned. -** -** RETURNS: -** PRTraceHandle associated with qName and rName or NULL when -** there is no match. -** -** RESTRICTIONS: -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_GET_TRACE_HANDLE_FROM_NAME(handle,qName,rName)\ - (handle) = PR_GetTraceHandleFromName((qName),(rName)) -#else -#define PR_GET_TRACE_HANDLE_FROM_NAME(handle,qName,rName) -#endif - -NSPR_API(PRTraceHandle) - PR_GetTraceHandleFromName( - const char *qName, /* QName search argument */ - const char *rName /* RName search argument */ -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_GetTraceNameFromHandle() -- Retreive trace name -** by bandle. -** -** DESCRIPTION: -** PR_GetTraceNameFromHandle() retreives the existing qName, -** rName, and description for the referenced trace handle. -** -** INPUTS: handle: PRTraceHandle. -** -** OUTPUTS: pointers to the Trace Facility's copy of qName, -** rName and description. ... Don't mess with these values. -** They're mine. -** -** RETURNS: void -** -** RESTRICTIONS: -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_GET_TRACE_NAME_FROM_HANDLE(handle,qName,rName,description)\ - PR_GetTraceNameFromHandle((handle),(qName),(rName),(description)) -#else -#define PR_GET_TRACE_NAME_FROM_HANDLE(handle,qName,rName,description) -#endif - -NSPR_API(void) - PR_GetTraceNameFromHandle( - PRTraceHandle handle, /* handle as search argument */ - const char **qName, /* pointer to associated QName */ - const char **rName, /* pointer to associated RName */ - const char **description /* pointer to associated description */ -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_FindNextTraceQname() -- Retrieive a QName handle -** iterator. -** -** DESCRIPTION: -** PR_FindNextTraceQname() retreives the first or next trace -** QName handle, depending on the value of handle, from the trace -** database. The PRTraceHandle returned can be used as an -** iterator to traverse the QName handles in the Trace database. -** -** INPUTS: -** handle: When NULL, PR_FindNextQname() returns the first QName -** handle. When a handle is a valid PRTraceHandle previously -** retreived using PR_FindNextQname() the next QName handle is -** retreived. -** -** OUTPUTS: returned. -** -** RETURNS: -** PRTraceHandle or NULL when there are no trace handles. -** -** RESTRICTIONS: -** Iterating thru the trace handles via FindFirst/FindNext -** should be done under protection of the trace handle lock. -** See: PR_SetTraceOption( PRLockTraceHandles ). -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_FIND_NEXT_TRACE_QNAME(next,handle)\ - (next) = PR_FindNextTraceQname((handle)) -#else -#define PR_FIND_NEXT_TRACE_QNAME(next,handle) -#endif - -NSPR_API(PRTraceHandle) - PR_FindNextTraceQname( - PRTraceHandle handle -); - - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_FindNextTraceRname() -- Retrieive an RName handle -** iterator. -** -** DESCRIPTION: -** PR_FindNextTraceRname() retreives the first or next trace -** RName handle, depending on the value of handle, from the trace -** database. The PRTraceHandle returned can be used as an -** iterator to traverse the RName handles in the Trace database. -** -** INPUTS: -** rhandle: When NULL, PR_FindNextRname() returns the first -** RName handle. When a handle is a valid PRTraceHandle -** previously retreived using PR_FindNextRname() the next RName -** handle is retreived. -** qhandle: A valid PRTraceHandle retruned from a previous call -** to PR_FIND_NEXT_TRACE_QNAME(). -** -** OUTPUTS: returned. -** -** RETURNS: -** PRTraceHandle or NULL when there are no trace handles. -** -** RESTRICTIONS: -** Iterating thru the trace handles via FindNext should be done -** under protection of the trace handle lock. See: ( -** PR_SetTraceOption( PRLockTraceHandles ). -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_FIND_NEXT_TRACE_RNAME(next,rhandle,qhandle)\ - (next) = PR_FindNextTraceRname((rhandle),(qhandle)) -#else -#define PR_FIND_NEXT_TRACE_RNAME(next,rhandle,qhandle) -#endif - -NSPR_API(PRTraceHandle) - PR_FindNextTraceRname( - PRTraceHandle rhandle, - PRTraceHandle qhandle -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_RecordTraceEntries() -- Write trace entries to external media -** -** DESCRIPTION: -** PR_RecordTraceEntries() causes entries in the in-memory trace -** buffer to be written to external media. -** -** When PR_RecordTraceEntries() is called from an application -** thread, the function appears to block until another thread -** calls PR_SetTraceOption() with the PRTraceStopRecording -** option. This suggests that PR_RecordTraceEntries() should be -** called from a user supplied thread whose only job is to -** record trace entries. -** -** The environment variable NSPR_TRACE_LOG controls the operation -** of this function. When NSPR_TRACE_LOG is not defined in the -** environment, no recording of trace entries occurs. When -** NSPR_TRACE_LOG is defined, the value of its definition must be -** the filename of the file to receive the trace entry buffer. -** -** PR_RecordTraceEntries() attempts to record the in-memory -** buffer to a file, subject to the setting of the environment -** variable NSPR_TRACE_LOG. It is possible because of system -** load, the thread priority of the recording thread, number of -** active trace records being written over time, and other -** variables that some trace records can be lost. ... In other -** words: don't bet the farm on getting everything. -** -** INPUTS: none -** -** OUTPUTS: none -** -** RETURNS: PR_STATUS -** PR_SUCCESS no errors were found. -** PR_FAILURE errors were found. -** -** RESTRICTIONS: -** Only one thread can call PR_RecordTraceEntries() within a -** process. -** -** On error, PR_RecordTraceEntries() may return prematurely. -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_RECORD_TRACE_ENTRIES()\ - PR_RecordTraceEntries() -#else -#define PR_RECORD_TRACE_ENTRIES() -#endif - -NSPR_API(void) - PR_RecordTraceEntries( - void -); - -/* ----------------------------------------------------------------------- -** FUNCTION: PR_GetTraceEntries() -- Retreive trace entries from -** the Trace Facility -** -** DESCRIPTION: -** PR_GetTraceEntries() retreives trace entries from the Trace -** Facility. Up to count trace entries are copied from the Trace -** Facility into buffer. Only those trace entries that have not -** been copied via a previous call to PR_GetTraceEntries() are -** copied. The actual number copied is placed in the PRInt32 -** variable pointed to by found. -** -** If more than count trace entries have entered the Trace -** Facility since the last call to PR_GetTraceEntries() -** a lost data condition is returned. In this case, the most -** recent count trace entries are copied into buffer and found is -** set to count. -** -** INPUTS: -** count. The number of trace entries to be copied into buffer. -** -** -** OUTPUTS: -** buffer. An array of PRTraceEntries. The buffer is supplied -** by the caller. -** -** found: 32bit signed integer. The number of PRTraceEntries -** actually copied. found is always less than or equal to count. -** -** RETURNS: -** zero when there is no lost data. -** non-zero when some PRTraceEntries have been lost. -** -** RESTRICTIONS: -** This is a real performance pig. The copy out operation is bad -** enough, but depending on then frequency of calls to the -** function, serious performance impact to the operating -** application may be realized. ... YMMV. -** -*/ -#if defined (DEBUG) || defined (FORCE_NSPR_TRACE) -#define PR_GET_TRACE_ENTRIES(buffer,count,found)\ - PR_GetTraceEntries((buffer),(count),(found)) -#else -#define PR_GET_TRACE_ENTRIES(buffer,count,found) -#endif - -NSPR_API(PRIntn) - PR_GetTraceEntries( - PRTraceEntry *buffer, /* where to write output */ - PRInt32 count, /* number to get */ - PRInt32 *found /* number you got */ -); - -PR_END_EXTERN_C - -#endif /* prtrace_h___ */ - diff --git a/win32/include/spidermonkey/nspr/prtypes.h b/win32/include/spidermonkey/nspr/prtypes.h deleted file mode 100755 index 52b3ab0b..00000000 --- a/win32/include/spidermonkey/nspr/prtypes.h +++ /dev/null @@ -1,590 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -** File: prtypes.h -** Description: Definitions of NSPR's basic types -** -** Prototypes and macros used to make up for deficiencies that we have found -** in ANSI environments. -** -** Since we do not wrap and all the other standard headers, authors -** of portable code will not know in general that they need these definitions. -** Instead of requiring these authors to find the dependent uses in their code -** and take the following steps only in those C files, we take steps once here -** for all C files. -**/ - -#ifndef prtypes_h___ -#define prtypes_h___ - -#ifdef MDCPUCFG -#include MDCPUCFG -#else -#include "prcpucfg.h" -#endif - -#include - -/*********************************************************************** -** MACROS: PR_EXTERN -** PR_IMPLEMENT -** DESCRIPTION: -** These are only for externally visible routines and globals. For -** internal routines, just use "extern" for type checking and that -** will not export internal cross-file or forward-declared symbols. -** Define a macro for declaring procedures return types. We use this to -** deal with windoze specific type hackery for DLL definitions. Use -** PR_EXTERN when the prototype for the method is declared. Use -** PR_IMPLEMENT for the implementation of the method. -** -** Example: -** in dowhim.h -** PR_EXTERN( void ) DoWhatIMean( void ); -** in dowhim.c -** PR_IMPLEMENT( void ) DoWhatIMean( void ) { return; } -** -** -***********************************************************************/ -#if defined(WIN32) - -#define PR_EXPORT(__type) extern __declspec(dllexport) __type -#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type -#define PR_IMPORT(__type) __declspec(dllimport) __type -#define PR_IMPORT_DATA(__type) __declspec(dllimport) __type - -#define PR_EXTERN(__type) extern __declspec(dllexport) __type -#define PR_IMPLEMENT(__type) __declspec(dllexport) __type -#define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type -#define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type - -#define PR_CALLBACK -#define PR_CALLBACK_DECL -#define PR_STATIC_CALLBACK(__x) static __x - -#elif defined(XP_BEOS) - -#define PR_EXPORT(__type) extern __declspec(dllexport) __type -#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type -#define PR_IMPORT(__type) extern __declspec(dllexport) __type -#define PR_IMPORT_DATA(__type) extern __declspec(dllexport) __type - -#define PR_EXTERN(__type) extern __declspec(dllexport) __type -#define PR_IMPLEMENT(__type) __declspec(dllexport) __type -#define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type -#define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type - -#define PR_CALLBACK -#define PR_CALLBACK_DECL -#define PR_STATIC_CALLBACK(__x) static __x - -#elif defined(XP_OS2) && defined(__declspec) - -#define PR_EXPORT(__type) extern __declspec(dllexport) __type -#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type -#define PR_IMPORT(__type) extern __declspec(dllimport) __type -#define PR_IMPORT_DATA(__type) extern __declspec(dllimport) __type - -#define PR_EXTERN(__type) extern __declspec(dllexport) __type -#define PR_IMPLEMENT(__type) __declspec(dllexport) __type -#define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type -#define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type - -#define PR_CALLBACK -#define PR_CALLBACK_DECL -#define PR_STATIC_CALLBACK(__x) static __x - -#elif defined(SYMBIAN) - -#define PR_EXPORT(__type) extern __declspec(dllexport) __type -#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type -#ifdef __WINS__ -#define PR_IMPORT(__type) extern __declspec(dllexport) __type -#define PR_IMPORT_DATA(__type) extern __declspec(dllexport) __type -#else -#define PR_IMPORT(__type) extern __declspec(dllimport) __type -#define PR_IMPORT_DATA(__type) extern __declspec(dllimport) __type -#endif - -#define PR_EXTERN(__type) extern __type -#define PR_IMPLEMENT(__type) __type -#define PR_EXTERN_DATA(__type) extern __type -#define PR_IMPLEMENT_DATA(__type) __type - -#define PR_CALLBACK -#define PR_CALLBACK_DECL -#define PR_STATIC_CALLBACK(__x) static __x - -#else /* Unix */ - -/* GCC 3.3 and later support the visibility attribute. */ -#if (__GNUC__ >= 4) || \ - (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) -#define PR_VISIBILITY_DEFAULT __attribute__((visibility("default"))) -#else -#define PR_VISIBILITY_DEFAULT -#endif - -#define PR_EXPORT(__type) extern PR_VISIBILITY_DEFAULT __type -#define PR_EXPORT_DATA(__type) extern PR_VISIBILITY_DEFAULT __type -#define PR_IMPORT(__type) extern PR_VISIBILITY_DEFAULT __type -#define PR_IMPORT_DATA(__type) extern PR_VISIBILITY_DEFAULT __type - -#define PR_EXTERN(__type) extern PR_VISIBILITY_DEFAULT __type -#define PR_IMPLEMENT(__type) PR_VISIBILITY_DEFAULT __type -#define PR_EXTERN_DATA(__type) extern PR_VISIBILITY_DEFAULT __type -#define PR_IMPLEMENT_DATA(__type) PR_VISIBILITY_DEFAULT __type -#define PR_CALLBACK -#define PR_CALLBACK_DECL -#define PR_STATIC_CALLBACK(__x) static __x - -#endif - -#if defined(_NSPR_BUILD_) -#define NSPR_API(__type) PR_EXPORT(__type) -#define NSPR_DATA_API(__type) PR_EXPORT_DATA(__type) -#else -#define NSPR_API(__type) PR_IMPORT(__type) -#define NSPR_DATA_API(__type) PR_IMPORT_DATA(__type) -#endif - -/*********************************************************************** -** MACROS: PR_BEGIN_MACRO -** PR_END_MACRO -** DESCRIPTION: -** Macro body brackets so that macros with compound statement definitions -** behave syntactically more like functions when called. -***********************************************************************/ -#define PR_BEGIN_MACRO do { -#define PR_END_MACRO } while (0) - -/*********************************************************************** -** MACROS: PR_BEGIN_EXTERN_C -** PR_END_EXTERN_C -** DESCRIPTION: -** Macro shorthands for conditional C++ extern block delimiters. -***********************************************************************/ -#ifdef __cplusplus -#define PR_BEGIN_EXTERN_C extern "C" { -#define PR_END_EXTERN_C } -#else -#define PR_BEGIN_EXTERN_C -#define PR_END_EXTERN_C -#endif - -/*********************************************************************** -** MACROS: PR_BIT -** PR_BITMASK -** DESCRIPTION: -** Bit masking macros. XXX n must be <= 31 to be portable -***********************************************************************/ -#define PR_BIT(n) ((PRUint32)1 << (n)) -#define PR_BITMASK(n) (PR_BIT(n) - 1) - -/*********************************************************************** -** MACROS: PR_ROUNDUP -** PR_MIN -** PR_MAX -** PR_ABS -** DESCRIPTION: -** Commonly used macros for operations on compatible types. -***********************************************************************/ -#define PR_ROUNDUP(x,y) ((((x)+((y)-1))/(y))*(y)) -#define PR_MIN(x,y) ((x)<(y)?(x):(y)) -#define PR_MAX(x,y) ((x)>(y)?(x):(y)) -#define PR_ABS(x) ((x)<0?-(x):(x)) - -/*********************************************************************** -** MACROS: PR_ARRAY_SIZE -** DESCRIPTION: -** The number of elements in an array. -***********************************************************************/ -#define PR_ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) - -PR_BEGIN_EXTERN_C - -/* -** Starting in NSPR 4.9.5, NSPR's exact-width integer types should match -** the exact-width integer types defined in . This allows sloppy -** code to use PRInt{N} and int{N}_t interchangeably. -** -** The 8-bit and 16-bit integer types can only be defined using char and -** short. All platforms define the 32-bit integer types using int. So only -** the 64-bit integer types could be defined differently. -** -** NSPR's original strategy was to use the "shortest" 64-bit integer type: -** if long is 64-bit, then prefer it over long long. This strategy is also -** used by Linux/glibc, FreeBSD, and NetBSD. -** -** Other platforms use a different strategy: simply define the 64-bit -** integer types using long long. We define the PR_ALTERNATE_INT64_TYPEDEF -** macro on these platforms. Note that PR_ALTERNATE_INT64_TYPEDEF is for -** internal use by NSPR headers only. Do not define or test this macro in -** your code. -** -** NOTE: NSPR can't use because C99 requires C++ code to define -** __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS to make all the macros -** defined in available. This strange requirement is gone in -** C11. When most platforms ignore this C99 requirement, NSPR will be able -** to use . A patch to do that is in NSPR bug 634793. -*/ - -#if defined(__APPLE__) || defined(__ANDROID__) || defined(__OpenBSD__) -#define PR_ALTERNATE_INT64_TYPEDEF -#endif - -/************************************************************************ -** TYPES: PRUint8 -** PRInt8 -** DESCRIPTION: -** The int8 types are known to be 8 bits each. There is no type that -** is equivalent to a plain "char". -************************************************************************/ -#if PR_BYTES_PER_BYTE == 1 -typedef unsigned char PRUint8; -/* -** Some cfront-based C++ compilers do not like 'signed char' and -** issue the warning message: -** warning: "signed" not implemented (ignored) -** For these compilers, we have to define PRInt8 as plain 'char'. -** Make sure that plain 'char' is indeed signed under these compilers. -*/ -#if (defined(HPUX) && defined(__cplusplus) \ - && !defined(__GNUC__) && __cplusplus < 199707L) \ - || (defined(SCO) && defined(__cplusplus) \ - && !defined(__GNUC__) && __cplusplus == 1L) -typedef char PRInt8; -#else -typedef signed char PRInt8; -#endif -#else -#error No suitable type for PRInt8/PRUint8 -#endif - -/************************************************************************ - * MACROS: PR_INT8_MAX - * PR_INT8_MIN - * PR_UINT8_MAX - * DESCRIPTION: - * The maximum and minimum values of a PRInt8 or PRUint8. -************************************************************************/ - -#define PR_INT8_MAX 127 -#define PR_INT8_MIN (-128) -#define PR_UINT8_MAX 255U - -/************************************************************************ -** TYPES: PRUint16 -** PRInt16 -** DESCRIPTION: -** The int16 types are known to be 16 bits each. -************************************************************************/ -#if PR_BYTES_PER_SHORT == 2 -typedef unsigned short PRUint16; -typedef short PRInt16; -#else -#error No suitable type for PRInt16/PRUint16 -#endif - -/************************************************************************ - * MACROS: PR_INT16_MAX - * PR_INT16_MIN - * PR_UINT16_MAX - * DESCRIPTION: - * The maximum and minimum values of a PRInt16 or PRUint16. -************************************************************************/ - -#define PR_INT16_MAX 32767 -#define PR_INT16_MIN (-32768) -#define PR_UINT16_MAX 65535U - -/************************************************************************ -** TYPES: PRUint32 -** PRInt32 -** DESCRIPTION: -** The int32 types are known to be 32 bits each. -************************************************************************/ -#if PR_BYTES_PER_INT == 4 -typedef unsigned int PRUint32; -typedef int PRInt32; -#define PR_INT32(x) x -#define PR_UINT32(x) x ## U -#elif PR_BYTES_PER_LONG == 4 -typedef unsigned long PRUint32; -typedef long PRInt32; -#define PR_INT32(x) x ## L -#define PR_UINT32(x) x ## UL -#else -#error No suitable type for PRInt32/PRUint32 -#endif - -/************************************************************************ - * MACROS: PR_INT32_MAX - * PR_INT32_MIN - * PR_UINT32_MAX - * DESCRIPTION: - * The maximum and minimum values of a PRInt32 or PRUint32. -************************************************************************/ - -#define PR_INT32_MAX PR_INT32(2147483647) -#define PR_INT32_MIN (-PR_INT32_MAX - 1) -#define PR_UINT32_MAX PR_UINT32(4294967295) - -/************************************************************************ -** TYPES: PRUint64 -** PRInt64 -** DESCRIPTION: -** The int64 types are known to be 64 bits each. Care must be used when -** declaring variables of type PRUint64 or PRInt64. Different hardware -** architectures and even different compilers have varying support for -** 64 bit values. The only guaranteed portability requires the use of -** the LL_ macros (see prlong.h). -** -** MACROS: PR_INT64 -** PR_UINT64 -** DESCRIPTION: -** The PR_INT64 and PR_UINT64 macros provide a portable way for -** specifying 64-bit integer constants. They can only be used if -** PRInt64 and PRUint64 are defined as compiler-supported 64-bit -** integer types (i.e., if HAVE_LONG_LONG is defined, which is true -** for all the supported compilers topday). If PRInt64 and PRUint64 -** are defined as structs, the LL_INIT macro defined in prlong.h has -** to be used. -** -** MACROS: PR_INT64_MAX -** PR_INT64_MIN -** PR_UINT64_MAX -** DESCRIPTION: -** The maximum and minimum values of a PRInt64 or PRUint64. -************************************************************************/ -#ifdef HAVE_LONG_LONG -/* Keep this in sync with prlong.h. */ -#if PR_BYTES_PER_LONG == 8 && !defined(PR_ALTERNATE_INT64_TYPEDEF) -typedef long PRInt64; -typedef unsigned long PRUint64; -#define PR_INT64(x) x ## L -#define PR_UINT64(x) x ## UL -#elif defined(WIN32) && !defined(__GNUC__) -typedef __int64 PRInt64; -typedef unsigned __int64 PRUint64; -#define PR_INT64(x) x ## i64 -#define PR_UINT64(x) x ## ui64 -#else -typedef long long PRInt64; -typedef unsigned long long PRUint64; -#define PR_INT64(x) x ## LL -#define PR_UINT64(x) x ## ULL -#endif /* PR_BYTES_PER_LONG == 8 */ - -#define PR_INT64_MAX PR_INT64(0x7fffffffffffffff) -#define PR_INT64_MIN (-PR_INT64_MAX - 1) -#define PR_UINT64_MAX PR_UINT64(-1) -#else /* !HAVE_LONG_LONG */ -typedef struct { -#ifdef IS_LITTLE_ENDIAN - PRUint32 lo, hi; -#else - PRUint32 hi, lo; -#endif -} PRInt64; -typedef PRInt64 PRUint64; - -#define PR_INT64_MAX (PRInt64){0x7fffffff, 0xffffffff} -#define PR_INT64_MIN (PRInt64){0xffffffff, 0xffffffff} -#define PR_UINT64_MAX (PRUint64){0xffffffff, 0xffffffff} - -#endif /* !HAVE_LONG_LONG */ - -/************************************************************************ -** TYPES: PRUintn -** PRIntn -** DESCRIPTION: -** The PRIntn types are most appropriate for automatic variables. They are -** guaranteed to be at least 16 bits, though various architectures may -** define them to be wider (e.g., 32 or even 64 bits). These types are -** never valid for fields of a structure. -************************************************************************/ -#if PR_BYTES_PER_INT >= 2 -typedef int PRIntn; -typedef unsigned int PRUintn; -#else -#error 'sizeof(int)' not sufficient for platform use -#endif - -/************************************************************************ -** TYPES: PRFloat64 -** DESCRIPTION: -** NSPR's floating point type is always 64 bits. -************************************************************************/ -typedef double PRFloat64; - -/************************************************************************ -** TYPES: PRSize -** DESCRIPTION: -** A type for representing the size of objects. -************************************************************************/ -typedef size_t PRSize; - - -/************************************************************************ -** TYPES: PROffset32, PROffset64 -** DESCRIPTION: -** A type for representing byte offsets from some location. -************************************************************************/ -typedef PRInt32 PROffset32; -typedef PRInt64 PROffset64; - -/************************************************************************ -** TYPES: PRPtrDiff -** DESCRIPTION: -** A type for pointer difference. Variables of this type are suitable -** for storing a pointer or pointer subtraction. -************************************************************************/ -typedef ptrdiff_t PRPtrdiff; - -/************************************************************************ -** TYPES: PRUptrdiff -** DESCRIPTION: -** A type for pointer difference. Variables of this type are suitable -** for storing a pointer or pointer sutraction. -************************************************************************/ -#ifdef _WIN64 -typedef PRUint64 PRUptrdiff; -#else -typedef unsigned long PRUptrdiff; -#endif - -/************************************************************************ -** TYPES: PRBool -** DESCRIPTION: -** Use PRBool for variables and parameter types. Use PR_FALSE and PR_TRUE -** for clarity of target type in assignments and actual arguments. Use -** 'if (bool)', 'while (!bool)', '(bool) ? x : y' etc., to test booleans -** just as you would C int-valued conditions. -************************************************************************/ -typedef PRIntn PRBool; -#define PR_TRUE 1 -#define PR_FALSE 0 - -/************************************************************************ -** TYPES: PRPackedBool -** DESCRIPTION: -** Use PRPackedBool within structs where bitfields are not desirable -** but minimum and consistant overhead matters. -************************************************************************/ -typedef PRUint8 PRPackedBool; - -/* -** Status code used by some routines that have a single point of failure or -** special status return. -*/ -typedef enum { PR_FAILURE = -1, PR_SUCCESS = 0 } PRStatus; - -#ifndef __PRUNICHAR__ -#define __PRUNICHAR__ -#ifdef WIN32 -typedef wchar_t PRUnichar; -#else -typedef PRUint16 PRUnichar; -#endif -#endif - -/* -** WARNING: The undocumented data types PRWord and PRUword are -** only used in the garbage collection and arena code. Do not -** use PRWord and PRUword in new code. -** -** A PRWord is an integer that is the same size as a void*. -** It implements the notion of a "word" in the Java Virtual -** Machine. (See Sec. 3.4 "Words", The Java Virtual Machine -** Specification, Addison-Wesley, September 1996. -** http://java.sun.com/docs/books/vmspec/index.html.) -*/ -#ifdef _WIN64 -typedef PRInt64 PRWord; -typedef PRUint64 PRUword; -#else -typedef long PRWord; -typedef unsigned long PRUword; -#endif - -/* - * PR_PRETEND_NORETURN, specified at the end of a function declaration, - * indicates that for the purposes of static analysis, this function does not - * return. (The function definition does not need to be annotated.) - * - * void PR_Assert(const char *s, const char *file, PRIntn ln) - * PR_PRETEND_NORETURN; - * - * Some static analyzers, like scan-build from clang, can use this information - * to eliminate false positives. From the upstream documentation of - * scan-build: - * This attribute is useful for annotating assertion handlers that actually - * can return, but for the purpose of using the analyzer we want to pretend - * that such functions do not return. - */ -#ifdef __clang_analyzer__ -#if __has_extension(attribute_analyzer_noreturn) -#define PR_PRETEND_NORETURN __attribute__((analyzer_noreturn)) -#endif -#endif - -#ifndef PR_PRETEND_NORETURN -#define PR_PRETEND_NORETURN /* no support */ -#endif - -#if defined(NO_NSPR_10_SUPPORT) -#else -/********* ???????????????? FIX ME ??????????????????????????? *****/ -/********************** Some old definitions until pr=>ds transition is done ***/ -/********************** Also, we are still using NSPR 1.0. GC ******************/ -/* -** Fundamental NSPR macros, used nearly everywhere. -*/ - -#define PR_PUBLIC_API PR_IMPLEMENT - -/* -** Macro body brackets so that macros with compound statement definitions -** behave syntactically more like functions when called. -*/ -#define NSPR_BEGIN_MACRO do { -#define NSPR_END_MACRO } while (0) - -/* -** Macro shorthands for conditional C++ extern block delimiters. -*/ -#ifdef NSPR_BEGIN_EXTERN_C -#undef NSPR_BEGIN_EXTERN_C -#endif -#ifdef NSPR_END_EXTERN_C -#undef NSPR_END_EXTERN_C -#endif - -#ifdef __cplusplus -#define NSPR_BEGIN_EXTERN_C extern "C" { -#define NSPR_END_EXTERN_C } -#else -#define NSPR_BEGIN_EXTERN_C -#define NSPR_END_EXTERN_C -#endif - -#include "obsolete/protypes.h" - -/********* ????????????? End Fix me ?????????????????????????????? *****/ -#endif /* NO_NSPR_10_SUPPORT */ - -/* -** Compile-time assert. "condition" must be a constant expression. -** The macro can be used only in places where an "extern" declaration is -** allowed. -*/ -#define PR_STATIC_ASSERT(condition) \ - extern void pr_static_assert(int arg[(condition) ? 1 : -1]) - -PR_END_EXTERN_C - -#endif /* prtypes_h___ */ - diff --git a/win32/include/spidermonkey/nspr/prvrsion.h b/win32/include/spidermonkey/nspr/prvrsion.h deleted file mode 100755 index a8415b2a..00000000 --- a/win32/include/spidermonkey/nspr/prvrsion.h +++ /dev/null @@ -1,105 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - - -/* author: jstewart */ - -#if defined(_PRVERSION_H) -#else -#define _PRVERSION_H - -#include "prtypes.h" - -PR_BEGIN_EXTERN_C - -/* All components participating in the PR version protocol must expose - * a structure and a function. The structure is defined below and named - * according to the naming conventions outlined further below. The function - * is called libVersionPoint and returns a pointer to this structure. - */ - -/* on NT, always pack the structure the same. */ -#ifdef _WIN32 -#pragma pack(push, 8) -#endif - -typedef struct { - /* - * The first field defines which version of this structure is in use. - * At this time, only version 2 is specified. If this value is not - * 2, you must read no further into the structure. - */ - PRInt32 version; - - /* for Version 2, this is the body format. */ - PRInt64 buildTime; /* 64 bits - usecs since midnight, 1/1/1970 */ - char * buildTimeString;/* a human readable version of the time */ - - PRUint8 vMajor; /* Major version of this component */ - PRUint8 vMinor; /* Minor version of this component */ - PRUint8 vPatch; /* Patch level of this component */ - - PRBool beta; /* true if this is a beta component */ - PRBool debug; /* true if this is a debug component */ - PRBool special; /* true if this component is a special build */ - - char * filename; /* The original filename */ - char * description; /* description of this component */ - char * security; /* level of security in this component */ - char * copyright; /* The copyright for this file */ - char * comment; /* free form field for misc usage */ - char * specialString; /* the special variant for this build */ -} PRVersionDescription; - -/* on NT, restore the previous packing */ -#ifdef _WIN32 -#pragma pack(pop) -#endif - -/* - * All components must define an entrypoint named libVersionPoint which - * is of type versionEntryPointType. - * - * For example, for a library named libfoo, we would have: - * - * PRVersionDescription prVersionDescription_libfoo = - * { - * ... - * }; - * - * PR_IMPLEMENT(const PRVersionDescription*) libVersionPoint(void) - * { - * return &prVersionDescription_libfoo; - * } - */ -typedef const PRVersionDescription *(*versionEntryPointType)(void); - -/* - * Where you declare your libVersionPoint, do it like this: - * PR_IMPLEMENT(const PRVersionDescription *) libVersionPoint(void) { - * fill it in... - * } - */ - -/* - * NAMING CONVENTION FOR struct - * - * all components should also expose a static PRVersionDescription - * The name of the struct should be calculated as follows: - * Take the value of filename. (If filename is not specified, calculate - * a short, unique string.) Convert all non-alphanumeric characters - * to '_'. To this, prepend "PRVersionDescription_". Thus for libfoo.so, - * the symbol name is "PRVersionDescription_libfoo_so". - * so the file should have - * PRVersionDescription PRVersionDescription_libfoo_so { fill it in }; - * on NT, this file should be declspec export. - */ - -PR_END_EXTERN_C - -#endif /* defined(_PRVERSION_H) */ - -/* prvrsion.h */ - diff --git a/win32/include/spidermonkey/nspr/prwin16.h b/win32/include/spidermonkey/nspr/prwin16.h deleted file mode 100755 index 9f8d7a99..00000000 --- a/win32/include/spidermonkey/nspr/prwin16.h +++ /dev/null @@ -1,164 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef prwin16_h___ -#define prwin16_h___ - -/* -** Condition use of this header on platform. -*/ -#if (defined(XP_PC) && !defined(_WIN32) && !defined(XP_OS2) && defined(MOZILLA_CLIENT)) || defined(WIN16) -#include - -PR_BEGIN_EXTERN_C -/* -** Win16 stdio special case. -** To get stdio to work for Win16, all calls to printf() and related -** things must be called from the environment of the .EXE; calls to -** printf() from the .DLL send output to the bit-bucket. -** -** To make sure that PR_fprintf(), and related functions, work correctly, -** the actual stream I/O to stdout, stderr, stdin must be done in the -** .EXE. To do this, a hack is placed in _MD_Write() such that the -** fd for stdio handles results in a call to the .EXE. -** -** file w16stdio.c contains the functions that get called from NSPR -** to do the actual I/O. w16stdio.o must be statically linked with -** any application needing stdio for Win16. -** -** The address of these functions must be made available to the .DLL -** so he can call back to the .EXE. To do this, function -** PR_MD_RegisterW16StdioCallbacks() is called from the .EXE. -** The arguments are the functions defined in w16stdio.c -** At runtime, MD_Write() calls the registered functions, if any -** were registered. -** -** prinit.h contains a macro PR_STDIO_INIT() that calls the registration -** function for Win16; For other platforms, the macro is a No-Op. -** -** Note that stdio is not operational at all on Win16 GUI applications. -** This special case exists to provide stdio capability from the NSPR -** .DLL for command line applications only. NSPR's test cases are -** almost exclusively command line applications. -** -** See also: w16io.c, w16stdio.c -*/ -typedef PRInt32 (PR_CALLBACK *PRStdinRead)( void *buf, PRInt32 amount); -typedef PRInt32 (PR_CALLBACK *PRStdoutWrite)( void *buf, PRInt32 amount); -typedef PRInt32 (PR_CALLBACK *PRStderrWrite)( void *buf, PRInt32 amount); - -NSPR_API(PRStatus) -PR_MD_RegisterW16StdioCallbacks( - PRStdinRead inReadf, /* i: function pointer for stdin read */ - PRStdoutWrite outWritef, /* i: function pointer for stdout write */ - PRStderrWrite errWritef /* i: function pointer for stderr write */ - ); - -NSPR_API(PRInt32) -_PL_W16StdioWrite( void *buf, PRInt32 amount ); - -NSPR_API(PRInt32) -_PL_W16StdioRead( void *buf, PRInt32 amount ); - -#define PR_STDIO_INIT() PR_MD_RegisterW16StdioCallbacks( \ - _PL_W16StdioRead, _PL_W16StdioWrite, _PL_W16StdioWrite ); \ - PR_INIT_CALLBACKS(); - -/* -** Win16 hackery. -** -*/ -struct PRMethodCallbackStr { - int (PR_CALLBACK *auxOutput)(const char *outputString); - size_t (PR_CALLBACK *strftime)(char *s, size_t len, const char *fmt, const struct tm *p); - void * (PR_CALLBACK *malloc)( size_t size ); - void * (PR_CALLBACK *calloc)(size_t n, size_t size ); - void * (PR_CALLBACK *realloc)( void* old_blk, size_t size ); - void (PR_CALLBACK *free)( void *ptr ); - void * (PR_CALLBACK *getenv)( const char *name); - int (PR_CALLBACK *putenv)( const char *assoc); -/* void * (PR_CALLBACK *perror)( const char *prefix ); */ -}; - -NSPR_API(void) PR_MDRegisterCallbacks(struct PRMethodCallbackStr *); - -int PR_CALLBACK _PL_W16CallBackPuts( const char *outputString ); -size_t PR_CALLBACK _PL_W16CallBackStrftime( - char *s, - size_t len, - const char *fmt, - const struct tm *p ); -void * PR_CALLBACK _PL_W16CallBackMalloc( size_t size ); -void * PR_CALLBACK _PL_W16CallBackCalloc( size_t n, size_t size ); -void * PR_CALLBACK _PL_W16CallBackRealloc( - void *old_blk, - size_t size ); -void PR_CALLBACK _PL_W16CallBackFree( void *ptr ); -void * PR_CALLBACK _PL_W16CallBackGetenv( const char *name ); -int PR_CALLBACK _PL_W16CallBackPutenv( const char *assoc ); - -/* -** Hackery! -** -** These functions are provided as static link points. -** This is to satisfy the quick port of Gromit to NSPR 2.0 -** ... Don't do this! ... alas, It may never go away. -** -*/ -NSPR_API(int) PR_MD_printf(const char *, ...); -NSPR_API(void) PR_MD_exit(int); -NSPR_API(size_t) PR_MD_strftime(char *, size_t, const char *, const struct tm *); -NSPR_API(int) PR_MD_sscanf(const char *, const char *, ...); -NSPR_API(void*) PR_MD_malloc( size_t size ); -NSPR_API(void*) PR_MD_calloc( size_t n, size_t size ); -NSPR_API(void*) PR_MD_realloc( void* old_blk, size_t size ); -NSPR_API(void) PR_MD_free( void *ptr ); -NSPR_API(char*) PR_MD_getenv( const char *name ); -NSPR_API(int) PR_MD_putenv( const char *assoc ); -NSPR_API(int) PR_MD_fprintf(FILE *fPtr, const char *fmt, ...); - -#define PR_INIT_CALLBACKS() \ - { \ - static struct PRMethodCallbackStr cbf = { \ - _PL_W16CallBackPuts, \ - _PL_W16CallBackStrftime, \ - _PL_W16CallBackMalloc, \ - _PL_W16CallBackCalloc, \ - _PL_W16CallBackRealloc, \ - _PL_W16CallBackFree, \ - _PL_W16CallBackGetenv, \ - _PL_W16CallBackPutenv, \ - }; \ - PR_MDRegisterCallbacks( &cbf ); \ - } - - -/* -** Get the exception context for Win16 MFC applications threads -*/ -NSPR_API(void *) PR_W16GetExceptionContext(void); -/* -** Set the exception context for Win16 MFC applications threads -*/ -NSPR_API(void) PR_W16SetExceptionContext(void *context); - -PR_END_EXTERN_C -#else -/* -** For platforms other than Win16, define -** PR_STDIO_INIT() as a No-Op. -*/ -#define PR_STDIO_INIT() -#endif /* WIN16 || MOZILLA_CLIENT */ - -#endif /* prwin16_h___ */ - - - - - - - - diff --git a/win32/include/spidermonkey/unicode/alphaindex.h b/win32/include/spidermonkey/unicode/alphaindex.h deleted file mode 100755 index c7b361ff..00000000 --- a/win32/include/spidermonkey/unicode/alphaindex.h +++ /dev/null @@ -1,754 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2011-2014 International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -*/ - -#ifndef INDEXCHARS_H -#define INDEXCHARS_H - -#include "unicode/utypes.h" -#include "unicode/uobject.h" -#include "unicode/locid.h" - -#if !UCONFIG_NO_COLLATION - -/** - * \file - * \brief C++ API: Index Characters - */ - -U_CDECL_BEGIN - -/** - * Constants for Alphabetic Index Label Types. - * The form of these enum constants anticipates having a plain C API - * for Alphabetic Indexes that will also use them. - * @stable ICU 4.8 - */ -typedef enum UAlphabeticIndexLabelType { - /** - * Normal Label, typically the starting letter of the names - * in the bucket with this label. - * @stable ICU 4.8 - */ - U_ALPHAINDEX_NORMAL = 0, - - /** - * Undeflow Label. The bucket with this label contains names - * in scripts that sort before any of the bucket labels in this index. - * @stable ICU 4.8 - */ - U_ALPHAINDEX_UNDERFLOW = 1, - - /** - * Inflow Label. The bucket with this label contains names - * in scripts that sort between two of the bucket labels in this index. - * Inflow labels are created when an index contains normal labels for - * multiple scripts, and skips other scripts that sort between some of the - * included scripts. - * @stable ICU 4.8 - */ - U_ALPHAINDEX_INFLOW = 2, - - /** - * Overflow Label. Te bucket with this label contains names in scripts - * that sort after all of the bucket labels in this index. - * @stable ICU 4.8 - */ - U_ALPHAINDEX_OVERFLOW = 3 -} UAlphabeticIndexLabelType; - - -struct UHashtable; -U_CDECL_END - -U_NAMESPACE_BEGIN - -// Forward Declarations - -class BucketList; -class Collator; -class RuleBasedCollator; -class StringEnumeration; -class UnicodeSet; -class UVector; - -/** - * AlphabeticIndex supports the creation of a UI index appropriate for a given language. - * It can support either direct use, or use with a client that doesn't support localized collation. - * The following is an example of what an index might look like in a UI: - * - *
- *  ... A B C D E F G H I J K L M N O P Q R S T U V W X Y Z  ...
- *
- *  A
- *     Addison
- *     Albertson
- *     Azensky
- *  B
- *     Baker
- *  ...
- * 
- * - * The class can generate a list of labels for use as a UI "index", that is, a list of - * clickable characters (or character sequences) that allow the user to see a segment - * (bucket) of a larger "target" list. That is, each label corresponds to a bucket in - * the target list, where everything in the bucket is greater than or equal to the character - * (according to the locale's collation). Strings can be added to the index; - * they will be in sorted order in the right bucket. - *

- * The class also supports having buckets for strings before the first (underflow), - * after the last (overflow), and between scripts (inflow). For example, if the index - * is constructed with labels for Russian and English, Greek characters would fall - * into an inflow bucket between the other two scripts. - *

- * The AlphabeticIndex class is not intended for public subclassing. - * - *

Note: If you expect to have a lot of ASCII or Latin characters - * as well as characters from the user's language, - * then it is a good idea to call addLabels(Locale::getEnglish(), status).

- * - *

Direct Use

- *

The following shows an example of building an index directly. - * The "show..." methods below are just to illustrate usage. - * - *

- * // Create a simple index.  "Item" is assumed to be an application
- * // defined type that the application's UI and other processing knows about,
- * //  and that has a name.
- *
- * UErrorCode status = U_ZERO_ERROR;
- * AlphabeticIndex index = new AlphabeticIndex(desiredLocale, status);
- * index->addLabels(additionalLocale, status);
- * for (Item *item in some source of Items ) {
- *     index->addRecord(item->name(), item, status);
- * }
- * ...
- * // Show index at top. We could skip or gray out empty buckets
- *
- * while (index->nextBucket(status)) {
- *     if (showAll || index->getBucketRecordCount() != 0) {
- *         showLabelAtTop(UI, index->getBucketLabel());
- *     }
- * }
- *  ...
- * // Show the buckets with their contents, skipping empty buckets
- *
- * index->resetBucketIterator(status);
- * while (index->nextBucket(status)) {
- *    if (index->getBucketRecordCount() != 0) {
- *        showLabelInList(UI, index->getBucketLabel());
- *        while (index->nextRecord(status)) {
- *            showIndexedItem(UI, static_cast(index->getRecordData()))
- * 
- * - * The caller can build different UIs using this class. - * For example, an index character could be omitted or grayed-out - * if its bucket is empty. Small buckets could also be combined based on size, such as: - * - *
- * ... A-F G-N O-Z ...
- * 
- * - *

Client Support

- *

Callers can also use the AlphabeticIndex::ImmutableIndex, or the AlphabeticIndex itself, - * to support sorting on a client that doesn't support AlphabeticIndex functionality. - * - *

The ImmutableIndex is both immutable and thread-safe. - * The corresponding AlphabeticIndex methods are not thread-safe because - * they "lazily" build the index buckets. - *

    - *
  • ImmutableIndex.getBucket(index) provides random access to all - * buckets and their labels and label types. - *
  • The AlphabeticIndex bucket iterator or ImmutableIndex.getBucket(0..getBucketCount-1) - * can be used to get a list of the labels, - * such as "...", "A", "B",..., and send that list to the client. - *
  • When the client has a new name, it sends that name to the server. - * The server needs to call the following methods, - * and communicate the bucketIndex and collationKey back to the client. - * - *
    - * int32_t bucketIndex = index.getBucketIndex(name, status);
    - * const UnicodeString &label = immutableIndex.getBucket(bucketIndex)->getLabel();  // optional
    - * int32_t skLength = collator.getSortKey(name, sk, skCapacity);
    - * 
    - * - *
  • The client would put the name (and associated information) into its bucket for bucketIndex. The sort key sk is a - * sequence of bytes that can be compared with a binary compare, and produce the right localized result.
  • - *
- * - * @stable ICU 4.8 - */ -class U_I18N_API AlphabeticIndex: public UObject { -public: - /** - * An index "bucket" with a label string and type. - * It is referenced by getBucketIndex(), - * and returned by ImmutableIndex.getBucket(). - * - * The Bucket class is not intended for public subclassing. - * @stable ICU 51 - */ - class U_I18N_API Bucket : public UObject { - public: - /** - * Destructor. - * @stable ICU 51 - */ - virtual ~Bucket(); - - /** - * Returns the label string. - * - * @return the label string for the bucket - * @stable ICU 51 - */ - const UnicodeString &getLabel() const { return label_; } - /** - * Returns whether this bucket is a normal, underflow, overflow, or inflow bucket. - * - * @return the bucket label type - * @stable ICU 51 - */ - UAlphabeticIndexLabelType getLabelType() const { return labelType_; } - - private: - friend class AlphabeticIndex; - friend class BucketList; - - UnicodeString label_; - UnicodeString lowerBoundary_; - UAlphabeticIndexLabelType labelType_; - Bucket *displayBucket_; - int32_t displayIndex_; - UVector *records_; // Records are owned by the inputList_ vector. - - Bucket(const UnicodeString &label, // Parameter strings are copied. - const UnicodeString &lowerBoundary, - UAlphabeticIndexLabelType type); - }; - - /** - * Immutable, thread-safe version of AlphabeticIndex. - * This class provides thread-safe methods for bucketing, - * and random access to buckets and their properties, - * but does not offer adding records to the index. - * - * The ImmutableIndex class is not intended for public subclassing. - * - * @stable ICU 51 - */ - class U_I18N_API ImmutableIndex : public UObject { - public: - /** - * Destructor. - * @stable ICU 51 - */ - virtual ~ImmutableIndex(); - - /** - * Returns the number of index buckets and labels, including underflow/inflow/overflow. - * - * @return the number of index buckets - * @stable ICU 51 - */ - int32_t getBucketCount() const; - - /** - * Finds the index bucket for the given name and returns the number of that bucket. - * Use getBucket() to get the bucket's properties. - * - * @param name the string to be sorted into an index bucket - * @return the bucket number for the name - * @stable ICU 51 - */ - int32_t getBucketIndex(const UnicodeString &name, UErrorCode &errorCode) const; - - /** - * Returns the index-th bucket. Returns NULL if the index is out of range. - * - * @param index bucket number - * @return the index-th bucket - * @stable ICU 51 - */ - const Bucket *getBucket(int32_t index) const; - - private: - friend class AlphabeticIndex; - - ImmutableIndex(BucketList *bucketList, Collator *collatorPrimaryOnly) - : buckets_(bucketList), collatorPrimaryOnly_(collatorPrimaryOnly) {} - - BucketList *buckets_; - Collator *collatorPrimaryOnly_; - }; - - /** - * Construct an AlphabeticIndex object for the specified locale. If the locale's - * data does not include index characters, a set of them will be - * synthesized based on the locale's exemplar characters. The locale - * determines the sorting order for both the index characters and the - * user item names appearing under each Index character. - * - * @param locale the desired locale. - * @param status Error code, will be set with the reason if the construction - * of the AlphabeticIndex object fails. - * @stable ICU 4.8 - */ - AlphabeticIndex(const Locale &locale, UErrorCode &status); - - /** - * Construct an AlphabeticIndex that uses a specific collator. - * - * The index will be created with no labels; the addLabels() function must be called - * after creation to add the desired labels to the index. - * - * The index adopts the collator, and is responsible for deleting it. - * The caller should make no further use of the collator after creating the index. - * - * @param collator The collator to use to order the contents of this index. - * @param status Error code, will be set with the reason if the - * operation fails. - * @stable ICU 51 - */ - AlphabeticIndex(RuleBasedCollator *collator, UErrorCode &status); - - /** - * Add Labels to this Index. The labels are additions to those - * that are already in the index; they do not replace the existing - * ones. - * @param additions The additional characters to add to the index, such as A-Z. - * @param status Error code, will be set with the reason if the - * operation fails. - * @return this, for chaining - * @stable ICU 4.8 - */ - virtual AlphabeticIndex &addLabels(const UnicodeSet &additions, UErrorCode &status); - - /** - * Add the index characters from a Locale to the index. The labels - * are added to those that are already in the index; they do not replace the - * existing index characters. The collation order for this index is not - * changed; it remains that of the locale that was originally specified - * when creating this Index. - * - * @param locale The locale whose index characters are to be added. - * @param status Error code, will be set with the reason if the - * operation fails. - * @return this, for chaining - * @stable ICU 4.8 - */ - virtual AlphabeticIndex &addLabels(const Locale &locale, UErrorCode &status); - - /** - * Destructor - * @stable ICU 4.8 - */ - virtual ~AlphabeticIndex(); - - /** - * Builds an immutable, thread-safe version of this instance, without data records. - * - * @return an immutable index instance - * @stable ICU 51 - */ - ImmutableIndex *buildImmutableIndex(UErrorCode &errorCode); - - /** - * Get the Collator that establishes the ordering of the items in this index. - * Ownership of the collator remains with the AlphabeticIndex instance. - * - * The returned collator is a reference to the internal collator used by this - * index. It may be safely used to compare the names of items or to get - * sort keys for names. However if any settings need to be changed, - * or other non-const methods called, a cloned copy must be made first. - * - * @return The collator - * @stable ICU 4.8 - */ - virtual const RuleBasedCollator &getCollator() const; - - - /** - * Get the default label used for abbreviated buckets between other index characters. - * For example, consider the labels when Latin and Greek are used: - * X Y Z ... Α Β Γ. - * - * @return inflow label - * @stable ICU 4.8 - */ - virtual const UnicodeString &getInflowLabel() const; - - /** - * Set the default label used for abbreviated buckets between other index characters. - * An inflow label will be automatically inserted if two otherwise-adjacent label characters - * are from different scripts, e.g. Latin and Cyrillic, and a third script, e.g. Greek, - * sorts between the two. The default inflow character is an ellipsis (...) - * - * @param inflowLabel the new Inflow label. - * @param status Error code, will be set with the reason if the operation fails. - * @return this - * @stable ICU 4.8 - */ - virtual AlphabeticIndex &setInflowLabel(const UnicodeString &inflowLabel, UErrorCode &status); - - - /** - * Get the special label used for items that sort after the last normal label, - * and that would not otherwise have an appropriate label. - * - * @return the overflow label - * @stable ICU 4.8 - */ - virtual const UnicodeString &getOverflowLabel() const; - - - /** - * Set the label used for items that sort after the last normal label, - * and that would not otherwise have an appropriate label. - * - * @param overflowLabel the new overflow label. - * @param status Error code, will be set with the reason if the operation fails. - * @return this - * @stable ICU 4.8 - */ - virtual AlphabeticIndex &setOverflowLabel(const UnicodeString &overflowLabel, UErrorCode &status); - - /** - * Get the special label used for items that sort before the first normal label, - * and that would not otherwise have an appropriate label. - * - * @return underflow label - * @stable ICU 4.8 - */ - virtual const UnicodeString &getUnderflowLabel() const; - - /** - * Set the label used for items that sort before the first normal label, - * and that would not otherwise have an appropriate label. - * - * @param underflowLabel the new underflow label. - * @param status Error code, will be set with the reason if the operation fails. - * @return this - * @stable ICU 4.8 - */ - virtual AlphabeticIndex &setUnderflowLabel(const UnicodeString &underflowLabel, UErrorCode &status); - - - /** - * Get the limit on the number of labels permitted in the index. - * The number does not include over, under and inflow labels. - * - * @return maxLabelCount maximum number of labels. - * @stable ICU 4.8 - */ - virtual int32_t getMaxLabelCount() const; - - /** - * Set a limit on the number of labels permitted in the index. - * The number does not include over, under and inflow labels. - * Currently, if the number is exceeded, then every - * nth item is removed to bring the count down. - * A more sophisticated mechanism may be available in the future. - * - * @param maxLabelCount the maximum number of labels. - * @param status error code - * @return This, for chaining - * @stable ICU 4.8 - */ - virtual AlphabeticIndex &setMaxLabelCount(int32_t maxLabelCount, UErrorCode &status); - - - /** - * Add a record to the index. Each record will be associated with an index Bucket - * based on the record's name. The list of records for each bucket will be sorted - * based on the collation ordering of the names in the index's locale. - * Records with duplicate names are permitted; they will be kept in the order - * that they were added. - * - * @param name The display name for the Record. The Record will be placed in - * a bucket based on this name. - * @param data An optional pointer to user data associated with this - * item. When iterating the contents of a bucket, both the - * data pointer the name will be available for each Record. - * @param status Error code, will be set with the reason if the operation fails. - * @return This, for chaining. - * @stable ICU 4.8 - */ - virtual AlphabeticIndex &addRecord(const UnicodeString &name, const void *data, UErrorCode &status); - - /** - * Remove all Records from the Index. The set of Buckets, which define the headings under - * which records are classified, is not altered. - * - * @param status Error code, will be set with the reason if the operation fails. - * @return This, for chaining. - * @stable ICU 4.8 - */ - virtual AlphabeticIndex &clearRecords(UErrorCode &status); - - - /** Get the number of labels in this index. - * Note: may trigger lazy index construction. - * - * @param status Error code, will be set with the reason if the operation fails. - * @return The number of labels in this index, including any under, over or - * in-flow labels. - * @stable ICU 4.8 - */ - virtual int32_t getBucketCount(UErrorCode &status); - - - /** Get the total number of Records in this index, that is, the number - * of pairs added. - * - * @param status Error code, will be set with the reason if the operation fails. - * @return The number of records in this index, that is, the total number - * of (name, data) items added with addRecord(). - * @stable ICU 4.8 - */ - virtual int32_t getRecordCount(UErrorCode &status); - - - - /** - * Given the name of a record, return the zero-based index of the Bucket - * in which the item should appear. The name need not be in the index. - * A Record will not be added to the index by this function. - * Bucket numbers are zero-based, in Bucket iteration order. - * - * @param itemName The name whose bucket position in the index is to be determined. - * @param status Error code, will be set with the reason if the operation fails. - * @return The bucket number for this name. - * @stable ICU 4.8 - * - */ - virtual int32_t getBucketIndex(const UnicodeString &itemName, UErrorCode &status); - - - /** - * Get the zero based index of the current Bucket from an iteration - * over the Buckets of this index. Return -1 if no iteration is in process. - * @return the index of the current Bucket - * @stable ICU 4.8 - */ - virtual int32_t getBucketIndex() const; - - - /** - * Advance the iteration over the Buckets of this index. Return FALSE if - * there are no more Buckets. - * - * @param status Error code, will be set with the reason if the operation fails. - * U_ENUM_OUT_OF_SYNC_ERROR will be reported if the index is modified while - * an enumeration of its contents are in process. - * - * @return TRUE if success, FALSE if at end of iteration - * @stable ICU 4.8 - */ - virtual UBool nextBucket(UErrorCode &status); - - /** - * Return the name of the Label of the current bucket from an iteration over the buckets. - * If the iteration is before the first Bucket (nextBucket() has not been called), - * or after the last, return an empty string. - * - * @return the bucket label. - * @stable ICU 4.8 - */ - virtual const UnicodeString &getBucketLabel() const; - - /** - * Return the type of the label for the current Bucket (selected by the - * iteration over Buckets.) - * - * @return the label type. - * @stable ICU 4.8 - */ - virtual UAlphabeticIndexLabelType getBucketLabelType() const; - - /** - * Get the number of Records in the current Bucket. - * If the current bucket iteration position is before the first label or after the - * last, return 0. - * - * @return the number of Records. - * @stable ICU 4.8 - */ - virtual int32_t getBucketRecordCount() const; - - - /** - * Reset the Bucket iteration for this index. The next call to nextBucket() - * will restart the iteration at the first label. - * - * @param status Error code, will be set with the reason if the operation fails. - * @return this, for chaining. - * @stable ICU 4.8 - */ - virtual AlphabeticIndex &resetBucketIterator(UErrorCode &status); - - /** - * Advance to the next record in the current Bucket. - * When nextBucket() is called, Record iteration is reset to just before the - * first Record in the new Bucket. - * - * @param status Error code, will be set with the reason if the operation fails. - * U_ENUM_OUT_OF_SYNC_ERROR will be reported if the index is modified while - * an enumeration of its contents are in process. - * @return TRUE if successful, FALSE when the iteration advances past the last item. - * @stable ICU 4.8 - */ - virtual UBool nextRecord(UErrorCode &status); - - /** - * Get the name of the current Record. - * Return an empty string if the Record iteration position is before first - * or after the last. - * - * @return The name of the current index item. - * @stable ICU 4.8 - */ - virtual const UnicodeString &getRecordName() const; - - - /** - * Return the data pointer of the Record currently being iterated over. - * Return NULL if the current iteration position before the first item in this Bucket, - * or after the last. - * - * @return The current Record's data pointer. - * @stable ICU 4.8 - */ - virtual const void *getRecordData() const; - - - /** - * Reset the Record iterator position to before the first Record in the current Bucket. - * - * @return This, for chaining. - * @stable ICU 4.8 - */ - virtual AlphabeticIndex &resetRecordIterator(); - -private: - /** - * No Copy constructor. - * @internal - */ - AlphabeticIndex(const AlphabeticIndex &other); - - /** - * No assignment. - */ - AlphabeticIndex &operator =(const AlphabeticIndex & /*other*/) { return *this;}; - - /** - * No Equality operators. - * @internal - */ - virtual UBool operator==(const AlphabeticIndex& other) const; - - /** - * Inequality operator. - * @internal - */ - virtual UBool operator!=(const AlphabeticIndex& other) const; - - // Common initialization, for use from all constructors. - void init(const Locale *locale, UErrorCode &status); - - /** - * This method is called to get the index exemplars. Normally these come from the locale directly, - * but if they aren't available, we have to synthesize them. - */ - void addIndexExemplars(const Locale &locale, UErrorCode &status); - /** - * Add Chinese index characters from the tailoring. - */ - UBool addChineseIndexCharacters(UErrorCode &errorCode); - - UVector *firstStringsInScript(UErrorCode &status); - - static UnicodeString separated(const UnicodeString &item); - - /** - * Determine the best labels to use. - * This is based on the exemplars, but we also process to make sure that they are unique, - * and sort differently, and that the overall list is small enough. - */ - void initLabels(UVector &indexCharacters, UErrorCode &errorCode) const; - BucketList *createBucketList(UErrorCode &errorCode) const; - void initBuckets(UErrorCode &errorCode); - void clearBuckets(); - void internalResetBucketIterator(); - -public: - - // The Record is declared public only to allow access from - // implementation code written in plain C. - // It is not intended for public use. - -#ifndef U_HIDE_INTERNAL_API - /** - * A (name, data) pair, to be sorted by name into one of the index buckets. - * The user data is not used by the index implementation. - * @internal - */ - struct Record: public UMemory { - const UnicodeString name_; - const void *data_; - Record(const UnicodeString &name, const void *data); - ~Record(); - }; -#endif /* U_HIDE_INTERNAL_API */ - -private: - - /** - * Holds all user records before they are distributed into buckets. - * Type of contents is (Record *) - * @internal - */ - UVector *inputList_; - - int32_t labelsIterIndex_; // Index of next item to return. - int32_t itemsIterIndex_; - Bucket *currentBucket_; // While an iteration of the index in underway, - // point to the bucket for the current label. - // NULL when no iteration underway. - - int32_t maxLabelCount_; // Limit on # of labels permitted in the index. - - UnicodeSet *initialLabels_; // Initial (unprocessed) set of Labels. Union - // of those explicitly set by the user plus - // those from locales. Raw values, before - // crunching into bucket labels. - - UVector *firstCharsInScripts_; // The first character from each script, - // in collation order. - - RuleBasedCollator *collator_; - RuleBasedCollator *collatorPrimaryOnly_; - - // Lazy evaluated: null means that we have not built yet. - BucketList *buckets_; - - UnicodeString inflowLabel_; - UnicodeString overflowLabel_; - UnicodeString underflowLabel_; - UnicodeString overflowComparisonString_; - - UnicodeString emptyString_; -}; - -U_NAMESPACE_END - -#endif // !UCONFIG_NO_COLLATION -#endif diff --git a/win32/include/spidermonkey/unicode/appendable.h b/win32/include/spidermonkey/unicode/appendable.h deleted file mode 100755 index 2ae33450..00000000 --- a/win32/include/spidermonkey/unicode/appendable.h +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2011-2012, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* file name: appendable.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2010dec07 -* created by: Markus W. Scherer -*/ - -#ifndef __APPENDABLE_H__ -#define __APPENDABLE_H__ - -/** - * \file - * \brief C++ API: Appendable class: Sink for Unicode code points and 16-bit code units (UChars). - */ - -#include "unicode/utypes.h" -#include "unicode/uobject.h" - -U_NAMESPACE_BEGIN - -class UnicodeString; - -/** - * Base class for objects to which Unicode characters and strings can be appended. - * Combines elements of Java Appendable and ICU4C ByteSink. - * - * This class can be used in APIs where it does not matter whether the actual destination is - * a UnicodeString, a UChar[] array, a UnicodeSet, or any other object - * that receives and processes characters and/or strings. - * - * Implementation classes must implement at least appendCodeUnit(UChar). - * The base class provides default implementations for the other methods. - * - * The methods do not take UErrorCode parameters. - * If an error occurs (e.g., out-of-memory), - * in addition to returning FALSE from failing operations, - * the implementation must prevent unexpected behavior (e.g., crashes) - * from further calls and should make the error condition available separately - * (e.g., store a UErrorCode, make/keep a UnicodeString bogus). - * @stable ICU 4.8 - */ -class U_COMMON_API Appendable : public UObject { -public: - /** - * Destructor. - * @stable ICU 4.8 - */ - ~Appendable(); - - /** - * Appends a 16-bit code unit. - * @param c code unit - * @return TRUE if the operation succeeded - * @stable ICU 4.8 - */ - virtual UBool appendCodeUnit(UChar c) = 0; - - /** - * Appends a code point. - * The default implementation calls appendCodeUnit(UChar) once or twice. - * @param c code point 0..0x10ffff - * @return TRUE if the operation succeeded - * @stable ICU 4.8 - */ - virtual UBool appendCodePoint(UChar32 c); - - /** - * Appends a string. - * The default implementation calls appendCodeUnit(UChar) for each code unit. - * @param s string, must not be NULL if length!=0 - * @param length string length, or -1 if NUL-terminated - * @return TRUE if the operation succeeded - * @stable ICU 4.8 - */ - virtual UBool appendString(const UChar *s, int32_t length); - - /** - * Tells the object that the caller is going to append roughly - * appendCapacity UChars. A subclass might use this to pre-allocate - * a larger buffer if necessary. - * The default implementation does nothing. (It always returns TRUE.) - * @param appendCapacity estimated number of UChars that will be appended - * @return TRUE if the operation succeeded - * @stable ICU 4.8 - */ - virtual UBool reserveAppendCapacity(int32_t appendCapacity); - - /** - * Returns a writable buffer for appending and writes the buffer's capacity to - * *resultCapacity. Guarantees *resultCapacity>=minCapacity. - * May return a pointer to the caller-owned scratch buffer which must have - * scratchCapacity>=minCapacity. - * The returned buffer is only valid until the next operation - * on this Appendable. - * - * After writing at most *resultCapacity UChars, call appendString() with the - * pointer returned from this function and the number of UChars written. - * Many appendString() implementations will avoid copying UChars if this function - * returned an internal buffer. - * - * Partial usage example: - * \code - * int32_t capacity; - * UChar* buffer = app.getAppendBuffer(..., &capacity); - * ... Write n UChars into buffer, with n <= capacity. - * app.appendString(buffer, n); - * \endcode - * In many implementations, that call to append will avoid copying UChars. - * - * If the Appendable allocates or reallocates an internal buffer, it should use - * the desiredCapacityHint if appropriate. - * If a caller cannot provide a reasonable guess at the desired capacity, - * it should pass desiredCapacityHint=0. - * - * If a non-scratch buffer is returned, the caller may only pass - * a prefix to it to appendString(). - * That is, it is not correct to pass an interior pointer to appendString(). - * - * The default implementation always returns the scratch buffer. - * - * @param minCapacity required minimum capacity of the returned buffer; - * must be non-negative - * @param desiredCapacityHint desired capacity of the returned buffer; - * must be non-negative - * @param scratch default caller-owned buffer - * @param scratchCapacity capacity of the scratch buffer - * @param resultCapacity pointer to an integer which will be set to the - * capacity of the returned buffer - * @return a buffer with *resultCapacity>=minCapacity - * @stable ICU 4.8 - */ - virtual UChar *getAppendBuffer(int32_t minCapacity, - int32_t desiredCapacityHint, - UChar *scratch, int32_t scratchCapacity, - int32_t *resultCapacity); -}; - -/** - * An Appendable implementation which writes to a UnicodeString. - * - * This class is not intended for public subclassing. - * @stable ICU 4.8 - */ -class U_COMMON_API UnicodeStringAppendable : public Appendable { -public: - /** - * Aliases the UnicodeString (keeps its reference) for writing. - * @param s The UnicodeString to which this Appendable will write. - * @stable ICU 4.8 - */ - explicit UnicodeStringAppendable(UnicodeString &s) : str(s) {} - - /** - * Destructor. - * @stable ICU 4.8 - */ - ~UnicodeStringAppendable(); - - /** - * Appends a 16-bit code unit to the string. - * @param c code unit - * @return TRUE if the operation succeeded - * @stable ICU 4.8 - */ - virtual UBool appendCodeUnit(UChar c); - - /** - * Appends a code point to the string. - * @param c code point 0..0x10ffff - * @return TRUE if the operation succeeded - * @stable ICU 4.8 - */ - virtual UBool appendCodePoint(UChar32 c); - - /** - * Appends a string to the UnicodeString. - * @param s string, must not be NULL if length!=0 - * @param length string length, or -1 if NUL-terminated - * @return TRUE if the operation succeeded - * @stable ICU 4.8 - */ - virtual UBool appendString(const UChar *s, int32_t length); - - /** - * Tells the UnicodeString that the caller is going to append roughly - * appendCapacity UChars. - * @param appendCapacity estimated number of UChars that will be appended - * @return TRUE if the operation succeeded - * @stable ICU 4.8 - */ - virtual UBool reserveAppendCapacity(int32_t appendCapacity); - - /** - * Returns a writable buffer for appending and writes the buffer's capacity to - * *resultCapacity. Guarantees *resultCapacity>=minCapacity. - * May return a pointer to the caller-owned scratch buffer which must have - * scratchCapacity>=minCapacity. - * The returned buffer is only valid until the next write operation - * on the UnicodeString. - * - * For details see Appendable::getAppendBuffer(). - * - * @param minCapacity required minimum capacity of the returned buffer; - * must be non-negative - * @param desiredCapacityHint desired capacity of the returned buffer; - * must be non-negative - * @param scratch default caller-owned buffer - * @param scratchCapacity capacity of the scratch buffer - * @param resultCapacity pointer to an integer which will be set to the - * capacity of the returned buffer - * @return a buffer with *resultCapacity>=minCapacity - * @stable ICU 4.8 - */ - virtual UChar *getAppendBuffer(int32_t minCapacity, - int32_t desiredCapacityHint, - UChar *scratch, int32_t scratchCapacity, - int32_t *resultCapacity); - -private: - UnicodeString &str; -}; - -U_NAMESPACE_END - -#endif // __APPENDABLE_H__ diff --git a/win32/include/spidermonkey/unicode/basictz.h b/win32/include/spidermonkey/unicode/basictz.h deleted file mode 100755 index 90073b23..00000000 --- a/win32/include/spidermonkey/unicode/basictz.h +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2007-2013, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -*/ -#ifndef BASICTZ_H -#define BASICTZ_H - -/** - * \file - * \brief C++ API: ICU TimeZone base class - */ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/timezone.h" -#include "unicode/tzrule.h" -#include "unicode/tztrans.h" - -U_NAMESPACE_BEGIN - -// forward declarations -class UVector; - -/** - * BasicTimeZone is an abstract class extending TimeZone. - * This class provides some additional methods to access time zone transitions and rules. - * All ICU TimeZone concrete subclasses extend this class. - * @stable ICU 3.8 - */ -class U_I18N_API BasicTimeZone: public TimeZone { -public: - /** - * Destructor. - * @stable ICU 3.8 - */ - virtual ~BasicTimeZone(); - - /** - * Gets the first time zone transition after the base time. - * @param base The base time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives the first transition after the base time. - * @return TRUE if the transition is found. - * @stable ICU 3.8 - */ - virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const = 0; - - /** - * Gets the most recent time zone transition before the base time. - * @param base The base time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives the most recent transition before the base time. - * @return TRUE if the transition is found. - * @stable ICU 3.8 - */ - virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const = 0; - - /** - * Checks if the time zone has equivalent transitions in the time range. - * This method returns true when all of transition times, from/to standard - * offsets and DST savings used by this time zone match the other in the - * time range. - * @param tz The BasicTimeZone object to be compared with. - * @param start The start time of the evaluated time range (inclusive) - * @param end The end time of the evaluated time range (inclusive) - * @param ignoreDstAmount - * When true, any transitions with only daylight saving amount - * changes will be ignored, except either of them is zero. - * For example, a transition from rawoffset 3:00/dstsavings 1:00 - * to rawoffset 2:00/dstsavings 2:00 is excluded from the comparison, - * but a transtion from rawoffset 2:00/dstsavings 1:00 to - * rawoffset 3:00/dstsavings 0:00 is included. - * @param ec Output param to filled in with a success or an error. - * @return true if the other time zone has the equivalent transitions in the - * time range. - * @stable ICU 3.8 - */ - virtual UBool hasEquivalentTransitions(const BasicTimeZone& tz, UDate start, UDate end, - UBool ignoreDstAmount, UErrorCode& ec) const; - - /** - * Returns the number of TimeZoneRules which represents time transitions, - * for this time zone, that is, all TimeZoneRules for this time zone except - * InitialTimeZoneRule. The return value range is 0 or any positive value. - * @param status Receives error status code. - * @return The number of TimeZoneRules representing time transitions. - * @stable ICU 3.8 - */ - virtual int32_t countTransitionRules(UErrorCode& status) const = 0; - - /** - * Gets the InitialTimeZoneRule and the set of TimeZoneRule - * which represent time transitions for this time zone. On successful return, - * the argument initial points to non-NULL InitialTimeZoneRule and - * the array trsrules is filled with 0 or multiple TimeZoneRule - * instances up to the size specified by trscount. The results are referencing the - * rule instance held by this time zone instance. Therefore, after this time zone - * is destructed, they are no longer available. - * @param initial Receives the initial timezone rule - * @param trsrules Receives the timezone transition rules - * @param trscount On input, specify the size of the array 'transitions' receiving - * the timezone transition rules. On output, actual number of - * rules filled in the array will be set. - * @param status Receives error status code. - * @stable ICU 3.8 - */ - virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial, - const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const = 0; - - /** - * Gets the set of time zone rules valid at the specified time. Some known external time zone - * implementations are not capable to handle historic time zone rule changes. Also some - * implementations can only handle certain type of rule definitions. - * If this time zone does not use any daylight saving time within about 1 year from the specified - * time, only the InitialTimeZone is returned. Otherwise, the rule for standard - * time and daylight saving time transitions are returned in addition to the - * InitialTimeZoneRule. The standard and daylight saving time transition rules are - * represented by AnnualTimeZoneRule with DateTimeRule::DOW for its date - * rule and DateTimeRule::WALL_TIME for its time rule. Because daylight saving time - * rule is changing time to time in many time zones and also mapping a transition time rule to - * different type is lossy transformation, the set of rules returned by this method may be valid - * for short period of time. - * The time zone rule objects returned by this method is owned by the caller, so the caller is - * responsible for deleting them after use. - * @param date The date used for extracting time zone rules. - * @param initial Receives the InitialTimeZone, always not NULL. - * @param std Receives the AnnualTimeZoneRule for standard time transitions. - * When this time time zone does not observe daylight saving times around the - * specified date, NULL is set. - * @param dst Receives the AnnualTimeZoneRule for daylight saving time - * transitions. When this time zone does not observer daylight saving times - * around the specified date, NULL is set. - * @param status Receives error status code. - * @stable ICU 3.8 - */ - virtual void getSimpleRulesNear(UDate date, InitialTimeZoneRule*& initial, - AnnualTimeZoneRule*& std, AnnualTimeZoneRule*& dst, UErrorCode& status) const; - - -#ifndef U_HIDE_INTERNAL_API - /** - * The time type option bit flags used by getOffsetFromLocal - * @internal - */ - enum { - kStandard = 0x01, - kDaylight = 0x03, - kFormer = 0x04, - kLatter = 0x0C - }; -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Get time zone offsets from local wall time. - * @internal - */ - virtual void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt, - int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const; - -protected: - -#ifndef U_HIDE_INTERNAL_API - /** - * The time type option bit masks used by getOffsetFromLocal - * @internal - */ - enum { - kStdDstMask = kDaylight, - kFormerLatterMask = kLatter - }; -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Default constructor. - * @stable ICU 3.8 - */ - BasicTimeZone(); - - /** - * Construct a timezone with a given ID. - * @param id a system time zone ID - * @stable ICU 3.8 - */ - BasicTimeZone(const UnicodeString &id); - - /** - * Copy constructor. - * @param source the object to be copied. - * @stable ICU 3.8 - */ - BasicTimeZone(const BasicTimeZone& source); - - /** - * Gets the set of TimeZoneRule instances applicable to the specified time and after. - * @param start The start date used for extracting time zone rules - * @param initial Receives the InitialTimeZone, always not NULL - * @param transitionRules Receives the transition rules, could be NULL - * @param status Receives error status code - */ - void getTimeZoneRulesAfter(UDate start, InitialTimeZoneRule*& initial, UVector*& transitionRules, - UErrorCode& status) const; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // BASICTZ_H - -//eof diff --git a/win32/include/spidermonkey/unicode/brkiter.h b/win32/include/spidermonkey/unicode/brkiter.h deleted file mode 100755 index 88b39c66..00000000 --- a/win32/include/spidermonkey/unicode/brkiter.h +++ /dev/null @@ -1,665 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 1997-2016, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************** -* -* File brkiter.h -* -* Modification History: -* -* Date Name Description -* 02/18/97 aliu Added typedef for TextCount. Made DONE const. -* 05/07/97 aliu Fixed DLL declaration. -* 07/09/97 jfitz Renamed BreakIterator and interface synced with JDK -* 08/11/98 helena Sync-up JDK1.2. -* 01/13/2000 helena Added UErrorCode parameter to createXXXInstance methods. -******************************************************************************** -*/ - -#ifndef BRKITER_H -#define BRKITER_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Break Iterator. - */ - -#if UCONFIG_NO_BREAK_ITERATION - -U_NAMESPACE_BEGIN - -/* - * Allow the declaration of APIs with pointers to BreakIterator - * even when break iteration is removed from the build. - */ -class BreakIterator; - -U_NAMESPACE_END - -#else - -#include "unicode/uobject.h" -#include "unicode/unistr.h" -#include "unicode/chariter.h" -#include "unicode/locid.h" -#include "unicode/ubrk.h" -#include "unicode/strenum.h" -#include "unicode/utext.h" -#include "unicode/umisc.h" - -U_NAMESPACE_BEGIN - -/** - * The BreakIterator class implements methods for finding the location - * of boundaries in text. BreakIterator is an abstract base class. - * Instances of BreakIterator maintain a current position and scan over - * text returning the index of characters where boundaries occur. - *

- * Line boundary analysis determines where a text string can be broken - * when line-wrapping. The mechanism correctly handles punctuation and - * hyphenated words. - *

- * Sentence boundary analysis allows selection with correct - * interpretation of periods within numbers and abbreviations, and - * trailing punctuation marks such as quotation marks and parentheses. - *

- * Word boundary analysis is used by search and replace functions, as - * well as within text editing applications that allow the user to - * select words with a double click. Word selection provides correct - * interpretation of punctuation marks within and following - * words. Characters that are not part of a word, such as symbols or - * punctuation marks, have word-breaks on both sides. - *

- * Character boundary analysis allows users to interact with - * characters as they expect to, for example, when moving the cursor - * through a text string. Character boundary analysis provides correct - * navigation of through character strings, regardless of how the - * character is stored. For example, an accented character might be - * stored as a base character and a diacritical mark. What users - * consider to be a character can differ between languages. - *

- * The text boundary positions are found according to the rules - * described in Unicode Standard Annex #29, Text Boundaries, and - * Unicode Standard Annex #14, Line Breaking Properties. These - * are available at http://www.unicode.org/reports/tr14/ and - * http://www.unicode.org/reports/tr29/. - *

- * In addition to the C++ API defined in this header file, a - * plain C API with equivalent functionality is defined in the - * file ubrk.h - *

- * Code snippets illustrating the use of the Break Iterator APIs - * are available in the ICU User Guide, - * http://icu-project.org/userguide/boundaryAnalysis.html - * and in the sample program icu/source/samples/break/break.cpp - * - */ -class U_COMMON_API BreakIterator : public UObject { -public: - /** - * destructor - * @stable ICU 2.0 - */ - virtual ~BreakIterator(); - - /** - * Return true if another object is semantically equal to this - * one. The other object should be an instance of the same subclass of - * BreakIterator. Objects of different subclasses are considered - * unequal. - *

- * Return true if this BreakIterator is at the same position in the - * same text, and is the same class and type (word, line, etc.) of - * BreakIterator, as the argument. Text is considered the same if - * it contains the same characters, it need not be the same - * object, and styles are not considered. - * @stable ICU 2.0 - */ - virtual UBool operator==(const BreakIterator&) const = 0; - - /** - * Returns the complement of the result of operator== - * @param rhs The BreakIterator to be compared for inequality - * @return the complement of the result of operator== - * @stable ICU 2.0 - */ - UBool operator!=(const BreakIterator& rhs) const { return !operator==(rhs); } - - /** - * Return a polymorphic copy of this object. This is an abstract - * method which subclasses implement. - * @stable ICU 2.0 - */ - virtual BreakIterator* clone(void) const = 0; - - /** - * Return a polymorphic class ID for this object. Different subclasses - * will return distinct unequal values. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const = 0; - - /** - * Return a CharacterIterator over the text being analyzed. - * @stable ICU 2.0 - */ - virtual CharacterIterator& getText(void) const = 0; - - - /** - * Get a UText for the text being analyzed. - * The returned UText is a shallow clone of the UText used internally - * by the break iterator implementation. It can safely be used to - * access the text without impacting any break iterator operations, - * but the underlying text itself must not be altered. - * - * @param fillIn A UText to be filled in. If NULL, a new UText will be - * allocated to hold the result. - * @param status receives any error codes. - * @return The current UText for this break iterator. If an input - * UText was provided, it will always be returned. - * @stable ICU 3.4 - */ - virtual UText *getUText(UText *fillIn, UErrorCode &status) const = 0; - - /** - * Change the text over which this operates. The text boundary is - * reset to the start. - * - * The BreakIterator will retain a reference to the supplied string. - * The caller must not modify or delete the text while the BreakIterator - * retains the reference. - * - * @param text The UnicodeString used to change the text. - * @stable ICU 2.0 - */ - virtual void setText(const UnicodeString &text) = 0; - - /** - * Reset the break iterator to operate over the text represented by - * the UText. The iterator position is reset to the start. - * - * This function makes a shallow clone of the supplied UText. This means - * that the caller is free to immediately close or otherwise reuse the - * Utext that was passed as a parameter, but that the underlying text itself - * must not be altered while being referenced by the break iterator. - * - * All index positions returned by break iterator functions are - * native indices from the UText. For example, when breaking UTF-8 - * encoded text, the break positions returned by next(), previous(), etc. - * will be UTF-8 string indices, not UTF-16 positions. - * - * @param text The UText used to change the text. - * @param status receives any error codes. - * @stable ICU 3.4 - */ - virtual void setText(UText *text, UErrorCode &status) = 0; - - /** - * Change the text over which this operates. The text boundary is - * reset to the start. - * Note that setText(UText *) provides similar functionality to this function, - * and is more efficient. - * @param it The CharacterIterator used to change the text. - * @stable ICU 2.0 - */ - virtual void adoptText(CharacterIterator* it) = 0; - - enum { - /** - * DONE is returned by previous() and next() after all valid - * boundaries have been returned. - * @stable ICU 2.0 - */ - DONE = (int32_t)-1 - }; - - /** - * Sets the current iteration position to the beginning of the text, position zero. - * @return The offset of the beginning of the text, zero. - * @stable ICU 2.0 - */ - virtual int32_t first(void) = 0; - - /** - * Set the iterator position to the index immediately BEYOND the last character in the text being scanned. - * @return The index immediately BEYOND the last character in the text being scanned. - * @stable ICU 2.0 - */ - virtual int32_t last(void) = 0; - - /** - * Set the iterator position to the boundary preceding the current boundary. - * @return The character index of the previous text boundary or DONE if all - * boundaries have been returned. - * @stable ICU 2.0 - */ - virtual int32_t previous(void) = 0; - - /** - * Advance the iterator to the boundary following the current boundary. - * @return The character index of the next text boundary or DONE if all - * boundaries have been returned. - * @stable ICU 2.0 - */ - virtual int32_t next(void) = 0; - - /** - * Return character index of the current interator position within the text. - * @return The boundary most recently returned. - * @stable ICU 2.0 - */ - virtual int32_t current(void) const = 0; - - /** - * Advance the iterator to the first boundary following the specified offset. - * The value returned is always greater than the offset or - * the value BreakIterator.DONE - * @param offset the offset to begin scanning. - * @return The first boundary after the specified offset. - * @stable ICU 2.0 - */ - virtual int32_t following(int32_t offset) = 0; - - /** - * Set the iterator position to the first boundary preceding the specified offset. - * The value returned is always smaller than the offset or - * the value BreakIterator.DONE - * @param offset the offset to begin scanning. - * @return The first boundary before the specified offset. - * @stable ICU 2.0 - */ - virtual int32_t preceding(int32_t offset) = 0; - - /** - * Return true if the specfied position is a boundary position. - * As a side effect, the current position of the iterator is set - * to the first boundary position at or following the specified offset. - * @param offset the offset to check. - * @return True if "offset" is a boundary position. - * @stable ICU 2.0 - */ - virtual UBool isBoundary(int32_t offset) = 0; - - /** - * Set the iterator position to the nth boundary from the current boundary - * @param n the number of boundaries to move by. A value of 0 - * does nothing. Negative values move to previous boundaries - * and positive values move to later boundaries. - * @return The new iterator position, or - * DONE if there are fewer than |n| boundaries in the specfied direction. - * @stable ICU 2.0 - */ - virtual int32_t next(int32_t n) = 0; - - /** - * For RuleBasedBreakIterators, return the status tag from the - * break rule that determined the most recently - * returned break position. - *

- * For break iterator types that do not support a rule status, - * a default value of 0 is returned. - *

- * @return the status from the break rule that determined the most recently - * returned break position. - * @see RuleBaseBreakIterator::getRuleStatus() - * @see UWordBreak - * @stable ICU 52 - */ - virtual int32_t getRuleStatus() const; - - /** - * For RuleBasedBreakIterators, get the status (tag) values from the break rule(s) - * that determined the most recently returned break position. - *

- * For break iterator types that do not support rule status, - * no values are returned. - *

- * The returned status value(s) are stored into an array provided by the caller. - * The values are stored in sorted (ascending) order. - * If the capacity of the output array is insufficient to hold the data, - * the output will be truncated to the available length, and a - * U_BUFFER_OVERFLOW_ERROR will be signaled. - *

- * @see RuleBaseBreakIterator::getRuleStatusVec - * - * @param fillInVec an array to be filled in with the status values. - * @param capacity the length of the supplied vector. A length of zero causes - * the function to return the number of status values, in the - * normal way, without attemtping to store any values. - * @param status receives error codes. - * @return The number of rule status values from rules that determined - * the most recent boundary returned by the break iterator. - * In the event of a U_BUFFER_OVERFLOW_ERROR, the return value - * is the total number of status values that were available, - * not the reduced number that were actually returned. - * @see getRuleStatus - * @stable ICU 52 - */ - virtual int32_t getRuleStatusVec(int32_t *fillInVec, int32_t capacity, UErrorCode &status); - - /** - * Create BreakIterator for word-breaks using the given locale. - * Returns an instance of a BreakIterator implementing word breaks. - * WordBreak is useful for word selection (ex. double click) - * @param where the locale. - * @param status the error code - * @return A BreakIterator for word-breaks. The UErrorCode& status - * parameter is used to return status information to the user. - * To check whether the construction succeeded or not, you should check - * the value of U_SUCCESS(err). If you wish more detailed information, you - * can check for informational error results which still indicate success. - * U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For - * example, 'de_CH' was requested, but nothing was found there, so 'de' was - * used. U_USING_DEFAULT_WARNING indicates that the default locale data was - * used; neither the requested locale nor any of its fall back locales - * could be found. - * The caller owns the returned object and is responsible for deleting it. - * @stable ICU 2.0 - */ - static BreakIterator* U_EXPORT2 - createWordInstance(const Locale& where, UErrorCode& status); - - /** - * Create BreakIterator for line-breaks using specified locale. - * Returns an instance of a BreakIterator implementing line breaks. Line - * breaks are logically possible line breaks, actual line breaks are - * usually determined based on display width. - * LineBreak is useful for word wrapping text. - * @param where the locale. - * @param status The error code. - * @return A BreakIterator for line-breaks. The UErrorCode& status - * parameter is used to return status information to the user. - * To check whether the construction succeeded or not, you should check - * the value of U_SUCCESS(err). If you wish more detailed information, you - * can check for informational error results which still indicate success. - * U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For - * example, 'de_CH' was requested, but nothing was found there, so 'de' was - * used. U_USING_DEFAULT_WARNING indicates that the default locale data was - * used; neither the requested locale nor any of its fall back locales - * could be found. - * The caller owns the returned object and is responsible for deleting it. - * @stable ICU 2.0 - */ - static BreakIterator* U_EXPORT2 - createLineInstance(const Locale& where, UErrorCode& status); - - /** - * Create BreakIterator for character-breaks using specified locale - * Returns an instance of a BreakIterator implementing character breaks. - * Character breaks are boundaries of combining character sequences. - * @param where the locale. - * @param status The error code. - * @return A BreakIterator for character-breaks. The UErrorCode& status - * parameter is used to return status information to the user. - * To check whether the construction succeeded or not, you should check - * the value of U_SUCCESS(err). If you wish more detailed information, you - * can check for informational error results which still indicate success. - * U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For - * example, 'de_CH' was requested, but nothing was found there, so 'de' was - * used. U_USING_DEFAULT_WARNING indicates that the default locale data was - * used; neither the requested locale nor any of its fall back locales - * could be found. - * The caller owns the returned object and is responsible for deleting it. - * @stable ICU 2.0 - */ - static BreakIterator* U_EXPORT2 - createCharacterInstance(const Locale& where, UErrorCode& status); - - /** - * Create BreakIterator for sentence-breaks using specified locale - * Returns an instance of a BreakIterator implementing sentence breaks. - * @param where the locale. - * @param status The error code. - * @return A BreakIterator for sentence-breaks. The UErrorCode& status - * parameter is used to return status information to the user. - * To check whether the construction succeeded or not, you should check - * the value of U_SUCCESS(err). If you wish more detailed information, you - * can check for informational error results which still indicate success. - * U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For - * example, 'de_CH' was requested, but nothing was found there, so 'de' was - * used. U_USING_DEFAULT_WARNING indicates that the default locale data was - * used; neither the requested locale nor any of its fall back locales - * could be found. - * The caller owns the returned object and is responsible for deleting it. - * @stable ICU 2.0 - */ - static BreakIterator* U_EXPORT2 - createSentenceInstance(const Locale& where, UErrorCode& status); - - /** - * Create BreakIterator for title-casing breaks using the specified locale - * Returns an instance of a BreakIterator implementing title breaks. - * The iterator returned locates title boundaries as described for - * Unicode 3.2 only. For Unicode 4.0 and above title boundary iteration, - * please use Word Boundary iterator.{@link #createWordInstance } - * - * @param where the locale. - * @param status The error code. - * @return A BreakIterator for title-breaks. The UErrorCode& status - * parameter is used to return status information to the user. - * To check whether the construction succeeded or not, you should check - * the value of U_SUCCESS(err). If you wish more detailed information, you - * can check for informational error results which still indicate success. - * U_USING_FALLBACK_WARNING indicates that a fall back locale was used. For - * example, 'de_CH' was requested, but nothing was found there, so 'de' was - * used. U_USING_DEFAULT_WARNING indicates that the default locale data was - * used; neither the requested locale nor any of its fall back locales - * could be found. - * The caller owns the returned object and is responsible for deleting it. - * @stable ICU 2.1 - */ - static BreakIterator* U_EXPORT2 - createTitleInstance(const Locale& where, UErrorCode& status); - - /** - * Get the set of Locales for which TextBoundaries are installed. - *

Note: this will not return locales added through the register - * call. To see the registered locales too, use the getAvailableLocales - * function that returns a StringEnumeration object

- * @param count the output parameter of number of elements in the locale list - * @return available locales - * @stable ICU 2.0 - */ - static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); - - /** - * Get name of the object for the desired Locale, in the desired langauge. - * @param objectLocale must be from getAvailableLocales. - * @param displayLocale specifies the desired locale for output. - * @param name the fill-in parameter of the return value - * Uses best match. - * @return user-displayable name - * @stable ICU 2.0 - */ - static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale, - const Locale& displayLocale, - UnicodeString& name); - - /** - * Get name of the object for the desired Locale, in the langauge of the - * default locale. - * @param objectLocale must be from getMatchingLocales - * @param name the fill-in parameter of the return value - * @return user-displayable name - * @stable ICU 2.0 - */ - static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale, - UnicodeString& name); - - /** - * Deprecated functionality. Use clone() instead. - * - * Thread safe client-buffer-based cloning operation - * Do NOT call delete on a safeclone, since 'new' is not used to create it. - * @param stackBuffer user allocated space for the new clone. If NULL new memory will be allocated. - * If buffer is not large enough, new memory will be allocated. - * @param BufferSize reference to size of allocated space. - * If BufferSize == 0, a sufficient size for use in cloning will - * be returned ('pre-flighting') - * If BufferSize is not enough for a stack-based safe clone, - * new memory will be allocated. - * @param status to indicate whether the operation went on smoothly or there were errors - * An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used if any allocations were - * necessary. - * @return pointer to the new clone - * - * @deprecated ICU 52. Use clone() instead. - */ - virtual BreakIterator * createBufferClone(void *stackBuffer, - int32_t &BufferSize, - UErrorCode &status) = 0; - -#ifndef U_HIDE_DEPRECATED_API - - /** - * Determine whether the BreakIterator was created in user memory by - * createBufferClone(), and thus should not be deleted. Such objects - * must be closed by an explicit call to the destructor (not delete). - * @deprecated ICU 52. Always delete the BreakIterator. - */ - inline UBool isBufferClone(void); - -#endif /* U_HIDE_DEPRECATED_API */ - -#if !UCONFIG_NO_SERVICE - /** - * Register a new break iterator of the indicated kind, to use in the given locale. - * The break iterator will be adopted. Clones of the iterator will be returned - * if a request for a break iterator of the given kind matches or falls back to - * this locale. - * Because ICU may choose to cache BreakIterators internally, this must - * be called at application startup, prior to any calls to - * BreakIterator::createXXXInstance to avoid undefined behavior. - * @param toAdopt the BreakIterator instance to be adopted - * @param locale the Locale for which this instance is to be registered - * @param kind the type of iterator for which this instance is to be registered - * @param status the in/out status code, no special meanings are assigned - * @return a registry key that can be used to unregister this instance - * @stable ICU 2.4 - */ - static URegistryKey U_EXPORT2 registerInstance(BreakIterator* toAdopt, - const Locale& locale, - UBreakIteratorType kind, - UErrorCode& status); - - /** - * Unregister a previously-registered BreakIterator using the key returned from the - * register call. Key becomes invalid after a successful call and should not be used again. - * The BreakIterator corresponding to the key will be deleted. - * Because ICU may choose to cache BreakIterators internally, this should - * be called during application shutdown, after all calls to - * BreakIterator::createXXXInstance to avoid undefined behavior. - * @param key the registry key returned by a previous call to registerInstance - * @param status the in/out status code, no special meanings are assigned - * @return TRUE if the iterator for the key was successfully unregistered - * @stable ICU 2.4 - */ - static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status); - - /** - * Return a StringEnumeration over the locales available at the time of the call, - * including registered locales. - * @return a StringEnumeration over the locales available at the time of the call - * @stable ICU 2.4 - */ - static StringEnumeration* U_EXPORT2 getAvailableLocales(void); -#endif - - /** - * Returns the locale for this break iterator. Two flavors are available: valid and - * actual locale. - * @stable ICU 2.8 - */ - Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const; - -#ifndef U_HIDE_INTERNAL_API - /** Get the locale for this break iterator object. You can choose between valid and actual locale. - * @param type type of the locale we're looking for (valid or actual) - * @param status error code for the operation - * @return the locale - * @internal - */ - const char *getLocaleID(ULocDataLocaleType type, UErrorCode& status) const; -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Set the subject text string upon which the break iterator is operating - * without changing any other aspect of the matching state. - * The new and previous text strings must have the same content. - * - * This function is intended for use in environments where ICU is operating on - * strings that may move around in memory. It provides a mechanism for notifying - * ICU that the string has been relocated, and providing a new UText to access the - * string in its new position. - * - * Note that the break iterator implementation never copies the underlying text - * of a string being processed, but always operates directly on the original text - * provided by the user. Refreshing simply drops the references to the old text - * and replaces them with references to the new. - * - * Caution: this function is normally used only by very specialized, - * system-level code. One example use case is with garbage collection that moves - * the text in memory. - * - * @param input The new (moved) text string. - * @param status Receives errors detected by this function. - * @return *this - * - * @stable ICU 49 - */ - virtual BreakIterator &refreshInputText(UText *input, UErrorCode &status) = 0; - - private: - static BreakIterator* buildInstance(const Locale& loc, const char *type, int32_t kind, UErrorCode& status); - static BreakIterator* createInstance(const Locale& loc, int32_t kind, UErrorCode& status); - static BreakIterator* makeInstance(const Locale& loc, int32_t kind, UErrorCode& status); - - friend class ICUBreakIteratorFactory; - friend class ICUBreakIteratorService; - -protected: - // Do not enclose protected default/copy constructors with #ifndef U_HIDE_INTERNAL_API - // or else the compiler will create a public ones. - /** @internal */ - BreakIterator(); - /** @internal */ - BreakIterator (const BreakIterator &other) : UObject(other) {} -#ifndef U_HIDE_INTERNAL_API - /** @internal */ - BreakIterator (const Locale& valid, const Locale& actual); -#endif /* U_HIDE_INTERNAL_API */ - -private: - - /** @internal */ - char actualLocale[ULOC_FULLNAME_CAPACITY]; - char validLocale[ULOC_FULLNAME_CAPACITY]; - - /** - * The assignment operator has no real implementation. - * It's provided to make the compiler happy. Do not call. - */ - BreakIterator& operator=(const BreakIterator&); -}; - -#ifndef U_HIDE_DEPRECATED_API - -inline UBool BreakIterator::isBufferClone() -{ - return FALSE; -} - -#endif /* U_HIDE_DEPRECATED_API */ - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_BREAK_ITERATION */ - -#endif // _BRKITER -//eof diff --git a/win32/include/spidermonkey/unicode/bytestream.h b/win32/include/spidermonkey/unicode/bytestream.h deleted file mode 100755 index 15562271..00000000 --- a/win32/include/spidermonkey/unicode/bytestream.h +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -// Copyright (C) 2009-2012, International Business Machines -// Corporation and others. All Rights Reserved. -// -// Copyright 2007 Google Inc. All Rights Reserved. -// Author: sanjay@google.com (Sanjay Ghemawat) -// -// Abstract interface that consumes a sequence of bytes (ByteSink). -// -// Used so that we can write a single piece of code that can operate -// on a variety of output string types. -// -// Various implementations of this interface are provided: -// ByteSink: -// CheckedArrayByteSink Write to a flat array, with bounds checking -// StringByteSink Write to an STL string - -// This code is a contribution of Google code, and the style used here is -// a compromise between the original Google code and the ICU coding guidelines. -// For example, data types are ICU-ified (size_t,int->int32_t), -// and API comments doxygen-ified, but function names and behavior are -// as in the original, if possible. -// Assertion-style error handling, not available in ICU, was changed to -// parameter "pinning" similar to UnicodeString. -// -// In addition, this is only a partial port of the original Google code, -// limited to what was needed so far. The (nearly) complete original code -// is in the ICU svn repository at icuhtml/trunk/design/strings/contrib -// (see ICU ticket 6765, r25517). - -#ifndef __BYTESTREAM_H__ -#define __BYTESTREAM_H__ - -/** - * \file - * \brief C++ API: Interface for writing bytes, and implementation classes. - */ - -#include "unicode/utypes.h" -#include "unicode/uobject.h" -#include "unicode/std_string.h" - -U_NAMESPACE_BEGIN - -/** - * A ByteSink can be filled with bytes. - * @stable ICU 4.2 - */ -class U_COMMON_API ByteSink : public UMemory { -public: - /** - * Default constructor. - * @stable ICU 4.2 - */ - ByteSink() { } - /** - * Virtual destructor. - * @stable ICU 4.2 - */ - virtual ~ByteSink(); - - /** - * Append "bytes[0,n-1]" to this. - * @param bytes the pointer to the bytes - * @param n the number of bytes; must be non-negative - * @stable ICU 4.2 - */ - virtual void Append(const char* bytes, int32_t n) = 0; - - /** - * Returns a writable buffer for appending and writes the buffer's capacity to - * *result_capacity. Guarantees *result_capacity>=min_capacity. - * May return a pointer to the caller-owned scratch buffer which must have - * scratch_capacity>=min_capacity. - * The returned buffer is only valid until the next operation - * on this ByteSink. - * - * After writing at most *result_capacity bytes, call Append() with the - * pointer returned from this function and the number of bytes written. - * Many Append() implementations will avoid copying bytes if this function - * returned an internal buffer. - * - * Partial usage example: - * int32_t capacity; - * char* buffer = sink->GetAppendBuffer(..., &capacity); - * ... Write n bytes into buffer, with n <= capacity. - * sink->Append(buffer, n); - * In many implementations, that call to Append will avoid copying bytes. - * - * If the ByteSink allocates or reallocates an internal buffer, it should use - * the desired_capacity_hint if appropriate. - * If a caller cannot provide a reasonable guess at the desired capacity, - * it should pass desired_capacity_hint=0. - * - * If a non-scratch buffer is returned, the caller may only pass - * a prefix to it to Append(). - * That is, it is not correct to pass an interior pointer to Append(). - * - * The default implementation always returns the scratch buffer. - * - * @param min_capacity required minimum capacity of the returned buffer; - * must be non-negative - * @param desired_capacity_hint desired capacity of the returned buffer; - * must be non-negative - * @param scratch default caller-owned buffer - * @param scratch_capacity capacity of the scratch buffer - * @param result_capacity pointer to an integer which will be set to the - * capacity of the returned buffer - * @return a buffer with *result_capacity>=min_capacity - * @stable ICU 4.2 - */ - virtual char* GetAppendBuffer(int32_t min_capacity, - int32_t desired_capacity_hint, - char* scratch, int32_t scratch_capacity, - int32_t* result_capacity); - - /** - * Flush internal buffers. - * Some byte sinks use internal buffers or provide buffering - * and require calling Flush() at the end of the stream. - * The ByteSink should be ready for further Append() calls after Flush(). - * The default implementation of Flush() does nothing. - * @stable ICU 4.2 - */ - virtual void Flush(); - -private: - ByteSink(const ByteSink &); // copy constructor not implemented - ByteSink &operator=(const ByteSink &); // assignment operator not implemented -}; - -// ------------------------------------------------------------- -// Some standard implementations - -/** - * Implementation of ByteSink that writes to a flat byte array, - * with bounds-checking: - * This sink will not write more than capacity bytes to outbuf. - * If more than capacity bytes are Append()ed, then excess bytes are ignored, - * and Overflowed() will return true. - * Overflow does not cause a runtime error. - * @stable ICU 4.2 - */ -class U_COMMON_API CheckedArrayByteSink : public ByteSink { -public: - /** - * Constructs a ByteSink that will write to outbuf[0..capacity-1]. - * @param outbuf buffer to write to - * @param capacity size of the buffer - * @stable ICU 4.2 - */ - CheckedArrayByteSink(char* outbuf, int32_t capacity); - /** - * Destructor. - * @stable ICU 4.2 - */ - virtual ~CheckedArrayByteSink(); - /** - * Returns the sink to its original state, without modifying the buffer. - * Useful for reusing both the buffer and the sink for multiple streams. - * Resets the state to NumberOfBytesWritten()=NumberOfBytesAppended()=0 - * and Overflowed()=FALSE. - * @return *this - * @stable ICU 4.6 - */ - virtual CheckedArrayByteSink& Reset(); - /** - * Append "bytes[0,n-1]" to this. - * @param bytes the pointer to the bytes - * @param n the number of bytes; must be non-negative - * @stable ICU 4.2 - */ - virtual void Append(const char* bytes, int32_t n); - /** - * Returns a writable buffer for appending and writes the buffer's capacity to - * *result_capacity. For details see the base class documentation. - * @param min_capacity required minimum capacity of the returned buffer; - * must be non-negative - * @param desired_capacity_hint desired capacity of the returned buffer; - * must be non-negative - * @param scratch default caller-owned buffer - * @param scratch_capacity capacity of the scratch buffer - * @param result_capacity pointer to an integer which will be set to the - * capacity of the returned buffer - * @return a buffer with *result_capacity>=min_capacity - * @stable ICU 4.2 - */ - virtual char* GetAppendBuffer(int32_t min_capacity, - int32_t desired_capacity_hint, - char* scratch, int32_t scratch_capacity, - int32_t* result_capacity); - /** - * Returns the number of bytes actually written to the sink. - * @return number of bytes written to the buffer - * @stable ICU 4.2 - */ - int32_t NumberOfBytesWritten() const { return size_; } - /** - * Returns true if any bytes were discarded, i.e., if there was an - * attempt to write more than 'capacity' bytes. - * @return TRUE if more than 'capacity' bytes were Append()ed - * @stable ICU 4.2 - */ - UBool Overflowed() const { return overflowed_; } - /** - * Returns the number of bytes appended to the sink. - * If Overflowed() then NumberOfBytesAppended()>NumberOfBytesWritten() - * else they return the same number. - * @return number of bytes written to the buffer - * @stable ICU 4.6 - */ - int32_t NumberOfBytesAppended() const { return appended_; } -private: - char* outbuf_; - const int32_t capacity_; - int32_t size_; - int32_t appended_; - UBool overflowed_; - CheckedArrayByteSink(); ///< default constructor not implemented - CheckedArrayByteSink(const CheckedArrayByteSink &); ///< copy constructor not implemented - CheckedArrayByteSink &operator=(const CheckedArrayByteSink &); ///< assignment operator not implemented -}; - -#if U_HAVE_STD_STRING - -/** - * Implementation of ByteSink that writes to a "string". - * The StringClass is usually instantiated with a std::string. - * @stable ICU 4.2 - */ -template -class StringByteSink : public ByteSink { - public: - /** - * Constructs a ByteSink that will append bytes to the dest string. - * @param dest pointer to string object to append to - * @stable ICU 4.2 - */ - StringByteSink(StringClass* dest) : dest_(dest) { } - /** - * Append "bytes[0,n-1]" to this. - * @param data the pointer to the bytes - * @param n the number of bytes; must be non-negative - * @stable ICU 4.2 - */ - virtual void Append(const char* data, int32_t n) { dest_->append(data, n); } - private: - StringClass* dest_; - StringByteSink(); ///< default constructor not implemented - StringByteSink(const StringByteSink &); ///< copy constructor not implemented - StringByteSink &operator=(const StringByteSink &); ///< assignment operator not implemented -}; - -#endif - -U_NAMESPACE_END - -#endif // __BYTESTREAM_H__ diff --git a/win32/include/spidermonkey/unicode/bytestrie.h b/win32/include/spidermonkey/unicode/bytestrie.h deleted file mode 100755 index 4a30ce1c..00000000 --- a/win32/include/spidermonkey/unicode/bytestrie.h +++ /dev/null @@ -1,520 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2010-2012, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* file name: bytestrie.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2010sep25 -* created by: Markus W. Scherer -*/ - -#ifndef __BYTESTRIE_H__ -#define __BYTESTRIE_H__ - -/** - * \file - * \brief C++ API: Trie for mapping byte sequences to integer values. - */ - -#include "unicode/utypes.h" -#include "unicode/stringpiece.h" -#include "unicode/uobject.h" -#include "unicode/ustringtrie.h" - -U_NAMESPACE_BEGIN - -class ByteSink; -class BytesTrieBuilder; -class CharString; -class UVector32; - -/** - * Light-weight, non-const reader class for a BytesTrie. - * Traverses a byte-serialized data structure with minimal state, - * for mapping byte sequences to non-negative integer values. - * - * This class owns the serialized trie data only if it was constructed by - * the builder's build() method. - * The public constructor and the copy constructor only alias the data (only copy the pointer). - * There is no assignment operator. - * - * This class is not intended for public subclassing. - * @stable ICU 4.8 - */ -class U_COMMON_API BytesTrie : public UMemory { -public: - /** - * Constructs a BytesTrie reader instance. - * - * The trieBytes must contain a copy of a byte sequence from the BytesTrieBuilder, - * starting with the first byte of that sequence. - * The BytesTrie object will not read more bytes than - * the BytesTrieBuilder generated in the corresponding build() call. - * - * The array is not copied/cloned and must not be modified while - * the BytesTrie object is in use. - * - * @param trieBytes The byte array that contains the serialized trie. - * @stable ICU 4.8 - */ - BytesTrie(const void *trieBytes) - : ownedArray_(NULL), bytes_(static_cast(trieBytes)), - pos_(bytes_), remainingMatchLength_(-1) {} - - /** - * Destructor. - * @stable ICU 4.8 - */ - ~BytesTrie(); - - /** - * Copy constructor, copies the other trie reader object and its state, - * but not the byte array which will be shared. (Shallow copy.) - * @param other Another BytesTrie object. - * @stable ICU 4.8 - */ - BytesTrie(const BytesTrie &other) - : ownedArray_(NULL), bytes_(other.bytes_), - pos_(other.pos_), remainingMatchLength_(other.remainingMatchLength_) {} - - /** - * Resets this trie to its initial state. - * @return *this - * @stable ICU 4.8 - */ - BytesTrie &reset() { - pos_=bytes_; - remainingMatchLength_=-1; - return *this; - } - - /** - * BytesTrie state object, for saving a trie's current state - * and resetting the trie back to this state later. - * @stable ICU 4.8 - */ - class State : public UMemory { - public: - /** - * Constructs an empty State. - * @stable ICU 4.8 - */ - State() { bytes=NULL; } - private: - friend class BytesTrie; - - const uint8_t *bytes; - const uint8_t *pos; - int32_t remainingMatchLength; - }; - - /** - * Saves the state of this trie. - * @param state The State object to hold the trie's state. - * @return *this - * @see resetToState - * @stable ICU 4.8 - */ - const BytesTrie &saveState(State &state) const { - state.bytes=bytes_; - state.pos=pos_; - state.remainingMatchLength=remainingMatchLength_; - return *this; - } - - /** - * Resets this trie to the saved state. - * If the state object contains no state, or the state of a different trie, - * then this trie remains unchanged. - * @param state The State object which holds a saved trie state. - * @return *this - * @see saveState - * @see reset - * @stable ICU 4.8 - */ - BytesTrie &resetToState(const State &state) { - if(bytes_==state.bytes && bytes_!=NULL) { - pos_=state.pos; - remainingMatchLength_=state.remainingMatchLength; - } - return *this; - } - - /** - * Determines whether the byte sequence so far matches, whether it has a value, - * and whether another input byte can continue a matching byte sequence. - * @return The match/value Result. - * @stable ICU 4.8 - */ - UStringTrieResult current() const; - - /** - * Traverses the trie from the initial state for this input byte. - * Equivalent to reset().next(inByte). - * @param inByte Input byte value. Values -0x100..-1 are treated like 0..0xff. - * Values below -0x100 and above 0xff will never match. - * @return The match/value Result. - * @stable ICU 4.8 - */ - inline UStringTrieResult first(int32_t inByte) { - remainingMatchLength_=-1; - if(inByte<0) { - inByte+=0x100; - } - return nextImpl(bytes_, inByte); - } - - /** - * Traverses the trie from the current state for this input byte. - * @param inByte Input byte value. Values -0x100..-1 are treated like 0..0xff. - * Values below -0x100 and above 0xff will never match. - * @return The match/value Result. - * @stable ICU 4.8 - */ - UStringTrieResult next(int32_t inByte); - - /** - * Traverses the trie from the current state for this byte sequence. - * Equivalent to - * \code - * Result result=current(); - * for(each c in s) - * if(!USTRINGTRIE_HAS_NEXT(result)) return USTRINGTRIE_NO_MATCH; - * result=next(c); - * return result; - * \endcode - * @param s A string or byte sequence. Can be NULL if length is 0. - * @param length The length of the byte sequence. Can be -1 if NUL-terminated. - * @return The match/value Result. - * @stable ICU 4.8 - */ - UStringTrieResult next(const char *s, int32_t length); - - /** - * Returns a matching byte sequence's value if called immediately after - * current()/first()/next() returned USTRINGTRIE_INTERMEDIATE_VALUE or USTRINGTRIE_FINAL_VALUE. - * getValue() can be called multiple times. - * - * Do not call getValue() after USTRINGTRIE_NO_MATCH or USTRINGTRIE_NO_VALUE! - * @return The value for the byte sequence so far. - * @stable ICU 4.8 - */ - inline int32_t getValue() const { - const uint8_t *pos=pos_; - int32_t leadByte=*pos++; - // U_ASSERT(leadByte>=kMinValueLead); - return readValue(pos, leadByte>>1); - } - - /** - * Determines whether all byte sequences reachable from the current state - * map to the same value. - * @param uniqueValue Receives the unique value, if this function returns TRUE. - * (output-only) - * @return TRUE if all byte sequences reachable from the current state - * map to the same value. - * @stable ICU 4.8 - */ - inline UBool hasUniqueValue(int32_t &uniqueValue) const { - const uint8_t *pos=pos_; - // Skip the rest of a pending linear-match node. - return pos!=NULL && findUniqueValue(pos+remainingMatchLength_+1, FALSE, uniqueValue); - } - - /** - * Finds each byte which continues the byte sequence from the current state. - * That is, each byte b for which it would be next(b)!=USTRINGTRIE_NO_MATCH now. - * @param out Each next byte is appended to this object. - * (Only uses the out.Append(s, length) method.) - * @return the number of bytes which continue the byte sequence from here - * @stable ICU 4.8 - */ - int32_t getNextBytes(ByteSink &out) const; - - /** - * Iterator for all of the (byte sequence, value) pairs in a BytesTrie. - * @stable ICU 4.8 - */ - class U_COMMON_API Iterator : public UMemory { - public: - /** - * Iterates from the root of a byte-serialized BytesTrie. - * @param trieBytes The trie bytes. - * @param maxStringLength If 0, the iterator returns full strings/byte sequences. - * Otherwise, the iterator returns strings with this maximum length. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @stable ICU 4.8 - */ - Iterator(const void *trieBytes, int32_t maxStringLength, UErrorCode &errorCode); - - /** - * Iterates from the current state of the specified BytesTrie. - * @param trie The trie whose state will be copied for iteration. - * @param maxStringLength If 0, the iterator returns full strings/byte sequences. - * Otherwise, the iterator returns strings with this maximum length. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @stable ICU 4.8 - */ - Iterator(const BytesTrie &trie, int32_t maxStringLength, UErrorCode &errorCode); - - /** - * Destructor. - * @stable ICU 4.8 - */ - ~Iterator(); - - /** - * Resets this iterator to its initial state. - * @return *this - * @stable ICU 4.8 - */ - Iterator &reset(); - - /** - * @return TRUE if there are more elements. - * @stable ICU 4.8 - */ - UBool hasNext() const; - - /** - * Finds the next (byte sequence, value) pair if there is one. - * - * If the byte sequence is truncated to the maximum length and does not - * have a real value, then the value is set to -1. - * In this case, this "not a real value" is indistinguishable from - * a real value of -1. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return TRUE if there is another element. - * @stable ICU 4.8 - */ - UBool next(UErrorCode &errorCode); - - /** - * @return The NUL-terminated byte sequence for the last successful next(). - * @stable ICU 4.8 - */ - StringPiece getString() const; - /** - * @return The value for the last successful next(). - * @stable ICU 4.8 - */ - int32_t getValue() const { return value_; } - - private: - UBool truncateAndStop(); - - const uint8_t *branchNext(const uint8_t *pos, int32_t length, UErrorCode &errorCode); - - const uint8_t *bytes_; - const uint8_t *pos_; - const uint8_t *initialPos_; - int32_t remainingMatchLength_; - int32_t initialRemainingMatchLength_; - - CharString *str_; - int32_t maxLength_; - int32_t value_; - - // The stack stores pairs of integers for backtracking to another - // outbound edge of a branch node. - // The first integer is an offset from bytes_. - // The second integer has the str_->length() from before the node in bits 15..0, - // and the remaining branch length in bits 24..16. (Bits 31..25 are unused.) - // (We could store the remaining branch length minus 1 in bits 23..16 and not use bits 31..24, - // but the code looks more confusing that way.) - UVector32 *stack_; - }; - -private: - friend class BytesTrieBuilder; - - /** - * Constructs a BytesTrie reader instance. - * Unlike the public constructor which just aliases an array, - * this constructor adopts the builder's array. - * This constructor is only called by the builder. - */ - BytesTrie(void *adoptBytes, const void *trieBytes) - : ownedArray_(static_cast(adoptBytes)), - bytes_(static_cast(trieBytes)), - pos_(bytes_), remainingMatchLength_(-1) {} - - // No assignment operator. - BytesTrie &operator=(const BytesTrie &other); - - inline void stop() { - pos_=NULL; - } - - // Reads a compact 32-bit integer. - // pos is already after the leadByte, and the lead byte is already shifted right by 1. - static int32_t readValue(const uint8_t *pos, int32_t leadByte); - static inline const uint8_t *skipValue(const uint8_t *pos, int32_t leadByte) { - // U_ASSERT(leadByte>=kMinValueLead); - if(leadByte>=(kMinTwoByteValueLead<<1)) { - if(leadByte<(kMinThreeByteValueLead<<1)) { - ++pos; - } else if(leadByte<(kFourByteValueLead<<1)) { - pos+=2; - } else { - pos+=3+((leadByte>>1)&1); - } - } - return pos; - } - static inline const uint8_t *skipValue(const uint8_t *pos) { - int32_t leadByte=*pos++; - return skipValue(pos, leadByte); - } - - // Reads a jump delta and jumps. - static const uint8_t *jumpByDelta(const uint8_t *pos); - - static inline const uint8_t *skipDelta(const uint8_t *pos) { - int32_t delta=*pos++; - if(delta>=kMinTwoByteDeltaLead) { - if(delta>8)+1; // 0x6c - static const int32_t kFourByteValueLead=0x7e; - - // A little more than Unicode code points. (0x11ffff) - static const int32_t kMaxThreeByteValue=((kFourByteValueLead-kMinThreeByteValueLead)<<16)-1; - - static const int32_t kFiveByteValueLead=0x7f; - - // Compact delta integers. - static const int32_t kMaxOneByteDelta=0xbf; - static const int32_t kMinTwoByteDeltaLead=kMaxOneByteDelta+1; // 0xc0 - static const int32_t kMinThreeByteDeltaLead=0xf0; - static const int32_t kFourByteDeltaLead=0xfe; - static const int32_t kFiveByteDeltaLead=0xff; - - static const int32_t kMaxTwoByteDelta=((kMinThreeByteDeltaLead-kMinTwoByteDeltaLead)<<8)-1; // 0x2fff - static const int32_t kMaxThreeByteDelta=((kFourByteDeltaLead-kMinThreeByteDeltaLead)<<16)-1; // 0xdffff - - uint8_t *ownedArray_; - - // Fixed value referencing the BytesTrie bytes. - const uint8_t *bytes_; - - // Iterator variables. - - // Pointer to next trie byte to read. NULL if no more matches. - const uint8_t *pos_; - // Remaining length of a linear-match node, minus 1. Negative if not in such a node. - int32_t remainingMatchLength_; -}; - -U_NAMESPACE_END - -#endif // __BYTESTRIE_H__ diff --git a/win32/include/spidermonkey/unicode/bytestriebuilder.h b/win32/include/spidermonkey/unicode/bytestriebuilder.h deleted file mode 100755 index fe96887d..00000000 --- a/win32/include/spidermonkey/unicode/bytestriebuilder.h +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2010-2016, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* file name: bytestriebuilder.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2010sep25 -* created by: Markus W. Scherer -*/ - -/** - * \file - * \brief C++ API: Builder for icu::BytesTrie - */ - -#ifndef __BYTESTRIEBUILDER_H__ -#define __BYTESTRIEBUILDER_H__ - -#include "unicode/utypes.h" -#include "unicode/bytestrie.h" -#include "unicode/stringpiece.h" -#include "unicode/stringtriebuilder.h" - -U_NAMESPACE_BEGIN - -class BytesTrieElement; -class CharString; -/** - * Builder class for BytesTrie. - * - * This class is not intended for public subclassing. - * @stable ICU 4.8 - */ -class U_COMMON_API BytesTrieBuilder : public StringTrieBuilder { -public: - /** - * Constructs an empty builder. - * @param errorCode Standard ICU error code. - * @stable ICU 4.8 - */ - BytesTrieBuilder(UErrorCode &errorCode); - - /** - * Destructor. - * @stable ICU 4.8 - */ - virtual ~BytesTrieBuilder(); - - /** - * Adds a (byte sequence, value) pair. - * The byte sequence must be unique. - * The bytes will be copied; the builder does not keep - * a reference to the input StringPiece or its data(). - * @param s The input byte sequence. - * @param value The value associated with this byte sequence. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return *this - * @stable ICU 4.8 - */ - BytesTrieBuilder &add(StringPiece s, int32_t value, UErrorCode &errorCode); - - /** - * Builds a BytesTrie for the add()ed data. - * Once built, no further data can be add()ed until clear() is called. - * - * A BytesTrie cannot be empty. At least one (byte sequence, value) pair - * must have been add()ed. - * - * This method passes ownership of the builder's internal result array to the new trie object. - * Another call to any build() variant will re-serialize the trie. - * After clear() has been called, a new array will be used as well. - * @param buildOption Build option, see UStringTrieBuildOption. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return A new BytesTrie for the add()ed data. - * @stable ICU 4.8 - */ - BytesTrie *build(UStringTrieBuildOption buildOption, UErrorCode &errorCode); - - /** - * Builds a BytesTrie for the add()ed data and byte-serializes it. - * Once built, no further data can be add()ed until clear() is called. - * - * A BytesTrie cannot be empty. At least one (byte sequence, value) pair - * must have been add()ed. - * - * Multiple calls to buildStringPiece() return StringPieces referring to the - * builder's same byte array, without rebuilding. - * If buildStringPiece() is called after build(), the trie will be - * re-serialized into a new array. - * If build() is called after buildStringPiece(), the trie object will become - * the owner of the previously returned array. - * After clear() has been called, a new array will be used as well. - * @param buildOption Build option, see UStringTrieBuildOption. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return A StringPiece which refers to the byte-serialized BytesTrie for the add()ed data. - * @stable ICU 4.8 - */ - StringPiece buildStringPiece(UStringTrieBuildOption buildOption, UErrorCode &errorCode); - - /** - * Removes all (byte sequence, value) pairs. - * New data can then be add()ed and a new trie can be built. - * @return *this - * @stable ICU 4.8 - */ - BytesTrieBuilder &clear(); - -private: - BytesTrieBuilder(const BytesTrieBuilder &other); // no copy constructor - BytesTrieBuilder &operator=(const BytesTrieBuilder &other); // no assignment operator - - void buildBytes(UStringTrieBuildOption buildOption, UErrorCode &errorCode); - - virtual int32_t getElementStringLength(int32_t i) const; - virtual UChar getElementUnit(int32_t i, int32_t byteIndex) const; - virtual int32_t getElementValue(int32_t i) const; - - virtual int32_t getLimitOfLinearMatch(int32_t first, int32_t last, int32_t byteIndex) const; - - virtual int32_t countElementUnits(int32_t start, int32_t limit, int32_t byteIndex) const; - virtual int32_t skipElementsBySomeUnits(int32_t i, int32_t byteIndex, int32_t count) const; - virtual int32_t indexOfElementWithNextUnit(int32_t i, int32_t byteIndex, UChar byte) const; - - virtual UBool matchNodesCanHaveValues() const { return FALSE; } - - virtual int32_t getMaxBranchLinearSubNodeLength() const { return BytesTrie::kMaxBranchLinearSubNodeLength; } - virtual int32_t getMinLinearMatch() const { return BytesTrie::kMinLinearMatch; } - virtual int32_t getMaxLinearMatchLength() const { return BytesTrie::kMaxLinearMatchLength; } - - /** - * @internal - */ - class BTLinearMatchNode : public LinearMatchNode { - public: - BTLinearMatchNode(const char *units, int32_t len, Node *nextNode); - virtual UBool operator==(const Node &other) const; - virtual void write(StringTrieBuilder &builder); - private: - const char *s; - }; - - // don't use #ifndef U_HIDE_INTERNAL_API with private class members or virtual methods. - virtual Node *createLinearMatchNode(int32_t i, int32_t byteIndex, int32_t length, - Node *nextNode) const; - - UBool ensureCapacity(int32_t length); - virtual int32_t write(int32_t byte); - int32_t write(const char *b, int32_t length); - virtual int32_t writeElementUnits(int32_t i, int32_t byteIndex, int32_t length); - virtual int32_t writeValueAndFinal(int32_t i, UBool isFinal); - virtual int32_t writeValueAndType(UBool hasValue, int32_t value, int32_t node); - virtual int32_t writeDeltaTo(int32_t jumpTarget); - - CharString *strings; // Pointer not object so we need not #include internal charstr.h. - BytesTrieElement *elements; - int32_t elementsCapacity; - int32_t elementsLength; - - // Byte serialization of the trie. - // Grows from the back: bytesLength measures from the end of the buffer! - char *bytes; - int32_t bytesCapacity; - int32_t bytesLength; -}; - -U_NAMESPACE_END - -#endif // __BYTESTRIEBUILDER_H__ diff --git a/win32/include/spidermonkey/unicode/calendar.h b/win32/include/spidermonkey/unicode/calendar.h deleted file mode 100755 index 8776e21d..00000000 --- a/win32/include/spidermonkey/unicode/calendar.h +++ /dev/null @@ -1,2551 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 1997-2014, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************** -* -* File CALENDAR.H -* -* Modification History: -* -* Date Name Description -* 04/22/97 aliu Expanded and corrected comments and other header -* contents. -* 05/01/97 aliu Made equals(), before(), after() arguments const. -* 05/20/97 aliu Replaced fAreFieldsSet with fAreFieldsInSync and -* fAreAllFieldsSet. -* 07/27/98 stephen Sync up with JDK 1.2 -* 11/15/99 weiv added YEAR_WOY and DOW_LOCAL -* to EDateFields -* 8/19/2002 srl Removed Javaisms -* 11/07/2003 srl Update, clean up documentation. -******************************************************************************** -*/ - -#ifndef CALENDAR_H -#define CALENDAR_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Calendar object - */ -#if !UCONFIG_NO_FORMATTING - -#include "unicode/uobject.h" -#include "unicode/locid.h" -#include "unicode/timezone.h" -#include "unicode/ucal.h" -#include "unicode/umisc.h" - -U_NAMESPACE_BEGIN - -class ICUServiceFactory; - -/** - * @internal - */ -typedef int32_t UFieldResolutionTable[12][8]; - -class BasicTimeZone; -/** - * Calendar is an abstract base class for converting between - * a UDate object and a set of integer fields such as - * YEAR, MONTH, DAY, HOUR, - * and so on. (A UDate object represents a specific instant in - * time with millisecond precision. See UDate - * for information about the UDate class.) - * - *

- * Subclasses of Calendar interpret a UDate - * according to the rules of a specific calendar system. - * The most commonly used subclass of Calendar is - * GregorianCalendar. Other subclasses could represent - * the various types of lunar calendars in use in many parts of the world. - * - *

- * NOTE: (ICU 2.6) The subclass interface should be considered unstable - * - it WILL change. - * - *

- * Like other locale-sensitive classes, Calendar provides a - * static method, createInstance, for getting a generally useful - * object of this type. Calendar's createInstance method - * returns the appropriate Calendar subclass whose - * time fields have been initialized with the current date and time: - * \htmlonly

\endhtmlonly - *
- * Calendar *rightNow = Calendar::createInstance(errCode);
- * 
- * \htmlonly
\endhtmlonly - * - *

- * A Calendar object can produce all the time field values - * needed to implement the date-time formatting for a particular language - * and calendar style (for example, Japanese-Gregorian, Japanese-Traditional). - * - *

- * When computing a UDate from time fields, some special circumstances - * may arise: there may be insufficient information to compute the - * UDate (such as only year and month but no day in the month), - * there may be inconsistent information (such as "Tuesday, July 15, 1996" - * -- July 15, 1996 is actually a Monday), or the input time might be ambiguous - * because of time zone transition. - * - *

- * Insufficient information. The calendar will use default - * information to specify the missing fields. This may vary by calendar; for - * the Gregorian calendar, the default for a field is the same as that of the - * start of the epoch: i.e., YEAR = 1970, MONTH = JANUARY, DATE = 1, etc. - * - *

- * Inconsistent information. If fields conflict, the calendar - * will give preference to fields set more recently. For example, when - * determining the day, the calendar will look for one of the following - * combinations of fields. The most recent combination, as determined by the - * most recently set single field, will be used. - * - * \htmlonly

\endhtmlonly - *
- * MONTH + DAY_OF_MONTH
- * MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
- * MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
- * DAY_OF_YEAR
- * DAY_OF_WEEK + WEEK_OF_YEAR
- * 
- * \htmlonly
\endhtmlonly - * - * For the time of day: - * - * \htmlonly
\endhtmlonly - *
- * HOUR_OF_DAY
- * AM_PM + HOUR
- * 
- * \htmlonly
\endhtmlonly - * - *

- * Ambiguous Wall Clock Time. When time offset from UTC has - * changed, it produces an ambiguous time slot around the transition. For example, - * many US locations observe daylight saving time. On the date switching to daylight - * saving time in US, wall clock time jumps from 12:59 AM (standard) to 2:00 AM - * (daylight). Therefore, wall clock time from 1:00 AM to 1:59 AM do not exist on - * the date. When the input wall time fall into this missing time slot, the ICU - * Calendar resolves the time using the UTC offset before the transition by default. - * In this example, 1:30 AM is interpreted as 1:30 AM standard time (non-exist), - * so the final result will be 2:30 AM daylight time. - * - *

On the date switching back to standard time, wall clock time is moved back one - * hour at 2:00 AM. So wall clock time from 1:00 AM to 1:59 AM occur twice. In this - * case, the ICU Calendar resolves the time using the UTC offset after the transition - * by default. For example, 1:30 AM on the date is resolved as 1:30 AM standard time. - * - *

Ambiguous wall clock time resolution behaviors can be customized by Calendar APIs - * {@link #setRepeatedWallTimeOption} and {@link #setSkippedWallTimeOption}. - * These methods are available in ICU 49 or later versions. - * - *

- * Note: for some non-Gregorian calendars, different - * fields may be necessary for complete disambiguation. For example, a full - * specification of the historial Arabic astronomical calendar requires year, - * month, day-of-month and day-of-week in some cases. - * - *

- * Note: There are certain possible ambiguities in - * interpretation of certain singular times, which are resolved in the - * following ways: - *

    - *
  1. 24:00:00 "belongs" to the following day. That is, - * 23:59 on Dec 31, 1969 < 24:00 on Jan 1, 1970 < 24:01:00 on Jan 1, 1970 - * - *
  2. Although historically not precise, midnight also belongs to "am", - * and noon belongs to "pm", so on the same day, - * 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm - *
- * - *

- * The date or time format strings are not part of the definition of a - * calendar, as those must be modifiable or overridable by the user at - * runtime. Use {@link DateFormat} - * to format dates. - * - *

- * Calendar provides an API for field "rolling", where fields - * can be incremented or decremented, but wrap around. For example, rolling the - * month up in the date December 12, 1996 results in - * January 12, 1996. - * - *

- * Calendar also provides a date arithmetic function for - * adding the specified (signed) amount of time to a particular time field. - * For example, subtracting 5 days from the date September 12, 1996 - * results in September 7, 1996. - * - *

Supported range - * - *

The allowable range of Calendar has been - * narrowed. GregorianCalendar used to attempt to support - * the range of dates with millisecond values from - * Long.MIN_VALUE to Long.MAX_VALUE. - * The new Calendar protocol specifies the - * maximum range of supportable dates as those having Julian day numbers - * of -0x7F000000 to +0x7F000000. This - * corresponds to years from ~5,800,000 BCE to ~5,800,000 CE. Programmers - * should use the protected constants in Calendar to - * specify an extremely early or extremely late date.

- * - * @stable ICU 2.0 - */ -class U_I18N_API Calendar : public UObject { -public: - - /** - * Field IDs for date and time. Used to specify date/time fields. ERA is calendar - * specific. Example ranges given are for illustration only; see specific Calendar - * subclasses for actual ranges. - * @deprecated ICU 2.6. Use C enum UCalendarDateFields defined in ucal.h - */ - enum EDateFields { -#ifndef U_HIDE_DEPRECATED_API -/* - * ERA may be defined on other platforms. To avoid any potential problems undefined it here. - */ -#ifdef ERA -#undef ERA -#endif - ERA, // Example: 0..1 - YEAR, // Example: 1..big number - MONTH, // Example: 0..11 - WEEK_OF_YEAR, // Example: 1..53 - WEEK_OF_MONTH, // Example: 1..4 - DATE, // Example: 1..31 - DAY_OF_YEAR, // Example: 1..365 - DAY_OF_WEEK, // Example: 1..7 - DAY_OF_WEEK_IN_MONTH, // Example: 1..4, may be specified as -1 - AM_PM, // Example: 0..1 - HOUR, // Example: 0..11 - HOUR_OF_DAY, // Example: 0..23 - MINUTE, // Example: 0..59 - SECOND, // Example: 0..59 - MILLISECOND, // Example: 0..999 - ZONE_OFFSET, // Example: -12*U_MILLIS_PER_HOUR..12*U_MILLIS_PER_HOUR - DST_OFFSET, // Example: 0 or U_MILLIS_PER_HOUR - YEAR_WOY, // 'Y' Example: 1..big number - Year of Week of Year - DOW_LOCAL, // 'e' Example: 1..7 - Day of Week / Localized - - EXTENDED_YEAR, - JULIAN_DAY, - MILLISECONDS_IN_DAY, - IS_LEAP_MONTH, - - FIELD_COUNT = UCAL_FIELD_COUNT // See ucal.h for other fields. -#endif /* U_HIDE_DEPRECATED_API */ - }; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Useful constant for days of week. Note: Calendar day-of-week is 1-based. Clients - * who create locale resources for the field of first-day-of-week should be aware of - * this. For instance, in US locale, first-day-of-week is set to 1, i.e., SUNDAY. - * @deprecated ICU 2.6. Use C enum UCalendarDaysOfWeek defined in ucal.h - */ - enum EDaysOfWeek { - SUNDAY = 1, - MONDAY, - TUESDAY, - WEDNESDAY, - THURSDAY, - FRIDAY, - SATURDAY - }; - - /** - * Useful constants for month. Note: Calendar month is 0-based. - * @deprecated ICU 2.6. Use C enum UCalendarMonths defined in ucal.h - */ - enum EMonths { - JANUARY, - FEBRUARY, - MARCH, - APRIL, - MAY, - JUNE, - JULY, - AUGUST, - SEPTEMBER, - OCTOBER, - NOVEMBER, - DECEMBER, - UNDECIMBER - }; - - /** - * Useful constants for hour in 12-hour clock. Used in GregorianCalendar. - * @deprecated ICU 2.6. Use C enum UCalendarAMPMs defined in ucal.h - */ - enum EAmpm { - AM, - PM - }; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * destructor - * @stable ICU 2.0 - */ - virtual ~Calendar(); - - /** - * Create and return a polymorphic copy of this calendar. - * - * @return a polymorphic copy of this calendar. - * @stable ICU 2.0 - */ - virtual Calendar* clone(void) const = 0; - - /** - * Creates a Calendar using the default timezone and locale. Clients are responsible - * for deleting the object returned. - * - * @param success Indicates the success/failure of Calendar creation. Filled in - * with U_ZERO_ERROR if created successfully, set to a failure result - * otherwise. U_MISSING_RESOURCE_ERROR will be returned if the resource data - * requests a calendar type which has not been installed. - * @return A Calendar if created successfully. NULL otherwise. - * @stable ICU 2.0 - */ - static Calendar* U_EXPORT2 createInstance(UErrorCode& success); - - /** - * Creates a Calendar using the given timezone and the default locale. - * The Calendar takes ownership of zoneToAdopt; the - * client must not delete it. - * - * @param zoneToAdopt The given timezone to be adopted. - * @param success Indicates the success/failure of Calendar creation. Filled in - * with U_ZERO_ERROR if created successfully, set to a failure result - * otherwise. - * @return A Calendar if created successfully. NULL otherwise. - * @stable ICU 2.0 - */ - static Calendar* U_EXPORT2 createInstance(TimeZone* zoneToAdopt, UErrorCode& success); - - /** - * Creates a Calendar using the given timezone and the default locale. The TimeZone - * is _not_ adopted; the client is still responsible for deleting it. - * - * @param zone The timezone. - * @param success Indicates the success/failure of Calendar creation. Filled in - * with U_ZERO_ERROR if created successfully, set to a failure result - * otherwise. - * @return A Calendar if created successfully. NULL otherwise. - * @stable ICU 2.0 - */ - static Calendar* U_EXPORT2 createInstance(const TimeZone& zone, UErrorCode& success); - - /** - * Creates a Calendar using the default timezone and the given locale. - * - * @param aLocale The given locale. - * @param success Indicates the success/failure of Calendar creation. Filled in - * with U_ZERO_ERROR if created successfully, set to a failure result - * otherwise. - * @return A Calendar if created successfully. NULL otherwise. - * @stable ICU 2.0 - */ - static Calendar* U_EXPORT2 createInstance(const Locale& aLocale, UErrorCode& success); - - /** - * Creates a Calendar using the given timezone and given locale. - * The Calendar takes ownership of zoneToAdopt; the - * client must not delete it. - * - * @param zoneToAdopt The given timezone to be adopted. - * @param aLocale The given locale. - * @param success Indicates the success/failure of Calendar creation. Filled in - * with U_ZERO_ERROR if created successfully, set to a failure result - * otherwise. - * @return A Calendar if created successfully. NULL otherwise. - * @stable ICU 2.0 - */ - static Calendar* U_EXPORT2 createInstance(TimeZone* zoneToAdopt, const Locale& aLocale, UErrorCode& success); - - /** - * Gets a Calendar using the given timezone and given locale. The TimeZone - * is _not_ adopted; the client is still responsible for deleting it. - * - * @param zone The given timezone. - * @param aLocale The given locale. - * @param success Indicates the success/failure of Calendar creation. Filled in - * with U_ZERO_ERROR if created successfully, set to a failure result - * otherwise. - * @return A Calendar if created successfully. NULL otherwise. - * @stable ICU 2.0 - */ - static Calendar* U_EXPORT2 createInstance(const TimeZone& zone, const Locale& aLocale, UErrorCode& success); - - /** - * Returns a list of the locales for which Calendars are installed. - * - * @param count Number of locales returned. - * @return An array of Locale objects representing the set of locales for which - * Calendars are installed. The system retains ownership of this list; - * the caller must NOT delete it. Does not include user-registered Calendars. - * @stable ICU 2.0 - */ - static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); - - - /** - * Given a key and a locale, returns an array of string values in a preferred - * order that would make a difference. These are all and only those values where - * the open (creation) of the service with the locale formed from the input locale - * plus input keyword and that value has different behavior than creation with the - * input locale alone. - * @param key one of the keys supported by this service. For now, only - * "calendar" is supported. - * @param locale the locale - * @param commonlyUsed if set to true it will return only commonly used values - * with the given locale in preferred order. Otherwise, - * it will return all the available values for the locale. - * @param status ICU Error Code - * @return a string enumeration over keyword values for the given key and the locale. - * @stable ICU 4.2 - */ - static StringEnumeration* U_EXPORT2 getKeywordValuesForLocale(const char* key, - const Locale& locale, UBool commonlyUsed, UErrorCode& status); - - /** - * Returns the current UTC (GMT) time measured in milliseconds since 0:00:00 on 1/1/70 - * (derived from the system time). - * - * @return The current UTC time in milliseconds. - * @stable ICU 2.0 - */ - static UDate U_EXPORT2 getNow(void); - - /** - * Gets this Calendar's time as milliseconds. May involve recalculation of time due - * to previous calls to set time field values. The time specified is non-local UTC - * (GMT) time. Although this method is const, this object may actually be changed - * (semantically const). - * - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @return The current time in UTC (GMT) time, or zero if the operation - * failed. - * @stable ICU 2.0 - */ - inline UDate getTime(UErrorCode& status) const { return getTimeInMillis(status); } - - /** - * Sets this Calendar's current time with the given UDate. The time specified should - * be in non-local UTC (GMT) time. - * - * @param date The given UDate in UTC (GMT) time. - * @param status Output param set to success/failure code on exit. If any value - * set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @stable ICU 2.0 - */ - inline void setTime(UDate date, UErrorCode& status) { setTimeInMillis(date, status); } - - /** - * Compares the equality of two Calendar objects. Objects of different subclasses - * are considered unequal. This comparison is very exacting; two Calendar objects - * must be in exactly the same state to be considered equal. To compare based on the - * represented time, use equals() instead. - * - * @param that The Calendar object to be compared with. - * @return True if the given Calendar is the same as this Calendar; false - * otherwise. - * @stable ICU 2.0 - */ - virtual UBool operator==(const Calendar& that) const; - - /** - * Compares the inequality of two Calendar objects. - * - * @param that The Calendar object to be compared with. - * @return True if the given Calendar is not the same as this Calendar; false - * otherwise. - * @stable ICU 2.0 - */ - UBool operator!=(const Calendar& that) const {return !operator==(that);} - - /** - * Returns TRUE if the given Calendar object is equivalent to this - * one. An equivalent Calendar will behave exactly as this one - * does, but it may be set to a different time. By contrast, for - * the operator==() method to return TRUE, the other Calendar must - * be set to the same time. - * - * @param other the Calendar to be compared with this Calendar - * @stable ICU 2.4 - */ - virtual UBool isEquivalentTo(const Calendar& other) const; - - /** - * Compares the Calendar time, whereas Calendar::operator== compares the equality of - * Calendar objects. - * - * @param when The Calendar to be compared with this Calendar. Although this is a - * const parameter, the object may be modified physically - * (semantically const). - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @return True if the current time of this Calendar is equal to the time of - * Calendar when; false otherwise. - * @stable ICU 2.0 - */ - UBool equals(const Calendar& when, UErrorCode& status) const; - - /** - * Returns true if this Calendar's current time is before "when"'s current time. - * - * @param when The Calendar to be compared with this Calendar. Although this is a - * const parameter, the object may be modified physically - * (semantically const). - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @return True if the current time of this Calendar is before the time of - * Calendar when; false otherwise. - * @stable ICU 2.0 - */ - UBool before(const Calendar& when, UErrorCode& status) const; - - /** - * Returns true if this Calendar's current time is after "when"'s current time. - * - * @param when The Calendar to be compared with this Calendar. Although this is a - * const parameter, the object may be modified physically - * (semantically const). - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @return True if the current time of this Calendar is after the time of - * Calendar when; false otherwise. - * @stable ICU 2.0 - */ - UBool after(const Calendar& when, UErrorCode& status) const; - - /** - * UDate Arithmetic function. Adds the specified (signed) amount of time to the given - * time field, based on the calendar's rules. For example, to subtract 5 days from - * the current time of the calendar, call add(Calendar::DATE, -5). When adding on - * the month or Calendar::MONTH field, other fields like date might conflict and - * need to be changed. For instance, adding 1 month on the date 01/31/96 will result - * in 02/29/96. - * Adding a positive value always means moving forward in time, so for the Gregorian calendar, - * starting with 100 BC and adding +1 to year results in 99 BC (even though this actually reduces - * the numeric value of the field itself). - * - * @param field Specifies which date field to modify. - * @param amount The amount of time to be added to the field, in the natural unit - * for that field (e.g., days for the day fields, hours for the hour - * field.) - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @deprecated ICU 2.6. use add(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead. - */ - virtual void add(EDateFields field, int32_t amount, UErrorCode& status); - - /** - * UDate Arithmetic function. Adds the specified (signed) amount of time to the given - * time field, based on the calendar's rules. For example, to subtract 5 days from - * the current time of the calendar, call add(Calendar::DATE, -5). When adding on - * the month or Calendar::MONTH field, other fields like date might conflict and - * need to be changed. For instance, adding 1 month on the date 01/31/96 will result - * in 02/29/96. - * Adding a positive value always means moving forward in time, so for the Gregorian calendar, - * starting with 100 BC and adding +1 to year results in 99 BC (even though this actually reduces - * the numeric value of the field itself). - * - * @param field Specifies which date field to modify. - * @param amount The amount of time to be added to the field, in the natural unit - * for that field (e.g., days for the day fields, hours for the hour - * field.) - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @stable ICU 2.6. - */ - virtual void add(UCalendarDateFields field, int32_t amount, UErrorCode& status); - -#ifndef U_HIDE_DEPRECATED_API - /** - * Time Field Rolling function. Rolls (up/down) a single unit of time on the given - * time field. For example, to roll the current date up by one day, call - * roll(Calendar::DATE, true). When rolling on the year or Calendar::YEAR field, it - * will roll the year value in the range between getMinimum(Calendar::YEAR) and the - * value returned by getMaximum(Calendar::YEAR). When rolling on the month or - * Calendar::MONTH field, other fields like date might conflict and, need to be - * changed. For instance, rolling the month up on the date 01/31/96 will result in - * 02/29/96. Rolling up always means rolling forward in time (unless the limit of the - * field is reached, in which case it may pin or wrap), so for Gregorian calendar, - * starting with 100 BC and rolling the year up results in 99 BC. - * When eras have a definite beginning and end (as in the Chinese calendar, or as in - * most eras in the Japanese calendar) then rolling the year past either limit of the - * era will cause the year to wrap around. When eras only have a limit at one end, - * then attempting to roll the year past that limit will result in pinning the year - * at that limit. Note that for most calendars in which era 0 years move forward in - * time (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to - * result in negative years for era 0 (that is the only way to represent years before - * the calendar epoch). - * When rolling on the hour-in-day or Calendar::HOUR_OF_DAY field, it will roll the - * hour value in the range between 0 and 23, which is zero-based. - *

- * NOTE: Do not use this method -- use roll(EDateFields, int, UErrorCode&) instead. - * - * @param field The time field. - * @param up Indicates if the value of the specified time field is to be rolled - * up or rolled down. Use true if rolling up, false otherwise. - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @deprecated ICU 2.6. Use roll(UCalendarDateFields field, UBool up, UErrorCode& status) instead. - */ - inline void roll(EDateFields field, UBool up, UErrorCode& status); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Time Field Rolling function. Rolls (up/down) a single unit of time on the given - * time field. For example, to roll the current date up by one day, call - * roll(Calendar::DATE, true). When rolling on the year or Calendar::YEAR field, it - * will roll the year value in the range between getMinimum(Calendar::YEAR) and the - * value returned by getMaximum(Calendar::YEAR). When rolling on the month or - * Calendar::MONTH field, other fields like date might conflict and, need to be - * changed. For instance, rolling the month up on the date 01/31/96 will result in - * 02/29/96. Rolling up always means rolling forward in time (unless the limit of the - * field is reached, in which case it may pin or wrap), so for Gregorian calendar, - * starting with 100 BC and rolling the year up results in 99 BC. - * When eras have a definite beginning and end (as in the Chinese calendar, or as in - * most eras in the Japanese calendar) then rolling the year past either limit of the - * era will cause the year to wrap around. When eras only have a limit at one end, - * then attempting to roll the year past that limit will result in pinning the year - * at that limit. Note that for most calendars in which era 0 years move forward in - * time (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to - * result in negative years for era 0 (that is the only way to represent years before - * the calendar epoch). - * When rolling on the hour-in-day or Calendar::HOUR_OF_DAY field, it will roll the - * hour value in the range between 0 and 23, which is zero-based. - *

- * NOTE: Do not use this method -- use roll(UCalendarDateFields, int, UErrorCode&) instead. - * - * @param field The time field. - * @param up Indicates if the value of the specified time field is to be rolled - * up or rolled down. Use true if rolling up, false otherwise. - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @stable ICU 2.6. - */ - inline void roll(UCalendarDateFields field, UBool up, UErrorCode& status); - - /** - * Time Field Rolling function. Rolls by the given amount on the given - * time field. For example, to roll the current date up by one day, call - * roll(Calendar::DATE, +1, status). When rolling on the month or - * Calendar::MONTH field, other fields like date might conflict and, need to be - * changed. For instance, rolling the month up on the date 01/31/96 will result in - * 02/29/96. Rolling by a positive value always means rolling forward in time (unless - * the limit of the field is reached, in which case it may pin or wrap), so for - * Gregorian calendar, starting with 100 BC and rolling the year by + 1 results in 99 BC. - * When eras have a definite beginning and end (as in the Chinese calendar, or as in - * most eras in the Japanese calendar) then rolling the year past either limit of the - * era will cause the year to wrap around. When eras only have a limit at one end, - * then attempting to roll the year past that limit will result in pinning the year - * at that limit. Note that for most calendars in which era 0 years move forward in - * time (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to - * result in negative years for era 0 (that is the only way to represent years before - * the calendar epoch). - * When rolling on the hour-in-day or Calendar::HOUR_OF_DAY field, it will roll the - * hour value in the range between 0 and 23, which is zero-based. - *

- * The only difference between roll() and add() is that roll() does not change - * the value of more significant fields when it reaches the minimum or maximum - * of its range, whereas add() does. - * - * @param field The time field. - * @param amount Indicates amount to roll. - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid, this will be set to - * an error status. - * @deprecated ICU 2.6. Use roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead. - */ - virtual void roll(EDateFields field, int32_t amount, UErrorCode& status); - - /** - * Time Field Rolling function. Rolls by the given amount on the given - * time field. For example, to roll the current date up by one day, call - * roll(Calendar::DATE, +1, status). When rolling on the month or - * Calendar::MONTH field, other fields like date might conflict and, need to be - * changed. For instance, rolling the month up on the date 01/31/96 will result in - * 02/29/96. Rolling by a positive value always means rolling forward in time (unless - * the limit of the field is reached, in which case it may pin or wrap), so for - * Gregorian calendar, starting with 100 BC and rolling the year by + 1 results in 99 BC. - * When eras have a definite beginning and end (as in the Chinese calendar, or as in - * most eras in the Japanese calendar) then rolling the year past either limit of the - * era will cause the year to wrap around. When eras only have a limit at one end, - * then attempting to roll the year past that limit will result in pinning the year - * at that limit. Note that for most calendars in which era 0 years move forward in - * time (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to - * result in negative years for era 0 (that is the only way to represent years before - * the calendar epoch). - * When rolling on the hour-in-day or Calendar::HOUR_OF_DAY field, it will roll the - * hour value in the range between 0 and 23, which is zero-based. - *

- * The only difference between roll() and add() is that roll() does not change - * the value of more significant fields when it reaches the minimum or maximum - * of its range, whereas add() does. - * - * @param field The time field. - * @param amount Indicates amount to roll. - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid, this will be set to - * an error status. - * @stable ICU 2.6. - */ - virtual void roll(UCalendarDateFields field, int32_t amount, UErrorCode& status); - - /** - * Return the difference between the given time and the time this - * calendar object is set to. If this calendar is set - * before the given time, the returned value will be - * positive. If this calendar is set after the given - * time, the returned value will be negative. The - * field parameter specifies the units of the return - * value. For example, if fieldDifference(when, - * Calendar::MONTH) returns 3, then this calendar is set to - * 3 months before when, and possibly some addition - * time less than one month. - * - *

As a side effect of this call, this calendar is advanced - * toward when by the given amount. That is, calling - * this method has the side effect of calling add(field, - * n), where n is the return value. - * - *

Usage: To use this method, call it first with the largest - * field of interest, then with progressively smaller fields. For - * example: - * - *

-     * int y = cal->fieldDifference(when, Calendar::YEAR, err);
-     * int m = cal->fieldDifference(when, Calendar::MONTH, err);
-     * int d = cal->fieldDifference(when, Calendar::DATE, err);
- * - * computes the difference between cal and - * when in years, months, and days. - * - *

Note: fieldDifference() is - * asymmetrical. That is, in the following code: - * - *

-     * cal->setTime(date1, err);
-     * int m1 = cal->fieldDifference(date2, Calendar::MONTH, err);
-     * int d1 = cal->fieldDifference(date2, Calendar::DATE, err);
-     * cal->setTime(date2, err);
-     * int m2 = cal->fieldDifference(date1, Calendar::MONTH, err);
-     * int d2 = cal->fieldDifference(date1, Calendar::DATE, err);
- * - * one might expect that m1 == -m2 && d1 == -d2. - * However, this is not generally the case, because of - * irregularities in the underlying calendar system (e.g., the - * Gregorian calendar has a varying number of days per month). - * - * @param when the date to compare this calendar's time to - * @param field the field in which to compute the result - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid, this will be set to - * an error status. - * @return the difference, either positive or negative, between - * this calendar's time and when, in terms of - * field. - * @deprecated ICU 2.6. Use fieldDifference(UDate when, UCalendarDateFields field, UErrorCode& status). - */ - virtual int32_t fieldDifference(UDate when, EDateFields field, UErrorCode& status); - - /** - * Return the difference between the given time and the time this - * calendar object is set to. If this calendar is set - * before the given time, the returned value will be - * positive. If this calendar is set after the given - * time, the returned value will be negative. The - * field parameter specifies the units of the return - * value. For example, if fieldDifference(when, - * Calendar::MONTH) returns 3, then this calendar is set to - * 3 months before when, and possibly some addition - * time less than one month. - * - *

As a side effect of this call, this calendar is advanced - * toward when by the given amount. That is, calling - * this method has the side effect of calling add(field, - * n), where n is the return value. - * - *

Usage: To use this method, call it first with the largest - * field of interest, then with progressively smaller fields. For - * example: - * - *

-     * int y = cal->fieldDifference(when, Calendar::YEAR, err);
-     * int m = cal->fieldDifference(when, Calendar::MONTH, err);
-     * int d = cal->fieldDifference(when, Calendar::DATE, err);
- * - * computes the difference between cal and - * when in years, months, and days. - * - *

Note: fieldDifference() is - * asymmetrical. That is, in the following code: - * - *

-     * cal->setTime(date1, err);
-     * int m1 = cal->fieldDifference(date2, Calendar::MONTH, err);
-     * int d1 = cal->fieldDifference(date2, Calendar::DATE, err);
-     * cal->setTime(date2, err);
-     * int m2 = cal->fieldDifference(date1, Calendar::MONTH, err);
-     * int d2 = cal->fieldDifference(date1, Calendar::DATE, err);
- * - * one might expect that m1 == -m2 && d1 == -d2. - * However, this is not generally the case, because of - * irregularities in the underlying calendar system (e.g., the - * Gregorian calendar has a varying number of days per month). - * - * @param when the date to compare this calendar's time to - * @param field the field in which to compute the result - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid, this will be set to - * an error status. - * @return the difference, either positive or negative, between - * this calendar's time and when, in terms of - * field. - * @stable ICU 2.6. - */ - virtual int32_t fieldDifference(UDate when, UCalendarDateFields field, UErrorCode& status); - - /** - * Sets the calendar's time zone to be the one passed in. The Calendar takes ownership - * of the TimeZone; the caller is no longer responsible for deleting it. If the - * given time zone is NULL, this function has no effect. - * - * @param value The given time zone. - * @stable ICU 2.0 - */ - void adoptTimeZone(TimeZone* value); - - /** - * Sets the calendar's time zone to be the same as the one passed in. The TimeZone - * passed in is _not_ adopted; the client is still responsible for deleting it. - * - * @param zone The given time zone. - * @stable ICU 2.0 - */ - void setTimeZone(const TimeZone& zone); - - /** - * Returns a reference to the time zone owned by this calendar. The returned reference - * is only valid until clients make another call to adoptTimeZone or setTimeZone, - * or this Calendar is destroyed. - * - * @return The time zone object associated with this calendar. - * @stable ICU 2.0 - */ - const TimeZone& getTimeZone(void) const; - - /** - * Returns the time zone owned by this calendar. The caller owns the returned object - * and must delete it when done. After this call, the new time zone associated - * with this Calendar is the default TimeZone as returned by TimeZone::createDefault(). - * - * @return The time zone object which was associated with this calendar. - * @stable ICU 2.0 - */ - TimeZone* orphanTimeZone(void); - - /** - * Queries if the current date for this Calendar is in Daylight Savings Time. - * - * @param status Fill-in parameter which receives the status of this operation. - * @return True if the current date for this Calendar is in Daylight Savings Time, - * false, otherwise. - * @stable ICU 2.0 - */ - virtual UBool inDaylightTime(UErrorCode& status) const = 0; - - /** - * Specifies whether or not date/time interpretation is to be lenient. With lenient - * interpretation, a date such as "February 942, 1996" will be treated as being - * equivalent to the 941st day after February 1, 1996. With strict interpretation, - * such dates will cause an error when computing time from the time field values - * representing the dates. - * - * @param lenient True specifies date/time interpretation to be lenient. - * - * @see DateFormat#setLenient - * @stable ICU 2.0 - */ - void setLenient(UBool lenient); - - /** - * Tells whether date/time interpretation is to be lenient. - * - * @return True tells that date/time interpretation is to be lenient. - * @stable ICU 2.0 - */ - UBool isLenient(void) const; - - /** - * Sets the behavior for handling wall time repeating multiple times - * at negative time zone offset transitions. For example, 1:30 AM on - * November 6, 2011 in US Eastern time (Ameirca/New_York) occurs twice; - * 1:30 AM EDT, then 1:30 AM EST one hour later. When UCAL_WALLTIME_FIRST - * is used, the wall time 1:30AM in this example will be interpreted as 1:30 AM EDT - * (first occurrence). When UCAL_WALLTIME_LAST is used, it will be - * interpreted as 1:30 AM EST (last occurrence). The default value is - * UCAL_WALLTIME_LAST. - *

- * Note:When UCAL_WALLTIME_NEXT_VALID is not a valid - * option for this. When the argument is neither UCAL_WALLTIME_FIRST - * nor UCAL_WALLTIME_LAST, this method has no effect and will keep - * the current setting. - * - * @param option the behavior for handling repeating wall time, either - * UCAL_WALLTIME_FIRST or UCAL_WALLTIME_LAST. - * @see #getRepeatedWallTimeOption - * @stable ICU 49 - */ - void setRepeatedWallTimeOption(UCalendarWallTimeOption option); - - /** - * Gets the behavior for handling wall time repeating multiple times - * at negative time zone offset transitions. - * - * @return the behavior for handling repeating wall time, either - * UCAL_WALLTIME_FIRST or UCAL_WALLTIME_LAST. - * @see #setRepeatedWallTimeOption - * @stable ICU 49 - */ - UCalendarWallTimeOption getRepeatedWallTimeOption(void) const; - - /** - * Sets the behavior for handling skipped wall time at positive time zone offset - * transitions. For example, 2:30 AM on March 13, 2011 in US Eastern time (America/New_York) - * does not exist because the wall time jump from 1:59 AM EST to 3:00 AM EDT. When - * UCAL_WALLTIME_FIRST is used, 2:30 AM is interpreted as 30 minutes before 3:00 AM - * EDT, therefore, it will be resolved as 1:30 AM EST. When UCAL_WALLTIME_LAST - * is used, 2:30 AM is interpreted as 31 minutes after 1:59 AM EST, therefore, it will be - * resolved as 3:30 AM EDT. When UCAL_WALLTIME_NEXT_VALID is used, 2:30 AM will - * be resolved as next valid wall time, that is 3:00 AM EDT. The default value is - * UCAL_WALLTIME_LAST. - *

- * Note:This option is effective only when this calendar is lenient. - * When the calendar is strict, such non-existing wall time will cause an error. - * - * @param option the behavior for handling skipped wall time at positive time zone - * offset transitions, one of UCAL_WALLTIME_FIRST, UCAL_WALLTIME_LAST and - * UCAL_WALLTIME_NEXT_VALID. - * @see #getSkippedWallTimeOption - * - * @stable ICU 49 - */ - void setSkippedWallTimeOption(UCalendarWallTimeOption option); - - /** - * Gets the behavior for handling skipped wall time at positive time zone offset - * transitions. - * - * @return the behavior for handling skipped wall time, one of - * UCAL_WALLTIME_FIRST, UCAL_WALLTIME_LAST - * and UCAL_WALLTIME_NEXT_VALID. - * @see #setSkippedWallTimeOption - * @stable ICU 49 - */ - UCalendarWallTimeOption getSkippedWallTimeOption(void) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Sets what the first day of the week is; e.g., Sunday in US, Monday in France. - * - * @param value The given first day of the week. - * @deprecated ICU 2.6. Use setFirstDayOfWeek(UCalendarDaysOfWeek value) instead. - */ - void setFirstDayOfWeek(EDaysOfWeek value); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Sets what the first day of the week is; e.g., Sunday in US, Monday in France. - * - * @param value The given first day of the week. - * @stable ICU 2.6. - */ - void setFirstDayOfWeek(UCalendarDaysOfWeek value); - -#ifndef U_HIDE_DEPRECATED_API - /** - * Gets what the first day of the week is; e.g., Sunday in US, Monday in France. - * - * @return The first day of the week. - * @deprecated ICU 2.6 use the overload with error code - */ - EDaysOfWeek getFirstDayOfWeek(void) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Gets what the first day of the week is; e.g., Sunday in US, Monday in France. - * - * @param status error code - * @return The first day of the week. - * @stable ICU 2.6 - */ - UCalendarDaysOfWeek getFirstDayOfWeek(UErrorCode &status) const; - - /** - * Sets what the minimal days required in the first week of the year are; For - * example, if the first week is defined as one that contains the first day of the - * first month of a year, call the method with value 1. If it must be a full week, - * use value 7. - * - * @param value The given minimal days required in the first week of the year. - * @stable ICU 2.0 - */ - void setMinimalDaysInFirstWeek(uint8_t value); - - /** - * Gets what the minimal days required in the first week of the year are; e.g., if - * the first week is defined as one that contains the first day of the first month - * of a year, getMinimalDaysInFirstWeek returns 1. If the minimal days required must - * be a full week, getMinimalDaysInFirstWeek returns 7. - * - * @return The minimal days required in the first week of the year. - * @stable ICU 2.0 - */ - uint8_t getMinimalDaysInFirstWeek(void) const; - - /** - * Gets the minimum value for the given time field. e.g., for Gregorian - * DAY_OF_MONTH, 1. - * - * @param field The given time field. - * @return The minimum value for the given time field. - * @deprecated ICU 2.6. Use getMinimum(UCalendarDateFields field) instead. - */ - virtual int32_t getMinimum(EDateFields field) const; - - /** - * Gets the minimum value for the given time field. e.g., for Gregorian - * DAY_OF_MONTH, 1. - * - * @param field The given time field. - * @return The minimum value for the given time field. - * @stable ICU 2.6. - */ - virtual int32_t getMinimum(UCalendarDateFields field) const; - - /** - * Gets the maximum value for the given time field. e.g. for Gregorian DAY_OF_MONTH, - * 31. - * - * @param field The given time field. - * @return The maximum value for the given time field. - * @deprecated ICU 2.6. Use getMaximum(UCalendarDateFields field) instead. - */ - virtual int32_t getMaximum(EDateFields field) const; - - /** - * Gets the maximum value for the given time field. e.g. for Gregorian DAY_OF_MONTH, - * 31. - * - * @param field The given time field. - * @return The maximum value for the given time field. - * @stable ICU 2.6. - */ - virtual int32_t getMaximum(UCalendarDateFields field) const; - - /** - * Gets the highest minimum value for the given field if varies. Otherwise same as - * getMinimum(). For Gregorian, no difference. - * - * @param field The given time field. - * @return The highest minimum value for the given time field. - * @deprecated ICU 2.6. Use getGreatestMinimum(UCalendarDateFields field) instead. - */ - virtual int32_t getGreatestMinimum(EDateFields field) const; - - /** - * Gets the highest minimum value for the given field if varies. Otherwise same as - * getMinimum(). For Gregorian, no difference. - * - * @param field The given time field. - * @return The highest minimum value for the given time field. - * @stable ICU 2.6. - */ - virtual int32_t getGreatestMinimum(UCalendarDateFields field) const; - - /** - * Gets the lowest maximum value for the given field if varies. Otherwise same as - * getMaximum(). e.g., for Gregorian DAY_OF_MONTH, 28. - * - * @param field The given time field. - * @return The lowest maximum value for the given time field. - * @deprecated ICU 2.6. Use getLeastMaximum(UCalendarDateFields field) instead. - */ - virtual int32_t getLeastMaximum(EDateFields field) const; - - /** - * Gets the lowest maximum value for the given field if varies. Otherwise same as - * getMaximum(). e.g., for Gregorian DAY_OF_MONTH, 28. - * - * @param field The given time field. - * @return The lowest maximum value for the given time field. - * @stable ICU 2.6. - */ - virtual int32_t getLeastMaximum(UCalendarDateFields field) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Return the minimum value that this field could have, given the current date. - * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). - * - * The version of this function on Calendar uses an iterative algorithm to determine the - * actual minimum value for the field. There is almost always a more efficient way to - * accomplish this (in most cases, you can simply return getMinimum()). GregorianCalendar - * overrides this function with a more efficient implementation. - * - * @param field the field to determine the minimum of - * @param status Fill-in parameter which receives the status of this operation. - * @return the minimum of the given field for the current date of this Calendar - * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field, UErrorCode& status) instead. - */ - int32_t getActualMinimum(EDateFields field, UErrorCode& status) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Return the minimum value that this field could have, given the current date. - * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). - * - * The version of this function on Calendar uses an iterative algorithm to determine the - * actual minimum value for the field. There is almost always a more efficient way to - * accomplish this (in most cases, you can simply return getMinimum()). GregorianCalendar - * overrides this function with a more efficient implementation. - * - * @param field the field to determine the minimum of - * @param status Fill-in parameter which receives the status of this operation. - * @return the minimum of the given field for the current date of this Calendar - * @stable ICU 2.6. - */ - virtual int32_t getActualMinimum(UCalendarDateFields field, UErrorCode& status) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Return the maximum value that this field could have, given the current date. - * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual - * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar, - * for some years the actual maximum for MONTH is 12, and for others 13. - * - * The version of this function on Calendar uses an iterative algorithm to determine the - * actual maximum value for the field. There is almost always a more efficient way to - * accomplish this (in most cases, you can simply return getMaximum()). GregorianCalendar - * overrides this function with a more efficient implementation. - * - * @param field the field to determine the maximum of - * @param status Fill-in parameter which receives the status of this operation. - * @return the maximum of the given field for the current date of this Calendar - * @deprecated ICU 2.6. Use getActualMaximum(UCalendarDateFields field, UErrorCode& status) instead. - */ - int32_t getActualMaximum(EDateFields field, UErrorCode& status) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Return the maximum value that this field could have, given the current date. - * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual - * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar, - * for some years the actual maximum for MONTH is 12, and for others 13. - * - * The version of this function on Calendar uses an iterative algorithm to determine the - * actual maximum value for the field. There is almost always a more efficient way to - * accomplish this (in most cases, you can simply return getMaximum()). GregorianCalendar - * overrides this function with a more efficient implementation. - * - * @param field the field to determine the maximum of - * @param status Fill-in parameter which receives the status of this operation. - * @return the maximum of the given field for the current date of this Calendar - * @stable ICU 2.6. - */ - virtual int32_t getActualMaximum(UCalendarDateFields field, UErrorCode& status) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Gets the value for a given time field. Recalculate the current time field values - * if the time value has been changed by a call to setTime(). Return zero for unset - * fields if any fields have been explicitly set by a call to set(). To force a - * recomputation of all fields regardless of the previous state, call complete(). - * This method is semantically const, but may alter the object in memory. - * - * @param field The given time field. - * @param status Fill-in parameter which receives the status of the operation. - * @return The value for the given time field, or zero if the field is unset, - * and set() has been called for any other field. - * @deprecated ICU 2.6. Use get(UCalendarDateFields field, UErrorCode& status) instead. - */ - int32_t get(EDateFields field, UErrorCode& status) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Gets the value for a given time field. Recalculate the current time field values - * if the time value has been changed by a call to setTime(). Return zero for unset - * fields if any fields have been explicitly set by a call to set(). To force a - * recomputation of all fields regardless of the previous state, call complete(). - * This method is semantically const, but may alter the object in memory. - * - * @param field The given time field. - * @param status Fill-in parameter which receives the status of the operation. - * @return The value for the given time field, or zero if the field is unset, - * and set() has been called for any other field. - * @stable ICU 2.6. - */ - int32_t get(UCalendarDateFields field, UErrorCode& status) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Determines if the given time field has a value set. This can affect in the - * resolving of time in Calendar. Unset fields have a value of zero, by definition. - * - * @param field The given time field. - * @return True if the given time field has a value set; false otherwise. - * @deprecated ICU 2.6. Use isSet(UCalendarDateFields field) instead. - */ - UBool isSet(EDateFields field) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Determines if the given time field has a value set. This can affect in the - * resolving of time in Calendar. Unset fields have a value of zero, by definition. - * - * @param field The given time field. - * @return True if the given time field has a value set; false otherwise. - * @stable ICU 2.6. - */ - UBool isSet(UCalendarDateFields field) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Sets the given time field with the given value. - * - * @param field The given time field. - * @param value The value to be set for the given time field. - * @deprecated ICU 2.6. Use set(UCalendarDateFields field, int32_t value) instead. - */ - void set(EDateFields field, int32_t value); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Sets the given time field with the given value. - * - * @param field The given time field. - * @param value The value to be set for the given time field. - * @stable ICU 2.6. - */ - void set(UCalendarDateFields field, int32_t value); - - /** - * Sets the values for the fields YEAR, MONTH, and DATE. Other field values are - * retained; call clear() first if this is not desired. - * - * @param year The value used to set the YEAR time field. - * @param month The value used to set the MONTH time field. Month value is 0-based. - * e.g., 0 for January. - * @param date The value used to set the DATE time field. - * @stable ICU 2.0 - */ - void set(int32_t year, int32_t month, int32_t date); - - /** - * Sets the values for the fields YEAR, MONTH, DATE, HOUR_OF_DAY, and MINUTE. Other - * field values are retained; call clear() first if this is not desired. - * - * @param year The value used to set the YEAR time field. - * @param month The value used to set the MONTH time field. Month value is - * 0-based. E.g., 0 for January. - * @param date The value used to set the DATE time field. - * @param hour The value used to set the HOUR_OF_DAY time field. - * @param minute The value used to set the MINUTE time field. - * @stable ICU 2.0 - */ - void set(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute); - - /** - * Sets the values for the fields YEAR, MONTH, DATE, HOUR_OF_DAY, MINUTE, and SECOND. - * Other field values are retained; call clear() first if this is not desired. - * - * @param year The value used to set the YEAR time field. - * @param month The value used to set the MONTH time field. Month value is - * 0-based. E.g., 0 for January. - * @param date The value used to set the DATE time field. - * @param hour The value used to set the HOUR_OF_DAY time field. - * @param minute The value used to set the MINUTE time field. - * @param second The value used to set the SECOND time field. - * @stable ICU 2.0 - */ - void set(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second); - - /** - * Clears the values of all the time fields, making them both unset and assigning - * them a value of zero. The field values will be determined during the next - * resolving of time into time fields. - * @stable ICU 2.0 - */ - void clear(void); - -#ifndef U_HIDE_DEPRECATED_API - /** - * Clears the value in the given time field, both making it unset and assigning it a - * value of zero. This field value will be determined during the next resolving of - * time into time fields. - * - * @param field The time field to be cleared. - * @deprecated ICU 2.6. Use clear(UCalendarDateFields field) instead. - */ - void clear(EDateFields field); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Clears the value in the given time field, both making it unset and assigning it a - * value of zero. This field value will be determined during the next resolving of - * time into time fields. - * - * @param field The time field to be cleared. - * @stable ICU 2.6. - */ - void clear(UCalendarDateFields field); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual method. This method is to - * implement a simple version of RTTI, since not all C++ compilers support genuine - * RTTI. Polymorphic operator==() and clone() methods call this method. - *

- * Concrete subclasses of Calendar must implement getDynamicClassID() and also a - * static method and data member: - * - * static UClassID getStaticClassID() { return (UClassID)&fgClassID; } - * static char fgClassID; - * - * @return The class ID for this object. All objects of a given class have the - * same class ID. Objects of other classes have different class IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const = 0; - - /** - * Returns the calendar type name string for this Calendar object. - * The returned string is the legacy ICU calendar attribute value, - * for example, "gregorian" or "japanese". - * - * See type="old type name" for the calendar attribute of locale IDs - * at http://www.unicode.org/reports/tr35/#Key_Type_Definitions - * - * Sample code for getting the LDML/BCP 47 calendar key value: - * \code - * const char *calType = cal->getType(); - * if (0 == strcmp(calType, "unknown")) { - * // deal with unknown calendar type - * } else { - * string localeID("root@calendar="); - * localeID.append(calType); - * char langTag[100]; - * UErrorCode errorCode = U_ZERO_ERROR; - * int32_t length = uloc_toLanguageTag(localeID.c_str(), langTag, (int32_t)sizeof(langTag), TRUE, &errorCode); - * if (U_FAILURE(errorCode)) { - * // deal with errors & overflow - * } - * string lang(langTag, length); - * size_t caPos = lang.find("-ca-"); - * lang.erase(0, caPos + 4); - * // lang now contains the LDML calendar type - * } - * \endcode - * - * @return legacy calendar type name string - * @stable ICU 49 - */ - virtual const char * getType() const = 0; - - /** - * Returns whether the given day of the week is a weekday, a weekend day, - * or a day that transitions from one to the other, for the locale and - * calendar system associated with this Calendar (the locale's region is - * often the most determinant factor). If a transition occurs at midnight, - * then the days before and after the transition will have the - * type UCAL_WEEKDAY or UCAL_WEEKEND. If a transition occurs at a time - * other than midnight, then the day of the transition will have - * the type UCAL_WEEKEND_ONSET or UCAL_WEEKEND_CEASE. In this case, the - * method getWeekendTransition() will return the point of - * transition. - * @param dayOfWeek The day of the week whose type is desired (UCAL_SUNDAY..UCAL_SATURDAY). - * @param status The error code for the operation. - * @return The UCalendarWeekdayType for the day of the week. - * @stable ICU 4.4 - */ - virtual UCalendarWeekdayType getDayOfWeekType(UCalendarDaysOfWeek dayOfWeek, UErrorCode &status) const; - - /** - * Returns the time during the day at which the weekend begins or ends in - * this calendar system. If getDayOfWeekType() returns UCAL_WEEKEND_ONSET - * for the specified dayOfWeek, return the time at which the weekend begins. - * If getDayOfWeekType() returns UCAL_WEEKEND_CEASE for the specified dayOfWeek, - * return the time at which the weekend ends. If getDayOfWeekType() returns - * some other UCalendarWeekdayType for the specified dayOfWeek, is it an error condition - * (U_ILLEGAL_ARGUMENT_ERROR). - * @param dayOfWeek The day of the week for which the weekend transition time is - * desired (UCAL_SUNDAY..UCAL_SATURDAY). - * @param status The error code for the operation. - * @return The milliseconds after midnight at which the weekend begins or ends. - * @stable ICU 4.4 - */ - virtual int32_t getWeekendTransition(UCalendarDaysOfWeek dayOfWeek, UErrorCode &status) const; - - /** - * Returns TRUE if the given UDate is in the weekend in - * this calendar system. - * @param date The UDate in question. - * @param status The error code for the operation. - * @return TRUE if the given UDate is in the weekend in - * this calendar system, FALSE otherwise. - * @stable ICU 4.4 - */ - virtual UBool isWeekend(UDate date, UErrorCode &status) const; - - /** - * Returns TRUE if this Calendar's current date-time is in the weekend in - * this calendar system. - * @return TRUE if this Calendar's current date-time is in the weekend in - * this calendar system, FALSE otherwise. - * @stable ICU 4.4 - */ - virtual UBool isWeekend(void) const; - -protected: - - /** - * Constructs a Calendar with the default time zone as returned by - * TimeZone::createInstance(), and the default locale. - * - * @param success Indicates the status of Calendar object construction. Returns - * U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - Calendar(UErrorCode& success); - - /** - * Copy constructor - * - * @param source Calendar object to be copied from - * @stable ICU 2.0 - */ - Calendar(const Calendar& source); - - /** - * Default assignment operator - * - * @param right Calendar object to be copied - * @stable ICU 2.0 - */ - Calendar& operator=(const Calendar& right); - - /** - * Constructs a Calendar with the given time zone and locale. Clients are no longer - * responsible for deleting the given time zone object after it's adopted. - * - * @param zone The given time zone. - * @param aLocale The given locale. - * @param success Indicates the status of Calendar object construction. Returns - * U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - Calendar(TimeZone* zone, const Locale& aLocale, UErrorCode& success); - - /** - * Constructs a Calendar with the given time zone and locale. - * - * @param zone The given time zone. - * @param aLocale The given locale. - * @param success Indicates the status of Calendar object construction. Returns - * U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - Calendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& success); - - /** - * Converts Calendar's time field values to GMT as milliseconds. - * - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @stable ICU 2.0 - */ - virtual void computeTime(UErrorCode& status); - - /** - * Converts GMT as milliseconds to time field values. This allows you to sync up the - * time field values with a new time that is set for the calendar. This method - * does NOT recompute the time first; to recompute the time, then the fields, use - * the method complete(). - * - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @stable ICU 2.0 - */ - virtual void computeFields(UErrorCode& status); - - /** - * Gets this Calendar's current time as a long. - * - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @return the current time as UTC milliseconds from the epoch. - * @stable ICU 2.0 - */ - double getTimeInMillis(UErrorCode& status) const; - - /** - * Sets this Calendar's current time from the given long value. - * @param millis the new time in UTC milliseconds from the epoch. - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @stable ICU 2.0 - */ - void setTimeInMillis( double millis, UErrorCode& status ); - - /** - * Recomputes the current time from currently set fields, and then fills in any - * unset fields in the time field list. - * - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - * @stable ICU 2.0 - */ - void complete(UErrorCode& status); - -#ifndef U_HIDE_DEPRECATED_API - /** - * Gets the value for a given time field. Subclasses can use this function to get - * field values without forcing recomputation of time. - * - * @param field The given time field. - * @return The value for the given time field. - * @deprecated ICU 2.6. Use internalGet(UCalendarDateFields field) instead. - */ - inline int32_t internalGet(EDateFields field) const {return fFields[field];} -#endif /* U_HIDE_DEPRECATED_API */ - -#ifndef U_HIDE_INTERNAL_API - /** - * Gets the value for a given time field. Subclasses can use this function to get - * field values without forcing recomputation of time. If the field's stamp is UNSET, - * the defaultValue is used. - * - * @param field The given time field. - * @param defaultValue a default value used if the field is unset. - * @return The value for the given time field. - * @internal - */ - inline int32_t internalGet(UCalendarDateFields field, int32_t defaultValue) const {return fStamp[field]>kUnset ? fFields[field] : defaultValue;} - - /** - * Gets the value for a given time field. Subclasses can use this function to get - * field values without forcing recomputation of time. - * - * @param field The given time field. - * @return The value for the given time field. - * @internal - */ - inline int32_t internalGet(UCalendarDateFields field) const {return fFields[field];} -#endif /* U_HIDE_INTERNAL_API */ - -#ifndef U_HIDE_DEPRECATED_API - /** - * Sets the value for a given time field. This is a fast internal method for - * subclasses. It does not affect the areFieldsInSync, isTimeSet, or areAllFieldsSet - * flags. - * - * @param field The given time field. - * @param value The value for the given time field. - * @deprecated ICU 2.6. Use internalSet(UCalendarDateFields field, int32_t value) instead. - */ - void internalSet(EDateFields field, int32_t value); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Sets the value for a given time field. This is a fast internal method for - * subclasses. It does not affect the areFieldsInSync, isTimeSet, or areAllFieldsSet - * flags. - * - * @param field The given time field. - * @param value The value for the given time field. - * @stable ICU 2.6. - */ - inline void internalSet(UCalendarDateFields field, int32_t value); - - /** - * Prepare this calendar for computing the actual minimum or maximum. - * This method modifies this calendar's fields; it is called on a - * temporary calendar. - * @internal - */ - virtual void prepareGetActual(UCalendarDateFields field, UBool isMinimum, UErrorCode &status); - - /** - * Limit enums. Not in sync with UCalendarLimitType (refers to internal fields). - * @internal - */ - enum ELimitType { -#ifndef U_HIDE_INTERNAL_API - UCAL_LIMIT_MINIMUM = 0, - UCAL_LIMIT_GREATEST_MINIMUM, - UCAL_LIMIT_LEAST_MAXIMUM, - UCAL_LIMIT_MAXIMUM, - UCAL_LIMIT_COUNT -#endif /* U_HIDE_INTERNAL_API */ - }; - - /** - * Subclass API for defining limits of different types. - * Subclasses must implement this method to return limits for the - * following fields: - * - *

UCAL_ERA
-     * UCAL_YEAR
-     * UCAL_MONTH
-     * UCAL_WEEK_OF_YEAR
-     * UCAL_WEEK_OF_MONTH
-     * UCAL_DATE (DAY_OF_MONTH on Java)
-     * UCAL_DAY_OF_YEAR
-     * UCAL_DAY_OF_WEEK_IN_MONTH
-     * UCAL_YEAR_WOY
-     * UCAL_EXTENDED_YEAR
- * - * @param field one of the above field numbers - * @param limitType one of MINIMUM, GREATEST_MINIMUM, - * LEAST_MAXIMUM, or MAXIMUM - * @internal - */ - virtual int32_t handleGetLimit(UCalendarDateFields field, ELimitType limitType) const = 0; - - /** - * Return a limit for a field. - * @param field the field, from 0..UCAL_MAX_FIELD - * @param limitType the type specifier for the limit - * @see #ELimitType - * @internal - */ - virtual int32_t getLimit(UCalendarDateFields field, ELimitType limitType) const; - - - /** - * Return the Julian day number of day before the first day of the - * given month in the given extended year. Subclasses should override - * this method to implement their calendar system. - * @param eyear the extended year - * @param month the zero-based month, or 0 if useMonth is false - * @param useMonth if false, compute the day before the first day of - * the given year, otherwise, compute the day before the first day of - * the given month - * @return the Julian day number of the day before the first - * day of the given month and year - * @internal - */ - virtual int32_t handleComputeMonthStart(int32_t eyear, int32_t month, - UBool useMonth) const = 0; - - /** - * Return the number of days in the given month of the given extended - * year of this calendar system. Subclasses should override this - * method if they can provide a more correct or more efficient - * implementation than the default implementation in Calendar. - * @internal - */ - virtual int32_t handleGetMonthLength(int32_t extendedYear, int32_t month) const ; - - /** - * Return the number of days in the given extended year of this - * calendar system. Subclasses should override this method if they can - * provide a more correct or more efficient implementation than the - * default implementation in Calendar. - * @stable ICU 2.0 - */ - virtual int32_t handleGetYearLength(int32_t eyear) const; - - - /** - * Return the extended year defined by the current fields. This will - * use the UCAL_EXTENDED_YEAR field or the UCAL_YEAR and supra-year fields (such - * as UCAL_ERA) specific to the calendar system, depending on which set of - * fields is newer. - * @return the extended year - * @internal - */ - virtual int32_t handleGetExtendedYear() = 0; - - /** - * Subclasses may override this. This method calls - * handleGetMonthLength() to obtain the calendar-specific month - * length. - * @param bestField which field to use to calculate the date - * @return julian day specified by calendar fields. - * @internal - */ - virtual int32_t handleComputeJulianDay(UCalendarDateFields bestField); - - /** - * Subclasses must override this to convert from week fields - * (YEAR_WOY and WEEK_OF_YEAR) to an extended year in the case - * where YEAR, EXTENDED_YEAR are not set. - * The Calendar implementation assumes yearWoy is in extended gregorian form - * @return the extended year, UCAL_EXTENDED_YEAR - * @internal - */ - virtual int32_t handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy); - - /** - * Validate a single field of this calendar. Subclasses should - * override this method to validate any calendar-specific fields. - * Generic fields can be handled by - * Calendar::validateField(). - * @see #validateField(int, int, int, int&) - * @internal - */ - virtual void validateField(UCalendarDateFields field, UErrorCode &status); - -#ifndef U_HIDE_INTERNAL_API - /** - * Compute the Julian day from fields. Will determine whether to use - * the JULIAN_DAY field directly, or other fields. - * @return the julian day - * @internal - */ - int32_t computeJulianDay(); - - /** - * Compute the milliseconds in the day from the fields. This is a - * value from 0 to 23:59:59.999 inclusive, unless fields are out of - * range, in which case it can be an arbitrary value. This value - * reflects local zone wall time. - * @internal - */ - int32_t computeMillisInDay(); - - /** - * This method can assume EXTENDED_YEAR has been set. - * @param millis milliseconds of the date fields - * @param millisInDay milliseconds of the time fields; may be out - * or range. - * @param ec Output param set to failure code on function return - * when this function fails. - * @internal - */ - int32_t computeZoneOffset(double millis, int32_t millisInDay, UErrorCode &ec); - - - /** - * Determine the best stamp in a range. - * @param start first enum to look at - * @param end last enum to look at - * @param bestSoFar stamp prior to function call - * @return the stamp value of the best stamp - * @internal - */ - int32_t newestStamp(UCalendarDateFields start, UCalendarDateFields end, int32_t bestSoFar) const; - - /** - * Values for field resolution tables - * @see #resolveFields - * @internal - */ - enum { - /** Marker for end of resolve set (row or group). */ - kResolveSTOP = -1, - /** Value to be bitwised "ORed" against resolve table field values for remapping. Example: (UCAL_DATE | kResolveRemap) in 1st column will cause 'UCAL_DATE' to be returned, but will not examine the value of UCAL_DATE. */ - kResolveRemap = 32 - }; - - /** - * Precedence table for Dates - * @see #resolveFields - * @internal - */ - static const UFieldResolutionTable kDatePrecedence[]; - - /** - * Precedence table for Year - * @see #resolveFields - * @internal - */ - static const UFieldResolutionTable kYearPrecedence[]; - - /** - * Precedence table for Day of Week - * @see #resolveFields - * @internal - */ - static const UFieldResolutionTable kDOWPrecedence[]; - - /** - * Given a precedence table, return the newest field combination in - * the table, or UCAL_FIELD_COUNT if none is found. - * - *

The precedence table is a 3-dimensional array of integers. It - * may be thought of as an array of groups. Each group is an array of - * lines. Each line is an array of field numbers. Within a line, if - * all fields are set, then the time stamp of the line is taken to be - * the stamp of the most recently set field. If any field of a line is - * unset, then the line fails to match. Within a group, the line with - * the newest time stamp is selected. The first field of the line is - * returned to indicate which line matched. - * - *

In some cases, it may be desirable to map a line to field that - * whose stamp is NOT examined. For example, if the best field is - * DAY_OF_WEEK then the DAY_OF_WEEK_IN_MONTH algorithm may be used. In - * order to do this, insert the value kResolveRemap | F at - * the start of the line, where F is the desired return - * field value. This field will NOT be examined; it only determines - * the return value if the other fields in the line are the newest. - * - *

If all lines of a group contain at least one unset field, then no - * line will match, and the group as a whole will fail to match. In - * that case, the next group will be processed. If all groups fail to - * match, then UCAL_FIELD_COUNT is returned. - * @internal - */ - UCalendarDateFields resolveFields(const UFieldResolutionTable *precedenceTable); -#endif /* U_HIDE_INTERNAL_API */ - - - /** - * @internal - */ - virtual const UFieldResolutionTable* getFieldResolutionTable() const; - -#ifndef U_HIDE_INTERNAL_API - /** - * Return the field that is newer, either defaultField, or - * alternateField. If neither is newer or neither is set, return defaultField. - * @internal - */ - UCalendarDateFields newerField(UCalendarDateFields defaultField, UCalendarDateFields alternateField) const; -#endif /* U_HIDE_INTERNAL_API */ - - -private: - /** - * Helper function for calculating limits by trial and error - * @param field The field being investigated - * @param startValue starting (least max) value of field - * @param endValue ending (greatest max) value of field - * @param status return type - * @internal - */ - int32_t getActualHelper(UCalendarDateFields field, int32_t startValue, int32_t endValue, UErrorCode &status) const; - - -protected: - /** - * The flag which indicates if the current time is set in the calendar. - * @stable ICU 2.0 - */ - UBool fIsTimeSet; - - /** - * True if the fields are in sync with the currently set time of this Calendar. - * If false, then the next attempt to get the value of a field will - * force a recomputation of all fields from the current value of the time - * field. - *

- * This should really be named areFieldsInSync, but the old name is retained - * for backward compatibility. - * @stable ICU 2.0 - */ - UBool fAreFieldsSet; - - /** - * True if all of the fields have been set. This is initially false, and set to - * true by computeFields(). - * @stable ICU 2.0 - */ - UBool fAreAllFieldsSet; - - /** - * True if all fields have been virtually set, but have not yet been - * computed. This occurs only in setTimeInMillis(). A calendar set - * to this state will compute all fields from the time if it becomes - * necessary, but otherwise will delay such computation. - * @stable ICU 3.0 - */ - UBool fAreFieldsVirtuallySet; - - /** - * Get the current time without recomputing. - * - * @return the current time without recomputing. - * @stable ICU 2.0 - */ - UDate internalGetTime(void) const { return fTime; } - - /** - * Set the current time without affecting flags or fields. - * - * @param time The time to be set - * @return the current time without recomputing. - * @stable ICU 2.0 - */ - void internalSetTime(UDate time) { fTime = time; } - - /** - * The time fields containing values into which the millis is computed. - * @stable ICU 2.0 - */ - int32_t fFields[UCAL_FIELD_COUNT]; - - /** - * The flags which tell if a specified time field for the calendar is set. - * @deprecated ICU 2.8 use (fStamp[n]!=kUnset) - */ - UBool fIsSet[UCAL_FIELD_COUNT]; - - /** Special values of stamp[] - * @stable ICU 2.0 - */ - enum { - kUnset = 0, - kInternallySet, - kMinimumUserStamp - }; - - /** - * Pseudo-time-stamps which specify when each field was set. There - * are two special values, UNSET and INTERNALLY_SET. Values from - * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values. - * @stable ICU 2.0 - */ - int32_t fStamp[UCAL_FIELD_COUNT]; - - /** - * Subclasses may override this method to compute several fields - * specific to each calendar system. These are: - * - *

  • ERA - *
  • YEAR - *
  • MONTH - *
  • DAY_OF_MONTH - *
  • DAY_OF_YEAR - *
  • EXTENDED_YEAR
- * - * Subclasses can refer to the DAY_OF_WEEK and DOW_LOCAL fields, which - * will be set when this method is called. Subclasses can also call - * the getGregorianXxx() methods to obtain Gregorian calendar - * equivalents for the given Julian day. - * - *

In addition, subclasses should compute any subclass-specific - * fields, that is, fields from BASE_FIELD_COUNT to - * getFieldCount() - 1. - * - *

The default implementation in Calendar implements - * a pure proleptic Gregorian calendar. - * @internal - */ - virtual void handleComputeFields(int32_t julianDay, UErrorCode &status); - -#ifndef U_HIDE_INTERNAL_API - /** - * Return the extended year on the Gregorian calendar as computed by - * computeGregorianFields(). - * @internal - */ - int32_t getGregorianYear() const { - return fGregorianYear; - } - - /** - * Return the month (0-based) on the Gregorian calendar as computed by - * computeGregorianFields(). - * @internal - */ - int32_t getGregorianMonth() const { - return fGregorianMonth; - } - - /** - * Return the day of year (1-based) on the Gregorian calendar as - * computed by computeGregorianFields(). - * @internal - */ - int32_t getGregorianDayOfYear() const { - return fGregorianDayOfYear; - } - - /** - * Return the day of month (1-based) on the Gregorian calendar as - * computed by computeGregorianFields(). - * @internal - */ - int32_t getGregorianDayOfMonth() const { - return fGregorianDayOfMonth; - } -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Called by computeJulianDay. Returns the default month (0-based) for the year, - * taking year and era into account. Defaults to 0 for Gregorian, which doesn't care. - * @param eyear The extended year - * @internal - */ - virtual int32_t getDefaultMonthInYear(int32_t eyear) ; - - - /** - * Called by computeJulianDay. Returns the default day (1-based) for the month, - * taking currently-set year and era into account. Defaults to 1 for Gregorian. - * @param eyear the extended year - * @param month the month in the year - * @internal - */ - virtual int32_t getDefaultDayInMonth(int32_t eyear, int32_t month); - - //------------------------------------------------------------------------- - // Protected utility methods for use by subclasses. These are very handy - // for implementing add, roll, and computeFields. - //------------------------------------------------------------------------- - - /** - * Adjust the specified field so that it is within - * the allowable range for the date to which this calendar is set. - * For example, in a Gregorian calendar pinning the {@link #UCalendarDateFields DAY_OF_MONTH} - * field for a calendar set to April 31 would cause it to be set - * to April 30. - *

- * Subclassing: - *
- * This utility method is intended for use by subclasses that need to implement - * their own overrides of {@link #roll roll} and {@link #add add}. - *

- * Note: - * pinField is implemented in terms of - * {@link #getActualMinimum getActualMinimum} - * and {@link #getActualMaximum getActualMaximum}. If either of those methods uses - * a slow, iterative algorithm for a particular field, it would be - * unwise to attempt to call pinField for that field. If you - * really do need to do so, you should override this method to do - * something more efficient for that field. - *

- * @param field The calendar field whose value should be pinned. - * @param status Output param set to failure code on function return - * when this function fails. - * - * @see #getActualMinimum - * @see #getActualMaximum - * @stable ICU 2.0 - */ - virtual void pinField(UCalendarDateFields field, UErrorCode& status); - - /** - * Return the week number of a day, within a period. This may be the week number in - * a year or the week number in a month. Usually this will be a value >= 1, but if - * some initial days of the period are excluded from week 1, because - * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} is > 1, then - * the week number will be zero for those - * initial days. This method requires the day number and day of week for some - * known date in the period in order to determine the day of week - * on the desired day. - *

- * Subclassing: - *
- * This method is intended for use by subclasses in implementing their - * {@link #computeTime computeTime} and/or {@link #computeFields computeFields} methods. - * It is often useful in {@link #getActualMinimum getActualMinimum} and - * {@link #getActualMaximum getActualMaximum} as well. - *

- * This variant is handy for computing the week number of some other - * day of a period (often the first or last day of the period) when its day - * of the week is not known but the day number and day of week for some other - * day in the period (e.g. the current date) is known. - *

- * @param desiredDay The {@link #UCalendarDateFields DAY_OF_YEAR} or - * {@link #UCalendarDateFields DAY_OF_MONTH} whose week number is desired. - * Should be 1 for the first day of the period. - * - * @param dayOfPeriod The {@link #UCalendarDateFields DAY_OF_YEAR} - * or {@link #UCalendarDateFields DAY_OF_MONTH} for a day in the period whose - * {@link #UCalendarDateFields DAY_OF_WEEK} is specified by the - * knownDayOfWeek parameter. - * Should be 1 for first day of period. - * - * @param dayOfWeek The {@link #UCalendarDateFields DAY_OF_WEEK} for the day - * corresponding to the knownDayOfPeriod parameter. - * 1-based with 1=Sunday. - * - * @return The week number (one-based), or zero if the day falls before - * the first week because - * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} - * is more than one. - * - * @stable ICU 2.8 - */ - int32_t weekNumber(int32_t desiredDay, int32_t dayOfPeriod, int32_t dayOfWeek); - - -#ifndef U_HIDE_INTERNAL_API - /** - * Return the week number of a day, within a period. This may be the week number in - * a year, or the week number in a month. Usually this will be a value >= 1, but if - * some initial days of the period are excluded from week 1, because - * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} is > 1, - * then the week number will be zero for those - * initial days. This method requires the day of week for the given date in order to - * determine the result. - *

- * Subclassing: - *
- * This method is intended for use by subclasses in implementing their - * {@link #computeTime computeTime} and/or {@link #computeFields computeFields} methods. - * It is often useful in {@link #getActualMinimum getActualMinimum} and - * {@link #getActualMaximum getActualMaximum} as well. - *

- * @param dayOfPeriod The {@link #UCalendarDateFields DAY_OF_YEAR} or - * {@link #UCalendarDateFields DAY_OF_MONTH} whose week number is desired. - * Should be 1 for the first day of the period. - * - * @param dayOfWeek The {@link #UCalendarDateFields DAY_OF_WEEK} for the day - * corresponding to the dayOfPeriod parameter. - * 1-based with 1=Sunday. - * - * @return The week number (one-based), or zero if the day falls before - * the first week because - * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} - * is more than one. - * @internal - */ - inline int32_t weekNumber(int32_t dayOfPeriod, int32_t dayOfWeek); - - /** - * returns the local DOW, valid range 0..6 - * @internal - */ - int32_t getLocalDOW(); -#endif /* U_HIDE_INTERNAL_API */ - -private: - - /** - * The next available value for fStamp[] - */ - int32_t fNextStamp;// = MINIMUM_USER_STAMP; - - /** - * Recalculates the time stamp array (fStamp). - * Resets fNextStamp to lowest next stamp value. - */ - void recalculateStamp(); - - /** - * The current time set for the calendar. - */ - UDate fTime; - - /** - * @see #setLenient - */ - UBool fLenient; - - /** - * Time zone affects the time calculation done by Calendar. Calendar subclasses use - * the time zone data to produce the local time. Always set; never NULL. - */ - TimeZone* fZone; - - /** - * Option for rpeated wall time - * @see #setRepeatedWallTimeOption - */ - UCalendarWallTimeOption fRepeatedWallTime; - - /** - * Option for skipped wall time - * @see #setSkippedWallTimeOption - */ - UCalendarWallTimeOption fSkippedWallTime; - - /** - * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent. They are - * used to figure out the week count for a specific date for a given locale. These - * must be set when a Calendar is constructed. For example, in US locale, - * firstDayOfWeek is SUNDAY; minimalDaysInFirstWeek is 1. They are used to figure - * out the week count for a specific date for a given locale. These must be set when - * a Calendar is constructed. - */ - UCalendarDaysOfWeek fFirstDayOfWeek; - uint8_t fMinimalDaysInFirstWeek; - UCalendarDaysOfWeek fWeekendOnset; - int32_t fWeekendOnsetMillis; - UCalendarDaysOfWeek fWeekendCease; - int32_t fWeekendCeaseMillis; - - /** - * Sets firstDayOfWeek and minimalDaysInFirstWeek. Called at Calendar construction - * time. - * - * @param desiredLocale The given locale. - * @param type The calendar type identifier, e.g: gregorian, buddhist, etc. - * @param success Indicates the status of setting the week count data from - * the resource for the given locale. Returns U_ZERO_ERROR if - * constructed successfully. - */ - void setWeekData(const Locale& desiredLocale, const char *type, UErrorCode& success); - - /** - * Recompute the time and update the status fields isTimeSet - * and areFieldsSet. Callers should check isTimeSet and only - * call this method if isTimeSet is false. - * - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid or restricted by - * leniency, this will be set to an error status. - */ - void updateTime(UErrorCode& status); - - /** - * The Gregorian year, as computed by computeGregorianFields() and - * returned by getGregorianYear(). - * @see #computeGregorianFields - */ - int32_t fGregorianYear; - - /** - * The Gregorian month, as computed by computeGregorianFields() and - * returned by getGregorianMonth(). - * @see #computeGregorianFields - */ - int32_t fGregorianMonth; - - /** - * The Gregorian day of the year, as computed by - * computeGregorianFields() and returned by getGregorianDayOfYear(). - * @see #computeGregorianFields - */ - int32_t fGregorianDayOfYear; - - /** - * The Gregorian day of the month, as computed by - * computeGregorianFields() and returned by getGregorianDayOfMonth(). - * @see #computeGregorianFields - */ - int32_t fGregorianDayOfMonth; - - /* calculations */ - - /** - * Compute the Gregorian calendar year, month, and day of month from - * the given Julian day. These values are not stored in fields, but in - * member variables gregorianXxx. Also compute the DAY_OF_WEEK and - * DOW_LOCAL fields. - */ - void computeGregorianAndDOWFields(int32_t julianDay, UErrorCode &ec); - -protected: - - /** - * Compute the Gregorian calendar year, month, and day of month from the - * Julian day. These values are not stored in fields, but in member - * variables gregorianXxx. They are used for time zone computations and by - * subclasses that are Gregorian derivatives. Subclasses may call this - * method to perform a Gregorian calendar millis->fields computation. - */ - void computeGregorianFields(int32_t julianDay, UErrorCode &ec); - -private: - - /** - * Compute the fields WEEK_OF_YEAR, YEAR_WOY, WEEK_OF_MONTH, - * DAY_OF_WEEK_IN_MONTH, and DOW_LOCAL from EXTENDED_YEAR, YEAR, - * DAY_OF_WEEK, and DAY_OF_YEAR. The latter fields are computed by the - * subclass based on the calendar system. - * - *

The YEAR_WOY field is computed simplistically. It is equal to YEAR - * most of the time, but at the year boundary it may be adjusted to YEAR-1 - * or YEAR+1 to reflect the overlap of a week into an adjacent year. In - * this case, a simple increment or decrement is performed on YEAR, even - * though this may yield an invalid YEAR value. For instance, if the YEAR - * is part of a calendar system with an N-year cycle field CYCLE, then - * incrementing the YEAR may involve incrementing CYCLE and setting YEAR - * back to 0 or 1. This is not handled by this code, and in fact cannot be - * simply handled without having subclasses define an entire parallel set of - * fields for fields larger than or equal to a year. This additional - * complexity is not warranted, since the intention of the YEAR_WOY field is - * to support ISO 8601 notation, so it will typically be used with a - * proleptic Gregorian calendar, which has no field larger than a year. - */ - void computeWeekFields(UErrorCode &ec); - - - /** - * Ensure that each field is within its valid range by calling {@link - * #validateField(int, int&)} on each field that has been set. This method - * should only be called if this calendar is not lenient. - * @see #isLenient - * @see #validateField(int, int&) - * @internal - */ - void validateFields(UErrorCode &status); - - /** - * Validate a single field of this calendar given its minimum and - * maximum allowed value. If the field is out of range, - * U_ILLEGAL_ARGUMENT_ERROR will be set. Subclasses may - * use this method in their implementation of {@link - * #validateField(int, int&)}. - * @internal - */ - void validateField(UCalendarDateFields field, int32_t min, int32_t max, UErrorCode& status); - - protected: -#ifndef U_HIDE_INTERNAL_API - /** - * Convert a quasi Julian date to the day of the week. The Julian date used here is - * not a true Julian date, since it is measured from midnight, not noon. Return - * value is one-based. - * - * @param julian The given Julian date number. - * @return Day number from 1..7 (SUN..SAT). - * @internal - */ - static uint8_t julianDayToDayOfWeek(double julian); -#endif /* U_HIDE_INTERNAL_API */ - - private: - char validLocale[ULOC_FULLNAME_CAPACITY]; - char actualLocale[ULOC_FULLNAME_CAPACITY]; - - public: -#if !UCONFIG_NO_SERVICE - /** - * INTERNAL FOR 2.6 -- Registration. - */ - -#ifndef U_HIDE_INTERNAL_API - /** - * Return a StringEnumeration over the locales available at the time of the call, - * including registered locales. - * @return a StringEnumeration over the locales available at the time of the call - * @internal - */ - static StringEnumeration* getAvailableLocales(void); - - /** - * Register a new Calendar factory. The factory will be adopted. - * INTERNAL in 2.6 - * - * Because ICU may choose to cache Calendars internally, this must - * be called at application startup, prior to any calls to - * Calendar::createInstance to avoid undefined behavior. - * - * @param toAdopt the factory instance to be adopted - * @param status the in/out status code, no special meanings are assigned - * @return a registry key that can be used to unregister this factory - * @internal - */ - static URegistryKey registerFactory(ICUServiceFactory* toAdopt, UErrorCode& status); - - /** - * Unregister a previously-registered CalendarFactory using the key returned from the - * register call. Key becomes invalid after a successful call and should not be used again. - * The CalendarFactory corresponding to the key will be deleted. - * INTERNAL in 2.6 - * - * Because ICU may choose to cache Calendars internally, this should - * be called during application shutdown, after all calls to - * Calendar::createInstance to avoid undefined behavior. - * - * @param key the registry key returned by a previous call to registerFactory - * @param status the in/out status code, no special meanings are assigned - * @return TRUE if the factory for the key was successfully unregistered - * @internal - */ - static UBool unregister(URegistryKey key, UErrorCode& status); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Multiple Calendar Implementation - * @internal - */ - friend class CalendarFactory; - - /** - * Multiple Calendar Implementation - * @internal - */ - friend class CalendarService; - - /** - * Multiple Calendar Implementation - * @internal - */ - friend class DefaultCalendarFactory; -#endif /* !UCONFIG_NO_SERVICE */ - - /** - * @return TRUE if this calendar has a default century (i.e. 03 -> 2003) - * @internal - */ - virtual UBool haveDefaultCentury() const = 0; - - /** - * @return the start of the default century, as a UDate - * @internal - */ - virtual UDate defaultCenturyStart() const = 0; - /** - * @return the beginning year of the default century, as a year - * @internal - */ - virtual int32_t defaultCenturyStartYear() const = 0; - - /** Get the locale for this calendar object. You can choose between valid and actual locale. - * @param type type of the locale we're looking for (valid or actual) - * @param status error code for the operation - * @return the locale - * @stable ICU 2.8 - */ - Locale getLocale(ULocDataLocaleType type, UErrorCode &status) const; - - /** - * @return The related Gregorian year; will be obtained by modifying the value - * obtained by get from UCAL_EXTENDED_YEAR field - * @internal - */ - virtual int32_t getRelatedYear(UErrorCode &status) const; - - /** - * @param year The related Gregorian year to set; will be modified as necessary then - * set in UCAL_EXTENDED_YEAR field - * @internal - */ - virtual void setRelatedYear(int32_t year); - -#ifndef U_HIDE_INTERNAL_API - /** Get the locale for this calendar object. You can choose between valid and actual locale. - * @param type type of the locale we're looking for (valid or actual) - * @param status error code for the operation - * @return the locale - * @internal - */ - const char* getLocaleID(ULocDataLocaleType type, UErrorCode &status) const; -#endif /* U_HIDE_INTERNAL_API */ - -private: - /** - * Cast TimeZone used by this object to BasicTimeZone, or NULL if the TimeZone - * is not an instance of BasicTimeZone. - */ - BasicTimeZone* getBasicTimeZone() const; - - /** - * Find the previous zone transtion near the given time. - * @param base The base time, inclusive - * @param transitionTime Receives the result time - * @param status The error status - * @return TRUE if a transition is found. - */ - UBool getImmediatePreviousZoneTransition(UDate base, UDate *transitionTime, UErrorCode& status) const; - -public: -#ifndef U_HIDE_INTERNAL_API - /** - * Creates a new Calendar from a Locale for the cache. - * This method does not set the time or timezone in returned calendar. - * @param locale the locale. - * @param status any error returned here. - * @return the new Calendar object with no time or timezone set. - * @internal For ICU use only. - */ - static Calendar * U_EXPORT2 makeInstance( - const Locale &locale, UErrorCode &status); - - /** - * Get the calendar type for given locale. - * @param locale the locale - * @param typeBuffer calendar type returned here - * @param typeBufferSize The size of typeBuffer in bytes. If the type - * can't fit in the buffer, this method sets status to - * U_BUFFER_OVERFLOW_ERROR - * @param status error, if any, returned here. - * @internal For ICU use only. - */ - static void U_EXPORT2 getCalendarTypeFromLocale( - const Locale &locale, - char *typeBuffer, - int32_t typeBufferSize, - UErrorCode &status); -#endif /* U_HIDE_INTERNAL_API */ -}; - -// ------------------------------------- - -inline Calendar* -Calendar::createInstance(TimeZone* zone, UErrorCode& errorCode) -{ - // since the Locale isn't specified, use the default locale - return createInstance(zone, Locale::getDefault(), errorCode); -} - -// ------------------------------------- - -inline void -Calendar::roll(UCalendarDateFields field, UBool up, UErrorCode& status) -{ - roll(field, (int32_t)(up ? +1 : -1), status); -} - -#ifndef U_HIDE_DEPRECATED_API -inline void -Calendar::roll(EDateFields field, UBool up, UErrorCode& status) -{ - roll((UCalendarDateFields) field, up, status); -} -#endif /* U_HIDE_DEPRECATED_API */ - - -// ------------------------------------- - -/** - * Fast method for subclasses. The caller must maintain fUserSetDSTOffset and - * fUserSetZoneOffset, as well as the isSet[] array. - */ - -inline void -Calendar::internalSet(UCalendarDateFields field, int32_t value) -{ - fFields[field] = value; - fStamp[field] = kInternallySet; - fIsSet[field] = TRUE; // Remove later -} - - -#ifndef U_HIDE_INTERNAL_API -inline int32_t Calendar::weekNumber(int32_t dayOfPeriod, int32_t dayOfWeek) -{ - return weekNumber(dayOfPeriod, dayOfPeriod, dayOfWeek); -} -#endif /* U_HIDE_INTERNAL_API */ - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _CALENDAR diff --git a/win32/include/spidermonkey/unicode/caniter.h b/win32/include/spidermonkey/unicode/caniter.h deleted file mode 100755 index 7c1bf6af..00000000 --- a/win32/include/spidermonkey/unicode/caniter.h +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * Copyright (C) 1996-2014, International Business Machines Corporation and - * others. All Rights Reserved. - ******************************************************************************* - */ - -#ifndef CANITER_H -#define CANITER_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_NORMALIZATION - -#include "unicode/uobject.h" -#include "unicode/unistr.h" - -/** - * \file - * \brief C++ API: Canonical Iterator - */ - -/** Should permutation skip characters with combining class zero - * Should be either TRUE or FALSE. This is a compile time option - * @stable ICU 2.4 - */ -#ifndef CANITER_SKIP_ZEROES -#define CANITER_SKIP_ZEROES TRUE -#endif - -U_NAMESPACE_BEGIN - -class Hashtable; -class Normalizer2; -class Normalizer2Impl; - -/** - * This class allows one to iterate through all the strings that are canonically equivalent to a given - * string. For example, here are some sample results: -Results for: {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA} -1: \\u0041\\u030A\\u0064\\u0307\\u0327 - = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA} -2: \\u0041\\u030A\\u0064\\u0327\\u0307 - = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE} -3: \\u0041\\u030A\\u1E0B\\u0327 - = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA} -4: \\u0041\\u030A\\u1E11\\u0307 - = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE} -5: \\u00C5\\u0064\\u0307\\u0327 - = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA} -6: \\u00C5\\u0064\\u0327\\u0307 - = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE} -7: \\u00C5\\u1E0B\\u0327 - = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA} -8: \\u00C5\\u1E11\\u0307 - = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE} -9: \\u212B\\u0064\\u0307\\u0327 - = {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA} -10: \\u212B\\u0064\\u0327\\u0307 - = {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE} -11: \\u212B\\u1E0B\\u0327 - = {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA} -12: \\u212B\\u1E11\\u0307 - = {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE} - *
Note: the code is intended for use with small strings, and is not suitable for larger ones, - * since it has not been optimized for that situation. - * Note, CanonicalIterator is not intended to be subclassed. - * @author M. Davis - * @author C++ port by V. Weinstein - * @stable ICU 2.4 - */ -class U_COMMON_API CanonicalIterator U_FINAL : public UObject { -public: - /** - * Construct a CanonicalIterator object - * @param source string to get results for - * @param status Fill-in parameter which receives the status of this operation. - * @stable ICU 2.4 - */ - CanonicalIterator(const UnicodeString &source, UErrorCode &status); - - /** Destructor - * Cleans pieces - * @stable ICU 2.4 - */ - virtual ~CanonicalIterator(); - - /** - * Gets the NFD form of the current source we are iterating over. - * @return gets the source: NOTE: it is the NFD form of source - * @stable ICU 2.4 - */ - UnicodeString getSource(); - - /** - * Resets the iterator so that one can start again from the beginning. - * @stable ICU 2.4 - */ - void reset(); - - /** - * Get the next canonically equivalent string. - *
Warning: The strings are not guaranteed to be in any particular order. - * @return the next string that is canonically equivalent. A bogus string is returned when - * the iteration is done. - * @stable ICU 2.4 - */ - UnicodeString next(); - - /** - * Set a new source for this iterator. Allows object reuse. - * @param newSource the source string to iterate against. This allows the same iterator to be used - * while changing the source string, saving object creation. - * @param status Fill-in parameter which receives the status of this operation. - * @stable ICU 2.4 - */ - void setSource(const UnicodeString &newSource, UErrorCode &status); - -#ifndef U_HIDE_INTERNAL_API - /** - * Dumb recursive implementation of permutation. - * TODO: optimize - * @param source the string to find permutations for - * @param skipZeros determine if skip zeros - * @param result the results in a set. - * @param status Fill-in parameter which receives the status of this operation. - * @internal - */ - static void U_EXPORT2 permute(UnicodeString &source, UBool skipZeros, Hashtable *result, UErrorCode &status); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - -private: - // ===================== PRIVATES ============================== - // private default constructor - CanonicalIterator(); - - - /** - * Copy constructor. Private for now. - * @internal - */ - CanonicalIterator(const CanonicalIterator& other); - - /** - * Assignment operator. Private for now. - * @internal - */ - CanonicalIterator& operator=(const CanonicalIterator& other); - - // fields - UnicodeString source; - UBool done; - - // 2 dimensional array holds the pieces of the string with - // their different canonically equivalent representations - UnicodeString **pieces; - int32_t pieces_length; - int32_t *pieces_lengths; - - // current is used in iterating to combine pieces - int32_t *current; - int32_t current_length; - - // transient fields - UnicodeString buffer; - - const Normalizer2 &nfd; - const Normalizer2Impl &nfcImpl; - - // we have a segment, in NFD. Find all the strings that are canonically equivalent to it. - UnicodeString *getEquivalents(const UnicodeString &segment, int32_t &result_len, UErrorCode &status); //private String[] getEquivalents(String segment) - - //Set getEquivalents2(String segment); - Hashtable *getEquivalents2(Hashtable *fillinResult, const UChar *segment, int32_t segLen, UErrorCode &status); - //Hashtable *getEquivalents2(const UnicodeString &segment, int32_t segLen, UErrorCode &status); - - /** - * See if the decomposition of cp2 is at segment starting at segmentPos - * (with canonical rearrangment!) - * If so, take the remainder, and return the equivalents - */ - //Set extract(int comp, String segment, int segmentPos, StringBuffer buffer); - Hashtable *extract(Hashtable *fillinResult, UChar32 comp, const UChar *segment, int32_t segLen, int32_t segmentPos, UErrorCode &status); - //Hashtable *extract(UChar32 comp, const UnicodeString &segment, int32_t segLen, int32_t segmentPos, UErrorCode &status); - - void cleanPieces(); - -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_NORMALIZATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/chariter.h b/win32/include/spidermonkey/unicode/chariter.h deleted file mode 100755 index 07d1ca3d..00000000 --- a/win32/include/spidermonkey/unicode/chariter.h +++ /dev/null @@ -1,724 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************** -* -* Copyright (C) 1997-2011, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************** -*/ - -#ifndef CHARITER_H -#define CHARITER_H - -#include "unicode/utypes.h" -#include "unicode/uobject.h" -#include "unicode/unistr.h" -/** - * \file - * \brief C++ API: Character Iterator - */ - -U_NAMESPACE_BEGIN -/** - * Abstract class that defines an API for forward-only iteration - * on text objects. - * This is a minimal interface for iteration without random access - * or backwards iteration. It is especially useful for wrapping - * streams with converters into an object for collation or - * normalization. - * - *

Characters can be accessed in two ways: as code units or as - * code points. - * Unicode code points are 21-bit integers and are the scalar values - * of Unicode characters. ICU uses the type UChar32 for them. - * Unicode code units are the storage units of a given - * Unicode/UCS Transformation Format (a character encoding scheme). - * With UTF-16, all code points can be represented with either one - * or two code units ("surrogates"). - * String storage is typically based on code units, while properties - * of characters are typically determined using code point values. - * Some processes may be designed to work with sequences of code units, - * or it may be known that all characters that are important to an - * algorithm can be represented with single code units. - * Other processes will need to use the code point access functions.

- * - *

ForwardCharacterIterator provides nextPostInc() to access - * a code unit and advance an internal position into the text object, - * similar to a return text[position++].
- * It provides next32PostInc() to access a code point and advance an internal - * position.

- * - *

next32PostInc() assumes that the current position is that of - * the beginning of a code point, i.e., of its first code unit. - * After next32PostInc(), this will be true again. - * In general, access to code units and code points in the same - * iteration loop should not be mixed. In UTF-16, if the current position - * is on a second code unit (Low Surrogate), then only that code unit - * is returned even by next32PostInc().

- * - *

For iteration with either function, there are two ways to - * check for the end of the iteration. When there are no more - * characters in the text object: - *

    - *
  • The hasNext() function returns FALSE.
  • - *
  • nextPostInc() and next32PostInc() return DONE - * when one attempts to read beyond the end of the text object.
  • - *
- * - * Example: - * \code - * void function1(ForwardCharacterIterator &it) { - * UChar32 c; - * while(it.hasNext()) { - * c=it.next32PostInc(); - * // use c - * } - * } - * - * void function1(ForwardCharacterIterator &it) { - * UChar c; - * while((c=it.nextPostInc())!=ForwardCharacterIterator::DONE) { - * // use c - * } - * } - * \endcode - *

- * - * @stable ICU 2.0 - */ -class U_COMMON_API ForwardCharacterIterator : public UObject { -public: - /** - * Value returned by most of ForwardCharacterIterator's functions - * when the iterator has reached the limits of its iteration. - * @stable ICU 2.0 - */ - enum { DONE = 0xffff }; - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~ForwardCharacterIterator(); - - /** - * Returns true when both iterators refer to the same - * character in the same character-storage object. - * @param that The ForwardCharacterIterator to be compared for equality - * @return true when both iterators refer to the same - * character in the same character-storage object - * @stable ICU 2.0 - */ - virtual UBool operator==(const ForwardCharacterIterator& that) const = 0; - - /** - * Returns true when the iterators refer to different - * text-storage objects, or to different characters in the - * same text-storage object. - * @param that The ForwardCharacterIterator to be compared for inequality - * @return true when the iterators refer to different - * text-storage objects, or to different characters in the - * same text-storage object - * @stable ICU 2.0 - */ - inline UBool operator!=(const ForwardCharacterIterator& that) const; - - /** - * Generates a hash code for this iterator. - * @return the hash code. - * @stable ICU 2.0 - */ - virtual int32_t hashCode(void) const = 0; - - /** - * Returns a UClassID for this ForwardCharacterIterator ("poor man's - * RTTI").

Despite the fact that this function is public, - * DO NOT CONSIDER IT PART OF CHARACTERITERATOR'S API! - * @return a UClassID for this ForwardCharacterIterator - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const = 0; - - /** - * Gets the current code unit for returning and advances to the next code unit - * in the iteration range - * (toward endIndex()). If there are - * no more code units to return, returns DONE. - * @return the current code unit. - * @stable ICU 2.0 - */ - virtual UChar nextPostInc(void) = 0; - - /** - * Gets the current code point for returning and advances to the next code point - * in the iteration range - * (toward endIndex()). If there are - * no more code points to return, returns DONE. - * @return the current code point. - * @stable ICU 2.0 - */ - virtual UChar32 next32PostInc(void) = 0; - - /** - * Returns FALSE if there are no more code units or code points - * at or after the current position in the iteration range. - * This is used with nextPostInc() or next32PostInc() in forward - * iteration. - * @returns FALSE if there are no more code units or code points - * at or after the current position in the iteration range. - * @stable ICU 2.0 - */ - virtual UBool hasNext() = 0; - -protected: - /** Default constructor to be overridden in the implementing class. @stable ICU 2.0*/ - ForwardCharacterIterator(); - - /** Copy constructor to be overridden in the implementing class. @stable ICU 2.0*/ - ForwardCharacterIterator(const ForwardCharacterIterator &other); - - /** - * Assignment operator to be overridden in the implementing class. - * @stable ICU 2.0 - */ - ForwardCharacterIterator &operator=(const ForwardCharacterIterator&) { return *this; } -}; - -/** - * Abstract class that defines an API for iteration - * on text objects. - * This is an interface for forward and backward iteration - * and random access into a text object. - * - *

The API provides backward compatibility to the Java and older ICU - * CharacterIterator classes but extends them significantly: - *

    - *
  1. CharacterIterator is now a subclass of ForwardCharacterIterator.
  2. - *
  3. While the old API functions provided forward iteration with - * "pre-increment" semantics, the new one also provides functions - * with "post-increment" semantics. They are more efficient and should - * be the preferred iterator functions for new implementations. - * The backward iteration always had "pre-decrement" semantics, which - * are efficient.
  4. - *
  5. Just like ForwardCharacterIterator, it provides access to - * both code units and code points. Code point access versions are available - * for the old and the new iteration semantics.
  6. - *
  7. There are new functions for setting and moving the current position - * without returning a character, for efficiency.
  8. - *
- * - * See ForwardCharacterIterator for examples for using the new forward iteration - * functions. For backward iteration, there is also a hasPrevious() function - * that can be used analogously to hasNext(). - * The old functions work as before and are shown below.

- * - *

Examples for some of the new functions:

- * - * Forward iteration with hasNext(): - * \code - * void forward1(CharacterIterator &it) { - * UChar32 c; - * for(it.setToStart(); it.hasNext();) { - * c=it.next32PostInc(); - * // use c - * } - * } - * \endcode - * Forward iteration more similar to loops with the old forward iteration, - * showing a way to convert simple for() loops: - * \code - * void forward2(CharacterIterator &it) { - * UChar c; - * for(c=it.firstPostInc(); c!=CharacterIterator::DONE; c=it.nextPostInc()) { - * // use c - * } - * } - * \endcode - * Backward iteration with setToEnd() and hasPrevious(): - * \code - * void backward1(CharacterIterator &it) { - * UChar32 c; - * for(it.setToEnd(); it.hasPrevious();) { - * c=it.previous32(); - * // use c - * } - * } - * \endcode - * Backward iteration with a more traditional for() loop: - * \code - * void backward2(CharacterIterator &it) { - * UChar c; - * for(c=it.last(); c!=CharacterIterator::DONE; c=it.previous()) { - * // use c - * } - * } - * \endcode - * - * Example for random access: - * \code - * void random(CharacterIterator &it) { - * // set to the third code point from the beginning - * it.move32(3, CharacterIterator::kStart); - * // get a code point from here without moving the position - * UChar32 c=it.current32(); - * // get the position - * int32_t pos=it.getIndex(); - * // get the previous code unit - * UChar u=it.previous(); - * // move back one more code unit - * it.move(-1, CharacterIterator::kCurrent); - * // set the position back to where it was - * // and read the same code point c and move beyond it - * it.setIndex(pos); - * if(c!=it.next32PostInc()) { - * exit(1); // CharacterIterator inconsistent - * } - * } - * \endcode - * - *

Examples, especially for the old API:

- * - * Function processing characters, in this example simple output - *
- * \code
- *  void processChar( UChar c )
- *  {
- *      cout << " " << c;
- *  }
- * \endcode
- * 
- * Traverse the text from start to finish - *
 
- * \code
- *  void traverseForward(CharacterIterator& iter)
- *  {
- *      for(UChar c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
- *          processChar(c);
- *      }
- *  }
- * \endcode
- * 
- * Traverse the text backwards, from end to start - *
- * \code
- *  void traverseBackward(CharacterIterator& iter)
- *  {
- *      for(UChar c = iter.last(); c != CharacterIterator.DONE; c = iter.previous()) {
- *          processChar(c);
- *      }
- *  }
- * \endcode
- * 
- * Traverse both forward and backward from a given position in the text. - * Calls to notBoundary() in this example represents some additional stopping criteria. - *
- * \code
- * void traverseOut(CharacterIterator& iter, int32_t pos)
- * {
- *      UChar c;
- *      for (c = iter.setIndex(pos);
- *      c != CharacterIterator.DONE && (Unicode::isLetter(c) || Unicode::isDigit(c));
- *          c = iter.next()) {}
- *      int32_t end = iter.getIndex();
- *      for (c = iter.setIndex(pos);
- *          c != CharacterIterator.DONE && (Unicode::isLetter(c) || Unicode::isDigit(c));
- *          c = iter.previous()) {}
- *      int32_t start = iter.getIndex() + 1;
- *  
- *      cout << "start: " << start << " end: " << end << endl;
- *      for (c = iter.setIndex(start); iter.getIndex() < end; c = iter.next() ) {
- *          processChar(c);
- *     }
- *  }
- * \endcode
- * 
- * Creating a StringCharacterIterator and calling the test functions - *
- * \code
- *  void CharacterIterator_Example( void )
- *   {
- *       cout << endl << "===== CharacterIterator_Example: =====" << endl;
- *       UnicodeString text("Ein kleiner Satz.");
- *       StringCharacterIterator iterator(text);
- *       cout << "----- traverseForward: -----------" << endl;
- *       traverseForward( iterator );
- *       cout << endl << endl << "----- traverseBackward: ----------" << endl;
- *       traverseBackward( iterator );
- *       cout << endl << endl << "----- traverseOut: ---------------" << endl;
- *       traverseOut( iterator, 7 );
- *       cout << endl << endl << "-----" << endl;
- *   }
- * \endcode
- * 
- * - * @stable ICU 2.0 - */ -class U_COMMON_API CharacterIterator : public ForwardCharacterIterator { -public: - /** - * Origin enumeration for the move() and move32() functions. - * @stable ICU 2.0 - */ - enum EOrigin { kStart, kCurrent, kEnd }; - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~CharacterIterator(); - - /** - * Returns a pointer to a new CharacterIterator of the same - * concrete class as this one, and referring to the same - * character in the same text-storage object as this one. The - * caller is responsible for deleting the new clone. - * @return a pointer to a new CharacterIterator - * @stable ICU 2.0 - */ - virtual CharacterIterator* clone(void) const = 0; - - /** - * Sets the iterator to refer to the first code unit in its - * iteration range, and returns that code unit. - * This can be used to begin an iteration with next(). - * @return the first code unit in its iteration range. - * @stable ICU 2.0 - */ - virtual UChar first(void) = 0; - - /** - * Sets the iterator to refer to the first code unit in its - * iteration range, returns that code unit, and moves the position - * to the second code unit. This is an alternative to setToStart() - * for forward iteration with nextPostInc(). - * @return the first code unit in its iteration range. - * @stable ICU 2.0 - */ - virtual UChar firstPostInc(void); - - /** - * Sets the iterator to refer to the first code point in its - * iteration range, and returns that code unit, - * This can be used to begin an iteration with next32(). - * Note that an iteration with next32PostInc(), beginning with, - * e.g., setToStart() or firstPostInc(), is more efficient. - * @return the first code point in its iteration range. - * @stable ICU 2.0 - */ - virtual UChar32 first32(void) = 0; - - /** - * Sets the iterator to refer to the first code point in its - * iteration range, returns that code point, and moves the position - * to the second code point. This is an alternative to setToStart() - * for forward iteration with next32PostInc(). - * @return the first code point in its iteration range. - * @stable ICU 2.0 - */ - virtual UChar32 first32PostInc(void); - - /** - * Sets the iterator to refer to the first code unit or code point in its - * iteration range. This can be used to begin a forward - * iteration with nextPostInc() or next32PostInc(). - * @return the start position of the iteration range - * @stable ICU 2.0 - */ - inline int32_t setToStart(); - - /** - * Sets the iterator to refer to the last code unit in its - * iteration range, and returns that code unit. - * This can be used to begin an iteration with previous(). - * @return the last code unit. - * @stable ICU 2.0 - */ - virtual UChar last(void) = 0; - - /** - * Sets the iterator to refer to the last code point in its - * iteration range, and returns that code unit. - * This can be used to begin an iteration with previous32(). - * @return the last code point. - * @stable ICU 2.0 - */ - virtual UChar32 last32(void) = 0; - - /** - * Sets the iterator to the end of its iteration range, just behind - * the last code unit or code point. This can be used to begin a backward - * iteration with previous() or previous32(). - * @return the end position of the iteration range - * @stable ICU 2.0 - */ - inline int32_t setToEnd(); - - /** - * Sets the iterator to refer to the "position"-th code unit - * in the text-storage object the iterator refers to, and - * returns that code unit. - * @param position the "position"-th code unit in the text-storage object - * @return the "position"-th code unit. - * @stable ICU 2.0 - */ - virtual UChar setIndex(int32_t position) = 0; - - /** - * Sets the iterator to refer to the beginning of the code point - * that contains the "position"-th code unit - * in the text-storage object the iterator refers to, and - * returns that code point. - * The current position is adjusted to the beginning of the code point - * (its first code unit). - * @param position the "position"-th code unit in the text-storage object - * @return the "position"-th code point. - * @stable ICU 2.0 - */ - virtual UChar32 setIndex32(int32_t position) = 0; - - /** - * Returns the code unit the iterator currently refers to. - * @return the current code unit. - * @stable ICU 2.0 - */ - virtual UChar current(void) const = 0; - - /** - * Returns the code point the iterator currently refers to. - * @return the current code point. - * @stable ICU 2.0 - */ - virtual UChar32 current32(void) const = 0; - - /** - * Advances to the next code unit in the iteration range - * (toward endIndex()), and returns that code unit. If there are - * no more code units to return, returns DONE. - * @return the next code unit. - * @stable ICU 2.0 - */ - virtual UChar next(void) = 0; - - /** - * Advances to the next code point in the iteration range - * (toward endIndex()), and returns that code point. If there are - * no more code points to return, returns DONE. - * Note that iteration with "pre-increment" semantics is less - * efficient than iteration with "post-increment" semantics - * that is provided by next32PostInc(). - * @return the next code point. - * @stable ICU 2.0 - */ - virtual UChar32 next32(void) = 0; - - /** - * Advances to the previous code unit in the iteration range - * (toward startIndex()), and returns that code unit. If there are - * no more code units to return, returns DONE. - * @return the previous code unit. - * @stable ICU 2.0 - */ - virtual UChar previous(void) = 0; - - /** - * Advances to the previous code point in the iteration range - * (toward startIndex()), and returns that code point. If there are - * no more code points to return, returns DONE. - * @return the previous code point. - * @stable ICU 2.0 - */ - virtual UChar32 previous32(void) = 0; - - /** - * Returns FALSE if there are no more code units or code points - * before the current position in the iteration range. - * This is used with previous() or previous32() in backward - * iteration. - * @return FALSE if there are no more code units or code points - * before the current position in the iteration range, return TRUE otherwise. - * @stable ICU 2.0 - */ - virtual UBool hasPrevious() = 0; - - /** - * Returns the numeric index in the underlying text-storage - * object of the character returned by first(). Since it's - * possible to create an iterator that iterates across only - * part of a text-storage object, this number isn't - * necessarily 0. - * @returns the numeric index in the underlying text-storage - * object of the character returned by first(). - * @stable ICU 2.0 - */ - inline int32_t startIndex(void) const; - - /** - * Returns the numeric index in the underlying text-storage - * object of the position immediately BEYOND the character - * returned by last(). - * @return the numeric index in the underlying text-storage - * object of the position immediately BEYOND the character - * returned by last(). - * @stable ICU 2.0 - */ - inline int32_t endIndex(void) const; - - /** - * Returns the numeric index in the underlying text-storage - * object of the character the iterator currently refers to - * (i.e., the character returned by current()). - * @return the numberic index in the text-storage object of - * the character the iterator currently refers to - * @stable ICU 2.0 - */ - inline int32_t getIndex(void) const; - - /** - * Returns the length of the entire text in the underlying - * text-storage object. - * @return the length of the entire text in the text-storage object - * @stable ICU 2.0 - */ - inline int32_t getLength() const; - - /** - * Moves the current position relative to the start or end of the - * iteration range, or relative to the current position itself. - * The movement is expressed in numbers of code units forward - * or backward by specifying a positive or negative delta. - * @param delta the position relative to origin. A positive delta means forward; - * a negative delta means backward. - * @param origin Origin enumeration {kStart, kCurrent, kEnd} - * @return the new position - * @stable ICU 2.0 - */ - virtual int32_t move(int32_t delta, EOrigin origin) = 0; - - /** - * Moves the current position relative to the start or end of the - * iteration range, or relative to the current position itself. - * The movement is expressed in numbers of code points forward - * or backward by specifying a positive or negative delta. - * @param delta the position relative to origin. A positive delta means forward; - * a negative delta means backward. - * @param origin Origin enumeration {kStart, kCurrent, kEnd} - * @return the new position - * @stable ICU 2.0 - */ - virtual int32_t move32(int32_t delta, EOrigin origin) = 0; - - /** - * Copies the text under iteration into the UnicodeString - * referred to by "result". - * @param result Receives a copy of the text under iteration. - * @stable ICU 2.0 - */ - virtual void getText(UnicodeString& result) = 0; - -protected: - /** - * Empty constructor. - * @stable ICU 2.0 - */ - CharacterIterator(); - - /** - * Constructor, just setting the length field in this base class. - * @stable ICU 2.0 - */ - CharacterIterator(int32_t length); - - /** - * Constructor, just setting the length and position fields in this base class. - * @stable ICU 2.0 - */ - CharacterIterator(int32_t length, int32_t position); - - /** - * Constructor, just setting the length, start, end, and position fields in this base class. - * @stable ICU 2.0 - */ - CharacterIterator(int32_t length, int32_t textBegin, int32_t textEnd, int32_t position); - - /** - * Copy constructor. - * - * @param that The CharacterIterator to be copied - * @stable ICU 2.0 - */ - CharacterIterator(const CharacterIterator &that); - - /** - * Assignment operator. Sets this CharacterIterator to have the same behavior, - * as the one passed in. - * @param that The CharacterIterator passed in. - * @return the newly set CharacterIterator. - * @stable ICU 2.0 - */ - CharacterIterator &operator=(const CharacterIterator &that); - - /** - * Base class text length field. - * Necessary this for correct getText() and hashCode(). - * @stable ICU 2.0 - */ - int32_t textLength; - - /** - * Base class field for the current position. - * @stable ICU 2.0 - */ - int32_t pos; - - /** - * Base class field for the start of the iteration range. - * @stable ICU 2.0 - */ - int32_t begin; - - /** - * Base class field for the end of the iteration range. - * @stable ICU 2.0 - */ - int32_t end; -}; - -inline UBool -ForwardCharacterIterator::operator!=(const ForwardCharacterIterator& that) const { - return !operator==(that); -} - -inline int32_t -CharacterIterator::setToStart() { - return move(0, kStart); -} - -inline int32_t -CharacterIterator::setToEnd() { - return move(0, kEnd); -} - -inline int32_t -CharacterIterator::startIndex(void) const { - return begin; -} - -inline int32_t -CharacterIterator::endIndex(void) const { - return end; -} - -inline int32_t -CharacterIterator::getIndex(void) const { - return pos; -} - -inline int32_t -CharacterIterator::getLength(void) const { - return textLength; -} - -U_NAMESPACE_END -#endif diff --git a/win32/include/spidermonkey/unicode/choicfmt.h b/win32/include/spidermonkey/unicode/choicfmt.h deleted file mode 100755 index ab3c28fe..00000000 --- a/win32/include/spidermonkey/unicode/choicfmt.h +++ /dev/null @@ -1,596 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 1997-2013, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************** -* -* File CHOICFMT.H -* -* Modification History: -* -* Date Name Description -* 02/19/97 aliu Converted from java. -* 03/20/97 helena Finished first cut of implementation and got rid -* of nextDouble/previousDouble and replaced with -* boolean array. -* 4/10/97 aliu Clean up. Modified to work on AIX. -* 8/6/97 nos Removed overloaded constructor, member var 'buffer'. -* 07/22/98 stephen Removed operator!= (implemented in Format) -******************************************************************************** -*/ - -#ifndef CHOICFMT_H -#define CHOICFMT_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Choice Format. - */ - -#if !UCONFIG_NO_FORMATTING -#ifndef U_HIDE_DEPRECATED_API - -#include "unicode/fieldpos.h" -#include "unicode/format.h" -#include "unicode/messagepattern.h" -#include "unicode/numfmt.h" -#include "unicode/unistr.h" - -U_NAMESPACE_BEGIN - -class MessageFormat; - -/** - * ChoiceFormat converts between ranges of numeric values and strings for those ranges. - * The strings must conform to the MessageFormat pattern syntax. - * - *

ChoiceFormat is probably not what you need. - * Please use MessageFormat - * with plural arguments for proper plural selection, - * and select arguments for simple selection among a fixed set of choices!

- * - *

A ChoiceFormat splits - * the real number line \htmlonly-∞ to - * +∞\endhtmlonly into two - * or more contiguous ranges. Each range is mapped to a - * string.

- * - *

ChoiceFormat was originally intended - * for displaying grammatically correct - * plurals such as "There is one file." vs. "There are 2 files." - * However, plural rules for many languages - * are too complex for the capabilities of ChoiceFormat, - * and its requirement of specifying the precise rules for each message - * is unmanageable for translators.

- * - *

There are two methods of defining a ChoiceFormat; both - * are equivalent. The first is by using a string pattern. This is the - * preferred method in most cases. The second method is through direct - * specification of the arrays that logically make up the - * ChoiceFormat.

- * - *

Note: Typically, choice formatting is done (if done at all) via MessageFormat - * with a choice argument type, - * rather than using a stand-alone ChoiceFormat.

- * - *
Patterns and Their Interpretation
- * - *

The pattern string defines the range boundaries and the strings for each number range. - * Syntax: - *

- * choiceStyle = number separator message ('|' number separator message)*
- * number = normal_number | ['-'] \htmlonly∞\endhtmlonly (U+221E, infinity)
- * normal_number = double value (unlocalized ASCII string)
- * separator = less_than | less_than_or_equal
- * less_than = '<'
- * less_than_or_equal = '#' | \htmlonly≤\endhtmlonly (U+2264)
- * message: see {@link MessageFormat}
- * 
- * Pattern_White_Space between syntax elements is ignored, except - * around each range's sub-message.

- * - *

Each numeric sub-range extends from the current range's number - * to the next range's number. - * The number itself is included in its range if a less_than_or_equal sign is used, - * and excluded from its range (and instead included in the previous range) - * if a less_than sign is used.

- * - *

When a ChoiceFormat is constructed from - * arrays of numbers, closure flags and strings, - * they are interpreted just like - * the sequence of (number separator string) in an equivalent pattern string. - * closure[i]==TRUE corresponds to a less_than separator sign. - * The equivalent pattern string will be constructed automatically.

- * - *

During formatting, a number is mapped to the first range - * where the number is not greater than the range's upper limit. - * That range's message string is returned. A NaN maps to the very first range.

- * - *

During parsing, a range is selected for the longest match of - * any range's message. That range's number is returned, ignoring the separator/closure. - * Only a simple string match is performed, without parsing of arguments that - * might be specified in the message strings.

- * - *

Note that the first range's number is ignored in formatting - * but may be returned from parsing.

- * - *
Examples
- * - *

Here is an example of two arrays that map the number - * 1..7 to the English day of the week abbreviations - * Sun..Sat. No closures array is given; this is the same as - * specifying all closures to be FALSE.

- * - *
    {1,2,3,4,5,6,7},
- *     {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}
- * - *

Here is an example that maps the ranges [-Inf, 1), [1, 1], and (1, - * +Inf] to three strings. That is, the number line is split into three - * ranges: x < 1.0, x = 1.0, and x > 1.0. - * (The round parentheses in the notation above indicate an exclusive boundary, - * like the turned bracket in European notation: [-Inf, 1) == [-Inf, 1[ )

- * - *
    {0, 1, 1},
- *     {FALSE, FALSE, TRUE},
- *     {"no files", "one file", "many files"}
- * - *

Here is an example that shows formatting and parsing:

- * - * \code - * #include - * #include - * #include - * - * int main(int argc, char *argv[]) { - * double limits[] = {1,2,3,4,5,6,7}; - * UnicodeString monthNames[] = { - * "Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; - * ChoiceFormat fmt(limits, monthNames, 7); - * UnicodeString str; - * char buf[256]; - * for (double x = 1.0; x <= 8.0; x += 1.0) { - * fmt.format(x, str); - * str.extract(0, str.length(), buf, 256, ""); - * str.truncate(0); - * cout << x << " -> " - * << buf << endl; - * } - * cout << endl; - * return 0; - * } - * \endcode - * - *

User subclasses are not supported. While clients may write - * subclasses, such code will not necessarily work and will not be - * guaranteed to work stably from release to release. - * - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ -class U_I18N_API ChoiceFormat: public NumberFormat { -public: - /** - * Constructs a new ChoiceFormat from the pattern string. - * - * @param pattern Pattern used to construct object. - * @param status Output param to receive success code. If the - * pattern cannot be parsed, set to failure code. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - ChoiceFormat(const UnicodeString& pattern, - UErrorCode& status); - - - /** - * Constructs a new ChoiceFormat with the given limits and message strings. - * All closure flags default to FALSE, - * equivalent to less_than_or_equal separators. - * - * Copies the limits and formats instead of adopting them. - * - * @param limits Array of limit values. - * @param formats Array of formats. - * @param count Size of 'limits' and 'formats' arrays. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - ChoiceFormat(const double* limits, - const UnicodeString* formats, - int32_t count ); - - /** - * Constructs a new ChoiceFormat with the given limits, closure flags and message strings. - * - * Copies the limits and formats instead of adopting them. - * - * @param limits Array of limit values - * @param closures Array of booleans specifying whether each - * element of 'limits' is open or closed. If FALSE, then the - * corresponding limit number is a member of its range. - * If TRUE, then the limit number belongs to the previous range it. - * @param formats Array of formats - * @param count Size of 'limits', 'closures', and 'formats' arrays - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - ChoiceFormat(const double* limits, - const UBool* closures, - const UnicodeString* formats, - int32_t count); - - /** - * Copy constructor. - * - * @param that ChoiceFormat object to be copied from - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - ChoiceFormat(const ChoiceFormat& that); - - /** - * Assignment operator. - * - * @param that ChoiceFormat object to be copied - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - const ChoiceFormat& operator=(const ChoiceFormat& that); - - /** - * Destructor. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual ~ChoiceFormat(); - - /** - * Clones this Format object. The caller owns the - * result and must delete it when done. - * - * @return a copy of this object - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual Format* clone(void) const; - - /** - * Returns true if the given Format objects are semantically equal. - * Objects of different subclasses are considered unequal. - * - * @param other ChoiceFormat object to be compared - * @return true if other is the same as this. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual UBool operator==(const Format& other) const; - - /** - * Sets the pattern. - * @param pattern The pattern to be applied. - * @param status Output param set to success/failure code on - * exit. If the pattern is invalid, this will be - * set to a failure result. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual void applyPattern(const UnicodeString& pattern, - UErrorCode& status); - - /** - * Sets the pattern. - * @param pattern The pattern to be applied. - * @param parseError Struct to receive information on position - * of error if an error is encountered - * @param status Output param set to success/failure code on - * exit. If the pattern is invalid, this will be - * set to a failure result. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual void applyPattern(const UnicodeString& pattern, - UParseError& parseError, - UErrorCode& status); - /** - * Gets the pattern. - * - * @param pattern Output param which will receive the pattern - * Previous contents are deleted. - * @return A reference to 'pattern' - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual UnicodeString& toPattern(UnicodeString &pattern) const; - - /** - * Sets the choices to be used in formatting. - * For details see the constructor with the same parameter list. - * - * @param limitsToCopy Contains the top value that you want - * parsed with that format,and should be in - * ascending sorted order. When formatting X, - * the choice will be the i, where limit[i] - * <= X < limit[i+1]. - * @param formatsToCopy The format strings you want to use for each limit. - * @param count The size of the above arrays. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual void setChoices(const double* limitsToCopy, - const UnicodeString* formatsToCopy, - int32_t count ); - - /** - * Sets the choices to be used in formatting. - * For details see the constructor with the same parameter list. - * - * @param limits Array of limits - * @param closures Array of limit booleans - * @param formats Array of format string - * @param count The size of the above arrays - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual void setChoices(const double* limits, - const UBool* closures, - const UnicodeString* formats, - int32_t count); - - /** - * Returns NULL and 0. - * Before ICU 4.8, this used to return the choice limits array. - * - * @param count Will be set to 0. - * @return NULL - * @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern. - */ - virtual const double* getLimits(int32_t& count) const; - - /** - * Returns NULL and 0. - * Before ICU 4.8, this used to return the limit booleans array. - * - * @param count Will be set to 0. - * @return NULL - * @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern. - */ - virtual const UBool* getClosures(int32_t& count) const; - - /** - * Returns NULL and 0. - * Before ICU 4.8, this used to return the array of choice strings. - * - * @param count Will be set to 0. - * @return NULL - * @deprecated ICU 4.8 Use the MessagePattern class to analyze a ChoiceFormat pattern. - */ - virtual const UnicodeString* getFormats(int32_t& count) const; - - - using NumberFormat::format; - - /** - * Formats a double number using this object's choices. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPosition& pos) const; - /** - * Formats an int32_t number using this object's choices. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPosition& pos) const; - - /** - * Formats an int64_t number using this object's choices. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& appendTo, - FieldPosition& pos) const; - - /** - * Formats an array of objects using this object's choices. - * - * @param objs The array of objects to be formatted. - * @param cnt The size of objs. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param success Output param set to success/failure code on - * exit. - * @return Reference to 'appendTo' parameter. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual UnicodeString& format(const Formattable* objs, - int32_t cnt, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& success) const; - - using NumberFormat::parse; - - /** - * Looks for the longest match of any message string on the input text and, - * if there is a match, sets the result object to the corresponding range's number. - * - * If no string matches, then the parsePosition is unchanged. - * - * @param text The text to be parsed. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param parsePosition The position to start parsing at on input. - * On output, moved to after the last successfully - * parse character. On parse failure, does not change. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual void parse(const UnicodeString& text, - Formattable& result, - ParsePosition& parsePosition) const; - - /** - * Returns a unique class ID POLYMORPHICALLY. Part of ICU's "poor man's RTTI". - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - virtual UClassID getDynamicClassID(void) const; - - /** - * Returns the class ID for this class. This is useful only for - * comparing to a return value from getDynamicClassID(). For example: - *

-     * .       Base* polymorphic_pointer = createPolymorphicObject();
-     * .       if (polymorphic_pointer->getDynamicClassID() ==
-     * .           Derived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @deprecated ICU 49 Use MessageFormat instead, with plural and select arguments. - */ - static UClassID U_EXPORT2 getStaticClassID(void); - -private: - /** - * Converts a double value to a string. - * @param value the double number to be converted. - * @param string the result string. - * @return the converted string. - */ - static UnicodeString& dtos(double value, UnicodeString& string); - - ChoiceFormat(); // default constructor not implemented - - /** - * Construct a new ChoiceFormat with the limits and the corresponding formats - * based on the pattern. - * - * @param newPattern Pattern used to construct object. - * @param parseError Struct to receive information on position - * of error if an error is encountered. - * @param status Output param to receive success code. If the - * pattern cannot be parsed, set to failure code. - */ - ChoiceFormat(const UnicodeString& newPattern, - UParseError& parseError, - UErrorCode& status); - - friend class MessageFormat; - - virtual void setChoices(const double* limits, - const UBool* closures, - const UnicodeString* formats, - int32_t count, - UErrorCode &errorCode); - - /** - * Finds the ChoiceFormat sub-message for the given number. - * @param pattern A MessagePattern. - * @param partIndex the index of the first ChoiceFormat argument style part. - * @param number a number to be mapped to one of the ChoiceFormat argument's intervals - * @return the sub-message start part index. - */ - static int32_t findSubMessage(const MessagePattern &pattern, int32_t partIndex, double number); - - static double parseArgument( - const MessagePattern &pattern, int32_t partIndex, - const UnicodeString &source, ParsePosition &pos); - - /** - * Matches the pattern string from the end of the partIndex to - * the beginning of the limitPartIndex, - * including all syntax except SKIP_SYNTAX, - * against the source string starting at sourceOffset. - * If they match, returns the length of the source string match. - * Otherwise returns -1. - */ - static int32_t matchStringUntilLimitPart( - const MessagePattern &pattern, int32_t partIndex, int32_t limitPartIndex, - const UnicodeString &source, int32_t sourceOffset); - - /** - * Some of the ChoiceFormat constructors do not have a UErrorCode paramater. - * We need _some_ way to provide one for the MessagePattern constructor. - * Alternatively, the MessagePattern could be a pointer field, but that is - * not nice either. - */ - UErrorCode constructorErrorCode; - - /** - * The MessagePattern which contains the parsed structure of the pattern string. - * - * Starting with ICU 4.8, the MessagePattern contains a sequence of - * numeric/selector/message parts corresponding to the parsed pattern. - * For details see the MessagePattern class API docs. - */ - MessagePattern msgPattern; - - /** - * Docs & fields from before ICU 4.8, before MessagePattern was used. - * Commented out, and left only for explanation of semantics. - * -------- - * Each ChoiceFormat divides the range -Inf..+Inf into fCount - * intervals. The intervals are: - * - * 0: fChoiceLimits[0]..fChoiceLimits[1] - * 1: fChoiceLimits[1]..fChoiceLimits[2] - * ... - * fCount-2: fChoiceLimits[fCount-2]..fChoiceLimits[fCount-1] - * fCount-1: fChoiceLimits[fCount-1]..+Inf - * - * Interval 0 is special; during formatting (mapping numbers to - * strings), it also contains all numbers less than - * fChoiceLimits[0], as well as NaN values. - * - * Interval i maps to and from string fChoiceFormats[i]. When - * parsing (mapping strings to numbers), then intervals map to - * their lower limit, that is, interval i maps to fChoiceLimit[i]. - * - * The intervals may be closed, half open, or open. This affects - * formatting but does not affect parsing. Interval i is affected - * by fClosures[i] and fClosures[i+1]. If fClosures[i] - * is FALSE, then the value fChoiceLimits[i] is in interval i. - * That is, intervals i and i are: - * - * i-1: ... x < fChoiceLimits[i] - * i: fChoiceLimits[i] <= x ... - * - * If fClosures[i] is TRUE, then the value fChoiceLimits[i] is - * in interval i-1. That is, intervals i-1 and i are: - * - * i-1: ... x <= fChoiceLimits[i] - * i: fChoiceLimits[i] < x ... - * - * Because of the nature of interval 0, fClosures[0] has no - * effect. - */ - // double* fChoiceLimits; - // UBool* fClosures; - // UnicodeString* fChoiceFormats; - // int32_t fCount; -}; - - -U_NAMESPACE_END - -#endif // U_HIDE_DEPRECATED_API -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // CHOICFMT_H -//eof diff --git a/win32/include/spidermonkey/unicode/coleitr.h b/win32/include/spidermonkey/unicode/coleitr.h deleted file mode 100755 index 4feaa1b5..00000000 --- a/win32/include/spidermonkey/unicode/coleitr.h +++ /dev/null @@ -1,406 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ****************************************************************************** - * Copyright (C) 1997-2014, International Business Machines - * Corporation and others. All Rights Reserved. - ****************************************************************************** - */ - -/** - * \file - * \brief C++ API: Collation Element Iterator. - */ - -/** -* File coleitr.h -* -* Created by: Helena Shih -* -* Modification History: -* -* Date Name Description -* -* 8/18/97 helena Added internal API documentation. -* 08/03/98 erm Synched with 1.2 version CollationElementIterator.java -* 12/10/99 aliu Ported Thai collation support from Java. -* 01/25/01 swquek Modified into a C++ wrapper calling C APIs (ucoliter.h) -* 02/19/01 swquek Removed CollationElementsIterator() since it is -* private constructor and no calls are made to it -* 2012-2014 markus Rewritten in C++ again. -*/ - -#ifndef COLEITR_H -#define COLEITR_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_COLLATION - -#include "unicode/unistr.h" -#include "unicode/uobject.h" - -struct UCollationElements; -struct UHashtable; - -U_NAMESPACE_BEGIN - -struct CollationData; - -class CollationIterator; -class RuleBasedCollator; -class UCollationPCE; -class UVector32; - -/** -* The CollationElementIterator class is used as an iterator to walk through -* each character of an international string. Use the iterator to return the -* ordering priority of the positioned character. The ordering priority of a -* character, which we refer to as a key, defines how a character is collated in -* the given collation object. -* For example, consider the following in Slovak and in traditional Spanish collation: -*
-*        "ca" -> the first key is key('c') and second key is key('a').
-*        "cha" -> the first key is key('ch') and second key is key('a').
-* And in German phonebook collation, -*
 \htmlonly       "æb"-> the first key is key('a'), the second key is key('e'), and
-*        the third key is key('b'). \endhtmlonly 
-* The key of a character, is an integer composed of primary order(short), -* secondary order(char), and tertiary order(char). Java strictly defines the -* size and signedness of its primitive data types. Therefore, the static -* functions primaryOrder(), secondaryOrder(), and tertiaryOrder() return -* int32_t to ensure the correctness of the key value. -*

Example of the iterator usage: (without error checking) -*

-* \code
-*   void CollationElementIterator_Example()
-*   {
-*       UnicodeString str = "This is a test";
-*       UErrorCode success = U_ZERO_ERROR;
-*       RuleBasedCollator* rbc =
-*           (RuleBasedCollator*) RuleBasedCollator::createInstance(success);
-*       CollationElementIterator* c =
-*           rbc->createCollationElementIterator( str );
-*       int32_t order = c->next(success);
-*       c->reset();
-*       order = c->previous(success);
-*       delete c;
-*       delete rbc;
-*   }
-* \endcode
-* 
-*

-* The method next() returns the collation order of the next character based on -* the comparison level of the collator. The method previous() returns the -* collation order of the previous character based on the comparison level of -* the collator. The Collation Element Iterator moves only in one direction -* between calls to reset(), setOffset(), or setText(). That is, next() -* and previous() can not be inter-used. Whenever previous() is to be called after -* next() or vice versa, reset(), setOffset() or setText() has to be called first -* to reset the status, shifting pointers to either the end or the start of -* the string (reset() or setText()), or the specified position (setOffset()). -* Hence at the next call of next() or previous(), the first or last collation order, -* or collation order at the spefcifieid position will be returned. If a change of -* direction is done without one of these calls, the result is undefined. -*

-* The result of a forward iterate (next()) and reversed result of the backward -* iterate (previous()) on the same string are equivalent, if collation orders -* with the value 0 are ignored. -* Character based on the comparison level of the collator. A collation order -* consists of primary order, secondary order and tertiary order. The data -* type of the collation order is int32_t. -* -* Note, CollationElementIterator should not be subclassed. -* @see Collator -* @see RuleBasedCollator -* @version 1.8 Jan 16 2001 -*/ -class U_I18N_API CollationElementIterator U_FINAL : public UObject { -public: - - // CollationElementIterator public data member ------------------------------ - - enum { - /** - * NULLORDER indicates that an error has occured while processing - * @stable ICU 2.0 - */ - NULLORDER = (int32_t)0xffffffff - }; - - // CollationElementIterator public constructor/destructor ------------------- - - /** - * Copy constructor. - * - * @param other the object to be copied from - * @stable ICU 2.0 - */ - CollationElementIterator(const CollationElementIterator& other); - - /** - * Destructor - * @stable ICU 2.0 - */ - virtual ~CollationElementIterator(); - - // CollationElementIterator public methods ---------------------------------- - - /** - * Returns true if "other" is the same as "this" - * - * @param other the object to be compared - * @return true if "other" is the same as "this" - * @stable ICU 2.0 - */ - UBool operator==(const CollationElementIterator& other) const; - - /** - * Returns true if "other" is not the same as "this". - * - * @param other the object to be compared - * @return true if "other" is not the same as "this" - * @stable ICU 2.0 - */ - UBool operator!=(const CollationElementIterator& other) const; - - /** - * Resets the cursor to the beginning of the string. - * @stable ICU 2.0 - */ - void reset(void); - - /** - * Gets the ordering priority of the next character in the string. - * @param status the error code status. - * @return the next character's ordering. otherwise returns NULLORDER if an - * error has occured or if the end of string has been reached - * @stable ICU 2.0 - */ - int32_t next(UErrorCode& status); - - /** - * Get the ordering priority of the previous collation element in the string. - * @param status the error code status. - * @return the previous element's ordering. otherwise returns NULLORDER if an - * error has occured or if the start of string has been reached - * @stable ICU 2.0 - */ - int32_t previous(UErrorCode& status); - - /** - * Gets the primary order of a collation order. - * @param order the collation order - * @return the primary order of a collation order. - * @stable ICU 2.0 - */ - static inline int32_t primaryOrder(int32_t order); - - /** - * Gets the secondary order of a collation order. - * @param order the collation order - * @return the secondary order of a collation order. - * @stable ICU 2.0 - */ - static inline int32_t secondaryOrder(int32_t order); - - /** - * Gets the tertiary order of a collation order. - * @param order the collation order - * @return the tertiary order of a collation order. - * @stable ICU 2.0 - */ - static inline int32_t tertiaryOrder(int32_t order); - - /** - * Return the maximum length of any expansion sequences that end with the - * specified comparison order. - * @param order a collation order returned by previous or next. - * @return maximum size of the expansion sequences ending with the collation - * element or 1 if collation element does not occur at the end of any - * expansion sequence - * @stable ICU 2.0 - */ - int32_t getMaxExpansion(int32_t order) const; - - /** - * Gets the comparison order in the desired strength. Ignore the other - * differences. - * @param order The order value - * @stable ICU 2.0 - */ - int32_t strengthOrder(int32_t order) const; - - /** - * Sets the source string. - * @param str the source string. - * @param status the error code status. - * @stable ICU 2.0 - */ - void setText(const UnicodeString& str, UErrorCode& status); - - /** - * Sets the source string. - * @param str the source character iterator. - * @param status the error code status. - * @stable ICU 2.0 - */ - void setText(CharacterIterator& str, UErrorCode& status); - - /** - * Checks if a comparison order is ignorable. - * @param order the collation order. - * @return TRUE if a character is ignorable, FALSE otherwise. - * @stable ICU 2.0 - */ - static inline UBool isIgnorable(int32_t order); - - /** - * Gets the offset of the currently processed character in the source string. - * @return the offset of the character. - * @stable ICU 2.0 - */ - int32_t getOffset(void) const; - - /** - * Sets the offset of the currently processed character in the source string. - * @param newOffset the new offset. - * @param status the error code status. - * @return the offset of the character. - * @stable ICU 2.0 - */ - void setOffset(int32_t newOffset, UErrorCode& status); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - -#ifndef U_HIDE_INTERNAL_API - /** @internal */ - static inline CollationElementIterator *fromUCollationElements(UCollationElements *uc) { - return reinterpret_cast(uc); - } - /** @internal */ - static inline const CollationElementIterator *fromUCollationElements(const UCollationElements *uc) { - return reinterpret_cast(uc); - } - /** @internal */ - inline UCollationElements *toUCollationElements() { - return reinterpret_cast(this); - } - /** @internal */ - inline const UCollationElements *toUCollationElements() const { - return reinterpret_cast(this); - } -#endif // U_HIDE_INTERNAL_API - -private: - friend class RuleBasedCollator; - friend class UCollationPCE; - - /** - * CollationElementIterator constructor. This takes the source string and the - * collation object. The cursor will walk thru the source string based on the - * predefined collation rules. If the source string is empty, NULLORDER will - * be returned on the calls to next(). - * @param sourceText the source string. - * @param order the collation object. - * @param status the error code status. - */ - CollationElementIterator(const UnicodeString& sourceText, - const RuleBasedCollator* order, UErrorCode& status); - // Note: The constructors should take settings & tailoring, not a collator, - // to avoid circular dependencies. - // However, for operator==() we would need to be able to compare tailoring data for equality - // without making CollationData or CollationTailoring depend on TailoredSet. - // (See the implementation of RuleBasedCollator::operator==().) - // That might require creating an intermediate class that would be used - // by both CollationElementIterator and RuleBasedCollator - // but only contain the part of RBC== related to data and rules. - - /** - * CollationElementIterator constructor. This takes the source string and the - * collation object. The cursor will walk thru the source string based on the - * predefined collation rules. If the source string is empty, NULLORDER will - * be returned on the calls to next(). - * @param sourceText the source string. - * @param order the collation object. - * @param status the error code status. - */ - CollationElementIterator(const CharacterIterator& sourceText, - const RuleBasedCollator* order, UErrorCode& status); - - /** - * Assignment operator - * - * @param other the object to be copied - */ - const CollationElementIterator& - operator=(const CollationElementIterator& other); - - CollationElementIterator(); // default constructor not implemented - - /** Normalizes dir_=1 (just after setOffset()) to dir_=0 (just after reset()). */ - inline int8_t normalizeDir() const { return dir_ == 1 ? 0 : dir_; } - - static UHashtable *computeMaxExpansions(const CollationData *data, UErrorCode &errorCode); - - static int32_t getMaxExpansion(const UHashtable *maxExpansions, int32_t order); - - // CollationElementIterator private data members ---------------------------- - - CollationIterator *iter_; // owned - const RuleBasedCollator *rbc_; // aliased - uint32_t otherHalf_; - /** - * <0: backwards; 0: just after reset() (previous() begins from end); - * 1: just after setOffset(); >1: forward - */ - int8_t dir_; - /** - * Stores offsets from expansions and from unsafe-backwards iteration, - * so that getOffset() returns intermediate offsets for the CEs - * that are consistent with forward iteration. - */ - UVector32 *offsets_; - - UnicodeString string_; -}; - -// CollationElementIterator inline method definitions -------------------------- - -inline int32_t CollationElementIterator::primaryOrder(int32_t order) -{ - return (order >> 16) & 0xffff; -} - -inline int32_t CollationElementIterator::secondaryOrder(int32_t order) -{ - return (order >> 8) & 0xff; -} - -inline int32_t CollationElementIterator::tertiaryOrder(int32_t order) -{ - return order & 0xff; -} - -inline UBool CollationElementIterator::isIgnorable(int32_t order) -{ - return (order & 0xffff0000) == 0; -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_COLLATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/coll.h b/win32/include/spidermonkey/unicode/coll.h deleted file mode 100755 index e41be2ee..00000000 --- a/win32/include/spidermonkey/unicode/coll.h +++ /dev/null @@ -1,1274 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* Copyright (C) 1996-2016, International Business Machines -* Corporation and others. All Rights Reserved. -****************************************************************************** -*/ - -/** - * \file - * \brief C++ API: Collation Service. - */ - -/** -* File coll.h -* -* Created by: Helena Shih -* -* Modification History: -* -* Date Name Description -* 02/5/97 aliu Modified createDefault to load collation data from -* binary files when possible. Added related methods -* createCollationFromFile, chopLocale, createPathName. -* 02/11/97 aliu Added members addToCache, findInCache, and fgCache. -* 02/12/97 aliu Modified to create objects from RuleBasedCollator cache. -* Moved cache out of Collation class. -* 02/13/97 aliu Moved several methods out of this class and into -* RuleBasedCollator, with modifications. Modified -* createDefault() to call new RuleBasedCollator(Locale&) -* constructor. General clean up and documentation. -* 02/20/97 helena Added clone, operator==, operator!=, operator=, copy -* constructor and getDynamicClassID. -* 03/25/97 helena Updated with platform independent data types. -* 05/06/97 helena Added memory allocation error detection. -* 06/20/97 helena Java class name change. -* 09/03/97 helena Added createCollationKeyValues(). -* 02/10/98 damiba Added compare() with length as parameter. -* 04/23/99 stephen Removed EDecompositionMode, merged with -* Normalizer::EMode. -* 11/02/99 helena Collator performance enhancements. Eliminates the -* UnicodeString construction and special case for NO_OP. -* 11/23/99 srl More performance enhancements. Inlining of -* critical accessors. -* 05/15/00 helena Added version information API. -* 01/29/01 synwee Modified into a C++ wrapper which calls C apis -* (ucol.h). -* 2012-2014 markus Rewritten in C++ again. -*/ - -#ifndef COLL_H -#define COLL_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_COLLATION - -#include "unicode/uobject.h" -#include "unicode/ucol.h" -#include "unicode/normlzr.h" -#include "unicode/locid.h" -#include "unicode/uniset.h" -#include "unicode/umisc.h" -#include "unicode/uiter.h" -#include "unicode/stringpiece.h" - -U_NAMESPACE_BEGIN - -class StringEnumeration; - -#if !UCONFIG_NO_SERVICE -/** - * @stable ICU 2.6 - */ -class CollatorFactory; -#endif - -/** -* @stable ICU 2.0 -*/ -class CollationKey; - -/** -* The Collator class performs locale-sensitive string -* comparison.
-* You use this class to build searching and sorting routines for natural -* language text. -*

-* Collator is an abstract base class. Subclasses implement -* specific collation strategies. One subclass, -* RuleBasedCollator, is currently provided and is applicable -* to a wide set of languages. Other subclasses may be created to handle more -* specialized needs. -*

-* Like other locale-sensitive classes, you can use the static factory method, -* createInstance, to obtain the appropriate -* Collator object for a given locale. You will only need to -* look at the subclasses of Collator if you need to -* understand the details of a particular collation strategy or if you need to -* modify that strategy. -*

-* The following example shows how to compare two strings using the -* Collator for the default locale. -* \htmlonly

\endhtmlonly -*
-* \code
-* // Compare two strings in the default locale
-* UErrorCode success = U_ZERO_ERROR;
-* Collator* myCollator = Collator::createInstance(success);
-* if (myCollator->compare("abc", "ABC") < 0)
-*   cout << "abc is less than ABC" << endl;
-* else
-*   cout << "abc is greater than or equal to ABC" << endl;
-* \endcode
-* 
-* \htmlonly
\endhtmlonly -*

-* You can set a Collator's strength attribute to -* determine the level of difference considered significant in comparisons. -* Five strengths are provided: PRIMARY, SECONDARY, -* TERTIARY, QUATERNARY and IDENTICAL. -* The exact assignment of strengths to language features is locale dependent. -* For example, in Czech, "e" and "f" are considered primary differences, -* while "e" and "\u00EA" are secondary differences, "e" and "E" are tertiary -* differences and "e" and "e" are identical. The following shows how both case -* and accents could be ignored for US English. -* \htmlonly

\endhtmlonly -*
-* \code
-* //Get the Collator for US English and set its strength to PRIMARY
-* UErrorCode success = U_ZERO_ERROR;
-* Collator* usCollator = Collator::createInstance(Locale::getUS(), success);
-* usCollator->setStrength(Collator::PRIMARY);
-* if (usCollator->compare("abc", "ABC") == 0)
-*     cout << "'abc' and 'ABC' strings are equivalent with strength PRIMARY" << endl;
-* \endcode
-* 
-* \htmlonly
\endhtmlonly -* -* The getSortKey methods -* convert a string to a series of bytes that can be compared bitwise against -* other sort keys using strcmp(). Sort keys are written as -* zero-terminated byte strings. -* -* Another set of APIs returns a CollationKey object that wraps -* the sort key bytes instead of returning the bytes themselves. -*

-*

-* Note: Collators with different Locale, -* and CollationStrength settings will return different sort -* orders for the same set of strings. Locales have specific collation rules, -* and the way in which secondary and tertiary differences are taken into -* account, for example, will result in a different sorting order for same -* strings. -*

-* @see RuleBasedCollator -* @see CollationKey -* @see CollationElementIterator -* @see Locale -* @see Normalizer -* @version 2.0 11/15/01 -*/ - -class U_I18N_API Collator : public UObject { -public: - - // Collator public enums ----------------------------------------------- - - /** - * Base letter represents a primary difference. Set comparison level to - * PRIMARY to ignore secondary and tertiary differences.
- * Use this to set the strength of a Collator object.
- * Example of primary difference, "abc" < "abd" - * - * Diacritical differences on the same base letter represent a secondary - * difference. Set comparison level to SECONDARY to ignore tertiary - * differences. Use this to set the strength of a Collator object.
- * Example of secondary difference, "ä" >> "a". - * - * Uppercase and lowercase versions of the same character represents a - * tertiary difference. Set comparison level to TERTIARY to include all - * comparison differences. Use this to set the strength of a Collator - * object.
- * Example of tertiary difference, "abc" <<< "ABC". - * - * Two characters are considered "identical" when they have the same unicode - * spellings.
- * For example, "ä" == "ä". - * - * UCollationStrength is also used to determine the strength of sort keys - * generated from Collator objects. - * @stable ICU 2.0 - */ - enum ECollationStrength - { - PRIMARY = UCOL_PRIMARY, // 0 - SECONDARY = UCOL_SECONDARY, // 1 - TERTIARY = UCOL_TERTIARY, // 2 - QUATERNARY = UCOL_QUATERNARY, // 3 - IDENTICAL = UCOL_IDENTICAL // 15 - }; - - - // Cannot use #ifndef U_HIDE_DEPRECATED_API for the following, it is - // used by virtual methods that cannot have that conditional. - /** - * LESS is returned if source string is compared to be less than target - * string in the compare() method. - * EQUAL is returned if source string is compared to be equal to target - * string in the compare() method. - * GREATER is returned if source string is compared to be greater than - * target string in the compare() method. - * @see Collator#compare - * @deprecated ICU 2.6. Use C enum UCollationResult defined in ucol.h - */ - enum EComparisonResult - { - LESS = UCOL_LESS, // -1 - EQUAL = UCOL_EQUAL, // 0 - GREATER = UCOL_GREATER // 1 - }; - - // Collator public destructor ----------------------------------------- - - /** - * Destructor - * @stable ICU 2.0 - */ - virtual ~Collator(); - - // Collator public methods -------------------------------------------- - - /** - * Returns TRUE if "other" is the same as "this". - * - * The base class implementation returns TRUE if "other" has the same type/class as "this": - * typeid(*this) == typeid(other). - * - * Subclass implementations should do something like the following: - *
-     *   if (this == &other) { return TRUE; }
-     *   if (!Collator::operator==(other)) { return FALSE; }  // not the same class
-     *
-     *   const MyCollator &o = (const MyCollator&)other;
-     *   (compare this vs. o's subclass fields)
-     * 
- * @param other Collator object to be compared - * @return TRUE if other is the same as this. - * @stable ICU 2.0 - */ - virtual UBool operator==(const Collator& other) const; - - /** - * Returns true if "other" is not the same as "this". - * Calls ! operator==(const Collator&) const which works for all subclasses. - * @param other Collator object to be compared - * @return TRUE if other is not the same as this. - * @stable ICU 2.0 - */ - virtual UBool operator!=(const Collator& other) const; - - /** - * Makes a copy of this object. - * @return a copy of this object, owned by the caller - * @stable ICU 2.0 - */ - virtual Collator* clone(void) const = 0; - - /** - * Creates the Collator object for the current default locale. - * The default locale is determined by Locale::getDefault. - * The UErrorCode& err parameter is used to return status information to the user. - * To check whether the construction succeeded or not, you should check the - * value of U_SUCCESS(err). If you wish more detailed information, you can - * check for informational error results which still indicate success. - * U_USING_FALLBACK_ERROR indicates that a fall back locale was used. For - * example, 'de_CH' was requested, but nothing was found there, so 'de' was - * used. U_USING_DEFAULT_ERROR indicates that the default locale data was - * used; neither the requested locale nor any of its fall back locales - * could be found. - * The caller owns the returned object and is responsible for deleting it. - * - * @param err the error code status. - * @return the collation object of the default locale.(for example, en_US) - * @see Locale#getDefault - * @stable ICU 2.0 - */ - static Collator* U_EXPORT2 createInstance(UErrorCode& err); - - /** - * Gets the collation object for the desired locale. The - * resource of the desired locale will be loaded. - * - * Locale::getRoot() is the base collation table and all other languages are - * built on top of it with additional language-specific modifications. - * - * For some languages, multiple collation types are available; - * for example, "de@collation=phonebook". - * Starting with ICU 54, collation attributes can be specified via locale keywords as well, - * in the old locale extension syntax ("el@colCaseFirst=upper") - * or in language tag syntax ("el-u-kf-upper"). - * See
User Guide: Collation API. - * - * The UErrorCode& err parameter is used to return status information to the user. - * To check whether the construction succeeded or not, you should check - * the value of U_SUCCESS(err). If you wish more detailed information, you - * can check for informational error results which still indicate success. - * U_USING_FALLBACK_ERROR indicates that a fall back locale was used. For - * example, 'de_CH' was requested, but nothing was found there, so 'de' was - * used. U_USING_DEFAULT_ERROR indicates that the default locale data was - * used; neither the requested locale nor any of its fall back locales - * could be found. - * - * The caller owns the returned object and is responsible for deleting it. - * @param loc The locale ID for which to open a collator. - * @param err the error code status. - * @return the created table-based collation object based on the desired - * locale. - * @see Locale - * @see ResourceLoader - * @stable ICU 2.2 - */ - static Collator* U_EXPORT2 createInstance(const Locale& loc, UErrorCode& err); - - /** - * The comparison function compares the character data stored in two - * different strings. Returns information about whether a string is less - * than, greater than or equal to another string. - * @param source the source string to be compared with. - * @param target the string that is to be compared with the source string. - * @return Returns a byte value. GREATER if source is greater - * than target; EQUAL if source is equal to target; LESS if source is less - * than target - * @deprecated ICU 2.6 use the overload with UErrorCode & - */ - virtual EComparisonResult compare(const UnicodeString& source, - const UnicodeString& target) const; - - /** - * The comparison function compares the character data stored in two - * different strings. Returns information about whether a string is less - * than, greater than or equal to another string. - * @param source the source string to be compared with. - * @param target the string that is to be compared with the source string. - * @param status possible error code - * @return Returns an enum value. UCOL_GREATER if source is greater - * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less - * than target - * @stable ICU 2.6 - */ - virtual UCollationResult compare(const UnicodeString& source, - const UnicodeString& target, - UErrorCode &status) const = 0; - - /** - * Does the same thing as compare but limits the comparison to a specified - * length - * @param source the source string to be compared with. - * @param target the string that is to be compared with the source string. - * @param length the length the comparison is limited to - * @return Returns a byte value. GREATER if source (up to the specified - * length) is greater than target; EQUAL if source (up to specified - * length) is equal to target; LESS if source (up to the specified - * length) is less than target. - * @deprecated ICU 2.6 use the overload with UErrorCode & - */ - virtual EComparisonResult compare(const UnicodeString& source, - const UnicodeString& target, - int32_t length) const; - - /** - * Does the same thing as compare but limits the comparison to a specified - * length - * @param source the source string to be compared with. - * @param target the string that is to be compared with the source string. - * @param length the length the comparison is limited to - * @param status possible error code - * @return Returns an enum value. UCOL_GREATER if source (up to the specified - * length) is greater than target; UCOL_EQUAL if source (up to specified - * length) is equal to target; UCOL_LESS if source (up to the specified - * length) is less than target. - * @stable ICU 2.6 - */ - virtual UCollationResult compare(const UnicodeString& source, - const UnicodeString& target, - int32_t length, - UErrorCode &status) const = 0; - - /** - * The comparison function compares the character data stored in two - * different string arrays. Returns information about whether a string array - * is less than, greater than or equal to another string array. - *

Example of use: - *

-     * .       UChar ABC[] = {0x41, 0x42, 0x43, 0};  // = "ABC"
-     * .       UChar abc[] = {0x61, 0x62, 0x63, 0};  // = "abc"
-     * .       UErrorCode status = U_ZERO_ERROR;
-     * .       Collator *myCollation =
-     * .                         Collator::createInstance(Locale::getUS(), status);
-     * .       if (U_FAILURE(status)) return;
-     * .       myCollation->setStrength(Collator::PRIMARY);
-     * .       // result would be Collator::EQUAL ("abc" == "ABC")
-     * .       // (no primary difference between "abc" and "ABC")
-     * .       Collator::EComparisonResult result =
-     * .                             myCollation->compare(abc, 3, ABC, 3);
-     * .       myCollation->setStrength(Collator::TERTIARY);
-     * .       // result would be Collator::LESS ("abc" <<< "ABC")
-     * .       // (with tertiary difference between "abc" and "ABC")
-     * .       result = myCollation->compare(abc, 3, ABC, 3);
-     * 
- * @param source the source string array to be compared with. - * @param sourceLength the length of the source string array. If this value - * is equal to -1, the string array is null-terminated. - * @param target the string that is to be compared with the source string. - * @param targetLength the length of the target string array. If this value - * is equal to -1, the string array is null-terminated. - * @return Returns a byte value. GREATER if source is greater than target; - * EQUAL if source is equal to target; LESS if source is less than - * target - * @deprecated ICU 2.6 use the overload with UErrorCode & - */ - virtual EComparisonResult compare(const UChar* source, int32_t sourceLength, - const UChar* target, int32_t targetLength) - const; - - /** - * The comparison function compares the character data stored in two - * different string arrays. Returns information about whether a string array - * is less than, greater than or equal to another string array. - * @param source the source string array to be compared with. - * @param sourceLength the length of the source string array. If this value - * is equal to -1, the string array is null-terminated. - * @param target the string that is to be compared with the source string. - * @param targetLength the length of the target string array. If this value - * is equal to -1, the string array is null-terminated. - * @param status possible error code - * @return Returns an enum value. UCOL_GREATER if source is greater - * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less - * than target - * @stable ICU 2.6 - */ - virtual UCollationResult compare(const UChar* source, int32_t sourceLength, - const UChar* target, int32_t targetLength, - UErrorCode &status) const = 0; - - /** - * Compares two strings using the Collator. - * Returns whether the first one compares less than/equal to/greater than - * the second one. - * This version takes UCharIterator input. - * @param sIter the first ("source") string iterator - * @param tIter the second ("target") string iterator - * @param status ICU status - * @return UCOL_LESS, UCOL_EQUAL or UCOL_GREATER - * @stable ICU 4.2 - */ - virtual UCollationResult compare(UCharIterator &sIter, - UCharIterator &tIter, - UErrorCode &status) const; - - /** - * Compares two UTF-8 strings using the Collator. - * Returns whether the first one compares less than/equal to/greater than - * the second one. - * This version takes UTF-8 input. - * Note that a StringPiece can be implicitly constructed - * from a std::string or a NUL-terminated const char * string. - * @param source the first UTF-8 string - * @param target the second UTF-8 string - * @param status ICU status - * @return UCOL_LESS, UCOL_EQUAL or UCOL_GREATER - * @stable ICU 4.2 - */ - virtual UCollationResult compareUTF8(const StringPiece &source, - const StringPiece &target, - UErrorCode &status) const; - - /** - * Transforms the string into a series of characters that can be compared - * with CollationKey::compareTo. It is not possible to restore the original - * string from the chars in the sort key. - *

Use CollationKey::equals or CollationKey::compare to compare the - * generated sort keys. - * If the source string is null, a null collation key will be returned. - * - * Note that sort keys are often less efficient than simply doing comparison. - * For more details, see the ICU User Guide. - * - * @param source the source string to be transformed into a sort key. - * @param key the collation key to be filled in - * @param status the error code status. - * @return the collation key of the string based on the collation rules. - * @see CollationKey#compare - * @stable ICU 2.0 - */ - virtual CollationKey& getCollationKey(const UnicodeString& source, - CollationKey& key, - UErrorCode& status) const = 0; - - /** - * Transforms the string into a series of characters that can be compared - * with CollationKey::compareTo. It is not possible to restore the original - * string from the chars in the sort key. - *

Use CollationKey::equals or CollationKey::compare to compare the - * generated sort keys. - *

If the source string is null, a null collation key will be returned. - * - * Note that sort keys are often less efficient than simply doing comparison. - * For more details, see the ICU User Guide. - * - * @param source the source string to be transformed into a sort key. - * @param sourceLength length of the collation key - * @param key the collation key to be filled in - * @param status the error code status. - * @return the collation key of the string based on the collation rules. - * @see CollationKey#compare - * @stable ICU 2.0 - */ - virtual CollationKey& getCollationKey(const UChar*source, - int32_t sourceLength, - CollationKey& key, - UErrorCode& status) const = 0; - /** - * Generates the hash code for the collation object - * @stable ICU 2.0 - */ - virtual int32_t hashCode(void) const = 0; - - /** - * Gets the locale of the Collator - * - * @param type can be either requested, valid or actual locale. For more - * information see the definition of ULocDataLocaleType in - * uloc.h - * @param status the error code status. - * @return locale where the collation data lives. If the collator - * was instantiated from rules, locale is empty. - * @deprecated ICU 2.8 This API is under consideration for revision - * in ICU 3.0. - */ - virtual Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const = 0; - - /** - * Convenience method for comparing two strings based on the collation rules. - * @param source the source string to be compared with. - * @param target the target string to be compared with. - * @return true if the first string is greater than the second one, - * according to the collation rules. false, otherwise. - * @see Collator#compare - * @stable ICU 2.0 - */ - UBool greater(const UnicodeString& source, const UnicodeString& target) - const; - - /** - * Convenience method for comparing two strings based on the collation rules. - * @param source the source string to be compared with. - * @param target the target string to be compared with. - * @return true if the first string is greater than or equal to the second - * one, according to the collation rules. false, otherwise. - * @see Collator#compare - * @stable ICU 2.0 - */ - UBool greaterOrEqual(const UnicodeString& source, - const UnicodeString& target) const; - - /** - * Convenience method for comparing two strings based on the collation rules. - * @param source the source string to be compared with. - * @param target the target string to be compared with. - * @return true if the strings are equal according to the collation rules. - * false, otherwise. - * @see Collator#compare - * @stable ICU 2.0 - */ - UBool equals(const UnicodeString& source, const UnicodeString& target) const; - - /** - * Determines the minimum strength that will be used in comparison or - * transformation. - *

E.g. with strength == SECONDARY, the tertiary difference is ignored - *

E.g. with strength == PRIMARY, the secondary and tertiary difference - * are ignored. - * @return the current comparison level. - * @see Collator#setStrength - * @deprecated ICU 2.6 Use getAttribute(UCOL_STRENGTH...) instead - */ - virtual ECollationStrength getStrength(void) const; - - /** - * Sets the minimum strength to be used in comparison or transformation. - *

Example of use: - *

-     *  \code
-     *  UErrorCode status = U_ZERO_ERROR;
-     *  Collator*myCollation = Collator::createInstance(Locale::getUS(), status);
-     *  if (U_FAILURE(status)) return;
-     *  myCollation->setStrength(Collator::PRIMARY);
-     *  // result will be "abc" == "ABC"
-     *  // tertiary differences will be ignored
-     *  Collator::ComparisonResult result = myCollation->compare("abc", "ABC");
-     * \endcode
-     * 
- * @see Collator#getStrength - * @param newStrength the new comparison level. - * @deprecated ICU 2.6 Use setAttribute(UCOL_STRENGTH...) instead - */ - virtual void setStrength(ECollationStrength newStrength); - - /** - * Retrieves the reordering codes for this collator. - * @param dest The array to fill with the script ordering. - * @param destCapacity The length of dest. If it is 0, then dest may be NULL and the function - * will only return the length of the result without writing any codes (pre-flighting). - * @param status A reference to an error code value, which must not indicate - * a failure before the function call. - * @return The length of the script ordering array. - * @see ucol_setReorderCodes - * @see Collator#getEquivalentReorderCodes - * @see Collator#setReorderCodes - * @see UScriptCode - * @see UColReorderCode - * @stable ICU 4.8 - */ - virtual int32_t getReorderCodes(int32_t *dest, - int32_t destCapacity, - UErrorCode& status) const; - - /** - * Sets the ordering of scripts for this collator. - * - *

The reordering codes are a combination of script codes and reorder codes. - * @param reorderCodes An array of script codes in the new order. This can be NULL if the - * length is also set to 0. An empty array will clear any reordering codes on the collator. - * @param reorderCodesLength The length of reorderCodes. - * @param status error code - * @see ucol_setReorderCodes - * @see Collator#getReorderCodes - * @see Collator#getEquivalentReorderCodes - * @see UScriptCode - * @see UColReorderCode - * @stable ICU 4.8 - */ - virtual void setReorderCodes(const int32_t* reorderCodes, - int32_t reorderCodesLength, - UErrorCode& status) ; - - /** - * Retrieves the reorder codes that are grouped with the given reorder code. Some reorder - * codes will be grouped and must reorder together. - * Beginning with ICU 55, scripts only reorder together if they are primary-equal, - * for example Hiragana and Katakana. - * - * @param reorderCode The reorder code to determine equivalence for. - * @param dest The array to fill with the script equivalence reordering codes. - * @param destCapacity The length of dest. If it is 0, then dest may be NULL and the - * function will only return the length of the result without writing any codes (pre-flighting). - * @param status A reference to an error code value, which must not indicate - * a failure before the function call. - * @return The length of the of the reordering code equivalence array. - * @see ucol_setReorderCodes - * @see Collator#getReorderCodes - * @see Collator#setReorderCodes - * @see UScriptCode - * @see UColReorderCode - * @stable ICU 4.8 - */ - static int32_t U_EXPORT2 getEquivalentReorderCodes(int32_t reorderCode, - int32_t* dest, - int32_t destCapacity, - UErrorCode& status); - - /** - * Get name of the object for the desired Locale, in the desired langauge - * @param objectLocale must be from getAvailableLocales - * @param displayLocale specifies the desired locale for output - * @param name the fill-in parameter of the return value - * @return display-able name of the object for the object locale in the - * desired language - * @stable ICU 2.0 - */ - static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale, - const Locale& displayLocale, - UnicodeString& name); - - /** - * Get name of the object for the desired Locale, in the langauge of the - * default locale. - * @param objectLocale must be from getAvailableLocales - * @param name the fill-in parameter of the return value - * @return name of the object for the desired locale in the default language - * @stable ICU 2.0 - */ - static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale, - UnicodeString& name); - - /** - * Get the set of Locales for which Collations are installed. - * - *

Note this does not include locales supported by registered collators. - * If collators might have been registered, use the overload of getAvailableLocales - * that returns a StringEnumeration.

- * - * @param count the output parameter of number of elements in the locale list - * @return the list of available locales for which collations are installed - * @stable ICU 2.0 - */ - static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); - - /** - * Return a StringEnumeration over the locales available at the time of the call, - * including registered locales. If a severe error occurs (such as out of memory - * condition) this will return null. If there is no locale data, an empty enumeration - * will be returned. - * @return a StringEnumeration over the locales available at the time of the call - * @stable ICU 2.6 - */ - static StringEnumeration* U_EXPORT2 getAvailableLocales(void); - - /** - * Create a string enumerator of all possible keywords that are relevant to - * collation. At this point, the only recognized keyword for this - * service is "collation". - * @param status input-output error code - * @return a string enumeration over locale strings. The caller is - * responsible for closing the result. - * @stable ICU 3.0 - */ - static StringEnumeration* U_EXPORT2 getKeywords(UErrorCode& status); - - /** - * Given a keyword, create a string enumeration of all values - * for that keyword that are currently in use. - * @param keyword a particular keyword as enumerated by - * ucol_getKeywords. If any other keyword is passed in, status is set - * to U_ILLEGAL_ARGUMENT_ERROR. - * @param status input-output error code - * @return a string enumeration over collation keyword values, or NULL - * upon error. The caller is responsible for deleting the result. - * @stable ICU 3.0 - */ - static StringEnumeration* U_EXPORT2 getKeywordValues(const char *keyword, UErrorCode& status); - - /** - * Given a key and a locale, returns an array of string values in a preferred - * order that would make a difference. These are all and only those values where - * the open (creation) of the service with the locale formed from the input locale - * plus input keyword and that value has different behavior than creation with the - * input locale alone. - * @param keyword one of the keys supported by this service. For now, only - * "collation" is supported. - * @param locale the locale - * @param commonlyUsed if set to true it will return only commonly used values - * with the given locale in preferred order. Otherwise, - * it will return all the available values for the locale. - * @param status ICU status - * @return a string enumeration over keyword values for the given key and the locale. - * @stable ICU 4.2 - */ - static StringEnumeration* U_EXPORT2 getKeywordValuesForLocale(const char* keyword, const Locale& locale, - UBool commonlyUsed, UErrorCode& status); - - /** - * Return the functionally equivalent locale for the given - * requested locale, with respect to given keyword, for the - * collation service. If two locales return the same result, then - * collators instantiated for these locales will behave - * equivalently. The converse is not always true; two collators - * may in fact be equivalent, but return different results, due to - * internal details. The return result has no other meaning than - * that stated above, and implies nothing as to the relationship - * between the two locales. This is intended for use by - * applications who wish to cache collators, or otherwise reuse - * collators when possible. The functional equivalent may change - * over time. For more information, please see the - * Locales and Services section of the ICU User Guide. - * @param keyword a particular keyword as enumerated by - * ucol_getKeywords. - * @param locale the requested locale - * @param isAvailable reference to a fillin parameter that - * indicates whether the requested locale was 'available' to the - * collation service. A locale is defined as 'available' if it - * physically exists within the collation locale data. - * @param status reference to input-output error code - * @return the functionally equivalent collation locale, or the root - * locale upon error. - * @stable ICU 3.0 - */ - static Locale U_EXPORT2 getFunctionalEquivalent(const char* keyword, const Locale& locale, - UBool& isAvailable, UErrorCode& status); - -#if !UCONFIG_NO_SERVICE - /** - * Register a new Collator. The collator will be adopted. - * Because ICU may choose to cache collators internally, this must be - * called at application startup, prior to any calls to - * Collator::createInstance to avoid undefined behavior. - * @param toAdopt the Collator instance to be adopted - * @param locale the locale with which the collator will be associated - * @param status the in/out status code, no special meanings are assigned - * @return a registry key that can be used to unregister this collator - * @stable ICU 2.6 - */ - static URegistryKey U_EXPORT2 registerInstance(Collator* toAdopt, const Locale& locale, UErrorCode& status); - - /** - * Register a new CollatorFactory. The factory will be adopted. - * Because ICU may choose to cache collators internally, this must be - * called at application startup, prior to any calls to - * Collator::createInstance to avoid undefined behavior. - * @param toAdopt the CollatorFactory instance to be adopted - * @param status the in/out status code, no special meanings are assigned - * @return a registry key that can be used to unregister this collator - * @stable ICU 2.6 - */ - static URegistryKey U_EXPORT2 registerFactory(CollatorFactory* toAdopt, UErrorCode& status); - - /** - * Unregister a previously-registered Collator or CollatorFactory - * using the key returned from the register call. Key becomes - * invalid after a successful call and should not be used again. - * The object corresponding to the key will be deleted. - * Because ICU may choose to cache collators internally, this should - * be called during application shutdown, after all calls to - * Collator::createInstance to avoid undefined behavior. - * @param key the registry key returned by a previous call to registerInstance - * @param status the in/out status code, no special meanings are assigned - * @return TRUE if the collator for the key was successfully unregistered - * @stable ICU 2.6 - */ - static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status); -#endif /* UCONFIG_NO_SERVICE */ - - /** - * Gets the version information for a Collator. - * @param info the version # information, the result will be filled in - * @stable ICU 2.0 - */ - virtual void getVersion(UVersionInfo info) const = 0; - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual method. - * This method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * @return The class ID for this object. All objects of a given class have - * the same class ID. Objects of other classes have different class - * IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const = 0; - - /** - * Universal attribute setter - * @param attr attribute type - * @param value attribute value - * @param status to indicate whether the operation went on smoothly or - * there were errors - * @stable ICU 2.2 - */ - virtual void setAttribute(UColAttribute attr, UColAttributeValue value, - UErrorCode &status) = 0; - - /** - * Universal attribute getter - * @param attr attribute type - * @param status to indicate whether the operation went on smoothly or - * there were errors - * @return attribute value - * @stable ICU 2.2 - */ - virtual UColAttributeValue getAttribute(UColAttribute attr, - UErrorCode &status) const = 0; - - /** - * Sets the variable top to the top of the specified reordering group. - * The variable top determines the highest-sorting character - * which is affected by UCOL_ALTERNATE_HANDLING. - * If that attribute is set to UCOL_NON_IGNORABLE, then the variable top has no effect. - * - * The base class implementation sets U_UNSUPPORTED_ERROR. - * @param group one of UCOL_REORDER_CODE_SPACE, UCOL_REORDER_CODE_PUNCTUATION, - * UCOL_REORDER_CODE_SYMBOL, UCOL_REORDER_CODE_CURRENCY; - * or UCOL_REORDER_CODE_DEFAULT to restore the default max variable group - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return *this - * @see getMaxVariable - * @stable ICU 53 - */ - virtual Collator &setMaxVariable(UColReorderCode group, UErrorCode &errorCode); - - /** - * Returns the maximum reordering group whose characters are affected by UCOL_ALTERNATE_HANDLING. - * - * The base class implementation returns UCOL_REORDER_CODE_PUNCTUATION. - * @return the maximum variable reordering group. - * @see setMaxVariable - * @stable ICU 53 - */ - virtual UColReorderCode getMaxVariable() const; - - /** - * Sets the variable top to the primary weight of the specified string. - * - * Beginning with ICU 53, the variable top is pinned to - * the top of one of the supported reordering groups, - * and it must not be beyond the last of those groups. - * See setMaxVariable(). - * @param varTop one or more (if contraction) UChars to which the variable top should be set - * @param len length of variable top string. If -1 it is considered to be zero terminated. - * @param status error code. If error code is set, the return value is undefined. Errors set by this function are:
- * U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction
- * U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond - * the last reordering group supported by setMaxVariable() - * @return variable top primary weight - * @deprecated ICU 53 Call setMaxVariable() instead. - */ - virtual uint32_t setVariableTop(const UChar *varTop, int32_t len, UErrorCode &status) = 0; - - /** - * Sets the variable top to the primary weight of the specified string. - * - * Beginning with ICU 53, the variable top is pinned to - * the top of one of the supported reordering groups, - * and it must not be beyond the last of those groups. - * See setMaxVariable(). - * @param varTop a UnicodeString size 1 or more (if contraction) of UChars to which the variable top should be set - * @param status error code. If error code is set, the return value is undefined. Errors set by this function are:
- * U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction
- * U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond - * the last reordering group supported by setMaxVariable() - * @return variable top primary weight - * @deprecated ICU 53 Call setMaxVariable() instead. - */ - virtual uint32_t setVariableTop(const UnicodeString &varTop, UErrorCode &status) = 0; - - /** - * Sets the variable top to the specified primary weight. - * - * Beginning with ICU 53, the variable top is pinned to - * the top of one of the supported reordering groups, - * and it must not be beyond the last of those groups. - * See setMaxVariable(). - * @param varTop primary weight, as returned by setVariableTop or ucol_getVariableTop - * @param status error code - * @deprecated ICU 53 Call setMaxVariable() instead. - */ - virtual void setVariableTop(uint32_t varTop, UErrorCode &status) = 0; - - /** - * Gets the variable top value of a Collator. - * @param status error code (not changed by function). If error code is set, the return value is undefined. - * @return the variable top primary weight - * @see getMaxVariable - * @stable ICU 2.0 - */ - virtual uint32_t getVariableTop(UErrorCode &status) const = 0; - - /** - * Get a UnicodeSet that contains all the characters and sequences - * tailored in this collator. - * @param status error code of the operation - * @return a pointer to a UnicodeSet object containing all the - * code points and sequences that may sort differently than - * in the root collator. The object must be disposed of by using delete - * @stable ICU 2.4 - */ - virtual UnicodeSet *getTailoredSet(UErrorCode &status) const; - - /** - * Same as clone(). - * The base class implementation simply calls clone(). - * @return a copy of this object, owned by the caller - * @see clone() - * @deprecated ICU 50 no need to have two methods for cloning - */ - virtual Collator* safeClone(void) const; - - /** - * Get the sort key as an array of bytes from a UnicodeString. - * Sort key byte arrays are zero-terminated and can be compared using - * strcmp(). - * - * Note that sort keys are often less efficient than simply doing comparison. - * For more details, see the ICU User Guide. - * - * @param source string to be processed. - * @param result buffer to store result in. If NULL, number of bytes needed - * will be returned. - * @param resultLength length of the result buffer. If if not enough the - * buffer will be filled to capacity. - * @return Number of bytes needed for storing the sort key - * @stable ICU 2.2 - */ - virtual int32_t getSortKey(const UnicodeString& source, - uint8_t* result, - int32_t resultLength) const = 0; - - /** - * Get the sort key as an array of bytes from a UChar buffer. - * Sort key byte arrays are zero-terminated and can be compared using - * strcmp(). - * - * Note that sort keys are often less efficient than simply doing comparison. - * For more details, see the ICU User Guide. - * - * @param source string to be processed. - * @param sourceLength length of string to be processed. - * If -1, the string is 0 terminated and length will be decided by the - * function. - * @param result buffer to store result in. If NULL, number of bytes needed - * will be returned. - * @param resultLength length of the result buffer. If if not enough the - * buffer will be filled to capacity. - * @return Number of bytes needed for storing the sort key - * @stable ICU 2.2 - */ - virtual int32_t getSortKey(const UChar*source, int32_t sourceLength, - uint8_t*result, int32_t resultLength) const = 0; - - /** - * Produce a bound for a given sortkey and a number of levels. - * Return value is always the number of bytes needed, regardless of - * whether the result buffer was big enough or even valid.
- * Resulting bounds can be used to produce a range of strings that are - * between upper and lower bounds. For example, if bounds are produced - * for a sortkey of string "smith", strings between upper and lower - * bounds with one level would include "Smith", "SMITH", "sMiTh".
- * There are two upper bounds that can be produced. If UCOL_BOUND_UPPER - * is produced, strings matched would be as above. However, if bound - * produced using UCOL_BOUND_UPPER_LONG is used, the above example will - * also match "Smithsonian" and similar.
- * For more on usage, see example in cintltst/capitst.c in procedure - * TestBounds. - * Sort keys may be compared using strcmp. - * @param source The source sortkey. - * @param sourceLength The length of source, or -1 if null-terminated. - * (If an unmodified sortkey is passed, it is always null - * terminated). - * @param boundType Type of bound required. It can be UCOL_BOUND_LOWER, which - * produces a lower inclusive bound, UCOL_BOUND_UPPER, that - * produces upper bound that matches strings of the same length - * or UCOL_BOUND_UPPER_LONG that matches strings that have the - * same starting substring as the source string. - * @param noOfLevels Number of levels required in the resulting bound (for most - * uses, the recommended value is 1). See users guide for - * explanation on number of levels a sortkey can have. - * @param result A pointer to a buffer to receive the resulting sortkey. - * @param resultLength The maximum size of result. - * @param status Used for returning error code if something went wrong. If the - * number of levels requested is higher than the number of levels - * in the source key, a warning (U_SORT_KEY_TOO_SHORT_WARNING) is - * issued. - * @return The size needed to fully store the bound. - * @see ucol_keyHashCode - * @stable ICU 2.1 - */ - static int32_t U_EXPORT2 getBound(const uint8_t *source, - int32_t sourceLength, - UColBoundMode boundType, - uint32_t noOfLevels, - uint8_t *result, - int32_t resultLength, - UErrorCode &status); - - -protected: - - // Collator protected constructors ------------------------------------- - - /** - * Default constructor. - * Constructor is different from the old default Collator constructor. - * The task for determing the default collation strength and normalization - * mode is left to the child class. - * @stable ICU 2.0 - */ - Collator(); - -#ifndef U_HIDE_DEPRECATED_API - /** - * Constructor. - * Empty constructor, does not handle the arguments. - * This constructor is done for backward compatibility with 1.7 and 1.8. - * The task for handling the argument collation strength and normalization - * mode is left to the child class. - * @param collationStrength collation strength - * @param decompositionMode - * @deprecated ICU 2.4. Subclasses should use the default constructor - * instead and handle the strength and normalization mode themselves. - */ - Collator(UCollationStrength collationStrength, - UNormalizationMode decompositionMode); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Copy constructor. - * @param other Collator object to be copied from - * @stable ICU 2.0 - */ - Collator(const Collator& other); - -public: - /** - * Used internally by registration to define the requested and valid locales. - * @param requestedLocale the requested locale - * @param validLocale the valid locale - * @param actualLocale the actual locale - * @internal - */ - virtual void setLocales(const Locale& requestedLocale, const Locale& validLocale, const Locale& actualLocale); - - /** Get the short definition string for a collator. This internal API harvests the collator's - * locale and the attribute set and produces a string that can be used for opening - * a collator with the same attributes using the ucol_openFromShortString API. - * This string will be normalized. - * The structure and the syntax of the string is defined in the "Naming collators" - * section of the users guide: - * http://userguide.icu-project.org/collation/concepts#TOC-Collator-naming-scheme - * This function supports preflighting. - * - * This is internal, and intended to be used with delegate converters. - * - * @param locale a locale that will appear as a collators locale in the resulting - * short string definition. If NULL, the locale will be harvested - * from the collator. - * @param buffer space to hold the resulting string - * @param capacity capacity of the buffer - * @param status for returning errors. All the preflighting errors are featured - * @return length of the resulting string - * @see ucol_openFromShortString - * @see ucol_normalizeShortDefinitionString - * @see ucol_getShortDefinitionString - * @internal - */ - virtual int32_t internalGetShortDefinitionString(const char *locale, - char *buffer, - int32_t capacity, - UErrorCode &status) const; - - /** - * Implements ucol_strcollUTF8(). - * @internal - */ - virtual UCollationResult internalCompareUTF8( - const char *left, int32_t leftLength, - const char *right, int32_t rightLength, - UErrorCode &errorCode) const; - - /** - * Implements ucol_nextSortKeyPart(). - * @internal - */ - virtual int32_t - internalNextSortKeyPart( - UCharIterator *iter, uint32_t state[2], - uint8_t *dest, int32_t count, UErrorCode &errorCode) const; - -#ifndef U_HIDE_INTERNAL_API - /** @internal */ - static inline Collator *fromUCollator(UCollator *uc) { - return reinterpret_cast(uc); - } - /** @internal */ - static inline const Collator *fromUCollator(const UCollator *uc) { - return reinterpret_cast(uc); - } - /** @internal */ - inline UCollator *toUCollator() { - return reinterpret_cast(this); - } - /** @internal */ - inline const UCollator *toUCollator() const { - return reinterpret_cast(this); - } -#endif // U_HIDE_INTERNAL_API - -private: - /** - * Assignment operator. Private for now. - */ - Collator& operator=(const Collator& other); - - friend class CFactory; - friend class SimpleCFactory; - friend class ICUCollatorFactory; - friend class ICUCollatorService; - static Collator* makeInstance(const Locale& desiredLocale, - UErrorCode& status); -}; - -#if !UCONFIG_NO_SERVICE -/** - * A factory, used with registerFactory, the creates multiple collators and provides - * display names for them. A factory supports some number of locales-- these are the - * locales for which it can create collators. The factory can be visible, in which - * case the supported locales will be enumerated by getAvailableLocales, or invisible, - * in which they are not. Invisible locales are still supported, they are just not - * listed by getAvailableLocales. - *

- * If standard locale display names are sufficient, Collator instances can - * be registered using registerInstance instead.

- *

- * Note: if the collators are to be used from C APIs, they must be instances - * of RuleBasedCollator.

- * - * @stable ICU 2.6 - */ -class U_I18N_API CollatorFactory : public UObject { -public: - - /** - * Destructor - * @stable ICU 3.0 - */ - virtual ~CollatorFactory(); - - /** - * Return true if this factory is visible. Default is true. - * If not visible, the locales supported by this factory will not - * be listed by getAvailableLocales. - * @return true if the factory is visible. - * @stable ICU 2.6 - */ - virtual UBool visible(void) const; - - /** - * Return a collator for the provided locale. If the locale - * is not supported, return NULL. - * @param loc the locale identifying the collator to be created. - * @return a new collator if the locale is supported, otherwise NULL. - * @stable ICU 2.6 - */ - virtual Collator* createCollator(const Locale& loc) = 0; - - /** - * Return the name of the collator for the objectLocale, localized for the displayLocale. - * If objectLocale is not supported, or the factory is not visible, set the result string - * to bogus. - * @param objectLocale the locale identifying the collator - * @param displayLocale the locale for which the display name of the collator should be localized - * @param result an output parameter for the display name, set to bogus if not supported. - * @return the display name - * @stable ICU 2.6 - */ - virtual UnicodeString& getDisplayName(const Locale& objectLocale, - const Locale& displayLocale, - UnicodeString& result); - - /** - * Return an array of all the locale names directly supported by this factory. - * The number of names is returned in count. This array is owned by the factory. - * Its contents must never change. - * @param count output parameter for the number of locales supported by the factory - * @param status the in/out error code - * @return a pointer to an array of count UnicodeStrings. - * @stable ICU 2.6 - */ - virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) = 0; -}; -#endif /* UCONFIG_NO_SERVICE */ - -// Collator inline methods ----------------------------------------------- - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_COLLATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/compactdecimalformat.h b/win32/include/spidermonkey/unicode/compactdecimalformat.h deleted file mode 100755 index 1fcc5c58..00000000 --- a/win32/include/spidermonkey/unicode/compactdecimalformat.h +++ /dev/null @@ -1,415 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 2012-2016, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************** -* -* File COMPACTDECIMALFORMAT.H -******************************************************************************** -*/ - -#ifndef __COMPACT_DECIMAL_FORMAT_H__ -#define __COMPACT_DECIMAL_FORMAT_H__ - -#include "unicode/utypes.h" -/** - * \file - * \brief C++ API: Formats decimal numbers in compact form. - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/decimfmt.h" - -struct UHashtable; - -U_NAMESPACE_BEGIN - -class PluralRules; - -/** - * The CompactDecimalFormat produces abbreviated numbers, suitable for display in - * environments will limited real estate. For example, 'Hits: 1.2B' instead of - * 'Hits: 1,200,000,000'. The format will be appropriate for the given language, - * such as "1,2 Mrd." for German. - *

- * For numbers under 1000 trillion (under 10^15, such as 123,456,789,012,345), - * the result will be short for supported languages. However, the result may - * sometimes exceed 7 characters, such as when there are combining marks or thin - * characters. In such cases, the visual width in fonts should still be short. - *

- * By default, there are 3 significant digits. After creation, if more than - * three significant digits are set (with setMaximumSignificantDigits), or if a - * fixed number of digits are set (with setMaximumIntegerDigits or - * setMaximumFractionDigits), then result may be wider. - *

- * At this time, parsing is not supported, and will produce a U_UNSUPPORTED_ERROR. - * Resetting the pattern prefixes or suffixes is not supported; the method calls - * are ignored. - *

- * @stable ICU 51 - */ -class U_I18N_API CompactDecimalFormat : public DecimalFormat { -public: - - /** - * Returns a compact decimal instance for specified locale. - * @param inLocale the given locale. - * @param style whether to use short or long style. - * @param status error code returned here. - * @stable ICU 51 - */ - static CompactDecimalFormat* U_EXPORT2 createInstance( - const Locale& inLocale, UNumberCompactStyle style, UErrorCode& status); - - /** - * Copy constructor. - * - * @param source the DecimalFormat object to be copied from. - * @stable ICU 51 - */ - CompactDecimalFormat(const CompactDecimalFormat& source); - - /** - * Destructor. - * @stable ICU 51 - */ - virtual ~CompactDecimalFormat(); - - /** - * Assignment operator. - * - * @param rhs the DecimalFormat object to be copied. - * @stable ICU 51 - */ - CompactDecimalFormat& operator=(const CompactDecimalFormat& rhs); - - /** - * Clone this Format object polymorphically. The caller owns the - * result and should delete it when done. - * - * @return a polymorphic copy of this CompactDecimalFormat. - * @stable ICU 51 - */ - virtual Format* clone() const; - - /** - * Return TRUE if the given Format objects are semantically equal. - * Objects of different subclasses are considered unequal. - * - * @param other the object to be compared with. - * @return TRUE if the given Format objects are semantically equal. - * @stable ICU 51 - */ - virtual UBool operator==(const Format& other) const; - - - using DecimalFormat::format; - - /** - * Format a double or long number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @stable ICU 51 - */ - virtual UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPosition& pos) const; - - /** - * Format a double or long number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode &status) const; - - /** - * Format a double or long number using base-10 representation. - * Currently sets status to U_UNSUPPORTED_ERROR. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format a long number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @stable ICU 56 - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPosition& pos) const; - - /** - * Format a long number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode &status) const; - - /** - * Format a long number using base-10 representation. - * Currently sets status to U_UNSUPPORTED_ERROR - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format an int64 number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @stable ICU 51 - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& appendTo, - FieldPosition& pos) const; - - /** - * Format an int64 number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode &status) const; - - /** - * Format an int64 number using base-10 representation. - * Currently sets status to U_UNSUPPORTED_ERROR - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format a decimal number. Currently sets status to U_UNSUPPORTED_ERROR - * The syntax of the unformatted number is a "numeric string" - * as defined in the Decimal Arithmetic Specification, available at - * http://speleotrove.com/decimal - * - * @param number The unformatted number, as a string. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(StringPiece number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format a decimal number. Currently sets status to U_UNSUPPORTED_ERROR - * The number is a DigitList wrapper onto a floating point decimal number. - * The default implementation in NumberFormat converts the decimal number - * to a double and formats that. - * - * @param number The number, a DigitList format Decimal Floating Point. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(const DigitList &number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format a decimal number. Currently sets status to U_UNSUPPORTED_ERROR. - * The number is a DigitList wrapper onto a floating point decimal number. - * The default implementation in NumberFormat converts the decimal number - * to a double and formats that. - * - * @param number The number, a DigitList format Decimal Floating Point. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(const DigitList &number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - /** - * CompactDecimalFormat does not support parsing. This implementation - * does nothing. - * @param text Unused. - * @param result Does not change. - * @param parsePosition Does not change. - * @see Formattable - * @stable ICU 51 - */ - virtual void parse(const UnicodeString& text, - Formattable& result, - ParsePosition& parsePosition) const; - - /** - * CompactDecimalFormat does not support parsing. This implementation - * sets status to U_UNSUPPORTED_ERROR - * - * @param text Unused. - * @param result Does not change. - * @param status Always set to U_UNSUPPORTED_ERROR. - * @stable ICU 51 - */ - virtual void parse(const UnicodeString& text, - Formattable& result, - UErrorCode& status) const; - - /** - * Parses text from the given string as a currency amount. Unlike - * the parse() method, this method will attempt to parse a generic - * currency name, searching for a match of this object's locale's - * currency display names, or for a 3-letter ISO currency code. - * This method will fail if this format is not a currency format, - * that is, if it does not contain the currency pattern symbol - * (U+00A4) in its prefix or suffix. This implementation always returns - * NULL. - * - * @param text the string to parse - * @param pos input-output position; on input, the position within text - * to match; must have 0 <= pos.getIndex() < text.length(); - * on output, the position after the last matched character. - * If the parse fails, the position in unchanged upon output. - * @return if parse succeeds, a pointer to a newly-created CurrencyAmount - * object (owned by the caller) containing information about - * the parsed currency; if parse fails, this is NULL. - * @internal - */ - virtual CurrencyAmount* parseCurrency(const UnicodeString& text, - ParsePosition& pos) const; - - /** - * Return the class ID for this class. This is useful only for - * comparing to a return value from getDynamicClassID(). For example: - *

-     * .      Base* polymorphic_pointer = createPolymorphicObject();
-     * .      if (polymorphic_pointer->getDynamicClassID() ==
-     * .          Derived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 51 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. - * This method is to implement a simple version of RTTI, since not all - * C++ compilers support genuine RTTI. Polymorphic operator==() and - * clone() methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 51 - */ - virtual UClassID getDynamicClassID() const; - -private: - - const UHashtable* _unitsByVariant; - const double* _divisors; - PluralRules* _pluralRules; - - // Default constructor not implemented. - CompactDecimalFormat(const DecimalFormat &, const UHashtable* unitsByVariant, const double* divisors, PluralRules* pluralRules); - - UBool eqHelper(const CompactDecimalFormat& that) const; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // __COMPACT_DECIMAL_FORMAT_H__ -//eof diff --git a/win32/include/spidermonkey/unicode/curramt.h b/win32/include/spidermonkey/unicode/curramt.h deleted file mode 100755 index 65c5b39a..00000000 --- a/win32/include/spidermonkey/unicode/curramt.h +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2004-2006, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* Author: Alan Liu -* Created: April 26, 2004 -* Since: ICU 3.0 -********************************************************************** -*/ -#ifndef __CURRENCYAMOUNT_H__ -#define __CURRENCYAMOUNT_H__ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/measure.h" -#include "unicode/currunit.h" - -/** - * \file - * \brief C++ API: Currency Amount Object. - */ - -U_NAMESPACE_BEGIN - -/** - * - * A currency together with a numeric amount, such as 200 USD. - * - * @author Alan Liu - * @stable ICU 3.0 - */ -class U_I18N_API CurrencyAmount: public Measure { - public: - /** - * Construct an object with the given numeric amount and the given - * ISO currency code. - * @param amount a numeric object; amount.isNumeric() must be TRUE - * @param isoCode the 3-letter ISO 4217 currency code; must not be - * NULL and must have length 3 - * @param ec input-output error code. If the amount or the isoCode - * is invalid, then this will be set to a failing value. - * @stable ICU 3.0 - */ - CurrencyAmount(const Formattable& amount, const UChar* isoCode, - UErrorCode &ec); - - /** - * Construct an object with the given numeric amount and the given - * ISO currency code. - * @param amount the amount of the given currency - * @param isoCode the 3-letter ISO 4217 currency code; must not be - * NULL and must have length 3 - * @param ec input-output error code. If the isoCode is invalid, - * then this will be set to a failing value. - * @stable ICU 3.0 - */ - CurrencyAmount(double amount, const UChar* isoCode, - UErrorCode &ec); - - /** - * Copy constructor - * @stable ICU 3.0 - */ - CurrencyAmount(const CurrencyAmount& other); - - /** - * Assignment operator - * @stable ICU 3.0 - */ - CurrencyAmount& operator=(const CurrencyAmount& other); - - /** - * Return a polymorphic clone of this object. The result will - * have the same class as returned by getDynamicClassID(). - * @stable ICU 3.0 - */ - virtual UObject* clone() const; - - /** - * Destructor - * @stable ICU 3.0 - */ - virtual ~CurrencyAmount(); - - /** - * Returns a unique class ID for this object POLYMORPHICALLY. - * This method implements a simple form of RTTI used by ICU. - * @return The class ID for this object. All objects of a given - * class have the same class ID. Objects of other classes have - * different class IDs. - * @stable ICU 3.0 - */ - virtual UClassID getDynamicClassID() const; - - /** - * Returns the class ID for this class. This is used to compare to - * the return value of getDynamicClassID(). - * @return The class ID for all objects of this class. - * @stable ICU 3.0 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - /** - * Return the currency unit object of this object. - * @stable ICU 3.0 - */ - inline const CurrencyUnit& getCurrency() const; - - /** - * Return the ISO currency code of this object. - * @stable ICU 3.0 - */ - inline const UChar* getISOCurrency() const; -}; - -inline const CurrencyUnit& CurrencyAmount::getCurrency() const { - return (const CurrencyUnit&) getUnit(); -} - -inline const UChar* CurrencyAmount::getISOCurrency() const { - return getCurrency().getISOCurrency(); -} - -U_NAMESPACE_END - -#endif // !UCONFIG_NO_FORMATTING -#endif // __CURRENCYAMOUNT_H__ diff --git a/win32/include/spidermonkey/unicode/currpinf.h b/win32/include/spidermonkey/unicode/currpinf.h deleted file mode 100755 index acf8b532..00000000 --- a/win32/include/spidermonkey/unicode/currpinf.h +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * Copyright (C) 2009-2015, International Business Machines Corporation and * - * others. All Rights Reserved. * - ******************************************************************************* - */ -#ifndef CURRPINF_H -#define CURRPINF_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Currency Plural Information used by Decimal Format - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/unistr.h" - -U_NAMESPACE_BEGIN - -class Locale; -class PluralRules; -class Hashtable; - -/** - * This class represents the information needed by - * DecimalFormat to format currency plural, - * such as "3.00 US dollars" or "1.00 US dollar". - * DecimalFormat creates for itself an instance of - * CurrencyPluralInfo from its locale data. - * If you need to change any of these symbols, you can get the - * CurrencyPluralInfo object from your - * DecimalFormat and modify it. - * - * Following are the information needed for currency plural format and parse: - * locale information, - * plural rule of the locale, - * currency plural pattern of the locale. - * - * @stable ICU 4.2 - */ -class U_I18N_API CurrencyPluralInfo : public UObject { -public: - - /** - * Create a CurrencyPluralInfo object for the default locale. - * @param status output param set to success/failure code on exit - * @stable ICU 4.2 - */ - CurrencyPluralInfo(UErrorCode& status); - - /** - * Create a CurrencyPluralInfo object for the given locale. - * @param locale the locale - * @param status output param set to success/failure code on exit - * @stable ICU 4.2 - */ - CurrencyPluralInfo(const Locale& locale, UErrorCode& status); - - /** - * Copy constructor - * - * @stable ICU 4.2 - */ - CurrencyPluralInfo(const CurrencyPluralInfo& info); - - - /** - * Assignment operator - * - * @stable ICU 4.2 - */ - CurrencyPluralInfo& operator=(const CurrencyPluralInfo& info); - - - /** - * Destructor - * - * @stable ICU 4.2 - */ - virtual ~CurrencyPluralInfo(); - - - /** - * Equal operator. - * - * @stable ICU 4.2 - */ - UBool operator==(const CurrencyPluralInfo& info) const; - - - /** - * Not equal operator - * - * @stable ICU 4.2 - */ - UBool operator!=(const CurrencyPluralInfo& info) const; - - - /** - * Clone - * - * @stable ICU 4.2 - */ - CurrencyPluralInfo* clone() const; - - - /** - * Gets plural rules of this locale, used for currency plural format - * - * @return plural rule - * @stable ICU 4.2 - */ - const PluralRules* getPluralRules() const; - - /** - * Given a plural count, gets currency plural pattern of this locale, - * used for currency plural format - * - * @param pluralCount currency plural count - * @param result output param to receive the pattern - * @return a currency plural pattern based on plural count - * @stable ICU 4.2 - */ - UnicodeString& getCurrencyPluralPattern(const UnicodeString& pluralCount, - UnicodeString& result) const; - - /** - * Get locale - * - * @return locale - * @stable ICU 4.2 - */ - const Locale& getLocale() const; - - /** - * Set plural rules. - * The plural rule is set when CurrencyPluralInfo - * instance is created. - * You can call this method to reset plural rules only if you want - * to modify the default plural rule of the locale. - * - * @param ruleDescription new plural rule description - * @param status output param set to success/failure code on exit - * @stable ICU 4.2 - */ - void setPluralRules(const UnicodeString& ruleDescription, - UErrorCode& status); - - /** - * Set currency plural pattern. - * The currency plural pattern is set when CurrencyPluralInfo - * instance is created. - * You can call this method to reset currency plural pattern only if - * you want to modify the default currency plural pattern of the locale. - * - * @param pluralCount the plural count for which the currency pattern will - * be overridden. - * @param pattern the new currency plural pattern - * @param status output param set to success/failure code on exit - * @stable ICU 4.2 - */ - void setCurrencyPluralPattern(const UnicodeString& pluralCount, - const UnicodeString& pattern, - UErrorCode& status); - - /** - * Set locale - * - * @param loc the new locale to set - * @param status output param set to success/failure code on exit - * @stable ICU 4.2 - */ - void setLocale(const Locale& loc, UErrorCode& status); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 4.2 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 4.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - -private: - friend class DecimalFormat; - friend class DecimalFormatImpl; - - void initialize(const Locale& loc, UErrorCode& status); - - void setupCurrencyPluralPattern(const Locale& loc, UErrorCode& status); - - /* - * delete hash table - * - * @param hTable hash table to be deleted - */ - void deleteHash(Hashtable* hTable); - - - /* - * initialize hash table - * - * @param status output param set to success/failure code on exit - * @return hash table initialized - */ - Hashtable* initHash(UErrorCode& status); - - - - /** - * copy hash table - * - * @param source the source to copy from - * @param target the target to copy to - * @param status error code - */ - void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status); - - //-------------------- private data member --------------------- - // map from plural count to currency plural pattern, for example - // a plural pattern defined in "CurrencyUnitPatterns" is - // "one{{0} {1}}", in which "one" is a plural count - // and "{0} {1}" is a currency plural pattern". - // The currency plural pattern saved in this mapping is the pattern - // defined in "CurrencyUnitPattern" by replacing - // {0} with the number format pattern, - // and {1} with 3 currency sign. - Hashtable* fPluralCountToCurrencyUnitPattern; - - /* - * The plural rule is used to format currency plural name, - * for example: "3.00 US Dollars". - * If there are 3 currency signs in the currency patttern, - * the 3 currency signs will be replaced by currency plural name. - */ - PluralRules* fPluralRules; - - // locale - Locale* fLocale; -}; - - -inline UBool -CurrencyPluralInfo::operator!=(const CurrencyPluralInfo& info) const { return !operator==(info); } - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _CURRPINFO -//eof diff --git a/win32/include/spidermonkey/unicode/currunit.h b/win32/include/spidermonkey/unicode/currunit.h deleted file mode 100755 index 9ca4dc59..00000000 --- a/win32/include/spidermonkey/unicode/currunit.h +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2004-2014, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* Author: Alan Liu -* Created: April 26, 2004 -* Since: ICU 3.0 -********************************************************************** -*/ -#ifndef __CURRENCYUNIT_H__ -#define __CURRENCYUNIT_H__ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/measunit.h" - -/** - * \file - * \brief C++ API: Currency Unit Information. - */ - -U_NAMESPACE_BEGIN - -/** - * A unit of currency, such as USD (U.S. dollars) or JPY (Japanese - * yen). This class is a thin wrapper over a UChar string that - * subclasses MeasureUnit, for use with Measure and MeasureFormat. - * - * @author Alan Liu - * @stable ICU 3.0 - */ -class U_I18N_API CurrencyUnit: public MeasureUnit { - public: - /** - * Construct an object with the given ISO currency code. - * @param isoCode the 3-letter ISO 4217 currency code; must not be - * NULL and must have length 3 - * @param ec input-output error code. If the isoCode is invalid, - * then this will be set to a failing value. - * @stable ICU 3.0 - */ - CurrencyUnit(const UChar* isoCode, UErrorCode &ec); - - /** - * Copy constructor - * @stable ICU 3.0 - */ - CurrencyUnit(const CurrencyUnit& other); - - /** - * Assignment operator - * @stable ICU 3.0 - */ - CurrencyUnit& operator=(const CurrencyUnit& other); - - /** - * Return a polymorphic clone of this object. The result will - * have the same class as returned by getDynamicClassID(). - * @stable ICU 3.0 - */ - virtual UObject* clone() const; - - /** - * Destructor - * @stable ICU 3.0 - */ - virtual ~CurrencyUnit(); - - /** - * Returns a unique class ID for this object POLYMORPHICALLY. - * This method implements a simple form of RTTI used by ICU. - * @return The class ID for this object. All objects of a given - * class have the same class ID. Objects of other classes have - * different class IDs. - * @stable ICU 3.0 - */ - virtual UClassID getDynamicClassID() const; - - /** - * Returns the class ID for this class. This is used to compare to - * the return value of getDynamicClassID(). - * @return The class ID for all objects of this class. - * @stable ICU 3.0 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - /** - * Return the ISO currency code of this object. - * @stable ICU 3.0 - */ - inline const UChar* getISOCurrency() const; - - private: - /** - * The ISO 4217 code of this object. - */ - UChar isoCode[4]; -}; - -inline const UChar* CurrencyUnit::getISOCurrency() const { - return isoCode; -} - -U_NAMESPACE_END - -#endif // !UCONFIG_NO_FORMATTING -#endif // __CURRENCYUNIT_H__ diff --git a/win32/include/spidermonkey/unicode/datefmt.h b/win32/include/spidermonkey/unicode/datefmt.h deleted file mode 100755 index 31141265..00000000 --- a/win32/include/spidermonkey/unicode/datefmt.h +++ /dev/null @@ -1,952 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************** - * Copyright (C) 1997-2016, International Business Machines - * Corporation and others. All Rights Reserved. - ******************************************************************************** - * - * File DATEFMT.H - * - * Modification History: - * - * Date Name Description - * 02/19/97 aliu Converted from java. - * 04/01/97 aliu Added support for centuries. - * 07/23/98 stephen JDK 1.2 sync - * 11/15/99 weiv Added support for week of year/day of week formatting - ******************************************************************************** - */ - -#ifndef DATEFMT_H -#define DATEFMT_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/udat.h" -#include "unicode/calendar.h" -#include "unicode/numfmt.h" -#include "unicode/format.h" -#include "unicode/locid.h" -#include "unicode/enumset.h" -#include "unicode/udisplaycontext.h" - -/** - * \file - * \brief C++ API: Abstract class for converting dates. - */ - -U_NAMESPACE_BEGIN - -class TimeZone; -class DateTimePatternGenerator; - -// explicit template instantiation. see digitlst.h -#if defined (_MSC_VER) -template class U_I18N_API EnumSet; -#endif - -/** - * DateFormat is an abstract class for a family of classes that convert dates and - * times from their internal representations to textual form and back again in a - * language-independent manner. Converting from the internal representation (milliseconds - * since midnight, January 1, 1970) to text is known as "formatting," and converting - * from text to millis is known as "parsing." We currently define only one concrete - * subclass of DateFormat: SimpleDateFormat, which can handle pretty much all normal - * date formatting and parsing actions. - *

- * DateFormat helps you to format and parse dates for any locale. Your code can - * be completely independent of the locale conventions for months, days of the - * week, or even the calendar format: lunar vs. solar. - *

- * To format a date for the current Locale, use one of the static factory - * methods: - *

- * \code
- *      DateFormat* dfmt = DateFormat::createDateInstance();
- *      UDate myDate = Calendar::getNow();
- *      UnicodeString myString;
- *      myString = dfmt->format( myDate, myString );
- * \endcode
- * 
- * If you are formatting multiple numbers, it is more efficient to get the - * format and use it multiple times so that the system doesn't have to fetch the - * information about the local language and country conventions multiple times. - *
- * \code
- *      DateFormat* df = DateFormat::createDateInstance();
- *      UnicodeString myString;
- *      UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
- *      for (int32_t i = 0; i < 3; ++i) {
- *          myString.remove();
- *          cout << df->format( myDateArr[i], myString ) << endl;
- *      }
- * \endcode
- * 
- * To get specific fields of a date, you can use UFieldPosition to - * get specific fields. - *
- * \code
- *      DateFormat* dfmt = DateFormat::createDateInstance();
- *      FieldPosition pos(DateFormat::YEAR_FIELD);
- *      UnicodeString myString;
- *      myString = dfmt->format( myDate, myString );
- *      cout << myString << endl;
- *      cout << pos.getBeginIndex() << "," << pos. getEndIndex() << endl;
- * \endcode
- * 
- * To format a date for a different Locale, specify it in the call to - * createDateInstance(). - *
- * \code
- *       DateFormat* df =
- *           DateFormat::createDateInstance( DateFormat::SHORT, Locale::getFrance());
- * \endcode
- * 
- * You can use a DateFormat to parse also. - *
- * \code
- *       UErrorCode status = U_ZERO_ERROR;
- *       UDate myDate = df->parse(myString, status);
- * \endcode
- * 
- * Use createDateInstance() to produce the normal date format for that country. - * There are other static factory methods available. Use createTimeInstance() - * to produce the normal time format for that country. Use createDateTimeInstance() - * to produce a DateFormat that formats both date and time. You can pass in - * different options to these factory methods to control the length of the - * result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the - * locale, but generally: - *
    - *
  • SHORT is completely numeric, such as 12/13/52 or 3:30pm - *
  • MEDIUM is longer, such as Jan 12, 1952 - *
  • LONG is longer, such as January 12, 1952 or 3:30:32pm - *
  • FULL is pretty completely specified, such as - * Tuesday, April 12, 1952 AD or 3:30:42pm PST. - *
- * You can also set the time zone on the format if you wish. If you want even - * more control over the format or parsing, (or want to give your users more - * control), you can try casting the DateFormat you get from the factory methods - * to a SimpleDateFormat. This will work for the majority of countries; just - * remember to chck getDynamicClassID() before carrying out the cast. - *

- * You can also use forms of the parse and format methods with ParsePosition and - * FieldPosition to allow you to - *

    - *
  • Progressively parse through pieces of a string. - *
  • Align any particular field, or find out where it is for selection - * on the screen. - *
- * - *

User subclasses are not supported. While clients may write - * subclasses, such code will not necessarily work and will not be - * guaranteed to work stably from release to release. - */ -class U_I18N_API DateFormat : public Format { -public: - - /** - * Constants for various style patterns. These reflect the order of items in - * the DateTimePatterns resource. There are 4 time patterns, 4 date patterns, - * the default date-time pattern, and 4 date-time patterns. Each block of 4 values - * in the resource occurs in the order full, long, medium, short. - * @stable ICU 2.4 - */ - enum EStyle - { - kNone = -1, - - kFull = 0, - kLong = 1, - kMedium = 2, - kShort = 3, - - kDateOffset = kShort + 1, - // kFull + kDateOffset = 4 - // kLong + kDateOffset = 5 - // kMedium + kDateOffset = 6 - // kShort + kDateOffset = 7 - - kDateTime = 8, - // Default DateTime - - kDateTimeOffset = kDateTime + 1, - // kFull + kDateTimeOffset = 9 - // kLong + kDateTimeOffset = 10 - // kMedium + kDateTimeOffset = 11 - // kShort + kDateTimeOffset = 12 - - // relative dates - kRelative = (1 << 7), - - kFullRelative = (kFull | kRelative), - - kLongRelative = kLong | kRelative, - - kMediumRelative = kMedium | kRelative, - - kShortRelative = kShort | kRelative, - - - kDefault = kMedium, - - - - /** - * These constants are provided for backwards compatibility only. - * Please use the C++ style constants defined above. - */ - FULL = kFull, - LONG = kLong, - MEDIUM = kMedium, - SHORT = kShort, - DEFAULT = kDefault, - DATE_OFFSET = kDateOffset, - NONE = kNone, - DATE_TIME = kDateTime - }; - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~DateFormat(); - - /** - * Equality operator. Returns true if the two formats have the same behavior. - * @stable ICU 2.0 - */ - virtual UBool operator==(const Format&) const; - - - using Format::format; - - /** - * Format an object to produce a string. This method handles Formattable - * objects with a UDate type. If a the Formattable object type is not a Date, - * then it returns a failing UErrorCode. - * - * @param obj The object to format. Must be a Date. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - /** - * Format an object to produce a string. This method handles Formattable - * objects with a UDate type. If a the Formattable object type is not a Date, - * then it returns a failing UErrorCode. - * - * @param obj The object to format. Must be a Date. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. Field values - * are defined in UDateFormatField. Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - /** - * Formats a date into a date/time string. This is an abstract method which - * concrete subclasses must implement. - *

- * On input, the FieldPosition parameter may have its "field" member filled with - * an enum value specifying a field. On output, the FieldPosition will be filled - * in with the text offsets for that field. - *

For example, given a time text - * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is - * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and - * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively. - *

Notice - * that if the same time field appears more than once in a pattern, the status will - * be set for the first occurence of that time field. For instance, - * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)" - * using the pattern "h a z (zzzz)" and the alignment field - * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and - * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first - * occurence of the timezone pattern character 'z'. - * - * @param cal Calendar set to the date and time to be formatted - * into a date/time string. When the calendar type is - * different from the internal calendar held by this - * DateFormat instance, the date and the time zone will - * be inherited from the input calendar, but other calendar - * field values will be calculated by the internal calendar. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param fieldPosition On input: an alignment field, if desired (see examples above) - * On output: the offsets of the alignment field (see examples above) - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.1 - */ - virtual UnicodeString& format( Calendar& cal, - UnicodeString& appendTo, - FieldPosition& fieldPosition) const = 0; - - /** - * Formats a date into a date/time string. Subclasses should implement this method. - * - * @param cal Calendar set to the date and time to be formatted - * into a date/time string. When the calendar type is - * different from the internal calendar held by this - * DateFormat instance, the date and the time zone will - * be inherited from the input calendar, but other calendar - * field values will be calculated by the internal calendar. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. Field values - * are defined in UDateFormatField. Can be NULL. - * @param status error status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(Calendar& cal, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - /** - * Formats a UDate into a date/time string. - *

- * On input, the FieldPosition parameter may have its "field" member filled with - * an enum value specifying a field. On output, the FieldPosition will be filled - * in with the text offsets for that field. - *

For example, given a time text - * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is - * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and - * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively. - *

Notice - * that if the same time field appears more than once in a pattern, the status will - * be set for the first occurence of that time field. For instance, - * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)" - * using the pattern "h a z (zzzz)" and the alignment field - * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and - * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first - * occurence of the timezone pattern character 'z'. - * - * @param date UDate to be formatted into a date/time string. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param fieldPosition On input: an alignment field, if desired (see examples above) - * On output: the offsets of the alignment field (see examples above) - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - UnicodeString& format( UDate date, - UnicodeString& appendTo, - FieldPosition& fieldPosition) const; - - /** - * Formats a UDate into a date/time string. - * - * @param date UDate to be formatted into a date/time string. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. Field values - * are defined in UDateFormatField. Can be NULL. - * @param status error status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - UnicodeString& format(UDate date, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - /** - * Formats a UDate into a date/time string. If there is a problem, you won't - * know, using this method. Use the overloaded format() method which takes a - * FieldPosition& to detect formatting problems. - * - * @param date The UDate value to be formatted into a string. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - UnicodeString& format(UDate date, UnicodeString& appendTo) const; - - /** - * Parse a date/time string. For example, a time text "07/10/96 4:5 PM, PDT" - * will be parsed into a UDate that is equivalent to Date(837039928046). - * Parsing begins at the beginning of the string and proceeds as far as - * possible. Assuming no parse errors were encountered, this function - * doesn't return any information about how much of the string was consumed - * by the parsing. If you need that information, use the version of - * parse() that takes a ParsePosition. - *

- * By default, parsing is lenient: If the input is not in the form used by - * this object's format method but can still be parsed as a date, then the - * parse succeeds. Clients may insist on strict adherence to the format by - * calling setLenient(false). - * @see DateFormat::setLenient(boolean) - *

- * Note that the normal date formats associated with some calendars - such - * as the Chinese lunar calendar - do not specify enough fields to enable - * dates to be parsed unambiguously. In the case of the Chinese lunar - * calendar, while the year within the current 60-year cycle is specified, - * the number of such cycles since the start date of the calendar (in the - * ERA field of the Calendar object) is not normally part of the format, - * and parsing may assume the wrong era. For cases such as this it is - * recommended that clients parse using the method - * parse(const UnicodeString&, Calendar& cal, ParsePosition&) - * with the Calendar passed in set to the current date, or to a date - * within the era/cycle that should be assumed if absent in the format. - * - * @param text The date/time string to be parsed into a UDate value. - * @param status Output param to be set to success/failure code. If - * 'text' cannot be parsed, it will be set to a failure - * code. - * @return The parsed UDate value, if successful. - * @stable ICU 2.0 - */ - virtual UDate parse( const UnicodeString& text, - UErrorCode& status) const; - - /** - * Parse a date/time string beginning at the given parse position. For - * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date - * that is equivalent to Date(837039928046). - *

- * By default, parsing is lenient: If the input is not in the form used by - * this object's format method but can still be parsed as a date, then the - * parse succeeds. Clients may insist on strict adherence to the format by - * calling setLenient(false). - * @see DateFormat::setLenient(boolean) - * - * @param text The date/time string to be parsed. - * @param cal A Calendar set on input to the date and time to be used for - * missing values in the date/time string being parsed, and set - * on output to the parsed date/time. When the calendar type is - * different from the internal calendar held by this DateFormat - * instance, the internal calendar will be cloned to a work - * calendar set to the same milliseconds and time zone as the - * cal parameter, field values will be parsed based on the work - * calendar, then the result (milliseconds and time zone) will - * be set in this calendar. - * @param pos On input, the position at which to start parsing; on - * output, the position at which parsing terminated, or the - * start position if the parse failed. - * @stable ICU 2.1 - */ - virtual void parse( const UnicodeString& text, - Calendar& cal, - ParsePosition& pos) const = 0; - - /** - * Parse a date/time string beginning at the given parse position. For - * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date - * that is equivalent to Date(837039928046). - *

- * By default, parsing is lenient: If the input is not in the form used by - * this object's format method but can still be parsed as a date, then the - * parse succeeds. Clients may insist on strict adherence to the format by - * calling setLenient(false). - * @see DateFormat::setLenient(boolean) - *

- * Note that the normal date formats associated with some calendars - such - * as the Chinese lunar calendar - do not specify enough fields to enable - * dates to be parsed unambiguously. In the case of the Chinese lunar - * calendar, while the year within the current 60-year cycle is specified, - * the number of such cycles since the start date of the calendar (in the - * ERA field of the Calendar object) is not normally part of the format, - * and parsing may assume the wrong era. For cases such as this it is - * recommended that clients parse using the method - * parse(const UnicodeString&, Calendar& cal, ParsePosition&) - * with the Calendar passed in set to the current date, or to a date - * within the era/cycle that should be assumed if absent in the format. - * - * @param text The date/time string to be parsed into a UDate value. - * @param pos On input, the position at which to start parsing; on - * output, the position at which parsing terminated, or the - * start position if the parse failed. - * @return A valid UDate if the input could be parsed. - * @stable ICU 2.0 - */ - UDate parse( const UnicodeString& text, - ParsePosition& pos) const; - - /** - * Parse a string to produce an object. This methods handles parsing of - * date/time strings into Formattable objects with UDate types. - *

- * Before calling, set parse_pos.index to the offset you want to start - * parsing at in the source. After calling, parse_pos.index is the end of - * the text you parsed. If error occurs, index is unchanged. - *

- * When parsing, leading whitespace is discarded (with a successful parse), - * while trailing whitespace is left as is. - *

- * See Format::parseObject() for more. - * - * @param source The string to be parsed into an object. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param parse_pos The position to start parsing at. Upon return - * this param is set to the position after the - * last character successfully parsed. If the - * source is not parsed successfully, this param - * will remain unchanged. - * @stable ICU 2.0 - */ - virtual void parseObject(const UnicodeString& source, - Formattable& result, - ParsePosition& parse_pos) const; - - /** - * Create a default date/time formatter that uses the SHORT style for both - * the date and the time. - * - * @return A date/time formatter which the caller owns. - * @stable ICU 2.0 - */ - static DateFormat* U_EXPORT2 createInstance(void); - - /** - * Creates a time formatter with the given formatting style for the given - * locale. - * - * @param style The given formatting style. For example, - * SHORT for "h:mm a" in the US locale. Relative - * time styles are not currently supported. - * @param aLocale The given locale. - * @return A time formatter which the caller owns. - * @stable ICU 2.0 - */ - static DateFormat* U_EXPORT2 createTimeInstance(EStyle style = kDefault, - const Locale& aLocale = Locale::getDefault()); - - /** - * Creates a date formatter with the given formatting style for the given - * const locale. - * - * @param style The given formatting style. For example, SHORT for "M/d/yy" in the - * US locale. As currently implemented, relative date formatting only - * affects a limited range of calendar days before or after the - * current date, based on the CLDR <field type="day">/<relative> data: - * For example, in English, "Yesterday", "Today", and "Tomorrow". - * Outside of this range, dates are formatted using the corresponding - * non-relative style. - * @param aLocale The given locale. - * @return A date formatter which the caller owns. - * @stable ICU 2.0 - */ - static DateFormat* U_EXPORT2 createDateInstance(EStyle style = kDefault, - const Locale& aLocale = Locale::getDefault()); - - /** - * Creates a date/time formatter with the given formatting styles for the - * given locale. - * - * @param dateStyle The given formatting style for the date portion of the result. - * For example, SHORT for "M/d/yy" in the US locale. As currently - * implemented, relative date formatting only affects a limited range - * of calendar days before or after the current date, based on the - * CLDR <field type="day">/<relative> data: For example, in English, - * "Yesterday", "Today", and "Tomorrow". Outside of this range, dates - * are formatted using the corresponding non-relative style. - * @param timeStyle The given formatting style for the time portion of the result. - * For example, SHORT for "h:mm a" in the US locale. Relative - * time styles are not currently supported. - * @param aLocale The given locale. - * @return A date/time formatter which the caller owns. - * @stable ICU 2.0 - */ - static DateFormat* U_EXPORT2 createDateTimeInstance(EStyle dateStyle = kDefault, - EStyle timeStyle = kDefault, - const Locale& aLocale = Locale::getDefault()); - -#ifndef U_HIDE_INTERNAL_API - /** - * Returns the best pattern given a skeleton and locale. - * @param locale the locale - * @param skeleton the skeleton - * @param status ICU error returned here - * @return the best pattern. - * @internal For ICU use only. - */ - static UnicodeString getBestPattern( - const Locale &locale, - const UnicodeString &skeleton, - UErrorCode &status); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Creates a date/time formatter for the given skeleton and - * default locale. - * - * @param skeleton The skeleton e.g "yMMMMd." Fields in the skeleton can - * be in any order, and this method uses the locale to - * map the skeleton to a pattern that includes locale - * specific separators with the fields in the appropriate - * order for that locale. - * @param status Any error returned here. - * @return A date/time formatter which the caller owns. - * @stable ICU 55 - */ - static DateFormat* U_EXPORT2 createInstanceForSkeleton( - const UnicodeString& skeleton, - UErrorCode &status); - - /** - * Creates a date/time formatter for the given skeleton and locale. - * - * @param skeleton The skeleton e.g "yMMMMd." Fields in the skeleton can - * be in any order, and this method uses the locale to - * map the skeleton to a pattern that includes locale - * specific separators with the fields in the appropriate - * order for that locale. - * @param locale The given locale. - * @param status Any error returned here. - * @return A date/time formatter which the caller owns. - * @stable ICU 55 - */ - static DateFormat* U_EXPORT2 createInstanceForSkeleton( - const UnicodeString& skeleton, - const Locale &locale, - UErrorCode &status); - - /** - * Creates a date/time formatter for the given skeleton and locale. - * - * @param calendarToAdopt the calendar returned DateFormat is to use. - * @param skeleton The skeleton e.g "yMMMMd." Fields in the skeleton can - * be in any order, and this method uses the locale to - * map the skeleton to a pattern that includes locale - * specific separators with the fields in the appropriate - * order for that locale. - * @param locale The given locale. - * @param status Any error returned here. - * @return A date/time formatter which the caller owns. - * @stable ICU 55 - */ - static DateFormat* U_EXPORT2 createInstanceForSkeleton( - Calendar *calendarToAdopt, - const UnicodeString& skeleton, - const Locale &locale, - UErrorCode &status); - - - /** - * Gets the set of locales for which DateFormats are installed. - * @param count Filled in with the number of locales in the list that is returned. - * @return the set of locales for which DateFormats are installed. The caller - * does NOT own this list and must not delete it. - * @stable ICU 2.0 - */ - static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); - - /** - * Returns whether both date/time parsing in the encapsulated Calendar object and DateFormat whitespace & - * numeric processing is lenient. - * @stable ICU 2.0 - */ - virtual UBool isLenient(void) const; - - /** - * Specifies whether date/time parsing is to be lenient. With - * lenient parsing, the parser may use heuristics to interpret inputs that - * do not precisely match this object's format. Without lenient parsing, - * inputs must match this object's format more closely. - * - * Note: ICU 53 introduced finer grained control of leniency (and added - * new control points) making the preferred method a combination of - * setCalendarLenient() & setBooleanAttribute() calls. - * This method supports prior functionality but may not support all - * future leniency control & behavior of DateFormat. For control of pre 53 leniency, - * Calendar and DateFormat whitespace & numeric tolerance, this method is safe to - * use. However, mixing leniency control via this method and modification of the - * newer attributes via setBooleanAttribute() may produce undesirable - * results. - * - * @param lenient True specifies date/time interpretation to be lenient. - * @see Calendar::setLenient - * @stable ICU 2.0 - */ - virtual void setLenient(UBool lenient); - - - /** - * Returns whether date/time parsing in the encapsulated Calendar object processing is lenient. - * @stable ICU 53 - */ - virtual UBool isCalendarLenient(void) const; - - - /** - * Specifies whether encapsulated Calendar date/time parsing is to be lenient. With - * lenient parsing, the parser may use heuristics to interpret inputs that - * do not precisely match this object's format. Without lenient parsing, - * inputs must match this object's format more closely. - * @param lenient when true, parsing is lenient - * @see com.ibm.icu.util.Calendar#setLenient - * @stable ICU 53 - */ - virtual void setCalendarLenient(UBool lenient); - - - /** - * Gets the calendar associated with this date/time formatter. - * The calendar is owned by the formatter and must not be modified. - * Also, the calendar does not reflect the results of a parse operation. - * To parse to a calendar, use {@link #parse(const UnicodeString&, Calendar& cal, ParsePosition&) const parse(const UnicodeString&, Calendar& cal, ParsePosition&)} - * @return the calendar associated with this date/time formatter. - * @stable ICU 2.0 - */ - virtual const Calendar* getCalendar(void) const; - - /** - * Set the calendar to be used by this date format. Initially, the default - * calendar for the specified or default locale is used. The caller should - * not delete the Calendar object after it is adopted by this call. - * Adopting a new calendar will change to the default symbols. - * - * @param calendarToAdopt Calendar object to be adopted. - * @stable ICU 2.0 - */ - virtual void adoptCalendar(Calendar* calendarToAdopt); - - /** - * Set the calendar to be used by this date format. Initially, the default - * calendar for the specified or default locale is used. - * - * @param newCalendar Calendar object to be set. - * @stable ICU 2.0 - */ - virtual void setCalendar(const Calendar& newCalendar); - - - /** - * Gets the number formatter which this date/time formatter uses to format - * and parse the numeric portions of the pattern. - * @return the number formatter which this date/time formatter uses. - * @stable ICU 2.0 - */ - virtual const NumberFormat* getNumberFormat(void) const; - - /** - * Allows you to set the number formatter. The caller should - * not delete the NumberFormat object after it is adopted by this call. - * @param formatToAdopt NumberFormat object to be adopted. - * @stable ICU 2.0 - */ - virtual void adoptNumberFormat(NumberFormat* formatToAdopt); - - /** - * Allows you to set the number formatter. - * @param newNumberFormat NumberFormat object to be set. - * @stable ICU 2.0 - */ - virtual void setNumberFormat(const NumberFormat& newNumberFormat); - - /** - * Returns a reference to the TimeZone used by this DateFormat's calendar. - * @return the time zone associated with the calendar of DateFormat. - * @stable ICU 2.0 - */ - virtual const TimeZone& getTimeZone(void) const; - - /** - * Sets the time zone for the calendar of this DateFormat object. The caller - * no longer owns the TimeZone object and should not delete it after this call. - * @param zoneToAdopt the TimeZone to be adopted. - * @stable ICU 2.0 - */ - virtual void adoptTimeZone(TimeZone* zoneToAdopt); - - /** - * Sets the time zone for the calendar of this DateFormat object. - * @param zone the new time zone. - * @stable ICU 2.0 - */ - virtual void setTimeZone(const TimeZone& zone); - - /** - * Set a particular UDisplayContext value in the formatter, such as - * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. - * @param value The UDisplayContext value to set. - * @param status Input/output status. If at entry this indicates a failure - * status, the function will do nothing; otherwise this will be - * updated with any new status from the function. - * @stable ICU 53 - */ - virtual void setContext(UDisplayContext value, UErrorCode& status); - - /** - * Get the formatter's UDisplayContext value for the specified UDisplayContextType, - * such as UDISPCTX_TYPE_CAPITALIZATION. - * @param type The UDisplayContextType whose value to return - * @param status Input/output status. If at entry this indicates a failure - * status, the function will do nothing; otherwise this will be - * updated with any new status from the function. - * @return The UDisplayContextValue for the specified type. - * @stable ICU 53 - */ - virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const; - - /** - * Sets an boolean attribute on this DateFormat. - * May return U_UNSUPPORTED_ERROR if this instance does not support - * the specified attribute. - * @param attr the attribute to set - * @param newvalue new value - * @param status the error type - * @return *this - for chaining (example: format.setAttribute(...).setAttribute(...) ) - * @stable ICU 53 - */ - - virtual DateFormat& U_EXPORT2 setBooleanAttribute(UDateFormatBooleanAttribute attr, - UBool newvalue, - UErrorCode &status); - - /** - * Returns a boolean from this DateFormat - * May return U_UNSUPPORTED_ERROR if this instance does not support - * the specified attribute. - * @param attr the attribute to set - * @param status the error type - * @return the attribute value. Undefined if there is an error. - * @stable ICU 53 - */ - virtual UBool U_EXPORT2 getBooleanAttribute(UDateFormatBooleanAttribute attr, UErrorCode &status) const; - -protected: - /** - * Default constructor. Creates a DateFormat with no Calendar or NumberFormat - * associated with it. This constructor depends on the subclasses to fill in - * the calendar and numberFormat fields. - * @stable ICU 2.0 - */ - DateFormat(); - - /** - * Copy constructor. - * @stable ICU 2.0 - */ - DateFormat(const DateFormat&); - - /** - * Default assignment operator. - * @stable ICU 2.0 - */ - DateFormat& operator=(const DateFormat&); - - /** - * The calendar that DateFormat uses to produce the time field values needed - * to implement date/time formatting. Subclasses should generally initialize - * this to the default calendar for the locale associated with this DateFormat. - * @stable ICU 2.4 - */ - Calendar* fCalendar; - - /** - * The number formatter that DateFormat uses to format numbers in dates and - * times. Subclasses should generally initialize this to the default number - * format for the locale associated with this DateFormat. - * @stable ICU 2.4 - */ - NumberFormat* fNumberFormat; - - -private: - - /** - * Gets the date/time formatter with the given formatting styles for the - * given locale. - * @param dateStyle the given date formatting style. - * @param timeStyle the given time formatting style. - * @param inLocale the given locale. - * @return a date/time formatter, or 0 on failure. - */ - static DateFormat* U_EXPORT2 create(EStyle timeStyle, EStyle dateStyle, const Locale& inLocale); - - - /** - * enum set of active boolean attributes for this instance - */ - EnumSet fBoolFlags; - - - UDisplayContext fCapitalizationContext; - friend class DateFmtKeyByStyle; - -public: -#ifndef U_HIDE_OBSOLETE_API - /** - * Field selector for FieldPosition for DateFormat fields. - * @obsolete ICU 3.4 use UDateFormatField instead, since this API will be - * removed in that release - */ - enum EField - { - // Obsolete; use UDateFormatField instead - kEraField = UDAT_ERA_FIELD, - kYearField = UDAT_YEAR_FIELD, - kMonthField = UDAT_MONTH_FIELD, - kDateField = UDAT_DATE_FIELD, - kHourOfDay1Field = UDAT_HOUR_OF_DAY1_FIELD, - kHourOfDay0Field = UDAT_HOUR_OF_DAY0_FIELD, - kMinuteField = UDAT_MINUTE_FIELD, - kSecondField = UDAT_SECOND_FIELD, - kMillisecondField = UDAT_FRACTIONAL_SECOND_FIELD, - kDayOfWeekField = UDAT_DAY_OF_WEEK_FIELD, - kDayOfYearField = UDAT_DAY_OF_YEAR_FIELD, - kDayOfWeekInMonthField = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD, - kWeekOfYearField = UDAT_WEEK_OF_YEAR_FIELD, - kWeekOfMonthField = UDAT_WEEK_OF_MONTH_FIELD, - kAmPmField = UDAT_AM_PM_FIELD, - kHour1Field = UDAT_HOUR1_FIELD, - kHour0Field = UDAT_HOUR0_FIELD, - kTimezoneField = UDAT_TIMEZONE_FIELD, - kYearWOYField = UDAT_YEAR_WOY_FIELD, - kDOWLocalField = UDAT_DOW_LOCAL_FIELD, - kExtendedYearField = UDAT_EXTENDED_YEAR_FIELD, - kJulianDayField = UDAT_JULIAN_DAY_FIELD, - kMillisecondsInDayField = UDAT_MILLISECONDS_IN_DAY_FIELD, - - // Obsolete; use UDateFormatField instead - ERA_FIELD = UDAT_ERA_FIELD, - YEAR_FIELD = UDAT_YEAR_FIELD, - MONTH_FIELD = UDAT_MONTH_FIELD, - DATE_FIELD = UDAT_DATE_FIELD, - HOUR_OF_DAY1_FIELD = UDAT_HOUR_OF_DAY1_FIELD, - HOUR_OF_DAY0_FIELD = UDAT_HOUR_OF_DAY0_FIELD, - MINUTE_FIELD = UDAT_MINUTE_FIELD, - SECOND_FIELD = UDAT_SECOND_FIELD, - MILLISECOND_FIELD = UDAT_FRACTIONAL_SECOND_FIELD, - DAY_OF_WEEK_FIELD = UDAT_DAY_OF_WEEK_FIELD, - DAY_OF_YEAR_FIELD = UDAT_DAY_OF_YEAR_FIELD, - DAY_OF_WEEK_IN_MONTH_FIELD = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD, - WEEK_OF_YEAR_FIELD = UDAT_WEEK_OF_YEAR_FIELD, - WEEK_OF_MONTH_FIELD = UDAT_WEEK_OF_MONTH_FIELD, - AM_PM_FIELD = UDAT_AM_PM_FIELD, - HOUR1_FIELD = UDAT_HOUR1_FIELD, - HOUR0_FIELD = UDAT_HOUR0_FIELD, - TIMEZONE_FIELD = UDAT_TIMEZONE_FIELD - }; -#endif /* U_HIDE_OBSOLETE_API */ -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _DATEFMT -//eof diff --git a/win32/include/spidermonkey/unicode/dbbi.h b/win32/include/spidermonkey/unicode/dbbi.h deleted file mode 100755 index 590b6f37..00000000 --- a/win32/include/spidermonkey/unicode/dbbi.h +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1999-2006,2013 IBM Corp. All rights reserved. -********************************************************************** -* Date Name Description -* 12/1/99 rgillam Complete port from Java. -* 01/13/2000 helena Added UErrorCode to ctors. -********************************************************************** -*/ - -#ifndef DBBI_H -#define DBBI_H - -#include "unicode/rbbi.h" - -#if !UCONFIG_NO_BREAK_ITERATION - -/** - * \file - * \brief C++ API: Dictionary Based Break Iterator - */ - -U_NAMESPACE_BEGIN - -#ifndef U_HIDE_DEPRECATED_API -/** - * An obsolete subclass of RuleBasedBreakIterator. Handling of dictionary- - * based break iteration has been folded into the base class. This class - * is deprecated as of ICU 3.6. - * @deprecated ICU 3.6 - */ -typedef RuleBasedBreakIterator DictionaryBasedBreakIterator; - -#endif /* U_HIDE_DEPRECATED_API */ - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_BREAK_ITERATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/dcfmtsym.h b/win32/include/spidermonkey/unicode/dcfmtsym.h deleted file mode 100755 index 946227ad..00000000 --- a/win32/include/spidermonkey/unicode/dcfmtsym.h +++ /dev/null @@ -1,505 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 1997-2016, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************** -* -* File DCFMTSYM.H -* -* Modification History: -* -* Date Name Description -* 02/19/97 aliu Converted from java. -* 03/18/97 clhuang Updated per C++ implementation. -* 03/27/97 helena Updated to pass the simple test after code review. -* 08/26/97 aliu Added currency/intl currency symbol support. -* 07/22/98 stephen Changed to match C++ style -* currencySymbol -> fCurrencySymbol -* Constants changed from CAPS to kCaps -* 06/24/99 helena Integrated Alan's NF enhancements and Java2 bug fixes -* 09/22/00 grhoten Marked deprecation tags with a pointer to replacement -* functions. -******************************************************************************** -*/ - -#ifndef DCFMTSYM_H -#define DCFMTSYM_H - -#include "unicode/utypes.h" -#include "unicode/uchar.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/uobject.h" -#include "unicode/locid.h" -#include "unicode/unum.h" - -/** - * \file - * \brief C++ API: Symbols for formatting numbers. - */ - - -U_NAMESPACE_BEGIN - -/** - * This class represents the set of symbols needed by DecimalFormat - * to format numbers. DecimalFormat creates for itself an instance of - * DecimalFormatSymbols from its locale data. If you need to change any - * of these symbols, you can get the DecimalFormatSymbols object from - * your DecimalFormat and modify it. - *

- * Here are the special characters used in the parts of the - * subpattern, with notes on their usage. - *

- * \code
- *        Symbol   Meaning
- *          0      a digit
- *          #      a digit, zero shows as absent
- *          .      placeholder for decimal separator
- *          ,      placeholder for grouping separator.
- *          ;      separates formats.
- *          -      default negative prefix.
- *          %      divide by 100 and show as percentage
- *          X      any other characters can be used in the prefix or suffix
- *          '      used to quote special characters in a prefix or suffix.
- * \endcode
- *  
- * [Notes] - *

- * If there is no explicit negative subpattern, - is prefixed to the - * positive form. That is, "0.00" alone is equivalent to "0.00;-0.00". - *

- * The grouping separator is commonly used for thousands, but in some - * countries for ten-thousands. The interval is a constant number of - * digits between the grouping characters, such as 100,000,000 or 1,0000,0000. - * If you supply a pattern with multiple grouping characters, the interval - * between the last one and the end of the integer is the one that is - * used. So "#,##,###,####" == "######,####" == "##,####,####". - *

- * This class only handles localized digits where the 10 digits are - * contiguous in Unicode, from 0 to 9. Other digits sets (such as - * superscripts) would need a different subclass. - */ -class U_I18N_API DecimalFormatSymbols : public UObject { -public: - /** - * Constants for specifying a number format symbol. - * @stable ICU 2.0 - */ - enum ENumberFormatSymbol { - /** The decimal separator */ - kDecimalSeparatorSymbol, - /** The grouping separator */ - kGroupingSeparatorSymbol, - /** The pattern separator */ - kPatternSeparatorSymbol, - /** The percent sign */ - kPercentSymbol, - /** Zero*/ - kZeroDigitSymbol, - /** Character representing a digit in the pattern */ - kDigitSymbol, - /** The minus sign */ - kMinusSignSymbol, - /** The plus sign */ - kPlusSignSymbol, - /** The currency symbol */ - kCurrencySymbol, - /** The international currency symbol */ - kIntlCurrencySymbol, - /** The monetary separator */ - kMonetarySeparatorSymbol, - /** The exponential symbol */ - kExponentialSymbol, - /** Per mill symbol - replaces kPermillSymbol */ - kPerMillSymbol, - /** Escape padding character */ - kPadEscapeSymbol, - /** Infinity symbol */ - kInfinitySymbol, - /** Nan symbol */ - kNaNSymbol, - /** Significant digit symbol - * @stable ICU 3.0 */ - kSignificantDigitSymbol, - /** The monetary grouping separator - * @stable ICU 3.6 - */ - kMonetaryGroupingSeparatorSymbol, - /** One - * @stable ICU 4.6 - */ - kOneDigitSymbol, - /** Two - * @stable ICU 4.6 - */ - kTwoDigitSymbol, - /** Three - * @stable ICU 4.6 - */ - kThreeDigitSymbol, - /** Four - * @stable ICU 4.6 - */ - kFourDigitSymbol, - /** Five - * @stable ICU 4.6 - */ - kFiveDigitSymbol, - /** Six - * @stable ICU 4.6 - */ - kSixDigitSymbol, - /** Seven - * @stable ICU 4.6 - */ - kSevenDigitSymbol, - /** Eight - * @stable ICU 4.6 - */ - kEightDigitSymbol, - /** Nine - * @stable ICU 4.6 - */ - kNineDigitSymbol, - /** Multiplication sign. - * @stable ICU 54 - */ - kExponentMultiplicationSymbol, - /** count symbol constants */ - kFormatSymbolCount = kNineDigitSymbol + 2 - }; - - /** - * Create a DecimalFormatSymbols object for the given locale. - * - * @param locale The locale to get symbols for. - * @param status Input/output parameter, set to success or - * failure code upon return. - * @stable ICU 2.0 - */ - DecimalFormatSymbols(const Locale& locale, UErrorCode& status); - - /** - * Create a DecimalFormatSymbols object for the default locale. - * This constructor will not fail. If the resource file data is - * not available, it will use hard-coded last-resort data and - * set status to U_USING_FALLBACK_ERROR. - * - * @param status Input/output parameter, set to success or - * failure code upon return. - * @stable ICU 2.0 - */ - DecimalFormatSymbols(UErrorCode& status); - - /** - * Creates a DecimalFormatSymbols object with last-resort data. - * Intended for callers who cache the symbols data and - * set all symbols on the resulting object. - * - * The last-resort symbols are similar to those for the root data, - * except that the grouping separators are empty, - * the NaN symbol is U+FFFD rather than "NaN", - * and the CurrencySpacing patterns are empty. - * - * @param status Input/output parameter, set to success or - * failure code upon return. - * @return last-resort symbols - * @stable ICU 52 - */ - static DecimalFormatSymbols* createWithLastResortData(UErrorCode& status); - - /** - * Copy constructor. - * @stable ICU 2.0 - */ - DecimalFormatSymbols(const DecimalFormatSymbols&); - - /** - * Assignment operator. - * @stable ICU 2.0 - */ - DecimalFormatSymbols& operator=(const DecimalFormatSymbols&); - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~DecimalFormatSymbols(); - - /** - * Return true if another object is semantically equal to this one. - * - * @param other the object to be compared with. - * @return true if another object is semantically equal to this one. - * @stable ICU 2.0 - */ - UBool operator==(const DecimalFormatSymbols& other) const; - - /** - * Return true if another object is semantically unequal to this one. - * - * @param other the object to be compared with. - * @return true if another object is semantically unequal to this one. - * @stable ICU 2.0 - */ - UBool operator!=(const DecimalFormatSymbols& other) const { return !operator==(other); } - - /** - * Get one of the format symbols by its enum constant. - * Each symbol is stored as a string so that graphemes - * (characters with modifier letters) can be used. - * - * @param symbol Constant to indicate a number format symbol. - * @return the format symbols by the param 'symbol' - * @stable ICU 2.0 - */ - inline UnicodeString getSymbol(ENumberFormatSymbol symbol) const; - - /** - * Set one of the format symbols by its enum constant. - * Each symbol is stored as a string so that graphemes - * (characters with modifier letters) can be used. - * - * @param symbol Constant to indicate a number format symbol. - * @param value value of the format symbol - * @param propogateDigits If false, setting the zero digit will not automatically set 1-9. - * The default behavior is to automatically set 1-9 if zero is being set and the value - * it is being set to corresponds to a known Unicode zero digit. - * @stable ICU 2.0 - */ - void setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value, const UBool propogateDigits); - - /** - * Returns the locale for which this object was constructed. - * @stable ICU 2.6 - */ - inline Locale getLocale() const; - - /** - * Returns the locale for this object. Two flavors are available: - * valid and actual locale. - * @stable ICU 2.8 - */ - Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const; - - /** - * Get pattern string for 'CurrencySpacing' that can be applied to - * currency format. - * This API gets the CurrencySpacing data from ResourceBundle. The pattern can - * be empty if there is no data from current locale and its parent locales. - * - * @param type : UNUM_CURRENCY_MATCH, UNUM_CURRENCY_SURROUNDING_MATCH or UNUM_CURRENCY_INSERT. - * @param beforeCurrency : true if the pattern is for before currency symbol. - * false if the pattern is for after currency symbol. - * @param status: Input/output parameter, set to success or - * failure code upon return. - * @return pattern string for currencyMatch, surroundingMatch or spaceInsert. - * Return empty string if there is no data for this locale and its parent - * locales. - * @stable ICU 4.8 - */ - const UnicodeString& getPatternForCurrencySpacing(UCurrencySpacing type, - UBool beforeCurrency, - UErrorCode& status) const; - /** - * Set pattern string for 'CurrencySpacing' that can be applied to - * currency format. - * - * @param type : UNUM_CURRENCY_MATCH, UNUM_CURRENCY_SURROUNDING_MATCH or UNUM_CURRENCY_INSERT. - * @param beforeCurrency : true if the pattern is for before currency symbol. - * false if the pattern is for after currency symbol. - * @param pattern : pattern string to override current setting. - * @stable ICU 4.8 - */ - void setPatternForCurrencySpacing(UCurrencySpacing type, - UBool beforeCurrency, - const UnicodeString& pattern); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - -private: - DecimalFormatSymbols(); - - /** - * Initializes the symbols from the LocaleElements resource bundle. - * Note: The organization of LocaleElements badly needs to be - * cleaned up. - * - * @param locale The locale to get symbols for. - * @param success Input/output parameter, set to success or - * failure code upon return. - * @param useLastResortData determine if use last resort data - */ - void initialize(const Locale& locale, UErrorCode& success, UBool useLastResortData = FALSE); - - /** - * Initialize the symbols with default values. - */ - void initialize(); - - void setCurrencyForSymbols(); - -public: - -#ifndef U_HIDE_INTERNAL_API - /** - * @internal For ICU use only - */ - inline UBool isCustomCurrencySymbol() const { - return fIsCustomCurrencySymbol; - } - - /** - * @internal For ICU use only - */ - inline UBool isCustomIntlCurrencySymbol() const { - return fIsCustomIntlCurrencySymbol; - } -#endif /* U_HIDE_INTERNAL_API */ - - /** - * _Internal_ function - more efficient version of getSymbol, - * returning a const reference to one of the symbol strings. - * The returned reference becomes invalid when the symbol is changed - * or when the DecimalFormatSymbols are destroyed. - * ### TODO markus 2002oct11: Consider proposing getConstSymbol() to be really public. - * Note: moved #ifndef U_HIDE_INTERNAL_API after this, since this is needed for inline in DecimalFormat - * - * @param symbol Constant to indicate a number format symbol. - * @return the format symbol by the param 'symbol' - * @internal - */ - inline const UnicodeString &getConstSymbol(ENumberFormatSymbol symbol) const; - -#ifndef U_HIDE_INTERNAL_API - /** - * Returns that pattern stored in currecy info. Internal API for use by NumberFormat API. - * @internal - */ - inline const UChar* getCurrencyPattern(void) const; -#endif /* U_HIDE_INTERNAL_API */ - -private: - /** - * Private symbol strings. - * They are either loaded from a resource bundle or otherwise owned. - * setSymbol() clones the symbol string. - * Readonly aliases can only come from a resource bundle, so that we can always - * use fastCopyFrom() with them. - * - * If DecimalFormatSymbols becomes subclassable and the status of fSymbols changes - * from private to protected, - * or when fSymbols can be set any other way that allows them to be readonly aliases - * to non-resource bundle strings, - * then regular UnicodeString copies must be used instead of fastCopyFrom(). - * - * @internal - */ - UnicodeString fSymbols[kFormatSymbolCount]; - - /** - * Non-symbol variable for getConstSymbol(). Always empty. - * @internal - */ - UnicodeString fNoSymbol; - - Locale locale; - - char actualLocale[ULOC_FULLNAME_CAPACITY]; - char validLocale[ULOC_FULLNAME_CAPACITY]; - const UChar* currPattern; - - UnicodeString currencySpcBeforeSym[UNUM_CURRENCY_SPACING_COUNT]; - UnicodeString currencySpcAfterSym[UNUM_CURRENCY_SPACING_COUNT]; - UBool fIsCustomCurrencySymbol; - UBool fIsCustomIntlCurrencySymbol; -}; - -// ------------------------------------- - -inline UnicodeString -DecimalFormatSymbols::getSymbol(ENumberFormatSymbol symbol) const { - const UnicodeString *strPtr; - if(symbol < kFormatSymbolCount) { - strPtr = &fSymbols[symbol]; - } else { - strPtr = &fNoSymbol; - } - return *strPtr; -} - -// See comments above for this function. Not hidden with #ifndef U_HIDE_INTERNAL_API -inline const UnicodeString & -DecimalFormatSymbols::getConstSymbol(ENumberFormatSymbol symbol) const { - const UnicodeString *strPtr; - if(symbol < kFormatSymbolCount) { - strPtr = &fSymbols[symbol]; - } else { - strPtr = &fNoSymbol; - } - return *strPtr; -} - -// ------------------------------------- - -inline void -DecimalFormatSymbols::setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value, const UBool propogateDigits = TRUE) { - if (symbol == kCurrencySymbol) { - fIsCustomCurrencySymbol = TRUE; - } - else if (symbol == kIntlCurrencySymbol) { - fIsCustomIntlCurrencySymbol = TRUE; - } - if(symbol; -#endif - -/** - * DecimalFormat is a concrete subclass of NumberFormat that formats decimal - * numbers. It has a variety of features designed to make it possible to parse - * and format numbers in any locale, including support for Western, Arabic, or - * Indic digits. It also supports different flavors of numbers, including - * integers ("123"), fixed-point numbers ("123.4"), scientific notation - * ("1.23E4"), percentages ("12%"), and currency amounts ("$123", "USD123", - * "123 US dollars"). All of these flavors can be easily localized. - * - *

To obtain a NumberFormat for a specific locale (including the default - * locale) call one of NumberFormat's factory methods such as - * createInstance(). Do not call the DecimalFormat constructors directly, unless - * you know what you are doing, since the NumberFormat factory methods may - * return subclasses other than DecimalFormat. - * - *

Example Usage - * - * \code - * // Normally we would have a GUI with a menu for this - * int32_t locCount; - * const Locale* locales = NumberFormat::getAvailableLocales(locCount); - * - * double myNumber = -1234.56; - * UErrorCode success = U_ZERO_ERROR; - * NumberFormat* form; - * - * // Print out a number with the localized number, currency and percent - * // format for each locale. - * UnicodeString countryName; - * UnicodeString displayName; - * UnicodeString str; - * UnicodeString pattern; - * Formattable fmtable; - * for (int32_t j = 0; j < 3; ++j) { - * cout << endl << "FORMAT " << j << endl; - * for (int32_t i = 0; i < locCount; ++i) { - * if (locales[i].getCountry(countryName).size() == 0) { - * // skip language-only - * continue; - * } - * switch (j) { - * case 0: - * form = NumberFormat::createInstance(locales[i], success ); break; - * case 1: - * form = NumberFormat::createCurrencyInstance(locales[i], success ); break; - * default: - * form = NumberFormat::createPercentInstance(locales[i], success ); break; - * } - * if (form) { - * str.remove(); - * pattern = ((DecimalFormat*)form)->toPattern(pattern); - * cout << locales[i].getDisplayName(displayName) << ": " << pattern; - * cout << " -> " << form->format(myNumber,str) << endl; - * form->parse(form->format(myNumber,str), fmtable, success); - * delete form; - * } - * } - * } - * \endcode - *

- * Another example use createInstance(style) - *

- *

- * // Print out a number using the localized number, currency,
- * // percent, scientific, integer, iso currency, and plural currency
- * // format for each locale
- * Locale* locale = new Locale("en", "US");
- * double myNumber = 1234.56;
- * UErrorCode success = U_ZERO_ERROR;
- * UnicodeString str;
- * Formattable fmtable;
- * for (int j=NumberFormat::kNumberStyle;
- *      j<=NumberFormat::kPluralCurrencyStyle;
- *      ++j) {
- *     NumberFormat* format = NumberFormat::createInstance(locale, j, success);
- *     str.remove();
- *     cout << "format result " << form->format(myNumber, str) << endl;
- *     format->parse(form->format(myNumber, str), fmtable, success);
- * }
- * - * - *

Patterns - * - *

A DecimalFormat consists of a pattern and a set of - * symbols. The pattern may be set directly using - * applyPattern(), or indirectly using other API methods which - * manipulate aspects of the pattern, such as the minimum number of integer - * digits. The symbols are stored in a DecimalFormatSymbols - * object. When using the NumberFormat factory methods, the - * pattern and symbols are read from ICU's locale data. - * - *

Special Pattern Characters - * - *

Many characters in a pattern are taken literally; they are matched during - * parsing and output unchanged during formatting. Special characters, on the - * other hand, stand for other characters, strings, or classes of characters. - * For example, the '#' character is replaced by a localized digit. Often the - * replacement character is the same as the pattern character; in the U.S. locale, - * the ',' grouping character is replaced by ','. However, the replacement is - * still happening, and if the symbols are modified, the grouping character - * changes. Some special characters affect the behavior of the formatter by - * their presence; for example, if the percent character is seen, then the - * value is multiplied by 100 before being displayed. - * - *

To insert a special character in a pattern as a literal, that is, without - * any special meaning, the character must be quoted. There are some exceptions to - * this which are noted below. - * - *

The characters listed here are used in non-localized patterns. Localized - * patterns use the corresponding characters taken from this formatter's - * DecimalFormatSymbols object instead, and these characters lose - * their special status. Two exceptions are the currency sign and quote, which - * are not localized. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Symbol - * Location - * Localized? - * Meaning - *
0 - * Number - * Yes - * Digit - *
1-9 - * Number - * Yes - * '1' through '9' indicate rounding. - *
\htmlonly@\endhtmlonly - * Number - * No - * Significant digit - *
# - * Number - * Yes - * Digit, zero shows as absent - *
. - * Number - * Yes - * Decimal separator or monetary decimal separator - *
- - * Number - * Yes - * Minus sign - *
, - * Number - * Yes - * Grouping separator - *
E - * Number - * Yes - * Separates mantissa and exponent in scientific notation. - * Need not be quoted in prefix or suffix. - *
+ - * Exponent - * Yes - * Prefix positive exponents with localized plus sign. - * Need not be quoted in prefix or suffix. - *
; - * Subpattern boundary - * Yes - * Separates positive and negative subpatterns - *
\% - * Prefix or suffix - * Yes - * Multiply by 100 and show as percentage - *
\\u2030 - * Prefix or suffix - * Yes - * Multiply by 1000 and show as per mille - *
\htmlonly¤\endhtmlonly (\\u00A4) - * Prefix or suffix - * No - * Currency sign, replaced by currency symbol. If - * doubled, replaced by international currency symbol. - * If tripled, replaced by currency plural names, for example, - * "US dollar" or "US dollars" for America. - * If present in a pattern, the monetary decimal separator - * is used instead of the decimal separator. - *
' - * Prefix or suffix - * No - * Used to quote special characters in a prefix or suffix, - * for example, "'#'#" formats 123 to - * "#123". To create a single quote - * itself, use two in a row: "# o''clock". - *
* - * Prefix or suffix boundary - * Yes - * Pad escape, precedes pad character - *
- * - *

A DecimalFormat pattern contains a postive and negative - * subpattern, for example, "#,##0.00;(#,##0.00)". Each subpattern has a - * prefix, a numeric part, and a suffix. If there is no explicit negative - * subpattern, the negative subpattern is the localized minus sign prefixed to the - * positive subpattern. That is, "0.00" alone is equivalent to "0.00;-0.00". If there - * is an explicit negative subpattern, it serves only to specify the negative - * prefix and suffix; the number of digits, minimal digits, and other - * characteristics are ignored in the negative subpattern. That means that - * "#,##0.0#;(#)" has precisely the same result as "#,##0.0#;(#,##0.0#)". - * - *

The prefixes, suffixes, and various symbols used for infinity, digits, - * thousands separators, decimal separators, etc. may be set to arbitrary - * values, and they will appear properly during formatting. However, care must - * be taken that the symbols and strings do not conflict, or parsing will be - * unreliable. For example, either the positive and negative prefixes or the - * suffixes must be distinct for parse() to be able - * to distinguish positive from negative values. Another example is that the - * decimal separator and thousands separator should be distinct characters, or - * parsing will be impossible. - * - *

The grouping separator is a character that separates clusters of - * integer digits to make large numbers more legible. It commonly used for - * thousands, but in some locales it separates ten-thousands. The grouping - * size is the number of digits between the grouping separators, such as 3 - * for "100,000,000" or 4 for "1 0000 0000". There are actually two different - * grouping sizes: One used for the least significant integer digits, the - * primary grouping size, and one used for all others, the - * secondary grouping size. In most locales these are the same, but - * sometimes they are different. For example, if the primary grouping interval - * is 3, and the secondary is 2, then this corresponds to the pattern - * "#,##,##0", and the number 123456789 is formatted as "12,34,56,789". If a - * pattern contains multiple grouping separators, the interval between the last - * one and the end of the integer defines the primary grouping size, and the - * interval between the last two defines the secondary grouping size. All others - * are ignored, so "#,##,###,####" == "###,###,####" == "##,#,###,####". - * - *

Illegal patterns, such as "#.#.#" or "#.###,###", will cause - * DecimalFormat to set a failing UErrorCode. - * - *

Pattern BNF - * - *

- * pattern    := subpattern (';' subpattern)?
- * subpattern := prefix? number exponent? suffix?
- * number     := (integer ('.' fraction)?) | sigDigits
- * prefix     := '\\u0000'..'\\uFFFD' - specialCharacters
- * suffix     := '\\u0000'..'\\uFFFD' - specialCharacters
- * integer    := '#'* '0'* '0'
- * fraction   := '0'* '#'*
- * sigDigits  := '#'* '@' '@'* '#'*
- * exponent   := 'E' '+'? '0'* '0'
- * padSpec    := '*' padChar
- * padChar    := '\\u0000'..'\\uFFFD' - quote
- *  
- * Notation:
- *   X*       0 or more instances of X
- *   X?       0 or 1 instances of X
- *   X|Y      either X or Y
- *   C..D     any character from C up to D, inclusive
- *   S-T      characters in S, except those in T
- * 
- * The first subpattern is for positive numbers. The second (optional) - * subpattern is for negative numbers. - * - *

Not indicated in the BNF syntax above: - * - *

  • The grouping separator ',' can occur inside the integer and - * sigDigits elements, between any two pattern characters of that - * element, as long as the integer or sigDigits element is not - * followed by the exponent element. - * - *
  • Two grouping intervals are recognized: That between the - * decimal point and the first grouping symbol, and that - * between the first and second grouping symbols. These - * intervals are identical in most locales, but in some - * locales they differ. For example, the pattern - * "#,##,###" formats the number 123456789 as - * "12,34,56,789".
  • - * - *
  • The pad specifier padSpec may appear before the prefix, - * after the prefix, before the suffix, after the suffix, or not at all. - * - *
  • In place of '0', the digits '1' through '9' may be used to - * indicate a rounding increment. - *
- * - *

Parsing - * - *

DecimalFormat parses all Unicode characters that represent - * decimal digits, as defined by u_charDigitValue(). In addition, - * DecimalFormat also recognizes as digits the ten consecutive - * characters starting with the localized zero digit defined in the - * DecimalFormatSymbols object. During formatting, the - * DecimalFormatSymbols-based digits are output. - * - *

During parsing, grouping separators are ignored if in lenient mode; - * otherwise, if present, they must be in appropriate positions. - * - *

For currency parsing, the formatter is able to parse every currency - * style formats no matter which style the formatter is constructed with. - * For example, a formatter instance gotten from - * NumberFormat.getInstance(ULocale, NumberFormat.CURRENCYSTYLE) can parse - * formats such as "USD1.00" and "3.00 US dollars". - * - *

If parse(UnicodeString&,Formattable&,ParsePosition&) - * fails to parse a string, it leaves the parse position unchanged. - * The convenience method parse(UnicodeString&,Formattable&,UErrorCode&) - * indicates parse failure by setting a failing - * UErrorCode. - * - *

Formatting - * - *

Formatting is guided by several parameters, all of which can be - * specified either using a pattern or using the API. The following - * description applies to formats that do not use scientific - * notation or significant digits. - * - *

  • If the number of actual integer digits exceeds the - * maximum integer digits, then only the least significant - * digits are shown. For example, 1997 is formatted as "97" if the - * maximum integer digits is set to 2. - * - *
  • If the number of actual integer digits is less than the - * minimum integer digits, then leading zeros are added. For - * example, 1997 is formatted as "01997" if the minimum integer digits - * is set to 5. - * - *
  • If the number of actual fraction digits exceeds the maximum - * fraction digits, then rounding is performed to the - * maximum fraction digits. For example, 0.125 is formatted as "0.12" - * if the maximum fraction digits is 2. This behavior can be changed - * by specifying a rounding increment and/or a rounding mode. - * - *
  • If the number of actual fraction digits is less than the - * minimum fraction digits, then trailing zeros are added. - * For example, 0.125 is formatted as "0.1250" if the mimimum fraction - * digits is set to 4. - * - *
  • Trailing fractional zeros are not displayed if they occur - * j positions after the decimal, where j is less - * than the maximum fraction digits. For example, 0.10004 is - * formatted as "0.1" if the maximum fraction digits is four or less. - *
- * - *

Special Values - * - *

NaN is represented as a single character, typically - * \\uFFFD. This character is determined by the - * DecimalFormatSymbols object. This is the only value for which - * the prefixes and suffixes are not used. - * - *

Infinity is represented as a single character, typically - * \\u221E, with the positive or negative prefixes and suffixes - * applied. The infinity character is determined by the - * DecimalFormatSymbols object. - * - * Scientific Notation - * - *

Numbers in scientific notation are expressed as the product of a mantissa - * and a power of ten, for example, 1234 can be expressed as 1.234 x 103. The - * mantissa is typically in the half-open interval [1.0, 10.0) or sometimes [0.0, 1.0), - * but it need not be. DecimalFormat supports arbitrary mantissas. - * DecimalFormat can be instructed to use scientific - * notation through the API or through the pattern. In a pattern, the exponent - * character immediately followed by one or more digit characters indicates - * scientific notation. Example: "0.###E0" formats the number 1234 as - * "1.234E3". - * - *

    - *
  • The number of digit characters after the exponent character gives the - * minimum exponent digit count. There is no maximum. Negative exponents are - * formatted using the localized minus sign, not the prefix and suffix - * from the pattern. This allows patterns such as "0.###E0 m/s". To prefix - * positive exponents with a localized plus sign, specify '+' between the - * exponent and the digits: "0.###E+0" will produce formats "1E+1", "1E+0", - * "1E-1", etc. (In localized patterns, use the localized plus sign rather than - * '+'.) - * - *
  • The minimum number of integer digits is achieved by adjusting the - * exponent. Example: 0.00123 formatted with "00.###E0" yields "12.3E-4". This - * only happens if there is no maximum number of integer digits. If there is a - * maximum, then the minimum number of integer digits is fixed at one. - * - *
  • The maximum number of integer digits, if present, specifies the exponent - * grouping. The most common use of this is to generate engineering - * notation, in which the exponent is a multiple of three, e.g., - * "##0.###E0". The number 12345 is formatted using "##0.####E0" as "12.345E3". - * - *
  • When using scientific notation, the formatter controls the - * digit counts using significant digits logic. The maximum number of - * significant digits limits the total number of integer and fraction - * digits that will be shown in the mantissa; it does not affect - * parsing. For example, 12345 formatted with "##0.##E0" is "12.3E3". - * See the section on significant digits for more details. - * - *
  • The number of significant digits shown is determined as - * follows: If areSignificantDigitsUsed() returns false, then the - * minimum number of significant digits shown is one, and the maximum - * number of significant digits shown is the sum of the minimum - * integer and maximum fraction digits, and is - * unaffected by the maximum integer digits. If this sum is zero, - * then all significant digits are shown. If - * areSignificantDigitsUsed() returns true, then the significant digit - * counts are specified by getMinimumSignificantDigits() and - * getMaximumSignificantDigits(). In this case, the number of - * integer digits is fixed at one, and there is no exponent grouping. - * - *
  • Exponential patterns may not contain grouping separators. - *
- * - * Significant Digits - * - * DecimalFormat has two ways of controlling how many - * digits are shows: (a) significant digits counts, or (b) integer and - * fraction digit counts. Integer and fraction digit counts are - * described above. When a formatter is using significant digits - * counts, the number of integer and fraction digits is not specified - * directly, and the formatter settings for these counts are ignored. - * Instead, the formatter uses however many integer and fraction - * digits are required to display the specified number of significant - * digits. Examples: - * - * - * - * - * - * - * - *
Pattern - * Minimum significant digits - * Maximum significant digits - * Number - * Output of format() - *
\@\@\@ - * 3 - * 3 - * 12345 - * 12300 - *
\@\@\@ - * 3 - * 3 - * 0.12345 - * 0.123 - *
\@\@## - * 2 - * 4 - * 3.14159 - * 3.142 - *
\@\@## - * 2 - * 4 - * 1.23004 - * 1.23 - *
- * - *
    - *
  • Significant digit counts may be expressed using patterns that - * specify a minimum and maximum number of significant digits. These - * are indicated by the '@' and '#' - * characters. The minimum number of significant digits is the number - * of '@' characters. The maximum number of significant - * digits is the number of '@' characters plus the number - * of '#' characters following on the right. For - * example, the pattern "@@@" indicates exactly 3 - * significant digits. The pattern "@##" indicates from - * 1 to 3 significant digits. Trailing zero digits to the right of - * the decimal separator are suppressed after the minimum number of - * significant digits have been shown. For example, the pattern - * "@##" formats the number 0.1203 as - * "0.12". - * - *
  • If a pattern uses significant digits, it may not contain a - * decimal separator, nor the '0' pattern character. - * Patterns such as "@00" or "@.###" are - * disallowed. - * - *
  • Any number of '#' characters may be prepended to - * the left of the leftmost '@' character. These have no - * effect on the minimum and maximum significant digits counts, but - * may be used to position grouping separators. For example, - * "#,#@#" indicates a minimum of one significant digits, - * a maximum of two significant digits, and a grouping size of three. - * - *
  • In order to enable significant digits formatting, use a pattern - * containing the '@' pattern character. Alternatively, - * call setSignificantDigitsUsed(TRUE). - * - *
  • In order to disable significant digits formatting, use a - * pattern that does not contain the '@' pattern - * character. Alternatively, call setSignificantDigitsUsed(FALSE). - * - *
  • The number of significant digits has no effect on parsing. - * - *
  • Significant digits may be used together with exponential notation. Such - * patterns are equivalent to a normal exponential pattern with a minimum and - * maximum integer digit count of one, a minimum fraction digit count of - * getMinimumSignificantDigits() - 1, and a maximum fraction digit - * count of getMaximumSignificantDigits() - 1. For example, the - * pattern "@@###E0" is equivalent to "0.0###E0". - * - *
  • If signficant digits are in use, then the integer and fraction - * digit counts, as set via the API, are ignored. If significant - * digits are not in use, then the signficant digit counts, as set via - * the API, are ignored. - * - *
- * - *

Padding - * - *

DecimalFormat supports padding the result of - * format() to a specific width. Padding may be specified either - * through the API or through the pattern syntax. In a pattern the pad escape - * character, followed by a single pad character, causes padding to be parsed - * and formatted. The pad escape character is '*' in unlocalized patterns, and - * can be localized using DecimalFormatSymbols::setSymbol() with a - * DecimalFormatSymbols::kPadEscapeSymbol - * selector. For example, "$*x#,##0.00" formats 123 to - * "$xx123.00", and 1234 to "$1,234.00". - * - *

    - *
  • When padding is in effect, the width of the positive subpattern, - * including prefix and suffix, determines the format width. For example, in - * the pattern "* #0 o''clock", the format width is 10. - * - *
  • The width is counted in 16-bit code units (UChars). - * - *
  • Some parameters which usually do not matter have meaning when padding is - * used, because the pattern width is significant with padding. In the pattern - * "* ##,##,#,##0.##", the format width is 14. The initial characters "##,##," - * do not affect the grouping size or maximum integer digits, but they do affect - * the format width. - * - *
  • Padding may be inserted at one of four locations: before the prefix, - * after the prefix, before the suffix, or after the suffix. If padding is - * specified in any other location, applyPattern() - * sets a failing UErrorCode. If there is no prefix, - * before the prefix and after the prefix are equivalent, likewise for the - * suffix. - * - *
  • When specified in a pattern, the 32-bit code point immediately - * following the pad escape is the pad character. This may be any character, - * including a special pattern character. That is, the pad escape - * escapes the following character. If there is no character after - * the pad escape, then the pattern is illegal. - * - *
- * - *

Rounding - * - *

DecimalFormat supports rounding to a specific increment. For - * example, 1230 rounded to the nearest 50 is 1250. 1.234 rounded to the - * nearest 0.65 is 1.3. The rounding increment may be specified through the API - * or in a pattern. To specify a rounding increment in a pattern, include the - * increment in the pattern itself. "#,#50" specifies a rounding increment of - * 50. "#,##0.05" specifies a rounding increment of 0.05. - * - *

In the absense of an explicit rounding increment numbers are - * rounded to their formatted width. - * - *

    - *
  • Rounding only affects the string produced by formatting. It does - * not affect parsing or change any numerical values. - * - *
  • A rounding mode determines how values are rounded; see - * DecimalFormat::ERoundingMode. The default rounding mode is - * DecimalFormat::kRoundHalfEven. The rounding mode can only be set - * through the API; it can not be set with a pattern. - * - *
  • Some locales use rounding in their currency formats to reflect the - * smallest currency denomination. - * - *
  • In a pattern, digits '1' through '9' specify rounding, but otherwise - * behave identically to digit '0'. - *
- * - *

Synchronization - * - *

DecimalFormat objects are not synchronized. Multiple - * threads should not access one formatter concurrently. - * - *

Subclassing - * - *

User subclasses are not supported. While clients may write - * subclasses, such code will not necessarily work and will not be - * guaranteed to work stably from release to release. - */ -class U_I18N_API DecimalFormat: public NumberFormat { -public: - /** - * Rounding mode. - * @stable ICU 2.4 - */ - enum ERoundingMode { - kRoundCeiling, /**< Round towards positive infinity */ - kRoundFloor, /**< Round towards negative infinity */ - kRoundDown, /**< Round towards zero */ - kRoundUp, /**< Round away from zero */ - kRoundHalfEven, /**< Round towards the nearest integer, or - towards the nearest even integer if equidistant */ - kRoundHalfDown, /**< Round towards the nearest integer, or - towards zero if equidistant */ - kRoundHalfUp, /**< Round towards the nearest integer, or - away from zero if equidistant */ - /** - * Return U_FORMAT_INEXACT_ERROR if number does not format exactly. - * @stable ICU 4.8 - */ - kRoundUnnecessary - }; - - /** - * Pad position. - * @stable ICU 2.4 - */ - enum EPadPosition { - kPadBeforePrefix, - kPadAfterPrefix, - kPadBeforeSuffix, - kPadAfterSuffix - }; - - /** - * Create a DecimalFormat using the default pattern and symbols - * for the default locale. This is a convenient way to obtain a - * DecimalFormat when internationalization is not the main concern. - *

- * To obtain standard formats for a given locale, use the factory methods - * on NumberFormat such as createInstance. These factories will - * return the most appropriate sub-class of NumberFormat for a given - * locale. - * @param status Output param set to success/failure code. If the - * pattern is invalid this will be set to a failure code. - * @stable ICU 2.0 - */ - DecimalFormat(UErrorCode& status); - - /** - * Create a DecimalFormat from the given pattern and the symbols - * for the default locale. This is a convenient way to obtain a - * DecimalFormat when internationalization is not the main concern. - *

- * To obtain standard formats for a given locale, use the factory methods - * on NumberFormat such as createInstance. These factories will - * return the most appropriate sub-class of NumberFormat for a given - * locale. - * @param pattern A non-localized pattern string. - * @param status Output param set to success/failure code. If the - * pattern is invalid this will be set to a failure code. - * @stable ICU 2.0 - */ - DecimalFormat(const UnicodeString& pattern, - UErrorCode& status); - - /** - * Create a DecimalFormat from the given pattern and symbols. - * Use this constructor when you need to completely customize the - * behavior of the format. - *

- * To obtain standard formats for a given - * locale, use the factory methods on NumberFormat such as - * createInstance or createCurrencyInstance. If you need only minor adjustments - * to a standard format, you can modify the format returned by - * a NumberFormat factory method. - * - * @param pattern a non-localized pattern string - * @param symbolsToAdopt the set of symbols to be used. The caller should not - * delete this object after making this call. - * @param status Output param set to success/failure code. If the - * pattern is invalid this will be set to a failure code. - * @stable ICU 2.0 - */ - DecimalFormat( const UnicodeString& pattern, - DecimalFormatSymbols* symbolsToAdopt, - UErrorCode& status); - -#ifndef U_HIDE_INTERNAL_API - /** - * This API is for ICU use only. - * Create a DecimalFormat from the given pattern, symbols, and style. - * - * @param pattern a non-localized pattern string - * @param symbolsToAdopt the set of symbols to be used. The caller should not - * delete this object after making this call. - * @param style style of decimal format - * @param status Output param set to success/failure code. If the - * pattern is invalid this will be set to a failure code. - * @internal - */ - DecimalFormat( const UnicodeString& pattern, - DecimalFormatSymbols* symbolsToAdopt, - UNumberFormatStyle style, - UErrorCode& status); - -#if UCONFIG_HAVE_PARSEALLINPUT - /** - * @internal - */ - void setParseAllInput(UNumberFormatAttributeValue value); -#endif - -#endif /* U_HIDE_INTERNAL_API */ - - - /** - * Set an integer attribute on this DecimalFormat. - * May return U_UNSUPPORTED_ERROR if this instance does not support - * the specified attribute. - * @param attr the attribute to set - * @param newvalue new value - * @param status the error type - * @return *this - for chaining (example: format.setAttribute(...).setAttribute(...) ) - * @stable ICU 51 - */ - virtual DecimalFormat& setAttribute( UNumberFormatAttribute attr, - int32_t newvalue, - UErrorCode &status); - - /** - * Get an integer - * May return U_UNSUPPORTED_ERROR if this instance does not support - * the specified attribute. - * @param attr the attribute to set - * @param status the error type - * @return the attribute value. Undefined if there is an error. - * @stable ICU 51 - */ - virtual int32_t getAttribute( UNumberFormatAttribute attr, - UErrorCode &status) const; - - - /** - * Set whether or not grouping will be used in this format. - * @param newValue True, grouping will be used in this format. - * @see getGroupingUsed - * @stable ICU 53 - */ - virtual void setGroupingUsed(UBool newValue); - - /** - * Sets whether or not numbers should be parsed as integers only. - * @param value set True, this format will parse numbers as integers - * only. - * @see isParseIntegerOnly - * @stable ICU 53 - */ - virtual void setParseIntegerOnly(UBool value); - - /** - * Set a particular UDisplayContext value in the formatter, such as - * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. - * @param value The UDisplayContext value to set. - * @param status Input/output status. If at entry this indicates a failure - * status, the function will do nothing; otherwise this will be - * updated with any new status from the function. - * @stable ICU 53 - */ - virtual void setContext(UDisplayContext value, UErrorCode& status); - - /** - * Create a DecimalFormat from the given pattern and symbols. - * Use this constructor when you need to completely customize the - * behavior of the format. - *

- * To obtain standard formats for a given - * locale, use the factory methods on NumberFormat such as - * createInstance or createCurrencyInstance. If you need only minor adjustments - * to a standard format, you can modify the format returned by - * a NumberFormat factory method. - * - * @param pattern a non-localized pattern string - * @param symbolsToAdopt the set of symbols to be used. The caller should not - * delete this object after making this call. - * @param parseError Output param to receive errors occured during parsing - * @param status Output param set to success/failure code. If the - * pattern is invalid this will be set to a failure code. - * @stable ICU 2.0 - */ - DecimalFormat( const UnicodeString& pattern, - DecimalFormatSymbols* symbolsToAdopt, - UParseError& parseError, - UErrorCode& status); - /** - * Create a DecimalFormat from the given pattern and symbols. - * Use this constructor when you need to completely customize the - * behavior of the format. - *

- * To obtain standard formats for a given - * locale, use the factory methods on NumberFormat such as - * createInstance or createCurrencyInstance. If you need only minor adjustments - * to a standard format, you can modify the format returned by - * a NumberFormat factory method. - * - * @param pattern a non-localized pattern string - * @param symbols the set of symbols to be used - * @param status Output param set to success/failure code. If the - * pattern is invalid this will be set to a failure code. - * @stable ICU 2.0 - */ - DecimalFormat( const UnicodeString& pattern, - const DecimalFormatSymbols& symbols, - UErrorCode& status); - - /** - * Copy constructor. - * - * @param source the DecimalFormat object to be copied from. - * @stable ICU 2.0 - */ - DecimalFormat(const DecimalFormat& source); - - /** - * Assignment operator. - * - * @param rhs the DecimalFormat object to be copied. - * @stable ICU 2.0 - */ - DecimalFormat& operator=(const DecimalFormat& rhs); - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~DecimalFormat(); - - /** - * Clone this Format object polymorphically. The caller owns the - * result and should delete it when done. - * - * @return a polymorphic copy of this DecimalFormat. - * @stable ICU 2.0 - */ - virtual Format* clone(void) const; - - /** - * Return true if the given Format objects are semantically equal. - * Objects of different subclasses are considered unequal. - * - * @param other the object to be compared with. - * @return true if the given Format objects are semantically equal. - * @stable ICU 2.0 - */ - virtual UBool operator==(const Format& other) const; - - - using NumberFormat::format; - - /** - * Format a double or long number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPosition& pos) const; - - - /** - * Format a double or long number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode &status) const; - - /** - * Format a double or long number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format a long number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPosition& pos) const; - - /** - * Format a long number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode &status) const; - - /** - * Format a long number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format an int64 number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.8 - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& appendTo, - FieldPosition& pos) const; - - /** - * Format an int64 number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode &status) const; - - /** - * Format an int64 number using base-10 representation. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format a decimal number. - * The syntax of the unformatted number is a "numeric string" - * as defined in the Decimal Arithmetic Specification, available at - * http://speleotrove.com/decimal - * - * @param number The unformatted number, as a string. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(StringPiece number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - - /** - * Format a decimal number. - * The number is a DigitList wrapper onto a floating point decimal number. - * The default implementation in NumberFormat converts the decimal number - * to a double and formats that. - * - * @param number The number, a DigitList format Decimal Floating Point. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(const DigitList &number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format a decimal number. - * @param number The number - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format( - const VisibleDigitsWithExponent &number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - /** - * Format a decimal number. - * @param number The number - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format( - const VisibleDigitsWithExponent &number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format a decimal number. - * The number is a DigitList wrapper onto a floating point decimal number. - * The default implementation in NumberFormat converts the decimal number - * to a double and formats that. - * - * @param number The number, a DigitList format Decimal Floating Point. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(const DigitList &number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - using NumberFormat::parse; - - /** - * Parse the given string using this object's choices. The method - * does string comparisons to try to find an optimal match. - * If no object can be parsed, index is unchanged, and NULL is - * returned. The result is returned as the most parsimonious - * type of Formattable that will accomodate all of the - * necessary precision. For example, if the result is exactly 12, - * it will be returned as a long. However, if it is 1.5, it will - * be returned as a double. - * - * @param text The text to be parsed. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param parsePosition The position to start parsing at on input. - * On output, moved to after the last successfully - * parse character. On parse failure, does not change. - * @see Formattable - * @stable ICU 2.0 - */ - virtual void parse(const UnicodeString& text, - Formattable& result, - ParsePosition& parsePosition) const; - - /** - * Parses text from the given string as a currency amount. Unlike - * the parse() method, this method will attempt to parse a generic - * currency name, searching for a match of this object's locale's - * currency display names, or for a 3-letter ISO currency code. - * This method will fail if this format is not a currency format, - * that is, if it does not contain the currency pattern symbol - * (U+00A4) in its prefix or suffix. - * - * @param text the string to parse - * @param pos input-output position; on input, the position within text - * to match; must have 0 <= pos.getIndex() < text.length(); - * on output, the position after the last matched character. - * If the parse fails, the position in unchanged upon output. - * @return if parse succeeds, a pointer to a newly-created CurrencyAmount - * object (owned by the caller) containing information about - * the parsed currency; if parse fails, this is NULL. - * @stable ICU 49 - */ - virtual CurrencyAmount* parseCurrency(const UnicodeString& text, - ParsePosition& pos) const; - - /** - * Returns the decimal format symbols, which is generally not changed - * by the programmer or user. - * @return desired DecimalFormatSymbols - * @see DecimalFormatSymbols - * @stable ICU 2.0 - */ - virtual const DecimalFormatSymbols* getDecimalFormatSymbols(void) const; - - /** - * Sets the decimal format symbols, which is generally not changed - * by the programmer or user. - * @param symbolsToAdopt DecimalFormatSymbols to be adopted. - * @stable ICU 2.0 - */ - virtual void adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt); - - /** - * Sets the decimal format symbols, which is generally not changed - * by the programmer or user. - * @param symbols DecimalFormatSymbols. - * @stable ICU 2.0 - */ - virtual void setDecimalFormatSymbols(const DecimalFormatSymbols& symbols); - - - /** - * Returns the currency plural format information, - * which is generally not changed by the programmer or user. - * @return desired CurrencyPluralInfo - * @stable ICU 4.2 - */ - virtual const CurrencyPluralInfo* getCurrencyPluralInfo(void) const; - - /** - * Sets the currency plural format information, - * which is generally not changed by the programmer or user. - * @param toAdopt CurrencyPluralInfo to be adopted. - * @stable ICU 4.2 - */ - virtual void adoptCurrencyPluralInfo(CurrencyPluralInfo* toAdopt); - - /** - * Sets the currency plural format information, - * which is generally not changed by the programmer or user. - * @param info Currency Plural Info. - * @stable ICU 4.2 - */ - virtual void setCurrencyPluralInfo(const CurrencyPluralInfo& info); - - - /** - * Get the positive prefix. - * - * @param result Output param which will receive the positive prefix. - * @return A reference to 'result'. - * Examples: +123, $123, sFr123 - * @stable ICU 2.0 - */ - UnicodeString& getPositivePrefix(UnicodeString& result) const; - - /** - * Set the positive prefix. - * - * @param newValue the new value of the the positive prefix to be set. - * Examples: +123, $123, sFr123 - * @stable ICU 2.0 - */ - virtual void setPositivePrefix(const UnicodeString& newValue); - - /** - * Get the negative prefix. - * - * @param result Output param which will receive the negative prefix. - * @return A reference to 'result'. - * Examples: -123, ($123) (with negative suffix), sFr-123 - * @stable ICU 2.0 - */ - UnicodeString& getNegativePrefix(UnicodeString& result) const; - - /** - * Set the negative prefix. - * - * @param newValue the new value of the the negative prefix to be set. - * Examples: -123, ($123) (with negative suffix), sFr-123 - * @stable ICU 2.0 - */ - virtual void setNegativePrefix(const UnicodeString& newValue); - - /** - * Get the positive suffix. - * - * @param result Output param which will receive the positive suffix. - * @return A reference to 'result'. - * Example: 123% - * @stable ICU 2.0 - */ - UnicodeString& getPositiveSuffix(UnicodeString& result) const; - - /** - * Set the positive suffix. - * - * @param newValue the new value of the positive suffix to be set. - * Example: 123% - * @stable ICU 2.0 - */ - virtual void setPositiveSuffix(const UnicodeString& newValue); - - /** - * Get the negative suffix. - * - * @param result Output param which will receive the negative suffix. - * @return A reference to 'result'. - * Examples: -123%, ($123) (with positive suffixes) - * @stable ICU 2.0 - */ - UnicodeString& getNegativeSuffix(UnicodeString& result) const; - - /** - * Set the negative suffix. - * - * @param newValue the new value of the negative suffix to be set. - * Examples: 123% - * @stable ICU 2.0 - */ - virtual void setNegativeSuffix(const UnicodeString& newValue); - - /** - * Get the multiplier for use in percent, permill, etc. - * For a percentage, set the suffixes to have "%" and the multiplier to be 100. - * (For Arabic, use arabic percent symbol). - * For a permill, set the suffixes to have "\\u2031" and the multiplier to be 1000. - * - * @return the multiplier for use in percent, permill, etc. - * Examples: with 100, 1.23 -> "123", and "123" -> 1.23 - * @stable ICU 2.0 - */ - int32_t getMultiplier(void) const; - - /** - * Set the multiplier for use in percent, permill, etc. - * For a percentage, set the suffixes to have "%" and the multiplier to be 100. - * (For Arabic, use arabic percent symbol). - * For a permill, set the suffixes to have "\\u2031" and the multiplier to be 1000. - * - * @param newValue the new value of the multiplier for use in percent, permill, etc. - * Examples: with 100, 1.23 -> "123", and "123" -> 1.23 - * @stable ICU 2.0 - */ - virtual void setMultiplier(int32_t newValue); - - /** - * Get the rounding increment. - * @return A positive rounding increment, or 0.0 if a custom rounding - * increment is not in effect. - * @see #setRoundingIncrement - * @see #getRoundingMode - * @see #setRoundingMode - * @stable ICU 2.0 - */ - virtual double getRoundingIncrement(void) const; - - /** - * Set the rounding increment. In the absence of a rounding increment, - * numbers will be rounded to the number of digits displayed. - * @param newValue A positive rounding increment, or 0.0 to - * use the default rounding increment. - * Negative increments are equivalent to 0.0. - * @see #getRoundingIncrement - * @see #getRoundingMode - * @see #setRoundingMode - * @stable ICU 2.0 - */ - virtual void setRoundingIncrement(double newValue); - - /** - * Get the rounding mode. - * @return A rounding mode - * @see #setRoundingIncrement - * @see #getRoundingIncrement - * @see #setRoundingMode - * @stable ICU 2.0 - */ - virtual ERoundingMode getRoundingMode(void) const; - - /** - * Set the rounding mode. - * @param roundingMode A rounding mode - * @see #setRoundingIncrement - * @see #getRoundingIncrement - * @see #getRoundingMode - * @stable ICU 2.0 - */ - virtual void setRoundingMode(ERoundingMode roundingMode); - - /** - * Get the width to which the output of format() is padded. - * The width is counted in 16-bit code units. - * @return the format width, or zero if no padding is in effect - * @see #setFormatWidth - * @see #getPadCharacterString - * @see #setPadCharacter - * @see #getPadPosition - * @see #setPadPosition - * @stable ICU 2.0 - */ - virtual int32_t getFormatWidth(void) const; - - /** - * Set the width to which the output of format() is padded. - * The width is counted in 16-bit code units. - * This method also controls whether padding is enabled. - * @param width the width to which to pad the result of - * format(), or zero to disable padding. A negative - * width is equivalent to 0. - * @see #getFormatWidth - * @see #getPadCharacterString - * @see #setPadCharacter - * @see #getPadPosition - * @see #setPadPosition - * @stable ICU 2.0 - */ - virtual void setFormatWidth(int32_t width); - - /** - * Get the pad character used to pad to the format width. The - * default is ' '. - * @return a string containing the pad character. This will always - * have a length of one 32-bit code point. - * @see #setFormatWidth - * @see #getFormatWidth - * @see #setPadCharacter - * @see #getPadPosition - * @see #setPadPosition - * @stable ICU 2.0 - */ - virtual UnicodeString getPadCharacterString() const; - - /** - * Set the character used to pad to the format width. If padding - * is not enabled, then this will take effect if padding is later - * enabled. - * @param padChar a string containing the pad charcter. If the string - * has length 0, then the pad characer is set to ' '. Otherwise - * padChar.char32At(0) will be used as the pad character. - * @see #setFormatWidth - * @see #getFormatWidth - * @see #getPadCharacterString - * @see #getPadPosition - * @see #setPadPosition - * @stable ICU 2.0 - */ - virtual void setPadCharacter(const UnicodeString &padChar); - - /** - * Get the position at which padding will take place. This is the location - * at which padding will be inserted if the result of format() - * is shorter than the format width. - * @return the pad position, one of kPadBeforePrefix, - * kPadAfterPrefix, kPadBeforeSuffix, or - * kPadAfterSuffix. - * @see #setFormatWidth - * @see #getFormatWidth - * @see #setPadCharacter - * @see #getPadCharacterString - * @see #setPadPosition - * @see #EPadPosition - * @stable ICU 2.0 - */ - virtual EPadPosition getPadPosition(void) const; - - /** - * Set the position at which padding will take place. This is the location - * at which padding will be inserted if the result of format() - * is shorter than the format width. This has no effect unless padding is - * enabled. - * @param padPos the pad position, one of kPadBeforePrefix, - * kPadAfterPrefix, kPadBeforeSuffix, or - * kPadAfterSuffix. - * @see #setFormatWidth - * @see #getFormatWidth - * @see #setPadCharacter - * @see #getPadCharacterString - * @see #getPadPosition - * @see #EPadPosition - * @stable ICU 2.0 - */ - virtual void setPadPosition(EPadPosition padPos); - - /** - * Return whether or not scientific notation is used. - * @return TRUE if this object formats and parses scientific notation - * @see #setScientificNotation - * @see #getMinimumExponentDigits - * @see #setMinimumExponentDigits - * @see #isExponentSignAlwaysShown - * @see #setExponentSignAlwaysShown - * @stable ICU 2.0 - */ - virtual UBool isScientificNotation(void) const; - - /** - * Set whether or not scientific notation is used. When scientific notation - * is used, the effective maximum number of integer digits is <= 8. If the - * maximum number of integer digits is set to more than 8, the effective - * maximum will be 1. This allows this call to generate a 'default' scientific - * number format without additional changes. - * @param useScientific TRUE if this object formats and parses scientific - * notation - * @see #isScientificNotation - * @see #getMinimumExponentDigits - * @see #setMinimumExponentDigits - * @see #isExponentSignAlwaysShown - * @see #setExponentSignAlwaysShown - * @stable ICU 2.0 - */ - virtual void setScientificNotation(UBool useScientific); - - /** - * Return the minimum exponent digits that will be shown. - * @return the minimum exponent digits that will be shown - * @see #setScientificNotation - * @see #isScientificNotation - * @see #setMinimumExponentDigits - * @see #isExponentSignAlwaysShown - * @see #setExponentSignAlwaysShown - * @stable ICU 2.0 - */ - virtual int8_t getMinimumExponentDigits(void) const; - - /** - * Set the minimum exponent digits that will be shown. This has no - * effect unless scientific notation is in use. - * @param minExpDig a value >= 1 indicating the fewest exponent digits - * that will be shown. Values less than 1 will be treated as 1. - * @see #setScientificNotation - * @see #isScientificNotation - * @see #getMinimumExponentDigits - * @see #isExponentSignAlwaysShown - * @see #setExponentSignAlwaysShown - * @stable ICU 2.0 - */ - virtual void setMinimumExponentDigits(int8_t minExpDig); - - /** - * Return whether the exponent sign is always shown. - * @return TRUE if the exponent is always prefixed with either the - * localized minus sign or the localized plus sign, false if only negative - * exponents are prefixed with the localized minus sign. - * @see #setScientificNotation - * @see #isScientificNotation - * @see #setMinimumExponentDigits - * @see #getMinimumExponentDigits - * @see #setExponentSignAlwaysShown - * @stable ICU 2.0 - */ - virtual UBool isExponentSignAlwaysShown(void) const; - - /** - * Set whether the exponent sign is always shown. This has no effect - * unless scientific notation is in use. - * @param expSignAlways TRUE if the exponent is always prefixed with either - * the localized minus sign or the localized plus sign, false if only - * negative exponents are prefixed with the localized minus sign. - * @see #setScientificNotation - * @see #isScientificNotation - * @see #setMinimumExponentDigits - * @see #getMinimumExponentDigits - * @see #isExponentSignAlwaysShown - * @stable ICU 2.0 - */ - virtual void setExponentSignAlwaysShown(UBool expSignAlways); - - /** - * Return the grouping size. Grouping size is the number of digits between - * grouping separators in the integer portion of a number. For example, - * in the number "123,456.78", the grouping size is 3. - * - * @return the grouping size. - * @see setGroupingSize - * @see NumberFormat::isGroupingUsed - * @see DecimalFormatSymbols::getGroupingSeparator - * @stable ICU 2.0 - */ - int32_t getGroupingSize(void) const; - - /** - * Set the grouping size. Grouping size is the number of digits between - * grouping separators in the integer portion of a number. For example, - * in the number "123,456.78", the grouping size is 3. - * - * @param newValue the new value of the grouping size. - * @see getGroupingSize - * @see NumberFormat::setGroupingUsed - * @see DecimalFormatSymbols::setGroupingSeparator - * @stable ICU 2.0 - */ - virtual void setGroupingSize(int32_t newValue); - - /** - * Return the secondary grouping size. In some locales one - * grouping interval is used for the least significant integer - * digits (the primary grouping size), and another is used for all - * others (the secondary grouping size). A formatter supporting a - * secondary grouping size will return a positive integer unequal - * to the primary grouping size returned by - * getGroupingSize(). For example, if the primary - * grouping size is 4, and the secondary grouping size is 2, then - * the number 123456789 formats as "1,23,45,6789", and the pattern - * appears as "#,##,###0". - * @return the secondary grouping size, or a value less than - * one if there is none - * @see setSecondaryGroupingSize - * @see NumberFormat::isGroupingUsed - * @see DecimalFormatSymbols::getGroupingSeparator - * @stable ICU 2.4 - */ - int32_t getSecondaryGroupingSize(void) const; - - /** - * Set the secondary grouping size. If set to a value less than 1, - * then secondary grouping is turned off, and the primary grouping - * size is used for all intervals, not just the least significant. - * - * @param newValue the new value of the secondary grouping size. - * @see getSecondaryGroupingSize - * @see NumberFormat#setGroupingUsed - * @see DecimalFormatSymbols::setGroupingSeparator - * @stable ICU 2.4 - */ - virtual void setSecondaryGroupingSize(int32_t newValue); - -#ifndef U_HIDE_INTERNAL_API - - /** - * Returns the minimum number of grouping digits. - * Grouping separators are output if there are at least this many - * digits to the left of the first (rightmost) grouping separator, - * that is, there are at least (minimum grouping + grouping size) integer digits. - * (Subject to isGroupingUsed().) - * - * For example, if this value is 2, and the grouping size is 3, then - * 9999 -> "9999" and 10000 -> "10,000" - * - * This is a technology preview. This API may change behavior or may be removed. - * - * The default value for this attribute is 0. - * A value of 1, 0, or lower, means that the use of grouping separators - * only depends on the grouping size (and on isGroupingUsed()). - * Currently, the corresponding CLDR data is not used; this is likely to change. - * - * @see setMinimumGroupingDigits - * @see getGroupingSize - * @internal technology preview - */ - int32_t getMinimumGroupingDigits() const; - -#endif /* U_HIDE_INTERNAL_API */ - - /* Cannot use #ifndef U_HIDE_INTERNAL_API for the following draft method since it is virtual. */ - /** - * Sets the minimum grouping digits. Setting to a value less than or - * equal to 1 turns off minimum grouping digits. - * - * @param newValue the new value of minimum grouping digits. - * @see getMinimumGroupingDigits - * @internal technology preview - */ - virtual void setMinimumGroupingDigits(int32_t newValue); - - - /** - * Allows you to get the behavior of the decimal separator with integers. - * (The decimal separator will always appear with decimals.) - * - * @return TRUE if the decimal separator always appear with decimals. - * Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345 - * @stable ICU 2.0 - */ - UBool isDecimalSeparatorAlwaysShown(void) const; - - /** - * Allows you to set the behavior of the decimal separator with integers. - * (The decimal separator will always appear with decimals.) - * - * @param newValue set TRUE if the decimal separator will always appear with decimals. - * Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345 - * @stable ICU 2.0 - */ - virtual void setDecimalSeparatorAlwaysShown(UBool newValue); - - /** - * Allows you to get the parse behavior of the pattern decimal mark. - * - * @return TRUE if input must contain a match to decimal mark in pattern - * @stable ICU 54 - */ - UBool isDecimalPatternMatchRequired(void) const; - - /** - * Allows you to set the behavior of the pattern decimal mark. - * - * if TRUE, the input must have a decimal mark if one was specified in the pattern. When - * FALSE the decimal mark may be omitted from the input. - * - * @param newValue set TRUE if input must contain a match to decimal mark in pattern - * @stable ICU 54 - */ - virtual void setDecimalPatternMatchRequired(UBool newValue); - - - /** - * Synthesizes a pattern string that represents the current state - * of this Format object. - * - * @param result Output param which will receive the pattern. - * Previous contents are deleted. - * @return A reference to 'result'. - * @see applyPattern - * @stable ICU 2.0 - */ - virtual UnicodeString& toPattern(UnicodeString& result) const; - - /** - * Synthesizes a localized pattern string that represents the current - * state of this Format object. - * - * @param result Output param which will receive the localized pattern. - * Previous contents are deleted. - * @return A reference to 'result'. - * @see applyPattern - * @stable ICU 2.0 - */ - virtual UnicodeString& toLocalizedPattern(UnicodeString& result) const; - - /** - * Apply the given pattern to this Format object. A pattern is a - * short-hand specification for the various formatting properties. - * These properties can also be changed individually through the - * various setter methods. - *

- * There is no limit to integer digits are set - * by this routine, since that is the typical end-user desire; - * use setMaximumInteger if you want to set a real value. - * For negative numbers, use a second pattern, separated by a semicolon - *

-     * .      Example "#,#00.0#" -> 1,234.56
-     * 
- * This means a minimum of 2 integer digits, 1 fraction digit, and - * a maximum of 2 fraction digits. - *
-     * .      Example: "#,#00.0#;(#,#00.0#)" for negatives in parantheses.
-     * 
- * In negative patterns, the minimum and maximum counts are ignored; - * these are presumed to be set in the positive pattern. - * - * @param pattern The pattern to be applied. - * @param parseError Struct to recieve information on position - * of error if an error is encountered - * @param status Output param set to success/failure code on - * exit. If the pattern is invalid, this will be - * set to a failure result. - * @stable ICU 2.0 - */ - virtual void applyPattern(const UnicodeString& pattern, - UParseError& parseError, - UErrorCode& status); - /** - * Sets the pattern. - * @param pattern The pattern to be applied. - * @param status Output param set to success/failure code on - * exit. If the pattern is invalid, this will be - * set to a failure result. - * @stable ICU 2.0 - */ - virtual void applyPattern(const UnicodeString& pattern, - UErrorCode& status); - - /** - * Apply the given pattern to this Format object. The pattern - * is assumed to be in a localized notation. A pattern is a - * short-hand specification for the various formatting properties. - * These properties can also be changed individually through the - * various setter methods. - *

- * There is no limit to integer digits are set - * by this routine, since that is the typical end-user desire; - * use setMaximumInteger if you want to set a real value. - * For negative numbers, use a second pattern, separated by a semicolon - *

-     * .      Example "#,#00.0#" -> 1,234.56
-     * 
- * This means a minimum of 2 integer digits, 1 fraction digit, and - * a maximum of 2 fraction digits. - * - * Example: "#,#00.0#;(#,#00.0#)" for negatives in parantheses. - * - * In negative patterns, the minimum and maximum counts are ignored; - * these are presumed to be set in the positive pattern. - * - * @param pattern The localized pattern to be applied. - * @param parseError Struct to recieve information on position - * of error if an error is encountered - * @param status Output param set to success/failure code on - * exit. If the pattern is invalid, this will be - * set to a failure result. - * @stable ICU 2.0 - */ - virtual void applyLocalizedPattern(const UnicodeString& pattern, - UParseError& parseError, - UErrorCode& status); - - /** - * Apply the given pattern to this Format object. - * - * @param pattern The localized pattern to be applied. - * @param status Output param set to success/failure code on - * exit. If the pattern is invalid, this will be - * set to a failure result. - * @stable ICU 2.0 - */ - virtual void applyLocalizedPattern(const UnicodeString& pattern, - UErrorCode& status); - - - /** - * Sets the maximum number of digits allowed in the integer portion of a - * number. This override limits the integer digit count to 309. - * - * @param newValue the new value of the maximum number of digits - * allowed in the integer portion of a number. - * @see NumberFormat#setMaximumIntegerDigits - * @stable ICU 2.0 - */ - virtual void setMaximumIntegerDigits(int32_t newValue); - - /** - * Sets the minimum number of digits allowed in the integer portion of a - * number. This override limits the integer digit count to 309. - * - * @param newValue the new value of the minimum number of digits - * allowed in the integer portion of a number. - * @see NumberFormat#setMinimumIntegerDigits - * @stable ICU 2.0 - */ - virtual void setMinimumIntegerDigits(int32_t newValue); - - /** - * Sets the maximum number of digits allowed in the fraction portion of a - * number. This override limits the fraction digit count to 340. - * - * @param newValue the new value of the maximum number of digits - * allowed in the fraction portion of a number. - * @see NumberFormat#setMaximumFractionDigits - * @stable ICU 2.0 - */ - virtual void setMaximumFractionDigits(int32_t newValue); - - /** - * Sets the minimum number of digits allowed in the fraction portion of a - * number. This override limits the fraction digit count to 340. - * - * @param newValue the new value of the minimum number of digits - * allowed in the fraction portion of a number. - * @see NumberFormat#setMinimumFractionDigits - * @stable ICU 2.0 - */ - virtual void setMinimumFractionDigits(int32_t newValue); - - /** - * Returns the minimum number of significant digits that will be - * displayed. This value has no effect unless areSignificantDigitsUsed() - * returns true. - * @return the fewest significant digits that will be shown - * @stable ICU 3.0 - */ - int32_t getMinimumSignificantDigits() const; - - /** - * Returns the maximum number of significant digits that will be - * displayed. This value has no effect unless areSignificantDigitsUsed() - * returns true. - * @return the most significant digits that will be shown - * @stable ICU 3.0 - */ - int32_t getMaximumSignificantDigits() const; - - /** - * Sets the minimum number of significant digits that will be - * displayed. If min is less than one then it is set - * to one. If the maximum significant digits count is less than - * min, then it is set to min. - * This function also enables the use of significant digits - * by this formatter - areSignificantDigitsUsed() will return TRUE. - * @see #areSignificantDigitsUsed - * @param min the fewest significant digits to be shown - * @stable ICU 3.0 - */ - void setMinimumSignificantDigits(int32_t min); - - /** - * Sets the maximum number of significant digits that will be - * displayed. If max is less than one then it is set - * to one. If the minimum significant digits count is greater - * than max, then it is set to max. - * This function also enables the use of significant digits - * by this formatter - areSignificantDigitsUsed() will return TRUE. - * @see #areSignificantDigitsUsed - * @param max the most significant digits to be shown - * @stable ICU 3.0 - */ - void setMaximumSignificantDigits(int32_t max); - - /** - * Returns true if significant digits are in use, or false if - * integer and fraction digit counts are in use. - * @return true if significant digits are in use - * @stable ICU 3.0 - */ - UBool areSignificantDigitsUsed() const; - - /** - * Sets whether significant digits are in use, or integer and - * fraction digit counts are in use. - * @param useSignificantDigits true to use significant digits, or - * false to use integer and fraction digit counts - * @stable ICU 3.0 - */ - void setSignificantDigitsUsed(UBool useSignificantDigits); - - public: - /** - * Sets the currency used to display currency - * amounts. This takes effect immediately, if this format is a - * currency format. If this format is not a currency format, then - * the currency is used if and when this object becomes a - * currency format through the application of a new pattern. - * @param theCurrency a 3-letter ISO code indicating new currency - * to use. It need not be null-terminated. May be the empty - * string or NULL to indicate no currency. - * @param ec input-output error code - * @stable ICU 3.0 - */ - virtual void setCurrency(const UChar* theCurrency, UErrorCode& ec); - - /** - * Sets the currency used to display currency amounts. See - * setCurrency(const UChar*, UErrorCode&). - * @deprecated ICU 3.0. Use setCurrency(const UChar*, UErrorCode&). - */ - virtual void setCurrency(const UChar* theCurrency); - - /** - * Sets the Currency Context object used to display currency. - * This takes effect immediately, if this format is a - * currency format. - * @param currencyContext new currency context object to use. - * @stable ICU 54 - */ - void setCurrencyUsage(UCurrencyUsage newUsage, UErrorCode* ec); - - /** - * Returns the Currency Context object used to display currency - * @stable ICU 54 - */ - UCurrencyUsage getCurrencyUsage() const; - - -#ifndef U_HIDE_DEPRECATED_API - /** - * The resource tags we use to retrieve decimal format data from - * locale resource bundles. - * @deprecated ICU 3.4. This string has no public purpose. Please don't use it. - */ - static const char fgNumberPatterns[]; -#endif /* U_HIDE_DEPRECATED_API */ - -#ifndef U_HIDE_INTERNAL_API - /** - * Get a FixedDecimal corresponding to a double as it would be - * formatted by this DecimalFormat. - * Internal, not intended for public use. - * @internal - */ - FixedDecimal getFixedDecimal(double number, UErrorCode &status) const; - - /** - * Get a FixedDecimal corresponding to a formattable as it would be - * formatted by this DecimalFormat. - * Internal, not intended for public use. - * @internal - */ - FixedDecimal getFixedDecimal(const Formattable &number, UErrorCode &status) const; - - /** - * Get a FixedDecimal corresponding to a DigitList as it would be - * formatted by this DecimalFormat. Note: the DigitList may be modified. - * Internal, not intended for public use. - * @internal - */ - FixedDecimal getFixedDecimal(DigitList &number, UErrorCode &status) const; - - /** - * Get a VisibleDigitsWithExponent corresponding to a double - * as it would be formatted by this DecimalFormat. - * Internal, not intended for public use. - * @internal - */ - VisibleDigitsWithExponent &initVisibleDigitsWithExponent( - double number, - VisibleDigitsWithExponent &digits, - UErrorCode &status) const; - - /** - * Get a VisibleDigitsWithExponent corresponding to a formattable - * as it would be formatted by this DecimalFormat. - * Internal, not intended for public use. - * @internal - */ - VisibleDigitsWithExponent &initVisibleDigitsWithExponent( - const Formattable &number, - VisibleDigitsWithExponent &digits, - UErrorCode &status) const; - - /** - * Get a VisibleDigitsWithExponent corresponding to a DigitList - * as it would be formatted by this DecimalFormat. - * Note: the DigitList may be modified. - * Internal, not intended for public use. - * @internal - */ - VisibleDigitsWithExponent &initVisibleDigitsWithExponent( - DigitList &number, - VisibleDigitsWithExponent &digits, - UErrorCode &status) const; - -#endif /* U_HIDE_INTERNAL_API */ - -public: - - /** - * Return the class ID for this class. This is useful only for - * comparing to a return value from getDynamicClassID(). For example: - *
-     * .      Base* polymorphic_pointer = createPolymorphicObject();
-     * .      if (polymorphic_pointer->getDynamicClassID() ==
-     * .          Derived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. - * This method is to implement a simple version of RTTI, since not all - * C++ compilers support genuine RTTI. Polymorphic operator==() and - * clone() methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const; - -private: - - DecimalFormat(); // default constructor not implemented - - /** - * Initialize all fields of a new DecimalFormatter to a safe default value. - * Common code for use by constructors. - */ - void init(); - - /** - * Do real work of constructing a new DecimalFormat. - */ - void construct(UErrorCode& status, - UParseError& parseErr, - const UnicodeString* pattern = 0, - DecimalFormatSymbols* symbolsToAdopt = 0 - ); - - void handleCurrencySignInPattern(UErrorCode& status); - - void parse(const UnicodeString& text, - Formattable& result, - ParsePosition& pos, - UChar* currency) const; - - enum { - fgStatusInfinite, - fgStatusLength // Leave last in list. - } StatusFlags; - - UBool subparse(const UnicodeString& text, - const UnicodeString* negPrefix, - const UnicodeString* negSuffix, - const UnicodeString* posPrefix, - const UnicodeString* posSuffix, - UBool complexCurrencyParsing, - int8_t type, - ParsePosition& parsePosition, - DigitList& digits, UBool* status, - UChar* currency) const; - - // Mixed style parsing for currency. - // It parses against the current currency pattern - // using complex affix comparison - // parses against the currency plural patterns using complex affix comparison, - // and parses against the current pattern using simple affix comparison. - UBool parseForCurrency(const UnicodeString& text, - ParsePosition& parsePosition, - DigitList& digits, - UBool* status, - UChar* currency) const; - - int32_t skipPadding(const UnicodeString& text, int32_t position) const; - - int32_t compareAffix(const UnicodeString& input, - int32_t pos, - UBool isNegative, - UBool isPrefix, - const UnicodeString* affixPat, - UBool complexCurrencyParsing, - int8_t type, - UChar* currency) const; - - static UnicodeString& trimMarksFromAffix(const UnicodeString& affix, UnicodeString& trimmedAffix); - - UBool equalWithSignCompatibility(UChar32 lhs, UChar32 rhs) const; - - int32_t compareSimpleAffix(const UnicodeString& affix, - const UnicodeString& input, - int32_t pos, - UBool lenient) const; - - static int32_t skipPatternWhiteSpace(const UnicodeString& text, int32_t pos); - - static int32_t skipUWhiteSpace(const UnicodeString& text, int32_t pos); - - static int32_t skipUWhiteSpaceAndMarks(const UnicodeString& text, int32_t pos); - - static int32_t skipBidiMarks(const UnicodeString& text, int32_t pos); - - int32_t compareComplexAffix(const UnicodeString& affixPat, - const UnicodeString& input, - int32_t pos, - int8_t type, - UChar* currency) const; - - static int32_t match(const UnicodeString& text, int32_t pos, UChar32 ch); - - static int32_t match(const UnicodeString& text, int32_t pos, const UnicodeString& str); - - static UBool matchSymbol(const UnicodeString &text, int32_t position, int32_t length, const UnicodeString &symbol, - UnicodeSet *sset, UChar32 schar); - - static UBool matchDecimal(UChar32 symbolChar, - UBool sawDecimal, UChar32 sawDecimalChar, - const UnicodeSet *sset, UChar32 schar); - - static UBool matchGrouping(UChar32 groupingChar, - UBool sawGrouping, UChar32 sawGroupingChar, - const UnicodeSet *sset, - UChar32 decimalChar, const UnicodeSet *decimalSet, - UChar32 schar); - - // set up currency affix patterns for mix parsing. - // The patterns saved here are the affix patterns of default currency - // pattern and the unique affix patterns of the plural currency patterns. - // Those patterns are used by parseForCurrency(). - void setupCurrencyAffixPatterns(UErrorCode& status); - - // get the currency rounding with respect to currency usage - double getCurrencyRounding(const UChar* currency, - UErrorCode* ec) const; - - // get the currency fraction with respect to currency usage - int getCurrencyFractionDigits(const UChar* currency, - UErrorCode* ec) const; - - // hashtable operations - Hashtable* initHashForAffixPattern(UErrorCode& status); - - void deleteHashForAffixPattern(); - - void copyHashForAffixPattern(const Hashtable* source, - Hashtable* target, UErrorCode& status); - - DecimalFormatImpl *fImpl; - - /** - * Constants. - */ - - - EnumSet - fBoolFlags; - - - // style is only valid when decimal formatter is constructed by - // DecimalFormat(pattern, decimalFormatSymbol, style) - int fStyle; - - - // Affix pattern set for currency. - // It is a set of AffixPatternsForCurrency, - // each element of the set saves the negative prefix pattern, - // negative suffix pattern, positive prefix pattern, - // and positive suffix pattern of a pattern. - // It is used for currency mixed style parsing. - // It is actually is a set. - // The set contains the default currency pattern from the locale, - // and the currency plural patterns. - // Since it is a set, it does not contain duplicated items. - // For example, if 2 currency plural patterns are the same, only one pattern - // is included in the set. When parsing, we do not check whether the plural - // count match or not. - Hashtable* fAffixPatternsForCurrency; - - // Information needed for DecimalFormat to format/parse currency plural. - CurrencyPluralInfo* fCurrencyPluralInfo; - -#if UCONFIG_HAVE_PARSEALLINPUT - UNumberFormatAttributeValue fParseAllInput; -#endif - - // Decimal Format Static Sets singleton. - const DecimalFormatStaticSets *fStaticSets; - -protected: - -#ifndef U_HIDE_INTERNAL_API - /** - * Rounds a value according to the rules of this object. - * @internal - */ - DigitList& _round(const DigitList& number, DigitList& adjustedNum, UBool& isNegative, UErrorCode& status) const; -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Returns the currency in effect for this formatter. Subclasses - * should override this method as needed. Unlike getCurrency(), - * this method should never return "". - * @result output parameter for null-terminated result, which must - * have a capacity of at least 4 - * @internal - */ - virtual void getEffectiveCurrency(UChar* result, UErrorCode& ec) const; - - /** number of integer digits - * @stable ICU 2.4 - */ - static const int32_t kDoubleIntegerDigits; - /** number of fraction digits - * @stable ICU 2.4 - */ - static const int32_t kDoubleFractionDigits; - - /** - * When someone turns on scientific mode, we assume that more than this - * number of digits is due to flipping from some other mode that didn't - * restrict the maximum, and so we force 1 integer digit. We don't bother - * to track and see if someone is using exponential notation with more than - * this number, it wouldn't make sense anyway, and this is just to make sure - * that someone turning on scientific mode with default settings doesn't - * end up with lots of zeroes. - * @stable ICU 2.8 - */ - static const int32_t kMaxScientificIntegerDigits; - -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _DECIMFMT -//eof diff --git a/win32/include/spidermonkey/unicode/docmain.h b/win32/include/spidermonkey/unicode/docmain.h deleted file mode 100755 index 7fc10848..00000000 --- a/win32/include/spidermonkey/unicode/docmain.h +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/******************************************************************** - * COPYRIGHT: - * Copyright (c) 1997-2012, International Business Machines Corporation and - * others. All Rights Reserved. - * - * FILE NAME: DOCMAIN.h - * - * Date Name Description - * 12/11/2000 Ram Creation. - */ - -/** - * \file - * \brief (Non API- contains Doxygen definitions) - * - * This file contains documentation for Doxygen and doesnot have - * any significance with respect to C or C++ API - */ - -/*! \mainpage - * - * \section API API Reference Usage - * - *

C++ Programmers:

- *

Use Class Hierarchy or Alphabetical List - * or Compound List - * to find the class you are interested in. For example, to find BreakIterator, - * you can go to the Alphabetical List, then click on - * "BreakIterator". Once you are at the class, you will find an inheritance - * chart, a list of the public members, a detailed description of the class, - * then detailed member descriptions.

- * - *

C Programmers:

- *

Use Module List or File Members - * to find a list of all the functions and constants. - * For example, to find BreakIterator functions you would click on - * File List, - * then find "ubrk.h" and click on it. You will find descriptions of Defines, - * Typedefs, Enumerations, and Functions, with detailed descriptions below. - * If you want to find a specific function, such as ubrk_next(), then click - * first on File Members, then use your browser - * Find dialog to search for "ubrk_next()".

- * - * - *

API References for Previous Releases

- *

The API References for each release of ICU are also available as - * a zip file from the ICU - * download page.

- * - *
- * - *

Architecture (User's Guide)

- * - * - *
- *\htmlonly

Module List

\endhtmlonly - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Module NameCC++
Basic Types and Constantsutypes.hutypes.h
Strings and Character Iterationustring.h, utf8.h, utf16.h, UText, UCharIteratoricu::UnicodeString, icu::CharacterIterator, icu::Appendable, icu::StringPiece,icu::ByteSink
Unicode Character
Properties and Names
uchar.h, uscript.hC API
Sets of Unicode Code Points and Stringsuset.hicu::UnicodeSet
Maps from Strings to Integer Values(no C API)icu::BytesTrie, icu::UCharsTrie
Codepage Conversionucnv.h, ucnvsel.hbC API
Unicode Text Compressionucnv.h
(encoding name "SCSU" or "BOCU-1")
C API
Locales uloc.hicu::Locale
Resource Bundlesures.hicu::ResourceBundle
Normalizationunorm2.hicu::Normalizer2
Calendarsucal.hicu::Calendar
Date and Time Formattingudat.hicu::DateFormat
Message Formattingumsg.hicu::MessageFormat
Number Formattingunum.hicu::NumberFormat
Number Spellout
(Rule Based Number Formatting)
unum.h
(use UNUM_SPELLOUT)
icu::RuleBasedNumberFormat
Text Transformation
(Transliteration)
utrans.hicu::Transliterator
Bidirectional Algorithmubidi.h, ubiditransform.hC API
Arabic Shapingushape.hC API
Collationucol.hicu::Collator
String Searchingusearch.hicu::StringSearch
Index Characters/
Bucketing for Sorted Lists
(no C API)icu::AlphabeticIndex
Text Boundary Analysis
(Break Iteration)
ubrk.hicu::BreakIterator
Regular Expressionsuregex.hicu::RegexPattern, icu::RegexMatcher
StringPrepusprep.hC API
International Domain Names in Applications:
- * UTS #46 in C/C++, IDNA2003 only via C API
uidna.hidna.h
Identifier Spoofing & Confusabilityuspoof.hC API
Universal Time Scaleutmscale.hC API
Layout Engine/Complex Text Layoutloengine.hicu::LayoutEngine,icu::ParagraphLayout
ICU I/Oustdio.hustream.h
- * This main page is generated from docmain.h - */ diff --git a/win32/include/spidermonkey/unicode/dtfmtsym.h b/win32/include/spidermonkey/unicode/dtfmtsym.h deleted file mode 100755 index 75734788..00000000 --- a/win32/include/spidermonkey/unicode/dtfmtsym.h +++ /dev/null @@ -1,1014 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 1997-2016, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************** -* -* File DTFMTSYM.H -* -* Modification History: -* -* Date Name Description -* 02/19/97 aliu Converted from java. -* 07/21/98 stephen Added getZoneIndex() -* Changed to match C++ conventions -******************************************************************************** -*/ - -#ifndef DTFMTSYM_H -#define DTFMTSYM_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/calendar.h" -#include "unicode/uobject.h" -#include "unicode/locid.h" -#include "unicode/udat.h" -#include "unicode/ures.h" - -/** - * \file - * \brief C++ API: Symbols for formatting dates. - */ - -U_NAMESPACE_BEGIN - -/* forward declaration */ -class SimpleDateFormat; -class Hashtable; - -/** - * DateFormatSymbols is a public class for encapsulating localizable date-time - * formatting data -- including timezone data. DateFormatSymbols is used by - * DateFormat and SimpleDateFormat. - *

- * Rather than first creating a DateFormatSymbols to get a date-time formatter - * by using a SimpleDateFormat constructor, clients are encouraged to create a - * date-time formatter using the getTimeInstance(), getDateInstance(), or - * getDateTimeInstance() method in DateFormat. Each of these methods can return a - * date/time formatter initialized with a default format pattern along with the - * date-time formatting data for a given or default locale. After a formatter is - * created, clients may modify the format pattern using the setPattern function - * as so desired. For more information on using these formatter factory - * functions, see DateFormat. - *

- * If clients decide to create a date-time formatter with a particular format - * pattern and locale, they can do so with new SimpleDateFormat(aPattern, - * new DateFormatSymbols(aLocale)). This will load the appropriate date-time - * formatting data from the locale. - *

- * DateFormatSymbols objects are clonable. When clients obtain a - * DateFormatSymbols object, they can feel free to modify the date-time - * formatting data as necessary. For instance, clients can - * replace the localized date-time format pattern characters with the ones that - * they feel easy to remember. Or they can change the representative cities - * originally picked by default to using their favorite ones. - *

- * DateFormatSymbols are not expected to be subclassed. Data for a calendar is - * loaded out of resource bundles. The 'type' parameter indicates the type of - * calendar, for example, "gregorian" or "japanese". If the type is not gregorian - * (or NULL, or an empty string) then the type is appended to the resource name, - * for example, 'Eras_japanese' instead of 'Eras'. If the resource 'Eras_japanese' did - * not exist (even in root), then this class will fall back to just 'Eras', that is, - * Gregorian data. Therefore, the calendar implementor MUST ensure that the root - * locale at least contains any resources that are to be particularized for the - * calendar type. - */ -class U_I18N_API DateFormatSymbols U_FINAL : public UObject { -public: - /** - * Construct a DateFormatSymbols object by loading format data from - * resources for the default locale, in the default calendar (Gregorian). - *

- * NOTE: This constructor will never fail; if it cannot get resource - * data for the default locale, it will return a last-resort object - * based on hard-coded strings. - * - * @param status Status code. Failure - * results if the resources for the default cannot be - * found or cannot be loaded - * @stable ICU 2.0 - */ - DateFormatSymbols(UErrorCode& status); - - /** - * Construct a DateFormatSymbols object by loading format data from - * resources for the given locale, in the default calendar (Gregorian). - * - * @param locale Locale to load format data from. - * @param status Status code. Failure - * results if the resources for the locale cannot be - * found or cannot be loaded - * @stable ICU 2.0 - */ - DateFormatSymbols(const Locale& locale, - UErrorCode& status); - -#ifndef U_HIDE_INTERNAL_API - /** - * Construct a DateFormatSymbols object by loading format data from - * resources for the default locale, in the default calendar (Gregorian). - *

- * NOTE: This constructor will never fail; if it cannot get resource - * data for the default locale, it will return a last-resort object - * based on hard-coded strings. - * - * @param type Type of calendar (as returned by Calendar::getType). - * Will be used to access the correct set of strings. - * (NULL or empty string defaults to "gregorian".) - * @param status Status code. Failure - * results if the resources for the default cannot be - * found or cannot be loaded - * @internal - */ - DateFormatSymbols(const char *type, UErrorCode& status); - - /** - * Construct a DateFormatSymbols object by loading format data from - * resources for the given locale, in the default calendar (Gregorian). - * - * @param locale Locale to load format data from. - * @param type Type of calendar (as returned by Calendar::getType). - * Will be used to access the correct set of strings. - * (NULL or empty string defaults to "gregorian".) - * @param status Status code. Failure - * results if the resources for the locale cannot be - * found or cannot be loaded - * @internal - */ - DateFormatSymbols(const Locale& locale, - const char *type, - UErrorCode& status); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Copy constructor. - * @stable ICU 2.0 - */ - DateFormatSymbols(const DateFormatSymbols&); - - /** - * Assignment operator. - * @stable ICU 2.0 - */ - DateFormatSymbols& operator=(const DateFormatSymbols&); - - /** - * Destructor. This is nonvirtual because this class is not designed to be - * subclassed. - * @stable ICU 2.0 - */ - virtual ~DateFormatSymbols(); - - /** - * Return true if another object is semantically equal to this one. - * - * @param other the DateFormatSymbols object to be compared with. - * @return true if other is semantically equal to this. - * @stable ICU 2.0 - */ - UBool operator==(const DateFormatSymbols& other) const; - - /** - * Return true if another object is semantically unequal to this one. - * - * @param other the DateFormatSymbols object to be compared with. - * @return true if other is semantically unequal to this. - * @stable ICU 2.0 - */ - UBool operator!=(const DateFormatSymbols& other) const { return !operator==(other); } - - /** - * Gets abbreviated era strings. For example: "AD" and "BC". - * - * @param count Filled in with length of the array. - * @return the era strings. - * @stable ICU 2.0 - */ - const UnicodeString* getEras(int32_t& count) const; - - /** - * Sets abbreviated era strings. For example: "AD" and "BC". - * @param eras Array of era strings (DateFormatSymbols retains ownership.) - * @param count Filled in with length of the array. - * @stable ICU 2.0 - */ - void setEras(const UnicodeString* eras, int32_t count); - - /** - * Gets era name strings. For example: "Anno Domini" and "Before Christ". - * - * @param count Filled in with length of the array. - * @return the era name strings. - * @stable ICU 3.4 - */ - const UnicodeString* getEraNames(int32_t& count) const; - - /** - * Sets era name strings. For example: "Anno Domini" and "Before Christ". - * @param eraNames Array of era name strings (DateFormatSymbols retains ownership.) - * @param count Filled in with length of the array. - * @stable ICU 3.6 - */ - void setEraNames(const UnicodeString* eraNames, int32_t count); - - /** - * Gets narrow era strings. For example: "A" and "B". - * - * @param count Filled in with length of the array. - * @return the narrow era strings. - * @stable ICU 4.2 - */ - const UnicodeString* getNarrowEras(int32_t& count) const; - - /** - * Sets narrow era strings. For example: "A" and "B". - * @param narrowEras Array of narrow era strings (DateFormatSymbols retains ownership.) - * @param count Filled in with length of the array. - * @stable ICU 4.2 - */ - void setNarrowEras(const UnicodeString* narrowEras, int32_t count); - - /** - * Gets month strings. For example: "January", "February", etc. - * @param count Filled in with length of the array. - * @return the month strings. (DateFormatSymbols retains ownership.) - * @stable ICU 2.0 - */ - const UnicodeString* getMonths(int32_t& count) const; - - /** - * Sets month strings. For example: "January", "February", etc. - * - * @param months the new month strings. (not adopted; caller retains ownership) - * @param count Filled in with length of the array. - * @stable ICU 2.0 - */ - void setMonths(const UnicodeString* months, int32_t count); - - /** - * Gets short month strings. For example: "Jan", "Feb", etc. - * - * @param count Filled in with length of the array. - * @return the short month strings. (DateFormatSymbols retains ownership.) - * @stable ICU 2.0 - */ - const UnicodeString* getShortMonths(int32_t& count) const; - - /** - * Sets short month strings. For example: "Jan", "Feb", etc. - * @param count Filled in with length of the array. - * @param shortMonths the new short month strings. (not adopted; caller retains ownership) - * @stable ICU 2.0 - */ - void setShortMonths(const UnicodeString* shortMonths, int32_t count); - - /** - * Selector for date formatting context - * @stable ICU 3.6 - */ - enum DtContextType { - FORMAT, - STANDALONE, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal DtContextType value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - DT_CONTEXT_COUNT -#endif // U_HIDE_DEPRECATED_API - }; - - /** - * Selector for date formatting width - * @stable ICU 3.6 - */ - enum DtWidthType { - ABBREVIATED, - WIDE, - NARROW, - /** - * Short width is currently only supported for weekday names. - * @stable ICU 51 - */ - SHORT, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal DtWidthType value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - DT_WIDTH_COUNT = 4 -#endif // U_HIDE_DEPRECATED_API - }; - - /** - * Gets month strings by width and context. For example: "January", "February", etc. - * @param count Filled in with length of the array. - * @param context The formatting context, either FORMAT or STANDALONE - * @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW. - * @return the month strings. (DateFormatSymbols retains ownership.) - * @stable ICU 3.4 - */ - const UnicodeString* getMonths(int32_t& count, DtContextType context, DtWidthType width) const; - - /** - * Sets month strings by width and context. For example: "January", "February", etc. - * - * @param months The new month strings. (not adopted; caller retains ownership) - * @param count Filled in with length of the array. - * @param context The formatting context, either FORMAT or STANDALONE - * @param width The width of returned strings, either WIDE, ABBREVIATED, or NARROW. - * @stable ICU 3.6 - */ - void setMonths(const UnicodeString* months, int32_t count, DtContextType context, DtWidthType width); - - /** - * Gets wide weekday strings. For example: "Sunday", "Monday", etc. - * @param count Filled in with length of the array. - * @return the weekday strings. (DateFormatSymbols retains ownership.) - * @stable ICU 2.0 - */ - const UnicodeString* getWeekdays(int32_t& count) const; - - - /** - * Sets wide weekday strings. For example: "Sunday", "Monday", etc. - * @param weekdays the new weekday strings. (not adopted; caller retains ownership) - * @param count Filled in with length of the array. - * @stable ICU 2.0 - */ - void setWeekdays(const UnicodeString* weekdays, int32_t count); - - /** - * Gets abbreviated weekday strings. For example: "Sun", "Mon", etc. (Note: The method name is - * misleading; it does not get the CLDR-style "short" weekday strings, e.g. "Su", "Mo", etc.) - * @param count Filled in with length of the array. - * @return the abbreviated weekday strings. (DateFormatSymbols retains ownership.) - * @stable ICU 2.0 - */ - const UnicodeString* getShortWeekdays(int32_t& count) const; - - /** - * Sets abbreviated weekday strings. For example: "Sun", "Mon", etc. (Note: The method name is - * misleading; it does not set the CLDR-style "short" weekday strings, e.g. "Su", "Mo", etc.) - * @param abbrevWeekdays the new abbreviated weekday strings. (not adopted; caller retains ownership) - * @param count Filled in with length of the array. - * @stable ICU 2.0 - */ - void setShortWeekdays(const UnicodeString* abbrevWeekdays, int32_t count); - - /** - * Gets weekday strings by width and context. For example: "Sunday", "Monday", etc. - * @param count Filled in with length of the array. - * @param context The formatting context, either FORMAT or STANDALONE - * @param width The width of returned strings, either WIDE, ABBREVIATED, SHORT, or NARROW - * @return the month strings. (DateFormatSymbols retains ownership.) - * @stable ICU 3.4 - */ - const UnicodeString* getWeekdays(int32_t& count, DtContextType context, DtWidthType width) const; - - /** - * Sets weekday strings by width and context. For example: "Sunday", "Monday", etc. - * @param weekdays The new weekday strings. (not adopted; caller retains ownership) - * @param count Filled in with length of the array. - * @param context The formatting context, either FORMAT or STANDALONE - * @param width The width of returned strings, either WIDE, ABBREVIATED, SHORT, or NARROW - * @stable ICU 3.6 - */ - void setWeekdays(const UnicodeString* weekdays, int32_t count, DtContextType context, DtWidthType width); - - /** - * Gets quarter strings by width and context. For example: "1st Quarter", "2nd Quarter", etc. - * @param count Filled in with length of the array. - * @param context The formatting context, either FORMAT or STANDALONE - * @param width The width of returned strings, either WIDE or ABBREVIATED. There - * are no NARROW quarters. - * @return the quarter strings. (DateFormatSymbols retains ownership.) - * @stable ICU 3.6 - */ - const UnicodeString* getQuarters(int32_t& count, DtContextType context, DtWidthType width) const; - - /** - * Sets quarter strings by width and context. For example: "1st Quarter", "2nd Quarter", etc. - * - * @param quarters The new quarter strings. (not adopted; caller retains ownership) - * @param count Filled in with length of the array. - * @param context The formatting context, either FORMAT or STANDALONE - * @param width The width of returned strings, either WIDE or ABBREVIATED. There - * are no NARROW quarters. - * @stable ICU 3.6 - */ - void setQuarters(const UnicodeString* quarters, int32_t count, DtContextType context, DtWidthType width); - - /** - * Gets AM/PM strings. For example: "AM" and "PM". - * @param count Filled in with length of the array. - * @return the weekday strings. (DateFormatSymbols retains ownership.) - * @stable ICU 2.0 - */ - const UnicodeString* getAmPmStrings(int32_t& count) const; - - /** - * Sets ampm strings. For example: "AM" and "PM". - * @param ampms the new ampm strings. (not adopted; caller retains ownership) - * @param count Filled in with length of the array. - * @stable ICU 2.0 - */ - void setAmPmStrings(const UnicodeString* ampms, int32_t count); - -#ifndef U_HIDE_INTERNAL_API - /** - * This default time separator is used for formatting when the locale - * doesn't specify any time separator, and always recognized when parsing. - * @internal - */ - static const UChar DEFAULT_TIME_SEPARATOR = 0x003a; // ':' - - /** - * This alternate time separator is always recognized when parsing. - * @internal - */ - static const UChar ALTERNATE_TIME_SEPARATOR = 0x002e; // '.' - - /** - * Gets the time separator string. For example: ":". - * @param result Output param which will receive the time separator string. - * @return A reference to 'result'. - * @internal - */ - UnicodeString& getTimeSeparatorString(UnicodeString& result) const; - - /** - * Sets the time separator string. For example: ":". - * @param newTimeSeparator the new time separator string. - * @internal - */ - void setTimeSeparatorString(const UnicodeString& newTimeSeparator); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Gets cyclic year name strings if the calendar has them, by width and context. - * For example: "jia-zi", "yi-chou", etc. - * @param count Filled in with length of the array. - * @param context The usage context: FORMAT, STANDALONE. - * @param width The requested name width: WIDE, ABBREVIATED, NARROW. - * @return The year name strings (DateFormatSymbols retains ownership), - * or null if they are not available for this calendar. - * @stable ICU 54 - */ - const UnicodeString* getYearNames(int32_t& count, - DtContextType context, DtWidthType width) const; - - /** - * Sets cyclic year name strings by width and context. For example: "jia-zi", "yi-chou", etc. - * - * @param yearNames The new cyclic year name strings (not adopted; caller retains ownership). - * @param count The length of the array. - * @param context The usage context: FORMAT, STANDALONE (currently only FORMAT is supported). - * @param width The name width: WIDE, ABBREVIATED, NARROW (currently only ABBREVIATED is supported). - * @stable ICU 54 - */ - void setYearNames(const UnicodeString* yearNames, int32_t count, - DtContextType context, DtWidthType width); - - /** - * Gets calendar zodiac name strings if the calendar has them, by width and context. - * For example: "Rat", "Ox", "Tiger", etc. - * @param count Filled in with length of the array. - * @param context The usage context: FORMAT, STANDALONE. - * @param width The requested name width: WIDE, ABBREVIATED, NARROW. - * @return The zodiac name strings (DateFormatSymbols retains ownership), - * or null if they are not available for this calendar. - * @stable ICU 54 - */ - const UnicodeString* getZodiacNames(int32_t& count, - DtContextType context, DtWidthType width) const; - - /** - * Sets calendar zodiac name strings by width and context. For example: "Rat", "Ox", "Tiger", etc. - * - * @param zodiacNames The new zodiac name strings (not adopted; caller retains ownership). - * @param count The length of the array. - * @param context The usage context: FORMAT, STANDALONE (currently only FORMAT is supported). - * @param width The name width: WIDE, ABBREVIATED, NARROW (currently only ABBREVIATED is supported). - * @stable ICU 54 - */ - void setZodiacNames(const UnicodeString* zodiacNames, int32_t count, - DtContextType context, DtWidthType width); - -#ifndef U_HIDE_INTERNAL_API - /** - * Somewhat temporary constants for leap month pattern types, adequate for supporting - * just leap month patterns as needed for Chinese lunar calendar. - * Eventually we will add full support for different month pattern types (needed for - * other calendars such as Hindu) at which point this approach will be replaced by a - * more complete approach. - * @internal - */ - enum EMonthPatternType - { - kLeapMonthPatternFormatWide, - kLeapMonthPatternFormatAbbrev, - kLeapMonthPatternFormatNarrow, - kLeapMonthPatternStandaloneWide, - kLeapMonthPatternStandaloneAbbrev, - kLeapMonthPatternStandaloneNarrow, - kLeapMonthPatternNumeric, - kMonthPatternsCount - }; - - /** - * Somewhat temporary function for getting complete set of leap month patterns for all - * contexts & widths, indexed by EMonthPatternType values. Returns NULL if calendar - * does not have leap month patterns. Note, there is currently no setter for this. - * Eventually we will add full support for different month pattern types (needed for - * other calendars such as Hindu) at which point this approach will be replaced by a - * more complete approach. - * @param count Filled in with length of the array (may be 0). - * @return The leap month patterns (DateFormatSymbols retains ownership). - * May be NULL if there are no leap month patterns for this calendar. - * @internal - */ - const UnicodeString* getLeapMonthPatterns(int32_t& count) const; - -#endif /* U_HIDE_INTERNAL_API */ - -#ifndef U_HIDE_DEPRECATED_API - /** - * Gets timezone strings. These strings are stored in a 2-dimensional array. - * @param rowCount Output param to receive number of rows. - * @param columnCount Output param to receive number of columns. - * @return The timezone strings as a 2-d array. (DateFormatSymbols retains ownership.) - * @deprecated ICU 3.6 - */ - const UnicodeString** getZoneStrings(int32_t& rowCount, int32_t& columnCount) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Sets timezone strings. These strings are stored in a 2-dimensional array. - *

Note: SimpleDateFormat no longer use the zone strings stored in - * a DateFormatSymbols. Therefore, the time zone strings set by this mthod - * have no effects in an instance of SimpleDateFormat for formatting time - * zones. - * @param strings The timezone strings as a 2-d array to be copied. (not adopted; caller retains ownership) - * @param rowCount The number of rows (count of first index). - * @param columnCount The number of columns (count of second index). - * @stable ICU 2.0 - */ - void setZoneStrings(const UnicodeString* const* strings, int32_t rowCount, int32_t columnCount); - - /** - * Get the non-localized date-time pattern characters. - * @return the non-localized date-time pattern characters - * @stable ICU 2.0 - */ - static const UChar * U_EXPORT2 getPatternUChars(void); - - /** - * Gets localized date-time pattern characters. For example: 'u', 't', etc. - *

- * Note: ICU no longer provides localized date-time pattern characters for a locale - * starting ICU 3.8. This method returns the non-localized date-time pattern - * characters unless user defined localized data is set by setLocalPatternChars. - * @param result Output param which will receive the localized date-time pattern characters. - * @return A reference to 'result'. - * @stable ICU 2.0 - */ - UnicodeString& getLocalPatternChars(UnicodeString& result) const; - - /** - * Sets localized date-time pattern characters. For example: 'u', 't', etc. - * @param newLocalPatternChars the new localized date-time - * pattern characters. - * @stable ICU 2.0 - */ - void setLocalPatternChars(const UnicodeString& newLocalPatternChars); - - /** - * Returns the locale for this object. Two flavors are available: - * valid and actual locale. - * @stable ICU 2.8 - */ - Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const; - - /* The following type and kCapContextUsageTypeCount cannot be #ifndef U_HIDE_INTERNAL_API, - they are needed for .h file declarations. */ - /** - * Constants for capitalization context usage types. - * @internal - */ - enum ECapitalizationContextUsageType - { -#ifndef U_HIDE_INTERNAL_API - kCapContextUsageOther = 0, - kCapContextUsageMonthFormat, /* except narrow */ - kCapContextUsageMonthStandalone, /* except narrow */ - kCapContextUsageMonthNarrow, - kCapContextUsageDayFormat, /* except narrow */ - kCapContextUsageDayStandalone, /* except narrow */ - kCapContextUsageDayNarrow, - kCapContextUsageEraWide, - kCapContextUsageEraAbbrev, - kCapContextUsageEraNarrow, - kCapContextUsageZoneLong, - kCapContextUsageZoneShort, - kCapContextUsageMetazoneLong, - kCapContextUsageMetazoneShort, -#endif /* U_HIDE_INTERNAL_API */ - kCapContextUsageTypeCount = 14 - }; - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - -private: - - friend class SimpleDateFormat; - friend class DateFormatSymbolsSingleSetter; // see udat.cpp - - /** - * Abbreviated era strings. For example: "AD" and "BC". - */ - UnicodeString* fEras; - int32_t fErasCount; - - /** - * Era name strings. For example: "Anno Domini" and "Before Christ". - */ - UnicodeString* fEraNames; - int32_t fEraNamesCount; - - /** - * Narrow era strings. For example: "A" and "B". - */ - UnicodeString* fNarrowEras; - int32_t fNarrowErasCount; - - /** - * Month strings. For example: "January", "February", etc. - */ - UnicodeString* fMonths; - int32_t fMonthsCount; - - /** - * Short month strings. For example: "Jan", "Feb", etc. - */ - UnicodeString* fShortMonths; - int32_t fShortMonthsCount; - - /** - * Narrow month strings. For example: "J", "F", etc. - */ - UnicodeString* fNarrowMonths; - int32_t fNarrowMonthsCount; - - /** - * Standalone Month strings. For example: "January", "February", etc. - */ - UnicodeString* fStandaloneMonths; - int32_t fStandaloneMonthsCount; - - /** - * Standalone Short month strings. For example: "Jan", "Feb", etc. - */ - UnicodeString* fStandaloneShortMonths; - int32_t fStandaloneShortMonthsCount; - - /** - * Standalone Narrow month strings. For example: "J", "F", etc. - */ - UnicodeString* fStandaloneNarrowMonths; - int32_t fStandaloneNarrowMonthsCount; - - /** - * CLDR-style format wide weekday strings. For example: "Sunday", "Monday", etc. - */ - UnicodeString* fWeekdays; - int32_t fWeekdaysCount; - - /** - * CLDR-style format abbreviated (not short) weekday strings. For example: "Sun", "Mon", etc. - */ - UnicodeString* fShortWeekdays; - int32_t fShortWeekdaysCount; - - /** - * CLDR-style format short weekday strings. For example: "Su", "Mo", etc. - */ - UnicodeString* fShorterWeekdays; - int32_t fShorterWeekdaysCount; - - /** - * CLDR-style format narrow weekday strings. For example: "S", "M", etc. - */ - UnicodeString* fNarrowWeekdays; - int32_t fNarrowWeekdaysCount; - - /** - * CLDR-style standalone wide weekday strings. For example: "Sunday", "Monday", etc. - */ - UnicodeString* fStandaloneWeekdays; - int32_t fStandaloneWeekdaysCount; - - /** - * CLDR-style standalone abbreviated (not short) weekday strings. For example: "Sun", "Mon", etc. - */ - UnicodeString* fStandaloneShortWeekdays; - int32_t fStandaloneShortWeekdaysCount; - - /** - * CLDR-style standalone short weekday strings. For example: "Su", "Mo", etc. - */ - UnicodeString* fStandaloneShorterWeekdays; - int32_t fStandaloneShorterWeekdaysCount; - - /** - * Standalone Narrow weekday strings. For example: "Sun", "Mon", etc. - */ - UnicodeString* fStandaloneNarrowWeekdays; - int32_t fStandaloneNarrowWeekdaysCount; - - /** - * Ampm strings. For example: "AM" and "PM". - */ - UnicodeString* fAmPms; - int32_t fAmPmsCount; - - /** - * Narrow Ampm strings. For example: "a" and "p". - */ - UnicodeString* fNarrowAmPms; - int32_t fNarrowAmPmsCount; - - /** - * Time separator string. For example: ":". - */ - UnicodeString fTimeSeparator; - - /** - * Quarter strings. For example: "1st quarter", "2nd quarter", etc. - */ - UnicodeString *fQuarters; - int32_t fQuartersCount; - - /** - * Short quarters. For example: "Q1", "Q2", etc. - */ - UnicodeString *fShortQuarters; - int32_t fShortQuartersCount; - - /** - * Standalone quarter strings. For example: "1st quarter", "2nd quarter", etc. - */ - UnicodeString *fStandaloneQuarters; - int32_t fStandaloneQuartersCount; - - /** - * Standalone short quarter strings. For example: "Q1", "Q2", etc. - */ - UnicodeString *fStandaloneShortQuarters; - int32_t fStandaloneShortQuartersCount; - - /** - * All leap month patterns, for example "{0}bis". - */ - UnicodeString *fLeapMonthPatterns; - int32_t fLeapMonthPatternsCount; - - /** - * Cyclic year names, for example: "jia-zi", "yi-chou", ... "gui-hai"; - * currently we only have data for format/abbreviated. - * For the others, just get from format/abbreviated, ignore set. - */ - UnicodeString *fShortYearNames; - int32_t fShortYearNamesCount; - - /** - * Cyclic zodiac names, for example "Rat", "Ox", "Tiger", etc.; - * currently we only have data for format/abbreviated. - * For the others, just get from format/abbreviated, ignore set. - */ - UnicodeString *fShortZodiacNames; - int32_t fShortZodiacNamesCount; - - /** - * Localized names of time zones in this locale. This is a - * two-dimensional array of strings of size n by m, - * where m is at least 5 and up to 7. Each of the n rows is an - * entry containing the localized names for a single TimeZone. - * - * Each such row contains (with i ranging from 0..n-1): - * - * zoneStrings[i][0] - time zone ID - * example: America/Los_Angeles - * zoneStrings[i][1] - long name of zone in standard time - * example: Pacific Standard Time - * zoneStrings[i][2] - short name of zone in standard time - * example: PST - * zoneStrings[i][3] - long name of zone in daylight savings time - * example: Pacific Daylight Time - * zoneStrings[i][4] - short name of zone in daylight savings time - * example: PDT - * zoneStrings[i][5] - location name of zone - * example: United States (Los Angeles) - * zoneStrings[i][6] - long generic name of zone - * example: Pacific Time - * zoneStrings[i][7] - short generic of zone - * example: PT - * - * The zone ID is not localized; it corresponds to the ID - * value associated with a system time zone object. All other entries - * are localized names. If a zone does not implement daylight savings - * time, the daylight savings time names are ignored. - * - * Note:CLDR 1.5 introduced metazone and its historical mappings. - * This simple two-dimensional array is no longer sufficient to represent - * localized names and its historic changes. Since ICU 3.8.1, localized - * zone names extracted from ICU locale data is stored in a ZoneStringFormat - * instance. But we still need to support the old way of customizing - * localized zone names, so we keep this field for the purpose. - */ - UnicodeString **fZoneStrings; // Zone string array set by setZoneStrings - UnicodeString **fLocaleZoneStrings; // Zone string array created by the locale - int32_t fZoneStringsRowCount; - int32_t fZoneStringsColCount; - - Locale fZSFLocale; // Locale used for getting ZoneStringFormat - - /** - * Localized date-time pattern characters. For example: use 'u' as 'y'. - */ - UnicodeString fLocalPatternChars; - - /** - * Capitalization transforms. For each usage type, the first array element indicates - * whether to titlecase for uiListOrMenu context, the second indicates whether to - * titlecase for stand-alone context. - */ - UBool fCapitalization[kCapContextUsageTypeCount][2]; - - /** - * Abbreviated (== short) day period strings. - */ - UnicodeString *fAbbreviatedDayPeriods; - int32_t fAbbreviatedDayPeriodsCount; - - /** - * Wide day period strings. - */ - UnicodeString *fWideDayPeriods; - int32_t fWideDayPeriodsCount; - - /** - * Narrow day period strings. - */ - UnicodeString *fNarrowDayPeriods; - int32_t fNarrowDayPeriodsCount; - - /** - * Stand-alone abbreviated (== short) day period strings. - */ - UnicodeString *fStandaloneAbbreviatedDayPeriods; - int32_t fStandaloneAbbreviatedDayPeriodsCount; - - /** - * Stand-alone wide day period strings. - */ - UnicodeString *fStandaloneWideDayPeriods; - int32_t fStandaloneWideDayPeriodsCount; - - /** - * Stand-alone narrow day period strings. - */ - UnicodeString *fStandaloneNarrowDayPeriods; - int32_t fStandaloneNarrowDayPeriodsCount; - -private: - /** valid/actual locale information - * these are always ICU locales, so the length should not be a problem - */ - char validLocale[ULOC_FULLNAME_CAPACITY]; - char actualLocale[ULOC_FULLNAME_CAPACITY]; - - DateFormatSymbols(); // default constructor not implemented - - /** - * Called by the constructors to actually load data from the resources - * - * @param locale The locale to get symbols for. - * @param type Calendar Type (as from Calendar::getType()) - * @param status Input/output parameter, set to success or - * failure code upon return. - * @param useLastResortData determine if use last resort data - */ - void initializeData(const Locale& locale, const char *type, UErrorCode& status, UBool useLastResortData = FALSE); - - /** - * Copy or alias an array in another object, as appropriate. - * - * @param dstArray the copy destination array. - * @param dstCount fill in with the lenth of 'dstArray'. - * @param srcArray the source array to be copied. - * @param srcCount the length of items to be copied from the 'srcArray'. - */ - static void assignArray(UnicodeString*& dstArray, - int32_t& dstCount, - const UnicodeString* srcArray, - int32_t srcCount); - - /** - * Return true if the given arrays' contents are equal, or if the arrays are - * identical (pointers are equal). - * - * @param array1 one array to be compared with. - * @param array2 another array to be compared with. - * @param count the length of items to be copied. - * @return true if the given arrays' contents are equal, or if the arrays are - * identical (pointers are equal). - */ - static UBool arrayCompare(const UnicodeString* array1, - const UnicodeString* array2, - int32_t count); - - /** - * Create a copy, in fZoneStrings, of the given zone strings array. The - * member variables fZoneStringsRowCount and fZoneStringsColCount should be - * set already by the caller. - */ - void createZoneStrings(const UnicodeString *const * otherStrings); - - /** - * Delete all the storage owned by this object. - */ - void dispose(void); - - /** - * Copy all of the other's data to this. - * @param other the object to be copied. - */ - void copyData(const DateFormatSymbols& other); - - /** - * Create zone strings array by locale if not yet available - */ - void initZoneStringsArray(void); - - /** - * Delete just the zone strings. - */ - void disposeZoneStrings(void); - - /** - * Returns the date format field index of the pattern character c, - * or UDAT_FIELD_COUNT if c is not a pattern character. - */ - static UDateFormatField U_EXPORT2 getPatternCharIndex(UChar c); - - /** - * Returns TRUE if f (with its pattern character repeated count times) is a numeric field. - */ - static UBool U_EXPORT2 isNumericField(UDateFormatField f, int32_t count); - - /** - * Returns TRUE if c (repeated count times) is the pattern character for a numeric field. - */ - static UBool U_EXPORT2 isNumericPatternChar(UChar c, int32_t count); -public: -#ifndef U_HIDE_INTERNAL_API - /** - * Gets a DateFormatSymbols by locale. - * Unlike the constructors which always use gregorian calendar, this - * method uses the calendar in the locale. If the locale contains no - * explicit calendar, this method uses the default calendar for that - * locale. - * @param locale the locale. - * @param status error returned here. - * @return the new DateFormatSymbols which the caller owns. - * @internal For ICU use only. - */ - static DateFormatSymbols * U_EXPORT2 createForLocale( - const Locale &locale, UErrorCode &status); -#endif /* U_HIDE_INTERNAL_API */ -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _DTFMTSYM -//eof diff --git a/win32/include/spidermonkey/unicode/dtintrv.h b/win32/include/spidermonkey/unicode/dtintrv.h deleted file mode 100755 index d45614a4..00000000 --- a/win32/include/spidermonkey/unicode/dtintrv.h +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2008-2009, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -* -* File DTINTRV.H -* -******************************************************************************* -*/ - -#ifndef __DTINTRV_H__ -#define __DTINTRV_H__ - -#include "unicode/utypes.h" -#include "unicode/uobject.h" - -/** - * \file - * \brief C++ API: Date Interval data type - */ - - -U_NAMESPACE_BEGIN - - -/** - * This class represents a date interval. - * It is a pair of UDate representing from UDate 1 to UDate 2. - * @stable ICU 4.0 -**/ -class U_COMMON_API DateInterval : public UObject { -public: - - /** - * Construct a DateInterval given a from date and a to date. - * @param fromDate The from date in date interval. - * @param toDate The to date in date interval. - * @stable ICU 4.0 - */ - DateInterval(UDate fromDate, UDate toDate); - - /** - * destructor - * @stable ICU 4.0 - */ - virtual ~DateInterval(); - - /** - * Get the from date. - * @return the from date in dateInterval. - * @stable ICU 4.0 - */ - UDate getFromDate() const; - - /** - * Get the to date. - * @return the to date in dateInterval. - * @stable ICU 4.0 - */ - UDate getToDate() const; - - - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 4.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 4.0 - */ - virtual UClassID getDynamicClassID(void) const; - - - /** - * Copy constructor. - * @stable ICU 4.0 - */ - DateInterval(const DateInterval& other); - - /** - * Default assignment operator - * @stable ICU 4.0 - */ - DateInterval& operator=(const DateInterval&); - - /** - * Equality operator. - * @return TRUE if the two DateIntervals are the same - * @stable ICU 4.0 - */ - virtual UBool operator==(const DateInterval& other) const; - - /** - * Non-equality operator - * @return TRUE if the two DateIntervals are not the same - * @stable ICU 4.0 - */ - UBool operator!=(const DateInterval& other) const; - - - /** - * clone this object. - * The caller owns the result and should delete it when done. - * @return a cloned DateInterval - * @stable ICU 4.0 - */ - virtual DateInterval* clone() const; - -private: - /** - * Default constructor, not implemented. - */ - DateInterval(); - - UDate fromDate; - UDate toDate; - -} ;// end class DateInterval - - -inline UDate -DateInterval::getFromDate() const { - return fromDate; -} - - -inline UDate -DateInterval::getToDate() const { - return toDate; -} - - -inline UBool -DateInterval::operator!=(const DateInterval& other) const { - return ( !operator==(other) ); -} - - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/dtitvfmt.h b/win32/include/spidermonkey/unicode/dtitvfmt.h deleted file mode 100755 index 68360b87..00000000 --- a/win32/include/spidermonkey/unicode/dtitvfmt.h +++ /dev/null @@ -1,1046 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/******************************************************************************** -* Copyright (C) 2008-2016, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -* -* File DTITVFMT.H -* -******************************************************************************* -*/ - -#ifndef __DTITVFMT_H__ -#define __DTITVFMT_H__ - - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Format and parse date interval in a language-independent manner. - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/ucal.h" -#include "unicode/smpdtfmt.h" -#include "unicode/dtintrv.h" -#include "unicode/dtitvinf.h" -#include "unicode/dtptngen.h" - -U_NAMESPACE_BEGIN - - - -/** - * DateIntervalFormat is a class for formatting and parsing date - * intervals in a language-independent manner. - * Only formatting is supported, parsing is not supported. - * - *

- * Date interval means from one date to another date, - * for example, from "Jan 11, 2008" to "Jan 18, 2008". - * We introduced class DateInterval to represent it. - * DateInterval is a pair of UDate, which is - * the standard milliseconds since 24:00 GMT, Jan 1, 1970. - * - *

- * DateIntervalFormat formats a DateInterval into - * text as compactly as possible. - * For example, the date interval format from "Jan 11, 2008" to "Jan 18,. 2008" - * is "Jan 11-18, 2008" for English. - * And it parses text into DateInterval, - * although initially, parsing is not supported. - * - *

- * There is no structural information in date time patterns. - * For any punctuations and string literals inside a date time pattern, - * we do not know whether it is just a separator, or a prefix, or a suffix. - * Without such information, so, it is difficult to generate a sub-pattern - * (or super-pattern) by algorithm. - * So, formatting a DateInterval is pattern-driven. It is very - * similar to formatting in SimpleDateFormat. - * We introduce class DateIntervalInfo to save date interval - * patterns, similar to date time pattern in SimpleDateFormat. - * - *

- * Logically, the interval patterns are mappings - * from (skeleton, the_largest_different_calendar_field) - * to (date_interval_pattern). - * - *

- * A skeleton - *

    - *
  1. - * only keeps the field pattern letter and ignores all other parts - * in a pattern, such as space, punctuations, and string literals. - *
  2. - *
  3. - * hides the order of fields. - *
  4. - *
  5. - * might hide a field's pattern letter length. - *
  6. - *
- * - * For those non-digit calendar fields, the pattern letter length is - * important, such as MMM, MMMM, and MMMMM; EEE and EEEE, - * and the field's pattern letter length is honored. - * - * For the digit calendar fields, such as M or MM, d or dd, yy or yyyy, - * the field pattern length is ignored and the best match, which is defined - * in date time patterns, will be returned without honor the field pattern - * letter length in skeleton. - * - *

- * The calendar fields we support for interval formatting are: - * year, month, date, day-of-week, am-pm, hour, hour-of-day, minute, and second - * (though we do not currently have specific intervalFormat date for skeletons - * with seconds). - * Those calendar fields can be defined in the following order: - * year > month > date > hour (in day) > minute > second - * - * The largest different calendar fields between 2 calendars is the - * first different calendar field in above order. - * - * For example: the largest different calendar fields between "Jan 10, 2007" - * and "Feb 20, 2008" is year. - * - *

- * For other calendar fields, the compact interval formatting is not - * supported. And the interval format will be fall back to fall-back - * patterns, which is mostly "{date0} - {date1}". - * - *

- * There is a set of pre-defined static skeleton strings. - * There are pre-defined interval patterns for those pre-defined skeletons - * in locales' resource files. - * For example, for a skeleton UDAT_YEAR_ABBR_MONTH_DAY, which is "yMMMd", - * in en_US, if the largest different calendar field between date1 and date2 - * is "year", the date interval pattern is "MMM d, yyyy - MMM d, yyyy", - * such as "Jan 10, 2007 - Jan 10, 2008". - * If the largest different calendar field between date1 and date2 is "month", - * the date interval pattern is "MMM d - MMM d, yyyy", - * such as "Jan 10 - Feb 10, 2007". - * If the largest different calendar field between date1 and date2 is "day", - * the date interval pattern is "MMM d-d, yyyy", such as "Jan 10-20, 2007". - * - * For date skeleton, the interval patterns when year, or month, or date is - * different are defined in resource files. - * For time skeleton, the interval patterns when am/pm, or hour, or minute is - * different are defined in resource files. - * - *

- * If a skeleton is not found in a locale's DateIntervalInfo, which means - * the interval patterns for the skeleton is not defined in resource file, - * the interval pattern will falls back to the interval "fallback" pattern - * defined in resource file. - * If the interval "fallback" pattern is not defined, the default fall-back - * is "{date0} - {data1}". - * - *

- * For the combination of date and time, - * The rule to generate interval patterns are: - *

    - *
  1. - * when the year, month, or day differs, falls back to fall-back - * interval pattern, which mostly is the concatenate the two original - * expressions with a separator between, - * For example, interval pattern from "Jan 10, 2007 10:10 am" - * to "Jan 11, 2007 10:10am" is - * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" - *
  2. - *
  3. - * otherwise, present the date followed by the range expression - * for the time. - * For example, interval pattern from "Jan 10, 2007 10:10 am" - * to "Jan 10, 2007 11:10am" is "Jan 10, 2007 10:10 am - 11:10am" - *
  4. - *
- * - * - *

- * If two dates are the same, the interval pattern is the single date pattern. - * For example, interval pattern from "Jan 10, 2007" to "Jan 10, 2007" is - * "Jan 10, 2007". - * - * Or if the presenting fields between 2 dates have the exact same values, - * the interval pattern is the single date pattern. - * For example, if user only requests year and month, - * the interval pattern from "Jan 10, 2007" to "Jan 20, 2007" is "Jan 2007". - * - *

- * DateIntervalFormat needs the following information for correct - * formatting: time zone, calendar type, pattern, date format symbols, - * and date interval patterns. - * It can be instantiated in 2 ways: - *

    - *
  1. - * create an instance using default or given locale plus given skeleton. - * Users are encouraged to created date interval formatter this way and - * to use the pre-defined skeleton macros, such as - * UDAT_YEAR_NUM_MONTH, which consists the calendar fields and - * the format style. - *
  2. - *
  3. - * create an instance using default or given locale plus given skeleton - * plus a given DateIntervalInfo. - * This factory method is for powerful users who want to provide their own - * interval patterns. - * Locale provides the timezone, calendar, and format symbols information. - * Local plus skeleton provides full pattern information. - * DateIntervalInfo provides the date interval patterns. - *
  4. - *
- * - *

- * For the calendar field pattern letter, such as G, y, M, d, a, h, H, m, s etc. - * DateIntervalFormat uses the same syntax as that of - * DateTime format. - * - *

- * Code Sample: general usage - *

- * \code
- *   // the date interval object which the DateIntervalFormat formats on
- *   // and parses into
- *   DateInterval*  dtInterval = new DateInterval(1000*3600*24, 1000*3600*24*2);
- *   UErrorCode status = U_ZERO_ERROR;
- *   DateIntervalFormat* dtIntervalFmt = DateIntervalFormat::createInstance(
- *                           UDAT_YEAR_MONTH_DAY,
- *                           Locale("en", "GB", ""), status);
- *   UnicodeUnicodeString dateIntervalString;
- *   FieldPosition pos = 0;
- *   // formatting
- *   dtIntervalFmt->format(dtInterval, dateIntervalUnicodeString, pos, status);
- *   delete dtIntervalFmt;
- * \endcode
- * 
- */ - -class U_I18N_API DateIntervalFormat : public Format { -public: - - /** - * Construct a DateIntervalFormat from skeleton and the default locale. - * - * This is a convenient override of - * createInstance(const UnicodeString& skeleton, const Locale& locale, - * UErrorCode&) - * with the value of locale as default locale. - * - * @param skeleton the skeleton on which interval format based. - * @param status output param set to success/failure code on exit - * @return a date time interval formatter which the caller owns. - * @stable ICU 4.0 - */ - static DateIntervalFormat* U_EXPORT2 createInstance( - const UnicodeString& skeleton, - UErrorCode& status); - - /** - * Construct a DateIntervalFormat from skeleton and a given locale. - *

- * In this factory method, - * the date interval pattern information is load from resource files. - * Users are encouraged to created date interval formatter this way and - * to use the pre-defined skeleton macros. - * - *

- * There are pre-defined skeletons (defined in udate.h) having predefined - * interval patterns in resource files. - * Users are encouraged to use those macros. - * For example: - * DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status) - * - * The given Locale provides the interval patterns. - * For example, for en_GB, if skeleton is UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY, - * which is "yMMMEEEd", - * the interval patterns defined in resource file to above skeleton are: - * "EEE, d MMM, yyyy - EEE, d MMM, yyyy" for year differs, - * "EEE, d MMM - EEE, d MMM, yyyy" for month differs, - * "EEE, d - EEE, d MMM, yyyy" for day differs, - * @param skeleton the skeleton on which the interval format is based. - * @param locale the given locale - * @param status output param set to success/failure code on exit - * @return a date time interval formatter which the caller owns. - * @stable ICU 4.0 - *

- *

Sample code

- * \snippet samples/dtitvfmtsample/dtitvfmtsample.cpp dtitvfmtPreDefined1 - * \snippet samples/dtitvfmtsample/dtitvfmtsample.cpp dtitvfmtPreDefined - *

- */ - - static DateIntervalFormat* U_EXPORT2 createInstance( - const UnicodeString& skeleton, - const Locale& locale, - UErrorCode& status); - - /** - * Construct a DateIntervalFormat from skeleton - * DateIntervalInfo, and default locale. - * - * This is a convenient override of - * createInstance(const UnicodeString& skeleton, const Locale& locale, - * const DateIntervalInfo& dtitvinf, UErrorCode&) - * with the locale value as default locale. - * - * @param skeleton the skeleton on which interval format based. - * @param dtitvinf the DateIntervalInfo object. - * @param status output param set to success/failure code on exit - * @return a date time interval formatter which the caller owns. - * @stable ICU 4.0 - */ - static DateIntervalFormat* U_EXPORT2 createInstance( - const UnicodeString& skeleton, - const DateIntervalInfo& dtitvinf, - UErrorCode& status); - - /** - * Construct a DateIntervalFormat from skeleton - * a DateIntervalInfo, and the given locale. - * - *

- * In this factory method, user provides its own date interval pattern - * information, instead of using those pre-defined data in resource file. - * This factory method is for powerful users who want to provide their own - * interval patterns. - *

- * There are pre-defined skeletons (defined in udate.h) having predefined - * interval patterns in resource files. - * Users are encouraged to use those macros. - * For example: - * DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status) - * - * The DateIntervalInfo provides the interval patterns. - * and the DateIntervalInfo ownership remains to the caller. - * - * User are encouraged to set default interval pattern in DateIntervalInfo - * as well, if they want to set other interval patterns ( instead of - * reading the interval patterns from resource files). - * When the corresponding interval pattern for a largest calendar different - * field is not found ( if user not set it ), interval format fallback to - * the default interval pattern. - * If user does not provide default interval pattern, it fallback to - * "{date0} - {date1}" - * - * @param skeleton the skeleton on which interval format based. - * @param locale the given locale - * @param dtitvinf the DateIntervalInfo object. - * @param status output param set to success/failure code on exit - * @return a date time interval formatter which the caller owns. - * @stable ICU 4.0 - *

- *

Sample code

- * \snippet samples/dtitvfmtsample/dtitvfmtsample.cpp dtitvfmtPreDefined1 - * \snippet samples/dtitvfmtsample/dtitvfmtsample.cpp dtitvfmtCustomized - *

- */ - static DateIntervalFormat* U_EXPORT2 createInstance( - const UnicodeString& skeleton, - const Locale& locale, - const DateIntervalInfo& dtitvinf, - UErrorCode& status); - - /** - * Destructor. - * @stable ICU 4.0 - */ - virtual ~DateIntervalFormat(); - - /** - * Clone this Format object polymorphically. The caller owns the result and - * should delete it when done. - * @return A copy of the object. - * @stable ICU 4.0 - */ - virtual Format* clone(void) const; - - /** - * Return true if the given Format objects are semantically equal. Objects - * of different subclasses are considered unequal. - * @param other the object to be compared with. - * @return true if the given Format objects are semantically equal. - * @stable ICU 4.0 - */ - virtual UBool operator==(const Format& other) const; - - /** - * Return true if the given Format objects are not semantically equal. - * Objects of different subclasses are considered unequal. - * @param other the object to be compared with. - * @return true if the given Format objects are not semantically equal. - * @stable ICU 4.0 - */ - UBool operator!=(const Format& other) const; - - - using Format::format; - - /** - * Format an object to produce a string. This method handles Formattable - * objects with a DateInterval type. - * If a the Formattable object type is not a DateInterval, - * then it returns a failing UErrorCode. - * - * @param obj The object to format. - * Must be a DateInterval. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param fieldPosition On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * There may be multiple instances of a given field type - * in an interval format; in this case the fieldPosition - * offsets refer to the first instance. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.0 - */ - virtual UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPosition& fieldPosition, - UErrorCode& status) const ; - - - - /** - * Format a DateInterval to produce a string. - * - * @param dtInterval DateInterval to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param fieldPosition On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * There may be multiple instances of a given field type - * in an interval format; in this case the fieldPosition - * offsets refer to the first instance. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.0 - */ - UnicodeString& format(const DateInterval* dtInterval, - UnicodeString& appendTo, - FieldPosition& fieldPosition, - UErrorCode& status) const ; - - - /** - * Format 2 Calendars to produce a string. - * - * Note: "fromCalendar" and "toCalendar" are not const, - * since calendar is not const in SimpleDateFormat::format(Calendar&), - * - * @param fromCalendar calendar set to the from date in date interval - * to be formatted into date interval string - * @param toCalendar calendar set to the to date in date interval - * to be formatted into date interval string - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param fieldPosition On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * There may be multiple instances of a given field type - * in an interval format; in this case the fieldPosition - * offsets refer to the first instance. - * @param status Output param filled with success/failure status. - * Caller needs to make sure it is SUCCESS - * at the function entrance - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.0 - */ - UnicodeString& format(Calendar& fromCalendar, - Calendar& toCalendar, - UnicodeString& appendTo, - FieldPosition& fieldPosition, - UErrorCode& status) const ; - - /** - * Date interval parsing is not supported. Please do not use. - *

- * This method should handle parsing of - * date time interval strings into Formattable objects with - * DateInterval type, which is a pair of UDate. - *

- * Before calling, set parse_pos.index to the offset you want to start - * parsing at in the source. After calling, parse_pos.index is the end of - * the text you parsed. If error occurs, index is unchanged. - *

- * When parsing, leading whitespace is discarded (with a successful parse), - * while trailing whitespace is left as is. - *

- * See Format::parseObject() for more. - * - * @param source The string to be parsed into an object. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param parse_pos The position to start parsing at. Since no parsing - * is supported, upon return this param is unchanged. - * @return A newly created Formattable* object, or NULL - * on failure. The caller owns this and should - * delete it when done. - * @internal ICU 4.0 - */ - virtual void parseObject(const UnicodeString& source, - Formattable& result, - ParsePosition& parse_pos) const; - - - /** - * Gets the date time interval patterns. - * @return the date time interval patterns associated with - * this date interval formatter. - * @stable ICU 4.0 - */ - const DateIntervalInfo* getDateIntervalInfo(void) const; - - - /** - * Set the date time interval patterns. - * @param newIntervalPatterns the given interval patterns to copy. - * @param status output param set to success/failure code on exit - * @stable ICU 4.0 - */ - void setDateIntervalInfo(const DateIntervalInfo& newIntervalPatterns, - UErrorCode& status); - - - /** - * Gets the date formatter. The DateIntervalFormat instance continues to own - * the returned DateFormatter object, and will use and possibly modify it - * during format operations. In a multi-threaded environment, the returned - * DateFormat can only be used if it is certain that no other threads are - * concurrently using this DateIntervalFormatter, even for nominally const - * functions. - * - * @return the date formatter associated with this date interval formatter. - * @stable ICU 4.0 - */ - const DateFormat* getDateFormat(void) const; - - /** - * Returns a reference to the TimeZone used by this DateIntervalFormat's calendar. - * @return the time zone associated with the calendar of DateIntervalFormat. - * @stable ICU 4.8 - */ - virtual const TimeZone& getTimeZone(void) const; - - /** - * Sets the time zone for the calendar used by this DateIntervalFormat object. The - * caller no longer owns the TimeZone object and should not delete it after this call. - * @param zoneToAdopt the TimeZone to be adopted. - * @stable ICU 4.8 - */ - virtual void adoptTimeZone(TimeZone* zoneToAdopt); - - /** - * Sets the time zone for the calendar used by this DateIntervalFormat object. - * @param zone the new time zone. - * @stable ICU 4.8 - */ - virtual void setTimeZone(const TimeZone& zone); - - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 4.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 4.0 - */ - virtual UClassID getDynamicClassID(void) const; - -protected: - - /** - * Copy constructor. - * @stable ICU 4.0 - */ - DateIntervalFormat(const DateIntervalFormat&); - - /** - * Assignment operator. - * @stable ICU 4.0 - */ - DateIntervalFormat& operator=(const DateIntervalFormat&); - -private: - - /* - * This is for ICU internal use only. Please do not use. - * Save the interval pattern information. - * Interval pattern consists of 2 single date patterns and the separator. - * For example, interval pattern "MMM d - MMM d, yyyy" consists - * a single date pattern "MMM d", another single date pattern "MMM d, yyyy", - * and a separator "-". - * The pattern is divided into 2 parts. For above example, - * the first part is "MMM d - ", and the second part is "MMM d, yyyy". - * Also, the first date appears in an interval pattern could be - * the earlier date or the later date. - * And such information is saved in the interval pattern as well. - */ - struct PatternInfo { - UnicodeString firstPart; - UnicodeString secondPart; - /** - * Whether the first date in interval pattern is later date or not. - * Fallback format set the default ordering. - * And for a particular interval pattern, the order can be - * overriden by prefixing the interval pattern with "latestFirst:" or - * "earliestFirst:" - * For example, given 2 date, Jan 10, 2007 to Feb 10, 2007. - * if the fallback format is "{0} - {1}", - * and the pattern is "d MMM - d MMM yyyy", the interval format is - * "10 Jan - 10 Feb, 2007". - * If the pattern is "latestFirst:d MMM - d MMM yyyy", - * the interval format is "10 Feb - 10 Jan, 2007" - */ - UBool laterDateFirst; - }; - - - /** - * default constructor - * @internal (private) - */ - DateIntervalFormat(); - - /** - * Construct a DateIntervalFormat from DateFormat, - * a DateIntervalInfo, and skeleton. - * DateFormat provides the timezone, calendar, - * full pattern, and date format symbols information. - * It should be a SimpleDateFormat object which - * has a pattern in it. - * the DateIntervalInfo provides the interval patterns. - * - * Note: the DateIntervalFormat takes ownership of both - * DateFormat and DateIntervalInfo objects. - * Caller should not delete them. - * - * @param locale the locale of this date interval formatter. - * @param dtItvInfo the DateIntervalInfo object to be adopted. - * @param skeleton the skeleton of the date formatter - * @param status output param set to success/failure code on exit - */ - DateIntervalFormat(const Locale& locale, DateIntervalInfo* dtItvInfo, - const UnicodeString* skeleton, UErrorCode& status); - - - /** - * Construct a DateIntervalFormat from DateFormat - * and a DateIntervalInfo. - * - * It is a wrapper of the constructor. - * - * @param locale the locale of this date interval formatter. - * @param dtitvinf the DateIntervalInfo object to be adopted. - * @param skeleton the skeleton of this formatter. - * @param status Output param set to success/failure code. - * @return a date time interval formatter which the caller owns. - */ - static DateIntervalFormat* U_EXPORT2 create(const Locale& locale, - DateIntervalInfo* dtitvinf, - const UnicodeString* skeleton, - UErrorCode& status); - - /** - * Below are for generating interval patterns local to the formatter - */ - - /** - * Provide an updated FieldPosition posResult based on two formats, - * the FieldPosition values for each of them, and the pattern used - * to combine them. The idea is for posResult to indicate the first - * instance (if any) of the specified field in the combined result, - * with correct offsets. - * - * @param combiningPattern Pattern used to combine pat0 and pat1 - * @param pat0 Formatted date/time value to replace {0} - * @param pos0 FieldPosition within pat0 - * @param pat1 Formatted date/time value to replace {1} - * @param pos1 FieldPosition within pat1 - * @param posResult FieldPosition to be set to the correct - * position of the first field instance when - * pat0 and pat1 are combined using combiningPattern - */ - static void - adjustPosition(UnicodeString& combiningPattern, // has {0} and {1} in it - UnicodeString& pat0, FieldPosition& pos0, // pattern and pos corresponding to {0} - UnicodeString& pat1, FieldPosition& pos1, // pattern and pos corresponding to {1} - FieldPosition& posResult); - - - /** - * Format 2 Calendars using fall-back interval pattern - * - * The full pattern used in this fall-back format is the - * full pattern of the date formatter. - * - * gFormatterMutex must already be locked when calling this function. - * - * @param fromCalendar calendar set to the from date in date interval - * to be formatted into date interval string - * @param toCalendar calendar set to the to date in date interval - * to be formatted into date interval string - * @param fromToOnSameDay TRUE iff from and to dates are on the same day - * (any difference is in ampm/hours or below) - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status output param set to success/failure code on exit - * @return Reference to 'appendTo' parameter. - * @internal (private) - */ - UnicodeString& fallbackFormat(Calendar& fromCalendar, - Calendar& toCalendar, - UBool fromToOnSameDay, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - - - /** - * Initialize interval patterns locale to this formatter - * - * This code is a bit complicated since - * 1. the interval patterns saved in resource bundle files are interval - * patterns based on date or time only. - * It does not have interval patterns based on both date and time. - * Interval patterns on both date and time are algorithm generated. - * - * For example, it has interval patterns on skeleton "dMy" and "hm", - * but it does not have interval patterns on skeleton "dMyhm". - * - * The rule to generate interval patterns for both date and time skeleton are - * 1) when the year, month, or day differs, concatenate the two original - * expressions with a separator between, - * For example, interval pattern from "Jan 10, 2007 10:10 am" - * to "Jan 11, 2007 10:10am" is - * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" - * - * 2) otherwise, present the date followed by the range expression - * for the time. - * For example, interval pattern from "Jan 10, 2007 10:10 am" - * to "Jan 10, 2007 11:10am" is - * "Jan 10, 2007 10:10 am - 11:10am" - * - * 2. even a pattern does not request a certain calendar field, - * the interval pattern needs to include such field if such fields are - * different between 2 dates. - * For example, a pattern/skeleton is "hm", but the interval pattern - * includes year, month, and date when year, month, and date differs. - * - * - * @param status output param set to success/failure code on exit - */ - void initializePattern(UErrorCode& status); - - - - /** - * Set fall back interval pattern given a calendar field, - * a skeleton, and a date time pattern generator. - * @param field the largest different calendar field - * @param skeleton a skeleton - * @param status output param set to success/failure code on exit - */ - void setFallbackPattern(UCalendarDateFields field, - const UnicodeString& skeleton, - UErrorCode& status); - - - - /** - * get separated date and time skeleton from a combined skeleton. - * - * The difference between date skeleton and normalizedDateSkeleton are: - * 1. both 'y' and 'd' are appeared only once in normalizeDateSkeleton - * 2. 'E' and 'EE' are normalized into 'EEE' - * 3. 'MM' is normalized into 'M' - * - ** the difference between time skeleton and normalizedTimeSkeleton are: - * 1. both 'H' and 'h' are normalized as 'h' in normalized time skeleton, - * 2. 'a' is omitted in normalized time skeleton. - * 3. there is only one appearance for 'h', 'm','v', 'z' in normalized time - * skeleton - * - * - * @param skeleton given combined skeleton. - * @param date Output parameter for date only skeleton. - * @param normalizedDate Output parameter for normalized date only - * - * @param time Output parameter for time only skeleton. - * @param normalizedTime Output parameter for normalized time only - * skeleton. - * - */ - static void U_EXPORT2 getDateTimeSkeleton(const UnicodeString& skeleton, - UnicodeString& date, - UnicodeString& normalizedDate, - UnicodeString& time, - UnicodeString& normalizedTime); - - - - /** - * Generate date or time interval pattern from resource, - * and set them into the interval pattern locale to this formatter. - * - * It needs to handle the following: - * 1. need to adjust field width. - * For example, the interval patterns saved in DateIntervalInfo - * includes "dMMMy", but not "dMMMMy". - * Need to get interval patterns for dMMMMy from dMMMy. - * Another example, the interval patterns saved in DateIntervalInfo - * includes "hmv", but not "hmz". - * Need to get interval patterns for "hmz' from 'hmv' - * - * 2. there might be no pattern for 'y' differ for skeleton "Md", - * in order to get interval patterns for 'y' differ, - * need to look for it from skeleton 'yMd' - * - * @param dateSkeleton normalized date skeleton - * @param timeSkeleton normalized time skeleton - * @return whether the resource is found for the skeleton. - * TRUE if interval pattern found for the skeleton, - * FALSE otherwise. - */ - UBool setSeparateDateTimePtn(const UnicodeString& dateSkeleton, - const UnicodeString& timeSkeleton); - - - - - /** - * Generate interval pattern from existing resource - * - * It not only save the interval patterns, - * but also return the extended skeleton and its best match skeleton. - * - * @param field largest different calendar field - * @param skeleton skeleton - * @param bestSkeleton the best match skeleton which has interval pattern - * defined in resource - * @param differenceInfo the difference between skeleton and best skeleton - * 0 means the best matched skeleton is the same as input skeleton - * 1 means the fields are the same, but field width are different - * 2 means the only difference between fields are v/z, - * -1 means there are other fields difference - * - * @param extendedSkeleton extended skeleton - * @param extendedBestSkeleton extended best match skeleton - * @return whether the interval pattern is found - * through extending skeleton or not. - * TRUE if interval pattern is found by - * extending skeleton, FALSE otherwise. - */ - UBool setIntervalPattern(UCalendarDateFields field, - const UnicodeString* skeleton, - const UnicodeString* bestSkeleton, - int8_t differenceInfo, - UnicodeString* extendedSkeleton = NULL, - UnicodeString* extendedBestSkeleton = NULL); - - /** - * Adjust field width in best match interval pattern to match - * the field width in input skeleton. - * - * TODO (xji) make a general solution - * The adjusting rule can be: - * 1. always adjust - * 2. never adjust - * 3. default adjust, which means adjust according to the following rules - * 3.1 always adjust string, such as MMM and MMMM - * 3.2 never adjust between string and numeric, such as MM and MMM - * 3.3 always adjust year - * 3.4 do not adjust 'd', 'h', or 'm' if h presents - * 3.5 do not adjust 'M' if it is numeric(?) - * - * Since date interval format is well-formed format, - * date and time skeletons are normalized previously, - * till this stage, the adjust here is only "adjust strings, such as MMM - * and MMMM, EEE and EEEE. - * - * @param inputSkeleton the input skeleton - * @param bestMatchSkeleton the best match skeleton - * @param bestMatchIntervalPattern the best match interval pattern - * @param differenceInfo the difference between 2 skeletons - * 1 means only field width differs - * 2 means v/z exchange - * @param adjustedIntervalPattern adjusted interval pattern - */ - static void U_EXPORT2 adjustFieldWidth( - const UnicodeString& inputSkeleton, - const UnicodeString& bestMatchSkeleton, - const UnicodeString& bestMatchIntervalPattern, - int8_t differenceInfo, - UnicodeString& adjustedIntervalPattern); - - /** - * Concat a single date pattern with a time interval pattern, - * set it into the intervalPatterns, while field is time field. - * This is used to handle time interval patterns on skeleton with - * both time and date. Present the date followed by - * the range expression for the time. - * @param format date and time format - * @param datePattern date pattern - * @param field time calendar field: AM_PM, HOUR, MINUTE - * @param status output param set to success/failure code on exit - */ - void concatSingleDate2TimeInterval(UnicodeString& format, - const UnicodeString& datePattern, - UCalendarDateFields field, - UErrorCode& status); - - /** - * check whether a calendar field present in a skeleton. - * @param field calendar field need to check - * @param skeleton given skeleton on which to check the calendar field - * @return true if field present in a skeleton. - */ - static UBool U_EXPORT2 fieldExistsInSkeleton(UCalendarDateFields field, - const UnicodeString& skeleton); - - - /** - * Split interval patterns into 2 part. - * @param intervalPattern interval pattern - * @return the index in interval pattern which split the pattern into 2 part - */ - static int32_t U_EXPORT2 splitPatternInto2Part(const UnicodeString& intervalPattern); - - - /** - * Break interval patterns as 2 part and save them into pattern info. - * @param field calendar field - * @param intervalPattern interval pattern - */ - void setIntervalPattern(UCalendarDateFields field, - const UnicodeString& intervalPattern); - - - /** - * Break interval patterns as 2 part and save them into pattern info. - * @param field calendar field - * @param intervalPattern interval pattern - * @param laterDateFirst whether later date appear first in interval pattern - */ - void setIntervalPattern(UCalendarDateFields field, - const UnicodeString& intervalPattern, - UBool laterDateFirst); - - - /** - * Set pattern information. - * - * @param field calendar field - * @param firstPart the first part in interval pattern - * @param secondPart the second part in interval pattern - * @param laterDateFirst whether the first date in intervalPattern - * is earlier date or later date - */ - void setPatternInfo(UCalendarDateFields field, - const UnicodeString* firstPart, - const UnicodeString* secondPart, - UBool laterDateFirst); - - /** - * Format 2 Calendars to produce a string. - * Implementation of the similar public format function. - * Must be called with gFormatterMutex already locked. - * - * Note: "fromCalendar" and "toCalendar" are not const, - * since calendar is not const in SimpleDateFormat::format(Calendar&), - * - * @param fromCalendar calendar set to the from date in date interval - * to be formatted into date interval string - * @param toCalendar calendar set to the to date in date interval - * to be formatted into date interval string - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param fieldPosition On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * There may be multiple instances of a given field type - * in an interval format; in this case the fieldPosition - * offsets refer to the first instance. - * @param status Output param filled with success/failure status. - * Caller needs to make sure it is SUCCESS - * at the function entrance - * @return Reference to 'appendTo' parameter. - * @internal (private) - */ - UnicodeString& formatImpl(Calendar& fromCalendar, - Calendar& toCalendar, - UnicodeString& appendTo, - FieldPosition& fieldPosition, - UErrorCode& status) const ; - - - // from calendar field to pattern letter - static const UChar fgCalendarFieldToPatternLetter[]; - - - /** - * The interval patterns for this locale. - */ - DateIntervalInfo* fInfo; - - /** - * The DateFormat object used to format single pattern - */ - SimpleDateFormat* fDateFormat; - - /** - * The 2 calendars with the from and to date. - * could re-use the calendar in fDateFormat, - * but keeping 2 calendars make it clear and clean. - */ - Calendar* fFromCalendar; - Calendar* fToCalendar; - - Locale fLocale; - - /** - * Following are interval information relevant (locale) to this formatter. - */ - UnicodeString fSkeleton; - PatternInfo fIntervalPatterns[DateIntervalInfo::kIPI_MAX_INDEX]; - - /** - * Patterns for fallback formatting. - */ - UnicodeString* fDatePattern; - UnicodeString* fTimePattern; - UnicodeString* fDateTimeFormat; -}; - -inline UBool -DateIntervalFormat::operator!=(const Format& other) const { - return !operator==(other); -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _DTITVFMT_H__ -//eof diff --git a/win32/include/spidermonkey/unicode/dtitvinf.h b/win32/include/spidermonkey/unicode/dtitvinf.h deleted file mode 100755 index 325eca66..00000000 --- a/win32/include/spidermonkey/unicode/dtitvinf.h +++ /dev/null @@ -1,522 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * Copyright (C) 2008-2016, International Business Machines Corporation and - * others. All Rights Reserved. - ******************************************************************************* - * - * File DTITVINF.H - * - ******************************************************************************* - */ - -#ifndef __DTITVINF_H__ -#define __DTITVINF_H__ - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Date/Time interval patterns for formatting date/time interval - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/udat.h" -#include "unicode/locid.h" -#include "unicode/ucal.h" -#include "unicode/dtptngen.h" - -U_NAMESPACE_BEGIN - -/** - * DateIntervalInfo is a public class for encapsulating localizable - * date time interval patterns. It is used by DateIntervalFormat. - * - *

- * For most users, ordinary use of DateIntervalFormat does not need to create - * DateIntervalInfo object directly. - * DateIntervalFormat will take care of it when creating a date interval - * formatter when user pass in skeleton and locale. - * - *

- * For power users, who want to create their own date interval patterns, - * or want to re-set date interval patterns, they could do so by - * directly creating DateIntervalInfo and manupulating it. - * - *

- * Logically, the interval patterns are mappings - * from (skeleton, the_largest_different_calendar_field) - * to (date_interval_pattern). - * - *

- * A skeleton - *

    - *
  1. - * only keeps the field pattern letter and ignores all other parts - * in a pattern, such as space, punctuations, and string literals. - *
  2. - * hides the order of fields. - *
  3. - * might hide a field's pattern letter length. - * - * For those non-digit calendar fields, the pattern letter length is - * important, such as MMM, MMMM, and MMMMM; EEE and EEEE, - * and the field's pattern letter length is honored. - * - * For the digit calendar fields, such as M or MM, d or dd, yy or yyyy, - * the field pattern length is ignored and the best match, which is defined - * in date time patterns, will be returned without honor the field pattern - * letter length in skeleton. - *
- * - *

- * The calendar fields we support for interval formatting are: - * year, month, date, day-of-week, am-pm, hour, hour-of-day, and minute. - * Those calendar fields can be defined in the following order: - * year > month > date > am-pm > hour > minute - * - * The largest different calendar fields between 2 calendars is the - * first different calendar field in above order. - * - * For example: the largest different calendar fields between "Jan 10, 2007" - * and "Feb 20, 2008" is year. - * - *

- * There is a set of pre-defined static skeleton strings. - * There are pre-defined interval patterns for those pre-defined skeletons - * in locales' resource files. - * For example, for a skeleton UDAT_YEAR_ABBR_MONTH_DAY, which is "yMMMd", - * in en_US, if the largest different calendar field between date1 and date2 - * is "year", the date interval pattern is "MMM d, yyyy - MMM d, yyyy", - * such as "Jan 10, 2007 - Jan 10, 2008". - * If the largest different calendar field between date1 and date2 is "month", - * the date interval pattern is "MMM d - MMM d, yyyy", - * such as "Jan 10 - Feb 10, 2007". - * If the largest different calendar field between date1 and date2 is "day", - * the date interval pattern is "MMM d-d, yyyy", such as "Jan 10-20, 2007". - * - * For date skeleton, the interval patterns when year, or month, or date is - * different are defined in resource files. - * For time skeleton, the interval patterns when am/pm, or hour, or minute is - * different are defined in resource files. - * - * - *

- * There are 2 dates in interval pattern. For most locales, the first date - * in an interval pattern is the earlier date. There might be a locale in which - * the first date in an interval pattern is the later date. - * We use fallback format for the default order for the locale. - * For example, if the fallback format is "{0} - {1}", it means - * the first date in the interval pattern for this locale is earlier date. - * If the fallback format is "{1} - {0}", it means the first date is the - * later date. - * For a particular interval pattern, the default order can be overriden - * by prefixing "latestFirst:" or "earliestFirst:" to the interval pattern. - * For example, if the fallback format is "{0}-{1}", - * but for skeleton "yMMMd", the interval pattern when day is different is - * "latestFirst:d-d MMM yy", it means by default, the first date in interval - * pattern is the earlier date. But for skeleton "yMMMd", when day is different, - * the first date in "d-d MMM yy" is the later date. - * - *

- * The recommended way to create a DateIntervalFormat object is to pass in - * the locale. - * By using a Locale parameter, the DateIntervalFormat object is - * initialized with the pre-defined interval patterns for a given or - * default locale. - *

- * Users can also create DateIntervalFormat object - * by supplying their own interval patterns. - * It provides flexibility for power users. - * - *

- * After a DateIntervalInfo object is created, clients may modify - * the interval patterns using setIntervalPattern function as so desired. - * Currently, users can only set interval patterns when the following - * calendar fields are different: ERA, YEAR, MONTH, DATE, DAY_OF_MONTH, - * DAY_OF_WEEK, AM_PM, HOUR, HOUR_OF_DAY, and MINUTE. - * Interval patterns when other calendar fields are different is not supported. - *

- * DateIntervalInfo objects are cloneable. - * When clients obtain a DateIntervalInfo object, - * they can feel free to modify it as necessary. - *

- * DateIntervalInfo are not expected to be subclassed. - * Data for a calendar is loaded out of resource bundles. - * Through ICU 4.4, date interval patterns are only supported in the Gregorian - * calendar; non-Gregorian calendars are supported from ICU 4.4.1. - * @stable ICU 4.0 -**/ - -class U_I18N_API DateIntervalInfo U_FINAL : public UObject { -public: - // Do not enclose the protected default constructor with #ifndef U_HIDE_INTERNAL_API - // or else the compiler will create a public default constructor. - /** - * Default constructor. - * It does not initialize any interval patterns except - * that it initialize default fall-back pattern as "{0} - {1}", - * which can be reset by setFallbackIntervalPattern(). - * It should be followed by setFallbackIntervalPattern() and - * setIntervalPattern(), - * and is recommended to be used only for power users who - * wants to create their own interval patterns and use them to create - * date interval formatter. - * @param status output param set to success/failure code on exit - * @internal ICU 4.0 - */ - DateIntervalInfo(UErrorCode& status); - - - /** - * Construct DateIntervalInfo for the given locale, - * @param locale the interval patterns are loaded from the appropriate calendar - * data (specified calendar or default calendar) in this locale. - * @param status output param set to success/failure code on exit - * @stable ICU 4.0 - */ - DateIntervalInfo(const Locale& locale, UErrorCode& status); - - - /** - * Copy constructor. - * @stable ICU 4.0 - */ - DateIntervalInfo(const DateIntervalInfo&); - - /** - * Assignment operator - * @stable ICU 4.0 - */ - DateIntervalInfo& operator=(const DateIntervalInfo&); - - /** - * Clone this object polymorphically. - * The caller owns the result and should delete it when done. - * @return a copy of the object - * @stable ICU 4.0 - */ - virtual DateIntervalInfo* clone(void) const; - - /** - * Destructor. - * It is virtual to be safe, but it is not designed to be subclassed. - * @stable ICU 4.0 - */ - virtual ~DateIntervalInfo(); - - - /** - * Return true if another object is semantically equal to this one. - * - * @param other the DateIntervalInfo object to be compared with. - * @return true if other is semantically equal to this. - * @stable ICU 4.0 - */ - virtual UBool operator==(const DateIntervalInfo& other) const; - - /** - * Return true if another object is semantically unequal to this one. - * - * @param other the DateIntervalInfo object to be compared with. - * @return true if other is semantically unequal to this. - * @stable ICU 4.0 - */ - UBool operator!=(const DateIntervalInfo& other) const; - - - - /** - * Provides a way for client to build interval patterns. - * User could construct DateIntervalInfo by providing a list of skeletons - * and their patterns. - *

- * For example: - *

-     * UErrorCode status = U_ZERO_ERROR;
-     * DateIntervalInfo dIntervalInfo = new DateIntervalInfo();
-     * dIntervalInfo->setFallbackIntervalPattern("{0} ~ {1}");
-     * dIntervalInfo->setIntervalPattern("yMd", UCAL_YEAR, "'from' yyyy-M-d 'to' yyyy-M-d", status);
-     * dIntervalInfo->setIntervalPattern("yMMMd", UCAL_MONTH, "'from' yyyy MMM d 'to' MMM d", status);
-     * dIntervalInfo->setIntervalPattern("yMMMd", UCAL_DAY, "yyyy MMM d-d", status, status);
-     * 
- * - * Restriction: - * Currently, users can only set interval patterns when the following - * calendar fields are different: ERA, YEAR, MONTH, DATE, DAY_OF_MONTH, - * DAY_OF_WEEK, AM_PM, HOUR, HOUR_OF_DAY, and MINUTE. - * Interval patterns when other calendar fields are different are - * not supported. - * - * @param skeleton the skeleton on which interval pattern based - * @param lrgDiffCalUnit the largest different calendar unit. - * @param intervalPattern the interval pattern on the largest different - * calendar unit. - * For example, if lrgDiffCalUnit is - * "year", the interval pattern for en_US when year - * is different could be "'from' yyyy 'to' yyyy". - * @param status output param set to success/failure code on exit - * @stable ICU 4.0 - */ - void setIntervalPattern(const UnicodeString& skeleton, - UCalendarDateFields lrgDiffCalUnit, - const UnicodeString& intervalPattern, - UErrorCode& status); - - /** - * Get the interval pattern given skeleton and - * the largest different calendar field. - * @param skeleton the skeleton - * @param field the largest different calendar field - * @param result output param to receive the pattern - * @param status output param set to success/failure code on exit - * @return a reference to 'result' - * @stable ICU 4.0 - */ - UnicodeString& getIntervalPattern(const UnicodeString& skeleton, - UCalendarDateFields field, - UnicodeString& result, - UErrorCode& status) const; - - /** - * Get the fallback interval pattern. - * @param result output param to receive the pattern - * @return a reference to 'result' - * @stable ICU 4.0 - */ - UnicodeString& getFallbackIntervalPattern(UnicodeString& result) const; - - - /** - * Re-set the fallback interval pattern. - * - * In construction, default fallback pattern is set as "{0} - {1}". - * And constructor taking locale as parameter will set the - * fallback pattern as what defined in the locale resource file. - * - * This method provides a way for user to replace the fallback pattern. - * - * @param fallbackPattern fall-back interval pattern. - * @param status output param set to success/failure code on exit - * @stable ICU 4.0 - */ - void setFallbackIntervalPattern(const UnicodeString& fallbackPattern, - UErrorCode& status); - - - /** Get default order -- whether the first date in pattern is later date - or not. - * return default date ordering in interval pattern. TRUE if the first date - * in pattern is later date, FALSE otherwise. - * @stable ICU 4.0 - */ - UBool getDefaultOrder() const; - - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 4.0 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 4.0 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - -private: - /** - * DateIntervalFormat will need access to - * getBestSkeleton(), parseSkeleton(), enum IntervalPatternIndex, - * and calendarFieldToPatternIndex(). - * - * Instead of making above public, - * make DateIntervalFormat a friend of DateIntervalInfo. - */ - friend class DateIntervalFormat; - - /** - * Internal struct used to load resource bundle data. - */ - struct DateIntervalSink; - - /** - * Following is for saving the interval patterns. - * We only support interval patterns on - * ERA, YEAR, MONTH, DAY, AM_PM, HOUR, and MINUTE - */ - enum IntervalPatternIndex - { - kIPI_ERA, - kIPI_YEAR, - kIPI_MONTH, - kIPI_DATE, - kIPI_AM_PM, - kIPI_HOUR, - kIPI_MINUTE, - kIPI_SECOND, - kIPI_MAX_INDEX - }; -public: -#ifndef U_HIDE_INTERNAL_API - /** - * Max index for stored interval patterns - * @internal ICU 4.4 - */ - enum { - kMaxIntervalPatternIndex = kIPI_MAX_INDEX - }; -#endif /* U_HIDE_INTERNAL_API */ -private: - - - /** - * Initialize the DateIntervalInfo from locale - * @param locale the given locale. - * @param status output param set to success/failure code on exit - */ - void initializeData(const Locale& locale, UErrorCode& status); - - - /* Set Interval pattern. - * - * It sets interval pattern into the hash map. - * - * @param skeleton skeleton on which the interval pattern based - * @param lrgDiffCalUnit the largest different calendar unit. - * @param intervalPattern the interval pattern on the largest different - * calendar unit. - * @param status output param set to success/failure code on exit - */ - void setIntervalPatternInternally(const UnicodeString& skeleton, - UCalendarDateFields lrgDiffCalUnit, - const UnicodeString& intervalPattern, - UErrorCode& status); - - - /**given an input skeleton, get the best match skeleton - * which has pre-defined interval pattern in resource file. - * Also return the difference between the input skeleton - * and the best match skeleton. - * - * TODO (xji): set field weight or - * isolate the funtionality in DateTimePatternGenerator - * @param skeleton input skeleton - * @param bestMatchDistanceInfo the difference between input skeleton - * and best match skeleton. - * 0, if there is exact match for input skeleton - * 1, if there is only field width difference between - * the best match and the input skeleton - * 2, the only field difference is 'v' and 'z' - * -1, if there is calendar field difference between - * the best match and the input skeleton - * @return best match skeleton - */ - const UnicodeString* getBestSkeleton(const UnicodeString& skeleton, - int8_t& bestMatchDistanceInfo) const; - - - /** - * Parse skeleton, save each field's width. - * It is used for looking for best match skeleton, - * and adjust pattern field width. - * @param skeleton skeleton to be parsed - * @param skeletonFieldWidth parsed skeleton field width - */ - static void U_EXPORT2 parseSkeleton(const UnicodeString& skeleton, - int32_t* skeletonFieldWidth); - - - /** - * Check whether one field width is numeric while the other is string. - * - * TODO (xji): make it general - * - * @param fieldWidth one field width - * @param anotherFieldWidth another field width - * @param patternLetter pattern letter char - * @return true if one field width is numeric and the other is string, - * false otherwise. - */ - static UBool U_EXPORT2 stringNumeric(int32_t fieldWidth, - int32_t anotherFieldWidth, - char patternLetter); - - - /** - * Convert calendar field to the interval pattern index in - * hash table. - * - * Since we only support the following calendar fields: - * ERA, YEAR, MONTH, DATE, DAY_OF_MONTH, DAY_OF_WEEK, - * AM_PM, HOUR, HOUR_OF_DAY, and MINUTE, - * We reserve only 4 interval patterns for a skeleton. - * - * @param field calendar field - * @param status output param set to success/failure code on exit - * @return interval pattern index in hash table - */ - static IntervalPatternIndex U_EXPORT2 calendarFieldToIntervalIndex( - UCalendarDateFields field, - UErrorCode& status); - - - /** - * delete hash table (of type fIntervalPatterns). - * - * @param hTable hash table to be deleted - */ - void deleteHash(Hashtable* hTable); - - - /** - * initialize hash table (of type fIntervalPatterns). - * - * @param status output param set to success/failure code on exit - * @return hash table initialized - */ - Hashtable* initHash(UErrorCode& status); - - - - /** - * copy hash table (of type fIntervalPatterns). - * - * @param source the source to copy from - * @param target the target to copy to - * @param status output param set to success/failure code on exit - */ - void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status); - - - // data members - // fallback interval pattern - UnicodeString fFallbackIntervalPattern; - // default order - UBool fFirstDateInPtnIsLaterDate; - - // HashMap - // HashMap( skeleton, pattern[largest_different_field] ) - Hashtable* fIntervalPatterns; - -};// end class DateIntervalInfo - - -inline UBool -DateIntervalInfo::operator!=(const DateIntervalInfo& other) const { - return !operator==(other); -} - - -U_NAMESPACE_END - -#endif - -#endif - diff --git a/win32/include/spidermonkey/unicode/dtptngen.h b/win32/include/spidermonkey/unicode/dtptngen.h deleted file mode 100755 index fd617ce3..00000000 --- a/win32/include/spidermonkey/unicode/dtptngen.h +++ /dev/null @@ -1,567 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2007-2016, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -* -* File DTPTNGEN.H -* -******************************************************************************* -*/ - -#ifndef __DTPTNGEN_H__ -#define __DTPTNGEN_H__ - -#include "unicode/datefmt.h" -#include "unicode/locid.h" -#include "unicode/udat.h" -#include "unicode/udatpg.h" - -U_NAMESPACE_BEGIN - -/** - * \file - * \brief C++ API: Date/Time Pattern Generator - */ - - -class Hashtable; -class FormatParser; -class DateTimeMatcher; -class DistanceInfo; -class PatternMap; -class PtnSkeleton; -class SharedDateTimePatternGenerator; - -/** - * This class provides flexible generation of date format patterns, like "yy-MM-dd". - * The user can build up the generator by adding successive patterns. Once that - * is done, a query can be made using a "skeleton", which is a pattern which just - * includes the desired fields and lengths. The generator will return the "best fit" - * pattern corresponding to that skeleton. - *

The main method people will use is getBestPattern(String skeleton), - * since normally this class is pre-built with data from a particular locale. - * However, generators can be built directly from other data as well. - *

Issue: may be useful to also have a function that returns the list of - * fields in a pattern, in order, since we have that internally. - * That would be useful for getting the UI order of field elements. - * @stable ICU 3.8 -**/ -class U_I18N_API DateTimePatternGenerator : public UObject { -public: - /** - * Construct a flexible generator according to default locale. - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @stable ICU 3.8 - */ - static DateTimePatternGenerator* U_EXPORT2 createInstance(UErrorCode& status); - - /** - * Construct a flexible generator according to data for a given locale. - * @param uLocale - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @stable ICU 3.8 - */ - static DateTimePatternGenerator* U_EXPORT2 createInstance(const Locale& uLocale, UErrorCode& status); - -#ifndef U_HIDE_INTERNAL_API - - /** - * For ICU use only - * - * @internal - */ - static DateTimePatternGenerator* U_EXPORT2 internalMakeInstance(const Locale& uLocale, UErrorCode& status); - -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Create an empty generator, to be constructed with addPattern(...) etc. - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @stable ICU 3.8 - */ - static DateTimePatternGenerator* U_EXPORT2 createEmptyInstance(UErrorCode& status); - - /** - * Destructor. - * @stable ICU 3.8 - */ - virtual ~DateTimePatternGenerator(); - - /** - * Clone DateTimePatternGenerator object. Clients are responsible for - * deleting the DateTimePatternGenerator object cloned. - * @stable ICU 3.8 - */ - DateTimePatternGenerator* clone() const; - - /** - * Return true if another object is semantically equal to this one. - * - * @param other the DateTimePatternGenerator object to be compared with. - * @return true if other is semantically equal to this. - * @stable ICU 3.8 - */ - UBool operator==(const DateTimePatternGenerator& other) const; - - /** - * Return true if another object is semantically unequal to this one. - * - * @param other the DateTimePatternGenerator object to be compared with. - * @return true if other is semantically unequal to this. - * @stable ICU 3.8 - */ - UBool operator!=(const DateTimePatternGenerator& other) const; - - /** - * Utility to return a unique skeleton from a given pattern. For example, - * both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd". - * - * @param pattern Input pattern, such as "dd/MMM" - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return skeleton such as "MMMdd" - * @stable ICU 56 - */ - static UnicodeString staticGetSkeleton(const UnicodeString& pattern, UErrorCode& status); - - /** - * Utility to return a unique skeleton from a given pattern. For example, - * both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd". - * getSkeleton() works exactly like staticGetSkeleton(). - * Use staticGetSkeleton() instead of getSkeleton(). - * - * @param pattern Input pattern, such as "dd/MMM" - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return skeleton such as "MMMdd" - * @stable ICU 3.8 - */ - UnicodeString getSkeleton(const UnicodeString& pattern, UErrorCode& status); /* { - The function is commented out because it is a stable API calling a draft API. - After staticGetSkeleton becomes stable, staticGetSkeleton can be used and - these comments and the definition of getSkeleton in dtptngen.cpp should be removed. - return staticGetSkeleton(pattern, status); - }*/ - - /** - * Utility to return a unique base skeleton from a given pattern. This is - * the same as the skeleton, except that differences in length are minimized - * so as to only preserve the difference between string and numeric form. So - * for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd" - * (notice the single d). - * - * @param pattern Input pattern, such as "dd/MMM" - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return base skeleton, such as "MMMd" - * @stable ICU 56 - */ - static UnicodeString staticGetBaseSkeleton(const UnicodeString& pattern, UErrorCode& status); - - /** - * Utility to return a unique base skeleton from a given pattern. This is - * the same as the skeleton, except that differences in length are minimized - * so as to only preserve the difference between string and numeric form. So - * for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd" - * (notice the single d). - * getBaseSkeleton() works exactly like staticGetBaseSkeleton(). - * Use staticGetBaseSkeleton() instead of getBaseSkeleton(). - * - * @param pattern Input pattern, such as "dd/MMM" - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return base skeleton, such as "MMMd" - * @stable ICU 3.8 - */ - UnicodeString getBaseSkeleton(const UnicodeString& pattern, UErrorCode& status); /* { - The function is commented out because it is a stable API calling a draft API. - After staticGetBaseSkeleton becomes stable, staticGetBaseSkeleton can be used and - these comments and the definition of getBaseSkeleton in dtptngen.cpp should be removed. - return staticGetBaseSkeleton(pattern, status); - }*/ - - /** - * Adds a pattern to the generator. If the pattern has the same skeleton as - * an existing pattern, and the override parameter is set, then the previous - * value is overriden. Otherwise, the previous value is retained. In either - * case, the conflicting status is set and previous vale is stored in - * conflicting pattern. - *

- * Note that single-field patterns (like "MMM") are automatically added, and - * don't need to be added explicitly! - * - * @param pattern Input pattern, such as "dd/MMM" - * @param override When existing values are to be overridden use true, - * otherwise use false. - * @param conflictingPattern Previous pattern with the same skeleton. - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return conflicting status. The value could be UDATPG_NO_CONFLICT, - * UDATPG_BASE_CONFLICT or UDATPG_CONFLICT. - * @stable ICU 3.8 - *

- *

Sample code

- * \snippet samples/dtptngsample/dtptngsample.cpp getBestPatternExample1 - * \snippet samples/dtptngsample/dtptngsample.cpp addPatternExample - *

- */ - UDateTimePatternConflict addPattern(const UnicodeString& pattern, - UBool override, - UnicodeString& conflictingPattern, - UErrorCode& status); - - /** - * An AppendItem format is a pattern used to append a field if there is no - * good match. For example, suppose that the input skeleton is "GyyyyMMMd", - * and there is no matching pattern internally, but there is a pattern - * matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the - * G. The way these two are conjoined is by using the AppendItemFormat for G - * (era). So if that value is, say "{0}, {1}" then the final resulting - * pattern is "d-MM-yyyy, G". - *

- * There are actually three available variables: {0} is the pattern so far, - * {1} is the element we are adding, and {2} is the name of the element. - *

- * This reflects the way that the CLDR data is organized. - * - * @param field such as UDATPG_ERA_FIELD. - * @param value pattern, such as "{0}, {1}" - * @stable ICU 3.8 - */ - void setAppendItemFormat(UDateTimePatternField field, const UnicodeString& value); - - /** - * Getter corresponding to setAppendItemFormat. Values below 0 or at or - * above UDATPG_FIELD_COUNT are illegal arguments. - * - * @param field such as UDATPG_ERA_FIELD. - * @return append pattern for field - * @stable ICU 3.8 - */ - const UnicodeString& getAppendItemFormat(UDateTimePatternField field) const; - - /** - * Sets the names of field, eg "era" in English for ERA. These are only - * used if the corresponding AppendItemFormat is used, and if it contains a - * {2} variable. - *

- * This reflects the way that the CLDR data is organized. - * - * @param field such as UDATPG_ERA_FIELD. - * @param value name of the field - * @stable ICU 3.8 - */ - void setAppendItemName(UDateTimePatternField field, const UnicodeString& value); - - /** - * Getter corresponding to setAppendItemNames. Values below 0 or at or above - * UDATPG_FIELD_COUNT are illegal arguments. - * - * @param field such as UDATPG_ERA_FIELD. - * @return name for field - * @stable ICU 3.8 - */ - const UnicodeString& getAppendItemName(UDateTimePatternField field) const; - - /** - * The DateTimeFormat is a message format pattern used to compose date and - * time patterns. The default pattern in the root locale is "{1} {0}", where - * {1} will be replaced by the date pattern and {0} will be replaced by the - * time pattern; however, other locales may specify patterns such as - * "{1}, {0}" or "{1} 'at' {0}", etc. - *

- * This is used when the input skeleton contains both date and time fields, - * but there is not a close match among the added patterns. For example, - * suppose that this object was created by adding "dd-MMM" and "hh:mm", and - * its datetimeFormat is the default "{1} {0}". Then if the input skeleton - * is "MMMdhmm", there is not an exact match, so the input skeleton is - * broken up into two components "MMMd" and "hmm". There are close matches - * for those two skeletons, so the result is put together with this pattern, - * resulting in "d-MMM h:mm". - * - * @param dateTimeFormat - * message format pattern, here {1} will be replaced by the date - * pattern and {0} will be replaced by the time pattern. - * @stable ICU 3.8 - */ - void setDateTimeFormat(const UnicodeString& dateTimeFormat); - - /** - * Getter corresponding to setDateTimeFormat. - * @return DateTimeFormat. - * @stable ICU 3.8 - */ - const UnicodeString& getDateTimeFormat() const; - - /** - * Return the best pattern matching the input skeleton. It is guaranteed to - * have all of the fields in the skeleton. - * - * @param skeleton - * The skeleton is a pattern containing only the variable fields. - * For example, "MMMdd" and "mmhh" are skeletons. - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return bestPattern - * The best pattern found from the given skeleton. - * @stable ICU 3.8 - *

- *

Sample code

- * \snippet samples/dtptngsample/dtptngsample.cpp getBestPatternExample1 - * \snippet samples/dtptngsample/dtptngsample.cpp getBestPatternExample - *

- */ - UnicodeString getBestPattern(const UnicodeString& skeleton, UErrorCode& status); - - - /** - * Return the best pattern matching the input skeleton. It is guaranteed to - * have all of the fields in the skeleton. - * - * @param skeleton - * The skeleton is a pattern containing only the variable fields. - * For example, "MMMdd" and "mmhh" are skeletons. - * @param options - * Options for forcing the length of specified fields in the - * returned pattern to match those in the skeleton (when this - * would not happen otherwise). For default behavior, use - * UDATPG_MATCH_NO_OPTIONS. - * @param status - * Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return bestPattern - * The best pattern found from the given skeleton. - * @stable ICU 4.4 - */ - UnicodeString getBestPattern(const UnicodeString& skeleton, - UDateTimePatternMatchOptions options, - UErrorCode& status); - - - /** - * Adjusts the field types (width and subtype) of a pattern to match what is - * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a - * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be - * "dd-MMMM hh:mm". This is used internally to get the best match for the - * input skeleton, but can also be used externally. - * - * @param pattern Input pattern - * @param skeleton - * The skeleton is a pattern containing only the variable fields. - * For example, "MMMdd" and "mmhh" are skeletons. - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return pattern adjusted to match the skeleton fields widths and subtypes. - * @stable ICU 3.8 - *

- *

Sample code

- * \snippet samples/dtptngsample/dtptngsample.cpp getBestPatternExample1 - * \snippet samples/dtptngsample/dtptngsample.cpp replaceFieldTypesExample - *

- */ - UnicodeString replaceFieldTypes(const UnicodeString& pattern, - const UnicodeString& skeleton, - UErrorCode& status); - - /** - * Adjusts the field types (width and subtype) of a pattern to match what is - * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a - * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be - * "dd-MMMM hh:mm". This is used internally to get the best match for the - * input skeleton, but can also be used externally. - * - * @param pattern Input pattern - * @param skeleton - * The skeleton is a pattern containing only the variable fields. - * For example, "MMMdd" and "mmhh" are skeletons. - * @param options - * Options controlling whether the length of specified fields in the - * pattern are adjusted to match those in the skeleton (when this - * would not happen otherwise). For default behavior, use - * UDATPG_MATCH_NO_OPTIONS. - * @param status - * Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return pattern adjusted to match the skeleton fields widths and subtypes. - * @stable ICU 4.4 - */ - UnicodeString replaceFieldTypes(const UnicodeString& pattern, - const UnicodeString& skeleton, - UDateTimePatternMatchOptions options, - UErrorCode& status); - - /** - * Return a list of all the skeletons (in canonical form) from this class. - * - * Call getPatternForSkeleton() to get the corresponding pattern. - * - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return StringEnumeration with the skeletons. - * The caller must delete the object. - * @stable ICU 3.8 - */ - StringEnumeration* getSkeletons(UErrorCode& status) const; - - /** - * Get the pattern corresponding to a given skeleton. - * @param skeleton - * @return pattern corresponding to a given skeleton. - * @stable ICU 3.8 - */ - const UnicodeString& getPatternForSkeleton(const UnicodeString& skeleton) const; - - /** - * Return a list of all the base skeletons (in canonical form) from this class. - * - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return a StringEnumeration with the base skeletons. - * The caller must delete the object. - * @stable ICU 3.8 - */ - StringEnumeration* getBaseSkeletons(UErrorCode& status) const; - -#ifndef U_HIDE_INTERNAL_API - /** - * Return a list of redundant patterns are those which if removed, make no - * difference in the resulting getBestPattern values. This method returns a - * list of them, to help check the consistency of the patterns used to build - * this generator. - * - * @param status Output param set to success/failure code on exit, - * which must not indicate a failure before the function call. - * @return a StringEnumeration with the redundant pattern. - * The caller must delete the object. - * @internal ICU 3.8 - */ - StringEnumeration* getRedundants(UErrorCode& status); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * The decimal value is used in formatting fractions of seconds. If the - * skeleton contains fractional seconds, then this is used with the - * fractional seconds. For example, suppose that the input pattern is - * "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and - * the decimal string is ",". Then the resulting pattern is modified to be - * "H:mm:ss,SSSS" - * - * @param decimal - * @stable ICU 3.8 - */ - void setDecimal(const UnicodeString& decimal); - - /** - * Getter corresponding to setDecimal. - * @return UnicodeString corresponding to the decimal point - * @stable ICU 3.8 - */ - const UnicodeString& getDecimal() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 3.8 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 3.8 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - -private: - /** - * Constructor. - * @stable ICU 3.8 - */ - DateTimePatternGenerator(UErrorCode & status); - - /** - * Constructor. - * @stable ICU 3.8 - */ - DateTimePatternGenerator(const Locale& locale, UErrorCode & status); - - /** - * Copy constructor. - * @param other DateTimePatternGenerator to copy - * @stable ICU 3.8 - */ - DateTimePatternGenerator(const DateTimePatternGenerator& other); - - /** - * Default assignment operator. - * @param other DateTimePatternGenerator to copy - * @stable ICU 3.8 - */ - DateTimePatternGenerator& operator=(const DateTimePatternGenerator& other); - - Locale pLocale; // pattern locale - FormatParser *fp; - DateTimeMatcher* dtMatcher; - DistanceInfo *distanceInfo; - PatternMap *patternMap; - UnicodeString appendItemFormats[UDATPG_FIELD_COUNT]; - UnicodeString appendItemNames[UDATPG_FIELD_COUNT]; - UnicodeString dateTimeFormat; - UnicodeString decimal; - DateTimeMatcher *skipMatcher; - Hashtable *fAvailableFormatKeyHash; - UnicodeString emptyString; - UChar fDefaultHourFormatChar; - - int32_t fAllowedHourFormats[7]; // Actually an array of AllowedHourFormat enum type, ending with UNKNOWN. - - /* internal flags masks for adjustFieldTypes etc. */ - enum { - kDTPGNoFlags = 0, - kDTPGFixFractionalSeconds = 1, - kDTPGSkeletonUsesCapJ = 2, - kDTPGSkeletonUsesLowB = 3, - kDTPGSkeletonUsesCapB = 4 - }; - - void initData(const Locale &locale, UErrorCode &status); - void addCanonicalItems(UErrorCode &status); - void addICUPatterns(const Locale& locale, UErrorCode& status); - void hackTimes(const UnicodeString& hackPattern, UErrorCode& status); - void getCalendarTypeToUse(const Locale& locale, CharString& destination, UErrorCode& err); - void consumeShortTimePattern(const UnicodeString& shortTimePattern, UErrorCode& status); - void addCLDRData(const Locale& locale, UErrorCode& status); - UDateTimePatternConflict addPatternWithSkeleton(const UnicodeString& pattern, const UnicodeString * skeletonToUse, UBool override, UnicodeString& conflictingPattern, UErrorCode& status); - void initHashtable(UErrorCode& status); - void setDateTimeFromCalendar(const Locale& locale, UErrorCode& status); - void setDecimalSymbols(const Locale& locale, UErrorCode& status); - UDateTimePatternField getAppendFormatNumber(const char* field) const; - UDateTimePatternField getAppendNameNumber(const char* field) const; - UnicodeString& getMutableAppendItemName(UDateTimePatternField field); - void getAppendName(UDateTimePatternField field, UnicodeString& value); - int32_t getCanonicalIndex(const UnicodeString& field); - const UnicodeString* getBestRaw(DateTimeMatcher& source, int32_t includeMask, DistanceInfo* missingFields, const PtnSkeleton** specifiedSkeletonPtr = 0); - UnicodeString adjustFieldTypes(const UnicodeString& pattern, const PtnSkeleton* specifiedSkeleton, int32_t flags, UDateTimePatternMatchOptions options = UDATPG_MATCH_NO_OPTIONS); - UnicodeString getBestAppending(int32_t missingFields, int32_t flags, UDateTimePatternMatchOptions options = UDATPG_MATCH_NO_OPTIONS); - int32_t getTopBitNumber(int32_t foundMask); - void setAvailableFormat(const UnicodeString &key, UErrorCode& status); - UBool isAvailableFormatSet(const UnicodeString &key) const; - void copyHashtable(Hashtable *other, UErrorCode &status); - UBool isCanonicalItem(const UnicodeString& item) const; - static void U_CALLCONV loadAllowedHourFormatsData(UErrorCode &status); - void getAllowedHourFormats(const Locale &locale, UErrorCode &status); - - struct AppendItemFormatsSink; - struct AppendItemNamesSink; - struct AvailableFormatsSink; -} ;// end class DateTimePatternGenerator - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/dtrule.h b/win32/include/spidermonkey/unicode/dtrule.h deleted file mode 100755 index fa1294e9..00000000 --- a/win32/include/spidermonkey/unicode/dtrule.h +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2007-2008, International Business Machines Corporation and * -* others. All Rights Reserved. * -******************************************************************************* -*/ -#ifndef DTRULE_H -#define DTRULE_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Rule for specifying date and time in an year - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/uobject.h" - -U_NAMESPACE_BEGIN -/** - * DateTimeRule is a class representing a time in a year by - * a rule specified by month, day of month, day of week and - * time in the day. - * - * @stable ICU 3.8 - */ -class U_I18N_API DateTimeRule : public UObject { -public: - - /** - * Date rule type constants. - * @stable ICU 3.8 - */ - enum DateRuleType { - DOM = 0, /**< The exact day of month, - for example, March 11. */ - DOW, /**< The Nth occurence of the day of week, - for example, 2nd Sunday in March. */ - DOW_GEQ_DOM, /**< The first occurence of the day of week on or after the day of monnth, - for example, first Sunday on or after March 8. */ - DOW_LEQ_DOM /**< The last occurence of the day of week on or before the day of month, - for example, first Sunday on or before March 14. */ - }; - - /** - * Time rule type constants. - * @stable ICU 3.8 - */ - enum TimeRuleType { - WALL_TIME = 0, /**< The local wall clock time */ - STANDARD_TIME, /**< The local standard time */ - UTC_TIME /**< The UTC time */ - }; - - /** - * Constructs a DateTimeRule by the day of month and - * the time rule. The date rule type for an instance created by - * this constructor is DOM. - * - * @param month The rule month, for example, Calendar::JANUARY - * @param dayOfMonth The day of month, 1-based. - * @param millisInDay The milliseconds in the rule date. - * @param timeType The time type, WALL_TIME or STANDARD_TIME - * or UTC_TIME. - * @stable ICU 3.8 - */ - DateTimeRule(int32_t month, int32_t dayOfMonth, - int32_t millisInDay, TimeRuleType timeType); - - /** - * Constructs a DateTimeRule by the day of week and its oridinal - * number and the time rule. The date rule type for an instance created - * by this constructor is DOW. - * - * @param month The rule month, for example, Calendar::JANUARY. - * @param weekInMonth The ordinal number of the day of week. Negative number - * may be used for specifying a rule date counted from the - * end of the rule month. - * @param dayOfWeek The day of week, for example, Calendar::SUNDAY. - * @param millisInDay The milliseconds in the rule date. - * @param timeType The time type, WALL_TIME or STANDARD_TIME - * or UTC_TIME. - * @stable ICU 3.8 - */ - DateTimeRule(int32_t month, int32_t weekInMonth, int32_t dayOfWeek, - int32_t millisInDay, TimeRuleType timeType); - - /** - * Constructs a DateTimeRule by the first/last day of week - * on or after/before the day of month and the time rule. The date rule - * type for an instance created by this constructor is either - * DOM_GEQ_DOM or DOM_LEQ_DOM. - * - * @param month The rule month, for example, Calendar::JANUARY - * @param dayOfMonth The day of month, 1-based. - * @param dayOfWeek The day of week, for example, Calendar::SUNDAY. - * @param after true if the rule date is on or after the day of month. - * @param millisInDay The milliseconds in the rule date. - * @param timeType The time type, WALL_TIME or STANDARD_TIME - * or UTC_TIME. - * @stable ICU 3.8 - */ - DateTimeRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, UBool after, - int32_t millisInDay, TimeRuleType timeType); - - /** - * Copy constructor. - * @param source The DateTimeRule object to be copied. - * @stable ICU 3.8 - */ - DateTimeRule(const DateTimeRule& source); - - /** - * Destructor. - * @stable ICU 3.8 - */ - ~DateTimeRule(); - - /** - * Clone this DateTimeRule object polymorphically. The caller owns the result and - * should delete it when done. - * @return A copy of the object. - * @stable ICU 3.8 - */ - DateTimeRule* clone(void) const; - - /** - * Assignment operator. - * @param right The object to be copied. - * @stable ICU 3.8 - */ - DateTimeRule& operator=(const DateTimeRule& right); - - /** - * Return true if the given DateTimeRule objects are semantically equal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given DateTimeRule objects are semantically equal. - * @stable ICU 3.8 - */ - UBool operator==(const DateTimeRule& that) const; - - /** - * Return true if the given DateTimeRule objects are semantically unequal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given DateTimeRule objects are semantically unequal. - * @stable ICU 3.8 - */ - UBool operator!=(const DateTimeRule& that) const; - - /** - * Gets the date rule type, such as DOM - * @return The date rule type. - * @stable ICU 3.8 - */ - DateRuleType getDateRuleType(void) const; - - /** - * Gets the time rule type - * @return The time rule type, either WALL_TIME or STANDARD_TIME - * or UTC_TIME. - * @stable ICU 3.8 - */ - TimeRuleType getTimeRuleType(void) const; - - /** - * Gets the rule month. - * @return The rule month. - * @stable ICU 3.8 - */ - int32_t getRuleMonth(void) const; - - /** - * Gets the rule day of month. When the date rule type - * is DOW, the value is always 0. - * @return The rule day of month - * @stable ICU 3.8 - */ - int32_t getRuleDayOfMonth(void) const; - - /** - * Gets the rule day of week. When the date rule type - * is DOM, the value is always 0. - * @return The rule day of week. - * @stable ICU 3.8 - */ - int32_t getRuleDayOfWeek(void) const; - - /** - * Gets the ordinal number of the occurence of the day of week - * in the month. When the date rule type is not DOW, - * the value is always 0. - * @return The rule day of week ordinal number in the month. - * @stable ICU 3.8 - */ - int32_t getRuleWeekInMonth(void) const; - - /** - * Gets the rule time in the rule day. - * @return The time in the rule day in milliseconds. - * @stable ICU 3.8 - */ - int32_t getRuleMillisInDay(void) const; - -private: - int32_t fMonth; - int32_t fDayOfMonth; - int32_t fDayOfWeek; - int32_t fWeekInMonth; - int32_t fMillisInDay; - DateRuleType fDateRuleType; - TimeRuleType fTimeRuleType; - -public: - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 3.8 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 3.8 - */ - virtual UClassID getDynamicClassID(void) const; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // DTRULE_H -//eof diff --git a/win32/include/spidermonkey/unicode/enumset.h b/win32/include/spidermonkey/unicode/enumset.h deleted file mode 100755 index 9c15b9a9..00000000 --- a/win32/include/spidermonkey/unicode/enumset.h +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 2012,2014 International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -*/ - -/** - * \file - * \brief C++: internal template EnumSet<> - */ - -#ifndef ENUMSET_H -#define ENUMSET_H - -#include "unicode/utypes.h" - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/* Can't use #ifndef U_HIDE_INTERNAL_API for the entire EnumSet class, needed in .h file declarations */ -/** - * enum bitset for boolean fields. Similar to Java EnumSet<>. - * Needs to range check. Used for private instance variables. - * @internal - */ -template -class EnumSet { -public: - inline EnumSet() : fBools(0) {} - inline EnumSet(const EnumSet& other) : fBools(other.fBools) {} - inline ~EnumSet() {} -#ifndef U_HIDE_INTERNAL_API - inline void clear() { fBools=0; } - inline void add(T toAdd) { set(toAdd, 1); } - inline void remove(T toRemove) { set(toRemove, 0); } - inline int32_t contains(T toCheck) const { return get(toCheck); } - inline void set(T toSet, int32_t v) { fBools=(fBools&(~flag(toSet)))|(v?(flag(toSet)):0); } - inline int32_t get(T toCheck) const { return (fBools & flag(toCheck))?1:0; } - inline UBool isValidEnum(T toCheck) const { return (toCheck>=minValue&&toCheck& operator=(const EnumSet& other) { - fBools = other.fBools; - return *this; - } - - inline uint32_t getAll() const { - return fBools; - } -#endif /* U_HIDE_INTERNAL_API */ - -private: - inline uint32_t flag(T toCheck) const { return (1<<(toCheck-minValue)); } -private: - uint32_t fBools; -}; - -U_NAMESPACE_END - -#endif /* U_SHOW_CPLUSPLUS_API */ -#endif /* ENUMSET_H */ diff --git a/win32/include/spidermonkey/unicode/errorcode.h b/win32/include/spidermonkey/unicode/errorcode.h deleted file mode 100755 index 13f43e19..00000000 --- a/win32/include/spidermonkey/unicode/errorcode.h +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2009-2011, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: errorcode.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2009mar10 -* created by: Markus W. Scherer -*/ - -#ifndef __ERRORCODE_H__ -#define __ERRORCODE_H__ - -/** - * \file - * \brief C++ API: ErrorCode class intended to make it easier to use - * ICU C and C++ APIs from C++ user code. - */ - -#include "unicode/utypes.h" -#include "unicode/uobject.h" - -U_NAMESPACE_BEGIN - -/** - * Wrapper class for UErrorCode, with conversion operators for direct use - * in ICU C and C++ APIs. - * Intended to be used as a base class, where a subclass overrides - * the handleFailure() function so that it throws an exception, - * does an assert(), logs an error, etc. - * This is not an abstract base class. This class can be used and instantiated - * by itself, although it will be more useful when subclassed. - * - * Features: - * - The constructor initializes the internal UErrorCode to U_ZERO_ERROR, - * removing one common source of errors. - * - Same use in C APIs taking a UErrorCode * (pointer) - * and C++ taking UErrorCode & (reference) via conversion operators. - * - Possible automatic checking for success when it goes out of scope. - * - * Note: For automatic checking for success in the destructor, a subclass - * must implement such logic in its own destructor because the base class - * destructor cannot call a subclass function (like handleFailure()). - * The ErrorCode base class destructor does nothing. - * - * Note also: While it is possible for a destructor to throw an exception, - * it is generally unsafe to do so. This means that in a subclass the destructor - * and the handleFailure() function may need to take different actions. - * - * Sample code: - * \code - * class IcuErrorCode: public icu::ErrorCode { - * public: - * virtual ~IcuErrorCode() { // should be defined in .cpp as "key function" - * // Safe because our handleFailure() does not throw exceptions. - * if(isFailure()) { handleFailure(); } - * } - * protected: - * virtual void handleFailure() const { - * log_failure(u_errorName(errorCode)); - * exit(errorCode); - * } - * }; - * IcuErrorCode error_code; - * UConverter *cnv = ucnv_open("Shift-JIS", error_code); - * length = ucnv_fromUChars(dest, capacity, src, length, error_code); - * ucnv_close(cnv); - * // IcuErrorCode destructor checks for success. - * \endcode - * - * @stable ICU 4.2 - */ -class U_COMMON_API ErrorCode: public UMemory { -public: - /** - * Default constructor. Initializes its UErrorCode to U_ZERO_ERROR. - * @stable ICU 4.2 - */ - ErrorCode() : errorCode(U_ZERO_ERROR) {} - /** Destructor, does nothing. See class documentation for details. @stable ICU 4.2 */ - virtual ~ErrorCode(); - /** Conversion operator, returns a reference. @stable ICU 4.2 */ - operator UErrorCode & () { return errorCode; } - /** Conversion operator, returns a pointer. @stable ICU 4.2 */ - operator UErrorCode * () { return &errorCode; } - /** Tests for U_SUCCESS(). @stable ICU 4.2 */ - UBool isSuccess() const { return U_SUCCESS(errorCode); } - /** Tests for U_FAILURE(). @stable ICU 4.2 */ - UBool isFailure() const { return U_FAILURE(errorCode); } - /** Returns the UErrorCode value. @stable ICU 4.2 */ - UErrorCode get() const { return errorCode; } - /** Sets the UErrorCode value. @stable ICU 4.2 */ - void set(UErrorCode value) { errorCode=value; } - /** Returns the UErrorCode value and resets it to U_ZERO_ERROR. @stable ICU 4.2 */ - UErrorCode reset(); - /** - * Asserts isSuccess(). - * In other words, this method checks for a failure code, - * and the base class handles it like this: - * \code - * if(isFailure()) { handleFailure(); } - * \endcode - * @stable ICU 4.4 - */ - void assertSuccess() const; - /** - * Return a string for the UErrorCode value. - * The string will be the same as the name of the error code constant - * in the UErrorCode enum. - * @stable ICU 4.4 - */ - const char* errorName() const; - -protected: - /** - * Internal UErrorCode, accessible to subclasses. - * @stable ICU 4.2 - */ - UErrorCode errorCode; - /** - * Called by assertSuccess() if isFailure() is true. - * A subclass should override this function to deal with a failure code: - * Throw an exception, log an error, terminate the program, or similar. - * @stable ICU 4.2 - */ - virtual void handleFailure() const {} -}; - -U_NAMESPACE_END - -#endif // __ERRORCODE_H__ diff --git a/win32/include/spidermonkey/unicode/fieldpos.h b/win32/include/spidermonkey/unicode/fieldpos.h deleted file mode 100755 index ad75b77f..00000000 --- a/win32/include/spidermonkey/unicode/fieldpos.h +++ /dev/null @@ -1,294 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************** - * Copyright (C) 1997-2006, International Business Machines - * Corporation and others. All Rights Reserved. - ******************************************************************************** - * - * File FIELDPOS.H - * - * Modification History: - * - * Date Name Description - * 02/25/97 aliu Converted from java. - * 03/17/97 clhuang Updated per Format implementation. - * 07/17/98 stephen Added default/copy ctors, and operators =, ==, != - ******************************************************************************** - */ - -// ***************************************************************************** -// This file was generated from the java source file FieldPosition.java -// ***************************************************************************** - -#ifndef FIELDPOS_H -#define FIELDPOS_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: FieldPosition identifies the fields in a formatted output. - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/uobject.h" - -U_NAMESPACE_BEGIN - -/** - * FieldPosition is a simple class used by Format - * and its subclasses to identify fields in formatted output. Fields are - * identified by constants, whose names typically end with _FIELD, - * defined in the various subclasses of Format. See - * ERA_FIELD and its friends in DateFormat for - * an example. - * - *

- * FieldPosition keeps track of the position of the - * field within the formatted output with two indices: the index - * of the first character of the field and the index of the last - * character of the field. - * - *

- * One version of the format method in the various - * Format classes requires a FieldPosition - * object as an argument. You use this format method - * to perform partial formatting or to get information about the - * formatted output (such as the position of a field). - * - * The FieldPosition class is not intended for public subclassing. - * - *

- * Below is an example of using FieldPosition to aid - * alignment of an array of formatted floating-point numbers on - * their decimal points: - *

- * \code
- *       double doubleNum[] = {123456789.0, -12345678.9, 1234567.89, -123456.789,
- *                  12345.6789, -1234.56789, 123.456789, -12.3456789, 1.23456789};
- *       int dNumSize = (int)(sizeof(doubleNum)/sizeof(double));
- *       
- *       UErrorCode status = U_ZERO_ERROR;
- *       DecimalFormat* fmt = (DecimalFormat*) NumberFormat::createInstance(status);
- *       fmt->setDecimalSeparatorAlwaysShown(true);
- *       
- *       const int tempLen = 20;
- *       char temp[tempLen];
- *       
- *       for (int i=0; iformat(doubleNum[i], buf, pos), fmtText);
- *           for (int j=0; j
- * 

- * The code will generate the following output: - *

- * \code
- *           123,456,789.000
- *           -12,345,678.900
- *             1,234,567.880
- *              -123,456.789
- *                12,345.678
- *                -1,234.567
- *                   123.456
- *                   -12.345
- *                     1.234
- *  \endcode
- * 
- */ -class U_I18N_API FieldPosition : public UObject { -public: - /** - * DONT_CARE may be specified as the field to indicate that the - * caller doesn't need to specify a field. - * @stable ICU 2.0 - */ - enum { DONT_CARE = -1 }; - - /** - * Creates a FieldPosition object with a non-specified field. - * @stable ICU 2.0 - */ - FieldPosition() - : UObject(), fField(DONT_CARE), fBeginIndex(0), fEndIndex(0) {} - - /** - * Creates a FieldPosition object for the given field. Fields are - * identified by constants, whose names typically end with _FIELD, - * in the various subclasses of Format. - * - * @see NumberFormat#INTEGER_FIELD - * @see NumberFormat#FRACTION_FIELD - * @see DateFormat#YEAR_FIELD - * @see DateFormat#MONTH_FIELD - * @stable ICU 2.0 - */ - FieldPosition(int32_t field) - : UObject(), fField(field), fBeginIndex(0), fEndIndex(0) {} - - /** - * Copy constructor - * @param copy the object to be copied from. - * @stable ICU 2.0 - */ - FieldPosition(const FieldPosition& copy) - : UObject(copy), fField(copy.fField), fBeginIndex(copy.fBeginIndex), fEndIndex(copy.fEndIndex) {} - - /** - * Destructor - * @stable ICU 2.0 - */ - virtual ~FieldPosition(); - - /** - * Assignment operator - * @param copy the object to be copied from. - * @stable ICU 2.0 - */ - FieldPosition& operator=(const FieldPosition& copy); - - /** - * Equality operator. - * @param that the object to be compared with. - * @return TRUE if the two field positions are equal, FALSE otherwise. - * @stable ICU 2.0 - */ - UBool operator==(const FieldPosition& that) const; - - /** - * Equality operator. - * @param that the object to be compared with. - * @return TRUE if the two field positions are not equal, FALSE otherwise. - * @stable ICU 2.0 - */ - UBool operator!=(const FieldPosition& that) const; - - /** - * Clone this object. - * Clones can be used concurrently in multiple threads. - * If an error occurs, then NULL is returned. - * The caller must delete the clone. - * - * @return a clone of this object - * - * @see getDynamicClassID - * @stable ICU 2.8 - */ - FieldPosition *clone() const; - - /** - * Retrieve the field identifier. - * @return the field identifier. - * @stable ICU 2.0 - */ - int32_t getField(void) const { return fField; } - - /** - * Retrieve the index of the first character in the requested field. - * @return the index of the first character in the requested field. - * @stable ICU 2.0 - */ - int32_t getBeginIndex(void) const { return fBeginIndex; } - - /** - * Retrieve the index of the character following the last character in the - * requested field. - * @return the index of the character following the last character in the - * requested field. - * @stable ICU 2.0 - */ - int32_t getEndIndex(void) const { return fEndIndex; } - - /** - * Set the field. - * @param f the new value of the field. - * @stable ICU 2.0 - */ - void setField(int32_t f) { fField = f; } - - /** - * Set the begin index. For use by subclasses of Format. - * @param bi the new value of the begin index - * @stable ICU 2.0 - */ - void setBeginIndex(int32_t bi) { fBeginIndex = bi; } - - /** - * Set the end index. For use by subclasses of Format. - * @param ei the new value of the end index - * @stable ICU 2.0 - */ - void setEndIndex(int32_t ei) { fEndIndex = ei; } - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - -private: - /** - * Input: Desired field to determine start and end offsets for. - * The meaning depends on the subclass of Format. - */ - int32_t fField; - - /** - * Output: Start offset of field in text. - * If the field does not occur in the text, 0 is returned. - */ - int32_t fBeginIndex; - - /** - * Output: End offset of field in text. - * If the field does not occur in the text, 0 is returned. - */ - int32_t fEndIndex; -}; - -inline FieldPosition& -FieldPosition::operator=(const FieldPosition& copy) -{ - fField = copy.fField; - fEndIndex = copy.fEndIndex; - fBeginIndex = copy.fBeginIndex; - return *this; -} - -inline UBool -FieldPosition::operator==(const FieldPosition& copy) const -{ - return (fField == copy.fField && - fEndIndex == copy.fEndIndex && - fBeginIndex == copy.fBeginIndex); -} - -inline UBool -FieldPosition::operator!=(const FieldPosition& copy) const -{ - return !operator==(copy); -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _FIELDPOS -//eof diff --git a/win32/include/spidermonkey/unicode/filteredbrk.h b/win32/include/spidermonkey/unicode/filteredbrk.h deleted file mode 100755 index 26115113..00000000 --- a/win32/include/spidermonkey/unicode/filteredbrk.h +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 1997-2015, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************** -*/ - -#ifndef FILTEREDBRK_H -#define FILTEREDBRK_H - -#include "unicode/utypes.h" -#include "unicode/brkiter.h" - -#if !UCONFIG_NO_BREAK_ITERATION && !UCONFIG_NO_FILTERED_BREAK_ITERATION - -U_NAMESPACE_BEGIN - -/** - * \file - * \brief C++ API: FilteredBreakIteratorBuilder - */ - -/** - * The BreakIteratorFilter is used to modify the behavior of a BreakIterator - * by constructing a new BreakIterator which suppresses certain segment boundaries. - * See http://www.unicode.org/reports/tr35/tr35-general.html#Segmentation_Exceptions . - * For example, a typical English Sentence Break Iterator would break on the space - * in the string "Mr. Smith" (resulting in two segments), - * but with "Mr." as an exception, a filtered break iterator - * would consider the string "Mr. Smith" to be a single segment. - * - * @stable ICU 56 - */ -class U_COMMON_API FilteredBreakIteratorBuilder : public UObject { - public: - /** - * destructor. - * @stable ICU 56 - */ - virtual ~FilteredBreakIteratorBuilder(); - - /** - * Construct a FilteredBreakIteratorBuilder based on rules in a locale. - * The rules are taken from CLDR exception data for the locale, - * see http://www.unicode.org/reports/tr35/tr35-general.html#Segmentation_Exceptions - * This is the equivalent of calling createInstance(UErrorCode&) - * and then repeatedly calling addNoBreakAfter(...) with the contents - * of the CLDR exception data. - * @param where the locale. - * @param status The error code. - * @return the new builder - * @stable ICU 56 - */ - static FilteredBreakIteratorBuilder *createInstance(const Locale& where, UErrorCode& status); - - /** - * Construct an empty FilteredBreakIteratorBuilder. - * In this state, it will not suppress any segment boundaries. - * @param status The error code. - * @return the new builder - * @stable ICU 56 - */ - static FilteredBreakIteratorBuilder *createInstance(UErrorCode &status); - - /** - * Suppress a certain string from being the end of a segment. - * For example, suppressing "Mr.", then segments ending in "Mr." will not be returned - * by the iterator. - * @param string the string to suppress, such as "Mr." - * @param status error code - * @return returns TRUE if the string was not present and now added, - * FALSE if the call was a no-op because the string was already being suppressed. - * @stable ICU 56 - */ - virtual UBool suppressBreakAfter(const UnicodeString& string, UErrorCode& status) = 0; - - /** - * Stop suppressing a certain string from being the end of the segment. - * This function does not create any new segment boundaries, but only serves to un-do - * the effect of earlier calls to suppressBreakAfter, or to un-do the effect of - * locale data which may be suppressing certain strings. - * @param exception the exception to remove - * @param status error code - * @return returns TRUE if the string was present and now removed, - * FALSE if the call was a no-op because the string was not being suppressed. - * @stable ICU 56 - */ - virtual UBool unsuppressBreakAfter(const UnicodeString& string, UErrorCode& status) = 0; - - /** - * Wrap (adopt) an existing break iterator in a new filtered instance. - * The resulting BreakIterator is owned by the caller. - * The BreakIteratorFilter may be destroyed before the BreakIterator is destroyed. - * Note that the adoptBreakIterator is adopted by the new BreakIterator - * and should no longer be used by the caller. - * The FilteredBreakIteratorBuilder may be reused. - * @param adoptBreakIterator the break iterator to adopt - * @param status error code - * @return the new BreakIterator, owned by the caller. - * @stable ICU 56 - */ - virtual BreakIterator *build(BreakIterator* adoptBreakIterator, UErrorCode& status) = 0; - - protected: - /** - * For subclass use - * @stable ICU 56 - */ - FilteredBreakIteratorBuilder(); -}; - - -U_NAMESPACE_END - -#endif // #if !UCONFIG_NO_BREAK_ITERATION && !UCONFIG_NO_FILTERED_BREAK_ITERATION - -#endif // #ifndef FILTEREDBRK_H diff --git a/win32/include/spidermonkey/unicode/fmtable.h b/win32/include/spidermonkey/unicode/fmtable.h deleted file mode 100755 index ac5daba8..00000000 --- a/win32/include/spidermonkey/unicode/fmtable.h +++ /dev/null @@ -1,762 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 1997-2014, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************** -* -* File FMTABLE.H -* -* Modification History: -* -* Date Name Description -* 02/29/97 aliu Creation. -******************************************************************************** -*/ -#ifndef FMTABLE_H -#define FMTABLE_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Formattable is a thin wrapper for primitive types used for formatting and parsing - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/unistr.h" -#include "unicode/stringpiece.h" -#include "unicode/uformattable.h" - -U_NAMESPACE_BEGIN - -class CharString; -class DigitList; - -/** - * \def UNUM_INTERNAL_STACKARRAY_SIZE - * @internal - */ -#if U_PLATFORM == U_PF_OS400 -#define UNUM_INTERNAL_STACKARRAY_SIZE 144 -#else -#define UNUM_INTERNAL_STACKARRAY_SIZE 128 -#endif - -/** - * Formattable objects can be passed to the Format class or - * its subclasses for formatting. Formattable is a thin wrapper - * class which interconverts between the primitive numeric types - * (double, long, etc.) as well as UDate and UnicodeString. - * - *

Internally, a Formattable object is a union of primitive types. - * As such, it can only store one flavor of data at a time. To - * determine what flavor of data it contains, use the getType method. - * - *

As of ICU 3.0, Formattable may also wrap a UObject pointer, - * which it owns. This allows an instance of any ICU class to be - * encapsulated in a Formattable. For legacy reasons and for - * efficiency, primitive numeric types are still stored directly - * within a Formattable. - * - *

The Formattable class is not suitable for subclassing. - * - *

See UFormattable for a C wrapper. - */ -class U_I18N_API Formattable : public UObject { -public: - /** - * This enum is only used to let callers distinguish between - * the Formattable(UDate) constructor and the Formattable(double) - * constructor; the compiler cannot distinguish the signatures, - * since UDate is currently typedefed to be either double or long. - * If UDate is changed later to be a bonafide class - * or struct, then we no longer need this enum. - * @stable ICU 2.4 - */ - enum ISDATE { kIsDate }; - - /** - * Default constructor - * @stable ICU 2.4 - */ - Formattable(); // Type kLong, value 0 - - /** - * Creates a Formattable object with a UDate instance. - * @param d the UDate instance. - * @param flag the flag to indicate this is a date. Always set it to kIsDate - * @stable ICU 2.0 - */ - Formattable(UDate d, ISDATE flag); - - /** - * Creates a Formattable object with a double number. - * @param d the double number. - * @stable ICU 2.0 - */ - Formattable(double d); - - /** - * Creates a Formattable object with a long number. - * @param l the long number. - * @stable ICU 2.0 - */ - Formattable(int32_t l); - - /** - * Creates a Formattable object with an int64_t number - * @param ll the int64_t number. - * @stable ICU 2.8 - */ - Formattable(int64_t ll); - -#if !UCONFIG_NO_CONVERSION - /** - * Creates a Formattable object with a char string pointer. - * Assumes that the char string is null terminated. - * @param strToCopy the char string. - * @stable ICU 2.0 - */ - Formattable(const char* strToCopy); -#endif - - /** - * Creates a Formattable object of an appropriate numeric type from a - * a decimal number in string form. The Formattable will retain the - * full precision of the input in decimal format, even when it exceeds - * what can be represented by a double or int64_t. - * - * @param number the unformatted (not localized) string representation - * of the Decimal number. - * @param status the error code. Possible errors include U_INVALID_FORMAT_ERROR - * if the format of the string does not conform to that of a - * decimal number. - * @stable ICU 4.4 - */ - Formattable(StringPiece number, UErrorCode &status); - - /** - * Creates a Formattable object with a UnicodeString object to copy from. - * @param strToCopy the UnicodeString string. - * @stable ICU 2.0 - */ - Formattable(const UnicodeString& strToCopy); - - /** - * Creates a Formattable object with a UnicodeString object to adopt from. - * @param strToAdopt the UnicodeString string. - * @stable ICU 2.0 - */ - Formattable(UnicodeString* strToAdopt); - - /** - * Creates a Formattable object with an array of Formattable objects. - * @param arrayToCopy the Formattable object array. - * @param count the array count. - * @stable ICU 2.0 - */ - Formattable(const Formattable* arrayToCopy, int32_t count); - - /** - * Creates a Formattable object that adopts the given UObject. - * @param objectToAdopt the UObject to set this object to - * @stable ICU 3.0 - */ - Formattable(UObject* objectToAdopt); - - /** - * Copy constructor. - * @stable ICU 2.0 - */ - Formattable(const Formattable&); - - /** - * Assignment operator. - * @param rhs The Formattable object to copy into this object. - * @stable ICU 2.0 - */ - Formattable& operator=(const Formattable &rhs); - - /** - * Equality comparison. - * @param other the object to be compared with. - * @return TRUE if other are equal to this, FALSE otherwise. - * @stable ICU 2.0 - */ - UBool operator==(const Formattable &other) const; - - /** - * Equality operator. - * @param other the object to be compared with. - * @return TRUE if other are unequal to this, FALSE otherwise. - * @stable ICU 2.0 - */ - UBool operator!=(const Formattable& other) const - { return !operator==(other); } - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~Formattable(); - - /** - * Clone this object. - * Clones can be used concurrently in multiple threads. - * If an error occurs, then NULL is returned. - * The caller must delete the clone. - * - * @return a clone of this object - * - * @see getDynamicClassID - * @stable ICU 2.8 - */ - Formattable *clone() const; - - /** - * Selector for flavor of data type contained within a - * Formattable object. Formattable is a union of several - * different types, and at any time contains exactly one type. - * @stable ICU 2.4 - */ - enum Type { - /** - * Selector indicating a UDate value. Use getDate to retrieve - * the value. - * @stable ICU 2.4 - */ - kDate, - - /** - * Selector indicating a double value. Use getDouble to - * retrieve the value. - * @stable ICU 2.4 - */ - kDouble, - - /** - * Selector indicating a 32-bit integer value. Use getLong to - * retrieve the value. - * @stable ICU 2.4 - */ - kLong, - - /** - * Selector indicating a UnicodeString value. Use getString - * to retrieve the value. - * @stable ICU 2.4 - */ - kString, - - /** - * Selector indicating an array of Formattables. Use getArray - * to retrieve the value. - * @stable ICU 2.4 - */ - kArray, - - /** - * Selector indicating a 64-bit integer value. Use getInt64 - * to retrieve the value. - * @stable ICU 2.8 - */ - kInt64, - - /** - * Selector indicating a UObject value. Use getObject to - * retrieve the value. - * @stable ICU 3.0 - */ - kObject - }; - - /** - * Gets the data type of this Formattable object. - * @return the data type of this Formattable object. - * @stable ICU 2.0 - */ - Type getType(void) const; - - /** - * Returns TRUE if the data type of this Formattable object - * is kDouble, kLong, or kInt64 - * @return TRUE if this is a pure numeric object - * @stable ICU 3.0 - */ - UBool isNumeric() const; - - /** - * Gets the double value of this object. If this object is not of type - * kDouble then the result is undefined. - * @return the double value of this object. - * @stable ICU 2.0 - */ - double getDouble(void) const { return fValue.fDouble; } - - /** - * Gets the double value of this object. If this object is of type - * long, int64 or Decimal Number then a conversion is peformed, with - * possible loss of precision. If the type is kObject and the - * object is a Measure, then the result of - * getNumber().getDouble(status) is returned. If this object is - * neither a numeric type nor a Measure, then 0 is returned and - * the status is set to U_INVALID_FORMAT_ERROR. - * @param status the error code - * @return the double value of this object. - * @stable ICU 3.0 - */ - double getDouble(UErrorCode& status) const; - - /** - * Gets the long value of this object. If this object is not of type - * kLong then the result is undefined. - * @return the long value of this object. - * @stable ICU 2.0 - */ - int32_t getLong(void) const { return (int32_t)fValue.fInt64; } - - /** - * Gets the long value of this object. If the magnitude is too - * large to fit in a long, then the maximum or minimum long value, - * as appropriate, is returned and the status is set to - * U_INVALID_FORMAT_ERROR. If this object is of type kInt64 and - * it fits within a long, then no precision is lost. If it is of - * type kDouble, then a conversion is peformed, with - * truncation of any fractional part. If the type is kObject and - * the object is a Measure, then the result of - * getNumber().getLong(status) is returned. If this object is - * neither a numeric type nor a Measure, then 0 is returned and - * the status is set to U_INVALID_FORMAT_ERROR. - * @param status the error code - * @return the long value of this object. - * @stable ICU 3.0 - */ - int32_t getLong(UErrorCode& status) const; - - /** - * Gets the int64 value of this object. If this object is not of type - * kInt64 then the result is undefined. - * @return the int64 value of this object. - * @stable ICU 2.8 - */ - int64_t getInt64(void) const { return fValue.fInt64; } - - /** - * Gets the int64 value of this object. If this object is of a numeric - * type and the magnitude is too large to fit in an int64, then - * the maximum or minimum int64 value, as appropriate, is returned - * and the status is set to U_INVALID_FORMAT_ERROR. If the - * magnitude fits in an int64, then a casting conversion is - * peformed, with truncation of any fractional part. If the type - * is kObject and the object is a Measure, then the result of - * getNumber().getDouble(status) is returned. If this object is - * neither a numeric type nor a Measure, then 0 is returned and - * the status is set to U_INVALID_FORMAT_ERROR. - * @param status the error code - * @return the int64 value of this object. - * @stable ICU 3.0 - */ - int64_t getInt64(UErrorCode& status) const; - - /** - * Gets the Date value of this object. If this object is not of type - * kDate then the result is undefined. - * @return the Date value of this object. - * @stable ICU 2.0 - */ - UDate getDate() const { return fValue.fDate; } - - /** - * Gets the Date value of this object. If the type is not a date, - * status is set to U_INVALID_FORMAT_ERROR and the return value is - * undefined. - * @param status the error code. - * @return the Date value of this object. - * @stable ICU 3.0 - */ - UDate getDate(UErrorCode& status) const; - - /** - * Gets the string value of this object. If this object is not of type - * kString then the result is undefined. - * @param result Output param to receive the Date value of this object. - * @return A reference to 'result'. - * @stable ICU 2.0 - */ - UnicodeString& getString(UnicodeString& result) const - { result=*fValue.fString; return result; } - - /** - * Gets the string value of this object. If the type is not a - * string, status is set to U_INVALID_FORMAT_ERROR and a bogus - * string is returned. - * @param result Output param to receive the Date value of this object. - * @param status the error code. - * @return A reference to 'result'. - * @stable ICU 3.0 - */ - UnicodeString& getString(UnicodeString& result, UErrorCode& status) const; - - /** - * Gets a const reference to the string value of this object. If - * this object is not of type kString then the result is - * undefined. - * @return a const reference to the string value of this object. - * @stable ICU 2.0 - */ - inline const UnicodeString& getString(void) const; - - /** - * Gets a const reference to the string value of this object. If - * the type is not a string, status is set to - * U_INVALID_FORMAT_ERROR and the result is a bogus string. - * @param status the error code. - * @return a const reference to the string value of this object. - * @stable ICU 3.0 - */ - const UnicodeString& getString(UErrorCode& status) const; - - /** - * Gets a reference to the string value of this object. If this - * object is not of type kString then the result is undefined. - * @return a reference to the string value of this object. - * @stable ICU 2.0 - */ - inline UnicodeString& getString(void); - - /** - * Gets a reference to the string value of this object. If the - * type is not a string, status is set to U_INVALID_FORMAT_ERROR - * and the result is a bogus string. - * @param status the error code. - * @return a reference to the string value of this object. - * @stable ICU 3.0 - */ - UnicodeString& getString(UErrorCode& status); - - /** - * Gets the array value and count of this object. If this object - * is not of type kArray then the result is undefined. - * @param count fill-in with the count of this object. - * @return the array value of this object. - * @stable ICU 2.0 - */ - const Formattable* getArray(int32_t& count) const - { count=fValue.fArrayAndCount.fCount; return fValue.fArrayAndCount.fArray; } - - /** - * Gets the array value and count of this object. If the type is - * not an array, status is set to U_INVALID_FORMAT_ERROR, count is - * set to 0, and the result is NULL. - * @param count fill-in with the count of this object. - * @param status the error code. - * @return the array value of this object. - * @stable ICU 3.0 - */ - const Formattable* getArray(int32_t& count, UErrorCode& status) const; - - /** - * Accesses the specified element in the array value of this - * Formattable object. If this object is not of type kArray then - * the result is undefined. - * @param index the specified index. - * @return the accessed element in the array. - * @stable ICU 2.0 - */ - Formattable& operator[](int32_t index) { return fValue.fArrayAndCount.fArray[index]; } - - /** - * Returns a pointer to the UObject contained within this - * formattable, or NULL if this object does not contain a UObject. - * @return a UObject pointer, or NULL - * @stable ICU 3.0 - */ - const UObject* getObject() const; - - /** - * Returns a numeric string representation of the number contained within this - * formattable, or NULL if this object does not contain numeric type. - * For values obtained by parsing, the returned decimal number retains - * the full precision and range of the original input, unconstrained by - * the limits of a double floating point or a 64 bit int. - * - * This function is not thread safe, and therfore is not declared const, - * even though it is logically const. - * - * Possible errors include U_MEMORY_ALLOCATION_ERROR, and - * U_INVALID_STATE if the formattable object has not been set to - * a numeric type. - * - * @param status the error code. - * @return the unformatted string representation of a number. - * @stable ICU 4.4 - */ - StringPiece getDecimalNumber(UErrorCode &status); - - /** - * Sets the double value of this object and changes the type to - * kDouble. - * @param d the new double value to be set. - * @stable ICU 2.0 - */ - void setDouble(double d); - - /** - * Sets the long value of this object and changes the type to - * kLong. - * @param l the new long value to be set. - * @stable ICU 2.0 - */ - void setLong(int32_t l); - - /** - * Sets the int64 value of this object and changes the type to - * kInt64. - * @param ll the new int64 value to be set. - * @stable ICU 2.8 - */ - void setInt64(int64_t ll); - - /** - * Sets the Date value of this object and changes the type to - * kDate. - * @param d the new Date value to be set. - * @stable ICU 2.0 - */ - void setDate(UDate d); - - /** - * Sets the string value of this object and changes the type to - * kString. - * @param stringToCopy the new string value to be set. - * @stable ICU 2.0 - */ - void setString(const UnicodeString& stringToCopy); - - /** - * Sets the array value and count of this object and changes the - * type to kArray. - * @param array the array value. - * @param count the number of array elements to be copied. - * @stable ICU 2.0 - */ - void setArray(const Formattable* array, int32_t count); - - /** - * Sets and adopts the string value and count of this object and - * changes the type to kArray. - * @param stringToAdopt the new string value to be adopted. - * @stable ICU 2.0 - */ - void adoptString(UnicodeString* stringToAdopt); - - /** - * Sets and adopts the array value and count of this object and - * changes the type to kArray. - * @stable ICU 2.0 - */ - void adoptArray(Formattable* array, int32_t count); - - /** - * Sets and adopts the UObject value of this object and changes - * the type to kObject. After this call, the caller must not - * delete the given object. - * @param objectToAdopt the UObject value to be adopted - * @stable ICU 3.0 - */ - void adoptObject(UObject* objectToAdopt); - - /** - * Sets the the numeric value from a decimal number string, and changes - * the type to to a numeric type appropriate for the number. - * The syntax of the number is a "numeric string" - * as defined in the Decimal Arithmetic Specification, available at - * http://speleotrove.com/decimal - * The full precision and range of the input number will be retained, - * even when it exceeds what can be represented by a double or an int64. - * - * @param numberString a string representation of the unformatted decimal number. - * @param status the error code. Set to U_INVALID_FORMAT_ERROR if the - * incoming string is not a valid decimal number. - * @stable ICU 4.4 - */ - void setDecimalNumber(StringPiece numberString, - UErrorCode &status); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - /** - * Convert the UFormattable to a Formattable. Internally, this is a reinterpret_cast. - * @param fmt a valid UFormattable - * @return the UFormattable as a Formattable object pointer. This is an alias to the original - * UFormattable, and so is only valid while the original argument remains in scope. - * @stable ICU 52 - */ - static inline Formattable *fromUFormattable(UFormattable *fmt); - - /** - * Convert the const UFormattable to a const Formattable. Internally, this is a reinterpret_cast. - * @param fmt a valid UFormattable - * @return the UFormattable as a Formattable object pointer. This is an alias to the original - * UFormattable, and so is only valid while the original argument remains in scope. - * @stable ICU 52 - */ - static inline const Formattable *fromUFormattable(const UFormattable *fmt); - - /** - * Convert this object pointer to a UFormattable. - * @return this object as a UFormattable pointer. This is an alias to this object, - * and so is only valid while this object remains in scope. - * @stable ICU 52 - */ - inline UFormattable *toUFormattable(); - - /** - * Convert this object pointer to a UFormattable. - * @return this object as a UFormattable pointer. This is an alias to this object, - * and so is only valid while this object remains in scope. - * @stable ICU 52 - */ - inline const UFormattable *toUFormattable() const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Deprecated variant of getLong(UErrorCode&). - * @param status the error code - * @return the long value of this object. - * @deprecated ICU 3.0 use getLong(UErrorCode&) instead - */ - inline int32_t getLong(UErrorCode* status) const; -#endif /* U_HIDE_DEPRECATED_API */ - -#ifndef U_HIDE_INTERNAL_API - /** - * Internal function, do not use. - * TODO: figure out how to make this be non-public. - * NumberFormat::format(Formattable, ... - * needs to get at the DigitList, if it exists, for - * big decimal formatting. - * @internal - */ - DigitList *getDigitList() const { return fDecimalNum;} - - /** - * @internal - */ - DigitList *getInternalDigitList(); - - /** - * Adopt, and set value from, a DigitList - * Internal Function, do not use. - * @param dl the Digit List to be adopted - * @internal - */ - void adoptDigitList(DigitList *dl); - - /** - * Internal function to return the CharString pointer. - * @param status error code - * @return pointer to the CharString - may become invalid if the object is modified - * @internal - */ - CharString *internalGetCharString(UErrorCode &status); - -#endif /* U_HIDE_INTERNAL_API */ - -private: - /** - * Cleans up the memory for unwanted values. For example, the adopted - * string or array objects. - */ - void dispose(void); - - /** - * Common initialization, for use by constructors. - */ - void init(); - - UnicodeString* getBogus() const; - - union { - UObject* fObject; - UnicodeString* fString; - double fDouble; - int64_t fInt64; - UDate fDate; - struct { - Formattable* fArray; - int32_t fCount; - } fArrayAndCount; - } fValue; - - CharString *fDecimalStr; - - DigitList *fDecimalNum; - - char fStackData[UNUM_INTERNAL_STACKARRAY_SIZE]; // must be big enough for DigitList - - Type fType; - UnicodeString fBogus; // Bogus string when it's needed. -}; - -inline UDate Formattable::getDate(UErrorCode& status) const { - if (fType != kDate) { - if (U_SUCCESS(status)) { - status = U_INVALID_FORMAT_ERROR; - } - return 0; - } - return fValue.fDate; -} - -inline const UnicodeString& Formattable::getString(void) const { - return *fValue.fString; -} - -inline UnicodeString& Formattable::getString(void) { - return *fValue.fString; -} - -#ifndef U_HIDE_DEPRECATED_API -inline int32_t Formattable::getLong(UErrorCode* status) const { - return getLong(*status); -} -#endif /* U_HIDE_DEPRECATED_API */ - -inline UFormattable* Formattable::toUFormattable() { - return reinterpret_cast(this); -} - -inline const UFormattable* Formattable::toUFormattable() const { - return reinterpret_cast(this); -} - -inline Formattable* Formattable::fromUFormattable(UFormattable *fmt) { - return reinterpret_cast(fmt); -} - -inline const Formattable* Formattable::fromUFormattable(const UFormattable *fmt) { - return reinterpret_cast(fmt); -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif //_FMTABLE -//eof diff --git a/win32/include/spidermonkey/unicode/format.h b/win32/include/spidermonkey/unicode/format.h deleted file mode 100755 index bce5251c..00000000 --- a/win32/include/spidermonkey/unicode/format.h +++ /dev/null @@ -1,307 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 1997-2011, International Business Machines Corporation and others. -* All Rights Reserved. -******************************************************************************** -* -* File FORMAT.H -* -* Modification History: -* -* Date Name Description -* 02/19/97 aliu Converted from java. -* 03/17/97 clhuang Updated per C++ implementation. -* 03/27/97 helena Updated to pass the simple test after code review. -******************************************************************************** -*/ -// ***************************************************************************** -// This file was generated from the java source file Format.java -// ***************************************************************************** - -#ifndef FORMAT_H -#define FORMAT_H - - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Base class for all formats. - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/unistr.h" -#include "unicode/fmtable.h" -#include "unicode/fieldpos.h" -#include "unicode/fpositer.h" -#include "unicode/parsepos.h" -#include "unicode/parseerr.h" -#include "unicode/locid.h" - -U_NAMESPACE_BEGIN - -/** - * Base class for all formats. This is an abstract base class which - * specifies the protocol for classes which convert other objects or - * values, such as numeric values and dates, and their string - * representations. In some cases these representations may be - * localized or contain localized characters or strings. For example, - * a numeric formatter such as DecimalFormat may convert a numeric - * value such as 12345 to the string "$12,345". It may also parse - * the string back into a numeric value. A date and time formatter - * like SimpleDateFormat may represent a specific date, encoded - * numerically, as a string such as "Wednesday, February 26, 1997 AD". - *

- * Many of the concrete subclasses of Format employ the notion of - * a pattern. A pattern is a string representation of the rules which - * govern the interconversion between values and strings. For example, - * a DecimalFormat object may be associated with the pattern - * "$#,##0.00;($#,##0.00)", which is a common US English format for - * currency values, yielding strings such as "$1,234.45" for 1234.45, - * and "($987.65)" for 987.6543. The specific syntax of a pattern - * is defined by each subclass. - *

- * Even though many subclasses use patterns, the notion of a pattern - * is not inherent to Format classes in general, and is not part of - * the explicit base class protocol. - *

- * Two complex formatting classes bear mentioning. These are - * MessageFormat and ChoiceFormat. ChoiceFormat is a subclass of - * NumberFormat which allows the user to format different number ranges - * as strings. For instance, 0 may be represented as "no files", 1 as - * "one file", and any number greater than 1 as "many files". - * MessageFormat is a formatter which utilizes other Format objects to - * format a string containing with multiple values. For instance, - * A MessageFormat object might produce the string "There are no files - * on the disk MyDisk on February 27, 1997." given the arguments 0, - * "MyDisk", and the date value of 2/27/97. See the ChoiceFormat - * and MessageFormat headers for further information. - *

- * If formatting is unsuccessful, a failing UErrorCode is returned when - * the Format cannot format the type of object, otherwise if there is - * something illformed about the the Unicode replacement character - * 0xFFFD is returned. - *

- * If there is no match when parsing, a parse failure UErrorCode is - * retured for methods which take no ParsePosition. For the method - * that takes a ParsePosition, the index parameter is left unchanged. - *

- * User subclasses are not supported. While clients may write - * subclasses, such code will not necessarily work and will not be - * guaranteed to work stably from release to release. - */ -class U_I18N_API Format : public UObject { -public: - - /** Destructor - * @stable ICU 2.4 - */ - virtual ~Format(); - - /** - * Return true if the given Format objects are semantically equal. - * Objects of different subclasses are considered unequal. - * @param other the object to be compared with. - * @return Return true if the given Format objects are semantically equal. - * Objects of different subclasses are considered unequal. - * @stable ICU 2.0 - */ - virtual UBool operator==(const Format& other) const = 0; - - /** - * Return true if the given Format objects are not semantically - * equal. - * @param other the object to be compared with. - * @return Return true if the given Format objects are not semantically. - * @stable ICU 2.0 - */ - UBool operator!=(const Format& other) const { return !operator==(other); } - - /** - * Clone this object polymorphically. The caller is responsible - * for deleting the result when done. - * @return A copy of the object - * @stable ICU 2.0 - */ - virtual Format* clone() const = 0; - - /** - * Formats an object to produce a string. - * - * @param obj The object to format. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param status Output parameter filled in with success or failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - UErrorCode& status) const; - - /** - * Format an object to produce a string. This is a pure virtual method which - * subclasses must implement. This method allows polymorphic formatting - * of Formattable objects. If a subclass of Format receives a Formattable - * object type it doesn't handle (e.g., if a numeric Formattable is passed - * to a DateFormat object) then it returns a failing UErrorCode. - * - * @param obj The object to format. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const = 0; - /** - * Format an object to produce a string. Subclasses should override this - * method. This method allows polymorphic formatting of Formattable objects. - * If a subclass of Format receives a Formattable object type it doesn't - * handle (e.g., if a numeric Formattable is passed to a DateFormat object) - * then it returns a failing UErrorCode. - * - * @param obj The object to format. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Parse a string to produce an object. This is a pure virtual - * method which subclasses must implement. This method allows - * polymorphic parsing of strings into Formattable objects. - *

- * Before calling, set parse_pos.index to the offset you want to - * start parsing at in the source. After calling, parse_pos.index - * is the end of the text you parsed. If error occurs, index is - * unchanged. - *

- * When parsing, leading whitespace is discarded (with successful - * parse), while trailing whitespace is left as is. - *

- * Example: - *

- * Parsing "_12_xy" (where _ represents a space) for a number, - * with index == 0 will result in the number 12, with - * parse_pos.index updated to 3 (just before the second space). - * Parsing a second time will result in a failing UErrorCode since - * "xy" is not a number, and leave index at 3. - *

- * Subclasses will typically supply specific parse methods that - * return different types of values. Since methods can't overload - * on return types, these will typically be named "parse", while - * this polymorphic method will always be called parseObject. Any - * parse method that does not take a parse_pos should set status - * to an error value when no text in the required format is at the - * start position. - * - * @param source The string to be parsed into an object. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param parse_pos The position to start parsing at. Upon return - * this param is set to the position after the - * last character successfully parsed. If the - * source is not parsed successfully, this param - * will remain unchanged. - * @stable ICU 2.0 - */ - virtual void parseObject(const UnicodeString& source, - Formattable& result, - ParsePosition& parse_pos) const = 0; - - /** - * Parses a string to produce an object. This is a convenience method - * which calls the pure virtual parseObject() method, and returns a - * failure UErrorCode if the ParsePosition indicates failure. - * - * @param source The string to be parsed into an object. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param status Output param to be filled with success/failure - * result code. - * @stable ICU 2.0 - */ - void parseObject(const UnicodeString& source, - Formattable& result, - UErrorCode& status) const; - - /** Get the locale for this format object. You can choose between valid and actual locale. - * @param type type of the locale we're looking for (valid or actual) - * @param status error code for the operation - * @return the locale - * @stable ICU 2.8 - */ - Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const; - -#ifndef U_HIDE_INTERNAL_API - /** Get the locale for this format object. You can choose between valid and actual locale. - * @param type type of the locale we're looking for (valid or actual) - * @param status error code for the operation - * @return the locale - * @internal - */ - const char* getLocaleID(ULocDataLocaleType type, UErrorCode &status) const; -#endif /* U_HIDE_INTERNAL_API */ - - protected: - /** @stable ICU 2.8 */ - void setLocaleIDs(const char* valid, const char* actual); - -protected: - /** - * Default constructor for subclass use only. Does nothing. - * @stable ICU 2.0 - */ - Format(); - - /** - * @stable ICU 2.0 - */ - Format(const Format&); // Does nothing; for subclasses only - - /** - * @stable ICU 2.0 - */ - Format& operator=(const Format&); // Does nothing; for subclasses - - - /** - * Simple function for initializing a UParseError from a UnicodeString. - * - * @param pattern The pattern to copy into the parseError - * @param pos The position in pattern where the error occured - * @param parseError The UParseError object to fill in - * @stable ICU 2.4 - */ - static void syntaxError(const UnicodeString& pattern, - int32_t pos, - UParseError& parseError); - - private: - char actualLocale[ULOC_FULLNAME_CAPACITY]; - char validLocale[ULOC_FULLNAME_CAPACITY]; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _FORMAT -//eof diff --git a/win32/include/spidermonkey/unicode/fpositer.h b/win32/include/spidermonkey/unicode/fpositer.h deleted file mode 100755 index 59c36380..00000000 --- a/win32/include/spidermonkey/unicode/fpositer.h +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 2010-2012, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************** -* -* File attiter.h -* -* Modification History: -* -* Date Name Description -* 12/15/2009 dougfelt Created -******************************************************************************** -*/ - -#ifndef FPOSITER_H -#define FPOSITER_H - -#include "unicode/utypes.h" -#include "unicode/uobject.h" - -/** - * \file - * \brief C++ API: FieldPosition Iterator. - */ - -#if UCONFIG_NO_FORMATTING - -U_NAMESPACE_BEGIN - -/* - * Allow the declaration of APIs with pointers to FieldPositionIterator - * even when formatting is removed from the build. - */ -class FieldPositionIterator; - -U_NAMESPACE_END - -#else - -#include "unicode/fieldpos.h" -#include "unicode/umisc.h" - -U_NAMESPACE_BEGIN - -class UVector32; - -/** - * FieldPositionIterator returns the field ids and their start/limit positions generated - * by a call to Format::format. See Format, NumberFormat, DecimalFormat. - * @stable ICU 4.4 - */ -class U_I18N_API FieldPositionIterator : public UObject { -public: - /** - * Destructor. - * @stable ICU 4.4 - */ - ~FieldPositionIterator(); - - /** - * Constructs a new, empty iterator. - * @stable ICU 4.4 - */ - FieldPositionIterator(void); - - /** - * Copy constructor. If the copy failed for some reason, the new iterator will - * be empty. - * @stable ICU 4.4 - */ - FieldPositionIterator(const FieldPositionIterator&); - - /** - * Return true if another object is semantically equal to this - * one. - *

- * Return true if this FieldPositionIterator is at the same position in an - * equal array of run values. - * @stable ICU 4.4 - */ - UBool operator==(const FieldPositionIterator&) const; - - /** - * Returns the complement of the result of operator== - * @param rhs The FieldPositionIterator to be compared for inequality - * @return the complement of the result of operator== - * @stable ICU 4.4 - */ - UBool operator!=(const FieldPositionIterator& rhs) const { return !operator==(rhs); } - - /** - * If the current position is valid, updates the FieldPosition values, advances the iterator, - * and returns TRUE, otherwise returns FALSE. - * @stable ICU 4.4 - */ - UBool next(FieldPosition& fp); - -private: - friend class FieldPositionIteratorHandler; - - /** - * Sets the data used by the iterator, and resets the position. - * Returns U_ILLEGAL_ARGUMENT_ERROR in status if the data is not valid - * (length is not a multiple of 3, or start >= limit for any run). - */ - void setData(UVector32 *adopt, UErrorCode& status); - - UVector32 *data; - int32_t pos; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // FPOSITER_H diff --git a/win32/include/spidermonkey/unicode/gender.h b/win32/include/spidermonkey/unicode/gender.h deleted file mode 100755 index 943d4454..00000000 --- a/win32/include/spidermonkey/unicode/gender.h +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2008-2013, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -* -* -* File GENDER.H -* -* Modification History:* -* Date Name Description -* -******************************************************************************** -*/ - -#ifndef _GENDER -#define _GENDER - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/locid.h" -#include "unicode/ugender.h" -#include "unicode/uobject.h" - -class GenderInfoTest; - -U_NAMESPACE_BEGIN - -// Forward Declaration -void U_CALLCONV GenderInfo_initCache(UErrorCode &status); - -/** - * GenderInfo computes the gender of a list as a whole given the gender of - * each element. - * @stable ICU 50 - */ -class U_I18N_API GenderInfo : public UObject { -public: - - /** - * Provides access to the predefined GenderInfo object for a given - * locale. - * - * @param locale The locale for which a GenderInfo object is - * returned. - * @param status Output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return The predefined GenderInfo object pointer for - * this locale. The returned object is immutable, so it is - * declared as const. Caller does not own the returned - * pointer, so it must not attempt to free it. - * @stable ICU 50 - */ - static const GenderInfo* U_EXPORT2 getInstance(const Locale& locale, UErrorCode& status); - - /** - * Determines the gender of a list as a whole given the gender of each - * of the elements. - * - * @param genders the gender of each element in the list. - * @param length the length of gender array. - * @param status Output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return the gender of the whole list. - * @stable ICU 50 - */ - UGender getListGender(const UGender* genders, int32_t length, UErrorCode& status) const; - - /** - * Destructor. - * - * @stable ICU 50 - */ - virtual ~GenderInfo(); - -private: - int32_t _style; - - /** - * Copy constructor. One object per locale invariant. Clients - * must never copy GenderInfo objects. - */ - GenderInfo(const GenderInfo& other); - - /** - * Assignment operator. Not applicable to immutable objects. - */ - GenderInfo& operator=(const GenderInfo&); - - GenderInfo(); - - static const GenderInfo* getNeutralInstance(); - - static const GenderInfo* getMixedNeutralInstance(); - - static const GenderInfo* getMaleTaintsInstance(); - - static const GenderInfo* loadInstance(const Locale& locale, UErrorCode& status); - - friend class ::GenderInfoTest; - friend void U_CALLCONV GenderInfo_initCache(UErrorCode &status); -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _GENDER -//eof diff --git a/win32/include/spidermonkey/unicode/gregocal.h b/win32/include/spidermonkey/unicode/gregocal.h deleted file mode 100755 index 756bba1b..00000000 --- a/win32/include/spidermonkey/unicode/gregocal.h +++ /dev/null @@ -1,779 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -* Copyright (C) 1997-2013, International Business Machines Corporation and others. -* All Rights Reserved. -******************************************************************************** -* -* File GREGOCAL.H -* -* Modification History: -* -* Date Name Description -* 04/22/97 aliu Overhauled header. -* 07/28/98 stephen Sync with JDK 1.2 -* 09/04/98 stephen Re-sync with JDK 8/31 putback -* 09/14/98 stephen Changed type of kOneDay, kOneWeek to double. -* Fixed bug in roll() -* 10/15/99 aliu Fixed j31, incorrect WEEK_OF_YEAR computation. -* Added documentation of WEEK_OF_YEAR computation. -* 10/15/99 aliu Fixed j32, cannot set date to Feb 29 2000 AD. -* {JDK bug 4210209 4209272} -* 11/07/2003 srl Update, clean up documentation. -******************************************************************************** -*/ - -#ifndef GREGOCAL_H -#define GREGOCAL_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/calendar.h" - -/** - * \file - * \brief C++ API: Concrete class which provides the standard calendar. - */ - -U_NAMESPACE_BEGIN - -/** - * Concrete class which provides the standard calendar used by most of the world. - *

- * The standard (Gregorian) calendar has 2 eras, BC and AD. - *

- * This implementation handles a single discontinuity, which corresponds by default to - * the date the Gregorian calendar was originally instituted (October 15, 1582). Not all - * countries adopted the Gregorian calendar then, so this cutover date may be changed by - * the caller. - *

- * Prior to the institution of the Gregorian Calendar, New Year's Day was March 25. To - * avoid confusion, this Calendar always uses January 1. A manual adjustment may be made - * if desired for dates that are prior to the Gregorian changeover and which fall - * between January 1 and March 24. - * - *

Values calculated for the WEEK_OF_YEAR field range from 1 to - * 53. Week 1 for a year is the first week that contains at least - * getMinimalDaysInFirstWeek() days from that year. It thus - * depends on the values of getMinimalDaysInFirstWeek(), - * getFirstDayOfWeek(), and the day of the week of January 1. - * Weeks between week 1 of one year and week 1 of the following year are - * numbered sequentially from 2 to 52 or 53 (as needed). - * - *

For example, January 1, 1998 was a Thursday. If - * getFirstDayOfWeek() is MONDAY and - * getMinimalDaysInFirstWeek() is 4 (these are the values - * reflecting ISO 8601 and many national standards), then week 1 of 1998 starts - * on December 29, 1997, and ends on January 4, 1998. If, however, - * getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 - * starts on January 4, 1998, and ends on January 10, 1998; the first three days - * of 1998 then are part of week 53 of 1997. - * - *

Example for using GregorianCalendar: - *

- * \code
- *     // get the supported ids for GMT-08:00 (Pacific Standard Time)
- *     UErrorCode success = U_ZERO_ERROR;
- *     const StringEnumeration *ids = TimeZone::createEnumeration(-8 * 60 * 60 * 1000);
- *     // if no ids were returned, something is wrong. get out.
- *     if (ids == 0 || ids->count(success) == 0) {
- *         return;
- *     }
- *
- *     // begin output
- *     cout << "Current Time" << endl;
- *
- *     // create a Pacific Standard Time time zone
- *     SimpleTimeZone* pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids->unext(NULL, success)));
- *
- *     // set up rules for daylight savings time
- *     pdt->setStartRule(UCAL_MARCH, 1, UCAL_SUNDAY, 2 * 60 * 60 * 1000);
- *     pdt->setEndRule(UCAL_NOVEMBER, 2, UCAL_SUNDAY, 2 * 60 * 60 * 1000);
- *
- *     // create a GregorianCalendar with the Pacific Daylight time zone
- *     // and the current date and time
- *     Calendar* calendar = new GregorianCalendar( pdt, success );
- *
- *     // print out a bunch of interesting things
- *     cout << "ERA: " << calendar->get( UCAL_ERA, success ) << endl;
- *     cout << "YEAR: " << calendar->get( UCAL_YEAR, success ) << endl;
- *     cout << "MONTH: " << calendar->get( UCAL_MONTH, success ) << endl;
- *     cout << "WEEK_OF_YEAR: " << calendar->get( UCAL_WEEK_OF_YEAR, success ) << endl;
- *     cout << "WEEK_OF_MONTH: " << calendar->get( UCAL_WEEK_OF_MONTH, success ) << endl;
- *     cout << "DATE: " << calendar->get( UCAL_DATE, success ) << endl;
- *     cout << "DAY_OF_MONTH: " << calendar->get( UCAL_DAY_OF_MONTH, success ) << endl;
- *     cout << "DAY_OF_YEAR: " << calendar->get( UCAL_DAY_OF_YEAR, success ) << endl;
- *     cout << "DAY_OF_WEEK: " << calendar->get( UCAL_DAY_OF_WEEK, success ) << endl;
- *     cout << "DAY_OF_WEEK_IN_MONTH: " << calendar->get( UCAL_DAY_OF_WEEK_IN_MONTH, success ) << endl;
- *     cout << "AM_PM: " << calendar->get( UCAL_AM_PM, success ) << endl;
- *     cout << "HOUR: " << calendar->get( UCAL_HOUR, success ) << endl;
- *     cout << "HOUR_OF_DAY: " << calendar->get( UCAL_HOUR_OF_DAY, success ) << endl;
- *     cout << "MINUTE: " << calendar->get( UCAL_MINUTE, success ) << endl;
- *     cout << "SECOND: " << calendar->get( UCAL_SECOND, success ) << endl;
- *     cout << "MILLISECOND: " << calendar->get( UCAL_MILLISECOND, success ) << endl;
- *     cout << "ZONE_OFFSET: " << (calendar->get( UCAL_ZONE_OFFSET, success )/(60*60*1000)) << endl;
- *     cout << "DST_OFFSET: " << (calendar->get( UCAL_DST_OFFSET, success )/(60*60*1000)) << endl;
- *
- *     cout << "Current Time, with hour reset to 3" << endl;
- *     calendar->clear(UCAL_HOUR_OF_DAY); // so doesn't override
- *     calendar->set(UCAL_HOUR, 3);
- *     cout << "ERA: " << calendar->get( UCAL_ERA, success ) << endl;
- *     cout << "YEAR: " << calendar->get( UCAL_YEAR, success ) << endl;
- *     cout << "MONTH: " << calendar->get( UCAL_MONTH, success ) << endl;
- *     cout << "WEEK_OF_YEAR: " << calendar->get( UCAL_WEEK_OF_YEAR, success ) << endl;
- *     cout << "WEEK_OF_MONTH: " << calendar->get( UCAL_WEEK_OF_MONTH, success ) << endl;
- *     cout << "DATE: " << calendar->get( UCAL_DATE, success ) << endl;
- *     cout << "DAY_OF_MONTH: " << calendar->get( UCAL_DAY_OF_MONTH, success ) << endl;
- *     cout << "DAY_OF_YEAR: " << calendar->get( UCAL_DAY_OF_YEAR, success ) << endl;
- *     cout << "DAY_OF_WEEK: " << calendar->get( UCAL_DAY_OF_WEEK, success ) << endl;
- *     cout << "DAY_OF_WEEK_IN_MONTH: " << calendar->get( UCAL_DAY_OF_WEEK_IN_MONTH, success ) << endl;
- *     cout << "AM_PM: " << calendar->get( UCAL_AM_PM, success ) << endl;
- *     cout << "HOUR: " << calendar->get( UCAL_HOUR, success ) << endl;
- *     cout << "HOUR_OF_DAY: " << calendar->get( UCAL_HOUR_OF_DAY, success ) << endl;
- *     cout << "MINUTE: " << calendar->get( UCAL_MINUTE, success ) << endl;
- *     cout << "SECOND: " << calendar->get( UCAL_SECOND, success ) << endl;
- *     cout << "MILLISECOND: " << calendar->get( UCAL_MILLISECOND, success ) << endl;
- *     cout << "ZONE_OFFSET: " << (calendar->get( UCAL_ZONE_OFFSET, success )/(60*60*1000)) << endl; // in hours
- *     cout << "DST_OFFSET: " << (calendar->get( UCAL_DST_OFFSET, success )/(60*60*1000)) << endl; // in hours
- *
- *     if (U_FAILURE(success)) {
- *         cout << "An error occured. success=" << u_errorName(success) << endl;
- *     }
- *
- *     delete ids;
- *     delete calendar; // also deletes pdt
- * \endcode
- * 
- * @stable ICU 2.0 - */ -class U_I18N_API GregorianCalendar: public Calendar { -public: - - /** - * Useful constants for GregorianCalendar and TimeZone. - * @stable ICU 2.0 - */ - enum EEras { - BC, - AD - }; - - /** - * Constructs a default GregorianCalendar using the current time in the default time - * zone with the default locale. - * - * @param success Indicates the status of GregorianCalendar object construction. - * Returns U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - GregorianCalendar(UErrorCode& success); - - /** - * Constructs a GregorianCalendar based on the current time in the given time zone - * with the default locale. Clients are no longer responsible for deleting the given - * time zone object after it's adopted. - * - * @param zoneToAdopt The given timezone. - * @param success Indicates the status of GregorianCalendar object construction. - * Returns U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - GregorianCalendar(TimeZone* zoneToAdopt, UErrorCode& success); - - /** - * Constructs a GregorianCalendar based on the current time in the given time zone - * with the default locale. - * - * @param zone The given timezone. - * @param success Indicates the status of GregorianCalendar object construction. - * Returns U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - GregorianCalendar(const TimeZone& zone, UErrorCode& success); - - /** - * Constructs a GregorianCalendar based on the current time in the default time zone - * with the given locale. - * - * @param aLocale The given locale. - * @param success Indicates the status of GregorianCalendar object construction. - * Returns U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - GregorianCalendar(const Locale& aLocale, UErrorCode& success); - - /** - * Constructs a GregorianCalendar based on the current time in the given time zone - * with the given locale. Clients are no longer responsible for deleting the given - * time zone object after it's adopted. - * - * @param zoneToAdopt The given timezone. - * @param aLocale The given locale. - * @param success Indicates the status of GregorianCalendar object construction. - * Returns U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - GregorianCalendar(TimeZone* zoneToAdopt, const Locale& aLocale, UErrorCode& success); - - /** - * Constructs a GregorianCalendar based on the current time in the given time zone - * with the given locale. - * - * @param zone The given timezone. - * @param aLocale The given locale. - * @param success Indicates the status of GregorianCalendar object construction. - * Returns U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - GregorianCalendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& success); - - /** - * Constructs a GregorianCalendar with the given AD date set in the default time - * zone with the default locale. - * - * @param year The value used to set the YEAR time field in the calendar. - * @param month The value used to set the MONTH time field in the calendar. Month - * value is 0-based. e.g., 0 for January. - * @param date The value used to set the DATE time field in the calendar. - * @param success Indicates the status of GregorianCalendar object construction. - * Returns U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - GregorianCalendar(int32_t year, int32_t month, int32_t date, UErrorCode& success); - - /** - * Constructs a GregorianCalendar with the given AD date and time set for the - * default time zone with the default locale. - * - * @param year The value used to set the YEAR time field in the calendar. - * @param month The value used to set the MONTH time field in the calendar. Month - * value is 0-based. e.g., 0 for January. - * @param date The value used to set the DATE time field in the calendar. - * @param hour The value used to set the HOUR_OF_DAY time field in the calendar. - * @param minute The value used to set the MINUTE time field in the calendar. - * @param success Indicates the status of GregorianCalendar object construction. - * Returns U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, UErrorCode& success); - - /** - * Constructs a GregorianCalendar with the given AD date and time set for the - * default time zone with the default locale. - * - * @param year The value used to set the YEAR time field in the calendar. - * @param month The value used to set the MONTH time field in the calendar. Month - * value is 0-based. e.g., 0 for January. - * @param date The value used to set the DATE time field in the calendar. - * @param hour The value used to set the HOUR_OF_DAY time field in the calendar. - * @param minute The value used to set the MINUTE time field in the calendar. - * @param second The value used to set the SECOND time field in the calendar. - * @param success Indicates the status of GregorianCalendar object construction. - * Returns U_ZERO_ERROR if constructed successfully. - * @stable ICU 2.0 - */ - GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second, UErrorCode& success); - - /** - * Destructor - * @stable ICU 2.0 - */ - virtual ~GregorianCalendar(); - - /** - * Copy constructor - * @param source the object to be copied. - * @stable ICU 2.0 - */ - GregorianCalendar(const GregorianCalendar& source); - - /** - * Default assignment operator - * @param right the object to be copied. - * @stable ICU 2.0 - */ - GregorianCalendar& operator=(const GregorianCalendar& right); - - /** - * Create and return a polymorphic copy of this calendar. - * @return return a polymorphic copy of this calendar. - * @stable ICU 2.0 - */ - virtual Calendar* clone(void) const; - - /** - * Sets the GregorianCalendar change date. This is the point when the switch from - * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October - * 15, 1582. Previous to this time and date will be Julian dates. - * - * @param date The given Gregorian cutover date. - * @param success Output param set to success/failure code on exit. - * @stable ICU 2.0 - */ - void setGregorianChange(UDate date, UErrorCode& success); - - /** - * Gets the Gregorian Calendar change date. This is the point when the switch from - * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October - * 15, 1582. Previous to this time and date will be Julian dates. - * - * @return The Gregorian cutover time for this calendar. - * @stable ICU 2.0 - */ - UDate getGregorianChange(void) const; - - /** - * Return true if the given year is a leap year. Determination of whether a year is - * a leap year is actually very complicated. We do something crude and mostly - * correct here, but for a real determination you need a lot of contextual - * information. For example, in Sweden, the change from Julian to Gregorian happened - * in a complex way resulting in missed leap years and double leap years between - * 1700 and 1753. Another example is that after the start of the Julian calendar in - * 45 B.C., the leap years did not regularize until 8 A.D. This method ignores these - * quirks, and pays attention only to the Julian onset date and the Gregorian - * cutover (which can be changed). - * - * @param year The given year. - * @return True if the given year is a leap year; false otherwise. - * @stable ICU 2.0 - */ - UBool isLeapYear(int32_t year) const; - - /** - * Returns TRUE if the given Calendar object is equivalent to this - * one. Calendar override. - * - * @param other the Calendar to be compared with this Calendar - * @stable ICU 2.4 - */ - virtual UBool isEquivalentTo(const Calendar& other) const; - - /** - * (Overrides Calendar) Rolls up or down by the given amount in the specified field. - * For more information, see the documentation for Calendar::roll(). - * - * @param field The time field. - * @param amount Indicates amount to roll. - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid, this will be set to - * an error status. - * @deprecated ICU 2.6. Use roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead. - */ - virtual void roll(EDateFields field, int32_t amount, UErrorCode& status); - - /** - * (Overrides Calendar) Rolls up or down by the given amount in the specified field. - * For more information, see the documentation for Calendar::roll(). - * - * @param field The time field. - * @param amount Indicates amount to roll. - * @param status Output param set to success/failure code on exit. If any value - * previously set in the time field is invalid, this will be set to - * an error status. - * @stable ICU 2.6. - */ - virtual void roll(UCalendarDateFields field, int32_t amount, UErrorCode& status); - -#ifndef U_HIDE_DEPRECATED_API - /** - * Return the minimum value that this field could have, given the current date. - * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). - * @param field the time field. - * @return the minimum value that this field could have, given the current date. - * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead. - */ - int32_t getActualMinimum(EDateFields field) const; - - /** - * Return the minimum value that this field could have, given the current date. - * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). - * @param field the time field. - * @param status - * @return the minimum value that this field could have, given the current date. - * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead. (Added to ICU 3.0 for signature consistency) - */ - int32_t getActualMinimum(EDateFields field, UErrorCode& status) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Return the minimum value that this field could have, given the current date. - * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). - * @param field the time field. - * @param status error result. - * @return the minimum value that this field could have, given the current date. - * @stable ICU 3.0 - */ - int32_t getActualMinimum(UCalendarDateFields field, UErrorCode &status) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Return the maximum value that this field could have, given the current date. - * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual - * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar, - * for some years the actual maximum for MONTH is 12, and for others 13. - * @param field the time field. - * @return the maximum value that this field could have, given the current date. - * @deprecated ICU 2.6. Use getActualMaximum(UCalendarDateFields field) instead. - */ - int32_t getActualMaximum(EDateFields field) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Return the maximum value that this field could have, given the current date. - * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual - * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar, - * for some years the actual maximum for MONTH is 12, and for others 13. - * @param field the time field. - * @param status returns any errors that may result from this function call. - * @return the maximum value that this field could have, given the current date. - * @stable ICU 2.6 - */ - virtual int32_t getActualMaximum(UCalendarDateFields field, UErrorCode& status) const; - - /** - * (Overrides Calendar) Return true if the current date for this Calendar is in - * Daylight Savings Time. Recognizes DST_OFFSET, if it is set. - * - * @param status Fill-in parameter which receives the status of this operation. - * @return True if the current date for this Calendar is in Daylight Savings Time, - * false, otherwise. - * @stable ICU 2.0 - */ - virtual UBool inDaylightTime(UErrorCode& status) const; - -public: - - /** - * Override Calendar Returns a unique class ID POLYMORPHICALLY. Pure virtual - * override. This method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() methods call - * this method. - * - * @return The class ID for this object. All objects of a given class have the - * same class ID. Objects of other classes have different class IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const; - - /** - * Return the class ID for this class. This is useful only for comparing to a return - * value from getDynamicClassID(). For example: - * - * Base* polymorphic_pointer = createPolymorphicObject(); - * if (polymorphic_pointer->getDynamicClassID() == - * Derived::getStaticClassID()) ... - * - * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns the calendar type name string for this Calendar object. - * The returned string is the legacy ICU calendar attribute value, - * for example, "gregorian" or "japanese". - * - * For more details see the Calendar::getType() documentation. - * - * @return legacy calendar type name string - * @stable ICU 49 - */ - virtual const char * getType() const; - - private: - GregorianCalendar(); // default constructor not implemented - - protected: - /** - * Return the ERA. We need a special method for this because the - * default ERA is AD, but a zero (unset) ERA is BC. - * @return the ERA. - * @internal - */ - virtual int32_t internalGetEra() const; - - /** - * Return the Julian day number of day before the first day of the - * given month in the given extended year. Subclasses should override - * this method to implement their calendar system. - * @param eyear the extended year - * @param month the zero-based month, or 0 if useMonth is false - * @param useMonth if false, compute the day before the first day of - * the given year, otherwise, compute the day before the first day of - * the given month - * @return the Julian day number of the day before the first - * day of the given month and year - * @internal - */ - virtual int32_t handleComputeMonthStart(int32_t eyear, int32_t month, - UBool useMonth) const; - - /** - * Subclasses may override this. This method calls - * handleGetMonthLength() to obtain the calendar-specific month - * length. - * @param bestField which field to use to calculate the date - * @return julian day specified by calendar fields. - * @internal - */ - virtual int32_t handleComputeJulianDay(UCalendarDateFields bestField) ; - - /** - * Return the number of days in the given month of the given extended - * year of this calendar system. Subclasses should override this - * method if they can provide a more correct or more efficient - * implementation than the default implementation in Calendar. - * @internal - */ - virtual int32_t handleGetMonthLength(int32_t extendedYear, int32_t month) const; - - /** - * Return the number of days in the given extended year of this - * calendar system. Subclasses should override this method if they can - * provide a more correct or more efficient implementation than the - * default implementation in Calendar. - * @stable ICU 2.0 - */ - virtual int32_t handleGetYearLength(int32_t eyear) const; - - /** - * return the length of the given month. - * @param month the given month. - * @return the length of the given month. - * @internal - */ - virtual int32_t monthLength(int32_t month) const; - - /** - * return the length of the month according to the given year. - * @param month the given month. - * @param year the given year. - * @return the length of the month - * @internal - */ - virtual int32_t monthLength(int32_t month, int32_t year) const; - -#ifndef U_HIDE_INTERNAL_API - /** - * return the length of the given year. - * @param year the given year. - * @return the length of the given year. - * @internal - */ - int32_t yearLength(int32_t year) const; - - /** - * return the length of the year field. - * @return the length of the year field - * @internal - */ - int32_t yearLength(void) const; - - /** - * After adjustments such as add(MONTH), add(YEAR), we don't want the - * month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar - * 3, we want it to go to Feb 28. Adjustments which might run into this - * problem call this method to retain the proper month. - * @internal - */ - void pinDayOfMonth(void); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Return the day number with respect to the epoch. January 1, 1970 (Gregorian) - * is day zero. - * @param status Fill-in parameter which receives the status of this operation. - * @return the day number with respect to the epoch. - * @internal - */ - virtual UDate getEpochDay(UErrorCode& status); - - /** - * Subclass API for defining limits of different types. - * Subclasses must implement this method to return limits for the - * following fields: - * - *
UCAL_ERA
-     * UCAL_YEAR
-     * UCAL_MONTH
-     * UCAL_WEEK_OF_YEAR
-     * UCAL_WEEK_OF_MONTH
-     * UCAL_DATE (DAY_OF_MONTH on Java)
-     * UCAL_DAY_OF_YEAR
-     * UCAL_DAY_OF_WEEK_IN_MONTH
-     * UCAL_YEAR_WOY
-     * UCAL_EXTENDED_YEAR
- * - * @param field one of the above field numbers - * @param limitType one of MINIMUM, GREATEST_MINIMUM, - * LEAST_MAXIMUM, or MAXIMUM - * @internal - */ - virtual int32_t handleGetLimit(UCalendarDateFields field, ELimitType limitType) const; - - /** - * Return the extended year defined by the current fields. This will - * use the UCAL_EXTENDED_YEAR field or the UCAL_YEAR and supra-year fields (such - * as UCAL_ERA) specific to the calendar system, depending on which set of - * fields is newer. - * @return the extended year - * @internal - */ - virtual int32_t handleGetExtendedYear(); - - /** - * Subclasses may override this to convert from week fields - * (YEAR_WOY and WEEK_OF_YEAR) to an extended year in the case - * where YEAR, EXTENDED_YEAR are not set. - * The Gregorian implementation assumes a yearWoy in gregorian format, according to the current era. - * @return the extended year, UCAL_EXTENDED_YEAR - * @internal - */ - virtual int32_t handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy); - - - /** - * Subclasses may override this method to compute several fields - * specific to each calendar system. These are: - * - *
  • ERA - *
  • YEAR - *
  • MONTH - *
  • DAY_OF_MONTH - *
  • DAY_OF_YEAR - *
  • EXTENDED_YEAR
- * - *

The GregorianCalendar implementation implements - * a calendar with the specified Julian/Gregorian cutover date. - * @internal - */ - virtual void handleComputeFields(int32_t julianDay, UErrorCode &status); - - private: - /** - * Compute the julian day number of the given year. - * @param isGregorian if true, using Gregorian calendar, otherwise using Julian calendar - * @param year the given year. - * @param isLeap true if the year is a leap year. - * @return - */ - static double computeJulianDayOfYear(UBool isGregorian, int32_t year, - UBool& isLeap); - - /** - * Validates the values of the set time fields. True if they're all valid. - * @return True if the set time fields are all valid. - */ - UBool validateFields(void) const; - - /** - * Validates the value of the given time field. True if it's valid. - */ - UBool boundsCheck(int32_t value, UCalendarDateFields field) const; - - /** - * Return the pseudo-time-stamp for two fields, given their - * individual pseudo-time-stamps. If either of the fields - * is unset, then the aggregate is unset. Otherwise, the - * aggregate is the later of the two stamps. - * @param stamp_a One given field. - * @param stamp_b Another given field. - * @return the pseudo-time-stamp for two fields - */ - int32_t aggregateStamp(int32_t stamp_a, int32_t stamp_b); - - /** - * The point at which the Gregorian calendar rules are used, measured in - * milliseconds from the standard epoch. Default is October 15, 1582 - * (Gregorian) 00:00:00 UTC, that is, October 4, 1582 (Julian) is followed - * by October 15, 1582 (Gregorian). This corresponds to Julian day number - * 2299161. This is measured from the standard epoch, not in Julian Days. - */ - UDate fGregorianCutover; - - /** - * Julian day number of the Gregorian cutover - */ - int32_t fCutoverJulianDay; - - /** - * Midnight, local time (using this Calendar's TimeZone) at or before the - * gregorianCutover. This is a pure date value with no time of day or - * timezone component. - */ - UDate fNormalizedGregorianCutover;// = gregorianCutover; - - /** - * The year of the gregorianCutover, with 0 representing - * 1 BC, -1 representing 2 BC, etc. - */ - int32_t fGregorianCutoverYear;// = 1582; - - /** - * The year of the gregorianCutover, with 0 representing - * 1 BC, -1 representing 2 BC, etc. - */ - int32_t fGregorianCutoverJulianDay;// = 2299161; - - /** - * Converts time as milliseconds to Julian date. The Julian date used here is not a - * true Julian date, since it is measured from midnight, not noon. - * - * @param millis The given milliseconds. - * @return The Julian date number. - */ - static double millisToJulianDay(UDate millis); - - /** - * Converts Julian date to time as milliseconds. The Julian date used here is not a - * true Julian date, since it is measured from midnight, not noon. - * - * @param julian The given Julian date number. - * @return Time as milliseconds. - */ - static UDate julianDayToMillis(double julian); - - /** - * Used by handleComputeJulianDay() and handleComputeMonthStart(). - * Temporary field indicating whether the calendar is currently Gregorian as opposed to Julian. - */ - UBool fIsGregorian; - - /** - * Used by handleComputeJulianDay() and handleComputeMonthStart(). - * Temporary field indicating that the sense of the gregorian cutover should be inverted - * to handle certain calculations on and around the cutover date. - */ - UBool fInvertGregorian; - - - public: // internal implementation - - /** - * @return TRUE if this calendar has the notion of a default century - * @internal - */ - virtual UBool haveDefaultCentury() const; - - /** - * @return the start of the default century - * @internal - */ - virtual UDate defaultCenturyStart() const; - - /** - * @return the beginning year of the default century - * @internal - */ - virtual int32_t defaultCenturyStartYear() const; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _GREGOCAL -//eof - diff --git a/win32/include/spidermonkey/unicode/icudataver.h b/win32/include/spidermonkey/unicode/icudataver.h deleted file mode 100755 index 99e7c284..00000000 --- a/win32/include/spidermonkey/unicode/icudataver.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 2009-2013, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -*/ - - -/** - * \file - * \brief C API: access to ICU Data Version number - */ - -#ifndef __ICU_DATA_VER_H__ -#define __ICU_DATA_VER_H__ - -#include "unicode/utypes.h" - -/** - * @stable ICU 49 - */ -#define U_ICU_VERSION_BUNDLE "icuver" - -/** - * @stable ICU 49 - */ -#define U_ICU_DATA_KEY "DataVersion" - -/** - * Retrieves the data version from icuver and stores it in dataVersionFillin. - * - * @param dataVersionFillin icuver data version information to be filled in if not-null - * @param status stores the error code from the calls to resource bundle - * - * @stable ICU 49 - */ -U_STABLE void U_EXPORT2 u_getDataVersion(UVersionInfo dataVersionFillin, UErrorCode *status); - -#endif diff --git a/win32/include/spidermonkey/unicode/icuplug.h b/win32/include/spidermonkey/unicode/icuplug.h deleted file mode 100755 index cffa6f35..00000000 --- a/win32/include/spidermonkey/unicode/icuplug.h +++ /dev/null @@ -1,388 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 2009-2015, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* -* FILE NAME : icuplug.h -* -* Date Name Description -* 10/29/2009 sl New. -****************************************************************************** -*/ - -/** - * \file - * \brief C API: ICU Plugin API - * - *

C API: ICU Plugin API

- * - *

C API allowing run-time loadable modules that extend or modify ICU functionality.

- * - *

Loading and Configuration

- * - *

At ICU startup time, the environment variable "ICU_PLUGINS" will be - * queried for a directory name. If it is not set, the preprocessor symbol - * "DEFAULT_ICU_PLUGINS" will be checked for a default value.

- * - *

Within the above-named directory, the file "icuplugins##.txt" will be - * opened, if present, where ## is the major+minor number of the currently - * running ICU (such as, 44 for ICU 4.4, thus icuplugins44.txt)

- * - *

The configuration file has this format:

- * - *
    - *
  • Hash (#) begins a comment line
  • - * - *
  • Non-comment lines have two or three components: - * LIBRARYNAME ENTRYPOINT [ CONFIGURATION .. ]
  • - * - *
  • Tabs or spaces separate the three items.
  • - * - *
  • LIBRARYNAME is the name of a shared library, either a short name if - * it is on the loader path, or a full pathname.
  • - * - *
  • ENTRYPOINT is the short (undecorated) symbol name of the plugin's - * entrypoint, as above.
  • - * - *
  • CONFIGURATION is the entire rest of the line . It's passed as-is to - * the plugin.
  • - *
- * - *

An example configuration file is, in its entirety:

- * - * \code - * # this is icuplugins44.txt - * testplug.dll myPlugin hello=world - * \endcode - *

Plugins are categorized as "high" or "low" level. Low level are those - * which must be run BEFORE high level plugins, and before any operations - * which cause ICU to be 'initialized'. If a plugin is low level but - * causes ICU to allocate memory or become initialized, that plugin is said - * to cause a 'level change'.

- * - *

At load time, ICU first queries all plugins to determine their level, - * then loads all 'low' plugins first, and then loads all 'high' plugins. - * Plugins are otherwise loaded in the order listed in the configuration file.

- * - *

Implementing a Plugin

- * \code - * U_CAPI UPlugTokenReturn U_EXPORT2 - * myPlugin (UPlugData *plug, UPlugReason reason, UErrorCode *status) { - * if(reason==UPLUG_REASON_QUERY) { - * uplug_setPlugName(plug, "Simple Plugin"); - * uplug_setPlugLevel(plug, UPLUG_LEVEL_HIGH); - * } else if(reason==UPLUG_REASON_LOAD) { - * ... Set up some ICU things here.... - * } else if(reason==UPLUG_REASON_UNLOAD) { - * ... unload, clean up ... - * } - * return UPLUG_TOKEN; - * } - * \endcode - * - *

The UPlugData* is an opaque pointer to the plugin-specific data, and is - * used in all other API calls.

- * - *

The API contract is:

- *
  1. The plugin MUST always return UPLUG_TOKEN as a return value- to - * indicate that it is a valid plugin.
  2. - * - *
  3. When the 'reason' parameter is set to UPLUG_REASON_QUERY, the - * plugin MUST call uplug_setPlugLevel() to indicate whether it is a high - * level or low level plugin.
  4. - * - *
  5. When the 'reason' parameter is UPLUG_REASON_QUERY, the plugin - * SHOULD call uplug_setPlugName to indicate a human readable plugin name.
- * - * - * \internal ICU 4.4 Technology Preview - */ - - -#ifndef ICUPLUG_H -#define ICUPLUG_H - -#include "unicode/utypes.h" - - -#if UCONFIG_ENABLE_PLUGINS - - - -/* === Basic types === */ - -#ifndef U_HIDE_INTERNAL_API -/** - * @{ - * Opaque structure passed to/from a plugin. - * use the APIs to access it. - * @internal ICU 4.4 Technology Preview - */ - -struct UPlugData; -typedef struct UPlugData UPlugData; - -/** @} */ - -/** - * Random Token to identify a valid ICU plugin. Plugins must return this - * from the entrypoint. - * @internal ICU 4.4 Technology Preview - */ -#define UPLUG_TOKEN 0x54762486 - -/** - * Max width of names, symbols, and configuration strings - * @internal ICU 4.4 Technology Preview - */ -#define UPLUG_NAME_MAX 100 - - -/** - * Return value from a plugin entrypoint. - * Must always be set to UPLUG_TOKEN - * @see UPLUG_TOKEN - * @internal ICU 4.4 Technology Preview - */ -typedef uint32_t UPlugTokenReturn; - -/** - * Reason code for the entrypoint's call - * @internal ICU 4.4 Technology Preview - */ -typedef enum { - UPLUG_REASON_QUERY = 0, /**< The plugin is being queried for info. **/ - UPLUG_REASON_LOAD = 1, /**< The plugin is being loaded. **/ - UPLUG_REASON_UNLOAD = 2, /**< The plugin is being unloaded. **/ - /** - * Number of known reasons. - * @internal The numeric value may change over time, see ICU ticket #12420. - */ - UPLUG_REASON_COUNT -} UPlugReason; - - -/** - * Level of plugin loading - * INITIAL: UNKNOWN - * QUERY: INVALID -> { LOW | HIGH } - * ERR -> INVALID - * @internal ICU 4.4 Technology Preview - */ -typedef enum { - UPLUG_LEVEL_INVALID = 0, /**< The plugin is invalid, hasn't called uplug_setLevel, or can't load. **/ - UPLUG_LEVEL_UNKNOWN = 1, /**< The plugin is waiting to be installed. **/ - UPLUG_LEVEL_LOW = 2, /**< The plugin must be called before u_init completes **/ - UPLUG_LEVEL_HIGH = 3, /**< The plugin can run at any time. **/ - /** - * Number of known levels. - * @internal The numeric value may change over time, see ICU ticket #12420. - */ - UPLUG_LEVEL_COUNT -} UPlugLevel; - -/** - * Entrypoint for an ICU plugin. - * @param plug the UPlugData handle. - * @param status the plugin's extended status code. - * @return A valid plugin must return UPLUG_TOKEN - * @internal ICU 4.4 Technology Preview - */ -typedef UPlugTokenReturn (U_EXPORT2 UPlugEntrypoint) ( - UPlugData *plug, - UPlugReason reason, - UErrorCode *status); - -/* === Needed for Implementing === */ - -/** - * Request that this plugin not be unloaded at cleanup time. - * This is appropriate for plugins which cannot be cleaned up. - * @see u_cleanup() - * @param plug plugin - * @param dontUnload set true if this plugin can't be unloaded - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL void U_EXPORT2 -uplug_setPlugNoUnload(UPlugData *plug, UBool dontUnload); - -/** - * Set the level of this plugin. - * @param plug plugin data handle - * @param level the level of this plugin - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL void U_EXPORT2 -uplug_setPlugLevel(UPlugData *plug, UPlugLevel level); - -/** - * Get the level of this plugin. - * @param plug plugin data handle - * @return the level of this plugin - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL UPlugLevel U_EXPORT2 -uplug_getPlugLevel(UPlugData *plug); - -/** - * Get the lowest level of plug which can currently load. - * For example, if UPLUG_LEVEL_LOW is returned, then low level plugins may load - * if UPLUG_LEVEL_HIGH is returned, then only high level plugins may load. - * @return the lowest level of plug which can currently load - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL UPlugLevel U_EXPORT2 -uplug_getCurrentLevel(void); - - -/** - * Get plug load status - * @return The error code of this plugin's load attempt. - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL UErrorCode U_EXPORT2 -uplug_getPlugLoadStatus(UPlugData *plug); - -/** - * Set the human-readable name of this plugin. - * @param plug plugin data handle - * @param name the name of this plugin. The first UPLUG_NAME_MAX characters willi be copied into a new buffer. - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL void U_EXPORT2 -uplug_setPlugName(UPlugData *plug, const char *name); - -/** - * Get the human-readable name of this plugin. - * @param plug plugin data handle - * @return the name of this plugin - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL const char * U_EXPORT2 -uplug_getPlugName(UPlugData *plug); - -/** - * Return the symbol name for this plugin, if known. - * @param plug plugin data handle - * @return the symbol name, or NULL - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL const char * U_EXPORT2 -uplug_getSymbolName(UPlugData *plug); - -/** - * Return the library name for this plugin, if known. - * @param plug plugin data handle - * @param status error code - * @return the library name, or NULL - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL const char * U_EXPORT2 -uplug_getLibraryName(UPlugData *plug, UErrorCode *status); - -/** - * Return the library used for this plugin, if known. - * Plugins could use this to load data out of their - * @param plug plugin data handle - * @return the library, or NULL - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL void * U_EXPORT2 -uplug_getLibrary(UPlugData *plug); - -/** - * Return the plugin-specific context data. - * @param plug plugin data handle - * @return the context, or NULL if not set - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL void * U_EXPORT2 -uplug_getContext(UPlugData *plug); - -/** - * Set the plugin-specific context data. - * @param plug plugin data handle - * @param context new context to set - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL void U_EXPORT2 -uplug_setContext(UPlugData *plug, void *context); - - -/** - * Get the configuration string, if available. - * The string is in the platform default codepage. - * @param plug plugin data handle - * @return configuration string, or else null. - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL const char * U_EXPORT2 -uplug_getConfiguration(UPlugData *plug); - -/** - * Return all currently installed plugins, from newest to oldest - * Usage Example: - * \code - * UPlugData *plug = NULL; - * while(plug=uplug_nextPlug(plug)) { - * ... do something with 'plug' ... - * } - * \endcode - * Not thread safe- do not call while plugs are added or removed. - * @param prior pass in 'NULL' to get the first (most recent) plug, - * otherwise pass the value returned on a prior call to uplug_nextPlug - * @return the next oldest plugin, or NULL if no more. - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL UPlugData* U_EXPORT2 -uplug_nextPlug(UPlugData *prior); - -/** - * Inject a plugin as if it were loaded from a library. - * This is useful for testing plugins. - * Note that it will have a 'NULL' library pointer associated - * with it, and therefore no llibrary will be closed at cleanup time. - * Low level plugins may not be able to load, as ordering can't be enforced. - * @param entrypoint entrypoint to install - * @param config user specified configuration string, if available, or NULL. - * @param status error result - * @return the new UPlugData associated with this plugin, or NULL if error. - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL UPlugData* U_EXPORT2 -uplug_loadPlugFromEntrypoint(UPlugEntrypoint *entrypoint, const char *config, UErrorCode *status); - - -/** - * Inject a plugin from a library, as if the information came from a config file. - * Low level plugins may not be able to load, and ordering can't be enforced. - * @param libName DLL name to load - * @param sym symbol of plugin (UPlugEntrypoint function) - * @param config configuration string, or NULL - * @param status error result - * @return the new UPlugData associated with this plugin, or NULL if error. - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL UPlugData* U_EXPORT2 -uplug_loadPlugFromLibrary(const char *libName, const char *sym, const char *config, UErrorCode *status); - -/** - * Remove a plugin. - * Will request the plugin to be unloaded, and close the library if needed - * @param plug plugin handle to close - * @param status error result - * @internal ICU 4.4 Technology Preview - */ -U_INTERNAL void U_EXPORT2 -uplug_removePlug(UPlugData *plug, UErrorCode *status); -#endif /* U_HIDE_INTERNAL_API */ - -#endif /* UCONFIG_ENABLE_PLUGINS */ - -#endif /* _ICUPLUG */ - diff --git a/win32/include/spidermonkey/unicode/idna.h b/win32/include/spidermonkey/unicode/idna.h deleted file mode 100755 index 23a1d7ca..00000000 --- a/win32/include/spidermonkey/unicode/idna.h +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2010-2012, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* file name: idna.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2010mar05 -* created by: Markus W. Scherer -*/ - -#ifndef __IDNA_H__ -#define __IDNA_H__ - -/** - * \file - * \brief C++ API: Internationalizing Domain Names in Applications (IDNA) - */ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_IDNA - -#include "unicode/bytestream.h" -#include "unicode/stringpiece.h" -#include "unicode/uidna.h" -#include "unicode/unistr.h" - -U_NAMESPACE_BEGIN - -class IDNAInfo; - -/** - * Abstract base class for IDNA processing. - * See http://www.unicode.org/reports/tr46/ - * and http://www.ietf.org/rfc/rfc3490.txt - * - * The IDNA class is not intended for public subclassing. - * - * This C++ API currently only implements UTS #46. - * The uidna.h C API implements both UTS #46 (functions using UIDNA service object) - * and IDNA2003 (functions that do not use a service object). - * @stable ICU 4.6 - */ -class U_COMMON_API IDNA : public UObject { -public: - /** - * Destructor. - * @stable ICU 4.6 - */ - ~IDNA(); - - /** - * Returns an IDNA instance which implements UTS #46. - * Returns an unmodifiable instance, owned by the caller. - * Cache it for multiple operations, and delete it when done. - * The instance is thread-safe, that is, it can be used concurrently. - * - * UTS #46 defines Unicode IDNA Compatibility Processing, - * updated to the latest version of Unicode and compatible with both - * IDNA2003 and IDNA2008. - * - * The worker functions use transitional processing, including deviation mappings, - * unless UIDNA_NONTRANSITIONAL_TO_ASCII or UIDNA_NONTRANSITIONAL_TO_UNICODE - * is used in which case the deviation characters are passed through without change. - * - * Disallowed characters are mapped to U+FFFD. - * - * For available options see the uidna.h header. - * Operations with the UTS #46 instance do not support the - * UIDNA_ALLOW_UNASSIGNED option. - * - * By default, the UTS #46 implementation allows all ASCII characters (as valid or mapped). - * When the UIDNA_USE_STD3_RULES option is used, ASCII characters other than - * letters, digits, hyphen (LDH) and dot/full stop are disallowed and mapped to U+FFFD. - * - * @param options Bit set to modify the processing and error checking. - * See option bit set values in uidna.h. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the UTS #46 IDNA instance, if successful - * @stable ICU 4.6 - */ - static IDNA * - createUTS46Instance(uint32_t options, UErrorCode &errorCode); - - /** - * Converts a single domain name label into its ASCII form for DNS lookup. - * If any processing step fails, then info.hasErrors() will be TRUE and - * the result might not be an ASCII string. - * The label might be modified according to the types of errors. - * Labels with severe errors will be left in (or turned into) their Unicode form. - * - * The UErrorCode indicates an error only in exceptional cases, - * such as a U_MEMORY_ALLOCATION_ERROR. - * - * @param label Input domain name label - * @param dest Destination string object - * @param info Output container of IDNA processing details. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.6 - */ - virtual UnicodeString & - labelToASCII(const UnicodeString &label, UnicodeString &dest, - IDNAInfo &info, UErrorCode &errorCode) const = 0; - - /** - * Converts a single domain name label into its Unicode form for human-readable display. - * If any processing step fails, then info.hasErrors() will be TRUE. - * The label might be modified according to the types of errors. - * - * The UErrorCode indicates an error only in exceptional cases, - * such as a U_MEMORY_ALLOCATION_ERROR. - * - * @param label Input domain name label - * @param dest Destination string object - * @param info Output container of IDNA processing details. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.6 - */ - virtual UnicodeString & - labelToUnicode(const UnicodeString &label, UnicodeString &dest, - IDNAInfo &info, UErrorCode &errorCode) const = 0; - - /** - * Converts a whole domain name into its ASCII form for DNS lookup. - * If any processing step fails, then info.hasErrors() will be TRUE and - * the result might not be an ASCII string. - * The domain name might be modified according to the types of errors. - * Labels with severe errors will be left in (or turned into) their Unicode form. - * - * The UErrorCode indicates an error only in exceptional cases, - * such as a U_MEMORY_ALLOCATION_ERROR. - * - * @param name Input domain name - * @param dest Destination string object - * @param info Output container of IDNA processing details. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.6 - */ - virtual UnicodeString & - nameToASCII(const UnicodeString &name, UnicodeString &dest, - IDNAInfo &info, UErrorCode &errorCode) const = 0; - - /** - * Converts a whole domain name into its Unicode form for human-readable display. - * If any processing step fails, then info.hasErrors() will be TRUE. - * The domain name might be modified according to the types of errors. - * - * The UErrorCode indicates an error only in exceptional cases, - * such as a U_MEMORY_ALLOCATION_ERROR. - * - * @param name Input domain name - * @param dest Destination string object - * @param info Output container of IDNA processing details. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.6 - */ - virtual UnicodeString & - nameToUnicode(const UnicodeString &name, UnicodeString &dest, - IDNAInfo &info, UErrorCode &errorCode) const = 0; - - // UTF-8 versions of the processing methods ---------------------------- *** - - /** - * Converts a single domain name label into its ASCII form for DNS lookup. - * UTF-8 version of labelToASCII(), same behavior. - * - * @param label Input domain name label - * @param dest Destination byte sink; Flush()ed if successful - * @param info Output container of IDNA processing details. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.6 - */ - virtual void - labelToASCII_UTF8(StringPiece label, ByteSink &dest, - IDNAInfo &info, UErrorCode &errorCode) const; - - /** - * Converts a single domain name label into its Unicode form for human-readable display. - * UTF-8 version of labelToUnicode(), same behavior. - * - * @param label Input domain name label - * @param dest Destination byte sink; Flush()ed if successful - * @param info Output container of IDNA processing details. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.6 - */ - virtual void - labelToUnicodeUTF8(StringPiece label, ByteSink &dest, - IDNAInfo &info, UErrorCode &errorCode) const; - - /** - * Converts a whole domain name into its ASCII form for DNS lookup. - * UTF-8 version of nameToASCII(), same behavior. - * - * @param name Input domain name - * @param dest Destination byte sink; Flush()ed if successful - * @param info Output container of IDNA processing details. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.6 - */ - virtual void - nameToASCII_UTF8(StringPiece name, ByteSink &dest, - IDNAInfo &info, UErrorCode &errorCode) const; - - /** - * Converts a whole domain name into its Unicode form for human-readable display. - * UTF-8 version of nameToUnicode(), same behavior. - * - * @param name Input domain name - * @param dest Destination byte sink; Flush()ed if successful - * @param info Output container of IDNA processing details. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.6 - */ - virtual void - nameToUnicodeUTF8(StringPiece name, ByteSink &dest, - IDNAInfo &info, UErrorCode &errorCode) const; -}; - -class UTS46; - -/** - * Output container for IDNA processing errors. - * The IDNAInfo class is not suitable for subclassing. - * @stable ICU 4.6 - */ -class U_COMMON_API IDNAInfo : public UMemory { -public: - /** - * Constructor for stack allocation. - * @stable ICU 4.6 - */ - IDNAInfo() : errors(0), labelErrors(0), isTransDiff(FALSE), isBiDi(FALSE), isOkBiDi(TRUE) {} - /** - * Were there IDNA processing errors? - * @return TRUE if there were processing errors - * @stable ICU 4.6 - */ - UBool hasErrors() const { return errors!=0; } - /** - * Returns a bit set indicating IDNA processing errors. - * See UIDNA_ERROR_... constants in uidna.h. - * @return bit set of processing errors - * @stable ICU 4.6 - */ - uint32_t getErrors() const { return errors; } - /** - * Returns TRUE if transitional and nontransitional processing produce different results. - * This is the case when the input label or domain name contains - * one or more deviation characters outside a Punycode label (see UTS #46). - *
    - *
  • With nontransitional processing, such characters are - * copied to the destination string. - *
  • With transitional processing, such characters are - * mapped (sharp s/sigma) or removed (joiner/nonjoiner). - *
- * @return TRUE if transitional and nontransitional processing produce different results - * @stable ICU 4.6 - */ - UBool isTransitionalDifferent() const { return isTransDiff; } - -private: - friend class UTS46; - - IDNAInfo(const IDNAInfo &other); // no copying - IDNAInfo &operator=(const IDNAInfo &other); // no copying - - void reset() { - errors=labelErrors=0; - isTransDiff=FALSE; - isBiDi=FALSE; - isOkBiDi=TRUE; - } - - uint32_t errors, labelErrors; - UBool isTransDiff; - UBool isBiDi; - UBool isOkBiDi; -}; - -U_NAMESPACE_END - -#endif // UCONFIG_NO_IDNA -#endif // __IDNA_H__ diff --git a/win32/include/spidermonkey/unicode/listformatter.h b/win32/include/spidermonkey/unicode/listformatter.h deleted file mode 100755 index f2c89888..00000000 --- a/win32/include/spidermonkey/unicode/listformatter.h +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2012-2016, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: listformatter.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 20120426 -* created by: Umesh P. Nair -*/ - -#ifndef __LISTFORMATTER_H__ -#define __LISTFORMATTER_H__ - -#include "unicode/utypes.h" - -#include "unicode/unistr.h" -#include "unicode/locid.h" - -U_NAMESPACE_BEGIN - -/** @internal */ -class Hashtable; - -/** @internal */ -struct ListFormatInternal; - -/* The following can't be #ifndef U_HIDE_INTERNAL_API, needed for other .h file declarations */ -/** @internal */ -struct ListFormatData : public UMemory { - UnicodeString twoPattern; - UnicodeString startPattern; - UnicodeString middlePattern; - UnicodeString endPattern; - - ListFormatData(const UnicodeString& two, const UnicodeString& start, const UnicodeString& middle, const UnicodeString& end) : - twoPattern(two), startPattern(start), middlePattern(middle), endPattern(end) {} -}; - - -/** - * \file - * \brief C++ API: API for formatting a list. - */ - - -/** - * An immutable class for formatting a list, using data from CLDR (or supplied - * separately). - * - * Example: Input data ["Alice", "Bob", "Charlie", "Delta"] will be formatted - * as "Alice, Bob, Charlie and Delta" in English. - * - * The ListFormatter class is not intended for public subclassing. - * @stable ICU 50 - */ -class U_COMMON_API ListFormatter : public UObject{ - - public: - - /** - * Copy constructor. - * @stable ICU 52 - */ - ListFormatter(const ListFormatter&); - - /** - * Assignment operator. - * @stable ICU 52 - */ - ListFormatter& operator=(const ListFormatter& other); - - /** - * Creates a ListFormatter appropriate for the default locale. - * - * @param errorCode ICU error code, set if no data available for default locale. - * @return Pointer to a ListFormatter object for the default locale, - * created from internal data derived from CLDR data. - * @stable ICU 50 - */ - static ListFormatter* createInstance(UErrorCode& errorCode); - - /** - * Creates a ListFormatter appropriate for a locale. - * - * @param locale The locale. - * @param errorCode ICU error code, set if no data available for the given locale. - * @return A ListFormatter object created from internal data derived from - * CLDR data. - * @stable ICU 50 - */ - static ListFormatter* createInstance(const Locale& locale, UErrorCode& errorCode); - -#ifndef U_HIDE_INTERNAL_API - /** - * Creates a ListFormatter appropriate for a locale and style. - * - * @param locale The locale. - * @param style the style, either "standard", "duration", or "duration-short" - * @param errorCode ICU error code, set if no data available for the given locale. - * @return A ListFormatter object created from internal data derived from - * CLDR data. - * @internal - */ - static ListFormatter* createInstance(const Locale& locale, const char* style, UErrorCode& errorCode); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Destructor. - * - * @stable ICU 50 - */ - virtual ~ListFormatter(); - - - /** - * Formats a list of strings. - * - * @param items An array of strings to be combined and formatted. - * @param n_items Length of the array items. - * @param appendTo The string to which the result should be appended to. - * @param errorCode ICU error code, set if there is an error. - * @return Formatted string combining the elements of items, appended to appendTo. - * @stable ICU 50 - */ - UnicodeString& format(const UnicodeString items[], int32_t n_items, - UnicodeString& appendTo, UErrorCode& errorCode) const; - -#ifndef U_HIDE_INTERNAL_API - /** - @internal for MeasureFormat - */ - UnicodeString& format( - const UnicodeString items[], - int32_t n_items, - UnicodeString& appendTo, - int32_t index, - int32_t &offset, - UErrorCode& errorCode) const; - /** - * @internal constructor made public for testing. - */ - ListFormatter(const ListFormatData &data, UErrorCode &errorCode); - /** - * @internal constructor made public for testing. - */ - ListFormatter(const ListFormatInternal* listFormatterInternal); -#endif /* U_HIDE_INTERNAL_API */ - - private: - static void initializeHash(UErrorCode& errorCode); - static const ListFormatInternal* getListFormatInternal(const Locale& locale, const char *style, UErrorCode& errorCode); - - ListFormatter(); - - ListFormatInternal* owned; - const ListFormatInternal* data; -}; - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/localpointer.h b/win32/include/spidermonkey/unicode/localpointer.h deleted file mode 100755 index 9ac5de5f..00000000 --- a/win32/include/spidermonkey/unicode/localpointer.h +++ /dev/null @@ -1,561 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2009-2016, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: localpointer.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2009nov13 -* created by: Markus W. Scherer -*/ - -#ifndef __LOCALPOINTER_H__ -#define __LOCALPOINTER_H__ - -/** - * \file - * \brief C++ API: "Smart pointers" for use with and in ICU4C C++ code. - * - * These classes are inspired by - * - std::auto_ptr - * - boost::scoped_ptr & boost::scoped_array - * - Taligent Safe Pointers (TOnlyPointerTo) - * - * but none of those provide for all of the goals for ICU smart pointers: - * - Smart pointer owns the object and releases it when it goes out of scope. - * - No transfer of ownership via copy/assignment to reduce misuse. Simpler & more robust. - * - ICU-compatible: No exceptions. - * - Need to be able to orphan/release the pointer and its ownership. - * - Need variants for normal C++ object pointers, C++ arrays, and ICU C service objects. - * - * For details see http://site.icu-project.org/design/cpp/scoped_ptr - */ - -#include "unicode/utypes.h" - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * "Smart pointer" base class; do not use directly: use LocalPointer etc. - * - * Base class for smart pointer classes that do not throw exceptions. - * - * Do not use this base class directly, since it does not delete its pointer. - * A subclass must implement methods that delete the pointer: - * Destructor and adoptInstead(). - * - * There is no operator T *() provided because the programmer must decide - * whether to use getAlias() (without transfer of ownership) or orphan() - * (with transfer of ownership and NULLing of the pointer). - * - * @see LocalPointer - * @see LocalArray - * @see U_DEFINE_LOCAL_OPEN_POINTER - * @stable ICU 4.4 - */ -template -class LocalPointerBase { -public: - /** - * Constructor takes ownership. - * @param p simple pointer to an object that is adopted - * @stable ICU 4.4 - */ - explicit LocalPointerBase(T *p=NULL) : ptr(p) {} - /** - * Destructor deletes the object it owns. - * Subclass must override: Base class does nothing. - * @stable ICU 4.4 - */ - ~LocalPointerBase() { /* delete ptr; */ } - /** - * NULL check. - * @return TRUE if ==NULL - * @stable ICU 4.4 - */ - UBool isNull() const { return ptr==NULL; } - /** - * NULL check. - * @return TRUE if !=NULL - * @stable ICU 4.4 - */ - UBool isValid() const { return ptr!=NULL; } - /** - * Comparison with a simple pointer, so that existing code - * with ==NULL need not be changed. - * @param other simple pointer for comparison - * @return true if this pointer value equals other - * @stable ICU 4.4 - */ - bool operator==(const T *other) const { return ptr==other; } - /** - * Comparison with a simple pointer, so that existing code - * with !=NULL need not be changed. - * @param other simple pointer for comparison - * @return true if this pointer value differs from other - * @stable ICU 4.4 - */ - bool operator!=(const T *other) const { return ptr!=other; } - /** - * Access without ownership change. - * @return the pointer value - * @stable ICU 4.4 - */ - T *getAlias() const { return ptr; } - /** - * Access without ownership change. - * @return the pointer value as a reference - * @stable ICU 4.4 - */ - T &operator*() const { return *ptr; } - /** - * Access without ownership change. - * @return the pointer value - * @stable ICU 4.4 - */ - T *operator->() const { return ptr; } - /** - * Gives up ownership; the internal pointer becomes NULL. - * @return the pointer value; - * caller becomes responsible for deleting the object - * @stable ICU 4.4 - */ - T *orphan() { - T *p=ptr; - ptr=NULL; - return p; - } - /** - * Deletes the object it owns, - * and adopts (takes ownership of) the one passed in. - * Subclass must override: Base class does not delete the object. - * @param p simple pointer to an object that is adopted - * @stable ICU 4.4 - */ - void adoptInstead(T *p) { - // delete ptr; - ptr=p; - } -protected: - /** - * Actual pointer. - * @internal - */ - T *ptr; -private: - // No comparison operators with other LocalPointerBases. - bool operator==(const LocalPointerBase &other); - bool operator!=(const LocalPointerBase &other); - // No ownership sharing: No copy constructor, no assignment operator. - LocalPointerBase(const LocalPointerBase &other); - void operator=(const LocalPointerBase &other); - // No heap allocation. Use only on the stack. - static void * U_EXPORT2 operator new(size_t size); - static void * U_EXPORT2 operator new[](size_t size); -#if U_HAVE_PLACEMENT_NEW - static void * U_EXPORT2 operator new(size_t, void *ptr); -#endif -}; - -/** - * "Smart pointer" class, deletes objects via the standard C++ delete operator. - * For most methods see the LocalPointerBase base class. - * - * Usage example: - * \code - * LocalPointer s(new UnicodeString((UChar32)0x50005)); - * int32_t length=s->length(); // 2 - * UChar lead=s->charAt(0); // 0xd900 - * if(some condition) { return; } // no need to explicitly delete the pointer - * s.adoptInstead(new UnicodeString((UChar)0xfffc)); - * length=s->length(); // 1 - * // no need to explicitly delete the pointer - * \endcode - * - * @see LocalPointerBase - * @stable ICU 4.4 - */ -template -class LocalPointer : public LocalPointerBase { -public: - using LocalPointerBase::operator*; - using LocalPointerBase::operator->; - /** - * Constructor takes ownership. - * @param p simple pointer to an object that is adopted - * @stable ICU 4.4 - */ - explicit LocalPointer(T *p=NULL) : LocalPointerBase(p) {} - /** - * Constructor takes ownership and reports an error if NULL. - * - * This constructor is intended to be used with other-class constructors - * that may report a failure UErrorCode, - * so that callers need to check only for U_FAILURE(errorCode) - * and not also separately for isNull(). - * - * @param p simple pointer to an object that is adopted - * @param errorCode in/out UErrorCode, set to U_MEMORY_ALLOCATION_ERROR - * if p==NULL and no other failure code had been set - * @stable ICU 55 - */ - LocalPointer(T *p, UErrorCode &errorCode) : LocalPointerBase(p) { - if(p==NULL && U_SUCCESS(errorCode)) { - errorCode=U_MEMORY_ALLOCATION_ERROR; - } - } -#if U_HAVE_RVALUE_REFERENCES - /** - * Move constructor, leaves src with isNull(). - * @param src source smart pointer - * @stable ICU 56 - */ - LocalPointer(LocalPointer &&src) U_NOEXCEPT : LocalPointerBase(src.ptr) { - src.ptr=NULL; - } -#endif - /** - * Destructor deletes the object it owns. - * @stable ICU 4.4 - */ - ~LocalPointer() { - delete LocalPointerBase::ptr; - } -#if U_HAVE_RVALUE_REFERENCES - /** - * Move assignment operator, leaves src with isNull(). - * The behavior is undefined if *this and src are the same object. - * @param src source smart pointer - * @return *this - * @stable ICU 56 - */ - LocalPointer &operator=(LocalPointer &&src) U_NOEXCEPT { - return moveFrom(src); - } -#endif - // do not use #ifndef U_HIDE_DRAFT_API for moveFrom, needed by non-draft API - /** - * Move assignment, leaves src with isNull(). - * The behavior is undefined if *this and src are the same object. - * - * Can be called explicitly, does not need C++11 support. - * @param src source smart pointer - * @return *this - * @draft ICU 56 - */ - LocalPointer &moveFrom(LocalPointer &src) U_NOEXCEPT { - delete LocalPointerBase::ptr; - LocalPointerBase::ptr=src.ptr; - src.ptr=NULL; - return *this; - } - /** - * Swap pointers. - * @param other other smart pointer - * @stable ICU 56 - */ - void swap(LocalPointer &other) U_NOEXCEPT { - T *temp=LocalPointerBase::ptr; - LocalPointerBase::ptr=other.ptr; - other.ptr=temp; - } - /** - * Non-member LocalPointer swap function. - * @param p1 will get p2's pointer - * @param p2 will get p1's pointer - * @stable ICU 56 - */ - friend inline void swap(LocalPointer &p1, LocalPointer &p2) U_NOEXCEPT { - p1.swap(p2); - } - /** - * Deletes the object it owns, - * and adopts (takes ownership of) the one passed in. - * @param p simple pointer to an object that is adopted - * @stable ICU 4.4 - */ - void adoptInstead(T *p) { - delete LocalPointerBase::ptr; - LocalPointerBase::ptr=p; - } - /** - * Deletes the object it owns, - * and adopts (takes ownership of) the one passed in. - * - * If U_FAILURE(errorCode), then the current object is retained and the new one deleted. - * - * If U_SUCCESS(errorCode) but the input pointer is NULL, - * then U_MEMORY_ALLOCATION_ERROR is set, - * the current object is deleted, and NULL is set. - * - * @param p simple pointer to an object that is adopted - * @param errorCode in/out UErrorCode, set to U_MEMORY_ALLOCATION_ERROR - * if p==NULL and no other failure code had been set - * @stable ICU 55 - */ - void adoptInsteadAndCheckErrorCode(T *p, UErrorCode &errorCode) { - if(U_SUCCESS(errorCode)) { - delete LocalPointerBase::ptr; - LocalPointerBase::ptr=p; - if(p==NULL) { - errorCode=U_MEMORY_ALLOCATION_ERROR; - } - } else { - delete p; - } - } -}; - -/** - * "Smart pointer" class, deletes objects via the C++ array delete[] operator. - * For most methods see the LocalPointerBase base class. - * Adds operator[] for array item access. - * - * Usage example: - * \code - * LocalArray a(new UnicodeString[2]); - * a[0].append((UChar)0x61); - * if(some condition) { return; } // no need to explicitly delete the array - * a.adoptInstead(new UnicodeString[4]); - * a[3].append((UChar)0x62).append((UChar)0x63).reverse(); - * // no need to explicitly delete the array - * \endcode - * - * @see LocalPointerBase - * @stable ICU 4.4 - */ -template -class LocalArray : public LocalPointerBase { -public: - using LocalPointerBase::operator*; - using LocalPointerBase::operator->; - /** - * Constructor takes ownership. - * @param p simple pointer to an array of T objects that is adopted - * @stable ICU 4.4 - */ - explicit LocalArray(T *p=NULL) : LocalPointerBase(p) {} - /** - * Constructor takes ownership and reports an error if NULL. - * - * This constructor is intended to be used with other-class constructors - * that may report a failure UErrorCode, - * so that callers need to check only for U_FAILURE(errorCode) - * and not also separately for isNull(). - * - * @param p simple pointer to an array of T objects that is adopted - * @param errorCode in/out UErrorCode, set to U_MEMORY_ALLOCATION_ERROR - * if p==NULL and no other failure code had been set - * @stable ICU 56 - */ - LocalArray(T *p, UErrorCode &errorCode) : LocalPointerBase(p) { - if(p==NULL && U_SUCCESS(errorCode)) { - errorCode=U_MEMORY_ALLOCATION_ERROR; - } - } -#if U_HAVE_RVALUE_REFERENCES - /** - * Move constructor, leaves src with isNull(). - * @param src source smart pointer - * @stable ICU 56 - */ - LocalArray(LocalArray &&src) U_NOEXCEPT : LocalPointerBase(src.ptr) { - src.ptr=NULL; - } -#endif - /** - * Destructor deletes the array it owns. - * @stable ICU 4.4 - */ - ~LocalArray() { - delete[] LocalPointerBase::ptr; - } -#if U_HAVE_RVALUE_REFERENCES - /** - * Move assignment operator, leaves src with isNull(). - * The behavior is undefined if *this and src are the same object. - * @param src source smart pointer - * @return *this - * @stable ICU 56 - */ - LocalArray &operator=(LocalArray &&src) U_NOEXCEPT { - return moveFrom(src); - } -#endif - // do not use #ifndef U_HIDE_DRAFT_API for moveFrom, needed by non-draft API - /** - * Move assignment, leaves src with isNull(). - * The behavior is undefined if *this and src are the same object. - * - * Can be called explicitly, does not need C++11 support. - * @param src source smart pointer - * @return *this - * @draft ICU 56 - */ - LocalArray &moveFrom(LocalArray &src) U_NOEXCEPT { - delete[] LocalPointerBase::ptr; - LocalPointerBase::ptr=src.ptr; - src.ptr=NULL; - return *this; - } - /** - * Swap pointers. - * @param other other smart pointer - * @stable ICU 56 - */ - void swap(LocalArray &other) U_NOEXCEPT { - T *temp=LocalPointerBase::ptr; - LocalPointerBase::ptr=other.ptr; - other.ptr=temp; - } - /** - * Non-member LocalArray swap function. - * @param p1 will get p2's pointer - * @param p2 will get p1's pointer - * @stable ICU 56 - */ - friend inline void swap(LocalArray &p1, LocalArray &p2) U_NOEXCEPT { - p1.swap(p2); - } - /** - * Deletes the array it owns, - * and adopts (takes ownership of) the one passed in. - * @param p simple pointer to an array of T objects that is adopted - * @stable ICU 4.4 - */ - void adoptInstead(T *p) { - delete[] LocalPointerBase::ptr; - LocalPointerBase::ptr=p; - } - /** - * Deletes the array it owns, - * and adopts (takes ownership of) the one passed in. - * - * If U_FAILURE(errorCode), then the current array is retained and the new one deleted. - * - * If U_SUCCESS(errorCode) but the input pointer is NULL, - * then U_MEMORY_ALLOCATION_ERROR is set, - * the current array is deleted, and NULL is set. - * - * @param p simple pointer to an array of T objects that is adopted - * @param errorCode in/out UErrorCode, set to U_MEMORY_ALLOCATION_ERROR - * if p==NULL and no other failure code had been set - * @stable ICU 56 - */ - void adoptInsteadAndCheckErrorCode(T *p, UErrorCode &errorCode) { - if(U_SUCCESS(errorCode)) { - delete[] LocalPointerBase::ptr; - LocalPointerBase::ptr=p; - if(p==NULL) { - errorCode=U_MEMORY_ALLOCATION_ERROR; - } - } else { - delete[] p; - } - } - /** - * Array item access (writable). - * No index bounds check. - * @param i array index - * @return reference to the array item - * @stable ICU 4.4 - */ - T &operator[](ptrdiff_t i) const { return LocalPointerBase::ptr[i]; } -}; - -/** - * \def U_DEFINE_LOCAL_OPEN_POINTER - * "Smart pointer" definition macro, deletes objects via the closeFunction. - * Defines a subclass of LocalPointerBase which works just - * like LocalPointer except that this subclass will use the closeFunction - * rather than the C++ delete operator. - * - * Usage example: - * \code - * LocalUCaseMapPointer csm(ucasemap_open(localeID, options, &errorCode)); - * utf8OutLength=ucasemap_utf8ToLower(csm.getAlias(), - * utf8Out, (int32_t)sizeof(utf8Out), - * utf8In, utf8InLength, &errorCode); - * if(U_FAILURE(errorCode)) { return; } // no need to explicitly delete the UCaseMap - * \endcode - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -#if U_HAVE_RVALUE_REFERENCES -#define U_DEFINE_LOCAL_OPEN_POINTER(LocalPointerClassName, Type, closeFunction) \ - class LocalPointerClassName : public LocalPointerBase { \ - public: \ - using LocalPointerBase::operator*; \ - using LocalPointerBase::operator->; \ - explicit LocalPointerClassName(Type *p=NULL) : LocalPointerBase(p) {} \ - LocalPointerClassName(LocalPointerClassName &&src) U_NOEXCEPT \ - : LocalPointerBase(src.ptr) { \ - src.ptr=NULL; \ - } \ - ~LocalPointerClassName() { if (ptr != NULL) { closeFunction(ptr); } } \ - LocalPointerClassName &operator=(LocalPointerClassName &&src) U_NOEXCEPT { \ - return moveFrom(src); \ - } \ - LocalPointerClassName &moveFrom(LocalPointerClassName &src) U_NOEXCEPT { \ - if (ptr != NULL) { closeFunction(ptr); } \ - LocalPointerBase::ptr=src.ptr; \ - src.ptr=NULL; \ - return *this; \ - } \ - void swap(LocalPointerClassName &other) U_NOEXCEPT { \ - Type *temp=LocalPointerBase::ptr; \ - LocalPointerBase::ptr=other.ptr; \ - other.ptr=temp; \ - } \ - friend inline void swap(LocalPointerClassName &p1, LocalPointerClassName &p2) U_NOEXCEPT { \ - p1.swap(p2); \ - } \ - void adoptInstead(Type *p) { \ - if (ptr != NULL) { closeFunction(ptr); } \ - ptr=p; \ - } \ - } -#else -#define U_DEFINE_LOCAL_OPEN_POINTER(LocalPointerClassName, Type, closeFunction) \ - class LocalPointerClassName : public LocalPointerBase { \ - public: \ - using LocalPointerBase::operator*; \ - using LocalPointerBase::operator->; \ - explicit LocalPointerClassName(Type *p=NULL) : LocalPointerBase(p) {} \ - ~LocalPointerClassName() { closeFunction(ptr); } \ - LocalPointerClassName &moveFrom(LocalPointerClassName &src) U_NOEXCEPT { \ - if (ptr != NULL) { closeFunction(ptr); } \ - LocalPointerBase::ptr=src.ptr; \ - src.ptr=NULL; \ - return *this; \ - } \ - void swap(LocalPointerClassName &other) U_NOEXCEPT { \ - Type *temp=LocalPointerBase::ptr; \ - LocalPointerBase::ptr=other.ptr; \ - other.ptr=temp; \ - } \ - friend inline void swap(LocalPointerClassName &p1, LocalPointerClassName &p2) U_NOEXCEPT { \ - p1.swap(p2); \ - } \ - void adoptInstead(Type *p) { \ - if (ptr != NULL) { closeFunction(ptr); } \ - ptr=p; \ - } \ - } -#endif - -U_NAMESPACE_END - -#endif /* U_SHOW_CPLUSPLUS_API */ -#endif /* __LOCALPOINTER_H__ */ diff --git a/win32/include/spidermonkey/unicode/locdspnm.h b/win32/include/spidermonkey/unicode/locdspnm.h deleted file mode 100755 index b8c7a0cc..00000000 --- a/win32/include/spidermonkey/unicode/locdspnm.h +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* Copyright (C) 2010-2016, International Business Machines Corporation and -* others. All Rights Reserved. -****************************************************************************** -*/ - -#ifndef LOCDSPNM_H -#define LOCDSPNM_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Provides display names of Locale and its components. - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/locid.h" -#include "unicode/uscript.h" -#include "unicode/uldnames.h" -#include "unicode/udisplaycontext.h" - -U_NAMESPACE_BEGIN - -/** - * Returns display names of Locales and components of Locales. For - * more information on language, script, region, variant, key, and - * values, see Locale. - * @stable ICU 4.4 - */ -class U_COMMON_API LocaleDisplayNames : public UObject { -public: - /** - * Destructor. - * @stable ICU 4.4 - */ - virtual ~LocaleDisplayNames(); - - /** - * Convenience overload of - * {@link #createInstance(const Locale& locale, UDialectHandling dialectHandling)} - * that specifies STANDARD dialect handling. - * @param locale the display locale - * @return a LocaleDisplayNames instance - * @stable ICU 4.4 - */ - static LocaleDisplayNames* U_EXPORT2 createInstance(const Locale& locale); - - /** - * Returns an instance of LocaleDisplayNames that returns names - * formatted for the provided locale, using the provided - * dialectHandling. - * - * @param locale the display locale - * @param dialectHandling how to select names for locales - * @return a LocaleDisplayNames instance - * @stable ICU 4.4 - */ - static LocaleDisplayNames* U_EXPORT2 createInstance(const Locale& locale, - UDialectHandling dialectHandling); - - /** - * Returns an instance of LocaleDisplayNames that returns names formatted - * for the provided locale, using the provided UDisplayContext settings. - * - * @param locale the display locale - * @param contexts List of one or more context settings (e.g. for dialect - * handling, capitalization, etc. - * @param length Number of items in the contexts list - * @return a LocaleDisplayNames instance - * @stable ICU 51 - */ - static LocaleDisplayNames* U_EXPORT2 createInstance(const Locale& locale, - UDisplayContext *contexts, int32_t length); - - // getters for state - /** - * Returns the locale used to determine the display names. This is - * not necessarily the same locale passed to {@link #createInstance}. - * @return the display locale - * @stable ICU 4.4 - */ - virtual const Locale& getLocale() const = 0; - - /** - * Returns the dialect handling used in the display names. - * @return the dialect handling enum - * @stable ICU 4.4 - */ - virtual UDialectHandling getDialectHandling() const = 0; - - /** - * Returns the UDisplayContext value for the specified UDisplayContextType. - * @param type the UDisplayContextType whose value to return - * @return the UDisplayContext for the specified type. - * @stable ICU 51 - */ - virtual UDisplayContext getContext(UDisplayContextType type) const = 0; - - // names for entire locales - /** - * Returns the display name of the provided locale. - * @param locale the locale whose display name to return - * @param result receives the locale's display name - * @return the display name of the provided locale - * @stable ICU 4.4 - */ - virtual UnicodeString& localeDisplayName(const Locale& locale, - UnicodeString& result) const = 0; - - /** - * Returns the display name of the provided locale id. - * @param localeId the id of the locale whose display name to return - * @param result receives the locale's display name - * @return the display name of the provided locale - * @stable ICU 4.4 - */ - virtual UnicodeString& localeDisplayName(const char* localeId, - UnicodeString& result) const = 0; - - // names for components of a locale id - /** - * Returns the display name of the provided language code. - * @param lang the language code - * @param result receives the language code's display name - * @return the display name of the provided language code - * @stable ICU 4.4 - */ - virtual UnicodeString& languageDisplayName(const char* lang, - UnicodeString& result) const = 0; - - /** - * Returns the display name of the provided script code. - * @param script the script code - * @param result receives the script code's display name - * @return the display name of the provided script code - * @stable ICU 4.4 - */ - virtual UnicodeString& scriptDisplayName(const char* script, - UnicodeString& result) const = 0; - - /** - * Returns the display name of the provided script code. - * @param scriptCode the script code number - * @param result receives the script code's display name - * @return the display name of the provided script code - * @stable ICU 4.4 - */ - virtual UnicodeString& scriptDisplayName(UScriptCode scriptCode, - UnicodeString& result) const = 0; - - /** - * Returns the display name of the provided region code. - * @param region the region code - * @param result receives the region code's display name - * @return the display name of the provided region code - * @stable ICU 4.4 - */ - virtual UnicodeString& regionDisplayName(const char* region, - UnicodeString& result) const = 0; - - /** - * Returns the display name of the provided variant. - * @param variant the variant string - * @param result receives the variant's display name - * @return the display name of the provided variant - * @stable ICU 4.4 - */ - virtual UnicodeString& variantDisplayName(const char* variant, - UnicodeString& result) const = 0; - - /** - * Returns the display name of the provided locale key. - * @param key the locale key name - * @param result receives the locale key's display name - * @return the display name of the provided locale key - * @stable ICU 4.4 - */ - virtual UnicodeString& keyDisplayName(const char* key, - UnicodeString& result) const = 0; - - /** - * Returns the display name of the provided value (used with the provided key). - * @param key the locale key name - * @param value the locale key's value - * @param result receives the value's display name - * @return the display name of the provided value - * @stable ICU 4.4 - */ - virtual UnicodeString& keyValueDisplayName(const char* key, const char* value, - UnicodeString& result) const = 0; -}; - -inline LocaleDisplayNames* LocaleDisplayNames::createInstance(const Locale& locale) { - return LocaleDisplayNames::createInstance(locale, ULDN_STANDARD_NAMES); -} - -U_NAMESPACE_END - -#endif - -#endif diff --git a/win32/include/spidermonkey/unicode/locid.h b/win32/include/spidermonkey/unicode/locid.h deleted file mode 100755 index a8ddb7f3..00000000 --- a/win32/include/spidermonkey/unicode/locid.h +++ /dev/null @@ -1,814 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 1996-2015, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* -* File locid.h -* -* Created by: Helena Shih -* -* Modification History: -* -* Date Name Description -* 02/11/97 aliu Changed gLocPath to fgLocPath and added methods to -* get and set it. -* 04/02/97 aliu Made operator!= inline; fixed return value of getName(). -* 04/15/97 aliu Cleanup for AIX/Win32. -* 04/24/97 aliu Numerous changes per code review. -* 08/18/98 stephen Added tokenizeString(),changed getDisplayName() -* 09/08/98 stephen Moved definition of kEmptyString for Mac Port -* 11/09/99 weiv Added const char * getName() const; -* 04/12/00 srl removing unicodestring api's and cached hash code -* 08/10/01 grhoten Change the static Locales to accessor functions -****************************************************************************** -*/ - -#ifndef LOCID_H -#define LOCID_H - -#include "unicode/utypes.h" -#include "unicode/uobject.h" -#include "unicode/unistr.h" -#include "unicode/putil.h" -#include "unicode/uloc.h" -#include "unicode/strenum.h" - -/** - * \file - * \brief C++ API: Locale ID object. - */ - -U_NAMESPACE_BEGIN - -// Forward Declarations -void U_CALLCONV locale_available_init(); /**< @internal */ - -/** - * A Locale object represents a specific geographical, political, - * or cultural region. An operation that requires a Locale to perform - * its task is called locale-sensitive and uses the Locale - * to tailor information for the user. For example, displaying a number - * is a locale-sensitive operation--the number should be formatted - * according to the customs/conventions of the user's native country, - * region, or culture. - * - * The Locale class is not suitable for subclassing. - * - *

- * You can create a Locale object using the constructor in - * this class: - * \htmlonly

\endhtmlonly - *
- *       Locale( const   char*  language,
- *               const   char*  country,
- *               const   char*  variant);
- * 
- * \htmlonly
\endhtmlonly - * The first argument to the constructors is a valid ISO - * Language Code. These codes are the lower-case two-letter - * codes as defined by ISO-639. - * You can find a full list of these codes at: - *
- * http://www.loc.gov/standards/iso639-2/ - * - *

- * The second argument to the constructors is a valid ISO Country - * Code. These codes are the upper-case two-letter codes - * as defined by ISO-3166. - * You can find a full list of these codes at a number of sites, such as: - *
- * http://www.iso.org/iso/en/prods-services/iso3166ma/index.html - * - *

- * The third constructor requires a third argument--the Variant. - * The Variant codes are vendor and browser-specific. - * For example, use REVISED for a langauge's revised script orthography, and POSIX for POSIX. - * Where there are two variants, separate them with an underscore, and - * put the most important one first. For - * example, a Traditional Spanish collation might be referenced, with - * "ES", "ES", "Traditional_POSIX". - * - *

- * Because a Locale object is just an identifier for a region, - * no validity check is performed when you construct a Locale. - * If you want to see whether particular resources are available for the - * Locale you construct, you must query those resources. For - * example, ask the NumberFormat for the locales it supports - * using its getAvailableLocales method. - *
Note: When you ask for a resource for a particular - * locale, you get back the best available match, not necessarily - * precisely what you asked for. For more information, look at - * ResourceBundle. - * - *

- * The Locale class provides a number of convenient constants - * that you can use to create Locale objects for commonly used - * locales. For example, the following refers to a Locale object - * for the United States: - * \htmlonly

\endhtmlonly - *
- *       Locale::getUS()
- * 
- * \htmlonly
\endhtmlonly - * - *

- * Once you've created a Locale you can query it for information about - * itself. Use getCountry to get the ISO Country Code and - * getLanguage to get the ISO Language Code. You can - * use getDisplayCountry to get the - * name of the country suitable for displaying to the user. Similarly, - * you can use getDisplayLanguage to get the name of - * the language suitable for displaying to the user. Interestingly, - * the getDisplayXXX methods are themselves locale-sensitive - * and have two versions: one that uses the default locale and one - * that takes a locale as an argument and displays the name or country in - * a language appropriate to that locale. - * - *

- * ICU provides a number of classes that perform locale-sensitive - * operations. For example, the NumberFormat class formats - * numbers, currency, or percentages in a locale-sensitive manner. Classes - * such as NumberFormat have a number of convenience methods - * for creating a default object of that type. For example, the - * NumberFormat class provides these three convenience methods - * for creating a default NumberFormat object: - * \htmlonly

\endhtmlonly - *
- *     UErrorCode success = U_ZERO_ERROR;
- *     Locale myLocale;
- *     NumberFormat *nf;
- *
- *     nf = NumberFormat::createInstance( success );          delete nf;
- *     nf = NumberFormat::createCurrencyInstance( success );  delete nf;
- *     nf = NumberFormat::createPercentInstance( success );   delete nf;
- * 
- * \htmlonly
\endhtmlonly - * Each of these methods has two variants; one with an explicit locale - * and one without; the latter using the default locale. - * \htmlonly
\endhtmlonly - *
- *     nf = NumberFormat::createInstance( myLocale, success );          delete nf;
- *     nf = NumberFormat::createCurrencyInstance( myLocale, success );  delete nf;
- *     nf = NumberFormat::createPercentInstance( myLocale, success );   delete nf;
- * 
- * \htmlonly
\endhtmlonly - * A Locale is the mechanism for identifying the kind of object - * (NumberFormat) that you would like to get. The locale is - * just a mechanism for identifying objects, - * not a container for the objects themselves. - * - *

- * Each class that performs locale-sensitive operations allows you - * to get all the available objects of that type. You can sift - * through these objects by language, country, or variant, - * and use the display names to present a menu to the user. - * For example, you can create a menu of all the collation objects - * suitable for a given language. Such classes implement these - * three class methods: - * \htmlonly

\endhtmlonly - *
- *       static Locale* getAvailableLocales(int32_t& numLocales)
- *       static UnicodeString& getDisplayName(const Locale&  objectLocale,
- *                                            const Locale&  displayLocale,
- *                                            UnicodeString& displayName)
- *       static UnicodeString& getDisplayName(const Locale&  objectLocale,
- *                                            UnicodeString& displayName)
- * 
- * \htmlonly
\endhtmlonly - * - * @stable ICU 2.0 - * @see ResourceBundle - */ -class U_COMMON_API Locale : public UObject { -public: - /** Useful constant for the Root locale. @stable ICU 4.4 */ - static const Locale &U_EXPORT2 getRoot(void); - /** Useful constant for this language. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getEnglish(void); - /** Useful constant for this language. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getFrench(void); - /** Useful constant for this language. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getGerman(void); - /** Useful constant for this language. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getItalian(void); - /** Useful constant for this language. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getJapanese(void); - /** Useful constant for this language. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getKorean(void); - /** Useful constant for this language. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getChinese(void); - /** Useful constant for this language. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getSimplifiedChinese(void); - /** Useful constant for this language. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getTraditionalChinese(void); - - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getFrance(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getGermany(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getItaly(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getJapan(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getKorea(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getChina(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getPRC(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getTaiwan(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getUK(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getUS(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getCanada(void); - /** Useful constant for this country/region. @stable ICU 2.0 */ - static const Locale &U_EXPORT2 getCanadaFrench(void); - - - /** - * Construct a default locale object, a Locale for the default locale ID. - * - * @see getDefault - * @see uloc_getDefault - * @stable ICU 2.0 - */ - Locale(); - - /** - * Construct a locale from language, country, variant. - * If an error occurs, then the constructed object will be "bogus" - * (isBogus() will return TRUE). - * - * @param language Lowercase two-letter or three-letter ISO-639 code. - * This parameter can instead be an ICU style C locale (e.g. "en_US"), - * but the other parameters must not be used. - * This parameter can be NULL; if so, - * the locale is initialized to match the current default locale. - * (This is the same as using the default constructor.) - * Please note: The Java Locale class does NOT accept the form - * 'new Locale("en_US")' but only 'new Locale("en","US")' - * - * @param country Uppercase two-letter ISO-3166 code. (optional) - * @param variant Uppercase vendor and browser specific code. See class - * description. (optional) - * @param keywordsAndValues A string consisting of keyword/values pairs, such as - * "collation=phonebook;currency=euro" - * - * @see getDefault - * @see uloc_getDefault - * @stable ICU 2.0 - */ - Locale( const char * language, - const char * country = 0, - const char * variant = 0, - const char * keywordsAndValues = 0); - - /** - * Initializes a Locale object from another Locale object. - * - * @param other The Locale object being copied in. - * @stable ICU 2.0 - */ - Locale(const Locale& other); - - - /** - * Destructor - * @stable ICU 2.0 - */ - virtual ~Locale() ; - - /** - * Replaces the entire contents of *this with the specified value. - * - * @param other The Locale object being copied in. - * @return *this - * @stable ICU 2.0 - */ - Locale& operator=(const Locale& other); - - /** - * Checks if two locale keys are the same. - * - * @param other The locale key object to be compared with this. - * @return True if the two locale keys are the same, false otherwise. - * @stable ICU 2.0 - */ - UBool operator==(const Locale& other) const; - - /** - * Checks if two locale keys are not the same. - * - * @param other The locale key object to be compared with this. - * @return True if the two locale keys are not the same, false - * otherwise. - * @stable ICU 2.0 - */ - UBool operator!=(const Locale& other) const; - - /** - * Clone this object. - * Clones can be used concurrently in multiple threads. - * If an error occurs, then NULL is returned. - * The caller must delete the clone. - * - * @return a clone of this object - * - * @see getDynamicClassID - * @stable ICU 2.8 - */ - Locale *clone() const; - -#ifndef U_HIDE_SYSTEM_API - /** - * Common methods of getting the current default Locale. Used for the - * presentation: menus, dialogs, etc. Generally set once when your applet or - * application is initialized, then never reset. (If you do reset the - * default locale, you probably want to reload your GUI, so that the change - * is reflected in your interface.) - * - * More advanced programs will allow users to use different locales for - * different fields, e.g. in a spreadsheet. - * - * Note that the initial setting will match the host system. - * @return a reference to the Locale object for the default locale ID - * @system - * @stable ICU 2.0 - */ - static const Locale& U_EXPORT2 getDefault(void); - - /** - * Sets the default. Normally set once at the beginning of a process, - * then never reset. - * setDefault() only changes ICU's default locale ID, not - * the default locale ID of the runtime environment. - * - * @param newLocale Locale to set to. If NULL, set to the value obtained - * from the runtime environement. - * @param success The error code. - * @system - * @stable ICU 2.0 - */ - static void U_EXPORT2 setDefault(const Locale& newLocale, - UErrorCode& success); -#endif /* U_HIDE_SYSTEM_API */ - - /** - * Creates a locale which has had minimal canonicalization - * as per uloc_getName(). - * @param name The name to create from. If name is null, - * the default Locale is used. - * @return new locale object - * @stable ICU 2.0 - * @see uloc_getName - */ - static Locale U_EXPORT2 createFromName(const char *name); - - /** - * Creates a locale from the given string after canonicalizing - * the string by calling uloc_canonicalize(). - * @param name the locale ID to create from. Must not be NULL. - * @return a new locale object corresponding to the given name - * @stable ICU 3.0 - * @see uloc_canonicalize - */ - static Locale U_EXPORT2 createCanonical(const char* name); - - /** - * Returns the locale's ISO-639 language code. - * @return An alias to the code - * @stable ICU 2.0 - */ - inline const char * getLanguage( ) const; - - /** - * Returns the locale's ISO-15924 abbreviation script code. - * @return An alias to the code - * @see uscript_getShortName - * @see uscript_getCode - * @stable ICU 2.8 - */ - inline const char * getScript( ) const; - - /** - * Returns the locale's ISO-3166 country code. - * @return An alias to the code - * @stable ICU 2.0 - */ - inline const char * getCountry( ) const; - - /** - * Returns the locale's variant code. - * @return An alias to the code - * @stable ICU 2.0 - */ - inline const char * getVariant( ) const; - - /** - * Returns the programmatic name of the entire locale, with the language, - * country and variant separated by underbars. If a field is missing, up - * to two leading underbars will occur. Example: "en", "de_DE", "en_US_WIN", - * "de__POSIX", "fr__MAC", "__MAC", "_MT", "_FR_EURO" - * @return A pointer to "name". - * @stable ICU 2.0 - */ - inline const char * getName() const; - - /** - * Returns the programmatic name of the entire locale as getName() would return, - * but without keywords. - * @return A pointer to "name". - * @see getName - * @stable ICU 2.8 - */ - const char * getBaseName() const; - - - /** - * Gets the list of keywords for the specified locale. - * - * @param status the status code - * @return pointer to StringEnumeration class, or NULL if there are no keywords. - * Client must dispose of it by calling delete. - * @stable ICU 2.8 - */ - StringEnumeration * createKeywords(UErrorCode &status) const; - - /** - * Gets the value for a keyword. - * - * @param keywordName name of the keyword for which we want the value. Case insensitive. - * @param buffer The buffer to receive the keyword value. - * @param bufferCapacity The capacity of receiving buffer - * @param status Returns any error information while performing this operation. - * @return the length of the keyword value - * - * @stable ICU 2.8 - */ - int32_t getKeywordValue(const char* keywordName, char *buffer, int32_t bufferCapacity, UErrorCode &status) const; - - /** - * Sets or removes the value for a keyword. - * - * For removing all keywords, use getBaseName(), - * and construct a new Locale if it differs from getName(). - * - * @param keywordName name of the keyword to be set. Case insensitive. - * @param keywordValue value of the keyword to be set. If 0-length or - * NULL, will result in the keyword being removed. No error is given if - * that keyword does not exist. - * @param status Returns any error information while performing this operation. - * - * @stable ICU 49 - */ - void setKeywordValue(const char* keywordName, const char* keywordValue, UErrorCode &status); - - /** - * returns the locale's three-letter language code, as specified - * in ISO draft standard ISO-639-2. - * @return An alias to the code, or an empty string - * @stable ICU 2.0 - */ - const char * getISO3Language() const; - - /** - * Fills in "name" with the locale's three-letter ISO-3166 country code. - * @return An alias to the code, or an empty string - * @stable ICU 2.0 - */ - const char * getISO3Country() const; - - /** - * Returns the Windows LCID value corresponding to this locale. - * This value is stored in the resource data for the locale as a one-to-four-digit - * hexadecimal number. If the resource is missing, in the wrong format, or - * there is no Windows LCID value that corresponds to this locale, returns 0. - * @stable ICU 2.0 - */ - uint32_t getLCID(void) const; - - /** - * Returns whether this locale's script is written right-to-left. - * If there is no script subtag, then the likely script is used, see uloc_addLikelySubtags(). - * If no likely script is known, then FALSE is returned. - * - * A script is right-to-left according to the CLDR script metadata - * which corresponds to whether the script's letters have Bidi_Class=R or AL. - * - * Returns TRUE for "ar" and "en-Hebr", FALSE for "zh" and "fa-Cyrl". - * - * @return TRUE if the locale's script is written right-to-left - * @stable ICU 54 - */ - UBool isRightToLeft() const; - - /** - * Fills in "dispLang" with the name of this locale's language in a format suitable for - * user display in the default locale. For example, if the locale's language code is - * "fr" and the default locale's language code is "en", this function would set - * dispLang to "French". - * @param dispLang Receives the language's display name. - * @return A reference to "dispLang". - * @stable ICU 2.0 - */ - UnicodeString& getDisplayLanguage(UnicodeString& dispLang) const; - - /** - * Fills in "dispLang" with the name of this locale's language in a format suitable for - * user display in the locale specified by "displayLocale". For example, if the locale's - * language code is "en" and displayLocale's language code is "fr", this function would set - * dispLang to "Anglais". - * @param displayLocale Specifies the locale to be used to display the name. In other words, - * if the locale's language code is "en", passing Locale::getFrench() for - * displayLocale would result in "Anglais", while passing Locale::getGerman() - * for displayLocale would result in "Englisch". - * @param dispLang Receives the language's display name. - * @return A reference to "dispLang". - * @stable ICU 2.0 - */ - UnicodeString& getDisplayLanguage( const Locale& displayLocale, - UnicodeString& dispLang) const; - - /** - * Fills in "dispScript" with the name of this locale's script in a format suitable - * for user display in the default locale. For example, if the locale's script code - * is "LATN" and the default locale's language code is "en", this function would set - * dispScript to "Latin". - * @param dispScript Receives the scripts's display name. - * @return A reference to "dispScript". - * @stable ICU 2.8 - */ - UnicodeString& getDisplayScript( UnicodeString& dispScript) const; - - /** - * Fills in "dispScript" with the name of this locale's country in a format suitable - * for user display in the locale specified by "displayLocale". For example, if the locale's - * script code is "LATN" and displayLocale's language code is "en", this function would set - * dispScript to "Latin". - * @param displayLocale Specifies the locale to be used to display the name. In other - * words, if the locale's script code is "LATN", passing - * Locale::getFrench() for displayLocale would result in "", while - * passing Locale::getGerman() for displayLocale would result in - * "". - * @param dispScript Receives the scripts's display name. - * @return A reference to "dispScript". - * @stable ICU 2.8 - */ - UnicodeString& getDisplayScript( const Locale& displayLocale, - UnicodeString& dispScript) const; - - /** - * Fills in "dispCountry" with the name of this locale's country in a format suitable - * for user display in the default locale. For example, if the locale's country code - * is "FR" and the default locale's language code is "en", this function would set - * dispCountry to "France". - * @param dispCountry Receives the country's display name. - * @return A reference to "dispCountry". - * @stable ICU 2.0 - */ - UnicodeString& getDisplayCountry( UnicodeString& dispCountry) const; - - /** - * Fills in "dispCountry" with the name of this locale's country in a format suitable - * for user display in the locale specified by "displayLocale". For example, if the locale's - * country code is "US" and displayLocale's language code is "fr", this function would set - * dispCountry to "États-Unis". - * @param displayLocale Specifies the locale to be used to display the name. In other - * words, if the locale's country code is "US", passing - * Locale::getFrench() for displayLocale would result in "États-Unis", while - * passing Locale::getGerman() for displayLocale would result in - * "Vereinigte Staaten". - * @param dispCountry Receives the country's display name. - * @return A reference to "dispCountry". - * @stable ICU 2.0 - */ - UnicodeString& getDisplayCountry( const Locale& displayLocale, - UnicodeString& dispCountry) const; - - /** - * Fills in "dispVar" with the name of this locale's variant code in a format suitable - * for user display in the default locale. - * @param dispVar Receives the variant's name. - * @return A reference to "dispVar". - * @stable ICU 2.0 - */ - UnicodeString& getDisplayVariant( UnicodeString& dispVar) const; - - /** - * Fills in "dispVar" with the name of this locale's variant code in a format - * suitable for user display in the locale specified by "displayLocale". - * @param displayLocale Specifies the locale to be used to display the name. - * @param dispVar Receives the variant's display name. - * @return A reference to "dispVar". - * @stable ICU 2.0 - */ - UnicodeString& getDisplayVariant( const Locale& displayLocale, - UnicodeString& dispVar) const; - - /** - * Fills in "name" with the name of this locale in a format suitable for user display - * in the default locale. This function uses getDisplayLanguage(), getDisplayCountry(), - * and getDisplayVariant() to do its work, and outputs the display name in the format - * "language (country[,variant])". For example, if the default locale is en_US, then - * fr_FR's display name would be "French (France)", and es_MX_Traditional's display name - * would be "Spanish (Mexico,Traditional)". - * @param name Receives the locale's display name. - * @return A reference to "name". - * @stable ICU 2.0 - */ - UnicodeString& getDisplayName( UnicodeString& name) const; - - /** - * Fills in "name" with the name of this locale in a format suitable for user display - * in the locale specfied by "displayLocale". This function uses getDisplayLanguage(), - * getDisplayCountry(), and getDisplayVariant() to do its work, and outputs the display - * name in the format "language (country[,variant])". For example, if displayLocale is - * fr_FR, then en_US's display name would be "Anglais (États-Unis)", and no_NO_NY's - * display name would be "norvégien (Norvège,NY)". - * @param displayLocale Specifies the locale to be used to display the name. - * @param name Receives the locale's display name. - * @return A reference to "name". - * @stable ICU 2.0 - */ - UnicodeString& getDisplayName( const Locale& displayLocale, - UnicodeString& name) const; - - /** - * Generates a hash code for the locale. - * @stable ICU 2.0 - */ - int32_t hashCode(void) const; - - /** - * Sets the locale to bogus - * A bogus locale represents a non-existing locale associated - * with services that can be instantiated from non-locale data - * in addition to locale (for example, collation can be - * instantiated from a locale and from a rule set). - * @stable ICU 2.1 - */ - void setToBogus(); - - /** - * Gets the bogus state. Locale object can be bogus if it doesn't exist - * @return FALSE if it is a real locale, TRUE if it is a bogus locale - * @stable ICU 2.1 - */ - UBool isBogus(void) const; - - /** - * Returns a list of all installed locales. - * @param count Receives the number of locales in the list. - * @return A pointer to an array of Locale objects. This array is the list - * of all locales with installed resource files. The called does NOT - * get ownership of this list, and must NOT delete it. - * @stable ICU 2.0 - */ - static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); - - /** - * Gets a list of all available 2-letter country codes defined in ISO 3166. This is a - * pointer to an array of pointers to arrays of char. All of these pointers are - * owned by ICU-- do not delete them, and do not write through them. The array is - * terminated with a null pointer. - * @return a list of all available country codes - * @stable ICU 2.0 - */ - static const char* const* U_EXPORT2 getISOCountries(); - - /** - * Gets a list of all available language codes defined in ISO 639. This is a pointer - * to an array of pointers to arrays of char. All of these pointers are owned - * by ICU-- do not delete them, and do not write through them. The array is - * terminated with a null pointer. - * @return a list of all available language codes - * @stable ICU 2.0 - */ - static const char* const* U_EXPORT2 getISOLanguages(); - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - -protected: /* only protected for testing purposes. DO NOT USE. */ -#ifndef U_HIDE_INTERNAL_API - /** - * Set this from a single POSIX style locale string. - * @internal - */ - void setFromPOSIXID(const char *posixID); -#endif /* U_HIDE_INTERNAL_API */ - -private: - /** - * Initialize the locale object with a new name. - * Was deprecated - used in implementation - moved internal - * - * @param cLocaleID The new locale name. - * @param canonicalize whether to call uloc_canonicalize on cLocaleID - */ - Locale& init(const char* cLocaleID, UBool canonicalize); - - /* - * Internal constructor to allow construction of a locale object with - * NO side effects. (Default constructor tries to get - * the default locale.) - */ - enum ELocaleType { - eBOGUS - }; - Locale(ELocaleType); - - /** - * Initialize the locale cache for commonly used locales - */ - static Locale *getLocaleCache(void); - - char language[ULOC_LANG_CAPACITY]; - char script[ULOC_SCRIPT_CAPACITY]; - char country[ULOC_COUNTRY_CAPACITY]; - int32_t variantBegin; - char* fullName; - char fullNameBuffer[ULOC_FULLNAME_CAPACITY]; - // name without keywords - char* baseName; - void initBaseName(UErrorCode& status); - - UBool fIsBogus; - - static const Locale &getLocale(int locid); - - /** - * A friend to allow the default locale to be set by either the C or C++ API. - * @internal - */ - friend Locale *locale_set_default_internal(const char *, UErrorCode& status); - - /** - * @internal - */ - friend void U_CALLCONV locale_available_init(); -}; - -inline UBool -Locale::operator!=(const Locale& other) const -{ - return !operator==(other); -} - -inline const char * -Locale::getCountry() const -{ - return country; -} - -inline const char * -Locale::getLanguage() const -{ - return language; -} - -inline const char * -Locale::getScript() const -{ - return script; -} - -inline const char * -Locale::getVariant() const -{ - return &baseName[variantBegin]; -} - -inline const char * -Locale::getName() const -{ - return fullName; -} - -inline UBool -Locale::isBogus(void) const { - return fIsBogus; -} - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/measfmt.h b/win32/include/spidermonkey/unicode/measfmt.h deleted file mode 100755 index 37b33149..00000000 --- a/win32/include/spidermonkey/unicode/measfmt.h +++ /dev/null @@ -1,401 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2004-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* Author: Alan Liu -* Created: April 20, 2004 -* Since: ICU 3.0 -********************************************************************** -*/ -#ifndef MEASUREFORMAT_H -#define MEASUREFORMAT_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/format.h" -#include "unicode/udat.h" - -/** - * \file - * \brief C++ API: Formatter for measure objects. - */ - -/** - * Constants for various widths. - * There are 4 widths: Wide, Short, Narrow, Numeric. - * For example, for English, when formatting "3 hours" - * Wide is "3 hours"; short is "3 hrs"; narrow is "3h"; - * formatting "3 hours 17 minutes" as numeric give "3:17" - * @stable ICU 53 - */ -enum UMeasureFormatWidth { - - // Wide, short, and narrow must be first and in this order. - /** - * Spell out measure units. - * @stable ICU 53 - */ - UMEASFMT_WIDTH_WIDE, - - /** - * Abbreviate measure units. - * @stable ICU 53 - */ - UMEASFMT_WIDTH_SHORT, - - /** - * Use symbols for measure units when possible. - * @stable ICU 53 - */ - UMEASFMT_WIDTH_NARROW, - - /** - * Completely omit measure units when possible. For example, format - * '5 hours, 37 minutes' as '5:37' - * @stable ICU 53 - */ - UMEASFMT_WIDTH_NUMERIC, - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UMeasureFormatWidth value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UMEASFMT_WIDTH_COUNT = 4 -#endif // U_HIDE_DEPRECATED_API -}; -/** @stable ICU 53 */ -typedef enum UMeasureFormatWidth UMeasureFormatWidth; - -U_NAMESPACE_BEGIN - -class Measure; -class MeasureUnit; -class NumberFormat; -class PluralRules; -class MeasureFormatCacheData; -class SharedNumberFormat; -class SharedPluralRules; -class QuantityFormatter; -class SimpleFormatter; -class ListFormatter; -class DateFormat; - -/** - * - * A formatter for measure objects. - * - * @see Format - * @author Alan Liu - * @stable ICU 3.0 - */ -class U_I18N_API MeasureFormat : public Format { - public: - using Format::parseObject; - using Format::format; - - /** - * Constructor. - * @stable ICU 53 - */ - MeasureFormat( - const Locale &locale, UMeasureFormatWidth width, UErrorCode &status); - - /** - * Constructor. - * @stable ICU 53 - */ - MeasureFormat( - const Locale &locale, - UMeasureFormatWidth width, - NumberFormat *nfToAdopt, - UErrorCode &status); - - /** - * Copy constructor. - * @stable ICU 3.0 - */ - MeasureFormat(const MeasureFormat &other); - - /** - * Assignment operator. - * @stable ICU 3.0 - */ - MeasureFormat &operator=(const MeasureFormat &rhs); - - /** - * Destructor. - * @stable ICU 3.0 - */ - virtual ~MeasureFormat(); - - /** - * Return true if given Format objects are semantically equal. - * @stable ICU 53 - */ - virtual UBool operator==(const Format &other) const; - - /** - * Clones this object polymorphically. - * @stable ICU 53 - */ - virtual Format *clone() const; - - /** - * Formats object to produce a string. - * @stable ICU 53 - */ - virtual UnicodeString &format( - const Formattable &obj, - UnicodeString &appendTo, - FieldPosition &pos, - UErrorCode &status) const; - - /** - * Parse a string to produce an object. This implementation sets - * status to U_UNSUPPORTED_ERROR. - * - * @draft ICU 53 - */ - virtual void parseObject( - const UnicodeString &source, - Formattable &reslt, - ParsePosition &pos) const; - - /** - * Formats measure objects to produce a string. An example of such a - * formatted string is 3 meters, 3.5 centimeters. Measure objects appear - * in the formatted string in the same order they appear in the "measures" - * array. The NumberFormat of this object is used only to format the amount - * of the very last measure. The other amounts are formatted with zero - * decimal places while rounding toward zero. - * @param measures array of measure objects. - * @param measureCount the number of measure objects. - * @param appendTo formatted string appended here. - * @param pos the field position. - * @param status the error. - * @return appendTo reference - * - * @stable ICU 53 - */ - UnicodeString &formatMeasures( - const Measure *measures, - int32_t measureCount, - UnicodeString &appendTo, - FieldPosition &pos, - UErrorCode &status) const; - - /** - * Formats a single measure per unit. An example of such a - * formatted string is 3.5 meters per second. - * @param measure The measure object. In above example, 3.5 meters. - * @param perUnit The per unit. In above example, it is - * *MeasureUnit::createSecond(status). - * @param appendTo formatted string appended here. - * @param pos the field position. - * @param status the error. - * @return appendTo reference - * - * @stable ICU 55 - */ - UnicodeString &formatMeasurePerUnit( - const Measure &measure, - const MeasureUnit &perUnit, - UnicodeString &appendTo, - FieldPosition &pos, - UErrorCode &status) const; - -#ifndef U_HIDE_DRAFT_API - /** - * Gets the display name of the specified {@link MeasureUnit} corresponding to the current - * locale and format width. - * @param unit The unit for which to get a display name. - * @param status the error. - * @return The display name in the locale and width specified in - * {@link MeasureFormat#getInstance}, or null if there is no display name available - * for the specified unit. - * - * @draft ICU 58 - */ - UnicodeString getUnitDisplayName(const MeasureUnit& unit, UErrorCode &status) const; -#endif /* U_HIDE_DRAFT_API */ - - - /** - * Return a formatter for CurrencyAmount objects in the given - * locale. - * @param locale desired locale - * @param ec input-output error code - * @return a formatter object, or NULL upon error - * @stable ICU 3.0 - */ - static MeasureFormat* U_EXPORT2 createCurrencyFormat(const Locale& locale, - UErrorCode& ec); - - /** - * Return a formatter for CurrencyAmount objects in the default - * locale. - * @param ec input-output error code - * @return a formatter object, or NULL upon error - * @stable ICU 3.0 - */ - static MeasureFormat* U_EXPORT2 createCurrencyFormat(UErrorCode& ec); - - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *
-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 53 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 53 - */ - virtual UClassID getDynamicClassID(void) const; - - protected: - /** - * Default constructor. - * @stable ICU 3.0 - */ - MeasureFormat(); - -#ifndef U_HIDE_INTERNAL_API - - /** - * ICU use only. - * Initialize or change MeasureFormat class from subclass. - * @internal. - */ - void initMeasureFormat( - const Locale &locale, - UMeasureFormatWidth width, - NumberFormat *nfToAdopt, - UErrorCode &status); - /** - * ICU use only. - * Allows subclass to change locale. Note that this method also changes - * the NumberFormat object. Returns TRUE if locale changed; FALSE if no - * change was made. - * @internal. - */ - UBool setMeasureFormatLocale(const Locale &locale, UErrorCode &status); - - /** - * ICU use only. - * Let subclass change NumberFormat. - * @internal. - */ - void adoptNumberFormat(NumberFormat *nfToAdopt, UErrorCode &status); - - /** - * ICU use only. - * @internal. - */ - const NumberFormat &getNumberFormat() const; - - /** - * ICU use only. - * @internal. - */ - const PluralRules &getPluralRules() const; - - /** - * ICU use only. - * @internal. - */ - Locale getLocale(UErrorCode &status) const; - - /** - * ICU use only. - * @internal. - */ - const char *getLocaleID(UErrorCode &status) const; - -#endif /* U_HIDE_INTERNAL_API */ - - private: - const MeasureFormatCacheData *cache; - const SharedNumberFormat *numberFormat; - const SharedPluralRules *pluralRules; - UMeasureFormatWidth width; - - // Declared outside of MeasureFormatSharedData because ListFormatter - // objects are relatively cheap to copy; therefore, they don't need to be - // shared across instances. - ListFormatter *listFormatter; - - const SimpleFormatter *getFormatterOrNull( - const MeasureUnit &unit, UMeasureFormatWidth width, int32_t index) const; - - const SimpleFormatter *getFormatter( - const MeasureUnit &unit, UMeasureFormatWidth width, int32_t index, - UErrorCode &errorCode) const; - - const SimpleFormatter *getPluralFormatter( - const MeasureUnit &unit, UMeasureFormatWidth width, int32_t index, - UErrorCode &errorCode) const; - - const SimpleFormatter *getPerFormatter( - UMeasureFormatWidth width, - UErrorCode &status) const; - - int32_t withPerUnitAndAppend( - const UnicodeString &formatted, - const MeasureUnit &perUnit, - UnicodeString &appendTo, - UErrorCode &status) const; - - UnicodeString &formatMeasure( - const Measure &measure, - const NumberFormat &nf, - UnicodeString &appendTo, - FieldPosition &pos, - UErrorCode &status) const; - - UnicodeString &formatMeasuresSlowTrack( - const Measure *measures, - int32_t measureCount, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - UnicodeString &formatNumeric( - const Formattable *hms, // always length 3: [0] is hour; [1] is - // minute; [2] is second. - int32_t bitMap, // 1=hour set, 2=minute set, 4=second set - UnicodeString &appendTo, - UErrorCode &status) const; - - UnicodeString &formatNumeric( - UDate date, - const DateFormat &dateFmt, - UDateFormatField smallestField, - const Formattable &smallestAmount, - UnicodeString &appendTo, - UErrorCode &status) const; -}; - -U_NAMESPACE_END - -#endif // #if !UCONFIG_NO_FORMATTING -#endif // #ifndef MEASUREFORMAT_H diff --git a/win32/include/spidermonkey/unicode/measunit.h b/win32/include/spidermonkey/unicode/measunit.h deleted file mode 100755 index afef83ed..00000000 --- a/win32/include/spidermonkey/unicode/measunit.h +++ /dev/null @@ -1,1370 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2004-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* Author: Alan Liu -* Created: April 26, 2004 -* Since: ICU 3.0 -********************************************************************** -*/ -#ifndef __MEASUREUNIT_H__ -#define __MEASUREUNIT_H__ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/unistr.h" - -/** - * \file - * \brief C++ API: A unit for measuring a quantity. - */ - -U_NAMESPACE_BEGIN - -class StringEnumeration; - -/** - * A unit such as length, mass, volume, currency, etc. A unit is - * coupled with a numeric amount to produce a Measure. - * - * @author Alan Liu - * @stable ICU 3.0 - */ -class U_I18N_API MeasureUnit: public UObject { - public: - - /** - * Default constructor. - * @stable ICU 3.0 - */ - MeasureUnit() : fTypeId(0), fSubTypeId(0) { - fCurrency[0] = 0; - } - - /** - * Copy constructor. - * @stable ICU 3.0 - */ - MeasureUnit(const MeasureUnit &other); - - /** - * Assignment operator. - * @stable ICU 3.0 - */ - MeasureUnit &operator=(const MeasureUnit &other); - - /** - * Returns a polymorphic clone of this object. The result will - * have the same class as returned by getDynamicClassID(). - * @stable ICU 3.0 - */ - virtual UObject* clone() const; - - /** - * Destructor - * @stable ICU 3.0 - */ - virtual ~MeasureUnit(); - - /** - * Equality operator. Return true if this object is equal - * to the given object. - * @stable ICU 3.0 - */ - virtual UBool operator==(const UObject& other) const; - - /** - * Inequality operator. Return true if this object is not equal - * to the given object. - * @stable ICU 53 - */ - UBool operator!=(const UObject& other) const { - return !(*this == other); - } - - /** - * Get the type. - * @stable ICU 53 - */ - const char *getType() const; - - /** - * Get the sub type. - * @stable ICU 53 - */ - const char *getSubtype() const; - - /** - * getAvailable gets all of the available units. - * If there are too many units to fit into destCapacity then the - * error code is set to U_BUFFER_OVERFLOW_ERROR. - * - * @param destArray destination buffer. - * @param destCapacity number of MeasureUnit instances available at dest. - * @param errorCode ICU error code. - * @return number of available units. - * @stable ICU 53 - */ - static int32_t getAvailable( - MeasureUnit *destArray, - int32_t destCapacity, - UErrorCode &errorCode); - - /** - * getAvailable gets all of the available units for a specific type. - * If there are too many units to fit into destCapacity then the - * error code is set to U_BUFFER_OVERFLOW_ERROR. - * - * @param type the type - * @param destArray destination buffer. - * @param destCapacity number of MeasureUnit instances available at dest. - * @param errorCode ICU error code. - * @return number of available units for type. - * @stable ICU 53 - */ - static int32_t getAvailable( - const char *type, - MeasureUnit *destArray, - int32_t destCapacity, - UErrorCode &errorCode); - - /** - * getAvailableTypes gets all of the available types. Caller owns the - * returned StringEnumeration and must delete it when finished using it. - * - * @param errorCode ICU error code. - * @return the types. - * @stable ICU 53 - */ - static StringEnumeration* getAvailableTypes(UErrorCode &errorCode); - - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *
-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 53 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 53 - */ - virtual UClassID getDynamicClassID(void) const; - -#ifndef U_HIDE_INTERNAL_API - /** - * ICU use only. - * Returns associated array index for this measure unit. Only valid for - * non-currency measure units. - * @internal - */ - int32_t getIndex() const; - - /** - * ICU use only. - * Returns maximum value from getIndex plus 1. - * @internal - */ - static int32_t getIndexCount(); - - /** - * ICU use only. - * @return the unit.getIndex() of the unit which has this unit.getType() and unit.getSubtype(), - * or a negative value if there is no such unit - * @internal - */ - static int32_t internalGetIndexForTypeAndSubtype(const char *type, const char *subtype); - - /** - * ICU use only. - * @internal - */ - static MeasureUnit *resolveUnitPerUnit( - const MeasureUnit &unit, const MeasureUnit &perUnit); -#endif /* U_HIDE_INTERNAL_API */ - -// All code between the "Start generated createXXX methods" comment and -// the "End generated createXXX methods" comment is auto generated code -// and must not be edited manually. For instructions on how to correctly -// update this code, refer to: -// http://site.icu-project.org/design/formatting/measureformat/updating-measure-unit -// -// Start generated createXXX methods - - /** - * Returns unit of acceleration: g-force. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createGForce(UErrorCode &status); - - /** - * Returns unit of acceleration: meter-per-second-squared. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMeterPerSecondSquared(UErrorCode &status); - - /** - * Returns unit of angle: arc-minute. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createArcMinute(UErrorCode &status); - - /** - * Returns unit of angle: arc-second. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createArcSecond(UErrorCode &status); - - /** - * Returns unit of angle: degree. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createDegree(UErrorCode &status); - - /** - * Returns unit of angle: radian. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createRadian(UErrorCode &status); - - /** - * Returns unit of angle: revolution. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 56 - */ - static MeasureUnit *createRevolutionAngle(UErrorCode &status); - - /** - * Returns unit of area: acre. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createAcre(UErrorCode &status); - - /** - * Returns unit of area: hectare. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createHectare(UErrorCode &status); - - /** - * Returns unit of area: square-centimeter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createSquareCentimeter(UErrorCode &status); - - /** - * Returns unit of area: square-foot. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createSquareFoot(UErrorCode &status); - - /** - * Returns unit of area: square-inch. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createSquareInch(UErrorCode &status); - - /** - * Returns unit of area: square-kilometer. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createSquareKilometer(UErrorCode &status); - - /** - * Returns unit of area: square-meter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createSquareMeter(UErrorCode &status); - - /** - * Returns unit of area: square-mile. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createSquareMile(UErrorCode &status); - - /** - * Returns unit of area: square-yard. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createSquareYard(UErrorCode &status); - - /** - * Returns unit of concentr: karat. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createKarat(UErrorCode &status); - -#ifndef U_HIDE_DRAFT_API - /** - * Returns unit of concentr: milligram-per-deciliter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @draft ICU 57 - */ - static MeasureUnit *createMilligramPerDeciliter(UErrorCode &status); -#endif /* U_HIDE_DRAFT_API */ - -#ifndef U_HIDE_DRAFT_API - /** - * Returns unit of concentr: millimole-per-liter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @draft ICU 57 - */ - static MeasureUnit *createMillimolePerLiter(UErrorCode &status); -#endif /* U_HIDE_DRAFT_API */ - -#ifndef U_HIDE_DRAFT_API - /** - * Returns unit of concentr: part-per-million. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @draft ICU 57 - */ - static MeasureUnit *createPartPerMillion(UErrorCode &status); -#endif /* U_HIDE_DRAFT_API */ - - /** - * Returns unit of consumption: liter-per-100kilometers. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 56 - */ - static MeasureUnit *createLiterPer100Kilometers(UErrorCode &status); - - /** - * Returns unit of consumption: liter-per-kilometer. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createLiterPerKilometer(UErrorCode &status); - - /** - * Returns unit of consumption: mile-per-gallon. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMilePerGallon(UErrorCode &status); - -#ifndef U_HIDE_DRAFT_API - /** - * Returns unit of consumption: mile-per-gallon-imperial. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @draft ICU 57 - */ - static MeasureUnit *createMilePerGallonImperial(UErrorCode &status); -#endif /* U_HIDE_DRAFT_API */ - -#ifndef U_HIDE_DRAFT_API - /** - * Returns unit of coordinate: east. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @draft ICU 58 - */ - static MeasureUnit *createEast(UErrorCode &status); -#endif /* U_HIDE_DRAFT_API */ - -#ifndef U_HIDE_DRAFT_API - /** - * Returns unit of coordinate: north. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @draft ICU 58 - */ - static MeasureUnit *createNorth(UErrorCode &status); -#endif /* U_HIDE_DRAFT_API */ - -#ifndef U_HIDE_DRAFT_API - /** - * Returns unit of coordinate: south. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @draft ICU 58 - */ - static MeasureUnit *createSouth(UErrorCode &status); -#endif /* U_HIDE_DRAFT_API */ - -#ifndef U_HIDE_DRAFT_API - /** - * Returns unit of coordinate: west. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @draft ICU 58 - */ - static MeasureUnit *createWest(UErrorCode &status); -#endif /* U_HIDE_DRAFT_API */ - - /** - * Returns unit of digital: bit. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createBit(UErrorCode &status); - - /** - * Returns unit of digital: byte. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createByte(UErrorCode &status); - - /** - * Returns unit of digital: gigabit. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createGigabit(UErrorCode &status); - - /** - * Returns unit of digital: gigabyte. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createGigabyte(UErrorCode &status); - - /** - * Returns unit of digital: kilobit. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createKilobit(UErrorCode &status); - - /** - * Returns unit of digital: kilobyte. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createKilobyte(UErrorCode &status); - - /** - * Returns unit of digital: megabit. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMegabit(UErrorCode &status); - - /** - * Returns unit of digital: megabyte. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMegabyte(UErrorCode &status); - - /** - * Returns unit of digital: terabit. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createTerabit(UErrorCode &status); - - /** - * Returns unit of digital: terabyte. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createTerabyte(UErrorCode &status); - - /** - * Returns unit of duration: century. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 56 - */ - static MeasureUnit *createCentury(UErrorCode &status); - - /** - * Returns unit of duration: day. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createDay(UErrorCode &status); - - /** - * Returns unit of duration: hour. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createHour(UErrorCode &status); - - /** - * Returns unit of duration: microsecond. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMicrosecond(UErrorCode &status); - - /** - * Returns unit of duration: millisecond. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createMillisecond(UErrorCode &status); - - /** - * Returns unit of duration: minute. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createMinute(UErrorCode &status); - - /** - * Returns unit of duration: month. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createMonth(UErrorCode &status); - - /** - * Returns unit of duration: nanosecond. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createNanosecond(UErrorCode &status); - - /** - * Returns unit of duration: second. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createSecond(UErrorCode &status); - - /** - * Returns unit of duration: week. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createWeek(UErrorCode &status); - - /** - * Returns unit of duration: year. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createYear(UErrorCode &status); - - /** - * Returns unit of electric: ampere. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createAmpere(UErrorCode &status); - - /** - * Returns unit of electric: milliampere. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMilliampere(UErrorCode &status); - - /** - * Returns unit of electric: ohm. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createOhm(UErrorCode &status); - - /** - * Returns unit of electric: volt. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createVolt(UErrorCode &status); - - /** - * Returns unit of energy: calorie. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createCalorie(UErrorCode &status); - - /** - * Returns unit of energy: foodcalorie. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createFoodcalorie(UErrorCode &status); - - /** - * Returns unit of energy: joule. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createJoule(UErrorCode &status); - - /** - * Returns unit of energy: kilocalorie. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createKilocalorie(UErrorCode &status); - - /** - * Returns unit of energy: kilojoule. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createKilojoule(UErrorCode &status); - - /** - * Returns unit of energy: kilowatt-hour. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createKilowattHour(UErrorCode &status); - - /** - * Returns unit of frequency: gigahertz. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createGigahertz(UErrorCode &status); - - /** - * Returns unit of frequency: hertz. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createHertz(UErrorCode &status); - - /** - * Returns unit of frequency: kilohertz. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createKilohertz(UErrorCode &status); - - /** - * Returns unit of frequency: megahertz. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMegahertz(UErrorCode &status); - - /** - * Returns unit of length: astronomical-unit. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createAstronomicalUnit(UErrorCode &status); - - /** - * Returns unit of length: centimeter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createCentimeter(UErrorCode &status); - - /** - * Returns unit of length: decimeter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createDecimeter(UErrorCode &status); - - /** - * Returns unit of length: fathom. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createFathom(UErrorCode &status); - - /** - * Returns unit of length: foot. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createFoot(UErrorCode &status); - - /** - * Returns unit of length: furlong. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createFurlong(UErrorCode &status); - - /** - * Returns unit of length: inch. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createInch(UErrorCode &status); - - /** - * Returns unit of length: kilometer. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createKilometer(UErrorCode &status); - - /** - * Returns unit of length: light-year. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createLightYear(UErrorCode &status); - - /** - * Returns unit of length: meter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createMeter(UErrorCode &status); - - /** - * Returns unit of length: micrometer. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMicrometer(UErrorCode &status); - - /** - * Returns unit of length: mile. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createMile(UErrorCode &status); - - /** - * Returns unit of length: mile-scandinavian. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 56 - */ - static MeasureUnit *createMileScandinavian(UErrorCode &status); - - /** - * Returns unit of length: millimeter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createMillimeter(UErrorCode &status); - - /** - * Returns unit of length: nanometer. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createNanometer(UErrorCode &status); - - /** - * Returns unit of length: nautical-mile. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createNauticalMile(UErrorCode &status); - - /** - * Returns unit of length: parsec. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createParsec(UErrorCode &status); - - /** - * Returns unit of length: picometer. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createPicometer(UErrorCode &status); - - /** - * Returns unit of length: yard. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createYard(UErrorCode &status); - - /** - * Returns unit of light: lux. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createLux(UErrorCode &status); - - /** - * Returns unit of mass: carat. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createCarat(UErrorCode &status); - - /** - * Returns unit of mass: gram. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createGram(UErrorCode &status); - - /** - * Returns unit of mass: kilogram. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createKilogram(UErrorCode &status); - - /** - * Returns unit of mass: metric-ton. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMetricTon(UErrorCode &status); - - /** - * Returns unit of mass: microgram. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMicrogram(UErrorCode &status); - - /** - * Returns unit of mass: milligram. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMilligram(UErrorCode &status); - - /** - * Returns unit of mass: ounce. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createOunce(UErrorCode &status); - - /** - * Returns unit of mass: ounce-troy. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createOunceTroy(UErrorCode &status); - - /** - * Returns unit of mass: pound. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createPound(UErrorCode &status); - - /** - * Returns unit of mass: stone. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createStone(UErrorCode &status); - - /** - * Returns unit of mass: ton. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createTon(UErrorCode &status); - - /** - * Returns unit of power: gigawatt. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createGigawatt(UErrorCode &status); - - /** - * Returns unit of power: horsepower. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createHorsepower(UErrorCode &status); - - /** - * Returns unit of power: kilowatt. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createKilowatt(UErrorCode &status); - - /** - * Returns unit of power: megawatt. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMegawatt(UErrorCode &status); - - /** - * Returns unit of power: milliwatt. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMilliwatt(UErrorCode &status); - - /** - * Returns unit of power: watt. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createWatt(UErrorCode &status); - - /** - * Returns unit of pressure: hectopascal. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createHectopascal(UErrorCode &status); - - /** - * Returns unit of pressure: inch-hg. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createInchHg(UErrorCode &status); - - /** - * Returns unit of pressure: millibar. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createMillibar(UErrorCode &status); - - /** - * Returns unit of pressure: millimeter-of-mercury. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMillimeterOfMercury(UErrorCode &status); - - /** - * Returns unit of pressure: pound-per-square-inch. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createPoundPerSquareInch(UErrorCode &status); - - /** - * Returns unit of speed: kilometer-per-hour. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createKilometerPerHour(UErrorCode &status); - - /** - * Returns unit of speed: knot. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 56 - */ - static MeasureUnit *createKnot(UErrorCode &status); - - /** - * Returns unit of speed: meter-per-second. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createMeterPerSecond(UErrorCode &status); - - /** - * Returns unit of speed: mile-per-hour. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createMilePerHour(UErrorCode &status); - - /** - * Returns unit of temperature: celsius. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createCelsius(UErrorCode &status); - - /** - * Returns unit of temperature: fahrenheit. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createFahrenheit(UErrorCode &status); - - /** - * Returns unit of temperature: generic. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 56 - */ - static MeasureUnit *createGenericTemperature(UErrorCode &status); - - /** - * Returns unit of temperature: kelvin. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createKelvin(UErrorCode &status); - - /** - * Returns unit of volume: acre-foot. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createAcreFoot(UErrorCode &status); - - /** - * Returns unit of volume: bushel. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createBushel(UErrorCode &status); - - /** - * Returns unit of volume: centiliter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createCentiliter(UErrorCode &status); - - /** - * Returns unit of volume: cubic-centimeter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createCubicCentimeter(UErrorCode &status); - - /** - * Returns unit of volume: cubic-foot. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createCubicFoot(UErrorCode &status); - - /** - * Returns unit of volume: cubic-inch. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createCubicInch(UErrorCode &status); - - /** - * Returns unit of volume: cubic-kilometer. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createCubicKilometer(UErrorCode &status); - - /** - * Returns unit of volume: cubic-meter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createCubicMeter(UErrorCode &status); - - /** - * Returns unit of volume: cubic-mile. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createCubicMile(UErrorCode &status); - - /** - * Returns unit of volume: cubic-yard. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createCubicYard(UErrorCode &status); - - /** - * Returns unit of volume: cup. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createCup(UErrorCode &status); - - /** - * Returns unit of volume: cup-metric. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 56 - */ - static MeasureUnit *createCupMetric(UErrorCode &status); - - /** - * Returns unit of volume: deciliter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createDeciliter(UErrorCode &status); - - /** - * Returns unit of volume: fluid-ounce. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createFluidOunce(UErrorCode &status); - - /** - * Returns unit of volume: gallon. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createGallon(UErrorCode &status); - -#ifndef U_HIDE_DRAFT_API - /** - * Returns unit of volume: gallon-imperial. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @draft ICU 57 - */ - static MeasureUnit *createGallonImperial(UErrorCode &status); -#endif /* U_HIDE_DRAFT_API */ - - /** - * Returns unit of volume: hectoliter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createHectoliter(UErrorCode &status); - - /** - * Returns unit of volume: liter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 53 - */ - static MeasureUnit *createLiter(UErrorCode &status); - - /** - * Returns unit of volume: megaliter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMegaliter(UErrorCode &status); - - /** - * Returns unit of volume: milliliter. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createMilliliter(UErrorCode &status); - - /** - * Returns unit of volume: pint. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createPint(UErrorCode &status); - - /** - * Returns unit of volume: pint-metric. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 56 - */ - static MeasureUnit *createPintMetric(UErrorCode &status); - - /** - * Returns unit of volume: quart. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createQuart(UErrorCode &status); - - /** - * Returns unit of volume: tablespoon. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createTablespoon(UErrorCode &status); - - /** - * Returns unit of volume: teaspoon. - * Caller owns returned value and must free it. - * @param status ICU error code. - * @stable ICU 54 - */ - static MeasureUnit *createTeaspoon(UErrorCode &status); - - -// End generated createXXX methods - - protected: - -#ifndef U_HIDE_INTERNAL_API - /** - * For ICU use only. - * @internal - */ - void initTime(const char *timeId); - - /** - * For ICU use only. - * @internal - */ - void initCurrency(const char *isoCurrency); - -#endif /* U_HIDE_INTERNAL_API */ - -private: - int32_t fTypeId; - int32_t fSubTypeId; - char fCurrency[4]; - - MeasureUnit(int32_t typeId, int32_t subTypeId) : fTypeId(typeId), fSubTypeId(subTypeId) { - fCurrency[0] = 0; - } - void setTo(int32_t typeId, int32_t subTypeId); - int32_t getOffset() const; - static MeasureUnit *create(int typeId, int subTypeId, UErrorCode &status); -}; - -U_NAMESPACE_END - -#endif // !UNCONFIG_NO_FORMATTING -#endif // __MEASUREUNIT_H__ diff --git a/win32/include/spidermonkey/unicode/measure.h b/win32/include/spidermonkey/unicode/measure.h deleted file mode 100755 index 2bd78d29..00000000 --- a/win32/include/spidermonkey/unicode/measure.h +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2004-2015, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* Author: Alan Liu -* Created: April 26, 2004 -* Since: ICU 3.0 -********************************************************************** -*/ -#ifndef __MEASURE_H__ -#define __MEASURE_H__ - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: MeasureUnit object. - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/fmtable.h" - -U_NAMESPACE_BEGIN - -class MeasureUnit; - -/** - * An amount of a specified unit, consisting of a number and a Unit. - * For example, a length measure consists of a number and a length - * unit, such as feet or meters. - * - *

Measure objects are formatted by MeasureFormat. - * - *

Measure objects are immutable. - * - * @author Alan Liu - * @stable ICU 3.0 - */ -class U_I18N_API Measure: public UObject { - public: - /** - * Construct an object with the given numeric amount and the given - * unit. After this call, the caller must not delete the given - * unit object. - * @param number a numeric object; amount.isNumeric() must be TRUE - * @param adoptedUnit the unit object, which must not be NULL - * @param ec input-output error code. If the amount or the unit - * is invalid, then this will be set to a failing value. - * @stable ICU 3.0 - */ - Measure(const Formattable& number, MeasureUnit* adoptedUnit, - UErrorCode& ec); - - /** - * Copy constructor - * @stable ICU 3.0 - */ - Measure(const Measure& other); - - /** - * Assignment operator - * @stable ICU 3.0 - */ - Measure& operator=(const Measure& other); - - /** - * Return a polymorphic clone of this object. The result will - * have the same class as returned by getDynamicClassID(). - * @stable ICU 3.0 - */ - virtual UObject* clone() const; - - /** - * Destructor - * @stable ICU 3.0 - */ - virtual ~Measure(); - - /** - * Equality operator. Return true if this object is equal - * to the given object. - * @stable ICU 3.0 - */ - UBool operator==(const UObject& other) const; - - /** - * Return a reference to the numeric value of this object. The - * numeric value may be of any numeric type supported by - * Formattable. - * @stable ICU 3.0 - */ - inline const Formattable& getNumber() const; - - /** - * Return a reference to the unit of this object. - * @stable ICU 3.0 - */ - inline const MeasureUnit& getUnit() const; - - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 53 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 53 - */ - virtual UClassID getDynamicClassID(void) const; - - protected: - /** - * Default constructor. - * @stable ICU 3.0 - */ - Measure(); - - private: - /** - * The numeric value of this object, e.g. 2.54 or 100. - */ - Formattable number; - - /** - * The unit of this object, e.g., "millimeter" or "JPY". This is - * owned by this object. - */ - MeasureUnit* unit; -}; - -inline const Formattable& Measure::getNumber() const { - return number; -} - -inline const MeasureUnit& Measure::getUnit() const { - return *unit; -} - -U_NAMESPACE_END - -#endif // !UCONFIG_NO_FORMATTING -#endif // __MEASURE_H__ diff --git a/win32/include/spidermonkey/unicode/messagepattern.h b/win32/include/spidermonkey/unicode/messagepattern.h deleted file mode 100755 index 8c1115e0..00000000 --- a/win32/include/spidermonkey/unicode/messagepattern.h +++ /dev/null @@ -1,945 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2011-2013, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* file name: messagepattern.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2011mar14 -* created by: Markus W. Scherer -*/ - -#ifndef __MESSAGEPATTERN_H__ -#define __MESSAGEPATTERN_H__ - -/** - * \file - * \brief C++ API: MessagePattern class: Parses and represents ICU MessageFormat patterns. - */ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/parseerr.h" -#include "unicode/unistr.h" - -/** - * Mode for when an apostrophe starts quoted literal text for MessageFormat output. - * The default is DOUBLE_OPTIONAL unless overridden via uconfig.h - * (UCONFIG_MSGPAT_DEFAULT_APOSTROPHE_MODE). - *

- * A pair of adjacent apostrophes always results in a single apostrophe in the output, - * even when the pair is between two single, text-quoting apostrophes. - *

- * The following table shows examples of desired MessageFormat.format() output - * with the pattern strings that yield that output. - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Desired outputDOUBLE_OPTIONALDOUBLE_REQUIRED
I see {many}I see '{many}'(same)
I said {'Wow!'}I said '{''Wow!''}'(same)
I don't knowI don't know OR
I don''t know
I don''t know
- * @stable ICU 4.8 - * @see UCONFIG_MSGPAT_DEFAULT_APOSTROPHE_MODE - */ -enum UMessagePatternApostropheMode { - /** - * A literal apostrophe is represented by - * either a single or a double apostrophe pattern character. - * Within a MessageFormat pattern, a single apostrophe only starts quoted literal text - * if it immediately precedes a curly brace {}, - * or a pipe symbol | if inside a choice format, - * or a pound symbol # if inside a plural format. - *

- * This is the default behavior starting with ICU 4.8. - * @stable ICU 4.8 - */ - UMSGPAT_APOS_DOUBLE_OPTIONAL, - /** - * A literal apostrophe must be represented by - * a double apostrophe pattern character. - * A single apostrophe always starts quoted literal text. - *

- * This is the behavior of ICU 4.6 and earlier, and of the JDK. - * @stable ICU 4.8 - */ - UMSGPAT_APOS_DOUBLE_REQUIRED -}; -/** - * @stable ICU 4.8 - */ -typedef enum UMessagePatternApostropheMode UMessagePatternApostropheMode; - -/** - * MessagePattern::Part type constants. - * @stable ICU 4.8 - */ -enum UMessagePatternPartType { - /** - * Start of a message pattern (main or nested). - * The length is 0 for the top-level message - * and for a choice argument sub-message, otherwise 1 for the '{'. - * The value indicates the nesting level, starting with 0 for the main message. - *

- * There is always a later MSG_LIMIT part. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_MSG_START, - /** - * End of a message pattern (main or nested). - * The length is 0 for the top-level message and - * the last sub-message of a choice argument, - * otherwise 1 for the '}' or (in a choice argument style) the '|'. - * The value indicates the nesting level, starting with 0 for the main message. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_MSG_LIMIT, - /** - * Indicates a substring of the pattern string which is to be skipped when formatting. - * For example, an apostrophe that begins or ends quoted text - * would be indicated with such a part. - * The value is undefined and currently always 0. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_SKIP_SYNTAX, - /** - * Indicates that a syntax character needs to be inserted for auto-quoting. - * The length is 0. - * The value is the character code of the insertion character. (U+0027=APOSTROPHE) - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_INSERT_CHAR, - /** - * Indicates a syntactic (non-escaped) # symbol in a plural variant. - * When formatting, replace this part's substring with the - * (value-offset) for the plural argument value. - * The value is undefined and currently always 0. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_REPLACE_NUMBER, - /** - * Start of an argument. - * The length is 1 for the '{'. - * The value is the ordinal value of the ArgType. Use getArgType(). - *

- * This part is followed by either an ARG_NUMBER or ARG_NAME, - * followed by optional argument sub-parts (see UMessagePatternArgType constants) - * and finally an ARG_LIMIT part. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_ARG_START, - /** - * End of an argument. - * The length is 1 for the '}'. - * The value is the ordinal value of the ArgType. Use getArgType(). - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_ARG_LIMIT, - /** - * The argument number, provided by the value. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_ARG_NUMBER, - /** - * The argument name. - * The value is undefined and currently always 0. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_ARG_NAME, - /** - * The argument type. - * The value is undefined and currently always 0. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_ARG_TYPE, - /** - * The argument style text. - * The value is undefined and currently always 0. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_ARG_STYLE, - /** - * A selector substring in a "complex" argument style. - * The value is undefined and currently always 0. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_ARG_SELECTOR, - /** - * An integer value, for example the offset or an explicit selector value - * in a PluralFormat style. - * The part value is the integer value. - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_ARG_INT, - /** - * A numeric value, for example the offset or an explicit selector value - * in a PluralFormat style. - * The part value is an index into an internal array of numeric values; - * use getNumericValue(). - * @stable ICU 4.8 - */ - UMSGPAT_PART_TYPE_ARG_DOUBLE -}; -/** - * @stable ICU 4.8 - */ -typedef enum UMessagePatternPartType UMessagePatternPartType; - -/** - * Argument type constants. - * Returned by Part.getArgType() for ARG_START and ARG_LIMIT parts. - * - * Messages nested inside an argument are each delimited by MSG_START and MSG_LIMIT, - * with a nesting level one greater than the surrounding message. - * @stable ICU 4.8 - */ -enum UMessagePatternArgType { - /** - * The argument has no specified type. - * @stable ICU 4.8 - */ - UMSGPAT_ARG_TYPE_NONE, - /** - * The argument has a "simple" type which is provided by the ARG_TYPE part. - * An ARG_STYLE part might follow that. - * @stable ICU 4.8 - */ - UMSGPAT_ARG_TYPE_SIMPLE, - /** - * The argument is a ChoiceFormat with one or more - * ((ARG_INT | ARG_DOUBLE), ARG_SELECTOR, message) tuples. - * @stable ICU 4.8 - */ - UMSGPAT_ARG_TYPE_CHOICE, - /** - * The argument is a cardinal-number PluralFormat with an optional ARG_INT or ARG_DOUBLE offset - * (e.g., offset:1) - * and one or more (ARG_SELECTOR [explicit-value] message) tuples. - * If the selector has an explicit value (e.g., =2), then - * that value is provided by the ARG_INT or ARG_DOUBLE part preceding the message. - * Otherwise the message immediately follows the ARG_SELECTOR. - * @stable ICU 4.8 - */ - UMSGPAT_ARG_TYPE_PLURAL, - /** - * The argument is a SelectFormat with one or more (ARG_SELECTOR, message) pairs. - * @stable ICU 4.8 - */ - UMSGPAT_ARG_TYPE_SELECT, - /** - * The argument is an ordinal-number PluralFormat - * with the same style parts sequence and semantics as UMSGPAT_ARG_TYPE_PLURAL. - * @stable ICU 50 - */ - UMSGPAT_ARG_TYPE_SELECTORDINAL -}; -/** - * @stable ICU 4.8 - */ -typedef enum UMessagePatternArgType UMessagePatternArgType; - -/** - * \def UMSGPAT_ARG_TYPE_HAS_PLURAL_STYLE - * Returns TRUE if the argument type has a plural style part sequence and semantics, - * for example UMSGPAT_ARG_TYPE_PLURAL and UMSGPAT_ARG_TYPE_SELECTORDINAL. - * @stable ICU 50 - */ -#define UMSGPAT_ARG_TYPE_HAS_PLURAL_STYLE(argType) \ - ((argType)==UMSGPAT_ARG_TYPE_PLURAL || (argType)==UMSGPAT_ARG_TYPE_SELECTORDINAL) - -enum { - /** - * Return value from MessagePattern.validateArgumentName() for when - * the string is a valid "pattern identifier" but not a number. - * @stable ICU 4.8 - */ - UMSGPAT_ARG_NAME_NOT_NUMBER=-1, - - /** - * Return value from MessagePattern.validateArgumentName() for when - * the string is invalid. - * It might not be a valid "pattern identifier", - * or it have only ASCII digits but there is a leading zero or the number is too large. - * @stable ICU 4.8 - */ - UMSGPAT_ARG_NAME_NOT_VALID=-2 -}; - -/** - * Special value that is returned by getNumericValue(Part) when no - * numeric value is defined for a part. - * @see MessagePattern.getNumericValue() - * @stable ICU 4.8 - */ -#define UMSGPAT_NO_NUMERIC_VALUE ((double)(-123456789)) - -U_NAMESPACE_BEGIN - -class MessagePatternDoubleList; -class MessagePatternPartsList; - -/** - * Parses and represents ICU MessageFormat patterns. - * Also handles patterns for ChoiceFormat, PluralFormat and SelectFormat. - * Used in the implementations of those classes as well as in tools - * for message validation, translation and format conversion. - *

- * The parser handles all syntax relevant for identifying message arguments. - * This includes "complex" arguments whose style strings contain - * nested MessageFormat pattern substrings. - * For "simple" arguments (with no nested MessageFormat pattern substrings), - * the argument style is not parsed any further. - *

- * The parser handles named and numbered message arguments and allows both in one message. - *

- * Once a pattern has been parsed successfully, iterate through the parsed data - * with countParts(), getPart() and related methods. - *

- * The data logically represents a parse tree, but is stored and accessed - * as a list of "parts" for fast and simple parsing and to minimize object allocations. - * Arguments and nested messages are best handled via recursion. - * For every _START "part", MessagePattern.getLimitPartIndex() efficiently returns - * the index of the corresponding _LIMIT "part". - *

- * List of "parts": - *

- * message = MSG_START (SKIP_SYNTAX | INSERT_CHAR | REPLACE_NUMBER | argument)* MSG_LIMIT
- * argument = noneArg | simpleArg | complexArg
- * complexArg = choiceArg | pluralArg | selectArg
- *
- * noneArg = ARG_START.NONE (ARG_NAME | ARG_NUMBER) ARG_LIMIT.NONE
- * simpleArg = ARG_START.SIMPLE (ARG_NAME | ARG_NUMBER) ARG_TYPE [ARG_STYLE] ARG_LIMIT.SIMPLE
- * choiceArg = ARG_START.CHOICE (ARG_NAME | ARG_NUMBER) choiceStyle ARG_LIMIT.CHOICE
- * pluralArg = ARG_START.PLURAL (ARG_NAME | ARG_NUMBER) pluralStyle ARG_LIMIT.PLURAL
- * selectArg = ARG_START.SELECT (ARG_NAME | ARG_NUMBER) selectStyle ARG_LIMIT.SELECT
- *
- * choiceStyle = ((ARG_INT | ARG_DOUBLE) ARG_SELECTOR message)+
- * pluralStyle = [ARG_INT | ARG_DOUBLE] (ARG_SELECTOR [ARG_INT | ARG_DOUBLE] message)+
- * selectStyle = (ARG_SELECTOR message)+
- * 
- *
    - *
  • Literal output text is not represented directly by "parts" but accessed - * between parts of a message, from one part's getLimit() to the next part's getIndex(). - *
  • ARG_START.CHOICE stands for an ARG_START Part with ArgType CHOICE. - *
  • In the choiceStyle, the ARG_SELECTOR has the '<', the '#' or - * the less-than-or-equal-to sign (U+2264). - *
  • In the pluralStyle, the first, optional numeric Part has the "offset:" value. - * The optional numeric Part between each (ARG_SELECTOR, message) pair - * is the value of an explicit-number selector like "=2", - * otherwise the selector is a non-numeric identifier. - *
  • The REPLACE_NUMBER Part can occur only in an immediate sub-message of the pluralStyle. - *
- *

- * This class is not intended for public subclassing. - * - * @stable ICU 4.8 - */ -class U_COMMON_API MessagePattern : public UObject { -public: - /** - * Constructs an empty MessagePattern with default UMessagePatternApostropheMode. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @stable ICU 4.8 - */ - MessagePattern(UErrorCode &errorCode); - - /** - * Constructs an empty MessagePattern. - * @param mode Explicit UMessagePatternApostropheMode. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @stable ICU 4.8 - */ - MessagePattern(UMessagePatternApostropheMode mode, UErrorCode &errorCode); - - /** - * Constructs a MessagePattern with default UMessagePatternApostropheMode and - * parses the MessageFormat pattern string. - * @param pattern a MessageFormat pattern string - * @param parseError Struct to receive information on the position - * of an error within the pattern. - * Can be NULL. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * TODO: turn @throws into UErrorCode specifics? - * @throws IllegalArgumentException for syntax errors in the pattern string - * @throws IndexOutOfBoundsException if certain limits are exceeded - * (e.g., argument number too high, argument name too long, etc.) - * @throws NumberFormatException if a number could not be parsed - * @stable ICU 4.8 - */ - MessagePattern(const UnicodeString &pattern, UParseError *parseError, UErrorCode &errorCode); - - /** - * Copy constructor. - * @param other Object to copy. - * @stable ICU 4.8 - */ - MessagePattern(const MessagePattern &other); - - /** - * Assignment operator. - * @param other Object to copy. - * @return *this=other - * @stable ICU 4.8 - */ - MessagePattern &operator=(const MessagePattern &other); - - /** - * Destructor. - * @stable ICU 4.8 - */ - virtual ~MessagePattern(); - - /** - * Parses a MessageFormat pattern string. - * @param pattern a MessageFormat pattern string - * @param parseError Struct to receive information on the position - * of an error within the pattern. - * Can be NULL. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return *this - * @throws IllegalArgumentException for syntax errors in the pattern string - * @throws IndexOutOfBoundsException if certain limits are exceeded - * (e.g., argument number too high, argument name too long, etc.) - * @throws NumberFormatException if a number could not be parsed - * @stable ICU 4.8 - */ - MessagePattern &parse(const UnicodeString &pattern, - UParseError *parseError, UErrorCode &errorCode); - - /** - * Parses a ChoiceFormat pattern string. - * @param pattern a ChoiceFormat pattern string - * @param parseError Struct to receive information on the position - * of an error within the pattern. - * Can be NULL. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return *this - * @throws IllegalArgumentException for syntax errors in the pattern string - * @throws IndexOutOfBoundsException if certain limits are exceeded - * (e.g., argument number too high, argument name too long, etc.) - * @throws NumberFormatException if a number could not be parsed - * @stable ICU 4.8 - */ - MessagePattern &parseChoiceStyle(const UnicodeString &pattern, - UParseError *parseError, UErrorCode &errorCode); - - /** - * Parses a PluralFormat pattern string. - * @param pattern a PluralFormat pattern string - * @param parseError Struct to receive information on the position - * of an error within the pattern. - * Can be NULL. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return *this - * @throws IllegalArgumentException for syntax errors in the pattern string - * @throws IndexOutOfBoundsException if certain limits are exceeded - * (e.g., argument number too high, argument name too long, etc.) - * @throws NumberFormatException if a number could not be parsed - * @stable ICU 4.8 - */ - MessagePattern &parsePluralStyle(const UnicodeString &pattern, - UParseError *parseError, UErrorCode &errorCode); - - /** - * Parses a SelectFormat pattern string. - * @param pattern a SelectFormat pattern string - * @param parseError Struct to receive information on the position - * of an error within the pattern. - * Can be NULL. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return *this - * @throws IllegalArgumentException for syntax errors in the pattern string - * @throws IndexOutOfBoundsException if certain limits are exceeded - * (e.g., argument number too high, argument name too long, etc.) - * @throws NumberFormatException if a number could not be parsed - * @stable ICU 4.8 - */ - MessagePattern &parseSelectStyle(const UnicodeString &pattern, - UParseError *parseError, UErrorCode &errorCode); - - /** - * Clears this MessagePattern. - * countParts() will return 0. - * @stable ICU 4.8 - */ - void clear(); - - /** - * Clears this MessagePattern and sets the UMessagePatternApostropheMode. - * countParts() will return 0. - * @param mode The new UMessagePatternApostropheMode. - * @stable ICU 4.8 - */ - void clearPatternAndSetApostropheMode(UMessagePatternApostropheMode mode) { - clear(); - aposMode=mode; - } - - /** - * @param other another object to compare with. - * @return TRUE if this object is equivalent to the other one. - * @stable ICU 4.8 - */ - UBool operator==(const MessagePattern &other) const; - - /** - * @param other another object to compare with. - * @return FALSE if this object is equivalent to the other one. - * @stable ICU 4.8 - */ - inline UBool operator!=(const MessagePattern &other) const { - return !operator==(other); - } - - /** - * @return A hash code for this object. - * @stable ICU 4.8 - */ - int32_t hashCode() const; - - /** - * @return this instance's UMessagePatternApostropheMode. - * @stable ICU 4.8 - */ - UMessagePatternApostropheMode getApostropheMode() const { - return aposMode; - } - - // Java has package-private jdkAposMode() here. - // In C++, this is declared in the MessageImpl class. - - /** - * @return the parsed pattern string (null if none was parsed). - * @stable ICU 4.8 - */ - const UnicodeString &getPatternString() const { - return msg; - } - - /** - * Does the parsed pattern have named arguments like {first_name}? - * @return TRUE if the parsed pattern has at least one named argument. - * @stable ICU 4.8 - */ - UBool hasNamedArguments() const { - return hasArgNames; - } - - /** - * Does the parsed pattern have numbered arguments like {2}? - * @return TRUE if the parsed pattern has at least one numbered argument. - * @stable ICU 4.8 - */ - UBool hasNumberedArguments() const { - return hasArgNumbers; - } - - /** - * Validates and parses an argument name or argument number string. - * An argument name must be a "pattern identifier", that is, it must contain - * no Unicode Pattern_Syntax or Pattern_White_Space characters. - * If it only contains ASCII digits, then it must be a small integer with no leading zero. - * @param name Input string. - * @return >=0 if the name is a valid number, - * ARG_NAME_NOT_NUMBER (-1) if it is a "pattern identifier" but not all ASCII digits, - * ARG_NAME_NOT_VALID (-2) if it is neither. - * @stable ICU 4.8 - */ - static int32_t validateArgumentName(const UnicodeString &name); - - /** - * Returns a version of the parsed pattern string where each ASCII apostrophe - * is doubled (escaped) if it is not already, and if it is not interpreted as quoting syntax. - *

- * For example, this turns "I don't '{know}' {gender,select,female{h''er}other{h'im}}." - * into "I don''t '{know}' {gender,select,female{h''er}other{h''im}}." - * @return the deep-auto-quoted version of the parsed pattern string. - * @see MessageFormat.autoQuoteApostrophe() - * @stable ICU 4.8 - */ - UnicodeString autoQuoteApostropheDeep() const; - - class Part; - - /** - * Returns the number of "parts" created by parsing the pattern string. - * Returns 0 if no pattern has been parsed or clear() was called. - * @return the number of pattern parts. - * @stable ICU 4.8 - */ - int32_t countParts() const { - return partsLength; - } - - /** - * Gets the i-th pattern "part". - * @param i The index of the Part data. (0..countParts()-1) - * @return the i-th pattern "part". - * @stable ICU 4.8 - */ - const Part &getPart(int32_t i) const { - return parts[i]; - } - - /** - * Returns the UMessagePatternPartType of the i-th pattern "part". - * Convenience method for getPart(i).getType(). - * @param i The index of the Part data. (0..countParts()-1) - * @return The UMessagePatternPartType of the i-th Part. - * @stable ICU 4.8 - */ - UMessagePatternPartType getPartType(int32_t i) const { - return getPart(i).type; - } - - /** - * Returns the pattern index of the specified pattern "part". - * Convenience method for getPart(partIndex).getIndex(). - * @param partIndex The index of the Part data. (0..countParts()-1) - * @return The pattern index of this Part. - * @stable ICU 4.8 - */ - int32_t getPatternIndex(int32_t partIndex) const { - return getPart(partIndex).index; - } - - /** - * Returns the substring of the pattern string indicated by the Part. - * Convenience method for getPatternString().substring(part.getIndex(), part.getLimit()). - * @param part a part of this MessagePattern. - * @return the substring associated with part. - * @stable ICU 4.8 - */ - UnicodeString getSubstring(const Part &part) const { - return msg.tempSubString(part.index, part.length); - } - - /** - * Compares the part's substring with the input string s. - * @param part a part of this MessagePattern. - * @param s a string. - * @return TRUE if getSubstring(part).equals(s). - * @stable ICU 4.8 - */ - UBool partSubstringMatches(const Part &part, const UnicodeString &s) const { - return 0==msg.compare(part.index, part.length, s); - } - - /** - * Returns the numeric value associated with an ARG_INT or ARG_DOUBLE. - * @param part a part of this MessagePattern. - * @return the part's numeric value, or UMSGPAT_NO_NUMERIC_VALUE if this is not a numeric part. - * @stable ICU 4.8 - */ - double getNumericValue(const Part &part) const; - - /** - * Returns the "offset:" value of a PluralFormat argument, or 0 if none is specified. - * @param pluralStart the index of the first PluralFormat argument style part. (0..countParts()-1) - * @return the "offset:" value. - * @stable ICU 4.8 - */ - double getPluralOffset(int32_t pluralStart) const; - - /** - * Returns the index of the ARG|MSG_LIMIT part corresponding to the ARG|MSG_START at start. - * @param start The index of some Part data (0..countParts()-1); - * this Part should be of Type ARG_START or MSG_START. - * @return The first i>start where getPart(i).getType()==ARG|MSG_LIMIT at the same nesting level, - * or start itself if getPartType(msgStart)!=ARG|MSG_START. - * @stable ICU 4.8 - */ - int32_t getLimitPartIndex(int32_t start) const { - int32_t limit=getPart(start).limitPartIndex; - if(limit parts=new ArrayList(); - MessagePatternPartsList *partsList; - Part *parts; - int32_t partsLength; - // ArrayList numericValues; - MessagePatternDoubleList *numericValuesList; - double *numericValues; - int32_t numericValuesLength; - UBool hasArgNames; - UBool hasArgNumbers; - UBool needsAutoQuoting; -}; - -U_NAMESPACE_END - -#endif // !UCONFIG_NO_FORMATTING - -#endif // __MESSAGEPATTERN_H__ diff --git a/win32/include/spidermonkey/unicode/msgfmt.h b/win32/include/spidermonkey/unicode/msgfmt.h deleted file mode 100755 index 1a997387..00000000 --- a/win32/include/spidermonkey/unicode/msgfmt.h +++ /dev/null @@ -1,1095 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -* Copyright (C) 2007-2013, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************** -* -* File MSGFMT.H -* -* Modification History: -* -* Date Name Description -* 02/19/97 aliu Converted from java. -* 03/20/97 helena Finished first cut of implementation. -* 07/22/98 stephen Removed operator!= (defined in Format) -* 08/19/2002 srl Removing Javaisms -*******************************************************************************/ - -#ifndef MSGFMT_H -#define MSGFMT_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Formats messages in a language-neutral way. - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/format.h" -#include "unicode/locid.h" -#include "unicode/messagepattern.h" -#include "unicode/parseerr.h" -#include "unicode/plurfmt.h" -#include "unicode/plurrule.h" - -U_CDECL_BEGIN -// Forward declaration. -struct UHashtable; -typedef struct UHashtable UHashtable; /**< @internal */ -U_CDECL_END - -U_NAMESPACE_BEGIN - -class AppendableWrapper; -class DateFormat; -class NumberFormat; - -/** - *

MessageFormat prepares strings for display to users, - * with optional arguments (variables/placeholders). - * The arguments can occur in any order, which is necessary for translation - * into languages with different grammars. - * - *

A MessageFormat is constructed from a pattern string - * with arguments in {curly braces} which will be replaced by formatted values. - * - *

MessageFormat differs from the other Format - * classes in that you create a MessageFormat object with one - * of its constructors (not with a createInstance style factory - * method). Factory methods aren't necessary because MessageFormat - * itself doesn't implement locale-specific behavior. Any locale-specific - * behavior is defined by the pattern that you provide and the - * subformats used for inserted arguments. - * - *

Arguments can be named (using identifiers) or numbered (using small ASCII-digit integers). - * Some of the API methods work only with argument numbers and throw an exception - * if the pattern has named arguments (see {@link #usesNamedArguments()}). - * - *

An argument might not specify any format type. In this case, - * a Number value is formatted with a default (for the locale) NumberFormat, - * a Date value is formatted with a default (for the locale) DateFormat, - * and for any other value its toString() value is used. - * - *

An argument might specify a "simple" type for which the specified - * Format object is created, cached and used. - * - *

An argument might have a "complex" type with nested MessageFormat sub-patterns. - * During formatting, one of these sub-messages is selected according to the argument value - * and recursively formatted. - * - *

After construction, a custom Format object can be set for - * a top-level argument, overriding the default formatting and parsing behavior - * for that argument. - * However, custom formatting can be achieved more simply by writing - * a typeless argument in the pattern string - * and supplying it with a preformatted string value. - * - *

When formatting, MessageFormat takes a collection of argument values - * and writes an output string. - * The argument values may be passed as an array - * (when the pattern contains only numbered arguments) - * or as an array of names and and an array of arguments (which works for both named - * and numbered arguments). - * - *

Each argument is matched with one of the input values by array index or argument name - * and formatted according to its pattern specification - * (or using a custom Format object if one was set). - * A numbered pattern argument is matched with an argument name that contains that number - * as an ASCII-decimal-digit string (without leading zero). - * - *

Patterns and Their Interpretation

- * - * MessageFormat uses patterns of the following form: - *
- * message = messageText (argument messageText)*
- * argument = noneArg | simpleArg | complexArg
- * complexArg = choiceArg | pluralArg | selectArg | selectordinalArg
- *
- * noneArg = '{' argNameOrNumber '}'
- * simpleArg = '{' argNameOrNumber ',' argType [',' argStyle] '}'
- * choiceArg = '{' argNameOrNumber ',' "choice" ',' choiceStyle '}'
- * pluralArg = '{' argNameOrNumber ',' "plural" ',' pluralStyle '}'
- * selectArg = '{' argNameOrNumber ',' "select" ',' selectStyle '}'
- * selectordinalArg = '{' argNameOrNumber ',' "selectordinal" ',' pluralStyle '}'
- *
- * choiceStyle: see {@link ChoiceFormat}
- * pluralStyle: see {@link PluralFormat}
- * selectStyle: see {@link SelectFormat}
- *
- * argNameOrNumber = argName | argNumber
- * argName = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
- * argNumber = '0' | ('1'..'9' ('0'..'9')*)
- *
- * argType = "number" | "date" | "time" | "spellout" | "ordinal" | "duration"
- * argStyle = "short" | "medium" | "long" | "full" | "integer" | "currency" | "percent" | argStyleText
- * 
- * - *
    - *
  • messageText can contain quoted literal strings including syntax characters. - * A quoted literal string begins with an ASCII apostrophe and a syntax character - * (usually a {curly brace}) and continues until the next single apostrophe. - * A double ASCII apostrohpe inside or outside of a quoted string represents - * one literal apostrophe. - *
  • Quotable syntax characters are the {curly braces} in all messageText parts, - * plus the '#' sign in a messageText immediately inside a pluralStyle, - * and the '|' symbol in a messageText immediately inside a choiceStyle. - *
  • See also {@link #UMessagePatternApostropheMode} - *
  • In argStyleText, every single ASCII apostrophe begins and ends quoted literal text, - * and unquoted {curly braces} must occur in matched pairs. - *
- * - *

Recommendation: Use the real apostrophe (single quote) character - * \htmlonly’\endhtmlonly (U+2019) for - * human-readable text, and use the ASCII apostrophe ' (U+0027) - * only in program syntax, like quoting in MessageFormat. - * See the annotations for U+0027 Apostrophe in The Unicode Standard. - * - *

The choice argument type is deprecated. - * Use plural arguments for proper plural selection, - * and select arguments for simple selection among a fixed set of choices. - * - *

The argType and argStyle values are used to create - * a Format instance for the format element. The following - * table shows how the values map to Format instances. Combinations not - * shown in the table are illegal. Any argStyleText must - * be a valid pattern string for the Format subclass used. - * - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
argType - * argStyle - * resulting Format object - *
(none) - * null - *
number - * (none) - * NumberFormat.createInstance(getLocale(), status) - *
integer - * NumberFormat.createInstance(getLocale(), kNumberStyle, status) - *
currency - * NumberFormat.createCurrencyInstance(getLocale(), status) - *
percent - * NumberFormat.createPercentInstance(getLocale(), status) - *
argStyleText - * new DecimalFormat(argStyleText, new DecimalFormatSymbols(getLocale(), status), status) - *
date - * (none) - * DateFormat.createDateInstance(kDefault, getLocale(), status) - *
short - * DateFormat.createDateInstance(kShort, getLocale(), status) - *
medium - * DateFormat.createDateInstance(kDefault, getLocale(), status) - *
long - * DateFormat.createDateInstance(kLong, getLocale(), status) - *
full - * DateFormat.createDateInstance(kFull, getLocale(), status) - *
argStyleText - * new SimpleDateFormat(argStyleText, getLocale(), status) - *
time - * (none) - * DateFormat.createTimeInstance(kDefault, getLocale(), status) - *
short - * DateFormat.createTimeInstance(kShort, getLocale(), status) - *
medium - * DateFormat.createTimeInstance(kDefault, getLocale(), status) - *
long - * DateFormat.createTimeInstance(kLong, getLocale(), status) - *
full - * DateFormat.createTimeInstance(kFull, getLocale(), status) - *
argStyleText - * new SimpleDateFormat(argStyleText, getLocale(), status) - *
spellout - * argStyleText (optional) - * new RuleBasedNumberFormat(URBNF_SPELLOUT, getLocale(), status) - *
    .setDefaultRuleset(argStyleText, status);
- *
ordinal - * argStyleText (optional) - * new RuleBasedNumberFormat(URBNF_ORDINAL, getLocale(), status) - *
    .setDefaultRuleset(argStyleText, status);
- *
duration - * argStyleText (optional) - * new RuleBasedNumberFormat(URBNF_DURATION, getLocale(), status) - *
    .setDefaultRuleset(argStyleText, status);
- *
- *

- * - *

Usage Information

- * - *

Here are some examples of usage: - * Example 1: - * - *

- * \code
- *     UErrorCode success = U_ZERO_ERROR;
- *     GregorianCalendar cal(success);
- *     Formattable arguments[] = {
- *         7L,
- *         Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
- *         "a disturbance in the Force"
- *     };
- *
- *     UnicodeString result;
- *     MessageFormat::format(
- *          "At {1,time} on {1,date}, there was {2} on planet {0,number}.",
- *          arguments, 3, result, success );
- *
- *     cout << "result: " << result << endl;
- *     //: At 4:34:20 PM on 23-Mar-98, there was a disturbance
- *     //             in the Force on planet 7.
- * \endcode
- * 
- * - * Typically, the message format will come from resources, and the - * arguments will be dynamically set at runtime. - * - *

Example 2: - * - *

- *  \code
- *     success = U_ZERO_ERROR;
- *     Formattable testArgs[] = {3L, "MyDisk"};
- *
- *     MessageFormat form(
- *         "The disk \"{1}\" contains {0} file(s).", success );
- *
- *     UnicodeString string;
- *     FieldPosition fpos = 0;
- *     cout << "format: " << form.format(testArgs, 2, string, fpos, success ) << endl;
- *
- *     // output, with different testArgs:
- *     // output: The disk "MyDisk" contains 0 file(s).
- *     // output: The disk "MyDisk" contains 1 file(s).
- *     // output: The disk "MyDisk" contains 1,273 file(s).
- *  \endcode
- *  
- * - * - *

For messages that include plural forms, you can use a plural argument: - *

- * \code
- *  success = U_ZERO_ERROR;
- *  MessageFormat msgFmt(
- *       "{num_files, plural, "
- *       "=0{There are no files on disk \"{disk_name}\".}"
- *       "=1{There is one file on disk \"{disk_name}\".}"
- *       "other{There are # files on disk \"{disk_name}\".}}",
- *      Locale("en"),
- *      success);
- *  FieldPosition fpos = 0;
- *  Formattable testArgs[] = {0L, "MyDisk"};
- *  UnicodeString testArgsNames[] = {"num_files", "disk_name"};
- *  UnicodeString result;
- *  cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
- *  testArgs[0] = 3L;
- *  cout << msgFmt.format(testArgs, testArgsNames, 2, result, fpos, 0, success);
- * \endcode
- * output:
- * There are no files on disk "MyDisk".
- * There are 3 files on "MyDisk".
- * 
- * See {@link PluralFormat} and {@link PluralRules} for details. - * - *

Synchronization

- * - *

MessageFormats are not synchronized. - * It is recommended to create separate format instances for each thread. - * If multiple threads access a format concurrently, it must be synchronized - * externally. - * - * @stable ICU 2.0 - */ -class U_I18N_API MessageFormat : public Format { -public: -#ifndef U_HIDE_OBSOLETE_API - /** - * Enum type for kMaxFormat. - * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6, - * rendering this enum type obsolete. - */ - enum EFormatNumber { - /** - * The maximum number of arguments. - * @obsolete ICU 3.0. The 10-argument limit was removed as of ICU 2.6, - * rendering this constant obsolete. - */ - kMaxFormat = 10 - }; -#endif /* U_HIDE_OBSOLETE_API */ - - /** - * Constructs a new MessageFormat using the given pattern and the - * default locale. - * - * @param pattern Pattern used to construct object. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @stable ICU 2.0 - */ - MessageFormat(const UnicodeString& pattern, - UErrorCode &status); - - /** - * Constructs a new MessageFormat using the given pattern and locale. - * @param pattern Pattern used to construct object. - * @param newLocale The locale to use for formatting dates and numbers. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @stable ICU 2.0 - */ - MessageFormat(const UnicodeString& pattern, - const Locale& newLocale, - UErrorCode& status); - /** - * Constructs a new MessageFormat using the given pattern and locale. - * @param pattern Pattern used to construct object. - * @param newLocale The locale to use for formatting dates and numbers. - * @param parseError Struct to receive information on the position - * of an error within the pattern. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @stable ICU 2.0 - */ - MessageFormat(const UnicodeString& pattern, - const Locale& newLocale, - UParseError& parseError, - UErrorCode& status); - /** - * Constructs a new MessageFormat from an existing one. - * @stable ICU 2.0 - */ - MessageFormat(const MessageFormat&); - - /** - * Assignment operator. - * @stable ICU 2.0 - */ - const MessageFormat& operator=(const MessageFormat&); - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~MessageFormat(); - - /** - * Clones this Format object polymorphically. The caller owns the - * result and should delete it when done. - * @stable ICU 2.0 - */ - virtual Format* clone(void) const; - - /** - * Returns true if the given Format objects are semantically equal. - * Objects of different subclasses are considered unequal. - * @param other the object to be compared with. - * @return true if the given Format objects are semantically equal. - * @stable ICU 2.0 - */ - virtual UBool operator==(const Format& other) const; - - /** - * Sets the locale to be used for creating argument Format objects. - * @param theLocale the new locale value to be set. - * @stable ICU 2.0 - */ - virtual void setLocale(const Locale& theLocale); - - /** - * Gets the locale used for creating argument Format objects. - * format information. - * @return the locale of the object. - * @stable ICU 2.0 - */ - virtual const Locale& getLocale(void) const; - - /** - * Applies the given pattern string to this message format. - * - * @param pattern The pattern to be applied. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @stable ICU 2.0 - */ - virtual void applyPattern(const UnicodeString& pattern, - UErrorCode& status); - /** - * Applies the given pattern string to this message format. - * - * @param pattern The pattern to be applied. - * @param parseError Struct to receive information on the position - * of an error within the pattern. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @stable ICU 2.0 - */ - virtual void applyPattern(const UnicodeString& pattern, - UParseError& parseError, - UErrorCode& status); - - /** - * Sets the UMessagePatternApostropheMode and the pattern used by this message format. - * Parses the pattern and caches Format objects for simple argument types. - * Patterns and their interpretation are specified in the - * class description. - *

- * This method is best used only once on a given object to avoid confusion about the mode, - * and after constructing the object with an empty pattern string to minimize overhead. - * - * @param pattern The pattern to be applied. - * @param aposMode The new apostrophe mode. - * @param parseError Struct to receive information on the position - * of an error within the pattern. - * Can be NULL. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @stable ICU 4.8 - */ - virtual void applyPattern(const UnicodeString& pattern, - UMessagePatternApostropheMode aposMode, - UParseError* parseError, - UErrorCode& status); - - /** - * @return this instance's UMessagePatternApostropheMode. - * @stable ICU 4.8 - */ - UMessagePatternApostropheMode getApostropheMode() const { - return msgPattern.getApostropheMode(); - } - - /** - * Returns a pattern that can be used to recreate this object. - * - * @param appendTo Output parameter to receive the pattern. - * Result is appended to existing contents. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - virtual UnicodeString& toPattern(UnicodeString& appendTo) const; - - /** - * Sets subformats. - * See the class description about format numbering. - * The caller should not delete the Format objects after this call. - * The array formatsToAdopt is not itself adopted. Its - * ownership is retained by the caller. If the call fails because - * memory cannot be allocated, then the formats will be deleted - * by this method, and this object will remain unchanged. - * - *

If this format uses named arguments, the new formats are discarded - * and this format remains unchanged. - * - * @stable ICU 2.0 - * @param formatsToAdopt the format to be adopted. - * @param count the size of the array. - */ - virtual void adoptFormats(Format** formatsToAdopt, int32_t count); - - /** - * Sets subformats. - * See the class description about format numbering. - * Each item in the array is cloned into the internal array. - * If the call fails because memory cannot be allocated, then this - * object will remain unchanged. - * - *

If this format uses named arguments, the new formats are discarded - * and this format remains unchanged. - * - * @stable ICU 2.0 - * @param newFormats the new format to be set. - * @param cnt the size of the array. - */ - virtual void setFormats(const Format** newFormats, int32_t cnt); - - - /** - * Sets one subformat. - * See the class description about format numbering. - * The caller should not delete the Format object after this call. - * If the number is over the number of formats already set, - * the item will be deleted and ignored. - * - *

If this format uses named arguments, the new format is discarded - * and this format remains unchanged. - * - * @stable ICU 2.0 - * @param formatNumber index of the subformat. - * @param formatToAdopt the format to be adopted. - */ - virtual void adoptFormat(int32_t formatNumber, Format* formatToAdopt); - - /** - * Sets one subformat. - * See the class description about format numbering. - * If the number is over the number of formats already set, - * the item will be ignored. - * @param formatNumber index of the subformat. - * @param format the format to be set. - * @stable ICU 2.0 - */ - virtual void setFormat(int32_t formatNumber, const Format& format); - - /** - * Gets format names. This function returns formatNames in StringEnumerations - * which can be used with getFormat() and setFormat() to export formattable - * array from current MessageFormat to another. It is the caller's responsibility - * to delete the returned formatNames. - * @param status output param set to success/failure code. - * @stable ICU 4.0 - */ - virtual StringEnumeration* getFormatNames(UErrorCode& status); - - /** - * Gets subformat pointer for given format name. - * This function supports both named and numbered - * arguments. If numbered, the formatName is the - * corresponding UnicodeStrings (e.g. "0", "1", "2"...). - * The returned Format object should not be deleted by the caller, - * nor should the ponter of other object . The pointer and its - * contents remain valid only until the next call to any method - * of this class is made with this object. - * @param formatName the name or number specifying a format - * @param status output param set to success/failure code. - * @stable ICU 4.0 - */ - virtual Format* getFormat(const UnicodeString& formatName, UErrorCode& status); - - /** - * Sets one subformat for given format name. - * See the class description about format name. - * This function supports both named and numbered - * arguments-- if numbered, the formatName is the - * corresponding UnicodeStrings (e.g. "0", "1", "2"...). - * If there is no matched formatName or wrong type, - * the item will be ignored. - * @param formatName Name of the subformat. - * @param format the format to be set. - * @param status output param set to success/failure code. - * @stable ICU 4.0 - */ - virtual void setFormat(const UnicodeString& formatName, const Format& format, UErrorCode& status); - - /** - * Sets one subformat for given format name. - * See the class description about format name. - * This function supports both named and numbered - * arguments-- if numbered, the formatName is the - * corresponding UnicodeStrings (e.g. "0", "1", "2"...). - * If there is no matched formatName or wrong type, - * the item will be ignored. - * The caller should not delete the Format object after this call. - * @param formatName Name of the subformat. - * @param formatToAdopt Format to be adopted. - * @param status output param set to success/failure code. - * @stable ICU 4.0 - */ - virtual void adoptFormat(const UnicodeString& formatName, Format* formatToAdopt, UErrorCode& status); - - /** - * Gets an array of subformats of this object. The returned array - * should not be deleted by the caller, nor should the pointers - * within the array. The array and its contents remain valid only - * until the next call to this format. See the class description - * about format numbering. - * - * @param count output parameter to receive the size of the array - * @return an array of count Format* objects, or NULL if out of - * memory. Any or all of the array elements may be NULL. - * @stable ICU 2.0 - */ - virtual const Format** getFormats(int32_t& count) const; - - - using Format::format; - - /** - * Formats the given array of arguments into a user-readable string. - * Does not take ownership of the Formattable* array or its contents. - * - *

If this format uses named arguments, appendTo is unchanged and - * status is set to U_ILLEGAL_ARGUMENT_ERROR. - * - * @param source An array of objects to be formatted. - * @param count The number of elements of 'source'. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param ignore Not used; inherited from base class API. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - UnicodeString& format(const Formattable* source, - int32_t count, - UnicodeString& appendTo, - FieldPosition& ignore, - UErrorCode& status) const; - - /** - * Formats the given array of arguments into a user-readable string - * using the given pattern. - * - *

If this format uses named arguments, appendTo is unchanged and - * status is set to U_ILLEGAL_ARGUMENT_ERROR. - * - * @param pattern The pattern. - * @param arguments An array of objects to be formatted. - * @param count The number of elements of 'source'. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - static UnicodeString& format(const UnicodeString& pattern, - const Formattable* arguments, - int32_t count, - UnicodeString& appendTo, - UErrorCode& status); - - /** - * Formats the given array of arguments into a user-readable - * string. The array must be stored within a single Formattable - * object of type kArray. If the Formattable object type is not of - * type kArray, then returns a failing UErrorCode. - * - *

If this format uses named arguments, appendTo is unchanged and - * status is set to U_ILLEGAL_ARGUMENT_ERROR. - * - * @param obj A Formattable of type kArray containing - * arguments to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - /** - * Formats the given array of arguments into a user-defined argument name - * array. This function supports both named and numbered - * arguments-- if numbered, the formatName is the - * corresponding UnicodeStrings (e.g. "0", "1", "2"...). - * - * @param argumentNames argument name array - * @param arguments An array of objects to be formatted. - * @param count The number of elements of 'argumentNames' and - * arguments. The number of argumentNames and arguments - * must be the same. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.0 - */ - UnicodeString& format(const UnicodeString* argumentNames, - const Formattable* arguments, - int32_t count, - UnicodeString& appendTo, - UErrorCode& status) const; - /** - * Parses the given string into an array of output arguments. - * - * @param source String to be parsed. - * @param pos On input, starting position for parse. On output, - * final position after parse. Unchanged if parse - * fails. - * @param count Output parameter to receive the number of arguments - * parsed. - * @return an array of parsed arguments. The caller owns both - * the array and its contents. - * @stable ICU 2.0 - */ - virtual Formattable* parse(const UnicodeString& source, - ParsePosition& pos, - int32_t& count) const; - - /** - * Parses the given string into an array of output arguments. - * - *

If this format uses named arguments, status is set to - * U_ARGUMENT_TYPE_MISMATCH. - * - * @param source String to be parsed. - * @param count Output param to receive size of returned array. - * @param status Input/output error code. If the - * pattern cannot be parsed, set to failure code. - * @return an array of parsed arguments. The caller owns both - * the array and its contents. Returns NULL if status is not U_ZERO_ERROR. - * - * @stable ICU 2.0 - */ - virtual Formattable* parse(const UnicodeString& source, - int32_t& count, - UErrorCode& status) const; - - /** - * Parses the given string into an array of output arguments - * stored within a single Formattable of type kArray. - * - * @param source The string to be parsed into an object. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param pos On input, starting position for parse. On output, - * final position after parse. Unchanged if parse - * fails. - * @stable ICU 2.0 - */ - virtual void parseObject(const UnicodeString& source, - Formattable& result, - ParsePosition& pos) const; - - /** - * Convert an 'apostrophe-friendly' pattern into a standard - * pattern. Standard patterns treat all apostrophes as - * quotes, which is problematic in some languages, e.g. - * French, where apostrophe is commonly used. This utility - * assumes that only an unpaired apostrophe immediately before - * a brace is a true quote. Other unpaired apostrophes are paired, - * and the resulting standard pattern string is returned. - * - *

Note it is not guaranteed that the returned pattern - * is indeed a valid pattern. The only effect is to convert - * between patterns having different quoting semantics. - * - * @param pattern the 'apostrophe-friendly' patttern to convert - * @param status Input/output error code. If the pattern - * cannot be parsed, the failure code is set. - * @return the standard equivalent of the original pattern - * @stable ICU 3.4 - */ - static UnicodeString autoQuoteApostrophe(const UnicodeString& pattern, - UErrorCode& status); - - - /** - * Returns true if this MessageFormat uses named arguments, - * and false otherwise. See class description. - * - * @return true if named arguments are used. - * @stable ICU 4.0 - */ - UBool usesNamedArguments() const; - - -#ifndef U_HIDE_INTERNAL_API - /** - * This API is for ICU internal use only. - * Please do not use it. - * - * Returns argument types count in the parsed pattern. - * Used to distinguish pattern "{0} d" and "d". - * - * @return The number of formattable types in the pattern - * @internal - */ - int32_t getArgTypeCount() const; -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. - * This method is to implement a simple version of RTTI, since not all - * C++ compilers support genuine RTTI. Polymorphic operator==() and - * clone() methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const; - - /** - * Return the class ID for this class. This is useful only for - * comparing to a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .      Derived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - -#ifndef U_HIDE_INTERNAL_API - /** - * Compares two Format objects. This is used for constructing the hash - * tables. - * - * @param left pointer to a Format object. Must not be NULL. - * @param right pointer to a Format object. Must not be NULL. - * - * @return whether the two objects are the same - * @internal - */ - static UBool equalFormats(const void* left, const void* right); -#endif /* U_HIDE_INTERNAL_API */ - -private: - - Locale fLocale; - MessagePattern msgPattern; - Format** formatAliases; // see getFormats - int32_t formatAliasesCapacity; - - MessageFormat(); // default constructor not implemented - - /** - * This provider helps defer instantiation of a PluralRules object - * until we actually need to select a keyword. - * For example, if the number matches an explicit-value selector like "=1" - * we do not need any PluralRules. - */ - class U_I18N_API PluralSelectorProvider : public PluralFormat::PluralSelector { - public: - PluralSelectorProvider(const MessageFormat &mf, UPluralType type); - virtual ~PluralSelectorProvider(); - virtual UnicodeString select(void *ctx, double number, UErrorCode& ec) const; - - void reset(); - private: - const MessageFormat &msgFormat; - PluralRules* rules; - UPluralType type; - }; - - /** - * A MessageFormat formats an array of arguments. Each argument - * has an expected type, based on the pattern. For example, if - * the pattern contains the subformat "{3,number,integer}", then - * we expect argument 3 to have type Formattable::kLong. This - * array needs to grow dynamically if the MessageFormat is - * modified. - */ - Formattable::Type* argTypes; - int32_t argTypeCount; - int32_t argTypeCapacity; - - /** - * TRUE if there are different argTypes for the same argument. - * This only matters when the MessageFormat is used in the plain C (umsg_xxx) API - * where the pattern argTypes determine how the va_arg list is read. - */ - UBool hasArgTypeConflicts; - - // Variable-size array management - UBool allocateArgTypes(int32_t capacity, UErrorCode& status); - - /** - * Default Format objects used when no format is specified and a - * numeric or date argument is formatted. These are volatile - * cache objects maintained only for performance. They do not - * participate in operator=(), copy constructor(), nor - * operator==(). - */ - NumberFormat* defaultNumberFormat; - DateFormat* defaultDateFormat; - - UHashtable* cachedFormatters; - UHashtable* customFormatArgStarts; - - PluralSelectorProvider pluralProvider; - PluralSelectorProvider ordinalProvider; - - /** - * Method to retrieve default formats (or NULL on failure). - * These are semantically const, but may modify *this. - */ - const NumberFormat* getDefaultNumberFormat(UErrorCode&) const; - const DateFormat* getDefaultDateFormat(UErrorCode&) const; - - /** - * Finds the word s, in the keyword list and returns the located index. - * @param s the keyword to be searched for. - * @param list the list of keywords to be searched with. - * @return the index of the list which matches the keyword s. - */ - static int32_t findKeyword( const UnicodeString& s, - const UChar * const *list); - - /** - * Thin wrapper around the format(... AppendableWrapper ...) variant. - * Wraps the destination UnicodeString into an AppendableWrapper and - * supplies default values for some other parameters. - */ - UnicodeString& format(const Formattable* arguments, - const UnicodeString *argumentNames, - int32_t cnt, - UnicodeString& appendTo, - FieldPosition* pos, - UErrorCode& status) const; - - /** - * Formats the arguments and writes the result into the - * AppendableWrapper, updates the field position. - * - * @param msgStart Index to msgPattern part to start formatting from. - * @param plNumber NULL except when formatting a plural argument sub-message - * where a '#' is replaced by the format string for this number. - * @param arguments The formattable objects array. (Must not be NULL.) - * @param argumentNames NULL if numbered values are used. Otherwise the same - * length as "arguments", and each entry is the name of the - * corresponding argument in "arguments". - * @param cnt The length of arguments (and of argumentNames if that is not NULL). - * @param appendTo Output parameter to receive the result. - * The result string is appended to existing contents. - * @param pos Field position status. - * @param success The error code status. - */ - void format(int32_t msgStart, - const void *plNumber, - const Formattable* arguments, - const UnicodeString *argumentNames, - int32_t cnt, - AppendableWrapper& appendTo, - FieldPosition* pos, - UErrorCode& success) const; - - UnicodeString getArgName(int32_t partIndex); - - void setArgStartFormat(int32_t argStart, Format* formatter, UErrorCode& status); - - void setCustomArgStartFormat(int32_t argStart, Format* formatter, UErrorCode& status); - - int32_t nextTopLevelArgStart(int32_t partIndex) const; - - UBool argNameMatches(int32_t partIndex, const UnicodeString& argName, int32_t argNumber); - - void cacheExplicitFormats(UErrorCode& status); - - Format* createAppropriateFormat(UnicodeString& type, - UnicodeString& style, - Formattable::Type& formattableType, - UParseError& parseError, - UErrorCode& ec); - - const Formattable* getArgFromListByName(const Formattable* arguments, - const UnicodeString *argumentNames, - int32_t cnt, UnicodeString& name) const; - - Formattable* parse(int32_t msgStart, - const UnicodeString& source, - ParsePosition& pos, - int32_t& count, - UErrorCode& ec) const; - - FieldPosition* updateMetaData(AppendableWrapper& dest, int32_t prevLength, - FieldPosition* fp, const Formattable* argId) const; - - /** - * Finds the "other" sub-message. - * @param partIndex the index of the first PluralFormat argument style part. - * @return the "other" sub-message start part index. - */ - int32_t findOtherSubMessage(int32_t partIndex) const; - - /** - * Returns the ARG_START index of the first occurrence of the plural number in a sub-message. - * Returns -1 if it is a REPLACE_NUMBER. - * Returns 0 if there is neither. - */ - int32_t findFirstPluralNumberArg(int32_t msgStart, const UnicodeString &argName) const; - - Format* getCachedFormatter(int32_t argumentNumber) const; - - UnicodeString getLiteralStringUntilNextArgument(int32_t from) const; - - void copyObjects(const MessageFormat& that, UErrorCode& ec); - - void formatComplexSubMessage(int32_t msgStart, - const void *plNumber, - const Formattable* arguments, - const UnicodeString *argumentNames, - int32_t cnt, - AppendableWrapper& appendTo, - UErrorCode& success) const; - - /** - * Convenience method that ought to be in NumberFormat - */ - NumberFormat* createIntegerFormat(const Locale& locale, UErrorCode& status) const; - - /** - * Returns array of argument types in the parsed pattern - * for use in C API. Only for the use of umsg_vformat(). Not - * for public consumption. - * @param listCount Output parameter to receive the size of array - * @return The array of formattable types in the pattern - */ - const Formattable::Type* getArgTypeList(int32_t& listCount) const { - listCount = argTypeCount; - return argTypes; - } - - /** - * Resets the internal MessagePattern, and other associated caches. - */ - void resetPattern(); - - /** - * A DummyFormatter that we use solely to store a NULL value. UHash does - * not support storing NULL values. - */ - class U_I18N_API DummyFormat : public Format { - public: - virtual UBool operator==(const Format&) const; - virtual Format* clone() const; - virtual UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - UErrorCode& status) const; - virtual UnicodeString& format(const Formattable&, - UnicodeString& appendTo, - FieldPosition&, - UErrorCode& status) const; - virtual UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - virtual void parseObject(const UnicodeString&, - Formattable&, - ParsePosition&) const; - }; - - friend class MessageFormatAdapter; // getFormatTypeList() access -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _MSGFMT -//eof diff --git a/win32/include/spidermonkey/unicode/normalizer2.h b/win32/include/spidermonkey/unicode/normalizer2.h deleted file mode 100755 index 6a7668bf..00000000 --- a/win32/include/spidermonkey/unicode/normalizer2.h +++ /dev/null @@ -1,660 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2009-2013, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: normalizer2.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2009nov22 -* created by: Markus W. Scherer -*/ - -#ifndef __NORMALIZER2_H__ -#define __NORMALIZER2_H__ - -/** - * \file - * \brief C++ API: New API for Unicode Normalization. - */ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_NORMALIZATION - -#include "unicode/uniset.h" -#include "unicode/unistr.h" -#include "unicode/unorm2.h" - -U_NAMESPACE_BEGIN - -/** - * Unicode normalization functionality for standard Unicode normalization or - * for using custom mapping tables. - * All instances of this class are unmodifiable/immutable. - * Instances returned by getInstance() are singletons that must not be deleted by the caller. - * The Normalizer2 class is not intended for public subclassing. - * - * The primary functions are to produce a normalized string and to detect whether - * a string is already normalized. - * The most commonly used normalization forms are those defined in - * http://www.unicode.org/unicode/reports/tr15/ - * However, this API supports additional normalization forms for specialized purposes. - * For example, NFKC_Casefold is provided via getInstance("nfkc_cf", COMPOSE) - * and can be used in implementations of UTS #46. - * - * Not only are the standard compose and decompose modes supplied, - * but additional modes are provided as documented in the Mode enum. - * - * Some of the functions in this class identify normalization boundaries. - * At a normalization boundary, the portions of the string - * before it and starting from it do not interact and can be handled independently. - * - * The spanQuickCheckYes() stops at a normalization boundary. - * When the goal is a normalized string, then the text before the boundary - * can be copied, and the remainder can be processed with normalizeSecondAndAppend(). - * - * The hasBoundaryBefore(), hasBoundaryAfter() and isInert() functions test whether - * a character is guaranteed to be at a normalization boundary, - * regardless of context. - * This is used for moving from one normalization boundary to the next - * or preceding boundary, and for performing iterative normalization. - * - * Iterative normalization is useful when only a small portion of a - * longer string needs to be processed. - * For example, in ICU, iterative normalization is used by the NormalizationTransliterator - * (to avoid replacing already-normalized text) and ucol_nextSortKeyPart() - * (to process only the substring for which sort key bytes are computed). - * - * The set of normalization boundaries returned by these functions may not be - * complete: There may be more boundaries that could be returned. - * Different functions may return different boundaries. - * @stable ICU 4.4 - */ -class U_COMMON_API Normalizer2 : public UObject { -public: - /** - * Destructor. - * @stable ICU 4.4 - */ - ~Normalizer2(); - - /** - * Returns a Normalizer2 instance for Unicode NFC normalization. - * Same as getInstance(NULL, "nfc", UNORM2_COMPOSE, errorCode). - * Returns an unmodifiable singleton instance. Do not delete it. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 49 - */ - static const Normalizer2 * - getNFCInstance(UErrorCode &errorCode); - - /** - * Returns a Normalizer2 instance for Unicode NFD normalization. - * Same as getInstance(NULL, "nfc", UNORM2_DECOMPOSE, errorCode). - * Returns an unmodifiable singleton instance. Do not delete it. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 49 - */ - static const Normalizer2 * - getNFDInstance(UErrorCode &errorCode); - - /** - * Returns a Normalizer2 instance for Unicode NFKC normalization. - * Same as getInstance(NULL, "nfkc", UNORM2_COMPOSE, errorCode). - * Returns an unmodifiable singleton instance. Do not delete it. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 49 - */ - static const Normalizer2 * - getNFKCInstance(UErrorCode &errorCode); - - /** - * Returns a Normalizer2 instance for Unicode NFKD normalization. - * Same as getInstance(NULL, "nfkc", UNORM2_DECOMPOSE, errorCode). - * Returns an unmodifiable singleton instance. Do not delete it. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 49 - */ - static const Normalizer2 * - getNFKDInstance(UErrorCode &errorCode); - - /** - * Returns a Normalizer2 instance for Unicode NFKC_Casefold normalization. - * Same as getInstance(NULL, "nfkc_cf", UNORM2_COMPOSE, errorCode). - * Returns an unmodifiable singleton instance. Do not delete it. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 49 - */ - static const Normalizer2 * - getNFKCCasefoldInstance(UErrorCode &errorCode); - - /** - * Returns a Normalizer2 instance which uses the specified data file - * (packageName/name similar to ucnv_openPackage() and ures_open()/ResourceBundle) - * and which composes or decomposes text according to the specified mode. - * Returns an unmodifiable singleton instance. Do not delete it. - * - * Use packageName=NULL for data files that are part of ICU's own data. - * Use name="nfc" and UNORM2_COMPOSE/UNORM2_DECOMPOSE for Unicode standard NFC/NFD. - * Use name="nfkc" and UNORM2_COMPOSE/UNORM2_DECOMPOSE for Unicode standard NFKC/NFKD. - * Use name="nfkc_cf" and UNORM2_COMPOSE for Unicode standard NFKC_CF=NFKC_Casefold. - * - * @param packageName NULL for ICU built-in data, otherwise application data package name - * @param name "nfc" or "nfkc" or "nfkc_cf" or name of custom data file - * @param mode normalization mode (compose or decompose etc.) - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 4.4 - */ - static const Normalizer2 * - getInstance(const char *packageName, - const char *name, - UNormalization2Mode mode, - UErrorCode &errorCode); - - /** - * Returns the normalized form of the source string. - * @param src source string - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return normalized src - * @stable ICU 4.4 - */ - UnicodeString - normalize(const UnicodeString &src, UErrorCode &errorCode) const { - UnicodeString result; - normalize(src, result, errorCode); - return result; - } - /** - * Writes the normalized form of the source string to the destination string - * (replacing its contents) and returns the destination string. - * The source and destination strings must be different objects. - * @param src source string - * @param dest destination string; its contents is replaced with normalized src - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.4 - */ - virtual UnicodeString & - normalize(const UnicodeString &src, - UnicodeString &dest, - UErrorCode &errorCode) const = 0; - /** - * Appends the normalized form of the second string to the first string - * (merging them at the boundary) and returns the first string. - * The result is normalized if the first string was normalized. - * The first and second strings must be different objects. - * @param first string, should be normalized - * @param second string, will be normalized - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return first - * @stable ICU 4.4 - */ - virtual UnicodeString & - normalizeSecondAndAppend(UnicodeString &first, - const UnicodeString &second, - UErrorCode &errorCode) const = 0; - /** - * Appends the second string to the first string - * (merging them at the boundary) and returns the first string. - * The result is normalized if both the strings were normalized. - * The first and second strings must be different objects. - * @param first string, should be normalized - * @param second string, should be normalized - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return first - * @stable ICU 4.4 - */ - virtual UnicodeString & - append(UnicodeString &first, - const UnicodeString &second, - UErrorCode &errorCode) const = 0; - - /** - * Gets the decomposition mapping of c. - * Roughly equivalent to normalizing the String form of c - * on a UNORM2_DECOMPOSE Normalizer2 instance, but much faster, and except that this function - * returns FALSE and does not write a string - * if c does not have a decomposition mapping in this instance's data. - * This function is independent of the mode of the Normalizer2. - * @param c code point - * @param decomposition String object which will be set to c's - * decomposition mapping, if there is one. - * @return TRUE if c has a decomposition, otherwise FALSE - * @stable ICU 4.6 - */ - virtual UBool - getDecomposition(UChar32 c, UnicodeString &decomposition) const = 0; - - /** - * Gets the raw decomposition mapping of c. - * - * This is similar to the getDecomposition() method but returns the - * raw decomposition mapping as specified in UnicodeData.txt or - * (for custom data) in the mapping files processed by the gennorm2 tool. - * By contrast, getDecomposition() returns the processed, - * recursively-decomposed version of this mapping. - * - * When used on a standard NFKC Normalizer2 instance, - * getRawDecomposition() returns the Unicode Decomposition_Mapping (dm) property. - * - * When used on a standard NFC Normalizer2 instance, - * it returns the Decomposition_Mapping only if the Decomposition_Type (dt) is Canonical (Can); - * in this case, the result contains either one or two code points (=1..4 UChars). - * - * This function is independent of the mode of the Normalizer2. - * The default implementation returns FALSE. - * @param c code point - * @param decomposition String object which will be set to c's - * raw decomposition mapping, if there is one. - * @return TRUE if c has a decomposition, otherwise FALSE - * @stable ICU 49 - */ - virtual UBool - getRawDecomposition(UChar32 c, UnicodeString &decomposition) const; - - /** - * Performs pairwise composition of a & b and returns the composite if there is one. - * - * Returns a composite code point c only if c has a two-way mapping to a+b. - * In standard Unicode normalization, this means that - * c has a canonical decomposition to a+b - * and c does not have the Full_Composition_Exclusion property. - * - * This function is independent of the mode of the Normalizer2. - * The default implementation returns a negative value. - * @param a A (normalization starter) code point. - * @param b Another code point. - * @return The non-negative composite code point if there is one; otherwise a negative value. - * @stable ICU 49 - */ - virtual UChar32 - composePair(UChar32 a, UChar32 b) const; - - /** - * Gets the combining class of c. - * The default implementation returns 0 - * but all standard implementations return the Unicode Canonical_Combining_Class value. - * @param c code point - * @return c's combining class - * @stable ICU 49 - */ - virtual uint8_t - getCombiningClass(UChar32 c) const; - - /** - * Tests if the string is normalized. - * Internally, in cases where the quickCheck() method would return "maybe" - * (which is only possible for the two COMPOSE modes) this method - * resolves to "yes" or "no" to provide a definitive result, - * at the cost of doing more work in those cases. - * @param s input string - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return TRUE if s is normalized - * @stable ICU 4.4 - */ - virtual UBool - isNormalized(const UnicodeString &s, UErrorCode &errorCode) const = 0; - - /** - * Tests if the string is normalized. - * For the two COMPOSE modes, the result could be "maybe" in cases that - * would take a little more work to resolve definitively. - * Use spanQuickCheckYes() and normalizeSecondAndAppend() for a faster - * combination of quick check + normalization, to avoid - * re-checking the "yes" prefix. - * @param s input string - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return UNormalizationCheckResult - * @stable ICU 4.4 - */ - virtual UNormalizationCheckResult - quickCheck(const UnicodeString &s, UErrorCode &errorCode) const = 0; - - /** - * Returns the end of the normalized substring of the input string. - * In other words, with end=spanQuickCheckYes(s, ec); - * the substring UnicodeString(s, 0, end) - * will pass the quick check with a "yes" result. - * - * The returned end index is usually one or more characters before the - * "no" or "maybe" character: The end index is at a normalization boundary. - * (See the class documentation for more about normalization boundaries.) - * - * When the goal is a normalized string and most input strings are expected - * to be normalized already, then call this method, - * and if it returns a prefix shorter than the input string, - * copy that prefix and use normalizeSecondAndAppend() for the remainder. - * @param s input string - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return "yes" span end index - * @stable ICU 4.4 - */ - virtual int32_t - spanQuickCheckYes(const UnicodeString &s, UErrorCode &errorCode) const = 0; - - /** - * Tests if the character always has a normalization boundary before it, - * regardless of context. - * If true, then the character does not normalization-interact with - * preceding characters. - * In other words, a string containing this character can be normalized - * by processing portions before this character and starting from this - * character independently. - * This is used for iterative normalization. See the class documentation for details. - * @param c character to test - * @return TRUE if c has a normalization boundary before it - * @stable ICU 4.4 - */ - virtual UBool hasBoundaryBefore(UChar32 c) const = 0; - - /** - * Tests if the character always has a normalization boundary after it, - * regardless of context. - * If true, then the character does not normalization-interact with - * following characters. - * In other words, a string containing this character can be normalized - * by processing portions up to this character and after this - * character independently. - * This is used for iterative normalization. See the class documentation for details. - * Note that this operation may be significantly slower than hasBoundaryBefore(). - * @param c character to test - * @return TRUE if c has a normalization boundary after it - * @stable ICU 4.4 - */ - virtual UBool hasBoundaryAfter(UChar32 c) const = 0; - - /** - * Tests if the character is normalization-inert. - * If true, then the character does not change, nor normalization-interact with - * preceding or following characters. - * In other words, a string containing this character can be normalized - * by processing portions before this character and after this - * character independently. - * This is used for iterative normalization. See the class documentation for details. - * Note that this operation may be significantly slower than hasBoundaryBefore(). - * @param c character to test - * @return TRUE if c is normalization-inert - * @stable ICU 4.4 - */ - virtual UBool isInert(UChar32 c) const = 0; -}; - -/** - * Normalization filtered by a UnicodeSet. - * Normalizes portions of the text contained in the filter set and leaves - * portions not contained in the filter set unchanged. - * Filtering is done via UnicodeSet::span(..., USET_SPAN_SIMPLE). - * Not-in-the-filter text is treated as "is normalized" and "quick check yes". - * This class implements all of (and only) the Normalizer2 API. - * An instance of this class is unmodifiable/immutable but is constructed and - * must be destructed by the owner. - * @stable ICU 4.4 - */ -class U_COMMON_API FilteredNormalizer2 : public Normalizer2 { -public: - /** - * Constructs a filtered normalizer wrapping any Normalizer2 instance - * and a filter set. - * Both are aliased and must not be modified or deleted while this object - * is used. - * The filter set should be frozen; otherwise the performance will suffer greatly. - * @param n2 wrapped Normalizer2 instance - * @param filterSet UnicodeSet which determines the characters to be normalized - * @stable ICU 4.4 - */ - FilteredNormalizer2(const Normalizer2 &n2, const UnicodeSet &filterSet) : - norm2(n2), set(filterSet) {} - - /** - * Destructor. - * @stable ICU 4.4 - */ - ~FilteredNormalizer2(); - - /** - * Writes the normalized form of the source string to the destination string - * (replacing its contents) and returns the destination string. - * The source and destination strings must be different objects. - * @param src source string - * @param dest destination string; its contents is replaced with normalized src - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.4 - */ - virtual UnicodeString & - normalize(const UnicodeString &src, - UnicodeString &dest, - UErrorCode &errorCode) const; - /** - * Appends the normalized form of the second string to the first string - * (merging them at the boundary) and returns the first string. - * The result is normalized if the first string was normalized. - * The first and second strings must be different objects. - * @param first string, should be normalized - * @param second string, will be normalized - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return first - * @stable ICU 4.4 - */ - virtual UnicodeString & - normalizeSecondAndAppend(UnicodeString &first, - const UnicodeString &second, - UErrorCode &errorCode) const; - /** - * Appends the second string to the first string - * (merging them at the boundary) and returns the first string. - * The result is normalized if both the strings were normalized. - * The first and second strings must be different objects. - * @param first string, should be normalized - * @param second string, should be normalized - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return first - * @stable ICU 4.4 - */ - virtual UnicodeString & - append(UnicodeString &first, - const UnicodeString &second, - UErrorCode &errorCode) const; - - /** - * Gets the decomposition mapping of c. - * For details see the base class documentation. - * - * This function is independent of the mode of the Normalizer2. - * @param c code point - * @param decomposition String object which will be set to c's - * decomposition mapping, if there is one. - * @return TRUE if c has a decomposition, otherwise FALSE - * @stable ICU 4.6 - */ - virtual UBool - getDecomposition(UChar32 c, UnicodeString &decomposition) const; - - /** - * Gets the raw decomposition mapping of c. - * For details see the base class documentation. - * - * This function is independent of the mode of the Normalizer2. - * @param c code point - * @param decomposition String object which will be set to c's - * raw decomposition mapping, if there is one. - * @return TRUE if c has a decomposition, otherwise FALSE - * @stable ICU 49 - */ - virtual UBool - getRawDecomposition(UChar32 c, UnicodeString &decomposition) const; - - /** - * Performs pairwise composition of a & b and returns the composite if there is one. - * For details see the base class documentation. - * - * This function is independent of the mode of the Normalizer2. - * @param a A (normalization starter) code point. - * @param b Another code point. - * @return The non-negative composite code point if there is one; otherwise a negative value. - * @stable ICU 49 - */ - virtual UChar32 - composePair(UChar32 a, UChar32 b) const; - - /** - * Gets the combining class of c. - * The default implementation returns 0 - * but all standard implementations return the Unicode Canonical_Combining_Class value. - * @param c code point - * @return c's combining class - * @stable ICU 49 - */ - virtual uint8_t - getCombiningClass(UChar32 c) const; - - /** - * Tests if the string is normalized. - * For details see the Normalizer2 base class documentation. - * @param s input string - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return TRUE if s is normalized - * @stable ICU 4.4 - */ - virtual UBool - isNormalized(const UnicodeString &s, UErrorCode &errorCode) const; - /** - * Tests if the string is normalized. - * For details see the Normalizer2 base class documentation. - * @param s input string - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return UNormalizationCheckResult - * @stable ICU 4.4 - */ - virtual UNormalizationCheckResult - quickCheck(const UnicodeString &s, UErrorCode &errorCode) const; - /** - * Returns the end of the normalized substring of the input string. - * For details see the Normalizer2 base class documentation. - * @param s input string - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return "yes" span end index - * @stable ICU 4.4 - */ - virtual int32_t - spanQuickCheckYes(const UnicodeString &s, UErrorCode &errorCode) const; - - /** - * Tests if the character always has a normalization boundary before it, - * regardless of context. - * For details see the Normalizer2 base class documentation. - * @param c character to test - * @return TRUE if c has a normalization boundary before it - * @stable ICU 4.4 - */ - virtual UBool hasBoundaryBefore(UChar32 c) const; - - /** - * Tests if the character always has a normalization boundary after it, - * regardless of context. - * For details see the Normalizer2 base class documentation. - * @param c character to test - * @return TRUE if c has a normalization boundary after it - * @stable ICU 4.4 - */ - virtual UBool hasBoundaryAfter(UChar32 c) const; - - /** - * Tests if the character is normalization-inert. - * For details see the Normalizer2 base class documentation. - * @param c character to test - * @return TRUE if c is normalization-inert - * @stable ICU 4.4 - */ - virtual UBool isInert(UChar32 c) const; -private: - UnicodeString & - normalize(const UnicodeString &src, - UnicodeString &dest, - USetSpanCondition spanCondition, - UErrorCode &errorCode) const; - - UnicodeString & - normalizeSecondAndAppend(UnicodeString &first, - const UnicodeString &second, - UBool doNormalize, - UErrorCode &errorCode) const; - - const Normalizer2 &norm2; - const UnicodeSet &set; -}; - -U_NAMESPACE_END - -#endif // !UCONFIG_NO_NORMALIZATION -#endif // __NORMALIZER2_H__ diff --git a/win32/include/spidermonkey/unicode/normlzr.h b/win32/include/spidermonkey/unicode/normlzr.h deleted file mode 100755 index d529aa23..00000000 --- a/win32/include/spidermonkey/unicode/normlzr.h +++ /dev/null @@ -1,809 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************** - * COPYRIGHT: - * Copyright (c) 1996-2015, International Business Machines Corporation and - * others. All Rights Reserved. - ******************************************************************** - */ - -#ifndef NORMLZR_H -#define NORMLZR_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Unicode Normalization - */ - -#if !UCONFIG_NO_NORMALIZATION - -#include "unicode/chariter.h" -#include "unicode/normalizer2.h" -#include "unicode/unistr.h" -#include "unicode/unorm.h" -#include "unicode/uobject.h" - -U_NAMESPACE_BEGIN -/** - * Old Unicode normalization API. - * - * This API has been replaced by the Normalizer2 class and is only available - * for backward compatibility. This class simply delegates to the Normalizer2 class. - * There is one exception: The new API does not provide a replacement for Normalizer::compare(). - * - * The Normalizer class supports the standard normalization forms described in - * - * Unicode Standard Annex #15: Unicode Normalization Forms. - * - * The Normalizer class consists of two parts: - * - static functions that normalize strings or test if strings are normalized - * - a Normalizer object is an iterator that takes any kind of text and - * provides iteration over its normalized form - * - * The Normalizer class is not suitable for subclassing. - * - * For basic information about normalization forms and details about the C API - * please see the documentation in unorm.h. - * - * The iterator API with the Normalizer constructors and the non-static functions - * use a CharacterIterator as input. It is possible to pass a string which - * is then internally wrapped in a CharacterIterator. - * The input text is not normalized all at once, but incrementally where needed - * (providing efficient random access). - * This allows to pass in a large text but spend only a small amount of time - * normalizing a small part of that text. - * However, if the entire text is normalized, then the iterator will be - * slower than normalizing the entire text at once and iterating over the result. - * A possible use of the Normalizer iterator is also to report an index into the - * original text that is close to where the normalized characters come from. - * - * Important: The iterator API was cleaned up significantly for ICU 2.0. - * The earlier implementation reported the getIndex() inconsistently, - * and previous() could not be used after setIndex(), next(), first(), and current(). - * - * Normalizer allows to start normalizing from anywhere in the input text by - * calling setIndexOnly(), first(), or last(). - * Without calling any of these, the iterator will start at the beginning of the text. - * - * At any time, next() returns the next normalized code point (UChar32), - * with post-increment semantics (like CharacterIterator::next32PostInc()). - * previous() returns the previous normalized code point (UChar32), - * with pre-decrement semantics (like CharacterIterator::previous32()). - * - * current() returns the current code point - * (respectively the one at the newly set index) without moving - * the getIndex(). Note that if the text at the current position - * needs to be normalized, then these functions will do that. - * (This is why current() is not const.) - * It is more efficient to call setIndexOnly() instead, which does not - * normalize. - * - * getIndex() always refers to the position in the input text where the normalized - * code points are returned from. It does not always change with each returned - * code point. - * The code point that is returned from any of the functions - * corresponds to text at or after getIndex(), according to the - * function's iteration semantics (post-increment or pre-decrement). - * - * next() returns a code point from at or after the getIndex() - * from before the next() call. After the next() call, the getIndex() - * might have moved to where the next code point will be returned from - * (from a next() or current() call). - * This is semantically equivalent to array access with array[index++] - * (post-increment semantics). - * - * previous() returns a code point from at or after the getIndex() - * from after the previous() call. - * This is semantically equivalent to array access with array[--index] - * (pre-decrement semantics). - * - * Internally, the Normalizer iterator normalizes a small piece of text - * starting at the getIndex() and ending at a following "safe" index. - * The normalized results is stored in an internal string buffer, and - * the code points are iterated from there. - * With multiple iteration calls, this is repeated until the next piece - * of text needs to be normalized, and the getIndex() needs to be moved. - * - * The following "safe" index, the internal buffer, and the secondary - * iteration index into that buffer are not exposed on the API. - * This also means that it is currently not practical to return to - * a particular, arbitrary position in the text because one would need to - * know, and be able to set, in addition to the getIndex(), at least also the - * current index into the internal buffer. - * It is currently only possible to observe when getIndex() changes - * (with careful consideration of the iteration semantics), - * at which time the internal index will be 0. - * For example, if getIndex() is different after next() than before it, - * then the internal index is 0 and one can return to this getIndex() - * later with setIndexOnly(). - * - * Note: While the setIndex() and getIndex() refer to indices in the - * underlying Unicode input text, the next() and previous() methods - * iterate through characters in the normalized output. - * This means that there is not necessarily a one-to-one correspondence - * between characters returned by next() and previous() and the indices - * passed to and returned from setIndex() and getIndex(). - * It is for this reason that Normalizer does not implement the CharacterIterator interface. - * - * @author Laura Werner, Mark Davis, Markus Scherer - * @stable ICU 2.0 - */ -class U_COMMON_API Normalizer : public UObject { -public: -#ifndef U_HIDE_DEPRECATED_API - /** - * If DONE is returned from an iteration function that returns a code point, - * then there are no more normalization results available. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - enum { - DONE=0xffff - }; - - // Constructors - - /** - * Creates a new Normalizer object for iterating over the - * normalized form of a given string. - *

- * @param str The string to be normalized. The normalization - * will start at the beginning of the string. - * - * @param mode The normalization mode. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - Normalizer(const UnicodeString& str, UNormalizationMode mode); - - /** - * Creates a new Normalizer object for iterating over the - * normalized form of a given string. - *

- * @param str The string to be normalized. The normalization - * will start at the beginning of the string. - * - * @param length Length of the string, or -1 if NUL-terminated. - * @param mode The normalization mode. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - Normalizer(const UChar* str, int32_t length, UNormalizationMode mode); - - /** - * Creates a new Normalizer object for iterating over the - * normalized form of the given text. - *

- * @param iter The input text to be normalized. The normalization - * will start at the beginning of the string. - * - * @param mode The normalization mode. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - Normalizer(const CharacterIterator& iter, UNormalizationMode mode); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Copy constructor. - * @param copy The object to be copied. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - Normalizer(const Normalizer& copy); - - /** - * Destructor - * @deprecated ICU 56 Use Normalizer2 instead. - */ - virtual ~Normalizer(); - - - //------------------------------------------------------------------------- - // Static utility methods - //------------------------------------------------------------------------- - -#ifndef U_HIDE_DEPRECATED_API - /** - * Normalizes a UnicodeString according to the specified normalization mode. - * This is a wrapper for unorm_normalize(), using UnicodeString's. - * - * The options parameter specifies which optional - * Normalizer features are to be enabled for this operation. - * - * @param source the input string to be normalized. - * @param mode the normalization mode - * @param options the optional features to be enabled (0 for no options) - * @param result The normalized string (on output). - * @param status The error code. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - static void U_EXPORT2 normalize(const UnicodeString& source, - UNormalizationMode mode, int32_t options, - UnicodeString& result, - UErrorCode &status); - - /** - * Compose a UnicodeString. - * This is equivalent to normalize() with mode UNORM_NFC or UNORM_NFKC. - * This is a wrapper for unorm_normalize(), using UnicodeString's. - * - * The options parameter specifies which optional - * Normalizer features are to be enabled for this operation. - * - * @param source the string to be composed. - * @param compat Perform compatibility decomposition before composition. - * If this argument is FALSE, only canonical - * decomposition will be performed. - * @param options the optional features to be enabled (0 for no options) - * @param result The composed string (on output). - * @param status The error code. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - static void U_EXPORT2 compose(const UnicodeString& source, - UBool compat, int32_t options, - UnicodeString& result, - UErrorCode &status); - - /** - * Static method to decompose a UnicodeString. - * This is equivalent to normalize() with mode UNORM_NFD or UNORM_NFKD. - * This is a wrapper for unorm_normalize(), using UnicodeString's. - * - * The options parameter specifies which optional - * Normalizer features are to be enabled for this operation. - * - * @param source the string to be decomposed. - * @param compat Perform compatibility decomposition. - * If this argument is FALSE, only canonical - * decomposition will be performed. - * @param options the optional features to be enabled (0 for no options) - * @param result The decomposed string (on output). - * @param status The error code. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - static void U_EXPORT2 decompose(const UnicodeString& source, - UBool compat, int32_t options, - UnicodeString& result, - UErrorCode &status); - - /** - * Performing quick check on a string, to quickly determine if the string is - * in a particular normalization format. - * This is a wrapper for unorm_quickCheck(), using a UnicodeString. - * - * Three types of result can be returned UNORM_YES, UNORM_NO or - * UNORM_MAYBE. Result UNORM_YES indicates that the argument - * string is in the desired normalized format, UNORM_NO determines that - * argument string is not in the desired normalized format. A - * UNORM_MAYBE result indicates that a more thorough check is required, - * the user may have to put the string in its normalized form and compare the - * results. - * @param source string for determining if it is in a normalized format - * @param mode normalization format - * @param status A reference to a UErrorCode to receive any errors - * @return UNORM_YES, UNORM_NO or UNORM_MAYBE - * - * @see isNormalized - * @deprecated ICU 56 Use Normalizer2 instead. - */ - static inline UNormalizationCheckResult - quickCheck(const UnicodeString &source, UNormalizationMode mode, UErrorCode &status); - - /** - * Performing quick check on a string; same as the other version of quickCheck - * but takes an extra options parameter like most normalization functions. - * - * @param source string for determining if it is in a normalized format - * @param mode normalization format - * @param options the optional features to be enabled (0 for no options) - * @param status A reference to a UErrorCode to receive any errors - * @return UNORM_YES, UNORM_NO or UNORM_MAYBE - * - * @see isNormalized - * @deprecated ICU 56 Use Normalizer2 instead. - */ - static UNormalizationCheckResult - quickCheck(const UnicodeString &source, UNormalizationMode mode, int32_t options, UErrorCode &status); - - /** - * Test if a string is in a given normalization form. - * This is semantically equivalent to source.equals(normalize(source, mode)) . - * - * Unlike unorm_quickCheck(), this function returns a definitive result, - * never a "maybe". - * For NFD, NFKD, and FCD, both functions work exactly the same. - * For NFC and NFKC where quickCheck may return "maybe", this function will - * perform further tests to arrive at a TRUE/FALSE result. - * - * @param src String that is to be tested if it is in a normalization format. - * @param mode Which normalization form to test for. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return Boolean value indicating whether the source string is in the - * "mode" normalization form. - * - * @see quickCheck - * @deprecated ICU 56 Use Normalizer2 instead. - */ - static inline UBool - isNormalized(const UnicodeString &src, UNormalizationMode mode, UErrorCode &errorCode); - - /** - * Test if a string is in a given normalization form; same as the other version of isNormalized - * but takes an extra options parameter like most normalization functions. - * - * @param src String that is to be tested if it is in a normalization format. - * @param mode Which normalization form to test for. - * @param options the optional features to be enabled (0 for no options) - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return Boolean value indicating whether the source string is in the - * "mode" normalization form. - * - * @see quickCheck - * @deprecated ICU 56 Use Normalizer2 instead. - */ - static UBool - isNormalized(const UnicodeString &src, UNormalizationMode mode, int32_t options, UErrorCode &errorCode); - - /** - * Concatenate normalized strings, making sure that the result is normalized as well. - * - * If both the left and the right strings are in - * the normalization form according to "mode/options", - * then the result will be - * - * \code - * dest=normalize(left+right, mode, options) - * \endcode - * - * For details see unorm_concatenate in unorm.h. - * - * @param left Left source string. - * @param right Right source string. - * @param result The output string. - * @param mode The normalization mode. - * @param options A bit set of normalization options. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return result - * - * @see unorm_concatenate - * @see normalize - * @see unorm_next - * @see unorm_previous - * - * @deprecated ICU 56 Use Normalizer2 instead. - */ - static UnicodeString & - U_EXPORT2 concatenate(const UnicodeString &left, const UnicodeString &right, - UnicodeString &result, - UNormalizationMode mode, int32_t options, - UErrorCode &errorCode); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Compare two strings for canonical equivalence. - * Further options include case-insensitive comparison and - * code point order (as opposed to code unit order). - * - * Canonical equivalence between two strings is defined as their normalized - * forms (NFD or NFC) being identical. - * This function compares strings incrementally instead of normalizing - * (and optionally case-folding) both strings entirely, - * improving performance significantly. - * - * Bulk normalization is only necessary if the strings do not fulfill the FCD - * conditions. Only in this case, and only if the strings are relatively long, - * is memory allocated temporarily. - * For FCD strings and short non-FCD strings there is no memory allocation. - * - * Semantically, this is equivalent to - * strcmp[CodePointOrder](NFD(foldCase(s1)), NFD(foldCase(s2))) - * where code point order and foldCase are all optional. - * - * UAX 21 2.5 Caseless Matching specifies that for a canonical caseless match - * the case folding must be performed first, then the normalization. - * - * @param s1 First source string. - * @param s2 Second source string. - * - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Case-sensitive comparison in code unit order, and the input strings - * are quick-checked for FCD. - * - * - UNORM_INPUT_IS_FCD - * Set if the caller knows that both s1 and s2 fulfill the FCD conditions. - * If not set, the function will quickCheck for FCD - * and normalize if necessary. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_COMPARE_IGNORE_CASE - * Set to compare strings case-insensitively using case folding, - * instead of case-sensitively. - * If set, then the following case folding options are used. - * - * - Options as used with case-insensitive comparisons, currently: - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * (see u_strCaseCompare for details) - * - * - regular normalization options shifted left by UNORM_COMPARE_NORM_OPTIONS_SHIFT - * - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return <0 or 0 or >0 as usual for string comparisons - * - * @see unorm_compare - * @see normalize - * @see UNORM_FCD - * @see u_strCompare - * @see u_strCaseCompare - * - * @stable ICU 2.2 - */ - static inline int32_t - compare(const UnicodeString &s1, const UnicodeString &s2, - uint32_t options, - UErrorCode &errorCode); - -#ifndef U_HIDE_DEPRECATED_API - //------------------------------------------------------------------------- - // Iteration API - //------------------------------------------------------------------------- - - /** - * Return the current character in the normalized text. - * current() may need to normalize some text at getIndex(). - * The getIndex() is not changed. - * - * @return the current normalized code point - * @deprecated ICU 56 Use Normalizer2 instead. - */ - UChar32 current(void); - - /** - * Return the first character in the normalized text. - * This is equivalent to setIndexOnly(startIndex()) followed by next(). - * (Post-increment semantics.) - * - * @return the first normalized code point - * @deprecated ICU 56 Use Normalizer2 instead. - */ - UChar32 first(void); - - /** - * Return the last character in the normalized text. - * This is equivalent to setIndexOnly(endIndex()) followed by previous(). - * (Pre-decrement semantics.) - * - * @return the last normalized code point - * @deprecated ICU 56 Use Normalizer2 instead. - */ - UChar32 last(void); - - /** - * Return the next character in the normalized text. - * (Post-increment semantics.) - * If the end of the text has already been reached, DONE is returned. - * The DONE value could be confused with a U+FFFF non-character code point - * in the text. If this is possible, you can test getIndex()startIndex() || first()!=DONE). (Calling first() will change - * the iterator state!) - * - * The C API unorm_previous() is more efficient and does not have this ambiguity. - * - * @return the previous normalized code point - * @deprecated ICU 56 Use Normalizer2 instead. - */ - UChar32 previous(void); - - /** - * Set the iteration position in the input text that is being normalized, - * without any immediate normalization. - * After setIndexOnly(), getIndex() will return the same index that is - * specified here. - * - * @param index the desired index in the input text. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - void setIndexOnly(int32_t index); - - /** - * Reset the index to the beginning of the text. - * This is equivalent to setIndexOnly(startIndex)). - * @deprecated ICU 56 Use Normalizer2 instead. - */ - void reset(void); - - /** - * Retrieve the current iteration position in the input text that is - * being normalized. - * - * A following call to next() will return a normalized code point from - * the input text at or after this index. - * - * After a call to previous(), getIndex() will point at or before the - * position in the input text where the normalized code point - * was returned from with previous(). - * - * @return the current index in the input text - * @deprecated ICU 56 Use Normalizer2 instead. - */ - int32_t getIndex(void) const; - - /** - * Retrieve the index of the start of the input text. This is the begin index - * of the CharacterIterator or the start (i.e. index 0) of the string - * over which this Normalizer is iterating. - * - * @return the smallest index in the input text where the Normalizer operates - * @deprecated ICU 56 Use Normalizer2 instead. - */ - int32_t startIndex(void) const; - - /** - * Retrieve the index of the end of the input text. This is the end index - * of the CharacterIterator or the length of the string - * over which this Normalizer is iterating. - * This end index is exclusive, i.e., the Normalizer operates only on characters - * before this index. - * - * @return the first index in the input text where the Normalizer does not operate - * @deprecated ICU 56 Use Normalizer2 instead. - */ - int32_t endIndex(void) const; - - /** - * Returns TRUE when both iterators refer to the same character in the same - * input text. - * - * @param that a Normalizer object to compare this one to - * @return comparison result - * @deprecated ICU 56 Use Normalizer2 instead. - */ - UBool operator==(const Normalizer& that) const; - - /** - * Returns FALSE when both iterators refer to the same character in the same - * input text. - * - * @param that a Normalizer object to compare this one to - * @return comparison result - * @deprecated ICU 56 Use Normalizer2 instead. - */ - inline UBool operator!=(const Normalizer& that) const; - - /** - * Returns a pointer to a new Normalizer that is a clone of this one. - * The caller is responsible for deleting the new clone. - * @return a pointer to a new Normalizer - * @deprecated ICU 56 Use Normalizer2 instead. - */ - Normalizer* clone(void) const; - - /** - * Generates a hash code for this iterator. - * - * @return the hash code - * @deprecated ICU 56 Use Normalizer2 instead. - */ - int32_t hashCode(void) const; - - //------------------------------------------------------------------------- - // Property access methods - //------------------------------------------------------------------------- - - /** - * Set the normalization mode for this object. - *

- * Note:If the normalization mode is changed while iterating - * over a string, calls to {@link #next() } and {@link #previous() } may - * return previously buffers characters in the old normalization mode - * until the iteration is able to re-sync at the next base character. - * It is safest to call {@link #setIndexOnly }, {@link #reset() }, - * {@link #setText }, {@link #first() }, - * {@link #last() }, etc. after calling setMode. - *

- * @param newMode the new mode for this Normalizer. - * @see #getUMode - * @deprecated ICU 56 Use Normalizer2 instead. - */ - void setMode(UNormalizationMode newMode); - - /** - * Return the normalization mode for this object. - * - * This is an unusual name because there used to be a getMode() that - * returned a different type. - * - * @return the mode for this Normalizer - * @see #setMode - * @deprecated ICU 56 Use Normalizer2 instead. - */ - UNormalizationMode getUMode(void) const; - - /** - * Set options that affect this Normalizer's operation. - * Options do not change the basic composition or decomposition operation - * that is being performed, but they control whether - * certain optional portions of the operation are done. - * Currently the only available option is obsolete. - * - * It is possible to specify multiple options that are all turned on or off. - * - * @param option the option(s) whose value is/are to be set. - * @param value the new setting for the option. Use TRUE to - * turn the option(s) on and FALSE to turn it/them off. - * - * @see #getOption - * @deprecated ICU 56 Use Normalizer2 instead. - */ - void setOption(int32_t option, - UBool value); - - /** - * Determine whether an option is turned on or off. - * If multiple options are specified, then the result is TRUE if any - * of them are set. - *

- * @param option the option(s) that are to be checked - * @return TRUE if any of the option(s) are set - * @see #setOption - * @deprecated ICU 56 Use Normalizer2 instead. - */ - UBool getOption(int32_t option) const; - - /** - * Set the input text over which this Normalizer will iterate. - * The iteration position is set to the beginning. - * - * @param newText a string that replaces the current input text - * @param status a UErrorCode - * @deprecated ICU 56 Use Normalizer2 instead. - */ - void setText(const UnicodeString& newText, - UErrorCode &status); - - /** - * Set the input text over which this Normalizer will iterate. - * The iteration position is set to the beginning. - * - * @param newText a CharacterIterator object that replaces the current input text - * @param status a UErrorCode - * @deprecated ICU 56 Use Normalizer2 instead. - */ - void setText(const CharacterIterator& newText, - UErrorCode &status); - - /** - * Set the input text over which this Normalizer will iterate. - * The iteration position is set to the beginning. - * - * @param newText a string that replaces the current input text - * @param length the length of the string, or -1 if NUL-terminated - * @param status a UErrorCode - * @deprecated ICU 56 Use Normalizer2 instead. - */ - void setText(const UChar* newText, - int32_t length, - UErrorCode &status); - /** - * Copies the input text into the UnicodeString argument. - * - * @param result Receives a copy of the text under iteration. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - void getText(UnicodeString& result); - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * @returns a UClassID for this class. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - static UClassID U_EXPORT2 getStaticClassID(); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * @return a UClassID for the actual class. - * @deprecated ICU 56 Use Normalizer2 instead. - */ - virtual UClassID getDynamicClassID() const; - -private: - //------------------------------------------------------------------------- - // Private functions - //------------------------------------------------------------------------- - - Normalizer(); // default constructor not implemented - Normalizer &operator=(const Normalizer &that); // assignment operator not implemented - - // Private utility methods for iteration - // For documentation, see the source code - UBool nextNormalize(); - UBool previousNormalize(); - - void init(); - void clearBuffer(void); - - //------------------------------------------------------------------------- - // Private data - //------------------------------------------------------------------------- - - FilteredNormalizer2*fFilteredNorm2; // owned if not NULL - const Normalizer2 *fNorm2; // not owned; may be equal to fFilteredNorm2 - UNormalizationMode fUMode; // deprecated - int32_t fOptions; - - // The input text and our position in it - CharacterIterator *text; - - // The normalization buffer is the result of normalization - // of the source in [currentIndex..nextIndex[ . - int32_t currentIndex, nextIndex; - - // A buffer for holding intermediate results - UnicodeString buffer; - int32_t bufferPos; -}; - -//------------------------------------------------------------------------- -// Inline implementations -//------------------------------------------------------------------------- - -#ifndef U_HIDE_DEPRECATED_API -inline UBool -Normalizer::operator!= (const Normalizer& other) const -{ return ! operator==(other); } - -inline UNormalizationCheckResult -Normalizer::quickCheck(const UnicodeString& source, - UNormalizationMode mode, - UErrorCode &status) { - return quickCheck(source, mode, 0, status); -} - -inline UBool -Normalizer::isNormalized(const UnicodeString& source, - UNormalizationMode mode, - UErrorCode &status) { - return isNormalized(source, mode, 0, status); -} -#endif /* U_HIDE_DEPRECATED_API */ - -inline int32_t -Normalizer::compare(const UnicodeString &s1, const UnicodeString &s2, - uint32_t options, - UErrorCode &errorCode) { - // all argument checking is done in unorm_compare - return unorm_compare(s1.getBuffer(), s1.length(), - s2.getBuffer(), s2.length(), - options, - &errorCode); -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_NORMALIZATION */ - -#endif // NORMLZR_H diff --git a/win32/include/spidermonkey/unicode/numfmt.h b/win32/include/spidermonkey/unicode/numfmt.h deleted file mode 100755 index d46e1fd6..00000000 --- a/win32/include/spidermonkey/unicode/numfmt.h +++ /dev/null @@ -1,1180 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 1997-2016, International Business Machines Corporation and others. -* All Rights Reserved. -******************************************************************************** -* -* File NUMFMT.H -* -* Modification History: -* -* Date Name Description -* 02/19/97 aliu Converted from java. -* 03/18/97 clhuang Updated per C++ implementation. -* 04/17/97 aliu Changed DigitCount to int per code review. -* 07/20/98 stephen JDK 1.2 sync up. Added scientific support. -* Changed naming conventions to match C++ guidelines -* Derecated Java style constants (eg, INTEGER_FIELD) -******************************************************************************** -*/ - -#ifndef NUMFMT_H -#define NUMFMT_H - - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Abstract base class for all number formats. - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/unistr.h" -#include "unicode/format.h" -#include "unicode/unum.h" // UNumberFormatStyle -#include "unicode/locid.h" -#include "unicode/stringpiece.h" -#include "unicode/curramt.h" -#include "unicode/udisplaycontext.h" - -class NumberFormatTest; - -U_NAMESPACE_BEGIN - -class SharedNumberFormat; - -#if !UCONFIG_NO_SERVICE -class NumberFormatFactory; -class StringEnumeration; -#endif - -/** - * - * Abstract base class for all number formats. Provides interface for - * formatting and parsing a number. Also provides methods for - * determining which locales have number formats, and what their names - * are. - * \headerfile unicode/numfmt.h "unicode/numfmt.h" - *

- * NumberFormat helps you to format and parse numbers for any locale. - * Your code can be completely independent of the locale conventions - * for decimal points, thousands-separators, or even the particular - * decimal digits used, or whether the number format is even decimal. - *

- * To format a number for the current Locale, use one of the static - * factory methods: - * \code - * #include - * #include "unicode/numfmt.h" - * #include "unicode/unistr.h" - * #include "unicode/ustream.h" - * using namespace std; - * - * int main() { - * double myNumber = 7.0; - * UnicodeString myString; - * UErrorCode success = U_ZERO_ERROR; - * NumberFormat* nf = NumberFormat::createInstance(success); - * nf->format(myNumber, myString); - * cout << " Example 1: " << myString << endl; - * } - * \endcode - * Note that there are additional factory methods within subclasses of - * NumberFormat. - *

- * If you are formatting multiple numbers, it is more efficient to get - * the format and use it multiple times so that the system doesn't - * have to fetch the information about the local language and country - * conventions multiple times. - * \code - * UnicodeString myString; - * UErrorCode success = U_ZERO_ERROR; - * NumberFormat *nf = NumberFormat::createInstance( success ); - * for (int32_t number: {123, 3333, -1234567}) { - * nf->format(number, myString); - * myString += "; "; - * } - * cout << " Example 2: " << myString << endl; - * \endcode - * To format a number for a different Locale, specify it in the - * call to \c createInstance(). - * \code - * nf = NumberFormat::createInstance(Locale::getFrench(), success); - * \endcode - * You can use a \c NumberFormat to parse also. - * \code - * UErrorCode success; - * Formattable result(-999); // initialized with error code - * nf->parse(myString, result, success); - * \endcode - * Use \c createInstance() to get the normal number format for a \c Locale. - * There are other static factory methods available. Use \c createCurrencyInstance() - * to get the currency number format for that country. Use \c createPercentInstance() - * to get a format for displaying percentages. With this format, a - * fraction from 0.53 is displayed as 53%. - *

- * The type of number formatting can be specified by passing a 'style' parameter to \c createInstance(). - * For example, use\n - * \c createInstance(locale, UNUM_DECIMAL, errorCode) to get the normal number format,\n - * \c createInstance(locale, UNUM_PERCENT, errorCode) to get a format for displaying percentage,\n - * \c createInstance(locale, UNUM_SCIENTIFIC, errorCode) to get a format for displaying scientific number,\n - * \c createInstance(locale, UNUM_CURRENCY, errorCode) to get the currency number format, - * in which the currency is represented by its symbol, for example, "$3.00".\n - * \c createInstance(locale, UNUM_CURRENCY_ISO, errorCode) to get the currency number format, - * in which the currency is represented by its ISO code, for example "USD3.00".\n - * \c createInstance(locale, UNUM_CURRENCY_PLURAL, errorCode) to get the currency number format, - * in which the currency is represented by its full name in plural format, - * for example, "3.00 US dollars" or "1.00 US dollar". - *

- * You can also control the display of numbers with such methods as - * \c getMinimumFractionDigits(). If you want even more control over the - * format or parsing, or want to give your users more control, you can - * try dynamic_casting the \c NumberFormat you get from the factory methods to a - * \c DecimalFormat. This will work for the vast majority of - * countries; just remember to test for NULL in case you - * encounter an unusual one. - *

- * You can also use forms of the parse and format methods with - * \c ParsePosition and \c FieldPosition to allow you to: - *

    - *
  • (a) progressively parse through pieces of a string. - *
  • (b) align the decimal point and other areas. - *
- * For example, you can align numbers in two ways. - *

- * If you are using a monospaced font with spacing for alignment, you - * can pass the \c FieldPosition in your format call, with field = - * \c UNUM_INTEGER_FIELD. On output, \c getEndIndex will be set to the offset - * between the last character of the integer and the decimal. Add - * (desiredSpaceCount - getEndIndex) spaces at the front of the - * string. - *

- * If you are using proportional fonts, instead of padding with - * spaces, measure the width of the string in pixels from the start to - * getEndIndex. Then move the pen by (desiredPixelWidth - - * widthToAlignmentPoint) before drawing the text. It also works - * where there is no decimal, but possibly additional characters at - * the end, e.g. with parentheses in negative numbers: "(12)" for -12. - *

- * User subclasses are not supported. While clients may write - * subclasses, such code will not necessarily work and will not be - * guaranteed to work stably from release to release. - * - * @stable ICU 2.0 - */ -class U_I18N_API NumberFormat : public Format { -public: - /** - * Alignment Field constants used to construct a FieldPosition object. - * Signifies that the position of the integer part or fraction part of - * a formatted number should be returned. - * - * Note: as of ICU 4.4, the values in this enum have been extended to - * support identification of all number format fields, not just those - * pertaining to alignment. - * - * These constants are provided for backwards compatibility only. - * Please use the C style constants defined in the header file unum.h. - * - * @see FieldPosition - * @stable ICU 2.0 - */ - enum EAlignmentFields { - /** @stable ICU 2.0 */ - kIntegerField = UNUM_INTEGER_FIELD, - /** @stable ICU 2.0 */ - kFractionField = UNUM_FRACTION_FIELD, - /** @stable ICU 2.0 */ - kDecimalSeparatorField = UNUM_DECIMAL_SEPARATOR_FIELD, - /** @stable ICU 2.0 */ - kExponentSymbolField = UNUM_EXPONENT_SYMBOL_FIELD, - /** @stable ICU 2.0 */ - kExponentSignField = UNUM_EXPONENT_SIGN_FIELD, - /** @stable ICU 2.0 */ - kExponentField = UNUM_EXPONENT_FIELD, - /** @stable ICU 2.0 */ - kGroupingSeparatorField = UNUM_GROUPING_SEPARATOR_FIELD, - /** @stable ICU 2.0 */ - kCurrencyField = UNUM_CURRENCY_FIELD, - /** @stable ICU 2.0 */ - kPercentField = UNUM_PERCENT_FIELD, - /** @stable ICU 2.0 */ - kPermillField = UNUM_PERMILL_FIELD, - /** @stable ICU 2.0 */ - kSignField = UNUM_SIGN_FIELD, - - /** - * These constants are provided for backwards compatibility only. - * Please use the constants defined in the header file unum.h. - */ - /** @stable ICU 2.0 */ - INTEGER_FIELD = UNUM_INTEGER_FIELD, - /** @stable ICU 2.0 */ - FRACTION_FIELD = UNUM_FRACTION_FIELD - }; - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~NumberFormat(); - - /** - * Return true if the given Format objects are semantically equal. - * Objects of different subclasses are considered unequal. - * @return true if the given Format objects are semantically equal. - * @stable ICU 2.0 - */ - virtual UBool operator==(const Format& other) const; - - - using Format::format; - - /** - * Format an object to produce a string. This method handles - * Formattable objects with numeric types. If the Formattable - * object type is not a numeric type, then it returns a failing - * UErrorCode. - * - * @param obj The object to format. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - /** - * Format an object to produce a string. This method handles - * Formattable objects with numeric types. If the Formattable - * object type is not a numeric type, then it returns a failing - * UErrorCode. - * - * @param obj The object to format. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. Can be - * NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Parse a string to produce an object. This methods handles - * parsing of numeric strings into Formattable objects with numeric - * types. - *

- * Before calling, set parse_pos.index to the offset you want to - * start parsing at in the source. After calling, parse_pos.index - * indicates the position after the successfully parsed text. If - * an error occurs, parse_pos.index is unchanged. - *

- * When parsing, leading whitespace is discarded (with successful - * parse), while trailing whitespace is left as is. - *

- * See Format::parseObject() for more. - * - * @param source The string to be parsed into an object. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param parse_pos The position to start parsing at. Upon return - * this param is set to the position after the - * last character successfully parsed. If the - * source is not parsed successfully, this param - * will remain unchanged. - * @return A newly created Formattable* object, or NULL - * on failure. The caller owns this and should - * delete it when done. - * @stable ICU 2.0 - */ - virtual void parseObject(const UnicodeString& source, - Formattable& result, - ParsePosition& parse_pos) const; - - /** - * Format a double number. These methods call the NumberFormat - * pure virtual format() methods with the default FieldPosition. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - UnicodeString& format( double number, - UnicodeString& appendTo) const; - - /** - * Format a long number. These methods call the NumberFormat - * pure virtual format() methods with the default FieldPosition. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - UnicodeString& format( int32_t number, - UnicodeString& appendTo) const; - - /** - * Format an int64 number. These methods call the NumberFormat - * pure virtual format() methods with the default FieldPosition. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.8 - */ - UnicodeString& format( int64_t number, - UnicodeString& appendTo) const; - - /** - * Format a double number. Concrete subclasses must implement - * these pure virtual methods. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPosition& pos) const = 0; - /** - * Format a double number. By default, the parent function simply - * calls the base class and does not return an error status. - * Therefore, the status may be ignored in some subclasses. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status error status - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode &status) const; - /** - * Format a double number. Subclasses must implement - * this method. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - /** - * Format a long number. Concrete subclasses must implement - * these pure virtual methods. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPosition& pos) const = 0; - - /** - * Format a long number. Concrete subclasses may override - * this function to provide status return. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status the output status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode &status) const; - - /** - * Format an int32 number. Subclasses must implement - * this method. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - /** - * Format an int64 number. (Not abstract to retain compatibility - * with earlier releases, however subclasses should override this - * method as it just delegates to format(int32_t number...); - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.8 - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& appendTo, - FieldPosition& pos) const; - - /** - * Format an int64 number. (Not abstract to retain compatibility - * with earlier releases, however subclasses should override this - * method as it just delegates to format(int32_t number...); - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - /** - * Format an int64 number. Subclasses must implement - * this method. - * - * @param number The value to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format a decimal number. Subclasses must implement - * this method. The syntax of the unformatted number is a "numeric string" - * as defined in the Decimal Arithmetic Specification, available at - * http://speleotrove.com/decimal - * - * @param number The unformatted number, as a string, to be formatted. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * Can be NULL. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format(StringPiece number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; -public: - /** - * Format a decimal number. - * The number is a DigitList wrapper onto a floating point decimal number. - * The default implementation in NumberFormat converts the decimal number - * to a double and formats that. Subclasses of NumberFormat that want - * to specifically handle big decimal numbers must override this method. - * class DecimalFormat does so. - * - * @param number The number, a DigitList format Decimal Floating Point. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(const DigitList &number, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - /** - * Format a decimal number. - * The number is a DigitList wrapper onto a floating point decimal number. - * The default implementation in NumberFormat converts the decimal number - * to a double and formats that. Subclasses of NumberFormat that want - * to specifically handle big decimal numbers must override this method. - * class DecimalFormat does so. - * - * @param number The number, a DigitList format Decimal Floating Point. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @internal - */ - virtual UnicodeString& format(const DigitList &number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - -public: - - /** - * Return a long if possible (e.g. within range LONG_MAX, - * LONG_MAX], and with no decimals), otherwise a double. If - * IntegerOnly is set, will stop at a decimal point (or equivalent; - * e.g. for rational numbers "1 2/3", will stop after the 1). - *

- * If no object can be parsed, index is unchanged, and NULL is - * returned. - *

- * This is a pure virtual which concrete subclasses must implement. - * - * @param text The text to be parsed. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param parsePosition The position to start parsing at on input. - * On output, moved to after the last successfully - * parse character. On parse failure, does not change. - * @stable ICU 2.0 - */ - virtual void parse(const UnicodeString& text, - Formattable& result, - ParsePosition& parsePosition) const = 0; - - /** - * Parse a string as a numeric value, and return a Formattable - * numeric object. This method parses integers only if IntegerOnly - * is set. - * - * @param text The text to be parsed. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param status Output parameter set to a failure error code - * when a failure occurs. - * @see NumberFormat::isParseIntegerOnly - * @stable ICU 2.0 - */ - virtual void parse(const UnicodeString& text, - Formattable& result, - UErrorCode& status) const; - - /** - * Parses text from the given string as a currency amount. Unlike - * the parse() method, this method will attempt to parse a generic - * currency name, searching for a match of this object's locale's - * currency display names, or for a 3-letter ISO currency code. - * This method will fail if this format is not a currency format, - * that is, if it does not contain the currency pattern symbol - * (U+00A4) in its prefix or suffix. - * - * @param text the string to parse - * @param pos input-output position; on input, the position within text - * to match; must have 0 <= pos.getIndex() < text.length(); - * on output, the position after the last matched character. - * If the parse fails, the position in unchanged upon output. - * @return if parse succeeds, a pointer to a newly-created CurrencyAmount - * object (owned by the caller) containing information about - * the parsed currency; if parse fails, this is NULL. - * @stable ICU 49 - */ - virtual CurrencyAmount* parseCurrency(const UnicodeString& text, - ParsePosition& pos) const; - - /** - * Return true if this format will parse numbers as integers - * only. For example in the English locale, with ParseIntegerOnly - * true, the string "1234." would be parsed as the integer value - * 1234 and parsing would stop at the "." character. Of course, - * the exact format accepted by the parse operation is locale - * dependant and determined by sub-classes of NumberFormat. - * @return true if this format will parse numbers as integers - * only. - * @stable ICU 2.0 - */ - UBool isParseIntegerOnly(void) const; - - /** - * Sets whether or not numbers should be parsed as integers only. - * @param value set True, this format will parse numbers as integers - * only. - * @see isParseIntegerOnly - * @stable ICU 2.0 - */ - virtual void setParseIntegerOnly(UBool value); - - /** - * Sets whether lenient parsing should be enabled (it is off by default). - * - * @param enable \c TRUE if lenient parsing should be used, - * \c FALSE otherwise. - * @stable ICU 4.8 - */ - virtual void setLenient(UBool enable); - - /** - * Returns whether lenient parsing is enabled (it is off by default). - * - * @return \c TRUE if lenient parsing is enabled, - * \c FALSE otherwise. - * @see #setLenient - * @stable ICU 4.8 - */ - virtual UBool isLenient(void) const; - - /** - * Create a default style NumberFormat for the current default locale. - * The default formatting style is locale dependent. - * @stable ICU 2.0 - */ - static NumberFormat* U_EXPORT2 createInstance(UErrorCode&); - - /** - * Create a default style NumberFormat for the specified locale. - * The default formatting style is locale dependent. - * @param inLocale the given locale. - * @stable ICU 2.0 - */ - static NumberFormat* U_EXPORT2 createInstance(const Locale& inLocale, - UErrorCode&); - - /** - * Create a specific style NumberFormat for the specified locale. - * @param desiredLocale the given locale. - * @param style the given style. - * @param errorCode Output param filled with success/failure status. - * @return A new NumberFormat instance. - * @stable ICU 4.8 - */ - static NumberFormat* U_EXPORT2 createInstance(const Locale& desiredLocale, - UNumberFormatStyle style, - UErrorCode& errorCode); - -#ifndef U_HIDE_INTERNAL_API - - /** - * ICU use only. - * Creates NumberFormat instance without using the cache. - * @internal - */ - static NumberFormat* internalCreateInstance( - const Locale& desiredLocale, - UNumberFormatStyle style, - UErrorCode& errorCode); - - /** - * ICU use only. - * Returns handle to the shared, cached NumberFormat instance for given - * locale. On success, caller must call removeRef() on returned value - * once it is done with the shared instance. - * @internal - */ - static const SharedNumberFormat* U_EXPORT2 createSharedInstance( - const Locale& inLocale, UNumberFormatStyle style, UErrorCode& status); - -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Returns a currency format for the current default locale. - * @stable ICU 2.0 - */ - static NumberFormat* U_EXPORT2 createCurrencyInstance(UErrorCode&); - - /** - * Returns a currency format for the specified locale. - * @param inLocale the given locale. - * @stable ICU 2.0 - */ - static NumberFormat* U_EXPORT2 createCurrencyInstance(const Locale& inLocale, - UErrorCode&); - - /** - * Returns a percentage format for the current default locale. - * @stable ICU 2.0 - */ - static NumberFormat* U_EXPORT2 createPercentInstance(UErrorCode&); - - /** - * Returns a percentage format for the specified locale. - * @param inLocale the given locale. - * @stable ICU 2.0 - */ - static NumberFormat* U_EXPORT2 createPercentInstance(const Locale& inLocale, - UErrorCode&); - - /** - * Returns a scientific format for the current default locale. - * @stable ICU 2.0 - */ - static NumberFormat* U_EXPORT2 createScientificInstance(UErrorCode&); - - /** - * Returns a scientific format for the specified locale. - * @param inLocale the given locale. - * @stable ICU 2.0 - */ - static NumberFormat* U_EXPORT2 createScientificInstance(const Locale& inLocale, - UErrorCode&); - - /** - * Get the set of Locales for which NumberFormats are installed. - * @param count Output param to receive the size of the locales - * @stable ICU 2.0 - */ - static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count); - -#if !UCONFIG_NO_SERVICE - /** - * Register a new NumberFormatFactory. The factory will be adopted. - * Because ICU may choose to cache NumberFormat objects internally, - * this must be called at application startup, prior to any calls to - * NumberFormat::createInstance to avoid undefined behavior. - * @param toAdopt the NumberFormatFactory instance to be adopted - * @param status the in/out status code, no special meanings are assigned - * @return a registry key that can be used to unregister this factory - * @stable ICU 2.6 - */ - static URegistryKey U_EXPORT2 registerFactory(NumberFormatFactory* toAdopt, UErrorCode& status); - - /** - * Unregister a previously-registered NumberFormatFactory using the key returned from the - * register call. Key becomes invalid after a successful call and should not be used again. - * The NumberFormatFactory corresponding to the key will be deleted. - * Because ICU may choose to cache NumberFormat objects internally, - * this should be called during application shutdown, after all calls to - * NumberFormat::createInstance to avoid undefined behavior. - * @param key the registry key returned by a previous call to registerFactory - * @param status the in/out status code, no special meanings are assigned - * @return TRUE if the factory for the key was successfully unregistered - * @stable ICU 2.6 - */ - static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status); - - /** - * Return a StringEnumeration over the locales available at the time of the call, - * including registered locales. - * @return a StringEnumeration over the locales available at the time of the call - * @stable ICU 2.6 - */ - static StringEnumeration* U_EXPORT2 getAvailableLocales(void); -#endif /* UCONFIG_NO_SERVICE */ - - /** - * Returns true if grouping is used in this format. For example, - * in the English locale, with grouping on, the number 1234567 - * might be formatted as "1,234,567". The grouping separator as - * well as the size of each group is locale dependant and is - * determined by sub-classes of NumberFormat. - * @see setGroupingUsed - * @stable ICU 2.0 - */ - UBool isGroupingUsed(void) const; - - /** - * Set whether or not grouping will be used in this format. - * @param newValue True, grouping will be used in this format. - * @see getGroupingUsed - * @stable ICU 2.0 - */ - virtual void setGroupingUsed(UBool newValue); - - /** - * Returns the maximum number of digits allowed in the integer portion of a - * number. - * @return the maximum number of digits allowed in the integer portion of a - * number. - * @see setMaximumIntegerDigits - * @stable ICU 2.0 - */ - int32_t getMaximumIntegerDigits(void) const; - - /** - * Sets the maximum number of digits allowed in the integer portion of a - * number. maximumIntegerDigits must be >= minimumIntegerDigits. If the - * new value for maximumIntegerDigits is less than the current value - * of minimumIntegerDigits, then minimumIntegerDigits will also be set to - * the new value. - * - * @param newValue the new value for the maximum number of digits - * allowed in the integer portion of a number. - * @see getMaximumIntegerDigits - * @stable ICU 2.0 - */ - virtual void setMaximumIntegerDigits(int32_t newValue); - - /** - * Returns the minimum number of digits allowed in the integer portion of a - * number. - * @return the minimum number of digits allowed in the integer portion of a - * number. - * @see setMinimumIntegerDigits - * @stable ICU 2.0 - */ - int32_t getMinimumIntegerDigits(void) const; - - /** - * Sets the minimum number of digits allowed in the integer portion of a - * number. minimumIntegerDigits must be <= maximumIntegerDigits. If the - * new value for minimumIntegerDigits exceeds the current value - * of maximumIntegerDigits, then maximumIntegerDigits will also be set to - * the new value. - * @param newValue the new value to be set. - * @see getMinimumIntegerDigits - * @stable ICU 2.0 - */ - virtual void setMinimumIntegerDigits(int32_t newValue); - - /** - * Returns the maximum number of digits allowed in the fraction portion of a - * number. - * @return the maximum number of digits allowed in the fraction portion of a - * number. - * @see setMaximumFractionDigits - * @stable ICU 2.0 - */ - int32_t getMaximumFractionDigits(void) const; - - /** - * Sets the maximum number of digits allowed in the fraction portion of a - * number. maximumFractionDigits must be >= minimumFractionDigits. If the - * new value for maximumFractionDigits is less than the current value - * of minimumFractionDigits, then minimumFractionDigits will also be set to - * the new value. - * @param newValue the new value to be set. - * @see getMaximumFractionDigits - * @stable ICU 2.0 - */ - virtual void setMaximumFractionDigits(int32_t newValue); - - /** - * Returns the minimum number of digits allowed in the fraction portion of a - * number. - * @return the minimum number of digits allowed in the fraction portion of a - * number. - * @see setMinimumFractionDigits - * @stable ICU 2.0 - */ - int32_t getMinimumFractionDigits(void) const; - - /** - * Sets the minimum number of digits allowed in the fraction portion of a - * number. minimumFractionDigits must be <= maximumFractionDigits. If the - * new value for minimumFractionDigits exceeds the current value - * of maximumFractionDigits, then maximumIntegerDigits will also be set to - * the new value - * @param newValue the new value to be set. - * @see getMinimumFractionDigits - * @stable ICU 2.0 - */ - virtual void setMinimumFractionDigits(int32_t newValue); - - /** - * Sets the currency used to display currency - * amounts. This takes effect immediately, if this format is a - * currency format. If this format is not a currency format, then - * the currency is used if and when this object becomes a - * currency format. - * @param theCurrency a 3-letter ISO code indicating new currency - * to use. It need not be null-terminated. May be the empty - * string or NULL to indicate no currency. - * @param ec input-output error code - * @stable ICU 3.0 - */ - virtual void setCurrency(const UChar* theCurrency, UErrorCode& ec); - - /** - * Gets the currency used to display currency - * amounts. This may be an empty string for some subclasses. - * @return a 3-letter null-terminated ISO code indicating - * the currency in use, or a pointer to the empty string. - * @stable ICU 2.6 - */ - const UChar* getCurrency() const; - - /** - * Set a particular UDisplayContext value in the formatter, such as - * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. - * @param value The UDisplayContext value to set. - * @param status Input/output status. If at entry this indicates a failure - * status, the function will do nothing; otherwise this will be - * updated with any new status from the function. - * @stable ICU 53 - */ - virtual void setContext(UDisplayContext value, UErrorCode& status); - - /** - * Get the formatter's UDisplayContext value for the specified UDisplayContextType, - * such as UDISPCTX_TYPE_CAPITALIZATION. - * @param type The UDisplayContextType whose value to return - * @param status Input/output status. If at entry this indicates a failure - * status, the function will do nothing; otherwise this will be - * updated with any new status from the function. - * @return The UDisplayContextValue for the specified type. - * @stable ICU 53 - */ - virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const; - -public: - - /** - * Return the class ID for this class. This is useful for - * comparing to a return value from getDynamicClassID(). Note that, - * because NumberFormat is an abstract base class, no fully constructed object - * will have the class ID returned by NumberFormat::getStaticClassID(). - * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. - * This method is to implement a simple version of RTTI, since not all - * C++ compilers support genuine RTTI. Polymorphic operator==() and - * clone() methods call this method. - *

- * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const = 0; - -protected: - - /** - * Default constructor for subclass use only. - * @stable ICU 2.0 - */ - NumberFormat(); - - /** - * Copy constructor. - * @stable ICU 2.0 - */ - NumberFormat(const NumberFormat&); - - /** - * Assignment operator. - * @stable ICU 2.0 - */ - NumberFormat& operator=(const NumberFormat&); - - /** - * Returns the currency in effect for this formatter. Subclasses - * should override this method as needed. Unlike getCurrency(), - * this method should never return "". - * @result output parameter for null-terminated result, which must - * have a capacity of at least 4 - * @internal - */ - virtual void getEffectiveCurrency(UChar* result, UErrorCode& ec) const; - -#ifndef U_HIDE_INTERNAL_API - /** - * Creates the specified number format style of the desired locale. - * If mustBeDecimalFormat is TRUE, then the returned pointer is - * either a DecimalFormat or it is NULL. - * @internal - */ - static NumberFormat* makeInstance(const Locale& desiredLocale, - UNumberFormatStyle style, - UBool mustBeDecimalFormat, - UErrorCode& errorCode); -#endif /* U_HIDE_INTERNAL_API */ - -private: - - static UBool isStyleSupported(UNumberFormatStyle style); - - /** - * Creates the specified decimal format style of the desired locale. - * @param desiredLocale the given locale. - * @param style the given style. - * @param errorCode Output param filled with success/failure status. - * @return A new NumberFormat instance. - */ - static NumberFormat* makeInstance(const Locale& desiredLocale, - UNumberFormatStyle style, - UErrorCode& errorCode); - - UBool fGroupingUsed; - int32_t fMaxIntegerDigits; - int32_t fMinIntegerDigits; - int32_t fMaxFractionDigits; - int32_t fMinFractionDigits; - - protected: - /** \internal */ - static const int32_t gDefaultMaxIntegerDigits; - /** \internal */ - static const int32_t gDefaultMinIntegerDigits; - - private: - UBool fParseIntegerOnly; - UBool fLenient; // TRUE => lenient parse is enabled - - // ISO currency code - UChar fCurrency[4]; - - UDisplayContext fCapitalizationContext; - - friend class ICUNumberFormatFactory; // access to makeInstance - friend class ICUNumberFormatService; - friend class ::NumberFormatTest; // access to isStyleSupported() -}; - -#if !UCONFIG_NO_SERVICE -/** - * A NumberFormatFactory is used to register new number formats. The factory - * should be able to create any of the predefined formats for each locale it - * supports. When registered, the locales it supports extend or override the - * locale already supported by ICU. - * - * @stable ICU 2.6 - */ -class U_I18N_API NumberFormatFactory : public UObject { -public: - - /** - * Destructor - * @stable ICU 3.0 - */ - virtual ~NumberFormatFactory(); - - /** - * Return true if this factory will be visible. Default is true. - * If not visible, the locales supported by this factory will not - * be listed by getAvailableLocales. - * @stable ICU 2.6 - */ - virtual UBool visible(void) const = 0; - - /** - * Return the locale names directly supported by this factory. The number of names - * is returned in count; - * @stable ICU 2.6 - */ - virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const = 0; - - /** - * Return a number format of the appropriate type. If the locale - * is not supported, return null. If the locale is supported, but - * the type is not provided by this service, return null. Otherwise - * return an appropriate instance of NumberFormat. - * @stable ICU 2.6 - */ - virtual NumberFormat* createFormat(const Locale& loc, UNumberFormatStyle formatType) = 0; -}; - -/** - * A NumberFormatFactory that supports a single locale. It can be visible or invisible. - * @stable ICU 2.6 - */ -class U_I18N_API SimpleNumberFormatFactory : public NumberFormatFactory { -protected: - /** - * True if the locale supported by this factory is visible. - * @stable ICU 2.6 - */ - const UBool _visible; - - /** - * The locale supported by this factory, as a UnicodeString. - * @stable ICU 2.6 - */ - UnicodeString _id; - -public: - /** - * @stable ICU 2.6 - */ - SimpleNumberFormatFactory(const Locale& locale, UBool visible = TRUE); - - /** - * @stable ICU 3.0 - */ - virtual ~SimpleNumberFormatFactory(); - - /** - * @stable ICU 2.6 - */ - virtual UBool visible(void) const; - - /** - * @stable ICU 2.6 - */ - virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const; -}; -#endif /* #if !UCONFIG_NO_SERVICE */ - -// ------------------------------------- - -inline UBool -NumberFormat::isParseIntegerOnly() const -{ - return fParseIntegerOnly; -} - -inline UBool -NumberFormat::isLenient() const -{ - return fLenient; -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _NUMFMT -//eof diff --git a/win32/include/spidermonkey/unicode/numsys.h b/win32/include/spidermonkey/unicode/numsys.h deleted file mode 100755 index 4cc083f6..00000000 --- a/win32/include/spidermonkey/unicode/numsys.h +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2010-2014, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -* -* -* File NUMSYS.H -* -* Modification History:* -* Date Name Description -* -******************************************************************************** -*/ - -#ifndef NUMSYS -#define NUMSYS - -#include "unicode/utypes.h" - -/** - * \def NUMSYS_NAME_CAPACITY - * Size of a numbering system name. - * @internal - */ -#define NUMSYS_NAME_CAPACITY 8 - - -/** - * \file - * \brief C++ API: NumberingSystem object - */ - -#if !UCONFIG_NO_FORMATTING - - -#include "unicode/format.h" -#include "unicode/uobject.h" - -U_NAMESPACE_BEGIN - -/** - * Defines numbering systems. A numbering system describes the scheme by which - * numbers are to be presented to the end user. In its simplest form, a numbering - * system describes the set of digit characters that are to be used to display - * numbers, such as Western digits, Thai digits, Arabic-Indic digits, etc., in a - * positional numbering system with a specified radix (typically 10). - * More complicated numbering systems are algorithmic in nature, and require use - * of an RBNF formatter ( rule based number formatter ), in order to calculate - * the characters to be displayed for a given number. Examples of algorithmic - * numbering systems include Roman numerals, Chinese numerals, and Hebrew numerals. - * Formatting rules for many commonly used numbering systems are included in - * the ICU package, based on the numbering system rules defined in CLDR. - * Alternate numbering systems can be specified to a locale by using the - * numbers locale keyword. - */ - -class U_I18N_API NumberingSystem : public UObject { -public: - - /** - * Default Constructor. - * - * @stable ICU 4.2 - */ - NumberingSystem(); - - /** - * Copy constructor. - * @stable ICU 4.2 - */ - NumberingSystem(const NumberingSystem& other); - - /** - * Destructor. - * @stable ICU 4.2 - */ - virtual ~NumberingSystem(); - - /** - * Create the default numbering system associated with the specified locale. - * @param inLocale The given locale. - * @param status ICU status - * @stable ICU 4.2 - */ - static NumberingSystem* U_EXPORT2 createInstance(const Locale & inLocale, UErrorCode& status); - - /** - * Create the default numbering system associated with the default locale. - * @stable ICU 4.2 - */ - static NumberingSystem* U_EXPORT2 createInstance(UErrorCode& status); - - /** - * Create a numbering system using the specified radix, type, and description. - * @param radix The radix (base) for this numbering system. - * @param isAlgorithmic TRUE if the numbering system is algorithmic rather than numeric. - * @param description The string representing the set of digits used in a numeric system, or the name of the RBNF - * ruleset to be used in an algorithmic system. - * @param status ICU status - * @stable ICU 4.2 - */ - static NumberingSystem* U_EXPORT2 createInstance(int32_t radix, UBool isAlgorithmic, const UnicodeString& description, UErrorCode& status ); - - /** - * Return a StringEnumeration over all the names of numbering systems known to ICU. - * @stable ICU 4.2 - */ - - static StringEnumeration * U_EXPORT2 getAvailableNames(UErrorCode& status); - - /** - * Create a numbering system from one of the predefined numbering systems specified - * by CLDR and known to ICU, such as "latn", "arabext", or "hanidec"; the full list - * is returned by unumsys_openAvailableNames. Note that some of the names listed at - * http://unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml - e.g. - * default, native, traditional, finance - do not identify specific numbering systems, - * but rather key values that may only be used as part of a locale, which in turn - * defines how they are mapped to a specific numbering system such as "latn" or "hant". - * @param name The name of the numbering system. - * @param status ICU status - * @stable ICU 4.2 - */ - static NumberingSystem* U_EXPORT2 createInstanceByName(const char* name, UErrorCode& status); - - - /** - * Returns the radix of this numbering system. Simple positional numbering systems - * typically have radix 10, but might have a radix of e.g. 16 for hexadecimal. The - * radix is less well-defined for non-positional algorithmic systems. - * @stable ICU 4.2 - */ - int32_t getRadix() const; - - /** - * Returns the name of this numbering system if it was created using one of the predefined names - * known to ICU. Otherwise, returns NULL. - * The predefined names are identical to the numbering system names as defined by - * the BCP47 definition in Unicode CLDR. - * See also, http://www.unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml - * @stable ICU 4.6 - */ - const char * getName() const; - - /** - * Returns the description string of this numbering system. For simple - * positional systems this is the ordered string of digits (with length matching - * the radix), e.g. "\u3007\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D" - * for "hanidec"; it would be "0123456789ABCDEF" for hexadecimal. For - * algorithmic systems this is the name of the RBNF ruleset used for formatting, - * e.g. "zh/SpelloutRules/%spellout-cardinal" for "hans" or "%greek-upper" for - * "grek". - * @stable ICU 4.2 - */ - virtual UnicodeString getDescription() const; - - - - /** - * Returns TRUE if the given numbering system is algorithmic - * - * @return TRUE if the numbering system is algorithmic. - * Otherwise, return FALSE. - * @stable ICU 4.2 - */ - UBool isAlgorithmic() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 4.2 - * - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 4.2 - */ - virtual UClassID getDynamicClassID() const; - - -private: - UnicodeString desc; - int32_t radix; - UBool algorithmic; - char name[NUMSYS_NAME_CAPACITY+1]; - - void setRadix(int32_t radix); - - void setAlgorithmic(UBool algorithmic); - - void setDesc(UnicodeString desc); - - void setName(const char* name); - - static UBool isValidDigitString(const UnicodeString &str); - - UBool hasContiguousDecimalDigits() const; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _NUMSYS -//eof diff --git a/win32/include/spidermonkey/unicode/parseerr.h b/win32/include/spidermonkey/unicode/parseerr.h deleted file mode 100755 index 71aef40e..00000000 --- a/win32/include/spidermonkey/unicode/parseerr.h +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1999-2005, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* Date Name Description -* 03/14/00 aliu Creation. -* 06/27/00 aliu Change from C++ class to C struct -********************************************************************** -*/ -#ifndef PARSEERR_H -#define PARSEERR_H - -#include "unicode/utypes.h" - - -/** - * \file - * \brief C API: Parse Error Information - */ -/** - * The capacity of the context strings in UParseError. - * @stable ICU 2.0 - */ -enum { U_PARSE_CONTEXT_LEN = 16 }; - -/** - * A UParseError struct is used to returned detailed information about - * parsing errors. It is used by ICU parsing engines that parse long - * rules, patterns, or programs, where the text being parsed is long - * enough that more information than a UErrorCode is needed to - * localize the error. - * - *

The line, offset, and context fields are optional; parsing - * engines may choose not to use to use them. - * - *

The preContext and postContext strings include some part of the - * context surrounding the error. If the source text is "let for=7" - * and "for" is the error (e.g., because it is a reserved word), then - * some examples of what a parser might produce are the following: - * - *

- * preContext   postContext
- * ""           ""            The parser does not support context
- * "let "       "=7"          Pre- and post-context only
- * "let "       "for=7"       Pre- and post-context and error text
- * ""           "for"         Error text only
- * 
- * - *

Examples of engines which use UParseError (or may use it in the - * future) are Transliterator, RuleBasedBreakIterator, and - * RegexPattern. - * - * @stable ICU 2.0 - */ -typedef struct UParseError { - - /** - * The line on which the error occured. If the parser uses this - * field, it sets it to the line number of the source text line on - * which the error appears, which will be be a value >= 1. If the - * parse does not support line numbers, the value will be <= 0. - * @stable ICU 2.0 - */ - int32_t line; - - /** - * The character offset to the error. If the line field is >= 1, - * then this is the offset from the start of the line. Otherwise, - * this is the offset from the start of the text. If the parser - * does not support this field, it will have a value < 0. - * @stable ICU 2.0 - */ - int32_t offset; - - /** - * Textual context before the error. Null-terminated. The empty - * string if not supported by parser. - * @stable ICU 2.0 - */ - UChar preContext[U_PARSE_CONTEXT_LEN]; - - /** - * The error itself and/or textual context after the error. - * Null-terminated. The empty string if not supported by parser. - * @stable ICU 2.0 - */ - UChar postContext[U_PARSE_CONTEXT_LEN]; - -} UParseError; - -#endif diff --git a/win32/include/spidermonkey/unicode/parsepos.h b/win32/include/spidermonkey/unicode/parsepos.h deleted file mode 100755 index 1f74ebda..00000000 --- a/win32/include/spidermonkey/unicode/parsepos.h +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -* Copyright (C) 1997-2005, International Business Machines Corporation and others. All Rights Reserved. -******************************************************************************* -* -* File PARSEPOS.H -* -* Modification History: -* -* Date Name Description -* 07/09/97 helena Converted from java. -* 07/17/98 stephen Added errorIndex support. -* 05/11/99 stephen Cleaned up. -******************************************************************************* -*/ - -#ifndef PARSEPOS_H -#define PARSEPOS_H - -#include "unicode/utypes.h" -#include "unicode/uobject.h" - - -U_NAMESPACE_BEGIN - -/** - * \file - * \brief C++ API: Canonical Iterator - */ -/** - * ParsePosition is a simple class used by Format - * and its subclasses to keep track of the current position during parsing. - * The parseObject method in the various Format - * classes requires a ParsePosition object as an argument. - * - *

- * By design, as you parse through a string with different formats, - * you can use the same ParsePosition, since the index parameter - * records the current position. - * - * The ParsePosition class is not suitable for subclassing. - * - * @version 1.3 10/30/97 - * @author Mark Davis, Helena Shih - * @see java.text.Format - */ - -class U_COMMON_API ParsePosition : public UObject { -public: - /** - * Default constructor, the index starts with 0 as default. - * @stable ICU 2.0 - */ - ParsePosition() - : UObject(), - index(0), - errorIndex(-1) - {} - - /** - * Create a new ParsePosition with the given initial index. - * @param newIndex the new text offset. - * @stable ICU 2.0 - */ - ParsePosition(int32_t newIndex) - : UObject(), - index(newIndex), - errorIndex(-1) - {} - - /** - * Copy constructor - * @param copy the object to be copied from. - * @stable ICU 2.0 - */ - ParsePosition(const ParsePosition& copy) - : UObject(copy), - index(copy.index), - errorIndex(copy.errorIndex) - {} - - /** - * Destructor - * @stable ICU 2.0 - */ - virtual ~ParsePosition(); - - /** - * Assignment operator - * @stable ICU 2.0 - */ - ParsePosition& operator=(const ParsePosition& copy); - - /** - * Equality operator. - * @return TRUE if the two parse positions are equal, FALSE otherwise. - * @stable ICU 2.0 - */ - UBool operator==(const ParsePosition& that) const; - - /** - * Equality operator. - * @return TRUE if the two parse positions are not equal, FALSE otherwise. - * @stable ICU 2.0 - */ - UBool operator!=(const ParsePosition& that) const; - - /** - * Clone this object. - * Clones can be used concurrently in multiple threads. - * If an error occurs, then NULL is returned. - * The caller must delete the clone. - * - * @return a clone of this object - * - * @see getDynamicClassID - * @stable ICU 2.8 - */ - ParsePosition *clone() const; - - /** - * Retrieve the current parse position. On input to a parse method, this - * is the index of the character at which parsing will begin; on output, it - * is the index of the character following the last character parsed. - * @return the current index. - * @stable ICU 2.0 - */ - int32_t getIndex(void) const; - - /** - * Set the current parse position. - * @param index the new index. - * @stable ICU 2.0 - */ - void setIndex(int32_t index); - - /** - * Set the index at which a parse error occurred. Formatters - * should set this before returning an error code from their - * parseObject method. The default value is -1 if this is not - * set. - * @stable ICU 2.0 - */ - void setErrorIndex(int32_t ei); - - /** - * Retrieve the index at which an error occurred, or -1 if the - * error index has not been set. - * @stable ICU 2.0 - */ - int32_t getErrorIndex(void) const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - -private: - /** - * Input: the place you start parsing. - *
Output: position where the parse stopped. - * This is designed to be used serially, - * with each call setting index up for the next one. - */ - int32_t index; - - /** - * The index at which a parse error occurred. - */ - int32_t errorIndex; - -}; - -inline ParsePosition& -ParsePosition::operator=(const ParsePosition& copy) -{ - index = copy.index; - errorIndex = copy.errorIndex; - return *this; -} - -inline UBool -ParsePosition::operator==(const ParsePosition& copy) const -{ - if(index != copy.index || errorIndex != copy.errorIndex) - return FALSE; - else - return TRUE; -} - -inline UBool -ParsePosition::operator!=(const ParsePosition& copy) const -{ - return !operator==(copy); -} - -inline int32_t -ParsePosition::getIndex() const -{ - return index; -} - -inline void -ParsePosition::setIndex(int32_t offset) -{ - this->index = offset; -} - -inline int32_t -ParsePosition::getErrorIndex() const -{ - return errorIndex; -} - -inline void -ParsePosition::setErrorIndex(int32_t ei) -{ - this->errorIndex = ei; -} -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/platform.h b/win32/include/spidermonkey/unicode/platform.h deleted file mode 100755 index b42bef83..00000000 --- a/win32/include/spidermonkey/unicode/platform.h +++ /dev/null @@ -1,862 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 1997-2016, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* -* FILE NAME : platform.h -* -* Date Name Description -* 05/13/98 nos Creation (content moved here from ptypes.h). -* 03/02/99 stephen Added AS400 support. -* 03/30/99 stephen Added Linux support. -* 04/13/99 stephen Reworked for autoconf. -****************************************************************************** -*/ - -#ifndef _PLATFORM_H -#define _PLATFORM_H - -#include "unicode/uconfig.h" -#include "unicode/uvernum.h" - -/** - * \file - * \brief Basic types for the platform. - * - * This file used to be generated by autoconf/configure. - * Starting with ICU 49, platform.h is a normal source file, - * to simplify cross-compiling and working with non-autoconf/make build systems. - * - * When a value in this file does not work on a platform, then please - * try to derive it from the U_PLATFORM value - * (for which we might need a new value constant in rare cases) - * and/or from other macros that are predefined by the compiler - * or defined in standard (POSIX or platform or compiler) headers. - * - * As a temporary workaround, you can add an explicit #define for some macros - * before it is first tested, or add an equivalent -D macro definition - * to the compiler's command line. - * - * Note: Some compilers provide ways to show the predefined macros. - * For example, with gcc you can compile an empty .c file and have the compiler - * print the predefined macros with - * \code - * gcc -E -dM -x c /dev/null | sort - * \endcode - * (You can provide an actual empty .c file rather than /dev/null. - * -x c++ is for C++.) - */ - -/** - * Define some things so that they can be documented. - * @internal - */ -#ifdef U_IN_DOXYGEN -/* - * Problem: "platform.h:335: warning: documentation for unknown define U_HAVE_STD_STRING found." means that U_HAVE_STD_STRING is not documented. - * Solution: #define any defines for non @internal API here, so that they are visible in the docs. If you just set PREDEFINED in Doxyfile.in, they won't be documented. - */ - -/* None for now. */ -#endif - -/** - * \def U_PLATFORM - * The U_PLATFORM macro defines the platform we're on. - * - * We used to define one different, value-less macro per platform. - * That made it hard to know the set of relevant platforms and macros, - * and hard to deal with variants of platforms. - * - * Starting with ICU 49, we define platforms as numeric macros, - * with ranges of values for related platforms and their variants. - * The U_PLATFORM macro is set to one of these values. - * - * Historical note from the Solaris Wikipedia article: - * AT&T and Sun collaborated on a project to merge the most popular Unix variants - * on the market at that time: BSD, System V, and Xenix. - * This became Unix System V Release 4 (SVR4). - * - * @internal - */ - -/** Unknown platform. @internal */ -#define U_PF_UNKNOWN 0 -/** Windows @internal */ -#define U_PF_WINDOWS 1000 -/** MinGW. Windows, calls to Win32 API, but using GNU gcc and binutils. @internal */ -#define U_PF_MINGW 1800 -/** - * Cygwin. Windows, calls to cygwin1.dll for Posix functions, - * using MSVC or GNU gcc and binutils. - * @internal - */ -#define U_PF_CYGWIN 1900 -/* Reserve 2000 for U_PF_UNIX? */ -/** HP-UX is based on UNIX System V. @internal */ -#define U_PF_HPUX 2100 -/** Solaris is a Unix operating system based on SVR4. @internal */ -#define U_PF_SOLARIS 2600 -/** BSD is a UNIX operating system derivative. @internal */ -#define U_PF_BSD 3000 -/** AIX is based on UNIX System V Releases and 4.3 BSD. @internal */ -#define U_PF_AIX 3100 -/** IRIX is based on UNIX System V with BSD extensions. @internal */ -#define U_PF_IRIX 3200 -/** - * Darwin is a POSIX-compliant operating system, composed of code developed by Apple, - * as well as code derived from NeXTSTEP, BSD, and other projects, - * built around the Mach kernel. - * Darwin forms the core set of components upon which Mac OS X, Apple TV, and iOS are based. - * (Original description modified from WikiPedia.) - * @internal - */ -#define U_PF_DARWIN 3500 -/** iPhone OS (iOS) is a derivative of Mac OS X. @internal */ -#define U_PF_IPHONE 3550 -/** QNX is a commercial Unix-like real-time operating system related to BSD. @internal */ -#define U_PF_QNX 3700 -/** Linux is a Unix-like operating system. @internal */ -#define U_PF_LINUX 4000 -/** - * Native Client is pretty close to Linux. - * See https://developer.chrome.com/native-client and - * http://www.chromium.org/nativeclient - * @internal - */ -#define U_PF_BROWSER_NATIVE_CLIENT 4020 -/** Android is based on Linux. @internal */ -#define U_PF_ANDROID 4050 -/* Maximum value for Linux-based platform is 4499 */ -/** z/OS is the successor to OS/390 which was the successor to MVS. @internal */ -#define U_PF_OS390 9000 -/** "IBM i" is the current name of what used to be i5/OS and earlier OS/400. @internal */ -#define U_PF_OS400 9400 - -#ifdef U_PLATFORM - /* Use the predefined value. */ -#elif defined(__MINGW32__) -# define U_PLATFORM U_PF_MINGW -#elif defined(__CYGWIN__) -# define U_PLATFORM U_PF_CYGWIN -#elif defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) -# define U_PLATFORM U_PF_WINDOWS -#elif defined(__ANDROID__) -# define U_PLATFORM U_PF_ANDROID - /* Android wchar_t support depends on the API level. */ -# include -#elif defined(__native_client__) -# define U_PLATFORM U_PF_BROWSER_NATIVE_CLIENT -#elif defined(linux) || defined(__linux__) || defined(__linux) -# define U_PLATFORM U_PF_LINUX -#elif defined(__APPLE__) && defined(__MACH__) -# include -# if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE /* variant of TARGET_OS_MAC */ -# define U_PLATFORM U_PF_IPHONE -# else -# define U_PLATFORM U_PF_DARWIN -# endif -#elif defined(BSD) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__MirBSD__) -# if defined(__FreeBSD__) -# include -# endif -# define U_PLATFORM U_PF_BSD -#elif defined(sun) || defined(__sun) - /* Check defined(__SVR4) || defined(__svr4__) to distinguish Solaris from SunOS? */ -# define U_PLATFORM U_PF_SOLARIS -# if defined(__GNUC__) - /* Solaris/GCC needs this header file to get the proper endianness. Normally, this - * header file is included with stddef.h but on Solairs/GCC, the GCC version of stddef.h - * is included which does not include this header file. - */ -# include -# endif -#elif defined(_AIX) || defined(__TOS_AIX__) -# define U_PLATFORM U_PF_AIX -#elif defined(_hpux) || defined(hpux) || defined(__hpux) -# define U_PLATFORM U_PF_HPUX -#elif defined(sgi) || defined(__sgi) -# define U_PLATFORM U_PF_IRIX -#elif defined(__QNX__) || defined(__QNXNTO__) -# define U_PLATFORM U_PF_QNX -#elif defined(__TOS_MVS__) -# define U_PLATFORM U_PF_OS390 -#elif defined(__OS400__) || defined(__TOS_OS400__) -# define U_PLATFORM U_PF_OS400 -#else -# define U_PLATFORM U_PF_UNKNOWN -#endif - -/** - * \def CYGWINMSVC - * Defined if this is Windows with Cygwin, but using MSVC rather than gcc. - * Otherwise undefined. - * @internal - */ -/* Commented out because this is already set in mh-cygwin-msvc -#if U_PLATFORM == U_PF_CYGWIN && defined(_MSC_VER) -# define CYGWINMSVC -#endif -*/ - -/** - * \def U_PLATFORM_USES_ONLY_WIN32_API - * Defines whether the platform uses only the Win32 API. - * Set to 1 for Windows/MSVC and MinGW but not Cygwin. - * @internal - */ -#ifdef U_PLATFORM_USES_ONLY_WIN32_API - /* Use the predefined value. */ -#elif (U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_MINGW) || defined(CYGWINMSVC) -# define U_PLATFORM_USES_ONLY_WIN32_API 1 -#else - /* Cygwin implements POSIX. */ -# define U_PLATFORM_USES_ONLY_WIN32_API 0 -#endif - -/** - * \def U_PLATFORM_HAS_WIN32_API - * Defines whether the Win32 API is available on the platform. - * Set to 1 for Windows/MSVC, MinGW and Cygwin. - * @internal - */ -#ifdef U_PLATFORM_HAS_WIN32_API - /* Use the predefined value. */ -#elif U_PF_WINDOWS <= U_PLATFORM && U_PLATFORM <= U_PF_CYGWIN -# define U_PLATFORM_HAS_WIN32_API 1 -#else -# define U_PLATFORM_HAS_WIN32_API 0 -#endif - -/** - * \def U_PLATFORM_IMPLEMENTS_POSIX - * Defines whether the platform implements (most of) the POSIX API. - * Set to 1 for Cygwin and most other platforms. - * @internal - */ -#ifdef U_PLATFORM_IMPLEMENTS_POSIX - /* Use the predefined value. */ -#elif U_PLATFORM_USES_ONLY_WIN32_API -# define U_PLATFORM_IMPLEMENTS_POSIX 0 -#else -# define U_PLATFORM_IMPLEMENTS_POSIX 1 -#endif - -/** - * \def U_PLATFORM_IS_LINUX_BASED - * Defines whether the platform is Linux or one of its derivatives. - * @internal - */ -#ifdef U_PLATFORM_IS_LINUX_BASED - /* Use the predefined value. */ -#elif U_PF_LINUX <= U_PLATFORM && U_PLATFORM <= 4499 -# define U_PLATFORM_IS_LINUX_BASED 1 -#else -# define U_PLATFORM_IS_LINUX_BASED 0 -#endif - -/** - * \def U_PLATFORM_IS_DARWIN_BASED - * Defines whether the platform is Darwin or one of its derivatives. - * @internal - */ -#ifdef U_PLATFORM_IS_DARWIN_BASED - /* Use the predefined value. */ -#elif U_PF_DARWIN <= U_PLATFORM && U_PLATFORM <= U_PF_IPHONE -# define U_PLATFORM_IS_DARWIN_BASED 1 -#else -# define U_PLATFORM_IS_DARWIN_BASED 0 -#endif - -/** - * \def U_HAVE_STDINT_H - * Defines whether stdint.h is available. It is a C99 standard header. - * We used to include inttypes.h which includes stdint.h but we usually do not need - * the additional definitions from inttypes.h. - * @internal - */ -#ifdef U_HAVE_STDINT_H - /* Use the predefined value. */ -#elif U_PLATFORM_USES_ONLY_WIN32_API -# if defined(__BORLANDC__) || U_PLATFORM == U_PF_MINGW || (defined(_MSC_VER) && _MSC_VER>=1600) - /* Windows Visual Studio 9 and below do not have stdint.h & inttypes.h, but VS 2010 adds them. */ -# define U_HAVE_STDINT_H 1 -# else -# define U_HAVE_STDINT_H 0 -# endif -#elif U_PLATFORM == U_PF_SOLARIS - /* Solaris has inttypes.h but not stdint.h. */ -# define U_HAVE_STDINT_H 0 -#elif U_PLATFORM == U_PF_AIX && !defined(_AIX51) && defined(_POWER) - /* PPC AIX <= 4.3 has inttypes.h but not stdint.h. */ -# define U_HAVE_STDINT_H 0 -#else -# define U_HAVE_STDINT_H 1 -#endif - -/** - * \def U_HAVE_INTTYPES_H - * Defines whether inttypes.h is available. It is a C99 standard header. - * We include inttypes.h where it is available but stdint.h is not. - * @internal - */ -#ifdef U_HAVE_INTTYPES_H - /* Use the predefined value. */ -#elif U_PLATFORM == U_PF_SOLARIS - /* Solaris has inttypes.h but not stdint.h. */ -# define U_HAVE_INTTYPES_H 1 -#elif U_PLATFORM == U_PF_AIX && !defined(_AIX51) && defined(_POWER) - /* PPC AIX <= 4.3 has inttypes.h but not stdint.h. */ -# define U_HAVE_INTTYPES_H 1 -#else - /* Most platforms have both inttypes.h and stdint.h, or neither. */ -# define U_HAVE_INTTYPES_H U_HAVE_STDINT_H -#endif - -/** - * \def U_IOSTREAM_SOURCE - * Defines what support for C++ streams is available. - * - * If U_IOSTREAM_SOURCE is set to 199711, then <iostream> is available - * (the ISO/IEC C++ FDIS was published in November 1997), and then - * one should qualify streams using the std namespace in ICU header - * files. - * Starting with ICU 49, this is the only supported version. - * - * If U_IOSTREAM_SOURCE is set to 198506, then <iostream.h> is - * available instead (in June 1985 Stroustrup published - * "An Extensible I/O Facility for C++" at the summer USENIX conference). - * Starting with ICU 49, this version is not supported any more. - * - * If U_IOSTREAM_SOURCE is 0 (or any value less than 199711), - * then C++ streams are not available and - * support for them will be silently suppressed in ICU. - * - * @internal - */ -#ifndef U_IOSTREAM_SOURCE -#define U_IOSTREAM_SOURCE 199711 -#endif - -/** - * \def U_HAVE_STD_STRING - * Defines whether the standard C++ (STL) <string> header is available. - * @internal - */ -#ifdef U_HAVE_STD_STRING - /* Use the predefined value. */ -#else -# define U_HAVE_STD_STRING 1 -#endif - -/*===========================================================================*/ -/** @{ Compiler and environment features */ -/*===========================================================================*/ - -/** - * \def U_GCC_MAJOR_MINOR - * Indicates whether the compiler is gcc (test for != 0), - * and if so, contains its major (times 100) and minor version numbers. - * If the compiler is not gcc, then U_GCC_MAJOR_MINOR == 0. - * - * For example, for testing for whether we have gcc, and whether it's 4.6 or higher, - * use "#if U_GCC_MAJOR_MINOR >= 406". - * @internal - */ -#ifdef __GNUC__ -# define U_GCC_MAJOR_MINOR (__GNUC__ * 100 + __GNUC_MINOR__) -#else -# define U_GCC_MAJOR_MINOR 0 -#endif - -/** - * \def U_IS_BIG_ENDIAN - * Determines the endianness of the platform. - * @internal - */ -#ifdef U_IS_BIG_ENDIAN - /* Use the predefined value. */ -#elif defined(BYTE_ORDER) && defined(BIG_ENDIAN) -# define U_IS_BIG_ENDIAN (BYTE_ORDER == BIG_ENDIAN) -#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) - /* gcc */ -# define U_IS_BIG_ENDIAN (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) -#elif defined(__BIG_ENDIAN__) || defined(_BIG_ENDIAN) -# define U_IS_BIG_ENDIAN 1 -#elif defined(__LITTLE_ENDIAN__) || defined(_LITTLE_ENDIAN) -# define U_IS_BIG_ENDIAN 0 -#elif U_PLATFORM == U_PF_OS390 || U_PLATFORM == U_PF_OS400 || defined(__s390__) || defined(__s390x__) - /* These platforms do not appear to predefine any endianness macros. */ -# define U_IS_BIG_ENDIAN 1 -#elif defined(_PA_RISC1_0) || defined(_PA_RISC1_1) || defined(_PA_RISC2_0) - /* HPPA do not appear to predefine any endianness macros. */ -# define U_IS_BIG_ENDIAN 1 -#elif defined(sparc) || defined(__sparc) || defined(__sparc__) - /* Some sparc based systems (e.g. Linux) do not predefine any endianness macros. */ -# define U_IS_BIG_ENDIAN 1 -#else -# define U_IS_BIG_ENDIAN 0 -#endif - -/** - * \def U_HAVE_PLACEMENT_NEW - * Determines whether to override placement new and delete for STL. - * @stable ICU 2.6 - */ -#ifdef U_HAVE_PLACEMENT_NEW - /* Use the predefined value. */ -#elif defined(__BORLANDC__) -# define U_HAVE_PLACEMENT_NEW 0 -#else -# define U_HAVE_PLACEMENT_NEW 1 -#endif - -/** - * \def U_HAVE_DEBUG_LOCATION_NEW - * Define this to define the MFC debug version of the operator new. - * - * @stable ICU 3.4 - */ -#ifdef U_HAVE_DEBUG_LOCATION_NEW - /* Use the predefined value. */ -#elif defined(_MSC_VER) -# define U_HAVE_DEBUG_LOCATION_NEW 1 -#else -# define U_HAVE_DEBUG_LOCATION_NEW 0 -#endif - -/* Compatibility with non clang compilers: http://clang.llvm.org/docs/LanguageExtensions.html */ -#ifndef __has_attribute -# define __has_attribute(x) 0 -#endif -#ifndef __has_cpp_attribute -# define __has_cpp_attribute(x) 0 -#endif -#ifndef __has_builtin -# define __has_builtin(x) 0 -#endif -#ifndef __has_feature -# define __has_feature(x) 0 -#endif -#ifndef __has_extension -# define __has_extension(x) 0 -#endif -#ifndef __has_warning -# define __has_warning(x) 0 -#endif - -/** - * \def U_MALLOC_ATTR - * Attribute to mark functions as malloc-like - * @internal - */ -#if defined(__GNUC__) && __GNUC__>=3 -# define U_MALLOC_ATTR __attribute__ ((__malloc__)) -#else -# define U_MALLOC_ATTR -#endif - -/** - * \def U_ALLOC_SIZE_ATTR - * Attribute to specify the size of the allocated buffer for malloc-like functions - * @internal - */ -#if (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) || __has_attribute(alloc_size) -# define U_ALLOC_SIZE_ATTR(X) __attribute__ ((alloc_size(X))) -# define U_ALLOC_SIZE_ATTR2(X,Y) __attribute__ ((alloc_size(X,Y))) -#else -# define U_ALLOC_SIZE_ATTR(X) -# define U_ALLOC_SIZE_ATTR2(X,Y) -#endif - -/** - * \def U_CPLUSPLUS_VERSION - * 0 if no C++; 1, 11, 14, ... if C++. - * Support for specific features cannot always be determined by the C++ version alone. - * @internal - */ -#ifdef U_CPLUSPLUS_VERSION -# if U_CPLUSPLUS_VERSION != 0 && !defined(__cplusplus) -# undef U_CPLUSPLUS_VERSION -# define U_CPLUSPLUS_VERSION 0 -# endif - /* Otherwise use the predefined value. */ -#elif !defined(__cplusplus) -# define U_CPLUSPLUS_VERSION 0 -#elif __cplusplus >= 201402L -# define U_CPLUSPLUS_VERSION 14 -#elif __cplusplus >= 201103L -# define U_CPLUSPLUS_VERSION 11 -#else - // C++98 or C++03 -# define U_CPLUSPLUS_VERSION 1 -#endif - -/** - * \def U_HAVE_RVALUE_REFERENCES - * Set to 1 if the compiler supports rvalue references. - * C++11 feature, necessary for move constructor & move assignment. - * @internal - */ -#ifdef U_HAVE_RVALUE_REFERENCES - /* Use the predefined value. */ -#elif U_CPLUSPLUS_VERSION >= 11 || __has_feature(cxx_rvalue_references) \ - || defined(__GXX_EXPERIMENTAL_CXX0X__) \ - || (defined(_MSC_VER) && _MSC_VER >= 1600) /* Visual Studio 2010 */ -# define U_HAVE_RVALUE_REFERENCES 1 -#else -# define U_HAVE_RVALUE_REFERENCES 0 -#endif - -/** - * \def U_NOEXCEPT - * "noexcept" if supported, otherwise empty. - * Some code, especially STL containers, uses move semantics of objects only - * if the move constructor and the move operator are declared as not throwing exceptions. - * @internal - */ -#ifdef U_NOEXCEPT - /* Use the predefined value. */ -#elif defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS /* Visual Studio */ -# define U_NOEXCEPT -#elif U_CPLUSPLUS_VERSION >= 11 || __has_feature(cxx_noexcept) || __has_extension(cxx_noexcept) \ - || (defined(_MSC_VER) && _MSC_VER >= 1900) /* Visual Studio 2015 */ -# define U_NOEXCEPT noexcept -#else -# define U_NOEXCEPT -#endif - -/** - * \def U_FALLTHROUGH - * Annotate intentional fall-through between switch labels. - * http://clang.llvm.org/docs/AttributeReference.html#fallthrough-clang-fallthrough - * @internal - */ -#ifdef __cplusplus -# if __has_cpp_attribute(clang::fallthrough) || \ - (__has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough")) -# define U_FALLTHROUGH [[clang::fallthrough]] -# else -# define U_FALLTHROUGH -# endif -#else -# define U_FALLTHROUGH -#endif - - -/** @} */ - -/*===========================================================================*/ -/** @{ Character data types */ -/*===========================================================================*/ - -/** - * U_CHARSET_FAMILY is equal to this value when the platform is an ASCII based platform. - * @stable ICU 2.0 - */ -#define U_ASCII_FAMILY 0 - -/** - * U_CHARSET_FAMILY is equal to this value when the platform is an EBCDIC based platform. - * @stable ICU 2.0 - */ -#define U_EBCDIC_FAMILY 1 - -/** - * \def U_CHARSET_FAMILY - * - *

These definitions allow to specify the encoding of text - * in the char data type as defined by the platform and the compiler. - * It is enough to determine the code point values of "invariant characters", - * which are the ones shared by all encodings that are in use - * on a given platform.

- * - *

Those "invariant characters" should be all the uppercase and lowercase - * latin letters, the digits, the space, and "basic punctuation". - * Also, '\\n', '\\r', '\\t' should be available.

- * - *

The list of "invariant characters" is:
- * \code - * A-Z a-z 0-9 SPACE " % & ' ( ) * + , - . / : ; < = > ? _ - * \endcode - *
- * (52 letters + 10 numbers + 20 punc/sym/space = 82 total)

- * - *

This matches the IBM Syntactic Character Set (CS 640).

- * - *

In other words, all the graphic characters in 7-bit ASCII should - * be safely accessible except the following:

- * - * \code - * '\' - * '[' - * ']' - * '{' - * '}' - * '^' - * '~' - * '!' - * '#' - * '|' - * '$' - * '@' - * '`' - * \endcode - * @stable ICU 2.0 - */ -#ifdef U_CHARSET_FAMILY - /* Use the predefined value. */ -#elif U_PLATFORM == U_PF_OS390 && (!defined(__CHARSET_LIB) || !__CHARSET_LIB) -# define U_CHARSET_FAMILY U_EBCDIC_FAMILY -#elif U_PLATFORM == U_PF_OS400 && !defined(__UTF32__) -# define U_CHARSET_FAMILY U_EBCDIC_FAMILY -#else -# define U_CHARSET_FAMILY U_ASCII_FAMILY -#endif - -/** - * \def U_CHARSET_IS_UTF8 - * - * Hardcode the default charset to UTF-8. - * - * If this is set to 1, then - * - ICU will assume that all non-invariant char*, StringPiece, std::string etc. - * contain UTF-8 text, regardless of what the system API uses - * - some ICU code will use fast functions like u_strFromUTF8() - * rather than the more general and more heavy-weight conversion API (ucnv.h) - * - ucnv_getDefaultName() always returns "UTF-8" - * - ucnv_setDefaultName() is disabled and will not change the default charset - * - static builds of ICU are smaller - * - more functionality is available with the UCONFIG_NO_CONVERSION build-time - * configuration option (see unicode/uconfig.h) - * - the UCONFIG_NO_CONVERSION build option in uconfig.h is more usable - * - * @stable ICU 4.2 - * @see UCONFIG_NO_CONVERSION - */ -#ifdef U_CHARSET_IS_UTF8 - /* Use the predefined value. */ -#elif U_PLATFORM == U_PF_ANDROID || U_PLATFORM_IS_DARWIN_BASED -# define U_CHARSET_IS_UTF8 1 -#else -# define U_CHARSET_IS_UTF8 0 -#endif - -/** @} */ - -/*===========================================================================*/ -/** @{ Information about wchar support */ -/*===========================================================================*/ - -/** - * \def U_HAVE_WCHAR_H - * Indicates whether is available (1) or not (0). Set to 1 by default. - * - * @stable ICU 2.0 - */ -#ifdef U_HAVE_WCHAR_H - /* Use the predefined value. */ -#elif U_PLATFORM == U_PF_ANDROID && __ANDROID_API__ < 9 - /* - * Android before Gingerbread (Android 2.3, API level 9) did not support wchar_t. - * The type and header existed, but the library functions did not work as expected. - * The size of wchar_t was 1 but L"xyz" string literals had 32-bit units anyway. - */ -# define U_HAVE_WCHAR_H 0 -#else -# define U_HAVE_WCHAR_H 1 -#endif - -/** - * \def U_SIZEOF_WCHAR_T - * U_SIZEOF_WCHAR_T==sizeof(wchar_t) - * - * @stable ICU 2.0 - */ -#ifdef U_SIZEOF_WCHAR_T - /* Use the predefined value. */ -#elif (U_PLATFORM == U_PF_ANDROID && __ANDROID_API__ < 9) - /* - * Classic Mac OS and Mac OS X before 10.3 (Panther) did not support wchar_t or wstring. - * Newer Mac OS X has size 4. - */ -# define U_SIZEOF_WCHAR_T 1 -#elif U_PLATFORM_HAS_WIN32_API || U_PLATFORM == U_PF_CYGWIN -# define U_SIZEOF_WCHAR_T 2 -#elif U_PLATFORM == U_PF_AIX - /* - * AIX 6.1 information, section "Wide character data representation": - * "... the wchar_t datatype is 32-bit in the 64-bit environment and - * 16-bit in the 32-bit environment." - * and - * "All locales use Unicode for their wide character code values (process code), - * except the IBM-eucTW codeset." - */ -# ifdef __64BIT__ -# define U_SIZEOF_WCHAR_T 4 -# else -# define U_SIZEOF_WCHAR_T 2 -# endif -#elif U_PLATFORM == U_PF_OS390 - /* - * z/OS V1R11 information center, section "LP64 | ILP32": - * "In 31-bit mode, the size of long and pointers is 4 bytes and the size of wchar_t is 2 bytes. - * Under LP64, the size of long and pointer is 8 bytes and the size of wchar_t is 4 bytes." - */ -# ifdef _LP64 -# define U_SIZEOF_WCHAR_T 4 -# else -# define U_SIZEOF_WCHAR_T 2 -# endif -#elif U_PLATFORM == U_PF_OS400 -# if defined(__UTF32__) - /* - * LOCALETYPE(*LOCALEUTF) is specified. - * Wide-character strings are in UTF-32, - * narrow-character strings are in UTF-8. - */ -# define U_SIZEOF_WCHAR_T 4 -# elif defined(__UCS2__) - /* - * LOCALETYPE(*LOCALEUCS2) is specified. - * Wide-character strings are in UCS-2, - * narrow-character strings are in EBCDIC. - */ -# define U_SIZEOF_WCHAR_T 2 -#else - /* - * LOCALETYPE(*CLD) or LOCALETYPE(*LOCALE) is specified. - * Wide-character strings are in 16-bit EBCDIC, - * narrow-character strings are in EBCDIC. - */ -# define U_SIZEOF_WCHAR_T 2 -# endif -#else -# define U_SIZEOF_WCHAR_T 4 -#endif - -#ifndef U_HAVE_WCSCPY -#define U_HAVE_WCSCPY U_HAVE_WCHAR_H -#endif - -/** @} */ - -/** - * \def U_HAVE_CHAR16_T - * Defines whether the char16_t type is available for UTF-16 - * and u"abc" UTF-16 string literals are supported. - * This is a new standard type and standard string literal syntax in C++0x - * but has been available in some compilers before. - * @internal - */ -#ifdef U_HAVE_CHAR16_T - /* Use the predefined value. */ -#else - /* - * Notes: - * Visual Studio 10 (_MSC_VER>=1600) defines char16_t but - * does not support u"abc" string literals. - * gcc 4.4 defines the __CHAR16_TYPE__ macro to a usable type but - * does not support u"abc" string literals. - * C++11 and C11 require support for UTF-16 literals - */ -# if U_CPLUSPLUS_VERSION >= 11 || (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) -# define U_HAVE_CHAR16_T 1 -# else -# define U_HAVE_CHAR16_T 0 -# endif -#endif - -/** - * @{ - * \def U_DECLARE_UTF16 - * Do not use this macro because it is not defined on all platforms. - * Use the UNICODE_STRING or U_STRING_DECL macros instead. - * @internal - */ -#ifdef U_DECLARE_UTF16 - /* Use the predefined value. */ -#elif U_HAVE_CHAR16_T \ - || (defined(__xlC__) && defined(__IBM_UTF_LITERAL) && U_SIZEOF_WCHAR_T != 2) \ - || (defined(__HP_aCC) && __HP_aCC >= 035000) \ - || (defined(__HP_cc) && __HP_cc >= 111106) -# define U_DECLARE_UTF16(string) u ## string -#elif U_SIZEOF_WCHAR_T == 2 \ - && (U_CHARSET_FAMILY == 0 || (U_PF_OS390 <= U_PLATFORM && U_PLATFORM <= U_PF_OS400 && defined(__UCS2__))) -# define U_DECLARE_UTF16(string) L ## string -#else - /* Leave U_DECLARE_UTF16 undefined. See unistr.h. */ -#endif - -/** @} */ - -/*===========================================================================*/ -/** @{ Symbol import-export control */ -/*===========================================================================*/ - -#ifdef U_EXPORT - /* Use the predefined value. */ -#elif defined(U_STATIC_IMPLEMENTATION) -# define U_EXPORT -#elif defined(__GNUC__) -# define U_EXPORT __attribute__((visibility("default"))) -#elif (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x550) \ - || (defined(__SUNPRO_C) && __SUNPRO_C >= 0x550) -# define U_EXPORT __global -/*#elif defined(__HP_aCC) || defined(__HP_cc) -# define U_EXPORT __declspec(dllexport)*/ -#elif defined(_MSC_VER) -# define U_EXPORT __declspec(dllexport) -#else -# define U_EXPORT -#endif - -/* U_CALLCONV is releated to U_EXPORT2 */ -#ifdef U_EXPORT2 - /* Use the predefined value. */ -#elif defined(_MSC_VER) -# define U_EXPORT2 __cdecl -#else -# define U_EXPORT2 -#endif - -#ifdef U_IMPORT - /* Use the predefined value. */ -#elif defined(_MSC_VER) - /* Windows needs to export/import data. */ -# define U_IMPORT __declspec(dllimport) -#else -# define U_IMPORT -#endif - -/** - * \def U_CALLCONV - * Similar to U_CDECL_BEGIN/U_CDECL_END, this qualifier is necessary - * in callback function typedefs to make sure that the calling convention - * is compatible. - * - * This is only used for non-ICU-API functions. - * When a function is a public ICU API, - * you must use the U_CAPI and U_EXPORT2 qualifiers. - * - * Please note, you need to use U_CALLCONV after the *. - * - * NO : "static const char U_CALLCONV *func( . . . )" - * YES: "static const char* U_CALLCONV func( . . . )" - * - * @stable ICU 2.0 - */ -#if U_PLATFORM == U_PF_OS390 && defined(__cplusplus) -# define U_CALLCONV __cdecl -#else -# define U_CALLCONV U_EXPORT2 -#endif - -/* @} */ - -#endif diff --git a/win32/include/spidermonkey/unicode/plurfmt.h b/win32/include/spidermonkey/unicode/plurfmt.h deleted file mode 100755 index 369a8b7c..00000000 --- a/win32/include/spidermonkey/unicode/plurfmt.h +++ /dev/null @@ -1,617 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2007-2014, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -* - -* File PLURFMT.H -******************************************************************************** -*/ - -#ifndef PLURFMT -#define PLURFMT - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: PluralFormat object - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/messagepattern.h" -#include "unicode/numfmt.h" -#include "unicode/plurrule.h" - -U_NAMESPACE_BEGIN - -class Hashtable; -class NFRule; - -/** - *

- * PluralFormat supports the creation of internationalized - * messages with plural inflection. It is based on plural - * selection, i.e. the caller specifies messages for each - * plural case that can appear in the user's language and the - * PluralFormat selects the appropriate message based on - * the number. - *

- *

The Problem of Plural Forms in Internationalized Messages

- *

- * Different languages have different ways to inflect - * plurals. Creating internationalized messages that include plural - * forms is only feasible when the framework is able to handle plural - * forms of all languages correctly. ChoiceFormat - * doesn't handle this well, because it attaches a number interval to - * each message and selects the message whose interval contains a - * given number. This can only handle a finite number of - * intervals. But in some languages, like Polish, one plural case - * applies to infinitely many intervals (e.g., the plural case applies to - * numbers ending with 2, 3, or 4 except those ending with 12, 13, or - * 14). Thus ChoiceFormat is not adequate. - *

- * PluralFormat deals with this by breaking the problem - * into two parts: - *

    - *
  • It uses PluralRules that can define more complex - * conditions for a plural case than just a single interval. These plural - * rules define both what plural cases exist in a language, and to - * which numbers these cases apply. - *
  • It provides predefined plural rules for many languages. Thus, the programmer - * need not worry about the plural cases of a language and - * does not have to define the plural cases; they can simply - * use the predefined keywords. The whole plural formatting of messages can - * be done using localized patterns from resource bundles. For predefined plural - * rules, see the CLDR Language Plural Rules page at - * http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html - *
- *

- *

Usage of PluralFormat

- *

Note: Typically, plural formatting is done via MessageFormat - * with a plural argument type, - * rather than using a stand-alone PluralFormat. - *

- * This discussion assumes that you use PluralFormat with - * a predefined set of plural rules. You can create one using one of - * the constructors that takes a locale object. To - * specify the message pattern, you can either pass it to the - * constructor or set it explicitly using the - * applyPattern() method. The format() - * method takes a number object and selects the message of the - * matching plural case. This message will be returned. - *

- *
Patterns and Their Interpretation
- *

- * The pattern text defines the message output for each plural case of the - * specified locale. Syntax: - *

- * pluralStyle = [offsetValue] (selector '{' message '}')+
- * offsetValue = "offset:" number
- * selector = explicitValue | keyword
- * explicitValue = '=' number  // adjacent, no white space in between
- * keyword = [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+
- * message: see {@link MessageFormat}
- * 
- * Pattern_White_Space between syntax elements is ignored, except - * between the {curly braces} and their sub-message, - * and between the '=' and the number of an explicitValue. - * - *

- * There are 6 predefined casekeyword in CLDR/ICU - 'zero', 'one', 'two', 'few', 'many' and - * 'other'. You always have to define a message text for the default plural case - * other which is contained in every rule set. - * If you do not specify a message text for a particular plural case, the - * message text of the plural case other gets assigned to this - * plural case. - *

- * When formatting, the input number is first matched against the explicitValue clauses. - * If there is no exact-number match, then a keyword is selected by calling - * the PluralRules with the input number minus the offset. - * (The offset defaults to 0 if it is omitted from the pattern string.) - * If there is no clause with that keyword, then the "other" clauses is returned. - *

- * An unquoted pound sign (#) in the selected sub-message - * itself (i.e., outside of arguments nested in the sub-message) - * is replaced by the input number minus the offset. - * The number-minus-offset value is formatted using a - * NumberFormat for the PluralFormat's locale. If you - * need special number formatting, you have to use a MessageFormat - * and explicitly specify a NumberFormat argument. - * Note: That argument is formatting without subtracting the offset! - * If you need a custom format and have a non-zero offset, then you need to pass the - * number-minus-offset value as a separate parameter. - *

- * For a usage example, see the {@link MessageFormat} class documentation. - * - *

Defining Custom Plural Rules

- *

If you need to use PluralFormat with custom rules, you can - * create a PluralRules object and pass it to - * PluralFormat's constructor. If you also specify a locale in this - * constructor, this locale will be used to format the number in the message - * texts. - *

- * For more information about PluralRules, see - * {@link PluralRules}. - *

- * - * ported from Java - * @stable ICU 4.0 - */ - -class U_I18N_API PluralFormat : public Format { -public: - - /** - * Creates a new cardinal-number PluralFormat for the default locale. - * This locale will be used to get the set of plural rules and for standard - * number formatting. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.0 - */ - PluralFormat(UErrorCode& status); - - /** - * Creates a new cardinal-number PluralFormat for a given locale. - * @param locale the PluralFormat will be configured with - * rules for this locale. This locale will also be used for - * standard number formatting. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.0 - */ - PluralFormat(const Locale& locale, UErrorCode& status); - - /** - * Creates a new PluralFormat for a given set of rules. - * The standard number formatting will be done using the default locale. - * @param rules defines the behavior of the PluralFormat - * object. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.0 - */ - PluralFormat(const PluralRules& rules, UErrorCode& status); - - /** - * Creates a new PluralFormat for a given set of rules. - * The standard number formatting will be done using the given locale. - * @param locale the default number formatting will be done using this - * locale. - * @param rules defines the behavior of the PluralFormat - * object. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.0 - *

- *

Sample code

- * \snippet samples/plurfmtsample/plurfmtsample.cpp PluralFormatExample1 - * \snippet samples/plurfmtsample/plurfmtsample.cpp PluralFormatExample - *

- */ - PluralFormat(const Locale& locale, const PluralRules& rules, UErrorCode& status); - - /** - * Creates a new PluralFormat for the plural type. - * The standard number formatting will be done using the given locale. - * @param locale the default number formatting will be done using this - * locale. - * @param type The plural type (e.g., cardinal or ordinal). - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 50 - */ - PluralFormat(const Locale& locale, UPluralType type, UErrorCode& status); - - /** - * Creates a new cardinal-number PluralFormat for a given pattern string. - * The default locale will be used to get the set of plural rules and for - * standard number formatting. - * @param pattern the pattern for this PluralFormat. - * errors are returned to status if the pattern is invalid. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.0 - */ - PluralFormat(const UnicodeString& pattern, UErrorCode& status); - - /** - * Creates a new cardinal-number PluralFormat for a given pattern string and - * locale. - * The locale will be used to get the set of plural rules and for - * standard number formatting. - * @param locale the PluralFormat will be configured with - * rules for this locale. This locale will also be used for - * standard number formatting. - * @param pattern the pattern for this PluralFormat. - * errors are returned to status if the pattern is invalid. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.0 - */ - PluralFormat(const Locale& locale, const UnicodeString& pattern, UErrorCode& status); - - /** - * Creates a new PluralFormat for a given set of rules, a - * pattern and a locale. - * @param rules defines the behavior of the PluralFormat - * object. - * @param pattern the pattern for this PluralFormat. - * errors are returned to status if the pattern is invalid. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.0 - */ - PluralFormat(const PluralRules& rules, - const UnicodeString& pattern, - UErrorCode& status); - - /** - * Creates a new PluralFormat for a given set of rules, a - * pattern and a locale. - * @param locale the PluralFormat will be configured with - * rules for this locale. This locale will also be used for - * standard number formatting. - * @param rules defines the behavior of the PluralFormat - * object. - * @param pattern the pattern for this PluralFormat. - * errors are returned to status if the pattern is invalid. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.0 - */ - PluralFormat(const Locale& locale, - const PluralRules& rules, - const UnicodeString& pattern, - UErrorCode& status); - - /** - * Creates a new PluralFormat for a plural type, a - * pattern and a locale. - * @param locale the PluralFormat will be configured with - * rules for this locale. This locale will also be used for - * standard number formatting. - * @param type The plural type (e.g., cardinal or ordinal). - * @param pattern the pattern for this PluralFormat. - * errors are returned to status if the pattern is invalid. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 50 - */ - PluralFormat(const Locale& locale, - UPluralType type, - const UnicodeString& pattern, - UErrorCode& status); - - /** - * copy constructor. - * @stable ICU 4.0 - */ - PluralFormat(const PluralFormat& other); - - /** - * Destructor. - * @stable ICU 4.0 - */ - virtual ~PluralFormat(); - - /** - * Sets the pattern used by this plural format. - * The method parses the pattern and creates a map of format strings - * for the plural rules. - * Patterns and their interpretation are specified in the class description. - * - * @param pattern the pattern for this plural format - * errors are returned to status if the pattern is invalid. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.0 - */ - void applyPattern(const UnicodeString& pattern, UErrorCode& status); - - - using Format::format; - - /** - * Formats a plural message for a given number. - * - * @param number a number for which the plural message should be formatted - * for. If no pattern has been applied to this - * PluralFormat object yet, the formatted number - * will be returned. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return the string containing the formatted plural message. - * @stable ICU 4.0 - */ - UnicodeString format(int32_t number, UErrorCode& status) const; - - /** - * Formats a plural message for a given number. - * - * @param number a number for which the plural message should be formatted - * for. If no pattern has been applied to this - * PluralFormat object yet, the formatted number - * will be returned. - * @param status output param set to success or failure code on exit, which - * must not indicate a failure before the function call. - * @return the string containing the formatted plural message. - * @stable ICU 4.0 - */ - UnicodeString format(double number, UErrorCode& status) const; - - /** - * Formats a plural message for a given number. - * - * @param number a number for which the plural message should be formatted - * for. If no pattern has been applied to this - * PluralFormat object yet, the formatted number - * will be returned. - * @param appendTo output parameter to receive result. - * result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return the string containing the formatted plural message. - * @stable ICU 4.0 - */ - UnicodeString& format(int32_t number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - /** - * Formats a plural message for a given number. - * - * @param number a number for which the plural message should be formatted - * for. If no pattern has been applied to this - * PluralFormat object yet, the formatted number - * will be returned. - * @param appendTo output parameter to receive result. - * result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return the string containing the formatted plural message. - * @stable ICU 4.0 - */ - UnicodeString& format(double number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Sets the locale used by this PluraFormat object. - * Note: Calling this method resets this PluraFormat object, - * i.e., a pattern that was applied previously will be removed, - * and the NumberFormat is set to the default number format for - * the locale. The resulting format behaves the same as one - * constructed from {@link #PluralFormat(const Locale& locale, UPluralType type, UErrorCode& status)} - * with UPLURAL_TYPE_CARDINAL. - * @param locale the locale to use to configure the formatter. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @deprecated ICU 50 This method clears the pattern and might create - * a different kind of PluralRules instance; - * use one of the constructors to create a new instance instead. - */ - void setLocale(const Locale& locale, UErrorCode& status); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Sets the number format used by this formatter. You only need to - * call this if you want a different number format than the default - * formatter for the locale. - * @param format the number format to use. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.0 - */ - void setNumberFormat(const NumberFormat* format, UErrorCode& status); - - /** - * Assignment operator - * - * @param other the PluralFormat object to copy from. - * @stable ICU 4.0 - */ - PluralFormat& operator=(const PluralFormat& other); - - /** - * Return true if another object is semantically equal to this one. - * - * @param other the PluralFormat object to be compared with. - * @return true if other is semantically equal to this. - * @stable ICU 4.0 - */ - virtual UBool operator==(const Format& other) const; - - /** - * Return true if another object is semantically unequal to this one. - * - * @param other the PluralFormat object to be compared with. - * @return true if other is semantically unequal to this. - * @stable ICU 4.0 - */ - virtual UBool operator!=(const Format& other) const; - - /** - * Clones this Format object polymorphically. The caller owns the - * result and should delete it when done. - * @stable ICU 4.0 - */ - virtual Format* clone(void) const; - - /** - * Formats a plural message for a number taken from a Formattable object. - * - * @param obj The object containing a number for which the - * plural message should be formatted. - * The object must be of a numeric type. - * @param appendTo output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.0 - */ - UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - /** - * Returns the pattern from applyPattern() or constructor(). - * - * @param appendTo output parameter to receive result. - * Result is appended to existing contents. - * @return the UnicodeString with inserted pattern. - * @stable ICU 4.0 - */ - UnicodeString& toPattern(UnicodeString& appendTo); - - /** - * This method is not yet supported by PluralFormat. - *

- * Before calling, set parse_pos.index to the offset you want to start - * parsing at in the source. After calling, parse_pos.index is the end of - * the text you parsed. If error occurs, index is unchanged. - *

- * When parsing, leading whitespace is discarded (with a successful parse), - * while trailing whitespace is left as is. - *

- * See Format::parseObject() for more. - * - * @param source The string to be parsed into an object. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param parse_pos The position to start parsing at. Upon return - * this param is set to the position after the - * last character successfully parsed. If the - * source is not parsed successfully, this param - * will remain unchanged. - * @stable ICU 4.0 - */ - virtual void parseObject(const UnicodeString& source, - Formattable& result, - ParsePosition& parse_pos) const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 4.0 - * - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 4.0 - */ - virtual UClassID getDynamicClassID() const; - -#if (defined(__xlC__) && (__xlC__ < 0x0C00)) || (U_PLATFORM == U_PF_OS390) || (U_PLATFORM ==U_PF_OS400) -// Work around a compiler bug on xlC 11.1 on AIX 7.1 that would -// prevent PluralSelectorAdapter from implementing private PluralSelector. -// xlC error message: -// 1540-0300 (S) The "private" member "class icu_49::PluralFormat::PluralSelector" cannot be accessed. -public: -#else -private: -#endif - /** - * @internal - */ - class U_I18N_API PluralSelector : public UMemory { - public: - virtual ~PluralSelector(); - /** - * Given a number, returns the appropriate PluralFormat keyword. - * - * @param context worker object for the selector. - * @param number The number to be plural-formatted. - * @param ec Error code. - * @return The selected PluralFormat keyword. - * @internal - */ - virtual UnicodeString select(void *context, double number, UErrorCode& ec) const = 0; - }; - - /** - * @internal - */ - class U_I18N_API PluralSelectorAdapter : public PluralSelector { - public: - PluralSelectorAdapter() : pluralRules(NULL) { - } - - virtual ~PluralSelectorAdapter(); - - virtual UnicodeString select(void *context, double number, UErrorCode& /*ec*/) const; /**< @internal */ - - void reset(); - - PluralRules* pluralRules; - }; - -#if defined(__xlC__) -// End of xlC bug workaround, keep remaining definitions private. -private: -#endif - Locale locale; - MessagePattern msgPattern; - NumberFormat* numberFormat; - double offset; - PluralSelectorAdapter pluralRulesWrapper; - - PluralFormat(); // default constructor not implemented - void init(const PluralRules* rules, UPluralType type, UErrorCode& status); - /** - * Copies dynamically allocated values (pointer fields). - * Others are copied using their copy constructors and assignment operators. - */ - void copyObjects(const PluralFormat& other); - - UnicodeString& format(const Formattable& numberObject, double number, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; /**< @internal */ - - /** - * Finds the PluralFormat sub-message for the given number, or the "other" sub-message. - * @param pattern A MessagePattern. - * @param partIndex the index of the first PluralFormat argument style part. - * @param selector the PluralSelector for mapping the number (minus offset) to a keyword. - * @param context worker object for the selector. - * @param number a number to be matched to one of the PluralFormat argument's explicit values, - * or mapped via the PluralSelector. - * @param ec ICU error code. - * @return the sub-message start part index. - */ - static int32_t findSubMessage( - const MessagePattern& pattern, int32_t partIndex, - const PluralSelector& selector, void *context, double number, UErrorCode& ec); /**< @internal */ - - void parseType(const UnicodeString& source, const NFRule *rbnfLenientScanner, - Formattable& result, FieldPosition& pos) const; - - friend class MessageFormat; - friend class NFRule; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _PLURFMT -//eof diff --git a/win32/include/spidermonkey/unicode/plurrule.h b/win32/include/spidermonkey/unicode/plurrule.h deleted file mode 100755 index 146e6bea..00000000 --- a/win32/include/spidermonkey/unicode/plurrule.h +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2008-2015, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -* -* -* File PLURRULE.H -* -* Modification History:* -* Date Name Description -* -******************************************************************************** -*/ - -#ifndef PLURRULE -#define PLURRULE - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: PluralRules object - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/format.h" -#include "unicode/upluralrules.h" - -/** - * Value returned by PluralRules::getUniqueKeywordValue() when there is no - * unique value to return. - * @stable ICU 4.8 - */ -#define UPLRULES_NO_UNIQUE_VALUE ((double)-0.00123456777) - -U_NAMESPACE_BEGIN - -class Hashtable; -class FixedDecimal; -class VisibleDigitsWithExponent; -class RuleChain; -class PluralRuleParser; -class PluralKeywordEnumeration; -class AndConstraint; -class SharedPluralRules; - -/** - * Defines rules for mapping non-negative numeric values onto a small set of - * keywords. Rules are constructed from a text description, consisting - * of a series of keywords and conditions. The {@link #select} method - * examines each condition in order and returns the keyword for the - * first condition that matches the number. If none match, - * default rule(other) is returned. - * - * For more information, details, and tips for writing rules, see the - * LDML spec, C.11 Language Plural Rules: - * http://www.unicode.org/draft/reports/tr35/tr35.html#Language_Plural_Rules - * - * Examples:

- *   "one: n is 1; few: n in 2..4"
- * This defines two rules, for 'one' and 'few'. The condition for - * 'one' is "n is 1" which means that the number must be equal to - * 1 for this condition to pass. The condition for 'few' is - * "n in 2..4" which means that the number must be between 2 and - * 4 inclusive for this condition to pass. All other numbers - * are assigned the keyword "other" by the default rule. - *

- *    "zero: n is 0; one: n is 1; zero: n mod 100 in 1..19"
- * This illustrates that the same keyword can be defined multiple times. - * Each rule is examined in order, and the first keyword whose condition - * passes is the one returned. Also notes that a modulus is applied - * to n in the last rule. Thus its condition holds for 119, 219, 319... - *

- *    "one: n is 1; few: n mod 10 in 2..4 and n mod 100 not in 12..14"
- * This illustrates conjunction and negation. The condition for 'few' - * has two parts, both of which must be met: "n mod 10 in 2..4" and - * "n mod 100 not in 12..14". The first part applies a modulus to n - * before the test as in the previous example. The second part applies - * a different modulus and also uses negation, thus it matches all - * numbers _not_ in 12, 13, 14, 112, 113, 114, 212, 213, 214... - *

- *

- * Syntax:

- * \code
- * rules         = rule (';' rule)*
- * rule          = keyword ':' condition
- * keyword       = 
- * condition     = and_condition ('or' and_condition)*
- * and_condition = relation ('and' relation)*
- * relation      = is_relation | in_relation | within_relation | 'n' 
- * is_relation   = expr 'is' ('not')? value
- * in_relation   = expr ('not')? 'in' range_list
- * within_relation = expr ('not')? 'within' range
- * expr          = ('n' | 'i' | 'f' | 'v' | 'j') ('mod' value)?
- * range_list    = (range | value) (',' range_list)*
- * value         = digit+  ('.' digit+)?
- * digit         = 0|1|2|3|4|5|6|7|8|9
- * range         = value'..'value
- * \endcode
- * 

- *

- *

- * The i, f, and v values are defined as follows: - *

- *
    - *
  • i to be the integer digits.
  • - *
  • f to be the visible fractional digits, as an integer.
  • - *
  • v to be the number of visible fraction digits.
  • - *
  • j is defined to only match integers. That is j is 3 fails if v != 0 (eg for 3.1 or 3.0).
  • - *
- *

- * Examples are in the following table: - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
nifv
1.0101
1.00102
1.3131
1.03132
1.231232
- *

- * The difference between 'in' and 'within' is that 'in' only includes integers in the specified range, while 'within' - * includes all values. Using 'within' with a range_list consisting entirely of values is the same as using 'in' (it's - * not an error). - *

- - * An "identifier" is a sequence of characters that do not have the - * Unicode Pattern_Syntax or Pattern_White_Space properties. - *

- * The difference between 'in' and 'within' is that 'in' only includes - * integers in the specified range, while 'within' includes all values. - * Using 'within' with a range_list consisting entirely of values is the - * same as using 'in' (it's not an error). - *

- *

- * Keywords - * could be defined by users or from ICU locale data. There are 6 - * predefined values in ICU - 'zero', 'one', 'two', 'few', 'many' and - * 'other'. Callers need to check the value of keyword returned by - * {@link #select} method. - *

- * - * Examples:
- * UnicodeString keyword = pl->select(number);
- * if (keyword== UnicodeString("one") {
- *     ...
- * }
- * else if ( ... )
- * 
- * Note:
- *

- * ICU defines plural rules for many locales based on CLDR Language Plural Rules. - * For these predefined rules, see CLDR page at - * http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html - *

- */ -class U_I18N_API PluralRules : public UObject { -public: - - /** - * Constructor. - * @param status Output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * - * @stable ICU 4.0 - */ - PluralRules(UErrorCode& status); - - /** - * Copy constructor. - * @stable ICU 4.0 - */ - PluralRules(const PluralRules& other); - - /** - * Destructor. - * @stable ICU 4.0 - */ - virtual ~PluralRules(); - - /** - * Clone - * @stable ICU 4.0 - */ - PluralRules* clone() const; - - /** - * Assignment operator. - * @stable ICU 4.0 - */ - PluralRules& operator=(const PluralRules&); - - /** - * Creates a PluralRules from a description if it is parsable, otherwise - * returns NULL. - * - * @param description rule description - * @param status Output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return new PluralRules pointer. NULL if there is an error. - * @stable ICU 4.0 - */ - static PluralRules* U_EXPORT2 createRules(const UnicodeString& description, - UErrorCode& status); - - /** - * The default rules that accept any number. - * - * @param status Output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return new PluralRules pointer. NULL if there is an error. - * @stable ICU 4.0 - */ - static PluralRules* U_EXPORT2 createDefaultRules(UErrorCode& status); - - /** - * Provides access to the predefined cardinal-number PluralRules for a given - * locale. - * Same as forLocale(locale, UPLURAL_TYPE_CARDINAL, status). - * - * @param locale The locale for which a PluralRules object is - * returned. - * @param status Output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return The predefined PluralRules object pointer for - * this locale. If there's no predefined rules for this locale, - * the rules for the closest parent in the locale hierarchy - * that has one will be returned. The final fallback always - * returns the default 'other' rules. - * @stable ICU 4.0 - */ - static PluralRules* U_EXPORT2 forLocale(const Locale& locale, UErrorCode& status); - - /** - * Provides access to the predefined PluralRules for a given - * locale and the plural type. - * - * @param locale The locale for which a PluralRules object is - * returned. - * @param type The plural type (e.g., cardinal or ordinal). - * @param status Output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return The predefined PluralRules object pointer for - * this locale. If there's no predefined rules for this locale, - * the rules for the closest parent in the locale hierarchy - * that has one will be returned. The final fallback always - * returns the default 'other' rules. - * @stable ICU 50 - */ - static PluralRules* U_EXPORT2 forLocale(const Locale& locale, UPluralType type, UErrorCode& status); - -#ifndef U_HIDE_INTERNAL_API - /** - * Return a StringEnumeration over the locales for which there is plurals data. - * @return a StringEnumeration over the locales available. - * @internal - */ - static StringEnumeration* U_EXPORT2 getAvailableLocales(UErrorCode &status); - - /** - * Returns whether or not there are overrides. - * @param locale the locale to check. - * @return - * @internal - */ - static UBool hasOverride(const Locale &locale); - - /** - * For ICU use only. - * creates a SharedPluralRules object - * @internal - */ - static PluralRules* U_EXPORT2 internalForLocale(const Locale& locale, UPluralType type, UErrorCode& status); - - /** - * For ICU use only. - * Returns handle to the shared, cached PluralRules instance. - * Caller must call removeRef() on returned value once it is done with - * the shared instance. - * @internal - */ - static const SharedPluralRules* U_EXPORT2 createSharedInstance( - const Locale& locale, UPluralType type, UErrorCode& status); - - -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Given a number, returns the keyword of the first rule that applies to - * the number. This function can be used with isKeyword* functions to - * determine the keyword for default plural rules. - * - * @param number The number for which the rule has to be determined. - * @return The keyword of the selected rule. - * @stable ICU 4.0 - */ - UnicodeString select(int32_t number) const; - - /** - * Given a number, returns the keyword of the first rule that applies to - * the number. This function can be used with isKeyword* functions to - * determine the keyword for default plural rules. - * - * @param number The number for which the rule has to be determined. - * @return The keyword of the selected rule. - * @stable ICU 4.0 - */ - UnicodeString select(double number) const; - -#ifndef U_HIDE_INTERNAL_API - /** - * @internal - */ - UnicodeString select(const FixedDecimal &number) const; - /** - * @internal - */ - UnicodeString select(const VisibleDigitsWithExponent &number) const; -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Returns a list of all rule keywords used in this PluralRules - * object. The rule 'other' is always present by default. - * - * @param status Output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return StringEnumeration with the keywords. - * The caller must delete the object. - * @stable ICU 4.0 - */ - StringEnumeration* getKeywords(UErrorCode& status) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Deprecated Function, does not return useful results. - * - * Originally intended to return a unique value for this keyword if it exists, - * else the constant UPLRULES_NO_UNIQUE_VALUE. - * - * @param keyword The keyword. - * @return Stub deprecated function returns UPLRULES_NO_UNIQUE_VALUE always. - * @deprecated ICU 55 - */ - double getUniqueKeywordValue(const UnicodeString& keyword); - - /** - * Deprecated Function, does not produce useful results. - * - * Orginally intended to return all the values for which select() would return the keyword. - * If the keyword is unknown, returns no values, but this is not an error. If - * the number of values is unlimited, returns no values and -1 as the - * count. - * - * The number of returned values is typically small. - * - * @param keyword The keyword. - * @param dest Array into which to put the returned values. May - * be NULL if destCapacity is 0. - * @param destCapacity The capacity of the array, must be at least 0. - * @param status The error code. Deprecated function, always sets U_UNSUPPORTED_ERROR. - * @return The count of values available, or -1. This count - * can be larger than destCapacity, but no more than - * destCapacity values will be written. - * @deprecated ICU 55 - */ - int32_t getAllKeywordValues(const UnicodeString &keyword, - double *dest, int32_t destCapacity, - UErrorCode& status); -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Returns sample values for which select() would return the keyword. If - * the keyword is unknown, returns no values, but this is not an error. - * - * The number of returned values is typically small. - * - * @param keyword The keyword. - * @param dest Array into which to put the returned values. May - * be NULL if destCapacity is 0. - * @param destCapacity The capacity of the array, must be at least 0. - * @param status The error code. - * @return The count of values written. - * If more than destCapacity samples are available, then - * only destCapacity are written, and destCapacity is returned as the count, - * rather than setting a U_BUFFER_OVERFLOW_ERROR. - * (The actual number of keyword values could be unlimited.) - * @stable ICU 4.8 - */ - int32_t getSamples(const UnicodeString &keyword, - double *dest, int32_t destCapacity, - UErrorCode& status); - - /** - * Returns TRUE if the given keyword is defined in this - * PluralRules object. - * - * @param keyword the input keyword. - * @return TRUE if the input keyword is defined. - * Otherwise, return FALSE. - * @stable ICU 4.0 - */ - UBool isKeyword(const UnicodeString& keyword) const; - - - /** - * Returns keyword for default plural form. - * - * @return keyword for default plural form. - * @stable ICU 4.0 - */ - UnicodeString getKeywordOther() const; - -#ifndef U_HIDE_INTERNAL_API - /** - * - * @internal - */ - UnicodeString getRules() const; -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Compares the equality of two PluralRules objects. - * - * @param other The other PluralRules object to be compared with. - * @return True if the given PluralRules is the same as this - * PluralRules; false otherwise. - * @stable ICU 4.0 - */ - virtual UBool operator==(const PluralRules& other) const; - - /** - * Compares the inequality of two PluralRules objects. - * - * @param other The PluralRules object to be compared with. - * @return True if the given PluralRules is not the same as this - * PluralRules; false otherwise. - * @stable ICU 4.0 - */ - UBool operator!=(const PluralRules& other) const {return !operator==(other);} - - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 4.0 - * - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 4.0 - */ - virtual UClassID getDynamicClassID() const; - - -private: - RuleChain *mRules; - - PluralRules(); // default constructor not implemented - void parseDescription(const UnicodeString& ruleData, UErrorCode &status); - int32_t getNumberValue(const UnicodeString& token) const; - UnicodeString getRuleFromResource(const Locale& locale, UPluralType type, UErrorCode& status); - RuleChain *rulesForKeyword(const UnicodeString &keyword) const; - - friend class PluralRuleParser; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _PLURRULE -//eof diff --git a/win32/include/spidermonkey/unicode/ptypes.h b/win32/include/spidermonkey/unicode/ptypes.h deleted file mode 100755 index 69d7286d..00000000 --- a/win32/include/spidermonkey/unicode/ptypes.h +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 1997-2012, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* -* FILE NAME : ptypes.h -* -* Date Name Description -* 05/13/98 nos Creation (content moved here from ptypes.h). -* 03/02/99 stephen Added AS400 support. -* 03/30/99 stephen Added Linux support. -* 04/13/99 stephen Reworked for autoconf. -* 09/18/08 srl Moved basic types back to ptypes.h from platform.h -****************************************************************************** -*/ - -/** - * \file - * \brief C API: Definitions of integer types of various widths - */ - -#ifndef _PTYPES_H -#define _PTYPES_H - -/** - * \def __STDC_LIMIT_MACROS - * According to the Linux stdint.h, the ISO C99 standard specifies that in C++ implementations - * macros like INT32_MIN and UINTPTR_MAX should only be defined if explicitly requested. - * We need to define __STDC_LIMIT_MACROS before including stdint.h in C++ code - * that uses such limit macros. - * @internal - */ -#ifndef __STDC_LIMIT_MACROS -#define __STDC_LIMIT_MACROS -#endif - -/* NULL, size_t, wchar_t */ -#include - -/* - * If all compilers provided all of the C99 headers and types, - * we would just unconditionally #include here - * and not need any of the stuff after including platform.h. - */ - -/* Find out if we have stdint.h etc. */ -#include "unicode/platform.h" - -/*===========================================================================*/ -/* Generic data types */ -/*===========================================================================*/ - -/* If your platform does not have the header, you may - need to edit the typedefs in the #else section below. - Use #if...#else...#endif with predefined compiler macros if possible. */ -#if U_HAVE_STDINT_H - -/* - * We mostly need (which defines the standard integer types) but not . - * includes and adds the printf/scanf helpers PRId32, SCNx16 etc. - * which we almost never use, plus stuff like imaxabs() which we never use. - */ -#include - -#if U_PLATFORM == U_PF_OS390 -/* The features header is needed to get (u)int64_t sometimes. */ -#include -/* z/OS has , but some versions are missing uint8_t (APAR PK62248). */ -#if !defined(__uint8_t) -#define __uint8_t 1 -typedef unsigned char uint8_t; -#endif -#endif /* U_PLATFORM == U_PF_OS390 */ - -#elif U_HAVE_INTTYPES_H - -# include - -#else /* neither U_HAVE_STDINT_H nor U_HAVE_INTTYPES_H */ - -#if ! U_HAVE_INT8_T -typedef signed char int8_t; -#endif - -#if ! U_HAVE_UINT8_T -typedef unsigned char uint8_t; -#endif - -#if ! U_HAVE_INT16_T -typedef signed short int16_t; -#endif - -#if ! U_HAVE_UINT16_T -typedef unsigned short uint16_t; -#endif - -#if ! U_HAVE_INT32_T -typedef signed int int32_t; -#endif - -#if ! U_HAVE_UINT32_T -typedef unsigned int uint32_t; -#endif - -#if ! U_HAVE_INT64_T -#ifdef _MSC_VER - typedef signed __int64 int64_t; -#else - typedef signed long long int64_t; -#endif -#endif - -#if ! U_HAVE_UINT64_T -#ifdef _MSC_VER - typedef unsigned __int64 uint64_t; -#else - typedef unsigned long long uint64_t; -#endif -#endif - -#endif /* U_HAVE_STDINT_H / U_HAVE_INTTYPES_H */ - -#endif /* _PTYPES_H */ diff --git a/win32/include/spidermonkey/unicode/putil.h b/win32/include/spidermonkey/unicode/putil.h deleted file mode 100755 index 63a7b9b3..00000000 --- a/win32/include/spidermonkey/unicode/putil.h +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 1997-2014, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* -* FILE NAME : putil.h -* -* Date Name Description -* 05/14/98 nos Creation (content moved here from utypes.h). -* 06/17/99 erm Added IEEE_754 -* 07/22/98 stephen Added IEEEremainder, max, min, trunc -* 08/13/98 stephen Added isNegativeInfinity, isPositiveInfinity -* 08/24/98 stephen Added longBitsFromDouble -* 03/02/99 stephen Removed openFile(). Added AS400 support. -* 04/15/99 stephen Converted to C -* 11/15/99 helena Integrated S/390 changes for IEEE support. -* 01/11/00 helena Added u_getVersion. -****************************************************************************** -*/ - -#ifndef PUTIL_H -#define PUTIL_H - -#include "unicode/utypes.h" - /** - * \file - * \brief C API: Platform Utilities - */ - -/*==========================================================================*/ -/* Platform utilities */ -/*==========================================================================*/ - -/** - * Platform utilities isolates the platform dependencies of the - * libarary. For each platform which this code is ported to, these - * functions may have to be re-implemented. - */ - -/** - * Return the ICU data directory. - * The data directory is where common format ICU data files (.dat files) - * are loaded from. Note that normal use of the built-in ICU - * facilities does not require loading of an external data file; - * unless you are adding custom data to ICU, the data directory - * does not need to be set. - * - * The data directory is determined as follows: - * If u_setDataDirectory() has been called, that is it, otherwise - * if the ICU_DATA environment variable is set, use that, otherwise - * If a data directory was specifed at ICU build time - * - * \code - * #define ICU_DATA_DIR "path" - * \endcode - * use that, - * otherwise no data directory is available. - * - * @return the data directory, or an empty string ("") if no data directory has - * been specified. - * - * @stable ICU 2.0 - */ -U_STABLE const char* U_EXPORT2 u_getDataDirectory(void); - - -/** - * Set the ICU data directory. - * The data directory is where common format ICU data files (.dat files) - * are loaded from. Note that normal use of the built-in ICU - * facilities does not require loading of an external data file; - * unless you are adding custom data to ICU, the data directory - * does not need to be set. - * - * This function should be called at most once in a process, before the - * first ICU operation (e.g., u_init()) that will require the loading of an - * ICU data file. - * This function is not thread-safe. Use it before calling ICU APIs from - * multiple threads. - * - * @param directory The directory to be set. - * - * @see u_init - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 u_setDataDirectory(const char *directory); - -#ifndef U_HIDE_INTERNAL_API -/** - * Return the time zone files override directory, or an empty string if - * no directory was specified. Certain time zone resources will be preferrentially - * loaded from individual files in this directory. - * - * @return the time zone data override directory. - * @internal - */ -U_INTERNAL const char * U_EXPORT2 u_getTimeZoneFilesDirectory(UErrorCode *status); - -/** - * Set the time zone files override directory. - * This function is not thread safe; it must not be called concurrently with - * u_getTimeZoneFilesDirectory() or any other use of ICU time zone functions. - * This function should only be called before using any ICU service that - * will access the time zone data. - * @internal - */ -U_INTERNAL void U_EXPORT2 u_setTimeZoneFilesDirectory(const char *path, UErrorCode *status); -#endif /* U_HIDE_INTERNAL_API */ - - -/** - * @{ - * Filesystem file and path separator characters. - * Example: '/' and ':' on Unix, '\\' and ';' on Windows. - * @stable ICU 2.0 - */ -#if U_PLATFORM_USES_ONLY_WIN32_API -# define U_FILE_SEP_CHAR '\\' -# define U_FILE_ALT_SEP_CHAR '/' -# define U_PATH_SEP_CHAR ';' -# define U_FILE_SEP_STRING "\\" -# define U_FILE_ALT_SEP_STRING "/" -# define U_PATH_SEP_STRING ";" -#else -# define U_FILE_SEP_CHAR '/' -# define U_FILE_ALT_SEP_CHAR '/' -# define U_PATH_SEP_CHAR ':' -# define U_FILE_SEP_STRING "/" -# define U_FILE_ALT_SEP_STRING "/" -# define U_PATH_SEP_STRING ":" -#endif - -/** @} */ - -/** - * Convert char characters to UChar characters. - * This utility function is useful only for "invariant characters" - * that are encoded in the platform default encoding. - * They are a small, constant subset of the encoding and include - * just the latin letters, digits, and some punctuation. - * For details, see U_CHARSET_FAMILY. - * - * @param cs Input string, points to length - * character bytes from a subset of the platform encoding. - * @param us Output string, points to memory for length - * Unicode characters. - * @param length The number of characters to convert; this may - * include the terminating NUL. - * - * @see U_CHARSET_FAMILY - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -u_charsToUChars(const char *cs, UChar *us, int32_t length); - -/** - * Convert UChar characters to char characters. - * This utility function is useful only for "invariant characters" - * that can be encoded in the platform default encoding. - * They are a small, constant subset of the encoding and include - * just the latin letters, digits, and some punctuation. - * For details, see U_CHARSET_FAMILY. - * - * @param us Input string, points to length - * Unicode characters that can be encoded with the - * codepage-invariant subset of the platform encoding. - * @param cs Output string, points to memory for length - * character bytes. - * @param length The number of characters to convert; this may - * include the terminating NUL. - * - * @see U_CHARSET_FAMILY - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -u_UCharsToChars(const UChar *us, char *cs, int32_t length); - -#endif diff --git a/win32/include/spidermonkey/unicode/rbbi.h b/win32/include/spidermonkey/unicode/rbbi.h deleted file mode 100755 index 9f2a1a62..00000000 --- a/win32/include/spidermonkey/unicode/rbbi.h +++ /dev/null @@ -1,734 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -*************************************************************************** -* Copyright (C) 1999-2016 International Business Machines Corporation * -* and others. All rights reserved. * -*************************************************************************** - -********************************************************************** -* Date Name Description -* 10/22/99 alan Creation. -* 11/11/99 rgillam Complete port from Java. -********************************************************************** -*/ - -#ifndef RBBI_H -#define RBBI_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Rule Based Break Iterator - */ - -#if !UCONFIG_NO_BREAK_ITERATION - -#include "unicode/brkiter.h" -#include "unicode/udata.h" -#include "unicode/parseerr.h" -#include "unicode/schriter.h" -#include "unicode/uchriter.h" - - -struct UTrie; - -U_NAMESPACE_BEGIN - -/** @internal */ -struct RBBIDataHeader; -class RuleBasedBreakIteratorTables; -class BreakIterator; -class RBBIDataWrapper; -class UStack; -class LanguageBreakEngine; -class UnhandledEngine; -struct RBBIStateTable; - - - - -/** - * - * A subclass of BreakIterator whose behavior is specified using a list of rules. - *

Instances of this class are most commonly created by the factory methods of - * BreakIterator::createWordInstance(), BreakIterator::createLineInstance(), etc., - * and then used via the abstract API in class BreakIterator

- * - *

See the ICU User Guide for information on Break Iterator Rules.

- * - *

This class is not intended to be subclassed.

- */ -class U_COMMON_API RuleBasedBreakIterator /*U_FINAL*/ : public BreakIterator { - -private: - /** - * The UText through which this BreakIterator accesses the text - * @internal - */ - UText *fText; - - /** - * A character iterator that refers to the same text as the UText, above. - * Only included for compatibility with old API, which was based on CharacterIterators. - * Value may be adopted from outside, or one of fSCharIter or fDCharIter, below. - */ - CharacterIterator *fCharIter; - - /** - * When the input text is provided by a UnicodeString, this will point to - * a characterIterator that wraps that data. Needed only for the - * implementation of getText(), a backwards compatibility issue. - */ - StringCharacterIterator *fSCharIter; - - /** - * When the input text is provided by a UText, this - * dummy CharacterIterator over an empty string will - * be returned from getText() - */ - UCharCharacterIterator *fDCharIter; - - /** - * The rule data for this BreakIterator instance - * @internal - */ - RBBIDataWrapper *fData; - - /** Index of the Rule {tag} values for the most recent match. - * @internal - */ - int32_t fLastRuleStatusIndex; - - /** - * Rule tag value valid flag. - * Some iterator operations don't intrinsically set the correct tag value. - * This flag lets us lazily compute the value if we are ever asked for it. - * @internal - */ - UBool fLastStatusIndexValid; - - /** - * Counter for the number of characters encountered with the "dictionary" - * flag set. - * @internal - */ - uint32_t fDictionaryCharCount; - - /** - * When a range of characters is divided up using the dictionary, the break - * positions that are discovered are stored here, preventing us from having - * to use either the dictionary or the state table again until the iterator - * leaves this range of text. Has the most impact for line breaking. - * @internal - */ - int32_t* fCachedBreakPositions; - - /** - * The number of elements in fCachedBreakPositions - * @internal - */ - int32_t fNumCachedBreakPositions; - - /** - * if fCachedBreakPositions is not null, this indicates which item in the - * cache the current iteration position refers to - * @internal - */ - int32_t fPositionInCache; - - /** - * - * If present, UStack of LanguageBreakEngine objects that might handle - * dictionary characters. Searched from top to bottom to find an object to - * handle a given character. - * @internal - */ - UStack *fLanguageBreakEngines; - - /** - * - * If present, the special LanguageBreakEngine used for handling - * characters that are in the dictionary set, but not handled by any - * LangugageBreakEngine. - * @internal - */ - UnhandledEngine *fUnhandledBreakEngine; - - /** - * - * The type of the break iterator, or -1 if it has not been set. - * @internal - */ - int32_t fBreakType; - - //======================================================================= - // constructors - //======================================================================= - - /** - * Constructor from a flattened set of RBBI data in malloced memory. - * RulesBasedBreakIterators built from a custom set of rules - * are created via this constructor; the rules are compiled - * into memory, then the break iterator is constructed here. - * - * The break iterator adopts the memory, and will - * free it when done. - * @internal - */ - RuleBasedBreakIterator(RBBIDataHeader* data, UErrorCode &status); - - - friend class RBBIRuleBuilder; - /** @internal */ - friend class BreakIterator; - - - -public: - - /** Default constructor. Creates an empty shell of an iterator, with no - * rules or text to iterate over. Object can subsequently be assigned to. - * @stable ICU 2.2 - */ - RuleBasedBreakIterator(); - - /** - * Copy constructor. Will produce a break iterator with the same behavior, - * and which iterates over the same text, as the one passed in. - * @param that The RuleBasedBreakIterator passed to be copied - * @stable ICU 2.0 - */ - RuleBasedBreakIterator(const RuleBasedBreakIterator& that); - - /** - * Construct a RuleBasedBreakIterator from a set of rules supplied as a string. - * @param rules The break rules to be used. - * @param parseError In the event of a syntax error in the rules, provides the location - * within the rules of the problem. - * @param status Information on any errors encountered. - * @stable ICU 2.2 - */ - RuleBasedBreakIterator( const UnicodeString &rules, - UParseError &parseError, - UErrorCode &status); - - /** - * Contruct a RuleBasedBreakIterator from a set of precompiled binary rules. - * Binary rules are obtained from RulesBasedBreakIterator::getBinaryRules(). - * Construction of a break iterator in this way is substantially faster than - * constuction from source rules. - * - * Ownership of the storage containing the compiled rules remains with the - * caller of this function. The compiled rules must not be modified or - * deleted during the life of the break iterator. - * - * The compiled rules are not compatible across different major versions of ICU. - * The compiled rules are comaptible only between machines with the same - * byte ordering (little or big endian) and the same base character set family - * (ASCII or EBCDIC). - * - * @see #getBinaryRules - * @param compiledRules A pointer to the compiled break rules to be used. - * @param ruleLength The length of the compiled break rules, in bytes. This - * corresponds to the length value produced by getBinaryRules(). - * @param status Information on any errors encountered, including invalid - * binary rules. - * @stable ICU 4.8 - */ - RuleBasedBreakIterator(const uint8_t *compiledRules, - uint32_t ruleLength, - UErrorCode &status); - - /** - * This constructor uses the udata interface to create a BreakIterator - * whose internal tables live in a memory-mapped file. "image" is an - * ICU UDataMemory handle for the pre-compiled break iterator tables. - * @param image handle to the memory image for the break iterator data. - * Ownership of the UDataMemory handle passes to the Break Iterator, - * which will be responsible for closing it when it is no longer needed. - * @param status Information on any errors encountered. - * @see udata_open - * @see #getBinaryRules - * @stable ICU 2.8 - */ - RuleBasedBreakIterator(UDataMemory* image, UErrorCode &status); - - /** - * Destructor - * @stable ICU 2.0 - */ - virtual ~RuleBasedBreakIterator(); - - /** - * Assignment operator. Sets this iterator to have the same behavior, - * and iterate over the same text, as the one passed in. - * @param that The RuleBasedBreakItertor passed in - * @return the newly created RuleBasedBreakIterator - * @stable ICU 2.0 - */ - RuleBasedBreakIterator& operator=(const RuleBasedBreakIterator& that); - - /** - * Equality operator. Returns TRUE if both BreakIterators are of the - * same class, have the same behavior, and iterate over the same text. - * @param that The BreakIterator to be compared for equality - * @return TRUE if both BreakIterators are of the - * same class, have the same behavior, and iterate over the same text. - * @stable ICU 2.0 - */ - virtual UBool operator==(const BreakIterator& that) const; - - /** - * Not-equal operator. If operator== returns TRUE, this returns FALSE, - * and vice versa. - * @param that The BreakIterator to be compared for inequality - * @return TRUE if both BreakIterators are not same. - * @stable ICU 2.0 - */ - UBool operator!=(const BreakIterator& that) const; - - /** - * Returns a newly-constructed RuleBasedBreakIterator with the same - * behavior, and iterating over the same text, as this one. - * Differs from the copy constructor in that it is polymorphic, and - * will correctly clone (copy) a derived class. - * clone() is thread safe. Multiple threads may simultaeneously - * clone the same source break iterator. - * @return a newly-constructed RuleBasedBreakIterator - * @stable ICU 2.0 - */ - virtual BreakIterator* clone() const; - - /** - * Compute a hash code for this BreakIterator - * @return A hash code - * @stable ICU 2.0 - */ - virtual int32_t hashCode(void) const; - - /** - * Returns the description used to create this iterator - * @return the description used to create this iterator - * @stable ICU 2.0 - */ - virtual const UnicodeString& getRules(void) const; - - //======================================================================= - // BreakIterator overrides - //======================================================================= - - /** - *

- * Return a CharacterIterator over the text being analyzed. - * The returned character iterator is owned by the break iterator, and must - * not be deleted by the caller. Repeated calls to this function may - * return the same CharacterIterator. - *

- *

- * The returned character iterator must not be used concurrently with - * the break iterator. If concurrent operation is needed, clone the - * returned character iterator first and operate on the clone. - *

- *

- * When the break iterator is operating on text supplied via a UText, - * this function will fail. Lacking any way to signal failures, it - * returns an CharacterIterator containing no text. - * The function getUText() provides similar functionality, - * is reliable, and is more efficient. - *

- * - * TODO: deprecate this function? - * - * @return An iterator over the text being analyzed. - * @stable ICU 2.0 - */ - virtual CharacterIterator& getText(void) const; - - - /** - * Get a UText for the text being analyzed. - * The returned UText is a shallow clone of the UText used internally - * by the break iterator implementation. It can safely be used to - * access the text without impacting any break iterator operations, - * but the underlying text itself must not be altered. - * - * @param fillIn A UText to be filled in. If NULL, a new UText will be - * allocated to hold the result. - * @param status receives any error codes. - * @return The current UText for this break iterator. If an input - * UText was provided, it will always be returned. - * @stable ICU 3.4 - */ - virtual UText *getUText(UText *fillIn, UErrorCode &status) const; - - /** - * Set the iterator to analyze a new piece of text. This function resets - * the current iteration position to the beginning of the text. - * @param newText An iterator over the text to analyze. The BreakIterator - * takes ownership of the character iterator. The caller MUST NOT delete it! - * @stable ICU 2.0 - */ - virtual void adoptText(CharacterIterator* newText); - - /** - * Set the iterator to analyze a new piece of text. This function resets - * the current iteration position to the beginning of the text. - * - * The BreakIterator will retain a reference to the supplied string. - * The caller must not modify or delete the text while the BreakIterator - * retains the reference. - * - * @param newText The text to analyze. - * @stable ICU 2.0 - */ - virtual void setText(const UnicodeString& newText); - - /** - * Reset the break iterator to operate over the text represented by - * the UText. The iterator position is reset to the start. - * - * This function makes a shallow clone of the supplied UText. This means - * that the caller is free to immediately close or otherwise reuse the - * Utext that was passed as a parameter, but that the underlying text itself - * must not be altered while being referenced by the break iterator. - * - * @param text The UText used to change the text. - * @param status Receives any error codes. - * @stable ICU 3.4 - */ - virtual void setText(UText *text, UErrorCode &status); - - /** - * Sets the current iteration position to the beginning of the text, position zero. - * @return The offset of the beginning of the text, zero. - * @stable ICU 2.0 - */ - virtual int32_t first(void); - - /** - * Sets the current iteration position to the end of the text. - * @return The text's past-the-end offset. - * @stable ICU 2.0 - */ - virtual int32_t last(void); - - /** - * Advances the iterator either forward or backward the specified number of steps. - * Negative values move backward, and positive values move forward. This is - * equivalent to repeatedly calling next() or previous(). - * @param n The number of steps to move. The sign indicates the direction - * (negative is backwards, and positive is forwards). - * @return The character offset of the boundary position n boundaries away from - * the current one. - * @stable ICU 2.0 - */ - virtual int32_t next(int32_t n); - - /** - * Advances the iterator to the next boundary position. - * @return The position of the first boundary after this one. - * @stable ICU 2.0 - */ - virtual int32_t next(void); - - /** - * Moves the iterator backwards, to the last boundary preceding this one. - * @return The position of the last boundary position preceding this one. - * @stable ICU 2.0 - */ - virtual int32_t previous(void); - - /** - * Sets the iterator to refer to the first boundary position following - * the specified position. - * @param offset The position from which to begin searching for a break position. - * @return The position of the first break after the current position. - * @stable ICU 2.0 - */ - virtual int32_t following(int32_t offset); - - /** - * Sets the iterator to refer to the last boundary position before the - * specified position. - * @param offset The position to begin searching for a break from. - * @return The position of the last boundary before the starting position. - * @stable ICU 2.0 - */ - virtual int32_t preceding(int32_t offset); - - /** - * Returns true if the specfied position is a boundary position. As a side - * effect, leaves the iterator pointing to the first boundary position at - * or after "offset". - * @param offset the offset to check. - * @return True if "offset" is a boundary position. - * @stable ICU 2.0 - */ - virtual UBool isBoundary(int32_t offset); - - /** - * Returns the current iteration position. - * @return The current iteration position. - * @stable ICU 2.0 - */ - virtual int32_t current(void) const; - - - /** - * Return the status tag from the break rule that determined the most recently - * returned break position. For break rules that do not specify a - * status, a default value of 0 is returned. If more than one break rule - * would cause a boundary to be located at some position in the text, - * the numerically largest of the applicable status values is returned. - *

- * Of the standard types of ICU break iterators, only word break and - * line break provide status values. The values are defined in - * the header file ubrk.h. For Word breaks, the status allows distinguishing between words - * that contain alphabetic letters, "words" that appear to be numbers, - * punctuation and spaces, words containing ideographic characters, and - * more. For Line Break, the status distinguishes between hard (mandatory) breaks - * and soft (potential) break positions. - *

- * getRuleStatus() can be called after obtaining a boundary - * position from next(), previous(), or - * any other break iterator functions that returns a boundary position. - *

- * When creating custom break rules, one is free to define whatever - * status values may be convenient for the application. - *

- * Note: this function is not thread safe. It should not have been - * declared const, and the const remains only for compatibility - * reasons. (The function is logically const, but not bit-wise const). - *

- * @return the status from the break rule that determined the most recently - * returned break position. - * - * @see UWordBreak - * @stable ICU 2.2 - */ - virtual int32_t getRuleStatus() const; - - /** - * Get the status (tag) values from the break rule(s) that determined the most - * recently returned break position. - *

- * The returned status value(s) are stored into an array provided by the caller. - * The values are stored in sorted (ascending) order. - * If the capacity of the output array is insufficient to hold the data, - * the output will be truncated to the available length, and a - * U_BUFFER_OVERFLOW_ERROR will be signaled. - * - * @param fillInVec an array to be filled in with the status values. - * @param capacity the length of the supplied vector. A length of zero causes - * the function to return the number of status values, in the - * normal way, without attemtping to store any values. - * @param status receives error codes. - * @return The number of rule status values from rules that determined - * the most recent boundary returned by the break iterator. - * In the event of a U_BUFFER_OVERFLOW_ERROR, the return value - * is the total number of status values that were available, - * not the reduced number that were actually returned. - * @see getRuleStatus - * @stable ICU 3.0 - */ - virtual int32_t getRuleStatusVec(int32_t *fillInVec, int32_t capacity, UErrorCode &status); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. - * This method is to implement a simple version of RTTI, since not all - * C++ compilers support genuine RTTI. Polymorphic operator==() and - * clone() methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const; - - /** - * Returns the class ID for this class. This is useful only for - * comparing to a return value from getDynamicClassID(). For example: - * - * Base* polymorphic_pointer = createPolymorphicObject(); - * if (polymorphic_pointer->getDynamicClassID() == - * Derived::getStaticClassID()) ... - * - * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Deprecated functionality. Use clone() instead. - * - * Create a clone (copy) of this break iterator in memory provided - * by the caller. The idea is to increase performance by avoiding - * a storage allocation. Use of this functoin is NOT RECOMMENDED. - * Performance gains are minimal, and correct buffer management is - * tricky. Use clone() instead. - * - * @param stackBuffer The pointer to the memory into which the cloned object - * should be placed. If NULL, allocate heap memory - * for the cloned object. - * @param BufferSize The size of the buffer. If zero, return the required - * buffer size, but do not clone the object. If the - * size was too small (but not zero), allocate heap - * storage for the cloned object. - * - * @param status Error status. U_SAFECLONE_ALLOCATED_WARNING will be - * returned if the the provided buffer was too small, and - * the clone was therefore put on the heap. - * - * @return Pointer to the clone object. This may differ from the stackBuffer - * address if the byte alignment of the stack buffer was not suitable - * or if the stackBuffer was too small to hold the clone. - * @deprecated ICU 52. Use clone() instead. - */ - virtual BreakIterator * createBufferClone(void *stackBuffer, - int32_t &BufferSize, - UErrorCode &status); - - - /** - * Return the binary form of compiled break rules, - * which can then be used to create a new break iterator at some - * time in the future. Creating a break iterator from pre-compiled rules - * is much faster than building one from the source form of the - * break rules. - * - * The binary data can only be used with the same version of ICU - * and on the same platform type (processor endian-ness) - * - * @param length Returns the length of the binary data. (Out paramter.) - * - * @return A pointer to the binary (compiled) rule data. The storage - * belongs to the RulesBasedBreakIterator object, not the - * caller, and must not be modified or deleted. - * @stable ICU 4.8 - */ - virtual const uint8_t *getBinaryRules(uint32_t &length); - - /** - * Set the subject text string upon which the break iterator is operating - * without changing any other aspect of the matching state. - * The new and previous text strings must have the same content. - * - * This function is intended for use in environments where ICU is operating on - * strings that may move around in memory. It provides a mechanism for notifying - * ICU that the string has been relocated, and providing a new UText to access the - * string in its new position. - * - * Note that the break iterator implementation never copies the underlying text - * of a string being processed, but always operates directly on the original text - * provided by the user. Refreshing simply drops the references to the old text - * and replaces them with references to the new. - * - * Caution: this function is normally used only by very specialized, - * system-level code. One example use case is with garbage collection that moves - * the text in memory. - * - * @param input The new (moved) text string. - * @param status Receives errors detected by this function. - * @return *this - * - * @stable ICU 49 - */ - virtual RuleBasedBreakIterator &refreshInputText(UText *input, UErrorCode &status); - - -private: - //======================================================================= - // implementation - //======================================================================= - /** - * Dumps caches and performs other actions associated with a complete change - * in text or iteration position. - * @internal - */ - void reset(void); - - /** - * Set the type of the break iterator. - * @internal - */ - void setBreakType(int32_t type); - - /** - * Common initialization function, used by constructors and bufferClone. - * @internal - */ - void init(); - - /** - * This method backs the iterator back up to a "safe position" in the text. - * This is a position that we know, without any context, must be a break position. - * The various calling methods then iterate forward from this safe position to - * the appropriate position to return. (For more information, see the description - * of buildBackwardsStateTable() in RuleBasedBreakIterator.Builder.) - * @param statetable state table used of moving backwards - * @internal - */ - int32_t handlePrevious(const RBBIStateTable *statetable); - - /** - * This method is the actual implementation of the next() method. All iteration - * vectors through here. This method initializes the state machine to state 1 - * and advances through the text character by character until we reach the end - * of the text or the state machine transitions to state 0. We update our return - * value every time the state machine passes through a possible end state. - * @param statetable state table used of moving forwards - * @internal - */ - int32_t handleNext(const RBBIStateTable *statetable); - - - /** - * This is the function that actually implements dictionary-based - * breaking. Covering at least the range from startPos to endPos, - * it checks for dictionary characters, and if it finds them determines - * the appropriate object to deal with them. It may cache found breaks in - * fCachedBreakPositions as it goes. It may well also look at text outside - * the range startPos to endPos. - * If going forward, endPos is the normal Unicode break result, and - * if goind in reverse, startPos is the normal Unicode break result - * @param startPos The start position of a range of text - * @param endPos The end position of a range of text - * @param reverse The call is for the reverse direction - * @internal - */ - int32_t checkDictionary(int32_t startPos, int32_t endPos, UBool reverse); - - - /** - * This function returns the appropriate LanguageBreakEngine for a - * given character c. - * @param c A character in the dictionary set - * @internal - */ - const LanguageBreakEngine *getLanguageBreakEngine(UChar32 c); - - /** - * @internal - */ - void makeRuleStatusValid(); - -}; - -//------------------------------------------------------------------------------ -// -// Inline Functions Definitions ... -// -//------------------------------------------------------------------------------ - -inline UBool RuleBasedBreakIterator::operator!=(const BreakIterator& that) const { - return !operator==(that); -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_BREAK_ITERATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/rbnf.h b/win32/include/spidermonkey/unicode/rbnf.h deleted file mode 100755 index d41ffbe3..00000000 --- a/win32/include/spidermonkey/unicode/rbnf.h +++ /dev/null @@ -1,1078 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 1997-2015, International Business Machines Corporation and others. -* All Rights Reserved. -******************************************************************************* -*/ - -#ifndef RBNF_H -#define RBNF_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Rule Based Number Format - */ - -/** - * \def U_HAVE_RBNF - * This will be 0 if RBNF support is not included in ICU - * and 1 if it is. - * - * @stable ICU 2.4 - */ -#if UCONFIG_NO_FORMATTING -#define U_HAVE_RBNF 0 -#else -#define U_HAVE_RBNF 1 - -#include "unicode/dcfmtsym.h" -#include "unicode/fmtable.h" -#include "unicode/locid.h" -#include "unicode/numfmt.h" -#include "unicode/unistr.h" -#include "unicode/strenum.h" -#include "unicode/brkiter.h" -#include "unicode/upluralrules.h" - -U_NAMESPACE_BEGIN - -class NFRule; -class NFRuleSet; -class LocalizationInfo; -class PluralFormat; -class RuleBasedCollator; - -/** - * Tags for the predefined rulesets. - * - * @stable ICU 2.2 - */ -enum URBNFRuleSetTag { - URBNF_SPELLOUT, - URBNF_ORDINAL, - URBNF_DURATION, - URBNF_NUMBERING_SYSTEM, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal URBNFRuleSetTag value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - URBNF_COUNT -#endif // U_HIDE_DEPRECATED_API -}; - -/** - * The RuleBasedNumberFormat class formats numbers according to a set of rules. This number formatter is - * typically used for spelling out numeric values in words (e.g., 25,3476 as - * "twenty-five thousand three hundred seventy-six" or "vingt-cinq mille trois - * cents soixante-seize" or - * "fünfundzwanzigtausenddreihundertsechsundsiebzig"), but can also be used for - * other complicated formatting tasks, such as formatting a number of seconds as hours, - * minutes and seconds (e.g., 3,730 as "1:02:10"). - * - *

The resources contain three predefined formatters for each locale: spellout, which - * spells out a value in words (123 is "one hundred twenty-three"); ordinal, which - * appends an ordinal suffix to the end of a numeral (123 is "123rd"); and - * duration, which shows a duration in seconds as hours, minutes, and seconds (123 is - * "2:03").  The client can also define more specialized RuleBasedNumberFormats - * by supplying programmer-defined rule sets.

- * - *

The behavior of a RuleBasedNumberFormat is specified by a textual description - * that is either passed to the constructor as a String or loaded from a resource - * bundle. In its simplest form, the description consists of a semicolon-delimited list of rules. - * Each rule has a string of output text and a value or range of values it is applicable to. - * In a typical spellout rule set, the first twenty rules are the words for the numbers from - * 0 to 19:

- * - *
zero; one; two; three; four; five; six; seven; eight; nine;
- * ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen; seventeen; eighteen; nineteen;
- * - *

For larger numbers, we can use the preceding set of rules to format the ones place, and - * we only have to supply the words for the multiples of 10:

- * - *
 20: twenty[->>];
- * 30: thirty[->>];
- * 40: forty[->>];
- * 50: fifty[->>];
- * 60: sixty[->>];
- * 70: seventy[->>];
- * 80: eighty[->>];
- * 90: ninety[->>];
- * - *

In these rules, the base value is spelled out explicitly and set off from the - * rule's output text with a colon. The rules are in a sorted list, and a rule is applicable - * to all numbers from its own base value to one less than the next rule's base value. The - * ">>" token is called a substitution and tells the fomatter to - * isolate the number's ones digit, format it using this same set of rules, and place the - * result at the position of the ">>" token. Text in brackets is omitted if - * the number being formatted is an even multiple of 10 (the hyphen is a literal hyphen; 24 - * is "twenty-four," not "twenty four").

- * - *

For even larger numbers, we can actually look up several parts of the number in the - * list:

- * - *
100: << hundred[ >>];
- * - *

The "<<" represents a new kind of substitution. The << isolates - * the hundreds digit (and any digits to its left), formats it using this same rule set, and - * places the result where the "<<" was. Notice also that the meaning of - * >> has changed: it now refers to both the tens and the ones digits. The meaning of - * both substitutions depends on the rule's base value. The base value determines the rule's divisor, - * which is the highest power of 10 that is less than or equal to the base value (the user - * can change this). To fill in the substitutions, the formatter divides the number being - * formatted by the divisor. The integral quotient is used to fill in the << - * substitution, and the remainder is used to fill in the >> substitution. The meaning - * of the brackets changes similarly: text in brackets is omitted if the value being - * formatted is an even multiple of the rule's divisor. The rules are applied recursively, so - * if a substitution is filled in with text that includes another substitution, that - * substitution is also filled in.

- * - *

This rule covers values up to 999, at which point we add another rule:

- * - *
1000: << thousand[ >>];
- * - *

Again, the meanings of the brackets and substitution tokens shift because the rule's - * base value is a higher power of 10, changing the rule's divisor. This rule can actually be - * used all the way up to 999,999. This allows us to finish out the rules as follows:

- * - *
 1,000,000: << million[ >>];
- * 1,000,000,000: << billion[ >>];
- * 1,000,000,000,000: << trillion[ >>];
- * 1,000,000,000,000,000: OUT OF RANGE!;
- * - *

Commas, periods, and spaces can be used in the base values to improve legibility and - * are ignored by the rule parser. The last rule in the list is customarily treated as an - * "overflow rule," applying to everything from its base value on up, and often (as - * in this example) being used to print out an error message or default representation. - * Notice also that the size of the major groupings in large numbers is controlled by the - * spacing of the rules: because in English we group numbers by thousand, the higher rules - * are separated from each other by a factor of 1,000.

- * - *

To see how these rules actually work in practice, consider the following example: - * Formatting 25,430 with this rule set would work like this:

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
<< thousand >>[the rule whose base value is 1,000 is applicable to 25,340]
twenty->> thousand >>[25,340 over 1,000 is 25. The rule for 20 applies.]
twenty-five thousand >>[25 mod 10 is 5. The rule for 5 is "five."
twenty-five thousand << hundred >>[25,340 mod 1,000 is 340. The rule for 100 applies.]
twenty-five thousand three hundred >>[340 over 100 is 3. The rule for 3 is "three."]
twenty-five thousand three hundred forty[340 mod 100 is 40. The rule for 40 applies. Since 40 divides - * evenly by 10, the hyphen and substitution in the brackets are omitted.]
- * - *

The above syntax suffices only to format positive integers. To format negative numbers, - * we add a special rule:

- * - *
-x: minus >>;
- * - *

This is called a negative-number rule, and is identified by "-x" - * where the base value would be. This rule is used to format all negative numbers. the - * >> token here means "find the number's absolute value, format it with these - * rules, and put the result here."

- * - *

We also add a special rule called a fraction rule for numbers with fractional - * parts:

- * - *
x.x: << point >>;
- * - *

This rule is used for all positive non-integers (negative non-integers pass through the - * negative-number rule first and then through this rule). Here, the << token refers to - * the number's integral part, and the >> to the number's fractional part. The - * fractional part is formatted as a series of single-digit numbers (e.g., 123.456 would be - * formatted as "one hundred twenty-three point four five six").

- * - *

To see how this rule syntax is applied to various languages, examine the resource data.

- * - *

There is actually much more flexibility built into the rule language than the - * description above shows. A formatter may own multiple rule sets, which can be selected by - * the caller, and which can use each other to fill in their substitutions. Substitutions can - * also be filled in with digits, using a DecimalFormat object. There is syntax that can be - * used to alter a rule's divisor in various ways. And there is provision for much more - * flexible fraction handling. A complete description of the rule syntax follows:

- * - *
- * - *

The description of a RuleBasedNumberFormat's behavior consists of one or more rule - * sets. Each rule set consists of a name, a colon, and a list of rules. A rule - * set name must begin with a % sign. Rule sets with names that begin with a single % sign - * are public: the caller can specify that they be used to format and parse numbers. - * Rule sets with names that begin with %% are private: they exist only for the use - * of other rule sets. If a formatter only has one rule set, the name may be omitted.

- * - *

The user can also specify a special "rule set" named %%lenient-parse. - * The body of %%lenient-parse isn't a set of number-formatting rules, but a RuleBasedCollator - * description which is used to define equivalences for lenient parsing. For more information - * on the syntax, see RuleBasedCollator. For more information on lenient parsing, - * see setLenientParse(). Note: symbols that have syntactic meaning - * in collation rules, such as '&', have no particular meaning when appearing outside - * of the lenient-parse rule set.

- * - *

The body of a rule set consists of an ordered, semicolon-delimited list of rules. - * Internally, every rule has a base value, a divisor, rule text, and zero, one, or two substitutions. - * These parameters are controlled by the description syntax, which consists of a rule - * descriptor, a colon, and a rule body.

- * - *

A rule descriptor can take one of the following forms (text in italics is the - * name of a token):

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
bv:bv specifies the rule's base value. bv is a decimal - * number expressed using ASCII digits. bv may contain spaces, period, and commas, - * which are ignored. The rule's divisor is the highest power of 10 less than or equal to - * the base value.
bv/rad:bv specifies the rule's base value. The rule's divisor is the - * highest power of rad less than or equal to the base value.
bv>:bv specifies the rule's base value. To calculate the divisor, - * let the radix be 10, and the exponent be the highest exponent of the radix that yields a - * result less than or equal to the base value. Every > character after the base value - * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix - * raised to the power of the exponent; otherwise, the divisor is 1.
bv/rad>:bv specifies the rule's base value. To calculate the divisor, - * let the radix be rad, and the exponent be the highest exponent of the radix that - * yields a result less than or equal to the base value. Every > character after the radix - * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix - * raised to the power of the exponent; otherwise, the divisor is 1.
-x:The rule is a negative-number rule.
x.x:The rule is an improper fraction rule. If the full stop in - * the middle of the rule name is replaced with the decimal point - * that is used in the language or DecimalFormatSymbols, then that rule will - * have precedence when formatting and parsing this rule. For example, some - * languages use the comma, and can thus be written as x,x instead. For example, - * you can use "x.x: << point >>;x,x: << comma >>;" to - * handle the decimal point that matches the language's natural spelling of - * the punctuation of either the full stop or comma.
0.x:The rule is a proper fraction rule. If the full stop in - * the middle of the rule name is replaced with the decimal point - * that is used in the language or DecimalFormatSymbols, then that rule will - * have precedence when formatting and parsing this rule. For example, some - * languages use the comma, and can thus be written as 0,x instead. For example, - * you can use "0.x: point >>;0,x: comma >>;" to - * handle the decimal point that matches the language's natural spelling of - * the punctuation of either the full stop or comma.
x.0:The rule is a master rule. If the full stop in - * the middle of the rule name is replaced with the decimal point - * that is used in the language or DecimalFormatSymbols, then that rule will - * have precedence when formatting and parsing this rule. For example, some - * languages use the comma, and can thus be written as x,0 instead. For example, - * you can use "x.0: << point;x,0: << comma;" to - * handle the decimal point that matches the language's natural spelling of - * the punctuation of either the full stop or comma.
Inf:The rule for infinity.
NaN:The rule for an IEEE 754 NaN (not a number).
nothingIf the rule's rule descriptor is left out, the base value is one plus the - * preceding rule's base value (or zero if this is the first rule in the list) in a normal - * rule set.  In a fraction rule set, the base value is the same as the preceding rule's - * base value.
- * - *

A rule set may be either a regular rule set or a fraction rule set, depending - * on whether it is used to format a number's integral part (or the whole number) or a - * number's fractional part. Using a rule set to format a rule's fractional part makes it a - * fraction rule set.

- * - *

Which rule is used to format a number is defined according to one of the following - * algorithms: If the rule set is a regular rule set, do the following: - * - *

    - *
  • If the rule set includes a master rule (and the number was passed in as a double), - * use the master rule.  (If the number being formatted was passed in as a long, - * the master rule is ignored.)
  • - *
  • If the number is negative, use the negative-number rule.
  • - *
  • If the number has a fractional part and is greater than 1, use the improper fraction - * rule.
  • - *
  • If the number has a fractional part and is between 0 and 1, use the proper fraction - * rule.
  • - *
  • Binary-search the rule list for the rule with the highest base value less than or equal - * to the number. If that rule has two substitutions, its base value is not an even multiple - * of its divisor, and the number is an even multiple of the rule's divisor, use the - * rule that precedes it in the rule list. Otherwise, use the rule itself.
  • - *
- * - *

If the rule set is a fraction rule set, do the following: - * - *

    - *
  • Ignore negative-number and fraction rules.
  • - *
  • For each rule in the list, multiply the number being formatted (which will always be - * between 0 and 1) by the rule's base value. Keep track of the distance between the result - * the nearest integer.
  • - *
  • Use the rule that produced the result closest to zero in the above calculation. In the - * event of a tie or a direct hit, use the first matching rule encountered. (The idea here is - * to try each rule's base value as a possible denominator of a fraction. Whichever - * denominator produces the fraction closest in value to the number being formatted wins.) If - * the rule following the matching rule has the same base value, use it if the numerator of - * the fraction is anything other than 1; if the numerator is 1, use the original matching - * rule. (This is to allow singular and plural forms of the rule text without a lot of extra - * hassle.)
  • - *
- * - *

A rule's body consists of a string of characters terminated by a semicolon. The rule - * may include zero, one, or two substitution tokens, and a range of text in - * brackets. The brackets denote optional text (and may also include one or both - * substitutions). The exact meanings of the substitution tokens, and under what conditions - * optional text is omitted, depend on the syntax of the substitution token and the context. - * The rest of the text in a rule body is literal text that is output when the rule matches - * the number being formatted.

- * - *

A substitution token begins and ends with a token character. The token - * character and the context together specify a mathematical operation to be performed on the - * number being formatted. An optional substitution descriptor specifies how the - * value resulting from that operation is used to fill in the substitution. The position of - * the substitution token in the rule body specifies the location of the resultant text in - * the original rule text.

- * - *

The meanings of the substitution token characters are as follows:

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
>>in normal ruleDivide the number by the rule's divisor and format the remainder
in negative-number ruleFind the absolute value of the number and format the result
in fraction or master ruleIsolate the number's fractional part and format it.
in rule in fraction rule setNot allowed.
>>>in normal ruleDivide the number by the rule's divisor and format the remainder, - * but bypass the normal rule-selection process and just use the - * rule that precedes this one in this rule list.
in all other rulesNot allowed.
<<in normal ruleDivide the number by the rule's divisor and format the quotient
in negative-number ruleNot allowed.
in fraction or master ruleIsolate the number's integral part and format it.
in rule in fraction rule setMultiply the number by the rule's base value and format the result.
==in all rule setsFormat the number unchanged
[]in normal ruleOmit the optional text if the number is an even multiple of the rule's divisor
in negative-number ruleNot allowed.
in improper-fraction ruleOmit the optional text if the number is between 0 and 1 (same as specifying both an - * x.x rule and a 0.x rule)
in master ruleOmit the optional text if the number is an integer (same as specifying both an x.x - * rule and an x.0 rule)
in proper-fraction ruleNot allowed.
in rule in fraction rule setOmit the optional text if multiplying the number by the rule's base value yields 1.
$(cardinal,plural syntax)$in all rule setsThis provides the ability to choose a word based on the number divided by the radix to the power of the - * exponent of the base value for the specified locale, which is normally equivalent to the << value. - * This uses the cardinal plural rules from PluralFormat. All strings used in the plural format are treated - * as the same base value for parsing.
$(ordinal,plural syntax)$in all rule setsThis provides the ability to choose a word based on the number divided by the radix to the power of the - * exponent of the base value for the specified locale, which is normally equivalent to the << value. - * This uses the ordinal plural rules from PluralFormat. All strings used in the plural format are treated - * as the same base value for parsing.
- * - *

The substitution descriptor (i.e., the text between the token characters) may take one - * of three forms:

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
a rule set namePerform the mathematical operation on the number, and format the result using the - * named rule set.
a DecimalFormat patternPerform the mathematical operation on the number, and format the result using a - * DecimalFormat with the specified pattern.  The pattern must begin with 0 or #.
nothingPerform the mathematical operation on the number, and format the result using the rule - * set containing the current rule, except: - *
    - *
  • You can't have an empty substitution descriptor with a == substitution.
  • - *
  • If you omit the substitution descriptor in a >> substitution in a fraction rule, - * format the result one digit at a time using the rule set containing the current rule.
  • - *
  • If you omit the substitution descriptor in a << substitution in a rule in a - * fraction rule set, format the result using the default rule set for this formatter.
  • - *
- *
- * - *

Whitespace is ignored between a rule set name and a rule set body, between a rule - * descriptor and a rule body, or between rules. If a rule body begins with an apostrophe, - * the apostrophe is ignored, but all text after it becomes significant (this is how you can - * have a rule's rule text begin with whitespace). There is no escape function: the semicolon - * is not allowed in rule set names or in rule text, and the colon is not allowed in rule set - * names. The characters beginning a substitution token are always treated as the beginning - * of a substitution token.

- * - *

See the resource data and the demo program for annotated examples of real rule sets - * using these features.

- * - *

User subclasses are not supported. While clients may write - * subclasses, such code will not necessarily work and will not be - * guaranteed to work stably from release to release. - * - *

Localizations

- *

Constructors are available that allow the specification of localizations for the - * public rule sets (and also allow more control over what public rule sets are available). - * Localization data is represented as a textual description. The description represents - * an array of arrays of string. The first element is an array of the public rule set names, - * each of these must be one of the public rule set names that appear in the rules. Only - * names in this array will be treated as public rule set names by the API. Each subsequent - * element is an array of localizations of these names. The first element of one of these - * subarrays is the locale name, and the remaining elements are localizations of the - * public rule set names, in the same order as they were listed in the first arrray.

- *

In the syntax, angle brackets '<', '>' are used to delimit the arrays, and comma ',' is used - * to separate elements of an array. Whitespace is ignored, unless quoted.

- *

For example:

- * < < %foo, %bar, %baz >,
- *   < en, Foo, Bar, Baz >,
- *   < fr, 'le Foo', 'le Bar', 'le Baz' >
- *   < zh, \\u7532, \\u4e59, \\u4e19 > >
- * 

- * @author Richard Gillam - * @see NumberFormat - * @see DecimalFormat - * @see PluralFormat - * @see PluralRules - * @stable ICU 2.0 - */ -class U_I18N_API RuleBasedNumberFormat : public NumberFormat { -public: - - //----------------------------------------------------------------------- - // constructors - //----------------------------------------------------------------------- - - /** - * Creates a RuleBasedNumberFormat that behaves according to the description - * passed in. The formatter uses the default locale. - * @param rules A description of the formatter's desired behavior. - * See the class documentation for a complete explanation of the description - * syntax. - * @param perror The parse error if an error was encountered. - * @param status The status indicating whether the constructor succeeded. - * @stable ICU 3.2 - */ - RuleBasedNumberFormat(const UnicodeString& rules, UParseError& perror, UErrorCode& status); - - /** - * Creates a RuleBasedNumberFormat that behaves according to the description - * passed in. The formatter uses the default locale. - *

- * The localizations data provides information about the public - * rule sets and their localized display names for different - * locales. The first element in the list is an array of the names - * of the public rule sets. The first element in this array is - * the initial default ruleset. The remaining elements in the - * list are arrays of localizations of the names of the public - * rule sets. Each of these is one longer than the initial array, - * with the first String being the ULocale ID, and the remaining - * Strings being the localizations of the rule set names, in the - * same order as the initial array. Arrays are NULL-terminated. - * @param rules A description of the formatter's desired behavior. - * See the class documentation for a complete explanation of the description - * syntax. - * @param localizations the localization information. - * names in the description. These will be copied by the constructor. - * @param perror The parse error if an error was encountered. - * @param status The status indicating whether the constructor succeeded. - * @stable ICU 3.2 - */ - RuleBasedNumberFormat(const UnicodeString& rules, const UnicodeString& localizations, - UParseError& perror, UErrorCode& status); - - /** - * Creates a RuleBasedNumberFormat that behaves according to the rules - * passed in. The formatter uses the specified locale to determine the - * characters to use when formatting numerals, and to define equivalences - * for lenient parsing. - * @param rules The formatter rules. - * See the class documentation for a complete explanation of the rule - * syntax. - * @param locale A locale that governs which characters are used for - * formatting values in numerals and which characters are equivalent in - * lenient parsing. - * @param perror The parse error if an error was encountered. - * @param status The status indicating whether the constructor succeeded. - * @stable ICU 2.0 - */ - RuleBasedNumberFormat(const UnicodeString& rules, const Locale& locale, - UParseError& perror, UErrorCode& status); - - /** - * Creates a RuleBasedNumberFormat that behaves according to the description - * passed in. The formatter uses the default locale. - *

- * The localizations data provides information about the public - * rule sets and their localized display names for different - * locales. The first element in the list is an array of the names - * of the public rule sets. The first element in this array is - * the initial default ruleset. The remaining elements in the - * list are arrays of localizations of the names of the public - * rule sets. Each of these is one longer than the initial array, - * with the first String being the ULocale ID, and the remaining - * Strings being the localizations of the rule set names, in the - * same order as the initial array. Arrays are NULL-terminated. - * @param rules A description of the formatter's desired behavior. - * See the class documentation for a complete explanation of the description - * syntax. - * @param localizations a list of localizations for the rule set - * names in the description. These will be copied by the constructor. - * @param locale A locale that governs which characters are used for - * formatting values in numerals and which characters are equivalent in - * lenient parsing. - * @param perror The parse error if an error was encountered. - * @param status The status indicating whether the constructor succeeded. - * @stable ICU 3.2 - */ - RuleBasedNumberFormat(const UnicodeString& rules, const UnicodeString& localizations, - const Locale& locale, UParseError& perror, UErrorCode& status); - - /** - * Creates a RuleBasedNumberFormat from a predefined ruleset. The selector - * code choosed among three possible predefined formats: spellout, ordinal, - * and duration. - * @param tag A selector code specifying which kind of formatter to create for that - * locale. There are four legal values: URBNF_SPELLOUT, which creates a formatter that - * spells out a value in words in the desired language, URBNF_ORDINAL, which attaches - * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"), - * URBNF_DURATION, which formats a duration in seconds as hours, minutes, and seconds always rounding down, - * and URBNF_NUMBERING_SYSTEM, which is used to invoke rules for alternate numbering - * systems such as the Hebrew numbering system, or for Roman Numerals, etc. - * @param locale The locale for the formatter. - * @param status The status indicating whether the constructor succeeded. - * @stable ICU 2.0 - */ - RuleBasedNumberFormat(URBNFRuleSetTag tag, const Locale& locale, UErrorCode& status); - - //----------------------------------------------------------------------- - // boilerplate - //----------------------------------------------------------------------- - - /** - * Copy constructor - * @param rhs the object to be copied from. - * @stable ICU 2.6 - */ - RuleBasedNumberFormat(const RuleBasedNumberFormat& rhs); - - /** - * Assignment operator - * @param rhs the object to be copied from. - * @stable ICU 2.6 - */ - RuleBasedNumberFormat& operator=(const RuleBasedNumberFormat& rhs); - - /** - * Release memory allocated for a RuleBasedNumberFormat when you are finished with it. - * @stable ICU 2.6 - */ - virtual ~RuleBasedNumberFormat(); - - /** - * Clone this object polymorphically. The caller is responsible - * for deleting the result when done. - * @return A copy of the object. - * @stable ICU 2.6 - */ - virtual Format* clone(void) const; - - /** - * Return true if the given Format objects are semantically equal. - * Objects of different subclasses are considered unequal. - * @param other the object to be compared with. - * @return true if the given Format objects are semantically equal. - * @stable ICU 2.6 - */ - virtual UBool operator==(const Format& other) const; - -//----------------------------------------------------------------------- -// public API functions -//----------------------------------------------------------------------- - - /** - * return the rules that were provided to the RuleBasedNumberFormat. - * @return the result String that was passed in - * @stable ICU 2.0 - */ - virtual UnicodeString getRules() const; - - /** - * Return the number of public rule set names. - * @return the number of public rule set names. - * @stable ICU 2.0 - */ - virtual int32_t getNumberOfRuleSetNames() const; - - /** - * Return the name of the index'th public ruleSet. If index is not valid, - * the function returns null. - * @param index the index of the ruleset - * @return the name of the index'th public ruleSet. - * @stable ICU 2.0 - */ - virtual UnicodeString getRuleSetName(int32_t index) const; - - /** - * Return the number of locales for which we have localized rule set display names. - * @return the number of locales for which we have localized rule set display names. - * @stable ICU 3.2 - */ - virtual int32_t getNumberOfRuleSetDisplayNameLocales(void) const; - - /** - * Return the index'th display name locale. - * @param index the index of the locale - * @param status set to a failure code when this function fails - * @return the locale - * @see #getNumberOfRuleSetDisplayNameLocales - * @stable ICU 3.2 - */ - virtual Locale getRuleSetDisplayNameLocale(int32_t index, UErrorCode& status) const; - - /** - * Return the rule set display names for the provided locale. These are in the same order - * as those returned by getRuleSetName. The locale is matched against the locales for - * which there is display name data, using normal fallback rules. If no locale matches, - * the default display names are returned. (These are the internal rule set names minus - * the leading '%'.) - * @param index the index of the rule set - * @param locale the locale (returned by getRuleSetDisplayNameLocales) for which the localized - * display name is desired - * @return the display name for the given index, which might be bogus if there is an error - * @see #getRuleSetName - * @stable ICU 3.2 - */ - virtual UnicodeString getRuleSetDisplayName(int32_t index, - const Locale& locale = Locale::getDefault()); - - /** - * Return the rule set display name for the provided rule set and locale. - * The locale is matched against the locales for which there is display name data, using - * normal fallback rules. If no locale matches, the default display name is returned. - * @return the display name for the rule set - * @stable ICU 3.2 - * @see #getRuleSetDisplayName - */ - virtual UnicodeString getRuleSetDisplayName(const UnicodeString& ruleSetName, - const Locale& locale = Locale::getDefault()); - - - using NumberFormat::format; - - /** - * Formats the specified 32-bit number using the default ruleset. - * @param number The number to format. - * @param toAppendTo the string that will hold the (appended) result - * @param pos the fieldposition - * @return A textual representation of the number. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(int32_t number, - UnicodeString& toAppendTo, - FieldPosition& pos) const; - - /** - * Formats the specified 64-bit number using the default ruleset. - * @param number The number to format. - * @param toAppendTo the string that will hold the (appended) result - * @param pos the fieldposition - * @return A textual representation of the number. - * @stable ICU 2.1 - */ - virtual UnicodeString& format(int64_t number, - UnicodeString& toAppendTo, - FieldPosition& pos) const; - /** - * Formats the specified number using the default ruleset. - * @param number The number to format. - * @param toAppendTo the string that will hold the (appended) result - * @param pos the fieldposition - * @return A textual representation of the number. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(double number, - UnicodeString& toAppendTo, - FieldPosition& pos) const; - - /** - * Formats the specified number using the named ruleset. - * @param number The number to format. - * @param ruleSetName The name of the rule set to format the number with. - * This must be the name of a valid public rule set for this formatter. - * @param toAppendTo the string that will hold the (appended) result - * @param pos the fieldposition - * @param status the status - * @return A textual representation of the number. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(int32_t number, - const UnicodeString& ruleSetName, - UnicodeString& toAppendTo, - FieldPosition& pos, - UErrorCode& status) const; - /** - * Formats the specified 64-bit number using the named ruleset. - * @param number The number to format. - * @param ruleSetName The name of the rule set to format the number with. - * This must be the name of a valid public rule set for this formatter. - * @param toAppendTo the string that will hold the (appended) result - * @param pos the fieldposition - * @param status the status - * @return A textual representation of the number. - * @stable ICU 2.1 - */ - virtual UnicodeString& format(int64_t number, - const UnicodeString& ruleSetName, - UnicodeString& toAppendTo, - FieldPosition& pos, - UErrorCode& status) const; - /** - * Formats the specified number using the named ruleset. - * @param number The number to format. - * @param ruleSetName The name of the rule set to format the number with. - * This must be the name of a valid public rule set for this formatter. - * @param toAppendTo the string that will hold the (appended) result - * @param pos the fieldposition - * @param status the status - * @return A textual representation of the number. - * @stable ICU 2.0 - */ - virtual UnicodeString& format(double number, - const UnicodeString& ruleSetName, - UnicodeString& toAppendTo, - FieldPosition& pos, - UErrorCode& status) const; - - using NumberFormat::parse; - - /** - * Parses the specfied string, beginning at the specified position, according - * to this formatter's rules. This will match the string against all of the - * formatter's public rule sets and return the value corresponding to the longest - * parseable substring. This function's behavior is affected by the lenient - * parse mode. - * @param text The string to parse - * @param result the result of the parse, either a double or a long. - * @param parsePosition On entry, contains the position of the first character - * in "text" to examine. On exit, has been updated to contain the position - * of the first character in "text" that wasn't consumed by the parse. - * @see #setLenient - * @stable ICU 2.0 - */ - virtual void parse(const UnicodeString& text, - Formattable& result, - ParsePosition& parsePosition) const; - -#if !UCONFIG_NO_COLLATION - - /** - * Turns lenient parse mode on and off. - * - * When in lenient parse mode, the formatter uses a Collator for parsing the text. - * Only primary differences are treated as significant. This means that case - * differences, accent differences, alternate spellings of the same letter - * (e.g., ae and a-umlaut in German), ignorable characters, etc. are ignored in - * matching the text. In many cases, numerals will be accepted in place of words - * or phrases as well. - * - * For example, all of the following will correctly parse as 255 in English in - * lenient-parse mode: - *
"two hundred fifty-five" - *
"two hundred fifty five" - *
"TWO HUNDRED FIFTY-FIVE" - *
"twohundredfiftyfive" - *
"2 hundred fifty-5" - * - * The Collator used is determined by the locale that was - * passed to this object on construction. The description passed to this object - * on construction may supply additional collation rules that are appended to the - * end of the default collator for the locale, enabling additional equivalences - * (such as adding more ignorable characters or permitting spelled-out version of - * symbols; see the demo program for examples). - * - * It's important to emphasize that even strict parsing is relatively lenient: it - * will accept some text that it won't produce as output. In English, for example, - * it will correctly parse "two hundred zero" and "fifteen hundred". - * - * @param enabled If true, turns lenient-parse mode on; if false, turns it off. - * @see RuleBasedCollator - * @stable ICU 2.0 - */ - virtual void setLenient(UBool enabled); - - /** - * Returns true if lenient-parse mode is turned on. Lenient parsing is off - * by default. - * @return true if lenient-parse mode is turned on. - * @see #setLenient - * @stable ICU 2.0 - */ - virtual inline UBool isLenient(void) const; - -#endif - - /** - * Override the default rule set to use. If ruleSetName is null, reset - * to the initial default rule set. If the rule set is not a public rule set name, - * U_ILLEGAL_ARGUMENT_ERROR is returned in status. - * @param ruleSetName the name of the rule set, or null to reset the initial default. - * @param status set to failure code when a problem occurs. - * @stable ICU 2.6 - */ - virtual void setDefaultRuleSet(const UnicodeString& ruleSetName, UErrorCode& status); - - /** - * Return the name of the current default rule set. If the current rule set is - * not public, returns a bogus (and empty) UnicodeString. - * @return the name of the current default rule set - * @stable ICU 3.0 - */ - virtual UnicodeString getDefaultRuleSetName() const; - - /** - * Set a particular UDisplayContext value in the formatter, such as - * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. Note: For getContext, see - * NumberFormat. - * @param value The UDisplayContext value to set. - * @param status Input/output status. If at entry this indicates a failure - * status, the function will do nothing; otherwise this will be - * updated with any new status from the function. - * @stable ICU 53 - */ - virtual void setContext(UDisplayContext value, UErrorCode& status); - -public: - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.8 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.8 - */ - virtual UClassID getDynamicClassID(void) const; - - /** - * Sets the decimal format symbols, which is generally not changed - * by the programmer or user. The formatter takes ownership of - * symbolsToAdopt; the client must not delete it. - * - * @param symbolsToAdopt DecimalFormatSymbols to be adopted. - * @stable ICU 49 - */ - virtual void adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt); - - /** - * Sets the decimal format symbols, which is generally not changed - * by the programmer or user. A clone of the symbols is created and - * the symbols is _not_ adopted; the client is still responsible for - * deleting it. - * - * @param symbols DecimalFormatSymbols. - * @stable ICU 49 - */ - virtual void setDecimalFormatSymbols(const DecimalFormatSymbols& symbols); - -private: - RuleBasedNumberFormat(); // default constructor not implemented - - // this will ref the localizations if they are not NULL - // caller must deref to get adoption - RuleBasedNumberFormat(const UnicodeString& description, LocalizationInfo* localizations, - const Locale& locale, UParseError& perror, UErrorCode& status); - - void init(const UnicodeString& rules, LocalizationInfo* localizations, UParseError& perror, UErrorCode& status); - void initCapitalizationContextInfo(const Locale& thelocale); - void dispose(); - void stripWhitespace(UnicodeString& src); - void initDefaultRuleSet(); - void format(double number, NFRuleSet& ruleSet); - NFRuleSet* findRuleSet(const UnicodeString& name, UErrorCode& status) const; - - /* friend access */ - friend class NFSubstitution; - friend class NFRule; - friend class NFRuleSet; - friend class FractionalPartSubstitution; - - inline NFRuleSet * getDefaultRuleSet() const; - const RuleBasedCollator * getCollator() const; - DecimalFormatSymbols * initializeDecimalFormatSymbols(UErrorCode &status); - const DecimalFormatSymbols * getDecimalFormatSymbols() const; - NFRule * initializeDefaultInfinityRule(UErrorCode &status); - const NFRule * getDefaultInfinityRule() const; - NFRule * initializeDefaultNaNRule(UErrorCode &status); - const NFRule * getDefaultNaNRule() const; - PluralFormat *createPluralFormat(UPluralType pluralType, const UnicodeString &pattern, UErrorCode& status) const; - UnicodeString& adjustForCapitalizationContext(int32_t startPos, UnicodeString& currentResult) const; - -private: - NFRuleSet **ruleSets; - UnicodeString* ruleSetDescriptions; - int32_t numRuleSets; - NFRuleSet *defaultRuleSet; - Locale locale; - RuleBasedCollator* collator; - DecimalFormatSymbols* decimalFormatSymbols; - NFRule *defaultInfinityRule; - NFRule *defaultNaNRule; - UBool lenient; - UnicodeString* lenientParseRules; - LocalizationInfo* localizations; - UnicodeString originalDescription; - UBool capitalizationInfoSet; - UBool capitalizationForUIListMenu; - UBool capitalizationForStandAlone; - BreakIterator* capitalizationBrkIter; -}; - -// --------------- - -#if !UCONFIG_NO_COLLATION - -inline UBool -RuleBasedNumberFormat::isLenient(void) const { - return lenient; -} - -#endif - -inline NFRuleSet* -RuleBasedNumberFormat::getDefaultRuleSet() const { - return defaultRuleSet; -} - -U_NAMESPACE_END - -/* U_HAVE_RBNF */ -#endif - -/* RBNF_H */ -#endif diff --git a/win32/include/spidermonkey/unicode/rbtz.h b/win32/include/spidermonkey/unicode/rbtz.h deleted file mode 100755 index 4df5850a..00000000 --- a/win32/include/spidermonkey/unicode/rbtz.h +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2007-2013, International Business Machines Corporation and * -* others. All Rights Reserved. * -******************************************************************************* -*/ -#ifndef RBTZ_H -#define RBTZ_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Rule based customizable time zone - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/basictz.h" -#include "unicode/unistr.h" - -U_NAMESPACE_BEGIN - -// forward declaration -class UVector; -struct Transition; - -/** - * a BasicTimeZone subclass implemented in terms of InitialTimeZoneRule and TimeZoneRule instances - * @see BasicTimeZone - * @see InitialTimeZoneRule - * @see TimeZoneRule - */ -class U_I18N_API RuleBasedTimeZone : public BasicTimeZone { -public: - /** - * Constructs a RuleBasedTimeZone object with the ID and the - * InitialTimeZoneRule. The input InitialTimeZoneRule - * is adopted by this RuleBasedTimeZone, thus the caller must not - * delete it. - * @param id The time zone ID. - * @param initialRule The initial time zone rule. - * @stable ICU 3.8 - */ - RuleBasedTimeZone(const UnicodeString& id, InitialTimeZoneRule* initialRule); - - /** - * Copy constructor. - * @param source The RuleBasedTimeZone object to be copied. - * @stable ICU 3.8 - */ - RuleBasedTimeZone(const RuleBasedTimeZone& source); - - /** - * Destructor. - * @stable ICU 3.8 - */ - virtual ~RuleBasedTimeZone(); - - /** - * Assignment operator. - * @param right The object to be copied. - * @stable ICU 3.8 - */ - RuleBasedTimeZone& operator=(const RuleBasedTimeZone& right); - - /** - * Return true if the given TimeZone objects are - * semantically equal. Objects of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZone objects are - *semantically equal. - * @stable ICU 3.8 - */ - virtual UBool operator==(const TimeZone& that) const; - - /** - * Return true if the given TimeZone objects are - * semantically unequal. Objects of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZone objects are - * semantically unequal. - * @stable ICU 3.8 - */ - virtual UBool operator!=(const TimeZone& that) const; - - /** - * Adds the TimeZoneRule which represents time transitions. - * The TimeZoneRule must have start times, that is, the result - * of isTransitionRule() must be true. Otherwise, U_ILLEGAL_ARGUMENT_ERROR - * is set to the error code. - * The input TimeZoneRule is adopted by this - * RuleBasedTimeZone on successful completion of this method, - * thus, the caller must not delete it when no error is returned. - * After all rules are added, the caller must call complete() method to - * make this RuleBasedTimeZone ready to handle common time - * zone functions. - * @param rule The TimeZoneRule. - * @param status Output param to filled in with a success or an error. - * @stable ICU 3.8 - */ - void addTransitionRule(TimeZoneRule* rule, UErrorCode& status); - - /** - * Makes the TimeZoneRule ready to handle actual timezone - * calcuation APIs. This method collects time zone rules specified - * by the caller via the constructor and addTransitionRule() and - * builds internal structure for making the object ready to support - * time zone APIs such as getOffset(), getNextTransition() and others. - * @param status Output param to filled in with a success or an error. - * @stable ICU 3.8 - */ - void complete(UErrorCode& status); - - /** - * Clones TimeZone objects polymorphically. Clients are responsible for deleting - * the TimeZone object cloned. - * - * @return A new copy of this TimeZone object. - * @stable ICU 3.8 - */ - virtual TimeZone* clone(void) const; - - /** - * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time in this time zone, taking daylight savings time into - * account) as of a particular reference date. The reference date is used to determine - * whether daylight savings time is in effect and needs to be figured into the offset - * that is returned (in other words, what is the adjusted GMT offset in this time zone - * at this particular date and time?). For the time zones produced by createTimeZone(), - * the reference data is specified according to the Gregorian calendar, and the date - * and time fields are local standard time. - * - *

Note: Don't call this method. Instead, call the getOffset(UDate...) overload, - * which returns both the raw and the DST offset for a given time. This method - * is retained only for backward compatibility. - * - * @param era The reference date's era - * @param year The reference date's year - * @param month The reference date's month (0-based; 0 is January) - * @param day The reference date's day-in-month (1-based) - * @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday) - * @param millis The reference date's milliseconds in day, local standard time - * @param status Output param to filled in with a success or an error. - * @return The offset in milliseconds to add to GMT to get local time. - * @stable ICU 3.8 - */ - virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, - uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const; - - /** - * Gets the time zone offset, for current date, modified in case of - * daylight savings. This is the offset to add *to* UTC to get local time. - * - *

Note: Don't call this method. Instead, call the getOffset(UDate...) overload, - * which returns both the raw and the DST offset for a given time. This method - * is retained only for backward compatibility. - * - * @param era The reference date's era - * @param year The reference date's year - * @param month The reference date's month (0-based; 0 is January) - * @param day The reference date's day-in-month (1-based) - * @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday) - * @param millis The reference date's milliseconds in day, local standard time - * @param monthLength The length of the given month in days. - * @param status Output param to filled in with a success or an error. - * @return The offset in milliseconds to add to GMT to get local time. - * @stable ICU 3.8 - */ - virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, - uint8_t dayOfWeek, int32_t millis, - int32_t monthLength, UErrorCode& status) const; - - /** - * Returns the time zone raw and GMT offset for the given moment - * in time. Upon return, local-millis = GMT-millis + rawOffset + - * dstOffset. All computations are performed in the proleptic - * Gregorian calendar. The default implementation in the TimeZone - * class delegates to the 8-argument getOffset(). - * - * @param date moment in time for which to return offsets, in - * units of milliseconds from January 1, 1970 0:00 GMT, either GMT - * time or local wall time, depending on `local'. - * @param local if true, `date' is local wall time; otherwise it - * is in GMT time. - * @param rawOffset output parameter to receive the raw offset, that - * is, the offset not including DST adjustments - * @param dstOffset output parameter to receive the DST offset, - * that is, the offset to be added to `rawOffset' to obtain the - * total offset between local and GMT time. If DST is not in - * effect, this value is zero; otherwise it is a positive value, - * typically one hour. - * @param ec input-output error code - * @stable ICU 3.8 - */ - virtual void getOffset(UDate date, UBool local, int32_t& rawOffset, - int32_t& dstOffset, UErrorCode& ec) const; - - /** - * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time, before taking daylight savings time into account). - * - * @param offsetMillis The new raw GMT offset for this time zone. - * @stable ICU 3.8 - */ - virtual void setRawOffset(int32_t offsetMillis); - - /** - * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time, before taking daylight savings time into account). - * - * @return The TimeZone's raw GMT offset. - * @stable ICU 3.8 - */ - virtual int32_t getRawOffset(void) const; - - /** - * Queries if this time zone uses daylight savings time. - * @return true if this time zone uses daylight savings time, - * false, otherwise. - * @stable ICU 3.8 - */ - virtual UBool useDaylightTime(void) const; - - /** - * Queries if the given date is in daylight savings time in - * this time zone. - * This method is wasteful since it creates a new GregorianCalendar and - * deletes it each time it is called. This is a deprecated method - * and provided only for Java compatibility. - * - * @param date the given UDate. - * @param status Output param filled in with success/error code. - * @return true if the given date is in daylight savings time, - * false, otherwise. - * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead. - */ - virtual UBool inDaylightTime(UDate date, UErrorCode& status) const; - - /** - * Returns true if this zone has the same rule and offset as another zone. - * That is, if this zone differs only in ID, if at all. - * @param other the TimeZone object to be compared with - * @return true if the given zone is the same as this one, - * with the possible exception of the ID - * @stable ICU 3.8 - */ - virtual UBool hasSameRules(const TimeZone& other) const; - - /** - * Gets the first time zone transition after the base time. - * @param base The base time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives the first transition after the base time. - * @return TRUE if the transition is found. - * @stable ICU 3.8 - */ - virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const; - - /** - * Gets the most recent time zone transition before the base time. - * @param base The base time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives the most recent transition before the base time. - * @return TRUE if the transition is found. - * @stable ICU 3.8 - */ - virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const; - - /** - * Returns the number of TimeZoneRules which represents time transitions, - * for this time zone, that is, all TimeZoneRules for this time zone except - * InitialTimeZoneRule. The return value range is 0 or any positive value. - * @param status Receives error status code. - * @return The number of TimeZoneRules representing time transitions. - * @stable ICU 3.8 - */ - virtual int32_t countTransitionRules(UErrorCode& status) const; - - /** - * Gets the InitialTimeZoneRule and the set of TimeZoneRule - * which represent time transitions for this time zone. On successful return, - * the argument initial points to non-NULL InitialTimeZoneRule and - * the array trsrules is filled with 0 or multiple TimeZoneRule - * instances up to the size specified by trscount. The results are referencing the - * rule instance held by this time zone instance. Therefore, after this time zone - * is destructed, they are no longer available. - * @param initial Receives the initial timezone rule - * @param trsrules Receives the timezone transition rules - * @param trscount On input, specify the size of the array 'transitions' receiving - * the timezone transition rules. On output, actual number of - * rules filled in the array will be set. - * @param status Receives error status code. - * @stable ICU 3.8 - */ - virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial, - const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const; - - /** - * Get time zone offsets from local wall time. - * @internal - */ - virtual void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt, - int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const; - -private: - void deleteRules(void); - void deleteTransitions(void); - UVector* copyRules(UVector* source); - TimeZoneRule* findRuleInFinal(UDate date, UBool local, - int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const; - UBool findNext(UDate base, UBool inclusive, UDate& time, TimeZoneRule*& from, TimeZoneRule*& to) const; - UBool findPrev(UDate base, UBool inclusive, UDate& time, TimeZoneRule*& from, TimeZoneRule*& to) const; - int32_t getLocalDelta(int32_t rawBefore, int32_t dstBefore, int32_t rawAfter, int32_t dstAfter, - int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const; - UDate getTransitionTime(Transition* transition, UBool local, - int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const; - void getOffsetInternal(UDate date, UBool local, int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt, - int32_t& rawOffset, int32_t& dstOffset, UErrorCode& ec) const; - void completeConst(UErrorCode &status) const; - - InitialTimeZoneRule *fInitialRule; - UVector *fHistoricRules; - UVector *fFinalRules; - UVector *fHistoricTransitions; - UBool fUpToDate; - -public: - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 3.8 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 3.8 - */ - virtual UClassID getDynamicClassID(void) const; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // RBTZ_H - -//eof diff --git a/win32/include/spidermonkey/unicode/regex.h b/win32/include/spidermonkey/unicode/regex.h deleted file mode 100755 index d23a3ab4..00000000 --- a/win32/include/spidermonkey/unicode/regex.h +++ /dev/null @@ -1,1885 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 2002-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* file name: regex.h -* encoding: US-ASCII -* indentation:4 -* -* created on: 2002oct22 -* created by: Andy Heninger -* -* ICU Regular Expressions, API for C++ -*/ - -#ifndef REGEX_H -#define REGEX_H - -//#define REGEX_DEBUG - -/** - * \file - * \brief C++ API: Regular Expressions - * - *

Regular Expression API

- * - *

The ICU API for processing regular expressions consists of two classes, - * RegexPattern and RegexMatcher. - * RegexPattern objects represent a pre-processed, or compiled - * regular expression. They are created from a regular expression pattern string, - * and can be used to create RegexMatcher objects for the pattern.

- * - *

Class RegexMatcher bundles together a regular expression - * pattern and a target string to which the search pattern will be applied. - * RegexMatcher includes API for doing plain find or search - * operations, for search and replace operations, and for obtaining detailed - * information about bounds of a match.

- * - *

Note that by constructing RegexMatcher objects directly from regular - * expression pattern strings application code can be simplified and the explicit - * need for RegexPattern objects can usually be eliminated. - *

- */ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_REGULAR_EXPRESSIONS - -#include "unicode/uobject.h" -#include "unicode/unistr.h" -#include "unicode/utext.h" -#include "unicode/parseerr.h" - -#include "unicode/uregex.h" - -// Forward Declarations - -struct UHashtable; - -U_NAMESPACE_BEGIN - -struct Regex8BitSet; -class RegexCImpl; -class RegexMatcher; -class RegexPattern; -struct REStackFrame; -class RuleBasedBreakIterator; -class UnicodeSet; -class UVector; -class UVector32; -class UVector64; - - -/** - * Class RegexPattern represents a compiled regular expression. It includes - * factory methods for creating a RegexPattern object from the source (string) form - * of a regular expression, methods for creating RegexMatchers that allow the pattern - * to be applied to input text, and a few convenience methods for simple common - * uses of regular expressions. - * - *

Class RegexPattern is not intended to be subclassed.

- * - * @stable ICU 2.4 - */ -class U_I18N_API RegexPattern U_FINAL : public UObject { -public: - - /** - * default constructor. Create a RegexPattern object that refers to no actual - * pattern. Not normally needed; RegexPattern objects are usually - * created using the factory method compile(). - * - * @stable ICU 2.4 - */ - RegexPattern(); - - /** - * Copy Constructor. Create a new RegexPattern object that is equivalent - * to the source object. - * @param source the pattern object to be copied. - * @stable ICU 2.4 - */ - RegexPattern(const RegexPattern &source); - - /** - * Destructor. Note that a RegexPattern object must persist so long as any - * RegexMatcher objects that were created from the RegexPattern are active. - * @stable ICU 2.4 - */ - virtual ~RegexPattern(); - - /** - * Comparison operator. Two RegexPattern objects are considered equal if they - * were constructed from identical source patterns using the same match flag - * settings. - * @param that a RegexPattern object to compare with "this". - * @return TRUE if the objects are equivalent. - * @stable ICU 2.4 - */ - UBool operator==(const RegexPattern& that) const; - - /** - * Comparison operator. Two RegexPattern objects are considered equal if they - * were constructed from identical source patterns using the same match flag - * settings. - * @param that a RegexPattern object to compare with "this". - * @return TRUE if the objects are different. - * @stable ICU 2.4 - */ - inline UBool operator!=(const RegexPattern& that) const {return ! operator ==(that);} - - /** - * Assignment operator. After assignment, this RegexPattern will behave identically - * to the source object. - * @stable ICU 2.4 - */ - RegexPattern &operator =(const RegexPattern &source); - - /** - * Create an exact copy of this RegexPattern object. Since RegexPattern is not - * intended to be subclassed, clone() and the copy construction are - * equivalent operations. - * @return the copy of this RegexPattern - * @stable ICU 2.4 - */ - virtual RegexPattern *clone() const; - - - /** - * Compiles the regular expression in string form into a RegexPattern - * object. These compile methods, rather than the constructors, are the usual - * way that RegexPattern objects are created. - * - *

Note that RegexPattern objects must not be deleted while RegexMatcher - * objects created from the pattern are active. RegexMatchers keep a pointer - * back to their pattern, so premature deletion of the pattern is a - * catastrophic error.

- * - *

All pattern match mode flags are set to their default values.

- * - *

Note that it is often more convenient to construct a RegexMatcher directly - * from a pattern string rather than separately compiling the pattern and - * then creating a RegexMatcher object from the pattern.

- * - * @param regex The regular expression to be compiled. - * @param pe Receives the position (line and column nubers) of any error - * within the regular expression.) - * @param status A reference to a UErrorCode to receive any errors. - * @return A regexPattern object for the compiled pattern. - * - * @stable ICU 2.4 - */ - static RegexPattern * U_EXPORT2 compile( const UnicodeString ®ex, - UParseError &pe, - UErrorCode &status); - - /** - * Compiles the regular expression in string form into a RegexPattern - * object. These compile methods, rather than the constructors, are the usual - * way that RegexPattern objects are created. - * - *

Note that RegexPattern objects must not be deleted while RegexMatcher - * objects created from the pattern are active. RegexMatchers keep a pointer - * back to their pattern, so premature deletion of the pattern is a - * catastrophic error.

- * - *

All pattern match mode flags are set to their default values.

- * - *

Note that it is often more convenient to construct a RegexMatcher directly - * from a pattern string rather than separately compiling the pattern and - * then creating a RegexMatcher object from the pattern.

- * - * @param regex The regular expression to be compiled. Note, the text referred - * to by this UText must not be deleted during the lifetime of the - * RegexPattern object or any RegexMatcher object created from it. - * @param pe Receives the position (line and column nubers) of any error - * within the regular expression.) - * @param status A reference to a UErrorCode to receive any errors. - * @return A regexPattern object for the compiled pattern. - * - * @stable ICU 4.6 - */ - static RegexPattern * U_EXPORT2 compile( UText *regex, - UParseError &pe, - UErrorCode &status); - - /** - * Compiles the regular expression in string form into a RegexPattern - * object using the specified match mode flags. These compile methods, - * rather than the constructors, are the usual way that RegexPattern objects - * are created. - * - *

Note that RegexPattern objects must not be deleted while RegexMatcher - * objects created from the pattern are active. RegexMatchers keep a pointer - * back to their pattern, so premature deletion of the pattern is a - * catastrophic error.

- * - *

Note that it is often more convenient to construct a RegexMatcher directly - * from a pattern string instead of than separately compiling the pattern and - * then creating a RegexMatcher object from the pattern.

- * - * @param regex The regular expression to be compiled. - * @param flags The match mode flags to be used. - * @param pe Receives the position (line and column numbers) of any error - * within the regular expression.) - * @param status A reference to a UErrorCode to receive any errors. - * @return A regexPattern object for the compiled pattern. - * - * @stable ICU 2.4 - */ - static RegexPattern * U_EXPORT2 compile( const UnicodeString ®ex, - uint32_t flags, - UParseError &pe, - UErrorCode &status); - - /** - * Compiles the regular expression in string form into a RegexPattern - * object using the specified match mode flags. These compile methods, - * rather than the constructors, are the usual way that RegexPattern objects - * are created. - * - *

Note that RegexPattern objects must not be deleted while RegexMatcher - * objects created from the pattern are active. RegexMatchers keep a pointer - * back to their pattern, so premature deletion of the pattern is a - * catastrophic error.

- * - *

Note that it is often more convenient to construct a RegexMatcher directly - * from a pattern string instead of than separately compiling the pattern and - * then creating a RegexMatcher object from the pattern.

- * - * @param regex The regular expression to be compiled. Note, the text referred - * to by this UText must not be deleted during the lifetime of the - * RegexPattern object or any RegexMatcher object created from it. - * @param flags The match mode flags to be used. - * @param pe Receives the position (line and column numbers) of any error - * within the regular expression.) - * @param status A reference to a UErrorCode to receive any errors. - * @return A regexPattern object for the compiled pattern. - * - * @stable ICU 4.6 - */ - static RegexPattern * U_EXPORT2 compile( UText *regex, - uint32_t flags, - UParseError &pe, - UErrorCode &status); - - /** - * Compiles the regular expression in string form into a RegexPattern - * object using the specified match mode flags. These compile methods, - * rather than the constructors, are the usual way that RegexPattern objects - * are created. - * - *

Note that RegexPattern objects must not be deleted while RegexMatcher - * objects created from the pattern are active. RegexMatchers keep a pointer - * back to their pattern, so premature deletion of the pattern is a - * catastrophic error.

- * - *

Note that it is often more convenient to construct a RegexMatcher directly - * from a pattern string instead of than separately compiling the pattern and - * then creating a RegexMatcher object from the pattern.

- * - * @param regex The regular expression to be compiled. - * @param flags The match mode flags to be used. - * @param status A reference to a UErrorCode to receive any errors. - * @return A regexPattern object for the compiled pattern. - * - * @stable ICU 2.6 - */ - static RegexPattern * U_EXPORT2 compile( const UnicodeString ®ex, - uint32_t flags, - UErrorCode &status); - - /** - * Compiles the regular expression in string form into a RegexPattern - * object using the specified match mode flags. These compile methods, - * rather than the constructors, are the usual way that RegexPattern objects - * are created. - * - *

Note that RegexPattern objects must not be deleted while RegexMatcher - * objects created from the pattern are active. RegexMatchers keep a pointer - * back to their pattern, so premature deletion of the pattern is a - * catastrophic error.

- * - *

Note that it is often more convenient to construct a RegexMatcher directly - * from a pattern string instead of than separately compiling the pattern and - * then creating a RegexMatcher object from the pattern.

- * - * @param regex The regular expression to be compiled. Note, the text referred - * to by this UText must not be deleted during the lifetime of the - * RegexPattern object or any RegexMatcher object created from it. - * @param flags The match mode flags to be used. - * @param status A reference to a UErrorCode to receive any errors. - * @return A regexPattern object for the compiled pattern. - * - * @stable ICU 4.6 - */ - static RegexPattern * U_EXPORT2 compile( UText *regex, - uint32_t flags, - UErrorCode &status); - - /** - * Get the match mode flags that were used when compiling this pattern. - * @return the match mode flags - * @stable ICU 2.4 - */ - virtual uint32_t flags() const; - - /** - * Creates a RegexMatcher that will match the given input against this pattern. The - * RegexMatcher can then be used to perform match, find or replace operations - * on the input. Note that a RegexPattern object must not be deleted while - * RegexMatchers created from it still exist and might possibly be used again. - *

- * The matcher will retain a reference to the supplied input string, and all regexp - * pattern matching operations happen directly on this original string. It is - * critical that the string not be altered or deleted before use by the regular - * expression operations is complete. - * - * @param input The input string to which the regular expression will be applied. - * @param status A reference to a UErrorCode to receive any errors. - * @return A RegexMatcher object for this pattern and input. - * - * @stable ICU 2.4 - */ - virtual RegexMatcher *matcher(const UnicodeString &input, - UErrorCode &status) const; - -private: - /** - * Cause a compilation error if an application accidentally attempts to - * create a matcher with a (UChar *) string as input rather than - * a UnicodeString. Avoids a dangling reference to a temporary string. - *

- * To efficiently work with UChar *strings, wrap the data in a UnicodeString - * using one of the aliasing constructors, such as - * UnicodeString(UBool isTerminated, const UChar *text, int32_t textLength); - * or in a UText, using - * utext_openUChars(UText *ut, const UChar *text, int64_t textLength, UErrorCode *status); - * - */ - RegexMatcher *matcher(const UChar *input, - UErrorCode &status) const; -public: - - - /** - * Creates a RegexMatcher that will match against this pattern. The - * RegexMatcher can be used to perform match, find or replace operations. - * Note that a RegexPattern object must not be deleted while - * RegexMatchers created from it still exist and might possibly be used again. - * - * @param status A reference to a UErrorCode to receive any errors. - * @return A RegexMatcher object for this pattern and input. - * - * @stable ICU 2.6 - */ - virtual RegexMatcher *matcher(UErrorCode &status) const; - - - /** - * Test whether a string matches a regular expression. This convenience function - * both compiles the regular expression and applies it in a single operation. - * Note that if the same pattern needs to be applied repeatedly, this method will be - * less efficient than creating and reusing a RegexMatcher object. - * - * @param regex The regular expression - * @param input The string data to be matched - * @param pe Receives the position of any syntax errors within the regular expression - * @param status A reference to a UErrorCode to receive any errors. - * @return True if the regular expression exactly matches the full input string. - * - * @stable ICU 2.4 - */ - static UBool U_EXPORT2 matches(const UnicodeString ®ex, - const UnicodeString &input, - UParseError &pe, - UErrorCode &status); - - /** - * Test whether a string matches a regular expression. This convenience function - * both compiles the regular expression and applies it in a single operation. - * Note that if the same pattern needs to be applied repeatedly, this method will be - * less efficient than creating and reusing a RegexMatcher object. - * - * @param regex The regular expression - * @param input The string data to be matched - * @param pe Receives the position of any syntax errors within the regular expression - * @param status A reference to a UErrorCode to receive any errors. - * @return True if the regular expression exactly matches the full input string. - * - * @stable ICU 4.6 - */ - static UBool U_EXPORT2 matches(UText *regex, - UText *input, - UParseError &pe, - UErrorCode &status); - - /** - * Returns the regular expression from which this pattern was compiled. This method will work - * even if the pattern was compiled from a UText. - * - * Note: If the pattern was originally compiled from a UText, and that UText was modified, - * the returned string may no longer reflect the RegexPattern object. - * @stable ICU 2.4 - */ - virtual UnicodeString pattern() const; - - - /** - * Returns the regular expression from which this pattern was compiled. This method will work - * even if the pattern was compiled from a UnicodeString. - * - * Note: This is the original input, not a clone. If the pattern was originally compiled from a - * UText, and that UText was modified, the returned UText may no longer reflect the RegexPattern - * object. - * - * @stable ICU 4.6 - */ - virtual UText *patternText(UErrorCode &status) const; - - - /** - * Get the group number corresponding to a named capture group. - * The returned number can be used with any function that access - * capture groups by number. - * - * The function returns an error status if the specified name does not - * appear in the pattern. - * - * @param groupName The capture group name. - * @param status A UErrorCode to receive any errors. - * - * @stable ICU 55 - */ - virtual int32_t groupNumberFromName(const UnicodeString &groupName, UErrorCode &status) const; - - - /** - * Get the group number corresponding to a named capture group. - * The returned number can be used with any function that access - * capture groups by number. - * - * The function returns an error status if the specified name does not - * appear in the pattern. - * - * @param groupName The capture group name, - * platform invariant characters only. - * @param nameLength The length of the name, or -1 if the name is - * nul-terminated. - * @param status A UErrorCode to receive any errors. - * - * @stable ICU 55 - */ - virtual int32_t groupNumberFromName(const char *groupName, int32_t nameLength, UErrorCode &status) const; - - - /** - * Split a string into fields. Somewhat like split() from Perl or Java. - * Pattern matches identify delimiters that separate the input - * into fields. The input data between the delimiters becomes the - * fields themselves. - * - * If the delimiter pattern includes capture groups, the captured text will - * also appear in the destination array of output strings, interspersed - * with the fields. This is similar to Perl, but differs from Java, - * which ignores the presence of capture groups in the pattern. - * - * Trailing empty fields will always be returned, assuming sufficient - * destination capacity. This differs from the default behavior for Java - * and Perl where trailing empty fields are not returned. - * - * The number of strings produced by the split operation is returned. - * This count includes the strings from capture groups in the delimiter pattern. - * This behavior differs from Java, which ignores capture groups. - * - * For the best performance on split() operations, - * RegexMatcher::split is preferable to this function - * - * @param input The string to be split into fields. The field delimiters - * match the pattern (in the "this" object) - * @param dest An array of UnicodeStrings to receive the results of the split. - * This is an array of actual UnicodeString objects, not an - * array of pointers to strings. Local (stack based) arrays can - * work well here. - * @param destCapacity The number of elements in the destination array. - * If the number of fields found is less than destCapacity, the - * extra strings in the destination array are not altered. - * If the number of destination strings is less than the number - * of fields, the trailing part of the input string, including any - * field delimiters, is placed in the last destination string. - * @param status A reference to a UErrorCode to receive any errors. - * @return The number of fields into which the input string was split. - * @stable ICU 2.4 - */ - virtual int32_t split(const UnicodeString &input, - UnicodeString dest[], - int32_t destCapacity, - UErrorCode &status) const; - - - /** - * Split a string into fields. Somewhat like split() from Perl or Java. - * Pattern matches identify delimiters that separate the input - * into fields. The input data between the delimiters becomes the - * fields themselves. - * - * If the delimiter pattern includes capture groups, the captured text will - * also appear in the destination array of output strings, interspersed - * with the fields. This is similar to Perl, but differs from Java, - * which ignores the presence of capture groups in the pattern. - * - * Trailing empty fields will always be returned, assuming sufficient - * destination capacity. This differs from the default behavior for Java - * and Perl where trailing empty fields are not returned. - * - * The number of strings produced by the split operation is returned. - * This count includes the strings from capture groups in the delimiter pattern. - * This behavior differs from Java, which ignores capture groups. - * - * For the best performance on split() operations, - * RegexMatcher::split is preferable to this function - * - * @param input The string to be split into fields. The field delimiters - * match the pattern (in the "this" object) - * @param dest An array of mutable UText structs to receive the results of the split. - * If a field is NULL, a new UText is allocated to contain the results for - * that field. This new UText is not guaranteed to be mutable. - * @param destCapacity The number of elements in the destination array. - * If the number of fields found is less than destCapacity, the - * extra strings in the destination array are not altered. - * If the number of destination strings is less than the number - * of fields, the trailing part of the input string, including any - * field delimiters, is placed in the last destination string. - * @param status A reference to a UErrorCode to receive any errors. - * @return The number of destination strings used. - * - * @stable ICU 4.6 - */ - virtual int32_t split(UText *input, - UText *dest[], - int32_t destCapacity, - UErrorCode &status) const; - - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.4 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.4 - */ - static UClassID U_EXPORT2 getStaticClassID(); - -private: - // - // Implementation Data - // - UText *fPattern; // The original pattern string. - UnicodeString *fPatternString; // The original pattern UncodeString if relevant - uint32_t fFlags; // The flags used when compiling the pattern. - // - UVector64 *fCompiledPat; // The compiled pattern p-code. - UnicodeString fLiteralText; // Any literal string data from the pattern, - // after un-escaping, for use during the match. - - UVector *fSets; // Any UnicodeSets referenced from the pattern. - Regex8BitSet *fSets8; // (and fast sets for latin-1 range.) - - - UErrorCode fDeferredStatus; // status if some prior error has left this - // RegexPattern in an unusable state. - - int32_t fMinMatchLen; // Minimum Match Length. All matches will have length - // >= this value. For some patterns, this calculated - // value may be less than the true shortest - // possible match. - - int32_t fFrameSize; // Size of a state stack frame in the - // execution engine. - - int32_t fDataSize; // The size of the data needed by the pattern that - // does not go on the state stack, but has just - // a single copy per matcher. - - UVector32 *fGroupMap; // Map from capture group number to position of - // the group's variables in the matcher stack frame. - - UnicodeSet **fStaticSets; // Ptr to static (shared) sets for predefined - // regex character classes, e.g. Word. - - Regex8BitSet *fStaticSets8; // Ptr to the static (shared) latin-1 only - // sets for predefined regex classes. - - int32_t fStartType; // Info on how a match must start. - int32_t fInitialStringIdx; // - int32_t fInitialStringLen; - UnicodeSet *fInitialChars; - UChar32 fInitialChar; - Regex8BitSet *fInitialChars8; - UBool fNeedsAltInput; - - UHashtable *fNamedCaptureMap; // Map from capture group names to numbers. - - friend class RegexCompile; - friend class RegexMatcher; - friend class RegexCImpl; - - // - // Implementation Methods - // - void init(); // Common initialization, for use by constructors. - void zap(); // Common cleanup - - void dumpOp(int32_t index) const; - - public: -#ifndef U_HIDE_INTERNAL_API - /** - * Dump a compiled pattern. Internal debug function. - * @internal - */ - void dumpPattern() const; -#endif /* U_HIDE_INTERNAL_API */ -}; - - - -/** - * class RegexMatcher bundles together a regular expression pattern and - * input text to which the expression can be applied. It includes methods - * for testing for matches, and for find and replace operations. - * - *

Class RegexMatcher is not intended to be subclassed.

- * - * @stable ICU 2.4 - */ -class U_I18N_API RegexMatcher U_FINAL : public UObject { -public: - - /** - * Construct a RegexMatcher for a regular expression. - * This is a convenience method that avoids the need to explicitly create - * a RegexPattern object. Note that if several RegexMatchers need to be - * created for the same expression, it will be more efficient to - * separately create and cache a RegexPattern object, and use - * its matcher() method to create the RegexMatcher objects. - * - * @param regexp The Regular Expression to be compiled. - * @param flags Regular expression options, such as case insensitive matching. - * @see UREGEX_CASE_INSENSITIVE - * @param status Any errors are reported by setting this UErrorCode variable. - * @stable ICU 2.6 - */ - RegexMatcher(const UnicodeString ®exp, uint32_t flags, UErrorCode &status); - - /** - * Construct a RegexMatcher for a regular expression. - * This is a convenience method that avoids the need to explicitly create - * a RegexPattern object. Note that if several RegexMatchers need to be - * created for the same expression, it will be more efficient to - * separately create and cache a RegexPattern object, and use - * its matcher() method to create the RegexMatcher objects. - * - * @param regexp The regular expression to be compiled. - * @param flags Regular expression options, such as case insensitive matching. - * @see UREGEX_CASE_INSENSITIVE - * @param status Any errors are reported by setting this UErrorCode variable. - * - * @stable ICU 4.6 - */ - RegexMatcher(UText *regexp, uint32_t flags, UErrorCode &status); - - /** - * Construct a RegexMatcher for a regular expression. - * This is a convenience method that avoids the need to explicitly create - * a RegexPattern object. Note that if several RegexMatchers need to be - * created for the same expression, it will be more efficient to - * separately create and cache a RegexPattern object, and use - * its matcher() method to create the RegexMatcher objects. - *

- * The matcher will retain a reference to the supplied input string, and all regexp - * pattern matching operations happen directly on the original string. It is - * critical that the string not be altered or deleted before use by the regular - * expression operations is complete. - * - * @param regexp The Regular Expression to be compiled. - * @param input The string to match. The matcher retains a reference to the - * caller's string; mo copy is made. - * @param flags Regular expression options, such as case insensitive matching. - * @see UREGEX_CASE_INSENSITIVE - * @param status Any errors are reported by setting this UErrorCode variable. - * @stable ICU 2.6 - */ - RegexMatcher(const UnicodeString ®exp, const UnicodeString &input, - uint32_t flags, UErrorCode &status); - - /** - * Construct a RegexMatcher for a regular expression. - * This is a convenience method that avoids the need to explicitly create - * a RegexPattern object. Note that if several RegexMatchers need to be - * created for the same expression, it will be more efficient to - * separately create and cache a RegexPattern object, and use - * its matcher() method to create the RegexMatcher objects. - *

- * The matcher will make a shallow clone of the supplied input text, and all regexp - * pattern matching operations happen on this clone. While read-only operations on - * the supplied text are permitted, it is critical that the underlying string not be - * altered or deleted before use by the regular expression operations is complete. - * - * @param regexp The Regular Expression to be compiled. - * @param input The string to match. The matcher retains a shallow clone of the text. - * @param flags Regular expression options, such as case insensitive matching. - * @see UREGEX_CASE_INSENSITIVE - * @param status Any errors are reported by setting this UErrorCode variable. - * - * @stable ICU 4.6 - */ - RegexMatcher(UText *regexp, UText *input, - uint32_t flags, UErrorCode &status); - -private: - /** - * Cause a compilation error if an application accidentally attempts to - * create a matcher with a (UChar *) string as input rather than - * a UnicodeString. Avoids a dangling reference to a temporary string. - *

- * To efficiently work with UChar *strings, wrap the data in a UnicodeString - * using one of the aliasing constructors, such as - * UnicodeString(UBool isTerminated, const UChar *text, int32_t textLength); - * or in a UText, using - * utext_openUChars(UText *ut, const UChar *text, int64_t textLength, UErrorCode *status); - * - */ - RegexMatcher(const UnicodeString ®exp, const UChar *input, - uint32_t flags, UErrorCode &status); -public: - - - /** - * Destructor. - * - * @stable ICU 2.4 - */ - virtual ~RegexMatcher(); - - - /** - * Attempts to match the entire input region against the pattern. - * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if there is a match - * @stable ICU 2.4 - */ - virtual UBool matches(UErrorCode &status); - - - /** - * Resets the matcher, then attempts to match the input beginning - * at the specified startIndex, and extending to the end of the input. - * The input region is reset to include the entire input string. - * A successful match must extend to the end of the input. - * @param startIndex The input string (native) index at which to begin matching. - * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if there is a match - * @stable ICU 2.8 - */ - virtual UBool matches(int64_t startIndex, UErrorCode &status); - - - /** - * Attempts to match the input string, starting from the beginning of the region, - * against the pattern. Like the matches() method, this function - * always starts at the beginning of the input region; - * unlike that function, it does not require that the entire region be matched. - * - *

If the match succeeds then more information can be obtained via the start(), - * end(), and group() functions.

- * - * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if there is a match at the start of the input string. - * @stable ICU 2.4 - */ - virtual UBool lookingAt(UErrorCode &status); - - - /** - * Attempts to match the input string, starting from the specified index, against the pattern. - * The match may be of any length, and is not required to extend to the end - * of the input string. Contrast with match(). - * - *

If the match succeeds then more information can be obtained via the start(), - * end(), and group() functions.

- * - * @param startIndex The input string (native) index at which to begin matching. - * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if there is a match. - * @stable ICU 2.8 - */ - virtual UBool lookingAt(int64_t startIndex, UErrorCode &status); - - - /** - * Find the next pattern match in the input string. - * The find begins searching the input at the location following the end of - * the previous match, or at the start of the string if there is no previous match. - * If a match is found, start(), end() and group() - * will provide more information regarding the match. - *

Note that if the input string is changed by the application, - * use find(startPos, status) instead of find(), because the saved starting - * position may not be valid with the altered input string.

- * @return TRUE if a match is found. - * @stable ICU 2.4 - */ - virtual UBool find(); - - - /** - * Find the next pattern match in the input string. - * The find begins searching the input at the location following the end of - * the previous match, or at the start of the string if there is no previous match. - * If a match is found, start(), end() and group() - * will provide more information regarding the match. - *

Note that if the input string is changed by the application, - * use find(startPos, status) instead of find(), because the saved starting - * position may not be valid with the altered input string.

- * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if a match is found. - * @stable ICU 55 - */ - virtual UBool find(UErrorCode &status); - - /** - * Resets this RegexMatcher and then attempts to find the next substring of the - * input string that matches the pattern, starting at the specified index. - * - * @param start The (native) index in the input string to begin the search. - * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if a match is found. - * @stable ICU 2.4 - */ - virtual UBool find(int64_t start, UErrorCode &status); - - - /** - * Returns a string containing the text matched by the previous match. - * If the pattern can match an empty string, an empty string may be returned. - * @param status A reference to a UErrorCode to receive any errors. - * Possible errors are U_REGEX_INVALID_STATE if no match - * has been attempted or the last match failed. - * @return a string containing the matched input text. - * @stable ICU 2.4 - */ - virtual UnicodeString group(UErrorCode &status) const; - - - /** - * Returns a string containing the text captured by the given group - * during the previous match operation. Group(0) is the entire match. - * - * A zero length string is returned both for capture groups that did not - * participate in the match and for actual zero length matches. - * To distinguish between these two cases use the function start(), - * which returns -1 for non-participating groups. - * - * @param groupNum the capture group number - * @param status A reference to a UErrorCode to receive any errors. - * Possible errors are U_REGEX_INVALID_STATE if no match - * has been attempted or the last match failed and - * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number. - * @return the captured text - * @stable ICU 2.4 - */ - virtual UnicodeString group(int32_t groupNum, UErrorCode &status) const; - - /** - * Returns the number of capturing groups in this matcher's pattern. - * @return the number of capture groups - * @stable ICU 2.4 - */ - virtual int32_t groupCount() const; - - - /** - * Returns a shallow clone of the entire live input string with the UText current native index - * set to the beginning of the requested group. - * - * @param dest The UText into which the input should be cloned, or NULL to create a new UText - * @param group_len A reference to receive the length of the desired capture group - * @param status A reference to a UErrorCode to receive any errors. - * Possible errors are U_REGEX_INVALID_STATE if no match - * has been attempted or the last match failed and - * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number. - * @return dest if non-NULL, a shallow copy of the input text otherwise - * - * @stable ICU 4.6 - */ - virtual UText *group(UText *dest, int64_t &group_len, UErrorCode &status) const; - - /** - * Returns a shallow clone of the entire live input string with the UText current native index - * set to the beginning of the requested group. - * - * A group length of zero is returned both for capture groups that did not - * participate in the match and for actual zero length matches. - * To distinguish between these two cases use the function start(), - * which returns -1 for non-participating groups. - * - * @param groupNum The capture group number. - * @param dest The UText into which the input should be cloned, or NULL to create a new UText. - * @param group_len A reference to receive the length of the desired capture group - * @param status A reference to a UErrorCode to receive any errors. - * Possible errors are U_REGEX_INVALID_STATE if no match - * has been attempted or the last match failed and - * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number. - * @return dest if non-NULL, a shallow copy of the input text otherwise - * - * @stable ICU 4.6 - */ - virtual UText *group(int32_t groupNum, UText *dest, int64_t &group_len, UErrorCode &status) const; - - /** - * Returns the index in the input string of the start of the text matched - * during the previous match operation. - * @param status a reference to a UErrorCode to receive any errors. - * @return The (native) position in the input string of the start of the last match. - * @stable ICU 2.4 - */ - virtual int32_t start(UErrorCode &status) const; - - /** - * Returns the index in the input string of the start of the text matched - * during the previous match operation. - * @param status a reference to a UErrorCode to receive any errors. - * @return The (native) position in the input string of the start of the last match. - * @stable ICU 4.6 - */ - virtual int64_t start64(UErrorCode &status) const; - - - /** - * Returns the index in the input string of the start of the text matched by the - * specified capture group during the previous match operation. Return -1 if - * the capture group exists in the pattern, but was not part of the last match. - * - * @param group the capture group number - * @param status A reference to a UErrorCode to receive any errors. Possible - * errors are U_REGEX_INVALID_STATE if no match has been - * attempted or the last match failed, and - * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number - * @return the (native) start position of substring matched by the specified group. - * @stable ICU 2.4 - */ - virtual int32_t start(int32_t group, UErrorCode &status) const; - - /** - * Returns the index in the input string of the start of the text matched by the - * specified capture group during the previous match operation. Return -1 if - * the capture group exists in the pattern, but was not part of the last match. - * - * @param group the capture group number. - * @param status A reference to a UErrorCode to receive any errors. Possible - * errors are U_REGEX_INVALID_STATE if no match has been - * attempted or the last match failed, and - * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number. - * @return the (native) start position of substring matched by the specified group. - * @stable ICU 4.6 - */ - virtual int64_t start64(int32_t group, UErrorCode &status) const; - - /** - * Returns the index in the input string of the first character following the - * text matched during the previous match operation. - * - * @param status A reference to a UErrorCode to receive any errors. Possible - * errors are U_REGEX_INVALID_STATE if no match has been - * attempted or the last match failed. - * @return the index of the last character matched, plus one. - * The index value returned is a native index, corresponding to - * code units for the underlying encoding type, for example, - * a byte index for UTF-8. - * @stable ICU 2.4 - */ - virtual int32_t end(UErrorCode &status) const; - - /** - * Returns the index in the input string of the first character following the - * text matched during the previous match operation. - * - * @param status A reference to a UErrorCode to receive any errors. Possible - * errors are U_REGEX_INVALID_STATE if no match has been - * attempted or the last match failed. - * @return the index of the last character matched, plus one. - * The index value returned is a native index, corresponding to - * code units for the underlying encoding type, for example, - * a byte index for UTF-8. - * @stable ICU 4.6 - */ - virtual int64_t end64(UErrorCode &status) const; - - - /** - * Returns the index in the input string of the character following the - * text matched by the specified capture group during the previous match operation. - * - * @param group the capture group number - * @param status A reference to a UErrorCode to receive any errors. Possible - * errors are U_REGEX_INVALID_STATE if no match has been - * attempted or the last match failed and - * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number - * @return the index of the first character following the text - * captured by the specified group during the previous match operation. - * Return -1 if the capture group exists in the pattern but was not part of the match. - * The index value returned is a native index, corresponding to - * code units for the underlying encoding type, for example, - * a byte index for UTF8. - * @stable ICU 2.4 - */ - virtual int32_t end(int32_t group, UErrorCode &status) const; - - /** - * Returns the index in the input string of the character following the - * text matched by the specified capture group during the previous match operation. - * - * @param group the capture group number - * @param status A reference to a UErrorCode to receive any errors. Possible - * errors are U_REGEX_INVALID_STATE if no match has been - * attempted or the last match failed and - * U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number - * @return the index of the first character following the text - * captured by the specified group during the previous match operation. - * Return -1 if the capture group exists in the pattern but was not part of the match. - * The index value returned is a native index, corresponding to - * code units for the underlying encoding type, for example, - * a byte index for UTF8. - * @stable ICU 4.6 - */ - virtual int64_t end64(int32_t group, UErrorCode &status) const; - - /** - * Resets this matcher. The effect is to remove any memory of previous matches, - * and to cause subsequent find() operations to begin at the beginning of - * the input string. - * - * @return this RegexMatcher. - * @stable ICU 2.4 - */ - virtual RegexMatcher &reset(); - - - /** - * Resets this matcher, and set the current input position. - * The effect is to remove any memory of previous matches, - * and to cause subsequent find() operations to begin at - * the specified (native) position in the input string. - *

- * The matcher's region is reset to its default, which is the entire - * input string. - *

- * An alternative to this function is to set a match region - * beginning at the desired index. - * - * @return this RegexMatcher. - * @stable ICU 2.8 - */ - virtual RegexMatcher &reset(int64_t index, UErrorCode &status); - - - /** - * Resets this matcher with a new input string. This allows instances of RegexMatcher - * to be reused, which is more efficient than creating a new RegexMatcher for - * each input string to be processed. - * @param input The new string on which subsequent pattern matches will operate. - * The matcher retains a reference to the callers string, and operates - * directly on that. Ownership of the string remains with the caller. - * Because no copy of the string is made, it is essential that the - * caller not delete the string until after regexp operations on it - * are done. - * Note that while a reset on the matcher with an input string that is then - * modified across/during matcher operations may be supported currently for UnicodeString, - * this was not originally intended behavior, and support for this is not guaranteed - * in upcoming versions of ICU. - * @return this RegexMatcher. - * @stable ICU 2.4 - */ - virtual RegexMatcher &reset(const UnicodeString &input); - - - /** - * Resets this matcher with a new input string. This allows instances of RegexMatcher - * to be reused, which is more efficient than creating a new RegexMatcher for - * each input string to be processed. - * @param input The new string on which subsequent pattern matches will operate. - * The matcher makes a shallow clone of the given text; ownership of the - * original string remains with the caller. Because no deep copy of the - * text is made, it is essential that the caller not modify the string - * until after regexp operations on it are done. - * @return this RegexMatcher. - * - * @stable ICU 4.6 - */ - virtual RegexMatcher &reset(UText *input); - - - /** - * Set the subject text string upon which the regular expression is looking for matches - * without changing any other aspect of the matching state. - * The new and previous text strings must have the same content. - * - * This function is intended for use in environments where ICU is operating on - * strings that may move around in memory. It provides a mechanism for notifying - * ICU that the string has been relocated, and providing a new UText to access the - * string in its new position. - * - * Note that the regular expression implementation never copies the underlying text - * of a string being matched, but always operates directly on the original text - * provided by the user. Refreshing simply drops the references to the old text - * and replaces them with references to the new. - * - * Caution: this function is normally used only by very specialized, - * system-level code. One example use case is with garbage collection that moves - * the text in memory. - * - * @param input The new (moved) text string. - * @param status Receives errors detected by this function. - * - * @stable ICU 4.8 - */ - virtual RegexMatcher &refreshInputText(UText *input, UErrorCode &status); - -private: - /** - * Cause a compilation error if an application accidentally attempts to - * reset a matcher with a (UChar *) string as input rather than - * a UnicodeString. Avoids a dangling reference to a temporary string. - *

- * To efficiently work with UChar *strings, wrap the data in a UnicodeString - * using one of the aliasing constructors, such as - * UnicodeString(UBool isTerminated, const UChar *text, int32_t textLength); - * or in a UText, using - * utext_openUChars(UText *ut, const UChar *text, int64_t textLength, UErrorCode *status); - * - */ - RegexMatcher &reset(const UChar *input); -public: - - /** - * Returns the input string being matched. Ownership of the string belongs to - * the matcher; it should not be altered or deleted. This method will work even if the input - * was originally supplied as a UText. - * @return the input string - * @stable ICU 2.4 - */ - virtual const UnicodeString &input() const; - - /** - * Returns the input string being matched. This is the live input text; it should not be - * altered or deleted. This method will work even if the input was originally supplied as - * a UnicodeString. - * @return the input text - * - * @stable ICU 4.6 - */ - virtual UText *inputText() const; - - /** - * Returns the input string being matched, either by copying it into the provided - * UText parameter or by returning a shallow clone of the live input. Note that copying - * the entire input may cause significant performance and memory issues. - * @param dest The UText into which the input should be copied, or NULL to create a new UText - * @param status error code - * @return dest if non-NULL, a shallow copy of the input text otherwise - * - * @stable ICU 4.6 - */ - virtual UText *getInput(UText *dest, UErrorCode &status) const; - - - /** Sets the limits of this matcher's region. - * The region is the part of the input string that will be searched to find a match. - * Invoking this method resets the matcher, and then sets the region to start - * at the index specified by the start parameter and end at the index specified - * by the end parameter. - * - * Depending on the transparency and anchoring being used (see useTransparentBounds - * and useAnchoringBounds), certain constructs such as anchors may behave differently - * at or around the boundaries of the region - * - * The function will fail if start is greater than limit, or if either index - * is less than zero or greater than the length of the string being matched. - * - * @param start The (native) index to begin searches at. - * @param limit The index to end searches at (exclusive). - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.0 - */ - virtual RegexMatcher ®ion(int64_t start, int64_t limit, UErrorCode &status); - - /** - * Identical to region(start, limit, status) but also allows a start position without - * resetting the region state. - * @param regionStart The region start - * @param regionLimit the limit of the region - * @param startIndex The (native) index within the region bounds at which to begin searches. - * @param status A reference to a UErrorCode to receive any errors. - * If startIndex is not within the specified region bounds, - * U_INDEX_OUTOFBOUNDS_ERROR is returned. - * @stable ICU 4.6 - */ - virtual RegexMatcher ®ion(int64_t regionStart, int64_t regionLimit, int64_t startIndex, UErrorCode &status); - - /** - * Reports the start index of this matcher's region. The searches this matcher - * conducts are limited to finding matches within regionStart (inclusive) and - * regionEnd (exclusive). - * - * @return The starting (native) index of this matcher's region. - * @stable ICU 4.0 - */ - virtual int32_t regionStart() const; - - /** - * Reports the start index of this matcher's region. The searches this matcher - * conducts are limited to finding matches within regionStart (inclusive) and - * regionEnd (exclusive). - * - * @return The starting (native) index of this matcher's region. - * @stable ICU 4.6 - */ - virtual int64_t regionStart64() const; - - - /** - * Reports the end (limit) index (exclusive) of this matcher's region. The searches - * this matcher conducts are limited to finding matches within regionStart - * (inclusive) and regionEnd (exclusive). - * - * @return The ending point (native) of this matcher's region. - * @stable ICU 4.0 - */ - virtual int32_t regionEnd() const; - - /** - * Reports the end (limit) index (exclusive) of this matcher's region. The searches - * this matcher conducts are limited to finding matches within regionStart - * (inclusive) and regionEnd (exclusive). - * - * @return The ending point (native) of this matcher's region. - * @stable ICU 4.6 - */ - virtual int64_t regionEnd64() const; - - /** - * Queries the transparency of region bounds for this matcher. - * See useTransparentBounds for a description of transparent and opaque bounds. - * By default, a matcher uses opaque region boundaries. - * - * @return TRUE if this matcher is using opaque bounds, false if it is not. - * @stable ICU 4.0 - */ - virtual UBool hasTransparentBounds() const; - - /** - * Sets the transparency of region bounds for this matcher. - * Invoking this function with an argument of true will set this matcher to use transparent bounds. - * If the boolean argument is false, then opaque bounds will be used. - * - * Using transparent bounds, the boundaries of this matcher's region are transparent - * to lookahead, lookbehind, and boundary matching constructs. Those constructs can - * see text beyond the boundaries of the region while checking for a match. - * - * With opaque bounds, no text outside of the matcher's region is visible to lookahead, - * lookbehind, and boundary matching constructs. - * - * By default, a matcher uses opaque bounds. - * - * @param b TRUE for transparent bounds; FALSE for opaque bounds - * @return This Matcher; - * @stable ICU 4.0 - **/ - virtual RegexMatcher &useTransparentBounds(UBool b); - - - /** - * Return true if this matcher is using anchoring bounds. - * By default, matchers use anchoring region bounds. - * - * @return TRUE if this matcher is using anchoring bounds. - * @stable ICU 4.0 - */ - virtual UBool hasAnchoringBounds() const; - - - /** - * Set whether this matcher is using Anchoring Bounds for its region. - * With anchoring bounds, pattern anchors such as ^ and $ will match at the start - * and end of the region. Without Anchoring Bounds, anchors will only match at - * the positions they would in the complete text. - * - * Anchoring Bounds are the default for regions. - * - * @param b TRUE if to enable anchoring bounds; FALSE to disable them. - * @return This Matcher - * @stable ICU 4.0 - */ - virtual RegexMatcher &useAnchoringBounds(UBool b); - - - /** - * Return TRUE if the most recent matching operation attempted to access - * additional input beyond the available input text. - * In this case, additional input text could change the results of the match. - * - * hitEnd() is defined for both successful and unsuccessful matches. - * In either case hitEnd() will return TRUE if if the end of the text was - * reached at any point during the matching process. - * - * @return TRUE if the most recent match hit the end of input - * @stable ICU 4.0 - */ - virtual UBool hitEnd() const; - - /** - * Return TRUE the most recent match succeeded and additional input could cause - * it to fail. If this method returns false and a match was found, then more input - * might change the match but the match won't be lost. If a match was not found, - * then requireEnd has no meaning. - * - * @return TRUE if more input could cause the most recent match to no longer match. - * @stable ICU 4.0 - */ - virtual UBool requireEnd() const; - - - /** - * Returns the pattern that is interpreted by this matcher. - * @return the RegexPattern for this RegexMatcher - * @stable ICU 2.4 - */ - virtual const RegexPattern &pattern() const; - - - /** - * Replaces every substring of the input that matches the pattern - * with the given replacement string. This is a convenience function that - * provides a complete find-and-replace-all operation. - * - * This method first resets this matcher. It then scans the input string - * looking for matches of the pattern. Input that is not part of any - * match is left unchanged; each match is replaced in the result by the - * replacement string. The replacement string may contain references to - * capture groups. - * - * @param replacement a string containing the replacement text. - * @param status a reference to a UErrorCode to receive any errors. - * @return a string containing the results of the find and replace. - * @stable ICU 2.4 - */ - virtual UnicodeString replaceAll(const UnicodeString &replacement, UErrorCode &status); - - - /** - * Replaces every substring of the input that matches the pattern - * with the given replacement string. This is a convenience function that - * provides a complete find-and-replace-all operation. - * - * This method first resets this matcher. It then scans the input string - * looking for matches of the pattern. Input that is not part of any - * match is left unchanged; each match is replaced in the result by the - * replacement string. The replacement string may contain references to - * capture groups. - * - * @param replacement a string containing the replacement text. - * @param dest a mutable UText in which the results are placed. - * If NULL, a new UText will be created (which may not be mutable). - * @param status a reference to a UErrorCode to receive any errors. - * @return a string containing the results of the find and replace. - * If a pre-allocated UText was provided, it will always be used and returned. - * - * @stable ICU 4.6 - */ - virtual UText *replaceAll(UText *replacement, UText *dest, UErrorCode &status); - - - /** - * Replaces the first substring of the input that matches - * the pattern with the replacement string. This is a convenience - * function that provides a complete find-and-replace operation. - * - *

This function first resets this RegexMatcher. It then scans the input string - * looking for a match of the pattern. Input that is not part - * of the match is appended directly to the result string; the match is replaced - * in the result by the replacement string. The replacement string may contain - * references to captured groups.

- * - *

The state of the matcher (the position at which a subsequent find() - * would begin) after completing a replaceFirst() is not specified. The - * RegexMatcher should be reset before doing additional find() operations.

- * - * @param replacement a string containing the replacement text. - * @param status a reference to a UErrorCode to receive any errors. - * @return a string containing the results of the find and replace. - * @stable ICU 2.4 - */ - virtual UnicodeString replaceFirst(const UnicodeString &replacement, UErrorCode &status); - - - /** - * Replaces the first substring of the input that matches - * the pattern with the replacement string. This is a convenience - * function that provides a complete find-and-replace operation. - * - *

This function first resets this RegexMatcher. It then scans the input string - * looking for a match of the pattern. Input that is not part - * of the match is appended directly to the result string; the match is replaced - * in the result by the replacement string. The replacement string may contain - * references to captured groups.

- * - *

The state of the matcher (the position at which a subsequent find() - * would begin) after completing a replaceFirst() is not specified. The - * RegexMatcher should be reset before doing additional find() operations.

- * - * @param replacement a string containing the replacement text. - * @param dest a mutable UText in which the results are placed. - * If NULL, a new UText will be created (which may not be mutable). - * @param status a reference to a UErrorCode to receive any errors. - * @return a string containing the results of the find and replace. - * If a pre-allocated UText was provided, it will always be used and returned. - * - * @stable ICU 4.6 - */ - virtual UText *replaceFirst(UText *replacement, UText *dest, UErrorCode &status); - - - /** - * Implements a replace operation intended to be used as part of an - * incremental find-and-replace. - * - *

The input string, starting from the end of the previous replacement and ending at - * the start of the current match, is appended to the destination string. Then the - * replacement string is appended to the output string, - * including handling any substitutions of captured text.

- * - *

For simple, prepackaged, non-incremental find-and-replace - * operations, see replaceFirst() or replaceAll().

- * - * @param dest A UnicodeString to which the results of the find-and-replace are appended. - * @param replacement A UnicodeString that provides the text to be substituted for - * the input text that matched the regexp pattern. The replacement - * text may contain references to captured text from the - * input. - * @param status A reference to a UErrorCode to receive any errors. Possible - * errors are U_REGEX_INVALID_STATE if no match has been - * attempted or the last match failed, and U_INDEX_OUTOFBOUNDS_ERROR - * if the replacement text specifies a capture group that - * does not exist in the pattern. - * - * @return this RegexMatcher - * @stable ICU 2.4 - * - */ - virtual RegexMatcher &appendReplacement(UnicodeString &dest, - const UnicodeString &replacement, UErrorCode &status); - - - /** - * Implements a replace operation intended to be used as part of an - * incremental find-and-replace. - * - *

The input string, starting from the end of the previous replacement and ending at - * the start of the current match, is appended to the destination string. Then the - * replacement string is appended to the output string, - * including handling any substitutions of captured text.

- * - *

For simple, prepackaged, non-incremental find-and-replace - * operations, see replaceFirst() or replaceAll().

- * - * @param dest A mutable UText to which the results of the find-and-replace are appended. - * Must not be NULL. - * @param replacement A UText that provides the text to be substituted for - * the input text that matched the regexp pattern. The replacement - * text may contain references to captured text from the input. - * @param status A reference to a UErrorCode to receive any errors. Possible - * errors are U_REGEX_INVALID_STATE if no match has been - * attempted or the last match failed, and U_INDEX_OUTOFBOUNDS_ERROR - * if the replacement text specifies a capture group that - * does not exist in the pattern. - * - * @return this RegexMatcher - * - * @stable ICU 4.6 - */ - virtual RegexMatcher &appendReplacement(UText *dest, - UText *replacement, UErrorCode &status); - - - /** - * As the final step in a find-and-replace operation, append the remainder - * of the input string, starting at the position following the last appendReplacement(), - * to the destination string. appendTail() is intended to be invoked after one - * or more invocations of the RegexMatcher::appendReplacement(). - * - * @param dest A UnicodeString to which the results of the find-and-replace are appended. - * @return the destination string. - * @stable ICU 2.4 - */ - virtual UnicodeString &appendTail(UnicodeString &dest); - - - /** - * As the final step in a find-and-replace operation, append the remainder - * of the input string, starting at the position following the last appendReplacement(), - * to the destination string. appendTail() is intended to be invoked after one - * or more invocations of the RegexMatcher::appendReplacement(). - * - * @param dest A mutable UText to which the results of the find-and-replace are appended. - * Must not be NULL. - * @param status error cod - * @return the destination string. - * - * @stable ICU 4.6 - */ - virtual UText *appendTail(UText *dest, UErrorCode &status); - - - /** - * Split a string into fields. Somewhat like split() from Perl. - * The pattern matches identify delimiters that separate the input - * into fields. The input data between the matches becomes the - * fields themselves. - * - * @param input The string to be split into fields. The field delimiters - * match the pattern (in the "this" object). This matcher - * will be reset to this input string. - * @param dest An array of UnicodeStrings to receive the results of the split. - * This is an array of actual UnicodeString objects, not an - * array of pointers to strings. Local (stack based) arrays can - * work well here. - * @param destCapacity The number of elements in the destination array. - * If the number of fields found is less than destCapacity, the - * extra strings in the destination array are not altered. - * If the number of destination strings is less than the number - * of fields, the trailing part of the input string, including any - * field delimiters, is placed in the last destination string. - * @param status A reference to a UErrorCode to receive any errors. - * @return The number of fields into which the input string was split. - * @stable ICU 2.6 - */ - virtual int32_t split(const UnicodeString &input, - UnicodeString dest[], - int32_t destCapacity, - UErrorCode &status); - - - /** - * Split a string into fields. Somewhat like split() from Perl. - * The pattern matches identify delimiters that separate the input - * into fields. The input data between the matches becomes the - * fields themselves. - * - * @param input The string to be split into fields. The field delimiters - * match the pattern (in the "this" object). This matcher - * will be reset to this input string. - * @param dest An array of mutable UText structs to receive the results of the split. - * If a field is NULL, a new UText is allocated to contain the results for - * that field. This new UText is not guaranteed to be mutable. - * @param destCapacity The number of elements in the destination array. - * If the number of fields found is less than destCapacity, the - * extra strings in the destination array are not altered. - * If the number of destination strings is less than the number - * of fields, the trailing part of the input string, including any - * field delimiters, is placed in the last destination string. - * @param status A reference to a UErrorCode to receive any errors. - * @return The number of fields into which the input string was split. - * - * @stable ICU 4.6 - */ - virtual int32_t split(UText *input, - UText *dest[], - int32_t destCapacity, - UErrorCode &status); - - /** - * Set a processing time limit for match operations with this Matcher. - * - * Some patterns, when matching certain strings, can run in exponential time. - * For practical purposes, the match operation may appear to be in an - * infinite loop. - * When a limit is set a match operation will fail with an error if the - * limit is exceeded. - *

- * The units of the limit are steps of the match engine. - * Correspondence with actual processor time will depend on the speed - * of the processor and the details of the specific pattern, but will - * typically be on the order of milliseconds. - *

- * By default, the matching time is not limited. - *

- * - * @param limit The limit value, or 0 for no limit. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.0 - */ - virtual void setTimeLimit(int32_t limit, UErrorCode &status); - - /** - * Get the time limit, if any, for match operations made with this Matcher. - * - * @return the maximum allowed time for a match, in units of processing steps. - * @stable ICU 4.0 - */ - virtual int32_t getTimeLimit() const; - - /** - * Set the amount of heap storage available for use by the match backtracking stack. - * The matcher is also reset, discarding any results from previous matches. - *

- * ICU uses a backtracking regular expression engine, with the backtrack stack - * maintained on the heap. This function sets the limit to the amount of memory - * that can be used for this purpose. A backtracking stack overflow will - * result in an error from the match operation that caused it. - *

- * A limit is desirable because a malicious or poorly designed pattern can use - * excessive memory, potentially crashing the process. A limit is enabled - * by default. - *

- * @param limit The maximum size, in bytes, of the matching backtrack stack. - * A value of zero means no limit. - * The limit must be greater or equal to zero. - * - * @param status A reference to a UErrorCode to receive any errors. - * - * @stable ICU 4.0 - */ - virtual void setStackLimit(int32_t limit, UErrorCode &status); - - /** - * Get the size of the heap storage available for use by the back tracking stack. - * - * @return the maximum backtracking stack size, in bytes, or zero if the - * stack size is unlimited. - * @stable ICU 4.0 - */ - virtual int32_t getStackLimit() const; - - - /** - * Set a callback function for use with this Matcher. - * During matching operations the function will be called periodically, - * giving the application the opportunity to terminate a long-running - * match. - * - * @param callback A pointer to the user-supplied callback function. - * @param context User context pointer. The value supplied at the - * time the callback function is set will be saved - * and passed to the callback each time that it is called. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.0 - */ - virtual void setMatchCallback(URegexMatchCallback *callback, - const void *context, - UErrorCode &status); - - - /** - * Get the callback function for this URegularExpression. - * - * @param callback Out parameter, receives a pointer to the user-supplied - * callback function. - * @param context Out parameter, receives the user context pointer that - * was set when uregex_setMatchCallback() was called. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.0 - */ - virtual void getMatchCallback(URegexMatchCallback *&callback, - const void *&context, - UErrorCode &status); - - - /** - * Set a progress callback function for use with find operations on this Matcher. - * During find operations, the callback will be invoked after each return from a - * match attempt, giving the application the opportunity to terminate a long-running - * find operation. - * - * @param callback A pointer to the user-supplied callback function. - * @param context User context pointer. The value supplied at the - * time the callback function is set will be saved - * and passed to the callback each time that it is called. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.6 - */ - virtual void setFindProgressCallback(URegexFindProgressCallback *callback, - const void *context, - UErrorCode &status); - - - /** - * Get the find progress callback function for this URegularExpression. - * - * @param callback Out parameter, receives a pointer to the user-supplied - * callback function. - * @param context Out parameter, receives the user context pointer that - * was set when uregex_setFindProgressCallback() was called. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.6 - */ - virtual void getFindProgressCallback(URegexFindProgressCallback *&callback, - const void *&context, - UErrorCode &status); - -#ifndef U_HIDE_INTERNAL_API - /** - * setTrace Debug function, enable/disable tracing of the matching engine. - * For internal ICU development use only. DO NO USE!!!! - * @internal - */ - void setTrace(UBool state); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - -private: - // Constructors and other object boilerplate are private. - // Instances of RegexMatcher can not be assigned, copied, cloned, etc. - RegexMatcher(); // default constructor not implemented - RegexMatcher(const RegexPattern *pat); - RegexMatcher(const RegexMatcher &other); - RegexMatcher &operator =(const RegexMatcher &rhs); - void init(UErrorCode &status); // Common initialization - void init2(UText *t, UErrorCode &e); // Common initialization, part 2. - - friend class RegexPattern; - friend class RegexCImpl; -public: -#ifndef U_HIDE_INTERNAL_API - /** @internal */ - void resetPreserveRegion(); // Reset matcher state, but preserve any region. -#endif /* U_HIDE_INTERNAL_API */ -private: - - // - // MatchAt This is the internal interface to the match engine itself. - // Match status comes back in matcher member variables. - // - void MatchAt(int64_t startIdx, UBool toEnd, UErrorCode &status); - inline void backTrack(int64_t &inputIdx, int32_t &patIdx); - UBool isWordBoundary(int64_t pos); // perform Perl-like \b test - UBool isUWordBoundary(int64_t pos); // perform RBBI based \b test - REStackFrame *resetStack(); - inline REStackFrame *StateSave(REStackFrame *fp, int64_t savePatIdx, UErrorCode &status); - void IncrementTime(UErrorCode &status); - - // Call user find callback function, if set. Return TRUE if operation should be interrupted. - inline UBool findProgressInterrupt(int64_t matchIndex, UErrorCode &status); - - int64_t appendGroup(int32_t groupNum, UText *dest, UErrorCode &status) const; - - UBool findUsingChunk(UErrorCode &status); - void MatchChunkAt(int32_t startIdx, UBool toEnd, UErrorCode &status); - UBool isChunkWordBoundary(int32_t pos); - - const RegexPattern *fPattern; - RegexPattern *fPatternOwned; // Non-NULL if this matcher owns the pattern, and - // should delete it when through. - - const UnicodeString *fInput; // The string being matched. Only used for input() - UText *fInputText; // The text being matched. Is never NULL. - UText *fAltInputText; // A shallow copy of the text being matched. - // Only created if the pattern contains backreferences. - int64_t fInputLength; // Full length of the input text. - int32_t fFrameSize; // The size of a frame in the backtrack stack. - - int64_t fRegionStart; // Start of the input region, default = 0. - int64_t fRegionLimit; // End of input region, default to input.length. - - int64_t fAnchorStart; // Region bounds for anchoring operations (^ or $). - int64_t fAnchorLimit; // See useAnchoringBounds - - int64_t fLookStart; // Region bounds for look-ahead/behind and - int64_t fLookLimit; // and other boundary tests. See - // useTransparentBounds - - int64_t fActiveStart; // Currently active bounds for matching. - int64_t fActiveLimit; // Usually is the same as region, but - // is changed to fLookStart/Limit when - // entering look around regions. - - UBool fTransparentBounds; // True if using transparent bounds. - UBool fAnchoringBounds; // True if using anchoring bounds. - - UBool fMatch; // True if the last attempted match was successful. - int64_t fMatchStart; // Position of the start of the most recent match - int64_t fMatchEnd; // First position after the end of the most recent match - // Zero if no previous match, even when a region - // is active. - int64_t fLastMatchEnd; // First position after the end of the previous match, - // or -1 if there was no previous match. - int64_t fAppendPosition; // First position after the end of the previous - // appendReplacement(). As described by the - // JavaDoc for Java Matcher, where it is called - // "append position" - UBool fHitEnd; // True if the last match touched the end of input. - UBool fRequireEnd; // True if the last match required end-of-input - // (matched $ or Z) - - UVector64 *fStack; - REStackFrame *fFrame; // After finding a match, the last active stack frame, - // which will contain the capture group results. - // NOT valid while match engine is running. - - int64_t *fData; // Data area for use by the compiled pattern. - int64_t fSmallData[8]; // Use this for data if it's enough. - - int32_t fTimeLimit; // Max time (in arbitrary steps) to let the - // match engine run. Zero for unlimited. - - int32_t fTime; // Match time, accumulates while matching. - int32_t fTickCounter; // Low bits counter for time. Counts down StateSaves. - // Kept separately from fTime to keep as much - // code as possible out of the inline - // StateSave function. - - int32_t fStackLimit; // Maximum memory size to use for the backtrack - // stack, in bytes. Zero for unlimited. - - URegexMatchCallback *fCallbackFn; // Pointer to match progress callback funct. - // NULL if there is no callback. - const void *fCallbackContext; // User Context ptr for callback function. - - URegexFindProgressCallback *fFindProgressCallbackFn; // Pointer to match progress callback funct. - // NULL if there is no callback. - const void *fFindProgressCallbackContext; // User Context ptr for callback function. - - - UBool fInputUniStrMaybeMutable; // Set when fInputText wraps a UnicodeString that may be mutable - compatibility. - - UBool fTraceDebug; // Set true for debug tracing of match engine. - - UErrorCode fDeferredStatus; // Save error state that cannot be immediately - // reported, or that permanently disables this matcher. - - RuleBasedBreakIterator *fWordBreakItr; -}; - -U_NAMESPACE_END -#endif // UCONFIG_NO_REGULAR_EXPRESSIONS -#endif diff --git a/win32/include/spidermonkey/unicode/region.h b/win32/include/spidermonkey/unicode/region.h deleted file mode 100755 index 6bb6c746..00000000 --- a/win32/include/spidermonkey/unicode/region.h +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * Copyright (C) 2014-2016, International Business Machines Corporation and others. - * All Rights Reserved. - ******************************************************************************* - */ - -#ifndef REGION_H -#define REGION_H - -/** - * \file - * \brief C++ API: Region classes (territory containment) - */ - -#include "unicode/utypes.h" -#include "unicode/uregion.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/uobject.h" -#include "unicode/uniset.h" -#include "unicode/unistr.h" -#include "unicode/strenum.h" - -U_NAMESPACE_BEGIN - -/** - * Region is the class representing a Unicode Region Code, also known as a - * Unicode Region Subtag, which is defined based upon the BCP 47 standard. We often think of - * "regions" as "countries" when defining the characteristics of a locale. Region codes There are different - * types of region codes that are important to distinguish. - *

- * Macroregion - A code for a "macro geographical (continental) region, geographical sub-region, or - * selected economic and other grouping" as defined in - * UN M.49 (http://unstats.un.org/unsd/methods/m49/m49regin.htm). - * These are typically 3-digit codes, but contain some 2-letter codes, such as the LDML code QO - * added for Outlying Oceania. Not all UNM.49 codes are defined in LDML, but most of them are. - * Macroregions are represented in ICU by one of three region types: WORLD ( region code 001 ), - * CONTINENTS ( regions contained directly by WORLD ), and SUBCONTINENTS ( things contained directly - * by a continent ). - *

- * TERRITORY - A Region that is not a Macroregion. These are typically codes for countries, but also - * include areas that are not separate countries, such as the code "AQ" for Antarctica or the code - * "HK" for Hong Kong (SAR China). Overseas dependencies of countries may or may not have separate - * codes. The codes are typically 2-letter codes aligned with the ISO 3166 standard, but BCP47 allows - * for the use of 3-digit codes in the future. - *

- * UNKNOWN - The code ZZ is defined by Unicode LDML for use to indicate that the Region is unknown, - * or that the value supplied as a region was invalid. - *

- * DEPRECATED - Region codes that have been defined in the past but are no longer in modern usage, - * usually due to a country splitting into multiple territories or changing its name. - *

- * GROUPING - A widely understood grouping of territories that has a well defined membership such - * that a region code has been assigned for it. Some of these are UNM.49 codes that do't fall into - * the world/continent/sub-continent hierarchy, while others are just well known groupings that have - * their own region code. Region "EU" (European Union) is one such region code that is a grouping. - * Groupings will never be returned by the getContainingRegion() API, since a different type of region - * ( WORLD, CONTINENT, or SUBCONTINENT ) will always be the containing region instead. - * - * The Region class is not intended for public subclassing. - * - * @author John Emmons - * @stable ICU 51 - */ - -class U_I18N_API Region : public UObject { -public: - /** - * Destructor. - * @stable ICU 51 - */ - virtual ~Region(); - - /** - * Returns true if the two regions are equal. - * @stable ICU 51 - */ - UBool operator==(const Region &that) const; - - /** - * Returns true if the two regions are NOT equal; that is, if operator ==() returns false. - * @stable ICU 51 - */ - UBool operator!=(const Region &that) const; - - /** - * Returns a pointer to a Region using the given region code. The region code can be either 2-letter ISO code, - * 3-letter ISO code, UNM.49 numeric code, or other valid Unicode Region Code as defined by the LDML specification. - * The identifier will be canonicalized internally using the supplemental metadata as defined in the CLDR. - * If the region code is NULL or not recognized, the appropriate error code will be set ( U_ILLEGAL_ARGUMENT_ERROR ) - * @stable ICU 51 - */ - static const Region* U_EXPORT2 getInstance(const char *region_code, UErrorCode &status); - - /** - * Returns a pointer to a Region using the given numeric region code. If the numeric region code is not recognized, - * the appropriate error code will be set ( U_ILLEGAL_ARGUMENT_ERROR ). - * @stable ICU 51 - */ - static const Region* U_EXPORT2 getInstance (int32_t code, UErrorCode &status); - - /** - * Returns an enumeration over the IDs of all known regions that match the given type. - * @stable ICU 55 - */ - static StringEnumeration* U_EXPORT2 getAvailable(URegionType type, UErrorCode &status); - - /** - * Returns a pointer to the region that contains this region. Returns NULL if this region is code "001" (World) - * or "ZZ" (Unknown region). For example, calling this method with region "IT" (Italy) returns the - * region "039" (Southern Europe). - * @stable ICU 51 - */ - const Region* getContainingRegion() const; - - /** - * Return a pointer to the region that geographically contains this region and matches the given type, - * moving multiple steps up the containment chain if necessary. Returns NULL if no containing region can be found - * that matches the given type. Note: The URegionTypes = "URGN_GROUPING", "URGN_DEPRECATED", or "URGN_UNKNOWN" - * are not appropriate for use in this API. NULL will be returned in this case. For example, calling this method - * with region "IT" (Italy) for type "URGN_CONTINENT" returns the region "150" ( Europe ). - * @stable ICU 51 - */ - const Region* getContainingRegion(URegionType type) const; - - /** - * Return an enumeration over the IDs of all the regions that are immediate children of this region in the - * region hierarchy. These returned regions could be either macro regions, territories, or a mixture of the two, - * depending on the containment data as defined in CLDR. This API may return NULL if this region doesn't have - * any sub-regions. For example, calling this method with region "150" (Europe) returns an enumeration containing - * the various sub regions of Europe - "039" (Southern Europe) - "151" (Eastern Europe) - "154" (Northern Europe) - * and "155" (Western Europe). - * @stable ICU 55 - */ - StringEnumeration* getContainedRegions(UErrorCode &status) const; - - /** - * Returns an enumeration over the IDs of all the regions that are children of this region anywhere in the region - * hierarchy and match the given type. This API may return an empty enumeration if this region doesn't have any - * sub-regions that match the given type. For example, calling this method with region "150" (Europe) and type - * "URGN_TERRITORY" returns a set containing all the territories in Europe ( "FR" (France) - "IT" (Italy) - "DE" (Germany) etc. ) - * @stable ICU 55 - */ - StringEnumeration* getContainedRegions( URegionType type, UErrorCode &status ) const; - - /** - * Returns true if this region contains the supplied other region anywhere in the region hierarchy. - * @stable ICU 51 - */ - UBool contains(const Region &other) const; - - /** - * For deprecated regions, return an enumeration over the IDs of the regions that are the preferred replacement - * regions for this region. Returns null for a non-deprecated region. For example, calling this method with region - * "SU" (Soviet Union) would return a list of the regions containing "RU" (Russia), "AM" (Armenia), "AZ" (Azerbaijan), etc... - * @stable ICU 55 - */ - StringEnumeration* getPreferredValues(UErrorCode &status) const; - - /** - * Return this region's canonical region code. - * @stable ICU 51 - */ - const char* getRegionCode() const; - - /** - * Return this region's numeric code. - * Returns a negative value if the given region does not have a numeric code assigned to it. - * @stable ICU 51 - */ - int32_t getNumericCode() const; - - /** - * Returns the region type of this region. - * @stable ICU 51 - */ - URegionType getType() const; - -#ifndef U_HIDE_INTERNAL_API - /** - * Cleans up statically allocated memory. - * @internal - */ - static void cleanupRegionData(); -#endif /* U_HIDE_INTERNAL_API */ - -private: - char id[4]; - UnicodeString idStr; - int32_t code; - URegionType type; - Region *containingRegion; - UVector *containedRegions; - UVector *preferredValues; - - /** - * Default Constructor. Internal - use factory methods only. - */ - Region(); - - - /* - * Initializes the region data from the ICU resource bundles. The region data - * contains the basic relationships such as which regions are known, what the numeric - * codes are, any known aliases, and the territory containment data. - * - * If the region data has already loaded, then this method simply returns without doing - * anything meaningful. - */ - - static void U_CALLCONV loadRegionData(UErrorCode &status); - -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ -#endif // REGION_H - -//eof diff --git a/win32/include/spidermonkey/unicode/reldatefmt.h b/win32/include/spidermonkey/unicode/reldatefmt.h deleted file mode 100755 index e91d2066..00000000 --- a/win32/include/spidermonkey/unicode/reldatefmt.h +++ /dev/null @@ -1,523 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -***************************************************************************** -* Copyright (C) 2014-2016, International Business Machines Corporation and -* others. -* All Rights Reserved. -***************************************************************************** -* -* File RELDATEFMT.H -***************************************************************************** -*/ - -#ifndef __RELDATEFMT_H -#define __RELDATEFMT_H - -#include "unicode/utypes.h" -#include "unicode/uobject.h" -#include "unicode/udisplaycontext.h" -#include "unicode/ureldatefmt.h" -#include "unicode/locid.h" - -/** - * \file - * \brief C++ API: Formats relative dates such as "1 day ago" or "tomorrow" - */ - -#if !UCONFIG_NO_FORMATTING - -/** - * Represents the unit for formatting a relative date. e.g "in 5 days" - * or "in 3 months" - * @stable ICU 53 - */ -typedef enum UDateRelativeUnit { - - /** - * Seconds - * @stable ICU 53 - */ - UDAT_RELATIVE_SECONDS, - - /** - * Minutes - * @stable ICU 53 - */ - UDAT_RELATIVE_MINUTES, - - /** - * Hours - * @stable ICU 53 - */ - UDAT_RELATIVE_HOURS, - - /** - * Days - * @stable ICU 53 - */ - UDAT_RELATIVE_DAYS, - - /** - * Weeks - * @stable ICU 53 - */ - UDAT_RELATIVE_WEEKS, - - /** - * Months - * @stable ICU 53 - */ - UDAT_RELATIVE_MONTHS, - - /** - * Years - * @stable ICU 53 - */ - UDAT_RELATIVE_YEARS, - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UDateRelativeUnit value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UDAT_RELATIVE_UNIT_COUNT -#endif // U_HIDE_DEPRECATED_API -} UDateRelativeUnit; - -/** - * Represents an absolute unit. - * @stable ICU 53 - */ -typedef enum UDateAbsoluteUnit { - - // Days of week have to remain together and in order from Sunday to - // Saturday. - /** - * Sunday - * @stable ICU 53 - */ - UDAT_ABSOLUTE_SUNDAY, - - /** - * Monday - * @stable ICU 53 - */ - UDAT_ABSOLUTE_MONDAY, - - /** - * Tuesday - * @stable ICU 53 - */ - UDAT_ABSOLUTE_TUESDAY, - - /** - * Wednesday - * @stable ICU 53 - */ - UDAT_ABSOLUTE_WEDNESDAY, - - /** - * Thursday - * @stable ICU 53 - */ - UDAT_ABSOLUTE_THURSDAY, - - /** - * Friday - * @stable ICU 53 - */ - UDAT_ABSOLUTE_FRIDAY, - - /** - * Saturday - * @stable ICU 53 - */ - UDAT_ABSOLUTE_SATURDAY, - - /** - * Day - * @stable ICU 53 - */ - UDAT_ABSOLUTE_DAY, - - /** - * Week - * @stable ICU 53 - */ - UDAT_ABSOLUTE_WEEK, - - /** - * Month - * @stable ICU 53 - */ - UDAT_ABSOLUTE_MONTH, - - /** - * Year - * @stable ICU 53 - */ - UDAT_ABSOLUTE_YEAR, - - /** - * Now - * @stable ICU 53 - */ - UDAT_ABSOLUTE_NOW, - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UDateAbsoluteUnit value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UDAT_ABSOLUTE_UNIT_COUNT -#endif // U_HIDE_DEPRECATED_API -} UDateAbsoluteUnit; - -/** - * Represents a direction for an absolute unit e.g "Next Tuesday" - * or "Last Tuesday" - * @stable ICU 53 - */ -typedef enum UDateDirection { - - /** - * Two before. Not fully supported in every locale. - * @stable ICU 53 - */ - UDAT_DIRECTION_LAST_2, - - /** - * Last - * @stable ICU 53 - */ - UDAT_DIRECTION_LAST, - - /** - * This - * @stable ICU 53 - */ - UDAT_DIRECTION_THIS, - - /** - * Next - * @stable ICU 53 - */ - UDAT_DIRECTION_NEXT, - - /** - * Two after. Not fully supported in every locale. - * @stable ICU 53 - */ - UDAT_DIRECTION_NEXT_2, - - /** - * Plain, which means the absence of a qualifier. - * @stable ICU 53 - */ - UDAT_DIRECTION_PLAIN, - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UDateDirection value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UDAT_DIRECTION_COUNT -#endif // U_HIDE_DEPRECATED_API -} UDateDirection; - -#if !UCONFIG_NO_BREAK_ITERATION - -U_NAMESPACE_BEGIN - -class RelativeDateTimeCacheData; -class SharedNumberFormat; -class SharedPluralRules; -class SharedBreakIterator; -class NumberFormat; -class UnicodeString; - -/** - * Formats simple relative dates. There are two types of relative dates that - * it handles: - *

    - *
  • relative dates with a quantity e.g "in 5 days"
  • - *
  • relative dates without a quantity e.g "next Tuesday"
  • - *
- *

- * This API is very basic and is intended to be a building block for more - * fancy APIs. The caller tells it exactly what to display in a locale - * independent way. While this class automatically provides the correct plural - * forms, the grammatical form is otherwise as neutral as possible. It is the - * caller's responsibility to handle cut-off logic such as deciding between - * displaying "in 7 days" or "in 1 week." This API supports relative dates - * involving one single unit. This API does not support relative dates - * involving compound units, - * e.g "in 5 days and 4 hours" nor does it support parsing. - *

- * This class is mostly thread safe and immutable with the following caveats: - * 1. The assignment operator violates Immutability. It must not be used - * concurrently with other operations. - * 2. Caller must not hold onto adopted pointers. - *

- * This class is not intended for public subclassing. - *

- * Here are some examples of use: - *

- *
- * UErrorCode status = U_ZERO_ERROR;
- * UnicodeString appendTo;
- * RelativeDateTimeFormatter fmt(status);
- * // Appends "in 1 day"
- * fmt.format(
- *     1, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, appendTo, status);
- * // Appends "in 3 days"
- * fmt.format(
- *     3, UDAT_DIRECTION_NEXT, UDAT_RELATIVE_DAYS, appendTo, status);
- * // Appends "3.2 years ago"
- * fmt.format(
- *     3.2, UDAT_DIRECTION_LAST, UDAT_RELATIVE_YEARS, appendTo, status);
- * // Appends "last Sunday"
- * fmt.format(UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
- * // Appends "this Sunday"
- * fmt.format(UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
- * // Appends "next Sunday"
- * fmt.format(UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
- * // Appends "Sunday"
- * fmt.format(UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_SUNDAY, appendTo, status);
- *
- * // Appends "yesterday"
- * fmt.format(UDAT_DIRECTION_LAST, UDAT_ABSOLUTE_DAY, appendTo, status);
- * // Appends "today"
- * fmt.format(UDAT_DIRECTION_THIS, UDAT_ABSOLUTE_DAY, appendTo, status);
- * // Appends "tomorrow"
- * fmt.format(UDAT_DIRECTION_NEXT, UDAT_ABSOLUTE_DAY, appendTo, status);
- * // Appends "now"
- * fmt.format(UDAT_DIRECTION_PLAIN, UDAT_ABSOLUTE_NOW, appendTo, status);
- *
- * 
- *
- *

- * In the future, we may add more forms, such as abbreviated/short forms - * (3 secs ago), and relative day periods ("yesterday afternoon"), etc. - * - * The RelativeDateTimeFormatter class is not intended for public subclassing. - * - * @stable ICU 53 - */ -class U_I18N_API RelativeDateTimeFormatter : public UObject { -public: - - /** - * Create RelativeDateTimeFormatter with default locale. - * @stable ICU 53 - */ - RelativeDateTimeFormatter(UErrorCode& status); - - /** - * Create RelativeDateTimeFormatter with given locale. - * @stable ICU 53 - */ - RelativeDateTimeFormatter(const Locale& locale, UErrorCode& status); - - /** - * Create RelativeDateTimeFormatter with given locale and NumberFormat. - * - * @param locale the locale - * @param nfToAdopt Constructed object takes ownership of this pointer. - * It is an error for caller to delete this pointer or change its - * contents after calling this constructor. - * @status Any error is returned here. - * @stable ICU 53 - */ - RelativeDateTimeFormatter( - const Locale& locale, NumberFormat *nfToAdopt, UErrorCode& status); - - /** - * Create RelativeDateTimeFormatter with given locale, NumberFormat, - * and capitalization context. - * - * @param locale the locale - * @param nfToAdopt Constructed object takes ownership of this pointer. - * It is an error for caller to delete this pointer or change its - * contents after calling this constructor. Caller may pass NULL for - * this argument if they want default number format behavior. - * @param style the format style. The UDAT_RELATIVE bit field has no effect. - * @param capitalizationContext A value from UDisplayContext that pertains to - * capitalization. - * @status Any error is returned here. - * @stable ICU 54 - */ - RelativeDateTimeFormatter( - const Locale& locale, - NumberFormat *nfToAdopt, - UDateRelativeDateTimeFormatterStyle style, - UDisplayContext capitalizationContext, - UErrorCode& status); - - /** - * Copy constructor. - * @stable ICU 53 - */ - RelativeDateTimeFormatter(const RelativeDateTimeFormatter& other); - - /** - * Assignment operator. - * @stable ICU 53 - */ - RelativeDateTimeFormatter& operator=( - const RelativeDateTimeFormatter& other); - - /** - * Destructor. - * @stable ICU 53 - */ - virtual ~RelativeDateTimeFormatter(); - - /** - * Formats a relative date with a quantity such as "in 5 days" or - * "3 months ago" - * @param quantity The numerical amount e.g 5. This value is formatted - * according to this object's NumberFormat object. - * @param direction NEXT means a future relative date; LAST means a past - * relative date. If direction is anything else, this method sets - * status to U_ILLEGAL_ARGUMENT_ERROR. - * @param unit the unit e.g day? month? year? - * @param appendTo The string to which the formatted result will be - * appended - * @param status ICU error code returned here. - * @return appendTo - * @stable ICU 53 - */ - UnicodeString& format( - double quantity, - UDateDirection direction, - UDateRelativeUnit unit, - UnicodeString& appendTo, - UErrorCode& status) const; - - /** - * Formats a relative date without a quantity. - * @param direction NEXT, LAST, THIS, etc. - * @param unit e.g SATURDAY, DAY, MONTH - * @param appendTo The string to which the formatted result will be - * appended. If the value of direction is documented as not being fully - * supported in all locales then this method leaves appendTo unchanged if - * no format string is available. - * @param status ICU error code returned here. - * @return appendTo - * @stable ICU 53 - */ - UnicodeString& format( - UDateDirection direction, - UDateAbsoluteUnit unit, - UnicodeString& appendTo, - UErrorCode& status) const; - -#ifndef U_HIDE_DRAFT_API - /** - * Format a combination of URelativeDateTimeUnit and numeric offset - * using a numeric style, e.g. "1 week ago", "in 1 week", - * "5 weeks ago", "in 5 weeks". - * - * @param offset The signed offset for the specified unit. This - * will be formatted according to this object's - * NumberFormat object. - * @param unit The unit to use when formatting the relative - * date, e.g. UDAT_REL_UNIT_WEEK, - * UDAT_REL_UNIT_FRIDAY. - * @param appendTo The string to which the formatted result will be - * appended. - * @param status ICU error code returned here. - * @return appendTo - * @draft ICU 57 - */ - UnicodeString& formatNumeric( - double offset, - URelativeDateTimeUnit unit, - UnicodeString& appendTo, - UErrorCode& status) const; - - /** - * Format a combination of URelativeDateTimeUnit and numeric offset - * using a text style if possible, e.g. "last week", "this week", - * "next week", "yesterday", "tomorrow". Falls back to numeric - * style if no appropriate text term is available for the specified - * offset in the object's locale. - * - * @param offset The signed offset for the specified unit. - * @param unit The unit to use when formatting the relative - * date, e.g. UDAT_REL_UNIT_WEEK, - * UDAT_REL_UNIT_FRIDAY. - * @param appendTo The string to which the formatted result will be - * appended. - * @param status ICU error code returned here. - * @return appendTo - * @draft ICU 57 - */ - UnicodeString& format( - double offset, - URelativeDateTimeUnit unit, - UnicodeString& appendTo, - UErrorCode& status) const; -#endif /* U_HIDE_DRAFT_API */ - - /** - * Combines a relative date string and a time string in this object's - * locale. This is done with the same date-time separator used for the - * default calendar in this locale. - * - * @param relativeDateString the relative date, e.g 'yesterday' - * @param timeString the time e.g '3:45' - * @param appendTo concatenated date and time appended here - * @param status ICU error code returned here. - * @return appendTo - * @stable ICU 53 - */ - UnicodeString& combineDateAndTime( - const UnicodeString& relativeDateString, - const UnicodeString& timeString, - UnicodeString& appendTo, - UErrorCode& status) const; - - /** - * Returns the NumberFormat this object is using. - * - * @stable ICU 53 - */ - const NumberFormat& getNumberFormat() const; - - /** - * Returns the capitalization context. - * - * @stable ICU 54 - */ - UDisplayContext getCapitalizationContext() const; - - /** - * Returns the format style. - * - * @stable ICU 54 - */ - UDateRelativeDateTimeFormatterStyle getFormatStyle() const; - -private: - const RelativeDateTimeCacheData* fCache; - const SharedNumberFormat *fNumberFormat; - const SharedPluralRules *fPluralRules; - UDateRelativeDateTimeFormatterStyle fStyle; - UDisplayContext fContext; - const SharedBreakIterator *fOptBreakIterator; - Locale fLocale; - void init( - NumberFormat *nfToAdopt, - BreakIterator *brkIter, - UErrorCode &status); - void adjustForContext(UnicodeString &) const; -}; - -U_NAMESPACE_END - -#endif /* !UCONFIG_NO_BREAK_ITERATION */ -#endif /* !UCONFIG_NO_FORMATTING */ -#endif /* __RELDATEFMT_H */ diff --git a/win32/include/spidermonkey/unicode/rep.h b/win32/include/spidermonkey/unicode/rep.h deleted file mode 100755 index 6ffd1f49..00000000 --- a/win32/include/spidermonkey/unicode/rep.h +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -************************************************************************** -* Copyright (C) 1999-2012, International Business Machines Corporation and -* others. All Rights Reserved. -************************************************************************** -* Date Name Description -* 11/17/99 aliu Creation. Ported from java. Modified to -* match current UnicodeString API. Forced -* to use name "handleReplaceBetween" because -* of existing methods in UnicodeString. -************************************************************************** -*/ - -#ifndef REP_H -#define REP_H - -#include "unicode/uobject.h" - -/** - * \file - * \brief C++ API: Replaceable String - */ - -U_NAMESPACE_BEGIN - -class UnicodeString; - -/** - * Replaceable is an abstract base class representing a - * string of characters that supports the replacement of a range of - * itself with a new string of characters. It is used by APIs that - * change a piece of text while retaining metadata. Metadata is data - * other than the Unicode characters returned by char32At(). One - * example of metadata is style attributes; another is an edit - * history, marking each character with an author and revision number. - * - *

An implicit aspect of the Replaceable API is that - * during a replace operation, new characters take on the metadata of - * the old characters. For example, if the string "the bold - * font" has range (4, 8) replaced with "strong", then it becomes "the - * strong font". - * - *

Replaceable specifies ranges using a start - * offset and a limit offset. The range of characters thus specified - * includes the characters at offset start..limit-1. That is, the - * start offset is inclusive, and the limit offset is exclusive. - * - *

Replaceable also includes API to access characters - * in the string: length(), charAt(), - * char32At(), and extractBetween(). - * - *

For a subclass to support metadata, typical behavior of - * replace() is the following: - *

    - *
  • Set the metadata of the new text to the metadata of the first - * character replaced
  • - *
  • If no characters are replaced, use the metadata of the - * previous character
  • - *
  • If there is no previous character (i.e. start == 0), use the - * following character
  • - *
  • If there is no following character (i.e. the replaceable was - * empty), use default metadata.
    - *
  • If the code point U+FFFF is seen, it should be interpreted as - * a special marker having no metadata
  • - *
  • - *
- * If this is not the behavior, the subclass should document any differences. - * @author Alan Liu - * @stable ICU 2.0 - */ -class U_COMMON_API Replaceable : public UObject { - -public: - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~Replaceable(); - - /** - * Returns the number of 16-bit code units in the text. - * @return number of 16-bit code units in text - * @stable ICU 1.8 - */ - inline int32_t length() const; - - /** - * Returns the 16-bit code unit at the given offset into the text. - * @param offset an integer between 0 and length()-1 - * inclusive - * @return 16-bit code unit of text at given offset - * @stable ICU 1.8 - */ - inline UChar charAt(int32_t offset) const; - - /** - * Returns the 32-bit code point at the given 16-bit offset into - * the text. This assumes the text is stored as 16-bit code units - * with surrogate pairs intermixed. If the offset of a leading or - * trailing code unit of a surrogate pair is given, return the - * code point of the surrogate pair. - * - * @param offset an integer between 0 and length()-1 - * inclusive - * @return 32-bit code point of text at given offset - * @stable ICU 1.8 - */ - inline UChar32 char32At(int32_t offset) const; - - /** - * Copies characters in the range [start, limit) - * into the UnicodeString target. - * @param start offset of first character which will be copied - * @param limit offset immediately following the last character to - * be copied - * @param target UnicodeString into which to copy characters. - * @return A reference to target - * @stable ICU 2.1 - */ - virtual void extractBetween(int32_t start, - int32_t limit, - UnicodeString& target) const = 0; - - /** - * Replaces a substring of this object with the given text. If the - * characters being replaced have metadata, the new characters - * that replace them should be given the same metadata. - * - *

Subclasses must ensure that if the text between start and - * limit is equal to the replacement text, that replace has no - * effect. That is, any metadata - * should be unaffected. In addition, subclasses are encouraged to - * check for initial and trailing identical characters, and make a - * smaller replacement if possible. This will preserve as much - * metadata as possible. - * @param start the beginning index, inclusive; 0 <= start - * <= limit. - * @param limit the ending index, exclusive; start <= limit - * <= length(). - * @param text the text to replace characters start - * to limit - 1 - * @stable ICU 2.0 - */ - virtual void handleReplaceBetween(int32_t start, - int32_t limit, - const UnicodeString& text) = 0; - // Note: All other methods in this class take the names of - // existing UnicodeString methods. This method is the exception. - // It is named differently because all replace methods of - // UnicodeString return a UnicodeString&. The 'between' is - // required in order to conform to the UnicodeString naming - // convention; API taking start/length are named , and - // those taking start/limit are named . The - // 'handle' is added because 'replaceBetween' and - // 'doReplaceBetween' are already taken. - - /** - * Copies a substring of this object, retaining metadata. - * This method is used to duplicate or reorder substrings. - * The destination index must not overlap the source range. - * - * @param start the beginning index, inclusive; 0 <= start <= - * limit. - * @param limit the ending index, exclusive; start <= limit <= - * length(). - * @param dest the destination index. The characters from - * start..limit-1 will be copied to dest. - * Implementations of this method may assume that dest <= start || - * dest >= limit. - * @stable ICU 2.0 - */ - virtual void copy(int32_t start, int32_t limit, int32_t dest) = 0; - - /** - * Returns true if this object contains metadata. If a - * Replaceable object has metadata, calls to the Replaceable API - * must be made so as to preserve metadata. If it does not, calls - * to the Replaceable API may be optimized to improve performance. - * The default implementation returns true. - * @return true if this object contains metadata - * @stable ICU 2.2 - */ - virtual UBool hasMetaData() const; - - /** - * Clone this object, an instance of a subclass of Replaceable. - * Clones can be used concurrently in multiple threads. - * If a subclass does not implement clone(), or if an error occurs, - * then NULL is returned. - * The clone functions in all subclasses return a pointer to a Replaceable - * because some compilers do not support covariant (same-as-this) - * return types; cast to the appropriate subclass if necessary. - * The caller must delete the clone. - * - * @return a clone of this object - * - * @see getDynamicClassID - * @stable ICU 2.6 - */ - virtual Replaceable *clone() const; - -protected: - - /** - * Default constructor. - * @stable ICU 2.4 - */ - inline Replaceable(); - - /* - * Assignment operator not declared. The compiler will provide one - * which does nothing since this class does not contain any data members. - * API/code coverage may show the assignment operator as present and - * untested - ignore. - * Subclasses need this assignment operator if they use compiler-provided - * assignment operators of their own. An alternative to not declaring one - * here would be to declare and empty-implement a protected or public one. - Replaceable &Replaceable::operator=(const Replaceable &); - */ - - /** - * Virtual version of length(). - * @stable ICU 2.4 - */ - virtual int32_t getLength() const = 0; - - /** - * Virtual version of charAt(). - * @stable ICU 2.4 - */ - virtual UChar getCharAt(int32_t offset) const = 0; - - /** - * Virtual version of char32At(). - * @stable ICU 2.4 - */ - virtual UChar32 getChar32At(int32_t offset) const = 0; -}; - -inline Replaceable::Replaceable() {} - -inline int32_t -Replaceable::length() const { - return getLength(); -} - -inline UChar -Replaceable::charAt(int32_t offset) const { - return getCharAt(offset); -} - -inline UChar32 -Replaceable::char32At(int32_t offset) const { - return getChar32At(offset); -} - -// There is no rep.cpp, see unistr.cpp for Replaceable function implementations. - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/resbund.h b/win32/include/spidermonkey/unicode/resbund.h deleted file mode 100755 index 927a65b7..00000000 --- a/win32/include/spidermonkey/unicode/resbund.h +++ /dev/null @@ -1,492 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 1996-2013, International Business Machines Corporation -* and others. All Rights Reserved. -* -****************************************************************************** -* -* File resbund.h -* -* CREATED BY -* Richard Gillam -* -* Modification History: -* -* Date Name Description -* 2/5/97 aliu Added scanForLocaleInFile. Added -* constructor which attempts to read resource bundle -* from a specific file, without searching other files. -* 2/11/97 aliu Added UErrorCode return values to constructors. Fixed -* infinite loops in scanForFile and scanForLocale. -* Modified getRawResourceData to not delete storage -* in localeData and resourceData which it doesn't own. -* Added Mac compatibility #ifdefs for tellp() and -* ios::nocreate. -* 2/18/97 helena Updated with 100% documentation coverage. -* 3/13/97 aliu Rewrote to load in entire resource bundle and store -* it as a Hashtable of ResourceBundleData objects. -* Added state table to govern parsing of files. -* Modified to load locale index out of new file -* distinct from default.txt. -* 3/25/97 aliu Modified to support 2-d arrays, needed for timezone -* data. Added support for custom file suffixes. Again, -* needed to support timezone data. -* 4/7/97 aliu Cleaned up. -* 03/02/99 stephen Removed dependency on FILE*. -* 03/29/99 helena Merged Bertrand and Stephen's changes. -* 06/11/99 stephen Removed parsing of .txt files. -* Reworked to use new binary format. -* Cleaned up. -* 06/14/99 stephen Removed methods taking a filename suffix. -* 11/09/99 weiv Added getLocale(), fRealLocale, removed fRealLocaleID -****************************************************************************** -*/ - -#ifndef RESBUND_H -#define RESBUND_H - -#include "unicode/utypes.h" -#include "unicode/uobject.h" -#include "unicode/ures.h" -#include "unicode/unistr.h" -#include "unicode/locid.h" - -/** - * \file - * \brief C++ API: Resource Bundle - */ - -U_NAMESPACE_BEGIN - -/** - * A class representing a collection of resource information pertaining to a given - * locale. A resource bundle provides a way of accessing locale- specfic information in - * a data file. You create a resource bundle that manages the resources for a given - * locale and then ask it for individual resources. - *

- * Resource bundles in ICU4C are currently defined using text files which conform to the following - * BNF definition. - * More on resource bundle concepts and syntax can be found in the - * Users Guide. - *

- * - * The ResourceBundle class is not suitable for subclassing. - * - * @stable ICU 2.0 - */ -class U_COMMON_API ResourceBundle : public UObject { -public: - /** - * Constructor - * - * @param packageName The packageName and locale together point to an ICU udata object, - * as defined by udata_open( packageName, "res", locale, err) - * or equivalent. Typically, packageName will refer to a (.dat) file, or to - * a package registered with udata_setAppData(). Using a full file or directory - * pathname for packageName is deprecated. - * @param locale This is the locale this resource bundle is for. To get resources - * for the French locale, for example, you would create a - * ResourceBundle passing Locale::FRENCH for the "locale" parameter, - * and all subsequent calls to that resource bundle will return - * resources that pertain to the French locale. If the caller doesn't - * pass a locale parameter, the default locale for the system (as - * returned by Locale::getDefault()) will be used. - * @param err The Error Code. - * The UErrorCode& err parameter is used to return status information to the user. To - * check whether the construction succeeded or not, you should check the value of - * U_SUCCESS(err). If you wish more detailed information, you can check for - * informational error results which still indicate success. U_USING_FALLBACK_WARNING - * indicates that a fall back locale was used. For example, 'de_CH' was requested, - * but nothing was found there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that - * the default locale data was used; neither the requested locale nor any of its - * fall back locales could be found. - * @stable ICU 2.0 - */ - ResourceBundle(const UnicodeString& packageName, - const Locale& locale, - UErrorCode& err); - - /** - * Construct a resource bundle for the default bundle in the specified package. - * - * @param packageName The packageName and locale together point to an ICU udata object, - * as defined by udata_open( packageName, "res", locale, err) - * or equivalent. Typically, packageName will refer to a (.dat) file, or to - * a package registered with udata_setAppData(). Using a full file or directory - * pathname for packageName is deprecated. - * @param err A UErrorCode value - * @stable ICU 2.0 - */ - ResourceBundle(const UnicodeString& packageName, - UErrorCode& err); - - /** - * Construct a resource bundle for the ICU default bundle. - * - * @param err A UErrorCode value - * @stable ICU 2.0 - */ - ResourceBundle(UErrorCode &err); - - /** - * Standard constructor, onstructs a resource bundle for the locale-specific - * bundle in the specified package. - * - * @param packageName The packageName and locale together point to an ICU udata object, - * as defined by udata_open( packageName, "res", locale, err) - * or equivalent. Typically, packageName will refer to a (.dat) file, or to - * a package registered with udata_setAppData(). Using a full file or directory - * pathname for packageName is deprecated. - * NULL is used to refer to ICU data. - * @param locale The locale for which to open a resource bundle. - * @param err A UErrorCode value - * @stable ICU 2.0 - */ - ResourceBundle(const char* packageName, - const Locale& locale, - UErrorCode& err); - - /** - * Copy constructor. - * - * @param original The resource bundle to copy. - * @stable ICU 2.0 - */ - ResourceBundle(const ResourceBundle &original); - - /** - * Constructor from a C UResourceBundle. The resource bundle is - * copied and not adopted. ures_close will still need to be used on the - * original resource bundle. - * - * @param res A pointer to the C resource bundle. - * @param status A UErrorCode value. - * @stable ICU 2.0 - */ - ResourceBundle(UResourceBundle *res, - UErrorCode &status); - - /** - * Assignment operator. - * - * @param other The resource bundle to copy. - * @stable ICU 2.0 - */ - ResourceBundle& - operator=(const ResourceBundle& other); - - /** Destructor. - * @stable ICU 2.0 - */ - virtual ~ResourceBundle(); - - /** - * Clone this object. - * Clones can be used concurrently in multiple threads. - * If an error occurs, then NULL is returned. - * The caller must delete the clone. - * - * @return a clone of this object - * - * @see getDynamicClassID - * @stable ICU 2.8 - */ - ResourceBundle *clone() const; - - /** - * Returns the size of a resource. Size for scalar types is always 1, and for vector/table types is - * the number of child resources. - * @warning Integer array is treated as a scalar type. There are no - * APIs to access individual members of an integer array. It - * is always returned as a whole. - * - * @return number of resources in a given resource. - * @stable ICU 2.0 - */ - int32_t - getSize(void) const; - - /** - * returns a string from a string resource type - * - * @param status fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * could be a warning - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file. - * @stable ICU 2.0 - */ - UnicodeString - getString(UErrorCode& status) const; - - /** - * returns a binary data from a resource. Can be used at most primitive resource types (binaries, - * strings, ints) - * - * @param len fills in the length of resulting byte chunk - * @param status fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * could be a warning - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return a pointer to a chunk of unsigned bytes which live in a memory mapped/DLL file. - * @stable ICU 2.0 - */ - const uint8_t* - getBinary(int32_t& len, UErrorCode& status) const; - - - /** - * returns an integer vector from a resource. - * - * @param len fills in the length of resulting integer vector - * @param status fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * could be a warning - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return a pointer to a vector of integers that lives in a memory mapped/DLL file. - * @stable ICU 2.0 - */ - const int32_t* - getIntVector(int32_t& len, UErrorCode& status) const; - - /** - * returns an unsigned integer from a resource. - * This integer is originally 28 bits. - * - * @param status fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * could be a warning - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return an unsigned integer value - * @stable ICU 2.0 - */ - uint32_t - getUInt(UErrorCode& status) const; - - /** - * returns a signed integer from a resource. - * This integer is originally 28 bit and the sign gets propagated. - * - * @param status fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * could be a warning - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return a signed integer value - * @stable ICU 2.0 - */ - int32_t - getInt(UErrorCode& status) const; - - /** - * Checks whether the resource has another element to iterate over. - * - * @return TRUE if there are more elements, FALSE if there is no more elements - * @stable ICU 2.0 - */ - UBool - hasNext(void) const; - - /** - * Resets the internal context of a resource so that iteration starts from the first element. - * - * @stable ICU 2.0 - */ - void - resetIterator(void); - - /** - * Returns the key associated with this resource. Not all the resources have a key - only - * those that are members of a table. - * - * @return a key associated to this resource, or NULL if it doesn't have a key - * @stable ICU 2.0 - */ - const char* - getKey(void) const; - - /** - * Gets the locale ID of the resource bundle as a string. - * Same as getLocale().getName() . - * - * @return the locale ID of the resource bundle as a string - * @stable ICU 2.0 - */ - const char* - getName(void) const; - - - /** - * Returns the type of a resource. Available types are defined in enum UResType - * - * @return type of the given resource. - * @stable ICU 2.0 - */ - UResType - getType(void) const; - - /** - * Returns the next resource in a given resource or NULL if there are no more resources - * - * @param status fills in the outgoing error code - * @return ResourceBundle object. - * @stable ICU 2.0 - */ - ResourceBundle - getNext(UErrorCode& status); - - /** - * Returns the next string in a resource or NULL if there are no more resources - * to iterate over. - * - * @param status fills in the outgoing error code - * @return an UnicodeString object. - * @stable ICU 2.0 - */ - UnicodeString - getNextString(UErrorCode& status); - - /** - * Returns the next string in a resource or NULL if there are no more resources - * to iterate over. - * - * @param key fill in for key associated with this string - * @param status fills in the outgoing error code - * @return an UnicodeString object. - * @stable ICU 2.0 - */ - UnicodeString - getNextString(const char ** key, - UErrorCode& status); - - /** - * Returns the resource in a resource at the specified index. - * - * @param index an index to the wanted resource. - * @param status fills in the outgoing error code - * @return ResourceBundle object. If there is an error, resource is invalid. - * @stable ICU 2.0 - */ - ResourceBundle - get(int32_t index, - UErrorCode& status) const; - - /** - * Returns the string in a given resource at the specified index. - * - * @param index an index to the wanted string. - * @param status fills in the outgoing error code - * @return an UnicodeString object. If there is an error, string is bogus - * @stable ICU 2.0 - */ - UnicodeString - getStringEx(int32_t index, - UErrorCode& status) const; - - /** - * Returns a resource in a resource that has a given key. This procedure works only with table - * resources. - * - * @param key a key associated with the wanted resource - * @param status fills in the outgoing error code. - * @return ResourceBundle object. If there is an error, resource is invalid. - * @stable ICU 2.0 - */ - ResourceBundle - get(const char* key, - UErrorCode& status) const; - - /** - * Returns a string in a resource that has a given key. This procedure works only with table - * resources. - * - * @param key a key associated with the wanted string - * @param status fills in the outgoing error code - * @return an UnicodeString object. If there is an error, string is bogus - * @stable ICU 2.0 - */ - UnicodeString - getStringEx(const char* key, - UErrorCode& status) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Return the version number associated with this ResourceBundle as a string. Please - * use getVersion, as this method is going to be deprecated. - * - * @return A version number string as specified in the resource bundle or its parent. - * The caller does not own this string. - * @see getVersion - * @deprecated ICU 2.8 Use getVersion instead. - */ - const char* - getVersionNumber(void) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Return the version number associated with this ResourceBundle as a UVersionInfo array. - * - * @param versionInfo A UVersionInfo array that is filled with the version number - * as specified in the resource bundle or its parent. - * @stable ICU 2.0 - */ - void - getVersion(UVersionInfo versionInfo) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Return the Locale associated with this ResourceBundle. - * - * @return a Locale object - * @deprecated ICU 2.8 Use getLocale(ULocDataLocaleType type, UErrorCode &status) overload instead. - */ - const Locale& - getLocale(void) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Return the Locale associated with this ResourceBundle. - * @param type You can choose between requested, valid and actual - * locale. For description see the definition of - * ULocDataLocaleType in uloc.h - * @param status just for catching illegal arguments - * - * @return a Locale object - * @stable ICU 2.8 - */ - const Locale - getLocale(ULocDataLocaleType type, UErrorCode &status) const; -#ifndef U_HIDE_INTERNAL_API - /** - * This API implements multilevel fallback - * @internal - */ - ResourceBundle - getWithFallback(const char* key, UErrorCode& status); -#endif /* U_HIDE_INTERNAL_API */ - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - -private: - ResourceBundle(); // default constructor not implemented - - UResourceBundle *fResource; - void constructForLocale(const UnicodeString& path, const Locale& locale, UErrorCode& error); - Locale *fLocale; -}; - -U_NAMESPACE_END -#endif diff --git a/win32/include/spidermonkey/unicode/schriter.h b/win32/include/spidermonkey/unicode/schriter.h deleted file mode 100755 index e52b97c2..00000000 --- a/win32/include/spidermonkey/unicode/schriter.h +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 1998-2005, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* -* File schriter.h -* -* Modification History: -* -* Date Name Description -* 05/05/99 stephen Cleaned up. -****************************************************************************** -*/ - -#ifndef SCHRITER_H -#define SCHRITER_H - -#include "unicode/utypes.h" -#include "unicode/chariter.h" -#include "unicode/uchriter.h" - -/** - * \file - * \brief C++ API: String Character Iterator - */ - -U_NAMESPACE_BEGIN -/** - * A concrete subclass of CharacterIterator that iterates over the - * characters (code units or code points) in a UnicodeString. - * It's possible not only to create an - * iterator that iterates over an entire UnicodeString, but also to - * create one that iterates over only a subrange of a UnicodeString - * (iterators over different subranges of the same UnicodeString don't - * compare equal). - * @see CharacterIterator - * @see ForwardCharacterIterator - * @stable ICU 2.0 - */ -class U_COMMON_API StringCharacterIterator : public UCharCharacterIterator { -public: - /** - * Create an iterator over the UnicodeString referred to by "textStr". - * The UnicodeString object is copied. - * The iteration range is the whole string, and the starting position is 0. - * @param textStr The unicode string used to create an iterator - * @stable ICU 2.0 - */ - StringCharacterIterator(const UnicodeString& textStr); - - /** - * Create an iterator over the UnicodeString referred to by "textStr". - * The iteration range is the whole string, and the starting - * position is specified by "textPos". If "textPos" is outside the valid - * iteration range, the behavior of this object is undefined. - * @param textStr The unicode string used to create an iterator - * @param textPos The starting position of the iteration - * @stable ICU 2.0 - */ - StringCharacterIterator(const UnicodeString& textStr, - int32_t textPos); - - /** - * Create an iterator over the UnicodeString referred to by "textStr". - * The UnicodeString object is copied. - * The iteration range begins with the code unit specified by - * "textBegin" and ends with the code unit BEFORE the code unit specfied - * by "textEnd". The starting position is specified by "textPos". If - * "textBegin" and "textEnd" don't form a valid range on "text" (i.e., - * textBegin >= textEnd or either is negative or greater than text.size()), - * or "textPos" is outside the range defined by "textBegin" and "textEnd", - * the behavior of this iterator is undefined. - * @param textStr The unicode string used to create the StringCharacterIterator - * @param textBegin The begin position of the iteration range - * @param textEnd The end position of the iteration range - * @param textPos The starting position of the iteration - * @stable ICU 2.0 - */ - StringCharacterIterator(const UnicodeString& textStr, - int32_t textBegin, - int32_t textEnd, - int32_t textPos); - - /** - * Copy constructor. The new iterator iterates over the same range - * of the same string as "that", and its initial position is the - * same as "that"'s current position. - * The UnicodeString object in "that" is copied. - * @param that The StringCharacterIterator to be copied - * @stable ICU 2.0 - */ - StringCharacterIterator(const StringCharacterIterator& that); - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~StringCharacterIterator(); - - /** - * Assignment operator. *this is altered to iterate over the same - * range of the same string as "that", and refers to the same - * character within that string as "that" does. - * @param that The object to be copied. - * @return the newly created object. - * @stable ICU 2.0 - */ - StringCharacterIterator& - operator=(const StringCharacterIterator& that); - - /** - * Returns true if the iterators iterate over the same range of the - * same string and are pointing at the same character. - * @param that The ForwardCharacterIterator to be compared for equality - * @return true if the iterators iterate over the same range of the - * same string and are pointing at the same character. - * @stable ICU 2.0 - */ - virtual UBool operator==(const ForwardCharacterIterator& that) const; - - /** - * Returns a new StringCharacterIterator referring to the same - * character in the same range of the same string as this one. The - * caller must delete the new iterator. - * @return the newly cloned object. - * @stable ICU 2.0 - */ - virtual CharacterIterator* clone(void) const; - - /** - * Sets the iterator to iterate over the provided string. - * @param newText The string to be iterated over - * @stable ICU 2.0 - */ - void setText(const UnicodeString& newText); - - /** - * Copies the UnicodeString under iteration into the UnicodeString - * referred to by "result". Even if this iterator iterates across - * only a part of this string, the whole string is copied. - * @param result Receives a copy of the text under iteration. - * @stable ICU 2.0 - */ - virtual void getText(UnicodeString& result); - - /** - * Return a class ID for this object (not really public) - * @return a class ID for this object. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const; - - /** - * Return a class ID for this class (not really public) - * @return a class ID for this class - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - -protected: - /** - * Default constructor, iteration over empty string. - * @stable ICU 2.0 - */ - StringCharacterIterator(); - - /** - * Sets the iterator to iterate over the provided string. - * @param newText The string to be iterated over - * @param newTextLength The length of the String - * @stable ICU 2.0 - */ - void setText(const UChar* newText, int32_t newTextLength); - - /** - * Copy of the iterated string object. - * @stable ICU 2.0 - */ - UnicodeString text; - -}; - -U_NAMESPACE_END -#endif diff --git a/win32/include/spidermonkey/unicode/scientificnumberformatter.h b/win32/include/spidermonkey/unicode/scientificnumberformatter.h deleted file mode 100755 index 0035a6e6..00000000 --- a/win32/include/spidermonkey/unicode/scientificnumberformatter.h +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2014-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -*/ -#ifndef SCINUMBERFORMATTER_H -#define SCINUMBERFORMATTER_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - - -#include "unicode/unistr.h" - -/** - * \file - * \brief C++ API: Formats in scientific notation. - */ - -U_NAMESPACE_BEGIN - -class FieldPositionIterator; -class DecimalFormatStaticSets; -class DecimalFormatSymbols; -class DecimalFormat; -class Formattable; - -/** - * A formatter that formats numbers in user-friendly scientific notation. - * - * Sample code: - *

- * UErrorCode status = U_ZERO_ERROR;
- * LocalPointer fmt(
- *         ScientificNumberFormatter::createMarkupInstance(
- *                 "en", "", "", status));
- * if (U_FAILURE(status)) {
- *     return;
- * }
- * UnicodeString appendTo;
- * // appendTo = "1.23456x10-78"
- * fmt->format(1.23456e-78, appendTo, status);
- * 
- * - * @stable ICU 55 - */ -class U_I18N_API ScientificNumberFormatter : public UObject { -public: - - /** - * Creates a ScientificNumberFormatter instance that uses - * superscript characters for exponents. - * @param fmtToAdopt The DecimalFormat which must be configured for - * scientific notation. - * @param status error returned here. - * @return The new ScientificNumberFormatter instance. - * - * @stable ICU 55 - */ - static ScientificNumberFormatter *createSuperscriptInstance( - DecimalFormat *fmtToAdopt, UErrorCode &status); - - /** - * Creates a ScientificNumberFormatter instance that uses - * superscript characters for exponents for this locale. - * @param locale The locale - * @param status error returned here. - * @return The ScientificNumberFormatter instance. - * - * @stable ICU 55 - */ - static ScientificNumberFormatter *createSuperscriptInstance( - const Locale &locale, UErrorCode &status); - - - /** - * Creates a ScientificNumberFormatter instance that uses - * markup for exponents. - * @param fmtToAdopt The DecimalFormat which must be configured for - * scientific notation. - * @param beginMarkup the markup to start superscript. - * @param endMarkup the markup to end superscript. - * @param status error returned here. - * @return The new ScientificNumberFormatter instance. - * - * @stable ICU 55 - */ - static ScientificNumberFormatter *createMarkupInstance( - DecimalFormat *fmtToAdopt, - const UnicodeString &beginMarkup, - const UnicodeString &endMarkup, - UErrorCode &status); - - /** - * Creates a ScientificNumberFormatter instance that uses - * markup for exponents for this locale. - * @param locale The locale - * @param beginMarkup the markup to start superscript. - * @param endMarkup the markup to end superscript. - * @param status error returned here. - * @return The ScientificNumberFormatter instance. - * - * @stable ICU 55 - */ - static ScientificNumberFormatter *createMarkupInstance( - const Locale &locale, - const UnicodeString &beginMarkup, - const UnicodeString &endMarkup, - UErrorCode &status); - - - /** - * Returns a copy of this object. Caller must free returned copy. - * @stable ICU 55 - */ - ScientificNumberFormatter *clone() const { - return new ScientificNumberFormatter(*this); - } - - /** - * Destructor. - * @stable ICU 55 - */ - virtual ~ScientificNumberFormatter(); - - /** - * Formats a number into user friendly scientific notation. - * - * @param number the number to format. - * @param appendTo formatted string appended here. - * @param status any error returned here. - * @return appendTo - * - * @stable ICU 55 - */ - UnicodeString &format( - const Formattable &number, - UnicodeString &appendTo, - UErrorCode &status) const; - private: - class U_I18N_API Style : public UObject { - public: - virtual Style *clone() const = 0; - protected: - virtual UnicodeString &format( - const UnicodeString &original, - FieldPositionIterator &fpi, - const UnicodeString &preExponent, - const DecimalFormatStaticSets &decimalFormatSets, - UnicodeString &appendTo, - UErrorCode &status) const = 0; - private: - friend class ScientificNumberFormatter; - }; - - class U_I18N_API SuperscriptStyle : public Style { - public: - virtual Style *clone() const; - protected: - virtual UnicodeString &format( - const UnicodeString &original, - FieldPositionIterator &fpi, - const UnicodeString &preExponent, - const DecimalFormatStaticSets &decimalFormatSets, - UnicodeString &appendTo, - UErrorCode &status) const; - }; - - class U_I18N_API MarkupStyle : public Style { - public: - MarkupStyle( - const UnicodeString &beginMarkup, - const UnicodeString &endMarkup) - : Style(), - fBeginMarkup(beginMarkup), - fEndMarkup(endMarkup) { } - virtual Style *clone() const; - protected: - virtual UnicodeString &format( - const UnicodeString &original, - FieldPositionIterator &fpi, - const UnicodeString &preExponent, - const DecimalFormatStaticSets &decimalFormatSets, - UnicodeString &appendTo, - UErrorCode &status) const; - private: - UnicodeString fBeginMarkup; - UnicodeString fEndMarkup; - }; - - ScientificNumberFormatter( - DecimalFormat *fmtToAdopt, - Style *styleToAdopt, - UErrorCode &status); - - ScientificNumberFormatter(const ScientificNumberFormatter &other); - ScientificNumberFormatter &operator=(const ScientificNumberFormatter &); - - static void getPreExponent( - const DecimalFormatSymbols &dfs, UnicodeString &preExponent); - - static ScientificNumberFormatter *createInstance( - DecimalFormat *fmtToAdopt, - Style *styleToAdopt, - UErrorCode &status); - - UnicodeString fPreExponent; - DecimalFormat *fDecimalFormat; - Style *fStyle; - const DecimalFormatStaticSets *fStaticSets; - -}; - -U_NAMESPACE_END - - -#endif /* !UCONFIG_NO_FORMATTING */ -#endif diff --git a/win32/include/spidermonkey/unicode/search.h b/win32/include/spidermonkey/unicode/search.h deleted file mode 100755 index 0acfcced..00000000 --- a/win32/include/spidermonkey/unicode/search.h +++ /dev/null @@ -1,577 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 2001-2011 IBM and others. All rights reserved. -********************************************************************** -* Date Name Description -* 03/22/2000 helena Creation. -********************************************************************** -*/ - -#ifndef SEARCH_H -#define SEARCH_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: SearchIterator object. - */ - -#if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION - -#include "unicode/uobject.h" -#include "unicode/unistr.h" -#include "unicode/chariter.h" -#include "unicode/brkiter.h" -#include "unicode/usearch.h" - -/** -* @stable ICU 2.0 -*/ -struct USearch; -/** -* @stable ICU 2.0 -*/ -typedef struct USearch USearch; - -U_NAMESPACE_BEGIN - -/** - * - * SearchIterator is an abstract base class that provides - * methods to search for a pattern within a text string. Instances of - * SearchIterator maintain a current position and scans over the - * target text, returning the indices the pattern is matched and the length - * of each match. - *

- * SearchIterator defines a protocol for text searching. - * Subclasses provide concrete implementations of various search algorithms. - * For example, StringSearch implements language-sensitive pattern - * matching based on the comparison rules defined in a - * RuleBasedCollator object. - *

- * Other options for searching includes using a BreakIterator to restrict - * the points at which matches are detected. - *

- * SearchIterator provides an API that is similar to that of - * other text iteration classes such as BreakIterator. Using - * this class, it is easy to scan through text looking for all occurances of - * a given pattern. The following example uses a StringSearch - * object to find all instances of "fox" in the target string. Any other - * subclass of SearchIterator can be used in an identical - * manner. - *


- * UnicodeString target("The quick brown fox jumped over the lazy fox");
- * UnicodeString pattern("fox");
- *
- * SearchIterator *iter  = new StringSearch(pattern, target);
- * UErrorCode      error = U_ZERO_ERROR;
- * for (int pos = iter->first(error); pos != USEARCH_DONE; 
- *                               pos = iter->next(error)) {
- *     printf("Found match at %d pos, length is %d\n", pos, 
- *                                             iter.getMatchLength());
- * }
- * 
- * - * @see StringSearch - * @see RuleBasedCollator - */ -class U_I18N_API SearchIterator : public UObject { - -public: - - // public constructors and destructors ------------------------------- - - /** - * Copy constructor that creates a SearchIterator instance with the same - * behavior, and iterating over the same text. - * @param other the SearchIterator instance to be copied. - * @stable ICU 2.0 - */ - SearchIterator(const SearchIterator &other); - - /** - * Destructor. Cleans up the search iterator data struct. - * @stable ICU 2.0 - */ - virtual ~SearchIterator(); - - // public get and set methods ---------------------------------------- - - /** - * Sets the index to point to the given position, and clears any state - * that's affected. - *

- * This method takes the argument index and sets the position in the text - * string accordingly without checking if the index is pointing to a - * valid starting point to begin searching. - * @param position within the text to be set. If position is less - * than or greater than the text range for searching, - * an U_INDEX_OUTOFBOUNDS_ERROR will be returned - * @param status for errors if it occurs - * @stable ICU 2.0 - */ - virtual void setOffset(int32_t position, UErrorCode &status) = 0; - - /** - * Return the current index in the text being searched. - * If the iteration has gone past the end of the text - * (or past the beginning for a backwards search), USEARCH_DONE - * is returned. - * @return current index in the text being searched. - * @stable ICU 2.0 - */ - virtual int32_t getOffset(void) const = 0; - - /** - * Sets the text searching attributes located in the enum - * USearchAttribute with values from the enum USearchAttributeValue. - * USEARCH_DEFAULT can be used for all attributes for resetting. - * @param attribute text attribute (enum USearchAttribute) to be set - * @param value text attribute value - * @param status for errors if it occurs - * @stable ICU 2.0 - */ - void setAttribute(USearchAttribute attribute, - USearchAttributeValue value, - UErrorCode &status); - - /** - * Gets the text searching attributes - * @param attribute text attribute (enum USearchAttribute) to be retrieve - * @return text attribute value - * @stable ICU 2.0 - */ - USearchAttributeValue getAttribute(USearchAttribute attribute) const; - - /** - * Returns the index to the match in the text string that was searched. - * This call returns a valid result only after a successful call to - * first, next, previous, or last. - * Just after construction, or after a searching method returns - * USEARCH_DONE, this method will return USEARCH_DONE. - *

- * Use getMatchedLength to get the matched string length. - * @return index of a substring within the text string that is being - * searched. - * @see #first - * @see #next - * @see #previous - * @see #last - * @stable ICU 2.0 - */ - int32_t getMatchedStart(void) const; - - /** - * Returns the length of text in the string which matches the search - * pattern. This call returns a valid result only after a successful call - * to first, next, previous, or last. - * Just after construction, or after a searching method returns - * USEARCH_DONE, this method will return 0. - * @return The length of the match in the target text, or 0 if there - * is no match currently. - * @see #first - * @see #next - * @see #previous - * @see #last - * @stable ICU 2.0 - */ - int32_t getMatchedLength(void) const; - - /** - * Returns the text that was matched by the most recent call to - * first, next, previous, or last. - * If the iterator is not pointing at a valid match (e.g. just after - * construction or after USEARCH_DONE has been returned, - * returns an empty string. - * @param result stores the matched string or an empty string if a match - * is not found. - * @see #first - * @see #next - * @see #previous - * @see #last - * @stable ICU 2.0 - */ - void getMatchedText(UnicodeString &result) const; - - /** - * Set the BreakIterator that will be used to restrict the points - * at which matches are detected. The user is responsible for deleting - * the breakiterator. - * @param breakiter A BreakIterator that will be used to restrict the - * points at which matches are detected. If a match is - * found, but the match's start or end index is not a - * boundary as determined by the BreakIterator, - * the match will be rejected and another will be searched - * for. If this parameter is NULL, no break - * detection is attempted. - * @param status for errors if it occurs - * @see BreakIterator - * @stable ICU 2.0 - */ - void setBreakIterator(BreakIterator *breakiter, UErrorCode &status); - - /** - * Returns the BreakIterator that is used to restrict the points at - * which matches are detected. This will be the same object that was - * passed to the constructor or to setBreakIterator. - * Note that NULL is a legal value; it means that break - * detection should not be attempted. - * @return BreakIterator used to restrict matchings. - * @see #setBreakIterator - * @stable ICU 2.0 - */ - const BreakIterator * getBreakIterator(void) const; - - /** - * Set the string text to be searched. Text iteration will hence begin at - * the start of the text string. This method is useful if you want to - * re-use an iterator to search for the same pattern within a different - * body of text. The user is responsible for deleting the text. - * @param text string to be searched. - * @param status for errors. If the text length is 0, - * an U_ILLEGAL_ARGUMENT_ERROR is returned. - * @stable ICU 2.0 - */ - virtual void setText(const UnicodeString &text, UErrorCode &status); - - /** - * Set the string text to be searched. Text iteration will hence begin at - * the start of the text string. This method is useful if you want to - * re-use an iterator to search for the same pattern within a different - * body of text. - *

- * Note: No parsing of the text within the CharacterIterator - * will be done during searching for this version. The block of text - * in CharacterIterator will be used as it is. - * The user is responsible for deleting the text. - * @param text string iterator to be searched. - * @param status for errors if any. If the text length is 0 then an - * U_ILLEGAL_ARGUMENT_ERROR is returned. - * @stable ICU 2.0 - */ - virtual void setText(CharacterIterator &text, UErrorCode &status); - - /** - * Return the string text to be searched. - * @return text string to be searched. - * @stable ICU 2.0 - */ - const UnicodeString & getText(void) const; - - // operator overloading ---------------------------------------------- - - /** - * Equality operator. - * @param that SearchIterator instance to be compared. - * @return TRUE if both BreakIterators are of the same class, have the - * same behavior, terates over the same text and have the same - * attributes. FALSE otherwise. - * @stable ICU 2.0 - */ - virtual UBool operator==(const SearchIterator &that) const; - - /** - * Not-equal operator. - * @param that SearchIterator instance to be compared. - * @return FALSE if operator== returns TRUE, and vice versa. - * @stable ICU 2.0 - */ - UBool operator!=(const SearchIterator &that) const; - - // public methods ---------------------------------------------------- - - /** - * Returns a copy of SearchIterator with the same behavior, and - * iterating over the same text, as this one. Note that all data will be - * replicated, except for the text string to be searched. - * @return cloned object - * @stable ICU 2.0 - */ - virtual SearchIterator* safeClone(void) const = 0; - - /** - * Returns the first index at which the string text matches the search - * pattern. The iterator is adjusted so that its current index (as - * returned by getOffset) is the match position if one - * was found. - * If a match is not found, USEARCH_DONE will be returned and - * the iterator will be adjusted to the index USEARCH_DONE - * @param status for errors if it occurs - * @return The character index of the first match, or - * USEARCH_DONE if there are no matches. - * @see #getOffset - * @stable ICU 2.0 - */ - int32_t first(UErrorCode &status); - - /** - * Returns the first index equal or greater than position at which the - * string text matches the search pattern. The iterator is adjusted so - * that its current index (as returned by getOffset) is the - * match position if one was found. - * If a match is not found, USEARCH_DONE will be returned and the - * iterator will be adjusted to the index USEARCH_DONE. - * @param position where search if to start from. If position is less - * than or greater than the text range for searching, - * an U_INDEX_OUTOFBOUNDS_ERROR will be returned - * @param status for errors if it occurs - * @return The character index of the first match following - * position, or USEARCH_DONE if there are no - * matches. - * @see #getOffset - * @stable ICU 2.0 - */ - int32_t following(int32_t position, UErrorCode &status); - - /** - * Returns the last index in the target text at which it matches the - * search pattern. The iterator is adjusted so that its current index - * (as returned by getOffset) is the match position if one was - * found. - * If a match is not found, USEARCH_DONE will be returned and - * the iterator will be adjusted to the index USEARCH_DONE. - * @param status for errors if it occurs - * @return The index of the first match, or USEARCH_DONE if - * there are no matches. - * @see #getOffset - * @stable ICU 2.0 - */ - int32_t last(UErrorCode &status); - - /** - * Returns the first index less than position at which the string - * text matches the search pattern. The iterator is adjusted so that its - * current index (as returned by getOffset) is the match - * position if one was found. If a match is not found, - * USEARCH_DONE will be returned and the iterator will be - * adjusted to the index USEARCH_DONE - *

- * When USEARCH_OVERLAP option is off, the last index of the - * result match is always less than position. - * When USERARCH_OVERLAP is on, the result match may span across - * position. - * - * @param position where search is to start from. If position is less - * than or greater than the text range for searching, - * an U_INDEX_OUTOFBOUNDS_ERROR will be returned - * @param status for errors if it occurs - * @return The character index of the first match preceding - * position, or USEARCH_DONE if there are - * no matches. - * @see #getOffset - * @stable ICU 2.0 - */ - int32_t preceding(int32_t position, UErrorCode &status); - - /** - * Returns the index of the next point at which the text matches the - * search pattern, starting from the current position - * The iterator is adjusted so that its current index (as returned by - * getOffset) is the match position if one was found. - * If a match is not found, USEARCH_DONE will be returned and - * the iterator will be adjusted to a position after the end of the text - * string. - * @param status for errors if it occurs - * @return The index of the next match after the current position, - * or USEARCH_DONE if there are no more matches. - * @see #getOffset - * @stable ICU 2.0 - */ - int32_t next(UErrorCode &status); - - /** - * Returns the index of the previous point at which the string text - * matches the search pattern, starting at the current position. - * The iterator is adjusted so that its current index (as returned by - * getOffset) is the match position if one was found. - * If a match is not found, USEARCH_DONE will be returned and - * the iterator will be adjusted to the index USEARCH_DONE - * @param status for errors if it occurs - * @return The index of the previous match before the current position, - * or USEARCH_DONE if there are no more matches. - * @see #getOffset - * @stable ICU 2.0 - */ - int32_t previous(UErrorCode &status); - - /** - * Resets the iteration. - * Search will begin at the start of the text string if a forward - * iteration is initiated before a backwards iteration. Otherwise if a - * backwards iteration is initiated before a forwards iteration, the - * search will begin at the end of the text string. - * @stable ICU 2.0 - */ - virtual void reset(); - -protected: - // protected data members --------------------------------------------- - - /** - * C search data struct - * @stable ICU 2.0 - */ - USearch *m_search_; - - /** - * Break iterator. - * Currently the C++ breakiterator does not have getRules etc to reproduce - * another in C. Hence we keep the original around and do the verification - * at the end of the match. The user is responsible for deleting this - * break iterator. - * @stable ICU 2.0 - */ - BreakIterator *m_breakiterator_; - - /** - * Unicode string version of the search text - * @stable ICU 2.0 - */ - UnicodeString m_text_; - - // protected constructors and destructors ----------------------------- - - /** - * Default constructor. - * Initializes data to the default values. - * @stable ICU 2.0 - */ - SearchIterator(); - - /** - * Constructor for use by subclasses. - * @param text The target text to be searched. - * @param breakiter A {@link BreakIterator} that is used to restrict the - * points at which matches are detected. If - * handleNext or handlePrev finds a - * match, but the match's start or end index is not a - * boundary as determined by the BreakIterator, - * the match is rejected and handleNext or - * handlePrev is called again. If this parameter - * is NULL, no break detection is attempted. - * @see #handleNext - * @see #handlePrev - * @stable ICU 2.0 - */ - SearchIterator(const UnicodeString &text, - BreakIterator *breakiter = NULL); - - /** - * Constructor for use by subclasses. - *

- * Note: No parsing of the text within the CharacterIterator - * will be done during searching for this version. The block of text - * in CharacterIterator will be used as it is. - * @param text The target text to be searched. - * @param breakiter A {@link BreakIterator} that is used to restrict the - * points at which matches are detected. If - * handleNext or handlePrev finds a - * match, but the match's start or end index is not a - * boundary as determined by the BreakIterator, - * the match is rejected and handleNext or - * handlePrev is called again. If this parameter - * is NULL, no break detection is attempted. - * @see #handleNext - * @see #handlePrev - * @stable ICU 2.0 - */ - SearchIterator(CharacterIterator &text, BreakIterator *breakiter = NULL); - - // protected methods -------------------------------------------------- - - /** - * Assignment operator. Sets this iterator to have the same behavior, - * and iterate over the same text, as the one passed in. - * @param that instance to be copied. - * @stable ICU 2.0 - */ - SearchIterator & operator=(const SearchIterator &that); - - /** - * Abstract method which subclasses override to provide the mechanism - * for finding the next match in the target text. This allows different - * subclasses to provide different search algorithms. - *

- * If a match is found, the implementation should return the index at - * which the match starts and should call - * setMatchLength with the number of characters - * in the target text that make up the match. If no match is found, the - * method should return USEARCH_DONE. - *

- * @param position The index in the target text at which the search - * should start. - * @param status for error codes if it occurs. - * @return index at which the match starts, else if match is not found - * USEARCH_DONE is returned - * @see #setMatchLength - * @stable ICU 2.0 - */ - virtual int32_t handleNext(int32_t position, UErrorCode &status) - = 0; - - /** - * Abstract method which subclasses override to provide the mechanism for - * finding the previous match in the target text. This allows different - * subclasses to provide different search algorithms. - *

- * If a match is found, the implementation should return the index at - * which the match starts and should call - * setMatchLength with the number of characters - * in the target text that make up the match. If no match is found, the - * method should return USEARCH_DONE. - *

- * @param position The index in the target text at which the search - * should start. - * @param status for error codes if it occurs. - * @return index at which the match starts, else if match is not found - * USEARCH_DONE is returned - * @see #setMatchLength - * @stable ICU 2.0 - */ - virtual int32_t handlePrev(int32_t position, UErrorCode &status) - = 0; - - /** - * Sets the length of the currently matched string in the text string to - * be searched. - * Subclasses' handleNext and handlePrev - * methods should call this when they find a match in the target text. - * @param length length of the matched text. - * @see #handleNext - * @see #handlePrev - * @stable ICU 2.0 - */ - virtual void setMatchLength(int32_t length); - - /** - * Sets the offset of the currently matched string in the text string to - * be searched. - * Subclasses' handleNext and handlePrev - * methods should call this when they find a match in the target text. - * @param position start offset of the matched text. - * @see #handleNext - * @see #handlePrev - * @stable ICU 2.0 - */ - virtual void setMatchStart(int32_t position); - - /** - * sets match not found - * @stable ICU 2.0 - */ - void setMatchNotFound(); -}; - -inline UBool SearchIterator::operator!=(const SearchIterator &that) const -{ - return !operator==(that); -} -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_COLLATION */ - -#endif - diff --git a/win32/include/spidermonkey/unicode/selfmt.h b/win32/include/spidermonkey/unicode/selfmt.h deleted file mode 100755 index 37a8f2b8..00000000 --- a/win32/include/spidermonkey/unicode/selfmt.h +++ /dev/null @@ -1,369 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/******************************************************************** - * COPYRIGHT: - * Copyright (c) 1997-2011, International Business Machines Corporation and - * others. All Rights Reserved. - * Copyright (C) 2010 , Yahoo! Inc. - ******************************************************************** - * - * File SELFMT.H - * - * Modification History: - * - * Date Name Description - * 11/11/09 kirtig Finished first cut of implementation. - ********************************************************************/ - -#ifndef SELFMT -#define SELFMT - -#include "unicode/messagepattern.h" -#include "unicode/numfmt.h" -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: SelectFormat object - */ - -#if !UCONFIG_NO_FORMATTING - -U_NAMESPACE_BEGIN - -class MessageFormat; - -/** - *

SelectFormat supports the creation of internationalized - * messages by selecting phrases based on keywords. The pattern specifies - * how to map keywords to phrases and provides a default phrase. The - * object provided to the format method is a string that's matched - * against the keywords. If there is a match, the corresponding phrase - * is selected; otherwise, the default phrase is used.

- * - *

Using SelectFormat for Gender Agreement

- * - *

Note: Typically, select formatting is done via MessageFormat - * with a select argument type, - * rather than using a stand-alone SelectFormat.

- * - *

The main use case for the select format is gender based inflection. - * When names or nouns are inserted into sentences, their gender can affect pronouns, - * verb forms, articles, and adjectives. Special care needs to be - * taken for the case where the gender cannot be determined. - * The impact varies between languages:

- * \htmlonly - *
    - *
  • English has three genders, and unknown gender is handled as a special - * case. Names use the gender of the named person (if known), nouns referring - * to people use natural gender, and inanimate objects are usually neutral. - * The gender only affects pronouns: "he", "she", "it", "they". - * - *
  • German differs from English in that the gender of nouns is rather - * arbitrary, even for nouns referring to people ("Mädchen", girl, is neutral). - * The gender affects pronouns ("er", "sie", "es"), articles ("der", "die", - * "das"), and adjective forms ("guter Mann", "gute Frau", "gutes Mädchen"). - * - *
  • French has only two genders; as in German the gender of nouns - * is rather arbitrary - for sun and moon, the genders - * are the opposite of those in German. The gender affects - * pronouns ("il", "elle"), articles ("le", "la"), - * adjective forms ("bon", "bonne"), and sometimes - * verb forms ("allé", "allée"). - * - *
  • Polish distinguishes five genders (or noun classes), - * human masculine, animate non-human masculine, inanimate masculine, - * feminine, and neuter. - *
- * \endhtmlonly - *

Some other languages have noun classes that are not related to gender, - * but similar in grammatical use. - * Some African languages have around 20 noun classes.

- * - *

Note:For the gender of a person in a given sentence, - * we usually need to distinguish only between female, male and other/unknown.

- * - *

To enable localizers to create sentence patterns that take their - * language's gender dependencies into consideration, software has to provide - * information about the gender associated with a noun or name to - * MessageFormat. - * Two main cases can be distinguished:

- * - *
    - *
  • For people, natural gender information should be maintained for each person. - * Keywords like "male", "female", "mixed" (for groups of people) - * and "unknown" could be used. - * - *
  • For nouns, grammatical gender information should be maintained for - * each noun and per language, e.g., in resource bundles. - * The keywords "masculine", "feminine", and "neuter" are commonly used, - * but some languages may require other keywords. - *
- * - *

The resulting keyword is provided to MessageFormat as a - * parameter separate from the name or noun it's associated with. For example, - * to generate a message such as "Jean went to Paris", three separate arguments - * would be provided: The name of the person as argument 0, the gender of - * the person as argument 1, and the name of the city as argument 2. - * The sentence pattern for English, where the gender of the person has - * no impact on this simple sentence, would not refer to argument 1 at all:

- * - *
{0} went to {2}.
- * - *

Note: The entire sentence should be included (and partially repeated) - * inside each phrase. Otherwise translators would have to be trained on how to - * move bits of the sentence in and out of the select argument of a message. - * (The examples below do not follow this recommendation!)

- * - *

The sentence pattern for French, where the gender of the person affects - * the form of the participle, uses a select format based on argument 1:

- * - * \htmlonly
{0} est {1, select, female {allée} other {allé}} à {2}.
\endhtmlonly - * - *

Patterns can be nested, so that it's possible to handle interactions of - * number and gender where necessary. For example, if the above sentence should - * allow for the names of several people to be inserted, the following sentence - * pattern can be used (with argument 0 the list of people's names, - * argument 1 the number of people, argument 2 their combined gender, and - * argument 3 the city name):

- * - * \htmlonly - *
{0} {1, plural,
-  *                 one {est {2, select, female {allée} other  {allé}}}
-  *                 other {sont {2, select, female {allées} other {allés}}}
-  *          }à {3}.
- * \endhtmlonly - * - *

Patterns and Their Interpretation

- * - *

The SelectFormat pattern string defines the phrase output - * for each user-defined keyword. - * The pattern is a sequence of (keyword, message) pairs. - * A keyword is a "pattern identifier": [^[[:Pattern_Syntax:][:Pattern_White_Space:]]]+

- * - *

Each message is a MessageFormat pattern string enclosed in {curly braces}.

- * - *

You always have to define a phrase for the default keyword - * other; this phrase is returned when the keyword - * provided to - * the format method matches no other keyword. - * If a pattern does not provide a phrase for other, the method - * it's provided to returns the error U_DEFAULT_KEYWORD_MISSING. - *
- * Pattern_White_Space between keywords and messages is ignored. - * Pattern_White_Space within a message is preserved and output.

- * - *

Example:
-  * \htmlonly
-  *
-  * UErrorCode status = U_ZERO_ERROR;
-  * MessageFormat *msgFmt = new MessageFormat(UnicodeString("{0} est  {1, select, female {allée} other {allé}} à Paris."), Locale("fr"),  status);
-  * if (U_FAILURE(status)) {
-  *       return;
-  * }
-  * FieldPosition ignore(FieldPosition::DONT_CARE);
-  * UnicodeString result;
-  *
-  * char* str1= "Kirti,female";
-  * Formattable args1[] = {"Kirti","female"};
-  * msgFmt->format(args1, 2, result, ignore, status);
-  * cout << "Input is " << str1 << " and result is: " << result << endl;
-  * delete msgFmt;
-  *
-  * \endhtmlonly
-  * 
- *

- * - * Produces the output:
- * \htmlonly - * Kirti est allée à Paris. - * \endhtmlonly - * - * @stable ICU 4.4 - */ - -class U_I18N_API SelectFormat : public Format { -public: - - /** - * Creates a new SelectFormat for a given pattern string. - * @param pattern the pattern for this SelectFormat. - * errors are returned to status if the pattern is invalid. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.4 - */ - SelectFormat(const UnicodeString& pattern, UErrorCode& status); - - /** - * copy constructor. - * @stable ICU 4.4 - */ - SelectFormat(const SelectFormat& other); - - /** - * Destructor. - * @stable ICU 4.4 - */ - virtual ~SelectFormat(); - - /** - * Sets the pattern used by this select format. - * for the keyword rules. - * Patterns and their interpretation are specified in the class description. - * - * @param pattern the pattern for this select format - * errors are returned to status if the pattern is invalid. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @stable ICU 4.4 - */ - void applyPattern(const UnicodeString& pattern, UErrorCode& status); - - - using Format::format; - - /** - * Selects the phrase for the given keyword - * - * @param keyword The keyword that is used to select an alternative. - * @param appendTo output parameter to receive result. - * result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status output param set to success/failure code on exit, which - * must not indicate a failure before the function call. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - UnicodeString& format(const UnicodeString& keyword, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - /** - * Assignment operator - * - * @param other the SelectFormat object to copy from. - * @stable ICU 4.4 - */ - SelectFormat& operator=(const SelectFormat& other); - - /** - * Return true if another object is semantically equal to this one. - * - * @param other the SelectFormat object to be compared with. - * @return true if other is semantically equal to this. - * @stable ICU 4.4 - */ - virtual UBool operator==(const Format& other) const; - - /** - * Return true if another object is semantically unequal to this one. - * - * @param other the SelectFormat object to be compared with. - * @return true if other is semantically unequal to this. - * @stable ICU 4.4 - */ - virtual UBool operator!=(const Format& other) const; - - /** - * Clones this Format object polymorphically. The caller owns the - * result and should delete it when done. - * @stable ICU 4.4 - */ - virtual Format* clone(void) const; - - /** - * Format an object to produce a string. - * This method handles keyword strings. - * If the Formattable object is not a UnicodeString, - * then it returns a failing UErrorCode. - * - * @param obj A keyword string that is used to select an alternative. - * @param appendTo output parameter to receive result. - * Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. - * On output: the offsets of the alignment field. - * @param status output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - UnicodeString& format(const Formattable& obj, - UnicodeString& appendTo, - FieldPosition& pos, - UErrorCode& status) const; - - /** - * Returns the pattern from applyPattern() or constructor. - * - * @param appendTo output parameter to receive result. - * Result is appended to existing contents. - * @return the UnicodeString with inserted pattern. - * @stable ICU 4.4 - */ - UnicodeString& toPattern(UnicodeString& appendTo); - - /** - * This method is not yet supported by SelectFormat. - *

- * Before calling, set parse_pos.index to the offset you want to start - * parsing at in the source. After calling, parse_pos.index is the end of - * the text you parsed. If error occurs, index is unchanged. - *

- * When parsing, leading whitespace is discarded (with a successful parse), - * while trailing whitespace is left as is. - *

- * See Format::parseObject() for more. - * - * @param source The string to be parsed into an object. - * @param result Formattable to be set to the parse result. - * If parse fails, return contents are undefined. - * @param parse_pos The position to start parsing at. Upon return - * this param is set to the position after the - * last character successfully parsed. If the - * source is not parsed successfully, this param - * will remain unchanged. - * @stable ICU 4.4 - */ - virtual void parseObject(const UnicodeString& source, - Formattable& result, - ParsePosition& parse_pos) const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * @stable ICU 4.4 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * @stable ICU 4.4 - */ - virtual UClassID getDynamicClassID() const; - -private: - friend class MessageFormat; - - SelectFormat(); // default constructor not implemented. - - /** - * Finds the SelectFormat sub-message for the given keyword, or the "other" sub-message. - * @param pattern A MessagePattern. - * @param partIndex the index of the first SelectFormat argument style part. - * @param keyword a keyword to be matched to one of the SelectFormat argument's keywords. - * @param ec Error code. - * @return the sub-message start part index. - */ - static int32_t findSubMessage(const MessagePattern& pattern, int32_t partIndex, - const UnicodeString& keyword, UErrorCode& ec); - - MessagePattern msgPattern; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _SELFMT -//eof diff --git a/win32/include/spidermonkey/unicode/simpleformatter.h b/win32/include/spidermonkey/unicode/simpleformatter.h deleted file mode 100755 index 2b74f5ca..00000000 --- a/win32/include/spidermonkey/unicode/simpleformatter.h +++ /dev/null @@ -1,297 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* Copyright (C) 2014-2016, International Business Machines -* Corporation and others. All Rights Reserved. -****************************************************************************** -* simpleformatter.h -*/ - -#ifndef __SIMPLEFORMATTER_H__ -#define __SIMPLEFORMATTER_H__ - -/** - * \file - * \brief C++ API: Simple formatter, minimal subset of MessageFormat. - */ - -#include "unicode/utypes.h" -#include "unicode/unistr.h" - -#ifndef U_HIDE_DRAFT_API - -U_NAMESPACE_BEGIN - -/** - * Formats simple patterns like "{1} was born in {0}". - * Minimal subset of MessageFormat; fast, simple, minimal dependencies. - * Supports only numbered arguments with no type nor style parameters, - * and formats only string values. - * Quoting via ASCII apostrophe compatible with ICU MessageFormat default behavior. - * - * Factory methods set error codes for syntax errors - * and for too few or too many arguments/placeholders. - * - * SimpleFormatter objects are thread-safe except for assignment and applying new patterns. - * - * Example: - *

- * UErrorCode errorCode = U_ZERO_ERROR;
- * SimpleFormatter fmt("{1} '{born}' in {0}", errorCode);
- * UnicodeString result;
- *
- * // Output: "paul {born} in england"
- * fmt.format("england", "paul", result, errorCode);
- * 
- * - * This class is not intended for public subclassing. - * - * @see MessageFormat - * @see UMessagePatternApostropheMode - * @draft ICU 57 - */ -class U_COMMON_API SimpleFormatter U_FINAL : public UMemory { -public: - /** - * Default constructor. - * @draft ICU 57 - */ - SimpleFormatter() : compiledPattern((UChar)0) {} - - /** - * Constructs a formatter from the pattern string. - * - * @param pattern The pattern string. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * Set to U_ILLEGAL_ARGUMENT_ERROR for bad argument syntax. - * @draft ICU 57 - */ - SimpleFormatter(const UnicodeString& pattern, UErrorCode &errorCode) { - applyPattern(pattern, errorCode); - } - - /** - * Constructs a formatter from the pattern string. - * The number of arguments checked against the given limits is the - * highest argument number plus one, not the number of occurrences of arguments. - * - * @param pattern The pattern string. - * @param min The pattern must have at least this many arguments. - * @param max The pattern must have at most this many arguments. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * Set to U_ILLEGAL_ARGUMENT_ERROR for bad argument syntax and - * too few or too many arguments. - * @draft ICU 57 - */ - SimpleFormatter(const UnicodeString& pattern, int32_t min, int32_t max, - UErrorCode &errorCode) { - applyPatternMinMaxArguments(pattern, min, max, errorCode); - } - - /** - * Copy constructor. - * @draft ICU 57 - */ - SimpleFormatter(const SimpleFormatter& other) - : compiledPattern(other.compiledPattern) {} - - /** - * Assignment operator. - * @draft ICU 57 - */ - SimpleFormatter &operator=(const SimpleFormatter& other); - - /** - * Destructor. - * @draft ICU 57 - */ - ~SimpleFormatter(); - - /** - * Changes this object according to the new pattern. - * - * @param pattern The pattern string. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * Set to U_ILLEGAL_ARGUMENT_ERROR for bad argument syntax. - * @return TRUE if U_SUCCESS(errorCode). - * @draft ICU 57 - */ - UBool applyPattern(const UnicodeString &pattern, UErrorCode &errorCode) { - return applyPatternMinMaxArguments(pattern, 0, INT32_MAX, errorCode); - } - - /** - * Changes this object according to the new pattern. - * The number of arguments checked against the given limits is the - * highest argument number plus one, not the number of occurrences of arguments. - * - * @param pattern The pattern string. - * @param min The pattern must have at least this many arguments. - * @param max The pattern must have at most this many arguments. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * Set to U_ILLEGAL_ARGUMENT_ERROR for bad argument syntax and - * too few or too many arguments. - * @return TRUE if U_SUCCESS(errorCode). - * @draft ICU 57 - */ - UBool applyPatternMinMaxArguments(const UnicodeString &pattern, - int32_t min, int32_t max, UErrorCode &errorCode); - - /** - * @return The max argument number + 1. - * @draft ICU 57 - */ - int32_t getArgumentLimit() const { - return getArgumentLimit(compiledPattern.getBuffer(), compiledPattern.length()); - } - - /** - * Formats the given value, appending to the appendTo builder. - * The argument value must not be the same object as appendTo. - * getArgumentLimit() must be at most 1. - * - * @param value0 Value for argument {0}. - * @param appendTo Gets the formatted pattern and value appended. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return appendTo - * @draft ICU 57 - */ - UnicodeString &format( - const UnicodeString &value0, - UnicodeString &appendTo, UErrorCode &errorCode) const; - - /** - * Formats the given values, appending to the appendTo builder. - * An argument value must not be the same object as appendTo. - * getArgumentLimit() must be at most 2. - * - * @param value0 Value for argument {0}. - * @param value1 Value for argument {1}. - * @param appendTo Gets the formatted pattern and values appended. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return appendTo - * @draft ICU 57 - */ - UnicodeString &format( - const UnicodeString &value0, - const UnicodeString &value1, - UnicodeString &appendTo, UErrorCode &errorCode) const; - - /** - * Formats the given values, appending to the appendTo builder. - * An argument value must not be the same object as appendTo. - * getArgumentLimit() must be at most 3. - * - * @param value0 Value for argument {0}. - * @param value1 Value for argument {1}. - * @param value2 Value for argument {2}. - * @param appendTo Gets the formatted pattern and values appended. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return appendTo - * @draft ICU 57 - */ - UnicodeString &format( - const UnicodeString &value0, - const UnicodeString &value1, - const UnicodeString &value2, - UnicodeString &appendTo, UErrorCode &errorCode) const; - - /** - * Formats the given values, appending to the appendTo string. - * - * @param values The argument values. - * An argument value must not be the same object as appendTo. - * Can be NULL if valuesLength==getArgumentLimit()==0. - * @param valuesLength The length of the values array. - * Must be at least getArgumentLimit(). - * @param appendTo Gets the formatted pattern and values appended. - * @param offsets offsets[i] receives the offset of where - * values[i] replaced pattern argument {i}. - * Can be shorter or longer than values. Can be NULL if offsetsLength==0. - * If there is no {i} in the pattern, then offsets[i] is set to -1. - * @param offsetsLength The length of the offsets array. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return appendTo - * @draft ICU 57 - */ - UnicodeString &formatAndAppend( - const UnicodeString *const *values, int32_t valuesLength, - UnicodeString &appendTo, - int32_t *offsets, int32_t offsetsLength, UErrorCode &errorCode) const; - - /** - * Formats the given values, replacing the contents of the result string. - * May optimize by actually appending to the result if it is the same object - * as the value corresponding to the initial argument in the pattern. - * - * @param values The argument values. - * An argument value may be the same object as result. - * Can be NULL if valuesLength==getArgumentLimit()==0. - * @param valuesLength The length of the values array. - * Must be at least getArgumentLimit(). - * @param result Gets its contents replaced by the formatted pattern and values. - * @param offsets offsets[i] receives the offset of where - * values[i] replaced pattern argument {i}. - * Can be shorter or longer than values. Can be NULL if offsetsLength==0. - * If there is no {i} in the pattern, then offsets[i] is set to -1. - * @param offsetsLength The length of the offsets array. - * @param errorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return result - * @draft ICU 57 - */ - UnicodeString &formatAndReplace( - const UnicodeString *const *values, int32_t valuesLength, - UnicodeString &result, - int32_t *offsets, int32_t offsetsLength, UErrorCode &errorCode) const; - - /** - * Returns the pattern text with none of the arguments. - * Like formatting with all-empty string values. - * @draft ICU 57 - */ - UnicodeString getTextWithNoArguments() const { - return getTextWithNoArguments(compiledPattern.getBuffer(), compiledPattern.length()); - } - -private: - /** - * Binary representation of the compiled pattern. - * Index 0: One more than the highest argument number. - * Followed by zero or more arguments or literal-text segments. - * - * An argument is stored as its number, less than ARG_NUM_LIMIT. - * A literal-text segment is stored as its length (at least 1) offset by ARG_NUM_LIMIT, - * followed by that many chars. - */ - UnicodeString compiledPattern; - - static inline int32_t getArgumentLimit(const UChar *compiledPattern, - int32_t compiledPatternLength) { - return compiledPatternLength == 0 ? 0 : compiledPattern[0]; - } - - static UnicodeString getTextWithNoArguments(const UChar *compiledPattern, int32_t compiledPatternLength); - - static UnicodeString &format( - const UChar *compiledPattern, int32_t compiledPatternLength, - const UnicodeString *const *values, - UnicodeString &result, const UnicodeString *resultCopy, UBool forbidResultAsValue, - int32_t *offsets, int32_t offsetsLength, - UErrorCode &errorCode); -}; - -U_NAMESPACE_END - -#endif /* U_HIDE_DRAFT_API */ - -#endif // __SIMPLEFORMATTER_H__ diff --git a/win32/include/spidermonkey/unicode/simpletz.h b/win32/include/spidermonkey/unicode/simpletz.h deleted file mode 100755 index d71fe369..00000000 --- a/win32/include/spidermonkey/unicode/simpletz.h +++ /dev/null @@ -1,930 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************** - * Copyright (C) 1997-2013, International Business Machines * - * Corporation and others. All Rights Reserved. * - ******************************************************************************** - * - * File SIMPLETZ.H - * - * Modification History: - * - * Date Name Description - * 04/21/97 aliu Overhauled header. - * 08/10/98 stephen JDK 1.2 sync - * Added setStartRule() / setEndRule() overloads - * Added hasSameRules() - * 09/02/98 stephen Added getOffset(monthLen) - * Changed getOffset() to take UErrorCode - * 07/09/99 stephen Removed millisPerHour (unused, for HP compiler) - * 12/02/99 aliu Added TimeMode and constructor and setStart/EndRule - * methods that take TimeMode. Added to docs. - ******************************************************************************** - */ - -#ifndef SIMPLETZ_H -#define SIMPLETZ_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: SimpleTimeZone is a concrete subclass of TimeZone. - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/basictz.h" - -U_NAMESPACE_BEGIN - -// forward declaration -class InitialTimeZoneRule; -class TimeZoneTransition; -class AnnualTimeZoneRule; - -/** - * SimpleTimeZone is a concrete subclass of TimeZone - * that represents a time zone for use with a Gregorian calendar. This - * class does not handle historical changes. - *

- * When specifying daylight-savings-time begin and end dates, use a negative value for - * dayOfWeekInMonth to indicate that SimpleTimeZone should - * count from the end of the month backwards. For example, if Daylight Savings - * Time starts or ends at the last Sunday a month, use dayOfWeekInMonth = -1 - * along with dayOfWeek = UCAL_SUNDAY to specify the rule. - * - * @see Calendar - * @see GregorianCalendar - * @see TimeZone - * @author D. Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu - */ -class U_I18N_API SimpleTimeZone: public BasicTimeZone { -public: - - /** - * TimeMode is used, together with a millisecond offset after - * midnight, to specify a rule transition time. Most rules - * transition at a local wall time, that is, according to the - * current time in effect, either standard, or DST. However, some - * rules transition at local standard time, and some at a specific - * UTC time. Although it might seem that all times could be - * converted to wall time, thus eliminating the need for this - * parameter, this is not the case. - * @stable ICU 2.0 - */ - enum TimeMode { - WALL_TIME = 0, - STANDARD_TIME, - UTC_TIME - }; - - /** - * Copy constructor - * @param source the object to be copied. - * @stable ICU 2.0 - */ - SimpleTimeZone(const SimpleTimeZone& source); - - /** - * Default assignment operator - * @param right the object to be copied. - * @stable ICU 2.0 - */ - SimpleTimeZone& operator=(const SimpleTimeZone& right); - - /** - * Destructor - * @stable ICU 2.0 - */ - virtual ~SimpleTimeZone(); - - /** - * Returns true if the two TimeZone objects are equal; that is, they have - * the same ID, raw GMT offset, and DST rules. - * - * @param that The SimpleTimeZone object to be compared with. - * @return True if the given time zone is equal to this time zone; false - * otherwise. - * @stable ICU 2.0 - */ - virtual UBool operator==(const TimeZone& that) const; - - /** - * Constructs a SimpleTimeZone with the given raw GMT offset and time zone ID, - * and which doesn't observe daylight savings time. Normally you should use - * TimeZone::createInstance() to create a TimeZone instead of creating a - * SimpleTimeZone directly with this constructor. - * - * @param rawOffsetGMT The given base time zone offset to GMT. - * @param ID The timezone ID which is obtained from - * TimeZone.getAvailableIDs. - * @stable ICU 2.0 - */ - SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID); - - /** - * Construct a SimpleTimeZone with the given raw GMT offset, time zone ID, - * and times to start and end daylight savings time. To create a TimeZone that - * doesn't observe daylight savings time, don't use this constructor; use - * SimpleTimeZone(rawOffset, ID) instead. Normally, you should use - * TimeZone.createInstance() to create a TimeZone instead of creating a - * SimpleTimeZone directly with this constructor. - *

- * Various types of daylight-savings time rules can be specfied by using different - * values for startDay and startDayOfWeek and endDay and endDayOfWeek. For a - * complete explanation of how these parameters work, see the documentation for - * setStartRule(). - * - * @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset - * @param ID The new SimpleTimeZone's time zone ID. - * @param savingsStartMonth The daylight savings starting month. Month is - * 0-based. eg, 0 for January. - * @param savingsStartDayOfWeekInMonth The daylight savings starting - * day-of-week-in-month. See setStartRule() for a - * complete explanation. - * @param savingsStartDayOfWeek The daylight savings starting day-of-week. - * See setStartRule() for a complete explanation. - * @param savingsStartTime The daylight savings starting time, expressed as the - * number of milliseconds after midnight. - * @param savingsEndMonth The daylight savings ending month. Month is - * 0-based. eg, 0 for January. - * @param savingsEndDayOfWeekInMonth The daylight savings ending day-of-week-in-month. - * See setStartRule() for a complete explanation. - * @param savingsEndDayOfWeek The daylight savings ending day-of-week. - * See setStartRule() for a complete explanation. - * @param savingsEndTime The daylight savings ending time, expressed as the - * number of milliseconds after midnight. - * @param status An UErrorCode to receive the status. - * @stable ICU 2.0 - */ - SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID, - int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth, - int8_t savingsStartDayOfWeek, int32_t savingsStartTime, - int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth, - int8_t savingsEndDayOfWeek, int32_t savingsEndTime, - UErrorCode& status); - /** - * Construct a SimpleTimeZone with the given raw GMT offset, time zone ID, - * and times to start and end daylight savings time. To create a TimeZone that - * doesn't observe daylight savings time, don't use this constructor; use - * SimpleTimeZone(rawOffset, ID) instead. Normally, you should use - * TimeZone.createInstance() to create a TimeZone instead of creating a - * SimpleTimeZone directly with this constructor. - *

- * Various types of daylight-savings time rules can be specfied by using different - * values for startDay and startDayOfWeek and endDay and endDayOfWeek. For a - * complete explanation of how these parameters work, see the documentation for - * setStartRule(). - * - * @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset - * @param ID The new SimpleTimeZone's time zone ID. - * @param savingsStartMonth The daylight savings starting month. Month is - * 0-based. eg, 0 for January. - * @param savingsStartDayOfWeekInMonth The daylight savings starting - * day-of-week-in-month. See setStartRule() for a - * complete explanation. - * @param savingsStartDayOfWeek The daylight savings starting day-of-week. - * See setStartRule() for a complete explanation. - * @param savingsStartTime The daylight savings starting time, expressed as the - * number of milliseconds after midnight. - * @param savingsEndMonth The daylight savings ending month. Month is - * 0-based. eg, 0 for January. - * @param savingsEndDayOfWeekInMonth The daylight savings ending day-of-week-in-month. - * See setStartRule() for a complete explanation. - * @param savingsEndDayOfWeek The daylight savings ending day-of-week. - * See setStartRule() for a complete explanation. - * @param savingsEndTime The daylight savings ending time, expressed as the - * number of milliseconds after midnight. - * @param savingsDST The number of milliseconds added to standard time - * to get DST time. Default is one hour. - * @param status An UErrorCode to receive the status. - * @stable ICU 2.0 - */ - SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID, - int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth, - int8_t savingsStartDayOfWeek, int32_t savingsStartTime, - int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth, - int8_t savingsEndDayOfWeek, int32_t savingsEndTime, - int32_t savingsDST, UErrorCode& status); - - /** - * Construct a SimpleTimeZone with the given raw GMT offset, time zone ID, - * and times to start and end daylight savings time. To create a TimeZone that - * doesn't observe daylight savings time, don't use this constructor; use - * SimpleTimeZone(rawOffset, ID) instead. Normally, you should use - * TimeZone.createInstance() to create a TimeZone instead of creating a - * SimpleTimeZone directly with this constructor. - *

- * Various types of daylight-savings time rules can be specfied by using different - * values for startDay and startDayOfWeek and endDay and endDayOfWeek. For a - * complete explanation of how these parameters work, see the documentation for - * setStartRule(). - * - * @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset - * @param ID The new SimpleTimeZone's time zone ID. - * @param savingsStartMonth The daylight savings starting month. Month is - * 0-based. eg, 0 for January. - * @param savingsStartDayOfWeekInMonth The daylight savings starting - * day-of-week-in-month. See setStartRule() for a - * complete explanation. - * @param savingsStartDayOfWeek The daylight savings starting day-of-week. - * See setStartRule() for a complete explanation. - * @param savingsStartTime The daylight savings starting time, expressed as the - * number of milliseconds after midnight. - * @param savingsStartTimeMode Whether the start time is local wall time, local - * standard time, or UTC time. Default is local wall time. - * @param savingsEndMonth The daylight savings ending month. Month is - * 0-based. eg, 0 for January. - * @param savingsEndDayOfWeekInMonth The daylight savings ending day-of-week-in-month. - * See setStartRule() for a complete explanation. - * @param savingsEndDayOfWeek The daylight savings ending day-of-week. - * See setStartRule() for a complete explanation. - * @param savingsEndTime The daylight savings ending time, expressed as the - * number of milliseconds after midnight. - * @param savingsEndTimeMode Whether the end time is local wall time, local - * standard time, or UTC time. Default is local wall time. - * @param savingsDST The number of milliseconds added to standard time - * to get DST time. Default is one hour. - * @param status An UErrorCode to receive the status. - * @stable ICU 2.0 - */ - SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID, - int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth, - int8_t savingsStartDayOfWeek, int32_t savingsStartTime, - TimeMode savingsStartTimeMode, - int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth, - int8_t savingsEndDayOfWeek, int32_t savingsEndTime, TimeMode savingsEndTimeMode, - int32_t savingsDST, UErrorCode& status); - - /** - * Sets the daylight savings starting year, that is, the year this time zone began - * observing its specified daylight savings time rules. The time zone is considered - * not to observe daylight savings time prior to that year; SimpleTimeZone doesn't - * support historical daylight-savings-time rules. - * @param year the daylight savings starting year. - * @stable ICU 2.0 - */ - void setStartYear(int32_t year); - - /** - * Sets the daylight savings starting rule. For example, in the U.S., Daylight Savings - * Time starts at the second Sunday in March, at 2 AM in standard time. - * Therefore, you can set the start rule by calling: - * setStartRule(UCAL_MARCH, 2, UCAL_SUNDAY, 2*60*60*1000); - * The dayOfWeekInMonth and dayOfWeek parameters together specify how to calculate - * the exact starting date. Their exact meaning depend on their respective signs, - * allowing various types of rules to be constructed, as follows: - *

    - *
  • If both dayOfWeekInMonth and dayOfWeek are positive, they specify the - * day of week in the month (e.g., (2, WEDNESDAY) is the second Wednesday - * of the month).
  • - *
  • If dayOfWeek is positive and dayOfWeekInMonth is negative, they specify - * the day of week in the month counting backward from the end of the month. - * (e.g., (-1, MONDAY) is the last Monday in the month)
  • - *
  • If dayOfWeek is zero and dayOfWeekInMonth is positive, dayOfWeekInMonth - * specifies the day of the month, regardless of what day of the week it is. - * (e.g., (10, 0) is the tenth day of the month)
  • - *
  • If dayOfWeek is zero and dayOfWeekInMonth is negative, dayOfWeekInMonth - * specifies the day of the month counting backward from the end of the - * month, regardless of what day of the week it is (e.g., (-2, 0) is the - * next-to-last day of the month).
  • - *
  • If dayOfWeek is negative and dayOfWeekInMonth is positive, they specify the - * first specified day of the week on or after the specfied day of the month. - * (e.g., (15, -SUNDAY) is the first Sunday after the 15th of the month - * [or the 15th itself if the 15th is a Sunday].)
  • - *
  • If dayOfWeek and DayOfWeekInMonth are both negative, they specify the - * last specified day of the week on or before the specified day of the month. - * (e.g., (-20, -TUESDAY) is the last Tuesday before the 20th of the month - * [or the 20th itself if the 20th is a Tuesday].)
  • - *
- * @param month the daylight savings starting month. Month is 0-based. - * eg, 0 for January. - * @param dayOfWeekInMonth the daylight savings starting - * day-of-week-in-month. Please see the member description for an example. - * @param dayOfWeek the daylight savings starting day-of-week. Please see - * the member description for an example. - * @param time the daylight savings starting time. Please see the member - * description for an example. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setStartRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, - int32_t time, UErrorCode& status); - /** - * Sets the daylight savings starting rule. For example, in the U.S., Daylight Savings - * Time starts at the second Sunday in March, at 2 AM in standard time. - * Therefore, you can set the start rule by calling: - * setStartRule(UCAL_MARCH, 2, UCAL_SUNDAY, 2*60*60*1000); - * The dayOfWeekInMonth and dayOfWeek parameters together specify how to calculate - * the exact starting date. Their exact meaning depend on their respective signs, - * allowing various types of rules to be constructed, as follows: - *
    - *
  • If both dayOfWeekInMonth and dayOfWeek are positive, they specify the - * day of week in the month (e.g., (2, WEDNESDAY) is the second Wednesday - * of the month).
  • - *
  • If dayOfWeek is positive and dayOfWeekInMonth is negative, they specify - * the day of week in the month counting backward from the end of the month. - * (e.g., (-1, MONDAY) is the last Monday in the month)
  • - *
  • If dayOfWeek is zero and dayOfWeekInMonth is positive, dayOfWeekInMonth - * specifies the day of the month, regardless of what day of the week it is. - * (e.g., (10, 0) is the tenth day of the month)
  • - *
  • If dayOfWeek is zero and dayOfWeekInMonth is negative, dayOfWeekInMonth - * specifies the day of the month counting backward from the end of the - * month, regardless of what day of the week it is (e.g., (-2, 0) is the - * next-to-last day of the month).
  • - *
  • If dayOfWeek is negative and dayOfWeekInMonth is positive, they specify the - * first specified day of the week on or after the specfied day of the month. - * (e.g., (15, -SUNDAY) is the first Sunday after the 15th of the month - * [or the 15th itself if the 15th is a Sunday].)
  • - *
  • If dayOfWeek and DayOfWeekInMonth are both negative, they specify the - * last specified day of the week on or before the specified day of the month. - * (e.g., (-20, -TUESDAY) is the last Tuesday before the 20th of the month - * [or the 20th itself if the 20th is a Tuesday].)
  • - *
- * @param month the daylight savings starting month. Month is 0-based. - * eg, 0 for January. - * @param dayOfWeekInMonth the daylight savings starting - * day-of-week-in-month. Please see the member description for an example. - * @param dayOfWeek the daylight savings starting day-of-week. Please see - * the member description for an example. - * @param time the daylight savings starting time. Please see the member - * description for an example. - * @param mode whether the time is local wall time, local standard time, - * or UTC time. Default is local wall time. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setStartRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, - int32_t time, TimeMode mode, UErrorCode& status); - - /** - * Sets the DST start rule to a fixed date within a month. - * - * @param month The month in which this rule occurs (0-based). - * @param dayOfMonth The date in that month (1-based). - * @param time The time of that day (number of millis after midnight) - * when DST takes effect in local wall time, which is - * standard time in this case. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setStartRule(int32_t month, int32_t dayOfMonth, int32_t time, - UErrorCode& status); - /** - * Sets the DST start rule to a fixed date within a month. - * - * @param month The month in which this rule occurs (0-based). - * @param dayOfMonth The date in that month (1-based). - * @param time The time of that day (number of millis after midnight) - * when DST takes effect in local wall time, which is - * standard time in this case. - * @param mode whether the time is local wall time, local standard time, - * or UTC time. Default is local wall time. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setStartRule(int32_t month, int32_t dayOfMonth, int32_t time, - TimeMode mode, UErrorCode& status); - - /** - * Sets the DST start rule to a weekday before or after a give date within - * a month, e.g., the first Monday on or after the 8th. - * - * @param month The month in which this rule occurs (0-based). - * @param dayOfMonth A date within that month (1-based). - * @param dayOfWeek The day of the week on which this rule occurs. - * @param time The time of that day (number of millis after midnight) - * when DST takes effect in local wall time, which is - * standard time in this case. - * @param after If true, this rule selects the first dayOfWeek on - * or after dayOfMonth. If false, this rule selects - * the last dayOfWeek on or before dayOfMonth. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setStartRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, - int32_t time, UBool after, UErrorCode& status); - /** - * Sets the DST start rule to a weekday before or after a give date within - * a month, e.g., the first Monday on or after the 8th. - * - * @param month The month in which this rule occurs (0-based). - * @param dayOfMonth A date within that month (1-based). - * @param dayOfWeek The day of the week on which this rule occurs. - * @param time The time of that day (number of millis after midnight) - * when DST takes effect in local wall time, which is - * standard time in this case. - * @param mode whether the time is local wall time, local standard time, - * or UTC time. Default is local wall time. - * @param after If true, this rule selects the first dayOfWeek on - * or after dayOfMonth. If false, this rule selects - * the last dayOfWeek on or before dayOfMonth. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setStartRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, - int32_t time, TimeMode mode, UBool after, UErrorCode& status); - - /** - * Sets the daylight savings ending rule. For example, if Daylight - * Savings Time ends at the last (-1) Sunday in October, at 2 AM in standard time. - * Therefore, you can set the end rule by calling: - *
-     *    setEndRule(UCAL_OCTOBER, -1, UCAL_SUNDAY, 2*60*60*1000);
-     * 
- * Various other types of rules can be specified by manipulating the dayOfWeek - * and dayOfWeekInMonth parameters. For complete details, see the documentation - * for setStartRule(). - * - * @param month the daylight savings ending month. Month is 0-based. - * eg, 0 for January. - * @param dayOfWeekInMonth the daylight savings ending - * day-of-week-in-month. See setStartRule() for a complete explanation. - * @param dayOfWeek the daylight savings ending day-of-week. See setStartRule() - * for a complete explanation. - * @param time the daylight savings ending time. Please see the member - * description for an example. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setEndRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, - int32_t time, UErrorCode& status); - - /** - * Sets the daylight savings ending rule. For example, if Daylight - * Savings Time ends at the last (-1) Sunday in October, at 2 AM in standard time. - * Therefore, you can set the end rule by calling: - *
-     *    setEndRule(UCAL_OCTOBER, -1, UCAL_SUNDAY, 2*60*60*1000);
-     * 
- * Various other types of rules can be specified by manipulating the dayOfWeek - * and dayOfWeekInMonth parameters. For complete details, see the documentation - * for setStartRule(). - * - * @param month the daylight savings ending month. Month is 0-based. - * eg, 0 for January. - * @param dayOfWeekInMonth the daylight savings ending - * day-of-week-in-month. See setStartRule() for a complete explanation. - * @param dayOfWeek the daylight savings ending day-of-week. See setStartRule() - * for a complete explanation. - * @param time the daylight savings ending time. Please see the member - * description for an example. - * @param mode whether the time is local wall time, local standard time, - * or UTC time. Default is local wall time. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setEndRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek, - int32_t time, TimeMode mode, UErrorCode& status); - - /** - * Sets the DST end rule to a fixed date within a month. - * - * @param month The month in which this rule occurs (0-based). - * @param dayOfMonth The date in that month (1-based). - * @param time The time of that day (number of millis after midnight) - * when DST ends in local wall time, which is daylight - * time in this case. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setEndRule(int32_t month, int32_t dayOfMonth, int32_t time, UErrorCode& status); - - /** - * Sets the DST end rule to a fixed date within a month. - * - * @param month The month in which this rule occurs (0-based). - * @param dayOfMonth The date in that month (1-based). - * @param time The time of that day (number of millis after midnight) - * when DST ends in local wall time, which is daylight - * time in this case. - * @param mode whether the time is local wall time, local standard time, - * or UTC time. Default is local wall time. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setEndRule(int32_t month, int32_t dayOfMonth, int32_t time, - TimeMode mode, UErrorCode& status); - - /** - * Sets the DST end rule to a weekday before or after a give date within - * a month, e.g., the first Monday on or after the 8th. - * - * @param month The month in which this rule occurs (0-based). - * @param dayOfMonth A date within that month (1-based). - * @param dayOfWeek The day of the week on which this rule occurs. - * @param time The time of that day (number of millis after midnight) - * when DST ends in local wall time, which is daylight - * time in this case. - * @param after If true, this rule selects the first dayOfWeek on - * or after dayOfMonth. If false, this rule selects - * the last dayOfWeek on or before dayOfMonth. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, - int32_t time, UBool after, UErrorCode& status); - - /** - * Sets the DST end rule to a weekday before or after a give date within - * a month, e.g., the first Monday on or after the 8th. - * - * @param month The month in which this rule occurs (0-based). - * @param dayOfMonth A date within that month (1-based). - * @param dayOfWeek The day of the week on which this rule occurs. - * @param time The time of that day (number of millis after midnight) - * when DST ends in local wall time, which is daylight - * time in this case. - * @param mode whether the time is local wall time, local standard time, - * or UTC time. Default is local wall time. - * @param after If true, this rule selects the first dayOfWeek on - * or after dayOfMonth. If false, this rule selects - * the last dayOfWeek on or before dayOfMonth. - * @param status An UErrorCode - * @stable ICU 2.0 - */ - void setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, - int32_t time, TimeMode mode, UBool after, UErrorCode& status); - - /** - * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time in this time zone, taking daylight savings time into - * account) as of a particular reference date. The reference date is used to determine - * whether daylight savings time is in effect and needs to be figured into the offset - * that is returned (in other words, what is the adjusted GMT offset in this time zone - * at this particular date and time?). For the time zones produced by createTimeZone(), - * the reference data is specified according to the Gregorian calendar, and the date - * and time fields are in GMT, NOT local time. - * - * @param era The reference date's era - * @param year The reference date's year - * @param month The reference date's month (0-based; 0 is January) - * @param day The reference date's day-in-month (1-based) - * @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday) - * @param millis The reference date's milliseconds in day, UTT (NOT local time). - * @param status An UErrorCode to receive the status. - * @return The offset in milliseconds to add to GMT to get local time. - * @stable ICU 2.0 - */ - virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, - uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const; - - /** - * Gets the time zone offset, for current date, modified in case of - * daylight savings. This is the offset to add *to* UTC to get local time. - * @param era the era of the given date. - * @param year the year in the given date. - * @param month the month in the given date. - * Month is 0-based. e.g., 0 for January. - * @param day the day-in-month of the given date. - * @param dayOfWeek the day-of-week of the given date. - * @param milliseconds the millis in day in standard local time. - * @param monthLength the length of the given month in days. - * @param status An UErrorCode to receive the status. - * @return the offset to add *to* GMT to get local time. - * @stable ICU 2.0 - */ - virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, - uint8_t dayOfWeek, int32_t milliseconds, - int32_t monthLength, UErrorCode& status) const; - /** - * Gets the time zone offset, for current date, modified in case of - * daylight savings. This is the offset to add *to* UTC to get local time. - * @param era the era of the given date. - * @param year the year in the given date. - * @param month the month in the given date. - * Month is 0-based. e.g., 0 for January. - * @param day the day-in-month of the given date. - * @param dayOfWeek the day-of-week of the given date. - * @param milliseconds the millis in day in standard local time. - * @param monthLength the length of the given month in days. - * @param prevMonthLength length of the previous month in days. - * @param status An UErrorCode to receive the status. - * @return the offset to add *to* GMT to get local time. - * @stable ICU 2.0 - */ - virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, - uint8_t dayOfWeek, int32_t milliseconds, - int32_t monthLength, int32_t prevMonthLength, - UErrorCode& status) const; - - /** - * Redeclared TimeZone method. This implementation simply calls - * the base class method, which otherwise would be hidden. - * @stable ICU 2.8 - */ - virtual void getOffset(UDate date, UBool local, int32_t& rawOffset, - int32_t& dstOffset, UErrorCode& ec) const; - - /** - * Get time zone offsets from local wall time. - * @internal - */ - virtual void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt, - int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) const; - - /** - * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time, before taking daylight savings time into account). - * - * @return The TimeZone's raw GMT offset. - * @stable ICU 2.0 - */ - virtual int32_t getRawOffset(void) const; - - /** - * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time, before taking daylight savings time into account). - * - * @param offsetMillis The new raw GMT offset for this time zone. - * @stable ICU 2.0 - */ - virtual void setRawOffset(int32_t offsetMillis); - - /** - * Sets the amount of time in ms that the clock is advanced during DST. - * @param millisSavedDuringDST the number of milliseconds the time is - * advanced with respect to standard time when the daylight savings rules - * are in effect. A positive number, typically one hour (3600000). - * @param status An UErrorCode to receive the status. - * @stable ICU 2.0 - */ - void setDSTSavings(int32_t millisSavedDuringDST, UErrorCode& status); - - /** - * Returns the amount of time in ms that the clock is advanced during DST. - * @return the number of milliseconds the time is - * advanced with respect to standard time when the daylight savings rules - * are in effect. A positive number, typically one hour (3600000). - * @stable ICU 2.0 - */ - virtual int32_t getDSTSavings(void) const; - - /** - * Queries if this TimeZone uses Daylight Savings Time. - * - * @return True if this TimeZone uses Daylight Savings Time; false otherwise. - * @stable ICU 2.0 - */ - virtual UBool useDaylightTime(void) const; - - /** - * Returns true if the given date is within the period when daylight savings time - * is in effect; false otherwise. If the TimeZone doesn't observe daylight savings - * time, this functions always returns false. - * This method is wasteful since it creates a new GregorianCalendar and - * deletes it each time it is called. This is a deprecated method - * and provided only for Java compatibility. - * - * @param date The date to test. - * @param status An UErrorCode to receive the status. - * @return true if the given date is in Daylight Savings Time; - * false otherwise. - * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead. - */ - virtual UBool inDaylightTime(UDate date, UErrorCode& status) const; - - /** - * Return true if this zone has the same rules and offset as another zone. - * @param other the TimeZone object to be compared with - * @return true if the given zone has the same rules and offset as this one - * @stable ICU 2.0 - */ - UBool hasSameRules(const TimeZone& other) const; - - /** - * Clones TimeZone objects polymorphically. Clients are responsible for deleting - * the TimeZone object cloned. - * - * @return A new copy of this TimeZone object. - * @stable ICU 2.0 - */ - virtual TimeZone* clone(void) const; - - /** - * Gets the first time zone transition after the base time. - * @param base The base time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives the first transition after the base time. - * @return TRUE if the transition is found. - * @stable ICU 3.8 - */ - virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const; - - /** - * Gets the most recent time zone transition before the base time. - * @param base The base time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives the most recent transition before the base time. - * @return TRUE if the transition is found. - * @stable ICU 3.8 - */ - virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const; - - /** - * Returns the number of TimeZoneRules which represents time transitions, - * for this time zone, that is, all TimeZoneRules for this time zone except - * InitialTimeZoneRule. The return value range is 0 or any positive value. - * @param status Receives error status code. - * @return The number of TimeZoneRules representing time transitions. - * @stable ICU 3.8 - */ - virtual int32_t countTransitionRules(UErrorCode& status) const; - - /** - * Gets the InitialTimeZoneRule and the set of TimeZoneRule - * which represent time transitions for this time zone. On successful return, - * the argument initial points to non-NULL InitialTimeZoneRule and - * the array trsrules is filled with 0 or multiple TimeZoneRule - * instances up to the size specified by trscount. The results are referencing the - * rule instance held by this time zone instance. Therefore, after this time zone - * is destructed, they are no longer available. - * @param initial Receives the initial timezone rule - * @param trsrules Receives the timezone transition rules - * @param trscount On input, specify the size of the array 'transitions' receiving - * the timezone transition rules. On output, actual number of - * rules filled in the array will be set. - * @param status Receives error status code. - * @stable ICU 3.8 - */ - virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial, - const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const; - - -public: - - /** - * Override TimeZone Returns a unique class ID POLYMORPHICALLY. Pure virtual - * override. This method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() methods call - * this method. - * - * @return The class ID for this object. All objects of a given class have the - * same class ID. Objects of other classes have different class IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const; - - /** - * Return the class ID for this class. This is useful only for comparing to a return - * value from getDynamicClassID(). For example: - *
-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       Derived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - -private: - /** - * Constants specifying values of startMode and endMode. - */ - enum EMode - { - DOM_MODE = 1, - DOW_IN_MONTH_MODE, - DOW_GE_DOM_MODE, - DOW_LE_DOM_MODE - }; - - SimpleTimeZone(); // default constructor not implemented - - /** - * Internal construction method. - * @param rawOffsetGMT The new SimpleTimeZone's raw GMT offset - * @param startMonth the month DST starts - * @param startDay the day DST starts - * @param startDayOfWeek the DOW DST starts - * @param startTime the time DST starts - * @param startTimeMode Whether the start time is local wall time, local - * standard time, or UTC time. Default is local wall time. - * @param endMonth the month DST ends - * @param endDay the day DST ends - * @param endDayOfWeek the DOW DST ends - * @param endTime the time DST ends - * @param endTimeMode Whether the end time is local wall time, local - * standard time, or UTC time. Default is local wall time. - * @param dstSavings The number of milliseconds added to standard time - * to get DST time. Default is one hour. - * @param status An UErrorCode to receive the status. - */ - void construct(int32_t rawOffsetGMT, - int8_t startMonth, int8_t startDay, int8_t startDayOfWeek, - int32_t startTime, TimeMode startTimeMode, - int8_t endMonth, int8_t endDay, int8_t endDayOfWeek, - int32_t endTime, TimeMode endTimeMode, - int32_t dstSavings, UErrorCode& status); - - /** - * Compare a given date in the year to a rule. Return 1, 0, or -1, depending - * on whether the date is after, equal to, or before the rule date. The - * millis are compared directly against the ruleMillis, so any - * standard-daylight adjustments must be handled by the caller. - * - * @return 1 if the date is after the rule date, -1 if the date is before - * the rule date, or 0 if the date is equal to the rule date. - */ - static int32_t compareToRule(int8_t month, int8_t monthLen, int8_t prevMonthLen, - int8_t dayOfMonth, - int8_t dayOfWeek, int32_t millis, int32_t millisDelta, - EMode ruleMode, int8_t ruleMonth, int8_t ruleDayOfWeek, - int8_t ruleDay, int32_t ruleMillis); - - /** - * Given a set of encoded rules in startDay and startDayOfMonth, decode - * them and set the startMode appropriately. Do the same for endDay and - * endDayOfMonth. - *

- * Upon entry, the day of week variables may be zero or - * negative, in order to indicate special modes. The day of month - * variables may also be negative. - *

- * Upon exit, the mode variables will be - * set, and the day of week and day of month variables will be positive. - *

- * This method also recognizes a startDay or endDay of zero as indicating - * no DST. - */ - void decodeRules(UErrorCode& status); - void decodeStartRule(UErrorCode& status); - void decodeEndRule(UErrorCode& status); - - int8_t startMonth, startDay, startDayOfWeek; // the month, day, DOW, and time DST starts - int32_t startTime; - TimeMode startTimeMode, endTimeMode; // Mode for startTime, endTime; see TimeMode - int8_t endMonth, endDay, endDayOfWeek; // the month, day, DOW, and time DST ends - int32_t endTime; - int32_t startYear; // the year these DST rules took effect - int32_t rawOffset; // the TimeZone's raw GMT offset - UBool useDaylight; // flag indicating whether this TimeZone uses DST - static const int8_t STATICMONTHLENGTH[12]; // lengths of the months - EMode startMode, endMode; // flags indicating what kind of rules the DST rules are - - /** - * A positive value indicating the amount of time saved during DST in ms. - * Typically one hour; sometimes 30 minutes. - */ - int32_t dstSavings; - - /* Private for BasicTimeZone implementation */ - void checkTransitionRules(UErrorCode& status) const; - void initTransitionRules(UErrorCode& status); - void clearTransitionRules(void); - void deleteTransitionRules(void); - UBool transitionRulesInitialized; - InitialTimeZoneRule* initialRule; - TimeZoneTransition* firstTransition; - AnnualTimeZoneRule* stdRule; - AnnualTimeZoneRule* dstRule; -}; - -inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfWeekInMonth, - int32_t dayOfWeek, - int32_t time, UErrorCode& status) { - setStartRule(month, dayOfWeekInMonth, dayOfWeek, time, WALL_TIME, status); -} - -inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfMonth, - int32_t time, - UErrorCode& status) { - setStartRule(month, dayOfMonth, time, WALL_TIME, status); -} - -inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfMonth, - int32_t dayOfWeek, - int32_t time, UBool after, UErrorCode& status) { - setStartRule(month, dayOfMonth, dayOfWeek, time, WALL_TIME, after, status); -} - -inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfWeekInMonth, - int32_t dayOfWeek, - int32_t time, UErrorCode& status) { - setEndRule(month, dayOfWeekInMonth, dayOfWeek, time, WALL_TIME, status); -} - -inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfMonth, - int32_t time, UErrorCode& status) { - setEndRule(month, dayOfMonth, time, WALL_TIME, status); -} - -inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, - int32_t time, UBool after, UErrorCode& status) { - setEndRule(month, dayOfMonth, dayOfWeek, time, WALL_TIME, after, status); -} - -inline void -SimpleTimeZone::getOffset(UDate date, UBool local, int32_t& rawOffsetRef, - int32_t& dstOffsetRef, UErrorCode& ec) const { - TimeZone::getOffset(date, local, rawOffsetRef, dstOffsetRef, ec); -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _SIMPLETZ diff --git a/win32/include/spidermonkey/unicode/smpdtfmt.h b/win32/include/spidermonkey/unicode/smpdtfmt.h deleted file mode 100755 index e6cf28d2..00000000 --- a/win32/include/spidermonkey/unicode/smpdtfmt.h +++ /dev/null @@ -1,1620 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -* Copyright (C) 1997-2016, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -* -* File SMPDTFMT.H -* -* Modification History: -* -* Date Name Description -* 02/19/97 aliu Converted from java. -* 07/09/97 helena Make ParsePosition into a class. -* 07/21/98 stephen Added GMT_PLUS, GMT_MINUS -* Changed setTwoDigitStartDate to set2DigitYearStart -* Changed getTwoDigitStartDate to get2DigitYearStart -* Removed subParseLong -* Removed getZoneIndex (added in DateFormatSymbols) -* 06/14/99 stephen Removed fgTimeZoneDataSuffix -* 10/14/99 aliu Updated class doc to describe 2-digit year parsing -* {j28 4182066}. -******************************************************************************* -*/ - -#ifndef SMPDTFMT_H -#define SMPDTFMT_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Format and parse dates in a language-independent manner. - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/datefmt.h" -#include "unicode/udisplaycontext.h" -#include "unicode/tzfmt.h" /* for UTimeZoneFormatTimeType */ -#include "unicode/brkiter.h" - -U_NAMESPACE_BEGIN - -class DateFormatSymbols; -class DateFormat; -class MessageFormat; -class FieldPositionHandler; -class TimeZoneFormat; -class SharedNumberFormat; -class SimpleDateFormatMutableNFs; - -/** - * - * SimpleDateFormat is a concrete class for formatting and parsing dates in a - * language-independent manner. It allows for formatting (millis -> text), - * parsing (text -> millis), and normalization. Formats/Parses a date or time, - * which is the standard milliseconds since 24:00 GMT, Jan 1, 1970. - *

- * Clients are encouraged to create a date-time formatter using DateFormat::getInstance(), - * getDateInstance(), getDateInstance(), or getDateTimeInstance() rather than - * explicitly constructing an instance of SimpleDateFormat. This way, the client - * is guaranteed to get an appropriate formatting pattern for whatever locale the - * program is running in. However, if the client needs something more unusual than - * the default patterns in the locales, he can construct a SimpleDateFormat directly - * and give it an appropriate pattern (or use one of the factory methods on DateFormat - * and modify the pattern after the fact with toPattern() and applyPattern(). - * - *

Date and Time Patterns:

- * - *

Date and time formats are specified by date and time pattern strings. - * Within date and time pattern strings, all unquoted ASCII letters [A-Za-z] are reserved - * as pattern letters representing calendar fields. SimpleDateFormat supports - * the date and time formatting algorithm and pattern letters defined by - * UTS#35 - * Unicode Locale Data Markup Language (LDML) and further documented for ICU in the - * ICU - * User Guide. The following pattern letters are currently available (note that the actual - * values depend on CLDR and may change from the examples shown here):

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
FieldSym.No.ExampleDescription
eraG1..3ADEra - Replaced with the Era string for the current date. One to three letters for the - * abbreviated form, four letters for the long (wide) form, five for the narrow form.
4Anno Domini
5A
yeary1..n1996Year. Normally the length specifies the padding, but for two letters it also specifies the maximum - * length. Example:
- *
- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Yearyyyyyyyyyyyyyyy
AD 1101001000100001
AD 121212012001200012
AD 12312323123012300123
AD 12341234341234123401234
AD 123451234545123451234512345
- *
- *
Y1..n1997Year (in "Week of Year" based calendars). Normally the length specifies the padding, - * but for two letters it also specifies the maximum length. This year designation is used in ISO - * year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems - * where week date processing is desired. May not always be the same value as calendar year.
u1..n4601Extended year. This is a single number designating the year of this calendar system, encompassing - * all supra-year fields. For example, for the Julian calendar system, year numbers are positive, with an - * era of BCE or CE. An extended year value for the Julian calendar system assigns positive values to CE - * years and negative values to BCE years, with 1 BCE being year 0.
U1..3甲子Cyclic year name. Calendars such as the Chinese lunar calendar (and related calendars) - * and the Hindu calendars use 60-year cycles of year names. Use one through three letters for the abbreviated - * name, four for the full (wide) name, or five for the narrow name (currently the data only provides abbreviated names, - * which will be used for all requested name widths). If the calendar does not provide cyclic year name data, - * or if the year value to be formatted is out of the range of years for which cyclic name data is provided, - * then numeric formatting is used (behaves like 'y').
4(currently also 甲子)
5(currently also 甲子)
quarterQ1..202Quarter - Use one or two for the numerical quarter, three for the abbreviation, or four for the - * full (wide) name (five for the narrow name is not yet supported).
3Q2
42nd quarter
q1..202Stand-Alone Quarter - Use one or two for the numerical quarter, three for the abbreviation, - * or four for the full name (five for the narrow name is not yet supported).
3Q2
42nd quarter
monthM1..209Month - Use one or two for the numerical month, three for the abbreviation, four for - * the full (wide) name, or five for the narrow name. With two ("MM"), the month number is zero-padded - * if necessary (e.g. "08")
3Sep
4September
5S
L1..209Stand-Alone Month - Use one or two for the numerical month, three for the abbreviation, - * four for the full (wide) name, or 5 for the narrow name. With two ("LL"), the month number is zero-padded if - * necessary (e.g. "08")
3Sep
4September
5S
weekw1..227Week of Year. Use "w" to show the minimum number of digits, or "ww" to always show two digits - * (zero-padding if necessary, e.g. "08").
W13Week of Month
dayd1..21Date - Day of the month. Use "d" to show the minimum number of digits, or "dd" to always show - * two digits (zero-padding if necessary, e.g. "08").
D1..3345Day of year
F12Day of Week in Month. The example is for the 2nd Wed in July
g1..n2451334Modified Julian day. This is different from the conventional Julian day number in two regards. - * First, it demarcates days at local zone midnight, rather than noon GMT. Second, it is a local number; - * that is, it depends on the local time zone. It can be thought of as a single number that encompasses - * all the date-related fields.
week
- * day
E1..3TueDay of week - Use one through three letters for the short day, four for the full (wide) name, - * five for the narrow name, or six for the short name.
4Tuesday
5T
6Tu
e1..22Local day of week. Same as E except adds a numeric value that will depend on the local - * starting day of the week, using one or two letters. For this example, Monday is the first day of the week.
3Tue
4Tuesday
5T
6Tu
c12Stand-Alone local day of week - Use one letter for the local numeric value (same - * as 'e'), three for the short day, four for the full (wide) name, five for the narrow name, or six for - * the short name.
3Tue
4Tuesday
5T
6Tu
perioda1AMAM or PM
hourh1..211Hour [1-12]. When used in skeleton data or in a skeleton passed in an API for flexible data pattern - * generation, it should match the 12-hour-cycle format preferred by the locale (h or K); it should not match - * a 24-hour-cycle format (H or k). Use hh for zero padding.
H1..213Hour [0-23]. When used in skeleton data or in a skeleton passed in an API for flexible data pattern - * generation, it should match the 24-hour-cycle format preferred by the locale (H or k); it should not match a - * 12-hour-cycle format (h or K). Use HH for zero padding.
K1..20Hour [0-11]. When used in a skeleton, only matches K or h, see above. Use KK for zero padding.
k1..224Hour [1-24]. When used in a skeleton, only matches k or H, see above. Use kk for zero padding.
minutem1..259Minute. Use "m" to show the minimum number of digits, or "mm" to always show two digits - * (zero-padding if necessary, e.g. "08").
seconds1..212Second. Use "s" to show the minimum number of digits, or "ss" to always show two digits - * (zero-padding if necessary, e.g. "08").
S1..n3450Fractional Second - truncates (like other time fields) to the count of letters when formatting. - * Appends zeros if more than 3 letters specified. Truncates at three significant digits when parsing. - * (example shows display using pattern SSSS for seconds value 12.34567)
A1..n69540000Milliseconds in day. This field behaves exactly like a composite of all time-related fields, - * not including the zone fields. As such, it also reflects discontinuities of those fields on DST transition - * days. On a day of DST onset, it will jump forward. On a day of DST cessation, it will jump backward. This - * reflects the fact that is must be combined with the offset field to obtain a unique local time value.
zonez1..3PDTThe short specific non-location format. - * Where that is unavailable, falls back to the short localized GMT format ("O").
4Pacific Daylight TimeThe long specific non-location format. - * Where that is unavailable, falls back to the long localized GMT format ("OOOO").
Z1..3-0800The ISO8601 basic format with hours, minutes and optional seconds fields. - * The format is equivalent to RFC 822 zone format (when optional seconds field is absent). - * This is equivalent to the "xxxx" specifier.
4GMT-8:00The long localized GMT format. - * This is equivalent to the "OOOO" specifier.
5-08:00
- * -07:52:58
The ISO8601 extended format with hours, minutes and optional seconds fields. - * The ISO8601 UTC indicator "Z" is used when local time offset is 0. - * This is equivalent to the "XXXXX" specifier.
O1GMT-8The short localized GMT format.
4GMT-08:00The long localized GMT format.
v1PTThe short generic non-location format. - * Where that is unavailable, falls back to the generic location format ("VVVV"), - * then the short localized GMT format as the final fallback.
4Pacific TimeThe long generic non-location format. - * Where that is unavailable, falls back to generic location format ("VVVV"). - *
V1uslaxThe short time zone ID. - * Where that is unavailable, the special short time zone ID unk (Unknown Zone) is used.
- * Note: This specifier was originally used for a variant of the short specific non-location format, - * but it was deprecated in the later version of the LDML specification. In CLDR 23/ICU 51, the definition of - * the specifier was changed to designate a short time zone ID.
2America/Los_AngelesThe long time zone ID.
3Los AngelesThe exemplar city (location) for the time zone. - * Where that is unavailable, the localized exemplar city name for the special zone Etc/Unknown is used - * as the fallback (for example, "Unknown City").
4Los Angeles TimeThe generic location format. - * Where that is unavailable, falls back to the long localized GMT format ("OOOO"; - * Note: Fallback is only necessary with a GMT-style Time Zone ID, like Etc/GMT-830.)
- * This is especially useful when presenting possible timezone choices for user selection, - * since the naming is more uniform than the "v" format.
X1-08
- * +0530
- * Z
The ISO8601 basic format with hours field and optional minutes field. - * The ISO8601 UTC indicator "Z" is used when local time offset is 0.
2-0800
- * Z
The ISO8601 basic format with hours and minutes fields. - * The ISO8601 UTC indicator "Z" is used when local time offset is 0.
3-08:00
- * Z
The ISO8601 extended format with hours and minutes fields. - * The ISO8601 UTC indicator "Z" is used when local time offset is 0.
4-0800
- * -075258
- * Z
The ISO8601 basic format with hours, minutes and optional seconds fields. - * (Note: The seconds field is not supported by the ISO8601 specification.) - * The ISO8601 UTC indicator "Z" is used when local time offset is 0.
5-08:00
- * -07:52:58
- * Z
The ISO8601 extended format with hours, minutes and optional seconds fields. - * (Note: The seconds field is not supported by the ISO8601 specification.) - * The ISO8601 UTC indicator "Z" is used when local time offset is 0.
x1-08
- * +0530
The ISO8601 basic format with hours field and optional minutes field.
2-0800The ISO8601 basic format with hours and minutes fields.
3-08:00The ISO8601 extended format with hours and minutes fields.
4-0800
- * -075258
The ISO8601 basic format with hours, minutes and optional seconds fields. - * (Note: The seconds field is not supported by the ISO8601 specification.)
5-08:00
- * -07:52:58
The ISO8601 extended format with hours, minutes and optional seconds fields. - * (Note: The seconds field is not supported by the ISO8601 specification.)
- * - *

- * Any characters in the pattern that are not in the ranges of ['a'..'z'] and - * ['A'..'Z'] will be treated as quoted text. For instance, characters - * like ':', '.', ' ', '#' and '@' will appear in the resulting time text - * even they are not embraced within single quotes. - *

- * A pattern containing any invalid pattern letter will result in a failing - * UErrorCode result during formatting or parsing. - *

- * Examples using the US locale: - *

- * \code
- *    Format Pattern                         Result
- *    --------------                         -------
- *    "yyyy.MM.dd G 'at' HH:mm:ss vvvv" ->>  1996.07.10 AD at 15:08:56 Pacific Time
- *    "EEE, MMM d, ''yy"                ->>  Wed, July 10, '96
- *    "h:mm a"                          ->>  12:08 PM
- *    "hh 'o''clock' a, zzzz"           ->>  12 o'clock PM, Pacific Daylight Time
- *    "K:mm a, vvv"                     ->>  0:00 PM, PT
- *    "yyyyy.MMMMM.dd GGG hh:mm aaa"    ->>  1996.July.10 AD 12:08 PM
- * \endcode
- * 
- * Code Sample: - *
- * \code
- *     UErrorCode success = U_ZERO_ERROR;
- *     SimpleTimeZone* pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, "PST");
- *     pdt->setStartRule( Calendar::APRIL, 1, Calendar::SUNDAY, 2*60*60*1000);
- *     pdt->setEndRule( Calendar::OCTOBER, -1, Calendar::SUNDAY, 2*60*60*1000);
- *
- *     // Format the current time.
- *     SimpleDateFormat* formatter
- *         = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss a zzz", success );
- *     GregorianCalendar cal(success);
- *     UDate currentTime_1 = cal.getTime(success);
- *     FieldPosition fp(FieldPosition::DONT_CARE);
- *     UnicodeString dateString;
- *     formatter->format( currentTime_1, dateString, fp );
- *     cout << "result: " << dateString << endl;
- *
- *     // Parse the previous string back into a Date.
- *     ParsePosition pp(0);
- *     UDate currentTime_2 = formatter->parse(dateString, pp );
- * \endcode
- * 
- * In the above example, the time value "currentTime_2" obtained from parsing - * will be equal to currentTime_1. However, they may not be equal if the am/pm - * marker 'a' is left out from the format pattern while the "hour in am/pm" - * pattern symbol is used. This information loss can happen when formatting the - * time in PM. - * - *

- * When parsing a date string using the abbreviated year pattern ("y" or "yy"), - * SimpleDateFormat must interpret the abbreviated year - * relative to some century. It does this by adjusting dates to be - * within 80 years before and 20 years after the time the SimpleDateFormat - * instance is created. For example, using a pattern of "MM/dd/yy" and a - * SimpleDateFormat instance created on Jan 1, 1997, the string - * "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64" - * would be interpreted as May 4, 1964. - * During parsing, only strings consisting of exactly two digits, as defined by - * Unicode::isDigit(), will be parsed into the default century. - * Any other numeric string, such as a one digit string, a three or more digit - * string, or a two digit string that isn't all digits (for example, "-1"), is - * interpreted literally. So "01/02/3" or "01/02/003" are parsed (for the - * Gregorian calendar), using the same pattern, as Jan 2, 3 AD. Likewise (but - * only in lenient parse mode, the default) "01/02/-3" is parsed as Jan 2, 4 BC. - * - *

- * If the year pattern has more than two 'y' characters, the year is - * interpreted literally, regardless of the number of digits. So using the - * pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D. - * - *

- * When numeric fields abut one another directly, with no intervening delimiter - * characters, they constitute a run of abutting numeric fields. Such runs are - * parsed specially. For example, the format "HHmmss" parses the input text - * "123456" to 12:34:56, parses the input text "12345" to 1:23:45, and fails to - * parse "1234". In other words, the leftmost field of the run is flexible, - * while the others keep a fixed width. If the parse fails anywhere in the run, - * then the leftmost field is shortened by one character, and the entire run is - * parsed again. This is repeated until either the parse succeeds or the - * leftmost field is one character in length. If the parse still fails at that - * point, the parse of the run fails. - * - *

- * For time zones that have no names, SimpleDateFormat uses strings GMT+hours:minutes or - * GMT-hours:minutes. - *

- * The calendar defines what is the first day of the week, the first week of the - * year, whether hours are zero based or not (0 vs 12 or 24), and the timezone. - * There is one common number format to handle all the numbers; the digit count - * is handled programmatically according to the pattern. - * - *

User subclasses are not supported. While clients may write - * subclasses, such code will not necessarily work and will not be - * guaranteed to work stably from release to release. - */ -class U_I18N_API SimpleDateFormat: public DateFormat { -public: - /** - * Construct a SimpleDateFormat using the default pattern for the default - * locale. - *

- * [Note:] Not all locales support SimpleDateFormat; for full generality, - * use the factory methods in the DateFormat class. - * @param status Output param set to success/failure code. - * @stable ICU 2.0 - */ - SimpleDateFormat(UErrorCode& status); - - /** - * Construct a SimpleDateFormat using the given pattern and the default locale. - * The locale is used to obtain the symbols used in formatting (e.g., the - * names of the months), but not to provide the pattern. - *

- * [Note:] Not all locales support SimpleDateFormat; for full generality, - * use the factory methods in the DateFormat class. - * @param pattern the pattern for the format. - * @param status Output param set to success/failure code. - * @stable ICU 2.0 - */ - SimpleDateFormat(const UnicodeString& pattern, - UErrorCode& status); - - /** - * Construct a SimpleDateFormat using the given pattern, numbering system override, and the default locale. - * The locale is used to obtain the symbols used in formatting (e.g., the - * names of the months), but not to provide the pattern. - *

- * A numbering system override is a string containing either the name of a known numbering system, - * or a set of field and numbering system pairs that specify which fields are to be formattied with - * the alternate numbering system. For example, to specify that all numeric fields in the specified - * date or time pattern are to be rendered using Thai digits, simply specify the numbering system override - * as "thai". To specify that just the year portion of the date be formatted using Hebrew numbering, - * use the override string "y=hebrew". Numbering system overrides can be combined using a semi-colon - * character in the override string, such as "d=decimal;M=arabic;y=hebrew", etc. - * - *

- * [Note:] Not all locales support SimpleDateFormat; for full generality, - * use the factory methods in the DateFormat class. - * @param pattern the pattern for the format. - * @param override the override string. - * @param status Output param set to success/failure code. - * @stable ICU 4.2 - */ - SimpleDateFormat(const UnicodeString& pattern, - const UnicodeString& override, - UErrorCode& status); - - /** - * Construct a SimpleDateFormat using the given pattern and locale. - * The locale is used to obtain the symbols used in formatting (e.g., the - * names of the months), but not to provide the pattern. - *

- * [Note:] Not all locales support SimpleDateFormat; for full generality, - * use the factory methods in the DateFormat class. - * @param pattern the pattern for the format. - * @param locale the given locale. - * @param status Output param set to success/failure code. - * @stable ICU 2.0 - */ - SimpleDateFormat(const UnicodeString& pattern, - const Locale& locale, - UErrorCode& status); - - /** - * Construct a SimpleDateFormat using the given pattern, numbering system override, and locale. - * The locale is used to obtain the symbols used in formatting (e.g., the - * names of the months), but not to provide the pattern. - *

- * A numbering system override is a string containing either the name of a known numbering system, - * or a set of field and numbering system pairs that specify which fields are to be formattied with - * the alternate numbering system. For example, to specify that all numeric fields in the specified - * date or time pattern are to be rendered using Thai digits, simply specify the numbering system override - * as "thai". To specify that just the year portion of the date be formatted using Hebrew numbering, - * use the override string "y=hebrew". Numbering system overrides can be combined using a semi-colon - * character in the override string, such as "d=decimal;M=arabic;y=hebrew", etc. - *

- * [Note:] Not all locales support SimpleDateFormat; for full generality, - * use the factory methods in the DateFormat class. - * @param pattern the pattern for the format. - * @param override the numbering system override. - * @param locale the given locale. - * @param status Output param set to success/failure code. - * @stable ICU 4.2 - */ - SimpleDateFormat(const UnicodeString& pattern, - const UnicodeString& override, - const Locale& locale, - UErrorCode& status); - - /** - * Construct a SimpleDateFormat using the given pattern and locale-specific - * symbol data. The formatter takes ownership of the DateFormatSymbols object; - * the caller is no longer responsible for deleting it. - * @param pattern the given pattern for the format. - * @param formatDataToAdopt the symbols to be adopted. - * @param status Output param set to success/faulure code. - * @stable ICU 2.0 - */ - SimpleDateFormat(const UnicodeString& pattern, - DateFormatSymbols* formatDataToAdopt, - UErrorCode& status); - - /** - * Construct a SimpleDateFormat using the given pattern and locale-specific - * symbol data. The DateFormatSymbols object is NOT adopted; the caller - * remains responsible for deleting it. - * @param pattern the given pattern for the format. - * @param formatData the formatting symbols to be use. - * @param status Output param set to success/faulure code. - * @stable ICU 2.0 - */ - SimpleDateFormat(const UnicodeString& pattern, - const DateFormatSymbols& formatData, - UErrorCode& status); - - /** - * Copy constructor. - * @stable ICU 2.0 - */ - SimpleDateFormat(const SimpleDateFormat&); - - /** - * Assignment operator. - * @stable ICU 2.0 - */ - SimpleDateFormat& operator=(const SimpleDateFormat&); - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~SimpleDateFormat(); - - /** - * Clone this Format object polymorphically. The caller owns the result and - * should delete it when done. - * @return A copy of the object. - * @stable ICU 2.0 - */ - virtual Format* clone(void) const; - - /** - * Return true if the given Format objects are semantically equal. Objects - * of different subclasses are considered unequal. - * @param other the object to be compared with. - * @return true if the given Format objects are semantically equal. - * @stable ICU 2.0 - */ - virtual UBool operator==(const Format& other) const; - - - using DateFormat::format; - - /** - * Format a date or time, which is the standard millis since 24:00 GMT, Jan - * 1, 1970. Overrides DateFormat pure virtual method. - *

- * Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->> - * 1996.07.10 AD at 15:08:56 PDT - * - * @param cal Calendar set to the date and time to be formatted - * into a date/time string. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param pos The formatting position. On input: an alignment field, - * if desired. On output: the offsets of the alignment field. - * @return Reference to 'appendTo' parameter. - * @stable ICU 2.1 - */ - virtual UnicodeString& format( Calendar& cal, - UnicodeString& appendTo, - FieldPosition& pos) const; - - /** - * Format a date or time, which is the standard millis since 24:00 GMT, Jan - * 1, 1970. Overrides DateFormat pure virtual method. - *

- * Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->> - * 1996.07.10 AD at 15:08:56 PDT - * - * @param cal Calendar set to the date and time to be formatted - * into a date/time string. - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param posIter On return, can be used to iterate over positions - * of fields generated by this format call. Field values - * are defined in UDateFormatField. - * @param status Input/output param set to success/failure code. - * @return Reference to 'appendTo' parameter. - * @stable ICU 4.4 - */ - virtual UnicodeString& format( Calendar& cal, - UnicodeString& appendTo, - FieldPositionIterator* posIter, - UErrorCode& status) const; - - using DateFormat::parse; - - /** - * Parse a date/time string beginning at the given parse position. For - * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date - * that is equivalent to Date(837039928046). - *

- * By default, parsing is lenient: If the input is not in the form used by - * this object's format method but can still be parsed as a date, then the - * parse succeeds. Clients may insist on strict adherence to the format by - * calling setLenient(false). - * @see DateFormat::setLenient(boolean) - * - * @param text The date/time string to be parsed - * @param cal A Calendar set on input to the date and time to be used for - * missing values in the date/time string being parsed, and set - * on output to the parsed date/time. When the calendar type is - * different from the internal calendar held by this SimpleDateFormat - * instance, the internal calendar will be cloned to a work - * calendar set to the same milliseconds and time zone as the - * cal parameter, field values will be parsed based on the work - * calendar, then the result (milliseconds and time zone) will - * be set in this calendar. - * @param pos On input, the position at which to start parsing; on - * output, the position at which parsing terminated, or the - * start position if the parse failed. - * @stable ICU 2.1 - */ - virtual void parse( const UnicodeString& text, - Calendar& cal, - ParsePosition& pos) const; - - - /** - * Set the start UDate used to interpret two-digit year strings. - * When dates are parsed having 2-digit year strings, they are placed within - * a assumed range of 100 years starting on the two digit start date. For - * example, the string "24-Jan-17" may be in the year 1817, 1917, 2017, or - * some other year. SimpleDateFormat chooses a year so that the resultant - * date is on or after the two digit start date and within 100 years of the - * two digit start date. - *

- * By default, the two digit start date is set to 80 years before the current - * time at which a SimpleDateFormat object is created. - * @param d start UDate used to interpret two-digit year strings. - * @param status Filled in with U_ZERO_ERROR if the parse was successful, and with - * an error value if there was a parse error. - * @stable ICU 2.0 - */ - virtual void set2DigitYearStart(UDate d, UErrorCode& status); - - /** - * Get the start UDate used to interpret two-digit year strings. - * When dates are parsed having 2-digit year strings, they are placed within - * a assumed range of 100 years starting on the two digit start date. For - * example, the string "24-Jan-17" may be in the year 1817, 1917, 2017, or - * some other year. SimpleDateFormat chooses a year so that the resultant - * date is on or after the two digit start date and within 100 years of the - * two digit start date. - *

- * By default, the two digit start date is set to 80 years before the current - * time at which a SimpleDateFormat object is created. - * @param status Filled in with U_ZERO_ERROR if the parse was successful, and with - * an error value if there was a parse error. - * @stable ICU 2.0 - */ - UDate get2DigitYearStart(UErrorCode& status) const; - - /** - * Return a pattern string describing this date format. - * @param result Output param to receive the pattern. - * @return A reference to 'result'. - * @stable ICU 2.0 - */ - virtual UnicodeString& toPattern(UnicodeString& result) const; - - /** - * Return a localized pattern string describing this date format. - * In most cases, this will return the same thing as toPattern(), - * but a locale can specify characters to use in pattern descriptions - * in place of the ones described in this class's class documentation. - * (Presumably, letters that would be more mnemonic in that locale's - * language.) This function would produce a pattern using those - * letters. - *

- * Note: This implementation depends on DateFormatSymbols::getLocalPatternChars() - * to get localized format pattern characters. ICU does not include - * localized pattern character data, therefore, unless user sets localized - * pattern characters manually, this method returns the same result as - * toPattern(). - * - * @param result Receives the localized pattern. - * @param status Output param set to success/failure code on - * exit. If the pattern is invalid, this will be - * set to a failure result. - * @return A reference to 'result'. - * @stable ICU 2.0 - */ - virtual UnicodeString& toLocalizedPattern(UnicodeString& result, - UErrorCode& status) const; - - /** - * Apply the given unlocalized pattern string to this date format. - * (i.e., after this call, this formatter will format dates according to - * the new pattern) - * - * @param pattern The pattern to be applied. - * @stable ICU 2.0 - */ - virtual void applyPattern(const UnicodeString& pattern); - - /** - * Apply the given localized pattern string to this date format. - * (see toLocalizedPattern() for more information on localized patterns.) - * - * @param pattern The localized pattern to be applied. - * @param status Output param set to success/failure code on - * exit. If the pattern is invalid, this will be - * set to a failure result. - * @stable ICU 2.0 - */ - virtual void applyLocalizedPattern(const UnicodeString& pattern, - UErrorCode& status); - - /** - * Gets the date/time formatting symbols (this is an object carrying - * the various strings and other symbols used in formatting: e.g., month - * names and abbreviations, time zone names, AM/PM strings, etc.) - * @return a copy of the date-time formatting data associated - * with this date-time formatter. - * @stable ICU 2.0 - */ - virtual const DateFormatSymbols* getDateFormatSymbols(void) const; - - /** - * Set the date/time formatting symbols. The caller no longer owns the - * DateFormatSymbols object and should not delete it after making this call. - * @param newFormatSymbols the given date-time formatting symbols to copy. - * @stable ICU 2.0 - */ - virtual void adoptDateFormatSymbols(DateFormatSymbols* newFormatSymbols); - - /** - * Set the date/time formatting data. - * @param newFormatSymbols the given date-time formatting symbols to copy. - * @stable ICU 2.0 - */ - virtual void setDateFormatSymbols(const DateFormatSymbols& newFormatSymbols); - - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const; - - /** - * Set the calendar to be used by this date format. Initially, the default - * calendar for the specified or default locale is used. The caller should - * not delete the Calendar object after it is adopted by this call. - * Adopting a new calendar will change to the default symbols. - * - * @param calendarToAdopt Calendar object to be adopted. - * @stable ICU 2.0 - */ - virtual void adoptCalendar(Calendar* calendarToAdopt); - - /* Cannot use #ifndef U_HIDE_INTERNAL_API for the following methods since they are virtual */ - /** - * Sets the TimeZoneFormat to be used by this date/time formatter. - * The caller should not delete the TimeZoneFormat object after - * it is adopted by this call. - * @param timeZoneFormatToAdopt The TimeZoneFormat object to be adopted. - * @internal ICU 49 technology preview - */ - virtual void adoptTimeZoneFormat(TimeZoneFormat* timeZoneFormatToAdopt); - - /** - * Sets the TimeZoneFormat to be used by this date/time formatter. - * @param newTimeZoneFormat The TimeZoneFormat object to copy. - * @internal ICU 49 technology preview - */ - virtual void setTimeZoneFormat(const TimeZoneFormat& newTimeZoneFormat); - - /** - * Gets the time zone format object associated with this date/time formatter. - * @return the time zone format associated with this date/time formatter. - * @internal ICU 49 technology preview - */ - virtual const TimeZoneFormat* getTimeZoneFormat(void) const; - - /** - * Set a particular UDisplayContext value in the formatter, such as - * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. Note: For getContext, see - * DateFormat. - * @param value The UDisplayContext value to set. - * @param status Input/output status. If at entry this indicates a failure - * status, the function will do nothing; otherwise this will be - * updated with any new status from the function. - * @stable ICU 53 - */ - virtual void setContext(UDisplayContext value, UErrorCode& status); - - /** - * Overrides base class method and - * This method clears per field NumberFormat instances - * previously set by {@see adoptNumberFormat(const UnicodeString&, NumberFormat*, UErrorCode)} - * @param adoptNF the NumbeferFormat used - * @stable ICU 54 - */ - void adoptNumberFormat(NumberFormat *formatToAdopt); - - /** - * Allow the user to set the NumberFormat for several fields - * It can be a single field like: "y"(year) or "M"(month) - * It can be several field combined together: "yM"(year and month) - * Note: - * 1 symbol field is enough for multiple symbol field (so "y" will override "yy", "yyy") - * If the field is not numeric, then override has no effect (like "MMM" will use abbreviation, not numerical field) - * Per field NumberFormat can also be cleared in {@see DateFormat::setNumberFormat(const NumberFormat& newNumberFormat)} - * - * @param fields the fields to override(like y) - * @param adoptNF the NumbeferFormat used - * @param status Receives a status code, which will be U_ZERO_ERROR - * if the operation succeeds. - * @stable ICU 54 - */ - void adoptNumberFormat(const UnicodeString& fields, NumberFormat *formatToAdopt, UErrorCode &status); - - /** - * Get the numbering system to be used for a particular field. - * @param field The UDateFormatField to get - * @stable ICU 54 - */ - const NumberFormat * getNumberFormatForField(UChar field) const; - -#ifndef U_HIDE_INTERNAL_API - /** - * This is for ICU internal use only. Please do not use. - * Check whether the 'field' is smaller than all the fields covered in - * pattern, return TRUE if it is. The sequence of calendar field, - * from large to small is: ERA, YEAR, MONTH, DATE, AM_PM, HOUR, MINUTE,... - * @param field the calendar field need to check against - * @return TRUE if the 'field' is smaller than all the fields - * covered in pattern. FALSE otherwise. - * @internal ICU 4.0 - */ - UBool isFieldUnitIgnored(UCalendarDateFields field) const; - - - /** - * This is for ICU internal use only. Please do not use. - * Check whether the 'field' is smaller than all the fields covered in - * pattern, return TRUE if it is. The sequence of calendar field, - * from large to small is: ERA, YEAR, MONTH, DATE, AM_PM, HOUR, MINUTE,... - * @param pattern the pattern to check against - * @param field the calendar field need to check against - * @return TRUE if the 'field' is smaller than all the fields - * covered in pattern. FALSE otherwise. - * @internal ICU 4.0 - */ - static UBool isFieldUnitIgnored(const UnicodeString& pattern, - UCalendarDateFields field); - - /** - * This is for ICU internal use only. Please do not use. - * Get the locale of this simple date formatter. - * It is used in DateIntervalFormat. - * - * @return locale in this simple date formatter - * @internal ICU 4.0 - */ - const Locale& getSmpFmtLocale(void) const; -#endif /* U_HIDE_INTERNAL_API */ - -private: - friend class DateFormat; - - void initializeDefaultCentury(void); - - void initializeBooleanAttributes(void); - - SimpleDateFormat(); // default constructor not implemented - - /** - * Used by the DateFormat factory methods to construct a SimpleDateFormat. - * @param timeStyle the time style. - * @param dateStyle the date style. - * @param locale the given locale. - * @param status Output param set to success/failure code on - * exit. - */ - SimpleDateFormat(EStyle timeStyle, EStyle dateStyle, const Locale& locale, UErrorCode& status); - - /** - * Construct a SimpleDateFormat for the given locale. If no resource data - * is available, create an object of last resort, using hard-coded strings. - * This is an internal method, called by DateFormat. It should never fail. - * @param locale the given locale. - * @param status Output param set to success/failure code on - * exit. - */ - SimpleDateFormat(const Locale& locale, UErrorCode& status); // Use default pattern - - /** - * Hook called by format(... FieldPosition& ...) and format(...FieldPositionIterator&...) - */ - UnicodeString& _format(Calendar& cal, UnicodeString& appendTo, FieldPositionHandler& handler, UErrorCode& status) const; - - /** - * Called by format() to format a single field. - * - * @param appendTo Output parameter to receive result. - * Result is appended to existing contents. - * @param ch The format character we encountered in the pattern. - * @param count Number of characters in the current pattern symbol (e.g., - * "yyyy" in the pattern would result in a call to this function - * with ch equal to 'y' and count equal to 4) - * @param capitalizationContext Capitalization context for this date format. - * @param fieldNum Zero-based numbering of current field within the overall format. - * @param handler Records information about field positions. - * @param cal Calendar to use - * @param status Receives a status code, which will be U_ZERO_ERROR if the operation - * succeeds. - */ - void subFormat(UnicodeString &appendTo, - UChar ch, - int32_t count, - UDisplayContext capitalizationContext, - int32_t fieldNum, - FieldPositionHandler& handler, - Calendar& cal, - SimpleDateFormatMutableNFs &mutableNFs, - UErrorCode& status) const; // in case of illegal argument - - /** - * Used by subFormat() to format a numeric value. - * Appends to toAppendTo a string representation of "value" - * having a number of digits between "minDigits" and - * "maxDigits". Uses the DateFormat's NumberFormat. - * - * @param currentNumberFormat - * @param appendTo Output parameter to receive result. - * Formatted number is appended to existing contents. - * @param value Value to format. - * @param minDigits Minimum number of digits the result should have - * @param maxDigits Maximum number of digits the result should have - */ - void zeroPaddingNumber(NumberFormat *currentNumberFormat, - UnicodeString &appendTo, - int32_t value, - int32_t minDigits, - int32_t maxDigits) const; - - /** - * Return true if the given format character, occuring count - * times, represents a numeric field. - */ - static UBool isNumeric(UChar formatChar, int32_t count); - - /** - * Returns TRUE if the patternOffset is at the start of a numeric field. - */ - static UBool isAtNumericField(const UnicodeString &pattern, int32_t patternOffset); - - /** - * Returns TRUE if the patternOffset is right after a non-numeric field. - */ - static UBool isAfterNonNumericField(const UnicodeString &pattern, int32_t patternOffset); - - /** - * initializes fCalendar from parameters. Returns fCalendar as a convenience. - * @param adoptZone Zone to be adopted, or NULL for TimeZone::createDefault(). - * @param locale Locale of the calendar - * @param status Error code - * @return the newly constructed fCalendar - */ - Calendar *initializeCalendar(TimeZone* adoptZone, const Locale& locale, UErrorCode& status); - - /** - * Called by several of the constructors to load pattern data and formatting symbols - * out of a resource bundle and initialize the locale based on it. - * @param timeStyle The time style, as passed to DateFormat::createDateInstance(). - * @param dateStyle The date style, as passed to DateFormat::createTimeInstance(). - * @param locale The locale to load the patterns from. - * @param status Filled in with an error code if loading the data from the - * resources fails. - */ - void construct(EStyle timeStyle, EStyle dateStyle, const Locale& locale, UErrorCode& status); - - /** - * Called by construct() and the various constructors to set up the SimpleDateFormat's - * Calendar and NumberFormat objects. - * @param locale The locale for which we want a Calendar and a NumberFormat. - * @param status Filled in with an error code if creating either subobject fails. - */ - void initialize(const Locale& locale, UErrorCode& status); - - /** - * Private code-size reduction function used by subParse. - * @param text the time text being parsed. - * @param start where to start parsing. - * @param field the date field being parsed. - * @param stringArray the string array to parsed. - * @param stringArrayCount the size of the array. - * @param monthPattern pointer to leap month pattern, or NULL if none. - * @param cal a Calendar set to the date and time to be formatted - * into a date/time string. - * @return the new start position if matching succeeded; a negative number - * indicating matching failure, otherwise. - */ - int32_t matchString(const UnicodeString& text, int32_t start, UCalendarDateFields field, - const UnicodeString* stringArray, int32_t stringArrayCount, - const UnicodeString* monthPattern, Calendar& cal) const; - - /** - * Private code-size reduction function used by subParse. - * @param text the time text being parsed. - * @param start where to start parsing. - * @param field the date field being parsed. - * @param stringArray the string array to parsed. - * @param stringArrayCount the size of the array. - * @param cal a Calendar set to the date and time to be formatted - * into a date/time string. - * @return the new start position if matching succeeded; a negative number - * indicating matching failure, otherwise. - */ - int32_t matchQuarterString(const UnicodeString& text, int32_t start, UCalendarDateFields field, - const UnicodeString* stringArray, int32_t stringArrayCount, Calendar& cal) const; - - /** - * Used by subParse() to match localized day period strings. - */ - int32_t matchDayPeriodStrings(const UnicodeString& text, int32_t start, - const UnicodeString* stringArray, int32_t stringArrayCount, - int32_t &dayPeriod) const; - - /** - * Private function used by subParse to match literal pattern text. - * - * @param pattern the pattern string - * @param patternOffset the starting offset into the pattern text. On - * outupt will be set the offset of the first non-literal character in the pattern - * @param text the text being parsed - * @param textOffset the starting offset into the text. On output - * will be set to the offset of the character after the match - * @param whitespaceLenient TRUE if whitespace parse is lenient, FALSE otherwise. - * @param partialMatchLenient TRUE if partial match parse is lenient, FALSE otherwise. - * @param oldLeniency TRUE if old leniency control is lenient, FALSE otherwise. - * - * @return TRUE if the literal text could be matched, FALSE otherwise. - */ - static UBool matchLiterals(const UnicodeString &pattern, int32_t &patternOffset, - const UnicodeString &text, int32_t &textOffset, - UBool whitespaceLenient, UBool partialMatchLenient, UBool oldLeniency); - - /** - * Private member function that converts the parsed date strings into - * timeFields. Returns -start (for ParsePosition) if failed. - * @param text the time text to be parsed. - * @param start where to start parsing. - * @param ch the pattern character for the date field text to be parsed. - * @param count the count of a pattern character. - * @param obeyCount if true then the count is strictly obeyed. - * @param allowNegative - * @param ambiguousYear If true then the two-digit year == the default start year. - * @param saveHebrewMonth Used to hang onto month until year is known. - * @param cal a Calendar set to the date and time to be formatted - * into a date/time string. - * @param patLoc - * @param numericLeapMonthFormatter If non-null, used to parse numeric leap months. - * @param tzTimeType the type of parsed time zone - standard, daylight or unknown (output). - * This parameter can be NULL if caller does not need the information. - * @return the new start position if matching succeeded; a negative number - * indicating matching failure, otherwise. - */ - int32_t subParse(const UnicodeString& text, int32_t& start, UChar ch, int32_t count, - UBool obeyCount, UBool allowNegative, UBool ambiguousYear[], int32_t& saveHebrewMonth, Calendar& cal, - int32_t patLoc, MessageFormat * numericLeapMonthFormatter, UTimeZoneFormatTimeType *tzTimeType, SimpleDateFormatMutableNFs &mutableNFs, - int32_t *dayPeriod=NULL) const; - - void parseInt(const UnicodeString& text, - Formattable& number, - ParsePosition& pos, - UBool allowNegative, - NumberFormat *fmt) const; - - void parseInt(const UnicodeString& text, - Formattable& number, - int32_t maxDigits, - ParsePosition& pos, - UBool allowNegative, - NumberFormat *fmt) const; - - int32_t checkIntSuffix(const UnicodeString& text, int32_t start, - int32_t patLoc, UBool isNegative) const; - - /** - * Translate a pattern, mapping each character in the from string to the - * corresponding character in the to string. Return an error if the original - * pattern contains an unmapped character, or if a quote is unmatched. - * Quoted (single quotes only) material is not translated. - * @param originalPattern the original pattern. - * @param translatedPattern Output param to receive the translited pattern. - * @param from the characters to be translited from. - * @param to the characters to be translited to. - * @param status Receives a status code, which will be U_ZERO_ERROR - * if the operation succeeds. - */ - static void translatePattern(const UnicodeString& originalPattern, - UnicodeString& translatedPattern, - const UnicodeString& from, - const UnicodeString& to, - UErrorCode& status); - - /** - * Sets the starting date of the 100-year window that dates with 2-digit years - * are considered to fall within. - * @param startDate the start date - * @param status Receives a status code, which will be U_ZERO_ERROR - * if the operation succeeds. - */ - void parseAmbiguousDatesAsAfter(UDate startDate, UErrorCode& status); - - /** - * Return the length matched by the given affix, or -1 if none. - * Runs of white space in the affix, match runs of white space in - * the input. - * @param affix pattern string, taken as a literal - * @param input input text - * @param pos offset into input at which to begin matching - * @return length of input that matches, or -1 if match failure - */ - int32_t compareSimpleAffix(const UnicodeString& affix, - const UnicodeString& input, - int32_t pos) const; - - /** - * Skip over a run of zero or more Pattern_White_Space characters at - * pos in text. - */ - int32_t skipPatternWhiteSpace(const UnicodeString& text, int32_t pos) const; - - /** - * Skip over a run of zero or more isUWhiteSpace() characters at pos - * in text. - */ - int32_t skipUWhiteSpace(const UnicodeString& text, int32_t pos) const; - - /** - * Initialize NumberFormat instances used for numbering system overrides. - */ - void initNumberFormatters(const Locale &locale,UErrorCode &status); - - /** - * Parse the given override string and set up structures for number formats - */ - void processOverrideString(const Locale &locale, const UnicodeString &str, int8_t type, UErrorCode &status); - - /** - * Used to map pattern characters to Calendar field identifiers. - */ - static const UCalendarDateFields fgPatternIndexToCalendarField[]; - - /** - * Map index into pattern character string to DateFormat field number - */ - static const UDateFormatField fgPatternIndexToDateFormatField[]; - - /** - * Lazy TimeZoneFormat instantiation, semantically const - */ - TimeZoneFormat *tzFormat() const; - - const NumberFormat* getNumberFormatByIndex(UDateFormatField index) const; - - /** - * Used to map Calendar field to field level. - * The larger the level, the smaller the field unit. - * For example, UCAL_ERA level is 0, UCAL_YEAR level is 10, - * UCAL_MONTH level is 20. - */ - static const int32_t fgCalendarFieldToLevel[]; - - /** - * Map calendar field letter into calendar field level. - */ - static int32_t getLevelFromChar(UChar ch); - - /** - * Tell if a character can be used to define a field in a format string. - */ - static UBool isSyntaxChar(UChar ch); - - /** - * The formatting pattern for this formatter. - */ - UnicodeString fPattern; - - /** - * The numbering system override for dates. - */ - UnicodeString fDateOverride; - - /** - * The numbering system override for times. - */ - UnicodeString fTimeOverride; - - - /** - * The original locale used (for reloading symbols) - */ - Locale fLocale; - - /** - * A pointer to an object containing the strings to use in formatting (e.g., - * month and day names, AM and PM strings, time zone names, etc.) - */ - DateFormatSymbols* fSymbols; // Owned - - /** - * The time zone formatter - */ - TimeZoneFormat* fTimeZoneFormat; - - /** - * If dates have ambiguous years, we map them into the century starting - * at defaultCenturyStart, which may be any date. If defaultCenturyStart is - * set to SYSTEM_DEFAULT_CENTURY, which it is by default, then the system - * values are used. The instance values defaultCenturyStart and - * defaultCenturyStartYear are only used if explicitly set by the user - * through the API method parseAmbiguousDatesAsAfter(). - */ - UDate fDefaultCenturyStart; - - UBool fHasMinute; - UBool fHasSecond; - - /** - * Sets fHasMinutes and fHasSeconds. - */ - void parsePattern(); - - /** - * See documentation for defaultCenturyStart. - */ - /*transient*/ int32_t fDefaultCenturyStartYear; - - struct NSOverride : public UMemory { - const SharedNumberFormat *snf; - int32_t hash; - NSOverride *next; - void free(); - NSOverride() : snf(NULL), hash(0), next(NULL) { - } - ~NSOverride(); - }; - - /** - * The number format in use for each date field. NULL means fall back - * to fNumberFormat in DateFormat. - */ - const SharedNumberFormat **fSharedNumberFormatters; - - UBool fHaveDefaultCentury; - - BreakIterator* fCapitalizationBrkIter; -}; - -inline UDate -SimpleDateFormat::get2DigitYearStart(UErrorCode& /*status*/) const -{ - return fDefaultCenturyStart; -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // _SMPDTFMT -//eof diff --git a/win32/include/spidermonkey/unicode/sortkey.h b/win32/include/spidermonkey/unicode/sortkey.h deleted file mode 100755 index 814e29c4..00000000 --- a/win32/include/spidermonkey/unicode/sortkey.h +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ***************************************************************************** - * Copyright (C) 1996-2014, International Business Machines Corporation and others. - * All Rights Reserved. - ***************************************************************************** - * - * File sortkey.h - * - * Created by: Helena Shih - * - * Modification History: - * - * Date Name Description - * - * 6/20/97 helena Java class name change. - * 8/18/97 helena Added internal API documentation. - * 6/26/98 erm Changed to use byte arrays and memcmp. - ***************************************************************************** - */ - -#ifndef SORTKEY_H -#define SORTKEY_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Keys for comparing strings multiple times. - */ - -#if !UCONFIG_NO_COLLATION - -#include "unicode/uobject.h" -#include "unicode/unistr.h" -#include "unicode/coll.h" - -U_NAMESPACE_BEGIN - -/* forward declaration */ -class RuleBasedCollator; -class CollationKeyByteSink; - -/** - * - * Collation keys are generated by the Collator class. Use the CollationKey objects - * instead of Collator to compare strings multiple times. A CollationKey - * preprocesses the comparison information from the Collator object to - * make the comparison faster. If you are not going to comparing strings - * multiple times, then using the Collator object is generally faster, - * since it only processes as much of the string as needed to make a - * comparison. - *

For example (with strength == tertiary) - *

When comparing "Abernathy" to "Baggins-Smythworthy", Collator - * only needs to process a couple of characters, while a comparison - * with CollationKeys will process all of the characters. On the other hand, - * if you are doing a sort of a number of fields, it is much faster to use - * CollationKeys, since you will be comparing strings multiple times. - *

Typical use of CollationKeys are in databases, where you store a CollationKey - * in a hidden field, and use it for sorting or indexing. - * - *

Example of use: - *

- * \code
- *     UErrorCode success = U_ZERO_ERROR;
- *     Collator* myCollator = Collator::createInstance(success);
- *     CollationKey* keys = new CollationKey [3];
- *     myCollator->getCollationKey("Tom", keys[0], success );
- *     myCollator->getCollationKey("Dick", keys[1], success );
- *     myCollator->getCollationKey("Harry", keys[2], success );
- *
- *     // Inside body of sort routine, compare keys this way:
- *     CollationKey tmp;
- *     if(keys[0].compareTo( keys[1] ) > 0 ) {
- *         tmp = keys[0]; keys[0] = keys[1]; keys[1] = tmp;
- *     }
- *     //...
- * \endcode
- * 
- *

Because Collator::compare()'s algorithm is complex, it is faster to sort - * long lists of words by retrieving collation keys with Collator::getCollationKey(). - * You can then cache the collation keys and compare them using CollationKey::compareTo(). - *

- * Note: Collators with different Locale, - * CollationStrength and DecompositionMode settings will return different - * CollationKeys for the same set of strings. Locales have specific - * collation rules, and the way in which secondary and tertiary differences - * are taken into account, for example, will result in different CollationKeys - * for same strings. - *

- - * @see Collator - * @see RuleBasedCollator - * @version 1.3 12/18/96 - * @author Helena Shih - * @stable ICU 2.0 - */ -class U_I18N_API CollationKey : public UObject { -public: - /** - * This creates an empty collation key based on the null string. An empty - * collation key contains no sorting information. When comparing two empty - * collation keys, the result is Collator::EQUAL. Comparing empty collation key - * with non-empty collation key is always Collator::LESS. - * @stable ICU 2.0 - */ - CollationKey(); - - - /** - * Creates a collation key based on the collation key values. - * @param values the collation key values - * @param count number of collation key values, including trailing nulls. - * @stable ICU 2.0 - */ - CollationKey(const uint8_t* values, - int32_t count); - - /** - * Copy constructor. - * @param other the object to be copied. - * @stable ICU 2.0 - */ - CollationKey(const CollationKey& other); - - /** - * Sort key destructor. - * @stable ICU 2.0 - */ - virtual ~CollationKey(); - - /** - * Assignment operator - * @param other the object to be copied. - * @stable ICU 2.0 - */ - const CollationKey& operator=(const CollationKey& other); - - /** - * Compare if two collation keys are the same. - * @param source the collation key to compare to. - * @return Returns true if two collation keys are equal, false otherwise. - * @stable ICU 2.0 - */ - UBool operator==(const CollationKey& source) const; - - /** - * Compare if two collation keys are not the same. - * @param source the collation key to compare to. - * @return Returns TRUE if two collation keys are different, FALSE otherwise. - * @stable ICU 2.0 - */ - UBool operator!=(const CollationKey& source) const; - - - /** - * Test to see if the key is in an invalid state. The key will be in an - * invalid state if it couldn't allocate memory for some operation. - * @return Returns TRUE if the key is in an invalid, FALSE otherwise. - * @stable ICU 2.0 - */ - UBool isBogus(void) const; - - /** - * Returns a pointer to the collation key values. The storage is owned - * by the collation key and the pointer will become invalid if the key - * is deleted. - * @param count the output parameter of number of collation key values, - * including any trailing nulls. - * @return a pointer to the collation key values. - * @stable ICU 2.0 - */ - const uint8_t* getByteArray(int32_t& count) const; - -#ifdef U_USE_COLLATION_KEY_DEPRECATES - /** - * Extracts the collation key values into a new array. The caller owns - * this storage and should free it. - * @param count the output parameter of number of collation key values, - * including any trailing nulls. - * @obsolete ICU 2.6. Use getByteArray instead since this API will be removed in that release. - */ - uint8_t* toByteArray(int32_t& count) const; -#endif - -#ifndef U_HIDE_DEPRECATED_API - /** - * Convenience method which does a string(bit-wise) comparison of the - * two collation keys. - * @param target target collation key to be compared with - * @return Returns Collator::LESS if sourceKey < targetKey, - * Collator::GREATER if sourceKey > targetKey and Collator::EQUAL - * otherwise. - * @deprecated ICU 2.6 use the overload with error code - */ - Collator::EComparisonResult compareTo(const CollationKey& target) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Convenience method which does a string(bit-wise) comparison of the - * two collation keys. - * @param target target collation key to be compared with - * @param status error code - * @return Returns UCOL_LESS if sourceKey < targetKey, - * UCOL_GREATER if sourceKey > targetKey and UCOL_EQUAL - * otherwise. - * @stable ICU 2.6 - */ - UCollationResult compareTo(const CollationKey& target, UErrorCode &status) const; - - /** - * Creates an integer that is unique to the collation key. NOTE: this - * is not the same as String.hashCode. - *

Example of use: - *

-    * .    UErrorCode status = U_ZERO_ERROR;
-    * .    Collator *myCollation = Collator::createInstance(Locale::US, status);
-    * .    if (U_FAILURE(status)) return;
-    * .    CollationKey key1, key2;
-    * .    UErrorCode status1 = U_ZERO_ERROR, status2 = U_ZERO_ERROR;
-    * .    myCollation->getCollationKey("abc", key1, status1);
-    * .    if (U_FAILURE(status1)) { delete myCollation; return; }
-    * .    myCollation->getCollationKey("ABC", key2, status2);
-    * .    if (U_FAILURE(status2)) { delete myCollation; return; }
-    * .    // key1.hashCode() != key2.hashCode()
-    * 
- * @return the hash value based on the string's collation order. - * @see UnicodeString#hashCode - * @stable ICU 2.0 - */ - int32_t hashCode(void) const; - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - -private: - /** - * Replaces the current bytes buffer with a new one of newCapacity - * and copies length bytes from the old buffer to the new one. - * @return the new buffer, or NULL if the allocation failed - */ - uint8_t *reallocate(int32_t newCapacity, int32_t length); - /** - * Set a new length for a new sort key in the existing fBytes. - */ - void setLength(int32_t newLength); - - uint8_t *getBytes() { - return (fFlagAndLength >= 0) ? fUnion.fStackBuffer : fUnion.fFields.fBytes; - } - const uint8_t *getBytes() const { - return (fFlagAndLength >= 0) ? fUnion.fStackBuffer : fUnion.fFields.fBytes; - } - int32_t getCapacity() const { - return (fFlagAndLength >= 0) ? (int32_t)sizeof(fUnion) : fUnion.fFields.fCapacity; - } - int32_t getLength() const { return fFlagAndLength & 0x7fffffff; } - - /** - * Set the CollationKey to a "bogus" or invalid state - * @return this CollationKey - */ - CollationKey& setToBogus(void); - /** - * Resets this CollationKey to an empty state - * @return this CollationKey - */ - CollationKey& reset(void); - - /** - * Allow private access to RuleBasedCollator - */ - friend class RuleBasedCollator; - friend class CollationKeyByteSink; - - // Class fields. sizeof(CollationKey) is intended to be 48 bytes - // on a machine with 64-bit pointers. - // We use a union to maximize the size of the internal buffer, - // similar to UnicodeString but not as tight and complex. - - // (implicit) *vtable; - /** - * Sort key length and flag. - * Bit 31 is set if the buffer is heap-allocated. - * Bits 30..0 contain the sort key length. - */ - int32_t fFlagAndLength; - /** - * Unique hash value of this CollationKey. - * Special value 2 if the key is bogus. - */ - mutable int32_t fHashCode; - /** - * fUnion provides 32 bytes for the internal buffer or for - * pointer+capacity. - */ - union StackBufferOrFields { - /** fStackBuffer is used iff fFlagAndLength>=0, else fFields is used */ - uint8_t fStackBuffer[32]; - struct { - uint8_t *fBytes; - int32_t fCapacity; - } fFields; - } fUnion; -}; - -inline UBool -CollationKey::operator!=(const CollationKey& other) const -{ - return !(*this == other); -} - -inline UBool -CollationKey::isBogus() const -{ - return fHashCode == 2; // kBogusHashCode -} - -inline const uint8_t* -CollationKey::getByteArray(int32_t &count) const -{ - count = getLength(); - return getBytes(); -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_COLLATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/std_string.h b/win32/include/spidermonkey/unicode/std_string.h deleted file mode 100755 index 10e49ff7..00000000 --- a/win32/include/spidermonkey/unicode/std_string.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2009-2014, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: std_string.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2009feb19 -* created by: Markus W. Scherer -*/ - -#ifndef __STD_STRING_H__ -#define __STD_STRING_H__ - -/** - * \file - * \brief C++ API: Central ICU header for including the C++ standard <string> - * header and for related definitions. - */ - -#include "unicode/utypes.h" - -#if U_HAVE_STD_STRING - -#if defined(__GLIBCXX__) -namespace std { class type_info; } // WORKAROUND: http://llvm.org/bugs/show_bug.cgi?id=13364 -#endif -#include - -#endif // U_HAVE_STD_STRING - -#endif // __STD_STRING_H__ diff --git a/win32/include/spidermonkey/unicode/strenum.h b/win32/include/spidermonkey/unicode/strenum.h deleted file mode 100755 index 5a33f7f1..00000000 --- a/win32/include/spidermonkey/unicode/strenum.h +++ /dev/null @@ -1,278 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2002-2012, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -*/ - -#ifndef STRENUM_H -#define STRENUM_H - -#include "unicode/uobject.h" -#include "unicode/unistr.h" - -/** - * \file - * \brief C++ API: String Enumeration - */ - -U_NAMESPACE_BEGIN - -/** - * Base class for 'pure' C++ implementations of uenum api. Adds a - * method that returns the next UnicodeString since in C++ this can - * be a common storage format for strings. - * - *

The model is that the enumeration is over strings maintained by - * a 'service.' At any point, the service might change, invalidating - * the enumerator (though this is expected to be rare). The iterator - * returns an error if this has occurred. Lack of the error is no - * guarantee that the service didn't change immediately after the - * call, so the returned string still might not be 'valid' on - * subsequent use.

- * - *

Strings may take the form of const char*, const UChar*, or const - * UnicodeString*. The type you get is determine by the variant of - * 'next' that you call. In general the StringEnumeration is - * optimized for one of these types, but all StringEnumerations can - * return all types. Returned strings are each terminated with a NUL. - * Depending on the service data, they might also include embedded NUL - * characters, so API is provided to optionally return the true - * length, counting the embedded NULs but not counting the terminating - * NUL.

- * - *

The pointers returned by next, unext, and snext become invalid - * upon any subsequent call to the enumeration's destructor, next, - * unext, snext, or reset.

- * - * ICU 2.8 adds some default implementations and helper functions - * for subclasses. - * - * @stable ICU 2.4 - */ -class U_COMMON_API StringEnumeration : public UObject { -public: - /** - * Destructor. - * @stable ICU 2.4 - */ - virtual ~StringEnumeration(); - - /** - * Clone this object, an instance of a subclass of StringEnumeration. - * Clones can be used concurrently in multiple threads. - * If a subclass does not implement clone(), or if an error occurs, - * then NULL is returned. - * The clone functions in all subclasses return a base class pointer - * because some compilers do not support covariant (same-as-this) - * return types; cast to the appropriate subclass if necessary. - * The caller must delete the clone. - * - * @return a clone of this object - * - * @see getDynamicClassID - * @stable ICU 2.8 - */ - virtual StringEnumeration *clone() const; - - /** - *

Return the number of elements that the iterator traverses. If - * the iterator is out of sync with its service, status is set to - * U_ENUM_OUT_OF_SYNC_ERROR, and the return value is zero.

- * - *

The return value will not change except possibly as a result of - * a subsequent call to reset, or if the iterator becomes out of sync.

- * - *

This is a convenience function. It can end up being very - * expensive as all the items might have to be pre-fetched - * (depending on the storage format of the data being - * traversed).

- * - * @param status the error code. - * @return number of elements in the iterator. - * - * @stable ICU 2.4 */ - virtual int32_t count(UErrorCode& status) const = 0; - - /** - *

Returns the next element as a NUL-terminated char*. If there - * are no more elements, returns NULL. If the resultLength pointer - * is not NULL, the length of the string (not counting the - * terminating NUL) is returned at that address. If an error - * status is returned, the value at resultLength is undefined.

- * - *

The returned pointer is owned by this iterator and must not be - * deleted by the caller. The pointer is valid until the next call - * to next, unext, snext, reset, or the enumerator's destructor.

- * - *

If the iterator is out of sync with its service, status is set - * to U_ENUM_OUT_OF_SYNC_ERROR and NULL is returned.

- * - *

If the native service string is a UChar* string, it is - * converted to char* with the invariant converter. If the - * conversion fails (because a character cannot be converted) then - * status is set to U_INVARIANT_CONVERSION_ERROR and the return - * value is undefined (though not NULL).

- * - * Starting with ICU 2.8, the default implementation calls snext() - * and handles the conversion. - * Either next() or snext() must be implemented differently by a subclass. - * - * @param status the error code. - * @param resultLength a pointer to receive the length, can be NULL. - * @return a pointer to the string, or NULL. - * - * @stable ICU 2.4 - */ - virtual const char* next(int32_t *resultLength, UErrorCode& status); - - /** - *

Returns the next element as a NUL-terminated UChar*. If there - * are no more elements, returns NULL. If the resultLength pointer - * is not NULL, the length of the string (not counting the - * terminating NUL) is returned at that address. If an error - * status is returned, the value at resultLength is undefined.

- * - *

The returned pointer is owned by this iterator and must not be - * deleted by the caller. The pointer is valid until the next call - * to next, unext, snext, reset, or the enumerator's destructor.

- * - *

If the iterator is out of sync with its service, status is set - * to U_ENUM_OUT_OF_SYNC_ERROR and NULL is returned.

- * - * Starting with ICU 2.8, the default implementation calls snext() - * and handles the conversion. - * - * @param status the error code. - * @param resultLength a ponter to receive the length, can be NULL. - * @return a pointer to the string, or NULL. - * - * @stable ICU 2.4 - */ - virtual const UChar* unext(int32_t *resultLength, UErrorCode& status); - - /** - *

Returns the next element a UnicodeString*. If there are no - * more elements, returns NULL.

- * - *

The returned pointer is owned by this iterator and must not be - * deleted by the caller. The pointer is valid until the next call - * to next, unext, snext, reset, or the enumerator's destructor.

- * - *

If the iterator is out of sync with its service, status is set - * to U_ENUM_OUT_OF_SYNC_ERROR and NULL is returned.

- * - * Starting with ICU 2.8, the default implementation calls next() - * and handles the conversion. - * Either next() or snext() must be implemented differently by a subclass. - * - * @param status the error code. - * @return a pointer to the string, or NULL. - * - * @stable ICU 2.4 - */ - virtual const UnicodeString* snext(UErrorCode& status); - - /** - *

Resets the iterator. This re-establishes sync with the - * service and rewinds the iterator to start at the first - * element.

- * - *

Previous pointers returned by next, unext, or snext become - * invalid, and the value returned by count might change.

- * - * @param status the error code. - * - * @stable ICU 2.4 - */ - virtual void reset(UErrorCode& status) = 0; - - /** - * Compares this enumeration to other to check if both are equal - * - * @param that The other string enumeration to compare this object to - * @return TRUE if the enumerations are equal. FALSE if not. - * @stable ICU 3.6 - */ - virtual UBool operator==(const StringEnumeration& that)const; - /** - * Compares this enumeration to other to check if both are not equal - * - * @param that The other string enumeration to compare this object to - * @return TRUE if the enumerations are equal. FALSE if not. - * @stable ICU 3.6 - */ - virtual UBool operator!=(const StringEnumeration& that)const; - -protected: - /** - * UnicodeString field for use with default implementations and subclasses. - * @stable ICU 2.8 - */ - UnicodeString unistr; - /** - * char * default buffer for use with default implementations and subclasses. - * @stable ICU 2.8 - */ - char charsBuffer[32]; - /** - * char * buffer for use with default implementations and subclasses. - * Allocated in constructor and in ensureCharsCapacity(). - * @stable ICU 2.8 - */ - char *chars; - /** - * Capacity of chars, for use with default implementations and subclasses. - * @stable ICU 2.8 - */ - int32_t charsCapacity; - - /** - * Default constructor for use with default implementations and subclasses. - * @stable ICU 2.8 - */ - StringEnumeration(); - - /** - * Ensures that chars is at least as large as the requested capacity. - * For use with default implementations and subclasses. - * - * @param capacity Requested capacity. - * @param status ICU in/out error code. - * @stable ICU 2.8 - */ - void ensureCharsCapacity(int32_t capacity, UErrorCode &status); - - /** - * Converts s to Unicode and sets unistr to the result. - * For use with default implementations and subclasses, - * especially for implementations of snext() in terms of next(). - * This is provided with a helper function instead of a default implementation - * of snext() to avoid potential infinite loops between next() and snext(). - * - * For example: - * \code - * const UnicodeString* snext(UErrorCode& status) { - * int32_t resultLength=0; - * const char *s=next(&resultLength, status); - * return setChars(s, resultLength, status); - * } - * \endcode - * - * @param s String to be converted to Unicode. - * @param length Length of the string. - * @param status ICU in/out error code. - * @return A pointer to unistr. - * @stable ICU 2.8 - */ - UnicodeString *setChars(const char *s, int32_t length, UErrorCode &status); -}; - -U_NAMESPACE_END - -/* STRENUM_H */ -#endif diff --git a/win32/include/spidermonkey/unicode/stringpiece.h b/win32/include/spidermonkey/unicode/stringpiece.h deleted file mode 100755 index 5e40d4ac..00000000 --- a/win32/include/spidermonkey/unicode/stringpiece.h +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -// Copyright (C) 2009-2013, International Business Machines -// Corporation and others. All Rights Reserved. -// -// Copyright 2001 and onwards Google Inc. -// Author: Sanjay Ghemawat - -// This code is a contribution of Google code, and the style used here is -// a compromise between the original Google code and the ICU coding guidelines. -// For example, data types are ICU-ified (size_t,int->int32_t), -// and API comments doxygen-ified, but function names and behavior are -// as in the original, if possible. -// Assertion-style error handling, not available in ICU, was changed to -// parameter "pinning" similar to UnicodeString. -// -// In addition, this is only a partial port of the original Google code, -// limited to what was needed so far. The (nearly) complete original code -// is in the ICU svn repository at icuhtml/trunk/design/strings/contrib -// (see ICU ticket 6765, r25517). - -#ifndef __STRINGPIECE_H__ -#define __STRINGPIECE_H__ - -/** - * \file - * \brief C++ API: StringPiece: Read-only byte string wrapper class. - */ - -#include "unicode/utypes.h" -#include "unicode/uobject.h" -#include "unicode/std_string.h" - -// Arghh! I wish C++ literals were "string". - -U_NAMESPACE_BEGIN - -/** - * A string-like object that points to a sized piece of memory. - * - * We provide non-explicit singleton constructors so users can pass - * in a "const char*" or a "string" wherever a "StringPiece" is - * expected. - * - * Functions or methods may use StringPiece parameters to accept either a - * "const char*" or a "string" value that will be implicitly converted to a - * StringPiece. - * - * Systematic usage of StringPiece is encouraged as it will reduce unnecessary - * conversions from "const char*" to "string" and back again. - * - * @stable ICU 4.2 - */ -class U_COMMON_API StringPiece : public UMemory { - private: - const char* ptr_; - int32_t length_; - - public: - /** - * Default constructor, creates an empty StringPiece. - * @stable ICU 4.2 - */ - StringPiece() : ptr_(NULL), length_(0) { } - /** - * Constructs from a NUL-terminated const char * pointer. - * @param str a NUL-terminated const char * pointer - * @stable ICU 4.2 - */ - StringPiece(const char* str); -#if U_HAVE_STD_STRING - /** - * Constructs from a std::string. - * @stable ICU 4.2 - */ - StringPiece(const std::string& str) - : ptr_(str.data()), length_(static_cast(str.size())) { } -#endif - /** - * Constructs from a const char * pointer and a specified length. - * @param offset a const char * pointer (need not be terminated) - * @param len the length of the string; must be non-negative - * @stable ICU 4.2 - */ - StringPiece(const char* offset, int32_t len) : ptr_(offset), length_(len) { } - /** - * Substring of another StringPiece. - * @param x the other StringPiece - * @param pos start position in x; must be non-negative and <= x.length(). - * @stable ICU 4.2 - */ - StringPiece(const StringPiece& x, int32_t pos); - /** - * Substring of another StringPiece. - * @param x the other StringPiece - * @param pos start position in x; must be non-negative and <= x.length(). - * @param len length of the substring; - * must be non-negative and will be pinned to at most x.length() - pos. - * @stable ICU 4.2 - */ - StringPiece(const StringPiece& x, int32_t pos, int32_t len); - - /** - * Returns the string pointer. May be NULL if it is empty. - * - * data() may return a pointer to a buffer with embedded NULs, and the - * returned buffer may or may not be null terminated. Therefore it is - * typically a mistake to pass data() to a routine that expects a NUL - * terminated string. - * @return the string pointer - * @stable ICU 4.2 - */ - const char* data() const { return ptr_; } - /** - * Returns the string length. Same as length(). - * @return the string length - * @stable ICU 4.2 - */ - int32_t size() const { return length_; } - /** - * Returns the string length. Same as size(). - * @return the string length - * @stable ICU 4.2 - */ - int32_t length() const { return length_; } - /** - * Returns whether the string is empty. - * @return TRUE if the string is empty - * @stable ICU 4.2 - */ - UBool empty() const { return length_ == 0; } - - /** - * Sets to an empty string. - * @stable ICU 4.2 - */ - void clear() { ptr_ = NULL; length_ = 0; } - - /** - * Reset the stringpiece to refer to new data. - * @param xdata pointer the new string data. Need not be nul terminated. - * @param len the length of the new data - * @stable ICU 4.8 - */ - void set(const char* xdata, int32_t len) { ptr_ = xdata; length_ = len; } - - /** - * Reset the stringpiece to refer to new data. - * @param str a pointer to a NUL-terminated string. - * @stable ICU 4.8 - */ - void set(const char* str); - - /** - * Removes the first n string units. - * @param n prefix length, must be non-negative and <=length() - * @stable ICU 4.2 - */ - void remove_prefix(int32_t n) { - if (n >= 0) { - if (n > length_) { - n = length_; - } - ptr_ += n; - length_ -= n; - } - } - - /** - * Removes the last n string units. - * @param n suffix length, must be non-negative and <=length() - * @stable ICU 4.2 - */ - void remove_suffix(int32_t n) { - if (n >= 0) { - if (n <= length_) { - length_ -= n; - } else { - length_ = 0; - } - } - } - - /** - * Maximum integer, used as a default value for substring methods. - * @stable ICU 4.2 - */ - static const int32_t npos; // = 0x7fffffff; - - /** - * Returns a substring of this StringPiece. - * @param pos start position; must be non-negative and <= length(). - * @param len length of the substring; - * must be non-negative and will be pinned to at most length() - pos. - * @return the substring StringPiece - * @stable ICU 4.2 - */ - StringPiece substr(int32_t pos, int32_t len = npos) const { - return StringPiece(*this, pos, len); - } -}; - -/** - * Global operator == for StringPiece - * @param x The first StringPiece to compare. - * @param y The second StringPiece to compare. - * @return TRUE if the string data is equal - * @stable ICU 4.8 - */ -U_EXPORT UBool U_EXPORT2 -operator==(const StringPiece& x, const StringPiece& y); - -/** - * Global operator != for StringPiece - * @param x The first StringPiece to compare. - * @param y The second StringPiece to compare. - * @return TRUE if the string data is not equal - * @stable ICU 4.8 - */ -inline UBool operator!=(const StringPiece& x, const StringPiece& y) { - return !(x == y); -} - -U_NAMESPACE_END - -#endif // __STRINGPIECE_H__ diff --git a/win32/include/spidermonkey/unicode/stringtriebuilder.h b/win32/include/spidermonkey/unicode/stringtriebuilder.h deleted file mode 100755 index 95cd841a..00000000 --- a/win32/include/spidermonkey/unicode/stringtriebuilder.h +++ /dev/null @@ -1,414 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2010-2012,2014, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* file name: stringtriebuilder.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2010dec24 -* created by: Markus W. Scherer -*/ - -#ifndef __STRINGTRIEBUILDER_H__ -#define __STRINGTRIEBUILDER_H__ - -#include "unicode/utypes.h" -#include "unicode/uobject.h" - -/** - * \file - * \brief C++ API: Builder API for trie builders - */ - -// Forward declaration. -struct UHashtable; -typedef struct UHashtable UHashtable; - -/** - * Build options for BytesTrieBuilder and CharsTrieBuilder. - * @stable ICU 4.8 - */ -enum UStringTrieBuildOption { - /** - * Builds a trie quickly. - * @stable ICU 4.8 - */ - USTRINGTRIE_BUILD_FAST, - /** - * Builds a trie more slowly, attempting to generate - * a shorter but equivalent serialization. - * This build option also uses more memory. - * - * This option can be effective when many integer values are the same - * and string/byte sequence suffixes can be shared. - * Runtime speed is not expected to improve. - * @stable ICU 4.8 - */ - USTRINGTRIE_BUILD_SMALL -}; - -U_NAMESPACE_BEGIN - -/** - * Base class for string trie builder classes. - * - * This class is not intended for public subclassing. - * @stable ICU 4.8 - */ -class U_COMMON_API StringTrieBuilder : public UObject { -public: -#ifndef U_HIDE_INTERNAL_API - /** @internal */ - static UBool hashNode(const void *node); - /** @internal */ - static UBool equalNodes(const void *left, const void *right); -#endif /* U_HIDE_INTERNAL_API */ - -protected: - // Do not enclose the protected default constructor with #ifndef U_HIDE_INTERNAL_API - // or else the compiler will create a public default constructor. - /** @internal */ - StringTrieBuilder(); - /** @internal */ - virtual ~StringTrieBuilder(); - -#ifndef U_HIDE_INTERNAL_API - /** @internal */ - void createCompactBuilder(int32_t sizeGuess, UErrorCode &errorCode); - /** @internal */ - void deleteCompactBuilder(); - - /** @internal */ - void build(UStringTrieBuildOption buildOption, int32_t elementsLength, UErrorCode &errorCode); - - /** @internal */ - int32_t writeNode(int32_t start, int32_t limit, int32_t unitIndex); - /** @internal */ - int32_t writeBranchSubNode(int32_t start, int32_t limit, int32_t unitIndex, int32_t length); -#endif /* U_HIDE_INTERNAL_API */ - - class Node; - -#ifndef U_HIDE_INTERNAL_API - /** @internal */ - Node *makeNode(int32_t start, int32_t limit, int32_t unitIndex, UErrorCode &errorCode); - /** @internal */ - Node *makeBranchSubNode(int32_t start, int32_t limit, int32_t unitIndex, - int32_t length, UErrorCode &errorCode); -#endif /* U_HIDE_INTERNAL_API */ - - /** @internal */ - virtual int32_t getElementStringLength(int32_t i) const = 0; - /** @internal */ - virtual UChar getElementUnit(int32_t i, int32_t unitIndex) const = 0; - /** @internal */ - virtual int32_t getElementValue(int32_t i) const = 0; - - // Finds the first unit index after this one where - // the first and last element have different units again. - /** @internal */ - virtual int32_t getLimitOfLinearMatch(int32_t first, int32_t last, int32_t unitIndex) const = 0; - - // Number of different units at unitIndex. - /** @internal */ - virtual int32_t countElementUnits(int32_t start, int32_t limit, int32_t unitIndex) const = 0; - /** @internal */ - virtual int32_t skipElementsBySomeUnits(int32_t i, int32_t unitIndex, int32_t count) const = 0; - /** @internal */ - virtual int32_t indexOfElementWithNextUnit(int32_t i, int32_t unitIndex, UChar unit) const = 0; - - /** @internal */ - virtual UBool matchNodesCanHaveValues() const = 0; - - /** @internal */ - virtual int32_t getMaxBranchLinearSubNodeLength() const = 0; - /** @internal */ - virtual int32_t getMinLinearMatch() const = 0; - /** @internal */ - virtual int32_t getMaxLinearMatchLength() const = 0; - -#ifndef U_HIDE_INTERNAL_API - // max(BytesTrie::kMaxBranchLinearSubNodeLength, UCharsTrie::kMaxBranchLinearSubNodeLength). - /** @internal */ - static const int32_t kMaxBranchLinearSubNodeLength=5; - - // Maximum number of nested split-branch levels for a branch on all 2^16 possible UChar units. - // log2(2^16/kMaxBranchLinearSubNodeLength) rounded up. - /** @internal */ - static const int32_t kMaxSplitBranchLevels=14; - - /** - * Makes sure that there is only one unique node registered that is - * equivalent to newNode. - * @param newNode Input node. The builder takes ownership. - * @param errorCode ICU in/out UErrorCode. - Set to U_MEMORY_ALLOCATION_ERROR if it was success but newNode==NULL. - * @return newNode if it is the first of its kind, or - * an equivalent node if newNode is a duplicate. - * @internal - */ - Node *registerNode(Node *newNode, UErrorCode &errorCode); - /** - * Makes sure that there is only one unique FinalValueNode registered - * with this value. - * Avoids creating a node if the value is a duplicate. - * @param value A final value. - * @param errorCode ICU in/out UErrorCode. - Set to U_MEMORY_ALLOCATION_ERROR if it was success but newNode==NULL. - * @return A FinalValueNode with the given value. - * @internal - */ - Node *registerFinalValue(int32_t value, UErrorCode &errorCode); -#endif /* U_HIDE_INTERNAL_API */ - - /* - * C++ note: - * registerNode() and registerFinalValue() take ownership of their input nodes, - * and only return owned nodes. - * If they see a failure UErrorCode, they will delete the input node. - * If they get a NULL pointer, they will record a U_MEMORY_ALLOCATION_ERROR. - * If there is a failure, they return NULL. - * - * NULL Node pointers can be safely passed into other Nodes because - * they call the static Node::hashCode() which checks for a NULL pointer first. - * - * Therefore, as long as builder functions register a new node, - * they need to check for failures only before explicitly dereferencing - * a Node pointer, or before setting a new UErrorCode. - */ - - // Hash set of nodes, maps from nodes to integer 1. - /** @internal */ - UHashtable *nodes; - - // Do not conditionalize the following with #ifndef U_HIDE_INTERNAL_API, - // it is needed for layout of other objects. - /** @internal */ - class Node : public UObject { - public: - Node(int32_t initialHash) : hash(initialHash), offset(0) {} - inline int32_t hashCode() const { return hash; } - // Handles node==NULL. - static inline int32_t hashCode(const Node *node) { return node==NULL ? 0 : node->hashCode(); } - // Base class operator==() compares the actual class types. - virtual UBool operator==(const Node &other) const; - inline UBool operator!=(const Node &other) const { return !operator==(other); } - /** - * Traverses the Node graph and numbers branch edges, with rightmost edges first. - * This is to avoid writing a duplicate node twice. - * - * Branch nodes in this trie data structure are not symmetric. - * Most branch edges "jump" to other nodes but the rightmost branch edges - * just continue without a jump. - * Therefore, write() must write the rightmost branch edge last - * (trie units are written backwards), and must write it at that point even if - * it is a duplicate of a node previously written elsewhere. - * - * This function visits and marks right branch edges first. - * Edges are numbered with increasingly negative values because we share the - * offset field which gets positive values when nodes are written. - * A branch edge also remembers the first number for any of its edges. - * - * When a further-left branch edge has a number in the range of the rightmost - * edge's numbers, then it will be written as part of the required right edge - * and we can avoid writing it first. - * - * After root.markRightEdgesFirst(-1) the offsets of all nodes are negative - * edge numbers. - * - * @param edgeNumber The first edge number for this node and its sub-nodes. - * @return An edge number that is at least the maximum-negative - * of the input edge number and the numbers of this node and all of its sub-nodes. - */ - virtual int32_t markRightEdgesFirst(int32_t edgeNumber); - // write() must set the offset to a positive value. - virtual void write(StringTrieBuilder &builder) = 0; - // See markRightEdgesFirst. - inline void writeUnlessInsideRightEdge(int32_t firstRight, int32_t lastRight, - StringTrieBuilder &builder) { - // Note: Edge numbers are negative, lastRight<=firstRight. - // If offset>0 then this node and its sub-nodes have been written already - // and we need not write them again. - // If this node is part of the unwritten right branch edge, - // then we wait until that is written. - if(offset<0 && (offsetStringSearch is a SearchIterator that provides - * language-sensitive text searching based on the comparison rules defined - * in a {@link RuleBasedCollator} object. - * StringSearch ensures that language eccentricity can be - * handled, e.g. for the German collator, characters ß and SS will be matched - * if case is chosen to be ignored. - * See the - * "ICU Collation Design Document" for more information. - *

- * There are 2 match options for selection:
- * Let S' be the sub-string of a text string S between the offsets start and - * end [start, end]. - *
- * A pattern string P matches a text string S at the offsets [start, end] - * if - *

 
- * option 1. Some canonical equivalent of P matches some canonical equivalent
- *           of S'
- * option 2. P matches S' and if P starts or ends with a combining mark,
- *           there exists no non-ignorable combining mark before or after S?
- *           in S respectively.
- * 
- * Option 2. will be the default. - *

- * This search has APIs similar to that of other text iteration mechanisms - * such as the break iterators in BreakIterator. Using these - * APIs, it is easy to scan through text looking for all occurrences of - * a given pattern. This search iterator allows changing of direction by - * calling a reset followed by a next or previous. - * Though a direction change can occur without calling reset first, - * this operation comes with some speed penalty. - * Match results in the forward direction will match the result matches in - * the backwards direction in the reverse order - *

- * SearchIterator provides APIs to specify the starting position - * within the text string to be searched, e.g. setOffset, - * preceding and following. Since the - * starting position will be set as it is specified, please take note that - * there are some danger points which the search may render incorrect - * results: - *

    - *
  • The midst of a substring that requires normalization. - *
  • If the following match is to be found, the position should not be the - * second character which requires to be swapped with the preceding - * character. Vice versa, if the preceding match is to be found, - * position to search from should not be the first character which - * requires to be swapped with the next character. E.g certain Thai and - * Lao characters require swapping. - *
  • If a following pattern match is to be found, any position within a - * contracting sequence except the first will fail. Vice versa if a - * preceding pattern match is to be found, a invalid starting point - * would be any character within a contracting sequence except the last. - *
- *

- * A BreakIterator can be used if only matches at logical breaks are desired. - * Using a BreakIterator will only give you results that exactly matches the - * boundaries given by the breakiterator. For instance the pattern "e" will - * not be found in the string "\u00e9" if a character break iterator is used. - *

- * Options are provided to handle overlapping matches. - * E.g. In English, overlapping matches produces the result 0 and 2 - * for the pattern "abab" in the text "ababab", where else mutually - * exclusive matches only produce the result of 0. - *

- * Though collator attributes will be taken into consideration while - * performing matches, there are no APIs here for setting and getting the - * attributes. These attributes can be set by getting the collator - * from getCollator and using the APIs in coll.h. - * Lastly to update StringSearch to the new collator attributes, - * reset has to be called. - *

- * Restriction:
- * Currently there are no composite characters that consists of a - * character with combining class > 0 before a character with combining - * class == 0. However, if such a character exists in the future, - * StringSearch does not guarantee the results for option 1. - *

- * Consult the SearchIterator documentation for information on - * and examples of how to use instances of this class to implement text - * searching. - *


- * UnicodeString target("The quick brown fox jumps over the lazy dog.");
- * UnicodeString pattern("fox");
- *
- * UErrorCode      error = U_ZERO_ERROR;
- * StringSearch iter(pattern, target, Locale::getUS(), NULL, status);
- * for (int pos = iter.first(error);
- *      pos != USEARCH_DONE; 
- *      pos = iter.next(error))
- * {
- *     printf("Found match at %d pos, length is %d\n", pos, 
- *                                             iter.getMatchLength());
- * }
- * 
- *

- * Note, StringSearch is not to be subclassed. - *

- * @see SearchIterator - * @see RuleBasedCollator - * @since ICU 2.0 - */ - -class U_I18N_API StringSearch U_FINAL : public SearchIterator -{ -public: - - // public constructors and destructors -------------------------------- - - /** - * Creating a StringSearch instance using the argument locale - * language rule set. A collator will be created in the process, which - * will be owned by this instance and will be deleted during - * destruction - * @param pattern The text for which this object will search. - * @param text The text in which to search for the pattern. - * @param locale A locale which defines the language-sensitive - * comparison rules used to determine whether text in the - * pattern and target matches. - * @param breakiter A BreakIterator object used to constrain - * the matches that are found. Matches whose start and end - * indices in the target text are not boundaries as - * determined by the BreakIterator are - * ignored. If this behavior is not desired, - * NULL can be passed in instead. - * @param status for errors if any. If pattern or text is NULL, or if - * either the length of pattern or text is 0 then an - * U_ILLEGAL_ARGUMENT_ERROR is returned. - * @stable ICU 2.0 - */ - StringSearch(const UnicodeString &pattern, const UnicodeString &text, - const Locale &locale, - BreakIterator *breakiter, - UErrorCode &status); - - /** - * Creating a StringSearch instance using the argument collator - * language rule set. Note, user retains the ownership of this collator, - * it does not get destroyed during this instance's destruction. - * @param pattern The text for which this object will search. - * @param text The text in which to search for the pattern. - * @param coll A RuleBasedCollator object which defines - * the language-sensitive comparison rules used to - * determine whether text in the pattern and target - * matches. User is responsible for the clearing of this - * object. - * @param breakiter A BreakIterator object used to constrain - * the matches that are found. Matches whose start and end - * indices in the target text are not boundaries as - * determined by the BreakIterator are - * ignored. If this behavior is not desired, - * NULL can be passed in instead. - * @param status for errors if any. If either the length of pattern or - * text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned. - * @stable ICU 2.0 - */ - StringSearch(const UnicodeString &pattern, - const UnicodeString &text, - RuleBasedCollator *coll, - BreakIterator *breakiter, - UErrorCode &status); - - /** - * Creating a StringSearch instance using the argument locale - * language rule set. A collator will be created in the process, which - * will be owned by this instance and will be deleted during - * destruction - *

- * Note: No parsing of the text within the CharacterIterator - * will be done during searching for this version. The block of text - * in CharacterIterator will be used as it is. - * @param pattern The text for which this object will search. - * @param text The text iterator in which to search for the pattern. - * @param locale A locale which defines the language-sensitive - * comparison rules used to determine whether text in the - * pattern and target matches. User is responsible for - * the clearing of this object. - * @param breakiter A BreakIterator object used to constrain - * the matches that are found. Matches whose start and end - * indices in the target text are not boundaries as - * determined by the BreakIterator are - * ignored. If this behavior is not desired, - * NULL can be passed in instead. - * @param status for errors if any. If either the length of pattern or - * text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned. - * @stable ICU 2.0 - */ - StringSearch(const UnicodeString &pattern, CharacterIterator &text, - const Locale &locale, - BreakIterator *breakiter, - UErrorCode &status); - - /** - * Creating a StringSearch instance using the argument collator - * language rule set. Note, user retains the ownership of this collator, - * it does not get destroyed during this instance's destruction. - *

- * Note: No parsing of the text within the CharacterIterator - * will be done during searching for this version. The block of text - * in CharacterIterator will be used as it is. - * @param pattern The text for which this object will search. - * @param text The text in which to search for the pattern. - * @param coll A RuleBasedCollator object which defines - * the language-sensitive comparison rules used to - * determine whether text in the pattern and target - * matches. User is responsible for the clearing of this - * object. - * @param breakiter A BreakIterator object used to constrain - * the matches that are found. Matches whose start and end - * indices in the target text are not boundaries as - * determined by the BreakIterator are - * ignored. If this behavior is not desired, - * NULL can be passed in instead. - * @param status for errors if any. If either the length of pattern or - * text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned. - * @stable ICU 2.0 - */ - StringSearch(const UnicodeString &pattern, CharacterIterator &text, - RuleBasedCollator *coll, - BreakIterator *breakiter, - UErrorCode &status); - - /** - * Copy constructor that creates a StringSearch instance with the same - * behavior, and iterating over the same text. - * @param that StringSearch instance to be copied. - * @stable ICU 2.0 - */ - StringSearch(const StringSearch &that); - - /** - * Destructor. Cleans up the search iterator data struct. - * If a collator is created in the constructor, it will be destroyed here. - * @stable ICU 2.0 - */ - virtual ~StringSearch(void); - - /** - * Clone this object. - * Clones can be used concurrently in multiple threads. - * If an error occurs, then NULL is returned. - * The caller must delete the clone. - * - * @return a clone of this object - * - * @see getDynamicClassID - * @stable ICU 2.8 - */ - StringSearch *clone() const; - - // operator overloading --------------------------------------------- - - /** - * Assignment operator. Sets this iterator to have the same behavior, - * and iterate over the same text, as the one passed in. - * @param that instance to be copied. - * @stable ICU 2.0 - */ - StringSearch & operator=(const StringSearch &that); - - /** - * Equality operator. - * @param that instance to be compared. - * @return TRUE if both instances have the same attributes, - * breakiterators, collators and iterate over the same text - * while looking for the same pattern. - * @stable ICU 2.0 - */ - virtual UBool operator==(const SearchIterator &that) const; - - // public get and set methods ---------------------------------------- - - /** - * Sets the index to point to the given position, and clears any state - * that's affected. - *

- * This method takes the argument index and sets the position in the text - * string accordingly without checking if the index is pointing to a - * valid starting point to begin searching. - * @param position within the text to be set. If position is less - * than or greater than the text range for searching, - * an U_INDEX_OUTOFBOUNDS_ERROR will be returned - * @param status for errors if it occurs - * @stable ICU 2.0 - */ - virtual void setOffset(int32_t position, UErrorCode &status); - - /** - * Return the current index in the text being searched. - * If the iteration has gone past the end of the text - * (or past the beginning for a backwards search), USEARCH_DONE - * is returned. - * @return current index in the text being searched. - * @stable ICU 2.0 - */ - virtual int32_t getOffset(void) const; - - /** - * Set the target text to be searched. - * Text iteration will hence begin at the start of the text string. - * This method is - * useful if you want to re-use an iterator to search for the same - * pattern within a different body of text. - * @param text text string to be searched - * @param status for errors if any. If the text length is 0 then an - * U_ILLEGAL_ARGUMENT_ERROR is returned. - * @stable ICU 2.0 - */ - virtual void setText(const UnicodeString &text, UErrorCode &status); - - /** - * Set the target text to be searched. - * Text iteration will hence begin at the start of the text string. - * This method is - * useful if you want to re-use an iterator to search for the same - * pattern within a different body of text. - * Note: No parsing of the text within the CharacterIterator - * will be done during searching for this version. The block of text - * in CharacterIterator will be used as it is. - * @param text text string to be searched - * @param status for errors if any. If the text length is 0 then an - * U_ILLEGAL_ARGUMENT_ERROR is returned. - * @stable ICU 2.0 - */ - virtual void setText(CharacterIterator &text, UErrorCode &status); - - /** - * Gets the collator used for the language rules. - *

- * Caller may modify but must not delete the RuleBasedCollator! - * Modifications to this collator will affect the original collator passed in to - * the StringSearch> constructor or to setCollator, if any. - * @return collator used for string search - * @stable ICU 2.0 - */ - RuleBasedCollator * getCollator() const; - - /** - * Sets the collator used for the language rules. User retains the - * ownership of this collator, thus the responsibility of deletion lies - * with the user. The iterator's position will not be changed by this method. - * @param coll collator - * @param status for errors if any - * @stable ICU 2.0 - */ - void setCollator(RuleBasedCollator *coll, UErrorCode &status); - - /** - * Sets the pattern used for matching. - * The iterator's position will not be changed by this method. - * @param pattern search pattern to be found - * @param status for errors if any. If the pattern length is 0 then an - * U_ILLEGAL_ARGUMENT_ERROR is returned. - * @stable ICU 2.0 - */ - void setPattern(const UnicodeString &pattern, UErrorCode &status); - - /** - * Gets the search pattern. - * @return pattern used for matching - * @stable ICU 2.0 - */ - const UnicodeString & getPattern() const; - - // public methods ---------------------------------------------------- - - /** - * Reset the iteration. - * Search will begin at the start of the text string if a forward - * iteration is initiated before a backwards iteration. Otherwise if - * a backwards iteration is initiated before a forwards iteration, the - * search will begin at the end of the text string. - * @stable ICU 2.0 - */ - virtual void reset(); - - /** - * Returns a copy of StringSearch with the same behavior, and - * iterating over the same text, as this one. Note that all data will be - * replicated, except for the user-specified collator and the - * breakiterator. - * @return cloned object - * @stable ICU 2.0 - */ - virtual SearchIterator * safeClone(void) const; - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - -protected: - - // protected method ------------------------------------------------- - - /** - * Search forward for matching text, starting at a given location. - * Clients should not call this method directly; instead they should - * call {@link SearchIterator#next }. - *

- * If a match is found, this method returns the index at which the match - * starts and calls {@link SearchIterator#setMatchLength } with the number - * of characters in the target text that make up the match. If no match - * is found, the method returns USEARCH_DONE. - *

- * The StringSearch is adjusted so that its current index - * (as returned by {@link #getOffset }) is the match position if one was - * found. - * If a match is not found, USEARCH_DONE will be returned and - * the StringSearch will be adjusted to the index USEARCH_DONE. - * @param position The index in the target text at which the search - * starts - * @param status for errors if any occurs - * @return The index at which the matched text in the target starts, or - * USEARCH_DONE if no match was found. - * @stable ICU 2.0 - */ - virtual int32_t handleNext(int32_t position, UErrorCode &status); - - /** - * Search backward for matching text, starting at a given location. - * Clients should not call this method directly; instead they should call - * SearchIterator.previous(), which this method overrides. - *

- * If a match is found, this method returns the index at which the match - * starts and calls {@link SearchIterator#setMatchLength } with the number - * of characters in the target text that make up the match. If no match - * is found, the method returns USEARCH_DONE. - *

- * The StringSearch is adjusted so that its current index - * (as returned by {@link #getOffset }) is the match position if one was - * found. - * If a match is not found, USEARCH_DONE will be returned and - * the StringSearch will be adjusted to the index USEARCH_DONE. - * @param position The index in the target text at which the search - * starts. - * @param status for errors if any occurs - * @return The index at which the matched text in the target starts, or - * USEARCH_DONE if no match was found. - * @stable ICU 2.0 - */ - virtual int32_t handlePrev(int32_t position, UErrorCode &status); - -private : - StringSearch(); // default constructor not implemented - - // private data members ---------------------------------------------- - - /** - * Pattern text - * @stable ICU 2.0 - */ - UnicodeString m_pattern_; - /** - * String search struct data - * @stable ICU 2.0 - */ - UStringSearch *m_strsrch_; - -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_COLLATION */ - -#endif - diff --git a/win32/include/spidermonkey/unicode/symtable.h b/win32/include/spidermonkey/unicode/symtable.h deleted file mode 100755 index cf2c4f0f..00000000 --- a/win32/include/spidermonkey/unicode/symtable.h +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2000-2005, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* Date Name Description -* 02/04/00 aliu Creation. -********************************************************************** -*/ -#ifndef SYMTABLE_H -#define SYMTABLE_H - -#include "unicode/utypes.h" -#include "unicode/uobject.h" - -/** - * \file - * \brief C++ API: An interface that defines both lookup protocol and parsing of - * symbolic names. - */ - -U_NAMESPACE_BEGIN - -class ParsePosition; -class UnicodeFunctor; -class UnicodeSet; -class UnicodeString; - -/** - * An interface that defines both lookup protocol and parsing of - * symbolic names. - * - *

A symbol table maintains two kinds of mappings. The first is - * between symbolic names and their values. For example, if the - * variable with the name "start" is set to the value "alpha" - * (perhaps, though not necessarily, through an expression such as - * "$start=alpha"), then the call lookup("start") will return the - * char[] array ['a', 'l', 'p', 'h', 'a']. - * - *

The second kind of mapping is between character values and - * UnicodeMatcher objects. This is used by RuleBasedTransliterator, - * which uses characters in the private use area to represent objects - * such as UnicodeSets. If U+E015 is mapped to the UnicodeSet [a-z], - * then lookupMatcher(0xE015) will return the UnicodeSet [a-z]. - * - *

Finally, a symbol table defines parsing behavior for symbolic - * names. All symbolic names start with the SYMBOL_REF character. - * When a parser encounters this character, it calls parseReference() - * with the position immediately following the SYMBOL_REF. The symbol - * table parses the name, if there is one, and returns it. - * - * @stable ICU 2.8 - */ -class U_COMMON_API SymbolTable /* not : public UObject because this is an interface/mixin class */ { -public: - - /** - * The character preceding a symbol reference name. - * @stable ICU 2.8 - */ - enum { SYMBOL_REF = 0x0024 /*$*/ }; - - /** - * Destructor. - * @stable ICU 2.8 - */ - virtual ~SymbolTable(); - - /** - * Lookup the characters associated with this string and return it. - * Return NULL if no such name exists. The resultant - * string may have length zero. - * @param s the symbolic name to lookup - * @return a string containing the name's value, or NULL if - * there is no mapping for s. - * @stable ICU 2.8 - */ - virtual const UnicodeString* lookup(const UnicodeString& s) const = 0; - - /** - * Lookup the UnicodeMatcher associated with the given character, and - * return it. Return NULL if not found. - * @param ch a 32-bit code point from 0 to 0x10FFFF inclusive. - * @return the UnicodeMatcher object represented by the given - * character, or NULL if there is no mapping for ch. - * @stable ICU 2.8 - */ - virtual const UnicodeFunctor* lookupMatcher(UChar32 ch) const = 0; - - /** - * Parse a symbol reference name from the given string, starting - * at the given position. If no valid symbol reference name is - * found, return the empty string and leave pos unchanged. That is, if the - * character at pos cannot start a name, or if pos is at or after - * text.length(), then return an empty string. This indicates an - * isolated SYMBOL_REF character. - * @param text the text to parse for the name - * @param pos on entry, the index of the first character to parse. - * This is the character following the SYMBOL_REF character. On - * exit, the index after the last parsed character. If the parse - * failed, pos is unchanged on exit. - * @param limit the index after the last character to be parsed. - * @return the parsed name, or an empty string if there is no - * valid symbolic name at the given position. - * @stable ICU 2.8 - */ - virtual UnicodeString parseReference(const UnicodeString& text, - ParsePosition& pos, int32_t limit) const = 0; -}; -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/tblcoll.h b/win32/include/spidermonkey/unicode/tblcoll.h deleted file mode 100755 index c48ea38c..00000000 --- a/win32/include/spidermonkey/unicode/tblcoll.h +++ /dev/null @@ -1,877 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* Copyright (C) 1996-2016, International Business Machines Corporation and -* others. All Rights Reserved. -****************************************************************************** -*/ - -/** - * \file - * \brief C++ API: The RuleBasedCollator class implements the Collator abstract base class. - */ - -/** -* File tblcoll.h -* -* Created by: Helena Shih -* -* Modification History: -* -* Date Name Description -* 2/5/97 aliu Added streamIn and streamOut methods. Added -* constructor which reads RuleBasedCollator object from -* a binary file. Added writeToFile method which streams -* RuleBasedCollator out to a binary file. The streamIn -* and streamOut methods use istream and ostream objects -* in binary mode. -* 2/12/97 aliu Modified to use TableCollationData sub-object to -* hold invariant data. -* 2/13/97 aliu Moved several methods into this class from Collation. -* Added a private RuleBasedCollator(Locale&) constructor, -* to be used by Collator::createDefault(). General -* clean up. -* 2/20/97 helena Added clone, operator==, operator!=, operator=, and copy -* constructor and getDynamicClassID. -* 3/5/97 aliu Modified constructFromFile() to add parameter -* specifying whether or not binary loading is to be -* attempted. This is required for dynamic rule loading. -* 05/07/97 helena Added memory allocation error detection. -* 6/17/97 helena Added IDENTICAL strength for compare, changed getRules to -* use MergeCollation::getPattern. -* 6/20/97 helena Java class name change. -* 8/18/97 helena Added internal API documentation. -* 09/03/97 helena Added createCollationKeyValues(). -* 02/10/98 damiba Added compare with "length" parameter -* 08/05/98 erm Synched with 1.2 version of RuleBasedCollator.java -* 04/23/99 stephen Removed EDecompositionMode, merged with -* Normalizer::EMode -* 06/14/99 stephen Removed kResourceBundleSuffix -* 11/02/99 helena Collator performance enhancements. Eliminates the -* UnicodeString construction and special case for NO_OP. -* 11/23/99 srl More performance enhancements. Updates to NormalizerIterator -* internal state management. -* 12/15/99 aliu Update to support Thai collation. Move NormalizerIterator -* to implementation file. -* 01/29/01 synwee Modified into a C++ wrapper which calls C API -* (ucol.h) -* 2012-2014 markus Rewritten in C++ again. -*/ - -#ifndef TBLCOLL_H -#define TBLCOLL_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_COLLATION - -#include "unicode/coll.h" -#include "unicode/locid.h" -#include "unicode/uiter.h" -#include "unicode/ucol.h" - -U_NAMESPACE_BEGIN - -struct CollationCacheEntry; -struct CollationData; -struct CollationSettings; -struct CollationTailoring; -/** -* @stable ICU 2.0 -*/ -class StringSearch; -/** -* @stable ICU 2.0 -*/ -class CollationElementIterator; -class CollationKey; -class SortKeyByteSink; -class UnicodeSet; -class UnicodeString; -class UVector64; - -/** - * The RuleBasedCollator class provides the implementation of - * Collator, using data-driven tables. The user can create a customized - * table-based collation. - *

- * For more information about the collation service see - * the User Guide. - *

- * Collation service provides correct sorting orders for most locales supported in ICU. - * If specific data for a locale is not available, the orders eventually falls back - * to the CLDR root sort order. - *

- * Sort ordering may be customized by providing your own set of rules. For more on - * this subject see the - * Collation Customization section of the User Guide. - *

- * Note, RuleBasedCollator is not to be subclassed. - * @see Collator - */ -class U_I18N_API RuleBasedCollator : public Collator { -public: - /** - * RuleBasedCollator constructor. This takes the table rules and builds a - * collation table out of them. Please see RuleBasedCollator class - * description for more details on the collation rule syntax. - * @param rules the collation rules to build the collation table from. - * @param status reporting a success or an error. - * @stable ICU 2.0 - */ - RuleBasedCollator(const UnicodeString& rules, UErrorCode& status); - - /** - * RuleBasedCollator constructor. This takes the table rules and builds a - * collation table out of them. Please see RuleBasedCollator class - * description for more details on the collation rule syntax. - * @param rules the collation rules to build the collation table from. - * @param collationStrength strength for comparison - * @param status reporting a success or an error. - * @stable ICU 2.0 - */ - RuleBasedCollator(const UnicodeString& rules, - ECollationStrength collationStrength, - UErrorCode& status); - - /** - * RuleBasedCollator constructor. This takes the table rules and builds a - * collation table out of them. Please see RuleBasedCollator class - * description for more details on the collation rule syntax. - * @param rules the collation rules to build the collation table from. - * @param decompositionMode the normalisation mode - * @param status reporting a success or an error. - * @stable ICU 2.0 - */ - RuleBasedCollator(const UnicodeString& rules, - UColAttributeValue decompositionMode, - UErrorCode& status); - - /** - * RuleBasedCollator constructor. This takes the table rules and builds a - * collation table out of them. Please see RuleBasedCollator class - * description for more details on the collation rule syntax. - * @param rules the collation rules to build the collation table from. - * @param collationStrength strength for comparison - * @param decompositionMode the normalisation mode - * @param status reporting a success or an error. - * @stable ICU 2.0 - */ - RuleBasedCollator(const UnicodeString& rules, - ECollationStrength collationStrength, - UColAttributeValue decompositionMode, - UErrorCode& status); - -#ifndef U_HIDE_INTERNAL_API - /** - * TODO: document & propose as public API - * @internal - */ - RuleBasedCollator(const UnicodeString &rules, - UParseError &parseError, UnicodeString &reason, - UErrorCode &errorCode); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Copy constructor. - * @param other the RuleBasedCollator object to be copied - * @stable ICU 2.0 - */ - RuleBasedCollator(const RuleBasedCollator& other); - - - /** Opens a collator from a collator binary image created using - * cloneBinary. Binary image used in instantiation of the - * collator remains owned by the user and should stay around for - * the lifetime of the collator. The API also takes a base collator - * which must be the root collator. - * @param bin binary image owned by the user and required through the - * lifetime of the collator - * @param length size of the image. If negative, the API will try to - * figure out the length of the image - * @param base Base collator, for lookup of untailored characters. - * Must be the root collator, must not be NULL. - * The base is required to be present through the lifetime of the collator. - * @param status for catching errors - * @return newly created collator - * @see cloneBinary - * @stable ICU 3.4 - */ - RuleBasedCollator(const uint8_t *bin, int32_t length, - const RuleBasedCollator *base, - UErrorCode &status); - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~RuleBasedCollator(); - - /** - * Assignment operator. - * @param other other RuleBasedCollator object to copy from. - * @stable ICU 2.0 - */ - RuleBasedCollator& operator=(const RuleBasedCollator& other); - - /** - * Returns true if argument is the same as this object. - * @param other Collator object to be compared. - * @return true if arguments is the same as this object. - * @stable ICU 2.0 - */ - virtual UBool operator==(const Collator& other) const; - - /** - * Makes a copy of this object. - * @return a copy of this object, owned by the caller - * @stable ICU 2.0 - */ - virtual Collator* clone(void) const; - - /** - * Creates a collation element iterator for the source string. The caller of - * this method is responsible for the memory management of the return - * pointer. - * @param source the string over which the CollationElementIterator will - * iterate. - * @return the collation element iterator of the source string using this as - * the based Collator. - * @stable ICU 2.2 - */ - virtual CollationElementIterator* createCollationElementIterator( - const UnicodeString& source) const; - - /** - * Creates a collation element iterator for the source. The caller of this - * method is responsible for the memory management of the returned pointer. - * @param source the CharacterIterator which produces the characters over - * which the CollationElementItgerator will iterate. - * @return the collation element iterator of the source using this as the - * based Collator. - * @stable ICU 2.2 - */ - virtual CollationElementIterator* createCollationElementIterator( - const CharacterIterator& source) const; - - // Make deprecated versions of Collator::compare() visible. - using Collator::compare; - - /** - * The comparison function compares the character data stored in two - * different strings. Returns information about whether a string is less - * than, greater than or equal to another string. - * @param source the source string to be compared with. - * @param target the string that is to be compared with the source string. - * @param status possible error code - * @return Returns an enum value. UCOL_GREATER if source is greater - * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less - * than target - * @stable ICU 2.6 - **/ - virtual UCollationResult compare(const UnicodeString& source, - const UnicodeString& target, - UErrorCode &status) const; - - /** - * Does the same thing as compare but limits the comparison to a specified - * length - * @param source the source string to be compared with. - * @param target the string that is to be compared with the source string. - * @param length the length the comparison is limited to - * @param status possible error code - * @return Returns an enum value. UCOL_GREATER if source (up to the specified - * length) is greater than target; UCOL_EQUAL if source (up to specified - * length) is equal to target; UCOL_LESS if source (up to the specified - * length) is less than target. - * @stable ICU 2.6 - */ - virtual UCollationResult compare(const UnicodeString& source, - const UnicodeString& target, - int32_t length, - UErrorCode &status) const; - - /** - * The comparison function compares the character data stored in two - * different string arrays. Returns information about whether a string array - * is less than, greater than or equal to another string array. - * @param source the source string array to be compared with. - * @param sourceLength the length of the source string array. If this value - * is equal to -1, the string array is null-terminated. - * @param target the string that is to be compared with the source string. - * @param targetLength the length of the target string array. If this value - * is equal to -1, the string array is null-terminated. - * @param status possible error code - * @return Returns an enum value. UCOL_GREATER if source is greater - * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less - * than target - * @stable ICU 2.6 - */ - virtual UCollationResult compare(const UChar* source, int32_t sourceLength, - const UChar* target, int32_t targetLength, - UErrorCode &status) const; - - /** - * Compares two strings using the Collator. - * Returns whether the first one compares less than/equal to/greater than - * the second one. - * This version takes UCharIterator input. - * @param sIter the first ("source") string iterator - * @param tIter the second ("target") string iterator - * @param status ICU status - * @return UCOL_LESS, UCOL_EQUAL or UCOL_GREATER - * @stable ICU 4.2 - */ - virtual UCollationResult compare(UCharIterator &sIter, - UCharIterator &tIter, - UErrorCode &status) const; - - /** - * Compares two UTF-8 strings using the Collator. - * Returns whether the first one compares less than/equal to/greater than - * the second one. - * This version takes UTF-8 input. - * Note that a StringPiece can be implicitly constructed - * from a std::string or a NUL-terminated const char * string. - * @param source the first UTF-8 string - * @param target the second UTF-8 string - * @param status ICU status - * @return UCOL_LESS, UCOL_EQUAL or UCOL_GREATER - * @stable ICU 51 - */ - virtual UCollationResult compareUTF8(const StringPiece &source, - const StringPiece &target, - UErrorCode &status) const; - - /** - * Transforms the string into a series of characters - * that can be compared with CollationKey.compare(). - * - * Note that sort keys are often less efficient than simply doing comparison. - * For more details, see the ICU User Guide. - * - * @param source the source string. - * @param key the transformed key of the source string. - * @param status the error code status. - * @return the transformed key. - * @see CollationKey - * @stable ICU 2.0 - */ - virtual CollationKey& getCollationKey(const UnicodeString& source, - CollationKey& key, - UErrorCode& status) const; - - /** - * Transforms a specified region of the string into a series of characters - * that can be compared with CollationKey.compare. - * - * Note that sort keys are often less efficient than simply doing comparison. - * For more details, see the ICU User Guide. - * - * @param source the source string. - * @param sourceLength the length of the source string. - * @param key the transformed key of the source string. - * @param status the error code status. - * @return the transformed key. - * @see CollationKey - * @stable ICU 2.0 - */ - virtual CollationKey& getCollationKey(const UChar *source, - int32_t sourceLength, - CollationKey& key, - UErrorCode& status) const; - - /** - * Generates the hash code for the rule-based collation object. - * @return the hash code. - * @stable ICU 2.0 - */ - virtual int32_t hashCode() const; - - /** - * Gets the locale of the Collator - * @param type can be either requested, valid or actual locale. For more - * information see the definition of ULocDataLocaleType in - * uloc.h - * @param status the error code status. - * @return locale where the collation data lives. If the collator - * was instantiated from rules, locale is empty. - * @deprecated ICU 2.8 likely to change in ICU 3.0, based on feedback - */ - virtual Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const; - - /** - * Gets the tailoring rules for this collator. - * @return the collation tailoring from which this collator was created - * @stable ICU 2.0 - */ - const UnicodeString& getRules() const; - - /** - * Gets the version information for a Collator. - * @param info the version # information, the result will be filled in - * @stable ICU 2.0 - */ - virtual void getVersion(UVersionInfo info) const; - -#ifndef U_HIDE_DEPRECATED_API - /** - * Returns the maximum length of any expansion sequences that end with the - * specified comparison order. - * - * This is specific to the kind of collation element values and sequences - * returned by the CollationElementIterator. - * Call CollationElementIterator::getMaxExpansion() instead. - * - * @param order a collation order returned by CollationElementIterator::previous - * or CollationElementIterator::next. - * @return maximum size of the expansion sequences ending with the collation - * element, or 1 if the collation element does not occur at the end of - * any expansion sequence - * @see CollationElementIterator#getMaxExpansion - * @deprecated ICU 51 Use CollationElementIterator::getMaxExpansion() instead. - */ - int32_t getMaxExpansion(int32_t order) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * @return The class ID for this object. All objects of a given class have - * the same class ID. Objects of other classes have different class - * IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const; - - /** - * Returns the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * Base* polymorphic_pointer = createPolymorphicObject();
-     * if (polymorphic_pointer->getDynamicClassID() ==
-     *                                          Derived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - -#ifndef U_HIDE_DEPRECATED_API - /** - * Do not use this method: The caller and the ICU library might use different heaps. - * Use cloneBinary() instead which writes to caller-provided memory. - * - * Returns a binary format of this collator. - * @param length Returns the length of the data, in bytes - * @param status the error code status. - * @return memory, owned by the caller, of size 'length' bytes. - * @deprecated ICU 52. Use cloneBinary() instead. - */ - uint8_t *cloneRuleData(int32_t &length, UErrorCode &status) const; -#endif /* U_HIDE_DEPRECATED_API */ - - /** Creates a binary image of a collator. This binary image can be stored and - * later used to instantiate a collator using ucol_openBinary. - * This API supports preflighting. - * @param buffer a fill-in buffer to receive the binary image - * @param capacity capacity of the destination buffer - * @param status for catching errors - * @return size of the image - * @see ucol_openBinary - * @stable ICU 3.4 - */ - int32_t cloneBinary(uint8_t *buffer, int32_t capacity, UErrorCode &status) const; - - /** - * Returns current rules. Delta defines whether full rules are returned or - * just the tailoring. - * - * getRules(void) should normally be used instead. - * See http://userguide.icu-project.org/collation/customization#TOC-Building-on-Existing-Locales - * @param delta one of UCOL_TAILORING_ONLY, UCOL_FULL_RULES. - * @param buffer UnicodeString to store the result rules - * @stable ICU 2.2 - * @see UCOL_FULL_RULES - */ - void getRules(UColRuleOption delta, UnicodeString &buffer) const; - - /** - * Universal attribute setter - * @param attr attribute type - * @param value attribute value - * @param status to indicate whether the operation went on smoothly or there were errors - * @stable ICU 2.2 - */ - virtual void setAttribute(UColAttribute attr, UColAttributeValue value, - UErrorCode &status); - - /** - * Universal attribute getter. - * @param attr attribute type - * @param status to indicate whether the operation went on smoothly or there were errors - * @return attribute value - * @stable ICU 2.2 - */ - virtual UColAttributeValue getAttribute(UColAttribute attr, - UErrorCode &status) const; - - /** - * Sets the variable top to the top of the specified reordering group. - * The variable top determines the highest-sorting character - * which is affected by UCOL_ALTERNATE_HANDLING. - * If that attribute is set to UCOL_NON_IGNORABLE, then the variable top has no effect. - * @param group one of UCOL_REORDER_CODE_SPACE, UCOL_REORDER_CODE_PUNCTUATION, - * UCOL_REORDER_CODE_SYMBOL, UCOL_REORDER_CODE_CURRENCY; - * or UCOL_REORDER_CODE_DEFAULT to restore the default max variable group - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return *this - * @see getMaxVariable - * @stable ICU 53 - */ - virtual Collator &setMaxVariable(UColReorderCode group, UErrorCode &errorCode); - - /** - * Returns the maximum reordering group whose characters are affected by UCOL_ALTERNATE_HANDLING. - * @return the maximum variable reordering group. - * @see setMaxVariable - * @stable ICU 53 - */ - virtual UColReorderCode getMaxVariable() const; - - /** - * Sets the variable top to the primary weight of the specified string. - * - * Beginning with ICU 53, the variable top is pinned to - * the top of one of the supported reordering groups, - * and it must not be beyond the last of those groups. - * See setMaxVariable(). - * @param varTop one or more (if contraction) UChars to which the variable top should be set - * @param len length of variable top string. If -1 it is considered to be zero terminated. - * @param status error code. If error code is set, the return value is undefined. Errors set by this function are:
- * U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction
- * U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond - * the last reordering group supported by setMaxVariable() - * @return variable top primary weight - * @deprecated ICU 53 Call setMaxVariable() instead. - */ - virtual uint32_t setVariableTop(const UChar *varTop, int32_t len, UErrorCode &status); - - /** - * Sets the variable top to the primary weight of the specified string. - * - * Beginning with ICU 53, the variable top is pinned to - * the top of one of the supported reordering groups, - * and it must not be beyond the last of those groups. - * See setMaxVariable(). - * @param varTop a UnicodeString size 1 or more (if contraction) of UChars to which the variable top should be set - * @param status error code. If error code is set, the return value is undefined. Errors set by this function are:
- * U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction
- * U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond - * the last reordering group supported by setMaxVariable() - * @return variable top primary weight - * @deprecated ICU 53 Call setMaxVariable() instead. - */ - virtual uint32_t setVariableTop(const UnicodeString &varTop, UErrorCode &status); - - /** - * Sets the variable top to the specified primary weight. - * - * Beginning with ICU 53, the variable top is pinned to - * the top of one of the supported reordering groups, - * and it must not be beyond the last of those groups. - * See setMaxVariable(). - * @param varTop primary weight, as returned by setVariableTop or ucol_getVariableTop - * @param status error code - * @deprecated ICU 53 Call setMaxVariable() instead. - */ - virtual void setVariableTop(uint32_t varTop, UErrorCode &status); - - /** - * Gets the variable top value of a Collator. - * @param status error code (not changed by function). If error code is set, the return value is undefined. - * @return the variable top primary weight - * @see getMaxVariable - * @stable ICU 2.0 - */ - virtual uint32_t getVariableTop(UErrorCode &status) const; - - /** - * Get a UnicodeSet that contains all the characters and sequences tailored in - * this collator. - * @param status error code of the operation - * @return a pointer to a UnicodeSet object containing all the - * code points and sequences that may sort differently than - * in the root collator. The object must be disposed of by using delete - * @stable ICU 2.4 - */ - virtual UnicodeSet *getTailoredSet(UErrorCode &status) const; - - /** - * Get the sort key as an array of bytes from a UnicodeString. - * - * Note that sort keys are often less efficient than simply doing comparison. - * For more details, see the ICU User Guide. - * - * @param source string to be processed. - * @param result buffer to store result in. If NULL, number of bytes needed - * will be returned. - * @param resultLength length of the result buffer. If if not enough the - * buffer will be filled to capacity. - * @return Number of bytes needed for storing the sort key - * @stable ICU 2.0 - */ - virtual int32_t getSortKey(const UnicodeString& source, uint8_t *result, - int32_t resultLength) const; - - /** - * Get the sort key as an array of bytes from a UChar buffer. - * - * Note that sort keys are often less efficient than simply doing comparison. - * For more details, see the ICU User Guide. - * - * @param source string to be processed. - * @param sourceLength length of string to be processed. If -1, the string - * is 0 terminated and length will be decided by the function. - * @param result buffer to store result in. If NULL, number of bytes needed - * will be returned. - * @param resultLength length of the result buffer. If if not enough the - * buffer will be filled to capacity. - * @return Number of bytes needed for storing the sort key - * @stable ICU 2.2 - */ - virtual int32_t getSortKey(const UChar *source, int32_t sourceLength, - uint8_t *result, int32_t resultLength) const; - - /** - * Retrieves the reordering codes for this collator. - * @param dest The array to fill with the script ordering. - * @param destCapacity The length of dest. If it is 0, then dest may be NULL and the function - * will only return the length of the result without writing any codes (pre-flighting). - * @param status A reference to an error code value, which must not indicate - * a failure before the function call. - * @return The length of the script ordering array. - * @see ucol_setReorderCodes - * @see Collator#getEquivalentReorderCodes - * @see Collator#setReorderCodes - * @stable ICU 4.8 - */ - virtual int32_t getReorderCodes(int32_t *dest, - int32_t destCapacity, - UErrorCode& status) const; - - /** - * Sets the ordering of scripts for this collator. - * @param reorderCodes An array of script codes in the new order. This can be NULL if the - * length is also set to 0. An empty array will clear any reordering codes on the collator. - * @param reorderCodesLength The length of reorderCodes. - * @param status error code - * @see ucol_setReorderCodes - * @see Collator#getReorderCodes - * @see Collator#getEquivalentReorderCodes - * @stable ICU 4.8 - */ - virtual void setReorderCodes(const int32_t* reorderCodes, - int32_t reorderCodesLength, - UErrorCode& status) ; - - /** - * Implements ucol_strcollUTF8(). - * @internal - */ - virtual UCollationResult internalCompareUTF8( - const char *left, int32_t leftLength, - const char *right, int32_t rightLength, - UErrorCode &errorCode) const; - - /** Get the short definition string for a collator. This internal API harvests the collator's - * locale and the attribute set and produces a string that can be used for opening - * a collator with the same attributes using the ucol_openFromShortString API. - * This string will be normalized. - * The structure and the syntax of the string is defined in the "Naming collators" - * section of the users guide: - * http://userguide.icu-project.org/collation/concepts#TOC-Collator-naming-scheme - * This function supports preflighting. - * - * This is internal, and intended to be used with delegate converters. - * - * @param locale a locale that will appear as a collators locale in the resulting - * short string definition. If NULL, the locale will be harvested - * from the collator. - * @param buffer space to hold the resulting string - * @param capacity capacity of the buffer - * @param status for returning errors. All the preflighting errors are featured - * @return length of the resulting string - * @see ucol_openFromShortString - * @see ucol_normalizeShortDefinitionString - * @see ucol_getShortDefinitionString - * @internal - */ - virtual int32_t internalGetShortDefinitionString(const char *locale, - char *buffer, - int32_t capacity, - UErrorCode &status) const; - - /** - * Implements ucol_nextSortKeyPart(). - * @internal - */ - virtual int32_t internalNextSortKeyPart( - UCharIterator *iter, uint32_t state[2], - uint8_t *dest, int32_t count, UErrorCode &errorCode) const; - - // Do not enclose the default constructor with #ifndef U_HIDE_INTERNAL_API - /** - * Only for use in ucol_openRules(). - * @internal - */ - RuleBasedCollator(); - -#ifndef U_HIDE_INTERNAL_API - /** - * Implements ucol_getLocaleByType(). - * Needed because the lifetime of the locale ID string must match that of the collator. - * getLocale() returns a copy of a Locale, with minimal lifetime in a C wrapper. - * @internal - */ - const char *internalGetLocaleID(ULocDataLocaleType type, UErrorCode &errorCode) const; - - /** - * Implements ucol_getContractionsAndExpansions(). - * Gets this collator's sets of contraction strings and/or - * characters and strings that map to multiple collation elements (expansions). - * If addPrefixes is TRUE, then contractions that are expressed as - * prefix/pre-context rules are included. - * @param contractions if not NULL, the set to hold the contractions - * @param expansions if not NULL, the set to hold the expansions - * @param addPrefixes include prefix contextual mappings - * @param errorCode in/out ICU error code - * @internal - */ - void internalGetContractionsAndExpansions( - UnicodeSet *contractions, UnicodeSet *expansions, - UBool addPrefixes, UErrorCode &errorCode) const; - - /** - * Adds the contractions that start with character c to the set. - * Ignores prefixes. Used by AlphabeticIndex. - * @internal - */ - void internalAddContractions(UChar32 c, UnicodeSet &set, UErrorCode &errorCode) const; - - /** - * Implements from-rule constructors, and ucol_openRules(). - * @internal - */ - void internalBuildTailoring( - const UnicodeString &rules, - int32_t strength, - UColAttributeValue decompositionMode, - UParseError *outParseError, UnicodeString *outReason, - UErrorCode &errorCode); - - /** @internal */ - static inline RuleBasedCollator *rbcFromUCollator(UCollator *uc) { - return dynamic_cast(fromUCollator(uc)); - } - /** @internal */ - static inline const RuleBasedCollator *rbcFromUCollator(const UCollator *uc) { - return dynamic_cast(fromUCollator(uc)); - } - - /** - * Appends the CEs for the string to the vector. - * @internal for tests & tools - */ - void internalGetCEs(const UnicodeString &str, UVector64 &ces, UErrorCode &errorCode) const; -#endif // U_HIDE_INTERNAL_API - -protected: - /** - * Used internally by registration to define the requested and valid locales. - * @param requestedLocale the requested locale - * @param validLocale the valid locale - * @param actualLocale the actual locale - * @internal - */ - virtual void setLocales(const Locale& requestedLocale, const Locale& validLocale, const Locale& actualLocale); - -private: - friend class CollationElementIterator; - friend class Collator; - - RuleBasedCollator(const CollationCacheEntry *entry); - - /** - * Enumeration of attributes that are relevant for short definition strings - * (e.g., ucol_getShortDefinitionString()). - * Effectively extends UColAttribute. - */ - enum Attributes { - ATTR_VARIABLE_TOP = UCOL_ATTRIBUTE_COUNT, - ATTR_LIMIT - }; - - void adoptTailoring(CollationTailoring *t, UErrorCode &errorCode); - - // Both lengths must be <0 or else both must be >=0. - UCollationResult doCompare(const UChar *left, int32_t leftLength, - const UChar *right, int32_t rightLength, - UErrorCode &errorCode) const; - UCollationResult doCompare(const uint8_t *left, int32_t leftLength, - const uint8_t *right, int32_t rightLength, - UErrorCode &errorCode) const; - - void writeSortKey(const UChar *s, int32_t length, - SortKeyByteSink &sink, UErrorCode &errorCode) const; - - void writeIdenticalLevel(const UChar *s, const UChar *limit, - SortKeyByteSink &sink, UErrorCode &errorCode) const; - - const CollationSettings &getDefaultSettings() const; - - void setAttributeDefault(int32_t attribute) { - explicitlySetAttributes &= ~((uint32_t)1 << attribute); - } - void setAttributeExplicitly(int32_t attribute) { - explicitlySetAttributes |= (uint32_t)1 << attribute; - } - UBool attributeHasBeenSetExplicitly(int32_t attribute) const { - // assert(0 <= attribute < ATTR_LIMIT); - return (UBool)((explicitlySetAttributes & ((uint32_t)1 << attribute)) != 0); - } - - /** - * Tests whether a character is "unsafe" for use as a collation starting point. - * - * @param c code point or code unit - * @return TRUE if c is unsafe - * @see CollationElementIterator#setOffset(int) - */ - UBool isUnsafe(UChar32 c) const; - - static void U_CALLCONV computeMaxExpansions(const CollationTailoring *t, UErrorCode &errorCode); - UBool initMaxExpansions(UErrorCode &errorCode) const; - - void setFastLatinOptions(CollationSettings &ownedSettings) const; - - const CollationData *data; - const CollationSettings *settings; // reference-counted - const CollationTailoring *tailoring; // alias of cacheEntry->tailoring - const CollationCacheEntry *cacheEntry; // reference-counted - Locale validLocale; - uint32_t explicitlySetAttributes; - - UBool actualLocaleIsSameAsValid; -}; - -U_NAMESPACE_END - -#endif // !UCONFIG_NO_COLLATION -#endif // TBLCOLL_H diff --git a/win32/include/spidermonkey/unicode/timezone.h b/win32/include/spidermonkey/unicode/timezone.h deleted file mode 100755 index 4254cc7c..00000000 --- a/win32/include/spidermonkey/unicode/timezone.h +++ /dev/null @@ -1,968 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/************************************************************************* -* Copyright (c) 1997-2016, International Business Machines Corporation -* and others. All Rights Reserved. -************************************************************************** -* -* File TIMEZONE.H -* -* Modification History: -* -* Date Name Description -* 04/21/97 aliu Overhauled header. -* 07/09/97 helena Changed createInstance to createDefault. -* 08/06/97 aliu Removed dependency on internal header for Hashtable. -* 08/10/98 stephen Changed getDisplayName() API conventions to match -* 08/19/98 stephen Changed createTimeZone() to never return 0 -* 09/02/98 stephen Sync to JDK 1.2 8/31 -* - Added getOffset(... monthlen ...) -* - Added hasSameRules() -* 09/15/98 stephen Added getStaticClassID -* 12/03/99 aliu Moved data out of static table into icudata.dll. -* Hashtable replaced by new static data structures. -* 12/14/99 aliu Made GMT public. -* 08/15/01 grhoten Made GMT private and added the getGMT() function -************************************************************************** -*/ - -#ifndef TIMEZONE_H -#define TIMEZONE_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: TimeZone object - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/uobject.h" -#include "unicode/unistr.h" -#include "unicode/ures.h" -#include "unicode/ucal.h" - -U_NAMESPACE_BEGIN - -class StringEnumeration; - -/** - * - * TimeZone represents a time zone offset, and also figures out daylight - * savings. - * - *

- * Typically, you get a TimeZone using createDefault - * which creates a TimeZone based on the time zone where the program - * is running. For example, for a program running in Japan, createDefault - * creates a TimeZone object based on Japanese Standard Time. - * - *

- * You can also get a TimeZone using createTimeZone along - * with a time zone ID. For instance, the time zone ID for the US Pacific - * Time zone is "America/Los_Angeles". So, you can get a Pacific Time TimeZone object - * with: - * \htmlonly

\endhtmlonly - *
- * TimeZone *tz = TimeZone::createTimeZone("America/Los_Angeles");
- * 
- * \htmlonly
\endhtmlonly - * You can use the createEnumeration method to iterate through - * all the supported time zone IDs, or the getCanonicalID method to check - * if a time zone ID is supported or not. You can then choose a - * supported ID to get a TimeZone. - * If the time zone you want is not represented by one of the - * supported IDs, then you can create a custom time zone ID with - * the following syntax: - * - * \htmlonly
\endhtmlonly - *
- * GMT[+|-]hh[[:]mm]
- * 
- * \htmlonly
\endhtmlonly - * - * For example, you might specify GMT+14:00 as a custom - * time zone ID. The TimeZone that is returned - * when you specify a custom time zone ID uses the specified - * offset from GMT(=UTC) and does not observe daylight saving - * time. For example, you might specify GMT+14:00 as a custom - * time zone ID to create a TimeZone representing 14 hours ahead - * of GMT (with no daylight saving time). In addition, - * getCanonicalID can also be used to - * normalize a custom time zone ID. - * - * TimeZone is an abstract class representing a time zone. A TimeZone is needed for - * Calendar to produce local time for a particular time zone. A TimeZone comprises - * three basic pieces of information: - *
    - *
  • A time zone offset; that, is the number of milliseconds to add or subtract - * from a time expressed in terms of GMT to convert it to the same time in that - * time zone (without taking daylight savings time into account).
  • - *
  • Logic necessary to take daylight savings time into account if daylight savings - * time is observed in that time zone (e.g., the days and hours on which daylight - * savings time begins and ends).
  • - *
  • An ID. This is a text string that uniquely identifies the time zone.
  • - *
- * - * (Only the ID is actually implemented in TimeZone; subclasses of TimeZone may handle - * daylight savings time and GMT offset in different ways. Currently we have the following - * TimeZone subclasses: RuleBasedTimeZone, SimpleTimeZone, and VTimeZone.) - *

- * The TimeZone class contains a static list containing a TimeZone object for every - * combination of GMT offset and daylight-savings time rules currently in use in the - * world, each with a unique ID. Each ID consists of a region (usually a continent or - * ocean) and a city in that region, separated by a slash, (for example, US Pacific - * Time is "America/Los_Angeles.") Because older versions of this class used - * three- or four-letter abbreviations instead, there is also a table that maps the older - * abbreviations to the newer ones (for example, "PST" maps to "America/Los_Angeles"). - * Anywhere the API requires an ID, you can use either form. - *

- * To create a new TimeZone, you call the factory function TimeZone::createTimeZone() - * and pass it a time zone ID. You can use the createEnumeration() function to - * obtain a list of all the time zone IDs recognized by createTimeZone(). - *

- * You can also use TimeZone::createDefault() to create a TimeZone. This function uses - * platform-specific APIs to produce a TimeZone for the time zone corresponding to - * the client's computer's physical location. For example, if you're in Japan (assuming - * your machine is set up correctly), TimeZone::createDefault() will return a TimeZone - * for Japanese Standard Time ("Asia/Tokyo"). - */ -class U_I18N_API TimeZone : public UObject { -public: - /** - * @stable ICU 2.0 - */ - virtual ~TimeZone(); - - /** - * Returns the "unknown" time zone. - * It behaves like the GMT/UTC time zone but has the - * UCAL_UNKNOWN_ZONE_ID = "Etc/Unknown". - * createTimeZone() returns a mutable clone of this time zone if the input ID is not recognized. - * - * @return the "unknown" time zone. - * @see UCAL_UNKNOWN_ZONE_ID - * @see createTimeZone - * @see getGMT - * @stable ICU 49 - */ - static const TimeZone& U_EXPORT2 getUnknown(); - - /** - * The GMT (=UTC) time zone has a raw offset of zero and does not use daylight - * savings time. This is a commonly used time zone. - * - *

Note: For backward compatibility reason, the ID used by the time - * zone returned by this method is "GMT", although the ICU's canonical - * ID for the GMT time zone is "Etc/GMT". - * - * @return the GMT/UTC time zone. - * @see getUnknown - * @stable ICU 2.0 - */ - static const TimeZone* U_EXPORT2 getGMT(void); - - /** - * Creates a TimeZone for the given ID. - * @param ID the ID for a TimeZone, such as "America/Los_Angeles", - * or a custom ID such as "GMT-8:00". - * @return the specified TimeZone, or a mutable clone of getUnknown() - * if the given ID cannot be understood or if the given ID is "Etc/Unknown". - * The return result is guaranteed to be non-NULL. - * If you require that the specific zone asked for be returned, - * compare the result with getUnknown() or check the ID of the return result. - * @stable ICU 2.0 - */ - static TimeZone* U_EXPORT2 createTimeZone(const UnicodeString& ID); - - /** - * Returns an enumeration over system time zone IDs with the given - * filter conditions. - * @param zoneType The system time zone type. - * @param region The ISO 3166 two-letter country code or UN M.49 - * three-digit area code. When NULL, no filtering - * done by region. - * @param rawOffset An offset from GMT in milliseconds, ignoring - * the effect of daylight savings time, if any. - * When NULL, no filtering done by zone offset. - * @param ec Output param to filled in with a success or - * an error. - * @return an enumeration object, owned by the caller. - * @stable ICU 4.8 - */ - static StringEnumeration* U_EXPORT2 createTimeZoneIDEnumeration( - USystemTimeZoneType zoneType, - const char* region, - const int32_t* rawOffset, - UErrorCode& ec); - - /** - * Returns an enumeration over all recognized time zone IDs. (i.e., - * all strings that createTimeZone() accepts) - * - * @return an enumeration object, owned by the caller. - * @stable ICU 2.4 - */ - static StringEnumeration* U_EXPORT2 createEnumeration(); - - /** - * Returns an enumeration over time zone IDs with a given raw - * offset from GMT. There may be several times zones with the - * same GMT offset that differ in the way they handle daylight - * savings time. For example, the state of Arizona doesn't - * observe daylight savings time. If you ask for the time zone - * IDs corresponding to GMT-7:00, you'll get back an enumeration - * over two time zone IDs: "America/Denver," which corresponds to - * Mountain Standard Time in the winter and Mountain Daylight Time - * in the summer, and "America/Phoenix", which corresponds to - * Mountain Standard Time year-round, even in the summer. - * - * @param rawOffset an offset from GMT in milliseconds, ignoring - * the effect of daylight savings time, if any - * @return an enumeration object, owned by the caller - * @stable ICU 2.4 - */ - static StringEnumeration* U_EXPORT2 createEnumeration(int32_t rawOffset); - - /** - * Returns an enumeration over time zone IDs associated with the - * given country. Some zones are affiliated with no country - * (e.g., "UTC"); these may also be retrieved, as a group. - * - * @param country The ISO 3166 two-letter country code, or NULL to - * retrieve zones not affiliated with any country. - * @return an enumeration object, owned by the caller - * @stable ICU 2.4 - */ - static StringEnumeration* U_EXPORT2 createEnumeration(const char* country); - - /** - * Returns the number of IDs in the equivalency group that - * includes the given ID. An equivalency group contains zones - * that have the same GMT offset and rules. - * - *

The returned count includes the given ID; it is always >= 1. - * The given ID must be a system time zone. If it is not, returns - * zero. - * @param id a system time zone ID - * @return the number of zones in the equivalency group containing - * 'id', or zero if 'id' is not a valid system ID - * @see #getEquivalentID - * @stable ICU 2.0 - */ - static int32_t U_EXPORT2 countEquivalentIDs(const UnicodeString& id); - - /** - * Returns an ID in the equivalency group that - * includes the given ID. An equivalency group contains zones - * that have the same GMT offset and rules. - * - *

The given index must be in the range 0..n-1, where n is the - * value returned by countEquivalentIDs(id). For - * some value of 'index', the returned value will be equal to the - * given id. If the given id is not a valid system time zone, or - * if 'index' is out of range, then returns an empty string. - * @param id a system time zone ID - * @param index a value from 0 to n-1, where n is the value - * returned by countEquivalentIDs(id) - * @return the ID of the index-th zone in the equivalency group - * containing 'id', or an empty string if 'id' is not a valid - * system ID or 'index' is out of range - * @see #countEquivalentIDs - * @stable ICU 2.0 - */ - static const UnicodeString U_EXPORT2 getEquivalentID(const UnicodeString& id, - int32_t index); - - /** - * Creates an instance of TimeZone detected from the current host - * system configuration. Note that ICU4C does not change the default - * time zone unless TimeZone::adoptDefault(TimeZone*) or - * TimeZone::setDefault(const TimeZone&) is explicitly called by a - * user. This method does not update the current ICU's default, - * and may return a different TimeZone from the one returned by - * TimeZone::createDefault(). - * - * @return A new instance of TimeZone detected from the current host system - * configuration. - * @stable ICU 55 - */ - static TimeZone* U_EXPORT2 detectHostTimeZone(); - - /** - * Creates a new copy of the default TimeZone for this host. Unless the default time - * zone has already been set using adoptDefault() or setDefault(), the default is - * determined by querying the system using methods in TPlatformUtilities. If the - * system routines fail, or if they specify a TimeZone or TimeZone offset which is not - * recognized, the TimeZone indicated by the ID kLastResortID is instantiated - * and made the default. - * - * @return A default TimeZone. Clients are responsible for deleting the time zone - * object returned. - * @stable ICU 2.0 - */ - static TimeZone* U_EXPORT2 createDefault(void); - -#define ICU_TZ_HAS_RECREATE_DEFAULT - static void U_EXPORT2 recreateDefault(); - - /** - * Sets the default time zone (i.e., what's returned by createDefault()) to be the - * specified time zone. If NULL is specified for the time zone, the default time - * zone is set to the default host time zone. This call adopts the TimeZone object - * passed in; the client is no longer responsible for deleting it. - * - *

This function is not thread safe. It is an error for multiple threads - * to concurrently attempt to set the default time zone, or for any thread - * to attempt to reference the default zone while another thread is setting it. - * - * @param zone A pointer to the new TimeZone object to use as the default. - * @stable ICU 2.0 - */ - static void U_EXPORT2 adoptDefault(TimeZone* zone); - -#ifndef U_HIDE_SYSTEM_API - /** - * Same as adoptDefault(), except that the TimeZone object passed in is NOT adopted; - * the caller remains responsible for deleting it. - * - *

See the thread safety note under adoptDefault(). - * - * @param zone The given timezone. - * @system - * @stable ICU 2.0 - */ - static void U_EXPORT2 setDefault(const TimeZone& zone); -#endif /* U_HIDE_SYSTEM_API */ - - /** - * Returns the timezone data version currently used by ICU. - * @param status Output param to filled in with a success or an error. - * @return the version string, such as "2007f" - * @stable ICU 3.8 - */ - static const char* U_EXPORT2 getTZDataVersion(UErrorCode& status); - - /** - * Returns the canonical system timezone ID or the normalized - * custom time zone ID for the given time zone ID. - * @param id The input time zone ID to be canonicalized. - * @param canonicalID Receives the canonical system time zone ID - * or the custom time zone ID in normalized format. - * @param status Receives the status. When the given time zone ID - * is neither a known system time zone ID nor a - * valid custom time zone ID, U_ILLEGAL_ARGUMENT_ERROR - * is set. - * @return A reference to the result. - * @stable ICU 4.0 - */ - static UnicodeString& U_EXPORT2 getCanonicalID(const UnicodeString& id, - UnicodeString& canonicalID, UErrorCode& status); - - /** - * Returns the canonical system time zone ID or the normalized - * custom time zone ID for the given time zone ID. - * @param id The input time zone ID to be canonicalized. - * @param canonicalID Receives the canonical system time zone ID - * or the custom time zone ID in normalized format. - * @param isSystemID Receives if the given ID is a known system - * time zone ID. - * @param status Receives the status. When the given time zone ID - * is neither a known system time zone ID nor a - * valid custom time zone ID, U_ILLEGAL_ARGUMENT_ERROR - * is set. - * @return A reference to the result. - * @stable ICU 4.0 - */ - static UnicodeString& U_EXPORT2 getCanonicalID(const UnicodeString& id, - UnicodeString& canonicalID, UBool& isSystemID, UErrorCode& status); - - /** - * Converts a system time zone ID to an equivalent Windows time zone ID. For example, - * Windows time zone ID "Pacific Standard Time" is returned for input "America/Los_Angeles". - * - *

There are system time zones that cannot be mapped to Windows zones. When the input - * system time zone ID is unknown or unmappable to a Windows time zone, then the result will be - * empty, but the operation itself remains successful (no error status set on return). - * - *

This implementation utilizes - * Zone-Tzid mapping data. The mapping data is updated time to time. To get the latest changes, - * please read the ICU user guide section - * Updating the Time Zone Data. - * - * @param id A system time zone ID. - * @param winid Receives a Windows time zone ID. When the input system time zone ID is unknown - * or unmappable to a Windows time zone ID, then an empty string is set on return. - * @param status Receives the status. - * @return A reference to the result (winid). - * @see getIDForWindowsID - * - * @stable ICU 52 - */ - static UnicodeString& U_EXPORT2 getWindowsID(const UnicodeString& id, - UnicodeString& winid, UErrorCode& status); - - /** - * Converts a Windows time zone ID to an equivalent system time zone ID - * for a region. For example, system time zone ID "America/Los_Angeles" is returned - * for input Windows ID "Pacific Standard Time" and region "US" (or null), - * "America/Vancouver" is returned for the same Windows ID "Pacific Standard Time" and - * region "CA". - * - *

Not all Windows time zones can be mapped to system time zones. When the input - * Windows time zone ID is unknown or unmappable to a system time zone, then the result - * will be empty, but the operation itself remains successful (no error status set on return). - * - *

This implementation utilizes - * Zone-Tzid mapping data. The mapping data is updated time to time. To get the latest changes, - * please read the ICU user guide section - * Updating the Time Zone Data. - * - * @param winid A Windows time zone ID. - * @param region A null-terminated region code, or NULL if no regional preference. - * @param id Receives a system time zone ID. When the input Windows time zone ID is unknown - * or unmappable to a system time zone ID, then an empty string is set on return. - * @param status Receives the status. - * @return A reference to the result (id). - * @see getWindowsID - * - * @stable ICU 52 - */ - static UnicodeString& U_EXPORT2 getIDForWindowsID(const UnicodeString& winid, const char* region, - UnicodeString& id, UErrorCode& status); - - /** - * Returns true if the two TimeZones are equal. (The TimeZone version only compares - * IDs, but subclasses are expected to also compare the fields they add.) - * - * @param that The TimeZone object to be compared with. - * @return True if the given TimeZone is equal to this TimeZone; false - * otherwise. - * @stable ICU 2.0 - */ - virtual UBool operator==(const TimeZone& that) const; - - /** - * Returns true if the two TimeZones are NOT equal; that is, if operator==() returns - * false. - * - * @param that The TimeZone object to be compared with. - * @return True if the given TimeZone is not equal to this TimeZone; false - * otherwise. - * @stable ICU 2.0 - */ - UBool operator!=(const TimeZone& that) const {return !operator==(that);} - - /** - * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time in this time zone, taking daylight savings time into - * account) as of a particular reference date. The reference date is used to determine - * whether daylight savings time is in effect and needs to be figured into the offset - * that is returned (in other words, what is the adjusted GMT offset in this time zone - * at this particular date and time?). For the time zones produced by createTimeZone(), - * the reference data is specified according to the Gregorian calendar, and the date - * and time fields are local standard time. - * - *

Note: Don't call this method. Instead, call the getOffset(UDate...) overload, - * which returns both the raw and the DST offset for a given time. This method - * is retained only for backward compatibility. - * - * @param era The reference date's era - * @param year The reference date's year - * @param month The reference date's month (0-based; 0 is January) - * @param day The reference date's day-in-month (1-based) - * @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday) - * @param millis The reference date's milliseconds in day, local standard time - * @param status Output param to filled in with a success or an error. - * @return The offset in milliseconds to add to GMT to get local time. - * @stable ICU 2.0 - */ - virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, - uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const = 0; - - /** - * Gets the time zone offset, for current date, modified in case of - * daylight savings. This is the offset to add *to* UTC to get local time. - * - *

Note: Don't call this method. Instead, call the getOffset(UDate...) overload, - * which returns both the raw and the DST offset for a given time. This method - * is retained only for backward compatibility. - * - * @param era the era of the given date. - * @param year the year in the given date. - * @param month the month in the given date. - * Month is 0-based. e.g., 0 for January. - * @param day the day-in-month of the given date. - * @param dayOfWeek the day-of-week of the given date. - * @param milliseconds the millis in day in standard local time. - * @param monthLength the length of the given month in days. - * @param status Output param to filled in with a success or an error. - * @return the offset to add *to* GMT to get local time. - * @stable ICU 2.0 - */ - virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, - uint8_t dayOfWeek, int32_t milliseconds, - int32_t monthLength, UErrorCode& status) const = 0; - - /** - * Returns the time zone raw and GMT offset for the given moment - * in time. Upon return, local-millis = GMT-millis + rawOffset + - * dstOffset. All computations are performed in the proleptic - * Gregorian calendar. The default implementation in the TimeZone - * class delegates to the 8-argument getOffset(). - * - * @param date moment in time for which to return offsets, in - * units of milliseconds from January 1, 1970 0:00 GMT, either GMT - * time or local wall time, depending on `local'. - * @param local if true, `date' is local wall time; otherwise it - * is in GMT time. - * @param rawOffset output parameter to receive the raw offset, that - * is, the offset not including DST adjustments - * @param dstOffset output parameter to receive the DST offset, - * that is, the offset to be added to `rawOffset' to obtain the - * total offset between local and GMT time. If DST is not in - * effect, this value is zero; otherwise it is a positive value, - * typically one hour. - * @param ec input-output error code - * - * @stable ICU 2.8 - */ - virtual void getOffset(UDate date, UBool local, int32_t& rawOffset, - int32_t& dstOffset, UErrorCode& ec) const; - - /** - * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time, before taking daylight savings time into account). - * - * @param offsetMillis The new raw GMT offset for this time zone. - * @stable ICU 2.0 - */ - virtual void setRawOffset(int32_t offsetMillis) = 0; - - /** - * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time, before taking daylight savings time into account). - * - * @return The TimeZone's raw GMT offset. - * @stable ICU 2.0 - */ - virtual int32_t getRawOffset(void) const = 0; - - /** - * Fills in "ID" with the TimeZone's ID. - * - * @param ID Receives this TimeZone's ID. - * @return A reference to 'ID' - * @stable ICU 2.0 - */ - UnicodeString& getID(UnicodeString& ID) const; - - /** - * Sets the TimeZone's ID to the specified value. This doesn't affect any other - * fields (for example, if you say< - * blockquote>

-     * .     TimeZone* foo = TimeZone::createTimeZone("America/New_York");
-     * .     foo.setID("America/Los_Angeles");
-     * 
\htmlonly\endhtmlonly - * the time zone's GMT offset and daylight-savings rules don't change to those for - * Los Angeles. They're still those for New York. Only the ID has changed.) - * - * @param ID The new time zone ID. - * @stable ICU 2.0 - */ - void setID(const UnicodeString& ID); - - /** - * Enum for use with getDisplayName - * @stable ICU 2.4 - */ - enum EDisplayType { - /** - * Selector for short display name - * @stable ICU 2.4 - */ - SHORT = 1, - /** - * Selector for long display name - * @stable ICU 2.4 - */ - LONG, - /** - * Selector for short generic display name - * @stable ICU 4.4 - */ - SHORT_GENERIC, - /** - * Selector for long generic display name - * @stable ICU 4.4 - */ - LONG_GENERIC, - /** - * Selector for short display name derived - * from time zone offset - * @stable ICU 4.4 - */ - SHORT_GMT, - /** - * Selector for long display name derived - * from time zone offset - * @stable ICU 4.4 - */ - LONG_GMT, - /** - * Selector for short display name derived - * from the time zone's fallback name - * @stable ICU 4.4 - */ - SHORT_COMMONLY_USED, - /** - * Selector for long display name derived - * from the time zone's fallback name - * @stable ICU 4.4 - */ - GENERIC_LOCATION - }; - - /** - * Returns a name of this time zone suitable for presentation to the user - * in the default locale. - * This method returns the long name, not including daylight savings. - * If the display name is not available for the locale, - * then this method returns a string in the localized GMT offset format - * such as GMT[+-]HH:mm. - * @param result the human-readable name of this time zone in the default locale. - * @return A reference to 'result'. - * @stable ICU 2.0 - */ - UnicodeString& getDisplayName(UnicodeString& result) const; - - /** - * Returns a name of this time zone suitable for presentation to the user - * in the specified locale. - * This method returns the long name, not including daylight savings. - * If the display name is not available for the locale, - * then this method returns a string in the localized GMT offset format - * such as GMT[+-]HH:mm. - * @param locale the locale in which to supply the display name. - * @param result the human-readable name of this time zone in the given locale - * or in the default locale if the given locale is not recognized. - * @return A reference to 'result'. - * @stable ICU 2.0 - */ - UnicodeString& getDisplayName(const Locale& locale, UnicodeString& result) const; - - /** - * Returns a name of this time zone suitable for presentation to the user - * in the default locale. - * If the display name is not available for the locale, - * then this method returns a string in the localized GMT offset format - * such as GMT[+-]HH:mm. - * @param daylight if true, return the daylight savings name. - * @param style - * @param result the human-readable name of this time zone in the default locale. - * @return A reference to 'result'. - * @stable ICU 2.0 - */ - UnicodeString& getDisplayName(UBool daylight, EDisplayType style, UnicodeString& result) const; - - /** - * Returns a name of this time zone suitable for presentation to the user - * in the specified locale. - * If the display name is not available for the locale, - * then this method returns a string in the localized GMT offset format - * such as GMT[+-]HH:mm. - * @param daylight if true, return the daylight savings name. - * @param style - * @param locale the locale in which to supply the display name. - * @param result the human-readable name of this time zone in the given locale - * or in the default locale if the given locale is not recognized. - * @return A refence to 'result'. - * @stable ICU 2.0 - */ - UnicodeString& getDisplayName(UBool daylight, EDisplayType style, const Locale& locale, UnicodeString& result) const; - - /** - * Queries if this time zone uses daylight savings time. - * @return true if this time zone uses daylight savings time, - * false, otherwise. - *

Note:The default implementation of - * ICU TimeZone uses the tz database, which supports historic - * rule changes, for system time zones. With the implementation, - * there are time zones that used daylight savings time in the - * past, but no longer used currently. For example, Asia/Tokyo has - * never used daylight savings time since 1951. Most clients would - * expect that this method to return FALSE for such case. - * The default implementation of this method returns TRUE - * when the time zone uses daylight savings time in the current - * (Gregorian) calendar year. - *

In Java 7, observesDaylightTime() was added in - * addition to useDaylightTime(). In Java, useDaylightTime() - * only checks if daylight saving time is observed by the last known - * rule. This specification might not be what most users would expect - * if daylight saving time is currently observed, but not scheduled - * in future. In this case, Java's userDaylightTime() returns - * false. To resolve the issue, Java 7 added observesDaylightTime(), - * which takes the current rule into account. The method observesDaylightTime() - * was added in ICU4J for supporting API signature compatibility with JDK. - * In general, ICU4C also provides JDK compatible methods, but the current - * implementation userDaylightTime() serves the purpose - * (takes the current rule into account), observesDaylightTime() - * is not added in ICU4C. In addition to useDaylightTime(), ICU4C - * BasicTimeZone class (Note that TimeZone::createTimeZone(const UnicodeString &ID) - * always returns a BasicTimeZone) provides a series of methods allowing - * historic and future time zone rule iteration, so you can check if daylight saving - * time is observed or not within a given period. - * - * @stable ICU 2.0 - */ - virtual UBool useDaylightTime(void) const = 0; - - /** - * Queries if the given date is in daylight savings time in - * this time zone. - * This method is wasteful since it creates a new GregorianCalendar and - * deletes it each time it is called. This is a deprecated method - * and provided only for Java compatibility. - * - * @param date the given UDate. - * @param status Output param filled in with success/error code. - * @return true if the given date is in daylight savings time, - * false, otherwise. - * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead. - */ - virtual UBool inDaylightTime(UDate date, UErrorCode& status) const = 0; - - /** - * Returns true if this zone has the same rule and offset as another zone. - * That is, if this zone differs only in ID, if at all. - * @param other the TimeZone object to be compared with - * @return true if the given zone is the same as this one, - * with the possible exception of the ID - * @stable ICU 2.0 - */ - virtual UBool hasSameRules(const TimeZone& other) const; - - /** - * Clones TimeZone objects polymorphically. Clients are responsible for deleting - * the TimeZone object cloned. - * - * @return A new copy of this TimeZone object. - * @stable ICU 2.0 - */ - virtual TimeZone* clone(void) const = 0; - - /** - * Return the class ID for this class. This is useful only for - * comparing to a return value from getDynamicClassID(). - * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. This method is to - * implement a simple version of RTTI, since not all C++ compilers support genuine - * RTTI. Polymorphic operator==() and clone() methods call this method. - *

- * Concrete subclasses of TimeZone must use the UOBJECT_DEFINE_RTTI_IMPLEMENTATION - * macro from uobject.h in their implementation to provide correct RTTI information. - * @return The class ID for this object. All objects of a given class have the - * same class ID. Objects of other classes have different class IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const = 0; - - /** - * Returns the amount of time to be added to local standard time - * to get local wall clock time. - *

- * The default implementation always returns 3600000 milliseconds - * (i.e., one hour) if this time zone observes Daylight Saving - * Time. Otherwise, 0 (zero) is returned. - *

- * If an underlying TimeZone implementation subclass supports - * historical Daylight Saving Time changes, this method returns - * the known latest daylight saving value. - * - * @return the amount of saving time in milliseconds - * @stable ICU 3.6 - */ - virtual int32_t getDSTSavings() const; - - /** - * Gets the region code associated with the given - * system time zone ID. The region code is either ISO 3166 - * 2-letter country code or UN M.49 3-digit area code. - * When the time zone is not associated with a specific location, - * for example - "Etc/UTC", "EST5EDT", then this method returns - * "001" (UN M.49 area code for World). - * - * @param id The system time zone ID. - * @param region Output buffer for receiving the region code. - * @param capacity The size of the output buffer. - * @param status Receives the status. When the given time zone ID - * is not a known system time zone ID, - * U_ILLEGAL_ARGUMENT_ERROR is set. - * @return The length of the output region code. - * @stable ICU 4.8 - */ - static int32_t U_EXPORT2 getRegion(const UnicodeString& id, - char *region, int32_t capacity, UErrorCode& status); - -protected: - - /** - * Default constructor. ID is initialized to the empty string. - * @stable ICU 2.0 - */ - TimeZone(); - - /** - * Construct a TimeZone with a given ID. - * @param id a system time zone ID - * @stable ICU 2.0 - */ - TimeZone(const UnicodeString &id); - - /** - * Copy constructor. - * @param source the object to be copied. - * @stable ICU 2.0 - */ - TimeZone(const TimeZone& source); - - /** - * Default assignment operator. - * @param right the object to be copied. - * @stable ICU 2.0 - */ - TimeZone& operator=(const TimeZone& right); - -#ifndef U_HIDE_INTERNAL_API - /** - * Utility function. For internally loading rule data. - * @param top Top resource bundle for tz data - * @param ruleid ID of rule to load - * @param oldbundle Old bundle to reuse or NULL - * @param status Status parameter - * @return either a new bundle or *oldbundle - * @internal - */ - static UResourceBundle* loadRule(const UResourceBundle* top, const UnicodeString& ruleid, UResourceBundle* oldbundle, UErrorCode&status); -#endif /* U_HIDE_INTERNAL_API */ - -private: - friend class ZoneMeta; - - - static TimeZone* createCustomTimeZone(const UnicodeString&); // Creates a time zone based on the string. - - /** - * Finds the given ID in the Olson tzdata. If the given ID is found in the tzdata, - * returns the pointer to the ID resource. This method is exposed through ZoneMeta class - * for ICU internal implementation and useful for building hashtable using a time zone - * ID as a key. - * @param id zone id string - * @return the pointer of the ID resource, or NULL. - */ - static const UChar* findID(const UnicodeString& id); - - /** - * Resolve a link in Olson tzdata. When the given id is known and it's not a link, - * the id itself is returned. When the given id is known and it is a link, then - * dereferenced zone id is returned. When the given id is unknown, then it returns - * NULL. - * @param id zone id string - * @return the dereferenced zone or NULL - */ - static const UChar* dereferOlsonLink(const UnicodeString& id); - - /** - * Returns the region code associated with the given zone, - * or NULL if the zone is not known. - * @param id zone id string - * @return the region associated with the given zone - */ - static const UChar* getRegion(const UnicodeString& id); - - public: -#ifndef U_HIDE_INTERNAL_API - /** - * Returns the region code associated with the given zone, - * or NULL if the zone is not known. - * @param id zone id string - * @param status Status parameter - * @return the region associated with the given zone - * @internal - */ - static const UChar* getRegion(const UnicodeString& id, UErrorCode& status); -#endif /* U_HIDE_INTERNAL_API */ - - private: - /** - * Parses the given custom time zone identifier - * @param id id A string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or - * GMT[+-]hh. - * @param sign Receves parsed sign, 1 for positive, -1 for negative. - * @param hour Receives parsed hour field - * @param minute Receives parsed minute field - * @param second Receives parsed second field - * @return Returns TRUE when the given custom id is valid. - */ - static UBool parseCustomID(const UnicodeString& id, int32_t& sign, int32_t& hour, - int32_t& minute, int32_t& second); - - /** - * Parse a custom time zone identifier and return the normalized - * custom time zone identifier for the given custom id string. - * @param id a string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or - * GMT[+-]hh. - * @param normalized Receives the normalized custom ID - * @param status Receives the status. When the input ID string is invalid, - * U_ILLEGAL_ARGUMENT_ERROR is set. - * @return The normalized custom id string. - */ - static UnicodeString& getCustomID(const UnicodeString& id, UnicodeString& normalized, - UErrorCode& status); - - /** - * Returns the normalized custome time zone ID for the given offset fields. - * @param hour offset hours - * @param min offset minutes - * @param sec offset seconds - * @param negative sign of the offset, TRUE for negative offset. - * @param id Receves the format result (normalized custom ID) - * @return The reference to id - */ - static UnicodeString& formatCustomID(int32_t hour, int32_t min, int32_t sec, - UBool negative, UnicodeString& id); - - UnicodeString fID; // this time zone's ID - - friend class TZEnumeration; -}; - - -// ------------------------------------- - -inline UnicodeString& -TimeZone::getID(UnicodeString& ID) const -{ - ID = fID; - return ID; -} - -// ------------------------------------- - -inline void -TimeZone::setID(const UnicodeString& ID) -{ - fID = ID; -} -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif //_TIMEZONE -//eof diff --git a/win32/include/spidermonkey/unicode/tmunit.h b/win32/include/spidermonkey/unicode/tmunit.h deleted file mode 100755 index a19a1f3c..00000000 --- a/win32/include/spidermonkey/unicode/tmunit.h +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * Copyright (C) 2009-2016, International Business Machines Corporation, * - * Google, and others. All Rights Reserved. * - ******************************************************************************* - */ - -#ifndef __TMUNIT_H__ -#define __TMUNIT_H__ - - -/** - * \file - * \brief C++ API: time unit object - */ - - -#include "unicode/measunit.h" - -#if !UCONFIG_NO_FORMATTING - -U_NAMESPACE_BEGIN - -/** - * Measurement unit for time units. - * @see TimeUnitAmount - * @see TimeUnit - * @stable ICU 4.2 - */ -class U_I18N_API TimeUnit: public MeasureUnit { -public: - /** - * Constants for all the time units we supported. - * @stable ICU 4.2 - */ - enum UTimeUnitFields { - UTIMEUNIT_YEAR, - UTIMEUNIT_MONTH, - UTIMEUNIT_DAY, - UTIMEUNIT_WEEK, - UTIMEUNIT_HOUR, - UTIMEUNIT_MINUTE, - UTIMEUNIT_SECOND, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UTimeUnitFields value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UTIMEUNIT_FIELD_COUNT -#endif // U_HIDE_DEPRECATED_API - }; - - /** - * Create Instance. - * @param timeUnitField time unit field based on which the instance - * is created. - * @param status input-output error code. - * If the timeUnitField is invalid, - * then this will be set to U_ILLEGAL_ARGUMENT_ERROR. - * @return a TimeUnit instance - * @stable ICU 4.2 - */ - static TimeUnit* U_EXPORT2 createInstance(UTimeUnitFields timeUnitField, - UErrorCode& status); - - - /** - * Override clone. - * @stable ICU 4.2 - */ - virtual UObject* clone() const; - - /** - * Copy operator. - * @stable ICU 4.2 - */ - TimeUnit(const TimeUnit& other); - - /** - * Assignment operator. - * @stable ICU 4.2 - */ - TimeUnit& operator=(const TimeUnit& other); - - /** - * Returns a unique class ID for this object POLYMORPHICALLY. - * This method implements a simple form of RTTI used by ICU. - * @return The class ID for this object. All objects of a given - * class have the same class ID. Objects of other classes have - * different class IDs. - * @stable ICU 4.2 - */ - virtual UClassID getDynamicClassID() const; - - /** - * Returns the class ID for this class. This is used to compare to - * the return value of getDynamicClassID(). - * @return The class ID for all objects of this class. - * @stable ICU 4.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - - /** - * Get time unit field. - * @return time unit field. - * @stable ICU 4.2 - */ - UTimeUnitFields getTimeUnitField() const; - - /** - * Destructor. - * @stable ICU 4.2 - */ - virtual ~TimeUnit(); - -private: - UTimeUnitFields fTimeUnitField; - - /** - * Constructor - * @internal (private) - */ - TimeUnit(UTimeUnitFields timeUnitField); - -}; - - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // __TMUNIT_H__ -//eof -// diff --git a/win32/include/spidermonkey/unicode/tmutamt.h b/win32/include/spidermonkey/unicode/tmutamt.h deleted file mode 100755 index ff132f8a..00000000 --- a/win32/include/spidermonkey/unicode/tmutamt.h +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * Copyright (C) 2009-2010, Google, International Business Machines Corporation and * - * others. All Rights Reserved. * - ******************************************************************************* - */ - -#ifndef __TMUTAMT_H__ -#define __TMUTAMT_H__ - - -/** - * \file - * \brief C++ API: time unit amount object. - */ - -#include "unicode/measure.h" -#include "unicode/tmunit.h" - -#if !UCONFIG_NO_FORMATTING - -U_NAMESPACE_BEGIN - - -/** - * Express a duration as a time unit and number. Patterned after Currency. - * @see TimeUnitAmount - * @see TimeUnitFormat - * @stable ICU 4.2 - */ -class U_I18N_API TimeUnitAmount: public Measure { -public: - /** - * Construct TimeUnitAmount object with the given number and the - * given time unit. - * @param number a numeric object; number.isNumeric() must be TRUE - * @param timeUnitField the time unit field of a time unit - * @param status the input-output error code. - * If the number is not numeric or the timeUnitField - * is not valid, - * then this will be set to a failing value: - * U_ILLEGAL_ARGUMENT_ERROR. - * @stable ICU 4.2 - */ - TimeUnitAmount(const Formattable& number, - TimeUnit::UTimeUnitFields timeUnitField, - UErrorCode& status); - - /** - * Construct TimeUnitAmount object with the given numeric amount and the - * given time unit. - * @param amount a numeric amount. - * @param timeUnitField the time unit field on which a time unit amount - * object will be created. - * @param status the input-output error code. - * If the timeUnitField is not valid, - * then this will be set to a failing value: - * U_ILLEGAL_ARGUMENT_ERROR. - * @stable ICU 4.2 - */ - TimeUnitAmount(double amount, TimeUnit::UTimeUnitFields timeUnitField, - UErrorCode& status); - - - /** - * Copy constructor - * @stable ICU 4.2 - */ - TimeUnitAmount(const TimeUnitAmount& other); - - - /** - * Assignment operator - * @stable ICU 4.2 - */ - TimeUnitAmount& operator=(const TimeUnitAmount& other); - - - /** - * Clone. - * @return a polymorphic clone of this object. The result will have the same class as returned by getDynamicClassID(). - * @stable ICU 4.2 - */ - virtual UObject* clone() const; - - - /** - * Destructor - * @stable ICU 4.2 - */ - virtual ~TimeUnitAmount(); - - - /** - * Equality operator. - * @param other the object to compare to. - * @return true if this object is equal to the given object. - * @stable ICU 4.2 - */ - virtual UBool operator==(const UObject& other) const; - - - /** - * Not-equality operator. - * @param other the object to compare to. - * @return true if this object is not equal to the given object. - * @stable ICU 4.2 - */ - UBool operator!=(const UObject& other) const; - - - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 4.2 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 4.2 - */ - virtual UClassID getDynamicClassID(void) const; - - - /** - * Get the time unit. - * @return time unit object. - * @stable ICU 4.2 - */ - const TimeUnit& getTimeUnit() const; - - /** - * Get the time unit field value. - * @return time unit field value. - * @stable ICU 4.2 - */ - TimeUnit::UTimeUnitFields getTimeUnitField() const; -}; - - - -inline UBool -TimeUnitAmount::operator!=(const UObject& other) const { - return !operator==(other); -} - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // __TMUTAMT_H__ -//eof -// diff --git a/win32/include/spidermonkey/unicode/tmutfmt.h b/win32/include/spidermonkey/unicode/tmutfmt.h deleted file mode 100755 index b90d4a09..00000000 --- a/win32/include/spidermonkey/unicode/tmutfmt.h +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * Copyright (C) 2008-2014, Google, International Business Machines Corporation - * and others. All Rights Reserved. - ******************************************************************************* - */ - -#ifndef __TMUTFMT_H__ -#define __TMUTFMT_H__ - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Format and parse duration in single time unit - */ - - -#if !UCONFIG_NO_FORMATTING -#ifndef U_HIDE_DEPRECATED_API - -#include "unicode/unistr.h" -#include "unicode/tmunit.h" -#include "unicode/tmutamt.h" -#include "unicode/measfmt.h" -#include "unicode/numfmt.h" -#include "unicode/plurrule.h" - - -/** - * Constants for various styles. - * There are 2 styles: full name and abbreviated name. - * For example, for English, the full name for hour duration is "3 hours", - * and the abbreviated name is "3 hrs". - * @deprecated ICU 53 Use MeasureFormat and UMeasureFormatWidth instead. - */ -enum UTimeUnitFormatStyle { - /** @deprecated ICU 53 */ - UTMUTFMT_FULL_STYLE, - /** @deprecated ICU 53 */ - UTMUTFMT_ABBREVIATED_STYLE, - /** @deprecated ICU 53 */ - UTMUTFMT_FORMAT_STYLE_COUNT -}; -typedef enum UTimeUnitFormatStyle UTimeUnitFormatStyle; /**< @deprecated ICU 53 */ - - -U_NAMESPACE_BEGIN - -class Hashtable; -class UVector; - -struct TimeUnitFormatReadSink; - -/** - * Format or parse a TimeUnitAmount, using plural rules for the units where available. - * - *

- * Code Sample: - *

- *   // create time unit amount instance - a combination of Number and time unit
- *   UErrorCode status = U_ZERO_ERROR;
- *   TimeUnitAmount* source = new TimeUnitAmount(2, TimeUnit::UTIMEUNIT_YEAR, status);
- *   // create time unit format instance
- *   TimeUnitFormat* format = new TimeUnitFormat(Locale("en"), status);
- *   // format a time unit amount
- *   UnicodeString formatted;
- *   Formattable formattable;
- *   if (U_SUCCESS(status)) {
- *       formattable.adoptObject(source);
- *       formatted = ((Format*)format)->format(formattable, formatted, status);
- *       Formattable result;
- *       ((Format*)format)->parseObject(formatted, result, status);
- *       if (U_SUCCESS(status)) {
- *           assert (result == formattable);
- *       }
- *   }
- * 
- * - *

- * @see TimeUnitAmount - * @see TimeUnitFormat - * @deprecated ICU 53 Use the MeasureFormat class instead. - */ -class U_I18N_API TimeUnitFormat: public MeasureFormat { -public: - - /** - * Create TimeUnitFormat with default locale, and full name style. - * Use setLocale and/or setFormat to modify. - * @deprecated ICU 53 - */ - TimeUnitFormat(UErrorCode& status); - - /** - * Create TimeUnitFormat given locale, and full name style. - * @deprecated ICU 53 - */ - TimeUnitFormat(const Locale& locale, UErrorCode& status); - - /** - * Create TimeUnitFormat given locale and style. - * @deprecated ICU 53 - */ - TimeUnitFormat(const Locale& locale, UTimeUnitFormatStyle style, UErrorCode& status); - - /** - * Copy constructor. - * @deprecated ICU 53 - */ - TimeUnitFormat(const TimeUnitFormat&); - - /** - * deconstructor - * @deprecated ICU 53 - */ - virtual ~TimeUnitFormat(); - - /** - * Clone this Format object polymorphically. The caller owns the result and - * should delete it when done. - * @return A copy of the object. - * @deprecated ICU 53 - */ - virtual Format* clone(void) const; - - /** - * Assignment operator - * @deprecated ICU 53 - */ - TimeUnitFormat& operator=(const TimeUnitFormat& other); - - /** - * Return true if the given Format objects are not semantically equal. - * Objects of different subclasses are considered unequal. - * @param other the object to be compared with. - * @return true if the given Format objects are not semantically equal. - * @deprecated ICU 53 - */ - UBool operator!=(const Format& other) const; - - /** - * Set the locale used for formatting or parsing. - * @param locale the locale to be set - * @param status output param set to success/failure code on exit - * @deprecated ICU 53 - */ - void setLocale(const Locale& locale, UErrorCode& status); - - - /** - * Set the number format used for formatting or parsing. - * @param format the number formatter to be set - * @param status output param set to success/failure code on exit - * @deprecated ICU 53 - */ - void setNumberFormat(const NumberFormat& format, UErrorCode& status); - - /** - * Parse a TimeUnitAmount. - * @see Format#parseObject(const UnicodeString&, Formattable&, ParsePosition&) const; - * @deprecated ICU 53 - */ - virtual void parseObject(const UnicodeString& source, - Formattable& result, - ParsePosition& pos) const; - - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @deprecated ICU 53 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @deprecated ICU 53 - */ - virtual UClassID getDynamicClassID(void) const; - -private: - Hashtable* fTimeUnitToCountToPatterns[TimeUnit::UTIMEUNIT_FIELD_COUNT]; - UTimeUnitFormatStyle fStyle; - - void create(UTimeUnitFormatStyle style, UErrorCode& status); - - // it might actually be simpler to make them Decimal Formats later. - // initialize all private data members - void setup(UErrorCode& status); - - // initialize data member without fill in data for fTimeUnitToCountToPattern - void initDataMembers(UErrorCode& status); - - // initialize fTimeUnitToCountToPatterns from current locale's resource. - void readFromCurrentLocale(UTimeUnitFormatStyle style, const char* key, const UVector& pluralCounts, - UErrorCode& status); - - // check completeness of fTimeUnitToCountToPatterns against all time units, - // and all plural rules, fill in fallback as necessary. - void checkConsistency(UTimeUnitFormatStyle style, const char* key, UErrorCode& status); - - // fill in fTimeUnitToCountToPatterns from locale fall-back chain - void searchInLocaleChain(UTimeUnitFormatStyle style, const char* key, const char* localeName, - TimeUnit::UTimeUnitFields field, const UnicodeString&, - const char*, Hashtable*, UErrorCode&); - - // initialize hash table - Hashtable* initHash(UErrorCode& status); - - // delete hash table - void deleteHash(Hashtable* htable); - - // copy hash table - void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status); - // get time unit name, such as "year", from time unit field enum, such as - // UTIMEUNIT_YEAR. - static const char* getTimeUnitName(TimeUnit::UTimeUnitFields field, UErrorCode& status); - - friend struct TimeUnitFormatReadSink; -}; - -inline UBool -TimeUnitFormat::operator!=(const Format& other) const { - return !operator==(other); -} - -U_NAMESPACE_END - -#endif /* U_HIDE_DEPRECATED_API */ -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // __TMUTFMT_H__ -//eof diff --git a/win32/include/spidermonkey/unicode/translit.h b/win32/include/spidermonkey/unicode/translit.h deleted file mode 100755 index b0687910..00000000 --- a/win32/include/spidermonkey/unicode/translit.h +++ /dev/null @@ -1,1344 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1999-2014, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* Date Name Description -* 11/17/99 aliu Creation. -********************************************************************** -*/ -#ifndef TRANSLIT_H -#define TRANSLIT_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Tranforms text from one format to another. - */ - -#if !UCONFIG_NO_TRANSLITERATION - -#include "unicode/uobject.h" -#include "unicode/unistr.h" -#include "unicode/parseerr.h" -#include "unicode/utrans.h" // UTransPosition, UTransDirection -#include "unicode/strenum.h" - -U_NAMESPACE_BEGIN - -class UnicodeFilter; -class UnicodeSet; -class CompoundTransliterator; -class TransliteratorParser; -class NormalizationTransliterator; -class TransliteratorIDParser; - -/** - * - * Transliterator is an abstract class that - * transliterates text from one format to another. The most common - * kind of transliterator is a script, or alphabet, transliterator. - * For example, a Russian to Latin transliterator changes Russian text - * written in Cyrillic characters to phonetically equivalent Latin - * characters. It does not translate Russian to English! - * Transliteration, unlike translation, operates on characters, without - * reference to the meanings of words and sentences. - * - *

Although script conversion is its most common use, a - * transliterator can actually perform a more general class of tasks. - * In fact, Transliterator defines a very general API - * which specifies only that a segment of the input text is replaced - * by new text. The particulars of this conversion are determined - * entirely by subclasses of Transliterator. - * - *

Transliterators are stateless - * - *

Transliterator objects are stateless; they - * retain no information between calls to - * transliterate(). (However, this does not - * mean that threads may share transliterators without synchronizing - * them. Transliterators are not immutable, so they must be - * synchronized when shared between threads.) This might seem to - * limit the complexity of the transliteration operation. In - * practice, subclasses perform complex transliterations by delaying - * the replacement of text until it is known that no other - * replacements are possible. In other words, although the - * Transliterator objects are stateless, the source text - * itself embodies all the needed information, and delayed operation - * allows arbitrary complexity. - * - *

Batch transliteration - * - *

The simplest way to perform transliteration is all at once, on a - * string of existing text. This is referred to as batch - * transliteration. For example, given a string input - * and a transliterator t, the call - * - * \htmlonly

\endhtmlonlyString result = t.transliterate(input); - * \htmlonly
\endhtmlonly - * - * will transliterate it and return the result. Other methods allow - * the client to specify a substring to be transliterated and to use - * {@link Replaceable } objects instead of strings, in order to - * preserve out-of-band information (such as text styles). - * - *

Keyboard transliteration - * - *

Somewhat more involved is keyboard, or incremental - * transliteration. This is the transliteration of text that is - * arriving from some source (typically the user's keyboard) one - * character at a time, or in some other piecemeal fashion. - * - *

In keyboard transliteration, a Replaceable buffer - * stores the text. As text is inserted, as much as possible is - * transliterated on the fly. This means a GUI that displays the - * contents of the buffer may show text being modified as each new - * character arrives. - * - *

Consider the simple RuleBasedTransliterator: - * - * \htmlonly

\endhtmlonly - * th>{theta}
- * t>{tau} - *
\htmlonly
\endhtmlonly - * - * When the user types 't', nothing will happen, since the - * transliterator is waiting to see if the next character is 'h'. To - * remedy this, we introduce the notion of a cursor, marked by a '|' - * in the output string: - * - * \htmlonly
\endhtmlonly - * t>|{tau}
- * {tau}h>{theta} - *
\htmlonly
\endhtmlonly - * - * Now when the user types 't', tau appears, and if the next character - * is 'h', the tau changes to a theta. This is accomplished by - * maintaining a cursor position (independent of the insertion point, - * and invisible in the GUI) across calls to - * transliterate(). Typically, the cursor will - * be coincident with the insertion point, but in a case like the one - * above, it will precede the insertion point. - * - *

Keyboard transliteration methods maintain a set of three indices - * that are updated with each call to - * transliterate(), including the cursor, start, - * and limit. Since these indices are changed by the method, they are - * passed in an int[] array. The START index - * marks the beginning of the substring that the transliterator will - * look at. It is advanced as text becomes committed (but it is not - * the committed index; that's the CURSOR). The - * CURSOR index, described above, marks the point at - * which the transliterator last stopped, either because it reached - * the end, or because it required more characters to disambiguate - * between possible inputs. The CURSOR can also be - * explicitly set by rules in a RuleBasedTransliterator. - * Any characters before the CURSOR index are frozen; - * future keyboard transliteration calls within this input sequence - * will not change them. New text is inserted at the - * LIMIT index, which marks the end of the substring that - * the transliterator looks at. - * - *

Because keyboard transliteration assumes that more characters - * are to arrive, it is conservative in its operation. It only - * transliterates when it can do so unambiguously. Otherwise it waits - * for more characters to arrive. When the client code knows that no - * more characters are forthcoming, perhaps because the user has - * performed some input termination operation, then it should call - * finishTransliteration() to complete any - * pending transliterations. - * - *

Inverses - * - *

Pairs of transliterators may be inverses of one another. For - * example, if transliterator A transliterates characters by - * incrementing their Unicode value (so "abc" -> "def"), and - * transliterator B decrements character values, then A - * is an inverse of B and vice versa. If we compose A - * with B in a compound transliterator, the result is the - * indentity transliterator, that is, a transliterator that does not - * change its input text. - * - * The Transliterator method getInverse() - * returns a transliterator's inverse, if one exists, or - * null otherwise. However, the result of - * getInverse() usually will not be a true - * mathematical inverse. This is because true inverse transliterators - * are difficult to formulate. For example, consider two - * transliterators: AB, which transliterates the character 'A' - * to 'B', and BA, which transliterates 'B' to 'A'. It might - * seem that these are exact inverses, since - * - * \htmlonly

\endhtmlonly"A" x AB -> "B"
- * "B" x BA -> "A"\htmlonly
\endhtmlonly - * - * where 'x' represents transliteration. However, - * - * \htmlonly
\endhtmlonly"ABCD" x AB -> "BBCD"
- * "BBCD" x BA -> "AACD"\htmlonly
\endhtmlonly - * - * so AB composed with BA is not the - * identity. Nonetheless, BA may be usefully considered to be - * AB's inverse, and it is on this basis that - * AB.getInverse() could legitimately return - * BA. - * - *

IDs and display names - * - *

A transliterator is designated by a short identifier string or - * ID. IDs follow the format source-destination, - * where source describes the entity being replaced, and - * destination describes the entity replacing - * source. The entities may be the names of scripts, - * particular sequences of characters, or whatever else it is that the - * transliterator converts to or from. For example, a transliterator - * from Russian to Latin might be named "Russian-Latin". A - * transliterator from keyboard escape sequences to Latin-1 characters - * might be named "KeyboardEscape-Latin1". By convention, system - * entity names are in English, with the initial letters of words - * capitalized; user entity names may follow any format so long as - * they do not contain dashes. - * - *

In addition to programmatic IDs, transliterator objects have - * display names for presentation in user interfaces, returned by - * {@link #getDisplayName }. - * - *

Factory methods and registration - * - *

In general, client code should use the factory method - * {@link #createInstance } to obtain an instance of a - * transliterator given its ID. Valid IDs may be enumerated using - * getAvailableIDs(). Since transliterators are mutable, - * multiple calls to {@link #createInstance } with the same ID will - * return distinct objects. - * - *

In addition to the system transliterators registered at startup, - * user transliterators may be registered by calling - * registerInstance() at run time. A registered instance - * acts a template; future calls to {@link #createInstance } with the ID - * of the registered object return clones of that object. Thus any - * object passed to registerInstance() must implement - * clone() propertly. To register a transliterator subclass - * without instantiating it (until it is needed), users may call - * {@link #registerFactory }. In this case, the objects are - * instantiated by invoking the zero-argument public constructor of - * the class. - * - *

Subclassing - * - * Subclasses must implement the abstract method - * handleTransliterate().

Subclasses should override - * the transliterate() method taking a - * Replaceable and the transliterate() - * method taking a String and StringBuffer - * if the performance of these methods can be improved over the - * performance obtained by the default implementations in this class. - * - * @author Alan Liu - * @stable ICU 2.0 - */ -class U_I18N_API Transliterator : public UObject { - -private: - - /** - * Programmatic name, e.g., "Latin-Arabic". - */ - UnicodeString ID; - - /** - * This transliterator's filter. Any character for which - * filter.contains() returns false will not be - * altered by this transliterator. If filter is - * null then no filtering is applied. - */ - UnicodeFilter* filter; - - int32_t maximumContextLength; - - public: - - /** - * A context integer or pointer for a factory function, passed by - * value. - * @stable ICU 2.4 - */ - union Token { - /** - * This token, interpreted as a 32-bit integer. - * @stable ICU 2.4 - */ - int32_t integer; - /** - * This token, interpreted as a native pointer. - * @stable ICU 2.4 - */ - void* pointer; - }; - -#ifndef U_HIDE_INTERNAL_API - /** - * Return a token containing an integer. - * @return a token containing an integer. - * @internal - */ - inline static Token integerToken(int32_t); - - /** - * Return a token containing a pointer. - * @return a token containing a pointer. - * @internal - */ - inline static Token pointerToken(void*); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * A function that creates and returns a Transliterator. When - * invoked, it will be passed the ID string that is being - * instantiated, together with the context pointer that was passed - * in when the factory function was first registered. Many - * factory functions will ignore both parameters, however, - * functions that are registered to more than one ID may use the - * ID or the context parameter to parameterize the transliterator - * they create. - * @param ID the string identifier for this transliterator - * @param context a context pointer that will be stored and - * later passed to the factory function when an ID matching - * the registration ID is being instantiated with this factory. - * @stable ICU 2.4 - */ - typedef Transliterator* (U_EXPORT2 *Factory)(const UnicodeString& ID, Token context); - -protected: - - /** - * Default constructor. - * @param ID the string identifier for this transliterator - * @param adoptedFilter the filter. Any character for which - * filter.contains() returns false will not be - * altered by this transliterator. If filter is - * null then no filtering is applied. - * @stable ICU 2.4 - */ - Transliterator(const UnicodeString& ID, UnicodeFilter* adoptedFilter); - - /** - * Copy constructor. - * @stable ICU 2.4 - */ - Transliterator(const Transliterator&); - - /** - * Assignment operator. - * @stable ICU 2.4 - */ - Transliterator& operator=(const Transliterator&); - - /** - * Create a transliterator from a basic ID. This is an ID - * containing only the forward direction source, target, and - * variant. - * @param id a basic ID of the form S-T or S-T/V. - * @param canon canonical ID to assign to the object, or - * NULL to leave the ID unchanged - * @return a newly created Transliterator or null if the ID is - * invalid. - * @stable ICU 2.4 - */ - static Transliterator* createBasicInstance(const UnicodeString& id, - const UnicodeString* canon); - - friend class TransliteratorParser; // for parseID() - friend class TransliteratorIDParser; // for createBasicInstance() - friend class TransliteratorAlias; // for setID() - -public: - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~Transliterator(); - - /** - * Implements Cloneable. - * All subclasses are encouraged to implement this method if it is - * possible and reasonable to do so. Subclasses that are to be - * registered with the system using registerInstance() - * are required to implement this method. If a subclass does not - * implement clone() properly and is registered with the system - * using registerInstance(), then the default clone() implementation - * will return null, and calls to createInstance() will fail. - * - * @return a copy of the object. - * @see #registerInstance - * @stable ICU 2.0 - */ - virtual Transliterator* clone() const; - - /** - * Transliterates a segment of a string, with optional filtering. - * - * @param text the string to be transliterated - * @param start the beginning index, inclusive; 0 <= start - * <= limit. - * @param limit the ending index, exclusive; start <= limit - * <= text.length(). - * @return The new limit index. The text previously occupying [start, - * limit) has been transliterated, possibly to a string of a different - * length, at [start, new-limit), where - * new-limit is the return value. If the input offsets are out of bounds, - * the returned value is -1 and the input string remains unchanged. - * @stable ICU 2.0 - */ - virtual int32_t transliterate(Replaceable& text, - int32_t start, int32_t limit) const; - - /** - * Transliterates an entire string in place. Convenience method. - * @param text the string to be transliterated - * @stable ICU 2.0 - */ - virtual void transliterate(Replaceable& text) const; - - /** - * Transliterates the portion of the text buffer that can be - * transliterated unambiguosly after new text has been inserted, - * typically as a result of a keyboard event. The new text in - * insertion will be inserted into text - * at index.limit, advancing - * index.limit by insertion.length(). - * Then the transliterator will try to transliterate characters of - * text between index.cursor and - * index.limit. Characters before - * index.cursor will not be changed. - * - *

Upon return, values in index will be updated. - * index.start will be advanced to the first - * character that future calls to this method will read. - * index.cursor and index.limit will - * be adjusted to delimit the range of text that future calls to - * this method may change. - * - *

Typical usage of this method begins with an initial call - * with index.start and index.limit - * set to indicate the portion of text to be - * transliterated, and index.cursor == index.start. - * Thereafter, index can be used without - * modification in future calls, provided that all changes to - * text are made via this method. - * - *

This method assumes that future calls may be made that will - * insert new text into the buffer. As a result, it only performs - * unambiguous transliterations. After the last call to this - * method, there may be untransliterated text that is waiting for - * more input to resolve an ambiguity. In order to perform these - * pending transliterations, clients should call {@link - * #finishTransliteration } after the last call to this - * method has been made. - * - * @param text the buffer holding transliterated and untransliterated text - * @param index an array of three integers. - * - *

  • index.start: the beginning index, - * inclusive; 0 <= index.start <= index.limit. - * - *
  • index.limit: the ending index, exclusive; - * index.start <= index.limit <= text.length(). - * insertion is inserted at - * index.limit. - * - *
  • index.cursor: the next character to be - * considered for transliteration; index.start <= - * index.cursor <= index.limit. Characters before - * index.cursor will not be changed by future calls - * to this method.
- * - * @param insertion text to be inserted and possibly - * transliterated into the translation buffer at - * index.limit. If null then no text - * is inserted. - * @param status Output param to filled in with a success or an error. - * @see #handleTransliterate - * @exception IllegalArgumentException if index - * is invalid - * @see UTransPosition - * @stable ICU 2.0 - */ - virtual void transliterate(Replaceable& text, UTransPosition& index, - const UnicodeString& insertion, - UErrorCode& status) const; - - /** - * Transliterates the portion of the text buffer that can be - * transliterated unambiguosly after a new character has been - * inserted, typically as a result of a keyboard event. This is a - * convenience method. - * @param text the buffer holding transliterated and - * untransliterated text - * @param index an array of three integers. - * @param insertion text to be inserted and possibly - * transliterated into the translation buffer at - * index.limit. - * @param status Output param to filled in with a success or an error. - * @see #transliterate(Replaceable&, UTransPosition&, const UnicodeString&, UErrorCode&) const - * @stable ICU 2.0 - */ - virtual void transliterate(Replaceable& text, UTransPosition& index, - UChar32 insertion, - UErrorCode& status) const; - - /** - * Transliterates the portion of the text buffer that can be - * transliterated unambiguosly. This is a convenience method; see - * {@link - * #transliterate(Replaceable&, UTransPosition&, const UnicodeString&, UErrorCode&) const } - * for details. - * @param text the buffer holding transliterated and - * untransliterated text - * @param index an array of three integers. See {@link #transliterate(Replaceable&, UTransPosition&, const UnicodeString*, UErrorCode&) const }. - * @param status Output param to filled in with a success or an error. - * @see #transliterate(Replaceable, int[], String) - * @stable ICU 2.0 - */ - virtual void transliterate(Replaceable& text, UTransPosition& index, - UErrorCode& status) const; - - /** - * Finishes any pending transliterations that were waiting for - * more characters. Clients should call this method as the last - * call after a sequence of one or more calls to - * transliterate(). - * @param text the buffer holding transliterated and - * untransliterated text. - * @param index the array of indices previously passed to {@link - * #transliterate } - * @stable ICU 2.0 - */ - virtual void finishTransliteration(Replaceable& text, - UTransPosition& index) const; - -private: - - /** - * This internal method does incremental transliteration. If the - * 'insertion' is non-null then we append it to 'text' before - * proceeding. This method calls through to the pure virtual - * framework method handleTransliterate() to do the actual - * work. - * @param text the buffer holding transliterated and - * untransliterated text - * @param index an array of three integers. See {@link - * #transliterate(Replaceable, int[], String)}. - * @param insertion text to be inserted and possibly - * transliterated into the translation buffer at - * index.limit. - * @param status Output param to filled in with a success or an error. - */ - void _transliterate(Replaceable& text, - UTransPosition& index, - const UnicodeString* insertion, - UErrorCode &status) const; - -protected: - - /** - * Abstract method that concrete subclasses define to implement - * their transliteration algorithm. This method handles both - * incremental and non-incremental transliteration. Let - * originalStart refer to the value of - * pos.start upon entry. - * - *
    - *
  • If incremental is false, then this method - * should transliterate all characters between - * pos.start and pos.limit. Upon return - * pos.start must == pos.limit.
  • - * - *
  • If incremental is true, then this method - * should transliterate all characters between - * pos.start and pos.limit that can be - * unambiguously transliterated, regardless of future insertions - * of text at pos.limit. Upon return, - * pos.start should be in the range - * [originalStart, pos.limit). - * pos.start should be positioned such that - * characters [originalStart, - * pos.start) will not be changed in the future by this - * transliterator and characters [pos.start, - * pos.limit) are unchanged.
  • - *
- * - *

Implementations of this method should also obey the - * following invariants:

- * - *
    - *
  • pos.limit and pos.contextLimit - * should be updated to reflect changes in length of the text - * between pos.start and pos.limit. The - * difference pos.contextLimit - pos.limit should - * not change.
  • - * - *
  • pos.contextStart should not change.
  • - * - *
  • Upon return, neither pos.start nor - * pos.limit should be less than - * originalStart.
  • - * - *
  • Text before originalStart and text after - * pos.limit should not change.
  • - * - *
  • Text before pos.contextStart and text after - * pos.contextLimit should be ignored.
  • - *
- * - *

Subclasses may safely assume that all characters in - * [pos.start, pos.limit) are filtered. - * In other words, the filter has already been applied by the time - * this method is called. See - * filteredTransliterate(). - * - *

This method is not for public consumption. Calling - * this method directly will transliterate - * [pos.start, pos.limit) without - * applying the filter. End user code should call - * transliterate() instead of this method. Subclass code - * and wrapping transliterators should call - * filteredTransliterate() instead of this method.

- * - * @param text the buffer holding transliterated and - * untransliterated text - * - * @param pos the indices indicating the start, limit, context - * start, and context limit of the text. - * - * @param incremental if true, assume more text may be inserted at - * pos.limit and act accordingly. Otherwise, - * transliterate all text between pos.start and - * pos.limit and move pos.start up to - * pos.limit. - * - * @see #transliterate - * @stable ICU 2.4 - */ - virtual void handleTransliterate(Replaceable& text, - UTransPosition& pos, - UBool incremental) const = 0; - -public: - /** - * Transliterate a substring of text, as specified by index, taking filters - * into account. This method is for subclasses that need to delegate to - * another transliterator, such as CompoundTransliterator. - * @param text the text to be transliterated - * @param index the position indices - * @param incremental if TRUE, then assume more characters may be inserted - * at index.limit, and postpone processing to accomodate future incoming - * characters - * @stable ICU 2.4 - */ - virtual void filteredTransliterate(Replaceable& text, - UTransPosition& index, - UBool incremental) const; - -private: - - /** - * Top-level transliteration method, handling filtering, incremental and - * non-incremental transliteration, and rollback. All transliteration - * public API methods eventually call this method with a rollback argument - * of TRUE. Other entities may call this method but rollback should be - * FALSE. - * - *

If this transliterator has a filter, break up the input text into runs - * of unfiltered characters. Pass each run to - * subclass.handleTransliterate(). - * - *

In incremental mode, if rollback is TRUE, perform a special - * incremental procedure in which several passes are made over the input - * text, adding one character at a time, and committing successful - * transliterations as they occur. Unsuccessful transliterations are rolled - * back and retried with additional characters to give correct results. - * - * @param text the text to be transliterated - * @param index the position indices - * @param incremental if TRUE, then assume more characters may be inserted - * at index.limit, and postpone processing to accomodate future incoming - * characters - * @param rollback if TRUE and if incremental is TRUE, then perform special - * incremental processing, as described above, and undo partial - * transliterations where necessary. If incremental is FALSE then this - * parameter is ignored. - */ - virtual void filteredTransliterate(Replaceable& text, - UTransPosition& index, - UBool incremental, - UBool rollback) const; - -public: - - /** - * Returns the length of the longest context required by this transliterator. - * This is preceding context. The default implementation supplied - * by Transliterator returns zero; subclasses - * that use preceding context should override this method to return the - * correct value. For example, if a transliterator translates "ddd" (where - * d is any digit) to "555" when preceded by "(ddd)", then the preceding - * context length is 5, the length of "(ddd)". - * - * @return The maximum number of preceding context characters this - * transliterator needs to examine - * @stable ICU 2.0 - */ - int32_t getMaximumContextLength(void) const; - -protected: - - /** - * Method for subclasses to use to set the maximum context length. - * @param maxContextLength the new value to be set. - * @see #getMaximumContextLength - * @stable ICU 2.4 - */ - void setMaximumContextLength(int32_t maxContextLength); - -public: - - /** - * Returns a programmatic identifier for this transliterator. - * If this identifier is passed to createInstance(), it - * will return this object, if it has been registered. - * @return a programmatic identifier for this transliterator. - * @see #registerInstance - * @see #registerFactory - * @see #getAvailableIDs - * @stable ICU 2.0 - */ - virtual const UnicodeString& getID(void) const; - - /** - * Returns a name for this transliterator that is appropriate for - * display to the user in the default locale. See {@link - * #getDisplayName } for details. - * @param ID the string identifier for this transliterator - * @param result Output param to receive the display name - * @return A reference to 'result'. - * @stable ICU 2.0 - */ - static UnicodeString& U_EXPORT2 getDisplayName(const UnicodeString& ID, - UnicodeString& result); - - /** - * Returns a name for this transliterator that is appropriate for - * display to the user in the given locale. This name is taken - * from the locale resource data in the standard manner of the - * java.text package. - * - *

If no localized names exist in the system resource bundles, - * a name is synthesized using a localized - * MessageFormat pattern from the resource data. The - * arguments to this pattern are an integer followed by one or two - * strings. The integer is the number of strings, either 1 or 2. - * The strings are formed by splitting the ID for this - * transliterator at the first '-'. If there is no '-', then the - * entire ID forms the only string. - * @param ID the string identifier for this transliterator - * @param inLocale the Locale in which the display name should be - * localized. - * @param result Output param to receive the display name - * @return A reference to 'result'. - * @stable ICU 2.0 - */ - static UnicodeString& U_EXPORT2 getDisplayName(const UnicodeString& ID, - const Locale& inLocale, - UnicodeString& result); - - /** - * Returns the filter used by this transliterator, or NULL - * if this transliterator uses no filter. - * @return the filter used by this transliterator, or NULL - * if this transliterator uses no filter. - * @stable ICU 2.0 - */ - const UnicodeFilter* getFilter(void) const; - - /** - * Returns the filter used by this transliterator, or NULL if this - * transliterator uses no filter. The caller must eventually delete the - * result. After this call, this transliterator's filter is set to - * NULL. - * @return the filter used by this transliterator, or NULL if this - * transliterator uses no filter. - * @stable ICU 2.4 - */ - UnicodeFilter* orphanFilter(void); - - /** - * Changes the filter used by this transliterator. If the filter - * is set to null then no filtering will occur. - * - *

Callers must take care if a transliterator is in use by - * multiple threads. The filter should not be changed by one - * thread while another thread may be transliterating. - * @param adoptedFilter the new filter to be adopted. - * @stable ICU 2.0 - */ - void adoptFilter(UnicodeFilter* adoptedFilter); - - /** - * Returns this transliterator's inverse. See the class - * documentation for details. This implementation simply inverts - * the two entities in the ID and attempts to retrieve the - * resulting transliterator. That is, if getID() - * returns "A-B", then this method will return the result of - * createInstance("B-A"), or null if that - * call fails. - * - *

Subclasses with knowledge of their inverse may wish to - * override this method. - * - * @param status Output param to filled in with a success or an error. - * @return a transliterator that is an inverse, not necessarily - * exact, of this transliterator, or null if no such - * transliterator is registered. - * @see #registerInstance - * @stable ICU 2.0 - */ - Transliterator* createInverse(UErrorCode& status) const; - - /** - * Returns a Transliterator object given its ID. - * The ID must be either a system transliterator ID or a ID registered - * using registerInstance(). - * - * @param ID a valid ID, as enumerated by getAvailableIDs() - * @param dir either FORWARD or REVERSE. - * @param parseError Struct to recieve information on position - * of error if an error is encountered - * @param status Output param to filled in with a success or an error. - * @return A Transliterator object with the given ID - * @see #registerInstance - * @see #getAvailableIDs - * @see #getID - * @stable ICU 2.0 - */ - static Transliterator* U_EXPORT2 createInstance(const UnicodeString& ID, - UTransDirection dir, - UParseError& parseError, - UErrorCode& status); - - /** - * Returns a Transliterator object given its ID. - * The ID must be either a system transliterator ID or a ID registered - * using registerInstance(). - * @param ID a valid ID, as enumerated by getAvailableIDs() - * @param dir either FORWARD or REVERSE. - * @param status Output param to filled in with a success or an error. - * @return A Transliterator object with the given ID - * @stable ICU 2.0 - */ - static Transliterator* U_EXPORT2 createInstance(const UnicodeString& ID, - UTransDirection dir, - UErrorCode& status); - - /** - * Returns a Transliterator object constructed from - * the given rule string. This will be a RuleBasedTransliterator, - * if the rule string contains only rules, or a - * CompoundTransliterator, if it contains ID blocks, or a - * NullTransliterator, if it contains ID blocks which parse as - * empty for the given direction. - * @param ID the id for the transliterator. - * @param rules rules, separated by ';' - * @param dir either FORWARD or REVERSE. - * @param parseError Struct to recieve information on position - * of error if an error is encountered - * @param status Output param set to success/failure code. - * @stable ICU 2.0 - */ - static Transliterator* U_EXPORT2 createFromRules(const UnicodeString& ID, - const UnicodeString& rules, - UTransDirection dir, - UParseError& parseError, - UErrorCode& status); - - /** - * Create a rule string that can be passed to createFromRules() - * to recreate this transliterator. - * @param result the string to receive the rules. Previous - * contents will be deleted. - * @param escapeUnprintable if TRUE then convert unprintable - * character to their hex escape representations, \\uxxxx or - * \\Uxxxxxxxx. Unprintable characters are those other than - * U+000A, U+0020..U+007E. - * @stable ICU 2.0 - */ - virtual UnicodeString& toRules(UnicodeString& result, - UBool escapeUnprintable) const; - - /** - * Return the number of elements that make up this transliterator. - * For example, if the transliterator "NFD;Jamo-Latin;Latin-Greek" - * were created, the return value of this method would be 3. - * - *

If this transliterator is not composed of other - * transliterators, then this method returns 1. - * @return the number of transliterators that compose this - * transliterator, or 1 if this transliterator is not composed of - * multiple transliterators - * @stable ICU 3.0 - */ - int32_t countElements() const; - - /** - * Return an element that makes up this transliterator. For - * example, if the transliterator "NFD;Jamo-Latin;Latin-Greek" - * were created, the return value of this method would be one - * of the three transliterator objects that make up that - * transliterator: [NFD, Jamo-Latin, Latin-Greek]. - * - *

If this transliterator is not composed of other - * transliterators, then this method will return a reference to - * this transliterator when given the index 0. - * @param index a value from 0..countElements()-1 indicating the - * transliterator to return - * @param ec input-output error code - * @return one of the transliterators that makes up this - * transliterator, if this transliterator is made up of multiple - * transliterators, otherwise a reference to this object if given - * an index of 0 - * @stable ICU 3.0 - */ - const Transliterator& getElement(int32_t index, UErrorCode& ec) const; - - /** - * Returns the set of all characters that may be modified in the - * input text by this Transliterator. This incorporates this - * object's current filter; if the filter is changed, the return - * value of this function will change. The default implementation - * returns an empty set. Some subclasses may override {@link - * #handleGetSourceSet } to return a more precise result. The - * return result is approximate in any case and is intended for - * use by tests, tools, or utilities. - * @param result receives result set; previous contents lost - * @return a reference to result - * @see #getTargetSet - * @see #handleGetSourceSet - * @stable ICU 2.4 - */ - UnicodeSet& getSourceSet(UnicodeSet& result) const; - - /** - * Framework method that returns the set of all characters that - * may be modified in the input text by this Transliterator, - * ignoring the effect of this object's filter. The base class - * implementation returns the empty set. Subclasses that wish to - * implement this should override this method. - * @return the set of characters that this transliterator may - * modify. The set may be modified, so subclasses should return a - * newly-created object. - * @param result receives result set; previous contents lost - * @see #getSourceSet - * @see #getTargetSet - * @stable ICU 2.4 - */ - virtual void handleGetSourceSet(UnicodeSet& result) const; - - /** - * Returns the set of all characters that may be generated as - * replacement text by this transliterator. The default - * implementation returns the empty set. Some subclasses may - * override this method to return a more precise result. The - * return result is approximate in any case and is intended for - * use by tests, tools, or utilities requiring such - * meta-information. - * @param result receives result set; previous contents lost - * @return a reference to result - * @see #getTargetSet - * @stable ICU 2.4 - */ - virtual UnicodeSet& getTargetSet(UnicodeSet& result) const; - -public: - - /** - * Registers a factory function that creates transliterators of - * a given ID. - * - * Because ICU may choose to cache Transliterators internally, this must - * be called at application startup, prior to any calls to - * Transliterator::createXXX to avoid undefined behavior. - * - * @param id the ID being registered - * @param factory a function pointer that will be copied and - * called later when the given ID is passed to createInstance() - * @param context a context pointer that will be stored and - * later passed to the factory function when an ID matching - * the registration ID is being instantiated with this factory. - * @stable ICU 2.0 - */ - static void U_EXPORT2 registerFactory(const UnicodeString& id, - Factory factory, - Token context); - - /** - * Registers an instance obj of a subclass of - * Transliterator with the system. When - * createInstance() is called with an ID string that is - * equal to obj->getID(), then obj->clone() is - * returned. - * - * After this call the Transliterator class owns the adoptedObj - * and will delete it. - * - * Because ICU may choose to cache Transliterators internally, this must - * be called at application startup, prior to any calls to - * Transliterator::createXXX to avoid undefined behavior. - * - * @param adoptedObj an instance of subclass of - * Transliterator that defines clone() - * @see #createInstance - * @see #registerFactory - * @see #unregister - * @stable ICU 2.0 - */ - static void U_EXPORT2 registerInstance(Transliterator* adoptedObj); - - /** - * Registers an ID string as an alias of another ID string. - * That is, after calling this function, createInstance(aliasID) - * will return the same thing as createInstance(realID). - * This is generally used to create shorter, more mnemonic aliases - * for long compound IDs. - * - * @param aliasID The new ID being registered. - * @param realID The ID that the new ID is to be an alias for. - * This can be a compound ID and can include filters and should - * refer to transliterators that have already been registered with - * the framework, although this isn't checked. - * @stable ICU 3.6 - */ - static void U_EXPORT2 registerAlias(const UnicodeString& aliasID, - const UnicodeString& realID); - -protected: - -#ifndef U_HIDE_INTERNAL_API - /** - * @param id the ID being registered - * @param factory a function pointer that will be copied and - * called later when the given ID is passed to createInstance() - * @param context a context pointer that will be stored and - * later passed to the factory function when an ID matching - * the registration ID is being instantiated with this factory. - * @internal - */ - static void _registerFactory(const UnicodeString& id, - Factory factory, - Token context); - - /** - * @internal - */ - static void _registerInstance(Transliterator* adoptedObj); - - /** - * @internal - */ - static void _registerAlias(const UnicodeString& aliasID, const UnicodeString& realID); - - /** - * Register two targets as being inverses of one another. For - * example, calling registerSpecialInverse("NFC", "NFD", true) causes - * Transliterator to form the following inverse relationships: - * - *

NFC => NFD
-     * Any-NFC => Any-NFD
-     * NFD => NFC
-     * Any-NFD => Any-NFC
- * - * (Without the special inverse registration, the inverse of NFC - * would be NFC-Any.) Note that NFD is shorthand for Any-NFD, but - * that the presence or absence of "Any-" is preserved. - * - *

The relationship is symmetrical; registering (a, b) is - * equivalent to registering (b, a). - * - *

The relevant IDs must still be registered separately as - * factories or classes. - * - *

Only the targets are specified. Special inverses always - * have the form Any-Target1 <=> Any-Target2. The target should - * have canonical casing (the casing desired to be produced when - * an inverse is formed) and should contain no whitespace or other - * extraneous characters. - * - * @param target the target against which to register the inverse - * @param inverseTarget the inverse of target, that is - * Any-target.getInverse() => Any-inverseTarget - * @param bidirectional if true, register the reverse relation - * as well, that is, Any-inverseTarget.getInverse() => Any-target - * @internal - */ - static void _registerSpecialInverse(const UnicodeString& target, - const UnicodeString& inverseTarget, - UBool bidirectional); -#endif /* U_HIDE_INTERNAL_API */ - -public: - - /** - * Unregisters a transliterator or class. This may be either - * a system transliterator or a user transliterator or class. - * Any attempt to construct an unregistered transliterator based - * on its ID will fail. - * - * Because ICU may choose to cache Transliterators internally, this should - * be called during application shutdown, after all calls to - * Transliterator::createXXX to avoid undefined behavior. - * - * @param ID the ID of the transliterator or class - * @return the Object that was registered with - * ID, or null if none was - * @see #registerInstance - * @see #registerFactory - * @stable ICU 2.0 - */ - static void U_EXPORT2 unregister(const UnicodeString& ID); - -public: - - /** - * Return a StringEnumeration over the IDs available at the time of the - * call, including user-registered IDs. - * @param ec input-output error code - * @return a newly-created StringEnumeration over the transliterators - * available at the time of the call. The caller should delete this object - * when done using it. - * @stable ICU 3.0 - */ - static StringEnumeration* U_EXPORT2 getAvailableIDs(UErrorCode& ec); - - /** - * Return the number of registered source specifiers. - * @return the number of registered source specifiers. - * @stable ICU 2.0 - */ - static int32_t U_EXPORT2 countAvailableSources(void); - - /** - * Return a registered source specifier. - * @param index which specifier to return, from 0 to n-1, where - * n = countAvailableSources() - * @param result fill-in paramter to receive the source specifier. - * If index is out of range, result will be empty. - * @return reference to result - * @stable ICU 2.0 - */ - static UnicodeString& U_EXPORT2 getAvailableSource(int32_t index, - UnicodeString& result); - - /** - * Return the number of registered target specifiers for a given - * source specifier. - * @param source the given source specifier. - * @return the number of registered target specifiers for a given - * source specifier. - * @stable ICU 2.0 - */ - static int32_t U_EXPORT2 countAvailableTargets(const UnicodeString& source); - - /** - * Return a registered target specifier for a given source. - * @param index which specifier to return, from 0 to n-1, where - * n = countAvailableTargets(source) - * @param source the source specifier - * @param result fill-in paramter to receive the target specifier. - * If source is invalid or if index is out of range, result will - * be empty. - * @return reference to result - * @stable ICU 2.0 - */ - static UnicodeString& U_EXPORT2 getAvailableTarget(int32_t index, - const UnicodeString& source, - UnicodeString& result); - - /** - * Return the number of registered variant specifiers for a given - * source-target pair. - * @param source the source specifiers. - * @param target the target specifiers. - * @stable ICU 2.0 - */ - static int32_t U_EXPORT2 countAvailableVariants(const UnicodeString& source, - const UnicodeString& target); - - /** - * Return a registered variant specifier for a given source-target - * pair. - * @param index which specifier to return, from 0 to n-1, where - * n = countAvailableVariants(source, target) - * @param source the source specifier - * @param target the target specifier - * @param result fill-in paramter to receive the variant - * specifier. If source is invalid or if target is invalid or if - * index is out of range, result will be empty. - * @return reference to result - * @stable ICU 2.0 - */ - static UnicodeString& U_EXPORT2 getAvailableVariant(int32_t index, - const UnicodeString& source, - const UnicodeString& target, - UnicodeString& result); - -protected: - -#ifndef U_HIDE_INTERNAL_API - /** - * Non-mutexed internal method - * @internal - */ - static int32_t _countAvailableSources(void); - - /** - * Non-mutexed internal method - * @internal - */ - static UnicodeString& _getAvailableSource(int32_t index, - UnicodeString& result); - - /** - * Non-mutexed internal method - * @internal - */ - static int32_t _countAvailableTargets(const UnicodeString& source); - - /** - * Non-mutexed internal method - * @internal - */ - static UnicodeString& _getAvailableTarget(int32_t index, - const UnicodeString& source, - UnicodeString& result); - - /** - * Non-mutexed internal method - * @internal - */ - static int32_t _countAvailableVariants(const UnicodeString& source, - const UnicodeString& target); - - /** - * Non-mutexed internal method - * @internal - */ - static UnicodeString& _getAvailableVariant(int32_t index, - const UnicodeString& source, - const UnicodeString& target, - UnicodeString& result); -#endif /* U_HIDE_INTERNAL_API */ - -protected: - - /** - * Set the ID of this transliterators. Subclasses shouldn't do - * this, unless the underlying script behavior has changed. - * @param id the new id t to be set. - * @stable ICU 2.4 - */ - void setID(const UnicodeString& id); - -public: - - /** - * Return the class ID for this class. This is useful only for - * comparing to a return value from getDynamicClassID(). - * Note that Transliterator is an abstract base class, and therefor - * no fully constructed object will have a dynamic - * UCLassID that equals the UClassID returned from - * TRansliterator::getStaticClassID(). - * @return The class ID for class Transliterator. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID polymorphically. This method - * is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and - * clone() methods call this method. - * - *

Concrete subclasses of Transliterator must use the - * UOBJECT_DEFINE_RTTI_IMPLEMENTATION macro from - * uobject.h to provide the RTTI functions. - * - * @return The class ID for this object. All objects of a given - * class have the same class ID. Objects of other classes have - * different class IDs. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const = 0; - -private: - static UBool initializeRegistry(UErrorCode &status); - -public: -#ifndef U_HIDE_OBSOLETE_API - /** - * Return the number of IDs currently registered with the system. - * To retrieve the actual IDs, call getAvailableID(i) with - * i from 0 to countAvailableIDs() - 1. - * @return the number of IDs currently registered with the system. - * @obsolete ICU 3.4 use getAvailableIDs() instead - */ - static int32_t U_EXPORT2 countAvailableIDs(void); - - /** - * Return the index-th available ID. index must be between 0 - * and countAvailableIDs() - 1, inclusive. If index is out of - * range, the result of getAvailableID(0) is returned. - * @param index the given ID index. - * @return the index-th available ID. index must be between 0 - * and countAvailableIDs() - 1, inclusive. If index is out of - * range, the result of getAvailableID(0) is returned. - * @obsolete ICU 3.4 use getAvailableIDs() instead; this function - * is not thread safe, since it returns a reference to storage that - * may become invalid if another thread calls unregister - */ - static const UnicodeString& U_EXPORT2 getAvailableID(int32_t index); -#endif /* U_HIDE_OBSOLETE_API */ -}; - -inline int32_t Transliterator::getMaximumContextLength(void) const { - return maximumContextLength; -} - -inline void Transliterator::setID(const UnicodeString& id) { - ID = id; - // NUL-terminate the ID string, which is a non-aliased copy. - ID.append((UChar)0); - ID.truncate(ID.length()-1); -} - -#ifndef U_HIDE_INTERNAL_API -inline Transliterator::Token Transliterator::integerToken(int32_t i) { - Token t; - t.integer = i; - return t; -} - -inline Transliterator::Token Transliterator::pointerToken(void* p) { - Token t; - t.pointer = p; - return t; -} -#endif /* U_HIDE_INTERNAL_API */ - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_TRANSLITERATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/tzfmt.h b/win32/include/spidermonkey/unicode/tzfmt.h deleted file mode 100755 index faf4b814..00000000 --- a/win32/include/spidermonkey/unicode/tzfmt.h +++ /dev/null @@ -1,1097 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2011-2015, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -*/ -#ifndef __TZFMT_H -#define __TZFMT_H - -/** - * \file - * \brief C++ API: TimeZoneFormat - */ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/format.h" -#include "unicode/timezone.h" -#include "unicode/tznames.h" - -U_CDECL_BEGIN -/** - * Constants for time zone display format style used by format/parse APIs - * in TimeZoneFormat. - * @stable ICU 50 - */ -typedef enum UTimeZoneFormatStyle { - /** - * Generic location format, such as "United States Time (New York)", "Italy Time" - * @stable ICU 50 - */ - UTZFMT_STYLE_GENERIC_LOCATION, - /** - * Generic long non-location format, such as "Eastern Time". - * @stable ICU 50 - */ - UTZFMT_STYLE_GENERIC_LONG, - /** - * Generic short non-location format, such as "ET". - * @stable ICU 50 - */ - UTZFMT_STYLE_GENERIC_SHORT, - /** - * Specific long format, such as "Eastern Standard Time". - * @stable ICU 50 - */ - UTZFMT_STYLE_SPECIFIC_LONG, - /** - * Specific short format, such as "EST", "PDT". - * @stable ICU 50 - */ - UTZFMT_STYLE_SPECIFIC_SHORT, - /** - * Localized GMT offset format, such as "GMT-05:00", "UTC+0100" - * @stable ICU 50 - */ - UTZFMT_STYLE_LOCALIZED_GMT, - /** - * Short localized GMT offset format, such as "GMT-5", "UTC+1:30" - * This style is equivalent to the LDML date format pattern "O". - * @stable ICU 51 - */ - UTZFMT_STYLE_LOCALIZED_GMT_SHORT, - /** - * Short ISO 8601 local time difference (basic format) or the UTC indicator. - * For example, "-05", "+0530", and "Z"(UTC). - * This style is equivalent to the LDML date format pattern "X". - * @stable ICU 51 - */ - UTZFMT_STYLE_ISO_BASIC_SHORT, - /** - * Short ISO 8601 locale time difference (basic format). - * For example, "-05" and "+0530". - * This style is equivalent to the LDML date format pattern "x". - * @stable ICU 51 - */ - UTZFMT_STYLE_ISO_BASIC_LOCAL_SHORT, - /** - * Fixed width ISO 8601 local time difference (basic format) or the UTC indicator. - * For example, "-0500", "+0530", and "Z"(UTC). - * This style is equivalent to the LDML date format pattern "XX". - * @stable ICU 51 - */ - UTZFMT_STYLE_ISO_BASIC_FIXED, - /** - * Fixed width ISO 8601 local time difference (basic format). - * For example, "-0500" and "+0530". - * This style is equivalent to the LDML date format pattern "xx". - * @stable ICU 51 - */ - UTZFMT_STYLE_ISO_BASIC_LOCAL_FIXED, - /** - * ISO 8601 local time difference (basic format) with optional seconds field, or the UTC indicator. - * For example, "-0500", "+052538", and "Z"(UTC). - * This style is equivalent to the LDML date format pattern "XXXX". - * @stable ICU 51 - */ - UTZFMT_STYLE_ISO_BASIC_FULL, - /** - * ISO 8601 local time difference (basic format) with optional seconds field. - * For example, "-0500" and "+052538". - * This style is equivalent to the LDML date format pattern "xxxx". - * @stable ICU 51 - */ - UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL, - /** - * Fixed width ISO 8601 local time difference (extended format) or the UTC indicator. - * For example, "-05:00", "+05:30", and "Z"(UTC). - * This style is equivalent to the LDML date format pattern "XXX". - * @stable ICU 51 - */ - UTZFMT_STYLE_ISO_EXTENDED_FIXED, - /** - * Fixed width ISO 8601 local time difference (extended format). - * For example, "-05:00" and "+05:30". - * This style is equivalent to the LDML date format pattern "xxx" and "ZZZZZ". - * @stable ICU 51 - */ - UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FIXED, - /** - * ISO 8601 local time difference (extended format) with optional seconds field, or the UTC indicator. - * For example, "-05:00", "+05:25:38", and "Z"(UTC). - * This style is equivalent to the LDML date format pattern "XXXXX". - * @stable ICU 51 - */ - UTZFMT_STYLE_ISO_EXTENDED_FULL, - /** - * ISO 8601 local time difference (extended format) with optional seconds field. - * For example, "-05:00" and "+05:25:38". - * This style is equivalent to the LDML date format pattern "xxxxx". - * @stable ICU 51 - */ - UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FULL, - /** - * Time Zone ID, such as "America/Los_Angeles". - * @stable ICU 51 - */ - UTZFMT_STYLE_ZONE_ID, - /** - * Short Time Zone ID (BCP 47 Unicode location extension, time zone type value), such as "uslax". - * @stable ICU 51 - */ - UTZFMT_STYLE_ZONE_ID_SHORT, - /** - * Exemplar location, such as "Los Angeles" and "Paris". - * @stable ICU 51 - */ - UTZFMT_STYLE_EXEMPLAR_LOCATION -} UTimeZoneFormatStyle; - -/** - * Constants for GMT offset pattern types. - * @stable ICU 50 - */ -typedef enum UTimeZoneFormatGMTOffsetPatternType { - /** - * Positive offset with hours and minutes fields - * @stable ICU 50 - */ - UTZFMT_PAT_POSITIVE_HM, - /** - * Positive offset with hours, minutes and seconds fields - * @stable ICU 50 - */ - UTZFMT_PAT_POSITIVE_HMS, - /** - * Negative offset with hours and minutes fields - * @stable ICU 50 - */ - UTZFMT_PAT_NEGATIVE_HM, - /** - * Negative offset with hours, minutes and seconds fields - * @stable ICU 50 - */ - UTZFMT_PAT_NEGATIVE_HMS, - /** - * Positive offset with hours field - * @stable ICU 51 - */ - UTZFMT_PAT_POSITIVE_H, - /** - * Negative offset with hours field - * @stable ICU 51 - */ - UTZFMT_PAT_NEGATIVE_H, - - /* The following cannot be #ifndef U_HIDE_INTERNAL_API, needed for other .h declarations */ - /** - * Number of UTimeZoneFormatGMTOffsetPatternType types. - * @internal - */ - UTZFMT_PAT_COUNT = 6 -} UTimeZoneFormatGMTOffsetPatternType; - -/** - * Constants for time types used by TimeZoneFormat APIs for - * receiving time type (standard time, daylight time or unknown). - * @stable ICU 50 - */ -typedef enum UTimeZoneFormatTimeType { - /** - * Unknown - * @stable ICU 50 - */ - UTZFMT_TIME_TYPE_UNKNOWN, - /** - * Standard time - * @stable ICU 50 - */ - UTZFMT_TIME_TYPE_STANDARD, - /** - * Daylight saving time - * @stable ICU 50 - */ - UTZFMT_TIME_TYPE_DAYLIGHT -} UTimeZoneFormatTimeType; - -/** - * Constants for parse option flags, used for specifying optional parse behavior. - * @stable ICU 50 - */ -typedef enum UTimeZoneFormatParseOption { - /** - * No option. - * @stable ICU 50 - */ - UTZFMT_PARSE_OPTION_NONE = 0x00, - /** - * When a time zone display name is not found within a set of display names - * used for the specified style, look for the name from display names used - * by other styles. - * @stable ICU 50 - */ - UTZFMT_PARSE_OPTION_ALL_STYLES = 0x01, - /** - * When parsing a time zone display name in UTZFMT_STYLE_SPECIFIC_SHORT, - * look for the IANA tz database compatible zone abbreviations in addition - * to the localized names coming from the {@link TimeZoneNames} currently - * used by the {@link TimeZoneFormat}. - * @stable ICU 54 - */ - UTZFMT_PARSE_OPTION_TZ_DATABASE_ABBREVIATIONS = 0x02 -} UTimeZoneFormatParseOption; - -U_CDECL_END - -U_NAMESPACE_BEGIN - -class TimeZoneGenericNames; -class TZDBTimeZoneNames; -class UVector; - -/** - * TimeZoneFormat supports time zone display name formatting and parsing. - * An instance of TimeZoneFormat works as a subformatter of {@link SimpleDateFormat}, - * but you can also directly get a new instance of TimeZoneFormat and - * formatting/parsing time zone display names. - *

- * ICU implements the time zone display names defined by UTS#35 - * Unicode Locale Data Markup Language (LDML). {@link TimeZoneNames} represents the - * time zone display name data model and this class implements the algorithm for actual - * formatting and parsing. - * - * @see SimpleDateFormat - * @see TimeZoneNames - * @stable ICU 50 - */ -class U_I18N_API TimeZoneFormat : public Format { -public: - /** - * Copy constructor. - * @stable ICU 50 - */ - TimeZoneFormat(const TimeZoneFormat& other); - - /** - * Destructor. - * @stable ICU 50 - */ - virtual ~TimeZoneFormat(); - - /** - * Assignment operator. - * @stable ICU 50 - */ - TimeZoneFormat& operator=(const TimeZoneFormat& other); - - /** - * Return true if the given Format objects are semantically equal. - * Objects of different subclasses are considered unequal. - * @param other The object to be compared with. - * @return Return TRUE if the given Format objects are semantically equal. - * Objects of different subclasses are considered unequal. - * @stable ICU 50 - */ - virtual UBool operator==(const Format& other) const; - - /** - * Clone this object polymorphically. The caller is responsible - * for deleting the result when done. - * @return A copy of the object - * @stable ICU 50 - */ - virtual Format* clone() const; - - /** - * Creates an instance of TimeZoneFormat for the given locale. - * @param locale The locale. - * @param status Receives the status. - * @return An instance of TimeZoneFormat for the given locale, - * owned by the caller. - * @stable ICU 50 - */ - static TimeZoneFormat* U_EXPORT2 createInstance(const Locale& locale, UErrorCode& status); - - /** - * Returns the time zone display name data used by this instance. - * @return The time zone display name data. - * @stable ICU 50 - */ - const TimeZoneNames* getTimeZoneNames() const; - - /** - * Sets the time zone display name data to this format instnace. - * The caller should not delete the TimeZoenNames object after it is adopted - * by this call. - * @param tznames TimeZoneNames object to be adopted. - * @stable ICU 50 - */ - void adoptTimeZoneNames(TimeZoneNames *tznames); - - /** - * Sets the time zone display name data to this format instnace. - * @param tznames TimeZoneNames object to be set. - * @stable ICU 50 - */ - void setTimeZoneNames(const TimeZoneNames &tznames); - - /** - * Returns the localized GMT format pattern. - * @param pattern Receives the localized GMT format pattern. - * @return A reference to the result pattern. - * @see #setGMTPattern - * @stable ICU 50 - */ - UnicodeString& getGMTPattern(UnicodeString& pattern) const; - - /** - * Sets the localized GMT format pattern. The pattern must contain - * a single argument {0}, for example "GMT {0}". - * @param pattern The localized GMT format pattern to be used by this object. - * @param status Recieves the status. - * @see #getGMTPattern - * @stable ICU 50 - */ - void setGMTPattern(const UnicodeString& pattern, UErrorCode& status); - - /** - * Returns the offset pattern used for localized GMT format. - * @param type The offset pattern type enum. - * @param pattern Receives the offset pattern. - * @return A reference to the result pattern. - * @see #setGMTOffsetPattern - * @stable ICU 50 - */ - UnicodeString& getGMTOffsetPattern(UTimeZoneFormatGMTOffsetPatternType type, UnicodeString& pattern) const; - - /** - * Sets the offset pattern for the given offset type. - * @param type The offset pattern type enum. - * @param pattern The offset pattern used for localized GMT format for the type. - * @param status Receives the status. - * @see #getGMTOffsetPattern - * @stable ICU 50 - */ - void setGMTOffsetPattern(UTimeZoneFormatGMTOffsetPatternType type, const UnicodeString& pattern, UErrorCode& status); - - /** - * Returns the decimal digit characters used for localized GMT format. - * The return string contains exactly 10 code points (may include Unicode - * supplementary character) representing digit 0 to digit 9 in the ascending - * order. - * @param digits Receives the decimal digits used for localized GMT format. - * @see #setGMTOffsetDigits - * @stable ICU 50 - */ - UnicodeString& getGMTOffsetDigits(UnicodeString& digits) const; - - /** - * Sets the decimal digit characters used for localized GMT format. - * The input digits must contain exactly 10 code points - * (Unicode supplementary characters are also allowed) representing - * digit 0 to digit 9 in the ascending order. When the input digits - * does not satisfy the condition, U_ILLEGAL_ARGUMENT_ERROR - * will be set to the return status. - * @param digits The decimal digits used for localized GMT format. - * @param status Receives the status. - * @see #getGMTOffsetDigits - * @stable ICU 50 - */ - void setGMTOffsetDigits(const UnicodeString& digits, UErrorCode& status); - - /** - * Returns the localized GMT format string for GMT(UTC) itself (GMT offset is 0). - * @param gmtZeroFormat Receives the localized GMT string string for GMT(UTC) itself. - * @return A reference to the result GMT string. - * @see #setGMTZeroFormat - * @stable ICU 50 - */ - UnicodeString& getGMTZeroFormat(UnicodeString& gmtZeroFormat) const; - - /** - * Sets the localized GMT format string for GMT(UTC) itself (GMT offset is 0). - * @param gmtZeroFormat The localized GMT format string for GMT(UTC). - * @param status Receives the status. - * @see #getGMTZeroFormat - * @stable ICU 50 - */ - void setGMTZeroFormat(const UnicodeString& gmtZeroFormat, UErrorCode& status); - - /** - * Returns the bitwise flags of UTimeZoneFormatParseOption representing the default parse - * options used by this object. - * @return the default parse options. - * @see ParseOption - * @stable ICU 50 - */ - uint32_t getDefaultParseOptions(void) const; - - /** - * Sets the default parse options. - *

Note: By default, an instance of TimeZoneFormat - * created by {@link #createInstance} has no parse options set (UTZFMT_PARSE_OPTION_NONE). - * To specify multipe options, use bitwise flags of UTimeZoneFormatParseOption. - * @see #UTimeZoneFormatParseOption - * @stable ICU 50 - */ - void setDefaultParseOptions(uint32_t flags); - - /** - * Returns the ISO 8601 basic time zone string for the given offset. - * For example, "-08", "-0830" and "Z" - * - * @param offset the offset from GMT(UTC) in milliseconds. - * @param useUtcIndicator true if ISO 8601 UTC indicator "Z" is used when the offset is 0. - * @param isShort true if shortest form is used. - * @param ignoreSeconds true if non-zero offset seconds is appended. - * @param result Receives the ISO format string. - * @param status Receives the status - * @return the ISO 8601 basic format. - * @see #formatOffsetISO8601Extended - * @see #parseOffsetISO8601 - * @stable ICU 51 - */ - UnicodeString& formatOffsetISO8601Basic(int32_t offset, UBool useUtcIndicator, UBool isShort, UBool ignoreSeconds, - UnicodeString& result, UErrorCode& status) const; - - /** - * Returns the ISO 8601 extended time zone string for the given offset. - * For example, "-08:00", "-08:30" and "Z" - * - * @param offset the offset from GMT(UTC) in milliseconds. - * @param useUtcIndicator true if ISO 8601 UTC indicator "Z" is used when the offset is 0. - * @param isShort true if shortest form is used. - * @param ignoreSeconds true if non-zero offset seconds is appended. - * @param result Receives the ISO format string. - * @param status Receives the status - * @return the ISO 8601 basic format. - * @see #formatOffsetISO8601Extended - * @see #parseOffsetISO8601 - * @stable ICU 51 - */ - UnicodeString& formatOffsetISO8601Extended(int32_t offset, UBool useUtcIndicator, UBool isShort, UBool ignoreSeconds, - UnicodeString& result, UErrorCode& status) const; - - /** - * Returns the localized GMT(UTC) offset format for the given offset. - * The localized GMT offset is defined by; - *

    - *
  • GMT format pattern (e.g. "GMT {0}" - see {@link #getGMTPattern}) - *
  • Offset time pattern (e.g. "+HH:mm" - see {@link #getGMTOffsetPattern}) - *
  • Offset digits (e.g. "0123456789" - see {@link #getGMTOffsetDigits}) - *
  • GMT zero format (e.g. "GMT" - see {@link #getGMTZeroFormat}) - *
- * This format always uses 2 digit hours and minutes. When the given offset has non-zero - * seconds, 2 digit seconds field will be appended. For example, - * GMT+05:00 and GMT+05:28:06. - * @param offset the offset from GMT(UTC) in milliseconds. - * @param status Receives the status - * @param result Receives the localized GMT format string. - * @return A reference to the result. - * @see #parseOffsetLocalizedGMT - * @stable ICU 50 - */ - UnicodeString& formatOffsetLocalizedGMT(int32_t offset, UnicodeString& result, UErrorCode& status) const; - - /** - * Returns the short localized GMT(UTC) offset format for the given offset. - * The short localized GMT offset is defined by; - *
    - *
  • GMT format pattern (e.g. "GMT {0}" - see {@link #getGMTPattern}) - *
  • Offset time pattern (e.g. "+HH:mm" - see {@link #getGMTOffsetPattern}) - *
  • Offset digits (e.g. "0123456789" - see {@link #getGMTOffsetDigits}) - *
  • GMT zero format (e.g. "GMT" - see {@link #getGMTZeroFormat}) - *
- * This format uses the shortest representation of offset. The hours field does not - * have leading zero and lower fields with zero will be truncated. For example, - * GMT+5 and GMT+530. - * @param offset the offset from GMT(UTC) in milliseconds. - * @param status Receives the status - * @param result Receives the short localized GMT format string. - * @return A reference to the result. - * @see #parseOffsetShortLocalizedGMT - * @stable ICU 51 - */ - UnicodeString& formatOffsetShortLocalizedGMT(int32_t offset, UnicodeString& result, UErrorCode& status) const; - - using Format::format; - - /** - * Returns the display name of the time zone at the given date for the style. - * @param style The style (e.g. UTZFMT_STYLE_GENERIC_LONG, UTZFMT_STYLE_LOCALIZED_GMT...) - * @param tz The time zone. - * @param date The date. - * @param name Receives the display name. - * @param timeType the output argument for receiving the time type (standard/daylight/unknown) - * used for the display name, or NULL if the information is not necessary. - * @return A reference to the result - * @see #UTimeZoneFormatStyle - * @see #UTimeZoneFormatTimeType - * @stable ICU 50 - */ - virtual UnicodeString& format(UTimeZoneFormatStyle style, const TimeZone& tz, UDate date, - UnicodeString& name, UTimeZoneFormatTimeType* timeType = NULL) const; - - /** - * Returns offset from GMT(UTC) in milliseconds for the given ISO 8601 - * style time zone string. When the given string is not an ISO 8601 time zone - * string, this method sets the current position as the error index - * to ParsePosition pos and returns 0. - * @param text The text contains ISO8601 style time zone string (e.g. "-08:00", "Z") - * at the position. - * @param pos The ParsePosition object. - * @return The offset from GMT(UTC) in milliseconds for the given ISO 8601 style - * time zone string. - * @see #formatOffsetISO8601Basic - * @see #formatOffsetISO8601Extended - * @stable ICU 50 - */ - int32_t parseOffsetISO8601(const UnicodeString& text, ParsePosition& pos) const; - - /** - * Returns offset from GMT(UTC) in milliseconds for the given localized GMT - * offset format string. When the given string cannot be parsed, this method - * sets the current position as the error index to ParsePosition pos - * and returns 0. - * @param text The text contains a localized GMT offset string at the position. - * @param pos The ParsePosition object. - * @return The offset from GMT(UTC) in milliseconds for the given localized GMT - * offset format string. - * @see #formatOffsetLocalizedGMT - * @stable ICU 50 - */ - int32_t parseOffsetLocalizedGMT(const UnicodeString& text, ParsePosition& pos) const; - - /** - * Returns offset from GMT(UTC) in milliseconds for the given short localized GMT - * offset format string. When the given string cannot be parsed, this method - * sets the current position as the error index to ParsePosition pos - * and returns 0. - * @param text The text contains a short localized GMT offset string at the position. - * @param pos The ParsePosition object. - * @return The offset from GMT(UTC) in milliseconds for the given short localized GMT - * offset format string. - * @see #formatOffsetShortLocalizedGMT - * @stable ICU 51 - */ - int32_t parseOffsetShortLocalizedGMT(const UnicodeString& text, ParsePosition& pos) const; - - /** - * Returns a TimeZone by parsing the time zone string according to - * the given parse position, the specified format style and parse options. - * - * @param text The text contains a time zone string at the position. - * @param style The format style - * @param pos The position. - * @param parseOptions The parse options repesented by bitwise flags of UTimeZoneFormatParseOption. - * @param timeType The output argument for receiving the time type (standard/daylight/unknown), - * or NULL if the information is not necessary. - * @return A TimeZone, or null if the input could not be parsed. - * @see UTimeZoneFormatStyle - * @see UTimeZoneFormatParseOption - * @see UTimeZoneFormatTimeType - * @stable ICU 50 - */ - virtual TimeZone* parse(UTimeZoneFormatStyle style, const UnicodeString& text, ParsePosition& pos, - int32_t parseOptions, UTimeZoneFormatTimeType* timeType = NULL) const; - - /** - * Returns a TimeZone by parsing the time zone string according to - * the given parse position, the specified format style and the default parse options. - * - * @param text The text contains a time zone string at the position. - * @param style The format style - * @param pos The position. - * @param timeType The output argument for receiving the time type (standard/daylight/unknown), - * or NULL if the information is not necessary. - * @return A TimeZone, or null if the input could not be parsed. - * @see UTimeZoneFormatStyle - * @see UTimeZoneFormatParseOption - * @see UTimeZoneFormatTimeType - * @stable ICU 50 - */ - TimeZone* parse(UTimeZoneFormatStyle style, const UnicodeString& text, ParsePosition& pos, - UTimeZoneFormatTimeType* timeType = NULL) const; - - /* ---------------------------------------------- - * Format APIs - * ---------------------------------------------- */ - - /** - * Format an object to produce a time zone display string using localized GMT offset format. - * This method handles Formattable objects with a TimeZone. If a the Formattable - * object type is not a TimeZone, then it returns a failing UErrorCode. - * @param obj The object to format. Must be a TimeZone. - * @param appendTo Output parameter to receive result. Result is appended to existing contents. - * @param pos On input: an alignment field, if desired. On output: the offsets of the alignment field. - * @param status Output param filled with success/failure status. - * @return Reference to 'appendTo' parameter. - * @stable ICU 50 - */ - virtual UnicodeString& format(const Formattable& obj, UnicodeString& appendTo, - FieldPosition& pos, UErrorCode& status) const; - - /** - * Parse a string to produce an object. This methods handles parsing of - * time zone display strings into Formattable objects with TimeZone. - * @param source The string to be parsed into an object. - * @param result Formattable to be set to the parse result. If parse fails, return contents are undefined. - * @param parse_pos The position to start parsing at. Upon return this param is set to the position after the - * last character successfully parsed. If the source is not parsed successfully, this param - * will remain unchanged. - * @return A newly created Formattable* object, or NULL on failure. The caller owns this and should - * delete it when done. - * @stable ICU 50 - */ - virtual void parseObject(const UnicodeString& source, Formattable& result, ParsePosition& parse_pos) const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * @stable ICU 50 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * @stable ICU 50 - */ - virtual UClassID getDynamicClassID() const; - -protected: - /** - * Constructs a TimeZoneFormat object for the specified locale. - * @param locale the locale - * @param status receives the status. - * @stable ICU 50 - */ - TimeZoneFormat(const Locale& locale, UErrorCode& status); - -private: - /* Locale of this object */ - Locale fLocale; - - /* Stores the region (could be implicit default) */ - char fTargetRegion[ULOC_COUNTRY_CAPACITY]; - - /* TimeZoneNames object used by this formatter */ - TimeZoneNames* fTimeZoneNames; - - /* TimeZoneGenericNames object used by this formatter - lazily instantiated */ - TimeZoneGenericNames* fTimeZoneGenericNames; - - /* Localized GMT format pattern - e.g. "GMT{0}" */ - UnicodeString fGMTPattern; - - /* Array of offset patterns used by Localized GMT format - e.g. "+HH:mm" */ - UnicodeString fGMTOffsetPatterns[UTZFMT_PAT_COUNT]; - - /* Localized decimal digits used by Localized GMT format */ - UChar32 fGMTOffsetDigits[10]; - - /* Localized GMT zero format - e.g. "GMT" */ - UnicodeString fGMTZeroFormat; - - /* Bit flags representing parse options */ - uint32_t fDefParseOptionFlags; - - /* Constant parts of GMT format pattern, populated from localized GMT format pattern*/ - UnicodeString fGMTPatternPrefix; /* Substring before {0} */ - UnicodeString fGMTPatternSuffix; /* Substring after {0} */ - - /* Compiled offset patterns generated from fGMTOffsetPatterns[] */ - UVector* fGMTOffsetPatternItems[UTZFMT_PAT_COUNT]; - - UBool fAbuttingOffsetHoursAndMinutes; - - /* TZDBTimeZoneNames object used for parsing */ - TZDBTimeZoneNames* fTZDBTimeZoneNames; - - /** - * Returns the time zone's specific format string. - * @param tz the time zone - * @param stdType the name type used for standard time - * @param dstType the name type used for daylight time - * @param date the date - * @param name receives the time zone's specific format name string - * @param timeType when null, actual time type is set - * @return a reference to name. - */ - UnicodeString& formatSpecific(const TimeZone& tz, UTimeZoneNameType stdType, UTimeZoneNameType dstType, - UDate date, UnicodeString& name, UTimeZoneFormatTimeType *timeType) const; - - /** - * Returns the time zone's generic format string. - * @param tz the time zone - * @param genType the generic name type - * @param date the date - * @param name receives the time zone's generic format name string - * @return a reference to name. - */ - UnicodeString& formatGeneric(const TimeZone& tz, int32_t genType, UDate date, UnicodeString& name) const; - - /** - * Lazily create a TimeZoneGenericNames instance - * @param status receives the status - * @return the cached TimeZoneGenericNames. - */ - const TimeZoneGenericNames* getTimeZoneGenericNames(UErrorCode& status) const; - - /** - * Lazily create a TZDBTimeZoneNames instance - * @param status receives the status - * @return the cached TZDBTimeZoneNames. - */ - const TZDBTimeZoneNames* getTZDBTimeZoneNames(UErrorCode& status) const; - - /** - * Private method returning the time zone's exemplar location string. - * This method will never return empty. - * @param tz the time zone - * @param name receives the time zone's exemplar location name - * @return a reference to name. - */ - UnicodeString& formatExemplarLocation(const TimeZone& tz, UnicodeString& name) const; - - /** - * Private enum specifying a combination of offset fields - */ - enum OffsetFields { - FIELDS_H, - FIELDS_HM, - FIELDS_HMS - }; - - /** - * Parses the localized GMT pattern string and initialize - * localized gmt pattern fields. - * @param gmtPattern the localized GMT pattern string such as "GMT {0}" - * @param status U_ILLEGAL_ARGUMENT_ERROR is set when the specified pattern does not - * contain an argument "{0}". - */ - void initGMTPattern(const UnicodeString& gmtPattern, UErrorCode& status); - - /** - * Parse the GMT offset pattern into runtime optimized format. - * @param pattern the offset pattern string - * @param required the required set of fields, such as FIELDS_HM - * @param status U_ILLEGAL_ARGUMENT is set when the specified pattern does not contain - * pattern letters for the required fields. - * @return A list of GMTOffsetField objects, or NULL on error. - */ - static UVector* parseOffsetPattern(const UnicodeString& pattern, OffsetFields required, UErrorCode& status); - - /** - * Appends seconds field to the offset pattern with hour/minute - * Note: This code will be obsoleted once we add hour-minute-second pattern data in CLDR. - * @param offsetHM the offset pattern including hours and minutes fields - * @param result the output offset pattern including hour, minute and seconds fields - * @param status receives the status - * @return a reference to result - */ - static UnicodeString& expandOffsetPattern(const UnicodeString& offsetHM, UnicodeString& result, UErrorCode& status); - - /** - * Truncates minutes field to the offset pattern with hour/minute - * Note: This code will be obsoleted once we add hour pattern data in CLDR. - * @param offsetHM the offset pattern including hours and minutes fields - * @param result the output offset pattern including only hours field - * @param status receives the status - * @return a reference to result - */ - static UnicodeString& truncateOffsetPattern(const UnicodeString& offsetHM, UnicodeString& result, UErrorCode& status); - - /** - * Break input string into UChar32[]. Each array element represents - * a code point. This method is used for parsing localized digit - * characters and support characters in Unicode supplemental planes. - * @param str the string - * @param codeArray receives the result - * @param capacity the capacity of codeArray - * @return TRUE when the specified code array is fully filled with code points - * (no under/overflow). - */ - static UBool toCodePoints(const UnicodeString& str, UChar32* codeArray, int32_t capacity); - - /** - * Private method supprting all of ISO8601 formats - * @param offset the offset from GMT(UTC) in milliseconds. - * @param useUtcIndicator true if ISO 8601 UTC indicator "Z" is used when the offset is 0. - * @param isShort true if shortest form is used. - * @param ignoreSeconds true if non-zero offset seconds is appended. - * @param result Receives the result - * @param status Receives the status - * @return the ISO 8601 basic format. - */ - UnicodeString& formatOffsetISO8601(int32_t offset, UBool isBasic, UBool useUtcIndicator, - UBool isShort, UBool ignoreSeconds, UnicodeString& result, UErrorCode& status) const; - - /** - * Private method used for localized GMT formatting. - * @param offset the zone's UTC offset - * @param isShort true if the short localized GMT format is desired. - * @param result receives the localized GMT format string - * @param status receives the status - */ - UnicodeString& formatOffsetLocalizedGMT(int32_t offset, UBool isShort, UnicodeString& result, UErrorCode& status) const; - - /** - * Returns offset from GMT(UTC) in milliseconds for the given ISO 8601 style - * (extended format) time zone string. When the given string is not an ISO 8601 time - * zone string, this method sets the current position as the error index - * to ParsePosition pos and returns 0. - * @param text the text contains ISO 8601 style time zone string (e.g. "-08:00", "Z") - * at the position. - * @param pos the position, non-negative error index will be set on failure. - * @param extendedOnly TRUE if parsing the text as ISO 8601 extended offset format (e.g. "-08:00"), - * or FALSE to evaluate the text as basic format. - * @param hasDigitOffset receiving if the parsed zone string contains offset digits. - * @return the offset from GMT(UTC) in milliseconds for the given ISO 8601 style - * time zone string. - */ - int32_t parseOffsetISO8601(const UnicodeString& text, ParsePosition& pos, UBool extendedOnly, - UBool* hasDigitOffset = NULL) const; - - /** - * Appends localized digits to the buffer. - * This code assumes that the input number is 0 - 59 - * @param buf the target buffer - * @param n the integer number - * @param minDigits the minimum digits width - */ - void appendOffsetDigits(UnicodeString& buf, int32_t n, uint8_t minDigits) const; - - /** - * Returns offset from GMT(UTC) in milliseconds for the given localized GMT - * offset format string. When the given string cannot be parsed, this method - * sets the current position as the error index to ParsePosition pos - * and returns 0. - * @param text the text contains a localized GMT offset string at the position. - * @param pos the position, non-negative error index will be set on failure. - * @param isShort true if this parser to try the short format first - * @param hasDigitOffset receiving if the parsed zone string contains offset digits. - * @return the offset from GMT(UTC) in milliseconds for the given localized GMT - * offset format string. - */ - int32_t parseOffsetLocalizedGMT(const UnicodeString& text, ParsePosition& pos, - UBool isShort, UBool* hasDigitOffset) const; - - /** - * Parse localized GMT format generated by the patter used by this formatter, except - * GMT Zero format. - * @param text the input text - * @param start the start index - * @param isShort true if the short localized format is parsed. - * @param parsedLen receives the parsed length - * @return the parsed offset in milliseconds - */ - int32_t parseOffsetLocalizedGMTPattern(const UnicodeString& text, int32_t start, - UBool isShort, int32_t& parsedLen) const; - - /** - * Parses localized GMT offset fields into offset. - * @param text the input text - * @param start the start index - * @param isShort true if this is a short format - currently not used - * @param parsedLen the parsed length, or 0 on failure. - * @return the parsed offset in milliseconds. - */ - int32_t parseOffsetFields(const UnicodeString& text, int32_t start, UBool isShort, int32_t& parsedLen) const; - - /** - * Parse localized GMT offset fields with the given pattern. - * @param text the input text - * @param start the start index - * @param pattenItems the pattern (already itemized) - * @param forceSingleHourDigit true if hours field is parsed as a single digit - * @param hour receives the hour offset field - * @param min receives the minute offset field - * @param sec receives the second offset field - * @return the parsed length - */ - int32_t parseOffsetFieldsWithPattern(const UnicodeString& text, int32_t start, - UVector* patternItems, UBool forceSingleHourDigit, int32_t& hour, int32_t& min, int32_t& sec) const; - - /** - * Parses abutting localized GMT offset fields (such as 0800) into offset. - * @param text the input text - * @param start the start index - * @param parsedLen the parsed length, or 0 on failure - * @return the parsed offset in milliseconds. - */ - int32_t parseAbuttingOffsetFields(const UnicodeString& text, int32_t start, int32_t& parsedLen) const; - - /** - * Parses the input text using the default format patterns (e.g. "UTC{0}"). - * @param text the input text - * @param start the start index - * @param parsedLen the parsed length, or 0 on failure - * @return the parsed offset in milliseconds. - */ - int32_t parseOffsetDefaultLocalizedGMT(const UnicodeString& text, int start, int32_t& parsedLen) const; - - /** - * Parses the input GMT offset fields with the default offset pattern. - * @param text the input text - * @param start the start index - * @param separator the separator character, e.g. ':' - * @param parsedLen the parsed length, or 0 on failure. - * @return the parsed offset in milliseconds. - */ - int32_t parseDefaultOffsetFields(const UnicodeString& text, int32_t start, UChar separator, - int32_t& parsedLen) const; - - /** - * Reads an offset field value. This method will stop parsing when - * 1) number of digits reaches maxDigits - * 2) just before already parsed number exceeds maxVal - * - * @param text the text - * @param start the start offset - * @param minDigits the minimum number of required digits - * @param maxDigits the maximum number of digits - * @param minVal the minimum value - * @param maxVal the maximum value - * @param parsedLen the actual parsed length. - * @return the integer value parsed - */ - int32_t parseOffsetFieldWithLocalizedDigits(const UnicodeString& text, int32_t start, - uint8_t minDigits, uint8_t maxDigits, uint16_t minVal, uint16_t maxVal, int32_t& parsedLen) const; - - /** - * Reads a single decimal digit, either localized digits used by this object - * or any Unicode numeric character. - * @param text the text - * @param start the start index - * @param len the actual length read from the text - * the start index is not a decimal number. - * @return the integer value of the parsed digit, or -1 on failure. - */ - int32_t parseSingleLocalizedDigit(const UnicodeString& text, int32_t start, int32_t& len) const; - - /** - * Formats offset using ASCII digits. The input offset range must be - * within +/-24 hours (exclusive). - * @param offset The offset - * @param sep The field separator character or 0 if not required - * @param minFields The minimum fields - * @param maxFields The maximum fields - * @return The offset string - */ - static UnicodeString& formatOffsetWithAsciiDigits(int32_t offset, UChar sep, - OffsetFields minFields, OffsetFields maxFields, UnicodeString& result); - - /** - * Parses offset represented by contiguous ASCII digits. - *

- * Note: This method expects the input position is already at the start of - * ASCII digits and does not parse sign (+/-). - * @param text The text contains a sequence of ASCII digits - * @param pos The parse position - * @param minFields The minimum Fields to be parsed - * @param maxFields The maximum Fields to be parsed - * @param fixedHourWidth true if hours field must be width of 2 - * @return Parsed offset, 0 or positive number. - */ - static int32_t parseAbuttingAsciiOffsetFields(const UnicodeString& text, ParsePosition& pos, - OffsetFields minFields, OffsetFields maxFields, UBool fixedHourWidth); - - /** - * Parses offset represented by ASCII digits and separators. - *

- * Note: This method expects the input position is already at the start of - * ASCII digits and does not parse sign (+/-). - * @param text The text - * @param pos The parse position - * @param sep The separator character - * @param minFields The minimum Fields to be parsed - * @param maxFields The maximum Fields to be parsed - * @return Parsed offset, 0 or positive number. - */ - static int32_t parseAsciiOffsetFields(const UnicodeString& text, ParsePosition& pos, UChar sep, - OffsetFields minFields, OffsetFields maxFields); - - /** - * Unquotes the message format style pattern. - * @param pattern the pattern - * @param result receive the unquoted pattern. - * @return A reference to result. - */ - static UnicodeString& unquote(const UnicodeString& pattern, UnicodeString& result); - - /** - * Initialize localized GMT format offset hour/min/sec patterns. - * This method parses patterns into optimized run-time format. - * @param status receives the status. - */ - void initGMTOffsetPatterns(UErrorCode& status); - - /** - * Check if there are any GMT format offset patterns without - * any separators between hours field and minutes field and update - * fAbuttingOffsetHoursAndMinutes field. This method must be called - * after all patterns are parsed into pattern items. - */ - void checkAbuttingHoursAndMinutes(); - - /** - * Creates an instance of TimeZone for the given offset - * @param offset the offset - * @return A TimeZone with the given offset - */ - TimeZone* createTimeZoneForOffset(int32_t offset) const; - - /** - * Returns the time type for the given name type - * @param nameType the name type - * @return the time type (unknown/standard/daylight) - */ - static UTimeZoneFormatTimeType getTimeType(UTimeZoneNameType nameType); - - /** - * Returns the time zone ID of a match at the specified index within - * the MatchInfoCollection. - * @param matches the collection of matches - * @param idx the index withing matches - * @param tzID receives the resolved time zone ID - * @return a reference to tzID. - */ - UnicodeString& getTimeZoneID(const TimeZoneNames::MatchInfoCollection* matches, int32_t idx, UnicodeString& tzID) const; - - - /** - * Parse a zone ID. - * @param text the text contains a time zone ID string at the position. - * @param pos the position - * @param tzID receives the zone ID - * @return a reference to tzID - */ - UnicodeString& parseZoneID(const UnicodeString& text, ParsePosition& pos, UnicodeString& tzID) const; - - /** - * Parse a short zone ID. - * @param text the text contains a short time zone ID string at the position. - * @param pos the position - * @param tzID receives the short zone ID - * @return a reference to tzID - */ - UnicodeString& parseShortZoneID(const UnicodeString& text, ParsePosition& pos, UnicodeString& tzID) const; - - /** - * Parse an exemplar location string. - * @param text the text contains an exemplar location string at the position. - * @param pos the position. - * @param tzID receives the time zone ID - * @return a reference to tzID - */ - UnicodeString& parseExemplarLocation(const UnicodeString& text, ParsePosition& pos, UnicodeString& tzID) const; -}; - -U_NAMESPACE_END - -#endif /* !UCONFIG_NO_FORMATTING */ -#endif diff --git a/win32/include/spidermonkey/unicode/tznames.h b/win32/include/spidermonkey/unicode/tznames.h deleted file mode 100755 index 8861a7d0..00000000 --- a/win32/include/spidermonkey/unicode/tznames.h +++ /dev/null @@ -1,416 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2011-2016, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -*/ -#ifndef __TZNAMES_H -#define __TZNAMES_H - -/** - * \file - * \brief C++ API: TimeZoneNames - */ -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/uloc.h" -#include "unicode/unistr.h" - -U_CDECL_BEGIN - -/** - * Constants for time zone display name types. - * @stable ICU 50 - */ -typedef enum UTimeZoneNameType { - /** - * Unknown display name type. - * @stable ICU 50 - */ - UTZNM_UNKNOWN = 0x00, - /** - * Long display name, such as "Eastern Time". - * @stable ICU 50 - */ - UTZNM_LONG_GENERIC = 0x01, - /** - * Long display name for standard time, such as "Eastern Standard Time". - * @stable ICU 50 - */ - UTZNM_LONG_STANDARD = 0x02, - /** - * Long display name for daylight saving time, such as "Eastern Daylight Time". - * @stable ICU 50 - */ - UTZNM_LONG_DAYLIGHT = 0x04, - /** - * Short display name, such as "ET". - * @stable ICU 50 - */ - UTZNM_SHORT_GENERIC = 0x08, - /** - * Short display name for standard time, such as "EST". - * @stable ICU 50 - */ - UTZNM_SHORT_STANDARD = 0x10, - /** - * Short display name for daylight saving time, such as "EDT". - * @stable ICU 50 - */ - UTZNM_SHORT_DAYLIGHT = 0x20, - /** - * Exemplar location name, such as "Los Angeles". - * @stable ICU 51 - */ - UTZNM_EXEMPLAR_LOCATION = 0x40 -} UTimeZoneNameType; - -U_CDECL_END - -U_NAMESPACE_BEGIN - -class UVector; -struct MatchInfo; - -/** - * TimeZoneNames is an abstract class representing the time zone display name data model defined - * by UTS#35 Unicode Locale Data Markup Language (LDML). - * The model defines meta zone, which is used for storing a set of display names. A meta zone can be shared - * by multiple time zones. Also a time zone may have multiple meta zone historic mappings. - *

- * For example, people in the United States refer the zone used by the east part of North America as "Eastern Time". - * The tz database contains multiple time zones "America/New_York", "America/Detroit", "America/Montreal" and some - * others that belong to "Eastern Time". However, assigning different display names to these time zones does not make - * much sense for most of people. - *

- * In CLDR (which uses LDML for representing locale data), the display name - * "Eastern Time" is stored as long generic display name of a meta zone identified by the ID "America_Eastern". - * Then, there is another table maintaining the historic mapping to meta zones for each time zone. The time zones in - * the above example ("America/New_York", "America/Detroit"...) are mapped to the meta zone "America_Eastern". - *

- * Sometimes, a time zone is mapped to a different time zone in the past. For example, "America/Indiana/Knox" - * had been moving "Eastern Time" and "Central Time" back and forth. Therefore, it is necessary that time zone - * to meta zones mapping data are stored by date range. - * - *

Note: - * The methods in this class assume that time zone IDs are already canonicalized. For example, you may not get proper - * result returned by a method with time zone ID "America/Indiana/Indianapolis", because it's not a canonical time zone - * ID (the canonical time zone ID for the time zone is "America/Indianapolis". See - * {@link TimeZone#getCanonicalID(const UnicodeString& id, UnicodeString& canonicalID, UErrorCode& status)} about ICU - * canonical time zone IDs. - * - *

- * In CLDR, most of time zone display names except location names are provided through meta zones. But a time zone may - * have a specific name that is not shared with other time zones. - * - * For example, time zone "Europe/London" has English long name for standard time "Greenwich Mean Time", which is also - * shared with other time zones. However, the long name for daylight saving time is "British Summer Time", which is only - * used for "Europe/London". - * - *

- * {@link #getTimeZoneDisplayName} is designed for accessing a name only used by a single time zone. - * But is not necessarily mean that a subclass implementation use the same model with CLDR. A subclass implementation - * may provide time zone names only through {@link #getTimeZoneDisplayName}, or only through {@link #getMetaZoneDisplayName}, - * or both. - * - *

- * The default TimeZoneNames implementation returned by {@link #createInstance} - * uses the locale data imported from CLDR. In CLDR, set of meta zone IDs and mappings between zone IDs and meta zone - * IDs are shared by all locales. Therefore, the behavior of {@link #getAvailableMetaZoneIDs}, - * {@link #getMetaZoneID}, and {@link #getReferenceZoneID} won't be changed no matter - * what locale is used for getting an instance of TimeZoneNames. - * - * @stable ICU 50 - */ -class U_I18N_API TimeZoneNames : public UObject { -public: - /** - * Destructor. - * @stable ICU 50 - */ - virtual ~TimeZoneNames(); - - /** - * Return true if the given TimeZoneNames objects are semantically equal. - * @param other the object to be compared with. - * @return Return TRUE if the given Format objects are semantically equal. - * @stable ICU 50 - */ - virtual UBool operator==(const TimeZoneNames& other) const = 0; - - /** - * Return true if the given TimeZoneNames objects are not semantically - * equal. - * @param other the object to be compared with. - * @return Return TRUE if the given Format objects are not semantically equal. - * @stable ICU 50 - */ - UBool operator!=(const TimeZoneNames& other) const { return !operator==(other); } - - /** - * Clone this object polymorphically. The caller is responsible - * for deleting the result when done. - * @return A copy of the object - * @stable ICU 50 - */ - virtual TimeZoneNames* clone() const = 0; - - /** - * Returns an instance of TimeZoneNames for the specified locale. - * - * @param locale The locale. - * @param status Receives the status. - * @return An instance of TimeZoneNames - * @stable ICU 50 - */ - static TimeZoneNames* U_EXPORT2 createInstance(const Locale& locale, UErrorCode& status); - - /** - * Returns an instance of TimeZoneNames containing only short specific - * zone names (SHORT_STANDARD and SHORT_DAYLIGHT), - * compatible with the IANA tz database's zone abbreviations (not localized). - *
- * Note: The input locale is used for resolving ambiguous names (e.g. "IST" is parsed - * as Israel Standard Time for Israel, while it is parsed as India Standard Time for - * all other regions). The zone names returned by this instance are not localized. - * @stable ICU 54 - */ - static TimeZoneNames* U_EXPORT2 createTZDBInstance(const Locale& locale, UErrorCode& status); - - /** - * Returns an enumeration of all available meta zone IDs. - * @param status Receives the status. - * @return an enumeration object, owned by the caller. - * @stable ICU 50 - */ - virtual StringEnumeration* getAvailableMetaZoneIDs(UErrorCode& status) const = 0; - - /** - * Returns an enumeration of all available meta zone IDs used by the given time zone. - * @param tzID The canoical tiem zone ID. - * @param status Receives the status. - * @return an enumeration object, owned by the caller. - * @stable ICU 50 - */ - virtual StringEnumeration* getAvailableMetaZoneIDs(const UnicodeString& tzID, UErrorCode& status) const = 0; - - /** - * Returns the meta zone ID for the given canonical time zone ID at the given date. - * @param tzID The canonical time zone ID. - * @param date The date. - * @param mzID Receives the meta zone ID for the given time zone ID at the given date. If the time zone does not have a - * corresponding meta zone at the given date or the implementation does not support meta zones, "bogus" state - * is set. - * @return A reference to the result. - * @stable ICU 50 - */ - virtual UnicodeString& getMetaZoneID(const UnicodeString& tzID, UDate date, UnicodeString& mzID) const = 0; - - /** - * Returns the reference zone ID for the given meta zone ID for the region. - * - * Note: Each meta zone must have a reference zone associated with a special region "001" (world). - * Some meta zones may have region specific reference zone IDs other than the special region - * "001". When a meta zone does not have any region specific reference zone IDs, this method - * return the reference zone ID for the special region "001" (world). - * - * @param mzID The meta zone ID. - * @param region The region. - * @param tzID Receives the reference zone ID ("golden zone" in the LDML specification) for the given time zone ID for the - * region. If the meta zone is unknown or the implementation does not support meta zones, "bogus" state - * is set. - * @return A reference to the result. - * @stable ICU 50 - */ - virtual UnicodeString& getReferenceZoneID(const UnicodeString& mzID, const char* region, UnicodeString& tzID) const = 0; - - /** - * Returns the display name of the meta zone. - * @param mzID The meta zone ID. - * @param type The display name type. See {@link #UTimeZoneNameType}. - * @param name Receives the display name of the meta zone. When this object does not have a localized display name for the given - * meta zone with the specified type or the implementation does not provide any display names associated - * with meta zones, "bogus" state is set. - * @return A reference to the result. - * @stable ICU 50 - */ - virtual UnicodeString& getMetaZoneDisplayName(const UnicodeString& mzID, UTimeZoneNameType type, UnicodeString& name) const = 0; - - /** - * Returns the display name of the time zone. Unlike {@link #getDisplayName}, - * this method does not get a name from a meta zone used by the time zone. - * @param tzID The canonical time zone ID. - * @param type The display name type. See {@link #UTimeZoneNameType}. - * @param name Receives the display name for the time zone. When this object does not have a localized display name for the given - * time zone with the specified type, "bogus" state is set. - * @return A reference to the result. - * @stable ICU 50 - */ - virtual UnicodeString& getTimeZoneDisplayName(const UnicodeString& tzID, UTimeZoneNameType type, UnicodeString& name) const = 0; - - /** - * Returns the exemplar location name for the given time zone. When this object does not have a localized location - * name, the default implementation may still returns a programmatically generated name with the logic described - * below. - *

    - *
  1. Check if the ID contains "/". If not, return null. - *
  2. Check if the ID does not start with "Etc/" or "SystemV/". If it does, return null. - *
  3. Extract a substring after the last occurrence of "/". - *
  4. Replace "_" with " ". - *
- * For example, "New York" is returned for the time zone ID "America/New_York" when this object does not have the - * localized location name. - * - * @param tzID The canonical time zone ID - * @param name Receives the exemplar location name for the given time zone, or "bogus" state is set when a localized - * location name is not available and the fallback logic described above cannot extract location from the ID. - * @return A reference to the result. - * @stable ICU 50 - */ - virtual UnicodeString& getExemplarLocationName(const UnicodeString& tzID, UnicodeString& name) const; - - /** - * Returns the display name of the time zone at the given date. - *

- * Note: This method calls the subclass's {@link #getTimeZoneDisplayName} first. When the - * result is bogus, this method calls {@link #getMetaZoneID} to get the meta zone ID mapped from the - * time zone, then calls {@link #getMetaZoneDisplayName}. - * - * @param tzID The canonical time zone ID. - * @param type The display name type. See {@link #UTimeZoneNameType}. - * @param date The date. - * @param name Receives the display name for the time zone at the given date. When this object does not have a localized display - * name for the time zone with the specified type and date, "bogus" state is set. - * @return A reference to the result. - * @stable ICU 50 - */ - virtual UnicodeString& getDisplayName(const UnicodeString& tzID, UTimeZoneNameType type, UDate date, UnicodeString& name) const; - - /** - * @internal For specific users only until proposed publicly. - * @deprecated This API is ICU internal only. - */ - virtual void loadAllDisplayNames(UErrorCode& status); - - /** - * @internal For specific users only until proposed publicly. - * @deprecated This API is ICU internal only. - */ - virtual void getDisplayNames(const UnicodeString& tzID, const UTimeZoneNameType types[], int32_t numTypes, UDate date, UnicodeString dest[], UErrorCode& status) const; - - /** - * MatchInfoCollection represents a collection of time zone name matches used by - * {@link TimeZoneNames#find}. - * @internal - */ - class U_I18N_API MatchInfoCollection : public UMemory { - public: - /** - * Constructor. - * @internal - */ - MatchInfoCollection(); - /** - * Destructor. - * @internal - */ - virtual ~MatchInfoCollection(); - -#ifndef U_HIDE_INTERNAL_API - /** - * Adds a zone match. - * @param nameType The name type. - * @param matchLength The match length. - * @param tzID The time zone ID. - * @param status Receives the status - * @internal - */ - void addZone(UTimeZoneNameType nameType, int32_t matchLength, - const UnicodeString& tzID, UErrorCode& status); - - /** - * Adds a meata zone match. - * @param nameType The name type. - * @param matchLength The match length. - * @param mzID The metazone ID. - * @param status Receives the status - * @internal - */ - void addMetaZone(UTimeZoneNameType nameType, int32_t matchLength, - const UnicodeString& mzID, UErrorCode& status); - - /** - * Returns the number of entries available in this object. - * @return The number of entries. - * @internal - */ - int32_t size() const; - - /** - * Returns the time zone name type of a match at the specified index. - * @param idx The index - * @return The time zone name type. If the specified idx is out of range, - * it returns UTZNM_UNKNOWN. - * @see UTimeZoneNameType - * @internal - */ - UTimeZoneNameType getNameTypeAt(int32_t idx) const; - - /** - * Returns the match length of a match at the specified index. - * @param idx The index - * @return The match length. If the specified idx is out of range, - * it returns 0. - * @internal - */ - int32_t getMatchLengthAt(int32_t idx) const; - - /** - * Gets the zone ID of a match at the specified index. - * @param idx The index - * @param tzID Receives the zone ID. - * @return TRUE if the zone ID was set to tzID. - * @internal - */ - UBool getTimeZoneIDAt(int32_t idx, UnicodeString& tzID) const; - - /** - * Gets the metazone ID of a match at the specified index. - * @param idx The index - * @param mzID Receives the metazone ID - * @return TRUE if the meta zone ID was set to mzID. - * @internal - */ - UBool getMetaZoneIDAt(int32_t idx, UnicodeString& mzID) const; -#endif /* U_HIDE_INTERNAL_API */ - - private: - UVector* fMatches; // vector of MatchEntry - - UVector* matches(UErrorCode& status); - }; - - /** - * Finds time zone name prefix matches for the input text at the - * given offset and returns a collection of the matches. - * @param text The text. - * @param start The starting offset within the text. - * @param types The set of name types represented by bitwise flags of UTimeZoneNameType enums, - * or UTZNM_UNKNOWN for all name types. - * @param status Receives the status. - * @return A collection of matches (owned by the caller), or NULL if no matches are found. - * @see UTimeZoneNameType - * @see MatchInfoCollection - * @internal - */ - virtual MatchInfoCollection* find(const UnicodeString& text, int32_t start, uint32_t types, UErrorCode& status) const = 0; -}; - -U_NAMESPACE_END - -#endif -#endif diff --git a/win32/include/spidermonkey/unicode/tzrule.h b/win32/include/spidermonkey/unicode/tzrule.h deleted file mode 100755 index 51b3ae17..00000000 --- a/win32/include/spidermonkey/unicode/tzrule.h +++ /dev/null @@ -1,830 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2007-2008, International Business Machines Corporation and * -* others. All Rights Reserved. * -******************************************************************************* -*/ -#ifndef TZRULE_H -#define TZRULE_H - -/** - * \file - * \brief C++ API: Time zone rule classes - */ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/uobject.h" -#include "unicode/unistr.h" -#include "unicode/dtrule.h" - -U_NAMESPACE_BEGIN - -/** - * TimeZoneRule is a class representing a rule for time zone. - * TimeZoneRule has a set of time zone attributes, such as zone name, - * raw offset (UTC offset for standard time) and daylight saving time offset. - * - * @stable ICU 3.8 - */ -class U_I18N_API TimeZoneRule : public UObject { -public: - /** - * Destructor. - * @stable ICU 3.8 - */ - virtual ~TimeZoneRule(); - - /** - * Clone this TimeZoneRule object polymorphically. The caller owns the result and - * should delete it when done. - * @return A copy of the object. - * @stable ICU 3.8 - */ - virtual TimeZoneRule* clone(void) const = 0; - - /** - * Return true if the given TimeZoneRule objects are semantically equal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZoneRule objects are semantically equal. - * @stable ICU 3.8 - */ - virtual UBool operator==(const TimeZoneRule& that) const; - - /** - * Return true if the given TimeZoneRule objects are semantically unequal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZoneRule objects are semantically unequal. - * @stable ICU 3.8 - */ - virtual UBool operator!=(const TimeZoneRule& that) const; - - /** - * Fills in "name" with the name of this time zone. - * @param name Receives the name of this time zone. - * @return A reference to "name" - * @stable ICU 3.8 - */ - UnicodeString& getName(UnicodeString& name) const; - - /** - * Gets the standard time offset. - * @return The standard time offset from UTC in milliseconds. - * @stable ICU 3.8 - */ - int32_t getRawOffset(void) const; - - /** - * Gets the amount of daylight saving delta time from the standard time. - * @return The amount of daylight saving offset used by this rule - * in milliseconds. - * @stable ICU 3.8 - */ - int32_t getDSTSavings(void) const; - - /** - * Returns if this rule represents the same rule and offsets as another. - * When two TimeZoneRule objects differ only its names, this method - * returns true. - * @param other The TimeZoneRule object to be compared with. - * @return true if the other TimeZoneRule is the same as this one. - * @stable ICU 3.8 - */ - virtual UBool isEquivalentTo(const TimeZoneRule& other) const; - - /** - * Gets the very first time when this rule takes effect. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param result Receives the very first time when this rule takes effect. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const = 0; - - /** - * Gets the final time when this rule takes effect. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param result Receives the final time when this rule takes effect. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const = 0; - - /** - * Gets the first time when this rule takes effect after the specified time. - * @param base The first start time after this base time will be returned. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives The first time when this rule takes effect after - * the specified base time. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, - UBool inclusive, UDate& result) const = 0; - - /** - * Gets the most recent time when this rule takes effect before the specified time. - * @param base The most recent time before this base time will be returned. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives The most recent time when this rule takes effect before - * the specified base time. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, - UBool inclusive, UDate& result) const = 0; - -protected: - - /** - * Constructs a TimeZoneRule with the name, the GMT offset of its - * standard time and the amount of daylight saving offset adjustment. - * @param name The time zone name. - * @param rawOffset The UTC offset of its standard time in milliseconds. - * @param dstSavings The amount of daylight saving offset adjustment in milliseconds. - * If this ia a rule for standard time, the value of this argument is 0. - * @stable ICU 3.8 - */ - TimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings); - - /** - * Copy constructor. - * @param source The TimeZoneRule object to be copied. - * @stable ICU 3.8 - */ - TimeZoneRule(const TimeZoneRule& source); - - /** - * Assignment operator. - * @param right The object to be copied. - * @stable ICU 3.8 - */ - TimeZoneRule& operator=(const TimeZoneRule& right); - -private: - UnicodeString fName; // time name - int32_t fRawOffset; // UTC offset of the standard time in milliseconds - int32_t fDSTSavings; // DST saving amount in milliseconds -}; - -/** - * InitialTimeZoneRule represents a time zone rule - * representing a time zone effective from the beginning and - * has no actual start times. - * @stable ICU 3.8 - */ -class U_I18N_API InitialTimeZoneRule : public TimeZoneRule { -public: - /** - * Constructs an InitialTimeZoneRule with the name, the GMT offset of its - * standard time and the amount of daylight saving offset adjustment. - * @param name The time zone name. - * @param rawOffset The UTC offset of its standard time in milliseconds. - * @param dstSavings The amount of daylight saving offset adjustment in milliseconds. - * If this ia a rule for standard time, the value of this argument is 0. - * @stable ICU 3.8 - */ - InitialTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings); - - /** - * Copy constructor. - * @param source The InitialTimeZoneRule object to be copied. - * @stable ICU 3.8 - */ - InitialTimeZoneRule(const InitialTimeZoneRule& source); - - /** - * Destructor. - * @stable ICU 3.8 - */ - virtual ~InitialTimeZoneRule(); - - /** - * Clone this InitialTimeZoneRule object polymorphically. The caller owns the result and - * should delete it when done. - * @return A copy of the object. - * @stable ICU 3.8 - */ - virtual InitialTimeZoneRule* clone(void) const; - - /** - * Assignment operator. - * @param right The object to be copied. - * @stable ICU 3.8 - */ - InitialTimeZoneRule& operator=(const InitialTimeZoneRule& right); - - /** - * Return true if the given TimeZoneRule objects are semantically equal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZoneRule objects are semantically equal. - * @stable ICU 3.8 - */ - virtual UBool operator==(const TimeZoneRule& that) const; - - /** - * Return true if the given TimeZoneRule objects are semantically unequal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZoneRule objects are semantically unequal. - * @stable ICU 3.8 - */ - virtual UBool operator!=(const TimeZoneRule& that) const; - - /** - * Gets the time when this rule takes effect in the given year. - * @param year The Gregorian year, with 0 == 1 BCE, -1 == 2 BCE, etc. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param result Receives the start time in the year. - * @return true if this rule takes effect in the year and the result is set to - * "result". - * @stable ICU 3.8 - */ - UBool getStartInYear(int32_t year, int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const; - - /** - * Returns if this rule represents the same rule and offsets as another. - * When two TimeZoneRule objects differ only its names, this method - * returns true. - * @param that The TimeZoneRule object to be compared with. - * @return true if the other TimeZoneRule is equivalent to this one. - * @stable ICU 3.8 - */ - virtual UBool isEquivalentTo(const TimeZoneRule& that) const; - - /** - * Gets the very first time when this rule takes effect. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param result Receives the very first time when this rule takes effect. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const; - - /** - * Gets the final time when this rule takes effect. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param result Receives the final time when this rule takes effect. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const; - - /** - * Gets the first time when this rule takes effect after the specified time. - * @param base The first start time after this base time will be returned. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives The first time when this rule takes effect after - * the specified base time. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, - UBool inclusive, UDate& result) const; - - /** - * Gets the most recent time when this rule takes effect before the specified time. - * @param base The most recent time before this base time will be returned. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives The most recent time when this rule takes effect before - * the specified base time. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, - UBool inclusive, UDate& result) const; - -public: - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 3.8 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 3.8 - */ - virtual UClassID getDynamicClassID(void) const; -}; - -/** - * AnnualTimeZoneRule is a class used for representing a time zone - * rule which takes effect annually. The calenday system used for the rule is - * is based on Gregorian calendar - * - * @stable ICU 3.8 - */ -class U_I18N_API AnnualTimeZoneRule : public TimeZoneRule { -public: - /** - * The constant representing the maximum year used for designating - * a rule is permanent. - */ - static const int32_t MAX_YEAR; - - /** - * Constructs a AnnualTimeZoneRule with the name, the GMT offset of its - * standard time, the amount of daylight saving offset adjustment, the annual start - * time rule and the start/until years. The input DateTimeRule is copied by this - * constructor, so the caller remains responsible for deleting the object. - * @param name The time zone name. - * @param rawOffset The GMT offset of its standard time in milliseconds. - * @param dstSavings The amount of daylight saving offset adjustment in - * milliseconds. If this ia a rule for standard time, - * the value of this argument is 0. - * @param dateTimeRule The start date/time rule repeated annually. - * @param startYear The first year when this rule takes effect. - * @param endYear The last year when this rule takes effect. If this - * rule is effective forever in future, specify MAX_YEAR. - * @stable ICU 3.8 - */ - AnnualTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings, - const DateTimeRule& dateTimeRule, int32_t startYear, int32_t endYear); - - /** - * Constructs a AnnualTimeZoneRule with the name, the GMT offset of its - * standard time, the amount of daylight saving offset adjustment, the annual start - * time rule and the start/until years. The input DateTimeRule object is adopted - * by this object, therefore, the caller must not delete the object. - * @param name The time zone name. - * @param rawOffset The GMT offset of its standard time in milliseconds. - * @param dstSavings The amount of daylight saving offset adjustment in - * milliseconds. If this ia a rule for standard time, - * the value of this argument is 0. - * @param dateTimeRule The start date/time rule repeated annually. - * @param startYear The first year when this rule takes effect. - * @param endYear The last year when this rule takes effect. If this - * rule is effective forever in future, specify MAX_YEAR. - * @stable ICU 3.8 - */ - AnnualTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings, - DateTimeRule* dateTimeRule, int32_t startYear, int32_t endYear); - - /** - * Copy constructor. - * @param source The AnnualTimeZoneRule object to be copied. - * @stable ICU 3.8 - */ - AnnualTimeZoneRule(const AnnualTimeZoneRule& source); - - /** - * Destructor. - * @stable ICU 3.8 - */ - virtual ~AnnualTimeZoneRule(); - - /** - * Clone this AnnualTimeZoneRule object polymorphically. The caller owns the result and - * should delete it when done. - * @return A copy of the object. - * @stable ICU 3.8 - */ - virtual AnnualTimeZoneRule* clone(void) const; - - /** - * Assignment operator. - * @param right The object to be copied. - * @stable ICU 3.8 - */ - AnnualTimeZoneRule& operator=(const AnnualTimeZoneRule& right); - - /** - * Return true if the given TimeZoneRule objects are semantically equal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZoneRule objects are semantically equal. - * @stable ICU 3.8 - */ - virtual UBool operator==(const TimeZoneRule& that) const; - - /** - * Return true if the given TimeZoneRule objects are semantically unequal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZoneRule objects are semantically unequal. - * @stable ICU 3.8 - */ - virtual UBool operator!=(const TimeZoneRule& that) const; - - /** - * Gets the start date/time rule used by this rule. - * @return The AnnualDateTimeRule which represents the start date/time - * rule used by this time zone rule. - * @stable ICU 3.8 - */ - const DateTimeRule* getRule(void) const; - - /** - * Gets the first year when this rule takes effect. - * @return The start year of this rule. The year is in Gregorian calendar - * with 0 == 1 BCE, -1 == 2 BCE, etc. - * @stable ICU 3.8 - */ - int32_t getStartYear(void) const; - - /** - * Gets the end year when this rule takes effect. - * @return The end year of this rule (inclusive). The year is in Gregorian calendar - * with 0 == 1 BCE, -1 == 2 BCE, etc. - * @stable ICU 3.8 - */ - int32_t getEndYear(void) const; - - /** - * Gets the time when this rule takes effect in the given year. - * @param year The Gregorian year, with 0 == 1 BCE, -1 == 2 BCE, etc. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param result Receives the start time in the year. - * @return true if this rule takes effect in the year and the result is set to - * "result". - * @stable ICU 3.8 - */ - UBool getStartInYear(int32_t year, int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const; - - /** - * Returns if this rule represents the same rule and offsets as another. - * When two TimeZoneRule objects differ only its names, this method - * returns true. - * @param that The TimeZoneRule object to be compared with. - * @return true if the other TimeZoneRule is equivalent to this one. - * @stable ICU 3.8 - */ - virtual UBool isEquivalentTo(const TimeZoneRule& that) const; - - /** - * Gets the very first time when this rule takes effect. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param result Receives the very first time when this rule takes effect. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const; - - /** - * Gets the final time when this rule takes effect. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param result Receives the final time when this rule takes effect. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const; - - /** - * Gets the first time when this rule takes effect after the specified time. - * @param base The first start time after this base time will be returned. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives The first time when this rule takes effect after - * the specified base time. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, - UBool inclusive, UDate& result) const; - - /** - * Gets the most recent time when this rule takes effect before the specified time. - * @param base The most recent time before this base time will be returned. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives The most recent time when this rule takes effect before - * the specified base time. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, - UBool inclusive, UDate& result) const; - - -private: - DateTimeRule* fDateTimeRule; - int32_t fStartYear; - int32_t fEndYear; - -public: - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *
-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 3.8 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 3.8 - */ - virtual UClassID getDynamicClassID(void) const; -}; - -/** - * TimeArrayTimeZoneRule represents a time zone rule whose start times are - * defined by an array of milliseconds since the standard base time. - * - * @stable ICU 3.8 - */ -class U_I18N_API TimeArrayTimeZoneRule : public TimeZoneRule { -public: - /** - * Constructs a TimeArrayTimeZoneRule with the name, the GMT offset of its - * standard time, the amount of daylight saving offset adjustment and - * the array of times when this rule takes effect. - * @param name The time zone name. - * @param rawOffset The UTC offset of its standard time in milliseconds. - * @param dstSavings The amount of daylight saving offset adjustment in - * milliseconds. If this ia a rule for standard time, - * the value of this argument is 0. - * @param startTimes The array start times in milliseconds since the base time - * (January 1, 1970, 00:00:00). - * @param numStartTimes The number of elements in the parameter "startTimes" - * @param timeRuleType The time type of the start times, which is one of - * DataTimeRule::WALL_TIME, STANDARD_TIME - * and UTC_TIME. - * @stable ICU 3.8 - */ - TimeArrayTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings, - const UDate* startTimes, int32_t numStartTimes, DateTimeRule::TimeRuleType timeRuleType); - - /** - * Copy constructor. - * @param source The TimeArrayTimeZoneRule object to be copied. - * @stable ICU 3.8 - */ - TimeArrayTimeZoneRule(const TimeArrayTimeZoneRule& source); - - /** - * Destructor. - * @stable ICU 3.8 - */ - virtual ~TimeArrayTimeZoneRule(); - - /** - * Clone this TimeArrayTimeZoneRule object polymorphically. The caller owns the result and - * should delete it when done. - * @return A copy of the object. - * @stable ICU 3.8 - */ - virtual TimeArrayTimeZoneRule* clone(void) const; - - /** - * Assignment operator. - * @param right The object to be copied. - * @stable ICU 3.8 - */ - TimeArrayTimeZoneRule& operator=(const TimeArrayTimeZoneRule& right); - - /** - * Return true if the given TimeZoneRule objects are semantically equal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZoneRule objects are semantically equal. - * @stable ICU 3.8 - */ - virtual UBool operator==(const TimeZoneRule& that) const; - - /** - * Return true if the given TimeZoneRule objects are semantically unequal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZoneRule objects are semantically unequal. - * @stable ICU 3.8 - */ - virtual UBool operator!=(const TimeZoneRule& that) const; - - /** - * Gets the time type of the start times used by this rule. The return value - * is either DateTimeRule::WALL_TIME or STANDARD_TIME - * or UTC_TIME. - * - * @return The time type used of the start times used by this rule. - * @stable ICU 3.8 - */ - DateTimeRule::TimeRuleType getTimeType(void) const; - - /** - * Gets a start time at the index stored in this rule. - * @param index The index of start times - * @param result Receives the start time at the index - * @return true if the index is within the valid range and - * and the result is set. When false, the output - * parameger "result" is unchanged. - * @stable ICU 3.8 - */ - UBool getStartTimeAt(int32_t index, UDate& result) const; - - /** - * Returns the number of start times stored in this rule - * @return The number of start times. - * @stable ICU 3.8 - */ - int32_t countStartTimes(void) const; - - /** - * Returns if this rule represents the same rule and offsets as another. - * When two TimeZoneRule objects differ only its names, this method - * returns true. - * @param that The TimeZoneRule object to be compared with. - * @return true if the other TimeZoneRule is equivalent to this one. - * @stable ICU 3.8 - */ - virtual UBool isEquivalentTo(const TimeZoneRule& that) const; - - /** - * Gets the very first time when this rule takes effect. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param result Receives the very first time when this rule takes effect. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const; - - /** - * Gets the final time when this rule takes effect. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param result Receives the final time when this rule takes effect. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const; - - /** - * Gets the first time when this rule takes effect after the specified time. - * @param base The first start time after this base time will be returned. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives The first time when this rule takes effect after - * the specified base time. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, - UBool inclusive, UDate& result) const; - - /** - * Gets the most recent time when this rule takes effect before the specified time. - * @param base The most recent time before this base time will be returned. - * @param prevRawOffset The standard time offset from UTC before this rule - * takes effect in milliseconds. - * @param prevDSTSavings The amount of daylight saving offset from the - * standard time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives The most recent time when this rule takes effect before - * the specified base time. - * @return true if the start time is available. When false is returned, output parameter - * "result" is unchanged. - * @stable ICU 3.8 - */ - virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings, - UBool inclusive, UDate& result) const; - - -private: - enum { TIMEARRAY_STACK_BUFFER_SIZE = 32 }; - UBool initStartTimes(const UDate source[], int32_t size, UErrorCode& ec); - UDate getUTC(UDate time, int32_t raw, int32_t dst) const; - - DateTimeRule::TimeRuleType fTimeRuleType; - int32_t fNumStartTimes; - UDate* fStartTimes; - UDate fLocalStartTimes[TIMEARRAY_STACK_BUFFER_SIZE]; - -public: - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *
-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 3.8 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 3.8 - */ - virtual UClassID getDynamicClassID(void) const; -}; - - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // TZRULE_H - -//eof diff --git a/win32/include/spidermonkey/unicode/tztrans.h b/win32/include/spidermonkey/unicode/tztrans.h deleted file mode 100755 index 53c34fef..00000000 --- a/win32/include/spidermonkey/unicode/tztrans.h +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2007-2008, International Business Machines Corporation and * -* others. All Rights Reserved. * -******************************************************************************* -*/ -#ifndef TZTRANS_H -#define TZTRANS_H - -/** - * \file - * \brief C++ API: Time zone transition - */ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/uobject.h" - -U_NAMESPACE_BEGIN - -// Forward declaration -class TimeZoneRule; - -/** - * TimeZoneTransition is a class representing a time zone transition. - * An instance has a time of transition and rules for both before and after the transition. - * @stable ICU 3.8 - */ -class U_I18N_API TimeZoneTransition : public UObject { -public: - /** - * Constructs a TimeZoneTransition with the time and the rules before/after - * the transition. - * - * @param time The time of transition in milliseconds since the base time. - * @param from The time zone rule used before the transition. - * @param to The time zone rule used after the transition. - * @stable ICU 3.8 - */ - TimeZoneTransition(UDate time, const TimeZoneRule& from, const TimeZoneRule& to); - - /** - * Constructs an empty TimeZoneTransition - * @stable ICU 3.8 - */ - TimeZoneTransition(); - - /** - * Copy constructor. - * @param source The TimeZoneTransition object to be copied. - * @stable ICU 3.8 - */ - TimeZoneTransition(const TimeZoneTransition& source); - - /** - * Destructor. - * @stable ICU 3.8 - */ - ~TimeZoneTransition(); - - /** - * Clone this TimeZoneTransition object polymorphically. The caller owns the result and - * should delete it when done. - * @return A copy of the object. - * @stable ICU 3.8 - */ - TimeZoneTransition* clone(void) const; - - /** - * Assignment operator. - * @param right The object to be copied. - * @stable ICU 3.8 - */ - TimeZoneTransition& operator=(const TimeZoneTransition& right); - - /** - * Return true if the given TimeZoneTransition objects are semantically equal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZoneTransition objects are semantically equal. - * @stable ICU 3.8 - */ - UBool operator==(const TimeZoneTransition& that) const; - - /** - * Return true if the given TimeZoneTransition objects are semantically unequal. Objects - * of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZoneTransition objects are semantically unequal. - * @stable ICU 3.8 - */ - UBool operator!=(const TimeZoneTransition& that) const; - - /** - * Returns the time of transition in milliseconds. - * @return The time of the transition in milliseconds since the 1970 Jan 1 epoch time. - * @stable ICU 3.8 - */ - UDate getTime(void) const; - - /** - * Sets the time of transition in milliseconds. - * @param time The time of the transition in milliseconds since the 1970 Jan 1 epoch time. - * @stable ICU 3.8 - */ - void setTime(UDate time); - - /** - * Returns the rule used before the transition. - * @return The time zone rule used after the transition. - * @stable ICU 3.8 - */ - const TimeZoneRule* getFrom(void) const; - - /** - * Sets the rule used before the transition. The caller remains - * responsible for deleting the TimeZoneRule object. - * @param from The time zone rule used before the transition. - * @stable ICU 3.8 - */ - void setFrom(const TimeZoneRule& from); - - /** - * Adopts the rule used before the transition. The caller must - * not delete the TimeZoneRule object passed in. - * @param from The time zone rule used before the transition. - * @stable ICU 3.8 - */ - void adoptFrom(TimeZoneRule* from); - - /** - * Sets the rule used after the transition. The caller remains - * responsible for deleting the TimeZoneRule object. - * @param to The time zone rule used after the transition. - * @stable ICU 3.8 - */ - void setTo(const TimeZoneRule& to); - - /** - * Adopts the rule used after the transition. The caller must - * not delete the TimeZoneRule object passed in. - * @param to The time zone rule used after the transition. - * @stable ICU 3.8 - */ - void adoptTo(TimeZoneRule* to); - - /** - * Returns the rule used after the transition. - * @return The time zone rule used after the transition. - * @stable ICU 3.8 - */ - const TimeZoneRule* getTo(void) const; - -private: - UDate fTime; - TimeZoneRule* fFrom; - TimeZoneRule* fTo; - -public: - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *
-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 3.8 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 3.8 - */ - virtual UClassID getDynamicClassID(void) const; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // TZTRANS_H - -//eof diff --git a/win32/include/spidermonkey/unicode/ubidi.h b/win32/include/spidermonkey/unicode/ubidi.h deleted file mode 100755 index e5996986..00000000 --- a/win32/include/spidermonkey/unicode/ubidi.h +++ /dev/null @@ -1,2198 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 1999-2013, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* file name: ubidi.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 1999jul27 -* created by: Markus W. Scherer, updated by Matitiahu Allouche -*/ - -#ifndef UBIDI_H -#define UBIDI_H - -#include "unicode/utypes.h" -#include "unicode/uchar.h" -#include "unicode/localpointer.h" - -/** - *\file - * \brief C API: Bidi algorithm - * - *

Bidi algorithm for ICU

- * - * This is an implementation of the Unicode Bidirectional Algorithm. - * The algorithm is defined in the - * Unicode Standard Annex #9.

- * - * Note: Libraries that perform a bidirectional algorithm and - * reorder strings accordingly are sometimes called "Storage Layout Engines". - * ICU's Bidi and shaping (u_shapeArabic()) APIs can be used at the core of such - * "Storage Layout Engines". - * - *

General remarks about the API:

- * - * In functions with an error code parameter, - * the pErrorCode pointer must be valid - * and the value that it points to must not indicate a failure before - * the function call. Otherwise, the function returns immediately. - * After the function call, the value indicates success or failure.

- * - * The "limit" of a sequence of characters is the position just after their - * last character, i.e., one more than that position.

- * - * Some of the API functions provide access to "runs". - * Such a "run" is defined as a sequence of characters - * that are at the same embedding level - * after performing the Bidi algorithm.

- * - * @author Markus W. Scherer - * @version 1.0 - * - * - *

Sample code for the ICU Bidi API

- * - *
Rendering a paragraph with the ICU Bidi API
- * - * This is (hypothetical) sample code that illustrates - * how the ICU Bidi API could be used to render a paragraph of text. - * Rendering code depends highly on the graphics system, - * therefore this sample code must make a lot of assumptions, - * which may or may not match any existing graphics system's properties. - * - *

The basic assumptions are:

- *
    - *
  • Rendering is done from left to right on a horizontal line.
  • - *
  • A run of single-style, unidirectional text can be rendered at once.
  • - *
  • Such a run of text is passed to the graphics system with - * characters (code units) in logical order.
  • - *
  • The line-breaking algorithm is very complicated - * and Locale-dependent - - * and therefore its implementation omitted from this sample code.
  • - *
- * - *
- * \code
- *#include "unicode/ubidi.h"
- *
- *typedef enum {
- *     styleNormal=0, styleSelected=1,
- *     styleBold=2, styleItalics=4,
- *     styleSuper=8, styleSub=16
- *} Style;
- *
- *typedef struct { int32_t limit; Style style; } StyleRun;
- *
- *int getTextWidth(const UChar *text, int32_t start, int32_t limit,
- *                  const StyleRun *styleRuns, int styleRunCount);
- *
- * // set *pLimit and *pStyleRunLimit for a line
- * // from text[start] and from styleRuns[styleRunStart]
- * // using ubidi_getLogicalRun(para, ...)
- *void getLineBreak(const UChar *text, int32_t start, int32_t *pLimit,
- *                  UBiDi *para,
- *                  const StyleRun *styleRuns, int styleRunStart, int *pStyleRunLimit,
- *                  int *pLineWidth);
- *
- * // render runs on a line sequentially, always from left to right
- *
- * // prepare rendering a new line
- * void startLine(UBiDiDirection textDirection, int lineWidth);
- *
- * // render a run of text and advance to the right by the run width
- * // the text[start..limit-1] is always in logical order
- * void renderRun(const UChar *text, int32_t start, int32_t limit,
- *               UBiDiDirection textDirection, Style style);
- *
- * // We could compute a cross-product
- * // from the style runs with the directional runs
- * // and then reorder it.
- * // Instead, here we iterate over each run type
- * // and render the intersections -
- * // with shortcuts in simple (and common) cases.
- * // renderParagraph() is the main function.
- *
- * // render a directional run with
- * // (possibly) multiple style runs intersecting with it
- * void renderDirectionalRun(const UChar *text,
- *                           int32_t start, int32_t limit,
- *                           UBiDiDirection direction,
- *                           const StyleRun *styleRuns, int styleRunCount) {
- *     int i;
- *
- *     // iterate over style runs
- *     if(direction==UBIDI_LTR) {
- *         int styleLimit;
- *
- *         for(i=0; ilimit) { styleLimit=limit; }
- *                 renderRun(text, start, styleLimit,
- *                           direction, styleRun[i].style);
- *                 if(styleLimit==limit) { break; }
- *                 start=styleLimit;
- *             }
- *         }
- *     } else {
- *         int styleStart;
- *
- *         for(i=styleRunCount-1; i>=0; --i) {
- *             if(i>0) {
- *                 styleStart=styleRun[i-1].limit;
- *             } else {
- *                 styleStart=0;
- *             }
- *             if(limit>=styleStart) {
- *                 if(styleStart=length
- *
- *         width=getTextWidth(text, 0, length, styleRuns, styleRunCount);
- *         if(width<=lineWidth) {
- *             // everything fits onto one line
- *
- *            // prepare rendering a new line from either left or right
- *             startLine(paraLevel, width);
- *
- *             renderLine(para, text, 0, length,
- *                        styleRuns, styleRunCount);
- *         } else {
- *             UBiDi *line;
- *
- *             // we need to render several lines
- *             line=ubidi_openSized(length, 0, pErrorCode);
- *             if(line!=NULL) {
- *                 int32_t start=0, limit;
- *                 int styleRunStart=0, styleRunLimit;
- *
- *                 for(;;) {
- *                     limit=length;
- *                     styleRunLimit=styleRunCount;
- *                     getLineBreak(text, start, &limit, para,
- *                                  styleRuns, styleRunStart, &styleRunLimit,
- *                                 &width);
- *                     ubidi_setLine(para, start, limit, line, pErrorCode);
- *                     if(U_SUCCESS(*pErrorCode)) {
- *                         // prepare rendering a new line
- *                         // from either left or right
- *                         startLine(paraLevel, width);
- *
- *                         renderLine(line, text, start, limit,
- *                                    styleRuns+styleRunStart,
- *                                    styleRunLimit-styleRunStart);
- *                     }
- *                     if(limit==length) { break; }
- *                     start=limit;
- *                     styleRunStart=styleRunLimit-1;
- *                     if(start>=styleRuns[styleRunStart].limit) {
- *                         ++styleRunStart;
- *                     }
- *                 }
- *
- *                 ubidi_close(line);
- *             }
- *        }
- *    }
- *
- *     ubidi_close(para);
- *}
- *\endcode
- * 
- */ - -/*DOCXX_TAG*/ -/*@{*/ - -/** - * UBiDiLevel is the type of the level values in this - * Bidi implementation. - * It holds an embedding level and indicates the visual direction - * by its bit 0 (even/odd value).

- * - * It can also hold non-level values for the - * paraLevel and embeddingLevels - * arguments of ubidi_setPara(); there: - *

    - *
  • bit 7 of an embeddingLevels[] - * value indicates whether the using application is - * specifying the level of a character to override whatever the - * Bidi implementation would resolve it to.
  • - *
  • paraLevel can be set to the - * pseudo-level values UBIDI_DEFAULT_LTR - * and UBIDI_DEFAULT_RTL.
  • - *
- * - * @see ubidi_setPara - * - *

The related constants are not real, valid level values. - * UBIDI_DEFAULT_XXX can be used to specify - * a default for the paragraph level for - * when the ubidi_setPara() function - * shall determine it but there is no - * strongly typed character in the input.

- * - * Note that the value for UBIDI_DEFAULT_LTR is even - * and the one for UBIDI_DEFAULT_RTL is odd, - * just like with normal LTR and RTL level values - - * these special values are designed that way. Also, the implementation - * assumes that UBIDI_MAX_EXPLICIT_LEVEL is odd. - * - * @see UBIDI_DEFAULT_LTR - * @see UBIDI_DEFAULT_RTL - * @see UBIDI_LEVEL_OVERRIDE - * @see UBIDI_MAX_EXPLICIT_LEVEL - * @stable ICU 2.0 - */ -typedef uint8_t UBiDiLevel; - -/** Paragraph level setting.

- * - * Constant indicating that the base direction depends on the first strong - * directional character in the text according to the Unicode Bidirectional - * Algorithm. If no strong directional character is present, - * then set the paragraph level to 0 (left-to-right).

- * - * If this value is used in conjunction with reordering modes - * UBIDI_REORDER_INVERSE_LIKE_DIRECT or - * UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL, the text to reorder - * is assumed to be visual LTR, and the text after reordering is required - * to be the corresponding logical string with appropriate contextual - * direction. The direction of the result string will be RTL if either - * the righmost or leftmost strong character of the source text is RTL - * or Arabic Letter, the direction will be LTR otherwise.

- * - * If reordering option UBIDI_OPTION_INSERT_MARKS is set, an RLM may - * be added at the beginning of the result string to ensure round trip - * (that the result string, when reordered back to visual, will produce - * the original source text). - * @see UBIDI_REORDER_INVERSE_LIKE_DIRECT - * @see UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL - * @stable ICU 2.0 - */ -#define UBIDI_DEFAULT_LTR 0xfe - -/** Paragraph level setting.

- * - * Constant indicating that the base direction depends on the first strong - * directional character in the text according to the Unicode Bidirectional - * Algorithm. If no strong directional character is present, - * then set the paragraph level to 1 (right-to-left).

- * - * If this value is used in conjunction with reordering modes - * UBIDI_REORDER_INVERSE_LIKE_DIRECT or - * UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL, the text to reorder - * is assumed to be visual LTR, and the text after reordering is required - * to be the corresponding logical string with appropriate contextual - * direction. The direction of the result string will be RTL if either - * the righmost or leftmost strong character of the source text is RTL - * or Arabic Letter, or if the text contains no strong character; - * the direction will be LTR otherwise.

- * - * If reordering option UBIDI_OPTION_INSERT_MARKS is set, an RLM may - * be added at the beginning of the result string to ensure round trip - * (that the result string, when reordered back to visual, will produce - * the original source text). - * @see UBIDI_REORDER_INVERSE_LIKE_DIRECT - * @see UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL - * @stable ICU 2.0 - */ -#define UBIDI_DEFAULT_RTL 0xff - -/** - * Maximum explicit embedding level. - * (The maximum resolved level can be up to UBIDI_MAX_EXPLICIT_LEVEL+1). - * @stable ICU 2.0 - */ -#define UBIDI_MAX_EXPLICIT_LEVEL 125 - -/** Bit flag for level input. - * Overrides directional properties. - * @stable ICU 2.0 - */ -#define UBIDI_LEVEL_OVERRIDE 0x80 - -/** - * Special value which can be returned by the mapping functions when a logical - * index has no corresponding visual index or vice-versa. This may happen - * for the logical-to-visual mapping of a Bidi control when option - * #UBIDI_OPTION_REMOVE_CONTROLS is specified. This can also happen - * for the visual-to-logical mapping of a Bidi mark (LRM or RLM) inserted - * by option #UBIDI_OPTION_INSERT_MARKS. - * @see ubidi_getVisualIndex - * @see ubidi_getVisualMap - * @see ubidi_getLogicalIndex - * @see ubidi_getLogicalMap - * @stable ICU 3.6 - */ -#define UBIDI_MAP_NOWHERE (-1) - -/** - * UBiDiDirection values indicate the text direction. - * @stable ICU 2.0 - */ -enum UBiDiDirection { - /** Left-to-right text. This is a 0 value. - *

    - *
  • As return value for ubidi_getDirection(), it means - * that the source string contains no right-to-left characters, or - * that the source string is empty and the paragraph level is even. - *
  • As return value for ubidi_getBaseDirection(), it - * means that the first strong character of the source string has - * a left-to-right direction. - *
- * @stable ICU 2.0 - */ - UBIDI_LTR, - /** Right-to-left text. This is a 1 value. - *
    - *
  • As return value for ubidi_getDirection(), it means - * that the source string contains no left-to-right characters, or - * that the source string is empty and the paragraph level is odd. - *
  • As return value for ubidi_getBaseDirection(), it - * means that the first strong character of the source string has - * a right-to-left direction. - *
- * @stable ICU 2.0 - */ - UBIDI_RTL, - /** Mixed-directional text. - *

As return value for ubidi_getDirection(), it means - * that the source string contains both left-to-right and - * right-to-left characters. - * @stable ICU 2.0 - */ - UBIDI_MIXED, - /** No strongly directional text. - *

As return value for ubidi_getBaseDirection(), it means - * that the source string is missing or empty, or contains neither left-to-right - * nor right-to-left characters. - * @stable ICU 4.6 - */ - UBIDI_NEUTRAL -}; - -/** @stable ICU 2.0 */ -typedef enum UBiDiDirection UBiDiDirection; - -/** - * Forward declaration of the UBiDi structure for the declaration of - * the API functions. Its fields are implementation-specific.

- * This structure holds information about a paragraph (or multiple paragraphs) - * of text with Bidi-algorithm-related details, or about one line of - * such a paragraph.

- * Reordering can be done on a line, or on one or more paragraphs which are - * then interpreted each as one single line. - * @stable ICU 2.0 - */ -struct UBiDi; - -/** @stable ICU 2.0 */ -typedef struct UBiDi UBiDi; - -/** - * Allocate a UBiDi structure. - * Such an object is initially empty. It is assigned - * the Bidi properties of a piece of text containing one or more paragraphs - * by ubidi_setPara() - * or the Bidi properties of a line within a paragraph by - * ubidi_setLine().

- * This object can be reused for as long as it is not deallocated - * by calling ubidi_close().

- * ubidi_setPara() and ubidi_setLine() will allocate - * additional memory for internal structures as necessary. - * - * @return An empty UBiDi object. - * @stable ICU 2.0 - */ -U_STABLE UBiDi * U_EXPORT2 -ubidi_open(void); - -/** - * Allocate a UBiDi structure with preallocated memory - * for internal structures. - * This function provides a UBiDi object like ubidi_open() - * with no arguments, but it also preallocates memory for internal structures - * according to the sizings supplied by the caller.

- * Subsequent functions will not allocate any more memory, and are thus - * guaranteed not to fail because of lack of memory.

- * The preallocation can be limited to some of the internal memory - * by setting some values to 0 here. That means that if, e.g., - * maxRunCount cannot be reasonably predetermined and should not - * be set to maxLength (the only failproof value) to avoid - * wasting memory, then maxRunCount could be set to 0 here - * and the internal structures that are associated with it will be allocated - * on demand, just like with ubidi_open(). - * - * @param maxLength is the maximum text or line length that internal memory - * will be preallocated for. An attempt to associate this object with a - * longer text will fail, unless this value is 0, which leaves the allocation - * up to the implementation. - * - * @param maxRunCount is the maximum anticipated number of same-level runs - * that internal memory will be preallocated for. An attempt to access - * visual runs on an object that was not preallocated for as many runs - * as the text was actually resolved to will fail, - * unless this value is 0, which leaves the allocation up to the implementation.

- * The number of runs depends on the actual text and maybe anywhere between - * 1 and maxLength. It is typically small. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @return An empty UBiDi object with preallocated memory. - * @stable ICU 2.0 - */ -U_STABLE UBiDi * U_EXPORT2 -ubidi_openSized(int32_t maxLength, int32_t maxRunCount, UErrorCode *pErrorCode); - -/** - * ubidi_close() must be called to free the memory - * associated with a UBiDi object.

- * - * Important: - * A parent UBiDi object must not be destroyed or reused if - * it still has children. - * If a UBiDi object has become the child - * of another one (its parent) by calling - * ubidi_setLine(), then the child object must - * be destroyed (closed) or reused (by calling - * ubidi_setPara() or ubidi_setLine()) - * before the parent object. - * - * @param pBiDi is a UBiDi object. - * - * @see ubidi_setPara - * @see ubidi_setLine - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubidi_close(UBiDi *pBiDi); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUBiDiPointer - * "Smart pointer" class, closes a UBiDi via ubidi_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUBiDiPointer, UBiDi, ubidi_close); - -U_NAMESPACE_END - -#endif - -/** - * Modify the operation of the Bidi algorithm such that it - * approximates an "inverse Bidi" algorithm. This function - * must be called before ubidi_setPara(). - * - *

The normal operation of the Bidi algorithm as described - * in the Unicode Technical Report is to take text stored in logical - * (keyboard, typing) order and to determine the reordering of it for visual - * rendering. - * Some legacy systems store text in visual order, and for operations - * with standard, Unicode-based algorithms, the text needs to be transformed - * to logical order. This is effectively the inverse algorithm of the - * described Bidi algorithm. Note that there is no standard algorithm for - * this "inverse Bidi" and that the current implementation provides only an - * approximation of "inverse Bidi".

- * - *

With isInverse set to TRUE, - * this function changes the behavior of some of the subsequent functions - * in a way that they can be used for the inverse Bidi algorithm. - * Specifically, runs of text with numeric characters will be treated in a - * special way and may need to be surrounded with LRM characters when they are - * written in reordered sequence.

- * - *

Output runs should be retrieved using ubidi_getVisualRun(). - * Since the actual input for "inverse Bidi" is visually ordered text and - * ubidi_getVisualRun() gets the reordered runs, these are actually - * the runs of the logically ordered output.

- * - *

Calling this function with argument isInverse set to - * TRUE is equivalent to calling - * ubidi_setReorderingMode with argument - * reorderingMode - * set to #UBIDI_REORDER_INVERSE_NUMBERS_AS_L.
- * Calling this function with argument isInverse set to - * FALSE is equivalent to calling - * ubidi_setReorderingMode with argument - * reorderingMode - * set to #UBIDI_REORDER_DEFAULT. - * - * @param pBiDi is a UBiDi object. - * - * @param isInverse specifies "forward" or "inverse" Bidi operation. - * - * @see ubidi_setPara - * @see ubidi_writeReordered - * @see ubidi_setReorderingMode - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubidi_setInverse(UBiDi *pBiDi, UBool isInverse); - -/** - * Is this Bidi object set to perform the inverse Bidi algorithm? - *

Note: calling this function after setting the reordering mode with - * ubidi_setReorderingMode will return TRUE if the - * reordering mode was set to #UBIDI_REORDER_INVERSE_NUMBERS_AS_L, - * FALSE for all other values.

- * - * @param pBiDi is a UBiDi object. - * @return TRUE if the Bidi object is set to perform the inverse Bidi algorithm - * by handling numbers as L. - * - * @see ubidi_setInverse - * @see ubidi_setReorderingMode - * @stable ICU 2.0 - */ - -U_STABLE UBool U_EXPORT2 -ubidi_isInverse(UBiDi *pBiDi); - -/** - * Specify whether block separators must be allocated level zero, - * so that successive paragraphs will progress from left to right. - * This function must be called before ubidi_setPara(). - * Paragraph separators (B) may appear in the text. Setting them to level zero - * means that all paragraph separators (including one possibly appearing - * in the last text position) are kept in the reordered text after the text - * that they follow in the source text. - * When this feature is not enabled, a paragraph separator at the last - * position of the text before reordering will go to the first position - * of the reordered text when the paragraph level is odd. - * - * @param pBiDi is a UBiDi object. - * - * @param orderParagraphsLTR specifies whether paragraph separators (B) must - * receive level 0, so that successive paragraphs progress from left to right. - * - * @see ubidi_setPara - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -ubidi_orderParagraphsLTR(UBiDi *pBiDi, UBool orderParagraphsLTR); - -/** - * Is this Bidi object set to allocate level 0 to block separators so that - * successive paragraphs progress from left to right? - * - * @param pBiDi is a UBiDi object. - * @return TRUE if the Bidi object is set to allocate level 0 to block - * separators. - * - * @see ubidi_orderParagraphsLTR - * @stable ICU 3.4 - */ -U_STABLE UBool U_EXPORT2 -ubidi_isOrderParagraphsLTR(UBiDi *pBiDi); - -/** - * UBiDiReorderingMode values indicate which variant of the Bidi - * algorithm to use. - * - * @see ubidi_setReorderingMode - * @stable ICU 3.6 - */ -typedef enum UBiDiReorderingMode { - /** Regular Logical to Visual Bidi algorithm according to Unicode. - * This is a 0 value. - * @stable ICU 3.6 */ - UBIDI_REORDER_DEFAULT = 0, - /** Logical to Visual algorithm which handles numbers in a way which - * mimicks the behavior of Windows XP. - * @stable ICU 3.6 */ - UBIDI_REORDER_NUMBERS_SPECIAL, - /** Logical to Visual algorithm grouping numbers with adjacent R characters - * (reversible algorithm). - * @stable ICU 3.6 */ - UBIDI_REORDER_GROUP_NUMBERS_WITH_R, - /** Reorder runs only to transform a Logical LTR string to the Logical RTL - * string with the same display, or vice-versa.
- * If this mode is set together with option - * #UBIDI_OPTION_INSERT_MARKS, some Bidi controls in the source - * text may be removed and other controls may be added to produce the - * minimum combination which has the required display. - * @stable ICU 3.6 */ - UBIDI_REORDER_RUNS_ONLY, - /** Visual to Logical algorithm which handles numbers like L - * (same algorithm as selected by ubidi_setInverse(TRUE). - * @see ubidi_setInverse - * @stable ICU 3.6 */ - UBIDI_REORDER_INVERSE_NUMBERS_AS_L, - /** Visual to Logical algorithm equivalent to the regular Logical to Visual - * algorithm. - * @stable ICU 3.6 */ - UBIDI_REORDER_INVERSE_LIKE_DIRECT, - /** Inverse Bidi (Visual to Logical) algorithm for the - * UBIDI_REORDER_NUMBERS_SPECIAL Bidi algorithm. - * @stable ICU 3.6 */ - UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL, -#ifndef U_HIDE_DEPRECATED_API - /** - * Number of values for reordering mode. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UBIDI_REORDER_COUNT -#endif // U_HIDE_DEPRECATED_API -} UBiDiReorderingMode; - -/** - * Modify the operation of the Bidi algorithm such that it implements some - * variant to the basic Bidi algorithm or approximates an "inverse Bidi" - * algorithm, depending on different values of the "reordering mode". - * This function must be called before ubidi_setPara(), and stays - * in effect until called again with a different argument. - * - *

The normal operation of the Bidi algorithm as described - * in the Unicode Standard Annex #9 is to take text stored in logical - * (keyboard, typing) order and to determine how to reorder it for visual - * rendering.

- * - *

With the reordering mode set to a value other than - * #UBIDI_REORDER_DEFAULT, this function changes the behavior of - * some of the subsequent functions in a way such that they implement an - * inverse Bidi algorithm or some other algorithm variants.

- * - *

Some legacy systems store text in visual order, and for operations - * with standard, Unicode-based algorithms, the text needs to be transformed - * into logical order. This is effectively the inverse algorithm of the - * described Bidi algorithm. Note that there is no standard algorithm for - * this "inverse Bidi", so a number of variants are implemented here.

- * - *

In other cases, it may be desirable to emulate some variant of the - * Logical to Visual algorithm (e.g. one used in MS Windows), or perform a - * Logical to Logical transformation.

- * - *
    - *
  • When the reordering mode is set to #UBIDI_REORDER_DEFAULT, - * the standard Bidi Logical to Visual algorithm is applied.
  • - * - *
  • When the reordering mode is set to - * #UBIDI_REORDER_NUMBERS_SPECIAL, - * the algorithm used to perform Bidi transformations when calling - * ubidi_setPara should approximate the algorithm used in - * Microsoft Windows XP rather than strictly conform to the Unicode Bidi - * algorithm. - *
    - * The differences between the basic algorithm and the algorithm addressed - * by this option are as follows: - *
      - *
    • Within text at an even embedding level, the sequence "123AB" - * (where AB represent R or AL letters) is transformed to "123BA" by the - * Unicode algorithm and to "BA123" by the Windows algorithm.
    • - *
    • Arabic-Indic numbers (AN) are handled by the Windows algorithm just - * like regular numbers (EN).
    • - *
  • - * - *
  • When the reordering mode is set to - * #UBIDI_REORDER_GROUP_NUMBERS_WITH_R, - * numbers located between LTR text and RTL text are associated with the RTL - * text. For instance, an LTR paragraph with content "abc 123 DEF" (where - * upper case letters represent RTL characters) will be transformed to - * "abc FED 123" (and not "abc 123 FED"), "DEF 123 abc" will be transformed - * to "123 FED abc" and "123 FED abc" will be transformed to "DEF 123 abc". - * This makes the algorithm reversible and makes it useful when round trip - * (from visual to logical and back to visual) must be achieved without - * adding LRM characters. However, this is a variation from the standard - * Unicode Bidi algorithm.
    - * The source text should not contain Bidi control characters other than LRM - * or RLM.
  • - * - *
  • When the reordering mode is set to - * #UBIDI_REORDER_RUNS_ONLY, - * a "Logical to Logical" transformation must be performed: - *
      - *
    • If the default text level of the source text (argument paraLevel - * in ubidi_setPara) is even, the source text will be handled as - * LTR logical text and will be transformed to the RTL logical text which has - * the same LTR visual display.
    • - *
    • If the default level of the source text is odd, the source text - * will be handled as RTL logical text and will be transformed to the - * LTR logical text which has the same LTR visual display.
    • - *
    - * This mode may be needed when logical text which is basically Arabic or - * Hebrew, with possible included numbers or phrases in English, has to be - * displayed as if it had an even embedding level (this can happen if the - * displaying application treats all text as if it was basically LTR). - *
    - * This mode may also be needed in the reverse case, when logical text which is - * basically English, with possible included phrases in Arabic or Hebrew, has to - * be displayed as if it had an odd embedding level. - *
    - * Both cases could be handled by adding LRE or RLE at the head of the text, - * if the display subsystem supports these formatting controls. If it does not, - * the problem may be handled by transforming the source text in this mode - * before displaying it, so that it will be displayed properly.
    - * The source text should not contain Bidi control characters other than LRM - * or RLM.
  • - * - *
  • When the reordering mode is set to - * #UBIDI_REORDER_INVERSE_NUMBERS_AS_L, an "inverse Bidi" algorithm - * is applied. - * Runs of text with numeric characters will be treated like LTR letters and - * may need to be surrounded with LRM characters when they are written in - * reordered sequence (the option #UBIDI_INSERT_LRM_FOR_NUMERIC can - * be used with function ubidi_writeReordered to this end. This - * mode is equivalent to calling ubidi_setInverse() with - * argument isInverse set to TRUE.
  • - * - *
  • When the reordering mode is set to - * #UBIDI_REORDER_INVERSE_LIKE_DIRECT, the "direct" Logical to Visual - * Bidi algorithm is used as an approximation of an "inverse Bidi" algorithm. - * This mode is similar to mode #UBIDI_REORDER_INVERSE_NUMBERS_AS_L - * but is closer to the regular Bidi algorithm. - *
    - * For example, an LTR paragraph with the content "FED 123 456 CBA" (where - * upper case represents RTL characters) will be transformed to - * "ABC 456 123 DEF", as opposed to "DEF 123 456 ABC" - * with mode UBIDI_REORDER_INVERSE_NUMBERS_AS_L.
    - * When used in conjunction with option - * #UBIDI_OPTION_INSERT_MARKS, this mode generally - * adds Bidi marks to the output significantly more sparingly than mode - * #UBIDI_REORDER_INVERSE_NUMBERS_AS_L with option - * #UBIDI_INSERT_LRM_FOR_NUMERIC in calls to - * ubidi_writeReordered.
  • - * - *
  • When the reordering mode is set to - * #UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL, the Logical to Visual - * Bidi algorithm used in Windows XP is used as an approximation of an "inverse Bidi" algorithm. - *
    - * For example, an LTR paragraph with the content "abc FED123" (where - * upper case represents RTL characters) will be transformed to "abc 123DEF."
  • - *
- * - *

In all the reordering modes specifying an "inverse Bidi" algorithm - * (i.e. those with a name starting with UBIDI_REORDER_INVERSE), - * output runs should be retrieved using - * ubidi_getVisualRun(), and the output text with - * ubidi_writeReordered(). The caller should keep in mind that in - * "inverse Bidi" modes the input is actually visually ordered text and - * reordered output returned by ubidi_getVisualRun() or - * ubidi_writeReordered() are actually runs or character string - * of logically ordered output.
- * For all the "inverse Bidi" modes, the source text should not contain - * Bidi control characters other than LRM or RLM.

- * - *

Note that option #UBIDI_OUTPUT_REVERSE of - * ubidi_writeReordered has no useful meaning and should not be - * used in conjunction with any value of the reordering mode specifying - * "inverse Bidi" or with value UBIDI_REORDER_RUNS_ONLY. - * - * @param pBiDi is a UBiDi object. - * @param reorderingMode specifies the required variant of the Bidi algorithm. - * - * @see UBiDiReorderingMode - * @see ubidi_setInverse - * @see ubidi_setPara - * @see ubidi_writeReordered - * @stable ICU 3.6 - */ -U_STABLE void U_EXPORT2 -ubidi_setReorderingMode(UBiDi *pBiDi, UBiDiReorderingMode reorderingMode); - -/** - * What is the requested reordering mode for a given Bidi object? - * - * @param pBiDi is a UBiDi object. - * @return the current reordering mode of the Bidi object - * @see ubidi_setReorderingMode - * @stable ICU 3.6 - */ -U_STABLE UBiDiReorderingMode U_EXPORT2 -ubidi_getReorderingMode(UBiDi *pBiDi); - -/** - * UBiDiReorderingOption values indicate which options are - * specified to affect the Bidi algorithm. - * - * @see ubidi_setReorderingOptions - * @stable ICU 3.6 - */ -typedef enum UBiDiReorderingOption { - /** - * option value for ubidi_setReorderingOptions: - * disable all the options which can be set with this function - * @see ubidi_setReorderingOptions - * @stable ICU 3.6 - */ - UBIDI_OPTION_DEFAULT = 0, - - /** - * option bit for ubidi_setReorderingOptions: - * insert Bidi marks (LRM or RLM) when needed to ensure correct result of - * a reordering to a Logical order - * - *

This option must be set or reset before calling - * ubidi_setPara.

- * - *

This option is significant only with reordering modes which generate - * a result with Logical order, specifically:

- *
    - *
  • #UBIDI_REORDER_RUNS_ONLY
  • - *
  • #UBIDI_REORDER_INVERSE_NUMBERS_AS_L
  • - *
  • #UBIDI_REORDER_INVERSE_LIKE_DIRECT
  • - *
  • #UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL
  • - *
- * - *

If this option is set in conjunction with reordering mode - * #UBIDI_REORDER_INVERSE_NUMBERS_AS_L or with calling - * ubidi_setInverse(TRUE), it implies - * option #UBIDI_INSERT_LRM_FOR_NUMERIC - * in calls to function ubidi_writeReordered().

- * - *

For other reordering modes, a minimum number of LRM or RLM characters - * will be added to the source text after reordering it so as to ensure - * round trip, i.e. when applying the inverse reordering mode on the - * resulting logical text with removal of Bidi marks - * (option #UBIDI_OPTION_REMOVE_CONTROLS set before calling - * ubidi_setPara() or option #UBIDI_REMOVE_BIDI_CONTROLS - * in ubidi_writeReordered), the result will be identical to the - * source text in the first transformation. - * - *

This option will be ignored if specified together with option - * #UBIDI_OPTION_REMOVE_CONTROLS. It inhibits option - * UBIDI_REMOVE_BIDI_CONTROLS in calls to function - * ubidi_writeReordered() and it implies option - * #UBIDI_INSERT_LRM_FOR_NUMERIC in calls to function - * ubidi_writeReordered() if the reordering mode is - * #UBIDI_REORDER_INVERSE_NUMBERS_AS_L.

- * - * @see ubidi_setReorderingMode - * @see ubidi_setReorderingOptions - * @stable ICU 3.6 - */ - UBIDI_OPTION_INSERT_MARKS = 1, - - /** - * option bit for ubidi_setReorderingOptions: - * remove Bidi control characters - * - *

This option must be set or reset before calling - * ubidi_setPara.

- * - *

This option nullifies option #UBIDI_OPTION_INSERT_MARKS. - * It inhibits option #UBIDI_INSERT_LRM_FOR_NUMERIC in calls - * to function ubidi_writeReordered() and it implies option - * #UBIDI_REMOVE_BIDI_CONTROLS in calls to that function.

- * - * @see ubidi_setReorderingMode - * @see ubidi_setReorderingOptions - * @stable ICU 3.6 - */ - UBIDI_OPTION_REMOVE_CONTROLS = 2, - - /** - * option bit for ubidi_setReorderingOptions: - * process the output as part of a stream to be continued - * - *

This option must be set or reset before calling - * ubidi_setPara.

- * - *

This option specifies that the caller is interested in processing large - * text object in parts. - * The results of the successive calls are expected to be concatenated by the - * caller. Only the call for the last part will have this option bit off.

- * - *

When this option bit is on, ubidi_setPara() may process - * less than the full source text in order to truncate the text at a meaningful - * boundary. The caller should call ubidi_getProcessedLength() - * immediately after calling ubidi_setPara() in order to - * determine how much of the source text has been processed. - * Source text beyond that length should be resubmitted in following calls to - * ubidi_setPara. The processed length may be less than - * the length of the source text if a character preceding the last character of - * the source text constitutes a reasonable boundary (like a block separator) - * for text to be continued.
- * If the last character of the source text constitutes a reasonable - * boundary, the whole text will be processed at once.
- * If nowhere in the source text there exists - * such a reasonable boundary, the processed length will be zero.
- * The caller should check for such an occurrence and do one of the following: - *

  • submit a larger amount of text with a better chance to include - * a reasonable boundary.
  • - *
  • resubmit the same text after turning off option - * UBIDI_OPTION_STREAMING.
- * In all cases, this option should be turned off before processing the last - * part of the text.

- * - *

When the UBIDI_OPTION_STREAMING option is used, - * it is recommended to call ubidi_orderParagraphsLTR() with - * argument orderParagraphsLTR set to TRUE before - * calling ubidi_setPara so that later paragraphs may be - * concatenated to previous paragraphs on the right.

- * - * @see ubidi_setReorderingMode - * @see ubidi_setReorderingOptions - * @see ubidi_getProcessedLength - * @see ubidi_orderParagraphsLTR - * @stable ICU 3.6 - */ - UBIDI_OPTION_STREAMING = 4 -} UBiDiReorderingOption; - -/** - * Specify which of the reordering options - * should be applied during Bidi transformations. - * - * @param pBiDi is a UBiDi object. - * @param reorderingOptions is a combination of zero or more of the following - * options: - * #UBIDI_OPTION_DEFAULT, #UBIDI_OPTION_INSERT_MARKS, - * #UBIDI_OPTION_REMOVE_CONTROLS, #UBIDI_OPTION_STREAMING. - * - * @see ubidi_getReorderingOptions - * @stable ICU 3.6 - */ -U_STABLE void U_EXPORT2 -ubidi_setReorderingOptions(UBiDi *pBiDi, uint32_t reorderingOptions); - -/** - * What are the reordering options applied to a given Bidi object? - * - * @param pBiDi is a UBiDi object. - * @return the current reordering options of the Bidi object - * @see ubidi_setReorderingOptions - * @stable ICU 3.6 - */ -U_STABLE uint32_t U_EXPORT2 -ubidi_getReorderingOptions(UBiDi *pBiDi); - -/** - * Set the context before a call to ubidi_setPara().

- * - * ubidi_setPara() computes the left-right directionality for a given piece - * of text which is supplied as one of its arguments. Sometimes this piece - * of text (the "main text") should be considered in context, because text - * appearing before ("prologue") and/or after ("epilogue") the main text - * may affect the result of this computation.

- * - * This function specifies the prologue and/or the epilogue for the next - * call to ubidi_setPara(). The characters specified as prologue and - * epilogue should not be modified by the calling program until the call - * to ubidi_setPara() has returned. If successive calls to ubidi_setPara() - * all need specification of a context, ubidi_setContext() must be called - * before each call to ubidi_setPara(). In other words, a context is not - * "remembered" after the following successful call to ubidi_setPara().

- * - * If a call to ubidi_setPara() specifies UBIDI_DEFAULT_LTR or - * UBIDI_DEFAULT_RTL as paraLevel and is preceded by a call to - * ubidi_setContext() which specifies a prologue, the paragraph level will - * be computed taking in consideration the text in the prologue.

- * - * When ubidi_setPara() is called without a previous call to - * ubidi_setContext, the main text is handled as if preceded and followed - * by strong directional characters at the current paragraph level. - * Calling ubidi_setContext() with specification of a prologue will change - * this behavior by handling the main text as if preceded by the last - * strong character appearing in the prologue, if any. - * Calling ubidi_setContext() with specification of an epilogue will change - * the behavior of ubidi_setPara() by handling the main text as if followed - * by the first strong character or digit appearing in the epilogue, if any.

- * - * Note 1: if ubidi_setContext is called repeatedly without - * calling ubidi_setPara, the earlier calls have no effect, - * only the last call will be remembered for the next call to - * ubidi_setPara.

- * - * Note 2: calling ubidi_setContext(pBiDi, NULL, 0, NULL, 0, &errorCode) - * cancels any previous setting of non-empty prologue or epilogue. - * The next call to ubidi_setPara() will process no - * prologue or epilogue.

- * - * Note 3: users must be aware that even after setting the context - * before a call to ubidi_setPara() to perform e.g. a logical to visual - * transformation, the resulting string may not be identical to what it - * would have been if all the text, including prologue and epilogue, had - * been processed together.
- * Example (upper case letters represent RTL characters):
- *   prologue = "abc DE"
- *   epilogue = none
- *   main text = "FGH xyz"
- *   paraLevel = UBIDI_LTR
- *   display without prologue = "HGF xyz" - * ("HGF" is adjacent to "xyz")
- *   display with prologue = "abc HGFED xyz" - * ("HGF" is not adjacent to "xyz")
- * - * @param pBiDi is a paragraph UBiDi object. - * - * @param prologue is a pointer to the text which precedes the text that - * will be specified in a coming call to ubidi_setPara(). - * If there is no prologue to consider, then proLength - * must be zero and this pointer can be NULL. - * - * @param proLength is the length of the prologue; if proLength==-1 - * then the prologue must be zero-terminated. - * Otherwise proLength must be >= 0. If proLength==0, it means - * that there is no prologue to consider. - * - * @param epilogue is a pointer to the text which follows the text that - * will be specified in a coming call to ubidi_setPara(). - * If there is no epilogue to consider, then epiLength - * must be zero and this pointer can be NULL. - * - * @param epiLength is the length of the epilogue; if epiLength==-1 - * then the epilogue must be zero-terminated. - * Otherwise epiLength must be >= 0. If epiLength==0, it means - * that there is no epilogue to consider. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @see ubidi_setPara - * @stable ICU 4.8 - */ -U_STABLE void U_EXPORT2 -ubidi_setContext(UBiDi *pBiDi, - const UChar *prologue, int32_t proLength, - const UChar *epilogue, int32_t epiLength, - UErrorCode *pErrorCode); - -/** - * Perform the Unicode Bidi algorithm. It is defined in the - * Unicode Standard Anned #9, - * version 13, - * also described in The Unicode Standard, Version 4.0 .

- * - * This function takes a piece of plain text containing one or more paragraphs, - * with or without externally specified embedding levels from styled - * text and computes the left-right-directionality of each character.

- * - * If the entire text is all of the same directionality, then - * the function may not perform all the steps described by the algorithm, - * i.e., some levels may not be the same as if all steps were performed. - * This is not relevant for unidirectional text.
- * For example, in pure LTR text with numbers the numbers would get - * a resolved level of 2 higher than the surrounding text according to - * the algorithm. This implementation may set all resolved levels to - * the same value in such a case.

- * - * The text can be composed of multiple paragraphs. Occurrence of a block - * separator in the text terminates a paragraph, and whatever comes next starts - * a new paragraph. The exception to this rule is when a Carriage Return (CR) - * is followed by a Line Feed (LF). Both CR and LF are block separators, but - * in that case, the pair of characters is considered as terminating the - * preceding paragraph, and a new paragraph will be started by a character - * coming after the LF. - * - * @param pBiDi A UBiDi object allocated with ubidi_open() - * which will be set to contain the reordering information, - * especially the resolved levels for all the characters in text. - * - * @param text is a pointer to the text that the Bidi algorithm will be performed on. - * This pointer is stored in the UBiDi object and can be retrieved - * with ubidi_getText().
- * Note: the text must be (at least) length long. - * - * @param length is the length of the text; if length==-1 then - * the text must be zero-terminated. - * - * @param paraLevel specifies the default level for the text; - * it is typically 0 (LTR) or 1 (RTL). - * If the function shall determine the paragraph level from the text, - * then paraLevel can be set to - * either #UBIDI_DEFAULT_LTR - * or #UBIDI_DEFAULT_RTL; if the text contains multiple - * paragraphs, the paragraph level shall be determined separately for - * each paragraph; if a paragraph does not include any strongly typed - * character, then the desired default is used (0 for LTR or 1 for RTL). - * Any other value between 0 and #UBIDI_MAX_EXPLICIT_LEVEL - * is also valid, with odd levels indicating RTL. - * - * @param embeddingLevels (in) may be used to preset the embedding and override levels, - * ignoring characters like LRE and PDF in the text. - * A level overrides the directional property of its corresponding - * (same index) character if the level has the - * #UBIDI_LEVEL_OVERRIDE bit set.

- * Except for that bit, it must be - * paraLevel<=embeddingLevels[]<=UBIDI_MAX_EXPLICIT_LEVEL, - * with one exception: a level of zero may be specified for a paragraph - * separator even if paraLevel>0 when multiple paragraphs - * are submitted in the same call to ubidi_setPara().

- * Caution: A copy of this pointer, not of the levels, - * will be stored in the UBiDi object; - * the embeddingLevels array must not be - * deallocated before the UBiDi structure is destroyed or reused, - * and the embeddingLevels - * should not be modified to avoid unexpected results on subsequent Bidi operations. - * However, the ubidi_setPara() and - * ubidi_setLine() functions may modify some or all of the levels.

- * After the UBiDi object is reused or destroyed, the caller - * must take care of the deallocation of the embeddingLevels array.

- * Note: the embeddingLevels array must be - * at least length long. - * This pointer can be NULL if this - * value is not necessary. - * - * @param pErrorCode must be a valid pointer to an error code value. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubidi_setPara(UBiDi *pBiDi, const UChar *text, int32_t length, - UBiDiLevel paraLevel, UBiDiLevel *embeddingLevels, - UErrorCode *pErrorCode); - -/** - * ubidi_setLine() sets a UBiDi to - * contain the reordering information, especially the resolved levels, - * for all the characters in a line of text. This line of text is - * specified by referring to a UBiDi object representing - * this information for a piece of text containing one or more paragraphs, - * and by specifying a range of indexes in this text.

- * In the new line object, the indexes will range from 0 to limit-start-1.

- * - * This is used after calling ubidi_setPara() - * for a piece of text, and after line-breaking on that text. - * It is not necessary if each paragraph is treated as a single line.

- * - * After line-breaking, rules (L1) and (L2) for the treatment of - * trailing WS and for reordering are performed on - * a UBiDi object that represents a line.

- * - * Important: pLineBiDi shares data with - * pParaBiDi. - * You must destroy or reuse pLineBiDi before pParaBiDi. - * In other words, you must destroy or reuse the UBiDi object for a line - * before the object for its parent paragraph.

- * - * The text pointer that was stored in pParaBiDi is also copied, - * and start is added to it so that it points to the beginning of the - * line for this object. - * - * @param pParaBiDi is the parent paragraph object. It must have been set - * by a successful call to ubidi_setPara. - * - * @param start is the line's first index into the text. - * - * @param limit is just behind the line's last index into the text - * (its last index +1).
- * It must be 0<=startcontaining paragraph limit. - * If the specified line crosses a paragraph boundary, the function - * will terminate with error code U_ILLEGAL_ARGUMENT_ERROR. - * - * @param pLineBiDi is the object that will now represent a line of the text. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @see ubidi_setPara - * @see ubidi_getProcessedLength - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubidi_setLine(const UBiDi *pParaBiDi, - int32_t start, int32_t limit, - UBiDi *pLineBiDi, - UErrorCode *pErrorCode); - -/** - * Get the directionality of the text. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @return a value of UBIDI_LTR, UBIDI_RTL - * or UBIDI_MIXED - * that indicates if the entire text - * represented by this object is unidirectional, - * and which direction, or if it is mixed-directional. - * Note - The value UBIDI_NEUTRAL is never returned from this method. - * - * @see UBiDiDirection - * @stable ICU 2.0 - */ -U_STABLE UBiDiDirection U_EXPORT2 -ubidi_getDirection(const UBiDi *pBiDi); - -/** - * Gets the base direction of the text provided according - * to the Unicode Bidirectional Algorithm. The base direction - * is derived from the first character in the string with bidirectional - * character type L, R, or AL. If the first such character has type L, - * UBIDI_LTR is returned. If the first such character has - * type R or AL, UBIDI_RTL is returned. If the string does - * not contain any character of these types, then - * UBIDI_NEUTRAL is returned. - * - * This is a lightweight function for use when only the base direction - * is needed and no further bidi processing of the text is needed. - * - * @param text is a pointer to the text whose base - * direction is needed. - * Note: the text must be (at least) @c length long. - * - * @param length is the length of the text; - * if length==-1 then the text - * must be zero-terminated. - * - * @return UBIDI_LTR, UBIDI_RTL, - * UBIDI_NEUTRAL - * - * @see UBiDiDirection - * @stable ICU 4.6 - */ -U_STABLE UBiDiDirection U_EXPORT2 -ubidi_getBaseDirection(const UChar *text, int32_t length ); - -/** - * Get the pointer to the text. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @return The pointer to the text that the UBiDi object was created for. - * - * @see ubidi_setPara - * @see ubidi_setLine - * @stable ICU 2.0 - */ -U_STABLE const UChar * U_EXPORT2 -ubidi_getText(const UBiDi *pBiDi); - -/** - * Get the length of the text. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @return The length of the text that the UBiDi object was created for. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubidi_getLength(const UBiDi *pBiDi); - -/** - * Get the paragraph level of the text. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @return The paragraph level. If there are multiple paragraphs, their - * level may vary if the required paraLevel is UBIDI_DEFAULT_LTR or - * UBIDI_DEFAULT_RTL. In that case, the level of the first paragraph - * is returned. - * - * @see UBiDiLevel - * @see ubidi_getParagraph - * @see ubidi_getParagraphByIndex - * @stable ICU 2.0 - */ -U_STABLE UBiDiLevel U_EXPORT2 -ubidi_getParaLevel(const UBiDi *pBiDi); - -/** - * Get the number of paragraphs. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @return The number of paragraphs. - * @stable ICU 3.4 - */ -U_STABLE int32_t U_EXPORT2 -ubidi_countParagraphs(UBiDi *pBiDi); - -/** - * Get a paragraph, given a position within the text. - * This function returns information about a paragraph.
- * Note: if the paragraph index is known, it is more efficient to - * retrieve the paragraph information using ubidi_getParagraphByIndex().

- * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @param charIndex is the index of a character within the text, in the - * range [0..ubidi_getProcessedLength(pBiDi)-1]. - * - * @param pParaStart will receive the index of the first character of the - * paragraph in the text. - * This pointer can be NULL if this - * value is not necessary. - * - * @param pParaLimit will receive the limit of the paragraph. - * The l-value that you point to here may be the - * same expression (variable) as the one for - * charIndex. - * This pointer can be NULL if this - * value is not necessary. - * - * @param pParaLevel will receive the level of the paragraph. - * This pointer can be NULL if this - * value is not necessary. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @return The index of the paragraph containing the specified position. - * - * @see ubidi_getProcessedLength - * @stable ICU 3.4 - */ -U_STABLE int32_t U_EXPORT2 -ubidi_getParagraph(const UBiDi *pBiDi, int32_t charIndex, int32_t *pParaStart, - int32_t *pParaLimit, UBiDiLevel *pParaLevel, - UErrorCode *pErrorCode); - -/** - * Get a paragraph, given the index of this paragraph. - * - * This function returns information about a paragraph.

- * - * @param pBiDi is the paragraph UBiDi object. - * - * @param paraIndex is the number of the paragraph, in the - * range [0..ubidi_countParagraphs(pBiDi)-1]. - * - * @param pParaStart will receive the index of the first character of the - * paragraph in the text. - * This pointer can be NULL if this - * value is not necessary. - * - * @param pParaLimit will receive the limit of the paragraph. - * This pointer can be NULL if this - * value is not necessary. - * - * @param pParaLevel will receive the level of the paragraph. - * This pointer can be NULL if this - * value is not necessary. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -ubidi_getParagraphByIndex(const UBiDi *pBiDi, int32_t paraIndex, - int32_t *pParaStart, int32_t *pParaLimit, - UBiDiLevel *pParaLevel, UErrorCode *pErrorCode); - -/** - * Get the level for one character. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @param charIndex the index of a character. It must be in the range - * [0..ubidi_getProcessedLength(pBiDi)]. - * - * @return The level for the character at charIndex (0 if charIndex is not - * in the valid range). - * - * @see UBiDiLevel - * @see ubidi_getProcessedLength - * @stable ICU 2.0 - */ -U_STABLE UBiDiLevel U_EXPORT2 -ubidi_getLevelAt(const UBiDi *pBiDi, int32_t charIndex); - -/** - * Get an array of levels for each character.

- * - * Note that this function may allocate memory under some - * circumstances, unlike ubidi_getLevelAt(). - * - * @param pBiDi is the paragraph or line UBiDi object, whose - * text length must be strictly positive. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @return The levels array for the text, - * or NULL if an error occurs. - * - * @see UBiDiLevel - * @see ubidi_getProcessedLength - * @stable ICU 2.0 - */ -U_STABLE const UBiDiLevel * U_EXPORT2 -ubidi_getLevels(UBiDi *pBiDi, UErrorCode *pErrorCode); - -/** - * Get a logical run. - * This function returns information about a run and is used - * to retrieve runs in logical order.

- * This is especially useful for line-breaking on a paragraph. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @param logicalPosition is a logical position within the source text. - * - * @param pLogicalLimit will receive the limit of the corresponding run. - * The l-value that you point to here may be the - * same expression (variable) as the one for - * logicalPosition. - * This pointer can be NULL if this - * value is not necessary. - * - * @param pLevel will receive the level of the corresponding run. - * This pointer can be NULL if this - * value is not necessary. - * - * @see ubidi_getProcessedLength - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubidi_getLogicalRun(const UBiDi *pBiDi, int32_t logicalPosition, - int32_t *pLogicalLimit, UBiDiLevel *pLevel); - -/** - * Get the number of runs. - * This function may invoke the actual reordering on the - * UBiDi object, after ubidi_setPara() - * may have resolved only the levels of the text. Therefore, - * ubidi_countRuns() may have to allocate memory, - * and may fail doing so. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @return The number of runs. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubidi_countRuns(UBiDi *pBiDi, UErrorCode *pErrorCode); - -/** - * Get one run's logical start, length, and directionality, - * which can be 0 for LTR or 1 for RTL. - * In an RTL run, the character at the logical start is - * visually on the right of the displayed run. - * The length is the number of characters in the run.

- * ubidi_countRuns() should be called - * before the runs are retrieved. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @param runIndex is the number of the run in visual order, in the - * range [0..ubidi_countRuns(pBiDi)-1]. - * - * @param pLogicalStart is the first logical character index in the text. - * The pointer may be NULL if this index is not needed. - * - * @param pLength is the number of characters (at least one) in the run. - * The pointer may be NULL if this is not needed. - * - * @return the directionality of the run, - * UBIDI_LTR==0 or UBIDI_RTL==1, - * never UBIDI_MIXED, - * never UBIDI_NEUTRAL. - * - * @see ubidi_countRuns - * - * Example: - *

- * \code
- * int32_t i, count=ubidi_countRuns(pBiDi),
- *         logicalStart, visualIndex=0, length;
- * for(i=0; i0);
- *     } else {
- *         logicalStart+=length;  // logicalLimit
- *         do { // RTL
- *             show_char(text[--logicalStart], visualIndex++);
- *         } while(--length>0);
- *     }
- * }
- *\endcode
- * 
- * - * Note that in right-to-left runs, code like this places - * second surrogates before first ones (which is generally a bad idea) - * and combining characters before base characters. - *

- * Use of ubidi_writeReordered(), optionally with the - * #UBIDI_KEEP_BASE_COMBINING option, can be considered in order - * to avoid these issues. - * @stable ICU 2.0 - */ -U_STABLE UBiDiDirection U_EXPORT2 -ubidi_getVisualRun(UBiDi *pBiDi, int32_t runIndex, - int32_t *pLogicalStart, int32_t *pLength); - -/** - * Get the visual position from a logical text position. - * If such a mapping is used many times on the same - * UBiDi object, then calling - * ubidi_getLogicalMap() is more efficient.

- * - * The value returned may be #UBIDI_MAP_NOWHERE if there is no - * visual position because the corresponding text character is a Bidi control - * removed from output by the option #UBIDI_OPTION_REMOVE_CONTROLS. - *

- * When the visual output is altered by using options of - * ubidi_writeReordered() such as UBIDI_INSERT_LRM_FOR_NUMERIC, - * UBIDI_KEEP_BASE_COMBINING, UBIDI_OUTPUT_REVERSE, - * UBIDI_REMOVE_BIDI_CONTROLS, the visual position returned may not - * be correct. It is advised to use, when possible, reordering options - * such as UBIDI_OPTION_INSERT_MARKS and UBIDI_OPTION_REMOVE_CONTROLS. - *

- * Note that in right-to-left runs, this mapping places - * second surrogates before first ones (which is generally a bad idea) - * and combining characters before base characters. - * Use of ubidi_writeReordered(), optionally with the - * #UBIDI_KEEP_BASE_COMBINING option can be considered instead - * of using the mapping, in order to avoid these issues. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @param logicalIndex is the index of a character in the text. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @return The visual position of this character. - * - * @see ubidi_getLogicalMap - * @see ubidi_getLogicalIndex - * @see ubidi_getProcessedLength - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubidi_getVisualIndex(UBiDi *pBiDi, int32_t logicalIndex, UErrorCode *pErrorCode); - -/** - * Get the logical text position from a visual position. - * If such a mapping is used many times on the same - * UBiDi object, then calling - * ubidi_getVisualMap() is more efficient.

- * - * The value returned may be #UBIDI_MAP_NOWHERE if there is no - * logical position because the corresponding text character is a Bidi mark - * inserted in the output by option #UBIDI_OPTION_INSERT_MARKS. - *

- * This is the inverse function to ubidi_getVisualIndex(). - *

- * When the visual output is altered by using options of - * ubidi_writeReordered() such as UBIDI_INSERT_LRM_FOR_NUMERIC, - * UBIDI_KEEP_BASE_COMBINING, UBIDI_OUTPUT_REVERSE, - * UBIDI_REMOVE_BIDI_CONTROLS, the logical position returned may not - * be correct. It is advised to use, when possible, reordering options - * such as UBIDI_OPTION_INSERT_MARKS and UBIDI_OPTION_REMOVE_CONTROLS. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @param visualIndex is the visual position of a character. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @return The index of this character in the text. - * - * @see ubidi_getVisualMap - * @see ubidi_getVisualIndex - * @see ubidi_getResultLength - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubidi_getLogicalIndex(UBiDi *pBiDi, int32_t visualIndex, UErrorCode *pErrorCode); - -/** - * Get a logical-to-visual index map (array) for the characters in the UBiDi - * (paragraph or line) object. - *

- * Some values in the map may be #UBIDI_MAP_NOWHERE if the - * corresponding text characters are Bidi controls removed from the visual - * output by the option #UBIDI_OPTION_REMOVE_CONTROLS. - *

- * When the visual output is altered by using options of - * ubidi_writeReordered() such as UBIDI_INSERT_LRM_FOR_NUMERIC, - * UBIDI_KEEP_BASE_COMBINING, UBIDI_OUTPUT_REVERSE, - * UBIDI_REMOVE_BIDI_CONTROLS, the visual positions returned may not - * be correct. It is advised to use, when possible, reordering options - * such as UBIDI_OPTION_INSERT_MARKS and UBIDI_OPTION_REMOVE_CONTROLS. - *

- * Note that in right-to-left runs, this mapping places - * second surrogates before first ones (which is generally a bad idea) - * and combining characters before base characters. - * Use of ubidi_writeReordered(), optionally with the - * #UBIDI_KEEP_BASE_COMBINING option can be considered instead - * of using the mapping, in order to avoid these issues. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @param indexMap is a pointer to an array of ubidi_getProcessedLength() - * indexes which will reflect the reordering of the characters. - * If option #UBIDI_OPTION_INSERT_MARKS is set, the number - * of elements allocated in indexMap must be no less than - * ubidi_getResultLength(). - * The array does not need to be initialized.

- * The index map will result in indexMap[logicalIndex]==visualIndex. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @see ubidi_getVisualMap - * @see ubidi_getVisualIndex - * @see ubidi_getProcessedLength - * @see ubidi_getResultLength - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubidi_getLogicalMap(UBiDi *pBiDi, int32_t *indexMap, UErrorCode *pErrorCode); - -/** - * Get a visual-to-logical index map (array) for the characters in the UBiDi - * (paragraph or line) object. - *

- * Some values in the map may be #UBIDI_MAP_NOWHERE if the - * corresponding text characters are Bidi marks inserted in the visual output - * by the option #UBIDI_OPTION_INSERT_MARKS. - *

- * When the visual output is altered by using options of - * ubidi_writeReordered() such as UBIDI_INSERT_LRM_FOR_NUMERIC, - * UBIDI_KEEP_BASE_COMBINING, UBIDI_OUTPUT_REVERSE, - * UBIDI_REMOVE_BIDI_CONTROLS, the logical positions returned may not - * be correct. It is advised to use, when possible, reordering options - * such as UBIDI_OPTION_INSERT_MARKS and UBIDI_OPTION_REMOVE_CONTROLS. - * - * @param pBiDi is the paragraph or line UBiDi object. - * - * @param indexMap is a pointer to an array of ubidi_getResultLength() - * indexes which will reflect the reordering of the characters. - * If option #UBIDI_OPTION_REMOVE_CONTROLS is set, the number - * of elements allocated in indexMap must be no less than - * ubidi_getProcessedLength(). - * The array does not need to be initialized.

- * The index map will result in indexMap[visualIndex]==logicalIndex. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @see ubidi_getLogicalMap - * @see ubidi_getLogicalIndex - * @see ubidi_getProcessedLength - * @see ubidi_getResultLength - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubidi_getVisualMap(UBiDi *pBiDi, int32_t *indexMap, UErrorCode *pErrorCode); - -/** - * This is a convenience function that does not use a UBiDi object. - * It is intended to be used for when an application has determined the levels - * of objects (character sequences) and just needs to have them reordered (L2). - * This is equivalent to using ubidi_getLogicalMap() on a - * UBiDi object. - * - * @param levels is an array with length levels that have been determined by - * the application. - * - * @param length is the number of levels in the array, or, semantically, - * the number of objects to be reordered. - * It must be length>0. - * - * @param indexMap is a pointer to an array of length - * indexes which will reflect the reordering of the characters. - * The array does not need to be initialized.

- * The index map will result in indexMap[logicalIndex]==visualIndex. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubidi_reorderLogical(const UBiDiLevel *levels, int32_t length, int32_t *indexMap); - -/** - * This is a convenience function that does not use a UBiDi object. - * It is intended to be used for when an application has determined the levels - * of objects (character sequences) and just needs to have them reordered (L2). - * This is equivalent to using ubidi_getVisualMap() on a - * UBiDi object. - * - * @param levels is an array with length levels that have been determined by - * the application. - * - * @param length is the number of levels in the array, or, semantically, - * the number of objects to be reordered. - * It must be length>0. - * - * @param indexMap is a pointer to an array of length - * indexes which will reflect the reordering of the characters. - * The array does not need to be initialized.

- * The index map will result in indexMap[visualIndex]==logicalIndex. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubidi_reorderVisual(const UBiDiLevel *levels, int32_t length, int32_t *indexMap); - -/** - * Invert an index map. - * The index mapping of the first map is inverted and written to - * the second one. - * - * @param srcMap is an array with length elements - * which defines the original mapping from a source array containing - * length elements to a destination array. - * Some elements of the source array may have no mapping in the - * destination array. In that case, their value will be - * the special value UBIDI_MAP_NOWHERE. - * All elements must be >=0 or equal to UBIDI_MAP_NOWHERE. - * Some elements may have a value >= length, if the - * destination array has more elements than the source array. - * There must be no duplicate indexes (two or more elements with the - * same value except UBIDI_MAP_NOWHERE). - * - * @param destMap is an array with a number of elements equal to 1 + the highest - * value in srcMap. - * destMap will be filled with the inverse mapping. - * If element with index i in srcMap has a value k different - * from UBIDI_MAP_NOWHERE, this means that element i of - * the source array maps to element k in the destination array. - * The inverse map will have value i in its k-th element. - * For all elements of the destination array which do not map to - * an element in the source array, the corresponding element in the - * inverse map will have a value equal to UBIDI_MAP_NOWHERE. - * - * @param length is the length of each array. - * @see UBIDI_MAP_NOWHERE - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubidi_invertMap(const int32_t *srcMap, int32_t *destMap, int32_t length); - -/** option flags for ubidi_writeReordered() */ - -/** - * option bit for ubidi_writeReordered(): - * keep combining characters after their base characters in RTL runs - * - * @see ubidi_writeReordered - * @stable ICU 2.0 - */ -#define UBIDI_KEEP_BASE_COMBINING 1 - -/** - * option bit for ubidi_writeReordered(): - * replace characters with the "mirrored" property in RTL runs - * by their mirror-image mappings - * - * @see ubidi_writeReordered - * @stable ICU 2.0 - */ -#define UBIDI_DO_MIRRORING 2 - -/** - * option bit for ubidi_writeReordered(): - * surround the run with LRMs if necessary; - * this is part of the approximate "inverse Bidi" algorithm - * - *

This option does not imply corresponding adjustment of the index - * mappings.

- * - * @see ubidi_setInverse - * @see ubidi_writeReordered - * @stable ICU 2.0 - */ -#define UBIDI_INSERT_LRM_FOR_NUMERIC 4 - -/** - * option bit for ubidi_writeReordered(): - * remove Bidi control characters - * (this does not affect #UBIDI_INSERT_LRM_FOR_NUMERIC) - * - *

This option does not imply corresponding adjustment of the index - * mappings.

- * - * @see ubidi_writeReordered - * @stable ICU 2.0 - */ -#define UBIDI_REMOVE_BIDI_CONTROLS 8 - -/** - * option bit for ubidi_writeReordered(): - * write the output in reverse order - * - *

This has the same effect as calling ubidi_writeReordered() - * first without this option, and then calling - * ubidi_writeReverse() without mirroring. - * Doing this in the same step is faster and avoids a temporary buffer. - * An example for using this option is output to a character terminal that - * is designed for RTL scripts and stores text in reverse order.

- * - * @see ubidi_writeReordered - * @stable ICU 2.0 - */ -#define UBIDI_OUTPUT_REVERSE 16 - -/** - * Get the length of the source text processed by the last call to - * ubidi_setPara(). This length may be different from the length - * of the source text if option #UBIDI_OPTION_STREAMING - * has been set. - *
- * Note that whenever the length of the text affects the execution or the - * result of a function, it is the processed length which must be considered, - * except for ubidi_setPara (which receives unprocessed source - * text) and ubidi_getLength (which returns the original length - * of the source text).
- * In particular, the processed length is the one to consider in the following - * cases: - *
    - *
  • maximum value of the limit argument of - * ubidi_setLine
  • - *
  • maximum value of the charIndex argument of - * ubidi_getParagraph
  • - *
  • maximum value of the charIndex argument of - * ubidi_getLevelAt
  • - *
  • number of elements in the array returned by ubidi_getLevels
  • - *
  • maximum value of the logicalStart argument of - * ubidi_getLogicalRun
  • - *
  • maximum value of the logicalIndex argument of - * ubidi_getVisualIndex
  • - *
  • number of elements filled in the *indexMap argument of - * ubidi_getLogicalMap
  • - *
  • length of text processed by ubidi_writeReordered
  • - *
- * - * @param pBiDi is the paragraph UBiDi object. - * - * @return The length of the part of the source text processed by - * the last call to ubidi_setPara. - * @see ubidi_setPara - * @see UBIDI_OPTION_STREAMING - * @stable ICU 3.6 - */ -U_STABLE int32_t U_EXPORT2 -ubidi_getProcessedLength(const UBiDi *pBiDi); - -/** - * Get the length of the reordered text resulting from the last call to - * ubidi_setPara(). This length may be different from the length - * of the source text if option #UBIDI_OPTION_INSERT_MARKS - * or option #UBIDI_OPTION_REMOVE_CONTROLS has been set. - *
- * This resulting length is the one to consider in the following cases: - *
    - *
  • maximum value of the visualIndex argument of - * ubidi_getLogicalIndex
  • - *
  • number of elements of the *indexMap argument of - * ubidi_getVisualMap
  • - *
- * Note that this length stays identical to the source text length if - * Bidi marks are inserted or removed using option bits of - * ubidi_writeReordered, or if option - * #UBIDI_REORDER_INVERSE_NUMBERS_AS_L has been set. - * - * @param pBiDi is the paragraph UBiDi object. - * - * @return The length of the reordered text resulting from - * the last call to ubidi_setPara. - * @see ubidi_setPara - * @see UBIDI_OPTION_INSERT_MARKS - * @see UBIDI_OPTION_REMOVE_CONTROLS - * @stable ICU 3.6 - */ -U_STABLE int32_t U_EXPORT2 -ubidi_getResultLength(const UBiDi *pBiDi); - -U_CDECL_BEGIN - -#ifndef U_HIDE_DEPRECATED_API -/** - * Value returned by UBiDiClassCallback callbacks when - * there is no need to override the standard Bidi class for a given code point. - * - * This constant is deprecated; use u_getIntPropertyMaxValue(UCHAR_BIDI_CLASS)+1 instead. - * - * @see UBiDiClassCallback - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ -#define U_BIDI_CLASS_DEFAULT U_CHAR_DIRECTION_COUNT -#endif // U_HIDE_DEPRECATED_API - -/** - * Callback type declaration for overriding default Bidi class values with - * custom ones. - *

Usually, the function pointer will be propagated to a UBiDi - * object by calling the ubidi_setClassCallback() function; - * then the callback will be invoked by the UBA implementation any time the - * class of a character is to be determined.

- * - * @param context is a pointer to the callback private data. - * - * @param c is the code point to get a Bidi class for. - * - * @return The directional property / Bidi class for the given code point - * c if the default class has been overridden, or - * #U_BIDI_CLASS_DEFAULT=u_getIntPropertyMaxValue(UCHAR_BIDI_CLASS)+1 - * if the standard Bidi class value for c is to be used. - * @see ubidi_setClassCallback - * @see ubidi_getClassCallback - * @stable ICU 3.6 - */ -typedef UCharDirection U_CALLCONV -UBiDiClassCallback(const void *context, UChar32 c); - -U_CDECL_END - -/** - * Retrieve the Bidi class for a given code point. - *

If a #UBiDiClassCallback callback is defined and returns a - * value other than #U_BIDI_CLASS_DEFAULT=u_getIntPropertyMaxValue(UCHAR_BIDI_CLASS)+1, - * that value is used; otherwise the default class determination mechanism is invoked.

- * - * @param pBiDi is the paragraph UBiDi object. - * - * @param c is the code point whose Bidi class must be retrieved. - * - * @return The Bidi class for character c based - * on the given pBiDi instance. - * @see UBiDiClassCallback - * @stable ICU 3.6 - */ -U_STABLE UCharDirection U_EXPORT2 -ubidi_getCustomizedClass(UBiDi *pBiDi, UChar32 c); - -/** - * Set the callback function and callback data used by the UBA - * implementation for Bidi class determination. - *

This may be useful for assigning Bidi classes to PUA characters, or - * for special application needs. For instance, an application may want to - * handle all spaces like L or R characters (according to the base direction) - * when creating the visual ordering of logical lines which are part of a report - * organized in columns: there should not be interaction between adjacent - * cells.

- * - * @param pBiDi is the paragraph UBiDi object. - * - * @param newFn is the new callback function pointer. - * - * @param newContext is the new callback context pointer. This can be NULL. - * - * @param oldFn fillin: Returns the old callback function pointer. This can be - * NULL. - * - * @param oldContext fillin: Returns the old callback's context. This can be - * NULL. - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @see ubidi_getClassCallback - * @stable ICU 3.6 - */ -U_STABLE void U_EXPORT2 -ubidi_setClassCallback(UBiDi *pBiDi, UBiDiClassCallback *newFn, - const void *newContext, UBiDiClassCallback **oldFn, - const void **oldContext, UErrorCode *pErrorCode); - -/** - * Get the current callback function used for Bidi class determination. - * - * @param pBiDi is the paragraph UBiDi object. - * - * @param fn fillin: Returns the callback function pointer. - * - * @param context fillin: Returns the callback's private context. - * - * @see ubidi_setClassCallback - * @stable ICU 3.6 - */ -U_STABLE void U_EXPORT2 -ubidi_getClassCallback(UBiDi *pBiDi, UBiDiClassCallback **fn, const void **context); - -/** - * Take a UBiDi object containing the reordering - * information for a piece of text (one or more paragraphs) set by - * ubidi_setPara() or for a line of text set by - * ubidi_setLine() and write a reordered string to the - * destination buffer. - * - * This function preserves the integrity of characters with multiple - * code units and (optionally) combining characters. - * Characters in RTL runs can be replaced by mirror-image characters - * in the destination buffer. Note that "real" mirroring has - * to be done in a rendering engine by glyph selection - * and that for many "mirrored" characters there are no - * Unicode characters as mirror-image equivalents. - * There are also options to insert or remove Bidi control - * characters; see the description of the destSize - * and options parameters and of the option bit flags. - * - * @param pBiDi A pointer to a UBiDi object that - * is set by ubidi_setPara() or - * ubidi_setLine() and contains the reordering - * information for the text that it was defined for, - * as well as a pointer to that text.

- * The text was aliased (only the pointer was stored - * without copying the contents) and must not have been modified - * since the ubidi_setPara() call. - * - * @param dest A pointer to where the reordered text is to be copied. - * The source text and dest[destSize] - * must not overlap. - * - * @param destSize The size of the dest buffer, - * in number of UChars. - * If the UBIDI_INSERT_LRM_FOR_NUMERIC - * option is set, then the destination length could be - * as large as - * ubidi_getLength(pBiDi)+2*ubidi_countRuns(pBiDi). - * If the UBIDI_REMOVE_BIDI_CONTROLS option - * is set, then the destination length may be less than - * ubidi_getLength(pBiDi). - * If none of these options is set, then the destination length - * will be exactly ubidi_getProcessedLength(pBiDi). - * - * @param options A bit set of options for the reordering that control - * how the reordered text is written. - * The options include mirroring the characters on a code - * point basis and inserting LRM characters, which is used - * especially for transforming visually stored text - * to logically stored text (although this is still an - * imperfect implementation of an "inverse Bidi" algorithm - * because it uses the "forward Bidi" algorithm at its core). - * The available options are: - * #UBIDI_DO_MIRRORING, - * #UBIDI_INSERT_LRM_FOR_NUMERIC, - * #UBIDI_KEEP_BASE_COMBINING, - * #UBIDI_OUTPUT_REVERSE, - * #UBIDI_REMOVE_BIDI_CONTROLS - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @return The length of the output string. - * - * @see ubidi_getProcessedLength - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubidi_writeReordered(UBiDi *pBiDi, - UChar *dest, int32_t destSize, - uint16_t options, - UErrorCode *pErrorCode); - -/** - * Reverse a Right-To-Left run of Unicode text. - * - * This function preserves the integrity of characters with multiple - * code units and (optionally) combining characters. - * Characters can be replaced by mirror-image characters - * in the destination buffer. Note that "real" mirroring has - * to be done in a rendering engine by glyph selection - * and that for many "mirrored" characters there are no - * Unicode characters as mirror-image equivalents. - * There are also options to insert or remove Bidi control - * characters. - * - * This function is the implementation for reversing RTL runs as part - * of ubidi_writeReordered(). For detailed descriptions - * of the parameters, see there. - * Since no Bidi controls are inserted here, the output string length - * will never exceed srcLength. - * - * @see ubidi_writeReordered - * - * @param src A pointer to the RTL run text. - * - * @param srcLength The length of the RTL run. - * - * @param dest A pointer to where the reordered text is to be copied. - * src[srcLength] and dest[destSize] - * must not overlap. - * - * @param destSize The size of the dest buffer, - * in number of UChars. - * If the UBIDI_REMOVE_BIDI_CONTROLS option - * is set, then the destination length may be less than - * srcLength. - * If this option is not set, then the destination length - * will be exactly srcLength. - * - * @param options A bit set of options for the reordering that control - * how the reordered text is written. - * See the options parameter in ubidi_writeReordered(). - * - * @param pErrorCode must be a valid pointer to an error code value. - * - * @return The length of the output string. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubidi_writeReverse(const UChar *src, int32_t srcLength, - UChar *dest, int32_t destSize, - uint16_t options, - UErrorCode *pErrorCode); - -/*#define BIDI_SAMPLE_CODE*/ -/*@}*/ - -#endif diff --git a/win32/include/spidermonkey/unicode/ubiditransform.h b/win32/include/spidermonkey/unicode/ubiditransform.h deleted file mode 100755 index 509f68bc..00000000 --- a/win32/include/spidermonkey/unicode/ubiditransform.h +++ /dev/null @@ -1,321 +0,0 @@ -/* -****************************************************************************** -* -* Copyright (C) 2016 and later: Unicode, Inc. and others. -* License & terms of use: http://www.unicode.org/copyright.html -* -****************************************************************************** -* file name: ubiditransform.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2016jul24 -* created by: Lina Kemmel -* -*/ - -#ifndef UBIDITRANSFORM_H -#define UBIDITRANSFORM_H - -#include "unicode/utypes.h" -#include "unicode/ubidi.h" -#include "unicode/uchar.h" -#include "unicode/localpointer.h" - -#ifndef U_HIDE_DRAFT_API - -/** - * \file - * \brief Bidi Transformations - * - * UBiDiOrder indicates the order of text.

- * This bidi transformation engine supports all possible combinations (4 in - * total) of input and output text order: - *

    - *
  • : unless the output direction is RTL, this - * corresponds to a normal operation of the Bidi algorithm as described in the - * Unicode Technical Report and implemented by UBiDi when the - * reordering mode is set to UBIDI_REORDER_DEFAULT. Visual RTL - * mode is not supported by UBiDi and is accomplished through - * reversing a visual LTR string,
  • - *
  • : unless the input direction is RTL, this - * corresponds to an "inverse bidi algorithm" in UBiDi with the - * reordering mode set to UBIDI_REORDER_INVERSE_LIKE_DIRECT. - * Visual RTL mode is not not supported by UBiDi and is - * accomplished through reversing a visual LTR string,
  • - *
  • : if the input and output base directions - * mismatch, this corresponds to the UBiDi implementation with the - * reordering mode set to UBIDI_REORDER_RUNS_ONLY; and if the - * input and output base directions are identical, the transformation engine - * will only handle character mirroring and Arabic shaping operations without - * reordering,
  • - *
  • : this reordering mode is not supported by - * the UBiDi engine; it implies character mirroring, Arabic - * shaping, and - if the input/output base directions mismatch - string - * reverse operations.
  • - *
- * @see ubidi_setInverse - * @see ubidi_setReorderingMode - * @see UBIDI_REORDER_DEFAULT - * @see UBIDI_REORDER_INVERSE_LIKE_DIRECT - * @see UBIDI_REORDER_RUNS_ONLY - * @draft ICU 58 - */ -typedef enum { - /** 0: Constant indicating a logical order. - * This is the default for input text. - * @draft ICU 58 - */ - UBIDI_LOGICAL = 0, - /** 1: Constant indicating a visual order. - * This is a default for output text. - * @draft ICU 58 - */ - UBIDI_VISUAL -} UBiDiOrder; - -/** - * UBiDiMirroring indicates whether or not characters with the - * "mirrored" property in RTL runs should be replaced with their mirror-image - * counterparts. - * @see UBIDI_DO_MIRRORING - * @see ubidi_setReorderingOptions - * @see ubidi_writeReordered - * @see ubidi_writeReverse - * @draft ICU 58 - */ -typedef enum { - /** 0: Constant indicating that character mirroring should not be - * performed. - * This is the default. - * @draft ICU 58 - */ - UBIDI_MIRRORING_OFF = 0, - /** 1: Constant indicating that character mirroring should be performed. - * This corresponds to calling ubidi_writeReordered or - * ubidi_writeReverse with the - * UBIDI_DO_MIRRORING option bit set. - * @draft ICU 58 - */ - UBIDI_MIRRORING_ON -} UBiDiMirroring; - -/** - * Forward declaration of the UBiDiTransform structure that stores - * information used by the layout transformation engine. - * @draft ICU 58 - */ -typedef struct UBiDiTransform UBiDiTransform; - -/** - * Performs transformation of text from the bidi layout defined by the input - * ordering scheme to the bidi layout defined by the output ordering scheme, - * and applies character mirroring and Arabic shaping operations.

- * In terms of UBiDi, such a transformation implies: - *

    - *
  • calling ubidi_setReorderingMode as needed (when the - * reordering mode is other than normal),
  • - *
  • calling ubidi_setInverse as needed (when text should be - * transformed from a visual to a logical form),
  • - *
  • resolving embedding levels of each character in the input text by - * calling ubidi_setPara,
  • - *
  • reordering the characters based on the computed embedding levels, also - * performing character mirroring as needed, and streaming the result to the - * output, by calling ubidi_writeReordered,
  • - *
  • performing Arabic digit and letter shaping on the output text by calling - * u_shapeArabic.
  • - *
- * An "ordering scheme" encompasses the base direction and the order of text, - * and these characteristics must be defined by the caller for both input and - * output explicitly .

- * There are 36 possible combinations of ordering schemes, - * which are partially supported by UBiDi already. Examples of the - * currently supported combinations: - *

    - *
  • : this is equivalent to calling - * ubidi_setPara with paraLevel == UBIDI_LTR,
  • - *
  • : this is equivalent to calling - * ubidi_setPara with paraLevel == UBIDI_RTL,
  • - *
  • : this is equivalent to - * calling ubidi_setPara with - * paraLevel == UBIDI_DEFAULT_LTR,
  • - *
  • : this is equivalent to - * calling ubidi_setPara with - * paraLevel == UBIDI_DEFAULT_RTL,
  • - *
  • : this is equivalent to - * calling ubidi_setInverse(UBiDi*, TRUE) and then - * ubidi_setPara with paraLevel == UBIDI_LTR,
  • - *
  • : this is equivalent to - * calling ubidi_setInverse(UBiDi*, TRUE) and then - * ubidi_setPara with paraLevel == UBIDI_RTL.
  • - *
- * All combinations that involve the Visual RTL scheme are unsupported by - * UBiDi, for instance: - *
    - *
  • ,
  • - *
  • .
  • - *
- *

Example of usage of the transformation engine:
- *

- * \code
- * UChar text1[] = {'a', 'b', 'c', 0x0625, '1', 0};
- * UChar text2[] = {'a', 'b', 'c', 0x0625, '1', 0};
- * UErrorCode errorCode = U_ZERO_ERROR;
- * // Run a transformation.
- * ubiditransform_transform(pBidiTransform,
- *          text1, -1, text2, -1,
- *          UBIDI_LTR, UBIDI_VISUAL,
- *          UBIDI_RTL, UBIDI_LOGICAL,
- *          UBIDI_MIRRORING_OFF,
- *          U_SHAPE_DIGITS_AN2EN | U_SHAPE_DIGIT_TYPE_AN_EXTENDED,
- *          &errorCode);
- * // Do something with text2.
- *  text2[4] = '2';
- * // Run a reverse transformation.
- * ubiditransform_transform(pBidiTransform,
- *          text2, -1, text1, -1,
- *          UBIDI_RTL, UBIDI_LOGICAL,
- *          UBIDI_LTR, UBIDI_VISUAL,
- *          UBIDI_MIRRORING_OFF,
- *          U_SHAPE_DIGITS_EN2AN | U_SHAPE_DIGIT_TYPE_AN_EXTENDED,
- *          &errorCode);
- *\endcode
- * 
- *

- * - * @param pBiDiTransform A pointer to a UBiDiTransform object - * allocated with ubiditransform_open() or - * NULL.

- * This object serves for one-time setup to amortize initialization - * overheads. Use of this object is not thread-safe. All other threads - * should allocate a new UBiDiTransform object by calling - * ubiditransform_open() before using it. Alternatively, - * a caller can set this parameter to NULL, in which case - * the object will be allocated by the engine on the fly.

- * @param src A pointer to the text that the Bidi layout transformations will - * be performed on. - *

Note: the text must be (at least) - * srcLength long.

- * @param srcLength The length of the text, in number of UChars. If - * length == -1 then the text must be zero-terminated. - * @param dest A pointer to where the processed text is to be copied. - * @param destSize The size of the dest buffer, in number of - * UChars. If the U_SHAPE_LETTERS_UNSHAPE option is set, - * then the destination length could be as large as - * srcLength * 2. Otherwise, the destination length will - * not exceed srcLength. If the caller reserves the last - * position for zero-termination, it should be excluded from - * destSize. - *

destSize == -1 is allowed and makes sense when - * dest was holds some meaningful value, e.g. that of - * src. In this case dest must be - * zero-terminated.

- * @param inParaLevel A base embedding level of the input as defined in - * ubidi_setPara documentation for the - * paraLevel parameter. - * @param inOrder An order of the input, which can be one of the - * UBiDiOrder values. - * @param outParaLevel A base embedding level of the output as defined in - * ubidi_setPara documentation for the - * paraLevel parameter. - * @param outOrder An order of the output, which can be one of the - * UBiDiOrder values. - * @param doMirroring Indicates whether or not to perform character mirroring, - * and can accept one of the UBiDiMirroring values. - * @param shapingOptions Arabic digit and letter shaping options defined in the - * ushape.h documentation. - *

Note: Direction indicator options are computed by - * the transformation engine based on the effective ordering schemes, so - * user-defined direction indicators will be ignored.

- * @param pErrorCode A pointer to an error code value. - * - * @return The destination length, i.e. the number of UChars written to - * dest. If the transformation fails, the return value - * will be 0 (and the error code will be written to - * pErrorCode). - * - * @see UBiDiLevel - * @see UBiDiOrder - * @see UBiDiMirroring - * @see ubidi_setPara - * @see u_shapeArabic - * @draft ICU 58 - */ -U_DRAFT uint32_t U_EXPORT2 -ubiditransform_transform(UBiDiTransform *pBiDiTransform, - const UChar *src, int32_t srcLength, - UChar *dest, int32_t destSize, - UBiDiLevel inParaLevel, UBiDiOrder inOrder, - UBiDiLevel outParaLevel, UBiDiOrder outOrder, - UBiDiMirroring doMirroring, uint32_t shapingOptions, - UErrorCode *pErrorCode); - -/** - * Allocates a UBiDiTransform object. This object can be reused, - * e.g. with different ordering schemes, mirroring or shaping options.

- * Note:The object can only be reused in the same thread. - * All other threads should allocate a new UBiDiTransform object - * before using it.

- * Example of usage:

- *

- * \code
- * UErrorCode errorCode = U_ZERO_ERROR;
- * // Open a new UBiDiTransform.
- * UBiDiTransform* transform = ubiditransform_open(&errorCode);
- * // Run a transformation.
- * ubiditransform_transform(transform,
- *          text1, -1, text2, -1,
- *          UBIDI_RTL, UBIDI_LOGICAL,
- *          UBIDI_LTR, UBIDI_VISUAL,
- *          UBIDI_MIRRORING_ON,
- *          U_SHAPE_DIGITS_EN2AN,
- *          &errorCode);
- * // Do something with the output text and invoke another transformation using
- * //   that text as input.
- * ubiditransform_transform(transform,
- *          text2, -1, text3, -1,
- *          UBIDI_LTR, UBIDI_VISUAL,
- *          UBIDI_RTL, UBIDI_VISUAL,
- *          UBIDI_MIRRORING_ON,
- *          0, &errorCode);
- *\endcode
- * 
- *

- * The UBiDiTransform object must be deallocated by calling - * ubiditransform_close(). - * - * @return An empty UBiDiTransform object. - * @draft ICU 58 - */ -U_DRAFT UBiDiTransform* U_EXPORT2 -ubiditransform_open(UErrorCode *pErrorCode); - -/** - * Deallocates the given UBiDiTransform object. - * @draft ICU 58 - */ -U_DRAFT void U_EXPORT2 -ubiditransform_close(UBiDiTransform *pBidiTransform); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUBiDiTransformPointer - * "Smart pointer" class, closes a UBiDiTransform via ubiditransform_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @draft ICU 58 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUBiDiTransformPointer, UBiDiTransform, ubiditransform_close); - -U_NAMESPACE_END - -#endif - -#endif /* U_HIDE_DRAFT_API */ -#endif diff --git a/win32/include/spidermonkey/unicode/ubrk.h b/win32/include/spidermonkey/unicode/ubrk.h deleted file mode 100755 index f43943ed..00000000 --- a/win32/include/spidermonkey/unicode/ubrk.h +++ /dev/null @@ -1,571 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* Copyright (C) 1996-2015, International Business Machines Corporation and others. -* All Rights Reserved. -****************************************************************************** -*/ - -#ifndef UBRK_H -#define UBRK_H - -#include "unicode/utypes.h" -#include "unicode/uloc.h" -#include "unicode/utext.h" -#include "unicode/localpointer.h" - -/** - * A text-break iterator. - * For usage in C programs. - */ -#ifndef UBRK_TYPEDEF_UBREAK_ITERATOR -# define UBRK_TYPEDEF_UBREAK_ITERATOR - /** - * Opaque type representing an ICU Break iterator object. - * @stable ICU 2.0 - */ - typedef struct UBreakIterator UBreakIterator; -#endif - -#if !UCONFIG_NO_BREAK_ITERATION - -#include "unicode/parseerr.h" - -/** - * \file - * \brief C API: BreakIterator - * - *

BreakIterator C API

- * - * The BreakIterator C API defines methods for finding the location - * of boundaries in text. Pointer to a UBreakIterator maintain a - * current position and scan over text returning the index of characters - * where boundaries occur. - *

- * Line boundary analysis determines where a text string can be broken - * when line-wrapping. The mechanism correctly handles punctuation and - * hyphenated words. - *

- * Note: The locale keyword "lb" can be used to modify line break - * behavior according to the CSS level 3 line-break options, see - * . For example: - * "ja@lb=strict", "zh@lb=loose". - *

- * Sentence boundary analysis allows selection with correct - * interpretation of periods within numbers and abbreviations, and - * trailing punctuation marks such as quotation marks and parentheses. - *

- * Note: The locale keyword "ss" can be used to enable use of - * segmentation suppression data (preventing breaks in English after - * abbreviations such as "Mr." or "Est.", for example), as follows: - * "en@ss=standard". - *

- * Word boundary analysis is used by search and replace functions, as - * well as within text editing applications that allow the user to - * select words with a double click. Word selection provides correct - * interpretation of punctuation marks within and following - * words. Characters that are not part of a word, such as symbols or - * punctuation marks, have word-breaks on both sides. - *

- * Character boundary analysis identifies the boundaries of - * "Extended Grapheme Clusters", which are groupings of codepoints - * that should be treated as character-like units for many text operations. - * Please see Unicode Standard Annex #29, Unicode Text Segmentation, - * http://www.unicode.org/reports/tr29/ for additional information - * on grapheme clusters and guidelines on their use. - *

- * Title boundary analysis locates all positions, - * typically starts of words, that should be set to Title Case - * when title casing the text. - *

- * The text boundary positions are found according to the rules - * described in Unicode Standard Annex #29, Text Boundaries, and - * Unicode Standard Annex #14, Line Breaking Properties. These - * are available at http://www.unicode.org/reports/tr14/ and - * http://www.unicode.org/reports/tr29/. - *

- * In addition to the plain C API defined in this header file, an - * object oriented C++ API with equivalent functionality is defined in the - * file brkiter.h. - *

- * Code snippets illustrating the use of the Break Iterator APIs - * are available in the ICU User Guide, - * http://icu-project.org/userguide/boundaryAnalysis.html - * and in the sample program icu/source/samples/break/break.cpp - */ - -/** The possible types of text boundaries. @stable ICU 2.0 */ -typedef enum UBreakIteratorType { - /** Character breaks @stable ICU 2.0 */ - UBRK_CHARACTER = 0, - /** Word breaks @stable ICU 2.0 */ - UBRK_WORD = 1, - /** Line breaks @stable ICU 2.0 */ - UBRK_LINE = 2, - /** Sentence breaks @stable ICU 2.0 */ - UBRK_SENTENCE = 3, - -#ifndef U_HIDE_DEPRECATED_API - /** - * Title Case breaks - * The iterator created using this type locates title boundaries as described for - * Unicode 3.2 only. For Unicode 4.0 and above title boundary iteration, - * please use Word Boundary iterator. - * - * @deprecated ICU 2.8 Use the word break iterator for titlecasing for Unicode 4 and later. - */ - UBRK_TITLE = 4, - /** - * One more than the highest normal UBreakIteratorType value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UBRK_COUNT = 5 -#endif // U_HIDE_DEPRECATED_API -} UBreakIteratorType; - -/** Value indicating all text boundaries have been returned. - * @stable ICU 2.0 - */ -#define UBRK_DONE ((int32_t) -1) - - -/** - * Enum constants for the word break tags returned by - * getRuleStatus(). A range of values is defined for each category of - * word, to allow for further subdivisions of a category in future releases. - * Applications should check for tag values falling within the range, rather - * than for single individual values. - * - * The numeric values of all of these constants are stable (will not change). - * - * @stable ICU 2.2 -*/ -typedef enum UWordBreak { - /** Tag value for "words" that do not fit into any of other categories. - * Includes spaces and most punctuation. */ - UBRK_WORD_NONE = 0, - /** Upper bound for tags for uncategorized words. */ - UBRK_WORD_NONE_LIMIT = 100, - /** Tag value for words that appear to be numbers, lower limit. */ - UBRK_WORD_NUMBER = 100, - /** Tag value for words that appear to be numbers, upper limit. */ - UBRK_WORD_NUMBER_LIMIT = 200, - /** Tag value for words that contain letters, excluding - * hiragana, katakana or ideographic characters, lower limit. */ - UBRK_WORD_LETTER = 200, - /** Tag value for words containing letters, upper limit */ - UBRK_WORD_LETTER_LIMIT = 300, - /** Tag value for words containing kana characters, lower limit */ - UBRK_WORD_KANA = 300, - /** Tag value for words containing kana characters, upper limit */ - UBRK_WORD_KANA_LIMIT = 400, - /** Tag value for words containing ideographic characters, lower limit */ - UBRK_WORD_IDEO = 400, - /** Tag value for words containing ideographic characters, upper limit */ - UBRK_WORD_IDEO_LIMIT = 500 -} UWordBreak; - -/** - * Enum constants for the line break tags returned by getRuleStatus(). - * A range of values is defined for each category of - * word, to allow for further subdivisions of a category in future releases. - * Applications should check for tag values falling within the range, rather - * than for single individual values. - * - * The numeric values of all of these constants are stable (will not change). - * - * @stable ICU 2.8 -*/ -typedef enum ULineBreakTag { - /** Tag value for soft line breaks, positions at which a line break - * is acceptable but not required */ - UBRK_LINE_SOFT = 0, - /** Upper bound for soft line breaks. */ - UBRK_LINE_SOFT_LIMIT = 100, - /** Tag value for a hard, or mandatory line break */ - UBRK_LINE_HARD = 100, - /** Upper bound for hard line breaks. */ - UBRK_LINE_HARD_LIMIT = 200 -} ULineBreakTag; - - - -/** - * Enum constants for the sentence break tags returned by getRuleStatus(). - * A range of values is defined for each category of - * sentence, to allow for further subdivisions of a category in future releases. - * Applications should check for tag values falling within the range, rather - * than for single individual values. - * - * The numeric values of all of these constants are stable (will not change). - * - * @stable ICU 2.8 -*/ -typedef enum USentenceBreakTag { - /** Tag value for for sentences ending with a sentence terminator - * ('.', '?', '!', etc.) character, possibly followed by a - * hard separator (CR, LF, PS, etc.) - */ - UBRK_SENTENCE_TERM = 0, - /** Upper bound for tags for sentences ended by sentence terminators. */ - UBRK_SENTENCE_TERM_LIMIT = 100, - /** Tag value for for sentences that do not contain an ending - * sentence terminator ('.', '?', '!', etc.) character, but - * are ended only by a hard separator (CR, LF, PS, etc.) or end of input. - */ - UBRK_SENTENCE_SEP = 100, - /** Upper bound for tags for sentences ended by a separator. */ - UBRK_SENTENCE_SEP_LIMIT = 200 - /** Tag value for a hard, or mandatory line break */ -} USentenceBreakTag; - - -/** - * Open a new UBreakIterator for locating text boundaries for a specified locale. - * A UBreakIterator may be used for detecting character, line, word, - * and sentence breaks in text. - * @param type The type of UBreakIterator to open: one of UBRK_CHARACTER, UBRK_WORD, - * UBRK_LINE, UBRK_SENTENCE - * @param locale The locale specifying the text-breaking conventions. Note that - * locale keys such as "lb" and "ss" may be used to modify text break behavior, - * see general discussion of BreakIterator C API. - * @param text The text to be iterated over. - * @param textLength The number of characters in text, or -1 if null-terminated. - * @param status A UErrorCode to receive any errors. - * @return A UBreakIterator for the specified locale. - * @see ubrk_openRules - * @stable ICU 2.0 - */ -U_STABLE UBreakIterator* U_EXPORT2 -ubrk_open(UBreakIteratorType type, - const char *locale, - const UChar *text, - int32_t textLength, - UErrorCode *status); - -/** - * Open a new UBreakIterator for locating text boundaries using specified breaking rules. - * The rule syntax is ... (TBD) - * @param rules A set of rules specifying the text breaking conventions. - * @param rulesLength The number of characters in rules, or -1 if null-terminated. - * @param text The text to be iterated over. May be null, in which case ubrk_setText() is - * used to specify the text to be iterated. - * @param textLength The number of characters in text, or -1 if null-terminated. - * @param parseErr Receives position and context information for any syntax errors - * detected while parsing the rules. - * @param status A UErrorCode to receive any errors. - * @return A UBreakIterator for the specified rules. - * @see ubrk_open - * @stable ICU 2.2 - */ -U_STABLE UBreakIterator* U_EXPORT2 -ubrk_openRules(const UChar *rules, - int32_t rulesLength, - const UChar *text, - int32_t textLength, - UParseError *parseErr, - UErrorCode *status); - -/** - * Thread safe cloning operation - * @param bi iterator to be cloned - * @param stackBuffer Deprecated functionality as of ICU 52, use NULL.
- * user allocated space for the new clone. If NULL new memory will be allocated. - * If buffer is not large enough, new memory will be allocated. - * Clients can use the U_BRK_SAFECLONE_BUFFERSIZE. - * @param pBufferSize Deprecated functionality as of ICU 52, use NULL or 1.
- * pointer to size of allocated space. - * If *pBufferSize == 0, a sufficient size for use in cloning will - * be returned ('pre-flighting') - * If *pBufferSize is not enough for a stack-based safe clone, - * new memory will be allocated. - * @param status to indicate whether the operation went on smoothly or there were errors - * An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used if any allocations were necessary. - * @return pointer to the new clone - * @stable ICU 2.0 - */ -U_STABLE UBreakIterator * U_EXPORT2 -ubrk_safeClone( - const UBreakIterator *bi, - void *stackBuffer, - int32_t *pBufferSize, - UErrorCode *status); - -#ifndef U_HIDE_DEPRECATED_API - -/** - * A recommended size (in bytes) for the memory buffer to be passed to ubrk_saveClone(). - * @deprecated ICU 52. Do not rely on ubrk_safeClone() cloning into any provided buffer. - */ -#define U_BRK_SAFECLONE_BUFFERSIZE 1 - -#endif /* U_HIDE_DEPRECATED_API */ - -/** -* Close a UBreakIterator. -* Once closed, a UBreakIterator may no longer be used. -* @param bi The break iterator to close. - * @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -ubrk_close(UBreakIterator *bi); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUBreakIteratorPointer - * "Smart pointer" class, closes a UBreakIterator via ubrk_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUBreakIteratorPointer, UBreakIterator, ubrk_close); - -U_NAMESPACE_END - -#endif - -/** - * Sets an existing iterator to point to a new piece of text. - * The break iterator retains a pointer to the supplied text. - * The caller must not modify or delete the text while the BreakIterator - * retains the reference. - * - * @param bi The iterator to use - * @param text The text to be set - * @param textLength The length of the text - * @param status The error code - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ubrk_setText(UBreakIterator* bi, - const UChar* text, - int32_t textLength, - UErrorCode* status); - - -/** - * Sets an existing iterator to point to a new piece of text. - * - * All index positions returned by break iterator functions are - * native indices from the UText. For example, when breaking UTF-8 - * encoded text, the break positions returned by \ref ubrk_next, \ref ubrk_previous, etc. - * will be UTF-8 string indices, not UTF-16 positions. - * - * @param bi The iterator to use - * @param text The text to be set. - * This function makes a shallow clone of the supplied UText. This means - * that the caller is free to immediately close or otherwise reuse the - * UText that was passed as a parameter, but that the underlying text itself - * must not be altered while being referenced by the break iterator. - * @param status The error code - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -ubrk_setUText(UBreakIterator* bi, - UText* text, - UErrorCode* status); - - - -/** - * Determine the most recently-returned text boundary. - * - * @param bi The break iterator to use. - * @return The character index most recently returned by \ref ubrk_next, \ref ubrk_previous, - * \ref ubrk_first, or \ref ubrk_last. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubrk_current(const UBreakIterator *bi); - -/** - * Advance the iterator to the boundary following the current boundary. - * - * @param bi The break iterator to use. - * @return The character index of the next text boundary, or UBRK_DONE - * if all text boundaries have been returned. - * @see ubrk_previous - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubrk_next(UBreakIterator *bi); - -/** - * Set the iterator position to the boundary preceding the current boundary. - * - * @param bi The break iterator to use. - * @return The character index of the preceding text boundary, or UBRK_DONE - * if all text boundaries have been returned. - * @see ubrk_next - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubrk_previous(UBreakIterator *bi); - -/** - * Set the iterator position to zero, the start of the text being scanned. - * @param bi The break iterator to use. - * @return The new iterator position (zero). - * @see ubrk_last - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubrk_first(UBreakIterator *bi); - -/** - * Set the iterator position to the index immediately beyond the last character in the text being scanned. - * This is not the same as the last character. - * @param bi The break iterator to use. - * @return The character offset immediately beyond the last character in the - * text being scanned. - * @see ubrk_first - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubrk_last(UBreakIterator *bi); - -/** - * Set the iterator position to the first boundary preceding the specified offset. - * The new position is always smaller than offset, or UBRK_DONE. - * @param bi The break iterator to use. - * @param offset The offset to begin scanning. - * @return The text boundary preceding offset, or UBRK_DONE. - * @see ubrk_following - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubrk_preceding(UBreakIterator *bi, - int32_t offset); - -/** - * Advance the iterator to the first boundary following the specified offset. - * The value returned is always greater than offset, or UBRK_DONE. - * @param bi The break iterator to use. - * @param offset The offset to begin scanning. - * @return The text boundary following offset, or UBRK_DONE. - * @see ubrk_preceding - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ubrk_following(UBreakIterator *bi, - int32_t offset); - -/** -* Get a locale for which text breaking information is available. -* A UBreakIterator in a locale returned by this function will perform the correct -* text breaking for the locale. -* @param index The index of the desired locale. -* @return A locale for which number text breaking information is available, or 0 if none. -* @see ubrk_countAvailable -* @stable ICU 2.0 -*/ -U_STABLE const char* U_EXPORT2 -ubrk_getAvailable(int32_t index); - -/** -* Determine how many locales have text breaking information available. -* This function is most useful as determining the loop ending condition for -* calls to \ref ubrk_getAvailable. -* @return The number of locales for which text breaking information is available. -* @see ubrk_getAvailable -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -ubrk_countAvailable(void); - - -/** -* Returns true if the specfied position is a boundary position. As a side -* effect, leaves the iterator pointing to the first boundary position at -* or after "offset". -* @param bi The break iterator to use. -* @param offset the offset to check. -* @return True if "offset" is a boundary position. -* @stable ICU 2.0 -*/ -U_STABLE UBool U_EXPORT2 -ubrk_isBoundary(UBreakIterator *bi, int32_t offset); - -/** - * Return the status from the break rule that determined the most recently - * returned break position. The values appear in the rule source - * within brackets, {123}, for example. For rules that do not specify a - * status, a default value of 0 is returned. - *

- * For word break iterators, the possible values are defined in enum UWordBreak. - * @stable ICU 2.2 - */ -U_STABLE int32_t U_EXPORT2 -ubrk_getRuleStatus(UBreakIterator *bi); - -/** - * Get the statuses from the break rules that determined the most recently - * returned break position. The values appear in the rule source - * within brackets, {123}, for example. The default status value for rules - * that do not explicitly provide one is zero. - *

- * For word break iterators, the possible values are defined in enum UWordBreak. - * @param bi The break iterator to use - * @param fillInVec an array to be filled in with the status values. - * @param capacity the length of the supplied vector. A length of zero causes - * the function to return the number of status values, in the - * normal way, without attemtping to store any values. - * @param status receives error codes. - * @return The number of rule status values from rules that determined - * the most recent boundary returned by the break iterator. - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -ubrk_getRuleStatusVec(UBreakIterator *bi, int32_t *fillInVec, int32_t capacity, UErrorCode *status); - -/** - * Return the locale of the break iterator. You can choose between the valid and - * the actual locale. - * @param bi break iterator - * @param type locale type (valid or actual) - * @param status error code - * @return locale string - * @stable ICU 2.8 - */ -U_STABLE const char* U_EXPORT2 -ubrk_getLocaleByType(const UBreakIterator *bi, ULocDataLocaleType type, UErrorCode* status); - -/** - * Set the subject text string upon which the break iterator is operating - * without changing any other aspect of the state. - * The new and previous text strings must have the same content. - * - * This function is intended for use in environments where ICU is operating on - * strings that may move around in memory. It provides a mechanism for notifying - * ICU that the string has been relocated, and providing a new UText to access the - * string in its new position. - * - * Note that the break iterator never copies the underlying text - * of a string being processed, but always operates directly on the original text - * provided by the user. Refreshing simply drops the references to the old text - * and replaces them with references to the new. - * - * Caution: this function is normally used only by very specialized - * system-level code. One example use case is with garbage collection - * that moves the text in memory. - * - * @param bi The break iterator. - * @param text The new (moved) text string. - * @param status Receives errors detected by this function. - * - * @stable ICU 49 - */ -U_STABLE void U_EXPORT2 -ubrk_refreshUText(UBreakIterator *bi, - UText *text, - UErrorCode *status); - -#endif /* #if !UCONFIG_NO_BREAK_ITERATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/ucal.h b/win32/include/spidermonkey/unicode/ucal.h deleted file mode 100755 index 29c08457..00000000 --- a/win32/include/spidermonkey/unicode/ucal.h +++ /dev/null @@ -1,1564 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * Copyright (C) 1996-2015, International Business Machines Corporation and - * others. All Rights Reserved. - ******************************************************************************* - */ - -#ifndef UCAL_H -#define UCAL_H - -#include "unicode/utypes.h" -#include "unicode/uenum.h" -#include "unicode/uloc.h" -#include "unicode/localpointer.h" - -#if !UCONFIG_NO_FORMATTING - -/** - * \file - * \brief C API: Calendar - * - *

Calendar C API

- * - * UCalendar C API is used for converting between a UDate object - * and a set of integer fields such as UCAL_YEAR, UCAL_MONTH, - * UCAL_DAY, UCAL_HOUR, and so on. - * (A UDate object represents a specific instant in - * time with millisecond precision. See UDate - * for information about the UDate .) - * - *

- * Types of UCalendar interpret a UDate - * according to the rules of a specific calendar system. The U_STABLE - * provides the enum UCalendarType with UCAL_TRADITIONAL and - * UCAL_GREGORIAN. - *

- * Like other locale-sensitive C API, calendar API provides a - * function, ucal_open(), which returns a pointer to - * UCalendar whose time fields have been initialized - * with the current date and time. We need to specify the type of - * calendar to be opened and the timezoneId. - * \htmlonly

\endhtmlonly - *
- * \code
- * UCalendar *caldef;
- * UChar *tzId;
- * UErrorCode status;
- * tzId=(UChar*)malloc(sizeof(UChar) * (strlen("PST") +1) );
- * u_uastrcpy(tzId, "PST");
- * caldef=ucal_open(tzID, u_strlen(tzID), NULL, UCAL_TRADITIONAL, &status);
- * \endcode
- * 
- * \htmlonly
\endhtmlonly - * - *

- * A UCalendar object can produce all the time field values - * needed to implement the date-time formatting for a particular language - * and calendar style (for example, Japanese-Gregorian, Japanese-Traditional). - * - *

- * When computing a UDate from time fields, two special circumstances - * may arise: there may be insufficient information to compute the - * UDate (such as only year and month but no day in the month), - * or there may be inconsistent information (such as "Tuesday, July 15, 1996" - * -- July 15, 1996 is actually a Monday). - * - *

- * Insufficient information. The calendar will use default - * information to specify the missing fields. This may vary by calendar; for - * the Gregorian calendar, the default for a field is the same as that of the - * start of the epoch: i.e., UCAL_YEAR = 1970, UCAL_MONTH = JANUARY, UCAL_DATE = 1, etc. - * - *

- * Inconsistent information. If fields conflict, the calendar - * will give preference to fields set more recently. For example, when - * determining the day, the calendar will look for one of the following - * combinations of fields. The most recent combination, as determined by the - * most recently set single field, will be used. - * - * \htmlonly

\endhtmlonly - *
- * \code
- * UCAL_MONTH + UCAL_DAY_OF_MONTH
- * UCAL_MONTH + UCAL_WEEK_OF_MONTH + UCAL_DAY_OF_WEEK
- * UCAL_MONTH + UCAL_DAY_OF_WEEK_IN_MONTH + UCAL_DAY_OF_WEEK
- * UCAL_DAY_OF_YEAR
- * UCAL_DAY_OF_WEEK + UCAL_WEEK_OF_YEAR
- * \endcode
- * 
- * \htmlonly
\endhtmlonly - * - * For the time of day: - * - * \htmlonly
\endhtmlonly - *
- * \code
- * UCAL_HOUR_OF_DAY
- * UCAL_AM_PM + UCAL_HOUR
- * \endcode
- * 
- * \htmlonly
\endhtmlonly - * - *

- * Note: for some non-Gregorian calendars, different - * fields may be necessary for complete disambiguation. For example, a full - * specification of the historial Arabic astronomical calendar requires year, - * month, day-of-month and day-of-week in some cases. - * - *

- * Note: There are certain possible ambiguities in - * interpretation of certain singular times, which are resolved in the - * following ways: - *

    - *
  1. 24:00:00 "belongs" to the following day. That is, - * 23:59 on Dec 31, 1969 < 24:00 on Jan 1, 1970 < 24:01:00 on Jan 1, 1970 - * - *
  2. Although historically not precise, midnight also belongs to "am", - * and noon belongs to "pm", so on the same day, - * 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm - *
- * - *

- * The date or time format strings are not part of the definition of a - * calendar, as those must be modifiable or overridable by the user at - * runtime. Use {@link icu::DateFormat} - * to format dates. - * - *

- * Calendar provides an API for field "rolling", where fields - * can be incremented or decremented, but wrap around. For example, rolling the - * month up in the date December 12, 1996 results in - * January 12, 1996. - * - *

- * Calendar also provides a date arithmetic function for - * adding the specified (signed) amount of time to a particular time field. - * For example, subtracting 5 days from the date September 12, 1996 - * results in September 7, 1996. - * - * @stable ICU 2.0 - */ - -/** - * The time zone ID reserved for unknown time zone. - * @stable ICU 4.8 - */ -#define UCAL_UNKNOWN_ZONE_ID "Etc/Unknown" - -/** A calendar. - * For usage in C programs. - * @stable ICU 2.0 - */ -typedef void* UCalendar; - -/** Possible types of UCalendars - * @stable ICU 2.0 - */ -enum UCalendarType { - /** - * Despite the name, UCAL_TRADITIONAL designates the locale's default calendar, - * which may be the Gregorian calendar or some other calendar. - * @stable ICU 2.0 - */ - UCAL_TRADITIONAL, - /** - * A better name for UCAL_TRADITIONAL. - * @stable ICU 4.2 - */ - UCAL_DEFAULT = UCAL_TRADITIONAL, - /** - * Unambiguously designates the Gregorian calendar for the locale. - * @stable ICU 2.0 - */ - UCAL_GREGORIAN -}; - -/** @stable ICU 2.0 */ -typedef enum UCalendarType UCalendarType; - -/** Possible fields in a UCalendar - * @stable ICU 2.0 - */ -enum UCalendarDateFields { - /** - * Field number indicating the era, e.g., AD or BC in the Gregorian (Julian) calendar. - * This is a calendar-specific value. - * @stable ICU 2.6 - */ - UCAL_ERA, - - /** - * Field number indicating the year. This is a calendar-specific value. - * @stable ICU 2.6 - */ - UCAL_YEAR, - - /** - * Field number indicating the month. This is a calendar-specific value. - * The first month of the year is - * JANUARY; the last depends on the number of months in a year. - * @see #UCAL_JANUARY - * @see #UCAL_FEBRUARY - * @see #UCAL_MARCH - * @see #UCAL_APRIL - * @see #UCAL_MAY - * @see #UCAL_JUNE - * @see #UCAL_JULY - * @see #UCAL_AUGUST - * @see #UCAL_SEPTEMBER - * @see #UCAL_OCTOBER - * @see #UCAL_NOVEMBER - * @see #UCAL_DECEMBER - * @see #UCAL_UNDECIMBER - * @stable ICU 2.6 - */ - UCAL_MONTH, - - /** - * Field number indicating the - * week number within the current year. The first week of the year, as - * defined by UCAL_FIRST_DAY_OF_WEEK and UCAL_MINIMAL_DAYS_IN_FIRST_WEEK - * attributes, has value 1. Subclasses define - * the value of UCAL_WEEK_OF_YEAR for days before the first week of - * the year. - * @see ucal_getAttribute - * @see ucal_setAttribute - * @stable ICU 2.6 - */ - UCAL_WEEK_OF_YEAR, - - /** - * Field number indicating the - * week number within the current month. The first week of the month, as - * defined by UCAL_FIRST_DAY_OF_WEEK and UCAL_MINIMAL_DAYS_IN_FIRST_WEEK - * attributes, has value 1. Subclasses define - * the value of WEEK_OF_MONTH for days before the first week of - * the month. - * @see ucal_getAttribute - * @see ucal_setAttribute - * @see #UCAL_FIRST_DAY_OF_WEEK - * @see #UCAL_MINIMAL_DAYS_IN_FIRST_WEEK - * @stable ICU 2.6 - */ - UCAL_WEEK_OF_MONTH, - - /** - * Field number indicating the - * day of the month. This is a synonym for DAY_OF_MONTH. - * The first day of the month has value 1. - * @see #UCAL_DAY_OF_MONTH - * @stable ICU 2.6 - */ - UCAL_DATE, - - /** - * Field number indicating the day - * number within the current year. The first day of the year has value 1. - * @stable ICU 2.6 - */ - UCAL_DAY_OF_YEAR, - - /** - * Field number indicating the day - * of the week. This field takes values SUNDAY, - * MONDAY, TUESDAY, WEDNESDAY, - * THURSDAY, FRIDAY, and SATURDAY. - * @see #UCAL_SUNDAY - * @see #UCAL_MONDAY - * @see #UCAL_TUESDAY - * @see #UCAL_WEDNESDAY - * @see #UCAL_THURSDAY - * @see #UCAL_FRIDAY - * @see #UCAL_SATURDAY - * @stable ICU 2.6 - */ - UCAL_DAY_OF_WEEK, - - /** - * Field number indicating the - * ordinal number of the day of the week within the current month. Together - * with the DAY_OF_WEEK field, this uniquely specifies a day - * within a month. Unlike WEEK_OF_MONTH and - * WEEK_OF_YEAR, this field's value does not depend on - * getFirstDayOfWeek() or - * getMinimalDaysInFirstWeek(). DAY_OF_MONTH 1 - * through 7 always correspond to DAY_OF_WEEK_IN_MONTH - * 1; 8 through 15 correspond to - * DAY_OF_WEEK_IN_MONTH 2, and so on. - * DAY_OF_WEEK_IN_MONTH 0 indicates the week before - * DAY_OF_WEEK_IN_MONTH 1. Negative values count back from the - * end of the month, so the last Sunday of a month is specified as - * DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1. Because - * negative values count backward they will usually be aligned differently - * within the month than positive values. For example, if a month has 31 - * days, DAY_OF_WEEK_IN_MONTH -1 will overlap - * DAY_OF_WEEK_IN_MONTH 5 and the end of 4. - * @see #UCAL_DAY_OF_WEEK - * @see #UCAL_WEEK_OF_MONTH - * @stable ICU 2.6 - */ - UCAL_DAY_OF_WEEK_IN_MONTH, - - /** - * Field number indicating - * whether the HOUR is before or after noon. - * E.g., at 10:04:15.250 PM the AM_PM is PM. - * @see #UCAL_AM - * @see #UCAL_PM - * @see #UCAL_HOUR - * @stable ICU 2.6 - */ - UCAL_AM_PM, - - /** - * Field number indicating the - * hour of the morning or afternoon. HOUR is used for the 12-hour - * clock. - * E.g., at 10:04:15.250 PM the HOUR is 10. - * @see #UCAL_AM_PM - * @see #UCAL_HOUR_OF_DAY - * @stable ICU 2.6 - */ - UCAL_HOUR, - - /** - * Field number indicating the - * hour of the day. HOUR_OF_DAY is used for the 24-hour clock. - * E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22. - * @see #UCAL_HOUR - * @stable ICU 2.6 - */ - UCAL_HOUR_OF_DAY, - - /** - * Field number indicating the - * minute within the hour. - * E.g., at 10:04:15.250 PM the UCAL_MINUTE is 4. - * @stable ICU 2.6 - */ - UCAL_MINUTE, - - /** - * Field number indicating the - * second within the minute. - * E.g., at 10:04:15.250 PM the UCAL_SECOND is 15. - * @stable ICU 2.6 - */ - UCAL_SECOND, - - /** - * Field number indicating the - * millisecond within the second. - * E.g., at 10:04:15.250 PM the UCAL_MILLISECOND is 250. - * @stable ICU 2.6 - */ - UCAL_MILLISECOND, - - /** - * Field number indicating the - * raw offset from GMT in milliseconds. - * @stable ICU 2.6 - */ - UCAL_ZONE_OFFSET, - - /** - * Field number indicating the - * daylight savings offset in milliseconds. - * @stable ICU 2.6 - */ - UCAL_DST_OFFSET, - - /** - * Field number - * indicating the extended year corresponding to the - * UCAL_WEEK_OF_YEAR field. This may be one greater or less - * than the value of UCAL_EXTENDED_YEAR. - * @stable ICU 2.6 - */ - UCAL_YEAR_WOY, - - /** - * Field number - * indicating the localized day of week. This will be a value from 1 - * to 7 inclusive, with 1 being the localized first day of the week. - * @stable ICU 2.6 - */ - UCAL_DOW_LOCAL, - - /** - * Year of this calendar system, encompassing all supra-year fields. For example, - * in Gregorian/Julian calendars, positive Extended Year values indicate years AD, - * 1 BC = 0 extended, 2 BC = -1 extended, and so on. - * @stable ICU 2.8 - */ - UCAL_EXTENDED_YEAR, - - /** - * Field number - * indicating the modified Julian day number. This is different from - * the conventional Julian day number in two regards. First, it - * demarcates days at local zone midnight, rather than noon GMT. - * Second, it is a local number; that is, it depends on the local time - * zone. It can be thought of as a single number that encompasses all - * the date-related fields. - * @stable ICU 2.8 - */ - UCAL_JULIAN_DAY, - - /** - * Ranges from 0 to 23:59:59.999 (regardless of DST). This field behaves exactly - * like a composite of all time-related fields, not including the zone fields. As such, - * it also reflects discontinuities of those fields on DST transition days. On a day - * of DST onset, it will jump forward. On a day of DST cessation, it will jump - * backward. This reflects the fact that it must be combined with the DST_OFFSET field - * to obtain a unique local time value. - * @stable ICU 2.8 - */ - UCAL_MILLISECONDS_IN_DAY, - - /** - * Whether or not the current month is a leap month (0 or 1). See the Chinese calendar for - * an example of this. - */ - UCAL_IS_LEAP_MONTH, - - // Do not conditionalize with #ifndef U_HIDE_DEPRECATED_API, - // it is needed for layout of Calendar, DateFormat, and other objects - /** - * One more than the highest normal UCalendarDateFields value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCAL_FIELD_COUNT, - - /** - * Field number indicating the - * day of the month. This is a synonym for UCAL_DATE. - * The first day of the month has value 1. - * @see #UCAL_DATE - * Synonym for UCAL_DATE - * @stable ICU 2.8 - **/ - UCAL_DAY_OF_MONTH=UCAL_DATE -}; - -/** @stable ICU 2.0 */ -typedef enum UCalendarDateFields UCalendarDateFields; - /** - * Useful constant for days of week. Note: Calendar day-of-week is 1-based. Clients - * who create locale resources for the field of first-day-of-week should be aware of - * this. For instance, in US locale, first-day-of-week is set to 1, i.e., UCAL_SUNDAY. - */ -/** Possible days of the week in a UCalendar - * @stable ICU 2.0 - */ -enum UCalendarDaysOfWeek { - /** Sunday */ - UCAL_SUNDAY = 1, - /** Monday */ - UCAL_MONDAY, - /** Tuesday */ - UCAL_TUESDAY, - /** Wednesday */ - UCAL_WEDNESDAY, - /** Thursday */ - UCAL_THURSDAY, - /** Friday */ - UCAL_FRIDAY, - /** Saturday */ - UCAL_SATURDAY -}; - -/** @stable ICU 2.0 */ -typedef enum UCalendarDaysOfWeek UCalendarDaysOfWeek; - -/** Possible months in a UCalendar. Note: Calendar month is 0-based. - * @stable ICU 2.0 - */ -enum UCalendarMonths { - /** January */ - UCAL_JANUARY, - /** February */ - UCAL_FEBRUARY, - /** March */ - UCAL_MARCH, - /** April */ - UCAL_APRIL, - /** May */ - UCAL_MAY, - /** June */ - UCAL_JUNE, - /** July */ - UCAL_JULY, - /** August */ - UCAL_AUGUST, - /** September */ - UCAL_SEPTEMBER, - /** October */ - UCAL_OCTOBER, - /** November */ - UCAL_NOVEMBER, - /** December */ - UCAL_DECEMBER, - /** Value of the UCAL_MONTH field indicating the - * thirteenth month of the year. Although the Gregorian calendar - * does not use this value, lunar calendars do. - */ - UCAL_UNDECIMBER -}; - -/** @stable ICU 2.0 */ -typedef enum UCalendarMonths UCalendarMonths; - -/** Possible AM/PM values in a UCalendar - * @stable ICU 2.0 - */ -enum UCalendarAMPMs { - /** AM */ - UCAL_AM, - /** PM */ - UCAL_PM -}; - -/** @stable ICU 2.0 */ -typedef enum UCalendarAMPMs UCalendarAMPMs; - -/** - * System time zone type constants used by filtering zones - * in ucal_openTimeZoneIDEnumeration. - * @see ucal_openTimeZoneIDEnumeration - * @stable ICU 4.8 - */ -enum USystemTimeZoneType { - /** - * Any system zones. - * @stable ICU 4.8 - */ - UCAL_ZONE_TYPE_ANY, - /** - * Canonical system zones. - * @stable ICU 4.8 - */ - UCAL_ZONE_TYPE_CANONICAL, - /** - * Canonical system zones associated with actual locations. - * @stable ICU 4.8 - */ - UCAL_ZONE_TYPE_CANONICAL_LOCATION -}; - -/** @stable ICU 4.8 */ -typedef enum USystemTimeZoneType USystemTimeZoneType; - -/** - * Create an enumeration over system time zone IDs with the given - * filter conditions. - * @param zoneType The system time zone type. - * @param region The ISO 3166 two-letter country code or UN M.49 - * three-digit area code. When NULL, no filtering - * done by region. - * @param rawOffset An offset from GMT in milliseconds, ignoring the - * effect of daylight savings time, if any. When NULL, - * no filtering done by zone offset. - * @param ec A pointer to an UErrorCode to receive any errors - * @return an enumeration object that the caller must dispose of - * using enum_close(), or NULL upon failure. In case of failure, - * *ec will indicate the error. - * @stable ICU 4.8 - */ -U_STABLE UEnumeration* U_EXPORT2 -ucal_openTimeZoneIDEnumeration(USystemTimeZoneType zoneType, const char* region, - const int32_t* rawOffset, UErrorCode* ec); - -/** - * Create an enumeration over all time zones. - * - * @param ec input/output error code - * - * @return an enumeration object that the caller must dispose of using - * uenum_close(), or NULL upon failure. In case of failure *ec will - * indicate the error. - * - * @stable ICU 2.6 - */ -U_STABLE UEnumeration* U_EXPORT2 -ucal_openTimeZones(UErrorCode* ec); - -/** - * Create an enumeration over all time zones associated with the given - * country. Some zones are affiliated with no country (e.g., "UTC"); - * these may also be retrieved, as a group. - * - * @param country the ISO 3166 two-letter country code, or NULL to - * retrieve zones not affiliated with any country - * - * @param ec input/output error code - * - * @return an enumeration object that the caller must dispose of using - * uenum_close(), or NULL upon failure. In case of failure *ec will - * indicate the error. - * - * @stable ICU 2.6 - */ -U_STABLE UEnumeration* U_EXPORT2 -ucal_openCountryTimeZones(const char* country, UErrorCode* ec); - -/** - * Return the default time zone. The default is determined initially - * by querying the host operating system. It may be changed with - * ucal_setDefaultTimeZone() or with the C++ TimeZone API. - * - * @param result A buffer to receive the result, or NULL - * - * @param resultCapacity The capacity of the result buffer - * - * @param ec input/output error code - * - * @return The result string length, not including the terminating - * null - * - * @stable ICU 2.6 - */ -U_STABLE int32_t U_EXPORT2 -ucal_getDefaultTimeZone(UChar* result, int32_t resultCapacity, UErrorCode* ec); - -/** - * Set the default time zone. - * - * @param zoneID null-terminated time zone ID - * - * @param ec input/output error code - * - * @stable ICU 2.6 - */ -U_STABLE void U_EXPORT2 -ucal_setDefaultTimeZone(const UChar* zoneID, UErrorCode* ec); - -/** - * Return the amount of time in milliseconds that the clock is - * advanced during daylight savings time for the given time zone, or - * zero if the time zone does not observe daylight savings time. - * - * @param zoneID null-terminated time zone ID - * - * @param ec input/output error code - * - * @return the number of milliseconds the time is advanced with - * respect to standard time when the daylight savings rules are in - * effect. This is always a non-negative number, most commonly either - * 3,600,000 (one hour) or zero. - * - * @stable ICU 2.6 - */ -U_STABLE int32_t U_EXPORT2 -ucal_getDSTSavings(const UChar* zoneID, UErrorCode* ec); - -/** - * Get the current date and time. - * The value returned is represented as milliseconds from the epoch. - * @return The current date and time. - * @stable ICU 2.0 - */ -U_STABLE UDate U_EXPORT2 -ucal_getNow(void); - -/** - * Open a UCalendar. - * A UCalendar may be used to convert a millisecond value to a year, - * month, and day. - *

- * Note: When unknown TimeZone ID is specified or if the TimeZone ID specified is "Etc/Unknown", - * the UCalendar returned by the function is initialized with GMT zone with TimeZone ID - * UCAL_UNKNOWN_ZONE_ID ("Etc/Unknown") without any errors/warnings. If you want - * to check if a TimeZone ID is valid prior to this function, use ucal_getCanonicalTimeZoneID. - * - * @param zoneID The desired TimeZone ID. If 0, use the default time zone. - * @param len The length of zoneID, or -1 if null-terminated. - * @param locale The desired locale - * @param type The type of UCalendar to open. This can be UCAL_GREGORIAN to open the Gregorian - * calendar for the locale, or UCAL_DEFAULT to open the default calendar for the locale (the - * default calendar may also be Gregorian). To open a specific non-Gregorian calendar for the - * locale, use uloc_setKeywordValue to set the value of the calendar keyword for the locale - * and then pass the locale to ucal_open with UCAL_DEFAULT as the type. - * @param status A pointer to an UErrorCode to receive any errors - * @return A pointer to a UCalendar, or 0 if an error occurred. - * @see #UCAL_UNKNOWN_ZONE_ID - * @stable ICU 2.0 - */ -U_STABLE UCalendar* U_EXPORT2 -ucal_open(const UChar* zoneID, - int32_t len, - const char* locale, - UCalendarType type, - UErrorCode* status); - -/** - * Close a UCalendar. - * Once closed, a UCalendar may no longer be used. - * @param cal The UCalendar to close. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_close(UCalendar *cal); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUCalendarPointer - * "Smart pointer" class, closes a UCalendar via ucal_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUCalendarPointer, UCalendar, ucal_close); - -U_NAMESPACE_END - -#endif - -/** - * Open a copy of a UCalendar. - * This function performs a deep copy. - * @param cal The calendar to copy - * @param status A pointer to an UErrorCode to receive any errors. - * @return A pointer to a UCalendar identical to cal. - * @stable ICU 4.0 - */ -U_STABLE UCalendar* U_EXPORT2 -ucal_clone(const UCalendar* cal, - UErrorCode* status); - -/** - * Set the TimeZone used by a UCalendar. - * A UCalendar uses a timezone for converting from Greenwich time to local time. - * @param cal The UCalendar to set. - * @param zoneID The desired TimeZone ID. If 0, use the default time zone. - * @param len The length of zoneID, or -1 if null-terminated. - * @param status A pointer to an UErrorCode to receive any errors. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_setTimeZone(UCalendar* cal, - const UChar* zoneID, - int32_t len, - UErrorCode* status); - -/** - * Get the ID of the UCalendar's time zone. - * - * @param cal The UCalendar to query. - * @param result Receives the UCalendar's time zone ID. - * @param resultLength The maximum size of result. - * @param status Receives the status. - * @return The total buffer size needed; if greater than resultLength, the output was truncated. - * @stable ICU 51 - */ -U_STABLE int32_t U_EXPORT2 -ucal_getTimeZoneID(const UCalendar *cal, - UChar *result, - int32_t resultLength, - UErrorCode *status); - -/** - * Possible formats for a UCalendar's display name - * @stable ICU 2.0 - */ -enum UCalendarDisplayNameType { - /** Standard display name */ - UCAL_STANDARD, - /** Short standard display name */ - UCAL_SHORT_STANDARD, - /** Daylight savings display name */ - UCAL_DST, - /** Short daylight savings display name */ - UCAL_SHORT_DST -}; - -/** @stable ICU 2.0 */ -typedef enum UCalendarDisplayNameType UCalendarDisplayNameType; - -/** - * Get the display name for a UCalendar's TimeZone. - * A display name is suitable for presentation to a user. - * @param cal The UCalendar to query. - * @param type The desired display name format; one of UCAL_STANDARD, UCAL_SHORT_STANDARD, - * UCAL_DST, UCAL_SHORT_DST - * @param locale The desired locale for the display name. - * @param result A pointer to a buffer to receive the formatted number. - * @param resultLength The maximum size of result. - * @param status A pointer to an UErrorCode to receive any errors - * @return The total buffer size needed; if greater than resultLength, the output was truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucal_getTimeZoneDisplayName(const UCalendar* cal, - UCalendarDisplayNameType type, - const char* locale, - UChar* result, - int32_t resultLength, - UErrorCode* status); - -/** - * Determine if a UCalendar is currently in daylight savings time. - * Daylight savings time is not used in all parts of the world. - * @param cal The UCalendar to query. - * @param status A pointer to an UErrorCode to receive any errors - * @return TRUE if cal is currently in daylight savings time, FALSE otherwise - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -ucal_inDaylightTime(const UCalendar* cal, - UErrorCode* status ); - -/** - * Sets the GregorianCalendar change date. This is the point when the switch from - * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October - * 15, 1582. Previous to this time and date will be Julian dates. - * - * This function works only for Gregorian calendars. If the UCalendar is not - * an instance of a Gregorian calendar, then a U_UNSUPPORTED_ERROR - * error code is set. - * - * @param cal The calendar object. - * @param date The given Gregorian cutover date. - * @param pErrorCode Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * - * @see GregorianCalendar::setGregorianChange - * @see ucal_getGregorianChange - * @stable ICU 3.6 - */ -U_STABLE void U_EXPORT2 -ucal_setGregorianChange(UCalendar *cal, UDate date, UErrorCode *pErrorCode); - -/** - * Gets the Gregorian Calendar change date. This is the point when the switch from - * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October - * 15, 1582. Previous to this time and date will be Julian dates. - * - * This function works only for Gregorian calendars. If the UCalendar is not - * an instance of a Gregorian calendar, then a U_UNSUPPORTED_ERROR - * error code is set. - * - * @param cal The calendar object. - * @param pErrorCode Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The Gregorian cutover time for this calendar. - * - * @see GregorianCalendar::getGregorianChange - * @see ucal_setGregorianChange - * @stable ICU 3.6 - */ -U_STABLE UDate U_EXPORT2 -ucal_getGregorianChange(const UCalendar *cal, UErrorCode *pErrorCode); - -/** - * Types of UCalendar attributes - * @stable ICU 2.0 - */ -enum UCalendarAttribute { - /** - * Lenient parsing - * @stable ICU 2.0 - */ - UCAL_LENIENT, - /** - * First day of week - * @stable ICU 2.0 - */ - UCAL_FIRST_DAY_OF_WEEK, - /** - * Minimum number of days in first week - * @stable ICU 2.0 - */ - UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, - /** - * The behavior for handling wall time repeating multiple times - * at negative time zone offset transitions - * @stable ICU 49 - */ - UCAL_REPEATED_WALL_TIME, - /** - * The behavior for handling skipped wall time at positive time - * zone offset transitions. - * @stable ICU 49 - */ - UCAL_SKIPPED_WALL_TIME -}; - -/** @stable ICU 2.0 */ -typedef enum UCalendarAttribute UCalendarAttribute; - -/** - * Options for handling ambiguous wall time at time zone - * offset transitions. - * @stable ICU 49 - */ -enum UCalendarWallTimeOption { - /** - * An ambiguous wall time to be interpreted as the latest. - * This option is valid for UCAL_REPEATED_WALL_TIME and - * UCAL_SKIPPED_WALL_TIME. - * @stable ICU 49 - */ - UCAL_WALLTIME_LAST, - /** - * An ambiguous wall time to be interpreted as the earliest. - * This option is valid for UCAL_REPEATED_WALL_TIME and - * UCAL_SKIPPED_WALL_TIME. - * @stable ICU 49 - */ - UCAL_WALLTIME_FIRST, - /** - * An ambiguous wall time to be interpreted as the next valid - * wall time. This option is valid for UCAL_SKIPPED_WALL_TIME. - * @stable ICU 49 - */ - UCAL_WALLTIME_NEXT_VALID -}; -/** @stable ICU 49 */ -typedef enum UCalendarWallTimeOption UCalendarWallTimeOption; - -/** - * Get a numeric attribute associated with a UCalendar. - * Numeric attributes include the first day of the week, or the minimal numbers - * of days in the first week of the month. - * @param cal The UCalendar to query. - * @param attr The desired attribute; one of UCAL_LENIENT, UCAL_FIRST_DAY_OF_WEEK, - * UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, UCAL_REPEATED_WALL_TIME or UCAL_SKIPPED_WALL_TIME - * @return The value of attr. - * @see ucal_setAttribute - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucal_getAttribute(const UCalendar* cal, - UCalendarAttribute attr); - -/** - * Set a numeric attribute associated with a UCalendar. - * Numeric attributes include the first day of the week, or the minimal numbers - * of days in the first week of the month. - * @param cal The UCalendar to set. - * @param attr The desired attribute; one of UCAL_LENIENT, UCAL_FIRST_DAY_OF_WEEK, - * UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, UCAL_REPEATED_WALL_TIME or UCAL_SKIPPED_WALL_TIME - * @param newValue The new value of attr. - * @see ucal_getAttribute - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_setAttribute(UCalendar* cal, - UCalendarAttribute attr, - int32_t newValue); - -/** - * Get a locale for which calendars are available. - * A UCalendar in a locale returned by this function will contain the correct - * day and month names for the locale. - * @param localeIndex The index of the desired locale. - * @return A locale for which calendars are available, or 0 if none. - * @see ucal_countAvailable - * @stable ICU 2.0 - */ -U_STABLE const char* U_EXPORT2 -ucal_getAvailable(int32_t localeIndex); - -/** - * Determine how many locales have calendars available. - * This function is most useful as determining the loop ending condition for - * calls to \ref ucal_getAvailable. - * @return The number of locales for which calendars are available. - * @see ucal_getAvailable - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucal_countAvailable(void); - -/** - * Get a UCalendar's current time in millis. - * The time is represented as milliseconds from the epoch. - * @param cal The UCalendar to query. - * @param status A pointer to an UErrorCode to receive any errors - * @return The calendar's current time in millis. - * @see ucal_setMillis - * @see ucal_setDate - * @see ucal_setDateTime - * @stable ICU 2.0 - */ -U_STABLE UDate U_EXPORT2 -ucal_getMillis(const UCalendar* cal, - UErrorCode* status); - -/** - * Set a UCalendar's current time in millis. - * The time is represented as milliseconds from the epoch. - * @param cal The UCalendar to set. - * @param dateTime The desired date and time. - * @param status A pointer to an UErrorCode to receive any errors - * @see ucal_getMillis - * @see ucal_setDate - * @see ucal_setDateTime - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_setMillis(UCalendar* cal, - UDate dateTime, - UErrorCode* status ); - -/** - * Set a UCalendar's current date. - * The date is represented as a series of 32-bit integers. - * @param cal The UCalendar to set. - * @param year The desired year. - * @param month The desired month; one of UCAL_JANUARY, UCAL_FEBRUARY, UCAL_MARCH, UCAL_APRIL, UCAL_MAY, - * UCAL_JUNE, UCAL_JULY, UCAL_AUGUST, UCAL_SEPTEMBER, UCAL_OCTOBER, UCAL_NOVEMBER, UCAL_DECEMBER, UCAL_UNDECIMBER - * @param date The desired day of the month. - * @param status A pointer to an UErrorCode to receive any errors - * @see ucal_getMillis - * @see ucal_setMillis - * @see ucal_setDateTime - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_setDate(UCalendar* cal, - int32_t year, - int32_t month, - int32_t date, - UErrorCode* status); - -/** - * Set a UCalendar's current date. - * The date is represented as a series of 32-bit integers. - * @param cal The UCalendar to set. - * @param year The desired year. - * @param month The desired month; one of UCAL_JANUARY, UCAL_FEBRUARY, UCAL_MARCH, UCAL_APRIL, UCAL_MAY, - * UCAL_JUNE, UCAL_JULY, UCAL_AUGUST, UCAL_SEPTEMBER, UCAL_OCTOBER, UCAL_NOVEMBER, UCAL_DECEMBER, UCAL_UNDECIMBER - * @param date The desired day of the month. - * @param hour The desired hour of day. - * @param minute The desired minute. - * @param second The desirec second. - * @param status A pointer to an UErrorCode to receive any errors - * @see ucal_getMillis - * @see ucal_setMillis - * @see ucal_setDate - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_setDateTime(UCalendar* cal, - int32_t year, - int32_t month, - int32_t date, - int32_t hour, - int32_t minute, - int32_t second, - UErrorCode* status); - -/** - * Returns TRUE if two UCalendars are equivalent. Equivalent - * UCalendars will behave identically, but they may be set to - * different times. - * @param cal1 The first of the UCalendars to compare. - * @param cal2 The second of the UCalendars to compare. - * @return TRUE if cal1 and cal2 are equivalent, FALSE otherwise. - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -ucal_equivalentTo(const UCalendar* cal1, - const UCalendar* cal2); - -/** - * Add a specified signed amount to a particular field in a UCalendar. - * This can modify more significant fields in the calendar. - * Adding a positive value always means moving forward in time, so for the Gregorian calendar, - * starting with 100 BC and adding +1 to year results in 99 BC (even though this actually reduces - * the numeric value of the field itself). - * @param cal The UCalendar to which to add. - * @param field The field to which to add the signed value; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, - * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, - * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, - * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. - * @param amount The signed amount to add to field. If the amount causes the value - * to exceed to maximum or minimum values for that field, other fields are modified - * to preserve the magnitude of the change. - * @param status A pointer to an UErrorCode to receive any errors - * @see ucal_roll - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_add(UCalendar* cal, - UCalendarDateFields field, - int32_t amount, - UErrorCode* status); - -/** - * Add a specified signed amount to a particular field in a UCalendar. - * This will not modify more significant fields in the calendar. - * Rolling by a positive value always means moving forward in time (unless the limit of the - * field is reached, in which case it may pin or wrap), so for Gregorian calendar, - * starting with 100 BC and rolling the year by +1 results in 99 BC. - * When eras have a definite beginning and end (as in the Chinese calendar, or as in most eras in the - * Japanese calendar) then rolling the year past either limit of the era will cause the year to wrap around. - * When eras only have a limit at one end, then attempting to roll the year past that limit will result in - * pinning the year at that limit. Note that for most calendars in which era 0 years move forward in time - * (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to result in negative years for - * era 0 (that is the only way to represent years before the calendar epoch). - * @param cal The UCalendar to which to add. - * @param field The field to which to add the signed value; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, - * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, - * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, - * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. - * @param amount The signed amount to add to field. If the amount causes the value - * to exceed to maximum or minimum values for that field, the field is pinned to a permissible - * value. - * @param status A pointer to an UErrorCode to receive any errors - * @see ucal_add - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_roll(UCalendar* cal, - UCalendarDateFields field, - int32_t amount, - UErrorCode* status); - -/** - * Get the current value of a field from a UCalendar. - * All fields are represented as 32-bit integers. - * @param cal The UCalendar to query. - * @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, - * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, - * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, - * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. - * @param status A pointer to an UErrorCode to receive any errors - * @return The value of the desired field. - * @see ucal_set - * @see ucal_isSet - * @see ucal_clearField - * @see ucal_clear - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucal_get(const UCalendar* cal, - UCalendarDateFields field, - UErrorCode* status ); - -/** - * Set the value of a field in a UCalendar. - * All fields are represented as 32-bit integers. - * @param cal The UCalendar to set. - * @param field The field to set; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, - * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, - * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, - * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. - * @param value The desired value of field. - * @see ucal_get - * @see ucal_isSet - * @see ucal_clearField - * @see ucal_clear - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_set(UCalendar* cal, - UCalendarDateFields field, - int32_t value); - -/** - * Determine if a field in a UCalendar is set. - * All fields are represented as 32-bit integers. - * @param cal The UCalendar to query. - * @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, - * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, - * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, - * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. - * @return TRUE if field is set, FALSE otherwise. - * @see ucal_get - * @see ucal_set - * @see ucal_clearField - * @see ucal_clear - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -ucal_isSet(const UCalendar* cal, - UCalendarDateFields field); - -/** - * Clear a field in a UCalendar. - * All fields are represented as 32-bit integers. - * @param cal The UCalendar containing the field to clear. - * @param field The field to clear; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, - * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, - * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, - * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. - * @see ucal_get - * @see ucal_set - * @see ucal_isSet - * @see ucal_clear - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_clearField(UCalendar* cal, - UCalendarDateFields field); - -/** - * Clear all fields in a UCalendar. - * All fields are represented as 32-bit integers. - * @param calendar The UCalendar to clear. - * @see ucal_get - * @see ucal_set - * @see ucal_isSet - * @see ucal_clearField - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucal_clear(UCalendar* calendar); - -/** - * Possible limit values for a UCalendar - * @stable ICU 2.0 - */ -enum UCalendarLimitType { - /** Minimum value */ - UCAL_MINIMUM, - /** Maximum value */ - UCAL_MAXIMUM, - /** Greatest minimum value */ - UCAL_GREATEST_MINIMUM, - /** Leaest maximum value */ - UCAL_LEAST_MAXIMUM, - /** Actual minimum value */ - UCAL_ACTUAL_MINIMUM, - /** Actual maximum value */ - UCAL_ACTUAL_MAXIMUM -}; - -/** @stable ICU 2.0 */ -typedef enum UCalendarLimitType UCalendarLimitType; - -/** - * Determine a limit for a field in a UCalendar. - * A limit is a maximum or minimum value for a field. - * @param cal The UCalendar to query. - * @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, - * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, - * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, - * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. - * @param type The desired critical point; one of UCAL_MINIMUM, UCAL_MAXIMUM, UCAL_GREATEST_MINIMUM, - * UCAL_LEAST_MAXIMUM, UCAL_ACTUAL_MINIMUM, UCAL_ACTUAL_MAXIMUM - * @param status A pointer to an UErrorCode to receive any errors. - * @return The requested value. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucal_getLimit(const UCalendar* cal, - UCalendarDateFields field, - UCalendarLimitType type, - UErrorCode* status); - -/** Get the locale for this calendar object. You can choose between valid and actual locale. - * @param cal The calendar object - * @param type type of the locale we're looking for (valid or actual) - * @param status error code for the operation - * @return the locale name - * @stable ICU 2.8 - */ -U_STABLE const char * U_EXPORT2 -ucal_getLocaleByType(const UCalendar *cal, ULocDataLocaleType type, UErrorCode* status); - -/** - * Returns the timezone data version currently used by ICU. - * @param status error code for the operation - * @return the version string, such as "2007f" - * @stable ICU 3.8 - */ -U_STABLE const char * U_EXPORT2 -ucal_getTZDataVersion(UErrorCode* status); - -/** - * Returns the canonical system timezone ID or the normalized - * custom time zone ID for the given time zone ID. - * @param id The input timezone ID to be canonicalized. - * @param len The length of id, or -1 if null-terminated. - * @param result The buffer receives the canonical system timezone ID - * or the custom timezone ID in normalized format. - * @param resultCapacity The capacity of the result buffer. - * @param isSystemID Receives if the given ID is a known system - * timezone ID. - * @param status Receives the status. When the given timezone ID - * is neither a known system time zone ID nor a - * valid custom timezone ID, U_ILLEGAL_ARGUMENT_ERROR - * is set. - * @return The result string length, not including the terminating - * null. - * @stable ICU 4.0 - */ -U_STABLE int32_t U_EXPORT2 -ucal_getCanonicalTimeZoneID(const UChar* id, int32_t len, - UChar* result, int32_t resultCapacity, UBool *isSystemID, UErrorCode* status); -/** - * Get the resource keyword value string designating the calendar type for the UCalendar. - * @param cal The UCalendar to query. - * @param status The error code for the operation. - * @return The resource keyword value string. - * @stable ICU 4.2 - */ -U_STABLE const char * U_EXPORT2 -ucal_getType(const UCalendar *cal, UErrorCode* status); - -/** - * Given a key and a locale, returns an array of string values in a preferred - * order that would make a difference. These are all and only those values where - * the open (creation) of the service with the locale formed from the input locale - * plus input keyword and that value has different behavior than creation with the - * input locale alone. - * @param key one of the keys supported by this service. For now, only - * "calendar" is supported. - * @param locale the locale - * @param commonlyUsed if set to true it will return only commonly used values - * with the given locale in preferred order. Otherwise, - * it will return all the available values for the locale. - * @param status error status - * @return a string enumeration over keyword values for the given key and the locale. - * @stable ICU 4.2 - */ -U_STABLE UEnumeration* U_EXPORT2 -ucal_getKeywordValuesForLocale(const char* key, - const char* locale, - UBool commonlyUsed, - UErrorCode* status); - - -/** Weekday types, as returned by ucal_getDayOfWeekType(). - * @stable ICU 4.4 - */ -enum UCalendarWeekdayType { - /** - * Designates a full weekday (no part of the day is included in the weekend). - * @stable ICU 4.4 - */ - UCAL_WEEKDAY, - /** - * Designates a full weekend day (the entire day is included in the weekend). - * @stable ICU 4.4 - */ - UCAL_WEEKEND, - /** - * Designates a day that starts as a weekday and transitions to the weekend. - * Call ucal_getWeekendTransition() to get the time of transition. - * @stable ICU 4.4 - */ - UCAL_WEEKEND_ONSET, - /** - * Designates a day that starts as the weekend and transitions to a weekday. - * Call ucal_getWeekendTransition() to get the time of transition. - * @stable ICU 4.4 - */ - UCAL_WEEKEND_CEASE -}; - -/** @stable ICU 4.4 */ -typedef enum UCalendarWeekdayType UCalendarWeekdayType; - -/** - * Returns whether the given day of the week is a weekday, a weekend day, - * or a day that transitions from one to the other, for the locale and - * calendar system associated with this UCalendar (the locale's region is - * often the most determinant factor). If a transition occurs at midnight, - * then the days before and after the transition will have the - * type UCAL_WEEKDAY or UCAL_WEEKEND. If a transition occurs at a time - * other than midnight, then the day of the transition will have - * the type UCAL_WEEKEND_ONSET or UCAL_WEEKEND_CEASE. In this case, the - * function ucal_getWeekendTransition() will return the point of - * transition. - * @param cal The UCalendar to query. - * @param dayOfWeek The day of the week whose type is desired (UCAL_SUNDAY..UCAL_SATURDAY). - * @param status The error code for the operation. - * @return The UCalendarWeekdayType for the day of the week. - * @stable ICU 4.4 - */ -U_STABLE UCalendarWeekdayType U_EXPORT2 -ucal_getDayOfWeekType(const UCalendar *cal, UCalendarDaysOfWeek dayOfWeek, UErrorCode* status); - -/** - * Returns the time during the day at which the weekend begins or ends in - * this calendar system. If ucal_getDayOfWeekType() returns UCAL_WEEKEND_ONSET - * for the specified dayOfWeek, return the time at which the weekend begins. - * If ucal_getDayOfWeekType() returns UCAL_WEEKEND_CEASE for the specified dayOfWeek, - * return the time at which the weekend ends. If ucal_getDayOfWeekType() returns - * some other UCalendarWeekdayType for the specified dayOfWeek, is it an error condition - * (U_ILLEGAL_ARGUMENT_ERROR). - * @param cal The UCalendar to query. - * @param dayOfWeek The day of the week for which the weekend transition time is - * desired (UCAL_SUNDAY..UCAL_SATURDAY). - * @param status The error code for the operation. - * @return The milliseconds after midnight at which the weekend begins or ends. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -ucal_getWeekendTransition(const UCalendar *cal, UCalendarDaysOfWeek dayOfWeek, UErrorCode *status); - -/** - * Returns TRUE if the given UDate is in the weekend in - * this calendar system. - * @param cal The UCalendar to query. - * @param date The UDate in question. - * @param status The error code for the operation. - * @return TRUE if the given UDate is in the weekend in - * this calendar system, FALSE otherwise. - * @stable ICU 4.4 - */ -U_STABLE UBool U_EXPORT2 -ucal_isWeekend(const UCalendar *cal, UDate date, UErrorCode *status); - -/** - * Return the difference between the target time and the time this calendar object is currently set to. - * If the target time is after the current calendar setting, the the returned value will be positive. - * The field parameter specifies the units of the return value. For example, if field is UCAL_MONTH - * and ucal_getFieldDifference returns 3, then the target time is 3 to less than 4 months after the - * current calendar setting. - * - * As a side effect of this call, this calendar is advanced toward target by the given amount. That is, - * calling this function has the side effect of calling ucal_add on this calendar with the specified - * field and an amount equal to the return value from this function. - * - * A typical way of using this function is to call it first with the largest field of interest, then - * with progressively smaller fields. - * - * @param cal The UCalendar to compare and update. - * @param target The target date to compare to the current calendar setting. - * @param field The field to compare; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH, - * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK, - * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND, - * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET. - * @param status A pointer to an UErrorCode to receive any errors - * @return The date difference for the specified field. - * @stable ICU 4.8 - */ -U_STABLE int32_t U_EXPORT2 -ucal_getFieldDifference(UCalendar* cal, - UDate target, - UCalendarDateFields field, - UErrorCode* status); - -/** - * Time zone transition types for ucal_getTimeZoneTransitionDate - * @stable ICU 50 - */ -enum UTimeZoneTransitionType { - /** - * Get the next transition after the current date, - * i.e. excludes the current date - * @stable ICU 50 - */ - UCAL_TZ_TRANSITION_NEXT, - /** - * Get the next transition on or after the current date, - * i.e. may include the current date - * @stable ICU 50 - */ - UCAL_TZ_TRANSITION_NEXT_INCLUSIVE, - /** - * Get the previous transition before the current date, - * i.e. excludes the current date - * @stable ICU 50 - */ - UCAL_TZ_TRANSITION_PREVIOUS, - /** - * Get the previous transition on or before the current date, - * i.e. may include the current date - * @stable ICU 50 - */ - UCAL_TZ_TRANSITION_PREVIOUS_INCLUSIVE -}; - -typedef enum UTimeZoneTransitionType UTimeZoneTransitionType; /**< @stable ICU 50 */ - -/** -* Get the UDate for the next/previous time zone transition relative to -* the calendar's current date, in the time zone to which the calendar -* is currently set. If there is no known time zone transition of the -* requested type relative to the calendar's date, the function returns -* FALSE. -* @param cal The UCalendar to query. -* @param type The type of transition desired. -* @param transition A pointer to a UDate to be set to the transition time. -* If the function returns FALSE, the value set is unspecified. -* @param status A pointer to a UErrorCode to receive any errors. -* @return TRUE if a valid transition time is set in *transition, FALSE -* otherwise. -* @stable ICU 50 -*/ -U_STABLE UBool U_EXPORT2 -ucal_getTimeZoneTransitionDate(const UCalendar* cal, UTimeZoneTransitionType type, - UDate* transition, UErrorCode* status); - -/** -* Converts a system time zone ID to an equivalent Windows time zone ID. For example, -* Windows time zone ID "Pacific Standard Time" is returned for input "America/Los_Angeles". -* -*

There are system time zones that cannot be mapped to Windows zones. When the input -* system time zone ID is unknown or unmappable to a Windows time zone, then this -* function returns 0 as the result length, but the operation itself remains successful -* (no error status set on return). -* -*

This implementation utilizes -* Zone-Tzid mapping data. The mapping data is updated time to time. To get the latest changes, -* please read the ICU user guide section -* Updating the Time Zone Data. -* -* @param id A system time zone ID. -* @param len The length of id, or -1 if null-terminated. -* @param winid A buffer to receive a Windows time zone ID. -* @param winidCapacity The capacity of the result buffer winid. -* @param status Receives the status. -* @return The result string length, not including the terminating null. -* @see ucal_getTimeZoneIDForWindowsID -* -* @stable ICU 52 -*/ -U_STABLE int32_t U_EXPORT2 -ucal_getWindowsTimeZoneID(const UChar* id, int32_t len, - UChar* winid, int32_t winidCapacity, UErrorCode* status); - -/** -* Converts a Windows time zone ID to an equivalent system time zone ID -* for a region. For example, system time zone ID "America/Los_Angeles" is returned -* for input Windows ID "Pacific Standard Time" and region "US" (or null), -* "America/Vancouver" is returned for the same Windows ID "Pacific Standard Time" and -* region "CA". -* -*

Not all Windows time zones can be mapped to system time zones. When the input -* Windows time zone ID is unknown or unmappable to a system time zone, then this -* function returns 0 as the result length, but the operation itself remains successful -* (no error status set on return). -* -*

This implementation utilizes -* Zone-Tzid mapping data. The mapping data is updated time to time. To get the latest changes, -* please read the ICU user guide section -* Updating the Time Zone Data. -* -* @param winid A Windows time zone ID. -* @param len The length of winid, or -1 if null-terminated. -* @param region A null-terminated region code, or NULL if no regional preference. -* @param id A buffer to receive a system time zone ID. -* @param idCapacity The capacity of the result buffer id. -* @param status Receives the status. -* @return The result string length, not including the terminating null. -* @see ucal_getWindowsTimeZoneID -* -* @stable ICU 52 -*/ -U_STABLE int32_t U_EXPORT2 -ucal_getTimeZoneIDForWindowsID(const UChar* winid, int32_t len, const char* region, - UChar* id, int32_t idCapacity, UErrorCode* status); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/ucasemap.h b/win32/include/spidermonkey/unicode/ucasemap.h deleted file mode 100755 index d7345e8a..00000000 --- a/win32/include/spidermonkey/unicode/ucasemap.h +++ /dev/null @@ -1,425 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2005-2012, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: ucasemap.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2005may06 -* created by: Markus W. Scherer -* -* Case mapping service object and functions using it. -*/ - -#ifndef __UCASEMAP_H__ -#define __UCASEMAP_H__ - -#include "unicode/utypes.h" -#include "unicode/ustring.h" -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: Unicode case mapping functions using a UCaseMap service object. - * - * The service object takes care of memory allocations, data loading, and setup - * for the attributes, as usual. - * - * Currently, the functionality provided here does not overlap with uchar.h - * and ustring.h, except for ucasemap_toTitle(). - * - * ucasemap_utf8XYZ() functions operate directly on UTF-8 strings. - */ - -/** - * UCaseMap is an opaque service object for newer ICU case mapping functions. - * Older functions did not use a service object. - * @stable ICU 3.4 - */ -struct UCaseMap; -typedef struct UCaseMap UCaseMap; /**< C typedef for struct UCaseMap. @stable ICU 3.4 */ - -/** - * Open a UCaseMap service object for a locale and a set of options. - * The locale ID and options are preprocessed so that functions using the - * service object need not process them in each call. - * - * @param locale ICU locale ID, used for language-dependent - * upper-/lower-/title-casing according to the Unicode standard. - * Usual semantics: ""=root, NULL=default locale, etc. - * @param options Options bit set, used for case folding and string comparisons. - * Same flags as for u_foldCase(), u_strFoldCase(), - * u_strCaseCompare(), etc. - * Use 0 or U_FOLD_CASE_DEFAULT for default behavior. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return Pointer to a UCaseMap service object, if successful. - * - * @see U_FOLD_CASE_DEFAULT - * @see U_FOLD_CASE_EXCLUDE_SPECIAL_I - * @see U_TITLECASE_NO_LOWERCASE - * @see U_TITLECASE_NO_BREAK_ADJUSTMENT - * @stable ICU 3.4 - */ -U_STABLE UCaseMap * U_EXPORT2 -ucasemap_open(const char *locale, uint32_t options, UErrorCode *pErrorCode); - -/** - * Close a UCaseMap service object. - * @param csm Object to be closed. - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -ucasemap_close(UCaseMap *csm); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUCaseMapPointer - * "Smart pointer" class, closes a UCaseMap via ucasemap_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUCaseMapPointer, UCaseMap, ucasemap_close); - -U_NAMESPACE_END - -#endif - -/** - * Get the locale ID that is used for language-dependent case mappings. - * @param csm UCaseMap service object. - * @return locale ID - * @stable ICU 3.4 - */ -U_STABLE const char * U_EXPORT2 -ucasemap_getLocale(const UCaseMap *csm); - -/** - * Get the options bit set that is used for case folding and string comparisons. - * @param csm UCaseMap service object. - * @return options bit set - * @stable ICU 3.4 - */ -U_STABLE uint32_t U_EXPORT2 -ucasemap_getOptions(const UCaseMap *csm); - -/** - * Set the locale ID that is used for language-dependent case mappings. - * - * @param csm UCaseMap service object. - * @param locale Locale ID, see ucasemap_open(). - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * - * @see ucasemap_open - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -ucasemap_setLocale(UCaseMap *csm, const char *locale, UErrorCode *pErrorCode); - -/** - * Set the options bit set that is used for case folding and string comparisons. - * - * @param csm UCaseMap service object. - * @param options Options bit set, see ucasemap_open(). - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * - * @see ucasemap_open - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -ucasemap_setOptions(UCaseMap *csm, uint32_t options, UErrorCode *pErrorCode); - -/** - * Do not lowercase non-initial parts of words when titlecasing. - * Option bit for titlecasing APIs that take an options bit set. - * - * By default, titlecasing will titlecase the first cased character - * of a word and lowercase all other characters. - * With this option, the other characters will not be modified. - * - * @see ucasemap_setOptions - * @see ucasemap_toTitle - * @see ucasemap_utf8ToTitle - * @see UnicodeString::toTitle - * @stable ICU 3.8 - */ -#define U_TITLECASE_NO_LOWERCASE 0x100 - -/** - * Do not adjust the titlecasing indexes from BreakIterator::next() indexes; - * titlecase exactly the characters at breaks from the iterator. - * Option bit for titlecasing APIs that take an options bit set. - * - * By default, titlecasing will take each break iterator index, - * adjust it by looking for the next cased character, and titlecase that one. - * Other characters are lowercased. - * - * This follows Unicode 4 & 5 section 3.13 Default Case Operations: - * - * R3 toTitlecase(X): Find the word boundaries based on Unicode Standard Annex - * #29, "Text Boundaries." Between each pair of word boundaries, find the first - * cased character F. If F exists, map F to default_title(F); then map each - * subsequent character C to default_lower(C). - * - * @see ucasemap_setOptions - * @see ucasemap_toTitle - * @see ucasemap_utf8ToTitle - * @see UnicodeString::toTitle - * @see U_TITLECASE_NO_LOWERCASE - * @stable ICU 3.8 - */ -#define U_TITLECASE_NO_BREAK_ADJUSTMENT 0x200 - -#if !UCONFIG_NO_BREAK_ITERATION - -/** - * Get the break iterator that is used for titlecasing. - * Do not modify the returned break iterator. - * @param csm UCaseMap service object. - * @return titlecasing break iterator - * @stable ICU 3.8 - */ -U_STABLE const UBreakIterator * U_EXPORT2 -ucasemap_getBreakIterator(const UCaseMap *csm); - -/** - * Set the break iterator that is used for titlecasing. - * The UCaseMap service object releases a previously set break iterator - * and "adopts" this new one, taking ownership of it. - * It will be released in a subsequent call to ucasemap_setBreakIterator() - * or ucasemap_close(). - * - * Break iterator operations are not thread-safe. Therefore, titlecasing - * functions use non-const UCaseMap objects. It is not possible to titlecase - * strings concurrently using the same UCaseMap. - * - * @param csm UCaseMap service object. - * @param iterToAdopt Break iterator to be adopted for titlecasing. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * - * @see ucasemap_toTitle - * @see ucasemap_utf8ToTitle - * @stable ICU 3.8 - */ -U_STABLE void U_EXPORT2 -ucasemap_setBreakIterator(UCaseMap *csm, UBreakIterator *iterToAdopt, UErrorCode *pErrorCode); - -/** - * Titlecase a UTF-16 string. This function is almost a duplicate of u_strToTitle(), - * except that it takes ucasemap_setOptions() into account and has performance - * advantages from being able to use a UCaseMap object for multiple case mapping - * operations, saving setup time. - * - * Casing is locale-dependent and context-sensitive. - * Titlecasing uses a break iterator to find the first characters of words - * that are to be titlecased. It titlecases those characters and lowercases - * all others. (This can be modified with ucasemap_setOptions().) - * - * Note: This function takes a non-const UCaseMap pointer because it will - * open a default break iterator if no break iterator was set yet, - * and effectively call ucasemap_setBreakIterator(); - * also because the break iterator is stateful and will be modified during - * the iteration. - * - * The titlecase break iterator can be provided to customize for arbitrary - * styles, using rules and dictionaries beyond the standard iterators. - * The standard titlecase iterator for the root locale implements the - * algorithm of Unicode TR 21. - * - * This function uses only the setUText(), first(), next() and close() methods of the - * provided break iterator. - * - * The result may be longer or shorter than the original. - * The source string and the destination buffer must not overlap. - * - * @param csm UCaseMap service object. This pointer is non-const! - * See the note above for details. - * @param dest A buffer for the result string. The result will be NUL-terminated if - * the buffer is large enough. - * The contents is undefined in case of failure. - * @param destCapacity The size of the buffer (number of bytes). If it is 0, then - * dest may be NULL and the function will only return the length of the result - * without writing any of the result string. - * @param src The original string. - * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The length of the result string, if successful - or in case of a buffer overflow, - * in which case it will be greater than destCapacity. - * - * @see u_strToTitle - * @stable ICU 3.8 - */ -U_STABLE int32_t U_EXPORT2 -ucasemap_toTitle(UCaseMap *csm, - UChar *dest, int32_t destCapacity, - const UChar *src, int32_t srcLength, - UErrorCode *pErrorCode); - -#endif - -/** - * Lowercase the characters in a UTF-8 string. - * Casing is locale-dependent and context-sensitive. - * The result may be longer or shorter than the original. - * The source string and the destination buffer must not overlap. - * - * @param csm UCaseMap service object. - * @param dest A buffer for the result string. The result will be NUL-terminated if - * the buffer is large enough. - * The contents is undefined in case of failure. - * @param destCapacity The size of the buffer (number of bytes). If it is 0, then - * dest may be NULL and the function will only return the length of the result - * without writing any of the result string. - * @param src The original string. - * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The length of the result string, if successful - or in case of a buffer overflow, - * in which case it will be greater than destCapacity. - * - * @see u_strToLower - * @stable ICU 3.4 - */ -U_STABLE int32_t U_EXPORT2 -ucasemap_utf8ToLower(const UCaseMap *csm, - char *dest, int32_t destCapacity, - const char *src, int32_t srcLength, - UErrorCode *pErrorCode); - -/** - * Uppercase the characters in a UTF-8 string. - * Casing is locale-dependent and context-sensitive. - * The result may be longer or shorter than the original. - * The source string and the destination buffer must not overlap. - * - * @param csm UCaseMap service object. - * @param dest A buffer for the result string. The result will be NUL-terminated if - * the buffer is large enough. - * The contents is undefined in case of failure. - * @param destCapacity The size of the buffer (number of bytes). If it is 0, then - * dest may be NULL and the function will only return the length of the result - * without writing any of the result string. - * @param src The original string. - * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The length of the result string, if successful - or in case of a buffer overflow, - * in which case it will be greater than destCapacity. - * - * @see u_strToUpper - * @stable ICU 3.4 - */ -U_STABLE int32_t U_EXPORT2 -ucasemap_utf8ToUpper(const UCaseMap *csm, - char *dest, int32_t destCapacity, - const char *src, int32_t srcLength, - UErrorCode *pErrorCode); - -#if !UCONFIG_NO_BREAK_ITERATION - -/** - * Titlecase a UTF-8 string. - * Casing is locale-dependent and context-sensitive. - * Titlecasing uses a break iterator to find the first characters of words - * that are to be titlecased. It titlecases those characters and lowercases - * all others. (This can be modified with ucasemap_setOptions().) - * - * Note: This function takes a non-const UCaseMap pointer because it will - * open a default break iterator if no break iterator was set yet, - * and effectively call ucasemap_setBreakIterator(); - * also because the break iterator is stateful and will be modified during - * the iteration. - * - * The titlecase break iterator can be provided to customize for arbitrary - * styles, using rules and dictionaries beyond the standard iterators. - * The standard titlecase iterator for the root locale implements the - * algorithm of Unicode TR 21. - * - * This function uses only the setUText(), first(), next() and close() methods of the - * provided break iterator. - * - * The result may be longer or shorter than the original. - * The source string and the destination buffer must not overlap. - * - * @param csm UCaseMap service object. This pointer is non-const! - * See the note above for details. - * @param dest A buffer for the result string. The result will be NUL-terminated if - * the buffer is large enough. - * The contents is undefined in case of failure. - * @param destCapacity The size of the buffer (number of bytes). If it is 0, then - * dest may be NULL and the function will only return the length of the result - * without writing any of the result string. - * @param src The original string. - * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The length of the result string, if successful - or in case of a buffer overflow, - * in which case it will be greater than destCapacity. - * - * @see u_strToTitle - * @see U_TITLECASE_NO_LOWERCASE - * @see U_TITLECASE_NO_BREAK_ADJUSTMENT - * @stable ICU 3.8 - */ -U_STABLE int32_t U_EXPORT2 -ucasemap_utf8ToTitle(UCaseMap *csm, - char *dest, int32_t destCapacity, - const char *src, int32_t srcLength, - UErrorCode *pErrorCode); - -#endif - -/** - * Case-folds the characters in a UTF-8 string. - * - * Case-folding is locale-independent and not context-sensitive, - * but there is an option for whether to include or exclude mappings for dotted I - * and dotless i that are marked with 'T' in CaseFolding.txt. - * - * The result may be longer or shorter than the original. - * The source string and the destination buffer must not overlap. - * - * @param csm UCaseMap service object. - * @param dest A buffer for the result string. The result will be NUL-terminated if - * the buffer is large enough. - * The contents is undefined in case of failure. - * @param destCapacity The size of the buffer (number of bytes). If it is 0, then - * dest may be NULL and the function will only return the length of the result - * without writing any of the result string. - * @param src The original string. - * @param srcLength The length of the original string. If -1, then src must be NUL-terminated. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The length of the result string, if successful - or in case of a buffer overflow, - * in which case it will be greater than destCapacity. - * - * @see u_strFoldCase - * @see ucasemap_setOptions - * @see U_FOLD_CASE_DEFAULT - * @see U_FOLD_CASE_EXCLUDE_SPECIAL_I - * @stable ICU 3.8 - */ -U_STABLE int32_t U_EXPORT2 -ucasemap_utf8FoldCase(const UCaseMap *csm, - char *dest, int32_t destCapacity, - const char *src, int32_t srcLength, - UErrorCode *pErrorCode); - -#endif diff --git a/win32/include/spidermonkey/unicode/ucat.h b/win32/include/spidermonkey/unicode/ucat.h deleted file mode 100755 index c52e4d91..00000000 --- a/win32/include/spidermonkey/unicode/ucat.h +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2003-2004, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* Author: Alan Liu -* Created: March 19 2003 -* Since: ICU 2.6 -********************************************************************** -*/ -#ifndef UCAT_H -#define UCAT_H - -#include "unicode/utypes.h" -#include "unicode/ures.h" - -/** - * \file - * \brief C API: Message Catalog Wrappers - * - * This C API provides look-alike functions that deliberately resemble - * the POSIX catopen, catclose, and catgets functions. The underlying - * implementation is in terms of ICU resource bundles, rather than - * POSIX message catalogs. - * - * The ICU resource bundles obey standard ICU inheritance policies. - * To facilitate this, sets and messages are flattened into one tier. - * This is done by creating resource bundle keys of the form - * <set_num>%<msg_num> where set_num is the set number and msg_num is - * the message number, formatted as decimal strings. - * - * Example: Consider a message catalog containing two sets: - * - * Set 1: Message 4 = "Good morning." - * Message 5 = "Good afternoon." - * Message 7 = "Good evening." - * Message 8 = "Good night." - * Set 4: Message 14 = "Please " - * Message 19 = "Thank you." - * Message 20 = "Sincerely," - * - * The ICU resource bundle source file would, assuming it is named - * "greet.txt", would look like this: - * - * greet - * { - * 1%4 { "Good morning." } - * 1%5 { "Good afternoon." } - * 1%7 { "Good evening." } - * 1%8 { "Good night." } - * - * 4%14 { "Please " } - * 4%19 { "Thank you." } - * 4%20 { "Sincerely," } - * } - * - * The catgets function is commonly used in combination with functions - * like printf and strftime. ICU components like message format can - * be used instead, although they use a different format syntax. - * There is an ICU package, icuio, that provides some of - * the POSIX-style formatting API. - */ - -U_CDECL_BEGIN - -/** - * An ICU message catalog descriptor, analogous to nl_catd. - * - * @stable ICU 2.6 - */ -typedef UResourceBundle* u_nl_catd; - -/** - * Open and return an ICU message catalog descriptor. The descriptor - * may be passed to u_catgets() to retrieve localized strings. - * - * @param name string containing the full path pointing to the - * directory where the resources reside followed by the package name - * e.g. "/usr/resource/my_app/resources/guimessages" on a Unix system. - * If NULL, ICU default data files will be used. - * - * Unlike POSIX, environment variables are not interpolated within the - * name. - * - * @param locale the locale for which we want to open the resource. If - * NULL, the default ICU locale will be used (see uloc_getDefault). If - * strlen(locale) == 0, the root locale will be used. - * - * @param ec input/output error code. Upon output, - * U_USING_FALLBACK_WARNING indicates that a fallback locale was - * used. For example, 'de_CH' was requested, but nothing was found - * there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that the - * default locale data or root locale data was used; neither the - * requested locale nor any of its fallback locales were found. - * - * @return a message catalog descriptor that may be passed to - * u_catgets(). If the ec parameter indicates success, then the caller - * is responsible for calling u_catclose() to close the message - * catalog. If the ec parameter indicates failure, then NULL will be - * returned. - * - * @stable ICU 2.6 - */ -U_STABLE u_nl_catd U_EXPORT2 -u_catopen(const char* name, const char* locale, UErrorCode* ec); - -/** - * Close an ICU message catalog, given its descriptor. - * - * @param catd a message catalog descriptor to be closed. May be NULL, - * in which case no action is taken. - * - * @stable ICU 2.6 - */ -U_STABLE void U_EXPORT2 -u_catclose(u_nl_catd catd); - -/** - * Retrieve a localized string from an ICU message catalog. - * - * @param catd a message catalog descriptor returned by u_catopen. - * - * @param set_num the message catalog set number. Sets need not be - * numbered consecutively. - * - * @param msg_num the message catalog message number within the - * set. Messages need not be numbered consecutively. - * - * @param s the default string. This is returned if the string - * specified by the set_num and msg_num is not found. It must be - * zero-terminated. - * - * @param len fill-in parameter to receive the length of the result. - * May be NULL, in which case it is ignored. - * - * @param ec input/output error code. May be U_USING_FALLBACK_WARNING - * or U_USING_DEFAULT_WARNING. U_MISSING_RESOURCE_ERROR indicates that - * the set_num/msg_num tuple does not specify a valid message string - * in this catalog. - * - * @return a pointer to a zero-terminated UChar array which lives in - * an internal buffer area, typically a memory mapped/DLL file. The - * caller must NOT delete this pointer. If the call is unsuccessful - * for any reason, then s is returned. This includes the situation in - * which ec indicates a failing error code upon entry to this - * function. - * - * @stable ICU 2.6 - */ -U_STABLE const UChar* U_EXPORT2 -u_catgets(u_nl_catd catd, int32_t set_num, int32_t msg_num, - const UChar* s, - int32_t* len, UErrorCode* ec); - -U_CDECL_END - -#endif /*UCAT_H*/ -/*eof*/ diff --git a/win32/include/spidermonkey/unicode/uchar.h b/win32/include/spidermonkey/unicode/uchar.h deleted file mode 100755 index 7f6ea6d9..00000000 --- a/win32/include/spidermonkey/unicode/uchar.h +++ /dev/null @@ -1,3706 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1997-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* -* File UCHAR.H -* -* Modification History: -* -* Date Name Description -* 04/02/97 aliu Creation. -* 03/29/99 helena Updated for C APIs. -* 4/15/99 Madhu Updated for C Implementation and Javadoc -* 5/20/99 Madhu Added the function u_getVersion() -* 8/19/1999 srl Upgraded scripts to Unicode 3.0 -* 8/27/1999 schererm UCharDirection constants: U_... -* 11/11/1999 weiv added u_isalnum(), cleaned comments -* 01/11/2000 helena Renamed u_getVersion to u_getUnicodeVersion(). -****************************************************************************** -*/ - -#ifndef UCHAR_H -#define UCHAR_H - -#include "unicode/utypes.h" - -U_CDECL_BEGIN - -/*==========================================================================*/ -/* Unicode version number */ -/*==========================================================================*/ -/** - * Unicode version number, default for the current ICU version. - * The actual Unicode Character Database (UCD) data is stored in uprops.dat - * and may be generated from UCD files from a different Unicode version. - * Call u_getUnicodeVersion to get the actual Unicode version of the data. - * - * @see u_getUnicodeVersion - * @stable ICU 2.0 - */ -#define U_UNICODE_VERSION "9.0" - -/** - * \file - * \brief C API: Unicode Properties - * - * This C API provides low-level access to the Unicode Character Database. - * In addition to raw property values, some convenience functions calculate - * derived properties, for example for Java-style programming. - * - * Unicode assigns each code point (not just assigned character) values for - * many properties. - * Most of them are simple boolean flags, or constants from a small enumerated list. - * For some properties, values are strings or other relatively more complex types. - * - * For more information see - * "About the Unicode Character Database" (http://www.unicode.org/ucd/) - * and the ICU User Guide chapter on Properties (http://icu-project.org/userguide/properties.html). - * - * Many functions are designed to match java.lang.Character functions. - * See the individual function documentation, - * and see the JDK 1.4 java.lang.Character documentation - * at http://java.sun.com/j2se/1.4/docs/api/java/lang/Character.html - * - * There are also functions that provide easy migration from C/POSIX functions - * like isblank(). Their use is generally discouraged because the C/POSIX - * standards do not define their semantics beyond the ASCII range, which means - * that different implementations exhibit very different behavior. - * Instead, Unicode properties should be used directly. - * - * There are also only a few, broad C/POSIX character classes, and they tend - * to be used for conflicting purposes. For example, the "isalpha()" class - * is sometimes used to determine word boundaries, while a more sophisticated - * approach would at least distinguish initial letters from continuation - * characters (the latter including combining marks). - * (In ICU, BreakIterator is the most sophisticated API for word boundaries.) - * Another example: There is no "istitle()" class for titlecase characters. - * - * ICU 3.4 and later provides API access for all twelve C/POSIX character classes. - * ICU implements them according to the Standard Recommendations in - * Annex C: Compatibility Properties of UTS #18 Unicode Regular Expressions - * (http://www.unicode.org/reports/tr18/#Compatibility_Properties). - * - * API access for C/POSIX character classes is as follows: - * - alpha: u_isUAlphabetic(c) or u_hasBinaryProperty(c, UCHAR_ALPHABETIC) - * - lower: u_isULowercase(c) or u_hasBinaryProperty(c, UCHAR_LOWERCASE) - * - upper: u_isUUppercase(c) or u_hasBinaryProperty(c, UCHAR_UPPERCASE) - * - punct: u_ispunct(c) - * - digit: u_isdigit(c) or u_charType(c)==U_DECIMAL_DIGIT_NUMBER - * - xdigit: u_isxdigit(c) or u_hasBinaryProperty(c, UCHAR_POSIX_XDIGIT) - * - alnum: u_hasBinaryProperty(c, UCHAR_POSIX_ALNUM) - * - space: u_isUWhiteSpace(c) or u_hasBinaryProperty(c, UCHAR_WHITE_SPACE) - * - blank: u_isblank(c) or u_hasBinaryProperty(c, UCHAR_POSIX_BLANK) - * - cntrl: u_charType(c)==U_CONTROL_CHAR - * - graph: u_hasBinaryProperty(c, UCHAR_POSIX_GRAPH) - * - print: u_hasBinaryProperty(c, UCHAR_POSIX_PRINT) - * - * Note: Some of the u_isxyz() functions in uchar.h predate, and do not match, - * the Standard Recommendations in UTS #18. Instead, they match Java - * functions according to their API documentation. - * - * \htmlonly - * The C/POSIX character classes are also available in UnicodeSet patterns, - * using patterns like [:graph:] or \p{graph}. - * \endhtmlonly - * - * Note: There are several ICU whitespace functions. - * Comparison: - * - u_isUWhiteSpace=UCHAR_WHITE_SPACE: Unicode White_Space property; - * most of general categories "Z" (separators) + most whitespace ISO controls - * (including no-break spaces, but excluding IS1..IS4 and ZWSP) - * - u_isWhitespace: Java isWhitespace; Z + whitespace ISO controls but excluding no-break spaces - * - u_isJavaSpaceChar: Java isSpaceChar; just Z (including no-break spaces) - * - u_isspace: Z + whitespace ISO controls (including no-break spaces) - * - u_isblank: "horizontal spaces" = TAB + Zs - ZWSP - */ - -/** - * Constants. - */ - -/** The lowest Unicode code point value. Code points are non-negative. @stable ICU 2.0 */ -#define UCHAR_MIN_VALUE 0 - -/** - * The highest Unicode code point value (scalar value) according to - * The Unicode Standard. This is a 21-bit value (20.1 bits, rounded up). - * For a single character, UChar32 is a simple type that can hold any code point value. - * - * @see UChar32 - * @stable ICU 2.0 - */ -#define UCHAR_MAX_VALUE 0x10ffff - -/** - * Get a single-bit bit set (a flag) from a bit number 0..31. - * @stable ICU 2.1 - */ -#define U_MASK(x) ((uint32_t)1<<(x)) - -/** - * Selection constants for Unicode properties. - * These constants are used in functions like u_hasBinaryProperty to select - * one of the Unicode properties. - * - * The properties APIs are intended to reflect Unicode properties as defined - * in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR). - * For details about the properties see http://www.unicode.org/ucd/ . - * For names of Unicode properties see the UCD file PropertyAliases.txt. - * - * Important: If ICU is built with UCD files from Unicode versions below, e.g., 3.2, - * then properties marked with "new in Unicode 3.2" are not or not fully available. - * Check u_getUnicodeVersion to be sure. - * - * @see u_hasBinaryProperty - * @see u_getIntPropertyValue - * @see u_getUnicodeVersion - * @stable ICU 2.1 - */ -typedef enum UProperty { - /* - * Note: UProperty constants are parsed by preparseucd.py. - * It matches lines like - * UCHAR_=, - */ - - /* Note: Place UCHAR_ALPHABETIC before UCHAR_BINARY_START so that - debuggers display UCHAR_ALPHABETIC as the symbolic name for 0, - rather than UCHAR_BINARY_START. Likewise for other *_START - identifiers. */ - - /** Binary property Alphabetic. Same as u_isUAlphabetic, different from u_isalpha. - Lu+Ll+Lt+Lm+Lo+Nl+Other_Alphabetic @stable ICU 2.1 */ - UCHAR_ALPHABETIC=0, - /** First constant for binary Unicode properties. @stable ICU 2.1 */ - UCHAR_BINARY_START=UCHAR_ALPHABETIC, - /** Binary property ASCII_Hex_Digit. 0-9 A-F a-f @stable ICU 2.1 */ - UCHAR_ASCII_HEX_DIGIT=1, - /** Binary property Bidi_Control. - Format controls which have specific functions - in the Bidi Algorithm. @stable ICU 2.1 */ - UCHAR_BIDI_CONTROL=2, - /** Binary property Bidi_Mirrored. - Characters that may change display in RTL text. - Same as u_isMirrored. - See Bidi Algorithm, UTR 9. @stable ICU 2.1 */ - UCHAR_BIDI_MIRRORED=3, - /** Binary property Dash. Variations of dashes. @stable ICU 2.1 */ - UCHAR_DASH=4, - /** Binary property Default_Ignorable_Code_Point (new in Unicode 3.2). - Ignorable in most processing. - <2060..206F, FFF0..FFFB, E0000..E0FFF>+Other_Default_Ignorable_Code_Point+(Cf+Cc+Cs-White_Space) @stable ICU 2.1 */ - UCHAR_DEFAULT_IGNORABLE_CODE_POINT=5, - /** Binary property Deprecated (new in Unicode 3.2). - The usage of deprecated characters is strongly discouraged. @stable ICU 2.1 */ - UCHAR_DEPRECATED=6, - /** Binary property Diacritic. Characters that linguistically modify - the meaning of another character to which they apply. @stable ICU 2.1 */ - UCHAR_DIACRITIC=7, - /** Binary property Extender. - Extend the value or shape of a preceding alphabetic character, - e.g., length and iteration marks. @stable ICU 2.1 */ - UCHAR_EXTENDER=8, - /** Binary property Full_Composition_Exclusion. - CompositionExclusions.txt+Singleton Decompositions+ - Non-Starter Decompositions. @stable ICU 2.1 */ - UCHAR_FULL_COMPOSITION_EXCLUSION=9, - /** Binary property Grapheme_Base (new in Unicode 3.2). - For programmatic determination of grapheme cluster boundaries. - [0..10FFFF]-Cc-Cf-Cs-Co-Cn-Zl-Zp-Grapheme_Link-Grapheme_Extend-CGJ @stable ICU 2.1 */ - UCHAR_GRAPHEME_BASE=10, - /** Binary property Grapheme_Extend (new in Unicode 3.2). - For programmatic determination of grapheme cluster boundaries. - Me+Mn+Mc+Other_Grapheme_Extend-Grapheme_Link-CGJ @stable ICU 2.1 */ - UCHAR_GRAPHEME_EXTEND=11, - /** Binary property Grapheme_Link (new in Unicode 3.2). - For programmatic determination of grapheme cluster boundaries. @stable ICU 2.1 */ - UCHAR_GRAPHEME_LINK=12, - /** Binary property Hex_Digit. - Characters commonly used for hexadecimal numbers. @stable ICU 2.1 */ - UCHAR_HEX_DIGIT=13, - /** Binary property Hyphen. Dashes used to mark connections - between pieces of words, plus the Katakana middle dot. @stable ICU 2.1 */ - UCHAR_HYPHEN=14, - /** Binary property ID_Continue. - Characters that can continue an identifier. - DerivedCoreProperties.txt also says "NOTE: Cf characters should be filtered out." - ID_Start+Mn+Mc+Nd+Pc @stable ICU 2.1 */ - UCHAR_ID_CONTINUE=15, - /** Binary property ID_Start. - Characters that can start an identifier. - Lu+Ll+Lt+Lm+Lo+Nl @stable ICU 2.1 */ - UCHAR_ID_START=16, - /** Binary property Ideographic. - CJKV ideographs. @stable ICU 2.1 */ - UCHAR_IDEOGRAPHIC=17, - /** Binary property IDS_Binary_Operator (new in Unicode 3.2). - For programmatic determination of - Ideographic Description Sequences. @stable ICU 2.1 */ - UCHAR_IDS_BINARY_OPERATOR=18, - /** Binary property IDS_Trinary_Operator (new in Unicode 3.2). - For programmatic determination of - Ideographic Description Sequences. @stable ICU 2.1 */ - UCHAR_IDS_TRINARY_OPERATOR=19, - /** Binary property Join_Control. - Format controls for cursive joining and ligation. @stable ICU 2.1 */ - UCHAR_JOIN_CONTROL=20, - /** Binary property Logical_Order_Exception (new in Unicode 3.2). - Characters that do not use logical order and - require special handling in most processing. @stable ICU 2.1 */ - UCHAR_LOGICAL_ORDER_EXCEPTION=21, - /** Binary property Lowercase. Same as u_isULowercase, different from u_islower. - Ll+Other_Lowercase @stable ICU 2.1 */ - UCHAR_LOWERCASE=22, - /** Binary property Math. Sm+Other_Math @stable ICU 2.1 */ - UCHAR_MATH=23, - /** Binary property Noncharacter_Code_Point. - Code points that are explicitly defined as illegal - for the encoding of characters. @stable ICU 2.1 */ - UCHAR_NONCHARACTER_CODE_POINT=24, - /** Binary property Quotation_Mark. @stable ICU 2.1 */ - UCHAR_QUOTATION_MARK=25, - /** Binary property Radical (new in Unicode 3.2). - For programmatic determination of - Ideographic Description Sequences. @stable ICU 2.1 */ - UCHAR_RADICAL=26, - /** Binary property Soft_Dotted (new in Unicode 3.2). - Characters with a "soft dot", like i or j. - An accent placed on these characters causes - the dot to disappear. @stable ICU 2.1 */ - UCHAR_SOFT_DOTTED=27, - /** Binary property Terminal_Punctuation. - Punctuation characters that generally mark - the end of textual units. @stable ICU 2.1 */ - UCHAR_TERMINAL_PUNCTUATION=28, - /** Binary property Unified_Ideograph (new in Unicode 3.2). - For programmatic determination of - Ideographic Description Sequences. @stable ICU 2.1 */ - UCHAR_UNIFIED_IDEOGRAPH=29, - /** Binary property Uppercase. Same as u_isUUppercase, different from u_isupper. - Lu+Other_Uppercase @stable ICU 2.1 */ - UCHAR_UPPERCASE=30, - /** Binary property White_Space. - Same as u_isUWhiteSpace, different from u_isspace and u_isWhitespace. - Space characters+TAB+CR+LF-ZWSP-ZWNBSP @stable ICU 2.1 */ - UCHAR_WHITE_SPACE=31, - /** Binary property XID_Continue. - ID_Continue modified to allow closure under - normalization forms NFKC and NFKD. @stable ICU 2.1 */ - UCHAR_XID_CONTINUE=32, - /** Binary property XID_Start. ID_Start modified to allow - closure under normalization forms NFKC and NFKD. @stable ICU 2.1 */ - UCHAR_XID_START=33, - /** Binary property Case_Sensitive. Either the source of a case - mapping or _in_ the target of a case mapping. Not the same as - the general category Cased_Letter. @stable ICU 2.6 */ - UCHAR_CASE_SENSITIVE=34, - /** Binary property STerm (new in Unicode 4.0.1). - Sentence Terminal. Used in UAX #29: Text Boundaries - (http://www.unicode.org/reports/tr29/) - @stable ICU 3.0 */ - UCHAR_S_TERM=35, - /** Binary property Variation_Selector (new in Unicode 4.0.1). - Indicates all those characters that qualify as Variation Selectors. - For details on the behavior of these characters, - see StandardizedVariants.html and 15.6 Variation Selectors. - @stable ICU 3.0 */ - UCHAR_VARIATION_SELECTOR=36, - /** Binary property NFD_Inert. - ICU-specific property for characters that are inert under NFD, - i.e., they do not interact with adjacent characters. - See the documentation for the Normalizer2 class and the - Normalizer2::isInert() method. - @stable ICU 3.0 */ - UCHAR_NFD_INERT=37, - /** Binary property NFKD_Inert. - ICU-specific property for characters that are inert under NFKD, - i.e., they do not interact with adjacent characters. - See the documentation for the Normalizer2 class and the - Normalizer2::isInert() method. - @stable ICU 3.0 */ - UCHAR_NFKD_INERT=38, - /** Binary property NFC_Inert. - ICU-specific property for characters that are inert under NFC, - i.e., they do not interact with adjacent characters. - See the documentation for the Normalizer2 class and the - Normalizer2::isInert() method. - @stable ICU 3.0 */ - UCHAR_NFC_INERT=39, - /** Binary property NFKC_Inert. - ICU-specific property for characters that are inert under NFKC, - i.e., they do not interact with adjacent characters. - See the documentation for the Normalizer2 class and the - Normalizer2::isInert() method. - @stable ICU 3.0 */ - UCHAR_NFKC_INERT=40, - /** Binary Property Segment_Starter. - ICU-specific property for characters that are starters in terms of - Unicode normalization and combining character sequences. - They have ccc=0 and do not occur in non-initial position of the - canonical decomposition of any character - (like a-umlaut in NFD and a Jamo T in an NFD(Hangul LVT)). - ICU uses this property for segmenting a string for generating a set of - canonically equivalent strings, e.g. for canonical closure while - processing collation tailoring rules. - @stable ICU 3.0 */ - UCHAR_SEGMENT_STARTER=41, - /** Binary property Pattern_Syntax (new in Unicode 4.1). - See UAX #31 Identifier and Pattern Syntax - (http://www.unicode.org/reports/tr31/) - @stable ICU 3.4 */ - UCHAR_PATTERN_SYNTAX=42, - /** Binary property Pattern_White_Space (new in Unicode 4.1). - See UAX #31 Identifier and Pattern Syntax - (http://www.unicode.org/reports/tr31/) - @stable ICU 3.4 */ - UCHAR_PATTERN_WHITE_SPACE=43, - /** Binary property alnum (a C/POSIX character class). - Implemented according to the UTS #18 Annex C Standard Recommendation. - See the uchar.h file documentation. - @stable ICU 3.4 */ - UCHAR_POSIX_ALNUM=44, - /** Binary property blank (a C/POSIX character class). - Implemented according to the UTS #18 Annex C Standard Recommendation. - See the uchar.h file documentation. - @stable ICU 3.4 */ - UCHAR_POSIX_BLANK=45, - /** Binary property graph (a C/POSIX character class). - Implemented according to the UTS #18 Annex C Standard Recommendation. - See the uchar.h file documentation. - @stable ICU 3.4 */ - UCHAR_POSIX_GRAPH=46, - /** Binary property print (a C/POSIX character class). - Implemented according to the UTS #18 Annex C Standard Recommendation. - See the uchar.h file documentation. - @stable ICU 3.4 */ - UCHAR_POSIX_PRINT=47, - /** Binary property xdigit (a C/POSIX character class). - Implemented according to the UTS #18 Annex C Standard Recommendation. - See the uchar.h file documentation. - @stable ICU 3.4 */ - UCHAR_POSIX_XDIGIT=48, - /** Binary property Cased. For Lowercase, Uppercase and Titlecase characters. @stable ICU 4.4 */ - UCHAR_CASED=49, - /** Binary property Case_Ignorable. Used in context-sensitive case mappings. @stable ICU 4.4 */ - UCHAR_CASE_IGNORABLE=50, - /** Binary property Changes_When_Lowercased. @stable ICU 4.4 */ - UCHAR_CHANGES_WHEN_LOWERCASED=51, - /** Binary property Changes_When_Uppercased. @stable ICU 4.4 */ - UCHAR_CHANGES_WHEN_UPPERCASED=52, - /** Binary property Changes_When_Titlecased. @stable ICU 4.4 */ - UCHAR_CHANGES_WHEN_TITLECASED=53, - /** Binary property Changes_When_Casefolded. @stable ICU 4.4 */ - UCHAR_CHANGES_WHEN_CASEFOLDED=54, - /** Binary property Changes_When_Casemapped. @stable ICU 4.4 */ - UCHAR_CHANGES_WHEN_CASEMAPPED=55, - /** Binary property Changes_When_NFKC_Casefolded. @stable ICU 4.4 */ - UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED=56, -#ifndef U_HIDE_DRAFT_API - /** - * Binary property Emoji. - * See http://www.unicode.org/reports/tr51/#Emoji_Properties - * - * @draft ICU 57 - */ - UCHAR_EMOJI=57, - /** - * Binary property Emoji_Presentation. - * See http://www.unicode.org/reports/tr51/#Emoji_Properties - * - * @draft ICU 57 - */ - UCHAR_EMOJI_PRESENTATION=58, - /** - * Binary property Emoji_Modifier. - * See http://www.unicode.org/reports/tr51/#Emoji_Properties - * - * @draft ICU 57 - */ - UCHAR_EMOJI_MODIFIER=59, - /** - * Binary property Emoji_Modifier_Base. - * See http://www.unicode.org/reports/tr51/#Emoji_Properties - * - * @draft ICU 57 - */ - UCHAR_EMOJI_MODIFIER_BASE=60, -#endif /* U_HIDE_DRAFT_API */ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the last constant for binary Unicode properties. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCHAR_BINARY_LIMIT=61, -#endif // U_HIDE_DEPRECATED_API - - /** Enumerated property Bidi_Class. - Same as u_charDirection, returns UCharDirection values. @stable ICU 2.2 */ - UCHAR_BIDI_CLASS=0x1000, - /** First constant for enumerated/integer Unicode properties. @stable ICU 2.2 */ - UCHAR_INT_START=UCHAR_BIDI_CLASS, - /** Enumerated property Block. - Same as ublock_getCode, returns UBlockCode values. @stable ICU 2.2 */ - UCHAR_BLOCK=0x1001, - /** Enumerated property Canonical_Combining_Class. - Same as u_getCombiningClass, returns 8-bit numeric values. @stable ICU 2.2 */ - UCHAR_CANONICAL_COMBINING_CLASS=0x1002, - /** Enumerated property Decomposition_Type. - Returns UDecompositionType values. @stable ICU 2.2 */ - UCHAR_DECOMPOSITION_TYPE=0x1003, - /** Enumerated property East_Asian_Width. - See http://www.unicode.org/reports/tr11/ - Returns UEastAsianWidth values. @stable ICU 2.2 */ - UCHAR_EAST_ASIAN_WIDTH=0x1004, - /** Enumerated property General_Category. - Same as u_charType, returns UCharCategory values. @stable ICU 2.2 */ - UCHAR_GENERAL_CATEGORY=0x1005, - /** Enumerated property Joining_Group. - Returns UJoiningGroup values. @stable ICU 2.2 */ - UCHAR_JOINING_GROUP=0x1006, - /** Enumerated property Joining_Type. - Returns UJoiningType values. @stable ICU 2.2 */ - UCHAR_JOINING_TYPE=0x1007, - /** Enumerated property Line_Break. - Returns ULineBreak values. @stable ICU 2.2 */ - UCHAR_LINE_BREAK=0x1008, - /** Enumerated property Numeric_Type. - Returns UNumericType values. @stable ICU 2.2 */ - UCHAR_NUMERIC_TYPE=0x1009, - /** Enumerated property Script. - Same as uscript_getScript, returns UScriptCode values. @stable ICU 2.2 */ - UCHAR_SCRIPT=0x100A, - /** Enumerated property Hangul_Syllable_Type, new in Unicode 4. - Returns UHangulSyllableType values. @stable ICU 2.6 */ - UCHAR_HANGUL_SYLLABLE_TYPE=0x100B, - /** Enumerated property NFD_Quick_Check. - Returns UNormalizationCheckResult values. @stable ICU 3.0 */ - UCHAR_NFD_QUICK_CHECK=0x100C, - /** Enumerated property NFKD_Quick_Check. - Returns UNormalizationCheckResult values. @stable ICU 3.0 */ - UCHAR_NFKD_QUICK_CHECK=0x100D, - /** Enumerated property NFC_Quick_Check. - Returns UNormalizationCheckResult values. @stable ICU 3.0 */ - UCHAR_NFC_QUICK_CHECK=0x100E, - /** Enumerated property NFKC_Quick_Check. - Returns UNormalizationCheckResult values. @stable ICU 3.0 */ - UCHAR_NFKC_QUICK_CHECK=0x100F, - /** Enumerated property Lead_Canonical_Combining_Class. - ICU-specific property for the ccc of the first code point - of the decomposition, or lccc(c)=ccc(NFD(c)[0]). - Useful for checking for canonically ordered text; - see UNORM_FCD and http://www.unicode.org/notes/tn5/#FCD . - Returns 8-bit numeric values like UCHAR_CANONICAL_COMBINING_CLASS. @stable ICU 3.0 */ - UCHAR_LEAD_CANONICAL_COMBINING_CLASS=0x1010, - /** Enumerated property Trail_Canonical_Combining_Class. - ICU-specific property for the ccc of the last code point - of the decomposition, or tccc(c)=ccc(NFD(c)[last]). - Useful for checking for canonically ordered text; - see UNORM_FCD and http://www.unicode.org/notes/tn5/#FCD . - Returns 8-bit numeric values like UCHAR_CANONICAL_COMBINING_CLASS. @stable ICU 3.0 */ - UCHAR_TRAIL_CANONICAL_COMBINING_CLASS=0x1011, - /** Enumerated property Grapheme_Cluster_Break (new in Unicode 4.1). - Used in UAX #29: Text Boundaries - (http://www.unicode.org/reports/tr29/) - Returns UGraphemeClusterBreak values. @stable ICU 3.4 */ - UCHAR_GRAPHEME_CLUSTER_BREAK=0x1012, - /** Enumerated property Sentence_Break (new in Unicode 4.1). - Used in UAX #29: Text Boundaries - (http://www.unicode.org/reports/tr29/) - Returns USentenceBreak values. @stable ICU 3.4 */ - UCHAR_SENTENCE_BREAK=0x1013, - /** Enumerated property Word_Break (new in Unicode 4.1). - Used in UAX #29: Text Boundaries - (http://www.unicode.org/reports/tr29/) - Returns UWordBreakValues values. @stable ICU 3.4 */ - UCHAR_WORD_BREAK=0x1014, - /** Enumerated property Bidi_Paired_Bracket_Type (new in Unicode 6.3). - Used in UAX #9: Unicode Bidirectional Algorithm - (http://www.unicode.org/reports/tr9/) - Returns UBidiPairedBracketType values. @stable ICU 52 */ - UCHAR_BIDI_PAIRED_BRACKET_TYPE=0x1015, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the last constant for enumerated/integer Unicode properties. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCHAR_INT_LIMIT=0x1016, -#endif // U_HIDE_DEPRECATED_API - - /** Bitmask property General_Category_Mask. - This is the General_Category property returned as a bit mask. - When used in u_getIntPropertyValue(c), same as U_MASK(u_charType(c)), - returns bit masks for UCharCategory values where exactly one bit is set. - When used with u_getPropertyValueName() and u_getPropertyValueEnum(), - a multi-bit mask is used for sets of categories like "Letters". - Mask values should be cast to uint32_t. - @stable ICU 2.4 */ - UCHAR_GENERAL_CATEGORY_MASK=0x2000, - /** First constant for bit-mask Unicode properties. @stable ICU 2.4 */ - UCHAR_MASK_START=UCHAR_GENERAL_CATEGORY_MASK, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the last constant for bit-mask Unicode properties. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCHAR_MASK_LIMIT=0x2001, -#endif // U_HIDE_DEPRECATED_API - - /** Double property Numeric_Value. - Corresponds to u_getNumericValue. @stable ICU 2.4 */ - UCHAR_NUMERIC_VALUE=0x3000, - /** First constant for double Unicode properties. @stable ICU 2.4 */ - UCHAR_DOUBLE_START=UCHAR_NUMERIC_VALUE, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the last constant for double Unicode properties. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCHAR_DOUBLE_LIMIT=0x3001, -#endif // U_HIDE_DEPRECATED_API - - /** String property Age. - Corresponds to u_charAge. @stable ICU 2.4 */ - UCHAR_AGE=0x4000, - /** First constant for string Unicode properties. @stable ICU 2.4 */ - UCHAR_STRING_START=UCHAR_AGE, - /** String property Bidi_Mirroring_Glyph. - Corresponds to u_charMirror. @stable ICU 2.4 */ - UCHAR_BIDI_MIRRORING_GLYPH=0x4001, - /** String property Case_Folding. - Corresponds to u_strFoldCase in ustring.h. @stable ICU 2.4 */ - UCHAR_CASE_FOLDING=0x4002, -#ifndef U_HIDE_DEPRECATED_API - /** Deprecated string property ISO_Comment. - Corresponds to u_getISOComment. @deprecated ICU 49 */ - UCHAR_ISO_COMMENT=0x4003, -#endif /* U_HIDE_DEPRECATED_API */ - /** String property Lowercase_Mapping. - Corresponds to u_strToLower in ustring.h. @stable ICU 2.4 */ - UCHAR_LOWERCASE_MAPPING=0x4004, - /** String property Name. - Corresponds to u_charName. @stable ICU 2.4 */ - UCHAR_NAME=0x4005, - /** String property Simple_Case_Folding. - Corresponds to u_foldCase. @stable ICU 2.4 */ - UCHAR_SIMPLE_CASE_FOLDING=0x4006, - /** String property Simple_Lowercase_Mapping. - Corresponds to u_tolower. @stable ICU 2.4 */ - UCHAR_SIMPLE_LOWERCASE_MAPPING=0x4007, - /** String property Simple_Titlecase_Mapping. - Corresponds to u_totitle. @stable ICU 2.4 */ - UCHAR_SIMPLE_TITLECASE_MAPPING=0x4008, - /** String property Simple_Uppercase_Mapping. - Corresponds to u_toupper. @stable ICU 2.4 */ - UCHAR_SIMPLE_UPPERCASE_MAPPING=0x4009, - /** String property Titlecase_Mapping. - Corresponds to u_strToTitle in ustring.h. @stable ICU 2.4 */ - UCHAR_TITLECASE_MAPPING=0x400A, -#ifndef U_HIDE_DEPRECATED_API - /** String property Unicode_1_Name. - This property is of little practical value. - Beginning with ICU 49, ICU APIs return an empty string for this property. - Corresponds to u_charName(U_UNICODE_10_CHAR_NAME). @deprecated ICU 49 */ - UCHAR_UNICODE_1_NAME=0x400B, -#endif /* U_HIDE_DEPRECATED_API */ - /** String property Uppercase_Mapping. - Corresponds to u_strToUpper in ustring.h. @stable ICU 2.4 */ - UCHAR_UPPERCASE_MAPPING=0x400C, - /** String property Bidi_Paired_Bracket (new in Unicode 6.3). - Corresponds to u_getBidiPairedBracket. @stable ICU 52 */ - UCHAR_BIDI_PAIRED_BRACKET=0x400D, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the last constant for string Unicode properties. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCHAR_STRING_LIMIT=0x400E, -#endif // U_HIDE_DEPRECATED_API - - /** Miscellaneous property Script_Extensions (new in Unicode 6.0). - Some characters are commonly used in multiple scripts. - For more information, see UAX #24: http://www.unicode.org/reports/tr24/. - Corresponds to uscript_hasScript and uscript_getScriptExtensions in uscript.h. - @stable ICU 4.6 */ - UCHAR_SCRIPT_EXTENSIONS=0x7000, - /** First constant for Unicode properties with unusual value types. @stable ICU 4.6 */ - UCHAR_OTHER_PROPERTY_START=UCHAR_SCRIPT_EXTENSIONS, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the last constant for Unicode properties with unusual value types. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCHAR_OTHER_PROPERTY_LIMIT=0x7001, -#endif // U_HIDE_DEPRECATED_API - - /** Represents a nonexistent or invalid property or property value. @stable ICU 2.4 */ - UCHAR_INVALID_CODE = -1 -} UProperty; - -/** - * Data for enumerated Unicode general category types. - * See http://www.unicode.org/Public/UNIDATA/UnicodeData.html . - * @stable ICU 2.0 - */ -typedef enum UCharCategory -{ - /* - * Note: UCharCategory constants and their API comments are parsed by preparseucd.py. - * It matches pairs of lines like - * / ** comment... * / - * U_<[A-Z_]+> = , - */ - - /** Non-category for unassigned and non-character code points. @stable ICU 2.0 */ - U_UNASSIGNED = 0, - /** Cn "Other, Not Assigned (no characters in [UnicodeData.txt] have this property)" (same as U_UNASSIGNED!) @stable ICU 2.0 */ - U_GENERAL_OTHER_TYPES = 0, - /** Lu @stable ICU 2.0 */ - U_UPPERCASE_LETTER = 1, - /** Ll @stable ICU 2.0 */ - U_LOWERCASE_LETTER = 2, - /** Lt @stable ICU 2.0 */ - U_TITLECASE_LETTER = 3, - /** Lm @stable ICU 2.0 */ - U_MODIFIER_LETTER = 4, - /** Lo @stable ICU 2.0 */ - U_OTHER_LETTER = 5, - /** Mn @stable ICU 2.0 */ - U_NON_SPACING_MARK = 6, - /** Me @stable ICU 2.0 */ - U_ENCLOSING_MARK = 7, - /** Mc @stable ICU 2.0 */ - U_COMBINING_SPACING_MARK = 8, - /** Nd @stable ICU 2.0 */ - U_DECIMAL_DIGIT_NUMBER = 9, - /** Nl @stable ICU 2.0 */ - U_LETTER_NUMBER = 10, - /** No @stable ICU 2.0 */ - U_OTHER_NUMBER = 11, - /** Zs @stable ICU 2.0 */ - U_SPACE_SEPARATOR = 12, - /** Zl @stable ICU 2.0 */ - U_LINE_SEPARATOR = 13, - /** Zp @stable ICU 2.0 */ - U_PARAGRAPH_SEPARATOR = 14, - /** Cc @stable ICU 2.0 */ - U_CONTROL_CHAR = 15, - /** Cf @stable ICU 2.0 */ - U_FORMAT_CHAR = 16, - /** Co @stable ICU 2.0 */ - U_PRIVATE_USE_CHAR = 17, - /** Cs @stable ICU 2.0 */ - U_SURROGATE = 18, - /** Pd @stable ICU 2.0 */ - U_DASH_PUNCTUATION = 19, - /** Ps @stable ICU 2.0 */ - U_START_PUNCTUATION = 20, - /** Pe @stable ICU 2.0 */ - U_END_PUNCTUATION = 21, - /** Pc @stable ICU 2.0 */ - U_CONNECTOR_PUNCTUATION = 22, - /** Po @stable ICU 2.0 */ - U_OTHER_PUNCTUATION = 23, - /** Sm @stable ICU 2.0 */ - U_MATH_SYMBOL = 24, - /** Sc @stable ICU 2.0 */ - U_CURRENCY_SYMBOL = 25, - /** Sk @stable ICU 2.0 */ - U_MODIFIER_SYMBOL = 26, - /** So @stable ICU 2.0 */ - U_OTHER_SYMBOL = 27, - /** Pi @stable ICU 2.0 */ - U_INITIAL_PUNCTUATION = 28, - /** Pf @stable ICU 2.0 */ - U_FINAL_PUNCTUATION = 29, - /** - * One higher than the last enum UCharCategory constant. - * This numeric value is stable (will not change), see - * http://www.unicode.org/policies/stability_policy.html#Property_Value - * - * @stable ICU 2.0 - */ - U_CHAR_CATEGORY_COUNT -} UCharCategory; - -/** - * U_GC_XX_MASK constants are bit flags corresponding to Unicode - * general category values. - * For each category, the nth bit is set if the numeric value of the - * corresponding UCharCategory constant is n. - * - * There are also some U_GC_Y_MASK constants for groups of general categories - * like L for all letter categories. - * - * @see u_charType - * @see U_GET_GC_MASK - * @see UCharCategory - * @stable ICU 2.1 - */ -#define U_GC_CN_MASK U_MASK(U_GENERAL_OTHER_TYPES) - -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_LU_MASK U_MASK(U_UPPERCASE_LETTER) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_LL_MASK U_MASK(U_LOWERCASE_LETTER) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_LT_MASK U_MASK(U_TITLECASE_LETTER) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_LM_MASK U_MASK(U_MODIFIER_LETTER) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_LO_MASK U_MASK(U_OTHER_LETTER) - -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_MN_MASK U_MASK(U_NON_SPACING_MARK) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_ME_MASK U_MASK(U_ENCLOSING_MARK) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_MC_MASK U_MASK(U_COMBINING_SPACING_MARK) - -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_ND_MASK U_MASK(U_DECIMAL_DIGIT_NUMBER) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_NL_MASK U_MASK(U_LETTER_NUMBER) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_NO_MASK U_MASK(U_OTHER_NUMBER) - -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_ZS_MASK U_MASK(U_SPACE_SEPARATOR) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_ZL_MASK U_MASK(U_LINE_SEPARATOR) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_ZP_MASK U_MASK(U_PARAGRAPH_SEPARATOR) - -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_CC_MASK U_MASK(U_CONTROL_CHAR) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_CF_MASK U_MASK(U_FORMAT_CHAR) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_CO_MASK U_MASK(U_PRIVATE_USE_CHAR) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_CS_MASK U_MASK(U_SURROGATE) - -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_PD_MASK U_MASK(U_DASH_PUNCTUATION) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_PS_MASK U_MASK(U_START_PUNCTUATION) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_PE_MASK U_MASK(U_END_PUNCTUATION) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_PC_MASK U_MASK(U_CONNECTOR_PUNCTUATION) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_PO_MASK U_MASK(U_OTHER_PUNCTUATION) - -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_SM_MASK U_MASK(U_MATH_SYMBOL) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_SC_MASK U_MASK(U_CURRENCY_SYMBOL) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_SK_MASK U_MASK(U_MODIFIER_SYMBOL) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_SO_MASK U_MASK(U_OTHER_SYMBOL) - -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_PI_MASK U_MASK(U_INITIAL_PUNCTUATION) -/** Mask constant for a UCharCategory. @stable ICU 2.1 */ -#define U_GC_PF_MASK U_MASK(U_FINAL_PUNCTUATION) - - -/** Mask constant for multiple UCharCategory bits (L Letters). @stable ICU 2.1 */ -#define U_GC_L_MASK \ - (U_GC_LU_MASK|U_GC_LL_MASK|U_GC_LT_MASK|U_GC_LM_MASK|U_GC_LO_MASK) - -/** Mask constant for multiple UCharCategory bits (LC Cased Letters). @stable ICU 2.1 */ -#define U_GC_LC_MASK \ - (U_GC_LU_MASK|U_GC_LL_MASK|U_GC_LT_MASK) - -/** Mask constant for multiple UCharCategory bits (M Marks). @stable ICU 2.1 */ -#define U_GC_M_MASK (U_GC_MN_MASK|U_GC_ME_MASK|U_GC_MC_MASK) - -/** Mask constant for multiple UCharCategory bits (N Numbers). @stable ICU 2.1 */ -#define U_GC_N_MASK (U_GC_ND_MASK|U_GC_NL_MASK|U_GC_NO_MASK) - -/** Mask constant for multiple UCharCategory bits (Z Separators). @stable ICU 2.1 */ -#define U_GC_Z_MASK (U_GC_ZS_MASK|U_GC_ZL_MASK|U_GC_ZP_MASK) - -/** Mask constant for multiple UCharCategory bits (C Others). @stable ICU 2.1 */ -#define U_GC_C_MASK \ - (U_GC_CN_MASK|U_GC_CC_MASK|U_GC_CF_MASK|U_GC_CO_MASK|U_GC_CS_MASK) - -/** Mask constant for multiple UCharCategory bits (P Punctuation). @stable ICU 2.1 */ -#define U_GC_P_MASK \ - (U_GC_PD_MASK|U_GC_PS_MASK|U_GC_PE_MASK|U_GC_PC_MASK|U_GC_PO_MASK| \ - U_GC_PI_MASK|U_GC_PF_MASK) - -/** Mask constant for multiple UCharCategory bits (S Symbols). @stable ICU 2.1 */ -#define U_GC_S_MASK (U_GC_SM_MASK|U_GC_SC_MASK|U_GC_SK_MASK|U_GC_SO_MASK) - -/** - * This specifies the language directional property of a character set. - * @stable ICU 2.0 - */ -typedef enum UCharDirection { - /* - * Note: UCharDirection constants and their API comments are parsed by preparseucd.py. - * It matches pairs of lines like - * / ** comment... * / - * U_<[A-Z_]+> = , - */ - - /** L @stable ICU 2.0 */ - U_LEFT_TO_RIGHT = 0, - /** R @stable ICU 2.0 */ - U_RIGHT_TO_LEFT = 1, - /** EN @stable ICU 2.0 */ - U_EUROPEAN_NUMBER = 2, - /** ES @stable ICU 2.0 */ - U_EUROPEAN_NUMBER_SEPARATOR = 3, - /** ET @stable ICU 2.0 */ - U_EUROPEAN_NUMBER_TERMINATOR = 4, - /** AN @stable ICU 2.0 */ - U_ARABIC_NUMBER = 5, - /** CS @stable ICU 2.0 */ - U_COMMON_NUMBER_SEPARATOR = 6, - /** B @stable ICU 2.0 */ - U_BLOCK_SEPARATOR = 7, - /** S @stable ICU 2.0 */ - U_SEGMENT_SEPARATOR = 8, - /** WS @stable ICU 2.0 */ - U_WHITE_SPACE_NEUTRAL = 9, - /** ON @stable ICU 2.0 */ - U_OTHER_NEUTRAL = 10, - /** LRE @stable ICU 2.0 */ - U_LEFT_TO_RIGHT_EMBEDDING = 11, - /** LRO @stable ICU 2.0 */ - U_LEFT_TO_RIGHT_OVERRIDE = 12, - /** AL @stable ICU 2.0 */ - U_RIGHT_TO_LEFT_ARABIC = 13, - /** RLE @stable ICU 2.0 */ - U_RIGHT_TO_LEFT_EMBEDDING = 14, - /** RLO @stable ICU 2.0 */ - U_RIGHT_TO_LEFT_OVERRIDE = 15, - /** PDF @stable ICU 2.0 */ - U_POP_DIRECTIONAL_FORMAT = 16, - /** NSM @stable ICU 2.0 */ - U_DIR_NON_SPACING_MARK = 17, - /** BN @stable ICU 2.0 */ - U_BOUNDARY_NEUTRAL = 18, - /** FSI @stable ICU 52 */ - U_FIRST_STRONG_ISOLATE = 19, - /** LRI @stable ICU 52 */ - U_LEFT_TO_RIGHT_ISOLATE = 20, - /** RLI @stable ICU 52 */ - U_RIGHT_TO_LEFT_ISOLATE = 21, - /** PDI @stable ICU 52 */ - U_POP_DIRECTIONAL_ISOLATE = 22, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest UCharDirection value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_BIDI_CLASS). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_CHAR_DIRECTION_COUNT -#endif // U_HIDE_DEPRECATED_API -} UCharDirection; - -/** - * Bidi Paired Bracket Type constants. - * - * @see UCHAR_BIDI_PAIRED_BRACKET_TYPE - * @stable ICU 52 - */ -typedef enum UBidiPairedBracketType { - /* - * Note: UBidiPairedBracketType constants are parsed by preparseucd.py. - * It matches lines like - * U_BPT_ - */ - - /** Not a paired bracket. @stable ICU 52 */ - U_BPT_NONE, - /** Open paired bracket. @stable ICU 52 */ - U_BPT_OPEN, - /** Close paired bracket. @stable ICU 52 */ - U_BPT_CLOSE, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UBidiPairedBracketType value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_BIDI_PAIRED_BRACKET_TYPE). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_BPT_COUNT /* 3 */ -#endif // U_HIDE_DEPRECATED_API -} UBidiPairedBracketType; - -/** - * Constants for Unicode blocks, see the Unicode Data file Blocks.txt - * @stable ICU 2.0 - */ -enum UBlockCode { - /* - * Note: UBlockCode constants are parsed by preparseucd.py. - * It matches lines like - * UBLOCK_ = , - */ - - /** New No_Block value in Unicode 4. @stable ICU 2.6 */ - UBLOCK_NO_BLOCK = 0, /*[none]*/ /* Special range indicating No_Block */ - - /** @stable ICU 2.0 */ - UBLOCK_BASIC_LATIN = 1, /*[0000]*/ - - /** @stable ICU 2.0 */ - UBLOCK_LATIN_1_SUPPLEMENT=2, /*[0080]*/ - - /** @stable ICU 2.0 */ - UBLOCK_LATIN_EXTENDED_A =3, /*[0100]*/ - - /** @stable ICU 2.0 */ - UBLOCK_LATIN_EXTENDED_B =4, /*[0180]*/ - - /** @stable ICU 2.0 */ - UBLOCK_IPA_EXTENSIONS =5, /*[0250]*/ - - /** @stable ICU 2.0 */ - UBLOCK_SPACING_MODIFIER_LETTERS =6, /*[02B0]*/ - - /** @stable ICU 2.0 */ - UBLOCK_COMBINING_DIACRITICAL_MARKS =7, /*[0300]*/ - - /** - * Unicode 3.2 renames this block to "Greek and Coptic". - * @stable ICU 2.0 - */ - UBLOCK_GREEK =8, /*[0370]*/ - - /** @stable ICU 2.0 */ - UBLOCK_CYRILLIC =9, /*[0400]*/ - - /** @stable ICU 2.0 */ - UBLOCK_ARMENIAN =10, /*[0530]*/ - - /** @stable ICU 2.0 */ - UBLOCK_HEBREW =11, /*[0590]*/ - - /** @stable ICU 2.0 */ - UBLOCK_ARABIC =12, /*[0600]*/ - - /** @stable ICU 2.0 */ - UBLOCK_SYRIAC =13, /*[0700]*/ - - /** @stable ICU 2.0 */ - UBLOCK_THAANA =14, /*[0780]*/ - - /** @stable ICU 2.0 */ - UBLOCK_DEVANAGARI =15, /*[0900]*/ - - /** @stable ICU 2.0 */ - UBLOCK_BENGALI =16, /*[0980]*/ - - /** @stable ICU 2.0 */ - UBLOCK_GURMUKHI =17, /*[0A00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_GUJARATI =18, /*[0A80]*/ - - /** @stable ICU 2.0 */ - UBLOCK_ORIYA =19, /*[0B00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_TAMIL =20, /*[0B80]*/ - - /** @stable ICU 2.0 */ - UBLOCK_TELUGU =21, /*[0C00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_KANNADA =22, /*[0C80]*/ - - /** @stable ICU 2.0 */ - UBLOCK_MALAYALAM =23, /*[0D00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_SINHALA =24, /*[0D80]*/ - - /** @stable ICU 2.0 */ - UBLOCK_THAI =25, /*[0E00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_LAO =26, /*[0E80]*/ - - /** @stable ICU 2.0 */ - UBLOCK_TIBETAN =27, /*[0F00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_MYANMAR =28, /*[1000]*/ - - /** @stable ICU 2.0 */ - UBLOCK_GEORGIAN =29, /*[10A0]*/ - - /** @stable ICU 2.0 */ - UBLOCK_HANGUL_JAMO =30, /*[1100]*/ - - /** @stable ICU 2.0 */ - UBLOCK_ETHIOPIC =31, /*[1200]*/ - - /** @stable ICU 2.0 */ - UBLOCK_CHEROKEE =32, /*[13A0]*/ - - /** @stable ICU 2.0 */ - UBLOCK_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS =33, /*[1400]*/ - - /** @stable ICU 2.0 */ - UBLOCK_OGHAM =34, /*[1680]*/ - - /** @stable ICU 2.0 */ - UBLOCK_RUNIC =35, /*[16A0]*/ - - /** @stable ICU 2.0 */ - UBLOCK_KHMER =36, /*[1780]*/ - - /** @stable ICU 2.0 */ - UBLOCK_MONGOLIAN =37, /*[1800]*/ - - /** @stable ICU 2.0 */ - UBLOCK_LATIN_EXTENDED_ADDITIONAL =38, /*[1E00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_GREEK_EXTENDED =39, /*[1F00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_GENERAL_PUNCTUATION =40, /*[2000]*/ - - /** @stable ICU 2.0 */ - UBLOCK_SUPERSCRIPTS_AND_SUBSCRIPTS =41, /*[2070]*/ - - /** @stable ICU 2.0 */ - UBLOCK_CURRENCY_SYMBOLS =42, /*[20A0]*/ - - /** - * Unicode 3.2 renames this block to "Combining Diacritical Marks for Symbols". - * @stable ICU 2.0 - */ - UBLOCK_COMBINING_MARKS_FOR_SYMBOLS =43, /*[20D0]*/ - - /** @stable ICU 2.0 */ - UBLOCK_LETTERLIKE_SYMBOLS =44, /*[2100]*/ - - /** @stable ICU 2.0 */ - UBLOCK_NUMBER_FORMS =45, /*[2150]*/ - - /** @stable ICU 2.0 */ - UBLOCK_ARROWS =46, /*[2190]*/ - - /** @stable ICU 2.0 */ - UBLOCK_MATHEMATICAL_OPERATORS =47, /*[2200]*/ - - /** @stable ICU 2.0 */ - UBLOCK_MISCELLANEOUS_TECHNICAL =48, /*[2300]*/ - - /** @stable ICU 2.0 */ - UBLOCK_CONTROL_PICTURES =49, /*[2400]*/ - - /** @stable ICU 2.0 */ - UBLOCK_OPTICAL_CHARACTER_RECOGNITION =50, /*[2440]*/ - - /** @stable ICU 2.0 */ - UBLOCK_ENCLOSED_ALPHANUMERICS =51, /*[2460]*/ - - /** @stable ICU 2.0 */ - UBLOCK_BOX_DRAWING =52, /*[2500]*/ - - /** @stable ICU 2.0 */ - UBLOCK_BLOCK_ELEMENTS =53, /*[2580]*/ - - /** @stable ICU 2.0 */ - UBLOCK_GEOMETRIC_SHAPES =54, /*[25A0]*/ - - /** @stable ICU 2.0 */ - UBLOCK_MISCELLANEOUS_SYMBOLS =55, /*[2600]*/ - - /** @stable ICU 2.0 */ - UBLOCK_DINGBATS =56, /*[2700]*/ - - /** @stable ICU 2.0 */ - UBLOCK_BRAILLE_PATTERNS =57, /*[2800]*/ - - /** @stable ICU 2.0 */ - UBLOCK_CJK_RADICALS_SUPPLEMENT =58, /*[2E80]*/ - - /** @stable ICU 2.0 */ - UBLOCK_KANGXI_RADICALS =59, /*[2F00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_IDEOGRAPHIC_DESCRIPTION_CHARACTERS =60, /*[2FF0]*/ - - /** @stable ICU 2.0 */ - UBLOCK_CJK_SYMBOLS_AND_PUNCTUATION =61, /*[3000]*/ - - /** @stable ICU 2.0 */ - UBLOCK_HIRAGANA =62, /*[3040]*/ - - /** @stable ICU 2.0 */ - UBLOCK_KATAKANA =63, /*[30A0]*/ - - /** @stable ICU 2.0 */ - UBLOCK_BOPOMOFO =64, /*[3100]*/ - - /** @stable ICU 2.0 */ - UBLOCK_HANGUL_COMPATIBILITY_JAMO =65, /*[3130]*/ - - /** @stable ICU 2.0 */ - UBLOCK_KANBUN =66, /*[3190]*/ - - /** @stable ICU 2.0 */ - UBLOCK_BOPOMOFO_EXTENDED =67, /*[31A0]*/ - - /** @stable ICU 2.0 */ - UBLOCK_ENCLOSED_CJK_LETTERS_AND_MONTHS =68, /*[3200]*/ - - /** @stable ICU 2.0 */ - UBLOCK_CJK_COMPATIBILITY =69, /*[3300]*/ - - /** @stable ICU 2.0 */ - UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A =70, /*[3400]*/ - - /** @stable ICU 2.0 */ - UBLOCK_CJK_UNIFIED_IDEOGRAPHS =71, /*[4E00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_YI_SYLLABLES =72, /*[A000]*/ - - /** @stable ICU 2.0 */ - UBLOCK_YI_RADICALS =73, /*[A490]*/ - - /** @stable ICU 2.0 */ - UBLOCK_HANGUL_SYLLABLES =74, /*[AC00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_HIGH_SURROGATES =75, /*[D800]*/ - - /** @stable ICU 2.0 */ - UBLOCK_HIGH_PRIVATE_USE_SURROGATES =76, /*[DB80]*/ - - /** @stable ICU 2.0 */ - UBLOCK_LOW_SURROGATES =77, /*[DC00]*/ - - /** - * Same as UBLOCK_PRIVATE_USE. - * Until Unicode 3.1.1, the corresponding block name was "Private Use", - * and multiple code point ranges had this block. - * Unicode 3.2 renames the block for the BMP PUA to "Private Use Area" and - * adds separate blocks for the supplementary PUAs. - * - * @stable ICU 2.0 - */ - UBLOCK_PRIVATE_USE_AREA =78, /*[E000]*/ - /** - * Same as UBLOCK_PRIVATE_USE_AREA. - * Until Unicode 3.1.1, the corresponding block name was "Private Use", - * and multiple code point ranges had this block. - * Unicode 3.2 renames the block for the BMP PUA to "Private Use Area" and - * adds separate blocks for the supplementary PUAs. - * - * @stable ICU 2.0 - */ - UBLOCK_PRIVATE_USE = UBLOCK_PRIVATE_USE_AREA, - - /** @stable ICU 2.0 */ - UBLOCK_CJK_COMPATIBILITY_IDEOGRAPHS =79, /*[F900]*/ - - /** @stable ICU 2.0 */ - UBLOCK_ALPHABETIC_PRESENTATION_FORMS =80, /*[FB00]*/ - - /** @stable ICU 2.0 */ - UBLOCK_ARABIC_PRESENTATION_FORMS_A =81, /*[FB50]*/ - - /** @stable ICU 2.0 */ - UBLOCK_COMBINING_HALF_MARKS =82, /*[FE20]*/ - - /** @stable ICU 2.0 */ - UBLOCK_CJK_COMPATIBILITY_FORMS =83, /*[FE30]*/ - - /** @stable ICU 2.0 */ - UBLOCK_SMALL_FORM_VARIANTS =84, /*[FE50]*/ - - /** @stable ICU 2.0 */ - UBLOCK_ARABIC_PRESENTATION_FORMS_B =85, /*[FE70]*/ - - /** @stable ICU 2.0 */ - UBLOCK_SPECIALS =86, /*[FFF0]*/ - - /** @stable ICU 2.0 */ - UBLOCK_HALFWIDTH_AND_FULLWIDTH_FORMS =87, /*[FF00]*/ - - /* New blocks in Unicode 3.1 */ - - /** @stable ICU 2.0 */ - UBLOCK_OLD_ITALIC = 88, /*[10300]*/ - /** @stable ICU 2.0 */ - UBLOCK_GOTHIC = 89, /*[10330]*/ - /** @stable ICU 2.0 */ - UBLOCK_DESERET = 90, /*[10400]*/ - /** @stable ICU 2.0 */ - UBLOCK_BYZANTINE_MUSICAL_SYMBOLS = 91, /*[1D000]*/ - /** @stable ICU 2.0 */ - UBLOCK_MUSICAL_SYMBOLS = 92, /*[1D100]*/ - /** @stable ICU 2.0 */ - UBLOCK_MATHEMATICAL_ALPHANUMERIC_SYMBOLS = 93, /*[1D400]*/ - /** @stable ICU 2.0 */ - UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B = 94, /*[20000]*/ - /** @stable ICU 2.0 */ - UBLOCK_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT = 95, /*[2F800]*/ - /** @stable ICU 2.0 */ - UBLOCK_TAGS = 96, /*[E0000]*/ - - /* New blocks in Unicode 3.2 */ - - /** @stable ICU 3.0 */ - UBLOCK_CYRILLIC_SUPPLEMENT = 97, /*[0500]*/ - /** - * Unicode 4.0.1 renames the "Cyrillic Supplementary" block to "Cyrillic Supplement". - * @stable ICU 2.2 - */ - UBLOCK_CYRILLIC_SUPPLEMENTARY = UBLOCK_CYRILLIC_SUPPLEMENT, - /** @stable ICU 2.2 */ - UBLOCK_TAGALOG = 98, /*[1700]*/ - /** @stable ICU 2.2 */ - UBLOCK_HANUNOO = 99, /*[1720]*/ - /** @stable ICU 2.2 */ - UBLOCK_BUHID = 100, /*[1740]*/ - /** @stable ICU 2.2 */ - UBLOCK_TAGBANWA = 101, /*[1760]*/ - /** @stable ICU 2.2 */ - UBLOCK_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A = 102, /*[27C0]*/ - /** @stable ICU 2.2 */ - UBLOCK_SUPPLEMENTAL_ARROWS_A = 103, /*[27F0]*/ - /** @stable ICU 2.2 */ - UBLOCK_SUPPLEMENTAL_ARROWS_B = 104, /*[2900]*/ - /** @stable ICU 2.2 */ - UBLOCK_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B = 105, /*[2980]*/ - /** @stable ICU 2.2 */ - UBLOCK_SUPPLEMENTAL_MATHEMATICAL_OPERATORS = 106, /*[2A00]*/ - /** @stable ICU 2.2 */ - UBLOCK_KATAKANA_PHONETIC_EXTENSIONS = 107, /*[31F0]*/ - /** @stable ICU 2.2 */ - UBLOCK_VARIATION_SELECTORS = 108, /*[FE00]*/ - /** @stable ICU 2.2 */ - UBLOCK_SUPPLEMENTARY_PRIVATE_USE_AREA_A = 109, /*[F0000]*/ - /** @stable ICU 2.2 */ - UBLOCK_SUPPLEMENTARY_PRIVATE_USE_AREA_B = 110, /*[100000]*/ - - /* New blocks in Unicode 4 */ - - /** @stable ICU 2.6 */ - UBLOCK_LIMBU = 111, /*[1900]*/ - /** @stable ICU 2.6 */ - UBLOCK_TAI_LE = 112, /*[1950]*/ - /** @stable ICU 2.6 */ - UBLOCK_KHMER_SYMBOLS = 113, /*[19E0]*/ - /** @stable ICU 2.6 */ - UBLOCK_PHONETIC_EXTENSIONS = 114, /*[1D00]*/ - /** @stable ICU 2.6 */ - UBLOCK_MISCELLANEOUS_SYMBOLS_AND_ARROWS = 115, /*[2B00]*/ - /** @stable ICU 2.6 */ - UBLOCK_YIJING_HEXAGRAM_SYMBOLS = 116, /*[4DC0]*/ - /** @stable ICU 2.6 */ - UBLOCK_LINEAR_B_SYLLABARY = 117, /*[10000]*/ - /** @stable ICU 2.6 */ - UBLOCK_LINEAR_B_IDEOGRAMS = 118, /*[10080]*/ - /** @stable ICU 2.6 */ - UBLOCK_AEGEAN_NUMBERS = 119, /*[10100]*/ - /** @stable ICU 2.6 */ - UBLOCK_UGARITIC = 120, /*[10380]*/ - /** @stable ICU 2.6 */ - UBLOCK_SHAVIAN = 121, /*[10450]*/ - /** @stable ICU 2.6 */ - UBLOCK_OSMANYA = 122, /*[10480]*/ - /** @stable ICU 2.6 */ - UBLOCK_CYPRIOT_SYLLABARY = 123, /*[10800]*/ - /** @stable ICU 2.6 */ - UBLOCK_TAI_XUAN_JING_SYMBOLS = 124, /*[1D300]*/ - /** @stable ICU 2.6 */ - UBLOCK_VARIATION_SELECTORS_SUPPLEMENT = 125, /*[E0100]*/ - - /* New blocks in Unicode 4.1 */ - - /** @stable ICU 3.4 */ - UBLOCK_ANCIENT_GREEK_MUSICAL_NOTATION = 126, /*[1D200]*/ - /** @stable ICU 3.4 */ - UBLOCK_ANCIENT_GREEK_NUMBERS = 127, /*[10140]*/ - /** @stable ICU 3.4 */ - UBLOCK_ARABIC_SUPPLEMENT = 128, /*[0750]*/ - /** @stable ICU 3.4 */ - UBLOCK_BUGINESE = 129, /*[1A00]*/ - /** @stable ICU 3.4 */ - UBLOCK_CJK_STROKES = 130, /*[31C0]*/ - /** @stable ICU 3.4 */ - UBLOCK_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT = 131, /*[1DC0]*/ - /** @stable ICU 3.4 */ - UBLOCK_COPTIC = 132, /*[2C80]*/ - /** @stable ICU 3.4 */ - UBLOCK_ETHIOPIC_EXTENDED = 133, /*[2D80]*/ - /** @stable ICU 3.4 */ - UBLOCK_ETHIOPIC_SUPPLEMENT = 134, /*[1380]*/ - /** @stable ICU 3.4 */ - UBLOCK_GEORGIAN_SUPPLEMENT = 135, /*[2D00]*/ - /** @stable ICU 3.4 */ - UBLOCK_GLAGOLITIC = 136, /*[2C00]*/ - /** @stable ICU 3.4 */ - UBLOCK_KHAROSHTHI = 137, /*[10A00]*/ - /** @stable ICU 3.4 */ - UBLOCK_MODIFIER_TONE_LETTERS = 138, /*[A700]*/ - /** @stable ICU 3.4 */ - UBLOCK_NEW_TAI_LUE = 139, /*[1980]*/ - /** @stable ICU 3.4 */ - UBLOCK_OLD_PERSIAN = 140, /*[103A0]*/ - /** @stable ICU 3.4 */ - UBLOCK_PHONETIC_EXTENSIONS_SUPPLEMENT = 141, /*[1D80]*/ - /** @stable ICU 3.4 */ - UBLOCK_SUPPLEMENTAL_PUNCTUATION = 142, /*[2E00]*/ - /** @stable ICU 3.4 */ - UBLOCK_SYLOTI_NAGRI = 143, /*[A800]*/ - /** @stable ICU 3.4 */ - UBLOCK_TIFINAGH = 144, /*[2D30]*/ - /** @stable ICU 3.4 */ - UBLOCK_VERTICAL_FORMS = 145, /*[FE10]*/ - - /* New blocks in Unicode 5.0 */ - - /** @stable ICU 3.6 */ - UBLOCK_NKO = 146, /*[07C0]*/ - /** @stable ICU 3.6 */ - UBLOCK_BALINESE = 147, /*[1B00]*/ - /** @stable ICU 3.6 */ - UBLOCK_LATIN_EXTENDED_C = 148, /*[2C60]*/ - /** @stable ICU 3.6 */ - UBLOCK_LATIN_EXTENDED_D = 149, /*[A720]*/ - /** @stable ICU 3.6 */ - UBLOCK_PHAGS_PA = 150, /*[A840]*/ - /** @stable ICU 3.6 */ - UBLOCK_PHOENICIAN = 151, /*[10900]*/ - /** @stable ICU 3.6 */ - UBLOCK_CUNEIFORM = 152, /*[12000]*/ - /** @stable ICU 3.6 */ - UBLOCK_CUNEIFORM_NUMBERS_AND_PUNCTUATION = 153, /*[12400]*/ - /** @stable ICU 3.6 */ - UBLOCK_COUNTING_ROD_NUMERALS = 154, /*[1D360]*/ - - /* New blocks in Unicode 5.1 */ - - /** @stable ICU 4.0 */ - UBLOCK_SUNDANESE = 155, /*[1B80]*/ - /** @stable ICU 4.0 */ - UBLOCK_LEPCHA = 156, /*[1C00]*/ - /** @stable ICU 4.0 */ - UBLOCK_OL_CHIKI = 157, /*[1C50]*/ - /** @stable ICU 4.0 */ - UBLOCK_CYRILLIC_EXTENDED_A = 158, /*[2DE0]*/ - /** @stable ICU 4.0 */ - UBLOCK_VAI = 159, /*[A500]*/ - /** @stable ICU 4.0 */ - UBLOCK_CYRILLIC_EXTENDED_B = 160, /*[A640]*/ - /** @stable ICU 4.0 */ - UBLOCK_SAURASHTRA = 161, /*[A880]*/ - /** @stable ICU 4.0 */ - UBLOCK_KAYAH_LI = 162, /*[A900]*/ - /** @stable ICU 4.0 */ - UBLOCK_REJANG = 163, /*[A930]*/ - /** @stable ICU 4.0 */ - UBLOCK_CHAM = 164, /*[AA00]*/ - /** @stable ICU 4.0 */ - UBLOCK_ANCIENT_SYMBOLS = 165, /*[10190]*/ - /** @stable ICU 4.0 */ - UBLOCK_PHAISTOS_DISC = 166, /*[101D0]*/ - /** @stable ICU 4.0 */ - UBLOCK_LYCIAN = 167, /*[10280]*/ - /** @stable ICU 4.0 */ - UBLOCK_CARIAN = 168, /*[102A0]*/ - /** @stable ICU 4.0 */ - UBLOCK_LYDIAN = 169, /*[10920]*/ - /** @stable ICU 4.0 */ - UBLOCK_MAHJONG_TILES = 170, /*[1F000]*/ - /** @stable ICU 4.0 */ - UBLOCK_DOMINO_TILES = 171, /*[1F030]*/ - - /* New blocks in Unicode 5.2 */ - - /** @stable ICU 4.4 */ - UBLOCK_SAMARITAN = 172, /*[0800]*/ - /** @stable ICU 4.4 */ - UBLOCK_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED = 173, /*[18B0]*/ - /** @stable ICU 4.4 */ - UBLOCK_TAI_THAM = 174, /*[1A20]*/ - /** @stable ICU 4.4 */ - UBLOCK_VEDIC_EXTENSIONS = 175, /*[1CD0]*/ - /** @stable ICU 4.4 */ - UBLOCK_LISU = 176, /*[A4D0]*/ - /** @stable ICU 4.4 */ - UBLOCK_BAMUM = 177, /*[A6A0]*/ - /** @stable ICU 4.4 */ - UBLOCK_COMMON_INDIC_NUMBER_FORMS = 178, /*[A830]*/ - /** @stable ICU 4.4 */ - UBLOCK_DEVANAGARI_EXTENDED = 179, /*[A8E0]*/ - /** @stable ICU 4.4 */ - UBLOCK_HANGUL_JAMO_EXTENDED_A = 180, /*[A960]*/ - /** @stable ICU 4.4 */ - UBLOCK_JAVANESE = 181, /*[A980]*/ - /** @stable ICU 4.4 */ - UBLOCK_MYANMAR_EXTENDED_A = 182, /*[AA60]*/ - /** @stable ICU 4.4 */ - UBLOCK_TAI_VIET = 183, /*[AA80]*/ - /** @stable ICU 4.4 */ - UBLOCK_MEETEI_MAYEK = 184, /*[ABC0]*/ - /** @stable ICU 4.4 */ - UBLOCK_HANGUL_JAMO_EXTENDED_B = 185, /*[D7B0]*/ - /** @stable ICU 4.4 */ - UBLOCK_IMPERIAL_ARAMAIC = 186, /*[10840]*/ - /** @stable ICU 4.4 */ - UBLOCK_OLD_SOUTH_ARABIAN = 187, /*[10A60]*/ - /** @stable ICU 4.4 */ - UBLOCK_AVESTAN = 188, /*[10B00]*/ - /** @stable ICU 4.4 */ - UBLOCK_INSCRIPTIONAL_PARTHIAN = 189, /*[10B40]*/ - /** @stable ICU 4.4 */ - UBLOCK_INSCRIPTIONAL_PAHLAVI = 190, /*[10B60]*/ - /** @stable ICU 4.4 */ - UBLOCK_OLD_TURKIC = 191, /*[10C00]*/ - /** @stable ICU 4.4 */ - UBLOCK_RUMI_NUMERAL_SYMBOLS = 192, /*[10E60]*/ - /** @stable ICU 4.4 */ - UBLOCK_KAITHI = 193, /*[11080]*/ - /** @stable ICU 4.4 */ - UBLOCK_EGYPTIAN_HIEROGLYPHS = 194, /*[13000]*/ - /** @stable ICU 4.4 */ - UBLOCK_ENCLOSED_ALPHANUMERIC_SUPPLEMENT = 195, /*[1F100]*/ - /** @stable ICU 4.4 */ - UBLOCK_ENCLOSED_IDEOGRAPHIC_SUPPLEMENT = 196, /*[1F200]*/ - /** @stable ICU 4.4 */ - UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C = 197, /*[2A700]*/ - - /* New blocks in Unicode 6.0 */ - - /** @stable ICU 4.6 */ - UBLOCK_MANDAIC = 198, /*[0840]*/ - /** @stable ICU 4.6 */ - UBLOCK_BATAK = 199, /*[1BC0]*/ - /** @stable ICU 4.6 */ - UBLOCK_ETHIOPIC_EXTENDED_A = 200, /*[AB00]*/ - /** @stable ICU 4.6 */ - UBLOCK_BRAHMI = 201, /*[11000]*/ - /** @stable ICU 4.6 */ - UBLOCK_BAMUM_SUPPLEMENT = 202, /*[16800]*/ - /** @stable ICU 4.6 */ - UBLOCK_KANA_SUPPLEMENT = 203, /*[1B000]*/ - /** @stable ICU 4.6 */ - UBLOCK_PLAYING_CARDS = 204, /*[1F0A0]*/ - /** @stable ICU 4.6 */ - UBLOCK_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS = 205, /*[1F300]*/ - /** @stable ICU 4.6 */ - UBLOCK_EMOTICONS = 206, /*[1F600]*/ - /** @stable ICU 4.6 */ - UBLOCK_TRANSPORT_AND_MAP_SYMBOLS = 207, /*[1F680]*/ - /** @stable ICU 4.6 */ - UBLOCK_ALCHEMICAL_SYMBOLS = 208, /*[1F700]*/ - /** @stable ICU 4.6 */ - UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D = 209, /*[2B740]*/ - - /* New blocks in Unicode 6.1 */ - - /** @stable ICU 49 */ - UBLOCK_ARABIC_EXTENDED_A = 210, /*[08A0]*/ - /** @stable ICU 49 */ - UBLOCK_ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS = 211, /*[1EE00]*/ - /** @stable ICU 49 */ - UBLOCK_CHAKMA = 212, /*[11100]*/ - /** @stable ICU 49 */ - UBLOCK_MEETEI_MAYEK_EXTENSIONS = 213, /*[AAE0]*/ - /** @stable ICU 49 */ - UBLOCK_MEROITIC_CURSIVE = 214, /*[109A0]*/ - /** @stable ICU 49 */ - UBLOCK_MEROITIC_HIEROGLYPHS = 215, /*[10980]*/ - /** @stable ICU 49 */ - UBLOCK_MIAO = 216, /*[16F00]*/ - /** @stable ICU 49 */ - UBLOCK_SHARADA = 217, /*[11180]*/ - /** @stable ICU 49 */ - UBLOCK_SORA_SOMPENG = 218, /*[110D0]*/ - /** @stable ICU 49 */ - UBLOCK_SUNDANESE_SUPPLEMENT = 219, /*[1CC0]*/ - /** @stable ICU 49 */ - UBLOCK_TAKRI = 220, /*[11680]*/ - - /* New blocks in Unicode 7.0 */ - - /** @stable ICU 54 */ - UBLOCK_BASSA_VAH = 221, /*[16AD0]*/ - /** @stable ICU 54 */ - UBLOCK_CAUCASIAN_ALBANIAN = 222, /*[10530]*/ - /** @stable ICU 54 */ - UBLOCK_COPTIC_EPACT_NUMBERS = 223, /*[102E0]*/ - /** @stable ICU 54 */ - UBLOCK_COMBINING_DIACRITICAL_MARKS_EXTENDED = 224, /*[1AB0]*/ - /** @stable ICU 54 */ - UBLOCK_DUPLOYAN = 225, /*[1BC00]*/ - /** @stable ICU 54 */ - UBLOCK_ELBASAN = 226, /*[10500]*/ - /** @stable ICU 54 */ - UBLOCK_GEOMETRIC_SHAPES_EXTENDED = 227, /*[1F780]*/ - /** @stable ICU 54 */ - UBLOCK_GRANTHA = 228, /*[11300]*/ - /** @stable ICU 54 */ - UBLOCK_KHOJKI = 229, /*[11200]*/ - /** @stable ICU 54 */ - UBLOCK_KHUDAWADI = 230, /*[112B0]*/ - /** @stable ICU 54 */ - UBLOCK_LATIN_EXTENDED_E = 231, /*[AB30]*/ - /** @stable ICU 54 */ - UBLOCK_LINEAR_A = 232, /*[10600]*/ - /** @stable ICU 54 */ - UBLOCK_MAHAJANI = 233, /*[11150]*/ - /** @stable ICU 54 */ - UBLOCK_MANICHAEAN = 234, /*[10AC0]*/ - /** @stable ICU 54 */ - UBLOCK_MENDE_KIKAKUI = 235, /*[1E800]*/ - /** @stable ICU 54 */ - UBLOCK_MODI = 236, /*[11600]*/ - /** @stable ICU 54 */ - UBLOCK_MRO = 237, /*[16A40]*/ - /** @stable ICU 54 */ - UBLOCK_MYANMAR_EXTENDED_B = 238, /*[A9E0]*/ - /** @stable ICU 54 */ - UBLOCK_NABATAEAN = 239, /*[10880]*/ - /** @stable ICU 54 */ - UBLOCK_OLD_NORTH_ARABIAN = 240, /*[10A80]*/ - /** @stable ICU 54 */ - UBLOCK_OLD_PERMIC = 241, /*[10350]*/ - /** @stable ICU 54 */ - UBLOCK_ORNAMENTAL_DINGBATS = 242, /*[1F650]*/ - /** @stable ICU 54 */ - UBLOCK_PAHAWH_HMONG = 243, /*[16B00]*/ - /** @stable ICU 54 */ - UBLOCK_PALMYRENE = 244, /*[10860]*/ - /** @stable ICU 54 */ - UBLOCK_PAU_CIN_HAU = 245, /*[11AC0]*/ - /** @stable ICU 54 */ - UBLOCK_PSALTER_PAHLAVI = 246, /*[10B80]*/ - /** @stable ICU 54 */ - UBLOCK_SHORTHAND_FORMAT_CONTROLS = 247, /*[1BCA0]*/ - /** @stable ICU 54 */ - UBLOCK_SIDDHAM = 248, /*[11580]*/ - /** @stable ICU 54 */ - UBLOCK_SINHALA_ARCHAIC_NUMBERS = 249, /*[111E0]*/ - /** @stable ICU 54 */ - UBLOCK_SUPPLEMENTAL_ARROWS_C = 250, /*[1F800]*/ - /** @stable ICU 54 */ - UBLOCK_TIRHUTA = 251, /*[11480]*/ - /** @stable ICU 54 */ - UBLOCK_WARANG_CITI = 252, /*[118A0]*/ - - /* New blocks in Unicode 8.0 */ - - /** @stable ICU 56 */ - UBLOCK_AHOM = 253, /*[11700]*/ - /** @stable ICU 56 */ - UBLOCK_ANATOLIAN_HIEROGLYPHS = 254, /*[14400]*/ - /** @stable ICU 56 */ - UBLOCK_CHEROKEE_SUPPLEMENT = 255, /*[AB70]*/ - /** @stable ICU 56 */ - UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E = 256, /*[2B820]*/ - /** @stable ICU 56 */ - UBLOCK_EARLY_DYNASTIC_CUNEIFORM = 257, /*[12480]*/ - /** @stable ICU 56 */ - UBLOCK_HATRAN = 258, /*[108E0]*/ - /** @stable ICU 56 */ - UBLOCK_MULTANI = 259, /*[11280]*/ - /** @stable ICU 56 */ - UBLOCK_OLD_HUNGARIAN = 260, /*[10C80]*/ - /** @stable ICU 56 */ - UBLOCK_SUPPLEMENTAL_SYMBOLS_AND_PICTOGRAPHS = 261, /*[1F900]*/ - /** @stable ICU 56 */ - UBLOCK_SUTTON_SIGNWRITING = 262, /*[1D800]*/ - - /* New blocks in Unicode 9.0 */ - - /** @stable ICU 58 */ - UBLOCK_ADLAM = 263, /*[1E900]*/ - /** @stable ICU 58 */ - UBLOCK_BHAIKSUKI = 264, /*[11C00]*/ - /** @stable ICU 58 */ - UBLOCK_CYRILLIC_EXTENDED_C = 265, /*[1C80]*/ - /** @stable ICU 58 */ - UBLOCK_GLAGOLITIC_SUPPLEMENT = 266, /*[1E000]*/ - /** @stable ICU 58 */ - UBLOCK_IDEOGRAPHIC_SYMBOLS_AND_PUNCTUATION = 267, /*[16FE0]*/ - /** @stable ICU 58 */ - UBLOCK_MARCHEN = 268, /*[11C70]*/ - /** @stable ICU 58 */ - UBLOCK_MONGOLIAN_SUPPLEMENT = 269, /*[11660]*/ - /** @stable ICU 58 */ - UBLOCK_NEWA = 270, /*[11400]*/ - /** @stable ICU 58 */ - UBLOCK_OSAGE = 271, /*[104B0]*/ - /** @stable ICU 58 */ - UBLOCK_TANGUT = 272, /*[17000]*/ - /** @stable ICU 58 */ - UBLOCK_TANGUT_COMPONENTS = 273, /*[18800]*/ - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UBlockCode value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_BLOCK). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UBLOCK_COUNT = 274, -#endif // U_HIDE_DEPRECATED_API - - /** @stable ICU 2.0 */ - UBLOCK_INVALID_CODE=-1 -}; - -/** @stable ICU 2.0 */ -typedef enum UBlockCode UBlockCode; - -/** - * East Asian Width constants. - * - * @see UCHAR_EAST_ASIAN_WIDTH - * @see u_getIntPropertyValue - * @stable ICU 2.2 - */ -typedef enum UEastAsianWidth { - /* - * Note: UEastAsianWidth constants are parsed by preparseucd.py. - * It matches lines like - * U_EA_ - */ - - U_EA_NEUTRAL, /*[N]*/ - U_EA_AMBIGUOUS, /*[A]*/ - U_EA_HALFWIDTH, /*[H]*/ - U_EA_FULLWIDTH, /*[F]*/ - U_EA_NARROW, /*[Na]*/ - U_EA_WIDE, /*[W]*/ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UEastAsianWidth value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_EAST_ASIAN_WIDTH). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_EA_COUNT -#endif // U_HIDE_DEPRECATED_API -} UEastAsianWidth; - -/** - * Selector constants for u_charName(). - * u_charName() returns the "modern" name of a - * Unicode character; or the name that was defined in - * Unicode version 1.0, before the Unicode standard merged - * with ISO-10646; or an "extended" name that gives each - * Unicode code point a unique name. - * - * @see u_charName - * @stable ICU 2.0 - */ -typedef enum UCharNameChoice { - /** Unicode character name (Name property). @stable ICU 2.0 */ - U_UNICODE_CHAR_NAME, -#ifndef U_HIDE_DEPRECATED_API - /** - * The Unicode_1_Name property value which is of little practical value. - * Beginning with ICU 49, ICU APIs return an empty string for this name choice. - * @deprecated ICU 49 - */ - U_UNICODE_10_CHAR_NAME, -#endif /* U_HIDE_DEPRECATED_API */ - /** Standard or synthetic character name. @stable ICU 2.0 */ - U_EXTENDED_CHAR_NAME = U_UNICODE_CHAR_NAME+2, - /** Corrected name from NameAliases.txt. @stable ICU 4.4 */ - U_CHAR_NAME_ALIAS, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UCharNameChoice value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_CHAR_NAME_CHOICE_COUNT -#endif // U_HIDE_DEPRECATED_API -} UCharNameChoice; - -/** - * Selector constants for u_getPropertyName() and - * u_getPropertyValueName(). These selectors are used to choose which - * name is returned for a given property or value. All properties and - * values have a long name. Most have a short name, but some do not. - * Unicode allows for additional names, beyond the long and short - * name, which would be indicated by U_LONG_PROPERTY_NAME + i, where - * i=1, 2,... - * - * @see u_getPropertyName() - * @see u_getPropertyValueName() - * @stable ICU 2.4 - */ -typedef enum UPropertyNameChoice { - U_SHORT_PROPERTY_NAME, - U_LONG_PROPERTY_NAME, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UPropertyNameChoice value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_PROPERTY_NAME_CHOICE_COUNT -#endif // U_HIDE_DEPRECATED_API -} UPropertyNameChoice; - -/** - * Decomposition Type constants. - * - * @see UCHAR_DECOMPOSITION_TYPE - * @stable ICU 2.2 - */ -typedef enum UDecompositionType { - /* - * Note: UDecompositionType constants are parsed by preparseucd.py. - * It matches lines like - * U_DT_ - */ - - U_DT_NONE, /*[none]*/ - U_DT_CANONICAL, /*[can]*/ - U_DT_COMPAT, /*[com]*/ - U_DT_CIRCLE, /*[enc]*/ - U_DT_FINAL, /*[fin]*/ - U_DT_FONT, /*[font]*/ - U_DT_FRACTION, /*[fra]*/ - U_DT_INITIAL, /*[init]*/ - U_DT_ISOLATED, /*[iso]*/ - U_DT_MEDIAL, /*[med]*/ - U_DT_NARROW, /*[nar]*/ - U_DT_NOBREAK, /*[nb]*/ - U_DT_SMALL, /*[sml]*/ - U_DT_SQUARE, /*[sqr]*/ - U_DT_SUB, /*[sub]*/ - U_DT_SUPER, /*[sup]*/ - U_DT_VERTICAL, /*[vert]*/ - U_DT_WIDE, /*[wide]*/ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UDecompositionType value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_DECOMPOSITION_TYPE). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_DT_COUNT /* 18 */ -#endif // U_HIDE_DEPRECATED_API -} UDecompositionType; - -/** - * Joining Type constants. - * - * @see UCHAR_JOINING_TYPE - * @stable ICU 2.2 - */ -typedef enum UJoiningType { - /* - * Note: UJoiningType constants are parsed by preparseucd.py. - * It matches lines like - * U_JT_ - */ - - U_JT_NON_JOINING, /*[U]*/ - U_JT_JOIN_CAUSING, /*[C]*/ - U_JT_DUAL_JOINING, /*[D]*/ - U_JT_LEFT_JOINING, /*[L]*/ - U_JT_RIGHT_JOINING, /*[R]*/ - U_JT_TRANSPARENT, /*[T]*/ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UJoiningType value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_JOINING_TYPE). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_JT_COUNT /* 6 */ -#endif // U_HIDE_DEPRECATED_API -} UJoiningType; - -/** - * Joining Group constants. - * - * @see UCHAR_JOINING_GROUP - * @stable ICU 2.2 - */ -typedef enum UJoiningGroup { - /* - * Note: UJoiningGroup constants are parsed by preparseucd.py. - * It matches lines like - * U_JG_ - */ - - U_JG_NO_JOINING_GROUP, - U_JG_AIN, - U_JG_ALAPH, - U_JG_ALEF, - U_JG_BEH, - U_JG_BETH, - U_JG_DAL, - U_JG_DALATH_RISH, - U_JG_E, - U_JG_FEH, - U_JG_FINAL_SEMKATH, - U_JG_GAF, - U_JG_GAMAL, - U_JG_HAH, - U_JG_TEH_MARBUTA_GOAL, /**< @stable ICU 4.6 */ - U_JG_HAMZA_ON_HEH_GOAL=U_JG_TEH_MARBUTA_GOAL, - U_JG_HE, - U_JG_HEH, - U_JG_HEH_GOAL, - U_JG_HETH, - U_JG_KAF, - U_JG_KAPH, - U_JG_KNOTTED_HEH, - U_JG_LAM, - U_JG_LAMADH, - U_JG_MEEM, - U_JG_MIM, - U_JG_NOON, - U_JG_NUN, - U_JG_PE, - U_JG_QAF, - U_JG_QAPH, - U_JG_REH, - U_JG_REVERSED_PE, - U_JG_SAD, - U_JG_SADHE, - U_JG_SEEN, - U_JG_SEMKATH, - U_JG_SHIN, - U_JG_SWASH_KAF, - U_JG_SYRIAC_WAW, - U_JG_TAH, - U_JG_TAW, - U_JG_TEH_MARBUTA, - U_JG_TETH, - U_JG_WAW, - U_JG_YEH, - U_JG_YEH_BARREE, - U_JG_YEH_WITH_TAIL, - U_JG_YUDH, - U_JG_YUDH_HE, - U_JG_ZAIN, - U_JG_FE, /**< @stable ICU 2.6 */ - U_JG_KHAPH, /**< @stable ICU 2.6 */ - U_JG_ZHAIN, /**< @stable ICU 2.6 */ - U_JG_BURUSHASKI_YEH_BARREE, /**< @stable ICU 4.0 */ - U_JG_FARSI_YEH, /**< @stable ICU 4.4 */ - U_JG_NYA, /**< @stable ICU 4.4 */ - U_JG_ROHINGYA_YEH, /**< @stable ICU 49 */ - U_JG_MANICHAEAN_ALEPH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_AYIN, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_BETH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_DALETH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_DHAMEDH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_FIVE, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_GIMEL, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_HETH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_HUNDRED, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_KAPH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_LAMEDH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_MEM, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_NUN, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_ONE, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_PE, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_QOPH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_RESH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_SADHE, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_SAMEKH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_TAW, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_TEN, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_TETH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_THAMEDH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_TWENTY, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_WAW, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_YODH, /**< @stable ICU 54 */ - U_JG_MANICHAEAN_ZAYIN, /**< @stable ICU 54 */ - U_JG_STRAIGHT_WAW, /**< @stable ICU 54 */ - U_JG_AFRICAN_FEH, /**< @stable ICU 58 */ - U_JG_AFRICAN_NOON, /**< @stable ICU 58 */ - U_JG_AFRICAN_QAF, /**< @stable ICU 58 */ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UJoiningGroup value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_JOINING_GROUP). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_JG_COUNT -#endif // U_HIDE_DEPRECATED_API -} UJoiningGroup; - -/** - * Grapheme Cluster Break constants. - * - * @see UCHAR_GRAPHEME_CLUSTER_BREAK - * @stable ICU 3.4 - */ -typedef enum UGraphemeClusterBreak { - /* - * Note: UGraphemeClusterBreak constants are parsed by preparseucd.py. - * It matches lines like - * U_GCB_ - */ - - U_GCB_OTHER = 0, /*[XX]*/ - U_GCB_CONTROL = 1, /*[CN]*/ - U_GCB_CR = 2, /*[CR]*/ - U_GCB_EXTEND = 3, /*[EX]*/ - U_GCB_L = 4, /*[L]*/ - U_GCB_LF = 5, /*[LF]*/ - U_GCB_LV = 6, /*[LV]*/ - U_GCB_LVT = 7, /*[LVT]*/ - U_GCB_T = 8, /*[T]*/ - U_GCB_V = 9, /*[V]*/ - /** @stable ICU 4.0 */ - U_GCB_SPACING_MARK = 10, /*[SM]*/ /* from here on: new in Unicode 5.1/ICU 4.0 */ - /** @stable ICU 4.0 */ - U_GCB_PREPEND = 11, /*[PP]*/ - /** @stable ICU 50 */ - U_GCB_REGIONAL_INDICATOR = 12, /*[RI]*/ /* new in Unicode 6.2/ICU 50 */ - /** @stable ICU 58 */ - U_GCB_E_BASE = 13, /*[EB]*/ /* from here on: new in Unicode 9.0/ICU 58 */ - /** @stable ICU 58 */ - U_GCB_E_BASE_GAZ = 14, /*[EBG]*/ - /** @stable ICU 58 */ - U_GCB_E_MODIFIER = 15, /*[EM]*/ - /** @stable ICU 58 */ - U_GCB_GLUE_AFTER_ZWJ = 16, /*[GAZ]*/ - /** @stable ICU 58 */ - U_GCB_ZWJ = 17, /*[ZWJ]*/ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UGraphemeClusterBreak value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_GRAPHEME_CLUSTER_BREAK). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_GCB_COUNT = 18 -#endif // U_HIDE_DEPRECATED_API -} UGraphemeClusterBreak; - -/** - * Word Break constants. - * (UWordBreak is a pre-existing enum type in ubrk.h for word break status tags.) - * - * @see UCHAR_WORD_BREAK - * @stable ICU 3.4 - */ -typedef enum UWordBreakValues { - /* - * Note: UWordBreakValues constants are parsed by preparseucd.py. - * It matches lines like - * U_WB_ - */ - - U_WB_OTHER = 0, /*[XX]*/ - U_WB_ALETTER = 1, /*[LE]*/ - U_WB_FORMAT = 2, /*[FO]*/ - U_WB_KATAKANA = 3, /*[KA]*/ - U_WB_MIDLETTER = 4, /*[ML]*/ - U_WB_MIDNUM = 5, /*[MN]*/ - U_WB_NUMERIC = 6, /*[NU]*/ - U_WB_EXTENDNUMLET = 7, /*[EX]*/ - /** @stable ICU 4.0 */ - U_WB_CR = 8, /*[CR]*/ /* from here on: new in Unicode 5.1/ICU 4.0 */ - /** @stable ICU 4.0 */ - U_WB_EXTEND = 9, /*[Extend]*/ - /** @stable ICU 4.0 */ - U_WB_LF = 10, /*[LF]*/ - /** @stable ICU 4.0 */ - U_WB_MIDNUMLET =11, /*[MB]*/ - /** @stable ICU 4.0 */ - U_WB_NEWLINE =12, /*[NL]*/ - /** @stable ICU 50 */ - U_WB_REGIONAL_INDICATOR = 13, /*[RI]*/ /* new in Unicode 6.2/ICU 50 */ - /** @stable ICU 52 */ - U_WB_HEBREW_LETTER = 14, /*[HL]*/ /* from here on: new in Unicode 6.3/ICU 52 */ - /** @stable ICU 52 */ - U_WB_SINGLE_QUOTE = 15, /*[SQ]*/ - /** @stable ICU 52 */ - U_WB_DOUBLE_QUOTE = 16, /*[DQ]*/ - /** @stable ICU 58 */ - U_WB_E_BASE = 17, /*[EB]*/ /* from here on: new in Unicode 9.0/ICU 58 */ - /** @stable ICU 58 */ - U_WB_E_BASE_GAZ = 18, /*[EBG]*/ - /** @stable ICU 58 */ - U_WB_E_MODIFIER = 19, /*[EM]*/ - /** @stable ICU 58 */ - U_WB_GLUE_AFTER_ZWJ = 20, /*[GAZ]*/ - /** @stable ICU 58 */ - U_WB_ZWJ = 21, /*[ZWJ]*/ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UWordBreakValues value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_WORD_BREAK). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_WB_COUNT = 22 -#endif // U_HIDE_DEPRECATED_API -} UWordBreakValues; - -/** - * Sentence Break constants. - * - * @see UCHAR_SENTENCE_BREAK - * @stable ICU 3.4 - */ -typedef enum USentenceBreak { - /* - * Note: USentenceBreak constants are parsed by preparseucd.py. - * It matches lines like - * U_SB_ - */ - - U_SB_OTHER = 0, /*[XX]*/ - U_SB_ATERM = 1, /*[AT]*/ - U_SB_CLOSE = 2, /*[CL]*/ - U_SB_FORMAT = 3, /*[FO]*/ - U_SB_LOWER = 4, /*[LO]*/ - U_SB_NUMERIC = 5, /*[NU]*/ - U_SB_OLETTER = 6, /*[LE]*/ - U_SB_SEP = 7, /*[SE]*/ - U_SB_SP = 8, /*[SP]*/ - U_SB_STERM = 9, /*[ST]*/ - U_SB_UPPER = 10, /*[UP]*/ - U_SB_CR = 11, /*[CR]*/ /* from here on: new in Unicode 5.1/ICU 4.0 */ - U_SB_EXTEND = 12, /*[EX]*/ - U_SB_LF = 13, /*[LF]*/ - U_SB_SCONTINUE = 14, /*[SC]*/ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal USentenceBreak value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_SENTENCE_BREAK). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_SB_COUNT = 15 -#endif // U_HIDE_DEPRECATED_API -} USentenceBreak; - -/** - * Line Break constants. - * - * @see UCHAR_LINE_BREAK - * @stable ICU 2.2 - */ -typedef enum ULineBreak { - /* - * Note: ULineBreak constants are parsed by preparseucd.py. - * It matches lines like - * U_LB_ - */ - - U_LB_UNKNOWN = 0, /*[XX]*/ - U_LB_AMBIGUOUS = 1, /*[AI]*/ - U_LB_ALPHABETIC = 2, /*[AL]*/ - U_LB_BREAK_BOTH = 3, /*[B2]*/ - U_LB_BREAK_AFTER = 4, /*[BA]*/ - U_LB_BREAK_BEFORE = 5, /*[BB]*/ - U_LB_MANDATORY_BREAK = 6, /*[BK]*/ - U_LB_CONTINGENT_BREAK = 7, /*[CB]*/ - U_LB_CLOSE_PUNCTUATION = 8, /*[CL]*/ - U_LB_COMBINING_MARK = 9, /*[CM]*/ - U_LB_CARRIAGE_RETURN = 10, /*[CR]*/ - U_LB_EXCLAMATION = 11, /*[EX]*/ - U_LB_GLUE = 12, /*[GL]*/ - U_LB_HYPHEN = 13, /*[HY]*/ - U_LB_IDEOGRAPHIC = 14, /*[ID]*/ - /** Renamed from the misspelled "inseperable" in Unicode 4.0.1/ICU 3.0 @stable ICU 3.0 */ - U_LB_INSEPARABLE = 15, /*[IN]*/ - U_LB_INSEPERABLE = U_LB_INSEPARABLE, - U_LB_INFIX_NUMERIC = 16, /*[IS]*/ - U_LB_LINE_FEED = 17, /*[LF]*/ - U_LB_NONSTARTER = 18, /*[NS]*/ - U_LB_NUMERIC = 19, /*[NU]*/ - U_LB_OPEN_PUNCTUATION = 20, /*[OP]*/ - U_LB_POSTFIX_NUMERIC = 21, /*[PO]*/ - U_LB_PREFIX_NUMERIC = 22, /*[PR]*/ - U_LB_QUOTATION = 23, /*[QU]*/ - U_LB_COMPLEX_CONTEXT = 24, /*[SA]*/ - U_LB_SURROGATE = 25, /*[SG]*/ - U_LB_SPACE = 26, /*[SP]*/ - U_LB_BREAK_SYMBOLS = 27, /*[SY]*/ - U_LB_ZWSPACE = 28, /*[ZW]*/ - /** @stable ICU 2.6 */ - U_LB_NEXT_LINE = 29, /*[NL]*/ /* from here on: new in Unicode 4/ICU 2.6 */ - /** @stable ICU 2.6 */ - U_LB_WORD_JOINER = 30, /*[WJ]*/ - /** @stable ICU 3.4 */ - U_LB_H2 = 31, /*[H2]*/ /* from here on: new in Unicode 4.1/ICU 3.4 */ - /** @stable ICU 3.4 */ - U_LB_H3 = 32, /*[H3]*/ - /** @stable ICU 3.4 */ - U_LB_JL = 33, /*[JL]*/ - /** @stable ICU 3.4 */ - U_LB_JT = 34, /*[JT]*/ - /** @stable ICU 3.4 */ - U_LB_JV = 35, /*[JV]*/ - /** @stable ICU 4.4 */ - U_LB_CLOSE_PARENTHESIS = 36, /*[CP]*/ /* new in Unicode 5.2/ICU 4.4 */ - /** @stable ICU 49 */ - U_LB_CONDITIONAL_JAPANESE_STARTER = 37,/*[CJ]*/ /* new in Unicode 6.1/ICU 49 */ - /** @stable ICU 49 */ - U_LB_HEBREW_LETTER = 38, /*[HL]*/ /* new in Unicode 6.1/ICU 49 */ - /** @stable ICU 50 */ - U_LB_REGIONAL_INDICATOR = 39,/*[RI]*/ /* new in Unicode 6.2/ICU 50 */ - /** @stable ICU 58 */ - U_LB_E_BASE = 40, /*[EB]*/ /* from here on: new in Unicode 9.0/ICU 58 */ - /** @stable ICU 58 */ - U_LB_E_MODIFIER = 41, /*[EM]*/ - /** @stable ICU 58 */ - U_LB_ZWJ = 42, /*[ZWJ]*/ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal ULineBreak value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_LINE_BREAK). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_LB_COUNT = 43 -#endif // U_HIDE_DEPRECATED_API -} ULineBreak; - -/** - * Numeric Type constants. - * - * @see UCHAR_NUMERIC_TYPE - * @stable ICU 2.2 - */ -typedef enum UNumericType { - /* - * Note: UNumericType constants are parsed by preparseucd.py. - * It matches lines like - * U_NT_ - */ - - U_NT_NONE, /*[None]*/ - U_NT_DECIMAL, /*[de]*/ - U_NT_DIGIT, /*[di]*/ - U_NT_NUMERIC, /*[nu]*/ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UNumericType value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_NUMERIC_TYPE). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_NT_COUNT -#endif // U_HIDE_DEPRECATED_API -} UNumericType; - -/** - * Hangul Syllable Type constants. - * - * @see UCHAR_HANGUL_SYLLABLE_TYPE - * @stable ICU 2.6 - */ -typedef enum UHangulSyllableType { - /* - * Note: UHangulSyllableType constants are parsed by preparseucd.py. - * It matches lines like - * U_HST_ - */ - - U_HST_NOT_APPLICABLE, /*[NA]*/ - U_HST_LEADING_JAMO, /*[L]*/ - U_HST_VOWEL_JAMO, /*[V]*/ - U_HST_TRAILING_JAMO, /*[T]*/ - U_HST_LV_SYLLABLE, /*[LV]*/ - U_HST_LVT_SYLLABLE, /*[LVT]*/ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UHangulSyllableType value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_HANGUL_SYLLABLE_TYPE). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_HST_COUNT -#endif // U_HIDE_DEPRECATED_API -} UHangulSyllableType; - -/** - * Check a binary Unicode property for a code point. - * - * Unicode, especially in version 3.2, defines many more properties than the - * original set in UnicodeData.txt. - * - * The properties APIs are intended to reflect Unicode properties as defined - * in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR). - * For details about the properties see http://www.unicode.org/ucd/ . - * For names of Unicode properties see the UCD file PropertyAliases.txt. - * - * Important: If ICU is built with UCD files from Unicode versions below 3.2, - * then properties marked with "new in Unicode 3.2" are not or not fully available. - * - * @param c Code point to test. - * @param which UProperty selector constant, identifies which binary property to check. - * Must be UCHAR_BINARY_START<=which=0. - * True for characters with general category "Nd" (decimal digit numbers) - * as well as Latin letters a-f and A-F in both ASCII and Fullwidth ASCII. - * (That is, for letters with code points - * 0041..0046, 0061..0066, FF21..FF26, FF41..FF46.) - * - * In order to narrow the definition of hexadecimal digits to only ASCII - * characters, use (c<=0x7f && u_isxdigit(c)). - * - * This is a C/POSIX migration function. - * See the comments about C/POSIX character classification functions in the - * documentation at the top of this header file. - * - * @param c the code point to be tested - * @return TRUE if the code point is a hexadecimal digit - * - * @stable ICU 2.6 - */ -U_STABLE UBool U_EXPORT2 -u_isxdigit(UChar32 c); - -/** - * Determines whether the specified code point is a punctuation character. - * True for characters with general categories "P" (punctuation). - * - * This is a C/POSIX migration function. - * See the comments about C/POSIX character classification functions in the - * documentation at the top of this header file. - * - * @param c the code point to be tested - * @return TRUE if the code point is a punctuation character - * - * @stable ICU 2.6 - */ -U_STABLE UBool U_EXPORT2 -u_ispunct(UChar32 c); - -/** - * Determines whether the specified code point is a "graphic" character - * (printable, excluding spaces). - * TRUE for all characters except those with general categories - * "Cc" (control codes), "Cf" (format controls), "Cs" (surrogates), - * "Cn" (unassigned), and "Z" (separators). - * - * This is a C/POSIX migration function. - * See the comments about C/POSIX character classification functions in the - * documentation at the top of this header file. - * - * @param c the code point to be tested - * @return TRUE if the code point is a "graphic" character - * - * @stable ICU 2.6 - */ -U_STABLE UBool U_EXPORT2 -u_isgraph(UChar32 c); - -/** - * Determines whether the specified code point is a "blank" or "horizontal space", - * a character that visibly separates words on a line. - * The following are equivalent definitions: - * - * TRUE for Unicode White_Space characters except for "vertical space controls" - * where "vertical space controls" are the following characters: - * U+000A (LF) U+000B (VT) U+000C (FF) U+000D (CR) U+0085 (NEL) U+2028 (LS) U+2029 (PS) - * - * same as - * - * TRUE for U+0009 (TAB) and characters with general category "Zs" (space separators) - * except Zero Width Space (ZWSP, U+200B). - * - * Note: There are several ICU whitespace functions; please see the uchar.h - * file documentation for a detailed comparison. - * - * This is a C/POSIX migration function. - * See the comments about C/POSIX character classification functions in the - * documentation at the top of this header file. - * - * @param c the code point to be tested - * @return TRUE if the code point is a "blank" - * - * @stable ICU 2.6 - */ -U_STABLE UBool U_EXPORT2 -u_isblank(UChar32 c); - -/** - * Determines whether the specified code point is "defined", - * which usually means that it is assigned a character. - * True for general categories other than "Cn" (other, not assigned), - * i.e., true for all code points mentioned in UnicodeData.txt. - * - * Note that non-character code points (e.g., U+FDD0) are not "defined" - * (they are Cn), but surrogate code points are "defined" (Cs). - * - * Same as java.lang.Character.isDefined(). - * - * @param c the code point to be tested - * @return TRUE if the code point is assigned a character - * - * @see u_isdigit - * @see u_isalpha - * @see u_isalnum - * @see u_isupper - * @see u_islower - * @see u_istitle - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -u_isdefined(UChar32 c); - -/** - * Determines if the specified character is a space character or not. - * - * Note: There are several ICU whitespace functions; please see the uchar.h - * file documentation for a detailed comparison. - * - * This is a C/POSIX migration function. - * See the comments about C/POSIX character classification functions in the - * documentation at the top of this header file. - * - * @param c the character to be tested - * @return true if the character is a space character; false otherwise. - * - * @see u_isJavaSpaceChar - * @see u_isWhitespace - * @see u_isUWhiteSpace - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -u_isspace(UChar32 c); - -/** - * Determine if the specified code point is a space character according to Java. - * True for characters with general categories "Z" (separators), - * which does not include control codes (e.g., TAB or Line Feed). - * - * Same as java.lang.Character.isSpaceChar(). - * - * Note: There are several ICU whitespace functions; please see the uchar.h - * file documentation for a detailed comparison. - * - * @param c the code point to be tested - * @return TRUE if the code point is a space character according to Character.isSpaceChar() - * - * @see u_isspace - * @see u_isWhitespace - * @see u_isUWhiteSpace - * @stable ICU 2.6 - */ -U_STABLE UBool U_EXPORT2 -u_isJavaSpaceChar(UChar32 c); - -/** - * Determines if the specified code point is a whitespace character according to Java/ICU. - * A character is considered to be a Java whitespace character if and only - * if it satisfies one of the following criteria: - * - * - It is a Unicode Separator character (categories "Z" = "Zs" or "Zl" or "Zp"), but is not - * also a non-breaking space (U+00A0 NBSP or U+2007 Figure Space or U+202F Narrow NBSP). - * - It is U+0009 HORIZONTAL TABULATION. - * - It is U+000A LINE FEED. - * - It is U+000B VERTICAL TABULATION. - * - It is U+000C FORM FEED. - * - It is U+000D CARRIAGE RETURN. - * - It is U+001C FILE SEPARATOR. - * - It is U+001D GROUP SEPARATOR. - * - It is U+001E RECORD SEPARATOR. - * - It is U+001F UNIT SEPARATOR. - * - * This API tries to sync with the semantics of Java's - * java.lang.Character.isWhitespace(), but it may not return - * the exact same results because of the Unicode version - * difference. - * - * Note: Unicode 4.0.1 changed U+200B ZERO WIDTH SPACE from a Space Separator (Zs) - * to a Format Control (Cf). Since then, isWhitespace(0x200b) returns false. - * See http://www.unicode.org/versions/Unicode4.0.1/ - * - * Note: There are several ICU whitespace functions; please see the uchar.h - * file documentation for a detailed comparison. - * - * @param c the code point to be tested - * @return TRUE if the code point is a whitespace character according to Java/ICU - * - * @see u_isspace - * @see u_isJavaSpaceChar - * @see u_isUWhiteSpace - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -u_isWhitespace(UChar32 c); - -/** - * Determines whether the specified code point is a control character - * (as defined by this function). - * A control character is one of the following: - * - ISO 8-bit control character (U+0000..U+001f and U+007f..U+009f) - * - U_CONTROL_CHAR (Cc) - * - U_FORMAT_CHAR (Cf) - * - U_LINE_SEPARATOR (Zl) - * - U_PARAGRAPH_SEPARATOR (Zp) - * - * This is a C/POSIX migration function. - * See the comments about C/POSIX character classification functions in the - * documentation at the top of this header file. - * - * @param c the code point to be tested - * @return TRUE if the code point is a control character - * - * @see UCHAR_DEFAULT_IGNORABLE_CODE_POINT - * @see u_isprint - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -u_iscntrl(UChar32 c); - -/** - * Determines whether the specified code point is an ISO control code. - * True for U+0000..U+001f and U+007f..U+009f (general category "Cc"). - * - * Same as java.lang.Character.isISOControl(). - * - * @param c the code point to be tested - * @return TRUE if the code point is an ISO control code - * - * @see u_iscntrl - * @stable ICU 2.6 - */ -U_STABLE UBool U_EXPORT2 -u_isISOControl(UChar32 c); - -/** - * Determines whether the specified code point is a printable character. - * True for general categories other than "C" (controls). - * - * This is a C/POSIX migration function. - * See the comments about C/POSIX character classification functions in the - * documentation at the top of this header file. - * - * @param c the code point to be tested - * @return TRUE if the code point is a printable character - * - * @see UCHAR_DEFAULT_IGNORABLE_CODE_POINT - * @see u_iscntrl - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -u_isprint(UChar32 c); - -/** - * Determines whether the specified code point is a base character. - * True for general categories "L" (letters), "N" (numbers), - * "Mc" (spacing combining marks), and "Me" (enclosing marks). - * - * Note that this is different from the Unicode definition in - * chapter 3.5, conformance clause D13, - * which defines base characters to be all characters (not Cn) - * that do not graphically combine with preceding characters (M) - * and that are neither control (Cc) or format (Cf) characters. - * - * @param c the code point to be tested - * @return TRUE if the code point is a base character according to this function - * - * @see u_isalpha - * @see u_isdigit - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -u_isbase(UChar32 c); - -/** - * Returns the bidirectional category value for the code point, - * which is used in the Unicode bidirectional algorithm - * (UAX #9 http://www.unicode.org/reports/tr9/). - * Note that some unassigned code points have bidi values - * of R or AL because they are in blocks that are reserved - * for Right-To-Left scripts. - * - * Same as java.lang.Character.getDirectionality() - * - * @param c the code point to be tested - * @return the bidirectional category (UCharDirection) value - * - * @see UCharDirection - * @stable ICU 2.0 - */ -U_STABLE UCharDirection U_EXPORT2 -u_charDirection(UChar32 c); - -/** - * Determines whether the code point has the Bidi_Mirrored property. - * This property is set for characters that are commonly used in - * Right-To-Left contexts and need to be displayed with a "mirrored" - * glyph. - * - * Same as java.lang.Character.isMirrored(). - * Same as UCHAR_BIDI_MIRRORED - * - * @param c the code point to be tested - * @return TRUE if the character has the Bidi_Mirrored property - * - * @see UCHAR_BIDI_MIRRORED - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -u_isMirrored(UChar32 c); - -/** - * Maps the specified character to a "mirror-image" character. - * For characters with the Bidi_Mirrored property, implementations - * sometimes need a "poor man's" mapping to another Unicode - * character (code point) such that the default glyph may serve - * as the mirror-image of the default glyph of the specified - * character. This is useful for text conversion to and from - * codepages with visual order, and for displays without glyph - * selection capabilities. - * - * @param c the code point to be mapped - * @return another Unicode code point that may serve as a mirror-image - * substitute, or c itself if there is no such mapping or c - * does not have the Bidi_Mirrored property - * - * @see UCHAR_BIDI_MIRRORED - * @see u_isMirrored - * @stable ICU 2.0 - */ -U_STABLE UChar32 U_EXPORT2 -u_charMirror(UChar32 c); - -/** - * Maps the specified character to its paired bracket character. - * For Bidi_Paired_Bracket_Type!=None, this is the same as u_charMirror(). - * Otherwise c itself is returned. - * See http://www.unicode.org/reports/tr9/ - * - * @param c the code point to be mapped - * @return the paired bracket code point, - * or c itself if there is no such mapping - * (Bidi_Paired_Bracket_Type=None) - * - * @see UCHAR_BIDI_PAIRED_BRACKET - * @see UCHAR_BIDI_PAIRED_BRACKET_TYPE - * @see u_charMirror - * @stable ICU 52 - */ -U_STABLE UChar32 U_EXPORT2 -u_getBidiPairedBracket(UChar32 c); - -/** - * Returns the general category value for the code point. - * - * Same as java.lang.Character.getType(). - * - * @param c the code point to be tested - * @return the general category (UCharCategory) value - * - * @see UCharCategory - * @stable ICU 2.0 - */ -U_STABLE int8_t U_EXPORT2 -u_charType(UChar32 c); - -/** - * Get a single-bit bit set for the general category of a character. - * This bit set can be compared bitwise with U_GC_SM_MASK, U_GC_L_MASK, etc. - * Same as U_MASK(u_charType(c)). - * - * @param c the code point to be tested - * @return a single-bit mask corresponding to the general category (UCharCategory) value - * - * @see u_charType - * @see UCharCategory - * @see U_GC_CN_MASK - * @stable ICU 2.1 - */ -#define U_GET_GC_MASK(c) U_MASK(u_charType(c)) - -/** - * Callback from u_enumCharTypes(), is called for each contiguous range - * of code points c (where start<=cnameChoice, the character name written - * into the buffer is the "modern" name or the name that was defined - * in Unicode version 1.0. - * The name contains only "invariant" characters - * like A-Z, 0-9, space, and '-'. - * Unicode 1.0 names are only retrieved if they are different from the modern - * names and if the data file contains the data for them. gennames may or may - * not be called with a command line option to include 1.0 names in unames.dat. - * - * @param code The character (code point) for which to get the name. - * It must be 0<=code<=0x10ffff. - * @param nameChoice Selector for which name to get. - * @param buffer Destination address for copying the name. - * The name will always be zero-terminated. - * If there is no name, then the buffer will be set to the empty string. - * @param bufferLength ==sizeof(buffer) - * @param pErrorCode Pointer to a UErrorCode variable; - * check for U_SUCCESS() after u_charName() - * returns. - * @return The length of the name, or 0 if there is no name for this character. - * If the bufferLength is less than or equal to the length, then the buffer - * contains the truncated name and the returned length indicates the full - * length of the name. - * The length does not include the zero-termination. - * - * @see UCharNameChoice - * @see u_charFromName - * @see u_enumCharNames - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_charName(UChar32 code, UCharNameChoice nameChoice, - char *buffer, int32_t bufferLength, - UErrorCode *pErrorCode); - -#ifndef U_HIDE_DEPRECATED_API -/** - * Returns an empty string. - * Used to return the ISO 10646 comment for a character. - * The Unicode ISO_Comment property is deprecated and has no values. - * - * @param c The character (code point) for which to get the ISO comment. - * It must be 0<=c<=0x10ffff. - * @param dest Destination address for copying the comment. - * The comment will be zero-terminated if possible. - * If there is no comment, then the buffer will be set to the empty string. - * @param destCapacity ==sizeof(dest) - * @param pErrorCode Pointer to a UErrorCode variable; - * check for U_SUCCESS() after u_getISOComment() - * returns. - * @return 0 - * - * @deprecated ICU 49 - */ -U_DEPRECATED int32_t U_EXPORT2 -u_getISOComment(UChar32 c, - char *dest, int32_t destCapacity, - UErrorCode *pErrorCode); -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * Find a Unicode character by its name and return its code point value. - * The name is matched exactly and completely. - * If the name does not correspond to a code point, pErrorCode - * is set to U_INVALID_CHAR_FOUND. - * A Unicode 1.0 name is matched only if it differs from the modern name. - * Unicode names are all uppercase. Extended names are lowercase followed - * by an uppercase hexadecimal number, and within angle brackets. - * - * @param nameChoice Selector for which name to match. - * @param name The name to match. - * @param pErrorCode Pointer to a UErrorCode variable - * @return The Unicode value of the code point with the given name, - * or an undefined value if there is no such code point. - * - * @see UCharNameChoice - * @see u_charName - * @see u_enumCharNames - * @stable ICU 1.7 - */ -U_STABLE UChar32 U_EXPORT2 -u_charFromName(UCharNameChoice nameChoice, - const char *name, - UErrorCode *pErrorCode); - -/** - * Type of a callback function for u_enumCharNames() that gets called - * for each Unicode character with the code point value and - * the character name. - * If such a function returns FALSE, then the enumeration is stopped. - * - * @param context The context pointer that was passed to u_enumCharNames(). - * @param code The Unicode code point for the character with this name. - * @param nameChoice Selector for which kind of names is enumerated. - * @param name The character's name, zero-terminated. - * @param length The length of the name. - * @return TRUE if the enumeration should continue, FALSE to stop it. - * - * @see UCharNameChoice - * @see u_enumCharNames - * @stable ICU 1.7 - */ -typedef UBool U_CALLCONV UEnumCharNamesFn(void *context, - UChar32 code, - UCharNameChoice nameChoice, - const char *name, - int32_t length); - -/** - * Enumerate all assigned Unicode characters between the start and limit - * code points (start inclusive, limit exclusive) and call a function - * for each, passing the code point value and the character name. - * For Unicode 1.0 names, only those are enumerated that differ from the - * modern names. - * - * @param start The first code point in the enumeration range. - * @param limit One more than the last code point in the enumeration range - * (the first one after the range). - * @param fn The function that is to be called for each character name. - * @param context An arbitrary pointer that is passed to the function. - * @param nameChoice Selector for which kind of names to enumerate. - * @param pErrorCode Pointer to a UErrorCode variable - * - * @see UCharNameChoice - * @see UEnumCharNamesFn - * @see u_charName - * @see u_charFromName - * @stable ICU 1.7 - */ -U_STABLE void U_EXPORT2 -u_enumCharNames(UChar32 start, UChar32 limit, - UEnumCharNamesFn *fn, - void *context, - UCharNameChoice nameChoice, - UErrorCode *pErrorCode); - -/** - * Return the Unicode name for a given property, as given in the - * Unicode database file PropertyAliases.txt. - * - * In addition, this function maps the property - * UCHAR_GENERAL_CATEGORY_MASK to the synthetic names "gcm" / - * "General_Category_Mask". These names are not in - * PropertyAliases.txt. - * - * @param property UProperty selector other than UCHAR_INVALID_CODE. - * If out of range, NULL is returned. - * - * @param nameChoice selector for which name to get. If out of range, - * NULL is returned. All properties have a long name. Most - * have a short name, but some do not. Unicode allows for - * additional names; if present these will be returned by - * U_LONG_PROPERTY_NAME + i, where i=1, 2,... - * - * @return a pointer to the name, or NULL if either the - * property or the nameChoice is out of range. If a given - * nameChoice returns NULL, then all larger values of - * nameChoice will return NULL, with one exception: if NULL is - * returned for U_SHORT_PROPERTY_NAME, then - * U_LONG_PROPERTY_NAME (and higher) may still return a - * non-NULL value. The returned pointer is valid until - * u_cleanup() is called. - * - * @see UProperty - * @see UPropertyNameChoice - * @stable ICU 2.4 - */ -U_STABLE const char* U_EXPORT2 -u_getPropertyName(UProperty property, - UPropertyNameChoice nameChoice); - -/** - * Return the UProperty enum for a given property name, as specified - * in the Unicode database file PropertyAliases.txt. Short, long, and - * any other variants are recognized. - * - * In addition, this function maps the synthetic names "gcm" / - * "General_Category_Mask" to the property - * UCHAR_GENERAL_CATEGORY_MASK. These names are not in - * PropertyAliases.txt. - * - * @param alias the property name to be matched. The name is compared - * using "loose matching" as described in PropertyAliases.txt. - * - * @return a UProperty enum, or UCHAR_INVALID_CODE if the given name - * does not match any property. - * - * @see UProperty - * @stable ICU 2.4 - */ -U_STABLE UProperty U_EXPORT2 -u_getPropertyEnum(const char* alias); - -/** - * Return the Unicode name for a given property value, as given in the - * Unicode database file PropertyValueAliases.txt. - * - * Note: Some of the names in PropertyValueAliases.txt can only be - * retrieved using UCHAR_GENERAL_CATEGORY_MASK, not - * UCHAR_GENERAL_CATEGORY. These include: "C" / "Other", "L" / - * "Letter", "LC" / "Cased_Letter", "M" / "Mark", "N" / "Number", "P" - * / "Punctuation", "S" / "Symbol", and "Z" / "Separator". - * - * @param property UProperty selector constant. - * Must be UCHAR_BINARY_START<=which2<=radix<=36 or if the - * value of c is not a valid digit in the specified - * radix, -1 is returned. A character is a valid digit - * if at least one of the following is true: - *

    - *
  • The character has a decimal digit value. - * Such characters have the general category "Nd" (decimal digit numbers) - * and a Numeric_Type of Decimal. - * In this case the value is the character's decimal digit value.
  • - *
  • The character is one of the uppercase Latin letters - * 'A' through 'Z'. - * In this case the value is c-'A'+10.
  • - *
  • The character is one of the lowercase Latin letters - * 'a' through 'z'. - * In this case the value is ch-'a'+10.
  • - *
  • Latin letters from both the ASCII range (0061..007A, 0041..005A) - * as well as from the Fullwidth ASCII range (FF41..FF5A, FF21..FF3A) - * are recognized.
  • - *
- * - * Same as java.lang.Character.digit(). - * - * @param ch the code point to be tested. - * @param radix the radix. - * @return the numeric value represented by the character in the - * specified radix, - * or -1 if there is no value or if the value exceeds the radix. - * - * @see UCHAR_NUMERIC_TYPE - * @see u_forDigit - * @see u_charDigitValue - * @see u_isdigit - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_digit(UChar32 ch, int8_t radix); - -/** - * Determines the character representation for a specific digit in - * the specified radix. If the value of radix is not a - * valid radix, or the value of digit is not a valid - * digit in the specified radix, the null character - * (U+0000) is returned. - *

- * The radix argument is valid if it is greater than or - * equal to 2 and less than or equal to 36. - * The digit argument is valid if - * 0 <= digit < radix. - *

- * If the digit is less than 10, then - * '0' + digit is returned. Otherwise, the value - * 'a' + digit - 10 is returned. - * - * Same as java.lang.Character.forDigit(). - * - * @param digit the number to convert to a character. - * @param radix the radix. - * @return the char representation of the specified digit - * in the specified radix. - * - * @see u_digit - * @see u_charDigitValue - * @see u_isdigit - * @stable ICU 2.0 - */ -U_STABLE UChar32 U_EXPORT2 -u_forDigit(int32_t digit, int8_t radix); - -/** - * Get the "age" of the code point. - * The "age" is the Unicode version when the code point was first - * designated (as a non-character or for Private Use) - * or assigned a character. - * This can be useful to avoid emitting code points to receiving - * processes that do not accept newer characters. - * The data is from the UCD file DerivedAge.txt. - * - * @param c The code point. - * @param versionArray The Unicode version number array, to be filled in. - * - * @stable ICU 2.1 - */ -U_STABLE void U_EXPORT2 -u_charAge(UChar32 c, UVersionInfo versionArray); - -/** - * Gets the Unicode version information. - * The version array is filled in with the version information - * for the Unicode standard that is currently used by ICU. - * For example, Unicode version 3.1.1 is represented as an array with - * the values { 3, 1, 1, 0 }. - * - * @param versionArray an output array that will be filled in with - * the Unicode version number - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -u_getUnicodeVersion(UVersionInfo versionArray); - -#if !UCONFIG_NO_NORMALIZATION -/** - * Get the FC_NFKC_Closure property string for a character. - * See Unicode Standard Annex #15 for details, search for "FC_NFKC_Closure" - * or for "FNC": http://www.unicode.org/reports/tr15/ - * - * @param c The character (code point) for which to get the FC_NFKC_Closure string. - * It must be 0<=c<=0x10ffff. - * @param dest Destination address for copying the string. - * The string will be zero-terminated if possible. - * If there is no FC_NFKC_Closure string, - * then the buffer will be set to the empty string. - * @param destCapacity ==sizeof(dest) - * @param pErrorCode Pointer to a UErrorCode variable. - * @return The length of the string, or 0 if there is no FC_NFKC_Closure string for this character. - * If the destCapacity is less than or equal to the length, then the buffer - * contains the truncated name and the returned length indicates the full - * length of the name. - * The length does not include the zero-termination. - * - * @stable ICU 2.2 - */ -U_STABLE int32_t U_EXPORT2 -u_getFC_NFKC_Closure(UChar32 c, UChar *dest, int32_t destCapacity, UErrorCode *pErrorCode); - -#endif - - -U_CDECL_END - -#endif /*_UCHAR*/ -/*eof*/ diff --git a/win32/include/spidermonkey/unicode/ucharstrie.h b/win32/include/spidermonkey/unicode/ucharstrie.h deleted file mode 100755 index 8daed447..00000000 --- a/win32/include/spidermonkey/unicode/ucharstrie.h +++ /dev/null @@ -1,578 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2010-2012, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* file name: ucharstrie.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2010nov14 -* created by: Markus W. Scherer -*/ - -#ifndef __UCHARSTRIE_H__ -#define __UCHARSTRIE_H__ - -/** - * \file - * \brief C++ API: Trie for mapping Unicode strings (or 16-bit-unit sequences) - * to integer values. - */ - -#include "unicode/utypes.h" -#include "unicode/unistr.h" -#include "unicode/uobject.h" -#include "unicode/ustringtrie.h" - -U_NAMESPACE_BEGIN - -class Appendable; -class UCharsTrieBuilder; -class UVector32; - -/** - * Light-weight, non-const reader class for a UCharsTrie. - * Traverses a UChar-serialized data structure with minimal state, - * for mapping strings (16-bit-unit sequences) to non-negative integer values. - * - * This class owns the serialized trie data only if it was constructed by - * the builder's build() method. - * The public constructor and the copy constructor only alias the data (only copy the pointer). - * There is no assignment operator. - * - * This class is not intended for public subclassing. - * @stable ICU 4.8 - */ -class U_COMMON_API UCharsTrie : public UMemory { -public: - /** - * Constructs a UCharsTrie reader instance. - * - * The trieUChars must contain a copy of a UChar sequence from the UCharsTrieBuilder, - * starting with the first UChar of that sequence. - * The UCharsTrie object will not read more UChars than - * the UCharsTrieBuilder generated in the corresponding build() call. - * - * The array is not copied/cloned and must not be modified while - * the UCharsTrie object is in use. - * - * @param trieUChars The UChar array that contains the serialized trie. - * @stable ICU 4.8 - */ - UCharsTrie(const UChar *trieUChars) - : ownedArray_(NULL), uchars_(trieUChars), - pos_(uchars_), remainingMatchLength_(-1) {} - - /** - * Destructor. - * @stable ICU 4.8 - */ - ~UCharsTrie(); - - /** - * Copy constructor, copies the other trie reader object and its state, - * but not the UChar array which will be shared. (Shallow copy.) - * @param other Another UCharsTrie object. - * @stable ICU 4.8 - */ - UCharsTrie(const UCharsTrie &other) - : ownedArray_(NULL), uchars_(other.uchars_), - pos_(other.pos_), remainingMatchLength_(other.remainingMatchLength_) {} - - /** - * Resets this trie to its initial state. - * @return *this - * @stable ICU 4.8 - */ - UCharsTrie &reset() { - pos_=uchars_; - remainingMatchLength_=-1; - return *this; - } - - /** - * UCharsTrie state object, for saving a trie's current state - * and resetting the trie back to this state later. - * @stable ICU 4.8 - */ - class State : public UMemory { - public: - /** - * Constructs an empty State. - * @stable ICU 4.8 - */ - State() { uchars=NULL; } - private: - friend class UCharsTrie; - - const UChar *uchars; - const UChar *pos; - int32_t remainingMatchLength; - }; - - /** - * Saves the state of this trie. - * @param state The State object to hold the trie's state. - * @return *this - * @see resetToState - * @stable ICU 4.8 - */ - const UCharsTrie &saveState(State &state) const { - state.uchars=uchars_; - state.pos=pos_; - state.remainingMatchLength=remainingMatchLength_; - return *this; - } - - /** - * Resets this trie to the saved state. - * If the state object contains no state, or the state of a different trie, - * then this trie remains unchanged. - * @param state The State object which holds a saved trie state. - * @return *this - * @see saveState - * @see reset - * @stable ICU 4.8 - */ - UCharsTrie &resetToState(const State &state) { - if(uchars_==state.uchars && uchars_!=NULL) { - pos_=state.pos; - remainingMatchLength_=state.remainingMatchLength; - } - return *this; - } - - /** - * Determines whether the string so far matches, whether it has a value, - * and whether another input UChar can continue a matching string. - * @return The match/value Result. - * @stable ICU 4.8 - */ - UStringTrieResult current() const; - - /** - * Traverses the trie from the initial state for this input UChar. - * Equivalent to reset().next(uchar). - * @param uchar Input char value. Values below 0 and above 0xffff will never match. - * @return The match/value Result. - * @stable ICU 4.8 - */ - inline UStringTrieResult first(int32_t uchar) { - remainingMatchLength_=-1; - return nextImpl(uchars_, uchar); - } - - /** - * Traverses the trie from the initial state for the - * one or two UTF-16 code units for this input code point. - * Equivalent to reset().nextForCodePoint(cp). - * @param cp A Unicode code point 0..0x10ffff. - * @return The match/value Result. - * @stable ICU 4.8 - */ - UStringTrieResult firstForCodePoint(UChar32 cp); - - /** - * Traverses the trie from the current state for this input UChar. - * @param uchar Input char value. Values below 0 and above 0xffff will never match. - * @return The match/value Result. - * @stable ICU 4.8 - */ - UStringTrieResult next(int32_t uchar); - - /** - * Traverses the trie from the current state for the - * one or two UTF-16 code units for this input code point. - * @param cp A Unicode code point 0..0x10ffff. - * @return The match/value Result. - * @stable ICU 4.8 - */ - UStringTrieResult nextForCodePoint(UChar32 cp); - - /** - * Traverses the trie from the current state for this string. - * Equivalent to - * \code - * Result result=current(); - * for(each c in s) - * if(!USTRINGTRIE_HAS_NEXT(result)) return USTRINGTRIE_NO_MATCH; - * result=next(c); - * return result; - * \endcode - * @param s A string. Can be NULL if length is 0. - * @param length The length of the string. Can be -1 if NUL-terminated. - * @return The match/value Result. - * @stable ICU 4.8 - */ - UStringTrieResult next(const UChar *s, int32_t length); - - /** - * Returns a matching string's value if called immediately after - * current()/first()/next() returned USTRINGTRIE_INTERMEDIATE_VALUE or USTRINGTRIE_FINAL_VALUE. - * getValue() can be called multiple times. - * - * Do not call getValue() after USTRINGTRIE_NO_MATCH or USTRINGTRIE_NO_VALUE! - * @return The value for the string so far. - * @stable ICU 4.8 - */ - inline int32_t getValue() const { - const UChar *pos=pos_; - int32_t leadUnit=*pos++; - // U_ASSERT(leadUnit>=kMinValueLead); - return leadUnit&kValueIsFinal ? - readValue(pos, leadUnit&0x7fff) : readNodeValue(pos, leadUnit); - } - - /** - * Determines whether all strings reachable from the current state - * map to the same value. - * @param uniqueValue Receives the unique value, if this function returns TRUE. - * (output-only) - * @return TRUE if all strings reachable from the current state - * map to the same value. - * @stable ICU 4.8 - */ - inline UBool hasUniqueValue(int32_t &uniqueValue) const { - const UChar *pos=pos_; - // Skip the rest of a pending linear-match node. - return pos!=NULL && findUniqueValue(pos+remainingMatchLength_+1, FALSE, uniqueValue); - } - - /** - * Finds each UChar which continues the string from the current state. - * That is, each UChar c for which it would be next(c)!=USTRINGTRIE_NO_MATCH now. - * @param out Each next UChar is appended to this object. - * @return the number of UChars which continue the string from here - * @stable ICU 4.8 - */ - int32_t getNextUChars(Appendable &out) const; - - /** - * Iterator for all of the (string, value) pairs in a UCharsTrie. - * @stable ICU 4.8 - */ - class U_COMMON_API Iterator : public UMemory { - public: - /** - * Iterates from the root of a UChar-serialized UCharsTrie. - * @param trieUChars The trie UChars. - * @param maxStringLength If 0, the iterator returns full strings. - * Otherwise, the iterator returns strings with this maximum length. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @stable ICU 4.8 - */ - Iterator(const UChar *trieUChars, int32_t maxStringLength, UErrorCode &errorCode); - - /** - * Iterates from the current state of the specified UCharsTrie. - * @param trie The trie whose state will be copied for iteration. - * @param maxStringLength If 0, the iterator returns full strings. - * Otherwise, the iterator returns strings with this maximum length. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @stable ICU 4.8 - */ - Iterator(const UCharsTrie &trie, int32_t maxStringLength, UErrorCode &errorCode); - - /** - * Destructor. - * @stable ICU 4.8 - */ - ~Iterator(); - - /** - * Resets this iterator to its initial state. - * @return *this - * @stable ICU 4.8 - */ - Iterator &reset(); - - /** - * @return TRUE if there are more elements. - * @stable ICU 4.8 - */ - UBool hasNext() const; - - /** - * Finds the next (string, value) pair if there is one. - * - * If the string is truncated to the maximum length and does not - * have a real value, then the value is set to -1. - * In this case, this "not a real value" is indistinguishable from - * a real value of -1. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return TRUE if there is another element. - * @stable ICU 4.8 - */ - UBool next(UErrorCode &errorCode); - - /** - * @return The string for the last successful next(). - * @stable ICU 4.8 - */ - const UnicodeString &getString() const { return str_; } - /** - * @return The value for the last successful next(). - * @stable ICU 4.8 - */ - int32_t getValue() const { return value_; } - - private: - UBool truncateAndStop() { - pos_=NULL; - value_=-1; // no real value for str - return TRUE; - } - - const UChar *branchNext(const UChar *pos, int32_t length, UErrorCode &errorCode); - - const UChar *uchars_; - const UChar *pos_; - const UChar *initialPos_; - int32_t remainingMatchLength_; - int32_t initialRemainingMatchLength_; - UBool skipValue_; // Skip intermediate value which was already delivered. - - UnicodeString str_; - int32_t maxLength_; - int32_t value_; - - // The stack stores pairs of integers for backtracking to another - // outbound edge of a branch node. - // The first integer is an offset from uchars_. - // The second integer has the str_.length() from before the node in bits 15..0, - // and the remaining branch length in bits 31..16. - // (We could store the remaining branch length minus 1 in bits 30..16 and not use the sign bit, - // but the code looks more confusing that way.) - UVector32 *stack_; - }; - -private: - friend class UCharsTrieBuilder; - - /** - * Constructs a UCharsTrie reader instance. - * Unlike the public constructor which just aliases an array, - * this constructor adopts the builder's array. - * This constructor is only called by the builder. - */ - UCharsTrie(UChar *adoptUChars, const UChar *trieUChars) - : ownedArray_(adoptUChars), uchars_(trieUChars), - pos_(uchars_), remainingMatchLength_(-1) {} - - // No assignment operator. - UCharsTrie &operator=(const UCharsTrie &other); - - inline void stop() { - pos_=NULL; - } - - // Reads a compact 32-bit integer. - // pos is already after the leadUnit, and the lead unit has bit 15 reset. - static inline int32_t readValue(const UChar *pos, int32_t leadUnit) { - int32_t value; - if(leadUnit=kMinTwoUnitValueLead) { - if(leadUnit>6)-1; - } else if(leadUnit=kMinTwoUnitNodeValueLead) { - if(leadUnit=kMinTwoUnitDeltaLead) { - if(delta==kThreeUnitDeltaLead) { - delta=(pos[0]<<16)|pos[1]; - pos+=2; - } else { - delta=((delta-kMinTwoUnitDeltaLead)<<16)|*pos++; - } - } - return pos+delta; - } - - static const UChar *skipDelta(const UChar *pos) { - int32_t delta=*pos++; - if(delta>=kMinTwoUnitDeltaLead) { - if(delta==kThreeUnitDeltaLead) { - pos+=2; - } else { - ++pos; - } - } - return pos; - } - - static inline UStringTrieResult valueResult(int32_t node) { - return (UStringTrieResult)(USTRINGTRIE_INTERMEDIATE_VALUE-(node>>15)); - } - - // Handles a branch node for both next(uchar) and next(string). - UStringTrieResult branchNext(const UChar *pos, int32_t length, int32_t uchar); - - // Requires remainingLength_<0. - UStringTrieResult nextImpl(const UChar *pos, int32_t uchar); - - // Helper functions for hasUniqueValue(). - // Recursively finds a unique value (or whether there is not a unique one) - // from a branch. - static const UChar *findUniqueValueFromBranch(const UChar *pos, int32_t length, - UBool haveUniqueValue, int32_t &uniqueValue); - // Recursively finds a unique value (or whether there is not a unique one) - // starting from a position on a node lead unit. - static UBool findUniqueValue(const UChar *pos, UBool haveUniqueValue, int32_t &uniqueValue); - - // Helper functions for getNextUChars(). - // getNextUChars() when pos is on a branch node. - static void getNextBranchUChars(const UChar *pos, int32_t length, Appendable &out); - - // UCharsTrie data structure - // - // The trie consists of a series of UChar-serialized nodes for incremental - // Unicode string/UChar sequence matching. (UChar=16-bit unsigned integer) - // The root node is at the beginning of the trie data. - // - // Types of nodes are distinguished by their node lead unit ranges. - // After each node, except a final-value node, another node follows to - // encode match values or continue matching further units. - // - // Node types: - // - Final-value node: Stores a 32-bit integer in a compact, variable-length format. - // The value is for the string/UChar sequence so far. - // - Match node, optionally with an intermediate value in a different compact format. - // The value, if present, is for the string/UChar sequence so far. - // - // Aside from the value, which uses the node lead unit's high bits: - // - // - Linear-match node: Matches a number of units. - // - Branch node: Branches to other nodes according to the current input unit. - // The node unit is the length of the branch (number of units to select from) - // minus 1. It is followed by a sub-node: - // - If the length is at most kMaxBranchLinearSubNodeLength, then - // there are length-1 (key, value) pairs and then one more comparison unit. - // If one of the key units matches, then the value is either a final value for - // the string so far, or a "jump" delta to the next node. - // If the last unit matches, then matching continues with the next node. - // (Values have the same encoding as final-value nodes.) - // - If the length is greater than kMaxBranchLinearSubNodeLength, then - // there is one unit and one "jump" delta. - // If the input unit is less than the sub-node unit, then "jump" by delta to - // the next sub-node which will have a length of length/2. - // (The delta has its own compact encoding.) - // Otherwise, skip the "jump" delta to the next sub-node - // which will have a length of length-length/2. - - // Match-node lead unit values, after masking off intermediate-value bits: - - // 0000..002f: Branch node. If node!=0 then the length is node+1, otherwise - // the length is one more than the next unit. - - // For a branch sub-node with at most this many entries, we drop down - // to a linear search. - static const int32_t kMaxBranchLinearSubNodeLength=5; - - // 0030..003f: Linear-match node, match 1..16 units and continue reading the next node. - static const int32_t kMinLinearMatch=0x30; - static const int32_t kMaxLinearMatchLength=0x10; - - // Match-node lead unit bits 14..6 for the optional intermediate value. - // If these bits are 0, then there is no intermediate value. - // Otherwise, see the *NodeValue* constants below. - static const int32_t kMinValueLead=kMinLinearMatch+kMaxLinearMatchLength; // 0x0040 - static const int32_t kNodeTypeMask=kMinValueLead-1; // 0x003f - - // A final-value node has bit 15 set. - static const int32_t kValueIsFinal=0x8000; - - // Compact value: After testing and masking off bit 15, use the following thresholds. - static const int32_t kMaxOneUnitValue=0x3fff; - - static const int32_t kMinTwoUnitValueLead=kMaxOneUnitValue+1; // 0x4000 - static const int32_t kThreeUnitValueLead=0x7fff; - - static const int32_t kMaxTwoUnitValue=((kThreeUnitValueLead-kMinTwoUnitValueLead)<<16)-1; // 0x3ffeffff - - // Compact intermediate-value integer, lead unit shared with a branch or linear-match node. - static const int32_t kMaxOneUnitNodeValue=0xff; - static const int32_t kMinTwoUnitNodeValueLead=kMinValueLead+((kMaxOneUnitNodeValue+1)<<6); // 0x4040 - static const int32_t kThreeUnitNodeValueLead=0x7fc0; - - static const int32_t kMaxTwoUnitNodeValue= - ((kThreeUnitNodeValueLead-kMinTwoUnitNodeValueLead)<<10)-1; // 0xfdffff - - // Compact delta integers. - static const int32_t kMaxOneUnitDelta=0xfbff; - static const int32_t kMinTwoUnitDeltaLead=kMaxOneUnitDelta+1; // 0xfc00 - static const int32_t kThreeUnitDeltaLead=0xffff; - - static const int32_t kMaxTwoUnitDelta=((kThreeUnitDeltaLead-kMinTwoUnitDeltaLead)<<16)-1; // 0x03feffff - - UChar *ownedArray_; - - // Fixed value referencing the UCharsTrie words. - const UChar *uchars_; - - // Iterator variables. - - // Pointer to next trie unit to read. NULL if no more matches. - const UChar *pos_; - // Remaining length of a linear-match node, minus 1. Negative if not in such a node. - int32_t remainingMatchLength_; -}; - -U_NAMESPACE_END - -#endif // __UCHARSTRIE_H__ diff --git a/win32/include/spidermonkey/unicode/ucharstriebuilder.h b/win32/include/spidermonkey/unicode/ucharstriebuilder.h deleted file mode 100755 index cc9fb77a..00000000 --- a/win32/include/spidermonkey/unicode/ucharstriebuilder.h +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2010-2016, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* file name: ucharstriebuilder.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2010nov14 -* created by: Markus W. Scherer -*/ - -#ifndef __UCHARSTRIEBUILDER_H__ -#define __UCHARSTRIEBUILDER_H__ - -#include "unicode/utypes.h" -#include "unicode/stringtriebuilder.h" -#include "unicode/ucharstrie.h" -#include "unicode/unistr.h" - -/** - * \file - * \brief C++ API: Builder for icu::UCharsTrie - */ - -U_NAMESPACE_BEGIN - -class UCharsTrieElement; - -/** - * Builder class for UCharsTrie. - * - * This class is not intended for public subclassing. - * @stable ICU 4.8 - */ -class U_COMMON_API UCharsTrieBuilder : public StringTrieBuilder { -public: - /** - * Constructs an empty builder. - * @param errorCode Standard ICU error code. - * @stable ICU 4.8 - */ - UCharsTrieBuilder(UErrorCode &errorCode); - - /** - * Destructor. - * @stable ICU 4.8 - */ - virtual ~UCharsTrieBuilder(); - - /** - * Adds a (string, value) pair. - * The string must be unique. - * The string contents will be copied; the builder does not keep - * a reference to the input UnicodeString or its buffer. - * @param s The input string. - * @param value The value associated with this string. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return *this - * @stable ICU 4.8 - */ - UCharsTrieBuilder &add(const UnicodeString &s, int32_t value, UErrorCode &errorCode); - - /** - * Builds a UCharsTrie for the add()ed data. - * Once built, no further data can be add()ed until clear() is called. - * - * A UCharsTrie cannot be empty. At least one (string, value) pair - * must have been add()ed. - * - * This method passes ownership of the builder's internal result array to the new trie object. - * Another call to any build() variant will re-serialize the trie. - * After clear() has been called, a new array will be used as well. - * @param buildOption Build option, see UStringTrieBuildOption. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return A new UCharsTrie for the add()ed data. - * @stable ICU 4.8 - */ - UCharsTrie *build(UStringTrieBuildOption buildOption, UErrorCode &errorCode); - - /** - * Builds a UCharsTrie for the add()ed data and UChar-serializes it. - * Once built, no further data can be add()ed until clear() is called. - * - * A UCharsTrie cannot be empty. At least one (string, value) pair - * must have been add()ed. - * - * Multiple calls to buildUnicodeString() set the UnicodeStrings to the - * builder's same UChar array, without rebuilding. - * If buildUnicodeString() is called after build(), the trie will be - * re-serialized into a new array. - * If build() is called after buildUnicodeString(), the trie object will become - * the owner of the previously returned array. - * After clear() has been called, a new array will be used as well. - * @param buildOption Build option, see UStringTrieBuildOption. - * @param result A UnicodeString which will be set to the UChar-serialized - * UCharsTrie for the add()ed data. - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return result - * @stable ICU 4.8 - */ - UnicodeString &buildUnicodeString(UStringTrieBuildOption buildOption, UnicodeString &result, - UErrorCode &errorCode); - - /** - * Removes all (string, value) pairs. - * New data can then be add()ed and a new trie can be built. - * @return *this - * @stable ICU 4.8 - */ - UCharsTrieBuilder &clear() { - strings.remove(); - elementsLength=0; - ucharsLength=0; - return *this; - } - -private: - UCharsTrieBuilder(const UCharsTrieBuilder &other); // no copy constructor - UCharsTrieBuilder &operator=(const UCharsTrieBuilder &other); // no assignment operator - - void buildUChars(UStringTrieBuildOption buildOption, UErrorCode &errorCode); - - virtual int32_t getElementStringLength(int32_t i) const; - virtual UChar getElementUnit(int32_t i, int32_t unitIndex) const; - virtual int32_t getElementValue(int32_t i) const; - - virtual int32_t getLimitOfLinearMatch(int32_t first, int32_t last, int32_t unitIndex) const; - - virtual int32_t countElementUnits(int32_t start, int32_t limit, int32_t unitIndex) const; - virtual int32_t skipElementsBySomeUnits(int32_t i, int32_t unitIndex, int32_t count) const; - virtual int32_t indexOfElementWithNextUnit(int32_t i, int32_t unitIndex, UChar unit) const; - - virtual UBool matchNodesCanHaveValues() const { return TRUE; } - - virtual int32_t getMaxBranchLinearSubNodeLength() const { return UCharsTrie::kMaxBranchLinearSubNodeLength; } - virtual int32_t getMinLinearMatch() const { return UCharsTrie::kMinLinearMatch; } - virtual int32_t getMaxLinearMatchLength() const { return UCharsTrie::kMaxLinearMatchLength; } - - class UCTLinearMatchNode : public LinearMatchNode { - public: - UCTLinearMatchNode(const UChar *units, int32_t len, Node *nextNode); - virtual UBool operator==(const Node &other) const; - virtual void write(StringTrieBuilder &builder); - private: - const UChar *s; - }; - - virtual Node *createLinearMatchNode(int32_t i, int32_t unitIndex, int32_t length, - Node *nextNode) const; - - UBool ensureCapacity(int32_t length); - virtual int32_t write(int32_t unit); - int32_t write(const UChar *s, int32_t length); - virtual int32_t writeElementUnits(int32_t i, int32_t unitIndex, int32_t length); - virtual int32_t writeValueAndFinal(int32_t i, UBool isFinal); - virtual int32_t writeValueAndType(UBool hasValue, int32_t value, int32_t node); - virtual int32_t writeDeltaTo(int32_t jumpTarget); - - UnicodeString strings; - UCharsTrieElement *elements; - int32_t elementsCapacity; - int32_t elementsLength; - - // UChar serialization of the trie. - // Grows from the back: ucharsLength measures from the end of the buffer! - UChar *uchars; - int32_t ucharsCapacity; - int32_t ucharsLength; -}; - -U_NAMESPACE_END - -#endif // __UCHARSTRIEBUILDER_H__ diff --git a/win32/include/spidermonkey/unicode/uchriter.h b/win32/include/spidermonkey/unicode/uchriter.h deleted file mode 100755 index d87ffb13..00000000 --- a/win32/include/spidermonkey/unicode/uchriter.h +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1998-2005, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -*/ - -#ifndef UCHRITER_H -#define UCHRITER_H - -#include "unicode/utypes.h" -#include "unicode/chariter.h" - -/** - * \file - * \brief C++ API: UChar Character Iterator - */ - -U_NAMESPACE_BEGIN - -/** - * A concrete subclass of CharacterIterator that iterates over the - * characters (code units or code points) in a UChar array. - * It's possible not only to create an - * iterator that iterates over an entire UChar array, but also to - * create one that iterates over only a subrange of a UChar array - * (iterators over different subranges of the same UChar array don't - * compare equal). - * @see CharacterIterator - * @see ForwardCharacterIterator - * @stable ICU 2.0 - */ -class U_COMMON_API UCharCharacterIterator : public CharacterIterator { -public: - /** - * Create an iterator over the UChar array referred to by "textPtr". - * The iteration range is 0 to length-1. - * text is only aliased, not adopted (the - * destructor will not delete it). - * @param textPtr The UChar array to be iterated over - * @param length The length of the UChar array - * @stable ICU 2.0 - */ - UCharCharacterIterator(const UChar* textPtr, int32_t length); - - /** - * Create an iterator over the UChar array referred to by "textPtr". - * The iteration range is 0 to length-1. - * text is only aliased, not adopted (the - * destructor will not delete it). - * The starting - * position is specified by "position". If "position" is outside the valid - * iteration range, the behavior of this object is undefined. - * @param textPtr The UChar array to be iteratd over - * @param length The length of the UChar array - * @param position The starting position of the iteration - * @stable ICU 2.0 - */ - UCharCharacterIterator(const UChar* textPtr, int32_t length, - int32_t position); - - /** - * Create an iterator over the UChar array referred to by "textPtr". - * The iteration range is 0 to end-1. - * text is only aliased, not adopted (the - * destructor will not delete it). - * The starting - * position is specified by "position". If begin and end do not - * form a valid iteration range or "position" is outside the valid - * iteration range, the behavior of this object is undefined. - * @param textPtr The UChar array to be iterated over - * @param length The length of the UChar array - * @param textBegin The begin position of the iteration range - * @param textEnd The end position of the iteration range - * @param position The starting position of the iteration - * @stable ICU 2.0 - */ - UCharCharacterIterator(const UChar* textPtr, int32_t length, - int32_t textBegin, - int32_t textEnd, - int32_t position); - - /** - * Copy constructor. The new iterator iterates over the same range - * of the same string as "that", and its initial position is the - * same as "that"'s current position. - * @param that The UCharCharacterIterator to be copied - * @stable ICU 2.0 - */ - UCharCharacterIterator(const UCharCharacterIterator& that); - - /** - * Destructor. - * @stable ICU 2.0 - */ - virtual ~UCharCharacterIterator(); - - /** - * Assignment operator. *this is altered to iterate over the sane - * range of the same string as "that", and refers to the same - * character within that string as "that" does. - * @param that The object to be copied - * @return the newly created object - * @stable ICU 2.0 - */ - UCharCharacterIterator& - operator=(const UCharCharacterIterator& that); - - /** - * Returns true if the iterators iterate over the same range of the - * same string and are pointing at the same character. - * @param that The ForwardCharacterIterator used to be compared for equality - * @return true if the iterators iterate over the same range of the - * same string and are pointing at the same character. - * @stable ICU 2.0 - */ - virtual UBool operator==(const ForwardCharacterIterator& that) const; - - /** - * Generates a hash code for this iterator. - * @return the hash code. - * @stable ICU 2.0 - */ - virtual int32_t hashCode(void) const; - - /** - * Returns a new UCharCharacterIterator referring to the same - * character in the same range of the same string as this one. The - * caller must delete the new iterator. - * @return the CharacterIterator newly created - * @stable ICU 2.0 - */ - virtual CharacterIterator* clone(void) const; - - /** - * Sets the iterator to refer to the first code unit in its - * iteration range, and returns that code unit. - * This can be used to begin an iteration with next(). - * @return the first code unit in its iteration range. - * @stable ICU 2.0 - */ - virtual UChar first(void); - - /** - * Sets the iterator to refer to the first code unit in its - * iteration range, returns that code unit, and moves the position - * to the second code unit. This is an alternative to setToStart() - * for forward iteration with nextPostInc(). - * @return the first code unit in its iteration range - * @stable ICU 2.0 - */ - virtual UChar firstPostInc(void); - - /** - * Sets the iterator to refer to the first code point in its - * iteration range, and returns that code unit, - * This can be used to begin an iteration with next32(). - * Note that an iteration with next32PostInc(), beginning with, - * e.g., setToStart() or firstPostInc(), is more efficient. - * @return the first code point in its iteration range - * @stable ICU 2.0 - */ - virtual UChar32 first32(void); - - /** - * Sets the iterator to refer to the first code point in its - * iteration range, returns that code point, and moves the position - * to the second code point. This is an alternative to setToStart() - * for forward iteration with next32PostInc(). - * @return the first code point in its iteration range. - * @stable ICU 2.0 - */ - virtual UChar32 first32PostInc(void); - - /** - * Sets the iterator to refer to the last code unit in its - * iteration range, and returns that code unit. - * This can be used to begin an iteration with previous(). - * @return the last code unit in its iteration range. - * @stable ICU 2.0 - */ - virtual UChar last(void); - - /** - * Sets the iterator to refer to the last code point in its - * iteration range, and returns that code unit. - * This can be used to begin an iteration with previous32(). - * @return the last code point in its iteration range. - * @stable ICU 2.0 - */ - virtual UChar32 last32(void); - - /** - * Sets the iterator to refer to the "position"-th code unit - * in the text-storage object the iterator refers to, and - * returns that code unit. - * @param position the position within the text-storage object - * @return the code unit - * @stable ICU 2.0 - */ - virtual UChar setIndex(int32_t position); - - /** - * Sets the iterator to refer to the beginning of the code point - * that contains the "position"-th code unit - * in the text-storage object the iterator refers to, and - * returns that code point. - * The current position is adjusted to the beginning of the code point - * (its first code unit). - * @param position the position within the text-storage object - * @return the code unit - * @stable ICU 2.0 - */ - virtual UChar32 setIndex32(int32_t position); - - /** - * Returns the code unit the iterator currently refers to. - * @return the code unit the iterator currently refers to. - * @stable ICU 2.0 - */ - virtual UChar current(void) const; - - /** - * Returns the code point the iterator currently refers to. - * @return the code point the iterator currently refers to. - * @stable ICU 2.0 - */ - virtual UChar32 current32(void) const; - - /** - * Advances to the next code unit in the iteration range (toward - * endIndex()), and returns that code unit. If there are no more - * code units to return, returns DONE. - * @return the next code unit in the iteration range. - * @stable ICU 2.0 - */ - virtual UChar next(void); - - /** - * Gets the current code unit for returning and advances to the next code unit - * in the iteration range - * (toward endIndex()). If there are - * no more code units to return, returns DONE. - * @return the current code unit. - * @stable ICU 2.0 - */ - virtual UChar nextPostInc(void); - - /** - * Advances to the next code point in the iteration range (toward - * endIndex()), and returns that code point. If there are no more - * code points to return, returns DONE. - * Note that iteration with "pre-increment" semantics is less - * efficient than iteration with "post-increment" semantics - * that is provided by next32PostInc(). - * @return the next code point in the iteration range. - * @stable ICU 2.0 - */ - virtual UChar32 next32(void); - - /** - * Gets the current code point for returning and advances to the next code point - * in the iteration range - * (toward endIndex()). If there are - * no more code points to return, returns DONE. - * @return the current point. - * @stable ICU 2.0 - */ - virtual UChar32 next32PostInc(void); - - /** - * Returns FALSE if there are no more code units or code points - * at or after the current position in the iteration range. - * This is used with nextPostInc() or next32PostInc() in forward - * iteration. - * @return FALSE if there are no more code units or code points - * at or after the current position in the iteration range. - * @stable ICU 2.0 - */ - virtual UBool hasNext(); - - /** - * Advances to the previous code unit in the iteration range (toward - * startIndex()), and returns that code unit. If there are no more - * code units to return, returns DONE. - * @return the previous code unit in the iteration range. - * @stable ICU 2.0 - */ - virtual UChar previous(void); - - /** - * Advances to the previous code point in the iteration range (toward - * startIndex()), and returns that code point. If there are no more - * code points to return, returns DONE. - * @return the previous code point in the iteration range. - * @stable ICU 2.0 - */ - virtual UChar32 previous32(void); - - /** - * Returns FALSE if there are no more code units or code points - * before the current position in the iteration range. - * This is used with previous() or previous32() in backward - * iteration. - * @return FALSE if there are no more code units or code points - * before the current position in the iteration range. - * @stable ICU 2.0 - */ - virtual UBool hasPrevious(); - - /** - * Moves the current position relative to the start or end of the - * iteration range, or relative to the current position itself. - * The movement is expressed in numbers of code units forward - * or backward by specifying a positive or negative delta. - * @param delta the position relative to origin. A positive delta means forward; - * a negative delta means backward. - * @param origin Origin enumeration {kStart, kCurrent, kEnd} - * @return the new position - * @stable ICU 2.0 - */ - virtual int32_t move(int32_t delta, EOrigin origin); - - /** - * Moves the current position relative to the start or end of the - * iteration range, or relative to the current position itself. - * The movement is expressed in numbers of code points forward - * or backward by specifying a positive or negative delta. - * @param delta the position relative to origin. A positive delta means forward; - * a negative delta means backward. - * @param origin Origin enumeration {kStart, kCurrent, kEnd} - * @return the new position - * @stable ICU 2.0 - */ - virtual int32_t move32(int32_t delta, EOrigin origin); - - /** - * Sets the iterator to iterate over a new range of text - * @stable ICU 2.0 - */ - void setText(const UChar* newText, int32_t newTextLength); - - /** - * Copies the UChar array under iteration into the UnicodeString - * referred to by "result". Even if this iterator iterates across - * only a part of this string, the whole string is copied. - * @param result Receives a copy of the text under iteration. - * @stable ICU 2.0 - */ - virtual void getText(UnicodeString& result); - - /** - * Return a class ID for this class (not really public) - * @return a class ID for this class - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Return a class ID for this object (not really public) - * @return a class ID for this object. - * @stable ICU 2.0 - */ - virtual UClassID getDynamicClassID(void) const; - -protected: - /** - * Protected constructor - * @stable ICU 2.0 - */ - UCharCharacterIterator(); - /** - * Protected member text - * @stable ICU 2.0 - */ - const UChar* text; - -}; - -U_NAMESPACE_END -#endif diff --git a/win32/include/spidermonkey/unicode/uclean.h b/win32/include/spidermonkey/unicode/uclean.h deleted file mode 100755 index d7801d69..00000000 --- a/win32/include/spidermonkey/unicode/uclean.h +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* Copyright (C) 2001-2014, International Business Machines -* Corporation and others. All Rights Reserved. -****************************************************************************** -* file name: uclean.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2001July05 -* created by: George Rhoten -*/ - -#ifndef __UCLEAN_H__ -#define __UCLEAN_H__ - -#include "unicode/utypes.h" -/** - * \file - * \brief C API: Initialize and clean up ICU - */ - -/** - * Initialize ICU. - * - * Use of this function is optional. It is OK to simply use ICU - * services and functions without first having initialized - * ICU by calling u_init(). - * - * u_init() will attempt to load some part of ICU's data, and is - * useful as a test for configuration or installation problems that - * leave the ICU data inaccessible. A successful invocation of u_init() - * does not, however, guarantee that all ICU data is accessible. - * - * Multiple calls to u_init() cause no harm, aside from the small amount - * of time required. - * - * In old versions of ICU, u_init() was required in multi-threaded applications - * to ensure the thread safety of ICU. u_init() is no longer needed for this purpose. - * - * @param status An ICU UErrorCode parameter. It must not be NULL. - * An Error will be returned if some required part of ICU data can not - * be loaded or initialized. - * The function returns immediately if the input error code indicates a - * failure, as usual. - * - * @stable ICU 2.6 - */ -U_STABLE void U_EXPORT2 -u_init(UErrorCode *status); - -#ifndef U_HIDE_SYSTEM_API -/** - * Clean up the system resources, such as allocated memory or open files, - * used in all ICU libraries. This will free/delete all memory owned by the - * ICU libraries, and return them to their original load state. All open ICU - * items (collators, resource bundles, converters, etc.) must be closed before - * calling this function, otherwise ICU may not free its allocated memory - * (e.g. close your converters and resource bundles before calling this - * function). Generally, this function should be called once just before - * an application exits. For applications that dynamically load and unload - * the ICU libraries (relatively uncommon), u_cleanup() should be called - * just before the library unload. - *

- * u_cleanup() also clears any ICU heap functions, mutex functions or - * trace functions that may have been set for the process. - * This has the effect of restoring ICU to its initial condition, before - * any of these override functions were installed. Refer to - * u_setMemoryFunctions(), u_setMutexFunctions and - * utrace_setFunctions(). If ICU is to be reinitialized after after - * calling u_cleanup(), these runtime override functions will need to - * be set up again if they are still required. - *

- * u_cleanup() is not thread safe. All other threads should stop using ICU - * before calling this function. - *

- * Any open ICU items will be left in an undefined state by u_cleanup(), - * and any subsequent attempt to use such an item will give unpredictable - * results. - *

- * After calling u_cleanup(), an application may continue to use ICU by - * calling u_init(). An application must invoke u_init() first from one single - * thread before allowing other threads call u_init(). All threads existing - * at the time of the first thread's call to u_init() must also call - * u_init() themselves before continuing with other ICU operations. - *

- * The use of u_cleanup() just before an application terminates is optional, - * but it should be called only once for performance reasons. The primary - * benefit is to eliminate reports of memory or resource leaks originating - * in ICU code from the results generated by heap analysis tools. - *

- * Use this function with great care! - *

- * - * @stable ICU 2.0 - * @system - */ -U_STABLE void U_EXPORT2 -u_cleanup(void); - - -/** - * Pointer type for a user supplied memory allocation function. - * @param context user supplied value, obtained from from u_setMemoryFunctions(). - * @param size The number of bytes to be allocated - * @return Pointer to the newly allocated memory, or NULL if the allocation failed. - * @stable ICU 2.8 - * @system - */ -typedef void *U_CALLCONV UMemAllocFn(const void *context, size_t size); -/** - * Pointer type for a user supplied memory re-allocation function. - * @param context user supplied value, obtained from from u_setMemoryFunctions(). - * @param size The number of bytes to be allocated - * @return Pointer to the newly allocated memory, or NULL if the allocation failed. - * @stable ICU 2.8 - * @system - */ -typedef void *U_CALLCONV UMemReallocFn(const void *context, void *mem, size_t size); -/** - * Pointer type for a user supplied memory free function. Behavior should be - * similar the standard C library free(). - * @param context user supplied value, obtained from from u_setMemoryFunctions(). - * @param mem Pointer to the memory block to be resized - * @param size The new size for the block - * @return Pointer to the resized memory block, or NULL if the resizing failed. - * @stable ICU 2.8 - * @system - */ -typedef void U_CALLCONV UMemFreeFn (const void *context, void *mem); - -/** - * Set the functions that ICU will use for memory allocation. - * Use of this function is optional; by default (without this function), ICU will - * use the standard C library malloc() and free() functions. - * This function can only be used when ICU is in an initial, unused state, before - * u_init() has been called. - * @param context This pointer value will be saved, and then (later) passed as - * a parameter to the memory functions each time they - * are called. - * @param a Pointer to a user-supplied malloc function. - * @param r Pointer to a user-supplied realloc function. - * @param f Pointer to a user-supplied free function. - * @param status Receives error values. - * @stable ICU 2.8 - * @system - */ -U_STABLE void U_EXPORT2 -u_setMemoryFunctions(const void *context, UMemAllocFn *a, UMemReallocFn *r, UMemFreeFn *f, - UErrorCode *status); - - -#ifndef U_HIDE_DEPRECATED_API -/********************************************************************************* - * - * Deprecated Functions - * - * The following functions for user supplied mutexes are no longer supported. - * Any attempt to use them will return a U_UNSUPPORTED_ERROR. - * - **********************************************************************************/ - -/** - * An opaque pointer type that represents an ICU mutex. - * For user-implemented mutexes, the value will typically point to a - * struct or object that implements the mutex. - * @deprecated ICU 52. This type is no longer supported. - * @system - */ -typedef void *UMTX; - -/** - * Function Pointer type for a user supplied mutex initialization function. - * The user-supplied function will be called by ICU whenever ICU needs to create a - * new mutex. The function implementation should create a mutex, and store a pointer - * to something that uniquely identifies the mutex into the UMTX that is supplied - * as a paramter. - * @param context user supplied value, obtained from from u_setMutexFunctions(). - * @param mutex Receives a pointer that identifies the new mutex. - * The mutex init function must set the UMTX to a non-null value. - * Subsequent calls by ICU to lock, unlock, or destroy a mutex will - * identify the mutex by the UMTX value. - * @param status Error status. Report errors back to ICU by setting this variable - * with an error code. - * @deprecated ICU 52. This function is no longer supported. - * @system - */ -typedef void U_CALLCONV UMtxInitFn (const void *context, UMTX *mutex, UErrorCode* status); - - -/** - * Function Pointer type for a user supplied mutex functions. - * One of the user-supplied functions with this signature will be called by ICU - * whenever ICU needs to lock, unlock, or destroy a mutex. - * @param context user supplied value, obtained from from u_setMutexFunctions(). - * @param mutex specify the mutex on which to operate. - * @deprecated ICU 52. This function is no longer supported. - * @system - */ -typedef void U_CALLCONV UMtxFn (const void *context, UMTX *mutex); - - -/** - * Set the functions that ICU will use for mutex operations - * Use of this function is optional; by default (without this function), ICU will - * directly access system functions for mutex operations - * This function can only be used when ICU is in an initial, unused state, before - * u_init() has been called. - * @param context This pointer value will be saved, and then (later) passed as - * a parameter to the user-supplied mutex functions each time they - * are called. - * @param init Pointer to a mutex initialization function. Must be non-null. - * @param destroy Pointer to the mutex destroy function. Must be non-null. - * @param lock pointer to the mutex lock function. Must be non-null. - * @param unlock Pointer to the mutex unlock function. Must be non-null. - * @param status Receives error values. - * @deprecated ICU 52. This function is no longer supported. - * @system - */ -U_DEPRECATED void U_EXPORT2 -u_setMutexFunctions(const void *context, UMtxInitFn *init, UMtxFn *destroy, UMtxFn *lock, UMtxFn *unlock, - UErrorCode *status); - - -/** - * Pointer type for a user supplied atomic increment or decrement function. - * @param context user supplied value, obtained from from u_setAtomicIncDecFunctions(). - * @param p Pointer to a 32 bit int to be incremented or decremented - * @return The value of the variable after the inc or dec operation. - * @deprecated ICU 52. This function is no longer supported. - * @system - */ -typedef int32_t U_CALLCONV UMtxAtomicFn(const void *context, int32_t *p); - -/** - * Set the functions that ICU will use for atomic increment and decrement of int32_t values. - * Use of this function is optional; by default (without this function), ICU will - * use its own internal implementation of atomic increment/decrement. - * This function can only be used when ICU is in an initial, unused state, before - * u_init() has been called. - * @param context This pointer value will be saved, and then (later) passed as - * a parameter to the increment and decrement functions each time they - * are called. This function can only be called - * @param inc Pointer to a function to do an atomic increment operation. Must be non-null. - * @param dec Pointer to a function to do an atomic decrement operation. Must be non-null. - * @param status Receives error values. - * @deprecated ICU 52. This function is no longer supported. - * @system - */ -U_DEPRECATED void U_EXPORT2 -u_setAtomicIncDecFunctions(const void *context, UMtxAtomicFn *inc, UMtxAtomicFn *dec, - UErrorCode *status); - -#endif /* U_HIDE_DEPRECATED_API */ -#endif /* U_HIDE_SYSTEM_API */ - -#endif diff --git a/win32/include/spidermonkey/unicode/ucnv.h b/win32/include/spidermonkey/unicode/ucnv.h deleted file mode 100755 index 767c1a2a..00000000 --- a/win32/include/spidermonkey/unicode/ucnv.h +++ /dev/null @@ -1,2043 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1999-2014, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** - * ucnv.h: - * External APIs for the ICU's codeset conversion library - * Bertrand A. Damiba - * - * Modification History: - * - * Date Name Description - * 04/04/99 helena Fixed internal header inclusion. - * 05/11/00 helena Added setFallback and usesFallback APIs. - * 06/29/2000 helena Major rewrite of the callback APIs. - * 12/07/2000 srl Update of documentation - */ - -/** - * \file - * \brief C API: Character conversion - * - *

Character Conversion C API

- * - *

This API is used to convert codepage or character encoded data to and - * from UTF-16. You can open a converter with {@link ucnv_open() }. With that - * converter, you can get its properties, set options, convert your data and - * close the converter.

- * - *

Since many software programs recogize different converter names for - * different types of converters, there are other functions in this API to - * iterate over the converter aliases. The functions {@link ucnv_getAvailableName() }, - * {@link ucnv_getAlias() } and {@link ucnv_getStandardName() } are some of the - * more frequently used alias functions to get this information.

- * - *

When a converter encounters an illegal, irregular, invalid or unmappable character - * its default behavior is to use a substitution character to replace the - * bad byte sequence. This behavior can be changed by using {@link ucnv_setFromUCallBack() } - * or {@link ucnv_setToUCallBack() } on the converter. The header ucnv_err.h defines - * many other callback actions that can be used instead of a character substitution.

- * - *

More information about this API can be found in our - * User's - * Guide.

- */ - -#ifndef UCNV_H -#define UCNV_H - -#include "unicode/ucnv_err.h" -#include "unicode/uenum.h" -#include "unicode/localpointer.h" - -#ifndef __USET_H__ - -/** - * USet is the C API type for Unicode sets. - * It is forward-declared here to avoid including the header file if related - * conversion APIs are not used. - * See unicode/uset.h - * - * @see ucnv_getUnicodeSet - * @stable ICU 2.6 - */ -struct USet; -/** @stable ICU 2.6 */ -typedef struct USet USet; - -#endif - -#if !UCONFIG_NO_CONVERSION - -U_CDECL_BEGIN - -/** Maximum length of a converter name including the terminating NULL @stable ICU 2.0 */ -#define UCNV_MAX_CONVERTER_NAME_LENGTH 60 -/** Maximum length of a converter name including path and terminating NULL @stable ICU 2.0 */ -#define UCNV_MAX_FULL_FILE_NAME_LENGTH (600+UCNV_MAX_CONVERTER_NAME_LENGTH) - -/** Shift in for EBDCDIC_STATEFUL and iso2022 states @stable ICU 2.0 */ -#define UCNV_SI 0x0F -/** Shift out for EBDCDIC_STATEFUL and iso2022 states @stable ICU 2.0 */ -#define UCNV_SO 0x0E - -/** - * Enum for specifying basic types of converters - * @see ucnv_getType - * @stable ICU 2.0 - */ -typedef enum { - /** @stable ICU 2.0 */ - UCNV_UNSUPPORTED_CONVERTER = -1, - /** @stable ICU 2.0 */ - UCNV_SBCS = 0, - /** @stable ICU 2.0 */ - UCNV_DBCS = 1, - /** @stable ICU 2.0 */ - UCNV_MBCS = 2, - /** @stable ICU 2.0 */ - UCNV_LATIN_1 = 3, - /** @stable ICU 2.0 */ - UCNV_UTF8 = 4, - /** @stable ICU 2.0 */ - UCNV_UTF16_BigEndian = 5, - /** @stable ICU 2.0 */ - UCNV_UTF16_LittleEndian = 6, - /** @stable ICU 2.0 */ - UCNV_UTF32_BigEndian = 7, - /** @stable ICU 2.0 */ - UCNV_UTF32_LittleEndian = 8, - /** @stable ICU 2.0 */ - UCNV_EBCDIC_STATEFUL = 9, - /** @stable ICU 2.0 */ - UCNV_ISO_2022 = 10, - - /** @stable ICU 2.0 */ - UCNV_LMBCS_1 = 11, - /** @stable ICU 2.0 */ - UCNV_LMBCS_2, - /** @stable ICU 2.0 */ - UCNV_LMBCS_3, - /** @stable ICU 2.0 */ - UCNV_LMBCS_4, - /** @stable ICU 2.0 */ - UCNV_LMBCS_5, - /** @stable ICU 2.0 */ - UCNV_LMBCS_6, - /** @stable ICU 2.0 */ - UCNV_LMBCS_8, - /** @stable ICU 2.0 */ - UCNV_LMBCS_11, - /** @stable ICU 2.0 */ - UCNV_LMBCS_16, - /** @stable ICU 2.0 */ - UCNV_LMBCS_17, - /** @stable ICU 2.0 */ - UCNV_LMBCS_18, - /** @stable ICU 2.0 */ - UCNV_LMBCS_19, - /** @stable ICU 2.0 */ - UCNV_LMBCS_LAST = UCNV_LMBCS_19, - /** @stable ICU 2.0 */ - UCNV_HZ, - /** @stable ICU 2.0 */ - UCNV_SCSU, - /** @stable ICU 2.0 */ - UCNV_ISCII, - /** @stable ICU 2.0 */ - UCNV_US_ASCII, - /** @stable ICU 2.0 */ - UCNV_UTF7, - /** @stable ICU 2.2 */ - UCNV_BOCU1, - /** @stable ICU 2.2 */ - UCNV_UTF16, - /** @stable ICU 2.2 */ - UCNV_UTF32, - /** @stable ICU 2.2 */ - UCNV_CESU8, - /** @stable ICU 2.4 */ - UCNV_IMAP_MAILBOX, - /** @stable ICU 4.8 */ - UCNV_COMPOUND_TEXT, - - /* Number of converter types for which we have conversion routines. */ - UCNV_NUMBER_OF_SUPPORTED_CONVERTER_TYPES -} UConverterType; - -/** - * Enum for specifying which platform a converter ID refers to. - * The use of platform/CCSID is not recommended. See ucnv_openCCSID(). - * - * @see ucnv_getPlatform - * @see ucnv_openCCSID - * @see ucnv_getCCSID - * @stable ICU 2.0 - */ -typedef enum { - UCNV_UNKNOWN = -1, - UCNV_IBM = 0 -} UConverterPlatform; - -/** - * Function pointer for error callback in the codepage to unicode direction. - * Called when an error has occured in conversion to unicode, or on open/close of the callback (see reason). - * @param context Pointer to the callback's private data - * @param args Information about the conversion in progress - * @param codeUnits Points to 'length' bytes of the concerned codepage sequence - * @param length Size (in bytes) of the concerned codepage sequence - * @param reason Defines the reason the callback was invoked - * @param pErrorCode ICU error code in/out parameter. - * For converter callback functions, set to a conversion error - * before the call, and the callback may reset it to U_ZERO_ERROR. - * @see ucnv_setToUCallBack - * @see UConverterToUnicodeArgs - * @stable ICU 2.0 - */ -typedef void (U_EXPORT2 *UConverterToUCallback) ( - const void* context, - UConverterToUnicodeArgs *args, - const char *codeUnits, - int32_t length, - UConverterCallbackReason reason, - UErrorCode *pErrorCode); - -/** - * Function pointer for error callback in the unicode to codepage direction. - * Called when an error has occured in conversion from unicode, or on open/close of the callback (see reason). - * @param context Pointer to the callback's private data - * @param args Information about the conversion in progress - * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence - * @param length Size (in bytes) of the concerned codepage sequence - * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint. - * @param reason Defines the reason the callback was invoked - * @param pErrorCode ICU error code in/out parameter. - * For converter callback functions, set to a conversion error - * before the call, and the callback may reset it to U_ZERO_ERROR. - * @see ucnv_setFromUCallBack - * @stable ICU 2.0 - */ -typedef void (U_EXPORT2 *UConverterFromUCallback) ( - const void* context, - UConverterFromUnicodeArgs *args, - const UChar* codeUnits, - int32_t length, - UChar32 codePoint, - UConverterCallbackReason reason, - UErrorCode *pErrorCode); - -U_CDECL_END - -/** - * Character that separates converter names from options and options from each other. - * @see ucnv_open - * @stable ICU 2.0 - */ -#define UCNV_OPTION_SEP_CHAR ',' - -/** - * String version of UCNV_OPTION_SEP_CHAR. - * @see ucnv_open - * @stable ICU 2.0 - */ -#define UCNV_OPTION_SEP_STRING "," - -/** - * Character that separates a converter option from its value. - * @see ucnv_open - * @stable ICU 2.0 - */ -#define UCNV_VALUE_SEP_CHAR '=' - -/** - * String version of UCNV_VALUE_SEP_CHAR. - * @see ucnv_open - * @stable ICU 2.0 - */ -#define UCNV_VALUE_SEP_STRING "=" - -/** - * Converter option for specifying a locale. - * For example, ucnv_open("SCSU,locale=ja", &errorCode); - * See convrtrs.txt. - * - * @see ucnv_open - * @stable ICU 2.0 - */ -#define UCNV_LOCALE_OPTION_STRING ",locale=" - -/** - * Converter option for specifying a version selector (0..9) for some converters. - * For example, - * \code - * ucnv_open("UTF-7,version=1", &errorCode); - * \endcode - * See convrtrs.txt. - * - * @see ucnv_open - * @stable ICU 2.4 - */ -#define UCNV_VERSION_OPTION_STRING ",version=" - -/** - * Converter option for EBCDIC SBCS or mixed-SBCS/DBCS (stateful) codepages. - * Swaps Unicode mappings for EBCDIC LF and NL codes, as used on - * S/390 (z/OS) Unix System Services (Open Edition). - * For example, ucnv_open("ibm-1047,swaplfnl", &errorCode); - * See convrtrs.txt. - * - * @see ucnv_open - * @stable ICU 2.4 - */ -#define UCNV_SWAP_LFNL_OPTION_STRING ",swaplfnl" - -/** - * Do a fuzzy compare of two converter/alias names. - * The comparison is case-insensitive, ignores leading zeroes if they are not - * followed by further digits, and ignores all but letters and digits. - * Thus the strings "UTF-8", "utf_8", "u*T@f08" and "Utf 8" are exactly equivalent. - * See section 1.4, Charset Alias Matching in Unicode Technical Standard #22 - * at http://www.unicode.org/reports/tr22/ - * - * @param name1 a converter name or alias, zero-terminated - * @param name2 a converter name or alias, zero-terminated - * @return 0 if the names match, or a negative value if the name1 - * lexically precedes name2, or a positive value if the name1 - * lexically follows name2. - * @stable ICU 2.0 - */ -U_STABLE int U_EXPORT2 -ucnv_compareNames(const char *name1, const char *name2); - - -/** - * Creates a UConverter object with the name of a coded character set specified as a C string. - * The actual name will be resolved with the alias file - * using a case-insensitive string comparison that ignores - * leading zeroes and all non-alphanumeric characters. - * E.g., the names "UTF8", "utf-8", "u*T@f08" and "Utf 8" are all equivalent. - * (See also ucnv_compareNames().) - * If NULL is passed for the converter name, it will create one with the - * getDefaultName return value. - * - *

A converter name for ICU 1.5 and above may contain options - * like a locale specification to control the specific behavior of - * the newly instantiated converter. - * The meaning of the options depends on the particular converter. - * If an option is not defined for or recognized by a given converter, then it is ignored.

- * - *

Options are appended to the converter name string, with a - * UCNV_OPTION_SEP_CHAR between the name and the first option and - * also between adjacent options.

- * - *

If the alias is ambiguous, then the preferred converter is used - * and the status is set to U_AMBIGUOUS_ALIAS_WARNING.

- * - *

The conversion behavior and names can vary between platforms. ICU may - * convert some characters differently from other platforms. Details on this topic - * are in the User's - * Guide. Aliases starting with a "cp" prefix have no specific meaning - * other than its an alias starting with the letters "cp". Please do not - * associate any meaning to these aliases.

- * - * \snippet samples/ucnv/convsamp.cpp ucnv_open - * - * @param converterName Name of the coded character set table. - * This may have options appended to the string. - * IANA alias character set names, IBM CCSIDs starting with "ibm-", - * Windows codepage numbers starting with "windows-" are frequently - * used for this parameter. See ucnv_getAvailableName and - * ucnv_getAlias for a complete list that is available. - * If this parameter is NULL, the default converter will be used. - * @param err outgoing error status U_MEMORY_ALLOCATION_ERROR, U_FILE_ACCESS_ERROR - * @return the created Unicode converter object, or NULL if an error occured - * @see ucnv_openU - * @see ucnv_openCCSID - * @see ucnv_getAvailableName - * @see ucnv_getAlias - * @see ucnv_getDefaultName - * @see ucnv_close - * @see ucnv_compareNames - * @stable ICU 2.0 - */ -U_STABLE UConverter* U_EXPORT2 -ucnv_open(const char *converterName, UErrorCode *err); - - -/** - * Creates a Unicode converter with the names specified as unicode string. - * The name should be limited to the ASCII-7 alphanumerics range. - * The actual name will be resolved with the alias file - * using a case-insensitive string comparison that ignores - * leading zeroes and all non-alphanumeric characters. - * E.g., the names "UTF8", "utf-8", "u*T@f08" and "Utf 8" are all equivalent. - * (See also ucnv_compareNames().) - * If NULL is passed for the converter name, it will create - * one with the ucnv_getDefaultName() return value. - * If the alias is ambiguous, then the preferred converter is used - * and the status is set to U_AMBIGUOUS_ALIAS_WARNING. - * - *

See ucnv_open for the complete details

- * @param name Name of the UConverter table in a zero terminated - * Unicode string - * @param err outgoing error status U_MEMORY_ALLOCATION_ERROR, - * U_FILE_ACCESS_ERROR - * @return the created Unicode converter object, or NULL if an - * error occured - * @see ucnv_open - * @see ucnv_openCCSID - * @see ucnv_close - * @see ucnv_compareNames - * @stable ICU 2.0 - */ -U_STABLE UConverter* U_EXPORT2 -ucnv_openU(const UChar *name, - UErrorCode *err); - -/** - * Creates a UConverter object from a CCSID number and platform pair. - * Note that the usefulness of this function is limited to platforms with numeric - * encoding IDs. Only IBM and Microsoft platforms use numeric (16-bit) identifiers for - * encodings. - * - * In addition, IBM CCSIDs and Unicode conversion tables are not 1:1 related. - * For many IBM CCSIDs there are multiple (up to six) Unicode conversion tables, and - * for some Unicode conversion tables there are multiple CCSIDs. - * Some "alternate" Unicode conversion tables are provided by the - * IBM CDRA conversion table registry. - * The most prominent example of a systematic modification of conversion tables that is - * not provided in the form of conversion table files in the repository is - * that S/390 Unix System Services swaps the codes for Line Feed and New Line in all - * EBCDIC codepages, which requires such a swap in the Unicode conversion tables as well. - * - * Only IBM default conversion tables are accessible with ucnv_openCCSID(). - * ucnv_getCCSID() will return the same CCSID for all conversion tables that are associated - * with that CCSID. - * - * Currently, the only "platform" supported in the ICU converter API is UCNV_IBM. - * - * In summary, the use of CCSIDs and the associated API functions is not recommended. - * - * In order to open a converter with the default IBM CDRA Unicode conversion table, - * you can use this function or use the prefix "ibm-": - * \code - * char name[20]; - * sprintf(name, "ibm-%hu", ccsid); - * cnv=ucnv_open(name, &errorCode); - * \endcode - * - * In order to open a converter with the IBM S/390 Unix System Services variant - * of a Unicode/EBCDIC conversion table, - * you can use the prefix "ibm-" together with the option string UCNV_SWAP_LFNL_OPTION_STRING: - * \code - * char name[20]; - * sprintf(name, "ibm-%hu" UCNV_SWAP_LFNL_OPTION_STRING, ccsid); - * cnv=ucnv_open(name, &errorCode); - * \endcode - * - * In order to open a converter from a Microsoft codepage number, use the prefix "cp": - * \code - * char name[20]; - * sprintf(name, "cp%hu", codepageID); - * cnv=ucnv_open(name, &errorCode); - * \endcode - * - * If the alias is ambiguous, then the preferred converter is used - * and the status is set to U_AMBIGUOUS_ALIAS_WARNING. - * - * @param codepage codepage number to create - * @param platform the platform in which the codepage number exists - * @param err error status U_MEMORY_ALLOCATION_ERROR, U_FILE_ACCESS_ERROR - * @return the created Unicode converter object, or NULL if an error - * occured. - * @see ucnv_open - * @see ucnv_openU - * @see ucnv_close - * @see ucnv_getCCSID - * @see ucnv_getPlatform - * @see UConverterPlatform - * @stable ICU 2.0 - */ -U_STABLE UConverter* U_EXPORT2 -ucnv_openCCSID(int32_t codepage, - UConverterPlatform platform, - UErrorCode * err); - -/** - *

Creates a UConverter object specified from a packageName and a converterName.

- * - *

The packageName and converterName must point to an ICU udata object, as defined by - * udata_open( packageName, "cnv", converterName, err) or equivalent. - * Typically, packageName will refer to a (.dat) file, or to a package registered with - * udata_setAppData(). Using a full file or directory pathname for packageName is deprecated.

- * - *

The name will NOT be looked up in the alias mechanism, nor will the converter be - * stored in the converter cache or the alias table. The only way to open further converters - * is call this function multiple times, or use the ucnv_safeClone() function to clone a - * 'master' converter.

- * - *

A future version of ICU may add alias table lookups and/or caching - * to this function.

- * - *

Example Use: - * cnv = ucnv_openPackage("myapp", "myconverter", &err); - *

- * - * @param packageName name of the package (equivalent to 'path' in udata_open() call) - * @param converterName name of the data item to be used, without suffix. - * @param err outgoing error status U_MEMORY_ALLOCATION_ERROR, U_FILE_ACCESS_ERROR - * @return the created Unicode converter object, or NULL if an error occured - * @see udata_open - * @see ucnv_open - * @see ucnv_safeClone - * @see ucnv_close - * @stable ICU 2.2 - */ -U_STABLE UConverter* U_EXPORT2 -ucnv_openPackage(const char *packageName, const char *converterName, UErrorCode *err); - -/** - * Thread safe converter cloning operation. - * For most efficient operation, pass in a stackBuffer (and a *pBufferSize) - * with at least U_CNV_SAFECLONE_BUFFERSIZE bytes of space. - * If the buffer size is sufficient, then the clone will use the stack buffer; - * otherwise, it will be allocated, and *pBufferSize will indicate - * the actual size. (This should not occur with U_CNV_SAFECLONE_BUFFERSIZE.) - * - * You must ucnv_close() the clone in any case. - * - * If *pBufferSize==0, (regardless of whether stackBuffer==NULL or not) - * then *pBufferSize will be changed to a sufficient size - * for cloning this converter, - * without actually cloning the converter ("pure pre-flighting"). - * - * If *pBufferSize is greater than zero but not large enough for a stack-based - * clone, then the converter is cloned using newly allocated memory - * and *pBufferSize is changed to the necessary size. - * - * If the converter clone fits into the stack buffer but the stack buffer is not - * sufficiently aligned for the clone, then the clone will use an - * adjusted pointer and use an accordingly smaller buffer size. - * - * @param cnv converter to be cloned - * @param stackBuffer Deprecated functionality as of ICU 52, use NULL.
- * user allocated space for the new clone. If NULL new memory will be allocated. - * If buffer is not large enough, new memory will be allocated. - * Clients can use the U_CNV_SAFECLONE_BUFFERSIZE. This will probably be enough to avoid memory allocations. - * @param pBufferSize Deprecated functionality as of ICU 52, use NULL or 1.
- * pointer to size of allocated space. - * @param status to indicate whether the operation went on smoothly or there were errors - * An informational status value, U_SAFECLONE_ALLOCATED_WARNING, - * is used if any allocations were necessary. - * However, it is better to check if *pBufferSize grew for checking for - * allocations because warning codes can be overridden by subsequent - * function calls. - * @return pointer to the new clone - * @stable ICU 2.0 - */ -U_STABLE UConverter * U_EXPORT2 -ucnv_safeClone(const UConverter *cnv, - void *stackBuffer, - int32_t *pBufferSize, - UErrorCode *status); - -#ifndef U_HIDE_DEPRECATED_API - -/** - * \def U_CNV_SAFECLONE_BUFFERSIZE - * Definition of a buffer size that is designed to be large enough for - * converters to be cloned with ucnv_safeClone(). - * @deprecated ICU 52. Do not rely on ucnv_safeClone() cloning into any provided buffer. - */ -#define U_CNV_SAFECLONE_BUFFERSIZE 1024 - -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * Deletes the unicode converter and releases resources associated - * with just this instance. - * Does not free up shared converter tables. - * - * @param converter the converter object to be deleted - * @see ucnv_open - * @see ucnv_openU - * @see ucnv_openCCSID - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_close(UConverter * converter); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUConverterPointer - * "Smart pointer" class, closes a UConverter via ucnv_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUConverterPointer, UConverter, ucnv_close); - -U_NAMESPACE_END - -#endif - -/** - * Fills in the output parameter, subChars, with the substitution characters - * as multiple bytes. - * If ucnv_setSubstString() set a Unicode string because the converter is - * stateful, then subChars will be an empty string. - * - * @param converter the Unicode converter - * @param subChars the subsitution characters - * @param len on input the capacity of subChars, on output the number - * of bytes copied to it - * @param err the outgoing error status code. - * If the substitution character array is too small, an - * U_INDEX_OUTOFBOUNDS_ERROR will be returned. - * @see ucnv_setSubstString - * @see ucnv_setSubstChars - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_getSubstChars(const UConverter *converter, - char *subChars, - int8_t *len, - UErrorCode *err); - -/** - * Sets the substitution chars when converting from unicode to a codepage. The - * substitution is specified as a string of 1-4 bytes, and may contain - * NULL bytes. - * The subChars must represent a single character. The caller needs to know the - * byte sequence of a valid character in the converter's charset. - * For some converters, for example some ISO 2022 variants, only single-byte - * substitution characters may be supported. - * The newer ucnv_setSubstString() function relaxes these limitations. - * - * @param converter the Unicode converter - * @param subChars the substitution character byte sequence we want set - * @param len the number of bytes in subChars - * @param err the error status code. U_INDEX_OUTOFBOUNDS_ERROR if - * len is bigger than the maximum number of bytes allowed in subchars - * @see ucnv_setSubstString - * @see ucnv_getSubstChars - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_setSubstChars(UConverter *converter, - const char *subChars, - int8_t len, - UErrorCode *err); - -/** - * Set a substitution string for converting from Unicode to a charset. - * The caller need not know the charset byte sequence for each charset. - * - * Unlike ucnv_setSubstChars() which is designed to set a charset byte sequence - * for a single character, this function takes a Unicode string with - * zero, one or more characters, and immediately verifies that the string can be - * converted to the charset. - * If not, or if the result is too long (more than 32 bytes as of ICU 3.6), - * then the function returns with an error accordingly. - * - * Also unlike ucnv_setSubstChars(), this function works for stateful charsets - * by converting on the fly at the point of substitution rather than setting - * a fixed byte sequence. - * - * @param cnv The UConverter object. - * @param s The Unicode string. - * @param length The number of UChars in s, or -1 for a NUL-terminated string. - * @param err Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * - * @see ucnv_setSubstChars - * @see ucnv_getSubstChars - * @stable ICU 3.6 - */ -U_STABLE void U_EXPORT2 -ucnv_setSubstString(UConverter *cnv, - const UChar *s, - int32_t length, - UErrorCode *err); - -/** - * Fills in the output parameter, errBytes, with the error characters from the - * last failing conversion. - * - * @param converter the Unicode converter - * @param errBytes the codepage bytes which were in error - * @param len on input the capacity of errBytes, on output the number of - * bytes which were copied to it - * @param err the error status code. - * If the substitution character array is too small, an - * U_INDEX_OUTOFBOUNDS_ERROR will be returned. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_getInvalidChars(const UConverter *converter, - char *errBytes, - int8_t *len, - UErrorCode *err); - -/** - * Fills in the output parameter, errChars, with the error characters from the - * last failing conversion. - * - * @param converter the Unicode converter - * @param errUChars the UChars which were in error - * @param len on input the capacity of errUChars, on output the number of - * UChars which were copied to it - * @param err the error status code. - * If the substitution character array is too small, an - * U_INDEX_OUTOFBOUNDS_ERROR will be returned. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_getInvalidUChars(const UConverter *converter, - UChar *errUChars, - int8_t *len, - UErrorCode *err); - -/** - * Resets the state of a converter to the default state. This is used - * in the case of an error, to restart a conversion from a known default state. - * It will also empty the internal output buffers. - * @param converter the Unicode converter - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_reset(UConverter *converter); - -/** - * Resets the to-Unicode part of a converter state to the default state. - * This is used in the case of an error to restart a conversion to - * Unicode to a known default state. It will also empty the internal - * output buffers used for the conversion to Unicode codepoints. - * @param converter the Unicode converter - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_resetToUnicode(UConverter *converter); - -/** - * Resets the from-Unicode part of a converter state to the default state. - * This is used in the case of an error to restart a conversion from - * Unicode to a known default state. It will also empty the internal output - * buffers used for the conversion from Unicode codepoints. - * @param converter the Unicode converter - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_resetFromUnicode(UConverter *converter); - -/** - * Returns the maximum number of bytes that are output per UChar in conversion - * from Unicode using this converter. - * The returned number can be used with UCNV_GET_MAX_BYTES_FOR_STRING - * to calculate the size of a target buffer for conversion from Unicode. - * - * Note: Before ICU 2.8, this function did not return reliable numbers for - * some stateful converters (EBCDIC_STATEFUL, ISO-2022) and LMBCS. - * - * This number may not be the same as the maximum number of bytes per - * "conversion unit". In other words, it may not be the intuitively expected - * number of bytes per character that would be published for a charset, - * and may not fulfill any other purpose than the allocation of an output - * buffer of guaranteed sufficient size for a given input length and converter. - * - * Examples for special cases that are taken into account: - * - Supplementary code points may convert to more bytes than BMP code points. - * This function returns bytes per UChar (UTF-16 code unit), not per - * Unicode code point, for efficient buffer allocation. - * - State-shifting output (SI/SO, escapes, etc.) from stateful converters. - * - When m input UChars are converted to n output bytes, then the maximum m/n - * is taken into account. - * - * The number returned here does not take into account - * (see UCNV_GET_MAX_BYTES_FOR_STRING): - * - callbacks which output more than one charset character sequence per call, - * like escape callbacks - * - initial and final non-character bytes that are output by some converters - * (automatic BOMs, initial escape sequence, final SI, etc.) - * - * Examples for returned values: - * - SBCS charsets: 1 - * - Shift-JIS: 2 - * - UTF-16: 2 (2 per BMP, 4 per surrogate _pair_, BOM not counted) - * - UTF-8: 3 (3 per BMP, 4 per surrogate _pair_) - * - EBCDIC_STATEFUL (EBCDIC mixed SBCS/DBCS): 3 (SO + DBCS) - * - ISO-2022: 3 (always outputs UTF-8) - * - ISO-2022-JP: 6 (4-byte escape sequences + DBCS) - * - ISO-2022-CN: 8 (4-byte designator sequences + 2-byte SS2/SS3 + DBCS) - * - * @param converter The Unicode converter. - * @return The maximum number of bytes per UChar (16 bit code unit) - * that are output by ucnv_fromUnicode(), - * to be used together with UCNV_GET_MAX_BYTES_FOR_STRING - * for buffer allocation. - * - * @see UCNV_GET_MAX_BYTES_FOR_STRING - * @see ucnv_getMinCharSize - * @stable ICU 2.0 - */ -U_STABLE int8_t U_EXPORT2 -ucnv_getMaxCharSize(const UConverter *converter); - -/** - * Calculates the size of a buffer for conversion from Unicode to a charset. - * The calculated size is guaranteed to be sufficient for this conversion. - * - * It takes into account initial and final non-character bytes that are output - * by some converters. - * It does not take into account callbacks which output more than one charset - * character sequence per call, like escape callbacks. - * The default (substitution) callback only outputs one charset character sequence. - * - * @param length Number of UChars to be converted. - * @param maxCharSize Return value from ucnv_getMaxCharSize() for the converter - * that will be used. - * @return Size of a buffer that will be large enough to hold the output bytes of - * converting length UChars with the converter that returned the maxCharSize. - * - * @see ucnv_getMaxCharSize - * @stable ICU 2.8 - */ -#define UCNV_GET_MAX_BYTES_FOR_STRING(length, maxCharSize) \ - (((int32_t)(length)+10)*(int32_t)(maxCharSize)) - -/** - * Returns the minimum byte length (per codepoint) for characters in this codepage. - * This is usually either 1 or 2. - * @param converter the Unicode converter - * @return the minimum number of bytes per codepoint allowed by this particular converter - * @see ucnv_getMaxCharSize - * @stable ICU 2.0 - */ -U_STABLE int8_t U_EXPORT2 -ucnv_getMinCharSize(const UConverter *converter); - -/** - * Returns the display name of the converter passed in based on the Locale - * passed in. If the locale contains no display name, the internal ASCII - * name will be filled in. - * - * @param converter the Unicode converter. - * @param displayLocale is the specific Locale we want to localised for - * @param displayName user provided buffer to be filled in - * @param displayNameCapacity size of displayName Buffer - * @param err error status code - * @return displayNameLength number of UChar needed in displayName - * @see ucnv_getName - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucnv_getDisplayName(const UConverter *converter, - const char *displayLocale, - UChar *displayName, - int32_t displayNameCapacity, - UErrorCode *err); - -/** - * Gets the internal, canonical name of the converter (zero-terminated). - * The lifetime of the returned string will be that of the converter - * passed to this function. - * @param converter the Unicode converter - * @param err UErrorCode status - * @return the internal name of the converter - * @see ucnv_getDisplayName - * @stable ICU 2.0 - */ -U_STABLE const char * U_EXPORT2 -ucnv_getName(const UConverter *converter, UErrorCode *err); - -/** - * Gets a codepage number associated with the converter. This is not guaranteed - * to be the one used to create the converter. Some converters do not represent - * platform registered codepages and return zero for the codepage number. - * The error code fill-in parameter indicates if the codepage number - * is available. - * Does not check if the converter is NULL or if converter's data - * table is NULL. - * - * Important: The use of CCSIDs is not recommended because it is limited - * to only two platforms in principle and only one (UCNV_IBM) in the current - * ICU converter API. - * Also, CCSIDs are insufficient to identify IBM Unicode conversion tables precisely. - * For more details see ucnv_openCCSID(). - * - * @param converter the Unicode converter - * @param err the error status code. - * @return If any error occurrs, -1 will be returned otherwise, the codepage number - * will be returned - * @see ucnv_openCCSID - * @see ucnv_getPlatform - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucnv_getCCSID(const UConverter *converter, - UErrorCode *err); - -/** - * Gets a codepage platform associated with the converter. Currently, - * only UCNV_IBM will be returned. - * Does not test if the converter is NULL or if converter's data - * table is NULL. - * @param converter the Unicode converter - * @param err the error status code. - * @return The codepage platform - * @stable ICU 2.0 - */ -U_STABLE UConverterPlatform U_EXPORT2 -ucnv_getPlatform(const UConverter *converter, - UErrorCode *err); - -/** - * Gets the type of the converter - * e.g. SBCS, MBCS, DBCS, UTF8, UTF16_BE, UTF16_LE, ISO_2022, - * EBCDIC_STATEFUL, LATIN_1 - * @param converter a valid, opened converter - * @return the type of the converter - * @stable ICU 2.0 - */ -U_STABLE UConverterType U_EXPORT2 -ucnv_getType(const UConverter * converter); - -/** - * Gets the "starter" (lead) bytes for converters of type MBCS. - * Will fill in an U_ILLEGAL_ARGUMENT_ERROR if converter passed in - * is not MBCS. Fills in an array of type UBool, with the value of the byte - * as offset to the array. For example, if (starters[0x20] == TRUE) at return, - * it means that the byte 0x20 is a starter byte in this converter. - * Context pointers are always owned by the caller. - * - * @param converter a valid, opened converter of type MBCS - * @param starters an array of size 256 to be filled in - * @param err error status, U_ILLEGAL_ARGUMENT_ERROR if the - * converter is not a type which can return starters. - * @see ucnv_getType - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_getStarters(const UConverter* converter, - UBool starters[256], - UErrorCode* err); - - -/** - * Selectors for Unicode sets that can be returned by ucnv_getUnicodeSet(). - * @see ucnv_getUnicodeSet - * @stable ICU 2.6 - */ -typedef enum UConverterUnicodeSet { - /** Select the set of roundtrippable Unicode code points. @stable ICU 2.6 */ - UCNV_ROUNDTRIP_SET, - /** Select the set of Unicode code points with roundtrip or fallback mappings. @stable ICU 4.0 */ - UCNV_ROUNDTRIP_AND_FALLBACK_SET, -#ifndef U_HIDE_DEPRECATED_API - /** - * Number of UConverterUnicodeSet selectors. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCNV_SET_COUNT -#endif // U_HIDE_DEPRECATED_API -} UConverterUnicodeSet; - - -/** - * Returns the set of Unicode code points that can be converted by an ICU converter. - * - * Returns one of several kinds of set: - * - * 1. UCNV_ROUNDTRIP_SET - * - * The set of all Unicode code points that can be roundtrip-converted - * (converted without any data loss) with the converter (ucnv_fromUnicode()). - * This set will not include code points that have fallback mappings - * or are only the result of reverse fallback mappings. - * This set will also not include PUA code points with fallbacks, although - * ucnv_fromUnicode() will always uses those mappings despite ucnv_setFallback(). - * See UTR #22 "Character Mapping Markup Language" - * at http://www.unicode.org/reports/tr22/ - * - * This is useful for example for - * - checking that a string or document can be roundtrip-converted with a converter, - * without/before actually performing the conversion - * - testing if a converter can be used for text for typical text for a certain locale, - * by comparing its roundtrip set with the set of ExemplarCharacters from - * ICU's locale data or other sources - * - * 2. UCNV_ROUNDTRIP_AND_FALLBACK_SET - * - * The set of all Unicode code points that can be converted with the converter (ucnv_fromUnicode()) - * when fallbacks are turned on (see ucnv_setFallback()). - * This set includes all code points with roundtrips and fallbacks (but not reverse fallbacks). - * - * In the future, there may be more UConverterUnicodeSet choices to select - * sets with different properties. - * - * @param cnv The converter for which a set is requested. - * @param setFillIn A valid USet *. It will be cleared by this function before - * the converter's specific set is filled into the USet. - * @param whichSet A UConverterUnicodeSet selector; - * currently UCNV_ROUNDTRIP_SET is the only supported value. - * @param pErrorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * - * @see UConverterUnicodeSet - * @see uset_open - * @see uset_close - * @stable ICU 2.6 - */ -U_STABLE void U_EXPORT2 -ucnv_getUnicodeSet(const UConverter *cnv, - USet *setFillIn, - UConverterUnicodeSet whichSet, - UErrorCode *pErrorCode); - -/** - * Gets the current calback function used by the converter when an illegal - * or invalid codepage sequence is found. - * Context pointers are always owned by the caller. - * - * @param converter the unicode converter - * @param action fillin: returns the callback function pointer - * @param context fillin: returns the callback's private void* context - * @see ucnv_setToUCallBack - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_getToUCallBack (const UConverter * converter, - UConverterToUCallback *action, - const void **context); - -/** - * Gets the current callback function used by the converter when illegal - * or invalid Unicode sequence is found. - * Context pointers are always owned by the caller. - * - * @param converter the unicode converter - * @param action fillin: returns the callback function pointer - * @param context fillin: returns the callback's private void* context - * @see ucnv_setFromUCallBack - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_getFromUCallBack (const UConverter * converter, - UConverterFromUCallback *action, - const void **context); - -/** - * Changes the callback function used by the converter when - * an illegal or invalid sequence is found. - * Context pointers are always owned by the caller. - * Predefined actions and contexts can be found in the ucnv_err.h header. - * - * @param converter the unicode converter - * @param newAction the new callback function - * @param newContext the new toUnicode callback context pointer. This can be NULL. - * @param oldAction fillin: returns the old callback function pointer. This can be NULL. - * @param oldContext fillin: returns the old callback's private void* context. This can be NULL. - * @param err The error code status - * @see ucnv_getToUCallBack - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_setToUCallBack (UConverter * converter, - UConverterToUCallback newAction, - const void* newContext, - UConverterToUCallback *oldAction, - const void** oldContext, - UErrorCode * err); - -/** - * Changes the current callback function used by the converter when - * an illegal or invalid sequence is found. - * Context pointers are always owned by the caller. - * Predefined actions and contexts can be found in the ucnv_err.h header. - * - * @param converter the unicode converter - * @param newAction the new callback function - * @param newContext the new fromUnicode callback context pointer. This can be NULL. - * @param oldAction fillin: returns the old callback function pointer. This can be NULL. - * @param oldContext fillin: returns the old callback's private void* context. This can be NULL. - * @param err The error code status - * @see ucnv_getFromUCallBack - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_setFromUCallBack (UConverter * converter, - UConverterFromUCallback newAction, - const void *newContext, - UConverterFromUCallback *oldAction, - const void **oldContext, - UErrorCode * err); - -/** - * Converts an array of unicode characters to an array of codepage - * characters. This function is optimized for converting a continuous - * stream of data in buffer-sized chunks, where the entire source and - * target does not fit in available buffers. - * - * The source pointer is an in/out parameter. It starts out pointing where the - * conversion is to begin, and ends up pointing after the last UChar consumed. - * - * Target similarly starts out pointer at the first available byte in the output - * buffer, and ends up pointing after the last byte written to the output. - * - * The converter always attempts to consume the entire source buffer, unless - * (1.) the target buffer is full, or (2.) a failing error is returned from the - * current callback function. When a successful error status has been - * returned, it means that all of the source buffer has been - * consumed. At that point, the caller should reset the source and - * sourceLimit pointers to point to the next chunk. - * - * At the end of the stream (flush==TRUE), the input is completely consumed - * when *source==sourceLimit and no error code is set. - * The converter object is then automatically reset by this function. - * (This means that a converter need not be reset explicitly between data - * streams if it finishes the previous stream without errors.) - * - * This is a stateful conversion. Additionally, even when all source data has - * been consumed, some data may be in the converters' internal state. - * Call this function repeatedly, updating the target pointers with - * the next empty chunk of target in case of a - * U_BUFFER_OVERFLOW_ERROR, and updating the source pointers - * with the next chunk of source when a successful error status is - * returned, until there are no more chunks of source data. - * @param converter the Unicode converter - * @param target I/O parameter. Input : Points to the beginning of the buffer to copy - * codepage characters to. Output : points to after the last codepage character copied - * to target. - * @param targetLimit the pointer just after last of the target buffer - * @param source I/O parameter, pointer to pointer to the source Unicode character buffer. - * @param sourceLimit the pointer just after the last of the source buffer - * @param offsets if NULL is passed, nothing will happen to it, otherwise it needs to have the same number - * of allocated cells as target. Will fill in offsets from target to source pointer - * e.g: offsets[3] is equal to 6, it means that the target[3] was a result of transcoding source[6] - * For output data carried across calls, and other data without a specific source character - * (such as from escape sequences or callbacks) -1 will be placed for offsets. - * @param flush set to TRUE if the current source buffer is the last available - * chunk of the source, FALSE otherwise. Note that if a failing status is returned, - * this function may have to be called multiple times with flush set to TRUE until - * the source buffer is consumed. - * @param err the error status. U_ILLEGAL_ARGUMENT_ERROR will be set if the - * converter is NULL. - * U_BUFFER_OVERFLOW_ERROR will be set if the target is full and there is - * still data to be written to the target. - * @see ucnv_fromUChars - * @see ucnv_convert - * @see ucnv_getMinCharSize - * @see ucnv_setToUCallBack - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_fromUnicode (UConverter * converter, - char **target, - const char *targetLimit, - const UChar ** source, - const UChar * sourceLimit, - int32_t* offsets, - UBool flush, - UErrorCode * err); - -/** - * Converts a buffer of codepage bytes into an array of unicode UChars - * characters. This function is optimized for converting a continuous - * stream of data in buffer-sized chunks, where the entire source and - * target does not fit in available buffers. - * - * The source pointer is an in/out parameter. It starts out pointing where the - * conversion is to begin, and ends up pointing after the last byte of source consumed. - * - * Target similarly starts out pointer at the first available UChar in the output - * buffer, and ends up pointing after the last UChar written to the output. - * It does NOT necessarily keep UChar sequences together. - * - * The converter always attempts to consume the entire source buffer, unless - * (1.) the target buffer is full, or (2.) a failing error is returned from the - * current callback function. When a successful error status has been - * returned, it means that all of the source buffer has been - * consumed. At that point, the caller should reset the source and - * sourceLimit pointers to point to the next chunk. - * - * At the end of the stream (flush==TRUE), the input is completely consumed - * when *source==sourceLimit and no error code is set - * The converter object is then automatically reset by this function. - * (This means that a converter need not be reset explicitly between data - * streams if it finishes the previous stream without errors.) - * - * This is a stateful conversion. Additionally, even when all source data has - * been consumed, some data may be in the converters' internal state. - * Call this function repeatedly, updating the target pointers with - * the next empty chunk of target in case of a - * U_BUFFER_OVERFLOW_ERROR, and updating the source pointers - * with the next chunk of source when a successful error status is - * returned, until there are no more chunks of source data. - * @param converter the Unicode converter - * @param target I/O parameter. Input : Points to the beginning of the buffer to copy - * UChars into. Output : points to after the last UChar copied. - * @param targetLimit the pointer just after the end of the target buffer - * @param source I/O parameter, pointer to pointer to the source codepage buffer. - * @param sourceLimit the pointer to the byte after the end of the source buffer - * @param offsets if NULL is passed, nothing will happen to it, otherwise it needs to have the same number - * of allocated cells as target. Will fill in offsets from target to source pointer - * e.g: offsets[3] is equal to 6, it means that the target[3] was a result of transcoding source[6] - * For output data carried across calls, and other data without a specific source character - * (such as from escape sequences or callbacks) -1 will be placed for offsets. - * @param flush set to TRUE if the current source buffer is the last available - * chunk of the source, FALSE otherwise. Note that if a failing status is returned, - * this function may have to be called multiple times with flush set to TRUE until - * the source buffer is consumed. - * @param err the error status. U_ILLEGAL_ARGUMENT_ERROR will be set if the - * converter is NULL. - * U_BUFFER_OVERFLOW_ERROR will be set if the target is full and there is - * still data to be written to the target. - * @see ucnv_fromUChars - * @see ucnv_convert - * @see ucnv_getMinCharSize - * @see ucnv_setFromUCallBack - * @see ucnv_getNextUChar - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_toUnicode(UConverter *converter, - UChar **target, - const UChar *targetLimit, - const char **source, - const char *sourceLimit, - int32_t *offsets, - UBool flush, - UErrorCode *err); - -/** - * Convert the Unicode string into a codepage string using an existing UConverter. - * The output string is NUL-terminated if possible. - * - * This function is a more convenient but less powerful version of ucnv_fromUnicode(). - * It is only useful for whole strings, not for streaming conversion. - * - * The maximum output buffer capacity required (barring output from callbacks) will be - * UCNV_GET_MAX_BYTES_FOR_STRING(srcLength, ucnv_getMaxCharSize(cnv)). - * - * @param cnv the converter object to be used (ucnv_resetFromUnicode() will be called) - * @param src the input Unicode string - * @param srcLength the input string length, or -1 if NUL-terminated - * @param dest destination string buffer, can be NULL if destCapacity==0 - * @param destCapacity the number of chars available at dest - * @param pErrorCode normal ICU error code; - * common error codes that may be set by this function include - * U_BUFFER_OVERFLOW_ERROR, U_STRING_NOT_TERMINATED_WARNING, - * U_ILLEGAL_ARGUMENT_ERROR, and conversion errors - * @return the length of the output string, not counting the terminating NUL; - * if the length is greater than destCapacity, then the string will not fit - * and a buffer of the indicated length would need to be passed in - * @see ucnv_fromUnicode - * @see ucnv_convert - * @see UCNV_GET_MAX_BYTES_FOR_STRING - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucnv_fromUChars(UConverter *cnv, - char *dest, int32_t destCapacity, - const UChar *src, int32_t srcLength, - UErrorCode *pErrorCode); - -/** - * Convert the codepage string into a Unicode string using an existing UConverter. - * The output string is NUL-terminated if possible. - * - * This function is a more convenient but less powerful version of ucnv_toUnicode(). - * It is only useful for whole strings, not for streaming conversion. - * - * The maximum output buffer capacity required (barring output from callbacks) will be - * 2*srcLength (each char may be converted into a surrogate pair). - * - * @param cnv the converter object to be used (ucnv_resetToUnicode() will be called) - * @param src the input codepage string - * @param srcLength the input string length, or -1 if NUL-terminated - * @param dest destination string buffer, can be NULL if destCapacity==0 - * @param destCapacity the number of UChars available at dest - * @param pErrorCode normal ICU error code; - * common error codes that may be set by this function include - * U_BUFFER_OVERFLOW_ERROR, U_STRING_NOT_TERMINATED_WARNING, - * U_ILLEGAL_ARGUMENT_ERROR, and conversion errors - * @return the length of the output string, not counting the terminating NUL; - * if the length is greater than destCapacity, then the string will not fit - * and a buffer of the indicated length would need to be passed in - * @see ucnv_toUnicode - * @see ucnv_convert - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucnv_toUChars(UConverter *cnv, - UChar *dest, int32_t destCapacity, - const char *src, int32_t srcLength, - UErrorCode *pErrorCode); - -/** - * Convert a codepage buffer into Unicode one character at a time. - * The input is completely consumed when the U_INDEX_OUTOFBOUNDS_ERROR is set. - * - * Advantage compared to ucnv_toUnicode() or ucnv_toUChars(): - * - Faster for small amounts of data, for most converters, e.g., - * US-ASCII, ISO-8859-1, UTF-8/16/32, and most "normal" charsets. - * (For complex converters, e.g., SCSU, UTF-7 and ISO 2022 variants, - * it uses ucnv_toUnicode() internally.) - * - Convenient. - * - * Limitations compared to ucnv_toUnicode(): - * - Always assumes flush=TRUE. - * This makes ucnv_getNextUChar() unsuitable for "streaming" conversion, - * that is, for where the input is supplied in multiple buffers, - * because ucnv_getNextUChar() will assume the end of the input at the end - * of the first buffer. - * - Does not provide offset output. - * - * It is possible to "mix" ucnv_getNextUChar() and ucnv_toUnicode() because - * ucnv_getNextUChar() uses the current state of the converter - * (unlike ucnv_toUChars() which always resets first). - * However, if ucnv_getNextUChar() is called after ucnv_toUnicode() - * stopped in the middle of a character sequence (with flush=FALSE), - * then ucnv_getNextUChar() will always use the slower ucnv_toUnicode() - * internally until the next character boundary. - * (This is new in ICU 2.6. In earlier releases, ucnv_getNextUChar() had to - * start at a character boundary.) - * - * Instead of using ucnv_getNextUChar(), it is recommended - * to convert using ucnv_toUnicode() or ucnv_toUChars() - * and then iterate over the text using U16_NEXT() or a UCharIterator (uiter.h) - * or a C++ CharacterIterator or similar. - * This allows streaming conversion and offset output, for example. - * - *

Handling of surrogate pairs and supplementary-plane code points:
- * There are two different kinds of codepages that provide mappings for surrogate characters: - *

    - *
  • Codepages like UTF-8, UTF-32, and GB 18030 provide direct representations for Unicode - * code points U+10000-U+10ffff as well as for single surrogates U+d800-U+dfff. - * Each valid sequence will result in exactly one returned code point. - * If a sequence results in a single surrogate, then that will be returned - * by itself, even if a neighboring sequence encodes the matching surrogate.
  • - *
  • Codepages like SCSU and LMBCS (and UTF-16) provide direct representations only for BMP code points - * including surrogates. Code points in supplementary planes are represented with - * two sequences, each encoding a surrogate. - * For these codepages, matching pairs of surrogates will be combined into single - * code points for returning from this function. - * (Note that SCSU is actually a mix of these codepage types.)
  • - *

- * - * @param converter an open UConverter - * @param source the address of a pointer to the codepage buffer, will be - * updated to point after the bytes consumed in the conversion call. - * @param sourceLimit points to the end of the input buffer - * @param err fills in error status (see ucnv_toUnicode) - * U_INDEX_OUTOFBOUNDS_ERROR will be set if the input - * is empty or does not convert to any output (e.g.: pure state-change - * codes SI/SO, escape sequences for ISO 2022, - * or if the callback did not output anything, ...). - * This function will not set a U_BUFFER_OVERFLOW_ERROR because - * the "buffer" is the return code. However, there might be subsequent output - * stored in the converter object - * that will be returned in following calls to this function. - * @return a UChar32 resulting from the partial conversion of source - * @see ucnv_toUnicode - * @see ucnv_toUChars - * @see ucnv_convert - * @stable ICU 2.0 - */ -U_STABLE UChar32 U_EXPORT2 -ucnv_getNextUChar(UConverter * converter, - const char **source, - const char * sourceLimit, - UErrorCode * err); - -/** - * Convert from one external charset to another using two existing UConverters. - * Internally, two conversions - ucnv_toUnicode() and ucnv_fromUnicode() - - * are used, "pivoting" through 16-bit Unicode. - * - * Important: For streaming conversion (multiple function calls for successive - * parts of a text stream), the caller must provide a pivot buffer explicitly, - * and must preserve the pivot buffer and associated pointers from one - * call to another. (The buffer may be moved if its contents and the relative - * pointer positions are preserved.) - * - * There is a similar function, ucnv_convert(), - * which has the following limitations: - * - it takes charset names, not converter objects, so that - * - two converters are opened for each call - * - only single-string conversion is possible, not streaming operation - * - it does not provide enough information to find out, - * in case of failure, whether the toUnicode or - * the fromUnicode conversion failed - * - * By contrast, ucnv_convertEx() - * - takes UConverter parameters instead of charset names - * - fully exposes the pivot buffer for streaming conversion and complete error handling - * - * ucnv_convertEx() also provides further convenience: - * - an option to reset the converters at the beginning - * (if reset==TRUE, see parameters; - * also sets *pivotTarget=*pivotSource=pivotStart) - * - allow NUL-terminated input - * (only a single NUL byte, will not work for charsets with multi-byte NULs) - * (if sourceLimit==NULL, see parameters) - * - terminate with a NUL on output - * (only a single NUL byte, not useful for charsets with multi-byte NULs), - * or set U_STRING_NOT_TERMINATED_WARNING if the output exactly fills - * the target buffer - * - the pivot buffer can be provided internally; - * possible only for whole-string conversion, not streaming conversion; - * in this case, the caller will not be able to get details about where an - * error occurred - * (if pivotStart==NULL, see below) - * - * The function returns when one of the following is true: - * - the entire source text has been converted successfully to the target buffer - * - a target buffer overflow occurred (U_BUFFER_OVERFLOW_ERROR) - * - a conversion error occurred - * (other U_FAILURE(), see description of pErrorCode) - * - * Limitation compared to the direct use of - * ucnv_fromUnicode() and ucnv_toUnicode(): - * ucnv_convertEx() does not provide offset information. - * - * Limitation compared to ucnv_fromUChars() and ucnv_toUChars(): - * ucnv_convertEx() does not support preflighting directly. - * - * Sample code for converting a single string from - * one external charset to UTF-8, ignoring the location of errors: - * - * \code - * int32_t - * myToUTF8(UConverter *cnv, - * const char *s, int32_t length, - * char *u8, int32_t capacity, - * UErrorCode *pErrorCode) { - * UConverter *utf8Cnv; - * char *target; - * - * if(U_FAILURE(*pErrorCode)) { - * return 0; - * } - * - * utf8Cnv=myGetCachedUTF8Converter(pErrorCode); - * if(U_FAILURE(*pErrorCode)) { - * return 0; - * } - * - * if(length<0) { - * length=strlen(s); - * } - * target=u8; - * ucnv_convertEx(utf8Cnv, cnv, - * &target, u8+capacity, - * &s, s+length, - * NULL, NULL, NULL, NULL, - * TRUE, TRUE, - * pErrorCode); - * - * myReleaseCachedUTF8Converter(utf8Cnv); - * - * // return the output string length, but without preflighting - * return (int32_t)(target-u8); - * } - * \endcode - * - * @param targetCnv Output converter, used to convert from the UTF-16 pivot - * to the target using ucnv_fromUnicode(). - * @param sourceCnv Input converter, used to convert from the source to - * the UTF-16 pivot using ucnv_toUnicode(). - * @param target I/O parameter, same as for ucnv_fromUChars(). - * Input: *target points to the beginning of the target buffer. - * Output: *target points to the first unit after the last char written. - * @param targetLimit Pointer to the first unit after the target buffer. - * @param source I/O parameter, same as for ucnv_toUChars(). - * Input: *source points to the beginning of the source buffer. - * Output: *source points to the first unit after the last char read. - * @param sourceLimit Pointer to the first unit after the source buffer. - * @param pivotStart Pointer to the UTF-16 pivot buffer. If pivotStart==NULL, - * then an internal buffer is used and the other pivot - * arguments are ignored and can be NULL as well. - * @param pivotSource I/O parameter, same as source in ucnv_fromUChars() for - * conversion from the pivot buffer to the target buffer. - * @param pivotTarget I/O parameter, same as target in ucnv_toUChars() for - * conversion from the source buffer to the pivot buffer. - * It must be pivotStart<=*pivotSource<=*pivotTarget<=pivotLimit - * and pivotStart[0..ucnv_countAvaiable()]) - * @return a pointer a string (library owned), or NULL if the index is out of bounds. - * @see ucnv_countAvailable - * @stable ICU 2.0 - */ -U_STABLE const char* U_EXPORT2 -ucnv_getAvailableName(int32_t n); - -/** - * Returns a UEnumeration to enumerate all of the canonical converter - * names, as per the alias file, regardless of the ability to open each - * converter. - * - * @return A UEnumeration object for getting all the recognized canonical - * converter names. - * @see ucnv_getAvailableName - * @see uenum_close - * @see uenum_next - * @stable ICU 2.4 - */ -U_STABLE UEnumeration * U_EXPORT2 -ucnv_openAllNames(UErrorCode *pErrorCode); - -/** - * Gives the number of aliases for a given converter or alias name. - * If the alias is ambiguous, then the preferred converter is used - * and the status is set to U_AMBIGUOUS_ALIAS_WARNING. - * This method only enumerates the listed entries in the alias file. - * @param alias alias name - * @param pErrorCode error status - * @return number of names on alias list for given alias - * @stable ICU 2.0 - */ -U_STABLE uint16_t U_EXPORT2 -ucnv_countAliases(const char *alias, UErrorCode *pErrorCode); - -/** - * Gives the name of the alias at given index of alias list. - * This method only enumerates the listed entries in the alias file. - * If the alias is ambiguous, then the preferred converter is used - * and the status is set to U_AMBIGUOUS_ALIAS_WARNING. - * @param alias alias name - * @param n index in alias list - * @param pErrorCode result of operation - * @return returns the name of the alias at given index - * @see ucnv_countAliases - * @stable ICU 2.0 - */ -U_STABLE const char * U_EXPORT2 -ucnv_getAlias(const char *alias, uint16_t n, UErrorCode *pErrorCode); - -/** - * Fill-up the list of alias names for the given alias. - * This method only enumerates the listed entries in the alias file. - * If the alias is ambiguous, then the preferred converter is used - * and the status is set to U_AMBIGUOUS_ALIAS_WARNING. - * @param alias alias name - * @param aliases fill-in list, aliases is a pointer to an array of - * ucnv_countAliases() string-pointers - * (const char *) that will be filled in. - * The strings themselves are owned by the library. - * @param pErrorCode result of operation - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_getAliases(const char *alias, const char **aliases, UErrorCode *pErrorCode); - -/** - * Return a new UEnumeration object for enumerating all the - * alias names for a given converter that are recognized by a standard. - * This method only enumerates the listed entries in the alias file. - * The convrtrs.txt file can be modified to change the results of - * this function. - * The first result in this list is the same result given by - * ucnv_getStandardName, which is the default alias for - * the specified standard name. The returned object must be closed with - * uenum_close when you are done with the object. - * - * @param convName original converter name - * @param standard name of the standard governing the names; MIME and IANA - * are such standards - * @param pErrorCode The error code - * @return A UEnumeration object for getting all aliases that are recognized - * by a standard. If any of the parameters are invalid, NULL - * is returned. - * @see ucnv_getStandardName - * @see uenum_close - * @see uenum_next - * @stable ICU 2.2 - */ -U_STABLE UEnumeration * U_EXPORT2 -ucnv_openStandardNames(const char *convName, - const char *standard, - UErrorCode *pErrorCode); - -/** - * Gives the number of standards associated to converter names. - * @return number of standards - * @stable ICU 2.0 - */ -U_STABLE uint16_t U_EXPORT2 -ucnv_countStandards(void); - -/** - * Gives the name of the standard at given index of standard list. - * @param n index in standard list - * @param pErrorCode result of operation - * @return returns the name of the standard at given index. Owned by the library. - * @stable ICU 2.0 - */ -U_STABLE const char * U_EXPORT2 -ucnv_getStandard(uint16_t n, UErrorCode *pErrorCode); - -/** - * Returns a standard name for a given converter name. - *

- * Example alias table:
- * conv alias1 { STANDARD1 } alias2 { STANDARD1* } - *

- * Result of ucnv_getStandardName("conv", "STANDARD1") from example - * alias table:
- * "alias2" - * - * @param name original converter name - * @param standard name of the standard governing the names; MIME and IANA - * are such standards - * @param pErrorCode result of operation - * @return returns the standard converter name; - * if a standard converter name cannot be determined, - * then NULL is returned. Owned by the library. - * @stable ICU 2.0 - */ -U_STABLE const char * U_EXPORT2 -ucnv_getStandardName(const char *name, const char *standard, UErrorCode *pErrorCode); - -/** - * This function will return the internal canonical converter name of the - * tagged alias. This is the opposite of ucnv_openStandardNames, which - * returns the tagged alias given the canonical name. - *

- * Example alias table:
- * conv alias1 { STANDARD1 } alias2 { STANDARD1* } - *

- * Result of ucnv_getStandardName("alias1", "STANDARD1") from example - * alias table:
- * "conv" - * - * @return returns the canonical converter name; - * if a standard or alias name cannot be determined, - * then NULL is returned. The returned string is - * owned by the library. - * @see ucnv_getStandardName - * @stable ICU 2.4 - */ -U_STABLE const char * U_EXPORT2 -ucnv_getCanonicalName(const char *alias, const char *standard, UErrorCode *pErrorCode); - -/** - * Returns the current default converter name. If you want to open - * a default converter, you do not need to use this function. - * It is faster if you pass a NULL argument to ucnv_open the - * default converter. - * - * If U_CHARSET_IS_UTF8 is defined to 1 in utypes.h then this function - * always returns "UTF-8". - * - * @return returns the current default converter name. - * Storage owned by the library - * @see ucnv_setDefaultName - * @stable ICU 2.0 - */ -U_STABLE const char * U_EXPORT2 -ucnv_getDefaultName(void); - -#ifndef U_HIDE_SYSTEM_API -/** - * This function is not thread safe. DO NOT call this function when ANY ICU - * function is being used from more than one thread! This function sets the - * current default converter name. If this function needs to be called, it - * should be called during application initialization. Most of the time, the - * results from ucnv_getDefaultName() or ucnv_open with a NULL string argument - * is sufficient for your application. - * - * If U_CHARSET_IS_UTF8 is defined to 1 in utypes.h then this function - * does nothing. - * - * @param name the converter name to be the default (must be known by ICU). - * @see ucnv_getDefaultName - * @system - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_setDefaultName(const char *name); -#endif /* U_HIDE_SYSTEM_API */ - -/** - * Fixes the backslash character mismapping. For example, in SJIS, the backslash - * character in the ASCII portion is also used to represent the yen currency sign. - * When mapping from Unicode character 0x005C, it's unclear whether to map the - * character back to yen or backslash in SJIS. This function will take the input - * buffer and replace all the yen sign characters with backslash. This is necessary - * when the user tries to open a file with the input buffer on Windows. - * This function will test the converter to see whether such mapping is - * required. You can sometimes avoid using this function by using the correct version - * of Shift-JIS. - * - * @param cnv The converter representing the target codepage. - * @param source the input buffer to be fixed - * @param sourceLen the length of the input buffer - * @see ucnv_isAmbiguous - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_fixFileSeparator(const UConverter *cnv, UChar *source, int32_t sourceLen); - -/** - * Determines if the converter contains ambiguous mappings of the same - * character or not. - * @param cnv the converter to be tested - * @return TRUE if the converter contains ambiguous mapping of the same - * character, FALSE otherwise. - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -ucnv_isAmbiguous(const UConverter *cnv); - -/** - * Sets the converter to use fallback mappings or not. - * Regardless of this flag, the converter will always use - * fallbacks from Unicode Private Use code points, as well as - * reverse fallbacks (to Unicode). - * For details see ".ucm File Format" - * in the Conversion Data chapter of the ICU User Guide: - * http://www.icu-project.org/userguide/conversion-data.html#ucmformat - * - * @param cnv The converter to set the fallback mapping usage on. - * @param usesFallback TRUE if the user wants the converter to take advantage of the fallback - * mapping, FALSE otherwise. - * @stable ICU 2.0 - * @see ucnv_usesFallback - */ -U_STABLE void U_EXPORT2 -ucnv_setFallback(UConverter *cnv, UBool usesFallback); - -/** - * Determines if the converter uses fallback mappings or not. - * This flag has restrictions, see ucnv_setFallback(). - * - * @param cnv The converter to be tested - * @return TRUE if the converter uses fallback, FALSE otherwise. - * @stable ICU 2.0 - * @see ucnv_setFallback - */ -U_STABLE UBool U_EXPORT2 -ucnv_usesFallback(const UConverter *cnv); - -/** - * Detects Unicode signature byte sequences at the start of the byte stream - * and returns the charset name of the indicated Unicode charset. - * NULL is returned when no Unicode signature is recognized. - * The number of bytes in the signature is output as well. - * - * The caller can ucnv_open() a converter using the charset name. - * The first code unit (UChar) from the start of the stream will be U+FEFF - * (the Unicode BOM/signature character) and can usually be ignored. - * - * For most Unicode charsets it is also possible to ignore the indicated - * number of initial stream bytes and start converting after them. - * However, there are stateful Unicode charsets (UTF-7 and BOCU-1) for which - * this will not work. Therefore, it is best to ignore the first output UChar - * instead of the input signature bytes. - *

- * Usage: - * \snippet samples/ucnv/convsamp.cpp ucnv_detectUnicodeSignature - * - * @param source The source string in which the signature should be detected. - * @param sourceLength Length of the input string, or -1 if terminated with a NUL byte. - * @param signatureLength A pointer to int32_t to receive the number of bytes that make up the signature - * of the detected UTF. 0 if not detected. - * Can be a NULL pointer. - * @param pErrorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return The name of the encoding detected. NULL if encoding is not detected. - * @stable ICU 2.4 - */ -U_STABLE const char* U_EXPORT2 -ucnv_detectUnicodeSignature(const char* source, - int32_t sourceLength, - int32_t *signatureLength, - UErrorCode *pErrorCode); - -/** - * Returns the number of UChars held in the converter's internal state - * because more input is needed for completing the conversion. This function is - * useful for mapping semantics of ICU's converter interface to those of iconv, - * and this information is not needed for normal conversion. - * @param cnv The converter in which the input is held - * @param status ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return The number of UChars in the state. -1 if an error is encountered. - * @stable ICU 3.4 - */ -U_STABLE int32_t U_EXPORT2 -ucnv_fromUCountPending(const UConverter* cnv, UErrorCode* status); - -/** - * Returns the number of chars held in the converter's internal state - * because more input is needed for completing the conversion. This function is - * useful for mapping semantics of ICU's converter interface to those of iconv, - * and this information is not needed for normal conversion. - * @param cnv The converter in which the input is held as internal state - * @param status ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return The number of chars in the state. -1 if an error is encountered. - * @stable ICU 3.4 - */ -U_STABLE int32_t U_EXPORT2 -ucnv_toUCountPending(const UConverter* cnv, UErrorCode* status); - -/** - * Returns whether or not the charset of the converter has a fixed number of bytes - * per charset character. - * An example of this are converters that are of the type UCNV_SBCS or UCNV_DBCS. - * Another example is UTF-32 which is always 4 bytes per character. - * A Unicode code point may be represented by more than one UTF-8 or UTF-16 code unit - * but a UTF-32 converter encodes each code point with 4 bytes. - * Note: This method is not intended to be used to determine whether the charset has a - * fixed ratio of bytes to Unicode codes units for any particular Unicode encoding form. - * FALSE is returned with the UErrorCode if error occurs or cnv is NULL. - * @param cnv The converter to be tested - * @param status ICU error code in/out paramter - * @return TRUE if the converter is fixed-width - * @stable ICU 4.8 - */ -U_STABLE UBool U_EXPORT2 -ucnv_isFixedWidth(UConverter *cnv, UErrorCode *status); - -#endif - -#endif -/*_UCNV*/ diff --git a/win32/include/spidermonkey/unicode/ucnv_cb.h b/win32/include/spidermonkey/unicode/ucnv_cb.h deleted file mode 100755 index 7104c724..00000000 --- a/win32/include/spidermonkey/unicode/ucnv_cb.h +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 2000-2004, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** - * ucnv_cb.h: - * External APIs for the ICU's codeset conversion library - * Helena Shih - * - * Modification History: - * - * Date Name Description - */ - -/** - * \file - * \brief C UConverter functions to aid the writers of callbacks - * - *

Callback API for UConverter

- * - * These functions are provided here for the convenience of the callback - * writer. If you are just looking for callback functions to use, please - * see ucnv_err.h. DO NOT call these functions directly when you are - * working with converters, unless your code has been called as a callback - * via ucnv_setFromUCallback or ucnv_setToUCallback !! - * - * A note about error codes and overflow. Unlike other ICU functions, - * these functions do not expect the error status to be U_ZERO_ERROR. - * Callbacks must be much more careful about their error codes. - * The error codes used here are in/out parameters, which should be passed - * back in the callback's error parameter. - * - * For example, if you call ucnv_cbfromUWriteBytes to write data out - * to the output codepage, it may return U_BUFFER_OVERFLOW_ERROR if - * the data did not fit in the target. But this isn't a failing error, - * in fact, ucnv_cbfromUWriteBytes may be called AGAIN with the error - * status still U_BUFFER_OVERFLOW_ERROR to attempt to write further bytes, - * which will also go into the internal overflow buffers. - * - * Concerning offsets, the 'offset' parameters here are relative to the start - * of SOURCE. For example, Suppose the string "ABCD" was being converted - * from Unicode into a codepage which doesn't have a mapping for 'B'. - * 'A' will be written out correctly, but - * The FromU Callback will be called on an unassigned character for 'B'. - * At this point, this is the state of the world: - * Target: A [..] [points after A] - * Source: A B [C] D [points to C - B has been consumed] - * 0 1 2 3 - * codePoint = "B" [the unassigned codepoint] - * - * Now, suppose a callback wants to write the substitution character '?' to - * the target. It calls ucnv_cbFromUWriteBytes() to write the ?. - * It should pass ZERO as the offset, because the offset as far as the - * callback is concerned is relative to the SOURCE pointer [which points - * before 'C'.] If the callback goes into the args and consumes 'C' also, - * it would call FromUWriteBytes with an offset of 1 (and advance the source - * pointer). - * - */ - -#ifndef UCNV_CB_H -#define UCNV_CB_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_CONVERSION - -#include "unicode/ucnv.h" -#include "unicode/ucnv_err.h" - -/** - * ONLY used by FromU callback functions. - * Writes out the specified byte output bytes to the target byte buffer or to converter internal buffers. - * - * @param args callback fromUnicode arguments - * @param source source bytes to write - * @param length length of bytes to write - * @param offsetIndex the relative offset index from callback. - * @param err error status. If U_BUFFER_OVERFLOW is returned, then U_BUFFER_OVERFLOW must - * be returned to the user, because it means that not all data could be written into the target buffer, and some is - * in the converter error buffer. - * @see ucnv_cbFromUWriteSub - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_cbFromUWriteBytes (UConverterFromUnicodeArgs *args, - const char* source, - int32_t length, - int32_t offsetIndex, - UErrorCode * err); - -/** - * ONLY used by FromU callback functions. - * This function will write out the correct substitution character sequence - * to the target. - * - * @param args callback fromUnicode arguments - * @param offsetIndex the relative offset index from the current source pointer to be used - * @param err error status. If U_BUFFER_OVERFLOW is returned, then U_BUFFER_OVERFLOW must - * be returned to the user, because it means that not all data could be written into the target buffer, and some is - * in the converter error buffer. - * @see ucnv_cbFromUWriteBytes - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucnv_cbFromUWriteSub (UConverterFromUnicodeArgs *args, - int32_t offsetIndex, - UErrorCode * err); - -/** - * ONLY used by fromU callback functions. - * This function will write out the error character(s) to the target UChar buffer. - * - * @param args callback fromUnicode arguments - * @param source pointer to pointer to first UChar to write [on exit: 1 after last UChar processed] - * @param sourceLimit pointer after last UChar to write - * @param offsetIndex the relative offset index from callback which will be set - * @param err error status U_BUFFER_OVERFLOW - * @see ucnv_cbToUWriteSub - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 ucnv_cbFromUWriteUChars(UConverterFromUnicodeArgs *args, - const UChar** source, - const UChar* sourceLimit, - int32_t offsetIndex, - UErrorCode * err); - -/** - * ONLY used by ToU callback functions. - * This function will write out the specified characters to the target - * UChar buffer. - * - * @param args callback toUnicode arguments - * @param source source string to write - * @param length the length of source string - * @param offsetIndex the relative offset index which will be written. - * @param err error status U_BUFFER_OVERFLOW - * @see ucnv_cbToUWriteSub - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 ucnv_cbToUWriteUChars (UConverterToUnicodeArgs *args, - const UChar* source, - int32_t length, - int32_t offsetIndex, - UErrorCode * err); - -/** - * ONLY used by ToU callback functions. - * This function will write out the Unicode substitution character (U+FFFD). - * - * @param args callback fromUnicode arguments - * @param offsetIndex the relative offset index from callback. - * @param err error status U_BUFFER_OVERFLOW - * @see ucnv_cbToUWriteUChars - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 ucnv_cbToUWriteSub (UConverterToUnicodeArgs *args, - int32_t offsetIndex, - UErrorCode * err); -#endif - -#endif diff --git a/win32/include/spidermonkey/unicode/ucnv_err.h b/win32/include/spidermonkey/unicode/ucnv_err.h deleted file mode 100755 index b970b891..00000000 --- a/win32/include/spidermonkey/unicode/ucnv_err.h +++ /dev/null @@ -1,465 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1999-2009, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** - * - * - * ucnv_err.h: - */ - -/** - * \file - * \brief C UConverter predefined error callbacks - * - *

Error Behaviour Functions

- * Defines some error behaviour functions called by ucnv_{from,to}Unicode - * These are provided as part of ICU and many are stable, but they - * can also be considered only as an example of what can be done with - * callbacks. You may of course write your own. - * - * If you want to write your own, you may also find the functions from - * ucnv_cb.h useful when writing your own callbacks. - * - * These functions, although public, should NEVER be called directly. - * They should be used as parameters to the ucnv_setFromUCallback - * and ucnv_setToUCallback functions, to set the behaviour of a converter - * when it encounters ILLEGAL/UNMAPPED/INVALID sequences. - * - * usage example: 'STOP' doesn't need any context, but newContext - * could be set to something other than 'NULL' if needed. The available - * contexts in this header can modify the default behavior of the callback. - * - * \code - * UErrorCode err = U_ZERO_ERROR; - * UConverter *myConverter = ucnv_open("ibm-949", &err); - * const void *oldContext; - * UConverterFromUCallback oldAction; - * - * - * if (U_SUCCESS(err)) - * { - * ucnv_setFromUCallBack(myConverter, - * UCNV_FROM_U_CALLBACK_STOP, - * NULL, - * &oldAction, - * &oldContext, - * &status); - * } - * \endcode - * - * The code above tells "myConverter" to stop when it encounters an - * ILLEGAL/TRUNCATED/INVALID sequences when it is used to convert from - * Unicode -> Codepage. The behavior from Codepage to Unicode is not changed, - * and ucnv_setToUCallBack would need to be called in order to change - * that behavior too. - * - * Here is an example with a context: - * - * \code - * UErrorCode err = U_ZERO_ERROR; - * UConverter *myConverter = ucnv_open("ibm-949", &err); - * const void *oldContext; - * UConverterFromUCallback oldAction; - * - * - * if (U_SUCCESS(err)) - * { - * ucnv_setToUCallBack(myConverter, - * UCNV_TO_U_CALLBACK_SUBSTITUTE, - * UCNV_SUB_STOP_ON_ILLEGAL, - * &oldAction, - * &oldContext, - * &status); - * } - * \endcode - * - * The code above tells "myConverter" to stop when it encounters an - * ILLEGAL/TRUNCATED/INVALID sequences when it is used to convert from - * Codepage -> Unicode. Any unmapped and legal characters will be - * substituted to be the default substitution character. - */ - -#ifndef UCNV_ERR_H -#define UCNV_ERR_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_CONVERSION - -/** Forward declaring the UConverter structure. @stable ICU 2.0 */ -struct UConverter; - -/** @stable ICU 2.0 */ -typedef struct UConverter UConverter; - -/** - * FROM_U, TO_U context options for sub callback - * @stable ICU 2.0 - */ -#define UCNV_SUB_STOP_ON_ILLEGAL "i" - -/** - * FROM_U, TO_U context options for skip callback - * @stable ICU 2.0 - */ -#define UCNV_SKIP_STOP_ON_ILLEGAL "i" - -/** - * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to ICU (%UXXXX) - * @stable ICU 2.0 - */ -#define UCNV_ESCAPE_ICU NULL -/** - * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to JAVA (\\uXXXX) - * @stable ICU 2.0 - */ -#define UCNV_ESCAPE_JAVA "J" -/** - * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to C (\\uXXXX \\UXXXXXXXX) - * TO_U_CALLBACK_ESCAPE option to escape the character value accoding to C (\\xXXXX) - * @stable ICU 2.0 - */ -#define UCNV_ESCAPE_C "C" -/** - * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to XML Decimal escape \htmlonly(&#DDDD;)\endhtmlonly - * TO_U_CALLBACK_ESCAPE context option to escape the character value accoding to XML Decimal escape \htmlonly(&#DDDD;)\endhtmlonly - * @stable ICU 2.0 - */ -#define UCNV_ESCAPE_XML_DEC "D" -/** - * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to XML Hex escape \htmlonly(&#xXXXX;)\endhtmlonly - * TO_U_CALLBACK_ESCAPE context option to escape the character value accoding to XML Hex escape \htmlonly(&#xXXXX;)\endhtmlonly - * @stable ICU 2.0 - */ -#define UCNV_ESCAPE_XML_HEX "X" -/** - * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to Unicode (U+XXXXX) - * @stable ICU 2.0 - */ -#define UCNV_ESCAPE_UNICODE "U" - -/** - * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to CSS2 conventions (\\HH..H, that is, - * a backslash, 1..6 hex digits, and a space) - * @stable ICU 4.0 - */ -#define UCNV_ESCAPE_CSS2 "S" - -/** - * The process condition code to be used with the callbacks. - * Codes which are greater than UCNV_IRREGULAR should be - * passed on to any chained callbacks. - * @stable ICU 2.0 - */ -typedef enum { - UCNV_UNASSIGNED = 0, /**< The code point is unassigned. - The error code U_INVALID_CHAR_FOUND will be set. */ - UCNV_ILLEGAL = 1, /**< The code point is illegal. For example, - \\x81\\x2E is illegal in SJIS because \\x2E - is not a valid trail byte for the \\x81 - lead byte. - Also, starting with Unicode 3.0.1, non-shortest byte sequences - in UTF-8 (like \\xC1\\xA1 instead of \\x61 for U+0061) - are also illegal, not just irregular. - The error code U_ILLEGAL_CHAR_FOUND will be set. */ - UCNV_IRREGULAR = 2, /**< The codepoint is not a regular sequence in - the encoding. For example, \\xED\\xA0\\x80..\\xED\\xBF\\xBF - are irregular UTF-8 byte sequences for single surrogate - code points. - The error code U_INVALID_CHAR_FOUND will be set. */ - UCNV_RESET = 3, /**< The callback is called with this reason when a - 'reset' has occured. Callback should reset all - state. */ - UCNV_CLOSE = 4, /**< Called when the converter is closed. The - callback should release any allocated memory.*/ - UCNV_CLONE = 5 /**< Called when ucnv_safeClone() is called on the - converter. the pointer available as the - 'context' is an alias to the original converters' - context pointer. If the context must be owned - by the new converter, the callback must clone - the data and call ucnv_setFromUCallback - (or setToUCallback) with the correct pointer. - @stable ICU 2.2 - */ -} UConverterCallbackReason; - - -/** - * The structure for the fromUnicode callback function parameter. - * @stable ICU 2.0 - */ -typedef struct { - uint16_t size; /**< The size of this struct. @stable ICU 2.0 */ - UBool flush; /**< The internal state of converter will be reset and data flushed if set to TRUE. @stable ICU 2.0 */ - UConverter *converter; /**< Pointer to the converter that is opened and to which this struct is passed as an argument. @stable ICU 2.0 */ - const UChar *source; /**< Pointer to the source source buffer. @stable ICU 2.0 */ - const UChar *sourceLimit; /**< Pointer to the limit (end + 1) of source buffer. @stable ICU 2.0 */ - char *target; /**< Pointer to the target buffer. @stable ICU 2.0 */ - const char *targetLimit; /**< Pointer to the limit (end + 1) of target buffer. @stable ICU 2.0 */ - int32_t *offsets; /**< Pointer to the buffer that recieves the offsets. *offset = blah ; offset++;. @stable ICU 2.0 */ -} UConverterFromUnicodeArgs; - - -/** - * The structure for the toUnicode callback function parameter. - * @stable ICU 2.0 - */ -typedef struct { - uint16_t size; /**< The size of this struct @stable ICU 2.0 */ - UBool flush; /**< The internal state of converter will be reset and data flushed if set to TRUE. @stable ICU 2.0 */ - UConverter *converter; /**< Pointer to the converter that is opened and to which this struct is passed as an argument. @stable ICU 2.0 */ - const char *source; /**< Pointer to the source source buffer. @stable ICU 2.0 */ - const char *sourceLimit; /**< Pointer to the limit (end + 1) of source buffer. @stable ICU 2.0 */ - UChar *target; /**< Pointer to the target buffer. @stable ICU 2.0 */ - const UChar *targetLimit; /**< Pointer to the limit (end + 1) of target buffer. @stable ICU 2.0 */ - int32_t *offsets; /**< Pointer to the buffer that recieves the offsets. *offset = blah ; offset++;. @stable ICU 2.0 */ -} UConverterToUnicodeArgs; - - -/** - * DO NOT CALL THIS FUNCTION DIRECTLY! - * This From Unicode callback STOPS at the ILLEGAL_SEQUENCE, - * returning the error code back to the caller immediately. - * - * @param context Pointer to the callback's private data - * @param fromUArgs Information about the conversion in progress - * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence - * @param length Size (in bytes) of the concerned codepage sequence - * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint. - * @param reason Defines the reason the callback was invoked - * @param err This should always be set to a failure status prior to calling. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_STOP ( - const void *context, - UConverterFromUnicodeArgs *fromUArgs, - const UChar* codeUnits, - int32_t length, - UChar32 codePoint, - UConverterCallbackReason reason, - UErrorCode * err); - - - -/** - * DO NOT CALL THIS FUNCTION DIRECTLY! - * This To Unicode callback STOPS at the ILLEGAL_SEQUENCE, - * returning the error code back to the caller immediately. - * - * @param context Pointer to the callback's private data - * @param toUArgs Information about the conversion in progress - * @param codeUnits Points to 'length' bytes of the concerned codepage sequence - * @param length Size (in bytes) of the concerned codepage sequence - * @param reason Defines the reason the callback was invoked - * @param err This should always be set to a failure status prior to calling. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_STOP ( - const void *context, - UConverterToUnicodeArgs *toUArgs, - const char* codeUnits, - int32_t length, - UConverterCallbackReason reason, - UErrorCode * err); - -/** - * DO NOT CALL THIS FUNCTION DIRECTLY! - * This From Unicode callback skips any ILLEGAL_SEQUENCE, or - * skips only UNASSINGED_SEQUENCE depending on the context parameter - * simply ignoring those characters. - * - * @param context The function currently recognizes the callback options: - * UCNV_SKIP_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE, - * returning the error code back to the caller immediately. - * NULL: Skips any ILLEGAL_SEQUENCE - * @param fromUArgs Information about the conversion in progress - * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence - * @param length Size (in bytes) of the concerned codepage sequence - * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint. - * @param reason Defines the reason the callback was invoked - * @param err Return value will be set to success if the callback was handled, - * otherwise this value will be set to a failure status. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_SKIP ( - const void *context, - UConverterFromUnicodeArgs *fromUArgs, - const UChar* codeUnits, - int32_t length, - UChar32 codePoint, - UConverterCallbackReason reason, - UErrorCode * err); - -/** - * DO NOT CALL THIS FUNCTION DIRECTLY! - * This From Unicode callback will Substitute the ILLEGAL SEQUENCE, or - * UNASSIGNED_SEQUENCE depending on context parameter, with the - * current substitution string for the converter. This is the default - * callback. - * - * @param context The function currently recognizes the callback options: - * UCNV_SUB_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE, - * returning the error code back to the caller immediately. - * NULL: Substitutes any ILLEGAL_SEQUENCE - * @param fromUArgs Information about the conversion in progress - * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence - * @param length Size (in bytes) of the concerned codepage sequence - * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint. - * @param reason Defines the reason the callback was invoked - * @param err Return value will be set to success if the callback was handled, - * otherwise this value will be set to a failure status. - * @see ucnv_setSubstChars - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_SUBSTITUTE ( - const void *context, - UConverterFromUnicodeArgs *fromUArgs, - const UChar* codeUnits, - int32_t length, - UChar32 codePoint, - UConverterCallbackReason reason, - UErrorCode * err); - -/** - * DO NOT CALL THIS FUNCTION DIRECTLY! - * This From Unicode callback will Substitute the ILLEGAL SEQUENCE with the - * hexadecimal representation of the illegal codepoints - * - * @param context The function currently recognizes the callback options: - *
    - *
  • UCNV_ESCAPE_ICU: Substitues the ILLEGAL SEQUENCE with the hexadecimal - * representation in the format %UXXXX, e.g. "%uFFFE%u00AC%uC8FE"). - * In the Event the converter doesn't support the characters {%,U}[A-F][0-9], - * it will substitute the illegal sequence with the substitution characters. - * Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as - * %UD84D%UDC56
  • - *
  • UCNV_ESCAPE_JAVA: Substitues the ILLEGAL SEQUENCE with the hexadecimal - * representation in the format \\uXXXX, e.g. "\\uFFFE\\u00AC\\uC8FE"). - * In the Event the converter doesn't support the characters {\,u}[A-F][0-9], - * it will substitute the illegal sequence with the substitution characters. - * Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as - * \\uD84D\\uDC56
  • - *
  • UCNV_ESCAPE_C: Substitues the ILLEGAL SEQUENCE with the hexadecimal - * representation in the format \\uXXXX, e.g. "\\uFFFE\\u00AC\\uC8FE"). - * In the Event the converter doesn't support the characters {\,u,U}[A-F][0-9], - * it will substitute the illegal sequence with the substitution characters. - * Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as - * \\U00023456
  • - *
  • UCNV_ESCAPE_XML_DEC: Substitues the ILLEGAL SEQUENCE with the decimal - * representation in the format \htmlonly&#DDDDDDDD;, e.g. "&#65534;&#172;&#51454;")\endhtmlonly. - * In the Event the converter doesn't support the characters {&,#}[0-9], - * it will substitute the illegal sequence with the substitution characters. - * Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as - * &#144470; and Zero padding is ignored.
  • - *
  • UCNV_ESCAPE_XML_HEX:Substitues the ILLEGAL SEQUENCE with the decimal - * representation in the format \htmlonly&#xXXXX; e.g. "&#xFFFE;&#x00AC;&#xC8FE;")\endhtmlonly. - * In the Event the converter doesn't support the characters {&,#,x}[0-9], - * it will substitute the illegal sequence with the substitution characters. - * Note that codeUnit(32bit int eg: unit of a surrogate pair) is represented as - * \htmlonly&#x23456;\endhtmlonly
  • - *
- * @param fromUArgs Information about the conversion in progress - * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence - * @param length Size (in bytes) of the concerned codepage sequence - * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint. - * @param reason Defines the reason the callback was invoked - * @param err Return value will be set to success if the callback was handled, - * otherwise this value will be set to a failure status. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_ESCAPE ( - const void *context, - UConverterFromUnicodeArgs *fromUArgs, - const UChar* codeUnits, - int32_t length, - UChar32 codePoint, - UConverterCallbackReason reason, - UErrorCode * err); - - -/** - * DO NOT CALL THIS FUNCTION DIRECTLY! - * This To Unicode callback skips any ILLEGAL_SEQUENCE, or - * skips only UNASSINGED_SEQUENCE depending on the context parameter - * simply ignoring those characters. - * - * @param context The function currently recognizes the callback options: - * UCNV_SKIP_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE, - * returning the error code back to the caller immediately. - * NULL: Skips any ILLEGAL_SEQUENCE - * @param toUArgs Information about the conversion in progress - * @param codeUnits Points to 'length' bytes of the concerned codepage sequence - * @param length Size (in bytes) of the concerned codepage sequence - * @param reason Defines the reason the callback was invoked - * @param err Return value will be set to success if the callback was handled, - * otherwise this value will be set to a failure status. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_SKIP ( - const void *context, - UConverterToUnicodeArgs *toUArgs, - const char* codeUnits, - int32_t length, - UConverterCallbackReason reason, - UErrorCode * err); - -/** - * DO NOT CALL THIS FUNCTION DIRECTLY! - * This To Unicode callback will Substitute the ILLEGAL SEQUENCE,or - * UNASSIGNED_SEQUENCE depending on context parameter, with the - * Unicode substitution character, U+FFFD. - * - * @param context The function currently recognizes the callback options: - * UCNV_SUB_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE, - * returning the error code back to the caller immediately. - * NULL: Substitutes any ILLEGAL_SEQUENCE - * @param toUArgs Information about the conversion in progress - * @param codeUnits Points to 'length' bytes of the concerned codepage sequence - * @param length Size (in bytes) of the concerned codepage sequence - * @param reason Defines the reason the callback was invoked - * @param err Return value will be set to success if the callback was handled, - * otherwise this value will be set to a failure status. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_SUBSTITUTE ( - const void *context, - UConverterToUnicodeArgs *toUArgs, - const char* codeUnits, - int32_t length, - UConverterCallbackReason reason, - UErrorCode * err); - -/** - * DO NOT CALL THIS FUNCTION DIRECTLY! - * This To Unicode callback will Substitute the ILLEGAL SEQUENCE with the - * hexadecimal representation of the illegal bytes - * (in the format %XNN, e.g. "%XFF%X0A%XC8%X03"). - * - * @param context This function currently recognizes the callback options: - * UCNV_ESCAPE_ICU, UCNV_ESCAPE_JAVA, UCNV_ESCAPE_C, UCNV_ESCAPE_XML_DEC, - * UCNV_ESCAPE_XML_HEX and UCNV_ESCAPE_UNICODE. - * @param toUArgs Information about the conversion in progress - * @param codeUnits Points to 'length' bytes of the concerned codepage sequence - * @param length Size (in bytes) of the concerned codepage sequence - * @param reason Defines the reason the callback was invoked - * @param err Return value will be set to success if the callback was handled, - * otherwise this value will be set to a failure status. - * @stable ICU 2.0 - */ - -U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_ESCAPE ( - const void *context, - UConverterToUnicodeArgs *toUArgs, - const char* codeUnits, - int32_t length, - UConverterCallbackReason reason, - UErrorCode * err); - -#endif - -#endif - -/*UCNV_ERR_H*/ diff --git a/win32/include/spidermonkey/unicode/ucnvsel.h b/win32/include/spidermonkey/unicode/ucnvsel.h deleted file mode 100755 index 3eed081a..00000000 --- a/win32/include/spidermonkey/unicode/ucnvsel.h +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2008-2011, International Business Machines -* Corporation, Google and others. All Rights Reserved. -* -******************************************************************************* -*/ -/* - * Author : eldawy@google.com (Mohamed Eldawy) - * ucnvsel.h - * - * Purpose: To generate a list of encodings capable of handling - * a given Unicode text - * - * Started 09-April-2008 - */ - -#ifndef __ICU_UCNV_SEL_H__ -#define __ICU_UCNV_SEL_H__ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_CONVERSION - -#include "unicode/uset.h" -#include "unicode/utf16.h" -#include "unicode/uenum.h" -#include "unicode/ucnv.h" -#include "unicode/localpointer.h" - -/** - * \file - * - * A converter selector is built with a set of encoding/charset names - * and given an input string returns the set of names of the - * corresponding converters which can convert the string. - * - * A converter selector can be serialized into a buffer and reopened - * from the serialized form. - */ - -/** - * @{ - * The selector data structure - */ -struct UConverterSelector; -typedef struct UConverterSelector UConverterSelector; -/** @} */ - -/** - * Open a selector. - * If converterListSize is 0, build for all available converters. - * If excludedCodePoints is NULL, don't exclude any code points. - * - * @param converterList a pointer to encoding names needed to be involved. - * Can be NULL if converterListSize==0. - * The list and the names will be cloned, and the caller - * retains ownership of the original. - * @param converterListSize number of encodings in above list. - * If 0, builds a selector for all available converters. - * @param excludedCodePoints a set of code points to be excluded from consideration. - * That is, excluded code points in a string do not change - * the selection result. (They might be handled by a callback.) - * Use NULL to exclude nothing. - * @param whichSet what converter set to use? Use this to determine whether - * to consider only roundtrip mappings or also fallbacks. - * @param status an in/out ICU UErrorCode - * @return the new selector - * - * @stable ICU 4.2 - */ -U_STABLE UConverterSelector* U_EXPORT2 -ucnvsel_open(const char* const* converterList, int32_t converterListSize, - const USet* excludedCodePoints, - const UConverterUnicodeSet whichSet, UErrorCode* status); - -/** - * Closes a selector. - * If any Enumerations were returned by ucnv_select*, they become invalid. - * They can be closed before or after calling ucnv_closeSelector, - * but should never be used after the selector is closed. - * - * @see ucnv_selectForString - * @see ucnv_selectForUTF8 - * - * @param sel selector to close - * - * @stable ICU 4.2 - */ -U_STABLE void U_EXPORT2 -ucnvsel_close(UConverterSelector *sel); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUConverterSelectorPointer - * "Smart pointer" class, closes a UConverterSelector via ucnvsel_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUConverterSelectorPointer, UConverterSelector, ucnvsel_close); - -U_NAMESPACE_END - -#endif - -/** - * Open a selector from its serialized form. - * The buffer must remain valid and unchanged for the lifetime of the selector. - * This is much faster than creating a selector from scratch. - * Using a serialized form from a different machine (endianness/charset) is supported. - * - * @param buffer pointer to the serialized form of a converter selector; - * must be 32-bit-aligned - * @param length the capacity of this buffer (can be equal to or larger than - * the actual data length) - * @param status an in/out ICU UErrorCode - * @return the new selector - * - * @stable ICU 4.2 - */ -U_STABLE UConverterSelector* U_EXPORT2 -ucnvsel_openFromSerialized(const void* buffer, int32_t length, UErrorCode* status); - -/** - * Serialize a selector into a linear buffer. - * The serialized form is portable to different machines. - * - * @param sel selector to consider - * @param buffer pointer to 32-bit-aligned memory to be filled with the - * serialized form of this converter selector - * @param bufferCapacity the capacity of this buffer - * @param status an in/out ICU UErrorCode - * @return the required buffer capacity to hold serialize data (even if the call fails - * with a U_BUFFER_OVERFLOW_ERROR, it will return the required capacity) - * - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -ucnvsel_serialize(const UConverterSelector* sel, - void* buffer, int32_t bufferCapacity, UErrorCode* status); - -/** - * Select converters that can map all characters in a UTF-16 string, - * ignoring the excluded code points. - * - * @param sel a selector - * @param s UTF-16 string - * @param length length of the string, or -1 if NUL-terminated - * @param status an in/out ICU UErrorCode - * @return an enumeration containing encoding names. - * The returned encoding names and their order will be the same as - * supplied when building the selector. - * - * @stable ICU 4.2 - */ -U_STABLE UEnumeration * U_EXPORT2 -ucnvsel_selectForString(const UConverterSelector* sel, - const UChar *s, int32_t length, UErrorCode *status); - -/** - * Select converters that can map all characters in a UTF-8 string, - * ignoring the excluded code points. - * - * @param sel a selector - * @param s UTF-8 string - * @param length length of the string, or -1 if NUL-terminated - * @param status an in/out ICU UErrorCode - * @return an enumeration containing encoding names. - * The returned encoding names and their order will be the same as - * supplied when building the selector. - * - * @stable ICU 4.2 - */ -U_STABLE UEnumeration * U_EXPORT2 -ucnvsel_selectForUTF8(const UConverterSelector* sel, - const char *s, int32_t length, UErrorCode *status); - -#endif /* !UCONFIG_NO_CONVERSION */ - -#endif /* __ICU_UCNV_SEL_H__ */ diff --git a/win32/include/spidermonkey/unicode/ucol.h b/win32/include/spidermonkey/unicode/ucol.h deleted file mode 100755 index eae88f8c..00000000 --- a/win32/include/spidermonkey/unicode/ucol.h +++ /dev/null @@ -1,1497 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (c) 1996-2015, International Business Machines Corporation and others. -* All Rights Reserved. -******************************************************************************* -*/ - -#ifndef UCOL_H -#define UCOL_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_COLLATION - -#include "unicode/unorm.h" -#include "unicode/localpointer.h" -#include "unicode/parseerr.h" -#include "unicode/uloc.h" -#include "unicode/uset.h" -#include "unicode/uscript.h" - -/** - * \file - * \brief C API: Collator - * - *

Collator C API

- * - * The C API for Collator performs locale-sensitive - * string comparison. You use this service to build - * searching and sorting routines for natural language text. - *

- * For more information about the collation service see - * the User Guide. - *

- * Collation service provides correct sorting orders for most locales supported in ICU. - * If specific data for a locale is not available, the orders eventually falls back - * to the CLDR root sort order. - *

- * Sort ordering may be customized by providing your own set of rules. For more on - * this subject see the - * Collation Customization section of the User Guide. - *

- * @see UCollationResult - * @see UNormalizationMode - * @see UCollationStrength - * @see UCollationElements - */ - -/** A collator. -* For usage in C programs. -*/ -struct UCollator; -/** structure representing a collator object instance - * @stable ICU 2.0 - */ -typedef struct UCollator UCollator; - - -/** - * UCOL_LESS is returned if source string is compared to be less than target - * string in the ucol_strcoll() method. - * UCOL_EQUAL is returned if source string is compared to be equal to target - * string in the ucol_strcoll() method. - * UCOL_GREATER is returned if source string is compared to be greater than - * target string in the ucol_strcoll() method. - * @see ucol_strcoll() - *

- * Possible values for a comparison result - * @stable ICU 2.0 - */ -typedef enum { - /** string a == string b */ - UCOL_EQUAL = 0, - /** string a > string b */ - UCOL_GREATER = 1, - /** string a < string b */ - UCOL_LESS = -1 -} UCollationResult ; - - -/** Enum containing attribute values for controling collation behavior. - * Here are all the allowable values. Not every attribute can take every value. The only - * universal value is UCOL_DEFAULT, which resets the attribute value to the predefined - * value for that locale - * @stable ICU 2.0 - */ -typedef enum { - /** accepted by most attributes */ - UCOL_DEFAULT = -1, - - /** Primary collation strength */ - UCOL_PRIMARY = 0, - /** Secondary collation strength */ - UCOL_SECONDARY = 1, - /** Tertiary collation strength */ - UCOL_TERTIARY = 2, - /** Default collation strength */ - UCOL_DEFAULT_STRENGTH = UCOL_TERTIARY, - UCOL_CE_STRENGTH_LIMIT, - /** Quaternary collation strength */ - UCOL_QUATERNARY=3, - /** Identical collation strength */ - UCOL_IDENTICAL=15, - UCOL_STRENGTH_LIMIT, - - /** Turn the feature off - works for UCOL_FRENCH_COLLATION, - UCOL_CASE_LEVEL, UCOL_HIRAGANA_QUATERNARY_MODE - & UCOL_DECOMPOSITION_MODE*/ - UCOL_OFF = 16, - /** Turn the feature on - works for UCOL_FRENCH_COLLATION, - UCOL_CASE_LEVEL, UCOL_HIRAGANA_QUATERNARY_MODE - & UCOL_DECOMPOSITION_MODE*/ - UCOL_ON = 17, - - /** Valid for UCOL_ALTERNATE_HANDLING. Alternate handling will be shifted */ - UCOL_SHIFTED = 20, - /** Valid for UCOL_ALTERNATE_HANDLING. Alternate handling will be non ignorable */ - UCOL_NON_IGNORABLE = 21, - - /** Valid for UCOL_CASE_FIRST - - lower case sorts before upper case */ - UCOL_LOWER_FIRST = 24, - /** upper case sorts before lower case */ - UCOL_UPPER_FIRST = 25, - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UColAttributeValue value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCOL_ATTRIBUTE_VALUE_COUNT -#endif // U_HIDE_DEPRECATED_API -} UColAttributeValue; - -/** - * Enum containing the codes for reordering segments of the collation table that are not script - * codes. These reordering codes are to be used in conjunction with the script codes. - * @see ucol_getReorderCodes - * @see ucol_setReorderCodes - * @see ucol_getEquivalentReorderCodes - * @see UScriptCode - * @stable ICU 4.8 - */ - typedef enum { - /** - * A special reordering code that is used to specify the default - * reordering codes for a locale. - * @stable ICU 4.8 - */ - UCOL_REORDER_CODE_DEFAULT = -1, - /** - * A special reordering code that is used to specify no reordering codes. - * @stable ICU 4.8 - */ - UCOL_REORDER_CODE_NONE = USCRIPT_UNKNOWN, - /** - * A special reordering code that is used to specify all other codes used for - * reordering except for the codes lised as UColReorderCode values and those - * listed explicitly in a reordering. - * @stable ICU 4.8 - */ - UCOL_REORDER_CODE_OTHERS = USCRIPT_UNKNOWN, - /** - * Characters with the space property. - * This is equivalent to the rule value "space". - * @stable ICU 4.8 - */ - UCOL_REORDER_CODE_SPACE = 0x1000, - /** - * The first entry in the enumeration of reordering groups. This is intended for use in - * range checking and enumeration of the reorder codes. - * @stable ICU 4.8 - */ - UCOL_REORDER_CODE_FIRST = UCOL_REORDER_CODE_SPACE, - /** - * Characters with the punctuation property. - * This is equivalent to the rule value "punct". - * @stable ICU 4.8 - */ - UCOL_REORDER_CODE_PUNCTUATION = 0x1001, - /** - * Characters with the symbol property. - * This is equivalent to the rule value "symbol". - * @stable ICU 4.8 - */ - UCOL_REORDER_CODE_SYMBOL = 0x1002, - /** - * Characters with the currency property. - * This is equivalent to the rule value "currency". - * @stable ICU 4.8 - */ - UCOL_REORDER_CODE_CURRENCY = 0x1003, - /** - * Characters with the digit property. - * This is equivalent to the rule value "digit". - * @stable ICU 4.8 - */ - UCOL_REORDER_CODE_DIGIT = 0x1004, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UColReorderCode value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCOL_REORDER_CODE_LIMIT = 0x1005 -#endif // U_HIDE_DEPRECATED_API -} UColReorderCode; - -/** - * Base letter represents a primary difference. Set comparison - * level to UCOL_PRIMARY to ignore secondary and tertiary differences. - * Use this to set the strength of a Collator object. - * Example of primary difference, "abc" < "abd" - * - * Diacritical differences on the same base letter represent a secondary - * difference. Set comparison level to UCOL_SECONDARY to ignore tertiary - * differences. Use this to set the strength of a Collator object. - * Example of secondary difference, "ä" >> "a". - * - * Uppercase and lowercase versions of the same character represents a - * tertiary difference. Set comparison level to UCOL_TERTIARY to include - * all comparison differences. Use this to set the strength of a Collator - * object. - * Example of tertiary difference, "abc" <<< "ABC". - * - * Two characters are considered "identical" when they have the same - * unicode spellings. UCOL_IDENTICAL. - * For example, "ä" == "ä". - * - * UCollationStrength is also used to determine the strength of sort keys - * generated from UCollator objects - * These values can be now found in the UColAttributeValue enum. - * @stable ICU 2.0 - **/ -typedef UColAttributeValue UCollationStrength; - -/** Attributes that collation service understands. All the attributes can take UCOL_DEFAULT - * value, as well as the values specific to each one. - * @stable ICU 2.0 - */ -typedef enum { - /** Attribute for direction of secondary weights - used in Canadian French. - * Acceptable values are UCOL_ON, which results in secondary weights - * being considered backwards and UCOL_OFF which treats secondary - * weights in the order they appear. - * @stable ICU 2.0 - */ - UCOL_FRENCH_COLLATION, - /** Attribute for handling variable elements. - * Acceptable values are UCOL_NON_IGNORABLE (default) - * which treats all the codepoints with non-ignorable - * primary weights in the same way, - * and UCOL_SHIFTED which causes codepoints with primary - * weights that are equal or below the variable top value - * to be ignored on primary level and moved to the quaternary - * level. - * @stable ICU 2.0 - */ - UCOL_ALTERNATE_HANDLING, - /** Controls the ordering of upper and lower case letters. - * Acceptable values are UCOL_OFF (default), which orders - * upper and lower case letters in accordance to their tertiary - * weights, UCOL_UPPER_FIRST which forces upper case letters to - * sort before lower case letters, and UCOL_LOWER_FIRST which does - * the opposite. - * @stable ICU 2.0 - */ - UCOL_CASE_FIRST, - /** Controls whether an extra case level (positioned before the third - * level) is generated or not. Acceptable values are UCOL_OFF (default), - * when case level is not generated, and UCOL_ON which causes the case - * level to be generated. Contents of the case level are affected by - * the value of UCOL_CASE_FIRST attribute. A simple way to ignore - * accent differences in a string is to set the strength to UCOL_PRIMARY - * and enable case level. - * @stable ICU 2.0 - */ - UCOL_CASE_LEVEL, - /** Controls whether the normalization check and necessary normalizations - * are performed. When set to UCOL_OFF (default) no normalization check - * is performed. The correctness of the result is guaranteed only if the - * input data is in so-called FCD form (see users manual for more info). - * When set to UCOL_ON, an incremental check is performed to see whether - * the input data is in the FCD form. If the data is not in the FCD form, - * incremental NFD normalization is performed. - * @stable ICU 2.0 - */ - UCOL_NORMALIZATION_MODE, - /** An alias for UCOL_NORMALIZATION_MODE attribute. - * @stable ICU 2.0 - */ - UCOL_DECOMPOSITION_MODE = UCOL_NORMALIZATION_MODE, - /** The strength attribute. Can be either UCOL_PRIMARY, UCOL_SECONDARY, - * UCOL_TERTIARY, UCOL_QUATERNARY or UCOL_IDENTICAL. The usual strength - * for most locales (except Japanese) is tertiary. - * - * Quaternary strength - * is useful when combined with shifted setting for alternate handling - * attribute and for JIS X 4061 collation, when it is used to distinguish - * between Katakana and Hiragana. - * Otherwise, quaternary level - * is affected only by the number of non-ignorable code points in - * the string. - * - * Identical strength is rarely useful, as it amounts - * to codepoints of the NFD form of the string. - * @stable ICU 2.0 - */ - UCOL_STRENGTH, -#ifndef U_HIDE_DEPRECATED_API - /** When turned on, this attribute positions Hiragana before all - * non-ignorables on quaternary level This is a sneaky way to produce JIS - * sort order. - * - * This attribute was an implementation detail of the CLDR Japanese tailoring. - * Since ICU 50, this attribute is not settable any more via API functions. - * Since CLDR 25/ICU 53, explicit quaternary relations are used - * to achieve the same Japanese sort order. - * - * @deprecated ICU 50 Implementation detail, cannot be set via API, was removed from implementation. - */ - UCOL_HIRAGANA_QUATERNARY_MODE = UCOL_STRENGTH + 1, -#endif /* U_HIDE_DEPRECATED_API */ - /** - * When turned on, this attribute makes - * substrings of digits sort according to their numeric values. - * - * This is a way to get '100' to sort AFTER '2'. Note that the longest - * digit substring that can be treated as a single unit is - * 254 digits (not counting leading zeros). If a digit substring is - * longer than that, the digits beyond the limit will be treated as a - * separate digit substring. - * - * A "digit" in this sense is a code point with General_Category=Nd, - * which does not include circled numbers, roman numerals, etc. - * Only a contiguous digit substring is considered, that is, - * non-negative integers without separators. - * There is no support for plus/minus signs, decimals, exponents, etc. - * - * @stable ICU 2.8 - */ - UCOL_NUMERIC_COLLATION = UCOL_STRENGTH + 2, - - // Do not conditionalize the following with #ifndef U_HIDE_DEPRECATED_API, - // it is needed for layout of RuleBasedCollator object. - /** - * One more than the highest normal UColAttribute value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCOL_ATTRIBUTE_COUNT -} UColAttribute; - -/** Options for retrieving the rule string - * @stable ICU 2.0 - */ -typedef enum { - /** - * Retrieves the tailoring rules only. - * Same as calling the version of getRules() without UColRuleOption. - * @stable ICU 2.0 - */ - UCOL_TAILORING_ONLY, - /** - * Retrieves the "UCA rules" concatenated with the tailoring rules. - * The "UCA rules" are an approximation of the root collator's sort order. - * They are almost never used or useful at runtime and can be removed from the data. - * See http://userguide.icu-project.org/collation/customization#TOC-Building-on-Existing-Locales - * @stable ICU 2.0 - */ - UCOL_FULL_RULES -} UColRuleOption ; - -/** - * Open a UCollator for comparing strings. - * - * For some languages, multiple collation types are available; - * for example, "de@collation=phonebook". - * Starting with ICU 54, collation attributes can be specified via locale keywords as well, - * in the old locale extension syntax ("el@colCaseFirst=upper") - * or in language tag syntax ("el-u-kf-upper"). - * See User Guide: Collation API. - * - * The UCollator pointer is used in all the calls to the Collation - * service. After finished, collator must be disposed of by calling - * {@link #ucol_close }. - * @param loc The locale containing the required collation rules. - * Special values for locales can be passed in - - * if NULL is passed for the locale, the default locale - * collation rules will be used. If empty string ("") or - * "root" are passed, the root collator will be returned. - * @param status A pointer to a UErrorCode to receive any errors - * @return A pointer to a UCollator, or 0 if an error occurred. - * @see ucol_openRules - * @see ucol_safeClone - * @see ucol_close - * @stable ICU 2.0 - */ -U_STABLE UCollator* U_EXPORT2 -ucol_open(const char *loc, UErrorCode *status); - -/** - * Produce a UCollator instance according to the rules supplied. - * The rules are used to change the default ordering, defined in the - * UCA in a process called tailoring. The resulting UCollator pointer - * can be used in the same way as the one obtained by {@link #ucol_strcoll }. - * @param rules A string describing the collation rules. For the syntax - * of the rules please see users guide. - * @param rulesLength The length of rules, or -1 if null-terminated. - * @param normalizationMode The normalization mode: One of - * UCOL_OFF (expect the text to not need normalization), - * UCOL_ON (normalize), or - * UCOL_DEFAULT (set the mode according to the rules) - * @param strength The default collation strength; one of UCOL_PRIMARY, UCOL_SECONDARY, - * UCOL_TERTIARY, UCOL_IDENTICAL,UCOL_DEFAULT_STRENGTH - can be also set in the rules. - * @param parseError A pointer to UParseError to recieve information about errors - * occurred during parsing. This argument can currently be set - * to NULL, but at users own risk. Please provide a real structure. - * @param status A pointer to a UErrorCode to receive any errors - * @return A pointer to a UCollator. It is not guaranteed that NULL be returned in case - * of error - please use status argument to check for errors. - * @see ucol_open - * @see ucol_safeClone - * @see ucol_close - * @stable ICU 2.0 - */ -U_STABLE UCollator* U_EXPORT2 -ucol_openRules( const UChar *rules, - int32_t rulesLength, - UColAttributeValue normalizationMode, - UCollationStrength strength, - UParseError *parseError, - UErrorCode *status); - -#ifndef U_HIDE_DEPRECATED_API -/** - * Open a collator defined by a short form string. - * The structure and the syntax of the string is defined in the "Naming collators" - * section of the users guide: - * http://userguide.icu-project.org/collation/concepts#TOC-Collator-naming-scheme - * Attributes are overriden by the subsequent attributes. So, for "S2_S3", final - * strength will be 3. 3066bis locale overrides individual locale parts. - * The call to this function is equivalent to a call to ucol_open, followed by a - * series of calls to ucol_setAttribute and ucol_setVariableTop. - * @param definition A short string containing a locale and a set of attributes. - * Attributes not explicitly mentioned are left at the default - * state for a locale. - * @param parseError if not NULL, structure that will get filled with error's pre - * and post context in case of error. - * @param forceDefaults if FALSE, the settings that are the same as the collator - * default settings will not be applied (for example, setting - * French secondary on a French collator would not be executed). - * If TRUE, all the settings will be applied regardless of the - * collator default value. If the definition - * strings are to be cached, should be set to FALSE. - * @param status Error code. Apart from regular error conditions connected to - * instantiating collators (like out of memory or similar), this - * API will return an error if an invalid attribute or attribute/value - * combination is specified. - * @return A pointer to a UCollator or 0 if an error occured (including an - * invalid attribute). - * @see ucol_open - * @see ucol_setAttribute - * @see ucol_setVariableTop - * @see ucol_getShortDefinitionString - * @see ucol_normalizeShortDefinitionString - * @deprecated ICU 54 Use ucol_open() with language tag collation keywords instead. - */ -U_DEPRECATED UCollator* U_EXPORT2 -ucol_openFromShortString( const char *definition, - UBool forceDefaults, - UParseError *parseError, - UErrorCode *status); -#endif /* U_HIDE_DEPRECATED_API */ - -#ifndef U_HIDE_DEPRECATED_API -/** - * Get a set containing the contractions defined by the collator. The set includes - * both the root collator's contractions and the contractions defined by the collator. This set - * will contain only strings. If a tailoring explicitly suppresses contractions from - * the root collator (like Russian), removed contractions will not be in the resulting set. - * @param coll collator - * @param conts the set to hold the result. It gets emptied before - * contractions are added. - * @param status to hold the error code - * @return the size of the contraction set - * - * @deprecated ICU 3.4, use ucol_getContractionsAndExpansions instead - */ -U_DEPRECATED int32_t U_EXPORT2 -ucol_getContractions( const UCollator *coll, - USet *conts, - UErrorCode *status); -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * Get a set containing the expansions defined by the collator. The set includes - * both the root collator's expansions and the expansions defined by the tailoring - * @param coll collator - * @param contractions if not NULL, the set to hold the contractions - * @param expansions if not NULL, the set to hold the expansions - * @param addPrefixes add the prefix contextual elements to contractions - * @param status to hold the error code - * - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -ucol_getContractionsAndExpansions( const UCollator *coll, - USet *contractions, USet *expansions, - UBool addPrefixes, UErrorCode *status); - -/** - * Close a UCollator. - * Once closed, a UCollator should not be used. Every open collator should - * be closed. Otherwise, a memory leak will result. - * @param coll The UCollator to close. - * @see ucol_open - * @see ucol_openRules - * @see ucol_safeClone - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucol_close(UCollator *coll); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUCollatorPointer - * "Smart pointer" class, closes a UCollator via ucol_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUCollatorPointer, UCollator, ucol_close); - -U_NAMESPACE_END - -#endif - -/** - * Compare two strings. - * The strings will be compared using the options already specified. - * @param coll The UCollator containing the comparison rules. - * @param source The source string. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param target The target string. - * @param targetLength The length of target, or -1 if null-terminated. - * @return The result of comparing the strings; one of UCOL_EQUAL, - * UCOL_GREATER, UCOL_LESS - * @see ucol_greater - * @see ucol_greaterOrEqual - * @see ucol_equal - * @stable ICU 2.0 - */ -U_STABLE UCollationResult U_EXPORT2 -ucol_strcoll( const UCollator *coll, - const UChar *source, - int32_t sourceLength, - const UChar *target, - int32_t targetLength); - -/** -* Compare two strings in UTF-8. -* The strings will be compared using the options already specified. -* Note: When input string contains malformed a UTF-8 byte sequence, -* this function treats these bytes as REPLACEMENT CHARACTER (U+FFFD). -* @param coll The UCollator containing the comparison rules. -* @param source The source UTF-8 string. -* @param sourceLength The length of source, or -1 if null-terminated. -* @param target The target UTF-8 string. -* @param targetLength The length of target, or -1 if null-terminated. -* @param status A pointer to a UErrorCode to receive any errors -* @return The result of comparing the strings; one of UCOL_EQUAL, -* UCOL_GREATER, UCOL_LESS -* @see ucol_greater -* @see ucol_greaterOrEqual -* @see ucol_equal -* @stable ICU 50 -*/ -U_STABLE UCollationResult U_EXPORT2 -ucol_strcollUTF8( - const UCollator *coll, - const char *source, - int32_t sourceLength, - const char *target, - int32_t targetLength, - UErrorCode *status); - -/** - * Determine if one string is greater than another. - * This function is equivalent to {@link #ucol_strcoll } == UCOL_GREATER - * @param coll The UCollator containing the comparison rules. - * @param source The source string. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param target The target string. - * @param targetLength The length of target, or -1 if null-terminated. - * @return TRUE if source is greater than target, FALSE otherwise. - * @see ucol_strcoll - * @see ucol_greaterOrEqual - * @see ucol_equal - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -ucol_greater(const UCollator *coll, - const UChar *source, int32_t sourceLength, - const UChar *target, int32_t targetLength); - -/** - * Determine if one string is greater than or equal to another. - * This function is equivalent to {@link #ucol_strcoll } != UCOL_LESS - * @param coll The UCollator containing the comparison rules. - * @param source The source string. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param target The target string. - * @param targetLength The length of target, or -1 if null-terminated. - * @return TRUE if source is greater than or equal to target, FALSE otherwise. - * @see ucol_strcoll - * @see ucol_greater - * @see ucol_equal - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -ucol_greaterOrEqual(const UCollator *coll, - const UChar *source, int32_t sourceLength, - const UChar *target, int32_t targetLength); - -/** - * Compare two strings for equality. - * This function is equivalent to {@link #ucol_strcoll } == UCOL_EQUAL - * @param coll The UCollator containing the comparison rules. - * @param source The source string. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param target The target string. - * @param targetLength The length of target, or -1 if null-terminated. - * @return TRUE if source is equal to target, FALSE otherwise - * @see ucol_strcoll - * @see ucol_greater - * @see ucol_greaterOrEqual - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -ucol_equal(const UCollator *coll, - const UChar *source, int32_t sourceLength, - const UChar *target, int32_t targetLength); - -/** - * Compare two UTF-8 encoded trings. - * The strings will be compared using the options already specified. - * @param coll The UCollator containing the comparison rules. - * @param sIter The source string iterator. - * @param tIter The target string iterator. - * @return The result of comparing the strings; one of UCOL_EQUAL, - * UCOL_GREATER, UCOL_LESS - * @param status A pointer to a UErrorCode to receive any errors - * @see ucol_strcoll - * @stable ICU 2.6 - */ -U_STABLE UCollationResult U_EXPORT2 -ucol_strcollIter( const UCollator *coll, - UCharIterator *sIter, - UCharIterator *tIter, - UErrorCode *status); - -/** - * Get the collation strength used in a UCollator. - * The strength influences how strings are compared. - * @param coll The UCollator to query. - * @return The collation strength; one of UCOL_PRIMARY, UCOL_SECONDARY, - * UCOL_TERTIARY, UCOL_QUATERNARY, UCOL_IDENTICAL - * @see ucol_setStrength - * @stable ICU 2.0 - */ -U_STABLE UCollationStrength U_EXPORT2 -ucol_getStrength(const UCollator *coll); - -/** - * Set the collation strength used in a UCollator. - * The strength influences how strings are compared. - * @param coll The UCollator to set. - * @param strength The desired collation strength; one of UCOL_PRIMARY, - * UCOL_SECONDARY, UCOL_TERTIARY, UCOL_QUATERNARY, UCOL_IDENTICAL, UCOL_DEFAULT - * @see ucol_getStrength - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucol_setStrength(UCollator *coll, - UCollationStrength strength); - -/** - * Retrieves the reordering codes for this collator. - * These reordering codes are a combination of UScript codes and UColReorderCode entries. - * @param coll The UCollator to query. - * @param dest The array to fill with the script ordering. - * @param destCapacity The length of dest. If it is 0, then dest may be NULL and the function - * will only return the length of the result without writing any codes (pre-flighting). - * @param pErrorCode Must be a valid pointer to an error code value, which must not indicate a - * failure before the function call. - * @return The number of reordering codes written to the dest array. - * @see ucol_setReorderCodes - * @see ucol_getEquivalentReorderCodes - * @see UScriptCode - * @see UColReorderCode - * @stable ICU 4.8 - */ -U_STABLE int32_t U_EXPORT2 -ucol_getReorderCodes(const UCollator* coll, - int32_t* dest, - int32_t destCapacity, - UErrorCode *pErrorCode); -/** - * Sets the reordering codes for this collator. - * Collation reordering allows scripts and some other groups of characters - * to be moved relative to each other. This reordering is done on top of - * the DUCET/CLDR standard collation order. Reordering can specify groups to be placed - * at the start and/or the end of the collation order. These groups are specified using - * UScript codes and UColReorderCode entries. - * - *

By default, reordering codes specified for the start of the order are placed in the - * order given after several special non-script blocks. These special groups of characters - * are space, punctuation, symbol, currency, and digit. These special groups are represented with - * UColReorderCode entries. Script groups can be intermingled with - * these special non-script groups if those special groups are explicitly specified in the reordering. - * - *

The special code OTHERS stands for any script that is not explicitly - * mentioned in the list of reordering codes given. Anything that is after OTHERS - * will go at the very end of the reordering in the order given. - * - *

The special reorder code DEFAULT will reset the reordering for this collator - * to the default for this collator. The default reordering may be the DUCET/CLDR order or may be a reordering that - * was specified when this collator was created from resource data or from rules. The - * DEFAULT code must be the sole code supplied when it is used. - * If not, then U_ILLEGAL_ARGUMENT_ERROR will be set. - * - *

The special reorder code NONE will remove any reordering for this collator. - * The result of setting no reordering will be to have the DUCET/CLDR ordering used. The - * NONE code must be the sole code supplied when it is used. - * - * @param coll The UCollator to set. - * @param reorderCodes An array of script codes in the new order. This can be NULL if the - * length is also set to 0. An empty array will clear any reordering codes on the collator. - * @param reorderCodesLength The length of reorderCodes. - * @param pErrorCode Must be a valid pointer to an error code value, which must not indicate a - * failure before the function call. - * @see ucol_getReorderCodes - * @see ucol_getEquivalentReorderCodes - * @see UScriptCode - * @see UColReorderCode - * @stable ICU 4.8 - */ -U_STABLE void U_EXPORT2 -ucol_setReorderCodes(UCollator* coll, - const int32_t* reorderCodes, - int32_t reorderCodesLength, - UErrorCode *pErrorCode); - -/** - * Retrieves the reorder codes that are grouped with the given reorder code. Some reorder - * codes will be grouped and must reorder together. - * Beginning with ICU 55, scripts only reorder together if they are primary-equal, - * for example Hiragana and Katakana. - * - * @param reorderCode The reorder code to determine equivalence for. - * @param dest The array to fill with the script ordering. - * @param destCapacity The length of dest. If it is 0, then dest may be NULL and the function - * will only return the length of the result without writing any codes (pre-flighting). - * @param pErrorCode Must be a valid pointer to an error code value, which must not indicate - * a failure before the function call. - * @return The number of reordering codes written to the dest array. - * @see ucol_setReorderCodes - * @see ucol_getReorderCodes - * @see UScriptCode - * @see UColReorderCode - * @stable ICU 4.8 - */ -U_STABLE int32_t U_EXPORT2 -ucol_getEquivalentReorderCodes(int32_t reorderCode, - int32_t* dest, - int32_t destCapacity, - UErrorCode *pErrorCode); - -/** - * Get the display name for a UCollator. - * The display name is suitable for presentation to a user. - * @param objLoc The locale of the collator in question. - * @param dispLoc The locale for display. - * @param result A pointer to a buffer to receive the attribute. - * @param resultLength The maximum size of result. - * @param status A pointer to a UErrorCode to receive any errors - * @return The total buffer size needed; if greater than resultLength, - * the output was truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucol_getDisplayName( const char *objLoc, - const char *dispLoc, - UChar *result, - int32_t resultLength, - UErrorCode *status); - -/** - * Get a locale for which collation rules are available. - * A UCollator in a locale returned by this function will perform the correct - * collation for the locale. - * @param localeIndex The index of the desired locale. - * @return A locale for which collation rules are available, or 0 if none. - * @see ucol_countAvailable - * @stable ICU 2.0 - */ -U_STABLE const char* U_EXPORT2 -ucol_getAvailable(int32_t localeIndex); - -/** - * Determine how many locales have collation rules available. - * This function is most useful as determining the loop ending condition for - * calls to {@link #ucol_getAvailable }. - * @return The number of locales for which collation rules are available. - * @see ucol_getAvailable - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucol_countAvailable(void); - -#if !UCONFIG_NO_SERVICE -/** - * Create a string enumerator of all locales for which a valid - * collator may be opened. - * @param status input-output error code - * @return a string enumeration over locale strings. The caller is - * responsible for closing the result. - * @stable ICU 3.0 - */ -U_STABLE UEnumeration* U_EXPORT2 -ucol_openAvailableLocales(UErrorCode *status); -#endif - -/** - * Create a string enumerator of all possible keywords that are relevant to - * collation. At this point, the only recognized keyword for this - * service is "collation". - * @param status input-output error code - * @return a string enumeration over locale strings. The caller is - * responsible for closing the result. - * @stable ICU 3.0 - */ -U_STABLE UEnumeration* U_EXPORT2 -ucol_getKeywords(UErrorCode *status); - -/** - * Given a keyword, create a string enumeration of all values - * for that keyword that are currently in use. - * @param keyword a particular keyword as enumerated by - * ucol_getKeywords. If any other keyword is passed in, *status is set - * to U_ILLEGAL_ARGUMENT_ERROR. - * @param status input-output error code - * @return a string enumeration over collation keyword values, or NULL - * upon error. The caller is responsible for closing the result. - * @stable ICU 3.0 - */ -U_STABLE UEnumeration* U_EXPORT2 -ucol_getKeywordValues(const char *keyword, UErrorCode *status); - -/** - * Given a key and a locale, returns an array of string values in a preferred - * order that would make a difference. These are all and only those values where - * the open (creation) of the service with the locale formed from the input locale - * plus input keyword and that value has different behavior than creation with the - * input locale alone. - * @param key one of the keys supported by this service. For now, only - * "collation" is supported. - * @param locale the locale - * @param commonlyUsed if set to true it will return only commonly used values - * with the given locale in preferred order. Otherwise, - * it will return all the available values for the locale. - * @param status error status - * @return a string enumeration over keyword values for the given key and the locale. - * @stable ICU 4.2 - */ -U_STABLE UEnumeration* U_EXPORT2 -ucol_getKeywordValuesForLocale(const char* key, - const char* locale, - UBool commonlyUsed, - UErrorCode* status); - -/** - * Return the functionally equivalent locale for the specified - * input locale, with respect to given keyword, for the - * collation service. If two different input locale + keyword - * combinations produce the same result locale, then collators - * instantiated for these two different input locales will behave - * equivalently. The converse is not always true; two collators - * may in fact be equivalent, but return different results, due to - * internal details. The return result has no other meaning than - * that stated above, and implies nothing as to the relationship - * between the two locales. This is intended for use by - * applications who wish to cache collators, or otherwise reuse - * collators when possible. The functional equivalent may change - * over time. For more information, please see the - * Locales and Services section of the ICU User Guide. - * @param result fillin for the functionally equivalent result locale - * @param resultCapacity capacity of the fillin buffer - * @param keyword a particular keyword as enumerated by - * ucol_getKeywords. - * @param locale the specified input locale - * @param isAvailable if non-NULL, pointer to a fillin parameter that - * on return indicates whether the specified input locale was 'available' - * to the collation service. A locale is defined as 'available' if it - * physically exists within the collation locale data. - * @param status pointer to input-output error code - * @return the actual buffer size needed for the locale. If greater - * than resultCapacity, the returned full name will be truncated and - * an error code will be returned. - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -ucol_getFunctionalEquivalent(char* result, int32_t resultCapacity, - const char* keyword, const char* locale, - UBool* isAvailable, UErrorCode* status); - -/** - * Get the collation tailoring rules from a UCollator. - * The rules will follow the rule syntax. - * @param coll The UCollator to query. - * @param length - * @return The collation tailoring rules. - * @stable ICU 2.0 - */ -U_STABLE const UChar* U_EXPORT2 -ucol_getRules( const UCollator *coll, - int32_t *length); - -#ifndef U_HIDE_DEPRECATED_API -/** Get the short definition string for a collator. This API harvests the collator's - * locale and the attribute set and produces a string that can be used for opening - * a collator with the same attributes using the ucol_openFromShortString API. - * This string will be normalized. - * The structure and the syntax of the string is defined in the "Naming collators" - * section of the users guide: - * http://userguide.icu-project.org/collation/concepts#TOC-Collator-naming-scheme - * This API supports preflighting. - * @param coll a collator - * @param locale a locale that will appear as a collators locale in the resulting - * short string definition. If NULL, the locale will be harvested - * from the collator. - * @param buffer space to hold the resulting string - * @param capacity capacity of the buffer - * @param status for returning errors. All the preflighting errors are featured - * @return length of the resulting string - * @see ucol_openFromShortString - * @see ucol_normalizeShortDefinitionString - * @deprecated ICU 54 - */ -U_DEPRECATED int32_t U_EXPORT2 -ucol_getShortDefinitionString(const UCollator *coll, - const char *locale, - char *buffer, - int32_t capacity, - UErrorCode *status); - -/** Verifies and normalizes short definition string. - * Normalized short definition string has all the option sorted by the argument name, - * so that equivalent definition strings are the same. - * This API supports preflighting. - * @param source definition string - * @param destination space to hold the resulting string - * @param capacity capacity of the buffer - * @param parseError if not NULL, structure that will get filled with error's pre - * and post context in case of error. - * @param status Error code. This API will return an error if an invalid attribute - * or attribute/value combination is specified. All the preflighting - * errors are also featured - * @return length of the resulting normalized string. - * - * @see ucol_openFromShortString - * @see ucol_getShortDefinitionString - * - * @deprecated ICU 54 - */ - -U_DEPRECATED int32_t U_EXPORT2 -ucol_normalizeShortDefinitionString(const char *source, - char *destination, - int32_t capacity, - UParseError *parseError, - UErrorCode *status); -#endif /* U_HIDE_DEPRECATED_API */ - - -/** - * Get a sort key for a string from a UCollator. - * Sort keys may be compared using strcmp. - * - * Note that sort keys are often less efficient than simply doing comparison. - * For more details, see the ICU User Guide. - * - * Like ICU functions that write to an output buffer, the buffer contents - * is undefined if the buffer capacity (resultLength parameter) is too small. - * Unlike ICU functions that write a string to an output buffer, - * the terminating zero byte is counted in the sort key length. - * @param coll The UCollator containing the collation rules. - * @param source The string to transform. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param result A pointer to a buffer to receive the attribute. - * @param resultLength The maximum size of result. - * @return The size needed to fully store the sort key. - * If there was an internal error generating the sort key, - * a zero value is returned. - * @see ucol_keyHashCode - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucol_getSortKey(const UCollator *coll, - const UChar *source, - int32_t sourceLength, - uint8_t *result, - int32_t resultLength); - - -/** Gets the next count bytes of a sort key. Caller needs - * to preserve state array between calls and to provide - * the same type of UCharIterator set with the same string. - * The destination buffer provided must be big enough to store - * the number of requested bytes. - * - * The generated sort key may or may not be compatible with - * sort keys generated using ucol_getSortKey(). - * @param coll The UCollator containing the collation rules. - * @param iter UCharIterator containing the string we need - * the sort key to be calculated for. - * @param state Opaque state of sortkey iteration. - * @param dest Buffer to hold the resulting sortkey part - * @param count number of sort key bytes required. - * @param status error code indicator. - * @return the actual number of bytes of a sortkey. It can be - * smaller than count if we have reached the end of - * the sort key. - * @stable ICU 2.6 - */ -U_STABLE int32_t U_EXPORT2 -ucol_nextSortKeyPart(const UCollator *coll, - UCharIterator *iter, - uint32_t state[2], - uint8_t *dest, int32_t count, - UErrorCode *status); - -/** enum that is taken by ucol_getBound API - * See below for explanation - * do not change the values assigned to the - * members of this enum. Underlying code - * depends on them having these numbers - * @stable ICU 2.0 - */ -typedef enum { - /** lower bound */ - UCOL_BOUND_LOWER = 0, - /** upper bound that will match strings of exact size */ - UCOL_BOUND_UPPER = 1, - /** upper bound that will match all the strings that have the same initial substring as the given string */ - UCOL_BOUND_UPPER_LONG = 2, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UColBoundMode value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCOL_BOUND_VALUE_COUNT -#endif // U_HIDE_DEPRECATED_API -} UColBoundMode; - -/** - * Produce a bound for a given sortkey and a number of levels. - * Return value is always the number of bytes needed, regardless of - * whether the result buffer was big enough or even valid.
- * Resulting bounds can be used to produce a range of strings that are - * between upper and lower bounds. For example, if bounds are produced - * for a sortkey of string "smith", strings between upper and lower - * bounds with one level would include "Smith", "SMITH", "sMiTh".
- * There are two upper bounds that can be produced. If UCOL_BOUND_UPPER - * is produced, strings matched would be as above. However, if bound - * produced using UCOL_BOUND_UPPER_LONG is used, the above example will - * also match "Smithsonian" and similar.
- * For more on usage, see example in cintltst/capitst.c in procedure - * TestBounds. - * Sort keys may be compared using strcmp. - * @param source The source sortkey. - * @param sourceLength The length of source, or -1 if null-terminated. - * (If an unmodified sortkey is passed, it is always null - * terminated). - * @param boundType Type of bound required. It can be UCOL_BOUND_LOWER, which - * produces a lower inclusive bound, UCOL_BOUND_UPPER, that - * produces upper bound that matches strings of the same length - * or UCOL_BOUND_UPPER_LONG that matches strings that have the - * same starting substring as the source string. - * @param noOfLevels Number of levels required in the resulting bound (for most - * uses, the recommended value is 1). See users guide for - * explanation on number of levels a sortkey can have. - * @param result A pointer to a buffer to receive the resulting sortkey. - * @param resultLength The maximum size of result. - * @param status Used for returning error code if something went wrong. If the - * number of levels requested is higher than the number of levels - * in the source key, a warning (U_SORT_KEY_TOO_SHORT_WARNING) is - * issued. - * @return The size needed to fully store the bound. - * @see ucol_keyHashCode - * @stable ICU 2.1 - */ -U_STABLE int32_t U_EXPORT2 -ucol_getBound(const uint8_t *source, - int32_t sourceLength, - UColBoundMode boundType, - uint32_t noOfLevels, - uint8_t *result, - int32_t resultLength, - UErrorCode *status); - -/** - * Gets the version information for a Collator. Version is currently - * an opaque 32-bit number which depends, among other things, on major - * versions of the collator tailoring and UCA. - * @param coll The UCollator to query. - * @param info the version # information, the result will be filled in - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucol_getVersion(const UCollator* coll, UVersionInfo info); - -/** - * Gets the UCA version information for a Collator. Version is the - * UCA version number (3.1.1, 4.0). - * @param coll The UCollator to query. - * @param info the version # information, the result will be filled in - * @stable ICU 2.8 - */ -U_STABLE void U_EXPORT2 -ucol_getUCAVersion(const UCollator* coll, UVersionInfo info); - -/** - * Merges two sort keys. The levels are merged with their corresponding counterparts - * (primaries with primaries, secondaries with secondaries etc.). Between the values - * from the same level a separator is inserted. - * - * This is useful, for example, for combining sort keys from first and last names - * to sort such pairs. - * See http://www.unicode.org/reports/tr10/#Merging_Sort_Keys - * - * The recommended way to achieve "merged" sorting is by - * concatenating strings with U+FFFE between them. - * The concatenation has the same sort order as the merged sort keys, - * but merge(getSortKey(str1), getSortKey(str2)) may differ from getSortKey(str1 + '\uFFFE' + str2). - * Using strings with U+FFFE may yield shorter sort keys. - * - * For details about Sort Key Features see - * http://userguide.icu-project.org/collation/api#TOC-Sort-Key-Features - * - * It is possible to merge multiple sort keys by consecutively merging - * another one with the intermediate result. - * - * The length of the merge result is the sum of the lengths of the input sort keys. - * - * Example (uncompressed): - *

191B1D 01 050505 01 910505 00
- * 1F2123 01 050505 01 910505 00
- * will be merged as - *
191B1D 02 1F2123 01 050505 02 050505 01 910505 02 910505 00
- * - * If the destination buffer is not big enough, then its contents are undefined. - * If any of source lengths are zero or any of the source pointers are NULL/undefined, - * the result is of size zero. - * - * @param src1 the first sort key - * @param src1Length the length of the first sort key, including the zero byte at the end; - * can be -1 if the function is to find the length - * @param src2 the second sort key - * @param src2Length the length of the second sort key, including the zero byte at the end; - * can be -1 if the function is to find the length - * @param dest the buffer where the merged sort key is written, - * can be NULL if destCapacity==0 - * @param destCapacity the number of bytes in the dest buffer - * @return the length of the merged sort key, src1Length+src2Length; - * can be larger than destCapacity, or 0 if an error occurs (only for illegal arguments), - * in which cases the contents of dest is undefined - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucol_mergeSortkeys(const uint8_t *src1, int32_t src1Length, - const uint8_t *src2, int32_t src2Length, - uint8_t *dest, int32_t destCapacity); - -/** - * Universal attribute setter - * @param coll collator which attributes are to be changed - * @param attr attribute type - * @param value attribute value - * @param status to indicate whether the operation went on smoothly or there were errors - * @see UColAttribute - * @see UColAttributeValue - * @see ucol_getAttribute - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucol_setAttribute(UCollator *coll, UColAttribute attr, UColAttributeValue value, UErrorCode *status); - -/** - * Universal attribute getter - * @param coll collator which attributes are to be changed - * @param attr attribute type - * @return attribute value - * @param status to indicate whether the operation went on smoothly or there were errors - * @see UColAttribute - * @see UColAttributeValue - * @see ucol_setAttribute - * @stable ICU 2.0 - */ -U_STABLE UColAttributeValue U_EXPORT2 -ucol_getAttribute(const UCollator *coll, UColAttribute attr, UErrorCode *status); - -/** - * Sets the variable top to the top of the specified reordering group. - * The variable top determines the highest-sorting character - * which is affected by UCOL_ALTERNATE_HANDLING. - * If that attribute is set to UCOL_NON_IGNORABLE, then the variable top has no effect. - * @param coll the collator - * @param group one of UCOL_REORDER_CODE_SPACE, UCOL_REORDER_CODE_PUNCTUATION, - * UCOL_REORDER_CODE_SYMBOL, UCOL_REORDER_CODE_CURRENCY; - * or UCOL_REORDER_CODE_DEFAULT to restore the default max variable group - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @see ucol_getMaxVariable - * @stable ICU 53 - */ -U_STABLE void U_EXPORT2 -ucol_setMaxVariable(UCollator *coll, UColReorderCode group, UErrorCode *pErrorCode); - -/** - * Returns the maximum reordering group whose characters are affected by UCOL_ALTERNATE_HANDLING. - * @param coll the collator - * @return the maximum variable reordering group. - * @see ucol_setMaxVariable - * @stable ICU 53 - */ -U_STABLE UColReorderCode U_EXPORT2 -ucol_getMaxVariable(const UCollator *coll); - -#ifndef U_HIDE_DEPRECATED_API -/** - * Sets the variable top to the primary weight of the specified string. - * - * Beginning with ICU 53, the variable top is pinned to - * the top of one of the supported reordering groups, - * and it must not be beyond the last of those groups. - * See ucol_setMaxVariable(). - * @param coll the collator - * @param varTop one or more (if contraction) UChars to which the variable top should be set - * @param len length of variable top string. If -1 it is considered to be zero terminated. - * @param status error code. If error code is set, the return value is undefined. - * Errors set by this function are:
- * U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such contraction
- * U_ILLEGAL_ARGUMENT_ERROR if the variable top is beyond - * the last reordering group supported by ucol_setMaxVariable() - * @return variable top primary weight - * @see ucol_getVariableTop - * @see ucol_restoreVariableTop - * @deprecated ICU 53 Call ucol_setMaxVariable() instead. - */ -U_DEPRECATED uint32_t U_EXPORT2 -ucol_setVariableTop(UCollator *coll, - const UChar *varTop, int32_t len, - UErrorCode *status); -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * Gets the variable top value of a Collator. - * @param coll collator which variable top needs to be retrieved - * @param status error code (not changed by function). If error code is set, - * the return value is undefined. - * @return the variable top primary weight - * @see ucol_getMaxVariable - * @see ucol_setVariableTop - * @see ucol_restoreVariableTop - * @stable ICU 2.0 - */ -U_STABLE uint32_t U_EXPORT2 ucol_getVariableTop(const UCollator *coll, UErrorCode *status); - -#ifndef U_HIDE_DEPRECATED_API -/** - * Sets the variable top to the specified primary weight. - * - * Beginning with ICU 53, the variable top is pinned to - * the top of one of the supported reordering groups, - * and it must not be beyond the last of those groups. - * See ucol_setMaxVariable(). - * @param varTop primary weight, as returned by ucol_setVariableTop or ucol_getVariableTop - * @param status error code - * @see ucol_getVariableTop - * @see ucol_setVariableTop - * @deprecated ICU 53 Call ucol_setMaxVariable() instead. - */ -U_DEPRECATED void U_EXPORT2 -ucol_restoreVariableTop(UCollator *coll, const uint32_t varTop, UErrorCode *status); -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * Thread safe cloning operation. The result is a clone of a given collator. - * @param coll collator to be cloned - * @param stackBuffer Deprecated functionality as of ICU 52, use NULL.
- * user allocated space for the new clone. - * If NULL new memory will be allocated. - * If buffer is not large enough, new memory will be allocated. - * Clients can use the U_COL_SAFECLONE_BUFFERSIZE. - * @param pBufferSize Deprecated functionality as of ICU 52, use NULL or 1.
- * pointer to size of allocated space. - * If *pBufferSize == 0, a sufficient size for use in cloning will - * be returned ('pre-flighting') - * If *pBufferSize is not enough for a stack-based safe clone, - * new memory will be allocated. - * @param status to indicate whether the operation went on smoothly or there were errors - * An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used if any - * allocations were necessary. - * @return pointer to the new clone - * @see ucol_open - * @see ucol_openRules - * @see ucol_close - * @stable ICU 2.0 - */ -U_STABLE UCollator* U_EXPORT2 -ucol_safeClone(const UCollator *coll, - void *stackBuffer, - int32_t *pBufferSize, - UErrorCode *status); - -#ifndef U_HIDE_DEPRECATED_API - -/** default memory size for the new clone. - * @deprecated ICU 52. Do not rely on ucol_safeClone() cloning into any provided buffer. - */ -#define U_COL_SAFECLONE_BUFFERSIZE 1 - -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * Returns current rules. Delta defines whether full rules are returned or just the tailoring. - * Returns number of UChars needed to store rules. If buffer is NULL or bufferLen is not enough - * to store rules, will store up to available space. - * - * ucol_getRules() should normally be used instead. - * See http://userguide.icu-project.org/collation/customization#TOC-Building-on-Existing-Locales - * @param coll collator to get the rules from - * @param delta one of UCOL_TAILORING_ONLY, UCOL_FULL_RULES. - * @param buffer buffer to store the result in. If NULL, you'll get no rules. - * @param bufferLen length of buffer to store rules in. If less than needed you'll get only the part that fits in. - * @return current rules - * @stable ICU 2.0 - * @see UCOL_FULL_RULES - */ -U_STABLE int32_t U_EXPORT2 -ucol_getRulesEx(const UCollator *coll, UColRuleOption delta, UChar *buffer, int32_t bufferLen); - -#ifndef U_HIDE_DEPRECATED_API -/** - * gets the locale name of the collator. If the collator - * is instantiated from the rules, then this function returns - * NULL. - * @param coll The UCollator for which the locale is needed - * @param type You can choose between requested, valid and actual - * locale. For description see the definition of - * ULocDataLocaleType in uloc.h - * @param status error code of the operation - * @return real locale name from which the collation data comes. - * If the collator was instantiated from rules, returns - * NULL. - * @deprecated ICU 2.8 Use ucol_getLocaleByType instead - */ -U_DEPRECATED const char * U_EXPORT2 -ucol_getLocale(const UCollator *coll, ULocDataLocaleType type, UErrorCode *status); -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * gets the locale name of the collator. If the collator - * is instantiated from the rules, then this function returns - * NULL. - * @param coll The UCollator for which the locale is needed - * @param type You can choose between requested, valid and actual - * locale. For description see the definition of - * ULocDataLocaleType in uloc.h - * @param status error code of the operation - * @return real locale name from which the collation data comes. - * If the collator was instantiated from rules, returns - * NULL. - * @stable ICU 2.8 - */ -U_STABLE const char * U_EXPORT2 -ucol_getLocaleByType(const UCollator *coll, ULocDataLocaleType type, UErrorCode *status); - -/** - * Get a Unicode set that contains all the characters and sequences tailored in - * this collator. The result must be disposed of by using uset_close. - * @param coll The UCollator for which we want to get tailored chars - * @param status error code of the operation - * @return a pointer to newly created USet. Must be be disposed by using uset_close - * @see ucol_openRules - * @see uset_close - * @stable ICU 2.4 - */ -U_STABLE USet * U_EXPORT2 -ucol_getTailoredSet(const UCollator *coll, UErrorCode *status); - -#ifndef U_HIDE_INTERNAL_API -/** Calculates the set of unsafe code points, given a collator. - * A character is unsafe if you could append any character and cause the ordering to alter significantly. - * Collation sorts in normalized order, so anything that rearranges in normalization can cause this. - * Thus if you have a character like a_umlaut, and you add a lower_dot to it, - * then it normalizes to a_lower_dot + umlaut, and sorts differently. - * @param coll Collator - * @param unsafe a fill-in set to receive the unsafe points - * @param status for catching errors - * @return number of elements in the set - * @internal ICU 3.0 - */ -U_INTERNAL int32_t U_EXPORT2 -ucol_getUnsafeSet( const UCollator *coll, - USet *unsafe, - UErrorCode *status); - -/** Touches all resources needed for instantiating a collator from a short string definition, - * thus filling up the cache. - * @param definition A short string containing a locale and a set of attributes. - * Attributes not explicitly mentioned are left at the default - * state for a locale. - * @param parseError if not NULL, structure that will get filled with error's pre - * and post context in case of error. - * @param forceDefaults if FALSE, the settings that are the same as the collator - * default settings will not be applied (for example, setting - * French secondary on a French collator would not be executed). - * If TRUE, all the settings will be applied regardless of the - * collator default value. If the definition - * strings are to be cached, should be set to FALSE. - * @param status Error code. Apart from regular error conditions connected to - * instantiating collators (like out of memory or similar), this - * API will return an error if an invalid attribute or attribute/value - * combination is specified. - * @see ucol_openFromShortString - * @internal ICU 3.2.1 - */ -U_INTERNAL void U_EXPORT2 -ucol_prepareShortStringOpen( const char *definition, - UBool forceDefaults, - UParseError *parseError, - UErrorCode *status); -#endif /* U_HIDE_INTERNAL_API */ - -/** Creates a binary image of a collator. This binary image can be stored and - * later used to instantiate a collator using ucol_openBinary. - * This API supports preflighting. - * @param coll Collator - * @param buffer a fill-in buffer to receive the binary image - * @param capacity capacity of the destination buffer - * @param status for catching errors - * @return size of the image - * @see ucol_openBinary - * @stable ICU 3.2 - */ -U_STABLE int32_t U_EXPORT2 -ucol_cloneBinary(const UCollator *coll, - uint8_t *buffer, int32_t capacity, - UErrorCode *status); - -/** Opens a collator from a collator binary image created using - * ucol_cloneBinary. Binary image used in instantiation of the - * collator remains owned by the user and should stay around for - * the lifetime of the collator. The API also takes a base collator - * which must be the root collator. - * @param bin binary image owned by the user and required through the - * lifetime of the collator - * @param length size of the image. If negative, the API will try to - * figure out the length of the image - * @param base Base collator, for lookup of untailored characters. - * Must be the root collator, must not be NULL. - * The base is required to be present through the lifetime of the collator. - * @param status for catching errors - * @return newly created collator - * @see ucol_cloneBinary - * @stable ICU 3.2 - */ -U_STABLE UCollator* U_EXPORT2 -ucol_openBinary(const uint8_t *bin, int32_t length, - const UCollator *base, - UErrorCode *status); - - -#endif /* #if !UCONFIG_NO_COLLATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/ucoleitr.h b/win32/include/spidermonkey/unicode/ucoleitr.h deleted file mode 100755 index b8410498..00000000 --- a/win32/include/spidermonkey/unicode/ucoleitr.h +++ /dev/null @@ -1,268 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2001-2014, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* -* File ucoleitr.h -* -* Modification History: -* -* Date Name Description -* 02/15/2001 synwee Modified all methods to process its own function -* instead of calling the equivalent c++ api (coleitr.h) -*******************************************************************************/ - -#ifndef UCOLEITR_H -#define UCOLEITR_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_COLLATION - -/** - * This indicates an error has occured during processing or if no more CEs is - * to be returned. - * @stable ICU 2.0 - */ -#define UCOL_NULLORDER ((int32_t)0xFFFFFFFF) - -#include "unicode/ucol.h" - -/** - * The UCollationElements struct. - * For usage in C programs. - * @stable ICU 2.0 - */ -typedef struct UCollationElements UCollationElements; - -/** - * \file - * \brief C API: UCollationElements - * - * The UCollationElements API is used as an iterator to walk through each - * character of an international string. Use the iterator to return the - * ordering priority of the positioned character. The ordering priority of a - * character, which we refer to as a key, defines how a character is collated - * in the given collation object. - * For example, consider the following in Slovak and in traditional Spanish collation: - *
- * .       "ca" -> the first key is key('c') and second key is key('a').
- * .       "cha" -> the first key is key('ch') and second key is key('a').
- * 
- * And in German phonebook collation, - *
- * .       "b"-> the first key is key('a'), the second key is key('e'), and
- * .       the third key is key('b').
- * 
- *

Example of the iterator usage: (without error checking) - *

- * .  void CollationElementIterator_Example()
- * .  {
- * .      UChar *s;
- * .      t_int32 order, primaryOrder;
- * .      UCollationElements *c;
- * .      UCollatorOld *coll;
- * .      UErrorCode success = U_ZERO_ERROR;
- * .      s=(UChar*)malloc(sizeof(UChar) * (strlen("This is a test")+1) );
- * .      u_uastrcpy(s, "This is a test");
- * .      coll = ucol_open(NULL, &success);
- * .      c = ucol_openElements(coll, str, u_strlen(str), &status);
- * .      order = ucol_next(c, &success);
- * .      ucol_reset(c);
- * .      order = ucol_prev(c, &success);
- * .      free(s);
- * .      ucol_close(coll);
- * .      ucol_closeElements(c);
- * .  }
- * 
- *

- * ucol_next() returns the collation order of the next. - * ucol_prev() returns the collation order of the previous character. - * The Collation Element Iterator moves only in one direction between calls to - * ucol_reset. That is, ucol_next() and ucol_prev can not be inter-used. - * Whenever ucol_prev is to be called after ucol_next() or vice versa, - * ucol_reset has to be called first to reset the status, shifting pointers to - * either the end or the start of the string. Hence at the next call of - * ucol_prev or ucol_next, the first or last collation order will be returned. - * If a change of direction is done without a ucol_reset, the result is - * undefined. - * The result of a forward iterate (ucol_next) and reversed result of the - * backward iterate (ucol_prev) on the same string are equivalent, if - * collation orders with the value 0 are ignored. - * Character based on the comparison level of the collator. A collation order - * consists of primary order, secondary order and tertiary order. The data - * type of the collation order is int32_t. - * - * @see UCollator - */ - -/** - * Open the collation elements for a string. - * - * @param coll The collator containing the desired collation rules. - * @param text The text to iterate over. - * @param textLength The number of characters in text, or -1 if null-terminated - * @param status A pointer to a UErrorCode to receive any errors. - * @return a struct containing collation element information - * @stable ICU 2.0 - */ -U_STABLE UCollationElements* U_EXPORT2 -ucol_openElements(const UCollator *coll, - const UChar *text, - int32_t textLength, - UErrorCode *status); - - -/** - * get a hash code for a key... Not very useful! - * @param key the given key. - * @param length the size of the key array. - * @return the hash code. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucol_keyHashCode(const uint8_t* key, int32_t length); - -/** - * Close a UCollationElements. - * Once closed, a UCollationElements may no longer be used. - * @param elems The UCollationElements to close. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucol_closeElements(UCollationElements *elems); - -/** - * Reset the collation elements to their initial state. - * This will move the 'cursor' to the beginning of the text. - * Property settings for collation will be reset to the current status. - * @param elems The UCollationElements to reset. - * @see ucol_next - * @see ucol_previous - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucol_reset(UCollationElements *elems); - -/** - * Get the ordering priority of the next collation element in the text. - * A single character may contain more than one collation element. - * @param elems The UCollationElements containing the text. - * @param status A pointer to a UErrorCode to receive any errors. - * @return The next collation elements ordering, otherwise returns NULLORDER - * if an error has occured or if the end of string has been reached - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucol_next(UCollationElements *elems, UErrorCode *status); - -/** - * Get the ordering priority of the previous collation element in the text. - * A single character may contain more than one collation element. - * Note that internally a stack is used to store buffered collation elements. - * @param elems The UCollationElements containing the text. - * @param status A pointer to a UErrorCode to receive any errors. Noteably - * a U_BUFFER_OVERFLOW_ERROR is returned if the internal stack - * buffer has been exhausted. - * @return The previous collation elements ordering, otherwise returns - * NULLORDER if an error has occured or if the start of string has - * been reached. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucol_previous(UCollationElements *elems, UErrorCode *status); - -/** - * Get the maximum length of any expansion sequences that end with the - * specified comparison order. - * This is useful for .... ? - * @param elems The UCollationElements containing the text. - * @param order A collation order returned by previous or next. - * @return maximum size of the expansion sequences ending with the collation - * element or 1 if collation element does not occur at the end of any - * expansion sequence - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucol_getMaxExpansion(const UCollationElements *elems, int32_t order); - -/** - * Set the text containing the collation elements. - * Property settings for collation will remain the same. - * In order to reset the iterator to the current collation property settings, - * the API reset() has to be called. - * @param elems The UCollationElements to set. - * @param text The source text containing the collation elements. - * @param textLength The length of text, or -1 if null-terminated. - * @param status A pointer to a UErrorCode to receive any errors. - * @see ucol_getText - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucol_setText( UCollationElements *elems, - const UChar *text, - int32_t textLength, - UErrorCode *status); - -/** - * Get the offset of the current source character. - * This is an offset into the text of the character containing the current - * collation elements. - * @param elems The UCollationElements to query. - * @return The offset of the current source character. - * @see ucol_setOffset - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ucol_getOffset(const UCollationElements *elems); - -/** - * Set the offset of the current source character. - * This is an offset into the text of the character to be processed. - * Property settings for collation will remain the same. - * In order to reset the iterator to the current collation property settings, - * the API reset() has to be called. - * @param elems The UCollationElements to set. - * @param offset The desired character offset. - * @param status A pointer to a UErrorCode to receive any errors. - * @see ucol_getOffset - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ucol_setOffset(UCollationElements *elems, - int32_t offset, - UErrorCode *status); - -/** -* Get the primary order of a collation order. -* @param order the collation order -* @return the primary order of a collation order. -* @stable ICU 2.6 -*/ -U_STABLE int32_t U_EXPORT2 -ucol_primaryOrder (int32_t order); - -/** -* Get the secondary order of a collation order. -* @param order the collation order -* @return the secondary order of a collation order. -* @stable ICU 2.6 -*/ -U_STABLE int32_t U_EXPORT2 -ucol_secondaryOrder (int32_t order); - -/** -* Get the tertiary order of a collation order. -* @param order the collation order -* @return the tertiary order of a collation order. -* @stable ICU 2.6 -*/ -U_STABLE int32_t U_EXPORT2 -ucol_tertiaryOrder (int32_t order); - -#endif /* #if !UCONFIG_NO_COLLATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/uconfig.h b/win32/include/spidermonkey/unicode/uconfig.h deleted file mode 100755 index 77a476dd..00000000 --- a/win32/include/spidermonkey/unicode/uconfig.h +++ /dev/null @@ -1,452 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 2002-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* file name: uconfig.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2002sep19 -* created by: Markus W. Scherer -*/ - -#ifndef __UCONFIG_H__ -#define __UCONFIG_H__ - - -/*! - * \file - * \brief User-configurable settings - * - * Miscellaneous switches: - * - * A number of macros affect a variety of minor aspects of ICU. - * Most of them used to be defined elsewhere (e.g., in utypes.h or platform.h) - * and moved here to make them easier to find. - * - * Switches for excluding parts of ICU library code modules: - * - * Changing these macros allows building partial, smaller libraries for special purposes. - * By default, all modules are built. - * The switches are fairly coarse, controlling large modules. - * Basic services cannot be turned off. - * - * Building with any of these options does not guarantee that the - * ICU build process will completely work. It is recommended that - * the ICU libraries and data be built using the normal build. - * At that time you should remove the data used by those services. - * After building the ICU data library, you should rebuild the ICU - * libraries with these switches customized to your needs. - * - * @stable ICU 2.4 - */ - -/** - * If this switch is defined, ICU will attempt to load a header file named "uconfig_local.h" - * prior to determining default settings for uconfig variables. - * - * @internal ICU 4.0 - */ -#if defined(UCONFIG_USE_LOCAL) -#include "uconfig_local.h" -#endif - -/** - * \def U_DEBUG - * Determines whether to include debugging code. - * Automatically set on Windows, but most compilers do not have - * related predefined macros. - * @internal - */ -#ifdef U_DEBUG - /* Use the predefined value. */ -#elif defined(_DEBUG) - /* - * _DEBUG is defined by Visual Studio debug compilation. - * Do *not* test for its NDEBUG macro: It is an orthogonal macro - * which disables assert(). - */ -# define U_DEBUG 1 -# else -# define U_DEBUG 0 -#endif - -/** - * Determines wheter to enable auto cleanup of libraries. - * @internal - */ -#ifndef UCLN_NO_AUTO_CLEANUP -#define UCLN_NO_AUTO_CLEANUP 1 -#endif - -/** - * \def U_DISABLE_RENAMING - * Determines whether to disable renaming or not. - * @internal - */ -#ifndef U_DISABLE_RENAMING -#define U_DISABLE_RENAMING 0 -#endif - -/** - * \def U_NO_DEFAULT_INCLUDE_UTF_HEADERS - * Determines whether utypes.h includes utf.h, utf8.h, utf16.h and utf_old.h. - * utypes.h includes those headers if this macro is defined to 0. - * Otherwise, each those headers must be included explicitly when using one of their macros. - * Defaults to 0 for backward compatibility, except inside ICU. - * @stable ICU 49 - */ -#ifdef U_NO_DEFAULT_INCLUDE_UTF_HEADERS - /* Use the predefined value. */ -#elif defined(U_COMBINED_IMPLEMENTATION) || defined(U_COMMON_IMPLEMENTATION) || defined(U_I18N_IMPLEMENTATION) || \ - defined(U_IO_IMPLEMENTATION) || defined(U_LAYOUT_IMPLEMENTATION) || defined(U_LAYOUTEX_IMPLEMENTATION) || \ - defined(U_TOOLUTIL_IMPLEMENTATION) -# define U_NO_DEFAULT_INCLUDE_UTF_HEADERS 1 -#else -# define U_NO_DEFAULT_INCLUDE_UTF_HEADERS 0 -#endif - -/** - * \def U_OVERRIDE_CXX_ALLOCATION - * Determines whether to override new and delete. - * ICU is normally built such that all of its C++ classes, via their UMemory base, - * override operators new and delete to use its internal, customizable, - * non-exception-throwing memory allocation functions. (Default value 1 for this macro.) - * - * This is especially important when the application and its libraries use multiple heaps. - * For example, on Windows, this allows the ICU DLL to be used by - * applications that statically link the C Runtime library. - * - * @stable ICU 2.2 - */ -#ifndef U_OVERRIDE_CXX_ALLOCATION -#define U_OVERRIDE_CXX_ALLOCATION 1 -#endif - -/** - * \def U_ENABLE_TRACING - * Determines whether to enable tracing. - * @internal - */ -#ifndef U_ENABLE_TRACING -#define U_ENABLE_TRACING 0 -#endif - -/** - * \def UCONFIG_ENABLE_PLUGINS - * Determines whether to enable ICU plugins. - * @internal - */ -#ifndef UCONFIG_ENABLE_PLUGINS -#define UCONFIG_ENABLE_PLUGINS 0 -#endif - -/** - * \def U_ENABLE_DYLOAD - * Whether to enable Dynamic loading in ICU. - * @internal - */ -#ifndef U_ENABLE_DYLOAD -#define U_ENABLE_DYLOAD 1 -#endif - -/** - * \def U_CHECK_DYLOAD - * Whether to test Dynamic loading as an OS capability. - * @internal - */ -#ifndef U_CHECK_DYLOAD -#define U_CHECK_DYLOAD 1 -#endif - -/** - * \def U_DEFAULT_SHOW_DRAFT - * Do we allow ICU users to use the draft APIs by default? - * @internal - */ -#ifndef U_DEFAULT_SHOW_DRAFT -#define U_DEFAULT_SHOW_DRAFT 1 -#endif - -/*===========================================================================*/ -/* Custom icu entry point renaming */ -/*===========================================================================*/ - -/** - * \def U_HAVE_LIB_SUFFIX - * 1 if a custom library suffix is set. - * @internal - */ -#ifdef U_HAVE_LIB_SUFFIX - /* Use the predefined value. */ -#elif defined(U_LIB_SUFFIX_C_NAME) -# define U_HAVE_LIB_SUFFIX 1 -#endif - -/** - * \def U_LIB_SUFFIX_C_NAME_STRING - * Defines the library suffix as a string with C syntax. - * @internal - */ -#ifdef U_LIB_SUFFIX_C_NAME_STRING - /* Use the predefined value. */ -#elif defined(U_LIB_SUFFIX_C_NAME) -# define CONVERT_TO_STRING(s) #s -# define U_LIB_SUFFIX_C_NAME_STRING CONVERT_TO_STRING(U_LIB_SUFFIX_C_NAME) -#else -# define U_LIB_SUFFIX_C_NAME_STRING "" -#endif - -/* common/i18n library switches --------------------------------------------- */ - -/** - * \def UCONFIG_ONLY_COLLATION - * This switch turns off modules that are not needed for collation. - * - * It does not turn off legacy conversion because that is necessary - * for ICU to work on EBCDIC platforms (for the default converter). - * If you want "only collation" and do not build for EBCDIC, - * then you can define UCONFIG_NO_CONVERSION or UCONFIG_NO_LEGACY_CONVERSION to 1 as well. - * - * @stable ICU 2.4 - */ -#ifndef UCONFIG_ONLY_COLLATION -# define UCONFIG_ONLY_COLLATION 0 -#endif - -#if UCONFIG_ONLY_COLLATION - /* common library */ -# define UCONFIG_NO_BREAK_ITERATION 1 -# define UCONFIG_NO_IDNA 1 - - /* i18n library */ -# if UCONFIG_NO_COLLATION -# error Contradictory collation switches in uconfig.h. -# endif -# define UCONFIG_NO_FORMATTING 1 -# define UCONFIG_NO_TRANSLITERATION 1 -# define UCONFIG_NO_REGULAR_EXPRESSIONS 1 -#endif - -/* common library switches -------------------------------------------------- */ - -/** - * \def UCONFIG_NO_FILE_IO - * This switch turns off all file access in the common library - * where file access is only used for data loading. - * ICU data must then be provided in the form of a data DLL (or with an - * equivalent way to link to the data residing in an executable, - * as in building a combined library with both the common library's code and - * the data), or via udata_setCommonData(). - * Application data must be provided via udata_setAppData() or by using - * "open" functions that take pointers to data, for example ucol_openBinary(). - * - * File access is not used at all in the i18n library. - * - * File access cannot be turned off for the icuio library or for the ICU - * test suites and ICU tools. - * - * @stable ICU 3.6 - */ -#ifndef UCONFIG_NO_FILE_IO -# define UCONFIG_NO_FILE_IO 0 -#endif - -#if UCONFIG_NO_FILE_IO && defined(U_TIMEZONE_FILES_DIR) -# error Contradictory file io switches in uconfig.h. -#endif - -/** - * \def UCONFIG_NO_CONVERSION - * ICU will not completely build with this switch turned on. - * This switch turns off all converters. - * - * You may want to use this together with U_CHARSET_IS_UTF8 defined to 1 - * in utypes.h if char* strings in your environment are always in UTF-8. - * - * @stable ICU 3.2 - * @see U_CHARSET_IS_UTF8 - */ -#ifndef UCONFIG_NO_CONVERSION -# define UCONFIG_NO_CONVERSION 0 -#endif - -#if UCONFIG_NO_CONVERSION -# define UCONFIG_NO_LEGACY_CONVERSION 1 -#endif - -/** - * \def UCONFIG_ONLY_HTML_CONVERSION - * This switch turns off all of the converters NOT listed in - * the HTML encoding standard: - * http://www.w3.org/TR/encoding/#names-and-labels - * - * This is not possible on EBCDIC platforms - * because they need ibm-37 or ibm-1047 default converters. - * - * @stable ICU 55 - */ -#ifndef UCONFIG_ONLY_HTML_CONVERSION -# define UCONFIG_ONLY_HTML_CONVERSION 0 -#endif - -/** - * \def UCONFIG_NO_LEGACY_CONVERSION - * This switch turns off all converters except for - * - Unicode charsets (UTF-7/8/16/32, CESU-8, SCSU, BOCU-1) - * - US-ASCII - * - ISO-8859-1 - * - * Turning off legacy conversion is not possible on EBCDIC platforms - * because they need ibm-37 or ibm-1047 default converters. - * - * @stable ICU 2.4 - */ -#ifndef UCONFIG_NO_LEGACY_CONVERSION -# define UCONFIG_NO_LEGACY_CONVERSION 0 -#endif - -/** - * \def UCONFIG_NO_NORMALIZATION - * This switch turns off normalization. - * It implies turning off several other services as well, for example - * collation and IDNA. - * - * @stable ICU 2.6 - */ -#ifndef UCONFIG_NO_NORMALIZATION -# define UCONFIG_NO_NORMALIZATION 0 -#elif UCONFIG_NO_NORMALIZATION - /* common library */ - /* ICU 50 CJK dictionary BreakIterator uses normalization */ -# define UCONFIG_NO_BREAK_ITERATION 1 - /* IDNA (UTS #46) is implemented via normalization */ -# define UCONFIG_NO_IDNA 1 - - /* i18n library */ -# if UCONFIG_ONLY_COLLATION -# error Contradictory collation switches in uconfig.h. -# endif -# define UCONFIG_NO_COLLATION 1 -# define UCONFIG_NO_TRANSLITERATION 1 -#endif - -/** - * \def UCONFIG_NO_BREAK_ITERATION - * This switch turns off break iteration. - * - * @stable ICU 2.4 - */ -#ifndef UCONFIG_NO_BREAK_ITERATION -# define UCONFIG_NO_BREAK_ITERATION 0 -#endif - -/** - * \def UCONFIG_NO_IDNA - * This switch turns off IDNA. - * - * @stable ICU 2.6 - */ -#ifndef UCONFIG_NO_IDNA -# define UCONFIG_NO_IDNA 0 -#endif - -/** - * \def UCONFIG_MSGPAT_DEFAULT_APOSTROPHE_MODE - * Determines the default UMessagePatternApostropheMode. - * See the documentation for that enum. - * - * @stable ICU 4.8 - */ -#ifndef UCONFIG_MSGPAT_DEFAULT_APOSTROPHE_MODE -# define UCONFIG_MSGPAT_DEFAULT_APOSTROPHE_MODE UMSGPAT_APOS_DOUBLE_OPTIONAL -#endif - -/* i18n library switches ---------------------------------------------------- */ - -/** - * \def UCONFIG_NO_COLLATION - * This switch turns off collation and collation-based string search. - * - * @stable ICU 2.4 - */ -#ifndef UCONFIG_NO_COLLATION -# define UCONFIG_NO_COLLATION 0 -#endif - -/** - * \def UCONFIG_NO_FORMATTING - * This switch turns off formatting and calendar/timezone services. - * - * @stable ICU 2.4 - */ -#ifndef UCONFIG_NO_FORMATTING -# define UCONFIG_NO_FORMATTING 0 -#endif - -/** - * \def UCONFIG_NO_TRANSLITERATION - * This switch turns off transliteration. - * - * @stable ICU 2.4 - */ -#ifndef UCONFIG_NO_TRANSLITERATION -# define UCONFIG_NO_TRANSLITERATION 0 -#endif - -/** - * \def UCONFIG_NO_REGULAR_EXPRESSIONS - * This switch turns off regular expressions. - * - * @stable ICU 2.4 - */ -#ifndef UCONFIG_NO_REGULAR_EXPRESSIONS -# define UCONFIG_NO_REGULAR_EXPRESSIONS 0 -#endif - -/** - * \def UCONFIG_NO_SERVICE - * This switch turns off service registration. - * - * @stable ICU 3.2 - */ -#ifndef UCONFIG_NO_SERVICE -# define UCONFIG_NO_SERVICE 0 -#endif - -/** - * \def UCONFIG_HAVE_PARSEALLINPUT - * This switch turns on the "parse all input" attribute. Binary incompatible. - * - * @internal - */ -#ifndef UCONFIG_HAVE_PARSEALLINPUT -# define UCONFIG_HAVE_PARSEALLINPUT 1 -#endif - - -/** - * \def UCONFIG_FORMAT_FASTPATHS_49 - * This switch turns on other formatting fastpaths. Binary incompatible in object DecimalFormat and DecimalFormatSymbols - * - * @internal - */ -#ifndef UCONFIG_FORMAT_FASTPATHS_49 -# define UCONFIG_FORMAT_FASTPATHS_49 1 -#endif - -/** - * \def UCONFIG_NO_FILTERED_BREAK_ITERATION - * This switch turns off filtered break iteration code. - * - * @internal - */ -#ifndef UCONFIG_NO_FILTERED_BREAK_ITERATION -# define UCONFIG_NO_FILTERED_BREAK_ITERATION 0 -#endif - -#endif diff --git a/win32/include/spidermonkey/unicode/ucsdet.h b/win32/include/spidermonkey/unicode/ucsdet.h deleted file mode 100755 index 470cbab6..00000000 --- a/win32/include/spidermonkey/unicode/ucsdet.h +++ /dev/null @@ -1,415 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ********************************************************************** - * Copyright (C) 2005-2013, International Business Machines - * Corporation and others. All Rights Reserved. - ********************************************************************** - * file name: ucsdet.h - * encoding: US-ASCII - * indentation:4 - * - * created on: 2005Aug04 - * created by: Andy Heninger - * - * ICU Character Set Detection, API for C - * - * Draft version 18 Oct 2005 - * - */ - -#ifndef __UCSDET_H -#define __UCSDET_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_CONVERSION - -#include "unicode/localpointer.h" -#include "unicode/uenum.h" - -/** - * \file - * \brief C API: Charset Detection API - * - * This API provides a facility for detecting the - * charset or encoding of character data in an unknown text format. - * The input data can be from an array of bytes. - *

- * Character set detection is at best an imprecise operation. The detection - * process will attempt to identify the charset that best matches the characteristics - * of the byte data, but the process is partly statistical in nature, and - * the results can not be guaranteed to always be correct. - *

- * For best accuracy in charset detection, the input data should be primarily - * in a single language, and a minimum of a few hundred bytes worth of plain text - * in the language are needed. The detection process will attempt to - * ignore html or xml style markup that could otherwise obscure the content. - */ - - -struct UCharsetDetector; -/** - * Structure representing a charset detector - * @stable ICU 3.6 - */ -typedef struct UCharsetDetector UCharsetDetector; - -struct UCharsetMatch; -/** - * Opaque structure representing a match that was identified - * from a charset detection operation. - * @stable ICU 3.6 - */ -typedef struct UCharsetMatch UCharsetMatch; - -/** - * Open a charset detector. - * - * @param status Any error conditions occurring during the open - * operation are reported back in this variable. - * @return the newly opened charset detector. - * @stable ICU 3.6 - */ -U_STABLE UCharsetDetector * U_EXPORT2 -ucsdet_open(UErrorCode *status); - -/** - * Close a charset detector. All storage and any other resources - * owned by this charset detector will be released. Failure to - * close a charset detector when finished with it can result in - * memory leaks in the application. - * - * @param ucsd The charset detector to be closed. - * @stable ICU 3.6 - */ -U_STABLE void U_EXPORT2 -ucsdet_close(UCharsetDetector *ucsd); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUCharsetDetectorPointer - * "Smart pointer" class, closes a UCharsetDetector via ucsdet_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUCharsetDetectorPointer, UCharsetDetector, ucsdet_close); - -U_NAMESPACE_END - -#endif - -/** - * Set the input byte data whose charset is to detected. - * - * Ownership of the input text byte array remains with the caller. - * The input string must not be altered or deleted until the charset - * detector is either closed or reset to refer to different input text. - * - * @param ucsd the charset detector to be used. - * @param textIn the input text of unknown encoding. . - * @param len the length of the input text, or -1 if the text - * is NUL terminated. - * @param status any error conditions are reported back in this variable. - * - * @stable ICU 3.6 - */ -U_STABLE void U_EXPORT2 -ucsdet_setText(UCharsetDetector *ucsd, const char *textIn, int32_t len, UErrorCode *status); - - -/** Set the declared encoding for charset detection. - * The declared encoding of an input text is an encoding obtained - * by the user from an http header or xml declaration or similar source that - * can be provided as an additional hint to the charset detector. - * - * How and whether the declared encoding will be used during the - * detection process is TBD. - * - * @param ucsd the charset detector to be used. - * @param encoding an encoding for the current data obtained from - * a header or declaration or other source outside - * of the byte data itself. - * @param length the length of the encoding name, or -1 if the name string - * is NUL terminated. - * @param status any error conditions are reported back in this variable. - * - * @stable ICU 3.6 - */ -U_STABLE void U_EXPORT2 -ucsdet_setDeclaredEncoding(UCharsetDetector *ucsd, const char *encoding, int32_t length, UErrorCode *status); - - -/** - * Return the charset that best matches the supplied input data. - * - * Note though, that because the detection - * only looks at the start of the input data, - * there is a possibility that the returned charset will fail to handle - * the full set of input data. - *

- * The returned UCharsetMatch object is owned by the UCharsetDetector. - * It will remain valid until the detector input is reset, or until - * the detector is closed. - *

- * The function will fail if - *

    - *
  • no charset appears to match the data.
  • - *
  • no input text has been provided
  • - *
- * - * @param ucsd the charset detector to be used. - * @param status any error conditions are reported back in this variable. - * @return a UCharsetMatch representing the best matching charset, - * or NULL if no charset matches the byte data. - * - * @stable ICU 3.6 - */ -U_STABLE const UCharsetMatch * U_EXPORT2 -ucsdet_detect(UCharsetDetector *ucsd, UErrorCode *status); - - -/** - * Find all charset matches that appear to be consistent with the input, - * returning an array of results. The results are ordered with the - * best quality match first. - * - * Because the detection only looks at a limited amount of the - * input byte data, some of the returned charsets may fail to handle - * the all of input data. - *

- * The returned UCharsetMatch objects are owned by the UCharsetDetector. - * They will remain valid until the detector is closed or modified - * - *

- * Return an error if - *

    - *
  • no charsets appear to match the input data.
  • - *
  • no input text has been provided
  • - *
- * - * @param ucsd the charset detector to be used. - * @param matchesFound pointer to a variable that will be set to the - * number of charsets identified that are consistent with - * the input data. Output only. - * @param status any error conditions are reported back in this variable. - * @return A pointer to an array of pointers to UCharSetMatch objects. - * This array, and the UCharSetMatch instances to which it refers, - * are owned by the UCharsetDetector, and will remain valid until - * the detector is closed or modified. - * @stable ICU 3.6 - */ -U_STABLE const UCharsetMatch ** U_EXPORT2 -ucsdet_detectAll(UCharsetDetector *ucsd, int32_t *matchesFound, UErrorCode *status); - - - -/** - * Get the name of the charset represented by a UCharsetMatch. - * - * The storage for the returned name string is owned by the - * UCharsetMatch, and will remain valid while the UCharsetMatch - * is valid. - * - * The name returned is suitable for use with the ICU conversion APIs. - * - * @param ucsm The charset match object. - * @param status Any error conditions are reported back in this variable. - * @return The name of the matching charset. - * - * @stable ICU 3.6 - */ -U_STABLE const char * U_EXPORT2 -ucsdet_getName(const UCharsetMatch *ucsm, UErrorCode *status); - -/** - * Get a confidence number for the quality of the match of the byte - * data with the charset. Confidence numbers range from zero to 100, - * with 100 representing complete confidence and zero representing - * no confidence. - * - * The confidence values are somewhat arbitrary. They define an - * an ordering within the results for any single detection operation - * but are not generally comparable between the results for different input. - * - * A confidence value of ten does have a general meaning - it is used - * for charsets that can represent the input data, but for which there - * is no other indication that suggests that the charset is the correct one. - * Pure 7 bit ASCII data, for example, is compatible with a - * great many charsets, most of which will appear as possible matches - * with a confidence of 10. - * - * @param ucsm The charset match object. - * @param status Any error conditions are reported back in this variable. - * @return A confidence number for the charset match. - * - * @stable ICU 3.6 - */ -U_STABLE int32_t U_EXPORT2 -ucsdet_getConfidence(const UCharsetMatch *ucsm, UErrorCode *status); - -/** - * Get the RFC 3066 code for the language of the input data. - * - * The Charset Detection service is intended primarily for detecting - * charsets, not language. For some, but not all, charsets, a language is - * identified as a byproduct of the detection process, and that is what - * is returned by this function. - * - * CAUTION: - * 1. Language information is not available for input data encoded in - * all charsets. In particular, no language is identified - * for UTF-8 input data. - * - * 2. Closely related languages may sometimes be confused. - * - * If more accurate language detection is required, a linguistic - * analysis package should be used. - * - * The storage for the returned name string is owned by the - * UCharsetMatch, and will remain valid while the UCharsetMatch - * is valid. - * - * @param ucsm The charset match object. - * @param status Any error conditions are reported back in this variable. - * @return The RFC 3066 code for the language of the input data, or - * an empty string if the language could not be determined. - * - * @stable ICU 3.6 - */ -U_STABLE const char * U_EXPORT2 -ucsdet_getLanguage(const UCharsetMatch *ucsm, UErrorCode *status); - - -/** - * Get the entire input text as a UChar string, placing it into - * a caller-supplied buffer. A terminating - * NUL character will be appended to the buffer if space is available. - * - * The number of UChars in the output string, not including the terminating - * NUL, is returned. - * - * If the supplied buffer is smaller than required to hold the output, - * the contents of the buffer are undefined. The full output string length - * (in UChars) is returned as always, and can be used to allocate a buffer - * of the correct size. - * - * - * @param ucsm The charset match object. - * @param buf A UChar buffer to be filled with the converted text data. - * @param cap The capacity of the buffer in UChars. - * @param status Any error conditions are reported back in this variable. - * @return The number of UChars in the output string. - * - * @stable ICU 3.6 - */ -U_STABLE int32_t U_EXPORT2 -ucsdet_getUChars(const UCharsetMatch *ucsm, - UChar *buf, int32_t cap, UErrorCode *status); - - - -/** - * Get an iterator over the set of all detectable charsets - - * over the charsets that are known to the charset detection - * service. - * - * The returned UEnumeration provides access to the names of - * the charsets. - * - *

- * The state of the Charset detector that is passed in does not - * affect the result of this function, but requiring a valid, open - * charset detector as a parameter insures that the charset detection - * service has been safely initialized and that the required detection - * data is available. - * - *

- * Note: Multiple different charset encodings in a same family may use - * a single shared name in this implementation. For example, this method returns - * an array including "ISO-8859-1" (ISO Latin 1), but not including "windows-1252" - * (Windows Latin 1). However, actual detection result could be "windows-1252" - * when the input data matches Latin 1 code points with any points only available - * in "windows-1252". - * - * @param ucsd a Charset detector. - * @param status Any error conditions are reported back in this variable. - * @return an iterator providing access to the detectable charset names. - * @stable ICU 3.6 - */ -U_STABLE UEnumeration * U_EXPORT2 -ucsdet_getAllDetectableCharsets(const UCharsetDetector *ucsd, UErrorCode *status); - -/** - * Test whether input filtering is enabled for this charset detector. - * Input filtering removes text that appears to be HTML or xml - * markup from the input before applying the code page detection - * heuristics. - * - * @param ucsd The charset detector to check. - * @return TRUE if filtering is enabled. - * @stable ICU 3.6 - */ - -U_STABLE UBool U_EXPORT2 -ucsdet_isInputFilterEnabled(const UCharsetDetector *ucsd); - - -/** - * Enable filtering of input text. If filtering is enabled, - * text within angle brackets ("<" and ">") will be removed - * before detection, which will remove most HTML or xml markup. - * - * @param ucsd the charset detector to be modified. - * @param filter true to enable input text filtering. - * @return The previous setting. - * - * @stable ICU 3.6 - */ -U_STABLE UBool U_EXPORT2 -ucsdet_enableInputFilter(UCharsetDetector *ucsd, UBool filter); - -#ifndef U_HIDE_INTERNAL_API -/** - * Get an iterator over the set of detectable charsets - - * over the charsets that are enabled by the specified charset detector. - * - * The returned UEnumeration provides access to the names of - * the charsets. - * - * @param ucsd a Charset detector. - * @param status Any error conditions are reported back in this variable. - * @return an iterator providing access to the detectable charset names by - * the specified charset detector. - * @internal - */ -U_INTERNAL UEnumeration * U_EXPORT2 -ucsdet_getDetectableCharsets(const UCharsetDetector *ucsd, UErrorCode *status); - -/** - * Enable or disable individual charset encoding. - * A name of charset encoding must be included in the names returned by - * {@link #getAllDetectableCharsets()}. - * - * @param ucsd a Charset detector. - * @param encoding encoding the name of charset encoding. - * @param enabled TRUE to enable, or FALSE to disable the - * charset encoding. - * @param status receives the return status. When the name of charset encoding - * is not supported, U_ILLEGAL_ARGUMENT_ERROR is set. - * @internal - */ -U_INTERNAL void U_EXPORT2 -ucsdet_setDetectableCharset(UCharsetDetector *ucsd, const char *encoding, UBool enabled, UErrorCode *status); -#endif /* U_HIDE_INTERNAL_API */ - -#endif -#endif /* __UCSDET_H */ - - diff --git a/win32/include/spidermonkey/unicode/ucurr.h b/win32/include/spidermonkey/unicode/ucurr.h deleted file mode 100755 index 56bad0ae..00000000 --- a/win32/include/spidermonkey/unicode/ucurr.h +++ /dev/null @@ -1,420 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2002-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -*/ -#ifndef _UCURR_H_ -#define _UCURR_H_ - -#include "unicode/utypes.h" -#include "unicode/uenum.h" - -/** - * \file - * \brief C API: Encapsulates information about a currency. - * - * The ucurr API encapsulates information about a currency, as defined by - * ISO 4217. A currency is represented by a 3-character string - * containing its ISO 4217 code. This API can return various data - * necessary the proper display of a currency: - * - *

  • A display symbol, for a specific locale - *
  • The number of fraction digits to display - *
  • A rounding increment - *
- * - * The DecimalFormat class uses these data to display - * currencies. - * @author Alan Liu - * @since ICU 2.2 - */ - -#if !UCONFIG_NO_FORMATTING - -/** - * Currency Usage used for Decimal Format - * @stable ICU 54 - */ -enum UCurrencyUsage { - /** - * a setting to specify currency usage which determines currency digit - * and rounding for standard usage, for example: "50.00 NT$" - * used as DEFAULT value - * @stable ICU 54 - */ - UCURR_USAGE_STANDARD=0, - /** - * a setting to specify currency usage which determines currency digit - * and rounding for cash usage, for example: "50 NT$" - * @stable ICU 54 - */ - UCURR_USAGE_CASH=1, -#ifndef U_HIDE_DEPRECATED_API - /** - * One higher than the last enum UCurrencyUsage constant. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UCURR_USAGE_COUNT=2 -#endif // U_HIDE_DEPRECATED_API -}; -typedef enum UCurrencyUsage UCurrencyUsage; - -/** - * Finds a currency code for the given locale. - * @param locale the locale for which to retrieve a currency code. - * Currency can be specified by the "currency" keyword - * in which case it overrides the default currency code - * @param buff fill in buffer. Can be NULL for preflighting. - * @param buffCapacity capacity of the fill in buffer. Can be 0 for - * preflighting. If it is non-zero, the buff parameter - * must not be NULL. - * @param ec error code - * @return length of the currency string. It should always be 3. If 0, - * currency couldn't be found or the input values are - * invalid. - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -ucurr_forLocale(const char* locale, - UChar* buff, - int32_t buffCapacity, - UErrorCode* ec); - -/** - * Selector constants for ucurr_getName(). - * - * @see ucurr_getName - * @stable ICU 2.6 - */ -typedef enum UCurrNameStyle { - /** - * Selector for ucurr_getName indicating a symbolic name for a - * currency, such as "$" for USD. - * @stable ICU 2.6 - */ - UCURR_SYMBOL_NAME, - - /** - * Selector for ucurr_getName indicating the long name for a - * currency, such as "US Dollar" for USD. - * @stable ICU 2.6 - */ - UCURR_LONG_NAME -} UCurrNameStyle; - -#if !UCONFIG_NO_SERVICE -/** - * @stable ICU 2.6 - */ -typedef const void* UCurrRegistryKey; - -/** - * Register an (existing) ISO 4217 currency code for the given locale. - * Only the country code and the two variants EURO and PRE_EURO are - * recognized. - * @param isoCode the three-letter ISO 4217 currency code - * @param locale the locale for which to register this currency code - * @param status the in/out status code - * @return a registry key that can be used to unregister this currency code, or NULL - * if there was an error. - * @stable ICU 2.6 - */ -U_STABLE UCurrRegistryKey U_EXPORT2 -ucurr_register(const UChar* isoCode, - const char* locale, - UErrorCode* status); -/** - * Unregister the previously-registered currency definitions using the - * URegistryKey returned from ucurr_register. Key becomes invalid after - * a successful call and should not be used again. Any currency - * that might have been hidden by the original ucurr_register call is - * restored. - * @param key the registry key returned by a previous call to ucurr_register - * @param status the in/out status code, no special meanings are assigned - * @return TRUE if the currency for this key was successfully unregistered - * @stable ICU 2.6 - */ -U_STABLE UBool U_EXPORT2 -ucurr_unregister(UCurrRegistryKey key, UErrorCode* status); -#endif /* UCONFIG_NO_SERVICE */ - -/** - * Returns the display name for the given currency in the - * given locale. For example, the display name for the USD - * currency object in the en_US locale is "$". - * @param currency null-terminated 3-letter ISO 4217 code - * @param locale locale in which to display currency - * @param nameStyle selector for which kind of name to return - * @param isChoiceFormat fill-in set to TRUE if the returned value - * is a ChoiceFormat pattern; otherwise it is a static string - * @param len fill-in parameter to receive length of result - * @param ec error code - * @return pointer to display string of 'len' UChars. If the resource - * data contains no entry for 'currency', then 'currency' itself is - * returned. If *isChoiceFormat is TRUE, then the result is a - * ChoiceFormat pattern. Otherwise it is a static string. - * @stable ICU 2.6 - */ -U_STABLE const UChar* U_EXPORT2 -ucurr_getName(const UChar* currency, - const char* locale, - UCurrNameStyle nameStyle, - UBool* isChoiceFormat, - int32_t* len, - UErrorCode* ec); - -/** - * Returns the plural name for the given currency in the - * given locale. For example, the plural name for the USD - * currency object in the en_US locale is "US dollar" or "US dollars". - * @param currency null-terminated 3-letter ISO 4217 code - * @param locale locale in which to display currency - * @param isChoiceFormat fill-in set to TRUE if the returned value - * is a ChoiceFormat pattern; otherwise it is a static string - * @param pluralCount plural count - * @param len fill-in parameter to receive length of result - * @param ec error code - * @return pointer to display string of 'len' UChars. If the resource - * data contains no entry for 'currency', then 'currency' itself is - * returned. - * @stable ICU 4.2 - */ -U_STABLE const UChar* U_EXPORT2 -ucurr_getPluralName(const UChar* currency, - const char* locale, - UBool* isChoiceFormat, - const char* pluralCount, - int32_t* len, - UErrorCode* ec); - -/** - * Returns the number of the number of fraction digits that should - * be displayed for the given currency. - * This is equivalent to ucurr_getDefaultFractionDigitsForUsage(currency,UCURR_USAGE_STANDARD,ec); - * @param currency null-terminated 3-letter ISO 4217 code - * @param ec input-output error code - * @return a non-negative number of fraction digits to be - * displayed, or 0 if there is an error - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -ucurr_getDefaultFractionDigits(const UChar* currency, - UErrorCode* ec); - -/** - * Returns the number of the number of fraction digits that should - * be displayed for the given currency with usage. - * @param currency null-terminated 3-letter ISO 4217 code - * @param usage enum usage for the currency - * @param ec input-output error code - * @return a non-negative number of fraction digits to be - * displayed, or 0 if there is an error - * @stable ICU 54 - */ -U_STABLE int32_t U_EXPORT2 -ucurr_getDefaultFractionDigitsForUsage(const UChar* currency, - const UCurrencyUsage usage, - UErrorCode* ec); - -/** - * Returns the rounding increment for the given currency, or 0.0 if no - * rounding is done by the currency. - * This is equivalent to ucurr_getRoundingIncrementForUsage(currency,UCURR_USAGE_STANDARD,ec); - * @param currency null-terminated 3-letter ISO 4217 code - * @param ec input-output error code - * @return the non-negative rounding increment, or 0.0 if none, - * or 0.0 if there is an error - * @stable ICU 3.0 - */ -U_STABLE double U_EXPORT2 -ucurr_getRoundingIncrement(const UChar* currency, - UErrorCode* ec); - -/** - * Returns the rounding increment for the given currency, or 0.0 if no - * rounding is done by the currency given usage. - * @param currency null-terminated 3-letter ISO 4217 code - * @param usage enum usage for the currency - * @param ec input-output error code - * @return the non-negative rounding increment, or 0.0 if none, - * or 0.0 if there is an error - * @stable ICU 54 - */ -U_STABLE double U_EXPORT2 -ucurr_getRoundingIncrementForUsage(const UChar* currency, - const UCurrencyUsage usage, - UErrorCode* ec); - -/** - * Selector constants for ucurr_openCurrencies(). - * - * @see ucurr_openCurrencies - * @stable ICU 3.2 - */ -typedef enum UCurrCurrencyType { - /** - * Select all ISO-4217 currency codes. - * @stable ICU 3.2 - */ - UCURR_ALL = INT32_MAX, - /** - * Select only ISO-4217 commonly used currency codes. - * These currencies can be found in common use, and they usually have - * bank notes or coins associated with the currency code. - * This does not include fund codes, precious metals and other - * various ISO-4217 codes limited to special financial products. - * @stable ICU 3.2 - */ - UCURR_COMMON = 1, - /** - * Select ISO-4217 uncommon currency codes. - * These codes respresent fund codes, precious metals and other - * various ISO-4217 codes limited to special financial products. - * A fund code is a monetary resource associated with a currency. - * @stable ICU 3.2 - */ - UCURR_UNCOMMON = 2, - /** - * Select only deprecated ISO-4217 codes. - * These codes are no longer in general public use. - * @stable ICU 3.2 - */ - UCURR_DEPRECATED = 4, - /** - * Select only non-deprecated ISO-4217 codes. - * These codes are in general public use. - * @stable ICU 3.2 - */ - UCURR_NON_DEPRECATED = 8 -} UCurrCurrencyType; - -/** - * Provides a UEnumeration object for listing ISO-4217 codes. - * @param currType You can use one of several UCurrCurrencyType values for this - * variable. You can also | (or) them together to get a specific list of - * currencies. Most people will want to use the (UCURR_CURRENCY|UCURR_NON_DEPRECATED) value to - * get a list of current currencies. - * @param pErrorCode Error code - * @stable ICU 3.2 - */ -U_STABLE UEnumeration * U_EXPORT2 -ucurr_openISOCurrencies(uint32_t currType, UErrorCode *pErrorCode); - -/** - * Queries if the given ISO 4217 3-letter code is available on the specified date range. - * - * Note: For checking availability of a currency on a specific date, specify the date on both 'from' and 'to' - * - * When 'from' is U_DATE_MIN and 'to' is U_DATE_MAX, this method checks if the specified currency is available any time. - * If 'from' and 'to' are same UDate value, this method checks if the specified currency is available on that date. - * - * @param isoCode - * The ISO 4217 3-letter code. - * - * @param from - * The lower bound of the date range, inclusive. When 'from' is U_DATE_MIN, check the availability - * of the currency any date before 'to' - * - * @param to - * The upper bound of the date range, inclusive. When 'to' is U_DATE_MAX, check the availability of - * the currency any date after 'from' - * - * @param errorCode - * ICU error code - * - * @return TRUE if the given ISO 4217 3-letter code is supported on the specified date range. - * - * @stable ICU 4.8 - */ -U_STABLE UBool U_EXPORT2 -ucurr_isAvailable(const UChar* isoCode, - UDate from, - UDate to, - UErrorCode* errorCode); - -/** - * Finds the number of valid currency codes for the - * given locale and date. - * @param locale the locale for which to retrieve the - * currency count. - * @param date the date for which to retrieve the - * currency count for the given locale. - * @param ec error code - * @return the number of currency codes for the - * given locale and date. If 0, currency - * codes couldn't be found for the input - * values are invalid. - * @stable ICU 4.0 - */ -U_STABLE int32_t U_EXPORT2 -ucurr_countCurrencies(const char* locale, - UDate date, - UErrorCode* ec); - -/** - * Finds a currency code for the given locale and date - * @param locale the locale for which to retrieve a currency code. - * Currency can be specified by the "currency" keyword - * in which case it overrides the default currency code - * @param date the date for which to retrieve a currency code for - * the given locale. - * @param index the index within the available list of currency codes - * for the given locale on the given date. - * @param buff fill in buffer. Can be NULL for preflighting. - * @param buffCapacity capacity of the fill in buffer. Can be 0 for - * preflighting. If it is non-zero, the buff parameter - * must not be NULL. - * @param ec error code - * @return length of the currency string. It should always be 3. - * If 0, currency couldn't be found or the input values are - * invalid. - * @stable ICU 4.0 - */ -U_STABLE int32_t U_EXPORT2 -ucurr_forLocaleAndDate(const char* locale, - UDate date, - int32_t index, - UChar* buff, - int32_t buffCapacity, - UErrorCode* ec); - -/** - * Given a key and a locale, returns an array of string values in a preferred - * order that would make a difference. These are all and only those values where - * the open (creation) of the service with the locale formed from the input locale - * plus input keyword and that value has different behavior than creation with the - * input locale alone. - * @param key one of the keys supported by this service. For now, only - * "currency" is supported. - * @param locale the locale - * @param commonlyUsed if set to true it will return only commonly used values - * with the given locale in preferred order. Otherwise, - * it will return all the available values for the locale. - * @param status error status - * @return a string enumeration over keyword values for the given key and the locale. - * @stable ICU 4.2 - */ -U_STABLE UEnumeration* U_EXPORT2 -ucurr_getKeywordValuesForLocale(const char* key, - const char* locale, - UBool commonlyUsed, - UErrorCode* status); - -/** - * Returns the ISO 4217 numeric code for the currency. - *

Note: If the ISO 4217 numeric code is not assigned for the currency or - * the currency is unknown, this function returns 0. - * - * @param currency null-terminated 3-letter ISO 4217 code - * @return The ISO 4217 numeric code of the currency - * @stable ICU 49 - */ -U_STABLE int32_t U_EXPORT2 -ucurr_getNumericCode(const UChar* currency); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/udat.h b/win32/include/spidermonkey/unicode/udat.h deleted file mode 100755 index cacfbe85..00000000 --- a/win32/include/spidermonkey/unicode/udat.h +++ /dev/null @@ -1,1662 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * Copyright (C) 1996-2016, International Business Machines - * Corporation and others. All Rights Reserved. - ******************************************************************************* -*/ - -#ifndef UDAT_H -#define UDAT_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/localpointer.h" -#include "unicode/ucal.h" -#include "unicode/unum.h" -#include "unicode/udisplaycontext.h" -#include "unicode/ufieldpositer.h" -/** - * \file - * \brief C API: DateFormat - * - *

Date Format C API

- * - * Date Format C API consists of functions that convert dates and - * times from their internal representations to textual form and back again in a - * language-independent manner. Converting from the internal representation (milliseconds - * since midnight, January 1, 1970) to text is known as "formatting," and converting - * from text to millis is known as "parsing." We currently define only one concrete - * structure UDateFormat, which can handle pretty much all normal - * date formatting and parsing actions. - *

- * Date Format helps you to format and parse dates for any locale. Your code can - * be completely independent of the locale conventions for months, days of the - * week, or even the calendar format: lunar vs. solar. - *

- * To format a date for the current Locale with default time and date style, - * use one of the static factory methods: - *

- * \code
- *  UErrorCode status = U_ZERO_ERROR;
- *  UChar *myString;
- *  int32_t myStrlen = 0;
- *  UDateFormat* dfmt = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, -1, &status);
- *  myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, NULL, &status);
- *  if (status==U_BUFFER_OVERFLOW_ERROR){
- *      status=U_ZERO_ERROR;
- *      myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
- *      udat_format(dfmt, myDate, myString, myStrlen+1, NULL, &status);
- *  }
- * \endcode
- * 
- * If you are formatting multiple numbers, it is more efficient to get the - * format and use it multiple times so that the system doesn't have to fetch the - * information about the local language and country conventions multiple times. - *
- * \code
- *  UErrorCode status = U_ZERO_ERROR;
- *  int32_t i, myStrlen = 0;
- *  UChar* myString;
- *  char buffer[1024];
- *  UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
- *  UDateFormat* df = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, 0, &status);
- *  for (i = 0; i < 3; i++) {
- *      myStrlen = udat_format(df, myDateArr[i], NULL, myStrlen, NULL, &status);
- *      if(status == U_BUFFER_OVERFLOW_ERROR){
- *          status = U_ZERO_ERROR;
- *          myString = (UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
- *          udat_format(df, myDateArr[i], myString, myStrlen+1, NULL, &status);
- *          printf("%s\n", u_austrcpy(buffer, myString) );
- *          free(myString);
- *      }
- *  }
- * \endcode
- * 
- * To get specific fields of a date, you can use UFieldPosition to - * get specific fields. - *
- * \code
- *  UErrorCode status = U_ZERO_ERROR;
- *  UFieldPosition pos;
- *  UChar *myString;
- *  int32_t myStrlen = 0;
- *  char buffer[1024];
- *
- *  pos.field = 1;  // Same as the DateFormat::EField enum
- *  UDateFormat* dfmt = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, -1, NULL, 0, &status);
- *  myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, &pos, &status);
- *  if (status==U_BUFFER_OVERFLOW_ERROR){
- *      status=U_ZERO_ERROR;
- *      myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
- *      udat_format(dfmt, myDate, myString, myStrlen+1, &pos, &status);
- *  }
- *  printf("date format: %s\n", u_austrcpy(buffer, myString));
- *  buffer[pos.endIndex] = 0;   // NULL terminate the string.
- *  printf("UFieldPosition position equals %s\n", &buffer[pos.beginIndex]);
- * \endcode
- * 
- * To format a date for a different Locale, specify it in the call to - * udat_open() - *
- * \code
- *        UDateFormat* df = udat_open(UDAT_SHORT, UDAT_SHORT, "fr_FR", NULL, -1, NULL, 0, &status);
- * \endcode
- * 
- * You can use a DateFormat API udat_parse() to parse. - *
- * \code
- *  UErrorCode status = U_ZERO_ERROR;
- *  int32_t parsepos=0;
- *  UDate myDate = udat_parse(df, myString, u_strlen(myString), &parsepos, &status);
- * \endcode
- * 
- * You can pass in different options for the arguments for date and time style - * to control the length of the result; from SHORT to MEDIUM to LONG to FULL. - * The exact result depends on the locale, but generally: - * see UDateFormatStyle for more details - *
    - *
  • UDAT_SHORT is completely numeric, such as 12/13/52 or 3:30pm - *
  • UDAT_MEDIUM is longer, such as Jan 12, 1952 - *
  • UDAT_LONG is longer, such as January 12, 1952 or 3:30:32pm - *
  • UDAT_FULL is pretty completely specified, such as - * Tuesday, April 12, 1952 AD or 3:30:42pm PST. - *
- * You can also set the time zone on the format if you wish. - *

- * You can also use forms of the parse and format methods with Parse Position and - * UFieldPosition to allow you to - *

    - *
  • Progressively parse through pieces of a string. - *
  • Align any particular field, or find out where it is for selection - * on the screen. - *
- *

Date and Time Patterns:

- * - *

Date and time formats are specified by date and time pattern strings. - * Within date and time pattern strings, all unquoted ASCII letters [A-Za-z] are reserved - * as pattern letters representing calendar fields. UDateFormat supports - * the date and time formatting algorithm and pattern letters defined by - * UTS#35 - * Unicode Locale Data Markup Language (LDML) and further documented for ICU in the - * ICU - * User Guide.

- */ - -/** A date formatter. - * For usage in C programs. - * @stable ICU 2.6 - */ -typedef void* UDateFormat; - -/** The possible date/time format styles - * @stable ICU 2.6 - */ -typedef enum UDateFormatStyle { - /** Full style */ - UDAT_FULL, - /** Long style */ - UDAT_LONG, - /** Medium style */ - UDAT_MEDIUM, - /** Short style */ - UDAT_SHORT, - /** Default style */ - UDAT_DEFAULT = UDAT_MEDIUM, - - /** Bitfield for relative date */ - UDAT_RELATIVE = (1 << 7), - - UDAT_FULL_RELATIVE = UDAT_FULL | UDAT_RELATIVE, - - UDAT_LONG_RELATIVE = UDAT_LONG | UDAT_RELATIVE, - - UDAT_MEDIUM_RELATIVE = UDAT_MEDIUM | UDAT_RELATIVE, - - UDAT_SHORT_RELATIVE = UDAT_SHORT | UDAT_RELATIVE, - - - /** No style */ - UDAT_NONE = -1, - - /** - * Use the pattern given in the parameter to udat_open - * @see udat_open - * @stable ICU 50 - */ - UDAT_PATTERN = -2, - -#ifndef U_HIDE_INTERNAL_API - /** @internal alias to UDAT_PATTERN */ - UDAT_IGNORE = UDAT_PATTERN -#endif /* U_HIDE_INTERNAL_API */ -} UDateFormatStyle; - -/* Skeletons for dates. */ - -/** - * Constant for date skeleton with year. - * @stable ICU 4.0 - */ -#define UDAT_YEAR "y" -/** - * Constant for date skeleton with quarter. - * @stable ICU 51 - */ -#define UDAT_QUARTER "QQQQ" -/** - * Constant for date skeleton with abbreviated quarter. - * @stable ICU 51 - */ -#define UDAT_ABBR_QUARTER "QQQ" -/** - * Constant for date skeleton with year and quarter. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_QUARTER "yQQQQ" -/** - * Constant for date skeleton with year and abbreviated quarter. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_ABBR_QUARTER "yQQQ" -/** - * Constant for date skeleton with month. - * @stable ICU 4.0 - */ -#define UDAT_MONTH "MMMM" -/** - * Constant for date skeleton with abbreviated month. - * @stable ICU 4.0 - */ -#define UDAT_ABBR_MONTH "MMM" -/** - * Constant for date skeleton with numeric month. - * @stable ICU 4.0 - */ -#define UDAT_NUM_MONTH "M" -/** - * Constant for date skeleton with year and month. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_MONTH "yMMMM" -/** - * Constant for date skeleton with year and abbreviated month. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_ABBR_MONTH "yMMM" -/** - * Constant for date skeleton with year and numeric month. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_NUM_MONTH "yM" -/** - * Constant for date skeleton with day. - * @stable ICU 4.0 - */ -#define UDAT_DAY "d" -/** - * Constant for date skeleton with year, month, and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_MONTH_DAY "yMMMMd" -/** - * Constant for date skeleton with year, abbreviated month, and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_ABBR_MONTH_DAY "yMMMd" -/** - * Constant for date skeleton with year, numeric month, and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_NUM_MONTH_DAY "yMd" -/** - * Constant for date skeleton with weekday. - * @stable ICU 51 - */ -#define UDAT_WEEKDAY "EEEE" -/** - * Constant for date skeleton with abbreviated weekday. - * @stable ICU 51 - */ -#define UDAT_ABBR_WEEKDAY "E" -/** - * Constant for date skeleton with year, month, weekday, and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_MONTH_WEEKDAY_DAY "yMMMMEEEEd" -/** - * Constant for date skeleton with year, abbreviated month, weekday, and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY "yMMMEd" -/** - * Constant for date skeleton with year, numeric month, weekday, and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_YEAR_NUM_MONTH_WEEKDAY_DAY "yMEd" -/** - * Constant for date skeleton with long month and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_MONTH_DAY "MMMMd" -/** - * Constant for date skeleton with abbreviated month and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_ABBR_MONTH_DAY "MMMd" -/** - * Constant for date skeleton with numeric month and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_NUM_MONTH_DAY "Md" -/** - * Constant for date skeleton with month, weekday, and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_MONTH_WEEKDAY_DAY "MMMMEEEEd" -/** - * Constant for date skeleton with abbreviated month, weekday, and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_ABBR_MONTH_WEEKDAY_DAY "MMMEd" -/** - * Constant for date skeleton with numeric month, weekday, and day. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_NUM_MONTH_WEEKDAY_DAY "MEd" - -/* Skeletons for times. */ - -/** - * Constant for date skeleton with hour, with the locale's preferred hour format (12 or 24). - * @stable ICU 4.0 - */ -#define UDAT_HOUR "j" -/** - * Constant for date skeleton with hour in 24-hour presentation. - * @stable ICU 51 - */ -#define UDAT_HOUR24 "H" -/** - * Constant for date skeleton with minute. - * @stable ICU 51 - */ -#define UDAT_MINUTE "m" -/** - * Constant for date skeleton with hour and minute, with the locale's preferred hour format (12 or 24). - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_HOUR_MINUTE "jm" -/** - * Constant for date skeleton with hour and minute in 24-hour presentation. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_HOUR24_MINUTE "Hm" -/** - * Constant for date skeleton with second. - * @stable ICU 51 - */ -#define UDAT_SECOND "s" -/** - * Constant for date skeleton with hour, minute, and second, - * with the locale's preferred hour format (12 or 24). - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_HOUR_MINUTE_SECOND "jms" -/** - * Constant for date skeleton with hour, minute, and second in - * 24-hour presentation. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_HOUR24_MINUTE_SECOND "Hms" -/** - * Constant for date skeleton with minute and second. - * Used in combinations date + time, date + time + zone, or time + zone. - * @stable ICU 4.0 - */ -#define UDAT_MINUTE_SECOND "ms" - -/* Skeletons for time zones. */ - -/** - * Constant for generic location format, such as Los Angeles Time; - * used in combinations date + time + zone, or time + zone. - * @see LDML Date Format Patterns - * @see LDML Time Zone Fallback - * @stable ICU 51 - */ -#define UDAT_LOCATION_TZ "VVVV" -/** - * Constant for generic non-location format, such as Pacific Time; - * used in combinations date + time + zone, or time + zone. - * @see LDML Date Format Patterns - * @see LDML Time Zone Fallback - * @stable ICU 51 - */ -#define UDAT_GENERIC_TZ "vvvv" -/** - * Constant for generic non-location format, abbreviated if possible, such as PT; - * used in combinations date + time + zone, or time + zone. - * @see LDML Date Format Patterns - * @see LDML Time Zone Fallback - * @stable ICU 51 - */ -#define UDAT_ABBR_GENERIC_TZ "v" -/** - * Constant for specific non-location format, such as Pacific Daylight Time; - * used in combinations date + time + zone, or time + zone. - * @see LDML Date Format Patterns - * @see LDML Time Zone Fallback - * @stable ICU 51 - */ -#define UDAT_SPECIFIC_TZ "zzzz" -/** - * Constant for specific non-location format, abbreviated if possible, such as PDT; - * used in combinations date + time + zone, or time + zone. - * @see LDML Date Format Patterns - * @see LDML Time Zone Fallback - * @stable ICU 51 - */ -#define UDAT_ABBR_SPECIFIC_TZ "z" -/** - * Constant for localized GMT/UTC format, such as GMT+8:00 or HPG-8:00; - * used in combinations date + time + zone, or time + zone. - * @see LDML Date Format Patterns - * @see LDML Time Zone Fallback - * @stable ICU 51 - */ -#define UDAT_ABBR_UTC_TZ "ZZZZ" - -/* deprecated skeleton constants */ - -#ifndef U_HIDE_DEPRECATED_API -/** - * Constant for date skeleton with standalone month. - * @deprecated ICU 50 Use UDAT_MONTH instead. - */ -#define UDAT_STANDALONE_MONTH "LLLL" -/** - * Constant for date skeleton with standalone abbreviated month. - * @deprecated ICU 50 Use UDAT_ABBR_MONTH instead. - */ -#define UDAT_ABBR_STANDALONE_MONTH "LLL" - -/** - * Constant for date skeleton with hour, minute, and generic timezone. - * @deprecated ICU 50 Use instead UDAT_HOUR_MINUTE UDAT_ABBR_GENERIC_TZ or some other timezone presentation. - */ -#define UDAT_HOUR_MINUTE_GENERIC_TZ "jmv" -/** - * Constant for date skeleton with hour, minute, and timezone. - * @deprecated ICU 50 Use instead UDAT_HOUR_MINUTE UDAT_ABBR_SPECIFIC_TZ or some other timezone presentation. - */ -#define UDAT_HOUR_MINUTE_TZ "jmz" -/** - * Constant for date skeleton with hour and generic timezone. - * @deprecated ICU 50 Use instead UDAT_HOUR UDAT_ABBR_GENERIC_TZ or some other timezone presentation. - */ -#define UDAT_HOUR_GENERIC_TZ "jv" -/** - * Constant for date skeleton with hour and timezone. - * @deprecated ICU 50 Use instead UDAT_HOUR UDAT_ABBR_SPECIFIC_TZ or some other timezone presentation. - */ -#define UDAT_HOUR_TZ "jz" -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * FieldPosition and UFieldPosition selectors for format fields - * defined by DateFormat and UDateFormat. - * @stable ICU 3.0 - */ -typedef enum UDateFormatField { - /** - * FieldPosition and UFieldPosition selector for 'G' field alignment, - * corresponding to the UCAL_ERA field. - * @stable ICU 3.0 - */ - UDAT_ERA_FIELD = 0, - - /** - * FieldPosition and UFieldPosition selector for 'y' field alignment, - * corresponding to the UCAL_YEAR field. - * @stable ICU 3.0 - */ - UDAT_YEAR_FIELD = 1, - - /** - * FieldPosition and UFieldPosition selector for 'M' field alignment, - * corresponding to the UCAL_MONTH field. - * @stable ICU 3.0 - */ - UDAT_MONTH_FIELD = 2, - - /** - * FieldPosition and UFieldPosition selector for 'd' field alignment, - * corresponding to the UCAL_DATE field. - * @stable ICU 3.0 - */ - UDAT_DATE_FIELD = 3, - - /** - * FieldPosition and UFieldPosition selector for 'k' field alignment, - * corresponding to the UCAL_HOUR_OF_DAY field. - * UDAT_HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock. - * For example, 23:59 + 01:00 results in 24:59. - * @stable ICU 3.0 - */ - UDAT_HOUR_OF_DAY1_FIELD = 4, - - /** - * FieldPosition and UFieldPosition selector for 'H' field alignment, - * corresponding to the UCAL_HOUR_OF_DAY field. - * UDAT_HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock. - * For example, 23:59 + 01:00 results in 00:59. - * @stable ICU 3.0 - */ - UDAT_HOUR_OF_DAY0_FIELD = 5, - - /** - * FieldPosition and UFieldPosition selector for 'm' field alignment, - * corresponding to the UCAL_MINUTE field. - * @stable ICU 3.0 - */ - UDAT_MINUTE_FIELD = 6, - - /** - * FieldPosition and UFieldPosition selector for 's' field alignment, - * corresponding to the UCAL_SECOND field. - * @stable ICU 3.0 - */ - UDAT_SECOND_FIELD = 7, - - /** - * FieldPosition and UFieldPosition selector for 'S' field alignment, - * corresponding to the UCAL_MILLISECOND field. - * - * Note: Time formats that use 'S' can display a maximum of three - * significant digits for fractional seconds, corresponding to millisecond - * resolution and a fractional seconds sub-pattern of SSS. If the - * sub-pattern is S or SS, the fractional seconds value will be truncated - * (not rounded) to the number of display places specified. If the - * fractional seconds sub-pattern is longer than SSS, the additional - * display places will be filled with zeros. - * @stable ICU 3.0 - */ - UDAT_FRACTIONAL_SECOND_FIELD = 8, - - /** - * FieldPosition and UFieldPosition selector for 'E' field alignment, - * corresponding to the UCAL_DAY_OF_WEEK field. - * @stable ICU 3.0 - */ - UDAT_DAY_OF_WEEK_FIELD = 9, - - /** - * FieldPosition and UFieldPosition selector for 'D' field alignment, - * corresponding to the UCAL_DAY_OF_YEAR field. - * @stable ICU 3.0 - */ - UDAT_DAY_OF_YEAR_FIELD = 10, - - /** - * FieldPosition and UFieldPosition selector for 'F' field alignment, - * corresponding to the UCAL_DAY_OF_WEEK_IN_MONTH field. - * @stable ICU 3.0 - */ - UDAT_DAY_OF_WEEK_IN_MONTH_FIELD = 11, - - /** - * FieldPosition and UFieldPosition selector for 'w' field alignment, - * corresponding to the UCAL_WEEK_OF_YEAR field. - * @stable ICU 3.0 - */ - UDAT_WEEK_OF_YEAR_FIELD = 12, - - /** - * FieldPosition and UFieldPosition selector for 'W' field alignment, - * corresponding to the UCAL_WEEK_OF_MONTH field. - * @stable ICU 3.0 - */ - UDAT_WEEK_OF_MONTH_FIELD = 13, - - /** - * FieldPosition and UFieldPosition selector for 'a' field alignment, - * corresponding to the UCAL_AM_PM field. - * @stable ICU 3.0 - */ - UDAT_AM_PM_FIELD = 14, - - /** - * FieldPosition and UFieldPosition selector for 'h' field alignment, - * corresponding to the UCAL_HOUR field. - * UDAT_HOUR1_FIELD is used for the one-based 12-hour clock. - * For example, 11:30 PM + 1 hour results in 12:30 AM. - * @stable ICU 3.0 - */ - UDAT_HOUR1_FIELD = 15, - - /** - * FieldPosition and UFieldPosition selector for 'K' field alignment, - * corresponding to the UCAL_HOUR field. - * UDAT_HOUR0_FIELD is used for the zero-based 12-hour clock. - * For example, 11:30 PM + 1 hour results in 00:30 AM. - * @stable ICU 3.0 - */ - UDAT_HOUR0_FIELD = 16, - - /** - * FieldPosition and UFieldPosition selector for 'z' field alignment, - * corresponding to the UCAL_ZONE_OFFSET and - * UCAL_DST_OFFSET fields. - * @stable ICU 3.0 - */ - UDAT_TIMEZONE_FIELD = 17, - - /** - * FieldPosition and UFieldPosition selector for 'Y' field alignment, - * corresponding to the UCAL_YEAR_WOY field. - * @stable ICU 3.0 - */ - UDAT_YEAR_WOY_FIELD = 18, - - /** - * FieldPosition and UFieldPosition selector for 'e' field alignment, - * corresponding to the UCAL_DOW_LOCAL field. - * @stable ICU 3.0 - */ - UDAT_DOW_LOCAL_FIELD = 19, - - /** - * FieldPosition and UFieldPosition selector for 'u' field alignment, - * corresponding to the UCAL_EXTENDED_YEAR field. - * @stable ICU 3.0 - */ - UDAT_EXTENDED_YEAR_FIELD = 20, - - /** - * FieldPosition and UFieldPosition selector for 'g' field alignment, - * corresponding to the UCAL_JULIAN_DAY field. - * @stable ICU 3.0 - */ - UDAT_JULIAN_DAY_FIELD = 21, - - /** - * FieldPosition and UFieldPosition selector for 'A' field alignment, - * corresponding to the UCAL_MILLISECONDS_IN_DAY field. - * @stable ICU 3.0 - */ - UDAT_MILLISECONDS_IN_DAY_FIELD = 22, - - /** - * FieldPosition and UFieldPosition selector for 'Z' field alignment, - * corresponding to the UCAL_ZONE_OFFSET and - * UCAL_DST_OFFSET fields. - * @stable ICU 3.0 - */ - UDAT_TIMEZONE_RFC_FIELD = 23, - - /** - * FieldPosition and UFieldPosition selector for 'v' field alignment, - * corresponding to the UCAL_ZONE_OFFSET field. - * @stable ICU 3.4 - */ - UDAT_TIMEZONE_GENERIC_FIELD = 24, - /** - * FieldPosition selector for 'c' field alignment, - * corresponding to the {@link #UCAL_DOW_LOCAL} field. - * This displays the stand alone day name, if available. - * @stable ICU 3.4 - */ - UDAT_STANDALONE_DAY_FIELD = 25, - - /** - * FieldPosition selector for 'L' field alignment, - * corresponding to the {@link #UCAL_MONTH} field. - * This displays the stand alone month name, if available. - * @stable ICU 3.4 - */ - UDAT_STANDALONE_MONTH_FIELD = 26, - - /** - * FieldPosition selector for "Q" field alignment, - * corresponding to quarters. This is implemented - * using the {@link #UCAL_MONTH} field. This - * displays the quarter. - * @stable ICU 3.6 - */ - UDAT_QUARTER_FIELD = 27, - - /** - * FieldPosition selector for the "q" field alignment, - * corresponding to stand-alone quarters. This is - * implemented using the {@link #UCAL_MONTH} field. - * This displays the stand-alone quarter. - * @stable ICU 3.6 - */ - UDAT_STANDALONE_QUARTER_FIELD = 28, - - /** - * FieldPosition and UFieldPosition selector for 'V' field alignment, - * corresponding to the UCAL_ZONE_OFFSET field. - * @stable ICU 3.8 - */ - UDAT_TIMEZONE_SPECIAL_FIELD = 29, - - /** - * FieldPosition selector for "U" field alignment, - * corresponding to cyclic year names. This is implemented - * using the {@link #UCAL_YEAR} field. This displays - * the cyclic year name, if available. - * @stable ICU 49 - */ - UDAT_YEAR_NAME_FIELD = 30, - - /** - * FieldPosition selector for 'O' field alignment, - * corresponding to the UCAL_ZONE_OFFSET and UCAL_DST_OFFSETfields. - * This displays the localized GMT format. - * @stable ICU 51 - */ - UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD = 31, - - /** - * FieldPosition selector for 'X' field alignment, - * corresponding to the UCAL_ZONE_OFFSET and UCAL_DST_OFFSETfields. - * This displays the ISO 8601 local time offset format or UTC indicator ("Z"). - * @stable ICU 51 - */ - UDAT_TIMEZONE_ISO_FIELD = 32, - - /** - * FieldPosition selector for 'x' field alignment, - * corresponding to the UCAL_ZONE_OFFSET and UCAL_DST_OFFSET fields. - * This displays the ISO 8601 local time offset format. - * @stable ICU 51 - */ - UDAT_TIMEZONE_ISO_LOCAL_FIELD = 33, - -#ifndef U_HIDE_INTERNAL_API - /** - * FieldPosition and UFieldPosition selector for 'r' field alignment, - * no directly corresponding UCAL_ field. - * @internal ICU 53 - */ - UDAT_RELATED_YEAR_FIELD = 34, -#endif /* U_HIDE_INTERNAL_API */ - -#ifndef U_HIDE_DRAFT_API - /** - * FieldPosition selector for 'b' field alignment. - * Displays midnight and noon for 12am and 12pm, respectively, if available; - * otherwise fall back to AM / PM. - * @draft ICU 57 - */ - UDAT_AM_PM_MIDNIGHT_NOON_FIELD = 35, - - /* FieldPosition selector for 'B' field alignment. - * Displays flexible day periods, such as "in the morning", if available. - * @draft ICU 57 - */ - UDAT_FLEXIBLE_DAY_PERIOD_FIELD = 36, -#endif /* U_HIDE_DRAFT_API */ - -#ifndef U_HIDE_INTERNAL_API - /** - * FieldPosition and UFieldPosition selector for time separator, - * no corresponding UCAL_ field. No pattern character is currently - * defined for this. - * @internal - */ - UDAT_TIME_SEPARATOR_FIELD = 37, -#endif /* U_HIDE_INTERNAL_API */ - -#ifndef U_HIDE_DEPRECATED_API - /** - * Number of FieldPosition and UFieldPosition selectors for - * DateFormat and UDateFormat. - * Valid selectors range from 0 to UDAT_FIELD_COUNT-1. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UDAT_FIELD_COUNT = 38 -#endif // U_HIDE_DEPRECATED_API -} UDateFormatField; - - -#ifndef U_HIDE_INTERNAL_API -/** - * Is a pattern character defined for UDAT_TIME_SEPARATOR_FIELD? - * In ICU 55 it was COLON, but that was withdrawn in ICU 56. - * @internal ICU 56 - */ -#define UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR 0 -#endif /* U_HIDE_INTERNAL_API */ - - -/** - * Maps from a UDateFormatField to the corresponding UCalendarDateFields. - * Note: since the mapping is many-to-one, there is no inverse mapping. - * @param field the UDateFormatField. - * @return the UCalendarDateField. This will be UCAL_FIELD_COUNT in case - * of error (e.g., the input field is UDAT_FIELD_COUNT). - * @stable ICU 4.4 - */ -U_STABLE UCalendarDateFields U_EXPORT2 -udat_toCalendarDateField(UDateFormatField field); - - -/** - * Open a new UDateFormat for formatting and parsing dates and times. - * A UDateFormat may be used to format dates in calls to {@link #udat_format }, - * and to parse dates in calls to {@link #udat_parse }. - * @param timeStyle The style used to format times; one of UDAT_FULL, UDAT_LONG, - * UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT, or UDAT_NONE (relative time styles - * are not currently supported). - * When the pattern parameter is used, pass in UDAT_PATTERN for both timeStyle and dateStyle. - * @param dateStyle The style used to format dates; one of UDAT_FULL, UDAT_LONG, - * UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT, UDAT_FULL_RELATIVE, UDAT_LONG_RELATIVE, - * UDAT_MEDIUM_RELATIVE, UDAT_SHORT_RELATIVE, or UDAT_NONE. - * When the pattern parameter is used, pass in UDAT_PATTERN for both timeStyle and dateStyle. - * As currently implemented, - * relative date formatting only affects a limited range of calendar days before or - * after the current date, based on the CLDR <field type="day">/<relative> data: For - * example, in English, "Yesterday", "Today", and "Tomorrow". Outside of this range, - * dates are formatted using the corresponding non-relative style. - * @param locale The locale specifying the formatting conventions - * @param tzID A timezone ID specifying the timezone to use. If 0, use - * the default timezone. - * @param tzIDLength The length of tzID, or -1 if null-terminated. - * @param pattern A pattern specifying the format to use. - * @param patternLength The number of characters in the pattern, or -1 if null-terminated. - * @param status A pointer to an UErrorCode to receive any errors - * @return A pointer to a UDateFormat to use for formatting dates and times, or 0 if - * an error occurred. - * @stable ICU 2.0 - */ -U_STABLE UDateFormat* U_EXPORT2 -udat_open(UDateFormatStyle timeStyle, - UDateFormatStyle dateStyle, - const char *locale, - const UChar *tzID, - int32_t tzIDLength, - const UChar *pattern, - int32_t patternLength, - UErrorCode *status); - - -/** -* Close a UDateFormat. -* Once closed, a UDateFormat may no longer be used. -* @param format The formatter to close. -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -udat_close(UDateFormat* format); - - -/** - * DateFormat boolean attributes - * - * @stable ICU 53 - */ -typedef enum UDateFormatBooleanAttribute { - /** - * indicates whether whitespace is allowed. Includes trailing dot tolerance. - * @stable ICU 53 - */ - UDAT_PARSE_ALLOW_WHITESPACE = 0, - /** - * indicates tolerance of numeric data when String data may be assumed. eg: UDAT_YEAR_NAME_FIELD, - * UDAT_STANDALONE_MONTH_FIELD, UDAT_DAY_OF_WEEK_FIELD - * @stable ICU 53 - */ - UDAT_PARSE_ALLOW_NUMERIC = 1, - /** - * indicates tolerance of a partial literal match - * e.g. accepting "--mon-02-march-2011" for a pattern of "'--: 'EEE-WW-MMMM-yyyy" - * @stable ICU 56 - */ - UDAT_PARSE_PARTIAL_LITERAL_MATCH = 2, - /** - * indicates tolerance of pattern mismatch between input data and specified format pattern. - * e.g. accepting "September" for a month pattern of MMM ("Sep") - * @stable ICU 56 - */ - UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH = 3, - - // Do not conditionalize the following with #ifndef U_HIDE_DEPRECATED_API, - // it is needed for layout of DateFormat object. - /** - * One more than the highest normal UDateFormatBooleanAttribute value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UDAT_BOOLEAN_ATTRIBUTE_COUNT = 4 -} UDateFormatBooleanAttribute; - -/** - * Get a boolean attribute associated with a UDateFormat. - * An example would be a true value for a key of UDAT_PARSE_ALLOW_WHITESPACE indicating allowing whitespace leniency. - * If the formatter does not understand the attribute, -1 is returned. - * @param fmt The formatter to query. - * @param attr The attribute to query; e.g. UDAT_PARSE_ALLOW_WHITESPACE. - * @param status A pointer to an UErrorCode to receive any errors - * @return The value of attr. - * @stable ICU 53 - */ -U_STABLE UBool U_EXPORT2 -udat_getBooleanAttribute(const UDateFormat* fmt, UDateFormatBooleanAttribute attr, UErrorCode* status); - -/** - * Set a boolean attribute associated with a UDateFormat. - * An example of a boolean attribute is parse leniency control. If the formatter does not understand - * the attribute, the call is ignored. - * @param fmt The formatter to set. - * @param attr The attribute to set; one of UDAT_PARSE_ALLOW_WHITESPACE or UDAT_PARSE_ALLOW_NUMERIC - * @param newValue The new value of attr. - * @param status A pointer to an UErrorCode to receive any errors - * @stable ICU 53 - */ -U_STABLE void U_EXPORT2 -udat_setBooleanAttribute(UDateFormat *fmt, UDateFormatBooleanAttribute attr, UBool newValue, UErrorCode* status); - - - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUDateFormatPointer - * "Smart pointer" class, closes a UDateFormat via udat_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateFormatPointer, UDateFormat, udat_close); - -U_NAMESPACE_END - -#endif - -/** - * Open a copy of a UDateFormat. - * This function performs a deep copy. - * @param fmt The format to copy - * @param status A pointer to an UErrorCode to receive any errors. - * @return A pointer to a UDateFormat identical to fmt. - * @stable ICU 2.0 - */ -U_STABLE UDateFormat* U_EXPORT2 -udat_clone(const UDateFormat *fmt, - UErrorCode *status); - -/** -* Format a date using a UDateFormat. -* The date will be formatted using the conventions specified in {@link #udat_open } -* @param format The formatter to use -* @param dateToFormat The date to format -* @param result A pointer to a buffer to receive the formatted number. -* @param resultLength The maximum size of result. -* @param position A pointer to a UFieldPosition. On input, position->field -* is read. On output, position->beginIndex and position->endIndex indicate -* the beginning and ending indices of field number position->field, if such -* a field exists. This parameter may be NULL, in which case no field -* position data is returned. -* @param status A pointer to an UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see udat_parse -* @see UFieldPosition -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -udat_format( const UDateFormat* format, - UDate dateToFormat, - UChar* result, - int32_t resultLength, - UFieldPosition* position, - UErrorCode* status); - -/** -* Format a date using an UDateFormat. -* The date will be formatted using the conventions specified in {@link #udat_open } -* @param format The formatter to use -* @param calendar The calendar to format. The calendar instance might be -* mutated if fields are not yet fully calculated, though -* the function won't change the logical date and time held -* by the instance. -* @param result A pointer to a buffer to receive the formatted number. -* @param capacity The maximum size of result. -* @param position A pointer to a UFieldPosition. On input, position->field -* is read. On output, position->beginIndex and position->endIndex indicate -* the beginning and ending indices of field number position->field, if such -* a field exists. This parameter may be NULL, in which case no field -* position data is returned. -* @param status A pointer to an UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see udat_format -* @see udat_parseCalendar -* @see UFieldPosition -* @stable ICU 55 -*/ -U_STABLE int32_t U_EXPORT2 -udat_formatCalendar( const UDateFormat* format, - UCalendar* calendar, - UChar* result, - int32_t capacity, - UFieldPosition* position, - UErrorCode* status); - -/** -* Format a date using a UDateFormat. -* The date will be formatted using the conventions specified in {@link #udat_open} -* @param format -* The formatter to use -* @param dateToFormat -* The date to format -* @param result -* A pointer to a buffer to receive the formatted number. -* @param resultLength -* The maximum size of result. -* @param fpositer -* A pointer to a UFieldPositionIterator created by {@link #ufieldpositer_open} -* (may be NULL if field position information is not needed). Any -* iteration information already present in the UFieldPositionIterator -* will be deleted, and the iterator will be reset to apply to the -* fields in the formatted string created by this function call; the -* field values provided by {@link #ufieldpositer_next} will be from the -* UDateFormatField enum. -* @param status -* A pointer to a UErrorCode to receive any errors -* @return -* The total buffer size needed; if greater than resultLength, the output was truncated. -* @see udat_parse -* @see UFieldPositionIterator -* @stable ICU 55 -*/ -U_STABLE int32_t U_EXPORT2 -udat_formatForFields( const UDateFormat* format, - UDate dateToFormat, - UChar* result, - int32_t resultLength, - UFieldPositionIterator* fpositer, - UErrorCode* status); - -/** -* Format a date using a UDateFormat. -* The date will be formatted using the conventions specified in {@link #udat_open } -* @param format -* The formatter to use -* @param calendar -* The calendar to format. The calendar instance might be mutated if fields -* are not yet fully calculated, though the function won't change the logical -* date and time held by the instance. -* @param result -* A pointer to a buffer to receive the formatted number. -* @param capacity -* The maximum size of result. -* @param fpositer -* A pointer to a UFieldPositionIterator created by {@link #ufieldpositer_open} -* (may be NULL if field position information is not needed). Any -* iteration information already present in the UFieldPositionIterator -* will be deleted, and the iterator will be reset to apply to the -* fields in the formatted string created by this function call; the -* field values provided by {@link #ufieldpositer_next} will be from the -* UDateFormatField enum. -* @param status -* A pointer to a UErrorCode to receive any errors -* @return -* The total buffer size needed; if greater than resultLength, the output was truncated. -* @see udat_format -* @see udat_parseCalendar -* @see UFieldPositionIterator -* @stable ICU 55 -*/ -U_STABLE int32_t U_EXPORT2 -udat_formatCalendarForFields( const UDateFormat* format, - UCalendar* calendar, - UChar* result, - int32_t capacity, - UFieldPositionIterator* fpositer, - UErrorCode* status); - - -/** -* Parse a string into an date/time using a UDateFormat. -* The date will be parsed using the conventions specified in {@link #udat_open }. -*

-* Note that the normal date formats associated with some calendars - such -* as the Chinese lunar calendar - do not specify enough fields to enable -* dates to be parsed unambiguously. In the case of the Chinese lunar -* calendar, while the year within the current 60-year cycle is specified, -* the number of such cycles since the start date of the calendar (in the -* UCAL_ERA field of the UCalendar object) is not normally part of the format, -* and parsing may assume the wrong era. For cases such as this it is -* recommended that clients parse using udat_parseCalendar with the UCalendar -* passed in set to the current date, or to a date within the era/cycle that -* should be assumed if absent in the format. -* -* @param format The formatter to use. -* @param text The text to parse. -* @param textLength The length of text, or -1 if null-terminated. -* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which -* to begin parsing. If not 0, on output the offset at which parsing ended. -* @param status A pointer to an UErrorCode to receive any errors -* @return The value of the parsed date/time -* @see udat_format -* @stable ICU 2.0 -*/ -U_STABLE UDate U_EXPORT2 -udat_parse(const UDateFormat* format, - const UChar* text, - int32_t textLength, - int32_t *parsePos, - UErrorCode *status); - -/** -* Parse a string into an date/time using a UDateFormat. -* The date will be parsed using the conventions specified in {@link #udat_open }. -* @param format The formatter to use. -* @param calendar A calendar set on input to the date and time to be used for -* missing values in the date/time string being parsed, and set -* on output to the parsed date/time. When the calendar type is -* different from the internal calendar held by the UDateFormat -* instance, the internal calendar will be cloned to a work -* calendar set to the same milliseconds and time zone as this -* calendar parameter, field values will be parsed based on the -* work calendar, then the result (milliseconds and time zone) -* will be set in this calendar. -* @param text The text to parse. -* @param textLength The length of text, or -1 if null-terminated. -* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which -* to begin parsing. If not 0, on output the offset at which parsing ended. -* @param status A pointer to an UErrorCode to receive any errors -* @see udat_format -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -udat_parseCalendar(const UDateFormat* format, - UCalendar* calendar, - const UChar* text, - int32_t textLength, - int32_t *parsePos, - UErrorCode *status); - -/** -* Determine if an UDateFormat will perform lenient parsing. -* With lenient parsing, the parser may use heuristics to interpret inputs that do not -* precisely match the pattern. With strict parsing, inputs must match the pattern. -* @param fmt The formatter to query -* @return TRUE if fmt is set to perform lenient parsing, FALSE otherwise. -* @see udat_setLenient -* @stable ICU 2.0 -*/ -U_STABLE UBool U_EXPORT2 -udat_isLenient(const UDateFormat* fmt); - -/** -* Specify whether an UDateFormat will perform lenient parsing. -* With lenient parsing, the parser may use heuristics to interpret inputs that do not -* precisely match the pattern. With strict parsing, inputs must match the pattern. -* @param fmt The formatter to set -* @param isLenient TRUE if fmt should perform lenient parsing, FALSE otherwise. -* @see dat_isLenient -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -udat_setLenient( UDateFormat* fmt, - UBool isLenient); - -/** -* Get the UCalendar associated with an UDateFormat. -* A UDateFormat uses a UCalendar to convert a raw value to, for example, -* the day of the week. -* @param fmt The formatter to query. -* @return A pointer to the UCalendar used by fmt. -* @see udat_setCalendar -* @stable ICU 2.0 -*/ -U_STABLE const UCalendar* U_EXPORT2 -udat_getCalendar(const UDateFormat* fmt); - -/** -* Set the UCalendar associated with an UDateFormat. -* A UDateFormat uses a UCalendar to convert a raw value to, for example, -* the day of the week. -* @param fmt The formatter to set. -* @param calendarToSet A pointer to an UCalendar to be used by fmt. -* @see udat_setCalendar -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -udat_setCalendar( UDateFormat* fmt, - const UCalendar* calendarToSet); - -/** -* Get the UNumberFormat associated with an UDateFormat. -* A UDateFormat uses a UNumberFormat to format numbers within a date, -* for example the day number. -* @param fmt The formatter to query. -* @return A pointer to the UNumberFormat used by fmt to format numbers. -* @see udat_setNumberFormat -* @stable ICU 2.0 -*/ -U_STABLE const UNumberFormat* U_EXPORT2 -udat_getNumberFormat(const UDateFormat* fmt); - -/** -* Get the UNumberFormat for specific field associated with an UDateFormat. -* For example: 'y' for year and 'M' for month -* @param fmt The formatter to query. -* @param field the field to query -* @return A pointer to the UNumberFormat used by fmt to format field numbers. -* @see udat_setNumberFormatForField -* @stable ICU 54 -*/ -U_STABLE const UNumberFormat* U_EXPORT2 -udat_getNumberFormatForField(const UDateFormat* fmt, UChar field); - -/** -* Set the UNumberFormat for specific field associated with an UDateFormat. -* It can be a single field like: "y"(year) or "M"(month) -* It can be several field combined together: "yM"(year and month) -* Note: -* 1 symbol field is enough for multiple symbol field (so "y" will override "yy", "yyy") -* If the field is not numeric, then override has no effect (like "MMM" will use abbreviation, not numerical field) -* -* @param fields the fields to set -* @param fmt The formatter to set. -* @param numberFormatToSet A pointer to the UNumberFormat to be used by fmt to format numbers. -* @param status error code passed around (memory allocation or invalid fields) -* @see udat_getNumberFormatForField -* @stable ICU 54 -*/ -U_STABLE void U_EXPORT2 -udat_adoptNumberFormatForFields( UDateFormat* fmt, - const UChar* fields, - UNumberFormat* numberFormatToSet, - UErrorCode* status); -/** -* Set the UNumberFormat associated with an UDateFormat. -* A UDateFormat uses a UNumberFormat to format numbers within a date, -* for example the day number. -* This method also clears per field NumberFormat instances previously -* set by {@see udat_setNumberFormatForField} -* @param fmt The formatter to set. -* @param numberFormatToSet A pointer to the UNumberFormat to be used by fmt to format numbers. -* @see udat_getNumberFormat -* @see udat_setNumberFormatForField -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -udat_setNumberFormat( UDateFormat* fmt, - const UNumberFormat* numberFormatToSet); -/** -* Adopt the UNumberFormat associated with an UDateFormat. -* A UDateFormat uses a UNumberFormat to format numbers within a date, -* for example the day number. -* @param fmt The formatter to set. -* @param numberFormatToAdopt A pointer to the UNumberFormat to be used by fmt to format numbers. -* @see udat_getNumberFormat -* @stable ICU 54 -*/ -U_STABLE void U_EXPORT2 -udat_adoptNumberFormat( UDateFormat* fmt, - UNumberFormat* numberFormatToAdopt); -/** -* Get a locale for which date/time formatting patterns are available. -* A UDateFormat in a locale returned by this function will perform the correct -* formatting and parsing for the locale. -* @param localeIndex The index of the desired locale. -* @return A locale for which date/time formatting patterns are available, or 0 if none. -* @see udat_countAvailable -* @stable ICU 2.0 -*/ -U_STABLE const char* U_EXPORT2 -udat_getAvailable(int32_t localeIndex); - -/** -* Determine how many locales have date/time formatting patterns available. -* This function is most useful as determining the loop ending condition for -* calls to {@link #udat_getAvailable }. -* @return The number of locales for which date/time formatting patterns are available. -* @see udat_getAvailable -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -udat_countAvailable(void); - -/** -* Get the year relative to which all 2-digit years are interpreted. -* For example, if the 2-digit start year is 2100, the year 99 will be -* interpreted as 2199. -* @param fmt The formatter to query. -* @param status A pointer to an UErrorCode to receive any errors -* @return The year relative to which all 2-digit years are interpreted. -* @see udat_Set2DigitYearStart -* @stable ICU 2.0 -*/ -U_STABLE UDate U_EXPORT2 -udat_get2DigitYearStart( const UDateFormat *fmt, - UErrorCode *status); - -/** -* Set the year relative to which all 2-digit years will be interpreted. -* For example, if the 2-digit start year is 2100, the year 99 will be -* interpreted as 2199. -* @param fmt The formatter to set. -* @param d The year relative to which all 2-digit years will be interpreted. -* @param status A pointer to an UErrorCode to receive any errors -* @see udat_Set2DigitYearStart -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -udat_set2DigitYearStart( UDateFormat *fmt, - UDate d, - UErrorCode *status); - -/** -* Extract the pattern from a UDateFormat. -* The pattern will follow the pattern syntax rules. -* @param fmt The formatter to query. -* @param localized TRUE if the pattern should be localized, FALSE otherwise. -* @param result A pointer to a buffer to receive the pattern. -* @param resultLength The maximum size of result. -* @param status A pointer to an UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see udat_applyPattern -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -udat_toPattern( const UDateFormat *fmt, - UBool localized, - UChar *result, - int32_t resultLength, - UErrorCode *status); - -/** -* Set the pattern used by an UDateFormat. -* The pattern should follow the pattern syntax rules. -* @param format The formatter to set. -* @param localized TRUE if the pattern is localized, FALSE otherwise. -* @param pattern The new pattern -* @param patternLength The length of pattern, or -1 if null-terminated. -* @see udat_toPattern -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -udat_applyPattern( UDateFormat *format, - UBool localized, - const UChar *pattern, - int32_t patternLength); - -/** - * The possible types of date format symbols - * @stable ICU 2.6 - */ -typedef enum UDateFormatSymbolType { - /** The era names, for example AD */ - UDAT_ERAS, - /** The month names, for example February */ - UDAT_MONTHS, - /** The short month names, for example Feb. */ - UDAT_SHORT_MONTHS, - /** The CLDR-style format "wide" weekday names, for example Monday */ - UDAT_WEEKDAYS, - /** - * The CLDR-style format "abbreviated" (not "short") weekday names, for example "Mon." - * For the CLDR-style format "short" weekday names, use UDAT_SHORTER_WEEKDAYS. - */ - UDAT_SHORT_WEEKDAYS, - /** The AM/PM names, for example AM */ - UDAT_AM_PMS, - /** The localized characters */ - UDAT_LOCALIZED_CHARS, - /** The long era names, for example Anno Domini */ - UDAT_ERA_NAMES, - /** The narrow month names, for example F */ - UDAT_NARROW_MONTHS, - /** The CLDR-style format "narrow" weekday names, for example "M" */ - UDAT_NARROW_WEEKDAYS, - /** Standalone context versions of months */ - UDAT_STANDALONE_MONTHS, - UDAT_STANDALONE_SHORT_MONTHS, - UDAT_STANDALONE_NARROW_MONTHS, - /** The CLDR-style stand-alone "wide" weekday names */ - UDAT_STANDALONE_WEEKDAYS, - /** - * The CLDR-style stand-alone "abbreviated" (not "short") weekday names. - * For the CLDR-style stand-alone "short" weekday names, use UDAT_STANDALONE_SHORTER_WEEKDAYS. - */ - UDAT_STANDALONE_SHORT_WEEKDAYS, - /** The CLDR-style stand-alone "narrow" weekday names */ - UDAT_STANDALONE_NARROW_WEEKDAYS, - /** The quarters, for example 1st Quarter */ - UDAT_QUARTERS, - /** The short quarter names, for example Q1 */ - UDAT_SHORT_QUARTERS, - /** Standalone context versions of quarters */ - UDAT_STANDALONE_QUARTERS, - UDAT_STANDALONE_SHORT_QUARTERS, - /** - * The CLDR-style short weekday names, e.g. "Su", Mo", etc. - * These are named "SHORTER" to contrast with the constants using _SHORT_ - * above, which actually get the CLDR-style *abbreviated* versions of the - * corresponding names. - * @stable ICU 51 - */ - UDAT_SHORTER_WEEKDAYS, - /** - * Standalone version of UDAT_SHORTER_WEEKDAYS. - * @stable ICU 51 - */ - UDAT_STANDALONE_SHORTER_WEEKDAYS, - /** - * Cyclic year names (only supported for some calendars, and only for FORMAT usage; - * udat_setSymbols not supported for UDAT_CYCLIC_YEARS_WIDE) - * @stable ICU 54 - */ - UDAT_CYCLIC_YEARS_WIDE, - /** - * Cyclic year names (only supported for some calendars, and only for FORMAT usage) - * @stable ICU 54 - */ - UDAT_CYCLIC_YEARS_ABBREVIATED, - /** - * Cyclic year names (only supported for some calendars, and only for FORMAT usage; - * udat_setSymbols not supported for UDAT_CYCLIC_YEARS_NARROW) - * @stable ICU 54 - */ - UDAT_CYCLIC_YEARS_NARROW, - /** - * Calendar zodiac names (only supported for some calendars, and only for FORMAT usage; - * udat_setSymbols not supported for UDAT_ZODIAC_NAMES_WIDE) - * @stable ICU 54 - */ - UDAT_ZODIAC_NAMES_WIDE, - /** - * Calendar zodiac names (only supported for some calendars, and only for FORMAT usage) - * @stable ICU 54 - */ - UDAT_ZODIAC_NAMES_ABBREVIATED, - /** - * Calendar zodiac names (only supported for some calendars, and only for FORMAT usage; - * udat_setSymbols not supported for UDAT_ZODIAC_NAMES_NARROW) - * @stable ICU 54 - */ - UDAT_ZODIAC_NAMES_NARROW -} UDateFormatSymbolType; - -struct UDateFormatSymbols; -/** Date format symbols. - * For usage in C programs. - * @stable ICU 2.6 - */ -typedef struct UDateFormatSymbols UDateFormatSymbols; - -/** -* Get the symbols associated with an UDateFormat. -* The symbols are what a UDateFormat uses to represent locale-specific data, -* for example month or day names. -* @param fmt The formatter to query. -* @param type The type of symbols to get. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS, -* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS -* @param symbolIndex The desired symbol of type type. -* @param result A pointer to a buffer to receive the pattern. -* @param resultLength The maximum size of result. -* @param status A pointer to an UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see udat_countSymbols -* @see udat_setSymbols -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -udat_getSymbols(const UDateFormat *fmt, - UDateFormatSymbolType type, - int32_t symbolIndex, - UChar *result, - int32_t resultLength, - UErrorCode *status); - -/** -* Count the number of particular symbols for an UDateFormat. -* This function is most useful as for detemining the loop termination condition -* for calls to {@link #udat_getSymbols }. -* @param fmt The formatter to query. -* @param type The type of symbols to count. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS, -* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS -* @return The number of symbols of type type. -* @see udat_getSymbols -* @see udat_setSymbols -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -udat_countSymbols( const UDateFormat *fmt, - UDateFormatSymbolType type); - -/** -* Set the symbols associated with an UDateFormat. -* The symbols are what a UDateFormat uses to represent locale-specific data, -* for example month or day names. -* @param format The formatter to set -* @param type The type of symbols to set. One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS, -* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS -* @param symbolIndex The index of the symbol to set of type type. -* @param value The new value -* @param valueLength The length of value, or -1 if null-terminated -* @param status A pointer to an UErrorCode to receive any errors -* @see udat_getSymbols -* @see udat_countSymbols -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -udat_setSymbols( UDateFormat *format, - UDateFormatSymbolType type, - int32_t symbolIndex, - UChar *value, - int32_t valueLength, - UErrorCode *status); - -/** - * Get the locale for this date format object. - * You can choose between valid and actual locale. - * @param fmt The formatter to get the locale from - * @param type type of the locale we're looking for (valid or actual) - * @param status error code for the operation - * @return the locale name - * @stable ICU 2.8 - */ -U_STABLE const char* U_EXPORT2 -udat_getLocaleByType(const UDateFormat *fmt, - ULocDataLocaleType type, - UErrorCode* status); - -/** - * Set a particular UDisplayContext value in the formatter, such as - * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. - * @param fmt The formatter for which to set a UDisplayContext value. - * @param value The UDisplayContext value to set. - * @param status A pointer to an UErrorCode to receive any errors - * @stable ICU 51 - */ -U_DRAFT void U_EXPORT2 -udat_setContext(UDateFormat* fmt, UDisplayContext value, UErrorCode* status); - -/** - * Get the formatter's UDisplayContext value for the specified UDisplayContextType, - * such as UDISPCTX_TYPE_CAPITALIZATION. - * @param fmt The formatter to query. - * @param type The UDisplayContextType whose value to return - * @param status A pointer to an UErrorCode to receive any errors - * @return The UDisplayContextValue for the specified type. - * @stable ICU 53 - */ -U_STABLE UDisplayContext U_EXPORT2 -udat_getContext(const UDateFormat* fmt, UDisplayContextType type, UErrorCode* status); - -#ifndef U_HIDE_INTERNAL_API -/** -* Extract the date pattern from a UDateFormat set for relative date formatting. -* The pattern will follow the pattern syntax rules. -* @param fmt The formatter to query. -* @param result A pointer to a buffer to receive the pattern. -* @param resultLength The maximum size of result. -* @param status A pointer to a UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see udat_applyPatternRelative -* @internal ICU 4.2 technology preview -*/ -U_INTERNAL int32_t U_EXPORT2 -udat_toPatternRelativeDate(const UDateFormat *fmt, - UChar *result, - int32_t resultLength, - UErrorCode *status); - -/** -* Extract the time pattern from a UDateFormat set for relative date formatting. -* The pattern will follow the pattern syntax rules. -* @param fmt The formatter to query. -* @param result A pointer to a buffer to receive the pattern. -* @param resultLength The maximum size of result. -* @param status A pointer to a UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see udat_applyPatternRelative -* @internal ICU 4.2 technology preview -*/ -U_INTERNAL int32_t U_EXPORT2 -udat_toPatternRelativeTime(const UDateFormat *fmt, - UChar *result, - int32_t resultLength, - UErrorCode *status); - -/** -* Set the date & time patterns used by a UDateFormat set for relative date formatting. -* The patterns should follow the pattern syntax rules. -* @param format The formatter to set. -* @param datePattern The new date pattern -* @param datePatternLength The length of datePattern, or -1 if null-terminated. -* @param timePattern The new time pattern -* @param timePatternLength The length of timePattern, or -1 if null-terminated. -* @param status A pointer to a UErrorCode to receive any errors -* @see udat_toPatternRelativeDate, udat_toPatternRelativeTime -* @internal ICU 4.2 technology preview -*/ -U_INTERNAL void U_EXPORT2 -udat_applyPatternRelative(UDateFormat *format, - const UChar *datePattern, - int32_t datePatternLength, - const UChar *timePattern, - int32_t timePatternLength, - UErrorCode *status); - -/** - * @internal - * @see udat_open - */ -typedef UDateFormat* (U_EXPORT2 *UDateFormatOpener) (UDateFormatStyle timeStyle, - UDateFormatStyle dateStyle, - const char *locale, - const UChar *tzID, - int32_t tzIDLength, - const UChar *pattern, - int32_t patternLength, - UErrorCode *status); - -/** - * Register a provider factory - * @internal ICU 49 - */ -U_INTERNAL void U_EXPORT2 -udat_registerOpener(UDateFormatOpener opener, UErrorCode *status); - -/** - * Un-Register a provider factory - * @internal ICU 49 - */ -U_INTERNAL UDateFormatOpener U_EXPORT2 -udat_unregisterOpener(UDateFormatOpener opener, UErrorCode *status); -#endif /* U_HIDE_INTERNAL_API */ - - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/udata.h b/win32/include/spidermonkey/unicode/udata.h deleted file mode 100755 index bde719d8..00000000 --- a/win32/include/spidermonkey/unicode/udata.h +++ /dev/null @@ -1,437 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 1999-2014, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* file name: udata.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 1999oct25 -* created by: Markus W. Scherer -*/ - -#ifndef __UDATA_H__ -#define __UDATA_H__ - -#include "unicode/utypes.h" -#include "unicode/localpointer.h" - -U_CDECL_BEGIN - -/** - * \file - * \brief C API: Data loading interface - * - *

Information about data loading interface

- * - * This API is used to find and efficiently load data for ICU and applications - * using ICU. It provides an abstract interface that specifies a data type and - * name to find and load the data. Normally this API is used by other ICU APIs - * to load required data out of the ICU data library, but it can be used to - * load data out of other places. - * - * See the User Guide Data Management chapter. - */ - -#ifndef U_HIDE_INTERNAL_API -/** - * Character used to separate package names from tree names - * @internal ICU 3.0 - */ -#define U_TREE_SEPARATOR '-' - -/** - * String used to separate package names from tree names - * @internal ICU 3.0 - */ -#define U_TREE_SEPARATOR_STRING "-" - -/** - * Character used to separate parts of entry names - * @internal ICU 3.0 - */ -#define U_TREE_ENTRY_SEP_CHAR '/' - -/** - * String used to separate parts of entry names - * @internal ICU 3.0 - */ -#define U_TREE_ENTRY_SEP_STRING "/" - -/** - * Alias for standard ICU data - * @internal ICU 3.0 - */ -#define U_ICUDATA_ALIAS "ICUDATA" - -#endif /* U_HIDE_INTERNAL_API */ - -/** - * UDataInfo contains the properties about the requested data. - * This is meta data. - * - *

This structure may grow in the future, indicated by the - * size field.

- * - *

ICU data must be at least 8-aligned, and should be 16-aligned. - * The UDataInfo struct begins 4 bytes after the start of the data item, - * so it is 4-aligned. - * - *

The platform data property fields help determine if a data - * file can be efficiently used on a given machine. - * The particular fields are of importance only if the data - * is affected by the properties - if there is integer data - * with word sizes > 1 byte, char* text, or UChar* text.

- * - *

The implementation for the udata_open[Choice]() - * functions may reject data based on the value in isBigEndian. - * No other field is used by the udata API implementation.

- * - *

The dataFormat may be used to identify - * the kind of data, e.g. a converter table.

- * - *

The formatVersion field should be used to - * make sure that the format can be interpreted. - * It may be a good idea to check only for the one or two highest - * of the version elements to allow the data memory to - * get more or somewhat rearranged contents, for as long - * as the using code can still interpret the older contents.

- * - *

The dataVersion field is intended to be a - * common place to store the source version of the data; - * for data from the Unicode character database, this could - * reflect the Unicode version.

- * - * @stable ICU 2.0 - */ -typedef struct { - /** sizeof(UDataInfo) - * @stable ICU 2.0 */ - uint16_t size; - - /** unused, set to 0 - * @stable ICU 2.0*/ - uint16_t reservedWord; - - /* platform data properties */ - /** 0 for little-endian machine, 1 for big-endian - * @stable ICU 2.0 */ - uint8_t isBigEndian; - - /** see U_CHARSET_FAMILY values in utypes.h - * @stable ICU 2.0*/ - uint8_t charsetFamily; - - /** sizeof(UChar), one of { 1, 2, 4 } - * @stable ICU 2.0*/ - uint8_t sizeofUChar; - - /** unused, set to 0 - * @stable ICU 2.0*/ - uint8_t reservedByte; - - /** data format identifier - * @stable ICU 2.0*/ - uint8_t dataFormat[4]; - - /** versions: [0] major [1] minor [2] milli [3] micro - * @stable ICU 2.0*/ - uint8_t formatVersion[4]; - - /** versions: [0] major [1] minor [2] milli [3] micro - * @stable ICU 2.0*/ - uint8_t dataVersion[4]; -} UDataInfo; - -/* API for reading data -----------------------------------------------------*/ - -/** - * Forward declaration of the data memory type. - * @stable ICU 2.0 - */ -typedef struct UDataMemory UDataMemory; - -/** - * Callback function for udata_openChoice(). - * @param context parameter passed into udata_openChoice(). - * @param type The type of the data as passed into udata_openChoice(). - * It may be NULL. - * @param name The name of the data as passed into udata_openChoice(). - * @param pInfo A pointer to the UDataInfo structure - * of data that has been loaded and will be returned - * by udata_openChoice() if this function - * returns TRUE. - * @return TRUE if the current data memory is acceptable - * @stable ICU 2.0 - */ -typedef UBool U_CALLCONV -UDataMemoryIsAcceptable(void *context, - const char *type, const char *name, - const UDataInfo *pInfo); - - -/** - * Convenience function. - * This function works the same as udata_openChoice - * except that any data that matches the type and name - * is assumed to be acceptable. - * @param path Specifies an absolute path and/or a basename for the - * finding of the data in the file system. - * NULL for ICU data. - * @param type A string that specifies the type of data to be loaded. - * For example, resource bundles are loaded with type "res", - * conversion tables with type "cnv". - * This may be NULL or empty. - * @param name A string that specifies the name of the data. - * @param pErrorCode An ICU UErrorCode parameter. It must not be NULL. - * @return A pointer (handle) to a data memory object, or NULL - * if an error occurs. Call udata_getMemory() - * to get a pointer to the actual data. - * - * @see udata_openChoice - * @stable ICU 2.0 - */ -U_STABLE UDataMemory * U_EXPORT2 -udata_open(const char *path, const char *type, const char *name, - UErrorCode *pErrorCode); - -/** - * Data loading function. - * This function is used to find and load efficiently data for - * ICU and applications using ICU. - * It provides an abstract interface that allows to specify a data - * type and name to find and load the data. - * - *

The implementation depends on platform properties and user preferences - * and may involve loading shared libraries (DLLs), mapping - * files into memory, or fopen()/fread() files. - * It may also involve using static memory or database queries etc. - * Several or all data items may be combined into one entity - * (DLL, memory-mappable file).

- * - *

The data is always preceded by a header that includes - * a UDataInfo structure. - * The caller's isAcceptable() function is called to make - * sure that the data is useful. It may be called several times if it - * rejects the data and there is more than one location with data - * matching the type and name.

- * - *

If path==NULL, then ICU data is loaded. - * Otherwise, it is separated into a basename and a basename-less directory string. - * The basename is used as the data package name, and the directory is - * logically prepended to the ICU data directory string.

- * - *

For details about ICU data loading see the User Guide - * Data Management chapter. (http://icu-project.org/userguide/icudata.html)

- * - * @param path Specifies an absolute path and/or a basename for the - * finding of the data in the file system. - * NULL for ICU data. - * @param type A string that specifies the type of data to be loaded. - * For example, resource bundles are loaded with type "res", - * conversion tables with type "cnv". - * This may be NULL or empty. - * @param name A string that specifies the name of the data. - * @param isAcceptable This function is called to verify that loaded data - * is useful for the client code. If it returns FALSE - * for all data items, then udata_openChoice() - * will return with an error. - * @param context Arbitrary parameter to be passed into isAcceptable. - * @param pErrorCode An ICU UErrorCode parameter. It must not be NULL. - * @return A pointer (handle) to a data memory object, or NULL - * if an error occurs. Call udata_getMemory() - * to get a pointer to the actual data. - * @stable ICU 2.0 - */ -U_STABLE UDataMemory * U_EXPORT2 -udata_openChoice(const char *path, const char *type, const char *name, - UDataMemoryIsAcceptable *isAcceptable, void *context, - UErrorCode *pErrorCode); - -/** - * Close the data memory. - * This function must be called to allow the system to - * release resources associated with this data memory. - * @param pData The pointer to data memory object - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -udata_close(UDataMemory *pData); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUDataMemoryPointer - * "Smart pointer" class, closes a UDataMemory via udata_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUDataMemoryPointer, UDataMemory, udata_close); - -U_NAMESPACE_END - -#endif - -/** - * Get the pointer to the actual data inside the data memory. - * The data is read-only. - * - * ICU data must be at least 8-aligned, and should be 16-aligned. - * - * @param pData The pointer to data memory object - * @stable ICU 2.0 - */ -U_STABLE const void * U_EXPORT2 -udata_getMemory(UDataMemory *pData); - -/** - * Get the information from the data memory header. - * This allows to get access to the header containing - * platform data properties etc. which is not part of - * the data itself and can therefore not be accessed - * via the pointer that udata_getMemory() returns. - * - * @param pData pointer to the data memory object - * @param pInfo pointer to a UDataInfo object; - * its size field must be set correctly, - * typically to sizeof(UDataInfo). - * - * *pInfo will be filled with the UDataInfo structure - * in the data memory object. If this structure is smaller than - * pInfo->size, then the size will be - * adjusted and only part of the structure will be filled. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -udata_getInfo(UDataMemory *pData, UDataInfo *pInfo); - -/** - * This function bypasses the normal ICU data loading process and - * allows you to force ICU's system data to come out of a user-specified - * area in memory. - * - * ICU data must be at least 8-aligned, and should be 16-aligned. - * See http://userguide.icu-project.org/icudata - * - * The format of this data is that of the icu common data file, as is - * generated by the pkgdata tool with mode=common or mode=dll. - * You can read in a whole common mode file and pass the address to the start of the - * data, or (with the appropriate link options) pass in the pointer to - * the data that has been loaded from a dll by the operating system, - * as shown in this code: - * - * extern const char U_IMPORT U_ICUDATA_ENTRY_POINT []; - * // U_ICUDATA_ENTRY_POINT is same as entry point specified to pkgdata tool - * UErrorCode status = U_ZERO_ERROR; - * - * udata_setCommonData(&U_ICUDATA_ENTRY_POINT, &status); - * - * It is important that the declaration be as above. The entry point - * must not be declared as an extern void*. - * - * Starting with ICU 4.4, it is possible to set several data packages, - * one per call to this function. - * udata_open() will look for data in the multiple data packages in the order - * in which they were set. - * The position of the linked-in or default-name ICU .data package in the - * search list depends on when the first data item is loaded that is not contained - * in the already explicitly set packages. - * If data was loaded implicitly before the first call to this function - * (for example, via opening a converter, constructing a UnicodeString - * from default-codepage data, using formatting or collation APIs, etc.), - * then the default data will be first in the list. - * - * This function has no effect on application (non ICU) data. See udata_setAppData() - * for similar functionality for application data. - * - * @param data pointer to ICU common data - * @param err outgoing error status U_USING_DEFAULT_WARNING, U_UNSUPPORTED_ERROR - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -udata_setCommonData(const void *data, UErrorCode *err); - - -/** - * This function bypasses the normal ICU data loading process for application-specific - * data and allows you to force the it to come out of a user-specified - * pointer. - * - * ICU data must be at least 8-aligned, and should be 16-aligned. - * See http://userguide.icu-project.org/icudata - * - * The format of this data is that of the icu common data file, like 'icudt26l.dat' - * or the corresponding shared library (DLL) file. - * The application must read in or otherwise construct an image of the data and then - * pass the address of it to this function. - * - * - * Warning: setAppData will set a U_USING_DEFAULT_WARNING code if - * data with the specifed path that has already been opened, or - * if setAppData with the same path has already been called. - * Any such calls to setAppData will have no effect. - * - * - * @param packageName the package name by which the application will refer - * to (open) this data - * @param data pointer to the data - * @param err outgoing error status U_USING_DEFAULT_WARNING, U_UNSUPPORTED_ERROR - * @see udata_setCommonData - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -udata_setAppData(const char *packageName, const void *data, UErrorCode *err); - -/** - * Possible settings for udata_setFileAccess() - * @see udata_setFileAccess - * @stable ICU 3.4 - */ -typedef enum UDataFileAccess { - /** ICU looks for data in single files first, then in packages. (default) @stable ICU 3.4 */ - UDATA_FILES_FIRST, - /** An alias for the default access mode. @stable ICU 3.4 */ - UDATA_DEFAULT_ACCESS = UDATA_FILES_FIRST, - /** ICU only loads data from packages, not from single files. @stable ICU 3.4 */ - UDATA_ONLY_PACKAGES, - /** ICU loads data from packages first, and only from single files - if the data cannot be found in a package. @stable ICU 3.4 */ - UDATA_PACKAGES_FIRST, - /** ICU does not access the file system for data loading. @stable ICU 3.4 */ - UDATA_NO_FILES, -#ifndef U_HIDE_DEPRECATED_API - /** - * Number of real UDataFileAccess values. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UDATA_FILE_ACCESS_COUNT -#endif // U_HIDE_DEPRECATED_API -} UDataFileAccess; - -/** - * This function may be called to control how ICU loads data. It must be called - * before any ICU data is loaded, including application data loaded with - * ures/ResourceBundle or udata APIs. This function is not multithread safe. - * The results of calling it while other threads are loading data are undefined. - * @param access The type of file access to be used - * @param status Error code. - * @see UDataFileAccess - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -udata_setFileAccess(UDataFileAccess access, UErrorCode *status); - -U_CDECL_END - -#endif diff --git a/win32/include/spidermonkey/unicode/udateintervalformat.h b/win32/include/spidermonkey/unicode/udateintervalformat.h deleted file mode 100755 index 582c4378..00000000 --- a/win32/include/spidermonkey/unicode/udateintervalformat.h +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -***************************************************************************************** -* Copyright (C) 2010-2012,2015 International Business Machines -* Corporation and others. All Rights Reserved. -***************************************************************************************** -*/ - -#ifndef UDATEINTERVALFORMAT_H -#define UDATEINTERVALFORMAT_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/umisc.h" -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: Format a date interval. - * - * A UDateIntervalFormat is used to format the range between two UDate values - * in a locale-sensitive way, using a skeleton that specifies the precision and - * completeness of the information to show. If the range smaller than the resolution - * specified by the skeleton, a single date format will be produced. If the range - * is larger than the format specified by the skeleton, a locale-specific fallback - * will be used to format the items missing from the skeleton. - * - * For example, if the range is 2010-03-04 07:56 - 2010-03-04 19:56 (12 hours) - * - The skeleton jm will produce - * for en_US, "7:56 AM - 7:56 PM" - * for en_GB, "7:56 - 19:56" - * - The skeleton MMMd will produce - * for en_US, "Mar 4" - * for en_GB, "4 Mar" - * If the range is 2010-03-04 07:56 - 2010-03-08 16:11 (4 days, 8 hours, 15 minutes) - * - The skeleton jm will produce - * for en_US, "3/4/2010 7:56 AM - 3/8/2010 4:11 PM" - * for en_GB, "4/3/2010 7:56 - 8/3/2010 16:11" - * - The skeleton MMMd will produce - * for en_US, "Mar 4-8" - * for en_GB, "4-8 Mar" - * - * Note: the "-" characters in the above sample output will actually be - * Unicode 2013, EN_DASH, in all but the last example. - * - * Note, in ICU 4.4 the standard skeletons for which date interval format data - * is usually available are as follows; best results will be obtained by using - * skeletons from this set, or those formed by combining these standard skeletons - * (note that for these skeletons, the length of digit field such as d, y, or - * M vs MM is irrelevant (but for non-digit fields such as MMM vs MMMM it is - * relevant). Note that a skeleton involving h or H generally explicitly requests - * that time style (12- or 24-hour time respectively). For a skeleton that - * requests the locale's default time style (h or H), use 'j' instead of h or H. - * h, H, hm, Hm, - * hv, Hv, hmv, Hmv, - * d, - * M, MMM, MMMM, - * Md, MMMd, - * MEd, MMMEd, - * y, - * yM, yMMM, yMMMM, - * yMd, yMMMd, - * yMEd, yMMMEd - * - * Locales for which ICU 4.4 seems to have a reasonable amount of this data - * include: - * af, am, ar, be, bg, bn, ca, cs, da, de (_AT), el, en (_AU,_CA,_GB,_IE,_IN...), - * eo, es (_AR,_CL,_CO,...,_US) et, fa, fi, fo, fr (_BE,_CH,_CA), fur, gsw, he, - * hr, hu, hy, is, it (_CH), ja, kk, km, ko, lt, lv, mk, ml, mt, nb, nl )_BE), - * nn, pl, pt (_PT), rm, ro, ru (_UA), sk, sl, so, sq, sr, sr_Latn, sv, th, to, - * tr, uk, ur, vi, zh (_SG), zh_Hant (_HK,_MO) - */ - -/** - * Opaque UDateIntervalFormat object for use in C programs. - * @stable ICU 4.8 - */ -struct UDateIntervalFormat; -typedef struct UDateIntervalFormat UDateIntervalFormat; /**< C typedef for struct UDateIntervalFormat. @stable ICU 4.8 */ - -/** - * Open a new UDateIntervalFormat object using the predefined rules for a - * given locale plus a specified skeleton. - * @param locale - * The locale for whose rules should be used; may be NULL for - * default locale. - * @param skeleton - * A pattern containing only the fields desired for the interval - * format, for example "Hm", "yMMMd", or "yMMMEdHm". - * @param skeletonLength - * The length of skeleton; may be -1 if the skeleton is zero-terminated. - * @param tzID - * A timezone ID specifying the timezone to use. If 0, use the default - * timezone. - * @param tzIDLength - * The length of tzID, or -1 if null-terminated. If 0, use the default - * timezone. - * @param status - * A pointer to a UErrorCode to receive any errors. - * @return - * A pointer to a UDateIntervalFormat object for the specified locale, - * or NULL if an error occurred. - * @stable ICU 4.8 - */ -U_STABLE UDateIntervalFormat* U_EXPORT2 -udtitvfmt_open(const char* locale, - const UChar* skeleton, - int32_t skeletonLength, - const UChar* tzID, - int32_t tzIDLength, - UErrorCode* status); - -/** - * Close a UDateIntervalFormat object. Once closed it may no longer be used. - * @param formatter - * The UDateIntervalFormat object to close. - * @stable ICU 4.8 - */ -U_STABLE void U_EXPORT2 -udtitvfmt_close(UDateIntervalFormat *formatter); - - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUDateIntervalFormatPointer - * "Smart pointer" class, closes a UDateIntervalFormat via udtitvfmt_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.8 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateIntervalFormatPointer, UDateIntervalFormat, udtitvfmt_close); - -U_NAMESPACE_END - -#endif - - -/** - * Formats a date/time range using the conventions established for the - * UDateIntervalFormat object. - * @param formatter - * The UDateIntervalFormat object specifying the format conventions. - * @param fromDate - * The starting point of the range. - * @param toDate - * The ending point of the range. - * @param result - * A pointer to a buffer to receive the formatted range. - * @param resultCapacity - * The maximum size of result. - * @param position - * A pointer to a UFieldPosition. On input, position->field is read. - * On output, position->beginIndex and position->endIndex indicate - * the beginning and ending indices of field number position->field, - * if such a field exists. This parameter may be NULL, in which case - * no field position data is returned. - * There may be multiple instances of a given field type in an - * interval format; in this case the position indices refer to the - * first instance. - * @param status - * A pointer to a UErrorCode to receive any errors. - * @return - * The total buffer size needed; if greater than resultLength, the - * output was truncated. - * @stable ICU 4.8 - */ -U_STABLE int32_t U_EXPORT2 -udtitvfmt_format(const UDateIntervalFormat* formatter, - UDate fromDate, - UDate toDate, - UChar* result, - int32_t resultCapacity, - UFieldPosition* position, - UErrorCode* status); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/udatpg.h b/win32/include/spidermonkey/unicode/udatpg.h deleted file mode 100755 index 47d3afb1..00000000 --- a/win32/include/spidermonkey/unicode/udatpg.h +++ /dev/null @@ -1,605 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2007-2015, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: udatpg.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2007jul30 -* created by: Markus W. Scherer -*/ - -#ifndef __UDATPG_H__ -#define __UDATPG_H__ - -#include "unicode/utypes.h" -#include "unicode/uenum.h" -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: Wrapper for icu::DateTimePatternGenerator (unicode/dtptngen.h). - * - * UDateTimePatternGenerator provides flexible generation of date format patterns, - * like "yy-MM-dd". The user can build up the generator by adding successive - * patterns. Once that is done, a query can be made using a "skeleton", which is - * a pattern which just includes the desired fields and lengths. The generator - * will return the "best fit" pattern corresponding to that skeleton. - *

The main method people will use is udatpg_getBestPattern, since normally - * UDateTimePatternGenerator is pre-built with data from a particular locale. - * However, generators can be built directly from other data as well. - *

Issue: may be useful to also have a function that returns the list of - * fields in a pattern, in order, since we have that internally. - * That would be useful for getting the UI order of field elements. - */ - -/** - * Opaque type for a date/time pattern generator object. - * @stable ICU 3.8 - */ -typedef void *UDateTimePatternGenerator; - -/** - * Field number constants for udatpg_getAppendItemFormats() and similar functions. - * These constants are separate from UDateFormatField despite semantic overlap - * because some fields are merged for the date/time pattern generator. - * @stable ICU 3.8 - */ -typedef enum UDateTimePatternField { - /** @stable ICU 3.8 */ - UDATPG_ERA_FIELD, - /** @stable ICU 3.8 */ - UDATPG_YEAR_FIELD, - /** @stable ICU 3.8 */ - UDATPG_QUARTER_FIELD, - /** @stable ICU 3.8 */ - UDATPG_MONTH_FIELD, - /** @stable ICU 3.8 */ - UDATPG_WEEK_OF_YEAR_FIELD, - /** @stable ICU 3.8 */ - UDATPG_WEEK_OF_MONTH_FIELD, - /** @stable ICU 3.8 */ - UDATPG_WEEKDAY_FIELD, - /** @stable ICU 3.8 */ - UDATPG_DAY_OF_YEAR_FIELD, - /** @stable ICU 3.8 */ - UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD, - /** @stable ICU 3.8 */ - UDATPG_DAY_FIELD, - /** @stable ICU 3.8 */ - UDATPG_DAYPERIOD_FIELD, - /** @stable ICU 3.8 */ - UDATPG_HOUR_FIELD, - /** @stable ICU 3.8 */ - UDATPG_MINUTE_FIELD, - /** @stable ICU 3.8 */ - UDATPG_SECOND_FIELD, - /** @stable ICU 3.8 */ - UDATPG_FRACTIONAL_SECOND_FIELD, - /** @stable ICU 3.8 */ - UDATPG_ZONE_FIELD, - - // Do not conditionalize the following with #ifndef U_HIDE_DEPRECATED_API, - // it is needed for layout of DateTimePatternGenerator object. - /** - * One more than the highest normal UDateTimePatternField value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UDATPG_FIELD_COUNT -} UDateTimePatternField; - -/** - * Masks to control forcing the length of specified fields in the returned - * pattern to match those in the skeleton (when this would not happen - * otherwise). These may be combined to force the length of multiple fields. - * Used with udatpg_getBestPatternWithOptions, udatpg_replaceFieldTypesWithOptions. - * @stable ICU 4.4 - */ -typedef enum UDateTimePatternMatchOptions { - /** @stable ICU 4.4 */ - UDATPG_MATCH_NO_OPTIONS = 0, - /** @stable ICU 4.4 */ - UDATPG_MATCH_HOUR_FIELD_LENGTH = 1 << UDATPG_HOUR_FIELD, -#ifndef U_HIDE_INTERNAL_API - /** @internal ICU 4.4 */ - UDATPG_MATCH_MINUTE_FIELD_LENGTH = 1 << UDATPG_MINUTE_FIELD, - /** @internal ICU 4.4 */ - UDATPG_MATCH_SECOND_FIELD_LENGTH = 1 << UDATPG_SECOND_FIELD, -#endif /* U_HIDE_INTERNAL_API */ - /** @stable ICU 4.4 */ - UDATPG_MATCH_ALL_FIELDS_LENGTH = (1 << UDATPG_FIELD_COUNT) - 1 -} UDateTimePatternMatchOptions; - -/** - * Status return values from udatpg_addPattern(). - * @stable ICU 3.8 - */ -typedef enum UDateTimePatternConflict { - /** @stable ICU 3.8 */ - UDATPG_NO_CONFLICT, - /** @stable ICU 3.8 */ - UDATPG_BASE_CONFLICT, - /** @stable ICU 3.8 */ - UDATPG_CONFLICT, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UDateTimePatternConflict value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UDATPG_CONFLICT_COUNT -#endif // U_HIDE_DEPRECATED_API -} UDateTimePatternConflict; - -/** - * Open a generator according to a given locale. - * @param locale - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return a pointer to UDateTimePatternGenerator. - * @stable ICU 3.8 - */ -U_STABLE UDateTimePatternGenerator * U_EXPORT2 -udatpg_open(const char *locale, UErrorCode *pErrorCode); - -/** - * Open an empty generator, to be constructed with udatpg_addPattern(...) etc. - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return a pointer to UDateTimePatternGenerator. - * @stable ICU 3.8 - */ -U_STABLE UDateTimePatternGenerator * U_EXPORT2 -udatpg_openEmpty(UErrorCode *pErrorCode); - -/** - * Close a generator. - * @param dtpg a pointer to UDateTimePatternGenerator. - * @stable ICU 3.8 - */ -U_STABLE void U_EXPORT2 -udatpg_close(UDateTimePatternGenerator *dtpg); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUDateTimePatternGeneratorPointer - * "Smart pointer" class, closes a UDateTimePatternGenerator via udatpg_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateTimePatternGeneratorPointer, UDateTimePatternGenerator, udatpg_close); - -U_NAMESPACE_END - -#endif - -/** - * Create a copy pf a generator. - * @param dtpg a pointer to UDateTimePatternGenerator to be copied. - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return a pointer to a new UDateTimePatternGenerator. - * @stable ICU 3.8 - */ -U_STABLE UDateTimePatternGenerator * U_EXPORT2 -udatpg_clone(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode); - -/** - * Get the best pattern matching the input skeleton. It is guaranteed to - * have all of the fields in the skeleton. - * - * Note that this function uses a non-const UDateTimePatternGenerator: - * It uses a stateful pattern parser which is set up for each generator object, - * rather than creating one for each function call. - * Consecutive calls to this function do not affect each other, - * but this function cannot be used concurrently on a single generator object. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param skeleton - * The skeleton is a pattern containing only the variable fields. - * For example, "MMMdd" and "mmhh" are skeletons. - * @param length the length of skeleton - * @param bestPattern - * The best pattern found from the given skeleton. - * @param capacity the capacity of bestPattern. - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return the length of bestPattern. - * @stable ICU 3.8 - */ -U_STABLE int32_t U_EXPORT2 -udatpg_getBestPattern(UDateTimePatternGenerator *dtpg, - const UChar *skeleton, int32_t length, - UChar *bestPattern, int32_t capacity, - UErrorCode *pErrorCode); - -/** - * Get the best pattern matching the input skeleton. It is guaranteed to - * have all of the fields in the skeleton. - * - * Note that this function uses a non-const UDateTimePatternGenerator: - * It uses a stateful pattern parser which is set up for each generator object, - * rather than creating one for each function call. - * Consecutive calls to this function do not affect each other, - * but this function cannot be used concurrently on a single generator object. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param skeleton - * The skeleton is a pattern containing only the variable fields. - * For example, "MMMdd" and "mmhh" are skeletons. - * @param length the length of skeleton - * @param options - * Options for forcing the length of specified fields in the - * returned pattern to match those in the skeleton (when this - * would not happen otherwise). For default behavior, use - * UDATPG_MATCH_NO_OPTIONS. - * @param bestPattern - * The best pattern found from the given skeleton. - * @param capacity - * the capacity of bestPattern. - * @param pErrorCode - * a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return the length of bestPattern. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -udatpg_getBestPatternWithOptions(UDateTimePatternGenerator *dtpg, - const UChar *skeleton, int32_t length, - UDateTimePatternMatchOptions options, - UChar *bestPattern, int32_t capacity, - UErrorCode *pErrorCode); - -/** - * Get a unique skeleton from a given pattern. For example, - * both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd". - * - * Note that this function uses a non-const UDateTimePatternGenerator: - * It uses a stateful pattern parser which is set up for each generator object, - * rather than creating one for each function call. - * Consecutive calls to this function do not affect each other, - * but this function cannot be used concurrently on a single generator object. - * - * @param unusedDtpg a pointer to UDateTimePatternGenerator. - * This parameter is no longer used. Callers may pass NULL. - * @param pattern input pattern, such as "dd/MMM". - * @param length the length of pattern. - * @param skeleton such as "MMMdd" - * @param capacity the capacity of skeleton. - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return the length of skeleton. - * @stable ICU 3.8 - */ -U_STABLE int32_t U_EXPORT2 -udatpg_getSkeleton(UDateTimePatternGenerator *unusedDtpg, - const UChar *pattern, int32_t length, - UChar *skeleton, int32_t capacity, - UErrorCode *pErrorCode); - -/** - * Get a unique base skeleton from a given pattern. This is the same - * as the skeleton, except that differences in length are minimized so - * as to only preserve the difference between string and numeric form. So - * for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd" - * (notice the single d). - * - * Note that this function uses a non-const UDateTimePatternGenerator: - * It uses a stateful pattern parser which is set up for each generator object, - * rather than creating one for each function call. - * Consecutive calls to this function do not affect each other, - * but this function cannot be used concurrently on a single generator object. - * - * @param unusedDtpg a pointer to UDateTimePatternGenerator. - * This parameter is no longer used. Callers may pass NULL. - * @param pattern input pattern, such as "dd/MMM". - * @param length the length of pattern. - * @param baseSkeleton such as "Md" - * @param capacity the capacity of base skeleton. - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return the length of baseSkeleton. - * @stable ICU 3.8 - */ -U_STABLE int32_t U_EXPORT2 -udatpg_getBaseSkeleton(UDateTimePatternGenerator *unusedDtpg, - const UChar *pattern, int32_t length, - UChar *baseSkeleton, int32_t capacity, - UErrorCode *pErrorCode); - -/** - * Adds a pattern to the generator. If the pattern has the same skeleton as - * an existing pattern, and the override parameter is set, then the previous - * value is overriden. Otherwise, the previous value is retained. In either - * case, the conflicting status is set and previous vale is stored in - * conflicting pattern. - *

- * Note that single-field patterns (like "MMM") are automatically added, and - * don't need to be added explicitly! - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param pattern input pattern, such as "dd/MMM" - * @param patternLength the length of pattern. - * @param override When existing values are to be overridden use true, - * otherwise use false. - * @param conflictingPattern Previous pattern with the same skeleton. - * @param capacity the capacity of conflictingPattern. - * @param pLength a pointer to the length of conflictingPattern. - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return conflicting status. The value could be UDATPG_NO_CONFLICT, - * UDATPG_BASE_CONFLICT or UDATPG_CONFLICT. - * @stable ICU 3.8 - */ -U_STABLE UDateTimePatternConflict U_EXPORT2 -udatpg_addPattern(UDateTimePatternGenerator *dtpg, - const UChar *pattern, int32_t patternLength, - UBool override, - UChar *conflictingPattern, int32_t capacity, int32_t *pLength, - UErrorCode *pErrorCode); - -/** - * An AppendItem format is a pattern used to append a field if there is no - * good match. For example, suppose that the input skeleton is "GyyyyMMMd", - * and there is no matching pattern internally, but there is a pattern - * matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the - * G. The way these two are conjoined is by using the AppendItemFormat for G - * (era). So if that value is, say "{0}, {1}" then the final resulting - * pattern is "d-MM-yyyy, G". - *

- * There are actually three available variables: {0} is the pattern so far, - * {1} is the element we are adding, and {2} is the name of the element. - *

- * This reflects the way that the CLDR data is organized. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param field UDateTimePatternField, such as UDATPG_ERA_FIELD - * @param value pattern, such as "{0}, {1}" - * @param length the length of value. - * @stable ICU 3.8 - */ -U_STABLE void U_EXPORT2 -udatpg_setAppendItemFormat(UDateTimePatternGenerator *dtpg, - UDateTimePatternField field, - const UChar *value, int32_t length); - -/** - * Getter corresponding to setAppendItemFormat. Values below 0 or at or - * above UDATPG_FIELD_COUNT are illegal arguments. - * - * @param dtpg A pointer to UDateTimePatternGenerator. - * @param field UDateTimePatternField, such as UDATPG_ERA_FIELD - * @param pLength A pointer that will receive the length of appendItemFormat. - * @return appendItemFormat for field. - * @stable ICU 3.8 - */ -U_STABLE const UChar * U_EXPORT2 -udatpg_getAppendItemFormat(const UDateTimePatternGenerator *dtpg, - UDateTimePatternField field, - int32_t *pLength); - -/** - * Set the name of field, eg "era" in English for ERA. These are only - * used if the corresponding AppendItemFormat is used, and if it contains a - * {2} variable. - *

- * This reflects the way that the CLDR data is organized. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param field UDateTimePatternField - * @param value name for the field. - * @param length the length of value. - * @stable ICU 3.8 - */ -U_STABLE void U_EXPORT2 -udatpg_setAppendItemName(UDateTimePatternGenerator *dtpg, - UDateTimePatternField field, - const UChar *value, int32_t length); - -/** - * Getter corresponding to setAppendItemNames. Values below 0 or at or above - * UDATPG_FIELD_COUNT are illegal arguments. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param field UDateTimePatternField, such as UDATPG_ERA_FIELD - * @param pLength A pointer that will receive the length of the name for field. - * @return name for field - * @stable ICU 3.8 - */ -U_STABLE const UChar * U_EXPORT2 -udatpg_getAppendItemName(const UDateTimePatternGenerator *dtpg, - UDateTimePatternField field, - int32_t *pLength); - -/** - * The DateTimeFormat is a message format pattern used to compose date and - * time patterns. The default pattern in the root locale is "{1} {0}", where - * {1} will be replaced by the date pattern and {0} will be replaced by the - * time pattern; however, other locales may specify patterns such as - * "{1}, {0}" or "{1} 'at' {0}", etc. - *

- * This is used when the input skeleton contains both date and time fields, - * but there is not a close match among the added patterns. For example, - * suppose that this object was created by adding "dd-MMM" and "hh:mm", and - * its DateTimeFormat is the default "{1} {0}". Then if the input skeleton - * is "MMMdhmm", there is not an exact match, so the input skeleton is - * broken up into two components "MMMd" and "hmm". There are close matches - * for those two skeletons, so the result is put together with this pattern, - * resulting in "d-MMM h:mm". - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param dtFormat - * message format pattern, here {1} will be replaced by the date - * pattern and {0} will be replaced by the time pattern. - * @param length the length of dtFormat. - * @stable ICU 3.8 - */ -U_STABLE void U_EXPORT2 -udatpg_setDateTimeFormat(const UDateTimePatternGenerator *dtpg, - const UChar *dtFormat, int32_t length); - -/** - * Getter corresponding to setDateTimeFormat. - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param pLength A pointer that will receive the length of the format - * @return dateTimeFormat. - * @stable ICU 3.8 - */ -U_STABLE const UChar * U_EXPORT2 -udatpg_getDateTimeFormat(const UDateTimePatternGenerator *dtpg, - int32_t *pLength); - -/** - * The decimal value is used in formatting fractions of seconds. If the - * skeleton contains fractional seconds, then this is used with the - * fractional seconds. For example, suppose that the input pattern is - * "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and - * the decimal string is ",". Then the resulting pattern is modified to be - * "H:mm:ss,SSSS" - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param decimal - * @param length the length of decimal. - * @stable ICU 3.8 - */ -U_STABLE void U_EXPORT2 -udatpg_setDecimal(UDateTimePatternGenerator *dtpg, - const UChar *decimal, int32_t length); - -/** - * Getter corresponding to setDecimal. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param pLength A pointer that will receive the length of the decimal string. - * @return corresponding to the decimal point. - * @stable ICU 3.8 - */ -U_STABLE const UChar * U_EXPORT2 -udatpg_getDecimal(const UDateTimePatternGenerator *dtpg, - int32_t *pLength); - -/** - * Adjusts the field types (width and subtype) of a pattern to match what is - * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a - * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be - * "dd-MMMM hh:mm". This is used internally to get the best match for the - * input skeleton, but can also be used externally. - * - * Note that this function uses a non-const UDateTimePatternGenerator: - * It uses a stateful pattern parser which is set up for each generator object, - * rather than creating one for each function call. - * Consecutive calls to this function do not affect each other, - * but this function cannot be used concurrently on a single generator object. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param pattern Input pattern - * @param patternLength the length of input pattern. - * @param skeleton - * @param skeletonLength the length of input skeleton. - * @param dest pattern adjusted to match the skeleton fields widths and subtypes. - * @param destCapacity the capacity of dest. - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return the length of dest. - * @stable ICU 3.8 - */ -U_STABLE int32_t U_EXPORT2 -udatpg_replaceFieldTypes(UDateTimePatternGenerator *dtpg, - const UChar *pattern, int32_t patternLength, - const UChar *skeleton, int32_t skeletonLength, - UChar *dest, int32_t destCapacity, - UErrorCode *pErrorCode); - -/** - * Adjusts the field types (width and subtype) of a pattern to match what is - * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a - * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be - * "dd-MMMM hh:mm". This is used internally to get the best match for the - * input skeleton, but can also be used externally. - * - * Note that this function uses a non-const UDateTimePatternGenerator: - * It uses a stateful pattern parser which is set up for each generator object, - * rather than creating one for each function call. - * Consecutive calls to this function do not affect each other, - * but this function cannot be used concurrently on a single generator object. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param pattern Input pattern - * @param patternLength the length of input pattern. - * @param skeleton - * @param skeletonLength the length of input skeleton. - * @param options - * Options controlling whether the length of specified fields in the - * pattern are adjusted to match those in the skeleton (when this - * would not happen otherwise). For default behavior, use - * UDATPG_MATCH_NO_OPTIONS. - * @param dest pattern adjusted to match the skeleton fields widths and subtypes. - * @param destCapacity the capacity of dest. - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return the length of dest. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -udatpg_replaceFieldTypesWithOptions(UDateTimePatternGenerator *dtpg, - const UChar *pattern, int32_t patternLength, - const UChar *skeleton, int32_t skeletonLength, - UDateTimePatternMatchOptions options, - UChar *dest, int32_t destCapacity, - UErrorCode *pErrorCode); - -/** - * Return a UEnumeration list of all the skeletons in canonical form. - * Call udatpg_getPatternForSkeleton() to get the corresponding pattern. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call - * @return a UEnumeration list of all the skeletons - * The caller must close the object. - * @stable ICU 3.8 - */ -U_STABLE UEnumeration * U_EXPORT2 -udatpg_openSkeletons(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode); - -/** - * Return a UEnumeration list of all the base skeletons in canonical form. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param pErrorCode a pointer to the UErrorCode which must not indicate a - * failure before the function call. - * @return a UEnumeration list of all the base skeletons - * The caller must close the object. - * @stable ICU 3.8 - */ -U_STABLE UEnumeration * U_EXPORT2 -udatpg_openBaseSkeletons(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode); - -/** - * Get the pattern corresponding to a given skeleton. - * - * @param dtpg a pointer to UDateTimePatternGenerator. - * @param skeleton - * @param skeletonLength pointer to the length of skeleton. - * @param pLength pointer to the length of return pattern. - * @return pattern corresponding to a given skeleton. - * @stable ICU 3.8 - */ -U_STABLE const UChar * U_EXPORT2 -udatpg_getPatternForSkeleton(const UDateTimePatternGenerator *dtpg, - const UChar *skeleton, int32_t skeletonLength, - int32_t *pLength); - -#endif diff --git a/win32/include/spidermonkey/unicode/udisplaycontext.h b/win32/include/spidermonkey/unicode/udisplaycontext.h deleted file mode 100755 index eaef02d7..00000000 --- a/win32/include/spidermonkey/unicode/udisplaycontext.h +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -***************************************************************************************** -* Copyright (C) 2014-2016, International Business Machines -* Corporation and others. All Rights Reserved. -***************************************************************************************** -*/ - -#ifndef UDISPLAYCONTEXT_H -#define UDISPLAYCONTEXT_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -/** - * \file - * \brief C API: Display context types (enum values) - */ - -/** - * Display context types, for getting values of a particular setting. - * Note, the specific numeric values are internal and may change. - * @stable ICU 51 - */ -enum UDisplayContextType { - /** - * Type to retrieve the dialect handling setting, e.g. - * UDISPCTX_STANDARD_NAMES or UDISPCTX_DIALECT_NAMES. - * @stable ICU 51 - */ - UDISPCTX_TYPE_DIALECT_HANDLING = 0, - /** - * Type to retrieve the capitalization context setting, e.g. - * UDISPCTX_CAPITALIZATION_NONE, UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE, - * UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, etc. - * @stable ICU 51 - */ - UDISPCTX_TYPE_CAPITALIZATION = 1, - /** - * Type to retrieve the display length setting, e.g. - * UDISPCTX_LENGTH_FULL, UDISPCTX_LENGTH_SHORT. - * @stable ICU 54 - */ - UDISPCTX_TYPE_DISPLAY_LENGTH = 2, -#ifndef U_HIDE_DRAFT_API - /** - * Type to retrieve the substitute handling setting, e.g. - * UDISPCTX_SUBSTITUTE, UDISPCTX_NO_SUBSTITUTE. - * @draft ICU 58 - */ - UDISPCTX_TYPE_SUBSTITUTE_HANDLING = 3 -#endif /* U_HIDE_DRAFT_API */ -}; -/** -* @stable ICU 51 -*/ -typedef enum UDisplayContextType UDisplayContextType; - -/** - * Display context settings. - * Note, the specific numeric values are internal and may change. - * @stable ICU 51 - */ -enum UDisplayContext { - /** - * ================================ - * DIALECT_HANDLING can be set to one of UDISPCTX_STANDARD_NAMES or - * UDISPCTX_DIALECT_NAMES. Use UDisplayContextType UDISPCTX_TYPE_DIALECT_HANDLING - * to get the value. - */ - /** - * A possible setting for DIALECT_HANDLING: - * use standard names when generating a locale name, - * e.g. en_GB displays as 'English (United Kingdom)'. - * @stable ICU 51 - */ - UDISPCTX_STANDARD_NAMES = (UDISPCTX_TYPE_DIALECT_HANDLING<<8) + 0, - /** - * A possible setting for DIALECT_HANDLING: - * use dialect names, when generating a locale name, - * e.g. en_GB displays as 'British English'. - * @stable ICU 51 - */ - UDISPCTX_DIALECT_NAMES = (UDISPCTX_TYPE_DIALECT_HANDLING<<8) + 1, - /** - * ================================ - * CAPITALIZATION can be set to one of UDISPCTX_CAPITALIZATION_NONE, - * UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE, - * UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, - * UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU, or - * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. - * Use UDisplayContextType UDISPCTX_TYPE_CAPITALIZATION to get the value. - */ - /** - * The capitalization context to be used is unknown (this is the default value). - * @stable ICU 51 - */ - UDISPCTX_CAPITALIZATION_NONE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 0, - /** - * The capitalization context if a date, date symbol or display name is to be - * formatted with capitalization appropriate for the middle of a sentence. - * @stable ICU 51 - */ - UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 1, - /** - * The capitalization context if a date, date symbol or display name is to be - * formatted with capitalization appropriate for the beginning of a sentence. - * @stable ICU 51 - */ - UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 2, - /** - * The capitalization context if a date, date symbol or display name is to be - * formatted with capitalization appropriate for a user-interface list or menu item. - * @stable ICU 51 - */ - UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 3, - /** - * The capitalization context if a date, date symbol or display name is to be - * formatted with capitalization appropriate for stand-alone usage such as an - * isolated name on a calendar page. - * @stable ICU 51 - */ - UDISPCTX_CAPITALIZATION_FOR_STANDALONE = (UDISPCTX_TYPE_CAPITALIZATION<<8) + 4, - /** - * ================================ - * DISPLAY_LENGTH can be set to one of UDISPCTX_LENGTH_FULL or - * UDISPCTX_LENGTH_SHORT. Use UDisplayContextType UDISPCTX_TYPE_DISPLAY_LENGTH - * to get the value. - */ - /** - * A possible setting for DISPLAY_LENGTH: - * use full names when generating a locale name, - * e.g. "United States" for US. - * @stable ICU 54 - */ - UDISPCTX_LENGTH_FULL = (UDISPCTX_TYPE_DISPLAY_LENGTH<<8) + 0, - /** - * A possible setting for DISPLAY_LENGTH: - * use short names when generating a locale name, - * e.g. "U.S." for US. - * @stable ICU 54 - */ - UDISPCTX_LENGTH_SHORT = (UDISPCTX_TYPE_DISPLAY_LENGTH<<8) + 1, -#ifndef U_HIDE_DRAFT_API - /** - * ================================ - * SUBSTITUTE_HANDLING can be set to one of UDISPCTX_SUBSTITUTE or - * UDISPCTX_NO_SUBSTITUTE. Use UDisplayContextType UDISPCTX_TYPE_SUBSTITUTE_HANDLING - * to get the value. - */ - /** - * A possible setting for SUBSTITUTE_HANDLING: - * Returns a fallback value (e.g., the input code) when no data is available. - * This is the default value. - * @draft ICU 58 - */ - UDISPCTX_SUBSTITUTE = (UDISPCTX_TYPE_SUBSTITUTE_HANDLING<<8) + 0, - /** - * A possible setting for SUBSTITUTE_HANDLING: - * Returns a null value when no data is available. - * @draft ICU 58 - */ - UDISPCTX_NO_SUBSTITUTE = (UDISPCTX_TYPE_SUBSTITUTE_HANDLING<<8) + 1 -#endif /* U_HIDE_DRAFT_API */ - -}; -/** -* @stable ICU 51 -*/ -typedef enum UDisplayContext UDisplayContext; - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/uenum.h b/win32/include/spidermonkey/unicode/uenum.h deleted file mode 100755 index 8da1bd45..00000000 --- a/win32/include/spidermonkey/unicode/uenum.h +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2002-2013, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: uenum.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:2 -* -* created on: 2002jul08 -* created by: Vladimir Weinstein -*/ - -#ifndef __UENUM_H -#define __UENUM_H - -#include "unicode/utypes.h" -#include "unicode/localpointer.h" - -#if U_SHOW_CPLUSPLUS_API -#include "unicode/strenum.h" -#endif - -/** - * \file - * \brief C API: String Enumeration - */ - -/** - * An enumeration object. - * For usage in C programs. - * @stable ICU 2.2 - */ -struct UEnumeration; -/** structure representing an enumeration object instance @stable ICU 2.2 */ -typedef struct UEnumeration UEnumeration; - -/** - * Disposes of resources in use by the iterator. If en is NULL, - * does nothing. After this call, any char* or UChar* pointer - * returned by uenum_unext() or uenum_next() is invalid. - * @param en UEnumeration structure pointer - * @stable ICU 2.2 - */ -U_STABLE void U_EXPORT2 -uenum_close(UEnumeration* en); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUEnumerationPointer - * "Smart pointer" class, closes a UEnumeration via uenum_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUEnumerationPointer, UEnumeration, uenum_close); - -U_NAMESPACE_END - -#endif - -/** - * Returns the number of elements that the iterator traverses. If - * the iterator is out-of-sync with its service, status is set to - * U_ENUM_OUT_OF_SYNC_ERROR. - * This is a convenience function. It can end up being very - * expensive as all the items might have to be pre-fetched (depending - * on the type of data being traversed). Use with caution and only - * when necessary. - * @param en UEnumeration structure pointer - * @param status error code, can be U_ENUM_OUT_OF_SYNC_ERROR if the - * iterator is out of sync. - * @return number of elements in the iterator - * @stable ICU 2.2 - */ -U_STABLE int32_t U_EXPORT2 -uenum_count(UEnumeration* en, UErrorCode* status); - -/** - * Returns the next element in the iterator's list. If there are - * no more elements, returns NULL. If the iterator is out-of-sync - * with its service, status is set to U_ENUM_OUT_OF_SYNC_ERROR and - * NULL is returned. If the native service string is a char* string, - * it is converted to UChar* with the invariant converter. - * The result is terminated by (UChar)0. - * @param en the iterator object - * @param resultLength pointer to receive the length of the result - * (not including the terminating \\0). - * If the pointer is NULL it is ignored. - * @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if - * the iterator is out of sync with its service. - * @return a pointer to the string. The string will be - * zero-terminated. The return pointer is owned by this iterator - * and must not be deleted by the caller. The pointer is valid - * until the next call to any uenum_... method, including - * uenum_next() or uenum_unext(). When all strings have been - * traversed, returns NULL. - * @stable ICU 2.2 - */ -U_STABLE const UChar* U_EXPORT2 -uenum_unext(UEnumeration* en, - int32_t* resultLength, - UErrorCode* status); - -/** - * Returns the next element in the iterator's list. If there are - * no more elements, returns NULL. If the iterator is out-of-sync - * with its service, status is set to U_ENUM_OUT_OF_SYNC_ERROR and - * NULL is returned. If the native service string is a UChar* - * string, it is converted to char* with the invariant converter. - * The result is terminated by (char)0. If the conversion fails - * (because a character cannot be converted) then status is set to - * U_INVARIANT_CONVERSION_ERROR and the return value is undefined - * (but non-NULL). - * @param en the iterator object - * @param resultLength pointer to receive the length of the result - * (not including the terminating \\0). - * If the pointer is NULL it is ignored. - * @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if - * the iterator is out of sync with its service. Set to - * U_INVARIANT_CONVERSION_ERROR if the underlying native string is - * UChar* and conversion to char* with the invariant converter - * fails. This error pertains only to current string, so iteration - * might be able to continue successfully. - * @return a pointer to the string. The string will be - * zero-terminated. The return pointer is owned by this iterator - * and must not be deleted by the caller. The pointer is valid - * until the next call to any uenum_... method, including - * uenum_next() or uenum_unext(). When all strings have been - * traversed, returns NULL. - * @stable ICU 2.2 - */ -U_STABLE const char* U_EXPORT2 -uenum_next(UEnumeration* en, - int32_t* resultLength, - UErrorCode* status); - -/** - * Resets the iterator to the current list of service IDs. This - * re-establishes sync with the service and rewinds the iterator - * to start at the first element. - * @param en the iterator object - * @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if - * the iterator is out of sync with its service. - * @stable ICU 2.2 - */ -U_STABLE void U_EXPORT2 -uenum_reset(UEnumeration* en, UErrorCode* status); - -#if U_SHOW_CPLUSPLUS_API - -/** - * Given a StringEnumeration, wrap it in a UEnumeration. The - * StringEnumeration is adopted; after this call, the caller must not - * delete it (regardless of error status). - * @param adopted the C++ StringEnumeration to be wrapped in a UEnumeration. - * @param ec the error code. - * @return a UEnumeration wrapping the adopted StringEnumeration. - * @stable ICU 4.2 - */ -U_STABLE UEnumeration* U_EXPORT2 -uenum_openFromStringEnumeration(icu::StringEnumeration* adopted, UErrorCode* ec); - -#endif - -/** - * Given an array of const UChar* strings, return a UEnumeration. String pointers from 0..count-1 must not be null. - * Do not free or modify either the string array or the characters it points to until this object has been destroyed with uenum_close. - * \snippet test/cintltst/uenumtst.c uenum_openUCharStringsEnumeration - * @param strings array of const UChar* strings (each null terminated). All storage is owned by the caller. - * @param count length of the array - * @param ec error code - * @return the new UEnumeration object. Caller is responsible for calling uenum_close to free memory. - * @see uenum_close - * @stable ICU 50 - */ -U_STABLE UEnumeration* U_EXPORT2 -uenum_openUCharStringsEnumeration(const UChar* const strings[], int32_t count, - UErrorCode* ec); - -/* Note: next function is not hidden as draft, as it is used internally (it was formerly an internal function). */ - -/** - * Given an array of const char* strings (invariant chars only), return a UEnumeration. String pointers from 0..count-1 must not be null. - * Do not free or modify either the string array or the characters it points to until this object has been destroyed with uenum_close. - * \snippet test/cintltst/uenumtst.c uenum_openCharStringsEnumeration - * @param strings array of char* strings (each null terminated). All storage is owned by the caller. - * @param count length of the array - * @param ec error code - * @return the new UEnumeration object. Caller is responsible for calling uenum_close to free memory - * @see uenum_close - * @stable ICU 50 - */ -U_STABLE UEnumeration* U_EXPORT2 -uenum_openCharStringsEnumeration(const char* const strings[], int32_t count, - UErrorCode* ec); - -#endif diff --git a/win32/include/spidermonkey/unicode/ufieldpositer.h b/win32/include/spidermonkey/unicode/ufieldpositer.h deleted file mode 100755 index 8dfa3df5..00000000 --- a/win32/include/spidermonkey/unicode/ufieldpositer.h +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -***************************************************************************************** -* Copyright (C) 2015-2016, International Business Machines -* Corporation and others. All Rights Reserved. -***************************************************************************************** -*/ - -#ifndef UFIELDPOSITER_H -#define UFIELDPOSITER_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: UFieldPositionIterator for use with format APIs. - * - * Usage: - * ufieldpositer_open creates an empty (unset) UFieldPositionIterator. - * This can be passed to format functions such as {@link #udat_formatForFields}, - * which will set it to apply to the fields in a particular formatted string. - * ufieldpositer_next can then be used to iterate over those fields, - * providing for each field its type (using values that are specific to the - * particular format type, such as date or number formats), as well as the - * start and end positions of the field in the formatted string. - * A given UFieldPositionIterator can be re-used for different format calls; - * each such call resets it to apply to that format string. - * ufieldpositer_close should be called to dispose of the UFieldPositionIterator - * when it is no longer needed. - * - * @see FieldPositionIterator - */ - -/** - * Opaque UFieldPositionIterator object for use in C. - * @stable ICU 55 - */ -struct UFieldPositionIterator; -typedef struct UFieldPositionIterator UFieldPositionIterator; /**< C typedef for struct UFieldPositionIterator. @stable ICU 55 */ - -/** - * Open a new, unset UFieldPositionIterator object. - * @param status - * A pointer to a UErrorCode to receive any errors. - * @return - * A pointer to an empty (unset) UFieldPositionIterator object, - * or NULL if an error occurred. - * @stable ICU 55 - */ -U_STABLE UFieldPositionIterator* U_EXPORT2 -ufieldpositer_open(UErrorCode* status); - -/** - * Close a UFieldPositionIterator object. Once closed it may no longer be used. - * @param fpositer - * A pointer to the UFieldPositionIterator object to close. - * @stable ICU 55 - */ -U_STABLE void U_EXPORT2 -ufieldpositer_close(UFieldPositionIterator *fpositer); - - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUFieldPositionIteratorPointer - * "Smart pointer" class, closes a UFieldPositionIterator via ufieldpositer_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 55 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUFieldPositionIteratorPointer, UFieldPositionIterator, ufieldpositer_close); - -U_NAMESPACE_END - -#endif - -/** - * Get information for the next field in the formatted string to which this - * UFieldPositionIterator currently applies, or return a negative value if there - * are no more fields. - * @param fpositer - * A pointer to the UFieldPositionIterator object containing iteration - * state for the format fields. - * @param beginIndex - * A pointer to an int32_t to receive information about the start offset - * of the field in the formatted string (undefined if the function - * returns a negative value). May be NULL if this information is not needed. - * @param endIndex - * A pointer to an int32_t to receive information about the end offset - * of the field in the formatted string (undefined if the function - * returns a negative value). May be NULL if this information is not needed. - * @return - * The field type (non-negative value), or a negative value if there are - * no more fields for which to provide information. If negative, then any - * values pointed to by beginIndex and endIndex are undefined. - * - * The values for field type depend on what type of formatter the - * UFieldPositionIterator has been set by; for a date formatter, the - * values from the UDateFormatField enum. For more information, see the - * descriptions of format functions that take a UFieldPositionIterator* - * parameter, such as {@link #udat_formatForFields}. - * - * @stable ICU 55 - */ -U_STABLE int32_t U_EXPORT2 -ufieldpositer_next(UFieldPositionIterator *fpositer, - int32_t *beginIndex, int32_t *endIndex); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/uformattable.h b/win32/include/spidermonkey/unicode/uformattable.h deleted file mode 100755 index e4683d56..00000000 --- a/win32/include/spidermonkey/unicode/uformattable.h +++ /dev/null @@ -1,288 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************** -* Copyright (C) 2013-2014, International Business Machines Corporation and others. -* All Rights Reserved. -******************************************************************************** -* -* File UFORMATTABLE.H -* -* Modification History: -* -* Date Name Description -* 2013 Jun 7 srl New -******************************************************************************** -*/ - -/** - * \file - * \brief C API: UFormattable is a thin wrapper for primitive types used for formatting and parsing. - * - * This is a C interface to the icu::Formattable class. Static functions on this class convert - * to and from this interface (via reinterpret_cast). Note that Formattables (and thus UFormattables) - * are mutable, and many operations (even getters) may actually modify the internal state. For this - * reason, UFormattables are not thread safe, and should not be shared between threads. - * - * See {@link unum_parseToUFormattable} for example code. - */ - -#ifndef UFORMATTABLE_H -#define UFORMATTABLE_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/localpointer.h" - -/** - * Enum designating the type of a UFormattable instance. - * Practically, this indicates which of the getters would return without conversion - * or error. - * @see icu::Formattable::Type - * @stable ICU 52 - */ -typedef enum UFormattableType { - UFMT_DATE = 0, /**< ufmt_getDate() will return without conversion. @see ufmt_getDate*/ - UFMT_DOUBLE, /**< ufmt_getDouble() will return without conversion. @see ufmt_getDouble*/ - UFMT_LONG, /**< ufmt_getLong() will return without conversion. @see ufmt_getLong */ - UFMT_STRING, /**< ufmt_getUChars() will return without conversion. @see ufmt_getUChars*/ - UFMT_ARRAY, /**< ufmt_countArray() and ufmt_getArray() will return the value. @see ufmt_getArrayItemByIndex */ - UFMT_INT64, /**< ufmt_getInt64() will return without conversion. @see ufmt_getInt64 */ - UFMT_OBJECT, /**< ufmt_getObject() will return without conversion. @see ufmt_getObject*/ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UFormattableType value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UFMT_COUNT -#endif // U_HIDE_DEPRECATED_API -} UFormattableType; - - -/** - * Opaque type representing various types of data which may be used for formatting - * and parsing operations. - * @see icu::Formattable - * @stable ICU 52 - */ -typedef void *UFormattable; - -/** - * Initialize a UFormattable, to type UNUM_LONG, value 0 - * may return error if memory allocation failed. - * parameter status error code. - * See {@link unum_parseToUFormattable} for example code. - * @stable ICU 52 - * @return the new UFormattable - * @see ufmt_close - * @see icu::Formattable::Formattable() - */ -U_STABLE UFormattable* U_EXPORT2 -ufmt_open(UErrorCode* status); - -/** - * Cleanup any additional memory allocated by this UFormattable. - * @param fmt the formatter - * @stable ICU 52 - * @see ufmt_open - */ -U_STABLE void U_EXPORT2 -ufmt_close(UFormattable* fmt); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUFormattablePointer - * "Smart pointer" class, closes a UFormattable via ufmt_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 52 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUFormattablePointer, UFormattable, ufmt_close); - -U_NAMESPACE_END - -#endif - -/** - * Return the type of this object - * @param fmt the UFormattable object - * @param status status code - U_ILLEGAL_ARGUMENT_ERROR is returned if the UFormattable contains data not supported by - * the API - * @return the value as a UFormattableType - * @see ufmt_isNumeric - * @see icu::Formattable::getType() const - * @stable ICU 52 - */ -U_STABLE UFormattableType U_EXPORT2 -ufmt_getType(const UFormattable* fmt, UErrorCode *status); - -/** - * Return whether the object is numeric. - * @param fmt the UFormattable object - * @return true if the object is a double, long, or int64 value, else false. - * @see ufmt_getType - * @see icu::Formattable::isNumeric() const - * @stable ICU 52 - */ -U_STABLE UBool U_EXPORT2 -ufmt_isNumeric(const UFormattable* fmt); - -/** - * Gets the UDate value of this object. If the type is not of type UFMT_DATE, - * status is set to U_INVALID_FORMAT_ERROR and the return value is - * undefined. - * @param fmt the UFormattable object - * @param status the error code - any conversion or format errors - * @return the value - * @stable ICU 52 - * @see icu::Formattable::getDate(UErrorCode&) const - */ -U_STABLE UDate U_EXPORT2 -ufmt_getDate(const UFormattable* fmt, UErrorCode *status); - -/** - * Gets the double value of this object. If the type is not a UFMT_DOUBLE, or - * if there are additional significant digits than fit in a double type, - * a conversion is performed with possible loss of precision. - * If the type is UFMT_OBJECT and the - * object is a Measure, then the result of - * getNumber().getDouble(status) is returned. If this object is - * neither a numeric type nor a Measure, then 0 is returned and - * the status is set to U_INVALID_FORMAT_ERROR. - * @param fmt the UFormattable object - * @param status the error code - any conversion or format errors - * @return the value - * @stable ICU 52 - * @see icu::Formattable::getDouble(UErrorCode&) const - */ -U_STABLE double U_EXPORT2 -ufmt_getDouble(UFormattable* fmt, UErrorCode *status); - -/** - * Gets the long (int32_t) value of this object. If the magnitude is too - * large to fit in a long, then the maximum or minimum long value, - * as appropriate, is returned and the status is set to - * U_INVALID_FORMAT_ERROR. If this object is of type UFMT_INT64 and - * it fits within a long, then no precision is lost. If it is of - * type kDouble or kDecimalNumber, then a conversion is peformed, with - * truncation of any fractional part. If the type is UFMT_OBJECT and - * the object is a Measure, then the result of - * getNumber().getLong(status) is returned. If this object is - * neither a numeric type nor a Measure, then 0 is returned and - * the status is set to U_INVALID_FORMAT_ERROR. - * @param fmt the UFormattable object - * @param status the error code - any conversion or format errors - * @return the value - * @stable ICU 52 - * @see icu::Formattable::getLong(UErrorCode&) const - */ -U_STABLE int32_t U_EXPORT2 -ufmt_getLong(UFormattable* fmt, UErrorCode *status); - - -/** - * Gets the int64_t value of this object. If this object is of a numeric - * type and the magnitude is too large to fit in an int64, then - * the maximum or minimum int64 value, as appropriate, is returned - * and the status is set to U_INVALID_FORMAT_ERROR. If the - * magnitude fits in an int64, then a casting conversion is - * peformed, with truncation of any fractional part. If the type - * is UFMT_OBJECT and the object is a Measure, then the result of - * getNumber().getDouble(status) is returned. If this object is - * neither a numeric type nor a Measure, then 0 is returned and - * the status is set to U_INVALID_FORMAT_ERROR. - * @param fmt the UFormattable object - * @param status the error code - any conversion or format errors - * @return the value - * @stable ICU 52 - * @see icu::Formattable::getInt64(UErrorCode&) const - */ -U_STABLE int64_t U_EXPORT2 -ufmt_getInt64(UFormattable* fmt, UErrorCode *status); - -/** - * Returns a pointer to the UObject contained within this - * formattable (as a const void*), or NULL if this object - * is not of type UFMT_OBJECT. - * @param fmt the UFormattable object - * @param status the error code - any conversion or format errors - * @return the value as a const void*. It is a polymorphic C++ object. - * @stable ICU 52 - * @see icu::Formattable::getObject() const - */ -U_STABLE const void *U_EXPORT2 -ufmt_getObject(const UFormattable* fmt, UErrorCode *status); - -/** - * Gets the string value of this object as a UChar string. If the type is not a - * string, status is set to U_INVALID_FORMAT_ERROR and a NULL pointer is returned. - * This function is not thread safe and may modify the UFormattable if need be to terminate the string. - * The returned pointer is not valid if any other functions are called on this UFormattable, or if the UFormattable is closed. - * @param fmt the UFormattable object - * @param status the error code - any conversion or format errors - * @param len if non null, contains the string length on return - * @return the null terminated string value - must not be referenced after any other functions are called on this UFormattable. - * @stable ICU 52 - * @see icu::Formattable::getString(UnicodeString&)const - */ -U_STABLE const UChar* U_EXPORT2 -ufmt_getUChars(UFormattable* fmt, int32_t *len, UErrorCode *status); - -/** - * Get the number of array objects contained, if an array type UFMT_ARRAY - * @param fmt the UFormattable object - * @param status the error code - any conversion or format errors. U_ILLEGAL_ARGUMENT_ERROR if not an array type. - * @return the number of array objects or undefined if not an array type - * @stable ICU 52 - * @see ufmt_getArrayItemByIndex - */ -U_STABLE int32_t U_EXPORT2 -ufmt_getArrayLength(const UFormattable* fmt, UErrorCode *status); - -/** - * Get the specified value from the array of UFormattables. Invalid if the object is not an array type UFMT_ARRAY - * @param fmt the UFormattable object - * @param n the number of the array to return (0 based). - * @param status the error code - any conversion or format errors. Returns an error if n is out of bounds. - * @return the nth array value, only valid while the containing UFormattable is valid. NULL if not an array. - * @stable ICU 52 - * @see icu::Formattable::getArray(int32_t&, UErrorCode&) const - */ -U_STABLE UFormattable * U_EXPORT2 -ufmt_getArrayItemByIndex(UFormattable* fmt, int32_t n, UErrorCode *status); - -/** - * Returns a numeric string representation of the number contained within this - * formattable, or NULL if this object does not contain numeric type. - * For values obtained by parsing, the returned decimal number retains - * the full precision and range of the original input, unconstrained by - * the limits of a double floating point or a 64 bit int. - * - * This function is not thread safe, and therfore is not declared const, - * even though it is logically const. - * The resulting buffer is owned by the UFormattable and is invalid if any other functions are - * called on the UFormattable. - * - * Possible errors include U_MEMORY_ALLOCATION_ERROR, and - * U_INVALID_STATE if the formattable object has not been set to - * a numeric type. - * @param fmt the UFormattable object - * @param len if non-null, on exit contains the string length (not including the terminating null) - * @param status the error code - * @return the character buffer as a NULL terminated string, which is owned by the object and must not be accessed if any other functions are called on this object. - * @stable ICU 52 - * @see icu::Formattable::getDecimalNumber(UErrorCode&) - */ -U_STABLE const char * U_EXPORT2 -ufmt_getDecNumChars(UFormattable *fmt, int32_t *len, UErrorCode *status); - -#endif - -#endif diff --git a/win32/include/spidermonkey/unicode/ugender.h b/win32/include/spidermonkey/unicode/ugender.h deleted file mode 100755 index c1e591ed..00000000 --- a/win32/include/spidermonkey/unicode/ugender.h +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -***************************************************************************************** -* Copyright (C) 2010-2013, International Business Machines -* Corporation and others. All Rights Reserved. -***************************************************************************************** -*/ - -#ifndef UGENDER_H -#define UGENDER_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: The purpose of this API is to compute the gender of a list as a - * whole given the gender of each element. - * - */ - -/** - * Genders - * @stable ICU 50 - */ -enum UGender { - /** - * Male gender. - * @stable ICU 50 - */ - UGENDER_MALE, - /** - * Female gender. - * @stable ICU 50 - */ - UGENDER_FEMALE, - /** - * Neutral gender. - * @stable ICU 50 - */ - UGENDER_OTHER -}; -/** - * @stable ICU 50 - */ -typedef enum UGender UGender; - -/** - * Opaque UGenderInfo object for use in C programs. - * @stable ICU 50 - */ -struct UGenderInfo; -typedef struct UGenderInfo UGenderInfo; - -/** - * Opens a new UGenderInfo object given locale. - * @param locale The locale for which the rules are desired. - * @param status UErrorCode pointer - * @return A UGenderInfo for the specified locale, or NULL if an error occurred. - * @stable ICU 50 - */ -U_STABLE const UGenderInfo* U_EXPORT2 -ugender_getInstance(const char *locale, UErrorCode *status); - - -/** - * Given a list, returns the gender of the list as a whole. - * @param genderInfo pointer that ugender_getInstance returns. - * @param genders the gender of each element in the list. - * @param size the size of the list. - * @param status A pointer to a UErrorCode to receive any errors. - * @return The gender of the list. - * @stable ICU 50 - */ -U_STABLE UGender U_EXPORT2 -ugender_getListGender(const UGenderInfo* genderinfo, const UGender *genders, int32_t size, UErrorCode *status); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/uidna.h b/win32/include/spidermonkey/unicode/uidna.h deleted file mode 100755 index af3455c1..00000000 --- a/win32/include/spidermonkey/unicode/uidna.h +++ /dev/null @@ -1,772 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * - * Copyright (C) 2003-2014, International Business Machines - * Corporation and others. All Rights Reserved. - * - ******************************************************************************* - * file name: uidna.h - * encoding: US-ASCII - * tab size: 8 (not used) - * indentation:4 - * - * created on: 2003feb1 - * created by: Ram Viswanadha - */ - -#ifndef __UIDNA_H__ -#define __UIDNA_H__ - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_IDNA - -#include "unicode/localpointer.h" -#include "unicode/parseerr.h" - -/** - * \file - * \brief C API: Internationalizing Domain Names in Applications (IDNA) - * - * IDNA2008 is implemented according to UTS #46, see the IDNA C++ class in idna.h. - * - * The C API functions which do take a UIDNA * service object pointer - * implement UTS #46 and IDNA2008. - * - * IDNA2003 is obsolete. - * The C API functions which do not take a service object pointer - * implement IDNA2003. They are all deprecated. - */ - -/* - * IDNA option bit set values. - */ -enum { - /** - * Default options value: None of the other options are set. - * For use in static worker and factory methods. - * @stable ICU 2.6 - */ - UIDNA_DEFAULT=0, -#ifndef U_HIDE_DEPRECATED_API - /** - * Option to allow unassigned code points in domain names and labels. - * For use in static worker and factory methods. - *

This option is ignored by the UTS46 implementation. - * (UTS #46 disallows unassigned code points.) - * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. - */ - UIDNA_ALLOW_UNASSIGNED=1, -#endif /* U_HIDE_DEPRECATED_API */ - /** - * Option to check whether the input conforms to the STD3 ASCII rules, - * for example the restriction of labels to LDH characters - * (ASCII Letters, Digits and Hyphen-Minus). - * For use in static worker and factory methods. - * @stable ICU 2.6 - */ - UIDNA_USE_STD3_RULES=2, - /** - * IDNA option to check for whether the input conforms to the BiDi rules. - * For use in static worker and factory methods. - *

This option is ignored by the IDNA2003 implementation. - * (IDNA2003 always performs a BiDi check.) - * @stable ICU 4.6 - */ - UIDNA_CHECK_BIDI=4, - /** - * IDNA option to check for whether the input conforms to the CONTEXTJ rules. - * For use in static worker and factory methods. - *

This option is ignored by the IDNA2003 implementation. - * (The CONTEXTJ check is new in IDNA2008.) - * @stable ICU 4.6 - */ - UIDNA_CHECK_CONTEXTJ=8, - /** - * IDNA option for nontransitional processing in ToASCII(). - * For use in static worker and factory methods. - *

By default, ToASCII() uses transitional processing. - *

This option is ignored by the IDNA2003 implementation. - * (This is only relevant for compatibility of newer IDNA implementations with IDNA2003.) - * @stable ICU 4.6 - */ - UIDNA_NONTRANSITIONAL_TO_ASCII=0x10, - /** - * IDNA option for nontransitional processing in ToUnicode(). - * For use in static worker and factory methods. - *

By default, ToUnicode() uses transitional processing. - *

This option is ignored by the IDNA2003 implementation. - * (This is only relevant for compatibility of newer IDNA implementations with IDNA2003.) - * @stable ICU 4.6 - */ - UIDNA_NONTRANSITIONAL_TO_UNICODE=0x20, - /** - * IDNA option to check for whether the input conforms to the CONTEXTO rules. - * For use in static worker and factory methods. - *

This option is ignored by the IDNA2003 implementation. - * (The CONTEXTO check is new in IDNA2008.) - *

This is for use by registries for IDNA2008 conformance. - * UTS #46 does not require the CONTEXTO check. - * @stable ICU 49 - */ - UIDNA_CHECK_CONTEXTO=0x40 -}; - -/** - * Opaque C service object type for the new IDNA API. - * @stable ICU 4.6 - */ -struct UIDNA; -typedef struct UIDNA UIDNA; /**< C typedef for struct UIDNA. @stable ICU 4.6 */ - -/** - * Returns a UIDNA instance which implements UTS #46. - * Returns an unmodifiable instance, owned by the caller. - * Cache it for multiple operations, and uidna_close() it when done. - * The instance is thread-safe, that is, it can be used concurrently. - * - * For details about the UTS #46 implementation see the IDNA C++ class in idna.h. - * - * @param options Bit set to modify the processing and error checking. - * See option bit set values in uidna.h. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the UTS #46 UIDNA instance, if successful - * @stable ICU 4.6 - */ -U_STABLE UIDNA * U_EXPORT2 -uidna_openUTS46(uint32_t options, UErrorCode *pErrorCode); - -/** - * Closes a UIDNA instance. - * @param idna UIDNA instance to be closed - * @stable ICU 4.6 - */ -U_STABLE void U_EXPORT2 -uidna_close(UIDNA *idna); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUIDNAPointer - * "Smart pointer" class, closes a UIDNA via uidna_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.6 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUIDNAPointer, UIDNA, uidna_close); - -U_NAMESPACE_END - -#endif - -/** - * Output container for IDNA processing errors. - * Initialize with UIDNA_INFO_INITIALIZER: - * \code - * UIDNAInfo info = UIDNA_INFO_INITIALIZER; - * int32_t length = uidna_nameToASCII(..., &info, &errorCode); - * if(U_SUCCESS(errorCode) && info.errors!=0) { ... } - * \endcode - * @stable ICU 4.6 - */ -typedef struct UIDNAInfo { - /** sizeof(UIDNAInfo) @stable ICU 4.6 */ - int16_t size; - /** - * Set to TRUE if transitional and nontransitional processing produce different results. - * For details see C++ IDNAInfo::isTransitionalDifferent(). - * @stable ICU 4.6 - */ - UBool isTransitionalDifferent; - UBool reservedB3; /**< Reserved field, do not use. @internal */ - /** - * Bit set indicating IDNA processing errors. 0 if no errors. - * See UIDNA_ERROR_... constants. - * @stable ICU 4.6 - */ - uint32_t errors; - int32_t reservedI2; /**< Reserved field, do not use. @internal */ - int32_t reservedI3; /**< Reserved field, do not use. @internal */ -} UIDNAInfo; - -/** - * Static initializer for a UIDNAInfo struct. - * @stable ICU 4.6 - */ -#define UIDNA_INFO_INITIALIZER { \ - (int16_t)sizeof(UIDNAInfo), \ - FALSE, FALSE, \ - 0, 0, 0 } - -/** - * Converts a single domain name label into its ASCII form for DNS lookup. - * If any processing step fails, then pInfo->errors will be non-zero and - * the result might not be an ASCII string. - * The label might be modified according to the types of errors. - * Labels with severe errors will be left in (or turned into) their Unicode form. - * - * The UErrorCode indicates an error only in exceptional cases, - * such as a U_MEMORY_ALLOCATION_ERROR. - * - * @param idna UIDNA instance - * @param label Input domain name label - * @param length Label length, or -1 if NUL-terminated - * @param dest Destination string buffer - * @param capacity Destination buffer capacity - * @param pInfo Output container of IDNA processing details. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return destination string length - * @stable ICU 4.6 - */ -U_STABLE int32_t U_EXPORT2 -uidna_labelToASCII(const UIDNA *idna, - const UChar *label, int32_t length, - UChar *dest, int32_t capacity, - UIDNAInfo *pInfo, UErrorCode *pErrorCode); - -/** - * Converts a single domain name label into its Unicode form for human-readable display. - * If any processing step fails, then pInfo->errors will be non-zero. - * The label might be modified according to the types of errors. - * - * The UErrorCode indicates an error only in exceptional cases, - * such as a U_MEMORY_ALLOCATION_ERROR. - * - * @param idna UIDNA instance - * @param label Input domain name label - * @param length Label length, or -1 if NUL-terminated - * @param dest Destination string buffer - * @param capacity Destination buffer capacity - * @param pInfo Output container of IDNA processing details. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return destination string length - * @stable ICU 4.6 - */ -U_STABLE int32_t U_EXPORT2 -uidna_labelToUnicode(const UIDNA *idna, - const UChar *label, int32_t length, - UChar *dest, int32_t capacity, - UIDNAInfo *pInfo, UErrorCode *pErrorCode); - -/** - * Converts a whole domain name into its ASCII form for DNS lookup. - * If any processing step fails, then pInfo->errors will be non-zero and - * the result might not be an ASCII string. - * The domain name might be modified according to the types of errors. - * Labels with severe errors will be left in (or turned into) their Unicode form. - * - * The UErrorCode indicates an error only in exceptional cases, - * such as a U_MEMORY_ALLOCATION_ERROR. - * - * @param idna UIDNA instance - * @param name Input domain name - * @param length Domain name length, or -1 if NUL-terminated - * @param dest Destination string buffer - * @param capacity Destination buffer capacity - * @param pInfo Output container of IDNA processing details. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return destination string length - * @stable ICU 4.6 - */ -U_STABLE int32_t U_EXPORT2 -uidna_nameToASCII(const UIDNA *idna, - const UChar *name, int32_t length, - UChar *dest, int32_t capacity, - UIDNAInfo *pInfo, UErrorCode *pErrorCode); - -/** - * Converts a whole domain name into its Unicode form for human-readable display. - * If any processing step fails, then pInfo->errors will be non-zero. - * The domain name might be modified according to the types of errors. - * - * The UErrorCode indicates an error only in exceptional cases, - * such as a U_MEMORY_ALLOCATION_ERROR. - * - * @param idna UIDNA instance - * @param name Input domain name - * @param length Domain name length, or -1 if NUL-terminated - * @param dest Destination string buffer - * @param capacity Destination buffer capacity - * @param pInfo Output container of IDNA processing details. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return destination string length - * @stable ICU 4.6 - */ -U_STABLE int32_t U_EXPORT2 -uidna_nameToUnicode(const UIDNA *idna, - const UChar *name, int32_t length, - UChar *dest, int32_t capacity, - UIDNAInfo *pInfo, UErrorCode *pErrorCode); - -/* UTF-8 versions of the processing methods --------------------------------- */ - -/** - * Converts a single domain name label into its ASCII form for DNS lookup. - * UTF-8 version of uidna_labelToASCII(), same behavior. - * - * @param idna UIDNA instance - * @param label Input domain name label - * @param length Label length, or -1 if NUL-terminated - * @param dest Destination string buffer - * @param capacity Destination buffer capacity - * @param pInfo Output container of IDNA processing details. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return destination string length - * @stable ICU 4.6 - */ -U_STABLE int32_t U_EXPORT2 -uidna_labelToASCII_UTF8(const UIDNA *idna, - const char *label, int32_t length, - char *dest, int32_t capacity, - UIDNAInfo *pInfo, UErrorCode *pErrorCode); - -/** - * Converts a single domain name label into its Unicode form for human-readable display. - * UTF-8 version of uidna_labelToUnicode(), same behavior. - * - * @param idna UIDNA instance - * @param label Input domain name label - * @param length Label length, or -1 if NUL-terminated - * @param dest Destination string buffer - * @param capacity Destination buffer capacity - * @param pInfo Output container of IDNA processing details. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return destination string length - * @stable ICU 4.6 - */ -U_STABLE int32_t U_EXPORT2 -uidna_labelToUnicodeUTF8(const UIDNA *idna, - const char *label, int32_t length, - char *dest, int32_t capacity, - UIDNAInfo *pInfo, UErrorCode *pErrorCode); - -/** - * Converts a whole domain name into its ASCII form for DNS lookup. - * UTF-8 version of uidna_nameToASCII(), same behavior. - * - * @param idna UIDNA instance - * @param name Input domain name - * @param length Domain name length, or -1 if NUL-terminated - * @param dest Destination string buffer - * @param capacity Destination buffer capacity - * @param pInfo Output container of IDNA processing details. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return destination string length - * @stable ICU 4.6 - */ -U_STABLE int32_t U_EXPORT2 -uidna_nameToASCII_UTF8(const UIDNA *idna, - const char *name, int32_t length, - char *dest, int32_t capacity, - UIDNAInfo *pInfo, UErrorCode *pErrorCode); - -/** - * Converts a whole domain name into its Unicode form for human-readable display. - * UTF-8 version of uidna_nameToUnicode(), same behavior. - * - * @param idna UIDNA instance - * @param name Input domain name - * @param length Domain name length, or -1 if NUL-terminated - * @param dest Destination string buffer - * @param capacity Destination buffer capacity - * @param pInfo Output container of IDNA processing details. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return destination string length - * @stable ICU 4.6 - */ -U_STABLE int32_t U_EXPORT2 -uidna_nameToUnicodeUTF8(const UIDNA *idna, - const char *name, int32_t length, - char *dest, int32_t capacity, - UIDNAInfo *pInfo, UErrorCode *pErrorCode); - -/* - * IDNA error bit set values. - * When a domain name or label fails a processing step or does not meet the - * validity criteria, then one or more of these error bits are set. - */ -enum { - /** - * A non-final domain name label (or the whole domain name) is empty. - * @stable ICU 4.6 - */ - UIDNA_ERROR_EMPTY_LABEL=1, - /** - * A domain name label is longer than 63 bytes. - * (See STD13/RFC1034 3.1. Name space specifications and terminology.) - * This is only checked in ToASCII operations, and only if the output label is all-ASCII. - * @stable ICU 4.6 - */ - UIDNA_ERROR_LABEL_TOO_LONG=2, - /** - * A domain name is longer than 255 bytes in its storage form. - * (See STD13/RFC1034 3.1. Name space specifications and terminology.) - * This is only checked in ToASCII operations, and only if the output domain name is all-ASCII. - * @stable ICU 4.6 - */ - UIDNA_ERROR_DOMAIN_NAME_TOO_LONG=4, - /** - * A label starts with a hyphen-minus ('-'). - * @stable ICU 4.6 - */ - UIDNA_ERROR_LEADING_HYPHEN=8, - /** - * A label ends with a hyphen-minus ('-'). - * @stable ICU 4.6 - */ - UIDNA_ERROR_TRAILING_HYPHEN=0x10, - /** - * A label contains hyphen-minus ('-') in the third and fourth positions. - * @stable ICU 4.6 - */ - UIDNA_ERROR_HYPHEN_3_4=0x20, - /** - * A label starts with a combining mark. - * @stable ICU 4.6 - */ - UIDNA_ERROR_LEADING_COMBINING_MARK=0x40, - /** - * A label or domain name contains disallowed characters. - * @stable ICU 4.6 - */ - UIDNA_ERROR_DISALLOWED=0x80, - /** - * A label starts with "xn--" but does not contain valid Punycode. - * That is, an xn-- label failed Punycode decoding. - * @stable ICU 4.6 - */ - UIDNA_ERROR_PUNYCODE=0x100, - /** - * A label contains a dot=full stop. - * This can occur in an input string for a single-label function. - * @stable ICU 4.6 - */ - UIDNA_ERROR_LABEL_HAS_DOT=0x200, - /** - * An ACE label does not contain a valid label string. - * The label was successfully ACE (Punycode) decoded but the resulting - * string had severe validation errors. For example, - * it might contain characters that are not allowed in ACE labels, - * or it might not be normalized. - * @stable ICU 4.6 - */ - UIDNA_ERROR_INVALID_ACE_LABEL=0x400, - /** - * A label does not meet the IDNA BiDi requirements (for right-to-left characters). - * @stable ICU 4.6 - */ - UIDNA_ERROR_BIDI=0x800, - /** - * A label does not meet the IDNA CONTEXTJ requirements. - * @stable ICU 4.6 - */ - UIDNA_ERROR_CONTEXTJ=0x1000, - /** - * A label does not meet the IDNA CONTEXTO requirements for punctuation characters. - * Some punctuation characters "Would otherwise have been DISALLOWED" - * but are allowed in certain contexts. (RFC 5892) - * @stable ICU 49 - */ - UIDNA_ERROR_CONTEXTO_PUNCTUATION=0x2000, - /** - * A label does not meet the IDNA CONTEXTO requirements for digits. - * Arabic-Indic Digits (U+066x) must not be mixed with Extended Arabic-Indic Digits (U+06Fx). - * @stable ICU 49 - */ - UIDNA_ERROR_CONTEXTO_DIGITS=0x4000 -}; - -#ifndef U_HIDE_DEPRECATED_API - -/* IDNA2003 API ------------------------------------------------------------- */ - -/** - * IDNA2003: This function implements the ToASCII operation as defined in the IDNA RFC. - * This operation is done on single labels before sending it to something that expects - * ASCII names. A label is an individual part of a domain name. Labels are usually - * separated by dots; e.g. "www.example.com" is composed of 3 labels "www","example", and "com". - * - * IDNA2003 API Overview: - * - * The uidna_ API implements the IDNA protocol as defined in the IDNA RFC - * (http://www.ietf.org/rfc/rfc3490.txt). - * The RFC defines 2 operations: ToASCII and ToUnicode. Domain name labels - * containing non-ASCII code points are processed by the - * ToASCII operation before passing it to resolver libraries. Domain names - * that are obtained from resolver libraries are processed by the - * ToUnicode operation before displaying the domain name to the user. - * IDNA requires that implementations process input strings with Nameprep - * (http://www.ietf.org/rfc/rfc3491.txt), - * which is a profile of Stringprep (http://www.ietf.org/rfc/rfc3454.txt), - * and then with Punycode (http://www.ietf.org/rfc/rfc3492.txt). - * Implementations of IDNA MUST fully implement Nameprep and Punycode; - * neither Nameprep nor Punycode are optional. - * The input and output of ToASCII and ToUnicode operations are Unicode - * and are designed to be chainable, i.e., applying ToASCII or ToUnicode operations - * multiple times to an input string will yield the same result as applying the operation - * once. - * ToUnicode(ToUnicode(ToUnicode...(ToUnicode(string)))) == ToUnicode(string) - * ToASCII(ToASCII(ToASCII...(ToASCII(string))) == ToASCII(string). - * - * @param src Input UChar array containing label in Unicode. - * @param srcLength Number of UChars in src, or -1 if NUL-terminated. - * @param dest Output UChar array with ASCII (ACE encoded) label. - * @param destCapacity Size of dest. - * @param options A bit set of options: - * - * - UIDNA_DEFAULT Use default options, i.e., do not process unassigned code points - * and do not use STD3 ASCII rules - * If unassigned code points are found the operation fails with - * U_UNASSIGNED_ERROR error code. - * - * - UIDNA_ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations - * If this option is set, the unassigned code points are in the input - * are treated as normal Unicode code points. - * - * - UIDNA_USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions - * If this option is set and the input does not satisfy STD3 rules, - * the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR - * - * @param parseError Pointer to UParseError struct to receive information on position - * of error if an error is encountered. Can be NULL. - * @param status ICU in/out error code parameter. - * U_INVALID_CHAR_FOUND if src contains - * unmatched single surrogates. - * U_INDEX_OUTOFBOUNDS_ERROR if src contains - * too many code points. - * U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough - * @return The length of the result string, if successful - or in case of a buffer overflow, - * in which case it will be greater than destCapacity. - * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. - */ -U_DEPRECATED int32_t U_EXPORT2 -uidna_toASCII(const UChar* src, int32_t srcLength, - UChar* dest, int32_t destCapacity, - int32_t options, - UParseError* parseError, - UErrorCode* status); - - -/** - * IDNA2003: This function implements the ToUnicode operation as defined in the IDNA RFC. - * This operation is done on single labels before sending it to something that expects - * Unicode names. A label is an individual part of a domain name. Labels are usually - * separated by dots; for e.g. "www.example.com" is composed of 3 labels "www","example", and "com". - * - * @param src Input UChar array containing ASCII (ACE encoded) label. - * @param srcLength Number of UChars in src, or -1 if NUL-terminated. - * @param dest Output Converted UChar array containing Unicode equivalent of label. - * @param destCapacity Size of dest. - * @param options A bit set of options: - * - * - UIDNA_DEFAULT Use default options, i.e., do not process unassigned code points - * and do not use STD3 ASCII rules - * If unassigned code points are found the operation fails with - * U_UNASSIGNED_ERROR error code. - * - * - UIDNA_ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations - * If this option is set, the unassigned code points are in the input - * are treated as normal Unicode code points. Note: This option is - * required on toUnicode operation because the RFC mandates - * verification of decoded ACE input by applying toASCII and comparing - * its output with source - * - * - UIDNA_USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions - * If this option is set and the input does not satisfy STD3 rules, - * the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR - * - * @param parseError Pointer to UParseError struct to receive information on position - * of error if an error is encountered. Can be NULL. - * @param status ICU in/out error code parameter. - * U_INVALID_CHAR_FOUND if src contains - * unmatched single surrogates. - * U_INDEX_OUTOFBOUNDS_ERROR if src contains - * too many code points. - * U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough - * @return The length of the result string, if successful - or in case of a buffer overflow, - * in which case it will be greater than destCapacity. - * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. - */ -U_DEPRECATED int32_t U_EXPORT2 -uidna_toUnicode(const UChar* src, int32_t srcLength, - UChar* dest, int32_t destCapacity, - int32_t options, - UParseError* parseError, - UErrorCode* status); - - -/** - * IDNA2003: Convenience function that implements the IDNToASCII operation as defined in the IDNA RFC. - * This operation is done on complete domain names, e.g: "www.example.com". - * It is important to note that this operation can fail. If it fails, then the input - * domain name cannot be used as an Internationalized Domain Name and the application - * should have methods defined to deal with the failure. - * - * Note: IDNA RFC specifies that a conformant application should divide a domain name - * into separate labels, decide whether to apply allowUnassigned and useSTD3ASCIIRules on each, - * and then convert. This function does not offer that level of granularity. The options once - * set will apply to all labels in the domain name - * - * @param src Input UChar array containing IDN in Unicode. - * @param srcLength Number of UChars in src, or -1 if NUL-terminated. - * @param dest Output UChar array with ASCII (ACE encoded) IDN. - * @param destCapacity Size of dest. - * @param options A bit set of options: - * - * - UIDNA_DEFAULT Use default options, i.e., do not process unassigned code points - * and do not use STD3 ASCII rules - * If unassigned code points are found the operation fails with - * U_UNASSIGNED_CODE_POINT_FOUND error code. - * - * - UIDNA_ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations - * If this option is set, the unassigned code points are in the input - * are treated as normal Unicode code points. - * - * - UIDNA_USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions - * If this option is set and the input does not satisfy STD3 rules, - * the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR - * - * @param parseError Pointer to UParseError struct to receive information on position - * of error if an error is encountered. Can be NULL. - * @param status ICU in/out error code parameter. - * U_INVALID_CHAR_FOUND if src contains - * unmatched single surrogates. - * U_INDEX_OUTOFBOUNDS_ERROR if src contains - * too many code points. - * U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough - * @return The length of the result string, if successful - or in case of a buffer overflow, - * in which case it will be greater than destCapacity. - * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. - */ -U_DEPRECATED int32_t U_EXPORT2 -uidna_IDNToASCII( const UChar* src, int32_t srcLength, - UChar* dest, int32_t destCapacity, - int32_t options, - UParseError* parseError, - UErrorCode* status); - -/** - * IDNA2003: Convenience function that implements the IDNToUnicode operation as defined in the IDNA RFC. - * This operation is done on complete domain names, e.g: "www.example.com". - * - * Note: IDNA RFC specifies that a conformant application should divide a domain name - * into separate labels, decide whether to apply allowUnassigned and useSTD3ASCIIRules on each, - * and then convert. This function does not offer that level of granularity. The options once - * set will apply to all labels in the domain name - * - * @param src Input UChar array containing IDN in ASCII (ACE encoded) form. - * @param srcLength Number of UChars in src, or -1 if NUL-terminated. - * @param dest Output UChar array containing Unicode equivalent of source IDN. - * @param destCapacity Size of dest. - * @param options A bit set of options: - * - * - UIDNA_DEFAULT Use default options, i.e., do not process unassigned code points - * and do not use STD3 ASCII rules - * If unassigned code points are found the operation fails with - * U_UNASSIGNED_CODE_POINT_FOUND error code. - * - * - UIDNA_ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations - * If this option is set, the unassigned code points are in the input - * are treated as normal Unicode code points. - * - * - UIDNA_USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions - * If this option is set and the input does not satisfy STD3 rules, - * the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR - * - * @param parseError Pointer to UParseError struct to receive information on position - * of error if an error is encountered. Can be NULL. - * @param status ICU in/out error code parameter. - * U_INVALID_CHAR_FOUND if src contains - * unmatched single surrogates. - * U_INDEX_OUTOFBOUNDS_ERROR if src contains - * too many code points. - * U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough - * @return The length of the result string, if successful - or in case of a buffer overflow, - * in which case it will be greater than destCapacity. - * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. - */ -U_DEPRECATED int32_t U_EXPORT2 -uidna_IDNToUnicode( const UChar* src, int32_t srcLength, - UChar* dest, int32_t destCapacity, - int32_t options, - UParseError* parseError, - UErrorCode* status); - -/** - * IDNA2003: Compare two IDN strings for equivalence. - * This function splits the domain names into labels and compares them. - * According to IDN RFC, whenever two labels are compared, they are - * considered equal if and only if their ASCII forms (obtained by - * applying toASCII) match using an case-insensitive ASCII comparison. - * Two domain names are considered a match if and only if all labels - * match regardless of whether label separators match. - * - * @param s1 First source string. - * @param length1 Length of first source string, or -1 if NUL-terminated. - * - * @param s2 Second source string. - * @param length2 Length of second source string, or -1 if NUL-terminated. - * @param options A bit set of options: - * - * - UIDNA_DEFAULT Use default options, i.e., do not process unassigned code points - * and do not use STD3 ASCII rules - * If unassigned code points are found the operation fails with - * U_UNASSIGNED_CODE_POINT_FOUND error code. - * - * - UIDNA_ALLOW_UNASSIGNED Unassigned values can be converted to ASCII for query operations - * If this option is set, the unassigned code points are in the input - * are treated as normal Unicode code points. - * - * - UIDNA_USE_STD3_RULES Use STD3 ASCII rules for host name syntax restrictions - * If this option is set and the input does not satisfy STD3 rules, - * the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR - * - * @param status ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return <0 or 0 or >0 as usual for string comparisons - * @deprecated ICU 55 Use UTS #46 instead via uidna_openUTS46() or class IDNA. - */ -U_DEPRECATED int32_t U_EXPORT2 -uidna_compare( const UChar *s1, int32_t length1, - const UChar *s2, int32_t length2, - int32_t options, - UErrorCode* status); - -#endif /* U_HIDE_DEPRECATED_API */ - -#endif /* #if !UCONFIG_NO_IDNA */ - -#endif diff --git a/win32/include/spidermonkey/unicode/uiter.h b/win32/include/spidermonkey/unicode/uiter.h deleted file mode 100755 index e6cb838c..00000000 --- a/win32/include/spidermonkey/unicode/uiter.h +++ /dev/null @@ -1,709 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2002-2011 International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: uiter.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2002jan18 -* created by: Markus W. Scherer -*/ - -#ifndef __UITER_H__ -#define __UITER_H__ - -/** - * \file - * \brief C API: Unicode Character Iteration - * - * @see UCharIterator - */ - -#include "unicode/utypes.h" - -#if U_SHOW_CPLUSPLUS_API - U_NAMESPACE_BEGIN - - class CharacterIterator; - class Replaceable; - - U_NAMESPACE_END -#endif - -U_CDECL_BEGIN - -struct UCharIterator; -typedef struct UCharIterator UCharIterator; /**< C typedef for struct UCharIterator. @stable ICU 2.1 */ - -/** - * Origin constants for UCharIterator.getIndex() and UCharIterator.move(). - * @see UCharIteratorMove - * @see UCharIterator - * @stable ICU 2.1 - */ -typedef enum UCharIteratorOrigin { - UITER_START, UITER_CURRENT, UITER_LIMIT, UITER_ZERO, UITER_LENGTH -} UCharIteratorOrigin; - -/** Constants for UCharIterator. @stable ICU 2.6 */ -enum { - /** - * Constant value that may be returned by UCharIteratorMove - * indicating that the final UTF-16 index is not known, but that the move succeeded. - * This can occur when moving relative to limit or length, or - * when moving relative to the current index after a setState() - * when the current UTF-16 index is not known. - * - * It would be very inefficient to have to count from the beginning of the text - * just to get the current/limit/length index after moving relative to it. - * The actual index can be determined with getIndex(UITER_CURRENT) - * which will count the UChars if necessary. - * - * @stable ICU 2.6 - */ - UITER_UNKNOWN_INDEX=-2 -}; - - -/** - * Constant for UCharIterator getState() indicating an error or - * an unknown state. - * Returned by uiter_getState()/UCharIteratorGetState - * when an error occurs. - * Also, some UCharIterator implementations may not be able to return - * a valid state for each position. This will be clearly documented - * for each such iterator (none of the public ones here). - * - * @stable ICU 2.6 - */ -#define UITER_NO_STATE ((uint32_t)0xffffffff) - -/** - * Function type declaration for UCharIterator.getIndex(). - * - * Gets the current position, or the start or limit of the - * iteration range. - * - * This function may perform slowly for UITER_CURRENT after setState() was called, - * or for UITER_LENGTH, because an iterator implementation may have to count - * UChars if the underlying storage is not UTF-16. - * - * @param iter the UCharIterator structure ("this pointer") - * @param origin get the 0, start, limit, length, or current index - * @return the requested index, or U_SENTINEL in an error condition - * - * @see UCharIteratorOrigin - * @see UCharIterator - * @stable ICU 2.1 - */ -typedef int32_t U_CALLCONV -UCharIteratorGetIndex(UCharIterator *iter, UCharIteratorOrigin origin); - -/** - * Function type declaration for UCharIterator.move(). - * - * Use iter->move(iter, index, UITER_ZERO) like CharacterIterator::setIndex(index). - * - * Moves the current position relative to the start or limit of the - * iteration range, or relative to the current position itself. - * The movement is expressed in numbers of code units forward - * or backward by specifying a positive or negative delta. - * Out of bounds movement will be pinned to the start or limit. - * - * This function may perform slowly for moving relative to UITER_LENGTH - * because an iterator implementation may have to count the rest of the - * UChars if the native storage is not UTF-16. - * - * When moving relative to the limit or length, or - * relative to the current position after setState() was called, - * move() may return UITER_UNKNOWN_INDEX (-2) to avoid an inefficient - * determination of the actual UTF-16 index. - * The actual index can be determined with getIndex(UITER_CURRENT) - * which will count the UChars if necessary. - * See UITER_UNKNOWN_INDEX for details. - * - * @param iter the UCharIterator structure ("this pointer") - * @param delta can be positive, zero, or negative - * @param origin move relative to the 0, start, limit, length, or current index - * @return the new index, or U_SENTINEL on an error condition, - * or UITER_UNKNOWN_INDEX when the index is not known. - * - * @see UCharIteratorOrigin - * @see UCharIterator - * @see UITER_UNKNOWN_INDEX - * @stable ICU 2.1 - */ -typedef int32_t U_CALLCONV -UCharIteratorMove(UCharIterator *iter, int32_t delta, UCharIteratorOrigin origin); - -/** - * Function type declaration for UCharIterator.hasNext(). - * - * Check if current() and next() can still - * return another code unit. - * - * @param iter the UCharIterator structure ("this pointer") - * @return boolean value for whether current() and next() can still return another code unit - * - * @see UCharIterator - * @stable ICU 2.1 - */ -typedef UBool U_CALLCONV -UCharIteratorHasNext(UCharIterator *iter); - -/** - * Function type declaration for UCharIterator.hasPrevious(). - * - * Check if previous() can still return another code unit. - * - * @param iter the UCharIterator structure ("this pointer") - * @return boolean value for whether previous() can still return another code unit - * - * @see UCharIterator - * @stable ICU 2.1 - */ -typedef UBool U_CALLCONV -UCharIteratorHasPrevious(UCharIterator *iter); - -/** - * Function type declaration for UCharIterator.current(). - * - * Return the code unit at the current position, - * or U_SENTINEL if there is none (index is at the limit). - * - * @param iter the UCharIterator structure ("this pointer") - * @return the current code unit - * - * @see UCharIterator - * @stable ICU 2.1 - */ -typedef UChar32 U_CALLCONV -UCharIteratorCurrent(UCharIterator *iter); - -/** - * Function type declaration for UCharIterator.next(). - * - * Return the code unit at the current index and increment - * the index (post-increment, like s[i++]), - * or return U_SENTINEL if there is none (index is at the limit). - * - * @param iter the UCharIterator structure ("this pointer") - * @return the current code unit (and post-increment the current index) - * - * @see UCharIterator - * @stable ICU 2.1 - */ -typedef UChar32 U_CALLCONV -UCharIteratorNext(UCharIterator *iter); - -/** - * Function type declaration for UCharIterator.previous(). - * - * Decrement the index and return the code unit from there - * (pre-decrement, like s[--i]), - * or return U_SENTINEL if there is none (index is at the start). - * - * @param iter the UCharIterator structure ("this pointer") - * @return the previous code unit (after pre-decrementing the current index) - * - * @see UCharIterator - * @stable ICU 2.1 - */ -typedef UChar32 U_CALLCONV -UCharIteratorPrevious(UCharIterator *iter); - -/** - * Function type declaration for UCharIterator.reservedFn(). - * Reserved for future use. - * - * @param iter the UCharIterator structure ("this pointer") - * @param something some integer argument - * @return some integer - * - * @see UCharIterator - * @stable ICU 2.1 - */ -typedef int32_t U_CALLCONV -UCharIteratorReserved(UCharIterator *iter, int32_t something); - -/** - * Function type declaration for UCharIterator.getState(). - * - * Get the "state" of the iterator in the form of a single 32-bit word. - * It is recommended that the state value be calculated to be as small as - * is feasible. For strings with limited lengths, fewer than 32 bits may - * be sufficient. - * - * This is used together with setState()/UCharIteratorSetState - * to save and restore the iterator position more efficiently than with - * getIndex()/move(). - * - * The iterator state is defined as a uint32_t value because it is designed - * for use in ucol_nextSortKeyPart() which provides 32 bits to store the state - * of the character iterator. - * - * With some UCharIterator implementations (e.g., UTF-8), - * getting and setting the UTF-16 index with existing functions - * (getIndex(UITER_CURRENT) followed by move(pos, UITER_ZERO)) is possible but - * relatively slow because the iterator has to "walk" from a known index - * to the requested one. - * This takes more time the farther it needs to go. - * - * An opaque state value allows an iterator implementation to provide - * an internal index (UTF-8: the source byte array index) for - * fast, constant-time restoration. - * - * After calling setState(), a getIndex(UITER_CURRENT) may be slow because - * the UTF-16 index may not be restored as well, but the iterator can deliver - * the correct text contents and move relative to the current position - * without performance degradation. - * - * Some UCharIterator implementations may not be able to return - * a valid state for each position, in which case they return UITER_NO_STATE instead. - * This will be clearly documented for each such iterator (none of the public ones here). - * - * @param iter the UCharIterator structure ("this pointer") - * @return the state word - * - * @see UCharIterator - * @see UCharIteratorSetState - * @see UITER_NO_STATE - * @stable ICU 2.6 - */ -typedef uint32_t U_CALLCONV -UCharIteratorGetState(const UCharIterator *iter); - -/** - * Function type declaration for UCharIterator.setState(). - * - * Restore the "state" of the iterator using a state word from a getState() call. - * The iterator object need not be the same one as for which getState() was called, - * but it must be of the same type (set up using the same uiter_setXYZ function) - * and it must iterate over the same string - * (binary identical regardless of memory address). - * For more about the state word see UCharIteratorGetState. - * - * After calling setState(), a getIndex(UITER_CURRENT) may be slow because - * the UTF-16 index may not be restored as well, but the iterator can deliver - * the correct text contents and move relative to the current position - * without performance degradation. - * - * @param iter the UCharIterator structure ("this pointer") - * @param state the state word from a getState() call - * on a same-type, same-string iterator - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * - * @see UCharIterator - * @see UCharIteratorGetState - * @stable ICU 2.6 - */ -typedef void U_CALLCONV -UCharIteratorSetState(UCharIterator *iter, uint32_t state, UErrorCode *pErrorCode); - - -/** - * C API for code unit iteration. - * This can be used as a C wrapper around - * CharacterIterator, Replaceable, or implemented using simple strings, etc. - * - * There are two roles for using UCharIterator: - * - * A "provider" sets the necessary function pointers and controls the "protected" - * fields of the UCharIterator structure. A "provider" passes a UCharIterator - * into C APIs that need a UCharIterator as an abstract, flexible string interface. - * - * Implementations of such C APIs are "callers" of UCharIterator functions; - * they only use the "public" function pointers and never access the "protected" - * fields directly. - * - * The current() and next() functions only check the current index against the - * limit, and previous() only checks the current index against the start, - * to see if the iterator already reached the end of the iteration range. - * - * The assumption - in all iterators - is that the index is moved via the API, - * which means it won't go out of bounds, or the index is modified by - * user code that knows enough about the iterator implementation to set valid - * index values. - * - * UCharIterator functions return code unit values 0..0xffff, - * or U_SENTINEL if the iteration bounds are reached. - * - * @stable ICU 2.1 - */ -struct UCharIterator { - /** - * (protected) Pointer to string or wrapped object or similar. - * Not used by caller. - * @stable ICU 2.1 - */ - const void *context; - - /** - * (protected) Length of string or similar. - * Not used by caller. - * @stable ICU 2.1 - */ - int32_t length; - - /** - * (protected) Start index or similar. - * Not used by caller. - * @stable ICU 2.1 - */ - int32_t start; - - /** - * (protected) Current index or similar. - * Not used by caller. - * @stable ICU 2.1 - */ - int32_t index; - - /** - * (protected) Limit index or similar. - * Not used by caller. - * @stable ICU 2.1 - */ - int32_t limit; - - /** - * (protected) Used by UTF-8 iterators and possibly others. - * @stable ICU 2.1 - */ - int32_t reservedField; - - /** - * (public) Returns the current position or the - * start or limit index of the iteration range. - * - * @see UCharIteratorGetIndex - * @stable ICU 2.1 - */ - UCharIteratorGetIndex *getIndex; - - /** - * (public) Moves the current position relative to the start or limit of the - * iteration range, or relative to the current position itself. - * The movement is expressed in numbers of code units forward - * or backward by specifying a positive or negative delta. - * - * @see UCharIteratorMove - * @stable ICU 2.1 - */ - UCharIteratorMove *move; - - /** - * (public) Check if current() and next() can still - * return another code unit. - * - * @see UCharIteratorHasNext - * @stable ICU 2.1 - */ - UCharIteratorHasNext *hasNext; - - /** - * (public) Check if previous() can still return another code unit. - * - * @see UCharIteratorHasPrevious - * @stable ICU 2.1 - */ - UCharIteratorHasPrevious *hasPrevious; - - /** - * (public) Return the code unit at the current position, - * or U_SENTINEL if there is none (index is at the limit). - * - * @see UCharIteratorCurrent - * @stable ICU 2.1 - */ - UCharIteratorCurrent *current; - - /** - * (public) Return the code unit at the current index and increment - * the index (post-increment, like s[i++]), - * or return U_SENTINEL if there is none (index is at the limit). - * - * @see UCharIteratorNext - * @stable ICU 2.1 - */ - UCharIteratorNext *next; - - /** - * (public) Decrement the index and return the code unit from there - * (pre-decrement, like s[--i]), - * or return U_SENTINEL if there is none (index is at the start). - * - * @see UCharIteratorPrevious - * @stable ICU 2.1 - */ - UCharIteratorPrevious *previous; - - /** - * (public) Reserved for future use. Currently NULL. - * - * @see UCharIteratorReserved - * @stable ICU 2.1 - */ - UCharIteratorReserved *reservedFn; - - /** - * (public) Return the state of the iterator, to be restored later with setState(). - * This function pointer is NULL if the iterator does not implement it. - * - * @see UCharIteratorGet - * @stable ICU 2.6 - */ - UCharIteratorGetState *getState; - - /** - * (public) Restore the iterator state from the state word from a call - * to getState(). - * This function pointer is NULL if the iterator does not implement it. - * - * @see UCharIteratorSet - * @stable ICU 2.6 - */ - UCharIteratorSetState *setState; -}; - -/** - * Helper function for UCharIterator to get the code point - * at the current index. - * - * Return the code point that includes the code unit at the current position, - * or U_SENTINEL if there is none (index is at the limit). - * If the current code unit is a lead or trail surrogate, - * then the following or preceding surrogate is used to form - * the code point value. - * - * @param iter the UCharIterator structure ("this pointer") - * @return the current code point - * - * @see UCharIterator - * @see U16_GET - * @see UnicodeString::char32At() - * @stable ICU 2.1 - */ -U_STABLE UChar32 U_EXPORT2 -uiter_current32(UCharIterator *iter); - -/** - * Helper function for UCharIterator to get the next code point. - * - * Return the code point at the current index and increment - * the index (post-increment, like s[i++]), - * or return U_SENTINEL if there is none (index is at the limit). - * - * @param iter the UCharIterator structure ("this pointer") - * @return the current code point (and post-increment the current index) - * - * @see UCharIterator - * @see U16_NEXT - * @stable ICU 2.1 - */ -U_STABLE UChar32 U_EXPORT2 -uiter_next32(UCharIterator *iter); - -/** - * Helper function for UCharIterator to get the previous code point. - * - * Decrement the index and return the code point from there - * (pre-decrement, like s[--i]), - * or return U_SENTINEL if there is none (index is at the start). - * - * @param iter the UCharIterator structure ("this pointer") - * @return the previous code point (after pre-decrementing the current index) - * - * @see UCharIterator - * @see U16_PREV - * @stable ICU 2.1 - */ -U_STABLE UChar32 U_EXPORT2 -uiter_previous32(UCharIterator *iter); - -/** - * Get the "state" of the iterator in the form of a single 32-bit word. - * This is a convenience function that calls iter->getState(iter) - * if iter->getState is not NULL; - * if it is NULL or any other error occurs, then UITER_NO_STATE is returned. - * - * Some UCharIterator implementations may not be able to return - * a valid state for each position, in which case they return UITER_NO_STATE instead. - * This will be clearly documented for each such iterator (none of the public ones here). - * - * @param iter the UCharIterator structure ("this pointer") - * @return the state word - * - * @see UCharIterator - * @see UCharIteratorGetState - * @see UITER_NO_STATE - * @stable ICU 2.6 - */ -U_STABLE uint32_t U_EXPORT2 -uiter_getState(const UCharIterator *iter); - -/** - * Restore the "state" of the iterator using a state word from a getState() call. - * This is a convenience function that calls iter->setState(iter, state, pErrorCode) - * if iter->setState is not NULL; if it is NULL, then U_UNSUPPORTED_ERROR is set. - * - * @param iter the UCharIterator structure ("this pointer") - * @param state the state word from a getState() call - * on a same-type, same-string iterator - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * - * @see UCharIterator - * @see UCharIteratorSetState - * @stable ICU 2.6 - */ -U_STABLE void U_EXPORT2 -uiter_setState(UCharIterator *iter, uint32_t state, UErrorCode *pErrorCode); - -/** - * Set up a UCharIterator to iterate over a string. - * - * Sets the UCharIterator function pointers for iteration over the string s - * with iteration boundaries start=index=0 and length=limit=string length. - * The "provider" may set the start, index, and limit values at any time - * within the range 0..length. - * The length field will be ignored. - * - * The string pointer s is set into UCharIterator.context without copying - * or reallocating the string contents. - * - * getState() simply returns the current index. - * move() will always return the final index. - * - * @param iter UCharIterator structure to be set for iteration - * @param s String to iterate over - * @param length Length of s, or -1 if NUL-terminated - * - * @see UCharIterator - * @stable ICU 2.1 - */ -U_STABLE void U_EXPORT2 -uiter_setString(UCharIterator *iter, const UChar *s, int32_t length); - -/** - * Set up a UCharIterator to iterate over a UTF-16BE string - * (byte vector with a big-endian pair of bytes per UChar). - * - * Everything works just like with a normal UChar iterator (uiter_setString), - * except that UChars are assembled from byte pairs, - * and that the length argument here indicates an even number of bytes. - * - * getState() simply returns the current index. - * move() will always return the final index. - * - * @param iter UCharIterator structure to be set for iteration - * @param s UTF-16BE string to iterate over - * @param length Length of s as an even number of bytes, or -1 if NUL-terminated - * (NUL means pair of 0 bytes at even index from s) - * - * @see UCharIterator - * @see uiter_setString - * @stable ICU 2.6 - */ -U_STABLE void U_EXPORT2 -uiter_setUTF16BE(UCharIterator *iter, const char *s, int32_t length); - -/** - * Set up a UCharIterator to iterate over a UTF-8 string. - * - * Sets the UCharIterator function pointers for iteration over the UTF-8 string s - * with UTF-8 iteration boundaries 0 and length. - * The implementation counts the UTF-16 index on the fly and - * lazily evaluates the UTF-16 length of the text. - * - * The start field is used as the UTF-8 offset, the limit field as the UTF-8 length. - * When the reservedField is not 0, then it contains a supplementary code point - * and the UTF-16 index is between the two corresponding surrogates. - * At that point, the UTF-8 index is behind that code point. - * - * The UTF-8 string pointer s is set into UCharIterator.context without copying - * or reallocating the string contents. - * - * getState() returns a state value consisting of - * - the current UTF-8 source byte index (bits 31..1) - * - a flag (bit 0) that indicates whether the UChar position is in the middle - * of a surrogate pair - * (from a 4-byte UTF-8 sequence for the corresponding supplementary code point) - * - * getState() cannot also encode the UTF-16 index in the state value. - * move(relative to limit or length), or - * move(relative to current) after setState(), may return UITER_UNKNOWN_INDEX. - * - * @param iter UCharIterator structure to be set for iteration - * @param s UTF-8 string to iterate over - * @param length Length of s in bytes, or -1 if NUL-terminated - * - * @see UCharIterator - * @stable ICU 2.6 - */ -U_STABLE void U_EXPORT2 -uiter_setUTF8(UCharIterator *iter, const char *s, int32_t length); - -#if U_SHOW_CPLUSPLUS_API - -/** - * Set up a UCharIterator to wrap around a C++ CharacterIterator. - * - * Sets the UCharIterator function pointers for iteration using the - * CharacterIterator charIter. - * - * The CharacterIterator pointer charIter is set into UCharIterator.context - * without copying or cloning the CharacterIterator object. - * The other "protected" UCharIterator fields are set to 0 and will be ignored. - * The iteration index and boundaries are controlled by the CharacterIterator. - * - * getState() simply returns the current index. - * move() will always return the final index. - * - * @param iter UCharIterator structure to be set for iteration - * @param charIter CharacterIterator to wrap - * - * @see UCharIterator - * @stable ICU 2.1 - */ -U_STABLE void U_EXPORT2 -uiter_setCharacterIterator(UCharIterator *iter, icu::CharacterIterator *charIter); - -/** - * Set up a UCharIterator to iterate over a C++ Replaceable. - * - * Sets the UCharIterator function pointers for iteration over the - * Replaceable rep with iteration boundaries start=index=0 and - * length=limit=rep->length(). - * The "provider" may set the start, index, and limit values at any time - * within the range 0..length=rep->length(). - * The length field will be ignored. - * - * The Replaceable pointer rep is set into UCharIterator.context without copying - * or cloning/reallocating the Replaceable object. - * - * getState() simply returns the current index. - * move() will always return the final index. - * - * @param iter UCharIterator structure to be set for iteration - * @param rep Replaceable to iterate over - * - * @see UCharIterator - * @stable ICU 2.1 - */ -U_STABLE void U_EXPORT2 -uiter_setReplaceable(UCharIterator *iter, const icu::Replaceable *rep); - -#endif - -U_CDECL_END - -#endif diff --git a/win32/include/spidermonkey/unicode/uldnames.h b/win32/include/spidermonkey/unicode/uldnames.h deleted file mode 100755 index 30f465a4..00000000 --- a/win32/include/spidermonkey/unicode/uldnames.h +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2010-2016, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -*/ - -#ifndef __ULDNAMES_H__ -#define __ULDNAMES_H__ - -/** - * \file - * \brief C API: Provides display names of Locale ids and their components. - */ - -#include "unicode/utypes.h" -#include "unicode/localpointer.h" -#include "unicode/uscript.h" -#include "unicode/udisplaycontext.h" - -/** - * Enum used in LocaleDisplayNames::createInstance. - * @stable ICU 4.4 - */ -typedef enum { - /** - * Use standard names when generating a locale name, - * e.g. en_GB displays as 'English (United Kingdom)'. - * @stable ICU 4.4 - */ - ULDN_STANDARD_NAMES = 0, - /** - * Use dialect names, when generating a locale name, - * e.g. en_GB displays as 'British English'. - * @stable ICU 4.4 - */ - ULDN_DIALECT_NAMES -} UDialectHandling; - -/** - * Opaque C service object type for the locale display names API - * @stable ICU 4.4 - */ -struct ULocaleDisplayNames; - -/** - * C typedef for struct ULocaleDisplayNames. - * @stable ICU 4.4 - */ -typedef struct ULocaleDisplayNames ULocaleDisplayNames; - -#if !UCONFIG_NO_FORMATTING - -/** - * Returns an instance of LocaleDisplayNames that returns names - * formatted for the provided locale, using the provided - * dialectHandling. The usual value for dialectHandling is - * ULOC_STANDARD_NAMES. - * - * @param locale the display locale - * @param dialectHandling how to select names for locales - * @return a ULocaleDisplayNames instance - * @param pErrorCode the status code - * @stable ICU 4.4 - */ -U_STABLE ULocaleDisplayNames * U_EXPORT2 -uldn_open(const char * locale, - UDialectHandling dialectHandling, - UErrorCode *pErrorCode); - -/** - * Closes a ULocaleDisplayNames instance obtained from uldn_open(). - * @param ldn the ULocaleDisplayNames instance to be closed - * @stable ICU 4.4 - */ -U_STABLE void U_EXPORT2 -uldn_close(ULocaleDisplayNames *ldn); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalULocaleDisplayNamesPointer - * "Smart pointer" class, closes a ULocaleDisplayNames via uldn_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalULocaleDisplayNamesPointer, ULocaleDisplayNames, uldn_close); - -U_NAMESPACE_END - -#endif - -/* getters for state */ - -/** - * Returns the locale used to determine the display names. This is - * not necessarily the same locale passed to {@link #uldn_open}. - * @param ldn the LocaleDisplayNames instance - * @return the display locale - * @stable ICU 4.4 - */ -U_STABLE const char * U_EXPORT2 -uldn_getLocale(const ULocaleDisplayNames *ldn); - -/** - * Returns the dialect handling used in the display names. - * @param ldn the LocaleDisplayNames instance - * @return the dialect handling enum - * @stable ICU 4.4 - */ -U_STABLE UDialectHandling U_EXPORT2 -uldn_getDialectHandling(const ULocaleDisplayNames *ldn); - -/* names for entire locales */ - -/** - * Returns the display name of the provided locale. - * @param ldn the LocaleDisplayNames instance - * @param locale the locale whose display name to return - * @param result receives the display name - * @param maxResultSize the size of the result buffer - * @param pErrorCode the status code - * @return the actual buffer size needed for the display name. If it's - * greater than maxResultSize, the returned name will be truncated. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -uldn_localeDisplayName(const ULocaleDisplayNames *ldn, - const char *locale, - UChar *result, - int32_t maxResultSize, - UErrorCode *pErrorCode); - -/* names for components of a locale */ - -/** - * Returns the display name of the provided language code. - * @param ldn the LocaleDisplayNames instance - * @param lang the language code whose display name to return - * @param result receives the display name - * @param maxResultSize the size of the result buffer - * @param pErrorCode the status code - * @return the actual buffer size needed for the display name. If it's - * greater than maxResultSize, the returned name will be truncated. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -uldn_languageDisplayName(const ULocaleDisplayNames *ldn, - const char *lang, - UChar *result, - int32_t maxResultSize, - UErrorCode *pErrorCode); - -/** - * Returns the display name of the provided script. - * @param ldn the LocaleDisplayNames instance - * @param script the script whose display name to return - * @param result receives the display name - * @param maxResultSize the size of the result buffer - * @param pErrorCode the status code - * @return the actual buffer size needed for the display name. If it's - * greater than maxResultSize, the returned name will be truncated. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -uldn_scriptDisplayName(const ULocaleDisplayNames *ldn, - const char *script, - UChar *result, - int32_t maxResultSize, - UErrorCode *pErrorCode); - -/** - * Returns the display name of the provided script code. - * @param ldn the LocaleDisplayNames instance - * @param scriptCode the script code whose display name to return - * @param result receives the display name - * @param maxResultSize the size of the result buffer - * @param pErrorCode the status code - * @return the actual buffer size needed for the display name. If it's - * greater than maxResultSize, the returned name will be truncated. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -uldn_scriptCodeDisplayName(const ULocaleDisplayNames *ldn, - UScriptCode scriptCode, - UChar *result, - int32_t maxResultSize, - UErrorCode *pErrorCode); - -/** - * Returns the display name of the provided region code. - * @param ldn the LocaleDisplayNames instance - * @param region the region code whose display name to return - * @param result receives the display name - * @param maxResultSize the size of the result buffer - * @param pErrorCode the status code - * @return the actual buffer size needed for the display name. If it's - * greater than maxResultSize, the returned name will be truncated. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -uldn_regionDisplayName(const ULocaleDisplayNames *ldn, - const char *region, - UChar *result, - int32_t maxResultSize, - UErrorCode *pErrorCode); - -/** - * Returns the display name of the provided variant - * @param ldn the LocaleDisplayNames instance - * @param variant the variant whose display name to return - * @param result receives the display name - * @param maxResultSize the size of the result buffer - * @param pErrorCode the status code - * @return the actual buffer size needed for the display name. If it's - * greater than maxResultSize, the returned name will be truncated. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -uldn_variantDisplayName(const ULocaleDisplayNames *ldn, - const char *variant, - UChar *result, - int32_t maxResultSize, - UErrorCode *pErrorCode); - -/** - * Returns the display name of the provided locale key - * @param ldn the LocaleDisplayNames instance - * @param key the locale key whose display name to return - * @param result receives the display name - * @param maxResultSize the size of the result buffer - * @param pErrorCode the status code - * @return the actual buffer size needed for the display name. If it's - * greater than maxResultSize, the returned name will be truncated. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -uldn_keyDisplayName(const ULocaleDisplayNames *ldn, - const char *key, - UChar *result, - int32_t maxResultSize, - UErrorCode *pErrorCode); - -/** - * Returns the display name of the provided value (used with the provided key). - * @param ldn the LocaleDisplayNames instance - * @param key the locale key - * @param value the locale key's value - * @param result receives the display name - * @param maxResultSize the size of the result buffer - * @param pErrorCode the status code - * @return the actual buffer size needed for the display name. If it's - * greater than maxResultSize, the returned name will be truncated. - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -uldn_keyValueDisplayName(const ULocaleDisplayNames *ldn, - const char *key, - const char *value, - UChar *result, - int32_t maxResultSize, - UErrorCode *pErrorCode); - -/** -* Returns an instance of LocaleDisplayNames that returns names formatted -* for the provided locale, using the provided UDisplayContext settings. -* -* @param locale The display locale -* @param contexts List of one or more context settings (e.g. for dialect -* handling, capitalization, etc. -* @param length Number of items in the contexts list -* @param pErrorCode Pointer to UErrorCode input/output status. If at entry this indicates -* a failure status, the function will do nothing; otherwise this will be -* updated with any new status from the function. -* @return a ULocaleDisplayNames instance -* @stable ICU 51 -*/ -U_STABLE ULocaleDisplayNames * U_EXPORT2 -uldn_openForContext(const char * locale, UDisplayContext *contexts, - int32_t length, UErrorCode *pErrorCode); - -/** -* Returns the UDisplayContext value for the specified UDisplayContextType. -* @param ldn the ULocaleDisplayNames instance -* @param type the UDisplayContextType whose value to return -* @param pErrorCode Pointer to UErrorCode input/output status. If at entry this indicates -* a failure status, the function will do nothing; otherwise this will be -* updated with any new status from the function. -* @return the UDisplayContextValue for the specified type. -* @stable ICU 51 -*/ -U_STABLE UDisplayContext U_EXPORT2 -uldn_getContext(const ULocaleDisplayNames *ldn, UDisplayContextType type, - UErrorCode *pErrorCode); - -#endif /* !UCONFIG_NO_FORMATTING */ -#endif /* __ULDNAMES_H__ */ diff --git a/win32/include/spidermonkey/unicode/ulistformatter.h b/win32/include/spidermonkey/unicode/ulistformatter.h deleted file mode 100755 index 2167f603..00000000 --- a/win32/include/spidermonkey/unicode/ulistformatter.h +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -***************************************************************************************** -* Copyright (C) 2015-2016, International Business Machines -* Corporation and others. All Rights Reserved. -***************************************************************************************** -*/ - -#ifndef ULISTFORMATTER_H -#define ULISTFORMATTER_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: Format a list in a locale-appropriate way. - * - * A UListFormatter is used to format a list of items in a locale-appropriate way, - * using data from CLDR. - * Example: Input data ["Alice", "Bob", "Charlie", "Delta"] will be formatted - * as "Alice, Bob, Charlie, and Delta" in English. - */ - -/** - * Opaque UListFormatter object for use in C - * @stable ICU 55 - */ -struct UListFormatter; -typedef struct UListFormatter UListFormatter; /**< C typedef for struct UListFormatter. @stable ICU 55 */ - -/** - * Open a new UListFormatter object using the rules for a given locale. - * @param locale - * The locale whose rules should be used; may be NULL for - * default locale. - * @param status - * A pointer to a standard ICU UErrorCode (input/output parameter). - * Its input value must pass the U_SUCCESS() test, or else the - * function returns immediately. The caller should check its output - * value with U_FAILURE(), or use with function chaining (see User - * Guide for details). - * @return - * A pointer to a UListFormatter object for the specified locale, - * or NULL if an error occurred. - * @stable ICU 55 - */ -U_STABLE UListFormatter* U_EXPORT2 -ulistfmt_open(const char* locale, - UErrorCode* status); - -/** - * Close a UListFormatter object. Once closed it may no longer be used. - * @param listfmt - * The UListFormatter object to close. - * @stable ICU 55 - */ -U_STABLE void U_EXPORT2 -ulistfmt_close(UListFormatter *listfmt); - - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUListFormatterPointer - * "Smart pointer" class, closes a UListFormatter via ulistfmt_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 55 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUListFormatterPointer, UListFormatter, ulistfmt_close); - -U_NAMESPACE_END - -#endif - -/** - * Formats a list of strings using the conventions established for the - * UListFormatter object. - * @param listfmt - * The UListFormatter object specifying the list conventions. - * @param strings - * An array of pointers to UChar strings; the array length is - * specified by stringCount. Must be non-NULL if stringCount > 0. - * @param stringLengths - * An array of string lengths corresponding to the strings[] - * parameter; any individual length value may be negative to indicate - * that the corresponding strings[] entry is 0-terminated, or - * stringLengths itself may be NULL if all of the strings are - * 0-terminated. If non-NULL, the stringLengths array must have - * stringCount entries. - * @param stringCount - * the number of entries in strings[], and the number of entries - * in the stringLengths array if it is not NULL. Must be >= 0. - * @param result - * A pointer to a buffer to receive the formatted list. - * @param resultCapacity - * The maximum size of result. - * @param status - * A pointer to a standard ICU UErrorCode (input/output parameter). - * Its input value must pass the U_SUCCESS() test, or else the - * function returns immediately. The caller should check its output - * value with U_FAILURE(), or use with function chaining (see User - * Guide for details). - * @return - * The total buffer size needed; if greater than resultLength, the - * output was truncated. May be <=0 if unable to determine the - * total buffer size needed (e.g. for illegal arguments). - * @stable ICU 55 - */ -U_DRAFT int32_t U_EXPORT2 -ulistfmt_format(const UListFormatter* listfmt, - const UChar* const strings[], - const int32_t * stringLengths, - int32_t stringCount, - UChar* result, - int32_t resultCapacity, - UErrorCode* status); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/uloc.h b/win32/include/spidermonkey/unicode/uloc.h deleted file mode 100755 index 92ce20ec..00000000 --- a/win32/include/spidermonkey/unicode/uloc.h +++ /dev/null @@ -1,1259 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1997-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* -* File ULOC.H -* -* Modification History: -* -* Date Name Description -* 04/01/97 aliu Creation. -* 08/22/98 stephen JDK 1.2 sync. -* 12/08/98 rtg New C API for Locale -* 03/30/99 damiba overhaul -* 03/31/99 helena Javadoc for uloc functions. -* 04/15/99 Madhu Updated Javadoc -******************************************************************************** -*/ - -#ifndef ULOC_H -#define ULOC_H - -#include "unicode/utypes.h" -#include "unicode/uenum.h" - -/** - * \file - * \brief C API: Locale - * - *

ULoc C API for Locale

- * A Locale represents a specific geographical, political, - * or cultural region. An operation that requires a Locale to perform - * its task is called locale-sensitive and uses the Locale - * to tailor information for the user. For example, displaying a number - * is a locale-sensitive operation--the number should be formatted - * according to the customs/conventions of the user's native country, - * region, or culture. In the C APIs, a locales is simply a const char string. - * - *

- * You create a Locale with one of the three options listed below. - * Each of the component is separated by '_' in the locale string. - * \htmlonly

\endhtmlonly - *
- * \code
- *       newLanguage
- * 
- *       newLanguage + newCountry
- * 
- *       newLanguage + newCountry + newVariant
- * \endcode
- * 
- * \htmlonly
\endhtmlonly - * The first option is a valid ISO - * Language Code. These codes are the lower-case two-letter - * codes as defined by ISO-639. - * You can find a full list of these codes at a number of sites, such as: - *
- * http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt - * - *

- * The second option includes an additonal ISO Country - * Code. These codes are the upper-case two-letter codes - * as defined by ISO-3166. - * You can find a full list of these codes at a number of sites, such as: - *
- * http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html - * - *

- * The third option requires another additonal information--the - * Variant. - * The Variant codes are vendor and browser-specific. - * For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX. - * Where there are two variants, separate them with an underscore, and - * put the most important one first. For - * example, a Traditional Spanish collation might be referenced, with - * "ES", "ES", "Traditional_WIN". - * - *

- * Because a Locale is just an identifier for a region, - * no validity check is performed when you specify a Locale. - * If you want to see whether particular resources are available for the - * Locale you asked for, you must query those resources. For - * example, ask the UNumberFormat for the locales it supports - * using its getAvailable method. - *
Note: When you ask for a resource for a particular - * locale, you get back the best available match, not necessarily - * precisely what you asked for. For more information, look at - * UResourceBundle. - * - *

- * The Locale provides a number of convenient constants - * that you can use to specify the commonly used - * locales. For example, the following refers to a locale - * for the United States: - * \htmlonly

\endhtmlonly - *
- * \code
- *       ULOC_US
- * \endcode
- * 
- * \htmlonly
\endhtmlonly - * - *

- * Once you've specified a locale you can query it for information about - * itself. Use uloc_getCountry to get the ISO Country Code and - * uloc_getLanguage to get the ISO Language Code. You can - * use uloc_getDisplayCountry to get the - * name of the country suitable for displaying to the user. Similarly, - * you can use uloc_getDisplayLanguage to get the name of - * the language suitable for displaying to the user. Interestingly, - * the uloc_getDisplayXXX methods are themselves locale-sensitive - * and have two versions: one that uses the default locale and one - * that takes a locale as an argument and displays the name or country in - * a language appropriate to that locale. - * - *

- * The ICU provides a number of services that perform locale-sensitive - * operations. For example, the unum_xxx functions format - * numbers, currency, or percentages in a locale-sensitive manner. - *

- * \htmlonly
\endhtmlonly - *
- * \code
- *     UErrorCode success = U_ZERO_ERROR;
- *     UNumberFormat *nf;
- *     const char* myLocale = "fr_FR";
- * 
- *     nf = unum_open( UNUM_DEFAULT, NULL, success );          
- *     unum_close(nf);
- *     nf = unum_open( UNUM_CURRENCY, NULL, success );
- *     unum_close(nf);
- *     nf = unum_open( UNUM_PERCENT, NULL, success );   
- *     unum_close(nf);
- * \endcode
- * 
- * \htmlonly
\endhtmlonly - * Each of these methods has two variants; one with an explicit locale - * and one without; the latter using the default locale. - * \htmlonly
\endhtmlonly - *
- * \code 
- * 
- *     nf = unum_open( UNUM_DEFAULT, myLocale, success );          
- *     unum_close(nf);
- *     nf = unum_open( UNUM_CURRENCY, myLocale, success );
- *     unum_close(nf);
- *     nf = unum_open( UNUM_PERCENT, myLocale, success );   
- *     unum_close(nf);
- * \endcode
- * 
- * \htmlonly
\endhtmlonly - * A Locale is the mechanism for identifying the kind of services - * (UNumberFormat) that you would like to get. The locale is - * just a mechanism for identifying these services. - * - *

- * Each international serivce that performs locale-sensitive operations - * allows you - * to get all the available objects of that type. You can sift - * through these objects by language, country, or variant, - * and use the display names to present a menu to the user. - * For example, you can create a menu of all the collation objects - * suitable for a given language. Such classes implement these - * three class methods: - * \htmlonly

\endhtmlonly - *
- * \code
- *       const char* uloc_getAvailable(int32_t index);
- *       int32_t uloc_countAvailable();
- *       int32_t
- *       uloc_getDisplayName(const char* localeID,
- *                 const char* inLocaleID, 
- *                 UChar* result,
- *                 int32_t maxResultSize,
- *                  UErrorCode* err);
- * 
- * \endcode
- * 
- * \htmlonly
\endhtmlonly - *

- * Concerning POSIX/RFC1766 Locale IDs, - * the getLanguage/getCountry/getVariant/getName functions do understand - * the POSIX type form of language_COUNTRY.ENCODING\@VARIANT - * and if there is not an ICU-stype variant, uloc_getVariant() for example - * will return the one listed after the \@at sign. As well, the hyphen - * "-" is recognized as a country/variant separator similarly to RFC1766. - * So for example, "en-us" will be interpreted as en_US. - * As a result, uloc_getName() is far from a no-op, and will have the - * effect of converting POSIX/RFC1766 IDs into ICU form, although it does - * NOT map any of the actual codes (i.e. russian->ru) in any way. - * Applications should call uloc_getName() at the point where a locale ID - * is coming from an external source (user entry, OS, web browser) - * and pass the resulting string to other ICU functions. For example, - * don't use de-de\@EURO as an argument to resourcebundle. - * - * @see UResourceBundle - */ - -/** Useful constant for this language. @stable ICU 2.0 */ -#define ULOC_CHINESE "zh" -/** Useful constant for this language. @stable ICU 2.0 */ -#define ULOC_ENGLISH "en" -/** Useful constant for this language. @stable ICU 2.0 */ -#define ULOC_FRENCH "fr" -/** Useful constant for this language. @stable ICU 2.0 */ -#define ULOC_GERMAN "de" -/** Useful constant for this language. @stable ICU 2.0 */ -#define ULOC_ITALIAN "it" -/** Useful constant for this language. @stable ICU 2.0 */ -#define ULOC_JAPANESE "ja" -/** Useful constant for this language. @stable ICU 2.0 */ -#define ULOC_KOREAN "ko" -/** Useful constant for this language. @stable ICU 2.0 */ -#define ULOC_SIMPLIFIED_CHINESE "zh_CN" -/** Useful constant for this language. @stable ICU 2.0 */ -#define ULOC_TRADITIONAL_CHINESE "zh_TW" - -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_CANADA "en_CA" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_CANADA_FRENCH "fr_CA" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_CHINA "zh_CN" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_PRC "zh_CN" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_FRANCE "fr_FR" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_GERMANY "de_DE" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_ITALY "it_IT" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_JAPAN "ja_JP" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_KOREA "ko_KR" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_TAIWAN "zh_TW" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_UK "en_GB" -/** Useful constant for this country/region. @stable ICU 2.0 */ -#define ULOC_US "en_US" - -/** - * Useful constant for the maximum size of the language part of a locale ID. - * (including the terminating NULL). - * @stable ICU 2.0 - */ -#define ULOC_LANG_CAPACITY 12 - -/** - * Useful constant for the maximum size of the country part of a locale ID - * (including the terminating NULL). - * @stable ICU 2.0 - */ -#define ULOC_COUNTRY_CAPACITY 4 -/** - * Useful constant for the maximum size of the whole locale ID - * (including the terminating NULL and all keywords). - * @stable ICU 2.0 - */ -#define ULOC_FULLNAME_CAPACITY 157 - -/** - * Useful constant for the maximum size of the script part of a locale ID - * (including the terminating NULL). - * @stable ICU 2.8 - */ -#define ULOC_SCRIPT_CAPACITY 6 - -/** - * Useful constant for the maximum size of keywords in a locale - * @stable ICU 2.8 - */ -#define ULOC_KEYWORDS_CAPACITY 96 - -/** - * Useful constant for the maximum total size of keywords and their values in a locale - * @stable ICU 2.8 - */ -#define ULOC_KEYWORD_AND_VALUES_CAPACITY 100 - -/** - * Invariant character separating keywords from the locale string - * @stable ICU 2.8 - */ -#define ULOC_KEYWORD_SEPARATOR '@' - -/** - * Unicode code point for '@' separating keywords from the locale string. - * @see ULOC_KEYWORD_SEPARATOR - * @stable ICU 4.6 - */ -#define ULOC_KEYWORD_SEPARATOR_UNICODE 0x40 - -/** - * Invariant character for assigning value to a keyword - * @stable ICU 2.8 - */ -#define ULOC_KEYWORD_ASSIGN '=' - -/** - * Unicode code point for '=' for assigning value to a keyword. - * @see ULOC_KEYWORD_ASSIGN - * @stable ICU 4.6 - */ -#define ULOC_KEYWORD_ASSIGN_UNICODE 0x3D - -/** - * Invariant character separating keywords - * @stable ICU 2.8 - */ -#define ULOC_KEYWORD_ITEM_SEPARATOR ';' - -/** - * Unicode code point for ';' separating keywords - * @see ULOC_KEYWORD_ITEM_SEPARATOR - * @stable ICU 4.6 - */ -#define ULOC_KEYWORD_ITEM_SEPARATOR_UNICODE 0x3B - -/** - * Constants for *_getLocale() - * Allow user to select whether she wants information on - * requested, valid or actual locale. - * For example, a collator for "en_US_CALIFORNIA" was - * requested. In the current state of ICU (2.0), - * the requested locale is "en_US_CALIFORNIA", - * the valid locale is "en_US" (most specific locale supported by ICU) - * and the actual locale is "root" (the collation data comes unmodified - * from the UCA) - * The locale is considered supported by ICU if there is a core ICU bundle - * for that locale (although it may be empty). - * @stable ICU 2.1 - */ -typedef enum { - /** This is locale the data actually comes from - * @stable ICU 2.1 - */ - ULOC_ACTUAL_LOCALE = 0, - /** This is the most specific locale supported by ICU - * @stable ICU 2.1 - */ - ULOC_VALID_LOCALE = 1, - -#ifndef U_HIDE_DEPRECATED_API - /** This is the requested locale - * @deprecated ICU 2.8 - */ - ULOC_REQUESTED_LOCALE = 2, - - /** - * One more than the highest normal ULocDataLocaleType value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - ULOC_DATA_LOCALE_TYPE_LIMIT = 3 -#endif // U_HIDE_DEPRECATED_API -} ULocDataLocaleType; - -#ifndef U_HIDE_SYSTEM_API -/** - * Gets ICU's default locale. - * The returned string is a snapshot in time, and will remain valid - * and unchanged even when uloc_setDefault() is called. - * The returned storage is owned by ICU, and must not be altered or deleted - * by the caller. - * - * @return the ICU default locale - * @system - * @stable ICU 2.0 - */ -U_STABLE const char* U_EXPORT2 -uloc_getDefault(void); - -/** - * Sets ICU's default locale. - * By default (without calling this function), ICU's default locale will be based - * on information obtained from the underlying system environment. - *

- * Changes to ICU's default locale do not propagate back to the - * system environment. - *

- * Changes to ICU's default locale to not affect any ICU services that - * may already be open based on the previous default locale value. - * - * @param localeID the new ICU default locale. A value of NULL will try to get - * the system's default locale. - * @param status the error information if the setting of default locale fails - * @system - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -uloc_setDefault(const char* localeID, - UErrorCode* status); -#endif /* U_HIDE_SYSTEM_API */ - -/** - * Gets the language code for the specified locale. - * - * @param localeID the locale to get the ISO language code with - * @param language the language code for localeID - * @param languageCapacity the size of the language buffer to store the - * language code with - * @param err error information if retrieving the language code failed - * @return the actual buffer size needed for the language code. If it's greater - * than languageCapacity, the returned language code will be truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getLanguage(const char* localeID, - char* language, - int32_t languageCapacity, - UErrorCode* err); - -/** - * Gets the script code for the specified locale. - * - * @param localeID the locale to get the ISO language code with - * @param script the language code for localeID - * @param scriptCapacity the size of the language buffer to store the - * language code with - * @param err error information if retrieving the language code failed - * @return the actual buffer size needed for the language code. If it's greater - * than scriptCapacity, the returned language code will be truncated. - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getScript(const char* localeID, - char* script, - int32_t scriptCapacity, - UErrorCode* err); - -/** - * Gets the country code for the specified locale. - * - * @param localeID the locale to get the country code with - * @param country the country code for localeID - * @param countryCapacity the size of the country buffer to store the - * country code with - * @param err error information if retrieving the country code failed - * @return the actual buffer size needed for the country code. If it's greater - * than countryCapacity, the returned country code will be truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getCountry(const char* localeID, - char* country, - int32_t countryCapacity, - UErrorCode* err); - -/** - * Gets the variant code for the specified locale. - * - * @param localeID the locale to get the variant code with - * @param variant the variant code for localeID - * @param variantCapacity the size of the variant buffer to store the - * variant code with - * @param err error information if retrieving the variant code failed - * @return the actual buffer size needed for the variant code. If it's greater - * than variantCapacity, the returned variant code will be truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getVariant(const char* localeID, - char* variant, - int32_t variantCapacity, - UErrorCode* err); - - -/** - * Gets the full name for the specified locale. - * Note: This has the effect of 'canonicalizing' the ICU locale ID to - * a certain extent. Upper and lower case are set as needed. - * It does NOT map aliased names in any way. - * See the top of this header file. - * This API supports preflighting. - * - * @param localeID the locale to get the full name with - * @param name fill in buffer for the name without keywords. - * @param nameCapacity capacity of the fill in buffer. - * @param err error information if retrieving the full name failed - * @return the actual buffer size needed for the full name. If it's greater - * than nameCapacity, the returned full name will be truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getName(const char* localeID, - char* name, - int32_t nameCapacity, - UErrorCode* err); - -/** - * Gets the full name for the specified locale. - * Note: This has the effect of 'canonicalizing' the string to - * a certain extent. Upper and lower case are set as needed, - * and if the components were in 'POSIX' format they are changed to - * ICU format. It does NOT map aliased names in any way. - * See the top of this header file. - * - * @param localeID the locale to get the full name with - * @param name the full name for localeID - * @param nameCapacity the size of the name buffer to store the - * full name with - * @param err error information if retrieving the full name failed - * @return the actual buffer size needed for the full name. If it's greater - * than nameCapacity, the returned full name will be truncated. - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -uloc_canonicalize(const char* localeID, - char* name, - int32_t nameCapacity, - UErrorCode* err); - -/** - * Gets the ISO language code for the specified locale. - * - * @param localeID the locale to get the ISO language code with - * @return language the ISO language code for localeID - * @stable ICU 2.0 - */ -U_STABLE const char* U_EXPORT2 -uloc_getISO3Language(const char* localeID); - - -/** - * Gets the ISO country code for the specified locale. - * - * @param localeID the locale to get the ISO country code with - * @return country the ISO country code for localeID - * @stable ICU 2.0 - */ -U_STABLE const char* U_EXPORT2 -uloc_getISO3Country(const char* localeID); - -/** - * Gets the Win32 LCID value for the specified locale. - * If the ICU locale is not recognized by Windows, 0 will be returned. - * - * @param localeID the locale to get the Win32 LCID value with - * @return country the Win32 LCID for localeID - * @stable ICU 2.0 - */ -U_STABLE uint32_t U_EXPORT2 -uloc_getLCID(const char* localeID); - -/** - * Gets the language name suitable for display for the specified locale. - * - * @param locale the locale to get the ISO language code with - * @param displayLocale Specifies the locale to be used to display the name. In other words, - * if the locale's language code is "en", passing Locale::getFrench() for - * inLocale would result in "Anglais", while passing Locale::getGerman() - * for inLocale would result in "Englisch". - * @param language the displayable language code for localeID - * @param languageCapacity the size of the language buffer to store the - * displayable language code with - * @param status error information if retrieving the displayable language code failed - * @return the actual buffer size needed for the displayable language code. If it's greater - * than languageCapacity, the returned language code will be truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getDisplayLanguage(const char* locale, - const char* displayLocale, - UChar* language, - int32_t languageCapacity, - UErrorCode* status); - -/** - * Gets the script name suitable for display for the specified locale. - * - * @param locale the locale to get the displayable script code with. NULL may be used to specify the default. - * @param displayLocale Specifies the locale to be used to display the name. In other words, - * if the locale's language code is "en", passing Locale::getFrench() for - * inLocale would result in "", while passing Locale::getGerman() - * for inLocale would result in "". NULL may be used to specify the default. - * @param script the displayable country code for localeID - * @param scriptCapacity the size of the script buffer to store the - * displayable script code with - * @param status error information if retrieving the displayable script code failed - * @return the actual buffer size needed for the displayable script code. If it's greater - * than scriptCapacity, the returned displayable script code will be truncated. - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getDisplayScript(const char* locale, - const char* displayLocale, - UChar* script, - int32_t scriptCapacity, - UErrorCode* status); - -/** - * Gets the country name suitable for display for the specified locale. - * Warning: this is for the region part of a valid locale ID; it cannot just be the region code (like "FR"). - * To get the display name for a region alone, or for other options, use ULocaleDisplayNames instead. - * - * @param locale the locale to get the displayable country code with. NULL may be used to specify the default. - * @param displayLocale Specifies the locale to be used to display the name. In other words, - * if the locale's language code is "en", passing Locale::getFrench() for - * inLocale would result in "Anglais", while passing Locale::getGerman() - * for inLocale would result in "Englisch". NULL may be used to specify the default. - * @param country the displayable country code for localeID - * @param countryCapacity the size of the country buffer to store the - * displayable country code with - * @param status error information if retrieving the displayable country code failed - * @return the actual buffer size needed for the displayable country code. If it's greater - * than countryCapacity, the returned displayable country code will be truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getDisplayCountry(const char* locale, - const char* displayLocale, - UChar* country, - int32_t countryCapacity, - UErrorCode* status); - - -/** - * Gets the variant name suitable for display for the specified locale. - * - * @param locale the locale to get the displayable variant code with. NULL may be used to specify the default. - * @param displayLocale Specifies the locale to be used to display the name. In other words, - * if the locale's language code is "en", passing Locale::getFrench() for - * inLocale would result in "Anglais", while passing Locale::getGerman() - * for inLocale would result in "Englisch". NULL may be used to specify the default. - * @param variant the displayable variant code for localeID - * @param variantCapacity the size of the variant buffer to store the - * displayable variant code with - * @param status error information if retrieving the displayable variant code failed - * @return the actual buffer size needed for the displayable variant code. If it's greater - * than variantCapacity, the returned displayable variant code will be truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getDisplayVariant(const char* locale, - const char* displayLocale, - UChar* variant, - int32_t variantCapacity, - UErrorCode* status); - -/** - * Gets the keyword name suitable for display for the specified locale. - * E.g: for the locale string de_DE\@collation=PHONEBOOK, this API gets the display - * string for the keyword collation. - * Usage: - * - * UErrorCode status = U_ZERO_ERROR; - * const char* keyword =NULL; - * int32_t keywordLen = 0; - * int32_t keywordCount = 0; - * UChar displayKeyword[256]; - * int32_t displayKeywordLen = 0; - * UEnumeration* keywordEnum = uloc_openKeywords("de_DE@collation=PHONEBOOK;calendar=TRADITIONAL", &status); - * for(keywordCount = uenum_count(keywordEnum, &status); keywordCount > 0 ; keywordCount--){ - * if(U_FAILURE(status)){ - * ...something went wrong so handle the error... - * break; - * } - * // the uenum_next returns NUL terminated string - * keyword = uenum_next(keywordEnum, &keywordLen, &status); - * displayKeywordLen = uloc_getDisplayKeyword(keyword, "en_US", displayKeyword, 256); - * ... do something interesting ..... - * } - * uenum_close(keywordEnum); - * - * @param keyword The keyword whose display string needs to be returned. - * @param displayLocale Specifies the locale to be used to display the name. In other words, - * if the locale's language code is "en", passing Locale::getFrench() for - * inLocale would result in "Anglais", while passing Locale::getGerman() - * for inLocale would result in "Englisch". NULL may be used to specify the default. - * @param dest the buffer to which the displayable keyword should be written. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param status error information if retrieving the displayable string failed. - * Should not be NULL and should not indicate failure on entry. - * @return the actual buffer size needed for the displayable variant code. - * @see #uloc_openKeywords - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getDisplayKeyword(const char* keyword, - const char* displayLocale, - UChar* dest, - int32_t destCapacity, - UErrorCode* status); -/** - * Gets the value of the keyword suitable for display for the specified locale. - * E.g: for the locale string de_DE\@collation=PHONEBOOK, this API gets the display - * string for PHONEBOOK, in the display locale, when "collation" is specified as the keyword. - * - * @param locale The locale to get the displayable variant code with. NULL may be used to specify the default. - * @param keyword The keyword for whose value should be used. - * @param displayLocale Specifies the locale to be used to display the name. In other words, - * if the locale's language code is "en", passing Locale::getFrench() for - * inLocale would result in "Anglais", while passing Locale::getGerman() - * for inLocale would result in "Englisch". NULL may be used to specify the default. - * @param dest the buffer to which the displayable keyword should be written. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param status error information if retrieving the displayable string failed. - * Should not be NULL and must not indicate failure on entry. - * @return the actual buffer size needed for the displayable variant code. - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getDisplayKeywordValue( const char* locale, - const char* keyword, - const char* displayLocale, - UChar* dest, - int32_t destCapacity, - UErrorCode* status); -/** - * Gets the full name suitable for display for the specified locale. - * - * @param localeID the locale to get the displayable name with. NULL may be used to specify the default. - * @param inLocaleID Specifies the locale to be used to display the name. In other words, - * if the locale's language code is "en", passing Locale::getFrench() for - * inLocale would result in "Anglais", while passing Locale::getGerman() - * for inLocale would result in "Englisch". NULL may be used to specify the default. - * @param result the displayable name for localeID - * @param maxResultSize the size of the name buffer to store the - * displayable full name with - * @param err error information if retrieving the displayable name failed - * @return the actual buffer size needed for the displayable name. If it's greater - * than maxResultSize, the returned displayable name will be truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getDisplayName(const char* localeID, - const char* inLocaleID, - UChar* result, - int32_t maxResultSize, - UErrorCode* err); - - -/** - * Gets the specified locale from a list of all available locales. - * The return value is a pointer to an item of - * a locale name array. Both this array and the pointers - * it contains are owned by ICU and should not be deleted or written through - * by the caller. The locale name is terminated by a null pointer. - * @param n the specific locale name index of the available locale list - * @return a specified locale name of all available locales - * @stable ICU 2.0 - */ -U_STABLE const char* U_EXPORT2 -uloc_getAvailable(int32_t n); - -/** - * Gets the size of the all available locale list. - * - * @return the size of the locale list - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 uloc_countAvailable(void); - -/** - * - * Gets a list of all available 2-letter language codes defined in ISO 639, - * plus additional 3-letter codes determined to be useful for locale generation as - * defined by Unicode CLDR. This is a pointer - * to an array of pointers to arrays of char. All of these pointers are owned - * by ICU-- do not delete them, and do not write through them. The array is - * terminated with a null pointer. - * @return a list of all available language codes - * @stable ICU 2.0 - */ -U_STABLE const char* const* U_EXPORT2 -uloc_getISOLanguages(void); - -/** - * - * Gets a list of all available 2-letter country codes defined in ISO 639. This is a - * pointer to an array of pointers to arrays of char. All of these pointers are - * owned by ICU-- do not delete them, and do not write through them. The array is - * terminated with a null pointer. - * @return a list of all available country codes - * @stable ICU 2.0 - */ -U_STABLE const char* const* U_EXPORT2 -uloc_getISOCountries(void); - -/** - * Truncate the locale ID string to get the parent locale ID. - * Copies the part of the string before the last underscore. - * The parent locale ID will be an empty string if there is no - * underscore, or if there is only one underscore at localeID[0]. - * - * @param localeID Input locale ID string. - * @param parent Output string buffer for the parent locale ID. - * @param parentCapacity Size of the output buffer. - * @param err A UErrorCode value. - * @return The length of the parent locale ID. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getParent(const char* localeID, - char* parent, - int32_t parentCapacity, - UErrorCode* err); - - - - -/** - * Gets the full name for the specified locale, like uloc_getName(), - * but without keywords. - * - * Note: This has the effect of 'canonicalizing' the string to - * a certain extent. Upper and lower case are set as needed, - * and if the components were in 'POSIX' format they are changed to - * ICU format. It does NOT map aliased names in any way. - * See the top of this header file. - * - * This API strips off the keyword part, so "de_DE\@collation=phonebook" - * will become "de_DE". - * This API supports preflighting. - * - * @param localeID the locale to get the full name with - * @param name fill in buffer for the name without keywords. - * @param nameCapacity capacity of the fill in buffer. - * @param err error information if retrieving the full name failed - * @return the actual buffer size needed for the full name. If it's greater - * than nameCapacity, the returned full name will be truncated. - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getBaseName(const char* localeID, - char* name, - int32_t nameCapacity, - UErrorCode* err); - -/** - * Gets an enumeration of keywords for the specified locale. Enumeration - * must get disposed of by the client using uenum_close function. - * - * @param localeID the locale to get the variant code with - * @param status error information if retrieving the keywords failed - * @return enumeration of keywords or NULL if there are no keywords. - * @stable ICU 2.8 - */ -U_STABLE UEnumeration* U_EXPORT2 -uloc_openKeywords(const char* localeID, - UErrorCode* status); - -/** - * Get the value for a keyword. Locale name does not need to be normalized. - * - * @param localeID locale name containing the keyword ("de_DE@currency=EURO;collation=PHONEBOOK") - * @param keywordName name of the keyword for which we want the value. Case insensitive. - * @param buffer receiving buffer - * @param bufferCapacity capacity of receiving buffer - * @param status containing error code - buffer not big enough. - * @return the length of keyword value - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getKeywordValue(const char* localeID, - const char* keywordName, - char* buffer, int32_t bufferCapacity, - UErrorCode* status); - - -/** - * Sets or removes the value of the specified keyword. - * - * For removing all keywords, use uloc_getBaseName(). - * - * NOTE: Unlike almost every other ICU function which takes a - * buffer, this function will NOT truncate the output text. If a - * BUFFER_OVERFLOW_ERROR is received, it means that the original - * buffer is untouched. This is done to prevent incorrect or possibly - * even malformed locales from being generated and used. - * - * @param keywordName name of the keyword to be set. Case insensitive. - * @param keywordValue value of the keyword to be set. If 0-length or - * NULL, will result in the keyword being removed. No error is given if - * that keyword does not exist. - * @param buffer input buffer containing locale to be modified. - * @param bufferCapacity capacity of receiving buffer - * @param status containing error code - buffer not big enough. - * @return the length needed for the buffer - * @see uloc_getKeywordValue - * @stable ICU 3.2 - */ -U_STABLE int32_t U_EXPORT2 -uloc_setKeywordValue(const char* keywordName, - const char* keywordValue, - char* buffer, int32_t bufferCapacity, - UErrorCode* status); - -/** - * Returns whether the locale's script is written right-to-left. - * If there is no script subtag, then the likely script is used, see uloc_addLikelySubtags(). - * If no likely script is known, then FALSE is returned. - * - * A script is right-to-left according to the CLDR script metadata - * which corresponds to whether the script's letters have Bidi_Class=R or AL. - * - * Returns TRUE for "ar" and "en-Hebr", FALSE for "zh" and "fa-Cyrl". - * - * @param locale input locale ID - * @return TRUE if the locale's script is written right-to-left - * @stable ICU 54 - */ -U_STABLE UBool U_EXPORT2 -uloc_isRightToLeft(const char *locale); - -/** - * enums for the return value for the character and line orientation - * functions. - * @stable ICU 4.0 - */ -typedef enum { - ULOC_LAYOUT_LTR = 0, /* left-to-right. */ - ULOC_LAYOUT_RTL = 1, /* right-to-left. */ - ULOC_LAYOUT_TTB = 2, /* top-to-bottom. */ - ULOC_LAYOUT_BTT = 3, /* bottom-to-top. */ - ULOC_LAYOUT_UNKNOWN -} ULayoutType; - -/** - * Get the layout character orientation for the specified locale. - * - * @param localeId locale name - * @param status Error status - * @return an enum indicating the layout orientation for characters. - * @stable ICU 4.0 - */ -U_STABLE ULayoutType U_EXPORT2 -uloc_getCharacterOrientation(const char* localeId, - UErrorCode *status); - -/** - * Get the layout line orientation for the specified locale. - * - * @param localeId locale name - * @param status Error status - * @return an enum indicating the layout orientation for lines. - * @stable ICU 4.0 - */ -U_STABLE ULayoutType U_EXPORT2 -uloc_getLineOrientation(const char* localeId, - UErrorCode *status); - -/** - * enums for the 'outResult' parameter return value - * @see uloc_acceptLanguageFromHTTP - * @see uloc_acceptLanguage - * @stable ICU 3.2 - */ -typedef enum { - ULOC_ACCEPT_FAILED = 0, /* No exact match was found. */ - ULOC_ACCEPT_VALID = 1, /* An exact match was found. */ - ULOC_ACCEPT_FALLBACK = 2 /* A fallback was found, for example, - Accept list contained 'ja_JP' - which matched available locale 'ja'. */ -} UAcceptResult; - - -/** - * Based on a HTTP header from a web browser and a list of available locales, - * determine an acceptable locale for the user. - * @param result - buffer to accept the result locale - * @param resultAvailable the size of the result buffer. - * @param outResult - An out parameter that contains the fallback status - * @param httpAcceptLanguage - "Accept-Language:" header as per HTTP. - * @param availableLocales - list of available locales to match - * @param status Error status, may be BUFFER_OVERFLOW_ERROR - * @return length needed for the locale. - * @stable ICU 3.2 - */ -U_STABLE int32_t U_EXPORT2 -uloc_acceptLanguageFromHTTP(char *result, int32_t resultAvailable, - UAcceptResult *outResult, - const char *httpAcceptLanguage, - UEnumeration* availableLocales, - UErrorCode *status); - -/** - * Based on a list of available locales, - * determine an acceptable locale for the user. - * @param result - buffer to accept the result locale - * @param resultAvailable the size of the result buffer. - * @param outResult - An out parameter that contains the fallback status - * @param acceptList - list of acceptable languages - * @param acceptListCount - count of acceptList items - * @param availableLocales - list of available locales to match - * @param status Error status, may be BUFFER_OVERFLOW_ERROR - * @return length needed for the locale. - * @stable ICU 3.2 - */ -U_STABLE int32_t U_EXPORT2 -uloc_acceptLanguage(char *result, int32_t resultAvailable, - UAcceptResult *outResult, const char **acceptList, - int32_t acceptListCount, - UEnumeration* availableLocales, - UErrorCode *status); - - -/** - * Gets the ICU locale ID for the specified Win32 LCID value. - * - * @param hostID the Win32 LCID to translate - * @param locale the output buffer for the ICU locale ID, which will be NUL-terminated - * if there is room. - * @param localeCapacity the size of the output buffer - * @param status an error is returned if the LCID is unrecognized or the output buffer - * is too small - * @return actual the actual size of the locale ID, not including NUL-termination - * @stable ICU 3.8 - */ -U_STABLE int32_t U_EXPORT2 -uloc_getLocaleForLCID(uint32_t hostID, char *locale, int32_t localeCapacity, - UErrorCode *status); - - -/** - * Add the likely subtags for a provided locale ID, per the algorithm described - * in the following CLDR technical report: - * - * http://www.unicode.org/reports/tr35/#Likely_Subtags - * - * If localeID is already in the maximal form, or there is no data available - * for maximization, it will be copied to the output buffer. For example, - * "und-Zzzz" cannot be maximized, since there is no reasonable maximization. - * - * Examples: - * - * "en" maximizes to "en_Latn_US" - * - * "de" maximizes to "de_Latn_US" - * - * "sr" maximizes to "sr_Cyrl_RS" - * - * "sh" maximizes to "sr_Latn_RS" (Note this will not reverse.) - * - * "zh_Hani" maximizes to "zh_Hans_CN" (Note this will not reverse.) - * - * @param localeID The locale to maximize - * @param maximizedLocaleID The maximized locale - * @param maximizedLocaleIDCapacity The capacity of the maximizedLocaleID buffer - * @param err Error information if maximizing the locale failed. If the length - * of the localeID and the null-terminator is greater than the maximum allowed size, - * or the localeId is not well-formed, the error code is U_ILLEGAL_ARGUMENT_ERROR. - * @return The actual buffer size needed for the maximized locale. If it's - * greater than maximizedLocaleIDCapacity, the returned ID will be truncated. - * On error, the return value is -1. - * @stable ICU 4.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_addLikelySubtags(const char* localeID, - char* maximizedLocaleID, - int32_t maximizedLocaleIDCapacity, - UErrorCode* err); - - -/** - * Minimize the subtags for a provided locale ID, per the algorithm described - * in the following CLDR technical report: - * - * http://www.unicode.org/reports/tr35/#Likely_Subtags - * - * If localeID is already in the minimal form, or there is no data available - * for minimization, it will be copied to the output buffer. Since the - * minimization algorithm relies on proper maximization, see the comments - * for uloc_addLikelySubtags for reasons why there might not be any data. - * - * Examples: - * - * "en_Latn_US" minimizes to "en" - * - * "de_Latn_US" minimizes to "de" - * - * "sr_Cyrl_RS" minimizes to "sr" - * - * "zh_Hant_TW" minimizes to "zh_TW" (The region is preferred to the - * script, and minimizing to "zh" would imply "zh_Hans_CN".) - * - * @param localeID The locale to minimize - * @param minimizedLocaleID The minimized locale - * @param minimizedLocaleIDCapacity The capacity of the minimizedLocaleID buffer - * @param err Error information if minimizing the locale failed. If the length - * of the localeID and the null-terminator is greater than the maximum allowed size, - * or the localeId is not well-formed, the error code is U_ILLEGAL_ARGUMENT_ERROR. - * @return The actual buffer size needed for the minimized locale. If it's - * greater than minimizedLocaleIDCapacity, the returned ID will be truncated. - * On error, the return value is -1. - * @stable ICU 4.0 - */ -U_STABLE int32_t U_EXPORT2 -uloc_minimizeSubtags(const char* localeID, - char* minimizedLocaleID, - int32_t minimizedLocaleIDCapacity, - UErrorCode* err); - -/** - * Returns a locale ID for the specified BCP47 language tag string. - * If the specified language tag contains any ill-formed subtags, - * the first such subtag and all following subtags are ignored. - *

- * This implements the 'Language-Tag' production of BCP47, and so - * supports grandfathered (regular and irregular) as well as private - * use language tags. Private use tags are represented as 'x-whatever', - * and grandfathered tags are converted to their canonical replacements - * where they exist. Note that a few grandfathered tags have no modern - * replacement, these will be converted using the fallback described in - * the first paragraph, so some information might be lost. - * @param langtag the input BCP47 language tag. - * @param localeID the output buffer receiving a locale ID for the - * specified BCP47 language tag. - * @param localeIDCapacity the size of the locale ID output buffer. - * @param parsedLength if not NULL, successfully parsed length - * for the input language tag is set. - * @param err error information if receiving the locald ID - * failed. - * @return the length of the locale ID. - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -uloc_forLanguageTag(const char* langtag, - char* localeID, - int32_t localeIDCapacity, - int32_t* parsedLength, - UErrorCode* err); - -/** - * Returns a well-formed language tag for this locale ID. - *

- * Note: When strict is FALSE, any locale - * fields which do not satisfy the BCP47 syntax requirement will - * be omitted from the result. When strict is - * TRUE, this function sets U_ILLEGAL_ARGUMENT_ERROR to the - * err if any locale fields do not satisfy the - * BCP47 syntax requirement. - * @param localeID the input locale ID - * @param langtag the output buffer receiving BCP47 language - * tag for the locale ID. - * @param langtagCapacity the size of the BCP47 language tag - * output buffer. - * @param strict boolean value indicating if the function returns - * an error for an ill-formed input locale ID. - * @param err error information if receiving the language - * tag failed. - * @return The length of the BCP47 language tag. - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -uloc_toLanguageTag(const char* localeID, - char* langtag, - int32_t langtagCapacity, - UBool strict, - UErrorCode* err); - -/** - * Converts the specified keyword (legacy key, or BCP 47 Unicode locale - * extension key) to the equivalent BCP 47 Unicode locale extension key. - * For example, BCP 47 Unicode locale extension key "co" is returned for - * the input keyword "collation". - *

- * When the specified keyword is unknown, but satisfies the BCP syntax, - * then the pointer to the input keyword itself will be returned. - * For example, - * uloc_toUnicodeLocaleKey("ZZ") returns "ZZ". - * - * @param keyword the input locale keyword (either legacy key - * such as "collation" or BCP 47 Unicode locale extension - * key such as "co"). - * @return the well-formed BCP 47 Unicode locale extension key, - * or NULL if the specified locale keyword cannot be - * mapped to a well-formed BCP 47 Unicode locale extension - * key. - * @see uloc_toLegacyKey - * @stable ICU 54 - */ -U_STABLE const char* U_EXPORT2 -uloc_toUnicodeLocaleKey(const char* keyword); - -/** - * Converts the specified keyword value (legacy type, or BCP 47 - * Unicode locale extension type) to the well-formed BCP 47 Unicode locale - * extension type for the specified keyword (category). For example, BCP 47 - * Unicode locale extension type "phonebk" is returned for the input - * keyword value "phonebook", with the keyword "collation" (or "co"). - *

- * When the specified keyword is not recognized, but the specified value - * satisfies the syntax of the BCP 47 Unicode locale extension type, - * or when the specified keyword allows 'variable' type and the specified - * value satisfies the syntax, then the pointer to the input type value itself - * will be returned. - * For example, - * uloc_toUnicodeLocaleType("Foo", "Bar") returns "Bar", - * uloc_toUnicodeLocaleType("variableTop", "00A4") returns "00A4". - * - * @param keyword the locale keyword (either legacy key such as - * "collation" or BCP 47 Unicode locale extension - * key such as "co"). - * @param value the locale keyword value (either legacy type - * such as "phonebook" or BCP 47 Unicode locale extension - * type such as "phonebk"). - * @return the well-formed BCP47 Unicode locale extension type, - * or NULL if the locale keyword value cannot be mapped to - * a well-formed BCP 47 Unicode locale extension type. - * @see uloc_toLegacyType - * @stable ICU 54 - */ -U_STABLE const char* U_EXPORT2 -uloc_toUnicodeLocaleType(const char* keyword, const char* value); - -/** - * Converts the specified keyword (BCP 47 Unicode locale extension key, or - * legacy key) to the legacy key. For example, legacy key "collation" is - * returned for the input BCP 47 Unicode locale extension key "co". - * - * @param keyword the input locale keyword (either BCP 47 Unicode locale - * extension key or legacy key). - * @return the well-formed legacy key, or NULL if the specified - * keyword cannot be mapped to a well-formed legacy key. - * @see toUnicodeLocaleKey - * @stable ICU 54 - */ -U_STABLE const char* U_EXPORT2 -uloc_toLegacyKey(const char* keyword); - -/** - * Converts the specified keyword value (BCP 47 Unicode locale extension type, - * or legacy type or type alias) to the canonical legacy type. For example, - * the legacy type "phonebook" is returned for the input BCP 47 Unicode - * locale extension type "phonebk" with the keyword "collation" (or "co"). - *

- * When the specified keyword is not recognized, but the specified value - * satisfies the syntax of legacy key, or when the specified keyword - * allows 'variable' type and the specified value satisfies the syntax, - * then the pointer to the input type value itself will be returned. - * For example, - * uloc_toLegacyType("Foo", "Bar") returns "Bar", - * uloc_toLegacyType("vt", "00A4") returns "00A4". - * - * @param keyword the locale keyword (either legacy keyword such as - * "collation" or BCP 47 Unicode locale extension - * key such as "co"). - * @param value the locale keyword value (either BCP 47 Unicode locale - * extension type such as "phonebk" or legacy keyword value - * such as "phonebook"). - * @return the well-formed legacy type, or NULL if the specified - * keyword value cannot be mapped to a well-formed legacy - * type. - * @see toUnicodeLocaleType - * @stable ICU 54 - */ -U_STABLE const char* U_EXPORT2 -uloc_toLegacyType(const char* keyword, const char* value); - -#endif /*_ULOC*/ diff --git a/win32/include/spidermonkey/unicode/ulocdata.h b/win32/include/spidermonkey/unicode/ulocdata.h deleted file mode 100755 index ecf6fdcb..00000000 --- a/win32/include/spidermonkey/unicode/ulocdata.h +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* * -* Copyright (C) 2003-2015, International Business Machines * -* Corporation and others. All Rights Reserved. * -* * -****************************************************************************** -* file name: ulocdata.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2003Oct21 -* created by: Ram Viswanadha -*/ - -#ifndef __ULOCDATA_H__ -#define __ULOCDATA_H__ - -#include "unicode/ures.h" -#include "unicode/uloc.h" -#include "unicode/uset.h" -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: Provides access to locale data. - */ - -/** Forward declaration of the ULocaleData structure. @stable ICU 3.6 */ -struct ULocaleData; - -/** A locale data object. @stable ICU 3.6 */ -typedef struct ULocaleData ULocaleData; - - - -/** The possible types of exemplar character sets. - * @stable ICU 3.4 - */ -typedef enum ULocaleDataExemplarSetType { - /** Basic set @stable ICU 3.4 */ - ULOCDATA_ES_STANDARD=0, - /** Auxiliary set @stable ICU 3.4 */ - ULOCDATA_ES_AUXILIARY=1, - /** Index Character set @stable ICU 4.8 */ - ULOCDATA_ES_INDEX=2, - /** Punctuation set @stable ICU 51 */ - ULOCDATA_ES_PUNCTUATION=3, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal ULocaleDataExemplarSetType value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - ULOCDATA_ES_COUNT=4 -#endif // U_HIDE_DEPRECATED_API -} ULocaleDataExemplarSetType; - -/** The possible types of delimiters. - * @stable ICU 3.4 - */ -typedef enum ULocaleDataDelimiterType { - /** Quotation start @stable ICU 3.4 */ - ULOCDATA_QUOTATION_START = 0, - /** Quotation end @stable ICU 3.4 */ - ULOCDATA_QUOTATION_END = 1, - /** Alternate quotation start @stable ICU 3.4 */ - ULOCDATA_ALT_QUOTATION_START = 2, - /** Alternate quotation end @stable ICU 3.4 */ - ULOCDATA_ALT_QUOTATION_END = 3, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal ULocaleDataDelimiterType value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - ULOCDATA_DELIMITER_COUNT = 4 -#endif // U_HIDE_DEPRECATED_API -} ULocaleDataDelimiterType; - -/** - * Opens a locale data object for the given locale - * - * @param localeID Specifies the locale associated with this locale - * data object. - * @param status Pointer to error status code. - * @stable ICU 3.4 - */ -U_STABLE ULocaleData* U_EXPORT2 -ulocdata_open(const char *localeID, UErrorCode *status); - -/** - * Closes a locale data object. - * - * @param uld The locale data object to close - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -ulocdata_close(ULocaleData *uld); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalULocaleDataPointer - * "Smart pointer" class, closes a ULocaleData via ulocdata_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalULocaleDataPointer, ULocaleData, ulocdata_close); - -U_NAMESPACE_END - -#endif - -/** - * Sets the "no Substitute" attribute of the locale data - * object. If true, then any methods associated with the - * locale data object will return null when there is no - * data available for that method, given the locale ID - * supplied to ulocdata_open(). - * - * @param uld The locale data object to set. - * @param setting Value of the "no substitute" attribute. - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -ulocdata_setNoSubstitute(ULocaleData *uld, UBool setting); - -/** - * Retrieves the current "no Substitute" value of the locale data - * object. If true, then any methods associated with the - * locale data object will return null when there is no - * data available for that method, given the locale ID - * supplied to ulocdata_open(). - * - * @param uld Pointer to the The locale data object to set. - * @return UBool Value of the "no substitute" attribute. - * @stable ICU 3.4 - */ -U_STABLE UBool U_EXPORT2 -ulocdata_getNoSubstitute(ULocaleData *uld); - -/** - * Returns the set of exemplar characters for a locale. - * - * @param uld Pointer to the locale data object from which the - * exemplar character set is to be retrieved. - * @param fillIn Pointer to a USet object to receive the - * exemplar character set for the given locale. Previous - * contents of fillIn are lost. If fillIn is NULL, - * then a new USet is created and returned. The caller - * owns the result and must dispose of it by calling - * uset_close. - * @param options Bitmask for options to apply to the exemplar pattern. - * Specify zero to retrieve the exemplar set as it is - * defined in the locale data. Specify - * USET_CASE_INSENSITIVE to retrieve a case-folded - * exemplar set. See uset_applyPattern for a complete - * list of valid options. The USET_IGNORE_SPACE bit is - * always set, regardless of the value of 'options'. - * @param extype Specifies the type of exemplar set to be retrieved. - * @param status Pointer to an input-output error code value; - * must not be NULL. Will be set to U_MISSING_RESOURCE_ERROR - * if the requested data is not available. - * @return USet* Either fillIn, or if fillIn is NULL, a pointer to - * a newly-allocated USet that the user must close. - * In case of error, NULL is returned. - * @stable ICU 3.4 - */ -U_STABLE USet* U_EXPORT2 -ulocdata_getExemplarSet(ULocaleData *uld, USet *fillIn, - uint32_t options, ULocaleDataExemplarSetType extype, UErrorCode *status); - -/** - * Returns one of the delimiter strings associated with a locale. - * - * @param uld Pointer to the locale data object from which the - * delimiter string is to be retrieved. - * @param type the type of delimiter to be retrieved. - * @param result A pointer to a buffer to receive the result. - * @param resultLength The maximum size of result. - * @param status Pointer to an error code value - * @return int32_t The total buffer size needed; if greater than resultLength, - * the output was truncated. - * @stable ICU 3.4 - */ -U_STABLE int32_t U_EXPORT2 -ulocdata_getDelimiter(ULocaleData *uld, ULocaleDataDelimiterType type, UChar *result, int32_t resultLength, UErrorCode *status); - -/** - * Enumeration for representing the measurement systems. - * @stable ICU 2.8 - */ -typedef enum UMeasurementSystem { - UMS_SI, /**< Measurement system specified by SI otherwise known as Metric system. @stable ICU 2.8 */ - UMS_US, /**< Measurement system followed in the United States of America. @stable ICU 2.8 */ - UMS_UK, /**< Mix of metric and imperial units used in Great Britain. @stable ICU 55 */ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UMeasurementSystem value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UMS_LIMIT -#endif // U_HIDE_DEPRECATED_API -} UMeasurementSystem; - -/** - * Returns the measurement system used in the locale specified by the localeID. - * Please note that this API will change in ICU 3.6 and will use an ulocdata object. - * - * @param localeID The id of the locale for which the measurement system to be retrieved. - * @param status Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return UMeasurementSystem the measurement system used in the locale. - * @stable ICU 2.8 - */ -U_STABLE UMeasurementSystem U_EXPORT2 -ulocdata_getMeasurementSystem(const char *localeID, UErrorCode *status); - -/** - * Returns the element gives the normal business letter size, and customary units. - * The units for the numbers are always in milli-meters. - * For US since 8.5 and 11 do not yeild an integral value when converted to milli-meters, - * the values are rounded off. - * So for A4 size paper the height and width are 297 mm and 210 mm repectively, - * and for US letter size the height and width are 279 mm and 216 mm respectively. - * Please note that this API will change in ICU 3.6 and will use an ulocdata object. - * - * @param localeID The id of the locale for which the paper size information to be retrieved. - * @param height A pointer to int to recieve the height information. - * @param width A pointer to int to recieve the width information. - * @param status Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @stable ICU 2.8 - */ -U_STABLE void U_EXPORT2 -ulocdata_getPaperSize(const char *localeID, int32_t *height, int32_t *width, UErrorCode *status); - -/** - * Return the current CLDR version used by the library. - * @param versionArray fillin that will recieve the version number - * @param status error code - could be U_MISSING_RESOURCE_ERROR if the version was not found. - * @stable ICU 4.2 - */ -U_STABLE void U_EXPORT2 -ulocdata_getCLDRVersion(UVersionInfo versionArray, UErrorCode *status); - -/** - * Returns locale display pattern associated with a locale. - * - * @param uld Pointer to the locale data object from which the - * exemplar character set is to be retrieved. - * @param pattern locale display pattern for locale. - * @param patternCapacity the size of the buffer to store the locale display - * pattern with. - * @param status Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return the actual buffer size needed for localeDisplayPattern. If it's greater - * than patternCapacity, the returned pattern will be truncated. - * - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -ulocdata_getLocaleDisplayPattern(ULocaleData *uld, - UChar *pattern, - int32_t patternCapacity, - UErrorCode *status); - - -/** - * Returns locale separator associated with a locale. - * - * @param uld Pointer to the locale data object from which the - * exemplar character set is to be retrieved. - * @param separator locale separator for locale. - * @param separatorCapacity the size of the buffer to store the locale - * separator with. - * @param status Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return the actual buffer size needed for localeSeparator. If it's greater - * than separatorCapacity, the returned separator will be truncated. - * - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -ulocdata_getLocaleSeparator(ULocaleData *uld, - UChar *separator, - int32_t separatorCapacity, - UErrorCode *status); -#endif diff --git a/win32/include/spidermonkey/unicode/umachine.h b/win32/include/spidermonkey/unicode/umachine.h deleted file mode 100755 index 51581c7d..00000000 --- a/win32/include/spidermonkey/unicode/umachine.h +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 1999-2015, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* file name: umachine.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 1999sep13 -* created by: Markus W. Scherer -* -* This file defines basic types and constants for ICU to be -* platform-independent. umachine.h and utf.h are included into -* utypes.h to provide all the general definitions for ICU. -* All of these definitions used to be in utypes.h before -* the UTF-handling macros made this unmaintainable. -*/ - -#ifndef __UMACHINE_H__ -#define __UMACHINE_H__ - - -/** - * \file - * \brief Basic types and constants for UTF - * - *

Basic types and constants for UTF

- * This file defines basic types and constants for utf.h to be - * platform-independent. umachine.h and utf.h are included into - * utypes.h to provide all the general definitions for ICU. - * All of these definitions used to be in utypes.h before - * the UTF-handling macros made this unmaintainable. - * - */ -/*==========================================================================*/ -/* Include platform-dependent definitions */ -/* which are contained in the platform-specific file platform.h */ -/*==========================================================================*/ - -#include "unicode/ptypes.h" /* platform.h is included in ptypes.h */ - -/* - * ANSI C headers: - * stddef.h defines wchar_t - */ -#include - -#ifndef U_HIDE_INTERNAL_API -/* - * U_USE_CHAR16_T - * When defined, force use of char16_t for UChar. - * Note: char16_t is expected to become the default and required in the future, - * and this option will be removed. - * @internal - */ -#ifdef U_USE_CHAR16_T -#ifdef UCHAR_TYPE -#undef UCHAR_TYPE -#endif -#define UCHAR_TYPE char16_t - -/* - * In plain C, is needed for the definition of char16_t - */ -#ifndef __cplusplus -#include -#endif -#endif -#endif /* U_HIDE_INTERNAL_API */ - -/*==========================================================================*/ -/* For C wrappers, we use the symbol U_STABLE. */ -/* This works properly if the includer is C or C++. */ -/* Functions are declared U_STABLE return-type U_EXPORT2 function-name()... */ -/*==========================================================================*/ - -/** - * \def U_CFUNC - * This is used in a declaration of a library private ICU C function. - * @stable ICU 2.4 - */ - -/** - * \def U_CDECL_BEGIN - * This is used to begin a declaration of a library private ICU C API. - * @stable ICU 2.4 - */ - -/** - * \def U_CDECL_END - * This is used to end a declaration of a library private ICU C API - * @stable ICU 2.4 - */ - -#ifdef __cplusplus -# define U_CFUNC extern "C" -# define U_CDECL_BEGIN extern "C" { -# define U_CDECL_END } -#else -# define U_CFUNC extern -# define U_CDECL_BEGIN -# define U_CDECL_END -#endif - -#ifndef U_ATTRIBUTE_DEPRECATED -/** - * \def U_ATTRIBUTE_DEPRECATED - * This is used for GCC specific attributes - * @internal - */ -#if U_GCC_MAJOR_MINOR >= 302 -# define U_ATTRIBUTE_DEPRECATED __attribute__ ((deprecated)) -/** - * \def U_ATTRIBUTE_DEPRECATED - * This is used for Visual C++ specific attributes - * @internal - */ -#elif defined(_MSC_VER) && (_MSC_VER >= 1400) -# define U_ATTRIBUTE_DEPRECATED __declspec(deprecated) -#else -# define U_ATTRIBUTE_DEPRECATED -#endif -#endif - -/** This is used to declare a function as a public ICU C API @stable ICU 2.0*/ -#define U_CAPI U_CFUNC U_EXPORT -/** This is used to declare a function as a stable public ICU C API*/ -#define U_STABLE U_CAPI -/** This is used to declare a function as a draft public ICU C API */ -#define U_DRAFT U_CAPI -/** This is used to declare a function as a deprecated public ICU C API */ -#define U_DEPRECATED U_CAPI U_ATTRIBUTE_DEPRECATED -/** This is used to declare a function as an obsolete public ICU C API */ -#define U_OBSOLETE U_CAPI -/** This is used to declare a function as an internal ICU C API */ -#define U_INTERNAL U_CAPI - -/** - * \def U_OVERRIDE - * Defined to the C++11 "override" keyword if available. - * Denotes a class or member which is an override of the base class. - * May result in an error if it applied to something not an override. - * @internal - */ - -/** - * \def U_FINAL - * Defined to the C++11 "final" keyword if available. - * Denotes a class or member which may not be overridden in subclasses. - * May result in an error if subclasses attempt to override. - * @internal - */ - -#if U_CPLUSPLUS_VERSION >= 11 -/* C++11 */ -#ifndef U_OVERRIDE -#define U_OVERRIDE override -#endif -#ifndef U_FINAL -#define U_FINAL final -#endif -#else -/* not C++11 - define to nothing */ -#ifndef U_OVERRIDE -#define U_OVERRIDE -#endif -#ifndef U_FINAL -#define U_FINAL -#endif -#endif - -/*==========================================================================*/ -/* limits for int32_t etc., like in POSIX inttypes.h */ -/*==========================================================================*/ - -#ifndef INT8_MIN -/** The smallest value an 8 bit signed integer can hold @stable ICU 2.0 */ -# define INT8_MIN ((int8_t)(-128)) -#endif -#ifndef INT16_MIN -/** The smallest value a 16 bit signed integer can hold @stable ICU 2.0 */ -# define INT16_MIN ((int16_t)(-32767-1)) -#endif -#ifndef INT32_MIN -/** The smallest value a 32 bit signed integer can hold @stable ICU 2.0 */ -# define INT32_MIN ((int32_t)(-2147483647-1)) -#endif - -#ifndef INT8_MAX -/** The largest value an 8 bit signed integer can hold @stable ICU 2.0 */ -# define INT8_MAX ((int8_t)(127)) -#endif -#ifndef INT16_MAX -/** The largest value a 16 bit signed integer can hold @stable ICU 2.0 */ -# define INT16_MAX ((int16_t)(32767)) -#endif -#ifndef INT32_MAX -/** The largest value a 32 bit signed integer can hold @stable ICU 2.0 */ -# define INT32_MAX ((int32_t)(2147483647)) -#endif - -#ifndef UINT8_MAX -/** The largest value an 8 bit unsigned integer can hold @stable ICU 2.0 */ -# define UINT8_MAX ((uint8_t)(255U)) -#endif -#ifndef UINT16_MAX -/** The largest value a 16 bit unsigned integer can hold @stable ICU 2.0 */ -# define UINT16_MAX ((uint16_t)(65535U)) -#endif -#ifndef UINT32_MAX -/** The largest value a 32 bit unsigned integer can hold @stable ICU 2.0 */ -# define UINT32_MAX ((uint32_t)(4294967295U)) -#endif - -#if defined(U_INT64_T_UNAVAILABLE) -# error int64_t is required for decimal format and rule-based number format. -#else -# ifndef INT64_C -/** - * Provides a platform independent way to specify a signed 64-bit integer constant. - * note: may be wrong for some 64 bit platforms - ensure your compiler provides INT64_C - * @stable ICU 2.8 - */ -# define INT64_C(c) c ## LL -# endif -# ifndef UINT64_C -/** - * Provides a platform independent way to specify an unsigned 64-bit integer constant. - * note: may be wrong for some 64 bit platforms - ensure your compiler provides UINT64_C - * @stable ICU 2.8 - */ -# define UINT64_C(c) c ## ULL -# endif -# ifndef U_INT64_MIN -/** The smallest value a 64 bit signed integer can hold @stable ICU 2.8 */ -# define U_INT64_MIN ((int64_t)(INT64_C(-9223372036854775807)-1)) -# endif -# ifndef U_INT64_MAX -/** The largest value a 64 bit signed integer can hold @stable ICU 2.8 */ -# define U_INT64_MAX ((int64_t)(INT64_C(9223372036854775807))) -# endif -# ifndef U_UINT64_MAX -/** The largest value a 64 bit unsigned integer can hold @stable ICU 2.8 */ -# define U_UINT64_MAX ((uint64_t)(UINT64_C(18446744073709551615))) -# endif -#endif - -/*==========================================================================*/ -/* Boolean data type */ -/*==========================================================================*/ - -/** The ICU boolean type @stable ICU 2.0 */ -typedef int8_t UBool; - -#ifndef TRUE -/** The TRUE value of a UBool @stable ICU 2.0 */ -# define TRUE 1 -#endif -#ifndef FALSE -/** The FALSE value of a UBool @stable ICU 2.0 */ -# define FALSE 0 -#endif - - -/*==========================================================================*/ -/* Unicode data types */ -/*==========================================================================*/ - -/* wchar_t-related definitions -------------------------------------------- */ - -/* - * \def U_WCHAR_IS_UTF16 - * Defined if wchar_t uses UTF-16. - * - * @stable ICU 2.0 - */ -/* - * \def U_WCHAR_IS_UTF32 - * Defined if wchar_t uses UTF-32. - * - * @stable ICU 2.0 - */ -#if !defined(U_WCHAR_IS_UTF16) && !defined(U_WCHAR_IS_UTF32) -# ifdef __STDC_ISO_10646__ -# if (U_SIZEOF_WCHAR_T==2) -# define U_WCHAR_IS_UTF16 -# elif (U_SIZEOF_WCHAR_T==4) -# define U_WCHAR_IS_UTF32 -# endif -# elif defined __UCS2__ -# if (U_PF_OS390 <= U_PLATFORM && U_PLATFORM <= U_PF_OS400) && (U_SIZEOF_WCHAR_T==2) -# define U_WCHAR_IS_UTF16 -# endif -# elif defined(__UCS4__) || (U_PLATFORM == U_PF_OS400 && defined(__UTF32__)) -# if (U_SIZEOF_WCHAR_T==4) -# define U_WCHAR_IS_UTF32 -# endif -# elif U_PLATFORM_IS_DARWIN_BASED || (U_SIZEOF_WCHAR_T==4 && U_PLATFORM_IS_LINUX_BASED) -# define U_WCHAR_IS_UTF32 -# elif U_PLATFORM_HAS_WIN32_API -# define U_WCHAR_IS_UTF16 -# endif -#endif - -/* UChar and UChar32 definitions -------------------------------------------- */ - -/** Number of bytes in a UChar. @stable ICU 2.0 */ -#define U_SIZEOF_UCHAR 2 - -/** - * \var UChar - * Define UChar to be UCHAR_TYPE, if that is #defined (for example, to char16_t), - * or wchar_t if that is 16 bits wide; always assumed to be unsigned. - * If neither is available, then define UChar to be uint16_t. - * - * This makes the definition of UChar platform-dependent - * but allows direct string type compatibility with platforms with - * 16-bit wchar_t types. - * - * @stable ICU 4.4 - */ -#if defined(UCHAR_TYPE) - typedef UCHAR_TYPE UChar; -/* Not #elif U_HAVE_CHAR16_T -- because that is type-incompatible with pre-C++11 callers - typedef char16_t UChar; */ -#elif U_SIZEOF_WCHAR_T==2 - typedef wchar_t UChar; -#elif defined(__CHAR16_TYPE__) - typedef __CHAR16_TYPE__ UChar; -#else - typedef uint16_t UChar; -#endif - -/** - * Define UChar32 as a type for single Unicode code points. - * UChar32 is a signed 32-bit integer (same as int32_t). - * - * The Unicode code point range is 0..0x10ffff. - * All other values (negative or >=0x110000) are illegal as Unicode code points. - * They may be used as sentinel values to indicate "done", "error" - * or similar non-code point conditions. - * - * Before ICU 2.4 (Jitterbug 2146), UChar32 was defined - * to be wchar_t if that is 32 bits wide (wchar_t may be signed or unsigned) - * or else to be uint32_t. - * That is, the definition of UChar32 was platform-dependent. - * - * @see U_SENTINEL - * @stable ICU 2.4 - */ -typedef int32_t UChar32; - -/** - * This value is intended for sentinel values for APIs that - * (take or) return single code points (UChar32). - * It is outside of the Unicode code point range 0..0x10ffff. - * - * For example, a "done" or "error" value in a new API - * could be indicated with U_SENTINEL. - * - * ICU APIs designed before ICU 2.4 usually define service-specific "done" - * values, mostly 0xffff. - * Those may need to be distinguished from - * actual U+ffff text contents by calling functions like - * CharacterIterator::hasNext() or UnicodeString::length(). - * - * @return -1 - * @see UChar32 - * @stable ICU 2.4 - */ -#define U_SENTINEL (-1) - -#include "unicode/urename.h" - -#endif diff --git a/win32/include/spidermonkey/unicode/umisc.h b/win32/include/spidermonkey/unicode/umisc.h deleted file mode 100755 index 7b6d35f5..00000000 --- a/win32/include/spidermonkey/unicode/umisc.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1999-2006, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* file name: umisc.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 1999oct15 -* created by: Markus W. Scherer -*/ - -#ifndef UMISC_H -#define UMISC_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C API:misc definitions - * - * This file contains miscellaneous definitions for the C APIs. - */ - -U_CDECL_BEGIN - -/** A struct representing a range of text containing a specific field - * @stable ICU 2.0 - */ -typedef struct UFieldPosition { - /** - * The field - * @stable ICU 2.0 - */ - int32_t field; - /** - * The start of the text range containing field - * @stable ICU 2.0 - */ - int32_t beginIndex; - /** - * The limit of the text range containing field - * @stable ICU 2.0 - */ - int32_t endIndex; -} UFieldPosition; - -#if !UCONFIG_NO_SERVICE -/** - * Opaque type returned by registerInstance, registerFactory and unregister for service registration. - * @stable ICU 2.6 - */ -typedef const void* URegistryKey; -#endif - -U_CDECL_END - -#endif diff --git a/win32/include/spidermonkey/unicode/umsg.h b/win32/include/spidermonkey/unicode/umsg.h deleted file mode 100755 index b5f2ae9d..00000000 --- a/win32/include/spidermonkey/unicode/umsg.h +++ /dev/null @@ -1,625 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/******************************************************************** - * COPYRIGHT: - * Copyright (c) 1997-2011, International Business Machines Corporation and - * others. All Rights Reserved. - * Copyright (C) 2010 , Yahoo! Inc. - ******************************************************************** - * - * file name: umsg.h - * encoding: US-ASCII - * tab size: 8 (not used) - * indentation:4 - * - * Change history: - * - * 08/5/2001 Ram Added C wrappers for C++ API. - ********************************************************************/ - -#ifndef UMSG_H -#define UMSG_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/localpointer.h" -#include "unicode/uloc.h" -#include "unicode/parseerr.h" -#include - -/** - * \file - * \brief C API: MessageFormat - * - *

MessageFormat C API

- * - *

MessageFormat prepares strings for display to users, - * with optional arguments (variables/placeholders). - * The arguments can occur in any order, which is necessary for translation - * into languages with different grammars. - * - *

The opaque UMessageFormat type is a thin C wrapper around - * a C++ MessageFormat. It is constructed from a pattern string - * with arguments in {curly braces} which will be replaced by formatted values. - * - *

Currently, the C API supports only numbered arguments. - * - *

For details about the pattern syntax and behavior, - * especially about the ASCII apostrophe vs. the - * real apostrophe (single quote) character \htmlonly’\endhtmlonly (U+2019), - * see the C++ MessageFormat class documentation. - * - *

Here are some examples of C API usage: - * Example 1: - *

- * \code
- *     UChar *result, *tzID, *str;
- *     UChar pattern[100];
- *     int32_t resultLengthOut, resultlength;
- *     UCalendar *cal;
- *     UDate d1;
- *     UDateFormat *def1;
- *     UErrorCode status = U_ZERO_ERROR;
- *
- *     str=(UChar*)malloc(sizeof(UChar) * (strlen("disturbance in force") +1));
- *     u_uastrcpy(str, "disturbance in force");
- *     tzID=(UChar*)malloc(sizeof(UChar) * 4);
- *     u_uastrcpy(tzID, "PST");
- *     cal=ucal_open(tzID, u_strlen(tzID), "en_US", UCAL_TRADITIONAL, &status);
- *     ucal_setDateTime(cal, 1999, UCAL_MARCH, 18, 0, 0, 0, &status);
- *     d1=ucal_getMillis(cal, &status);
- *     u_uastrcpy(pattern, "On {0, date, long}, there was a {1} on planet {2,number,integer}");
- *     resultlength=0;
- *     resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), NULL, resultlength, &status, d1, str, 7);
- *     if(status==U_BUFFER_OVERFLOW_ERROR){
- *         status=U_ZERO_ERROR;
- *         resultlength=resultLengthOut+1;
- *         result=(UChar*)realloc(result, sizeof(UChar) * resultlength);
- *         u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, d1, str, 7);
- *     }
- *     printf("%s\n", austrdup(result) );//austrdup( a function used to convert UChar* to char*)
- *     //output>: "On March 18, 1999, there was a disturbance in force on planet 7
- * \endcode
- * 
- * Typically, the message format will come from resources, and the - * arguments will be dynamically set at runtime. - *

- * Example 2: - *

- * \code
- *     UChar* str;
- *     UErrorCode status = U_ZERO_ERROR;
- *     UChar *result;
- *     UChar pattern[100];
- *     int32_t resultlength, resultLengthOut, i;
- *     double testArgs= { 100.0, 1.0, 0.0};
- *
- *     str=(UChar*)malloc(sizeof(UChar) * 10);
- *     u_uastrcpy(str, "MyDisk");
- *     u_uastrcpy(pattern, "The disk {1} contains {0,choice,0#no files|1#one file|1<{0,number,integer} files}");
- *     for(i=0; i<3; i++){
- *       resultlength=0; 
- *       resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), NULL, resultlength, &status, testArgs[i], str); 
- *       if(status==U_BUFFER_OVERFLOW_ERROR){
- *         status=U_ZERO_ERROR;
- *         resultlength=resultLengthOut+1;
- *         result=(UChar*)malloc(sizeof(UChar) * resultlength);
- *         u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, testArgs[i], str);
- *       }
- *       printf("%s\n", austrdup(result) );  //austrdup( a function used to convert UChar* to char*)
- *       free(result);
- *     }
- *     // output, with different testArgs:
- *     // output: The disk "MyDisk" contains 100 files.
- *     // output: The disk "MyDisk" contains one file.
- *     // output: The disk "MyDisk" contains no files.
- * \endcode
- *  
- * - * - * Example 3: - *
- * \code
- * UChar* str;
- * UChar* str1;
- * UErrorCode status = U_ZERO_ERROR;
- * UChar *result;
- * UChar pattern[100];
- * UChar expected[100];
- * int32_t resultlength,resultLengthOut;
-
- * str=(UChar*)malloc(sizeof(UChar) * 25);
- * u_uastrcpy(str, "Kirti");
- * str1=(UChar*)malloc(sizeof(UChar) * 25);
- * u_uastrcpy(str1, "female");
- * log_verbose("Testing message format with Select test #1\n:");
- * u_uastrcpy(pattern, "{0} est {1, select, female {all\\u00E9e} other {all\\u00E9}} \\u00E0 Paris.");
- * u_uastrcpy(expected, "Kirti est all\\u00E9e \\u00E0 Paris.");
- * resultlength=0;
- * resultLengthOut=u_formatMessage( "fr", pattern, u_strlen(pattern), NULL, resultlength, &status, str , str1);
- * if(status==U_BUFFER_OVERFLOW_ERROR)
- *  {
- *      status=U_ZERO_ERROR;
- *      resultlength=resultLengthOut+1;
- *      result=(UChar*)malloc(sizeof(UChar) * resultlength);
- *      u_formatMessage( "fr", pattern, u_strlen(pattern), result, resultlength, &status, str , str1);
- *      if(u_strcmp(result, expected)==0)
- *          log_verbose("PASS: MessagFormat successful on Select test#1\n");
- *      else{
- *          log_err("FAIL: Error in MessageFormat on Select test#1\n GOT %s EXPECTED %s\n", austrdup(result),
- *          austrdup(expected) );
- *      }
- *      free(result);
- * }
- * \endcode
- *  
- */ - -/** - * Format a message for a locale. - * This function may perform re-ordering of the arguments depending on the - * locale. For all numeric arguments, double is assumed unless the type is - * explicitly integer. All choice format arguments must be of type double. - * @param locale The locale for which the message will be formatted - * @param pattern The pattern specifying the message's format - * @param patternLength The length of pattern - * @param result A pointer to a buffer to receive the formatted message. - * @param resultLength The maximum size of result. - * @param status A pointer to an UErrorCode to receive any errors - * @param ... A variable-length argument list containing the arguments specified - * in pattern. - * @return The total buffer size needed; if greater than resultLength, the - * output was truncated. - * @see u_parseMessage - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_formatMessage(const char *locale, - const UChar *pattern, - int32_t patternLength, - UChar *result, - int32_t resultLength, - UErrorCode *status, - ...); - -/** - * Format a message for a locale. - * This function may perform re-ordering of the arguments depending on the - * locale. For all numeric arguments, double is assumed unless the type is - * explicitly integer. All choice format arguments must be of type double. - * @param locale The locale for which the message will be formatted - * @param pattern The pattern specifying the message's format - * @param patternLength The length of pattern - * @param result A pointer to a buffer to receive the formatted message. - * @param resultLength The maximum size of result. - * @param ap A variable-length argument list containing the arguments specified - * @param status A pointer to an UErrorCode to receive any errors - * in pattern. - * @return The total buffer size needed; if greater than resultLength, the - * output was truncated. - * @see u_parseMessage - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_vformatMessage( const char *locale, - const UChar *pattern, - int32_t patternLength, - UChar *result, - int32_t resultLength, - va_list ap, - UErrorCode *status); - -/** - * Parse a message. - * For numeric arguments, this function will always use doubles. Integer types - * should not be passed. - * This function is not able to parse all output from {@link #u_formatMessage }. - * @param locale The locale for which the message is formatted - * @param pattern The pattern specifying the message's format - * @param patternLength The length of pattern - * @param source The text to parse. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param status A pointer to an UErrorCode to receive any errors - * @param ... A variable-length argument list containing the arguments - * specified in pattern. - * @see u_formatMessage - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -u_parseMessage( const char *locale, - const UChar *pattern, - int32_t patternLength, - const UChar *source, - int32_t sourceLength, - UErrorCode *status, - ...); - -/** - * Parse a message. - * For numeric arguments, this function will always use doubles. Integer types - * should not be passed. - * This function is not able to parse all output from {@link #u_formatMessage }. - * @param locale The locale for which the message is formatted - * @param pattern The pattern specifying the message's format - * @param patternLength The length of pattern - * @param source The text to parse. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param ap A variable-length argument list containing the arguments - * @param status A pointer to an UErrorCode to receive any errors - * specified in pattern. - * @see u_formatMessage - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -u_vparseMessage(const char *locale, - const UChar *pattern, - int32_t patternLength, - const UChar *source, - int32_t sourceLength, - va_list ap, - UErrorCode *status); - -/** - * Format a message for a locale. - * This function may perform re-ordering of the arguments depending on the - * locale. For all numeric arguments, double is assumed unless the type is - * explicitly integer. All choice format arguments must be of type double. - * @param locale The locale for which the message will be formatted - * @param pattern The pattern specifying the message's format - * @param patternLength The length of pattern - * @param result A pointer to a buffer to receive the formatted message. - * @param resultLength The maximum size of result. - * @param status A pointer to an UErrorCode to receive any errors - * @param ... A variable-length argument list containing the arguments specified - * in pattern. - * @param parseError A pointer to UParseError to receive information about errors - * occurred during parsing. - * @return The total buffer size needed; if greater than resultLength, the - * output was truncated. - * @see u_parseMessage - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_formatMessageWithError( const char *locale, - const UChar *pattern, - int32_t patternLength, - UChar *result, - int32_t resultLength, - UParseError *parseError, - UErrorCode *status, - ...); - -/** - * Format a message for a locale. - * This function may perform re-ordering of the arguments depending on the - * locale. For all numeric arguments, double is assumed unless the type is - * explicitly integer. All choice format arguments must be of type double. - * @param locale The locale for which the message will be formatted - * @param pattern The pattern specifying the message's format - * @param patternLength The length of pattern - * @param result A pointer to a buffer to receive the formatted message. - * @param resultLength The maximum size of result. - * @param parseError A pointer to UParseError to receive information about errors - * occurred during parsing. - * @param ap A variable-length argument list containing the arguments specified - * @param status A pointer to an UErrorCode to receive any errors - * in pattern. - * @return The total buffer size needed; if greater than resultLength, the - * output was truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_vformatMessageWithError( const char *locale, - const UChar *pattern, - int32_t patternLength, - UChar *result, - int32_t resultLength, - UParseError* parseError, - va_list ap, - UErrorCode *status); - -/** - * Parse a message. - * For numeric arguments, this function will always use doubles. Integer types - * should not be passed. - * This function is not able to parse all output from {@link #u_formatMessage }. - * @param locale The locale for which the message is formatted - * @param pattern The pattern specifying the message's format - * @param patternLength The length of pattern - * @param source The text to parse. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param parseError A pointer to UParseError to receive information about errors - * occurred during parsing. - * @param status A pointer to an UErrorCode to receive any errors - * @param ... A variable-length argument list containing the arguments - * specified in pattern. - * @see u_formatMessage - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -u_parseMessageWithError(const char *locale, - const UChar *pattern, - int32_t patternLength, - const UChar *source, - int32_t sourceLength, - UParseError *parseError, - UErrorCode *status, - ...); - -/** - * Parse a message. - * For numeric arguments, this function will always use doubles. Integer types - * should not be passed. - * This function is not able to parse all output from {@link #u_formatMessage }. - * @param locale The locale for which the message is formatted - * @param pattern The pattern specifying the message's format - * @param patternLength The length of pattern - * @param source The text to parse. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param ap A variable-length argument list containing the arguments - * @param parseError A pointer to UParseError to receive information about errors - * occurred during parsing. - * @param status A pointer to an UErrorCode to receive any errors - * specified in pattern. - * @see u_formatMessage - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -u_vparseMessageWithError(const char *locale, - const UChar *pattern, - int32_t patternLength, - const UChar *source, - int32_t sourceLength, - va_list ap, - UParseError *parseError, - UErrorCode* status); - -/*----------------------- New experimental API --------------------------- */ -/** - * The message format object - * @stable ICU 2.0 - */ -typedef void* UMessageFormat; - - -/** - * Open a message formatter with given pattern and for the given locale. - * @param pattern A pattern specifying the format to use. - * @param patternLength Length of the pattern to use - * @param locale The locale for which the messages are formatted. - * @param parseError A pointer to UParseError struct to receive any errors - * occured during parsing. Can be NULL. - * @param status A pointer to an UErrorCode to receive any errors. - * @return A pointer to a UMessageFormat to use for formatting - * messages, or 0 if an error occurred. - * @stable ICU 2.0 - */ -U_STABLE UMessageFormat* U_EXPORT2 -umsg_open( const UChar *pattern, - int32_t patternLength, - const char *locale, - UParseError *parseError, - UErrorCode *status); - -/** - * Close a UMessageFormat. - * Once closed, a UMessageFormat may no longer be used. - * @param format The formatter to close. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -umsg_close(UMessageFormat* format); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUMessageFormatPointer - * "Smart pointer" class, closes a UMessageFormat via umsg_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUMessageFormatPointer, UMessageFormat, umsg_close); - -U_NAMESPACE_END - -#endif - -/** - * Open a copy of a UMessageFormat. - * This function performs a deep copy. - * @param fmt The formatter to copy - * @param status A pointer to an UErrorCode to receive any errors. - * @return A pointer to a UDateFormat identical to fmt. - * @stable ICU 2.0 - */ -U_STABLE UMessageFormat U_EXPORT2 -umsg_clone(const UMessageFormat *fmt, - UErrorCode *status); - -/** - * Sets the locale. This locale is used for fetching default number or date - * format information. - * @param fmt The formatter to set - * @param locale The locale the formatter should use. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -umsg_setLocale(UMessageFormat *fmt, - const char* locale); - -/** - * Gets the locale. This locale is used for fetching default number or date - * format information. - * @param fmt The formatter to querry - * @return the locale. - * @stable ICU 2.0 - */ -U_STABLE const char* U_EXPORT2 -umsg_getLocale(const UMessageFormat *fmt); - -/** - * Sets the pattern. - * @param fmt The formatter to use - * @param pattern The pattern to be applied. - * @param patternLength Length of the pattern to use - * @param parseError Struct to receive information on position - * of error if an error is encountered.Can be NULL. - * @param status Output param set to success/failure code on - * exit. If the pattern is invalid, this will be - * set to a failure result. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -umsg_applyPattern( UMessageFormat *fmt, - const UChar* pattern, - int32_t patternLength, - UParseError* parseError, - UErrorCode* status); - -/** - * Gets the pattern. - * @param fmt The formatter to use - * @param result A pointer to a buffer to receive the pattern. - * @param resultLength The maximum size of result. - * @param status Output param set to success/failure code on - * exit. If the pattern is invalid, this will be - * set to a failure result. - * @return the pattern of the format - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -umsg_toPattern(const UMessageFormat *fmt, - UChar* result, - int32_t resultLength, - UErrorCode* status); - -/** - * Format a message for a locale. - * This function may perform re-ordering of the arguments depending on the - * locale. For all numeric arguments, double is assumed unless the type is - * explicitly integer. All choice format arguments must be of type double. - * @param fmt The formatter to use - * @param result A pointer to a buffer to receive the formatted message. - * @param resultLength The maximum size of result. - * @param status A pointer to an UErrorCode to receive any errors - * @param ... A variable-length argument list containing the arguments - * specified in pattern. - * @return The total buffer size needed; if greater than resultLength, - * the output was truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -umsg_format( const UMessageFormat *fmt, - UChar *result, - int32_t resultLength, - UErrorCode *status, - ...); - -/** - * Format a message for a locale. - * This function may perform re-ordering of the arguments depending on the - * locale. For all numeric arguments, double is assumed unless the type is - * explicitly integer. All choice format arguments must be of type double. - * @param fmt The formatter to use - * @param result A pointer to a buffer to receive the formatted message. - * @param resultLength The maximum size of result. - * @param ap A variable-length argument list containing the arguments - * @param status A pointer to an UErrorCode to receive any errors - * specified in pattern. - * @return The total buffer size needed; if greater than resultLength, - * the output was truncated. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -umsg_vformat( const UMessageFormat *fmt, - UChar *result, - int32_t resultLength, - va_list ap, - UErrorCode *status); - -/** - * Parse a message. - * For numeric arguments, this function will always use doubles. Integer types - * should not be passed. - * This function is not able to parse all output from {@link #umsg_format }. - * @param fmt The formatter to use - * @param source The text to parse. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param count Output param to receive number of elements returned. - * @param status A pointer to an UErrorCode to receive any errors - * @param ... A variable-length argument list containing the arguments - * specified in pattern. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -umsg_parse( const UMessageFormat *fmt, - const UChar *source, - int32_t sourceLength, - int32_t *count, - UErrorCode *status, - ...); - -/** - * Parse a message. - * For numeric arguments, this function will always use doubles. Integer types - * should not be passed. - * This function is not able to parse all output from {@link #umsg_format }. - * @param fmt The formatter to use - * @param source The text to parse. - * @param sourceLength The length of source, or -1 if null-terminated. - * @param count Output param to receive number of elements returned. - * @param ap A variable-length argument list containing the arguments - * @param status A pointer to an UErrorCode to receive any errors - * specified in pattern. - * @see u_formatMessage - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -umsg_vparse(const UMessageFormat *fmt, - const UChar *source, - int32_t sourceLength, - int32_t *count, - va_list ap, - UErrorCode *status); - - -/** - * Convert an 'apostrophe-friendly' pattern into a standard - * pattern. Standard patterns treat all apostrophes as - * quotes, which is problematic in some languages, e.g. - * French, where apostrophe is commonly used. This utility - * assumes that only an unpaired apostrophe immediately before - * a brace is a true quote. Other unpaired apostrophes are paired, - * and the resulting standard pattern string is returned. - * - *

Note it is not guaranteed that the returned pattern - * is indeed a valid pattern. The only effect is to convert - * between patterns having different quoting semantics. - * - * @param pattern the 'apostrophe-friendly' patttern to convert - * @param patternLength the length of pattern, or -1 if unknown and pattern is null-terminated - * @param dest the buffer for the result, or NULL if preflight only - * @param destCapacity the length of the buffer, or 0 if preflighting - * @param ec the error code - * @return the length of the resulting text, not including trailing null - * if buffer has room for the trailing null, it is provided, otherwise - * not - * @stable ICU 3.4 - */ -U_STABLE int32_t U_EXPORT2 -umsg_autoQuoteApostrophe(const UChar* pattern, - int32_t patternLength, - UChar* dest, - int32_t destCapacity, - UErrorCode* ec); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/unifilt.h b/win32/include/spidermonkey/unicode/unifilt.h deleted file mode 100755 index 0fdcd148..00000000 --- a/win32/include/spidermonkey/unicode/unifilt.h +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1999-2010, International Business Machines Corporation and others. -* All Rights Reserved. -********************************************************************** -* Date Name Description -* 11/17/99 aliu Creation. -********************************************************************** -*/ -#ifndef UNIFILT_H -#define UNIFILT_H - -#include "unicode/unifunct.h" -#include "unicode/unimatch.h" - -/** - * \file - * \brief C++ API: Unicode Filter - */ - -U_NAMESPACE_BEGIN - -/** - * U_ETHER is used to represent character values for positions outside - * a range. For example, transliterator uses this to represent - * characters outside the range contextStart..contextLimit-1. This - * allows explicit matching by rules and UnicodeSets of text outside a - * defined range. - * @stable ICU 3.0 - */ -#define U_ETHER ((UChar)0xFFFF) - -/** - * - * UnicodeFilter defines a protocol for selecting a - * subset of the full range (U+0000 to U+10FFFF) of Unicode characters. - * Currently, filters are used in conjunction with classes like {@link - * Transliterator} to only process selected characters through a - * transformation. - * - *

Note: UnicodeFilter currently stubs out two pure virtual methods - * of its base class, UnicodeMatcher. These methods are toPattern() - * and matchesIndexValue(). This is done so that filter classes that - * are not actually used as matchers -- specifically, those in the - * UnicodeFilterLogic component, and those in tests -- can continue to - * work without defining these methods. As long as a filter is not - * used in an RBT during real transliteration, these methods will not - * be called. However, this breaks the UnicodeMatcher base class - * protocol, and it is not a correct solution. - * - *

In the future we may revisit the UnicodeMatcher / UnicodeFilter - * hierarchy and either redesign it, or simply remove the stubs in - * UnicodeFilter and force subclasses to implement the full - * UnicodeMatcher protocol. - * - * @see UnicodeFilterLogic - * @stable ICU 2.0 - */ -class U_COMMON_API UnicodeFilter : public UnicodeFunctor, public UnicodeMatcher { - -public: - /** - * Destructor - * @stable ICU 2.0 - */ - virtual ~UnicodeFilter(); - - /** - * Returns true for characters that are in the selected - * subset. In other words, if a character is to be - * filtered, then contains() returns - * false. - * @stable ICU 2.0 - */ - virtual UBool contains(UChar32 c) const = 0; - - /** - * UnicodeFunctor API. Cast 'this' to a UnicodeMatcher* pointer - * and return the pointer. - * @stable ICU 2.4 - */ - virtual UnicodeMatcher* toMatcher() const; - - /** - * Implement UnicodeMatcher API. - * @stable ICU 2.4 - */ - virtual UMatchDegree matches(const Replaceable& text, - int32_t& offset, - int32_t limit, - UBool incremental); - - /** - * UnicodeFunctor API. Nothing to do. - * @stable ICU 2.4 - */ - virtual void setData(const TransliterationRuleData*); - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - -protected: - - /* - * Since this class has pure virtual functions, - * a constructor can't be used. - * @stable ICU 2.0 - */ -/* UnicodeFilter();*/ -}; - -/*inline UnicodeFilter::UnicodeFilter() {}*/ - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/unifunct.h b/win32/include/spidermonkey/unicode/unifunct.h deleted file mode 100755 index b40027c0..00000000 --- a/win32/include/spidermonkey/unicode/unifunct.h +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2002-2005, International Business Machines Corporation -* and others. All Rights Reserved. -********************************************************************** -* Date Name Description -* 01/14/2002 aliu Creation. -********************************************************************** -*/ -#ifndef UNIFUNCT_H -#define UNIFUNCT_H - -#include "unicode/utypes.h" -#include "unicode/uobject.h" - -/** - * \file - * \brief C++ API: Unicode Functor - */ - -U_NAMESPACE_BEGIN - -class UnicodeMatcher; -class UnicodeReplacer; -class TransliterationRuleData; - -/** - * UnicodeFunctor is an abstract base class for objects - * that perform match and/or replace operations on Unicode strings. - * @author Alan Liu - * @stable ICU 2.4 - */ -class U_COMMON_API UnicodeFunctor : public UObject { - -public: - - /** - * Destructor - * @stable ICU 2.4 - */ - virtual ~UnicodeFunctor(); - - /** - * Return a copy of this object. All UnicodeFunctor objects - * have to support cloning in order to allow classes using - * UnicodeFunctor to implement cloning. - * @stable ICU 2.4 - */ - virtual UnicodeFunctor* clone() const = 0; - - /** - * Cast 'this' to a UnicodeMatcher* pointer and return the - * pointer, or null if this is not a UnicodeMatcher*. Subclasses - * that mix in UnicodeMatcher as a base class must override this. - * This protocol is required because a pointer to a UnicodeFunctor - * cannot be cast to a pointer to a UnicodeMatcher, since - * UnicodeMatcher is a mixin that does not derive from - * UnicodeFunctor. - * @stable ICU 2.4 - */ - virtual UnicodeMatcher* toMatcher() const; - - /** - * Cast 'this' to a UnicodeReplacer* pointer and return the - * pointer, or null if this is not a UnicodeReplacer*. Subclasses - * that mix in UnicodeReplacer as a base class must override this. - * This protocol is required because a pointer to a UnicodeFunctor - * cannot be cast to a pointer to a UnicodeReplacer, since - * UnicodeReplacer is a mixin that does not derive from - * UnicodeFunctor. - * @stable ICU 2.4 - */ - virtual UnicodeReplacer* toReplacer() const; - - /** - * Return the class ID for this class. This is useful only for - * comparing to a return value from getDynamicClassID(). - * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID polymorphically. This method - * is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and - * clone() methods call this method. - * - *

Concrete subclasses of UnicodeFunctor should use the macro - * UOBJECT_DEFINE_RTTI_IMPLEMENTATION from uobject.h to - * provide definitios getStaticClassID and getDynamicClassID. - * - * @return The class ID for this object. All objects of a given - * class have the same class ID. Objects of other classes have - * different class IDs. - * @stable ICU 2.4 - */ - virtual UClassID getDynamicClassID(void) const = 0; - - /** - * Set the data object associated with this functor. The data - * object provides context for functor-to-standin mapping. This - * method is required when assigning a functor to a different data - * object. This function MAY GO AWAY later if the architecture is - * changed to pass data object pointers through the API. - * @internal ICU 2.1 - */ - virtual void setData(const TransliterationRuleData*) = 0; - -protected: - - /** - * Since this class has pure virtual functions, - * a constructor can't be used. - * @stable ICU 2.0 - */ - /*UnicodeFunctor();*/ - -}; - -/*inline UnicodeFunctor::UnicodeFunctor() {}*/ - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/unimatch.h b/win32/include/spidermonkey/unicode/unimatch.h deleted file mode 100755 index 605f3f5e..00000000 --- a/win32/include/spidermonkey/unicode/unimatch.h +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -* Copyright (C) 2001-2005, International Business Machines Corporation and others. All Rights Reserved. -********************************************************************** -* Date Name Description -* 07/18/01 aliu Creation. -********************************************************************** -*/ -#ifndef UNIMATCH_H -#define UNIMATCH_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Unicode Matcher - */ - - -U_NAMESPACE_BEGIN - -class Replaceable; -class UnicodeString; -class UnicodeSet; - -/** - * Constants returned by UnicodeMatcher::matches() - * indicating the degree of match. - * @stable ICU 2.4 - */ -enum UMatchDegree { - /** - * Constant returned by matches() indicating a - * mismatch between the text and this matcher. The text contains - * a character which does not match, or the text does not contain - * all desired characters for a non-incremental match. - * @stable ICU 2.4 - */ - U_MISMATCH, - - /** - * Constant returned by matches() indicating a - * partial match between the text and this matcher. This value is - * only returned for incremental match operations. All characters - * of the text match, but more characters are required for a - * complete match. Alternatively, for variable-length matchers, - * all characters of the text match, and if more characters were - * supplied at limit, they might also match. - * @stable ICU 2.4 - */ - U_PARTIAL_MATCH, - - /** - * Constant returned by matches() indicating a - * complete match between the text and this matcher. For an - * incremental variable-length match, this value is returned if - * the given text matches, and it is known that additional - * characters would not alter the extent of the match. - * @stable ICU 2.4 - */ - U_MATCH -}; - -/** - * UnicodeMatcher defines a protocol for objects that can - * match a range of characters in a Replaceable string. - * @stable ICU 2.4 - */ -class U_COMMON_API UnicodeMatcher /* not : public UObject because this is an interface/mixin class */ { - -public: - /** - * Destructor. - * @stable ICU 2.4 - */ - virtual ~UnicodeMatcher(); - - /** - * Return a UMatchDegree value indicating the degree of match for - * the given text at the given offset. Zero, one, or more - * characters may be matched. - * - * Matching in the forward direction is indicated by limit > - * offset. Characters from offset forwards to limit-1 will be - * considered for matching. - * - * Matching in the reverse direction is indicated by limit < - * offset. Characters from offset backwards to limit+1 will be - * considered for matching. - * - * If limit == offset then the only match possible is a zero - * character match (which subclasses may implement if desired). - * - * As a side effect, advance the offset parameter to the limit of - * the matched substring. In the forward direction, this will be - * the index of the last matched character plus one. In the - * reverse direction, this will be the index of the last matched - * character minus one. - * - *

Note: This method is not const because some classes may - * modify their state as the result of a match. - * - * @param text the text to be matched - * @param offset on input, the index into text at which to begin - * matching. On output, the limit of the matched text. The - * number of matched characters is the output value of offset - * minus the input value. Offset should always point to the - * HIGH SURROGATE (leading code unit) of a pair of surrogates, - * both on entry and upon return. - * @param limit the limit index of text to be matched. Greater - * than offset for a forward direction match, less than offset for - * a backward direction match. The last character to be - * considered for matching will be text.charAt(limit-1) in the - * forward direction or text.charAt(limit+1) in the backward - * direction. - * @param incremental if TRUE, then assume further characters may - * be inserted at limit and check for partial matching. Otherwise - * assume the text as given is complete. - * @return a match degree value indicating a full match, a partial - * match, or a mismatch. If incremental is FALSE then - * U_PARTIAL_MATCH should never be returned. - * @stable ICU 2.4 - */ - virtual UMatchDegree matches(const Replaceable& text, - int32_t& offset, - int32_t limit, - UBool incremental) = 0; - - /** - * Returns a string representation of this matcher. If the result of - * calling this function is passed to the appropriate parser, it - * will produce another matcher that is equal to this one. - * @param result the string to receive the pattern. Previous - * contents will be deleted. - * @param escapeUnprintable if TRUE then convert unprintable - * character to their hex escape representations, \\uxxxx or - * \\Uxxxxxxxx. Unprintable characters are those other than - * U+000A, U+0020..U+007E. - * @stable ICU 2.4 - */ - virtual UnicodeString& toPattern(UnicodeString& result, - UBool escapeUnprintable = FALSE) const = 0; - - /** - * Returns TRUE if this matcher will match a character c, where c - * & 0xFF == v, at offset, in the forward direction (with limit > - * offset). This is used by RuleBasedTransliterator for - * indexing. - * @stable ICU 2.4 - */ - virtual UBool matchesIndexValue(uint8_t v) const = 0; - - /** - * Union the set of all characters that may be matched by this object - * into the given set. - * @param toUnionTo the set into which to union the source characters - * @stable ICU 2.4 - */ - virtual void addMatchSetTo(UnicodeSet& toUnionTo) const = 0; -}; - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/unirepl.h b/win32/include/spidermonkey/unicode/unirepl.h deleted file mode 100755 index 1e98ff64..00000000 --- a/win32/include/spidermonkey/unicode/unirepl.h +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2002-2005, International Business Machines Corporation -* and others. All Rights Reserved. -********************************************************************** -* Date Name Description -* 01/14/2002 aliu Creation. -********************************************************************** -*/ -#ifndef UNIREPL_H -#define UNIREPL_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: UnicodeReplacer - */ - -U_NAMESPACE_BEGIN - -class Replaceable; -class UnicodeString; -class UnicodeSet; - -/** - * UnicodeReplacer defines a protocol for objects that - * replace a range of characters in a Replaceable string with output - * text. The replacement is done via the Replaceable API so as to - * preserve out-of-band data. - * - *

This is a mixin class. - * @author Alan Liu - * @stable ICU 2.4 - */ -class U_I18N_API UnicodeReplacer /* not : public UObject because this is an interface/mixin class */ { - - public: - - /** - * Destructor. - * @stable ICU 2.4 - */ - virtual ~UnicodeReplacer(); - - /** - * Replace characters in 'text' from 'start' to 'limit' with the - * output text of this object. Update the 'cursor' parameter to - * give the cursor position and return the length of the - * replacement text. - * - * @param text the text to be matched - * @param start inclusive start index of text to be replaced - * @param limit exclusive end index of text to be replaced; - * must be greater than or equal to start - * @param cursor output parameter for the cursor position. - * Not all replacer objects will update this, but in a complete - * tree of replacer objects, representing the entire output side - * of a transliteration rule, at least one must update it. - * @return the number of 16-bit code units in the text replacing - * the characters at offsets start..(limit-1) in text - * @stable ICU 2.4 - */ - virtual int32_t replace(Replaceable& text, - int32_t start, - int32_t limit, - int32_t& cursor) = 0; - - /** - * Returns a string representation of this replacer. If the - * result of calling this function is passed to the appropriate - * parser, typically TransliteratorParser, it will produce another - * replacer that is equal to this one. - * @param result the string to receive the pattern. Previous - * contents will be deleted. - * @param escapeUnprintable if TRUE then convert unprintable - * character to their hex escape representations, \\uxxxx or - * \\Uxxxxxxxx. Unprintable characters are defined by - * Utility.isUnprintable(). - * @return a reference to 'result'. - * @stable ICU 2.4 - */ - virtual UnicodeString& toReplacerPattern(UnicodeString& result, - UBool escapeUnprintable) const = 0; - - /** - * Union the set of all characters that may output by this object - * into the given set. - * @param toUnionTo the set into which to union the output characters - * @stable ICU 2.4 - */ - virtual void addReplacementSetTo(UnicodeSet& toUnionTo) const = 0; -}; - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/uniset.h b/win32/include/spidermonkey/unicode/uniset.h deleted file mode 100755 index fdd7fc39..00000000 --- a/win32/include/spidermonkey/unicode/uniset.h +++ /dev/null @@ -1,1715 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -*************************************************************************** -* Copyright (C) 1999-2016, International Business Machines Corporation -* and others. All Rights Reserved. -*************************************************************************** -* Date Name Description -* 10/20/99 alan Creation. -*************************************************************************** -*/ - -#ifndef UNICODESET_H -#define UNICODESET_H - -#include "unicode/unifilt.h" -#include "unicode/unistr.h" -#include "unicode/uset.h" - -/** - * \file - * \brief C++ API: Unicode Set - */ - -U_NAMESPACE_BEGIN - -// Forward Declarations. -void U_CALLCONV UnicodeSet_initInclusion(int32_t src, UErrorCode &status); /**< @internal */ - -class BMPSet; -class ParsePosition; -class RBBIRuleScanner; -class SymbolTable; -class UnicodeSetStringSpan; -class UVector; -class RuleCharacterIterator; - -/** - * A mutable set of Unicode characters and multicharacter strings. Objects of this class - * represent character classes used in regular expressions. - * A character specifies a subset of Unicode code points. Legal - * code points are U+0000 to U+10FFFF, inclusive. - * - *

The UnicodeSet class is not designed to be subclassed. - * - *

UnicodeSet supports two APIs. The first is the - * operand API that allows the caller to modify the value of - * a UnicodeSet object. It conforms to Java 2's - * java.util.Set interface, although - * UnicodeSet does not actually implement that - * interface. All methods of Set are supported, with the - * modification that they take a character range or single character - * instead of an Object, and they take a - * UnicodeSet instead of a Collection. The - * operand API may be thought of in terms of boolean logic: a boolean - * OR is implemented by add, a boolean AND is implemented - * by retain, a boolean XOR is implemented by - * complement taking an argument, and a boolean NOT is - * implemented by complement with no argument. In terms - * of traditional set theory function names, add is a - * union, retain is an intersection, remove - * is an asymmetric difference, and complement with no - * argument is a set complement with respect to the superset range - * MIN_VALUE-MAX_VALUE - * - *

The second API is the - * applyPattern()/toPattern() API from the - * java.text.Format-derived classes. Unlike the - * methods that add characters, add categories, and control the logic - * of the set, the method applyPattern() sets all - * attributes of a UnicodeSet at once, based on a - * string pattern. - * - *

Pattern syntax

- * - * Patterns are accepted by the constructors and the - * applyPattern() methods and returned by the - * toPattern() method. These patterns follow a syntax - * similar to that employed by version 8 regular expression character - * classes. Here are some simple examples: - * - * \htmlonly
\endhtmlonly - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
[]No characters
[a]The character 'a'
[ae]The characters 'a' and 'e'
[a-e]The characters 'a' through 'e' inclusive, in Unicode code - * point order
[\\u4E01]The character U+4E01
[a{ab}{ac}]The character 'a' and the multicharacter strings "ab" and - * "ac"
[\\p{Lu}]All characters in the general category Uppercase Letter
- * \htmlonly
\endhtmlonly - * - * Any character may be preceded by a backslash in order to remove any special - * meaning. White space characters, as defined by UCharacter.isWhitespace(), are - * ignored, unless they are escaped. - * - *

Property patterns specify a set of characters having a certain - * property as defined by the Unicode standard. Both the POSIX-like - * "[:Lu:]" and the Perl-like syntax "\\p{Lu}" are recognized. For a - * complete list of supported property patterns, see the User's Guide - * for UnicodeSet at - * - * http://icu-project.org/userguide/unicodeSet.html. - * Actual determination of property data is defined by the underlying - * Unicode database as implemented by UCharacter. - * - *

Patterns specify individual characters, ranges of characters, and - * Unicode property sets. When elements are concatenated, they - * specify their union. To complement a set, place a '^' immediately - * after the opening '['. Property patterns are inverted by modifying - * their delimiters; "[:^foo]" and "\\P{foo}". In any other location, - * '^' has no special meaning. - * - *

Ranges are indicated by placing two a '-' between two - * characters, as in "a-z". This specifies the range of all - * characters from the left to the right, in Unicode order. If the - * left character is greater than or equal to the - * right character it is a syntax error. If a '-' occurs as the first - * character after the opening '[' or '[^', or if it occurs as the - * last character before the closing ']', then it is taken as a - * literal. Thus "[a\-b]", "[-ab]", and "[ab-]" all indicate the same - * set of three characters, 'a', 'b', and '-'. - * - *

Sets may be intersected using the '&' operator or the asymmetric - * set difference may be taken using the '-' operator, for example, - * "[[:L:]&[\\u0000-\\u0FFF]]" indicates the set of all Unicode letters - * with values less than 4096. Operators ('&' and '|') have equal - * precedence and bind left-to-right. Thus - * "[[:L:]-[a-z]-[\\u0100-\\u01FF]]" is equivalent to - * "[[[:L:]-[a-z]]-[\\u0100-\\u01FF]]". This only really matters for - * difference; intersection is commutative. - * - * - *
[a]The set containing 'a' - *
[a-z]The set containing 'a' - * through 'z' and all letters in between, in Unicode order - *
[^a-z]The set containing - * all characters but 'a' through 'z', - * that is, U+0000 through 'a'-1 and 'z'+1 through U+10FFFF - *
[[pat1][pat2]] - * The union of sets specified by pat1 and pat2 - *
[[pat1]&[pat2]] - * The intersection of sets specified by pat1 and pat2 - *
[[pat1]-[pat2]] - * The asymmetric difference of sets specified by pat1 and - * pat2 - *
[:Lu:] or \\p{Lu} - * The set of characters having the specified - * Unicode property; in - * this case, Unicode uppercase letters - *
[:^Lu:] or \\P{Lu} - * The set of characters not having the given - * Unicode property - *
- * - *

Warning: you cannot add an empty string ("") to a UnicodeSet.

- * - *

Formal syntax

- * - * \htmlonly
\endhtmlonly - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
pattern :=  ('[' '^'? item* ']') | - * property
item :=  char | (char '-' char) | pattern-expr
- *
pattern-expr :=  pattern | pattern-expr pattern | - * pattern-expr op pattern
- *
op :=  '&' | '-'
- *
special :=  '[' | ']' | '-'
- *
char :=  any character that is not special
- * | ('\'
any character)
- * | ('\\u' hex hex hex hex)
- *
hex :=  any character for which - * Character.digit(c, 16) - * returns a non-negative result
property :=  a Unicode property set pattern
- *
- * - * - * - * - *
Legend: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
a := b  a may be replaced by b
a?zero or one instance of a
- *
a*one or more instances of a
- *
a | beither a or b
- *
'a'the literal string between the quotes
- *
- * \htmlonly
\endhtmlonly - * - *

Note: - * - Most UnicodeSet methods do not take a UErrorCode parameter because - * there are usually very few opportunities for failure other than a shortage - * of memory, error codes in low-level C++ string methods would be inconvenient, - * and the error code as the last parameter (ICU convention) would prevent - * the use of default parameter values. - * Instead, such methods set the UnicodeSet into a "bogus" state - * (see isBogus()) if an error occurs. - * - * @author Alan Liu - * @stable ICU 2.0 - */ -class U_COMMON_API UnicodeSet U_FINAL : public UnicodeFilter { - - int32_t len; // length of list used; 0 <= len <= capacity - int32_t capacity; // capacity of list - UChar32* list; // MUST be terminated with HIGH - BMPSet *bmpSet; // The set is frozen iff either bmpSet or stringSpan is not NULL. - UChar32* buffer; // internal buffer, may be NULL - int32_t bufferCapacity; // capacity of buffer - int32_t patLen; - - /** - * The pattern representation of this set. This may not be the - * most economical pattern. It is the pattern supplied to - * applyPattern(), with variables substituted and whitespace - * removed. For sets constructed without applyPattern(), or - * modified using the non-pattern API, this string will be empty, - * indicating that toPattern() must generate a pattern - * representation from the inversion list. - */ - UChar *pat; - UVector* strings; // maintained in sorted order - UnicodeSetStringSpan *stringSpan; - -private: - enum { // constants - kIsBogus = 1 // This set is bogus (i.e. not valid) - }; - uint8_t fFlags; // Bit flag (see constants above) -public: - /** - * Determine if this object contains a valid set. - * A bogus set has no value. It is different from an empty set. - * It can be used to indicate that no set value is available. - * - * @return TRUE if the set is bogus/invalid, FALSE otherwise - * @see setToBogus() - * @stable ICU 4.0 - */ - inline UBool isBogus(void) const; - - /** - * Make this UnicodeSet object invalid. - * The string will test TRUE with isBogus(). - * - * A bogus set has no value. It is different from an empty set. - * It can be used to indicate that no set value is available. - * - * This utility function is used throughout the UnicodeSet - * implementation to indicate that a UnicodeSet operation failed, - * and may be used in other functions, - * especially but not exclusively when such functions do not - * take a UErrorCode for simplicity. - * - * @see isBogus() - * @stable ICU 4.0 - */ - void setToBogus(); - -public: - - enum { - /** - * Minimum value that can be stored in a UnicodeSet. - * @stable ICU 2.4 - */ - MIN_VALUE = 0, - - /** - * Maximum value that can be stored in a UnicodeSet. - * @stable ICU 2.4 - */ - MAX_VALUE = 0x10ffff - }; - - //---------------------------------------------------------------- - // Constructors &c - //---------------------------------------------------------------- - -public: - - /** - * Constructs an empty set. - * @stable ICU 2.0 - */ - UnicodeSet(); - - /** - * Constructs a set containing the given range. If end < - * start then an empty set is created. - * - * @param start first character, inclusive, of range - * @param end last character, inclusive, of range - * @stable ICU 2.4 - */ - UnicodeSet(UChar32 start, UChar32 end); - -#ifndef U_HIDE_INTERNAL_API - /** - * @internal - */ - enum ESerialization { - kSerialized /* result of serialize() */ - }; - - /** - * Constructs a set from the output of serialize(). - * - * @param buffer the 16 bit array - * @param bufferLen the original length returned from serialize() - * @param serialization the value 'kSerialized' - * @param status error code - * - * @internal - */ - UnicodeSet(const uint16_t buffer[], int32_t bufferLen, - ESerialization serialization, UErrorCode &status); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Constructs a set from the given pattern. See the class - * description for the syntax of the pattern language. - * @param pattern a string specifying what characters are in the set - * @param status returns U_ILLEGAL_ARGUMENT_ERROR if the pattern - * contains a syntax error. - * @stable ICU 2.0 - */ - UnicodeSet(const UnicodeString& pattern, - UErrorCode& status); - -#ifndef U_HIDE_INTERNAL_API - /** - * Constructs a set from the given pattern. See the class - * description for the syntax of the pattern language. - * @param pattern a string specifying what characters are in the set - * @param options bitmask for options to apply to the pattern. - * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE. - * @param symbols a symbol table mapping variable names to values - * and stand-in characters to UnicodeSets; may be NULL - * @param status returns U_ILLEGAL_ARGUMENT_ERROR if the pattern - * contains a syntax error. - * @internal - */ - UnicodeSet(const UnicodeString& pattern, - uint32_t options, - const SymbolTable* symbols, - UErrorCode& status); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Constructs a set from the given pattern. See the class description - * for the syntax of the pattern language. - * @param pattern a string specifying what characters are in the set - * @param pos on input, the position in pattern at which to start parsing. - * On output, the position after the last character parsed. - * @param options bitmask for options to apply to the pattern. - * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE. - * @param symbols a symbol table mapping variable names to values - * and stand-in characters to UnicodeSets; may be NULL - * @param status input-output error code - * @stable ICU 2.8 - */ - UnicodeSet(const UnicodeString& pattern, ParsePosition& pos, - uint32_t options, - const SymbolTable* symbols, - UErrorCode& status); - - /** - * Constructs a set that is identical to the given UnicodeSet. - * @stable ICU 2.0 - */ - UnicodeSet(const UnicodeSet& o); - - /** - * Destructs the set. - * @stable ICU 2.0 - */ - virtual ~UnicodeSet(); - - /** - * Assigns this object to be a copy of another. - * A frozen set will not be modified. - * @stable ICU 2.0 - */ - UnicodeSet& operator=(const UnicodeSet& o); - - /** - * Compares the specified object with this set for equality. Returns - * true if the two sets - * have the same size, and every member of the specified set is - * contained in this set (or equivalently, every member of this set is - * contained in the specified set). - * - * @param o set to be compared for equality with this set. - * @return true if the specified set is equal to this set. - * @stable ICU 2.0 - */ - virtual UBool operator==(const UnicodeSet& o) const; - - /** - * Compares the specified object with this set for equality. Returns - * true if the specified set is not equal to this set. - * @stable ICU 2.0 - */ - UBool operator!=(const UnicodeSet& o) const; - - /** - * Returns a copy of this object. All UnicodeFunctor objects have - * to support cloning in order to allow classes using - * UnicodeFunctors, such as Transliterator, to implement cloning. - * If this set is frozen, then the clone will be frozen as well. - * Use cloneAsThawed() for a mutable clone of a frozen set. - * @see cloneAsThawed - * @stable ICU 2.0 - */ - virtual UnicodeFunctor* clone() const; - - /** - * Returns the hash code value for this set. - * - * @return the hash code value for this set. - * @see Object#hashCode() - * @stable ICU 2.0 - */ - virtual int32_t hashCode(void) const; - - /** - * Get a UnicodeSet pointer from a USet - * - * @param uset a USet (the ICU plain C type for UnicodeSet) - * @return the corresponding UnicodeSet pointer. - * - * @stable ICU 4.2 - */ - inline static UnicodeSet *fromUSet(USet *uset); - - /** - * Get a UnicodeSet pointer from a const USet - * - * @param uset a const USet (the ICU plain C type for UnicodeSet) - * @return the corresponding UnicodeSet pointer. - * - * @stable ICU 4.2 - */ - inline static const UnicodeSet *fromUSet(const USet *uset); - - /** - * Produce a USet * pointer for this UnicodeSet. - * USet is the plain C type for UnicodeSet - * - * @return a USet pointer for this UnicodeSet - * @stable ICU 4.2 - */ - inline USet *toUSet(); - - - /** - * Produce a const USet * pointer for this UnicodeSet. - * USet is the plain C type for UnicodeSet - * - * @return a const USet pointer for this UnicodeSet - * @stable ICU 4.2 - */ - inline const USet * toUSet() const; - - - //---------------------------------------------------------------- - // Freezable API - //---------------------------------------------------------------- - - /** - * Determines whether the set has been frozen (made immutable) or not. - * See the ICU4J Freezable interface for details. - * @return TRUE/FALSE for whether the set has been frozen - * @see freeze - * @see cloneAsThawed - * @stable ICU 3.8 - */ - inline UBool isFrozen() const; - - /** - * Freeze the set (make it immutable). - * Once frozen, it cannot be unfrozen and is therefore thread-safe - * until it is deleted. - * See the ICU4J Freezable interface for details. - * Freezing the set may also make some operations faster, for example - * contains() and span(). - * A frozen set will not be modified. (It remains frozen.) - * @return this set. - * @see isFrozen - * @see cloneAsThawed - * @stable ICU 3.8 - */ - UnicodeFunctor *freeze(); - - /** - * Clone the set and make the clone mutable. - * See the ICU4J Freezable interface for details. - * @return the mutable clone - * @see freeze - * @see isFrozen - * @stable ICU 3.8 - */ - UnicodeFunctor *cloneAsThawed() const; - - //---------------------------------------------------------------- - // Public API - //---------------------------------------------------------------- - - /** - * Make this object represent the range start - end. - * If end > start then this object is set to an - * an empty range. - * A frozen set will not be modified. - * - * @param start first character in the set, inclusive - * @param end last character in the set, inclusive - * @stable ICU 2.4 - */ - UnicodeSet& set(UChar32 start, UChar32 end); - - /** - * Return true if the given position, in the given pattern, appears - * to be the start of a UnicodeSet pattern. - * @stable ICU 2.4 - */ - static UBool resemblesPattern(const UnicodeString& pattern, - int32_t pos); - - /** - * Modifies this set to represent the set specified by the given - * pattern, ignoring Unicode Pattern_White_Space characters. - * See the class description for the syntax of the pattern language. - * A frozen set will not be modified. - * @param pattern a string specifying what characters are in the set - * @param status returns U_ILLEGAL_ARGUMENT_ERROR if the pattern - * contains a syntax error. - * Empties the set passed before applying the pattern. - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeSet& applyPattern(const UnicodeString& pattern, - UErrorCode& status); - -#ifndef U_HIDE_INTERNAL_API - /** - * Modifies this set to represent the set specified by the given - * pattern, optionally ignoring Unicode Pattern_White_Space characters. - * See the class description for the syntax of the pattern language. - * A frozen set will not be modified. - * @param pattern a string specifying what characters are in the set - * @param options bitmask for options to apply to the pattern. - * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE. - * @param symbols a symbol table mapping variable names to - * values and stand-ins to UnicodeSets; may be NULL - * @param status returns U_ILLEGAL_ARGUMENT_ERROR if the pattern - * contains a syntax error. - * Empties the set passed before applying the pattern. - * @return a reference to this - * @internal - */ - UnicodeSet& applyPattern(const UnicodeString& pattern, - uint32_t options, - const SymbolTable* symbols, - UErrorCode& status); -#endif /* U_HIDE_INTERNAL_API */ - - /** - * Parses the given pattern, starting at the given position. The - * character at pattern.charAt(pos.getIndex()) must be '[', or the - * parse fails. Parsing continues until the corresponding closing - * ']'. If a syntax error is encountered between the opening and - * closing brace, the parse fails. Upon return from a successful - * parse, the ParsePosition is updated to point to the character - * following the closing ']', and a StringBuffer containing a - * pairs list for the parsed pattern is returned. This method calls - * itself recursively to parse embedded subpatterns. - * Empties the set passed before applying the pattern. - * A frozen set will not be modified. - * - * @param pattern the string containing the pattern to be parsed. - * The portion of the string from pos.getIndex(), which must be a - * '[', to the corresponding closing ']', is parsed. - * @param pos upon entry, the position at which to being parsing. - * The character at pattern.charAt(pos.getIndex()) must be a '['. - * Upon return from a successful parse, pos.getIndex() is either - * the character after the closing ']' of the parsed pattern, or - * pattern.length() if the closing ']' is the last character of - * the pattern string. - * @param options bitmask for options to apply to the pattern. - * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE. - * @param symbols a symbol table mapping variable names to - * values and stand-ins to UnicodeSets; may be NULL - * @param status returns U_ILLEGAL_ARGUMENT_ERROR if the pattern - * contains a syntax error. - * @return a reference to this - * @stable ICU 2.8 - */ - UnicodeSet& applyPattern(const UnicodeString& pattern, - ParsePosition& pos, - uint32_t options, - const SymbolTable* symbols, - UErrorCode& status); - - /** - * Returns a string representation of this set. If the result of - * calling this function is passed to a UnicodeSet constructor, it - * will produce another set that is equal to this one. - * A frozen set will not be modified. - * @param result the string to receive the rules. Previous - * contents will be deleted. - * @param escapeUnprintable if TRUE then convert unprintable - * character to their hex escape representations, \\uxxxx or - * \\Uxxxxxxxx. Unprintable characters are those other than - * U+000A, U+0020..U+007E. - * @stable ICU 2.0 - */ - virtual UnicodeString& toPattern(UnicodeString& result, - UBool escapeUnprintable = FALSE) const; - - /** - * Modifies this set to contain those code points which have the given value - * for the given binary or enumerated property, as returned by - * u_getIntPropertyValue. Prior contents of this set are lost. - * A frozen set will not be modified. - * - * @param prop a property in the range UCHAR_BIN_START..UCHAR_BIN_LIMIT-1 - * or UCHAR_INT_START..UCHAR_INT_LIMIT-1 - * or UCHAR_MASK_START..UCHAR_MASK_LIMIT-1. - * - * @param value a value in the range u_getIntPropertyMinValue(prop).. - * u_getIntPropertyMaxValue(prop), with one exception. If prop is - * UCHAR_GENERAL_CATEGORY_MASK, then value should not be a UCharCategory, but - * rather a mask value produced by U_GET_GC_MASK(). This allows grouped - * categories such as [:L:] to be represented. - * - * @param ec error code input/output parameter - * - * @return a reference to this set - * - * @stable ICU 2.4 - */ - UnicodeSet& applyIntPropertyValue(UProperty prop, - int32_t value, - UErrorCode& ec); - - /** - * Modifies this set to contain those code points which have the - * given value for the given property. Prior contents of this - * set are lost. - * A frozen set will not be modified. - * - * @param prop a property alias, either short or long. The name is matched - * loosely. See PropertyAliases.txt for names and a description of loose - * matching. If the value string is empty, then this string is interpreted - * as either a General_Category value alias, a Script value alias, a binary - * property alias, or a special ID. Special IDs are matched loosely and - * correspond to the following sets: - * - * "ANY" = [\\u0000-\\U0010FFFF], - * "ASCII" = [\\u0000-\\u007F], - * "Assigned" = [:^Cn:]. - * - * @param value a value alias, either short or long. The name is matched - * loosely. See PropertyValueAliases.txt for names and a description of - * loose matching. In addition to aliases listed, numeric values and - * canonical combining classes may be expressed numerically, e.g., ("nv", - * "0.5") or ("ccc", "220"). The value string may also be empty. - * - * @param ec error code input/output parameter - * - * @return a reference to this set - * - * @stable ICU 2.4 - */ - UnicodeSet& applyPropertyAlias(const UnicodeString& prop, - const UnicodeString& value, - UErrorCode& ec); - - /** - * Returns the number of elements in this set (its cardinality). - * Note than the elements of a set may include both individual - * codepoints and strings. - * - * @return the number of elements in this set (its cardinality). - * @stable ICU 2.0 - */ - virtual int32_t size(void) const; - - /** - * Returns true if this set contains no elements. - * - * @return true if this set contains no elements. - * @stable ICU 2.0 - */ - virtual UBool isEmpty(void) const; - - /** - * Returns true if this set contains the given character. - * This function works faster with a frozen set. - * @param c character to be checked for containment - * @return true if the test condition is met - * @stable ICU 2.0 - */ - virtual UBool contains(UChar32 c) const; - - /** - * Returns true if this set contains every character - * of the given range. - * @param start first character, inclusive, of the range - * @param end last character, inclusive, of the range - * @return true if the test condition is met - * @stable ICU 2.0 - */ - virtual UBool contains(UChar32 start, UChar32 end) const; - - /** - * Returns true if this set contains the given - * multicharacter string. - * @param s string to be checked for containment - * @return true if this set contains the specified string - * @stable ICU 2.4 - */ - UBool contains(const UnicodeString& s) const; - - /** - * Returns true if this set contains all the characters and strings - * of the given set. - * @param c set to be checked for containment - * @return true if the test condition is met - * @stable ICU 2.4 - */ - virtual UBool containsAll(const UnicodeSet& c) const; - - /** - * Returns true if this set contains all the characters - * of the given string. - * @param s string containing characters to be checked for containment - * @return true if the test condition is met - * @stable ICU 2.4 - */ - UBool containsAll(const UnicodeString& s) const; - - /** - * Returns true if this set contains none of the characters - * of the given range. - * @param start first character, inclusive, of the range - * @param end last character, inclusive, of the range - * @return true if the test condition is met - * @stable ICU 2.4 - */ - UBool containsNone(UChar32 start, UChar32 end) const; - - /** - * Returns true if this set contains none of the characters and strings - * of the given set. - * @param c set to be checked for containment - * @return true if the test condition is met - * @stable ICU 2.4 - */ - UBool containsNone(const UnicodeSet& c) const; - - /** - * Returns true if this set contains none of the characters - * of the given string. - * @param s string containing characters to be checked for containment - * @return true if the test condition is met - * @stable ICU 2.4 - */ - UBool containsNone(const UnicodeString& s) const; - - /** - * Returns true if this set contains one or more of the characters - * in the given range. - * @param start first character, inclusive, of the range - * @param end last character, inclusive, of the range - * @return true if the condition is met - * @stable ICU 2.4 - */ - inline UBool containsSome(UChar32 start, UChar32 end) const; - - /** - * Returns true if this set contains one or more of the characters - * and strings of the given set. - * @param s The set to be checked for containment - * @return true if the condition is met - * @stable ICU 2.4 - */ - inline UBool containsSome(const UnicodeSet& s) const; - - /** - * Returns true if this set contains one or more of the characters - * of the given string. - * @param s string containing characters to be checked for containment - * @return true if the condition is met - * @stable ICU 2.4 - */ - inline UBool containsSome(const UnicodeString& s) const; - - /** - * Returns the length of the initial substring of the input string which - * consists only of characters and strings that are contained in this set - * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), - * or only of characters and strings that are not contained - * in this set (USET_SPAN_NOT_CONTAINED). - * See USetSpanCondition for details. - * Similar to the strspn() C library function. - * Unpaired surrogates are treated according to contains() of their surrogate code points. - * This function works faster with a frozen set and with a non-negative string length argument. - * @param s start of the string - * @param length of the string; can be -1 for NUL-terminated - * @param spanCondition specifies the containment condition - * @return the length of the initial substring according to the spanCondition; - * 0 if the start of the string does not fit the spanCondition - * @stable ICU 3.8 - * @see USetSpanCondition - */ - int32_t span(const UChar *s, int32_t length, USetSpanCondition spanCondition) const; - - /** - * Returns the end of the substring of the input string according to the USetSpanCondition. - * Same as start+span(s.getBuffer()+start, s.length()-start, spanCondition) - * after pinning start to 0<=start<=s.length(). - * @param s the string - * @param start the start index in the string for the span operation - * @param spanCondition specifies the containment condition - * @return the exclusive end of the substring according to the spanCondition; - * the substring s.tempSubStringBetween(start, end) fulfills the spanCondition - * @stable ICU 4.4 - * @see USetSpanCondition - */ - inline int32_t span(const UnicodeString &s, int32_t start, USetSpanCondition spanCondition) const; - - /** - * Returns the start of the trailing substring of the input string which - * consists only of characters and strings that are contained in this set - * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), - * or only of characters and strings that are not contained - * in this set (USET_SPAN_NOT_CONTAINED). - * See USetSpanCondition for details. - * Unpaired surrogates are treated according to contains() of their surrogate code points. - * This function works faster with a frozen set and with a non-negative string length argument. - * @param s start of the string - * @param length of the string; can be -1 for NUL-terminated - * @param spanCondition specifies the containment condition - * @return the start of the trailing substring according to the spanCondition; - * the string length if the end of the string does not fit the spanCondition - * @stable ICU 3.8 - * @see USetSpanCondition - */ - int32_t spanBack(const UChar *s, int32_t length, USetSpanCondition spanCondition) const; - - /** - * Returns the start of the substring of the input string according to the USetSpanCondition. - * Same as spanBack(s.getBuffer(), limit, spanCondition) - * after pinning limit to 0<=end<=s.length(). - * @param s the string - * @param limit the exclusive-end index in the string for the span operation - * (use s.length() or INT32_MAX for spanning back from the end of the string) - * @param spanCondition specifies the containment condition - * @return the start of the substring according to the spanCondition; - * the substring s.tempSubStringBetween(start, limit) fulfills the spanCondition - * @stable ICU 4.4 - * @see USetSpanCondition - */ - inline int32_t spanBack(const UnicodeString &s, int32_t limit, USetSpanCondition spanCondition) const; - - /** - * Returns the length of the initial substring of the input string which - * consists only of characters and strings that are contained in this set - * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), - * or only of characters and strings that are not contained - * in this set (USET_SPAN_NOT_CONTAINED). - * See USetSpanCondition for details. - * Similar to the strspn() C library function. - * Malformed byte sequences are treated according to contains(0xfffd). - * This function works faster with a frozen set and with a non-negative string length argument. - * @param s start of the string (UTF-8) - * @param length of the string; can be -1 for NUL-terminated - * @param spanCondition specifies the containment condition - * @return the length of the initial substring according to the spanCondition; - * 0 if the start of the string does not fit the spanCondition - * @stable ICU 3.8 - * @see USetSpanCondition - */ - int32_t spanUTF8(const char *s, int32_t length, USetSpanCondition spanCondition) const; - - /** - * Returns the start of the trailing substring of the input string which - * consists only of characters and strings that are contained in this set - * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), - * or only of characters and strings that are not contained - * in this set (USET_SPAN_NOT_CONTAINED). - * See USetSpanCondition for details. - * Malformed byte sequences are treated according to contains(0xfffd). - * This function works faster with a frozen set and with a non-negative string length argument. - * @param s start of the string (UTF-8) - * @param length of the string; can be -1 for NUL-terminated - * @param spanCondition specifies the containment condition - * @return the start of the trailing substring according to the spanCondition; - * the string length if the end of the string does not fit the spanCondition - * @stable ICU 3.8 - * @see USetSpanCondition - */ - int32_t spanBackUTF8(const char *s, int32_t length, USetSpanCondition spanCondition) const; - - /** - * Implement UnicodeMatcher::matches() - * @stable ICU 2.4 - */ - virtual UMatchDegree matches(const Replaceable& text, - int32_t& offset, - int32_t limit, - UBool incremental); - -private: - /** - * Returns the longest match for s in text at the given position. - * If limit > start then match forward from start+1 to limit - * matching all characters except s.charAt(0). If limit < start, - * go backward starting from start-1 matching all characters - * except s.charAt(s.length()-1). This method assumes that the - * first character, text.charAt(start), matches s, so it does not - * check it. - * @param text the text to match - * @param start the first character to match. In the forward - * direction, text.charAt(start) is matched against s.charAt(0). - * In the reverse direction, it is matched against - * s.charAt(s.length()-1). - * @param limit the limit offset for matching, either last+1 in - * the forward direction, or last-1 in the reverse direction, - * where last is the index of the last character to match. - * @param s - * @return If part of s matches up to the limit, return |limit - - * start|. If all of s matches before reaching the limit, return - * s.length(). If there is a mismatch between s and text, return - * 0 - */ - static int32_t matchRest(const Replaceable& text, - int32_t start, int32_t limit, - const UnicodeString& s); - - /** - * Returns the smallest value i such that c < list[i]. Caller - * must ensure that c is a legal value or this method will enter - * an infinite loop. This method performs a binary search. - * @param c a character in the range MIN_VALUE..MAX_VALUE - * inclusive - * @return the smallest integer i in the range 0..len-1, - * inclusive, such that c < list[i] - */ - int32_t findCodePoint(UChar32 c) const; - -public: - - /** - * Implementation of UnicodeMatcher API. Union the set of all - * characters that may be matched by this object into the given - * set. - * @param toUnionTo the set into which to union the source characters - * @stable ICU 2.4 - */ - virtual void addMatchSetTo(UnicodeSet& toUnionTo) const; - - /** - * Returns the index of the given character within this set, where - * the set is ordered by ascending code point. If the character - * is not in this set, return -1. The inverse of this method is - * charAt(). - * @return an index from 0..size()-1, or -1 - * @stable ICU 2.4 - */ - int32_t indexOf(UChar32 c) const; - - /** - * Returns the character at the given index within this set, where - * the set is ordered by ascending code point. If the index is - * out of range, return (UChar32)-1. The inverse of this method is - * indexOf(). - * @param index an index from 0..size()-1 - * @return the character at the given index, or (UChar32)-1. - * @stable ICU 2.4 - */ - UChar32 charAt(int32_t index) const; - - /** - * Adds the specified range to this set if it is not already - * present. If this set already contains the specified range, - * the call leaves this set unchanged. If end > start - * then an empty range is added, leaving the set unchanged. - * This is equivalent to a boolean logic OR, or a set UNION. - * A frozen set will not be modified. - * - * @param start first character, inclusive, of range to be added - * to this set. - * @param end last character, inclusive, of range to be added - * to this set. - * @stable ICU 2.0 - */ - virtual UnicodeSet& add(UChar32 start, UChar32 end); - - /** - * Adds the specified character to this set if it is not already - * present. If this set already contains the specified character, - * the call leaves this set unchanged. - * A frozen set will not be modified. - * @stable ICU 2.0 - */ - UnicodeSet& add(UChar32 c); - - /** - * Adds the specified multicharacter to this set if it is not already - * present. If this set already contains the multicharacter, - * the call leaves this set unchanged. - * Thus "ch" => {"ch"} - *
Warning: you cannot add an empty string ("") to a UnicodeSet. - * A frozen set will not be modified. - * @param s the source string - * @return this object, for chaining - * @stable ICU 2.4 - */ - UnicodeSet& add(const UnicodeString& s); - - private: - /** - * @return a code point IF the string consists of a single one. - * otherwise returns -1. - * @param s string to test - */ - static int32_t getSingleCP(const UnicodeString& s); - - void _add(const UnicodeString& s); - - public: - /** - * Adds each of the characters in this string to the set. Thus "ch" => {"c", "h"} - * If this set already any particular character, it has no effect on that character. - * A frozen set will not be modified. - * @param s the source string - * @return this object, for chaining - * @stable ICU 2.4 - */ - UnicodeSet& addAll(const UnicodeString& s); - - /** - * Retains EACH of the characters in this string. Note: "ch" == {"c", "h"} - * If this set already any particular character, it has no effect on that character. - * A frozen set will not be modified. - * @param s the source string - * @return this object, for chaining - * @stable ICU 2.4 - */ - UnicodeSet& retainAll(const UnicodeString& s); - - /** - * Complement EACH of the characters in this string. Note: "ch" == {"c", "h"} - * If this set already any particular character, it has no effect on that character. - * A frozen set will not be modified. - * @param s the source string - * @return this object, for chaining - * @stable ICU 2.4 - */ - UnicodeSet& complementAll(const UnicodeString& s); - - /** - * Remove EACH of the characters in this string. Note: "ch" == {"c", "h"} - * If this set already any particular character, it has no effect on that character. - * A frozen set will not be modified. - * @param s the source string - * @return this object, for chaining - * @stable ICU 2.4 - */ - UnicodeSet& removeAll(const UnicodeString& s); - - /** - * Makes a set from a multicharacter string. Thus "ch" => {"ch"} - *
Warning: you cannot add an empty string ("") to a UnicodeSet. - * @param s the source string - * @return a newly created set containing the given string. - * The caller owns the return object and is responsible for deleting it. - * @stable ICU 2.4 - */ - static UnicodeSet* U_EXPORT2 createFrom(const UnicodeString& s); - - - /** - * Makes a set from each of the characters in the string. Thus "ch" => {"c", "h"} - * @param s the source string - * @return a newly created set containing the given characters - * The caller owns the return object and is responsible for deleting it. - * @stable ICU 2.4 - */ - static UnicodeSet* U_EXPORT2 createFromAll(const UnicodeString& s); - - /** - * Retain only the elements in this set that are contained in the - * specified range. If end > start then an empty range is - * retained, leaving the set empty. This is equivalent to - * a boolean logic AND, or a set INTERSECTION. - * A frozen set will not be modified. - * - * @param start first character, inclusive, of range to be retained - * to this set. - * @param end last character, inclusive, of range to be retained - * to this set. - * @stable ICU 2.0 - */ - virtual UnicodeSet& retain(UChar32 start, UChar32 end); - - - /** - * Retain the specified character from this set if it is present. - * A frozen set will not be modified. - * @stable ICU 2.0 - */ - UnicodeSet& retain(UChar32 c); - - /** - * Removes the specified range from this set if it is present. - * The set will not contain the specified range once the call - * returns. If end > start then an empty range is - * removed, leaving the set unchanged. - * A frozen set will not be modified. - * - * @param start first character, inclusive, of range to be removed - * from this set. - * @param end last character, inclusive, of range to be removed - * from this set. - * @stable ICU 2.0 - */ - virtual UnicodeSet& remove(UChar32 start, UChar32 end); - - /** - * Removes the specified character from this set if it is present. - * The set will not contain the specified range once the call - * returns. - * A frozen set will not be modified. - * @stable ICU 2.0 - */ - UnicodeSet& remove(UChar32 c); - - /** - * Removes the specified string from this set if it is present. - * The set will not contain the specified character once the call - * returns. - * A frozen set will not be modified. - * @param s the source string - * @return this object, for chaining - * @stable ICU 2.4 - */ - UnicodeSet& remove(const UnicodeString& s); - - /** - * Inverts this set. This operation modifies this set so that - * its value is its complement. This is equivalent to - * complement(MIN_VALUE, MAX_VALUE). - * A frozen set will not be modified. - * @stable ICU 2.0 - */ - virtual UnicodeSet& complement(void); - - /** - * Complements the specified range in this set. Any character in - * the range will be removed if it is in this set, or will be - * added if it is not in this set. If end > start - * then an empty range is complemented, leaving the set unchanged. - * This is equivalent to a boolean logic XOR. - * A frozen set will not be modified. - * - * @param start first character, inclusive, of range to be removed - * from this set. - * @param end last character, inclusive, of range to be removed - * from this set. - * @stable ICU 2.0 - */ - virtual UnicodeSet& complement(UChar32 start, UChar32 end); - - /** - * Complements the specified character in this set. The character - * will be removed if it is in this set, or will be added if it is - * not in this set. - * A frozen set will not be modified. - * @stable ICU 2.0 - */ - UnicodeSet& complement(UChar32 c); - - /** - * Complement the specified string in this set. - * The set will not contain the specified string once the call - * returns. - *
Warning: you cannot add an empty string ("") to a UnicodeSet. - * A frozen set will not be modified. - * @param s the string to complement - * @return this object, for chaining - * @stable ICU 2.4 - */ - UnicodeSet& complement(const UnicodeString& s); - - /** - * Adds all of the elements in the specified set to this set if - * they're not already present. This operation effectively - * modifies this set so that its value is the union of the two - * sets. The behavior of this operation is unspecified if the specified - * collection is modified while the operation is in progress. - * A frozen set will not be modified. - * - * @param c set whose elements are to be added to this set. - * @see #add(UChar32, UChar32) - * @stable ICU 2.0 - */ - virtual UnicodeSet& addAll(const UnicodeSet& c); - - /** - * Retains only the elements in this set that are contained in the - * specified set. In other words, removes from this set all of - * its elements that are not contained in the specified set. This - * operation effectively modifies this set so that its value is - * the intersection of the two sets. - * A frozen set will not be modified. - * - * @param c set that defines which elements this set will retain. - * @stable ICU 2.0 - */ - virtual UnicodeSet& retainAll(const UnicodeSet& c); - - /** - * Removes from this set all of its elements that are contained in the - * specified set. This operation effectively modifies this - * set so that its value is the asymmetric set difference of - * the two sets. - * A frozen set will not be modified. - * - * @param c set that defines which elements will be removed from - * this set. - * @stable ICU 2.0 - */ - virtual UnicodeSet& removeAll(const UnicodeSet& c); - - /** - * Complements in this set all elements contained in the specified - * set. Any character in the other set will be removed if it is - * in this set, or will be added if it is not in this set. - * A frozen set will not be modified. - * - * @param c set that defines which elements will be xor'ed from - * this set. - * @stable ICU 2.4 - */ - virtual UnicodeSet& complementAll(const UnicodeSet& c); - - /** - * Removes all of the elements from this set. This set will be - * empty after this call returns. - * A frozen set will not be modified. - * @stable ICU 2.0 - */ - virtual UnicodeSet& clear(void); - - /** - * Close this set over the given attribute. For the attribute - * USET_CASE, the result is to modify this set so that: - * - * 1. For each character or string 'a' in this set, all strings or - * characters 'b' such that foldCase(a) == foldCase(b) are added - * to this set. - * - * 2. For each string 'e' in the resulting set, if e != - * foldCase(e), 'e' will be removed. - * - * Example: [aq\\u00DF{Bc}{bC}{Fi}] => [aAqQ\\u00DF\\uFB01{ss}{bc}{fi}] - * - * (Here foldCase(x) refers to the operation u_strFoldCase, and a - * == b denotes that the contents are the same, not pointer - * comparison.) - * - * A frozen set will not be modified. - * - * @param attribute bitmask for attributes to close over. - * Currently only the USET_CASE bit is supported. Any undefined bits - * are ignored. - * @return a reference to this set. - * @stable ICU 4.2 - */ - UnicodeSet& closeOver(int32_t attribute); - - /** - * Remove all strings from this set. - * - * @return a reference to this set. - * @stable ICU 4.2 - */ - virtual UnicodeSet &removeAllStrings(); - - /** - * Iteration method that returns the number of ranges contained in - * this set. - * @see #getRangeStart - * @see #getRangeEnd - * @stable ICU 2.4 - */ - virtual int32_t getRangeCount(void) const; - - /** - * Iteration method that returns the first character in the - * specified range of this set. - * @see #getRangeCount - * @see #getRangeEnd - * @stable ICU 2.4 - */ - virtual UChar32 getRangeStart(int32_t index) const; - - /** - * Iteration method that returns the last character in the - * specified range of this set. - * @see #getRangeStart - * @see #getRangeEnd - * @stable ICU 2.4 - */ - virtual UChar32 getRangeEnd(int32_t index) const; - - /** - * Serializes this set into an array of 16-bit integers. Serialization - * (currently) only records the characters in the set; multicharacter - * strings are ignored. - * - * The array has following format (each line is one 16-bit - * integer): - * - * length = (n+2*m) | (m!=0?0x8000:0) - * bmpLength = n; present if m!=0 - * bmp[0] - * bmp[1] - * ... - * bmp[n-1] - * supp-high[0] - * supp-low[0] - * supp-high[1] - * supp-low[1] - * ... - * supp-high[m-1] - * supp-low[m-1] - * - * The array starts with a header. After the header are n bmp - * code points, then m supplementary code points. Either n or m - * or both may be zero. n+2*m is always <= 0x7FFF. - * - * If there are no supplementary characters (if m==0) then the - * header is one 16-bit integer, 'length', with value n. - * - * If there are supplementary characters (if m!=0) then the header - * is two 16-bit integers. The first, 'length', has value - * (n+2*m)|0x8000. The second, 'bmpLength', has value n. - * - * After the header the code points are stored in ascending order. - * Supplementary code points are stored as most significant 16 - * bits followed by least significant 16 bits. - * - * @param dest pointer to buffer of destCapacity 16-bit integers. - * May be NULL only if destCapacity is zero. - * @param destCapacity size of dest, or zero. Must not be negative. - * @param ec error code. Will be set to U_INDEX_OUTOFBOUNDS_ERROR - * if n+2*m > 0x7FFF. Will be set to U_BUFFER_OVERFLOW_ERROR if - * n+2*m+(m!=0?2:1) > destCapacity. - * @return the total length of the serialized format, including - * the header, that is, n+2*m+(m!=0?2:1), or 0 on error other - * than U_BUFFER_OVERFLOW_ERROR. - * @stable ICU 2.4 - */ - int32_t serialize(uint16_t *dest, int32_t destCapacity, UErrorCode& ec) const; - - /** - * Reallocate this objects internal structures to take up the least - * possible space, without changing this object's value. - * A frozen set will not be modified. - * @stable ICU 2.4 - */ - virtual UnicodeSet& compact(); - - /** - * Return the class ID for this class. This is useful only for - * comparing to a return value from getDynamicClassID(). For example: - *

-     * .      Base* polymorphic_pointer = createPolymorphicObject();
-     * .      if (polymorphic_pointer->getDynamicClassID() ==
-     * .          Derived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 2.0 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Implement UnicodeFunctor API. - * - * @return The class ID for this object. All objects of a given - * class have the same class ID. Objects of other classes have - * different class IDs. - * @stable ICU 2.4 - */ - virtual UClassID getDynamicClassID(void) const; - -private: - - // Private API for the USet API - - friend class USetAccess; - - int32_t getStringCount() const; - - const UnicodeString* getString(int32_t index) const; - - //---------------------------------------------------------------- - // RuleBasedTransliterator support - //---------------------------------------------------------------- - -private: - - /** - * Returns true if this set contains any character whose low byte - * is the given value. This is used by RuleBasedTransliterator for - * indexing. - */ - virtual UBool matchesIndexValue(uint8_t v) const; - -private: - friend class RBBIRuleScanner; - - //---------------------------------------------------------------- - // Implementation: Clone as thawed (see ICU4J Freezable) - //---------------------------------------------------------------- - - UnicodeSet(const UnicodeSet& o, UBool /* asThawed */); - - //---------------------------------------------------------------- - // Implementation: Pattern parsing - //---------------------------------------------------------------- - - void applyPatternIgnoreSpace(const UnicodeString& pattern, - ParsePosition& pos, - const SymbolTable* symbols, - UErrorCode& status); - - void applyPattern(RuleCharacterIterator& chars, - const SymbolTable* symbols, - UnicodeString& rebuiltPat, - uint32_t options, - UnicodeSet& (UnicodeSet::*caseClosure)(int32_t attribute), - UErrorCode& ec); - - //---------------------------------------------------------------- - // Implementation: Utility methods - //---------------------------------------------------------------- - - void ensureCapacity(int32_t newLen, UErrorCode& ec); - - void ensureBufferCapacity(int32_t newLen, UErrorCode& ec); - - void swapBuffers(void); - - UBool allocateStrings(UErrorCode &status); - - UnicodeString& _toPattern(UnicodeString& result, - UBool escapeUnprintable) const; - - UnicodeString& _generatePattern(UnicodeString& result, - UBool escapeUnprintable) const; - - static void _appendToPat(UnicodeString& buf, const UnicodeString& s, UBool escapeUnprintable); - - static void _appendToPat(UnicodeString& buf, UChar32 c, UBool escapeUnprintable); - - //---------------------------------------------------------------- - // Implementation: Fundamental operators - //---------------------------------------------------------------- - - void exclusiveOr(const UChar32* other, int32_t otherLen, int8_t polarity); - - void add(const UChar32* other, int32_t otherLen, int8_t polarity); - - void retain(const UChar32* other, int32_t otherLen, int8_t polarity); - - /** - * Return true if the given position, in the given pattern, appears - * to be the start of a property set pattern [:foo:], \\p{foo}, or - * \\P{foo}, or \\N{name}. - */ - static UBool resemblesPropertyPattern(const UnicodeString& pattern, - int32_t pos); - - static UBool resemblesPropertyPattern(RuleCharacterIterator& chars, - int32_t iterOpts); - - /** - * Parse the given property pattern at the given parse position - * and set this UnicodeSet to the result. - * - * The original design document is out of date, but still useful. - * Ignore the property and value names: - * http://source.icu-project.org/repos/icu/icuhtml/trunk/design/unicodeset_properties.html - * - * Recognized syntax: - * - * [:foo:] [:^foo:] - white space not allowed within "[:" or ":]" - * \\p{foo} \\P{foo} - white space not allowed within "\\p" or "\\P" - * \\N{name} - white space not allowed within "\\N" - * - * Other than the above restrictions, Unicode Pattern_White_Space characters are ignored. - * Case is ignored except in "\\p" and "\\P" and "\\N". In 'name' leading - * and trailing space is deleted, and internal runs of whitespace - * are collapsed to a single space. - * - * We support binary properties, enumerated properties, and the - * following non-enumerated properties: - * - * Numeric_Value - * Name - * Unicode_1_Name - * - * @param pattern the pattern string - * @param ppos on entry, the position at which to begin parsing. - * This should be one of the locations marked '^': - * - * [:blah:] \\p{blah} \\P{blah} \\N{name} - * ^ % ^ % ^ % ^ % - * - * On return, the position after the last character parsed, that is, - * the locations marked '%'. If the parse fails, ppos is returned - * unchanged. - * @param ec status - * @return a reference to this. - */ - UnicodeSet& applyPropertyPattern(const UnicodeString& pattern, - ParsePosition& ppos, - UErrorCode &ec); - - void applyPropertyPattern(RuleCharacterIterator& chars, - UnicodeString& rebuiltPat, - UErrorCode& ec); - - friend void U_CALLCONV UnicodeSet_initInclusion(int32_t src, UErrorCode &status); - static const UnicodeSet* getInclusions(int32_t src, UErrorCode &status); - - /** - * A filter that returns TRUE if the given code point should be - * included in the UnicodeSet being constructed. - */ - typedef UBool (*Filter)(UChar32 codePoint, void* context); - - /** - * Given a filter, set this UnicodeSet to the code points - * contained by that filter. The filter MUST be - * property-conformant. That is, if it returns value v for one - * code point, then it must return v for all affiliated code - * points, as defined by the inclusions list. See - * getInclusions(). - * src is a UPropertySource value. - */ - void applyFilter(Filter filter, - void* context, - int32_t src, - UErrorCode &status); - - /** - * Set the new pattern to cache. - */ - void setPattern(const UnicodeString& newPat); - /** - * Release existing cached pattern. - */ - void releasePattern(); - - friend class UnicodeSetIterator; -}; - - - -inline UBool UnicodeSet::operator!=(const UnicodeSet& o) const { - return !operator==(o); -} - -inline UBool UnicodeSet::isFrozen() const { - return (UBool)(bmpSet!=NULL || stringSpan!=NULL); -} - -inline UBool UnicodeSet::containsSome(UChar32 start, UChar32 end) const { - return !containsNone(start, end); -} - -inline UBool UnicodeSet::containsSome(const UnicodeSet& s) const { - return !containsNone(s); -} - -inline UBool UnicodeSet::containsSome(const UnicodeString& s) const { - return !containsNone(s); -} - -inline UBool UnicodeSet::isBogus() const { - return (UBool)(fFlags & kIsBogus); -} - -inline UnicodeSet *UnicodeSet::fromUSet(USet *uset) { - return reinterpret_cast(uset); -} - -inline const UnicodeSet *UnicodeSet::fromUSet(const USet *uset) { - return reinterpret_cast(uset); -} - -inline USet *UnicodeSet::toUSet() { - return reinterpret_cast(this); -} - -inline const USet *UnicodeSet::toUSet() const { - return reinterpret_cast(this); -} - -inline int32_t UnicodeSet::span(const UnicodeString &s, int32_t start, USetSpanCondition spanCondition) const { - int32_t sLength=s.length(); - if(start<0) { - start=0; - } else if(start>sLength) { - start=sLength; - } - return start+span(s.getBuffer()+start, sLength-start, spanCondition); -} - -inline int32_t UnicodeSet::spanBack(const UnicodeString &s, int32_t limit, USetSpanCondition spanCondition) const { - int32_t sLength=s.length(); - if(limit<0) { - limit=0; - } else if(limit>sLength) { - limit=sLength; - } - return spanBack(s.getBuffer(), limit, spanCondition); -} - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/unistr.h b/win32/include/spidermonkey/unicode/unistr.h deleted file mode 100755 index 6f62244a..00000000 --- a/win32/include/spidermonkey/unicode/unistr.h +++ /dev/null @@ -1,4657 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1998-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* -* File unistr.h -* -* Modification History: -* -* Date Name Description -* 09/25/98 stephen Creation. -* 11/11/98 stephen Changed per 11/9 code review. -* 04/20/99 stephen Overhauled per 4/16 code review. -* 11/18/99 aliu Made to inherit from Replaceable. Added method -* handleReplaceBetween(); other methods unchanged. -* 06/25/01 grhoten Remove dependency on iostream. -****************************************************************************** -*/ - -#ifndef UNISTR_H -#define UNISTR_H - -/** - * \file - * \brief C++ API: Unicode String - */ - -#include "unicode/utypes.h" -#include "unicode/rep.h" -#include "unicode/std_string.h" -#include "unicode/stringpiece.h" -#include "unicode/bytestream.h" -#include "unicode/ucasemap.h" - -struct UConverter; // unicode/ucnv.h - -#ifndef U_COMPARE_CODE_POINT_ORDER -/* see also ustring.h and unorm.h */ -/** - * Option bit for u_strCaseCompare, u_strcasecmp, unorm_compare, etc: - * Compare strings in code point order instead of code unit order. - * @stable ICU 2.2 - */ -#define U_COMPARE_CODE_POINT_ORDER 0x8000 -#endif - -#ifndef USTRING_H -/** - * \ingroup ustring_ustrlen - */ -U_STABLE int32_t U_EXPORT2 -u_strlen(const UChar *s); -#endif - -/** - * \def U_STRING_CASE_MAPPER_DEFINED - * @internal - */ -#ifndef U_STRING_CASE_MAPPER_DEFINED -#define U_STRING_CASE_MAPPER_DEFINED - -/** - * Internal string case mapping function type. - * @internal - */ -typedef int32_t U_CALLCONV -UStringCaseMapper(const UCaseMap *csm, - UChar *dest, int32_t destCapacity, - const UChar *src, int32_t srcLength, - UErrorCode *pErrorCode); - -#endif - -U_NAMESPACE_BEGIN - -#if !UCONFIG_NO_BREAK_ITERATION -class BreakIterator; // unicode/brkiter.h -#endif -class Locale; // unicode/locid.h -class StringCharacterIterator; -class UnicodeStringAppendable; // unicode/appendable.h - -/* The include has been moved to unicode/ustream.h */ - -/** - * Constant to be used in the UnicodeString(char *, int32_t, EInvariant) constructor - * which constructs a Unicode string from an invariant-character char * string. - * About invariant characters see utypes.h. - * This constructor has no runtime dependency on conversion code and is - * therefore recommended over ones taking a charset name string - * (where the empty string "" indicates invariant-character conversion). - * - * @stable ICU 3.2 - */ -#define US_INV icu::UnicodeString::kInvariant - -/** - * Unicode String literals in C++. - * Dependent on the platform properties, different UnicodeString - * constructors should be used to create a UnicodeString object from - * a string literal. - * The macros are defined for maximum performance. - * They work only for strings that contain "invariant characters", i.e., - * only latin letters, digits, and some punctuation. - * See utypes.h for details. - * - * The string parameter must be a C string literal. - * The length of the string, not including the terminating - * NUL, must be specified as a constant. - * The U_STRING_DECL macro should be invoked exactly once for one - * such string variable before it is used. - * @stable ICU 2.0 - */ -#if defined(U_DECLARE_UTF16) -# define UNICODE_STRING(cs, _length) icu::UnicodeString(TRUE, (const UChar *)U_DECLARE_UTF16(cs), _length) -#elif U_SIZEOF_WCHAR_T==U_SIZEOF_UCHAR && (U_CHARSET_FAMILY==U_ASCII_FAMILY || (U_SIZEOF_UCHAR == 2 && defined(U_WCHAR_IS_UTF16))) -# define UNICODE_STRING(cs, _length) icu::UnicodeString(TRUE, (const UChar *)L ## cs, _length) -#elif U_SIZEOF_UCHAR==1 && U_CHARSET_FAMILY==U_ASCII_FAMILY -# define UNICODE_STRING(cs, _length) icu::UnicodeString(TRUE, (const UChar *)cs, _length) -#else -# define UNICODE_STRING(cs, _length) icu::UnicodeString(cs, _length, US_INV) -#endif - -/** - * Unicode String literals in C++. - * Dependent on the platform properties, different UnicodeString - * constructors should be used to create a UnicodeString object from - * a string literal. - * The macros are defined for improved performance. - * They work only for strings that contain "invariant characters", i.e., - * only latin letters, digits, and some punctuation. - * See utypes.h for details. - * - * The string parameter must be a C string literal. - * @stable ICU 2.0 - */ -#define UNICODE_STRING_SIMPLE(cs) UNICODE_STRING(cs, -1) - -/** - * \def UNISTR_FROM_CHAR_EXPLICIT - * This can be defined to be empty or "explicit". - * If explicit, then the UnicodeString(UChar) and UnicodeString(UChar32) - * constructors are marked as explicit, preventing their inadvertent use. - * @stable ICU 49 - */ -#ifndef UNISTR_FROM_CHAR_EXPLICIT -# if defined(U_COMBINED_IMPLEMENTATION) || defined(U_COMMON_IMPLEMENTATION) || defined(U_I18N_IMPLEMENTATION) || defined(U_IO_IMPLEMENTATION) - // Auto-"explicit" in ICU library code. -# define UNISTR_FROM_CHAR_EXPLICIT explicit -# else - // Empty by default for source code compatibility. -# define UNISTR_FROM_CHAR_EXPLICIT -# endif -#endif - -/** - * \def UNISTR_FROM_STRING_EXPLICIT - * This can be defined to be empty or "explicit". - * If explicit, then the UnicodeString(const char *) and UnicodeString(const UChar *) - * constructors are marked as explicit, preventing their inadvertent use. - * - * In particular, this helps prevent accidentally depending on ICU conversion code - * by passing a string literal into an API with a const UnicodeString & parameter. - * @stable ICU 49 - */ -#ifndef UNISTR_FROM_STRING_EXPLICIT -# if defined(U_COMBINED_IMPLEMENTATION) || defined(U_COMMON_IMPLEMENTATION) || defined(U_I18N_IMPLEMENTATION) || defined(U_IO_IMPLEMENTATION) - // Auto-"explicit" in ICU library code. -# define UNISTR_FROM_STRING_EXPLICIT explicit -# else - // Empty by default for source code compatibility. -# define UNISTR_FROM_STRING_EXPLICIT -# endif -#endif - -/** - * \def UNISTR_OBJECT_SIZE - * Desired sizeof(UnicodeString) in bytes. - * It should be a multiple of sizeof(pointer) to avoid unusable space for padding. - * The object size may want to be a multiple of 16 bytes, - * which is a common granularity for heap allocation. - * - * Any space inside the object beyond sizeof(vtable pointer) + 2 - * is available for storing short strings inside the object. - * The bigger the object, the longer a string that can be stored inside the object, - * without additional heap allocation. - * - * Depending on a platform's pointer size, pointer alignment requirements, - * and struct padding, the compiler will usually round up sizeof(UnicodeString) - * to 4 * sizeof(pointer) (or 3 * sizeof(pointer) for P128 data models), - * to hold the fields for heap-allocated strings. - * Such a minimum size also ensures that the object is easily large enough - * to hold at least 2 UChars, for one supplementary code point (U16_MAX_LENGTH). - * - * sizeof(UnicodeString) >= 48 should work for all known platforms. - * - * For example, on a 64-bit machine where sizeof(vtable pointer) is 8, - * sizeof(UnicodeString) = 64 would leave space for - * (64 - sizeof(vtable pointer) - 2) / U_SIZEOF_UCHAR = (64 - 8 - 2) / 2 = 27 - * UChars stored inside the object. - * - * The minimum object size on a 64-bit machine would be - * 4 * sizeof(pointer) = 4 * 8 = 32 bytes, - * and the internal buffer would hold up to 11 UChars in that case. - * - * @see U16_MAX_LENGTH - * @stable ICU 56 - */ -#ifndef UNISTR_OBJECT_SIZE -# define UNISTR_OBJECT_SIZE 64 -#endif - -/** - * UnicodeString is a string class that stores Unicode characters directly and provides - * similar functionality as the Java String and StringBuffer/StringBuilder classes. - * It is a concrete implementation of the abstract class Replaceable (for transliteration). - * - * A UnicodeString may also "alias" an external array of characters - * (that is, point to it, rather than own the array) - * whose lifetime must then at least match the lifetime of the aliasing object. - * This aliasing may be preserved when returning a UnicodeString by value, - * depending on the compiler and the function implementation, - * via Return Value Optimization (RVO) or the move assignment operator. - * (However, the copy assignment operator does not preserve aliasing.) - * For details see the description of storage models at the end of the class API docs - * and in the User Guide chapter linked from there. - * - * The UnicodeString class is not suitable for subclassing. - * - *

For an overview of Unicode strings in C and C++ see the - * User Guide Strings chapter.

- * - *

In ICU, a Unicode string consists of 16-bit Unicode code units. - * A Unicode character may be stored with either one code unit - * (the most common case) or with a matched pair of special code units - * ("surrogates"). The data type for code units is UChar. - * For single-character handling, a Unicode character code point is a value - * in the range 0..0x10ffff. ICU uses the UChar32 type for code points.

- * - *

Indexes and offsets into and lengths of strings always count code units, not code points. - * This is the same as with multi-byte char* strings in traditional string handling. - * Operations on partial strings typically do not test for code point boundaries. - * If necessary, the user needs to take care of such boundaries by testing for the code unit - * values or by using functions like - * UnicodeString::getChar32Start() and UnicodeString::getChar32Limit() - * (or, in C, the equivalent macros U16_SET_CP_START() and U16_SET_CP_LIMIT(), see utf.h).

- * - * UnicodeString methods are more lenient with regard to input parameter values - * than other ICU APIs. In particular: - * - If indexes are out of bounds for a UnicodeString object - * (<0 or >length()) then they are "pinned" to the nearest boundary. - * - If primitive string pointer values (e.g., const UChar * or char *) - * for input strings are NULL, then those input string parameters are treated - * as if they pointed to an empty string. - * However, this is not the case for char * parameters for charset names - * or other IDs. - * - Most UnicodeString methods do not take a UErrorCode parameter because - * there are usually very few opportunities for failure other than a shortage - * of memory, error codes in low-level C++ string methods would be inconvenient, - * and the error code as the last parameter (ICU convention) would prevent - * the use of default parameter values. - * Instead, such methods set the UnicodeString into a "bogus" state - * (see isBogus()) if an error occurs. - * - * In string comparisons, two UnicodeString objects that are both "bogus" - * compare equal (to be transitive and prevent endless loops in sorting), - * and a "bogus" string compares less than any non-"bogus" one. - * - * Const UnicodeString methods are thread-safe. Multiple threads can use - * const methods on the same UnicodeString object simultaneously, - * but non-const methods must not be called concurrently (in multiple threads) - * with any other (const or non-const) methods. - * - * Similarly, const UnicodeString & parameters are thread-safe. - * One object may be passed in as such a parameter concurrently in multiple threads. - * This includes the const UnicodeString & parameters for - * copy construction, assignment, and cloning. - * - *

UnicodeString uses several storage methods. - * String contents can be stored inside the UnicodeString object itself, - * in an allocated and shared buffer, or in an outside buffer that is "aliased". - * Most of this is done transparently, but careful aliasing in particular provides - * significant performance improvements. - * Also, the internal buffer is accessible via special functions. - * For details see the - * User Guide Strings chapter.

- * - * @see utf.h - * @see CharacterIterator - * @stable ICU 2.0 - */ -class U_COMMON_API UnicodeString : public Replaceable -{ -public: - - /** - * Constant to be used in the UnicodeString(char *, int32_t, EInvariant) constructor - * which constructs a Unicode string from an invariant-character char * string. - * Use the macro US_INV instead of the full qualification for this value. - * - * @see US_INV - * @stable ICU 3.2 - */ - enum EInvariant { - /** - * @see EInvariant - * @stable ICU 3.2 - */ - kInvariant - }; - - //======================================== - // Read-only operations - //======================================== - - /* Comparison - bitwise only - for international comparison use collation */ - - /** - * Equality operator. Performs only bitwise comparison. - * @param text The UnicodeString to compare to this one. - * @return TRUE if text contains the same characters as this one, - * FALSE otherwise. - * @stable ICU 2.0 - */ - inline UBool operator== (const UnicodeString& text) const; - - /** - * Inequality operator. Performs only bitwise comparison. - * @param text The UnicodeString to compare to this one. - * @return FALSE if text contains the same characters as this one, - * TRUE otherwise. - * @stable ICU 2.0 - */ - inline UBool operator!= (const UnicodeString& text) const; - - /** - * Greater than operator. Performs only bitwise comparison. - * @param text The UnicodeString to compare to this one. - * @return TRUE if the characters in this are bitwise - * greater than the characters in text, FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool operator> (const UnicodeString& text) const; - - /** - * Less than operator. Performs only bitwise comparison. - * @param text The UnicodeString to compare to this one. - * @return TRUE if the characters in this are bitwise - * less than the characters in text, FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool operator< (const UnicodeString& text) const; - - /** - * Greater than or equal operator. Performs only bitwise comparison. - * @param text The UnicodeString to compare to this one. - * @return TRUE if the characters in this are bitwise - * greater than or equal to the characters in text, FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool operator>= (const UnicodeString& text) const; - - /** - * Less than or equal operator. Performs only bitwise comparison. - * @param text The UnicodeString to compare to this one. - * @return TRUE if the characters in this are bitwise - * less than or equal to the characters in text, FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool operator<= (const UnicodeString& text) const; - - /** - * Compare the characters bitwise in this UnicodeString to - * the characters in text. - * @param text The UnicodeString to compare to this one. - * @return The result of bitwise character comparison: 0 if this - * contains the same characters as text, -1 if the characters in - * this are bitwise less than the characters in text, +1 if the - * characters in this are bitwise greater than the characters - * in text. - * @stable ICU 2.0 - */ - inline int8_t compare(const UnicodeString& text) const; - - /** - * Compare the characters bitwise in the range - * [start, start + length) with the characters - * in the entire string text. - * (The parameters "start" and "length" are not applied to the other text "text".) - * @param start the offset at which the compare operation begins - * @param length the number of characters of text to compare. - * @param text the other text to be compared against this string. - * @return The result of bitwise character comparison: 0 if this - * contains the same characters as text, -1 if the characters in - * this are bitwise less than the characters in text, +1 if the - * characters in this are bitwise greater than the characters - * in text. - * @stable ICU 2.0 - */ - inline int8_t compare(int32_t start, - int32_t length, - const UnicodeString& text) const; - - /** - * Compare the characters bitwise in the range - * [start, start + length) with the characters - * in srcText in the range - * [srcStart, srcStart + srcLength). - * @param start the offset at which the compare operation begins - * @param length the number of characters in this to compare. - * @param srcText the text to be compared - * @param srcStart the offset into srcText to start comparison - * @param srcLength the number of characters in src to compare - * @return The result of bitwise character comparison: 0 if this - * contains the same characters as srcText, -1 if the characters in - * this are bitwise less than the characters in srcText, +1 if the - * characters in this are bitwise greater than the characters - * in srcText. - * @stable ICU 2.0 - */ - inline int8_t compare(int32_t start, - int32_t length, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const; - - /** - * Compare the characters bitwise in this UnicodeString with the first - * srcLength characters in srcChars. - * @param srcChars The characters to compare to this UnicodeString. - * @param srcLength the number of characters in srcChars to compare - * @return The result of bitwise character comparison: 0 if this - * contains the same characters as srcChars, -1 if the characters in - * this are bitwise less than the characters in srcChars, +1 if the - * characters in this are bitwise greater than the characters - * in srcChars. - * @stable ICU 2.0 - */ - inline int8_t compare(const UChar *srcChars, - int32_t srcLength) const; - - /** - * Compare the characters bitwise in the range - * [start, start + length) with the first - * length characters in srcChars - * @param start the offset at which the compare operation begins - * @param length the number of characters to compare. - * @param srcChars the characters to be compared - * @return The result of bitwise character comparison: 0 if this - * contains the same characters as srcChars, -1 if the characters in - * this are bitwise less than the characters in srcChars, +1 if the - * characters in this are bitwise greater than the characters - * in srcChars. - * @stable ICU 2.0 - */ - inline int8_t compare(int32_t start, - int32_t length, - const UChar *srcChars) const; - - /** - * Compare the characters bitwise in the range - * [start, start + length) with the characters - * in srcChars in the range - * [srcStart, srcStart + srcLength). - * @param start the offset at which the compare operation begins - * @param length the number of characters in this to compare - * @param srcChars the characters to be compared - * @param srcStart the offset into srcChars to start comparison - * @param srcLength the number of characters in srcChars to compare - * @return The result of bitwise character comparison: 0 if this - * contains the same characters as srcChars, -1 if the characters in - * this are bitwise less than the characters in srcChars, +1 if the - * characters in this are bitwise greater than the characters - * in srcChars. - * @stable ICU 2.0 - */ - inline int8_t compare(int32_t start, - int32_t length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) const; - - /** - * Compare the characters bitwise in the range - * [start, limit) with the characters - * in srcText in the range - * [srcStart, srcLimit). - * @param start the offset at which the compare operation begins - * @param limit the offset immediately following the compare operation - * @param srcText the text to be compared - * @param srcStart the offset into srcText to start comparison - * @param srcLimit the offset into srcText to limit comparison - * @return The result of bitwise character comparison: 0 if this - * contains the same characters as srcText, -1 if the characters in - * this are bitwise less than the characters in srcText, +1 if the - * characters in this are bitwise greater than the characters - * in srcText. - * @stable ICU 2.0 - */ - inline int8_t compareBetween(int32_t start, - int32_t limit, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLimit) const; - - /** - * Compare two Unicode strings in code point order. - * The result may be different from the results of compare(), operator<, etc. - * if supplementary characters are present: - * - * In UTF-16, supplementary characters (with code points U+10000 and above) are - * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff, - * which means that they compare as less than some other BMP characters like U+feff. - * This function compares Unicode strings in code point order. - * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined. - * - * @param text Another string to compare this one to. - * @return a negative/zero/positive integer corresponding to whether - * this string is less than/equal to/greater than the second one - * in code point order - * @stable ICU 2.0 - */ - inline int8_t compareCodePointOrder(const UnicodeString& text) const; - - /** - * Compare two Unicode strings in code point order. - * The result may be different from the results of compare(), operator<, etc. - * if supplementary characters are present: - * - * In UTF-16, supplementary characters (with code points U+10000 and above) are - * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff, - * which means that they compare as less than some other BMP characters like U+feff. - * This function compares Unicode strings in code point order. - * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined. - * - * @param start The start offset in this string at which the compare operation begins. - * @param length The number of code units from this string to compare. - * @param srcText Another string to compare this one to. - * @return a negative/zero/positive integer corresponding to whether - * this string is less than/equal to/greater than the second one - * in code point order - * @stable ICU 2.0 - */ - inline int8_t compareCodePointOrder(int32_t start, - int32_t length, - const UnicodeString& srcText) const; - - /** - * Compare two Unicode strings in code point order. - * The result may be different from the results of compare(), operator<, etc. - * if supplementary characters are present: - * - * In UTF-16, supplementary characters (with code points U+10000 and above) are - * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff, - * which means that they compare as less than some other BMP characters like U+feff. - * This function compares Unicode strings in code point order. - * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined. - * - * @param start The start offset in this string at which the compare operation begins. - * @param length The number of code units from this string to compare. - * @param srcText Another string to compare this one to. - * @param srcStart The start offset in that string at which the compare operation begins. - * @param srcLength The number of code units from that string to compare. - * @return a negative/zero/positive integer corresponding to whether - * this string is less than/equal to/greater than the second one - * in code point order - * @stable ICU 2.0 - */ - inline int8_t compareCodePointOrder(int32_t start, - int32_t length, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const; - - /** - * Compare two Unicode strings in code point order. - * The result may be different from the results of compare(), operator<, etc. - * if supplementary characters are present: - * - * In UTF-16, supplementary characters (with code points U+10000 and above) are - * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff, - * which means that they compare as less than some other BMP characters like U+feff. - * This function compares Unicode strings in code point order. - * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined. - * - * @param srcChars A pointer to another string to compare this one to. - * @param srcLength The number of code units from that string to compare. - * @return a negative/zero/positive integer corresponding to whether - * this string is less than/equal to/greater than the second one - * in code point order - * @stable ICU 2.0 - */ - inline int8_t compareCodePointOrder(const UChar *srcChars, - int32_t srcLength) const; - - /** - * Compare two Unicode strings in code point order. - * The result may be different from the results of compare(), operator<, etc. - * if supplementary characters are present: - * - * In UTF-16, supplementary characters (with code points U+10000 and above) are - * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff, - * which means that they compare as less than some other BMP characters like U+feff. - * This function compares Unicode strings in code point order. - * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined. - * - * @param start The start offset in this string at which the compare operation begins. - * @param length The number of code units from this string to compare. - * @param srcChars A pointer to another string to compare this one to. - * @return a negative/zero/positive integer corresponding to whether - * this string is less than/equal to/greater than the second one - * in code point order - * @stable ICU 2.0 - */ - inline int8_t compareCodePointOrder(int32_t start, - int32_t length, - const UChar *srcChars) const; - - /** - * Compare two Unicode strings in code point order. - * The result may be different from the results of compare(), operator<, etc. - * if supplementary characters are present: - * - * In UTF-16, supplementary characters (with code points U+10000 and above) are - * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff, - * which means that they compare as less than some other BMP characters like U+feff. - * This function compares Unicode strings in code point order. - * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined. - * - * @param start The start offset in this string at which the compare operation begins. - * @param length The number of code units from this string to compare. - * @param srcChars A pointer to another string to compare this one to. - * @param srcStart The start offset in that string at which the compare operation begins. - * @param srcLength The number of code units from that string to compare. - * @return a negative/zero/positive integer corresponding to whether - * this string is less than/equal to/greater than the second one - * in code point order - * @stable ICU 2.0 - */ - inline int8_t compareCodePointOrder(int32_t start, - int32_t length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) const; - - /** - * Compare two Unicode strings in code point order. - * The result may be different from the results of compare(), operator<, etc. - * if supplementary characters are present: - * - * In UTF-16, supplementary characters (with code points U+10000 and above) are - * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff, - * which means that they compare as less than some other BMP characters like U+feff. - * This function compares Unicode strings in code point order. - * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined. - * - * @param start The start offset in this string at which the compare operation begins. - * @param limit The offset after the last code unit from this string to compare. - * @param srcText Another string to compare this one to. - * @param srcStart The start offset in that string at which the compare operation begins. - * @param srcLimit The offset after the last code unit from that string to compare. - * @return a negative/zero/positive integer corresponding to whether - * this string is less than/equal to/greater than the second one - * in code point order - * @stable ICU 2.0 - */ - inline int8_t compareCodePointOrderBetween(int32_t start, - int32_t limit, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLimit) const; - - /** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to this->foldCase(options).compare(text.foldCase(options)). - * - * @param text Another string to compare this one to. - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @return A negative, zero, or positive integer indicating the comparison result. - * @stable ICU 2.0 - */ - inline int8_t caseCompare(const UnicodeString& text, uint32_t options) const; - - /** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to this->foldCase(options).compare(srcText.foldCase(options)). - * - * @param start The start offset in this string at which the compare operation begins. - * @param length The number of code units from this string to compare. - * @param srcText Another string to compare this one to. - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @return A negative, zero, or positive integer indicating the comparison result. - * @stable ICU 2.0 - */ - inline int8_t caseCompare(int32_t start, - int32_t length, - const UnicodeString& srcText, - uint32_t options) const; - - /** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to this->foldCase(options).compare(srcText.foldCase(options)). - * - * @param start The start offset in this string at which the compare operation begins. - * @param length The number of code units from this string to compare. - * @param srcText Another string to compare this one to. - * @param srcStart The start offset in that string at which the compare operation begins. - * @param srcLength The number of code units from that string to compare. - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @return A negative, zero, or positive integer indicating the comparison result. - * @stable ICU 2.0 - */ - inline int8_t caseCompare(int32_t start, - int32_t length, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength, - uint32_t options) const; - - /** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to this->foldCase(options).compare(srcChars.foldCase(options)). - * - * @param srcChars A pointer to another string to compare this one to. - * @param srcLength The number of code units from that string to compare. - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @return A negative, zero, or positive integer indicating the comparison result. - * @stable ICU 2.0 - */ - inline int8_t caseCompare(const UChar *srcChars, - int32_t srcLength, - uint32_t options) const; - - /** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to this->foldCase(options).compare(srcChars.foldCase(options)). - * - * @param start The start offset in this string at which the compare operation begins. - * @param length The number of code units from this string to compare. - * @param srcChars A pointer to another string to compare this one to. - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @return A negative, zero, or positive integer indicating the comparison result. - * @stable ICU 2.0 - */ - inline int8_t caseCompare(int32_t start, - int32_t length, - const UChar *srcChars, - uint32_t options) const; - - /** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to this->foldCase(options).compare(srcChars.foldCase(options)). - * - * @param start The start offset in this string at which the compare operation begins. - * @param length The number of code units from this string to compare. - * @param srcChars A pointer to another string to compare this one to. - * @param srcStart The start offset in that string at which the compare operation begins. - * @param srcLength The number of code units from that string to compare. - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @return A negative, zero, or positive integer indicating the comparison result. - * @stable ICU 2.0 - */ - inline int8_t caseCompare(int32_t start, - int32_t length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength, - uint32_t options) const; - - /** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to this->foldCase(options).compareBetween(text.foldCase(options)). - * - * @param start The start offset in this string at which the compare operation begins. - * @param limit The offset after the last code unit from this string to compare. - * @param srcText Another string to compare this one to. - * @param srcStart The start offset in that string at which the compare operation begins. - * @param srcLimit The offset after the last code unit from that string to compare. - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @return A negative, zero, or positive integer indicating the comparison result. - * @stable ICU 2.0 - */ - inline int8_t caseCompareBetween(int32_t start, - int32_t limit, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLimit, - uint32_t options) const; - - /** - * Determine if this starts with the characters in text - * @param text The text to match. - * @return TRUE if this starts with the characters in text, - * FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool startsWith(const UnicodeString& text) const; - - /** - * Determine if this starts with the characters in srcText - * in the range [srcStart, srcStart + srcLength). - * @param srcText The text to match. - * @param srcStart the offset into srcText to start matching - * @param srcLength the number of characters in srcText to match - * @return TRUE if this starts with the characters in text, - * FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool startsWith(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const; - - /** - * Determine if this starts with the characters in srcChars - * @param srcChars The characters to match. - * @param srcLength the number of characters in srcChars - * @return TRUE if this starts with the characters in srcChars, - * FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool startsWith(const UChar *srcChars, - int32_t srcLength) const; - - /** - * Determine if this ends with the characters in srcChars - * in the range [srcStart, srcStart + srcLength). - * @param srcChars The characters to match. - * @param srcStart the offset into srcText to start matching - * @param srcLength the number of characters in srcChars to match - * @return TRUE if this ends with the characters in srcChars, FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool startsWith(const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) const; - - /** - * Determine if this ends with the characters in text - * @param text The text to match. - * @return TRUE if this ends with the characters in text, - * FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool endsWith(const UnicodeString& text) const; - - /** - * Determine if this ends with the characters in srcText - * in the range [srcStart, srcStart + srcLength). - * @param srcText The text to match. - * @param srcStart the offset into srcText to start matching - * @param srcLength the number of characters in srcText to match - * @return TRUE if this ends with the characters in text, - * FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool endsWith(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const; - - /** - * Determine if this ends with the characters in srcChars - * @param srcChars The characters to match. - * @param srcLength the number of characters in srcChars - * @return TRUE if this ends with the characters in srcChars, - * FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool endsWith(const UChar *srcChars, - int32_t srcLength) const; - - /** - * Determine if this ends with the characters in srcChars - * in the range [srcStart, srcStart + srcLength). - * @param srcChars The characters to match. - * @param srcStart the offset into srcText to start matching - * @param srcLength the number of characters in srcChars to match - * @return TRUE if this ends with the characters in srcChars, - * FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool endsWith(const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) const; - - - /* Searching - bitwise only */ - - /** - * Locate in this the first occurrence of the characters in text, - * using bitwise comparison. - * @param text The text to search for. - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(const UnicodeString& text) const; - - /** - * Locate in this the first occurrence of the characters in text - * starting at offset start, using bitwise comparison. - * @param text The text to search for. - * @param start The offset at which searching will start. - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(const UnicodeString& text, - int32_t start) const; - - /** - * Locate in this the first occurrence in the range - * [start, start + length) of the characters - * in text, using bitwise comparison. - * @param text The text to search for. - * @param start The offset at which searching will start. - * @param length The number of characters to search - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(const UnicodeString& text, - int32_t start, - int32_t length) const; - - /** - * Locate in this the first occurrence in the range - * [start, start + length) of the characters - * in srcText in the range - * [srcStart, srcStart + srcLength), - * using bitwise comparison. - * @param srcText The text to search for. - * @param srcStart the offset into srcText at which - * to start matching - * @param srcLength the number of characters in srcText to match - * @param start the offset into this at which to start matching - * @param length the number of characters in this to search - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength, - int32_t start, - int32_t length) const; - - /** - * Locate in this the first occurrence of the characters in - * srcChars - * starting at offset start, using bitwise comparison. - * @param srcChars The text to search for. - * @param srcLength the number of characters in srcChars to match - * @param start the offset into this at which to start matching - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(const UChar *srcChars, - int32_t srcLength, - int32_t start) const; - - /** - * Locate in this the first occurrence in the range - * [start, start + length) of the characters - * in srcChars, using bitwise comparison. - * @param srcChars The text to search for. - * @param srcLength the number of characters in srcChars - * @param start The offset at which searching will start. - * @param length The number of characters to search - * @return The offset into this of the start of srcChars, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(const UChar *srcChars, - int32_t srcLength, - int32_t start, - int32_t length) const; - - /** - * Locate in this the first occurrence in the range - * [start, start + length) of the characters - * in srcChars in the range - * [srcStart, srcStart + srcLength), - * using bitwise comparison. - * @param srcChars The text to search for. - * @param srcStart the offset into srcChars at which - * to start matching - * @param srcLength the number of characters in srcChars to match - * @param start the offset into this at which to start matching - * @param length the number of characters in this to search - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - int32_t indexOf(const UChar *srcChars, - int32_t srcStart, - int32_t srcLength, - int32_t start, - int32_t length) const; - - /** - * Locate in this the first occurrence of the BMP code point c, - * using bitwise comparison. - * @param c The code unit to search for. - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(UChar c) const; - - /** - * Locate in this the first occurrence of the code point c, - * using bitwise comparison. - * - * @param c The code point to search for. - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(UChar32 c) const; - - /** - * Locate in this the first occurrence of the BMP code point c, - * starting at offset start, using bitwise comparison. - * @param c The code unit to search for. - * @param start The offset at which searching will start. - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(UChar c, - int32_t start) const; - - /** - * Locate in this the first occurrence of the code point c - * starting at offset start, using bitwise comparison. - * - * @param c The code point to search for. - * @param start The offset at which searching will start. - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(UChar32 c, - int32_t start) const; - - /** - * Locate in this the first occurrence of the BMP code point c - * in the range [start, start + length), - * using bitwise comparison. - * @param c The code unit to search for. - * @param start the offset into this at which to start matching - * @param length the number of characters in this to search - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(UChar c, - int32_t start, - int32_t length) const; - - /** - * Locate in this the first occurrence of the code point c - * in the range [start, start + length), - * using bitwise comparison. - * - * @param c The code point to search for. - * @param start the offset into this at which to start matching - * @param length the number of characters in this to search - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t indexOf(UChar32 c, - int32_t start, - int32_t length) const; - - /** - * Locate in this the last occurrence of the characters in text, - * using bitwise comparison. - * @param text The text to search for. - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(const UnicodeString& text) const; - - /** - * Locate in this the last occurrence of the characters in text - * starting at offset start, using bitwise comparison. - * @param text The text to search for. - * @param start The offset at which searching will start. - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(const UnicodeString& text, - int32_t start) const; - - /** - * Locate in this the last occurrence in the range - * [start, start + length) of the characters - * in text, using bitwise comparison. - * @param text The text to search for. - * @param start The offset at which searching will start. - * @param length The number of characters to search - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(const UnicodeString& text, - int32_t start, - int32_t length) const; - - /** - * Locate in this the last occurrence in the range - * [start, start + length) of the characters - * in srcText in the range - * [srcStart, srcStart + srcLength), - * using bitwise comparison. - * @param srcText The text to search for. - * @param srcStart the offset into srcText at which - * to start matching - * @param srcLength the number of characters in srcText to match - * @param start the offset into this at which to start matching - * @param length the number of characters in this to search - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength, - int32_t start, - int32_t length) const; - - /** - * Locate in this the last occurrence of the characters in srcChars - * starting at offset start, using bitwise comparison. - * @param srcChars The text to search for. - * @param srcLength the number of characters in srcChars to match - * @param start the offset into this at which to start matching - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(const UChar *srcChars, - int32_t srcLength, - int32_t start) const; - - /** - * Locate in this the last occurrence in the range - * [start, start + length) of the characters - * in srcChars, using bitwise comparison. - * @param srcChars The text to search for. - * @param srcLength the number of characters in srcChars - * @param start The offset at which searching will start. - * @param length The number of characters to search - * @return The offset into this of the start of srcChars, - * or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(const UChar *srcChars, - int32_t srcLength, - int32_t start, - int32_t length) const; - - /** - * Locate in this the last occurrence in the range - * [start, start + length) of the characters - * in srcChars in the range - * [srcStart, srcStart + srcLength), - * using bitwise comparison. - * @param srcChars The text to search for. - * @param srcStart the offset into srcChars at which - * to start matching - * @param srcLength the number of characters in srcChars to match - * @param start the offset into this at which to start matching - * @param length the number of characters in this to search - * @return The offset into this of the start of text, - * or -1 if not found. - * @stable ICU 2.0 - */ - int32_t lastIndexOf(const UChar *srcChars, - int32_t srcStart, - int32_t srcLength, - int32_t start, - int32_t length) const; - - /** - * Locate in this the last occurrence of the BMP code point c, - * using bitwise comparison. - * @param c The code unit to search for. - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(UChar c) const; - - /** - * Locate in this the last occurrence of the code point c, - * using bitwise comparison. - * - * @param c The code point to search for. - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(UChar32 c) const; - - /** - * Locate in this the last occurrence of the BMP code point c - * starting at offset start, using bitwise comparison. - * @param c The code unit to search for. - * @param start The offset at which searching will start. - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(UChar c, - int32_t start) const; - - /** - * Locate in this the last occurrence of the code point c - * starting at offset start, using bitwise comparison. - * - * @param c The code point to search for. - * @param start The offset at which searching will start. - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(UChar32 c, - int32_t start) const; - - /** - * Locate in this the last occurrence of the BMP code point c - * in the range [start, start + length), - * using bitwise comparison. - * @param c The code unit to search for. - * @param start the offset into this at which to start matching - * @param length the number of characters in this to search - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(UChar c, - int32_t start, - int32_t length) const; - - /** - * Locate in this the last occurrence of the code point c - * in the range [start, start + length), - * using bitwise comparison. - * - * @param c The code point to search for. - * @param start the offset into this at which to start matching - * @param length the number of characters in this to search - * @return The offset into this of c, or -1 if not found. - * @stable ICU 2.0 - */ - inline int32_t lastIndexOf(UChar32 c, - int32_t start, - int32_t length) const; - - - /* Character access */ - - /** - * Return the code unit at offset offset. - * If the offset is not valid (0..length()-1) then U+ffff is returned. - * @param offset a valid offset into the text - * @return the code unit at offset offset - * or 0xffff if the offset is not valid for this string - * @stable ICU 2.0 - */ - inline UChar charAt(int32_t offset) const; - - /** - * Return the code unit at offset offset. - * If the offset is not valid (0..length()-1) then U+ffff is returned. - * @param offset a valid offset into the text - * @return the code unit at offset offset - * @stable ICU 2.0 - */ - inline UChar operator[] (int32_t offset) const; - - /** - * Return the code point that contains the code unit - * at offset offset. - * If the offset is not valid (0..length()-1) then U+ffff is returned. - * @param offset a valid offset into the text - * that indicates the text offset of any of the code units - * that will be assembled into a code point (21-bit value) and returned - * @return the code point of text at offset - * or 0xffff if the offset is not valid for this string - * @stable ICU 2.0 - */ - UChar32 char32At(int32_t offset) const; - - /** - * Adjust a random-access offset so that - * it points to the beginning of a Unicode character. - * The offset that is passed in points to - * any code unit of a code point, - * while the returned offset will point to the first code unit - * of the same code point. - * In UTF-16, if the input offset points to a second surrogate - * of a surrogate pair, then the returned offset will point - * to the first surrogate. - * @param offset a valid offset into one code point of the text - * @return offset of the first code unit of the same code point - * @see U16_SET_CP_START - * @stable ICU 2.0 - */ - int32_t getChar32Start(int32_t offset) const; - - /** - * Adjust a random-access offset so that - * it points behind a Unicode character. - * The offset that is passed in points behind - * any code unit of a code point, - * while the returned offset will point behind the last code unit - * of the same code point. - * In UTF-16, if the input offset points behind the first surrogate - * (i.e., to the second surrogate) - * of a surrogate pair, then the returned offset will point - * behind the second surrogate (i.e., to the first surrogate). - * @param offset a valid offset after any code unit of a code point of the text - * @return offset of the first code unit after the same code point - * @see U16_SET_CP_LIMIT - * @stable ICU 2.0 - */ - int32_t getChar32Limit(int32_t offset) const; - - /** - * Move the code unit index along the string by delta code points. - * Interpret the input index as a code unit-based offset into the string, - * move the index forward or backward by delta code points, and - * return the resulting index. - * The input index should point to the first code unit of a code point, - * if there is more than one. - * - * Both input and output indexes are code unit-based as for all - * string indexes/offsets in ICU (and other libraries, like MBCS char*). - * If delta<0 then the index is moved backward (toward the start of the string). - * If delta>0 then the index is moved forward (toward the end of the string). - * - * This behaves like CharacterIterator::move32(delta, kCurrent). - * - * Behavior for out-of-bounds indexes: - * moveIndex32 pins the input index to 0..length(), i.e., - * if the input index<0 then it is pinned to 0; - * if it is index>length() then it is pinned to length(). - * Afterwards, the index is moved by delta code points - * forward or backward, - * but no further backward than to 0 and no further forward than to length(). - * The resulting index return value will be in between 0 and length(), inclusively. - * - * Examples: - *
-   * // s has code points 'a' U+10000 'b' U+10ffff U+2029
-   * UnicodeString s=UNICODE_STRING("a\\U00010000b\\U0010ffff\\u2029", 31).unescape();
-   *
-   * // initial index: position of U+10000
-   * int32_t index=1;
-   *
-   * // the following examples will all result in index==4, position of U+10ffff
-   *
-   * // skip 2 code points from some position in the string
-   * index=s.moveIndex32(index, 2); // skips U+10000 and 'b'
-   *
-   * // go to the 3rd code point from the start of s (0-based)
-   * index=s.moveIndex32(0, 3); // skips 'a', U+10000, and 'b'
-   *
-   * // go to the next-to-last code point of s
-   * index=s.moveIndex32(s.length(), -2); // backward-skips U+2029 and U+10ffff
-   * 
- * - * @param index input code unit index - * @param delta (signed) code point count to move the index forward or backward - * in the string - * @return the resulting code unit index - * @stable ICU 2.0 - */ - int32_t moveIndex32(int32_t index, int32_t delta) const; - - /* Substring extraction */ - - /** - * Copy the characters in the range - * [start, start + length) into the array dst, - * beginning at dstStart. - * If the string aliases to dst itself as an external buffer, - * then extract() will not copy the contents. - * - * @param start offset of first character which will be copied into the array - * @param length the number of characters to extract - * @param dst array in which to copy characters. The length of dst - * must be at least (dstStart + length). - * @param dstStart the offset in dst where the first character - * will be extracted - * @stable ICU 2.0 - */ - inline void extract(int32_t start, - int32_t length, - UChar *dst, - int32_t dstStart = 0) const; - - /** - * Copy the contents of the string into dest. - * This is a convenience function that - * checks if there is enough space in dest, - * extracts the entire string if possible, - * and NUL-terminates dest if possible. - * - * If the string fits into dest but cannot be NUL-terminated - * (length()==destCapacity) then the error code is set to U_STRING_NOT_TERMINATED_WARNING. - * If the string itself does not fit into dest - * (length()>destCapacity) then the error code is set to U_BUFFER_OVERFLOW_ERROR. - * - * If the string aliases to dest itself as an external buffer, - * then extract() will not copy the contents. - * - * @param dest Destination string buffer. - * @param destCapacity Number of UChars available at dest. - * @param errorCode ICU error code. - * @return length() - * @stable ICU 2.0 - */ - int32_t - extract(UChar *dest, int32_t destCapacity, - UErrorCode &errorCode) const; - - /** - * Copy the characters in the range - * [start, start + length) into the UnicodeString - * target. - * @param start offset of first character which will be copied - * @param length the number of characters to extract - * @param target UnicodeString into which to copy characters. - * @return A reference to target - * @stable ICU 2.0 - */ - inline void extract(int32_t start, - int32_t length, - UnicodeString& target) const; - - /** - * Copy the characters in the range [start, limit) - * into the array dst, beginning at dstStart. - * @param start offset of first character which will be copied into the array - * @param limit offset immediately following the last character to be copied - * @param dst array in which to copy characters. The length of dst - * must be at least (dstStart + (limit - start)). - * @param dstStart the offset in dst where the first character - * will be extracted - * @stable ICU 2.0 - */ - inline void extractBetween(int32_t start, - int32_t limit, - UChar *dst, - int32_t dstStart = 0) const; - - /** - * Copy the characters in the range [start, limit) - * into the UnicodeString target. Replaceable API. - * @param start offset of first character which will be copied - * @param limit offset immediately following the last character to be copied - * @param target UnicodeString into which to copy characters. - * @return A reference to target - * @stable ICU 2.0 - */ - virtual void extractBetween(int32_t start, - int32_t limit, - UnicodeString& target) const; - - /** - * Copy the characters in the range - * [start, start + startLength) into an array of characters. - * All characters must be invariant (see utypes.h). - * Use US_INV as the last, signature-distinguishing parameter. - * - * This function does not write any more than targetCapacity - * characters but returns the length of the entire output string - * so that one can allocate a larger buffer and call the function again - * if necessary. - * The output string is NUL-terminated if possible. - * - * @param start offset of first character which will be copied - * @param startLength the number of characters to extract - * @param target the target buffer for extraction, can be NULL - * if targetLength is 0 - * @param targetCapacity the length of the target buffer - * @param inv Signature-distinguishing paramater, use US_INV. - * @return the output string length, not including the terminating NUL - * @stable ICU 3.2 - */ - int32_t extract(int32_t start, - int32_t startLength, - char *target, - int32_t targetCapacity, - enum EInvariant inv) const; - -#if U_CHARSET_IS_UTF8 || !UCONFIG_NO_CONVERSION - - /** - * Copy the characters in the range - * [start, start + length) into an array of characters - * in the platform's default codepage. - * This function does not write any more than targetLength - * characters but returns the length of the entire output string - * so that one can allocate a larger buffer and call the function again - * if necessary. - * The output string is NUL-terminated if possible. - * - * @param start offset of first character which will be copied - * @param startLength the number of characters to extract - * @param target the target buffer for extraction - * @param targetLength the length of the target buffer - * If target is NULL, then the number of bytes required for - * target is returned. - * @return the output string length, not including the terminating NUL - * @stable ICU 2.0 - */ - int32_t extract(int32_t start, - int32_t startLength, - char *target, - uint32_t targetLength) const; - -#endif - -#if !UCONFIG_NO_CONVERSION - - /** - * Copy the characters in the range - * [start, start + length) into an array of characters - * in a specified codepage. - * The output string is NUL-terminated. - * - * Recommendation: For invariant-character strings use - * extract(int32_t start, int32_t length, char *target, int32_t targetCapacity, enum EInvariant inv) const - * because it avoids object code dependencies of UnicodeString on - * the conversion code. - * - * @param start offset of first character which will be copied - * @param startLength the number of characters to extract - * @param target the target buffer for extraction - * @param codepage the desired codepage for the characters. 0 has - * the special meaning of the default codepage - * If codepage is an empty string (""), - * then a simple conversion is performed on the codepage-invariant - * subset ("invariant characters") of the platform encoding. See utypes.h. - * If target is NULL, then the number of bytes required for - * target is returned. It is assumed that the target is big enough - * to fit all of the characters. - * @return the output string length, not including the terminating NUL - * @stable ICU 2.0 - */ - inline int32_t extract(int32_t start, - int32_t startLength, - char *target, - const char *codepage = 0) const; - - /** - * Copy the characters in the range - * [start, start + length) into an array of characters - * in a specified codepage. - * This function does not write any more than targetLength - * characters but returns the length of the entire output string - * so that one can allocate a larger buffer and call the function again - * if necessary. - * The output string is NUL-terminated if possible. - * - * Recommendation: For invariant-character strings use - * extract(int32_t start, int32_t length, char *target, int32_t targetCapacity, enum EInvariant inv) const - * because it avoids object code dependencies of UnicodeString on - * the conversion code. - * - * @param start offset of first character which will be copied - * @param startLength the number of characters to extract - * @param target the target buffer for extraction - * @param targetLength the length of the target buffer - * @param codepage the desired codepage for the characters. 0 has - * the special meaning of the default codepage - * If codepage is an empty string (""), - * then a simple conversion is performed on the codepage-invariant - * subset ("invariant characters") of the platform encoding. See utypes.h. - * If target is NULL, then the number of bytes required for - * target is returned. - * @return the output string length, not including the terminating NUL - * @stable ICU 2.0 - */ - int32_t extract(int32_t start, - int32_t startLength, - char *target, - uint32_t targetLength, - const char *codepage) const; - - /** - * Convert the UnicodeString into a codepage string using an existing UConverter. - * The output string is NUL-terminated if possible. - * - * This function avoids the overhead of opening and closing a converter if - * multiple strings are extracted. - * - * @param dest destination string buffer, can be NULL if destCapacity==0 - * @param destCapacity the number of chars available at dest - * @param cnv the converter object to be used (ucnv_resetFromUnicode() will be called), - * or NULL for the default converter - * @param errorCode normal ICU error code - * @return the length of the output string, not counting the terminating NUL; - * if the length is greater than destCapacity, then the string will not fit - * and a buffer of the indicated length would need to be passed in - * @stable ICU 2.0 - */ - int32_t extract(char *dest, int32_t destCapacity, - UConverter *cnv, - UErrorCode &errorCode) const; - -#endif - - /** - * Create a temporary substring for the specified range. - * Unlike the substring constructor and setTo() functions, - * the object returned here will be a read-only alias (using getBuffer()) - * rather than copying the text. - * As a result, this substring operation is much faster but requires - * that the original string not be modified or deleted during the lifetime - * of the returned substring object. - * @param start offset of the first character visible in the substring - * @param length length of the substring - * @return a read-only alias UnicodeString object for the substring - * @stable ICU 4.4 - */ - UnicodeString tempSubString(int32_t start=0, int32_t length=INT32_MAX) const; - - /** - * Create a temporary substring for the specified range. - * Same as tempSubString(start, length) except that the substring range - * is specified as a (start, limit) pair (with an exclusive limit index) - * rather than a (start, length) pair. - * @param start offset of the first character visible in the substring - * @param limit offset immediately following the last character visible in the substring - * @return a read-only alias UnicodeString object for the substring - * @stable ICU 4.4 - */ - inline UnicodeString tempSubStringBetween(int32_t start, int32_t limit=INT32_MAX) const; - - /** - * Convert the UnicodeString to UTF-8 and write the result - * to a ByteSink. This is called by toUTF8String(). - * Unpaired surrogates are replaced with U+FFFD. - * Calls u_strToUTF8WithSub(). - * - * @param sink A ByteSink to which the UTF-8 version of the string is written. - * sink.Flush() is called at the end. - * @stable ICU 4.2 - * @see toUTF8String - */ - void toUTF8(ByteSink &sink) const; - -#if U_HAVE_STD_STRING - - /** - * Convert the UnicodeString to UTF-8 and append the result - * to a standard string. - * Unpaired surrogates are replaced with U+FFFD. - * Calls toUTF8(). - * - * @param result A standard string (or a compatible object) - * to which the UTF-8 version of the string is appended. - * @return The string object. - * @stable ICU 4.2 - * @see toUTF8 - */ - template - StringClass &toUTF8String(StringClass &result) const { - StringByteSink sbs(&result); - toUTF8(sbs); - return result; - } - -#endif - - /** - * Convert the UnicodeString to UTF-32. - * Unpaired surrogates are replaced with U+FFFD. - * Calls u_strToUTF32WithSub(). - * - * @param utf32 destination string buffer, can be NULL if capacity==0 - * @param capacity the number of UChar32s available at utf32 - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The length of the UTF-32 string. - * @see fromUTF32 - * @stable ICU 4.2 - */ - int32_t toUTF32(UChar32 *utf32, int32_t capacity, UErrorCode &errorCode) const; - - /* Length operations */ - - /** - * Return the length of the UnicodeString object. - * The length is the number of UChar code units are in the UnicodeString. - * If you want the number of code points, please use countChar32(). - * @return the length of the UnicodeString object - * @see countChar32 - * @stable ICU 2.0 - */ - inline int32_t length(void) const; - - /** - * Count Unicode code points in the length UChar code units of the string. - * A code point may occupy either one or two UChar code units. - * Counting code points involves reading all code units. - * - * This functions is basically the inverse of moveIndex32(). - * - * @param start the index of the first code unit to check - * @param length the number of UChar code units to check - * @return the number of code points in the specified code units - * @see length - * @stable ICU 2.0 - */ - int32_t - countChar32(int32_t start=0, int32_t length=INT32_MAX) const; - - /** - * Check if the length UChar code units of the string - * contain more Unicode code points than a certain number. - * This is more efficient than counting all code points in this part of the string - * and comparing that number with a threshold. - * This function may not need to scan the string at all if the length - * falls within a certain range, and - * never needs to count more than 'number+1' code points. - * Logically equivalent to (countChar32(start, length)>number). - * A Unicode code point may occupy either one or two UChar code units. - * - * @param start the index of the first code unit to check (0 for the entire string) - * @param length the number of UChar code units to check - * (use INT32_MAX for the entire string; remember that start/length - * values are pinned) - * @param number The number of code points in the (sub)string is compared against - * the 'number' parameter. - * @return Boolean value for whether the string contains more Unicode code points - * than 'number'. Same as (u_countChar32(s, length)>number). - * @see countChar32 - * @see u_strHasMoreChar32Than - * @stable ICU 2.4 - */ - UBool - hasMoreChar32Than(int32_t start, int32_t length, int32_t number) const; - - /** - * Determine if this string is empty. - * @return TRUE if this string contains 0 characters, FALSE otherwise. - * @stable ICU 2.0 - */ - inline UBool isEmpty(void) const; - - /** - * Return the capacity of the internal buffer of the UnicodeString object. - * This is useful together with the getBuffer functions. - * See there for details. - * - * @return the number of UChars available in the internal buffer - * @see getBuffer - * @stable ICU 2.0 - */ - inline int32_t getCapacity(void) const; - - /* Other operations */ - - /** - * Generate a hash code for this object. - * @return The hash code of this UnicodeString. - * @stable ICU 2.0 - */ - inline int32_t hashCode(void) const; - - /** - * Determine if this object contains a valid string. - * A bogus string has no value. It is different from an empty string, - * although in both cases isEmpty() returns TRUE and length() returns 0. - * setToBogus() and isBogus() can be used to indicate that no string value is available. - * For a bogus string, getBuffer() and getTerminatedBuffer() return NULL, and - * length() returns 0. - * - * @return TRUE if the string is bogus/invalid, FALSE otherwise - * @see setToBogus() - * @stable ICU 2.0 - */ - inline UBool isBogus(void) const; - - - //======================================== - // Write operations - //======================================== - - /* Assignment operations */ - - /** - * Assignment operator. Replace the characters in this UnicodeString - * with the characters from srcText. - * - * Starting with ICU 2.4, the assignment operator and the copy constructor - * allocate a new buffer and copy the buffer contents even for readonly aliases. - * By contrast, the fastCopyFrom() function implements the old, - * more efficient but less safe behavior - * of making this string also a readonly alias to the same buffer. - * - * If the source object has an "open" buffer from getBuffer(minCapacity), - * then the copy is an empty string. - * - * @param srcText The text containing the characters to replace - * @return a reference to this - * @stable ICU 2.0 - * @see fastCopyFrom - */ - UnicodeString &operator=(const UnicodeString &srcText); - - /** - * Almost the same as the assignment operator. - * Replace the characters in this UnicodeString - * with the characters from srcText. - * - * This function works the same as the assignment operator - * for all strings except for ones that are readonly aliases. - * - * Starting with ICU 2.4, the assignment operator and the copy constructor - * allocate a new buffer and copy the buffer contents even for readonly aliases. - * This function implements the old, more efficient but less safe behavior - * of making this string also a readonly alias to the same buffer. - * - * The fastCopyFrom function must be used only if it is known that the lifetime of - * this UnicodeString does not exceed the lifetime of the aliased buffer - * including its contents, for example for strings from resource bundles - * or aliases to string constants. - * - * If the source object has an "open" buffer from getBuffer(minCapacity), - * then the copy is an empty string. - * - * @param src The text containing the characters to replace. - * @return a reference to this - * @stable ICU 2.4 - */ - UnicodeString &fastCopyFrom(const UnicodeString &src); - -#if U_HAVE_RVALUE_REFERENCES - /** - * Move assignment operator, might leave src in bogus state. - * This string will have the same contents and state that the source string had. - * The behavior is undefined if *this and src are the same object. - * @param src source string - * @return *this - * @stable ICU 56 - */ - UnicodeString &operator=(UnicodeString &&src) U_NOEXCEPT { - return moveFrom(src); - } -#endif - // do not use #ifndef U_HIDE_DRAFT_API for moveFrom, needed by non-draft API - /** - * Move assignment, might leave src in bogus state. - * This string will have the same contents and state that the source string had. - * The behavior is undefined if *this and src are the same object. - * - * Can be called explicitly, does not need C++11 support. - * @param src source string - * @return *this - * @draft ICU 56 - */ - UnicodeString &moveFrom(UnicodeString &src) U_NOEXCEPT; - - /** - * Swap strings. - * @param other other string - * @stable ICU 56 - */ - void swap(UnicodeString &other) U_NOEXCEPT; - - /** - * Non-member UnicodeString swap function. - * @param s1 will get s2's contents and state - * @param s2 will get s1's contents and state - * @stable ICU 56 - */ - friend U_COMMON_API inline void U_EXPORT2 - swap(UnicodeString &s1, UnicodeString &s2) U_NOEXCEPT { - s1.swap(s2); - } - - /** - * Assignment operator. Replace the characters in this UnicodeString - * with the code unit ch. - * @param ch the code unit to replace - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& operator= (UChar ch); - - /** - * Assignment operator. Replace the characters in this UnicodeString - * with the code point ch. - * @param ch the code point to replace - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& operator= (UChar32 ch); - - /** - * Set the text in the UnicodeString object to the characters - * in srcText in the range - * [srcStart, srcText.length()). - * srcText is not modified. - * @param srcText the source for the new characters - * @param srcStart the offset into srcText where new characters - * will be obtained - * @return a reference to this - * @stable ICU 2.2 - */ - inline UnicodeString& setTo(const UnicodeString& srcText, - int32_t srcStart); - - /** - * Set the text in the UnicodeString object to the characters - * in srcText in the range - * [srcStart, srcStart + srcLength). - * srcText is not modified. - * @param srcText the source for the new characters - * @param srcStart the offset into srcText where new characters - * will be obtained - * @param srcLength the number of characters in srcText in the - * replace string. - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& setTo(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength); - - /** - * Set the text in the UnicodeString object to the characters in - * srcText. - * srcText is not modified. - * @param srcText the source for the new characters - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& setTo(const UnicodeString& srcText); - - /** - * Set the characters in the UnicodeString object to the characters - * in srcChars. srcChars is not modified. - * @param srcChars the source for the new characters - * @param srcLength the number of Unicode characters in srcChars. - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& setTo(const UChar *srcChars, - int32_t srcLength); - - /** - * Set the characters in the UnicodeString object to the code unit - * srcChar. - * @param srcChar the code unit which becomes the UnicodeString's character - * content - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString& setTo(UChar srcChar); - - /** - * Set the characters in the UnicodeString object to the code point - * srcChar. - * @param srcChar the code point which becomes the UnicodeString's character - * content - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString& setTo(UChar32 srcChar); - - /** - * Aliasing setTo() function, analogous to the readonly-aliasing UChar* constructor. - * The text will be used for the UnicodeString object, but - * it will not be released when the UnicodeString is destroyed. - * This has copy-on-write semantics: - * When the string is modified, then the buffer is first copied into - * newly allocated memory. - * The aliased buffer is never modified. - * - * In an assignment to another UnicodeString, when using the copy constructor - * or the assignment operator, the text will be copied. - * When using fastCopyFrom(), the text will be aliased again, - * so that both strings then alias the same readonly-text. - * - * @param isTerminated specifies if text is NUL-terminated. - * This must be true if textLength==-1. - * @param text The characters to alias for the UnicodeString. - * @param textLength The number of Unicode characters in text to alias. - * If -1, then this constructor will determine the length - * by calling u_strlen(). - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString &setTo(UBool isTerminated, - const UChar *text, - int32_t textLength); - - /** - * Aliasing setTo() function, analogous to the writable-aliasing UChar* constructor. - * The text will be used for the UnicodeString object, but - * it will not be released when the UnicodeString is destroyed. - * This has write-through semantics: - * For as long as the capacity of the buffer is sufficient, write operations - * will directly affect the buffer. When more capacity is necessary, then - * a new buffer will be allocated and the contents copied as with regularly - * constructed strings. - * In an assignment to another UnicodeString, the buffer will be copied. - * The extract(UChar *dst) function detects whether the dst pointer is the same - * as the string buffer itself and will in this case not copy the contents. - * - * @param buffer The characters to alias for the UnicodeString. - * @param buffLength The number of Unicode characters in buffer to alias. - * @param buffCapacity The size of buffer in UChars. - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString &setTo(UChar *buffer, - int32_t buffLength, - int32_t buffCapacity); - - /** - * Make this UnicodeString object invalid. - * The string will test TRUE with isBogus(). - * - * A bogus string has no value. It is different from an empty string. - * It can be used to indicate that no string value is available. - * getBuffer() and getTerminatedBuffer() return NULL, and - * length() returns 0. - * - * This utility function is used throughout the UnicodeString - * implementation to indicate that a UnicodeString operation failed, - * and may be used in other functions, - * especially but not exclusively when such functions do not - * take a UErrorCode for simplicity. - * - * The following methods, and no others, will clear a string object's bogus flag: - * - remove() - * - remove(0, INT32_MAX) - * - truncate(0) - * - operator=() (assignment operator) - * - setTo(...) - * - * The simplest ways to turn a bogus string into an empty one - * is to use the remove() function. - * Examples for other functions that are equivalent to "set to empty string": - * \code - * if(s.isBogus()) { - * s.remove(); // set to an empty string (remove all), or - * s.remove(0, INT32_MAX); // set to an empty string (remove all), or - * s.truncate(0); // set to an empty string (complete truncation), or - * s=UnicodeString(); // assign an empty string, or - * s.setTo((UChar32)-1); // set to a pseudo code point that is out of range, or - * static const UChar nul=0; - * s.setTo(&nul, 0); // set to an empty C Unicode string - * } - * \endcode - * - * @see isBogus() - * @stable ICU 2.0 - */ - void setToBogus(); - - /** - * Set the character at the specified offset to the specified character. - * @param offset A valid offset into the text of the character to set - * @param ch The new character - * @return A reference to this - * @stable ICU 2.0 - */ - UnicodeString& setCharAt(int32_t offset, - UChar ch); - - - /* Append operations */ - - /** - * Append operator. Append the code unit ch to the UnicodeString - * object. - * @param ch the code unit to be appended - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& operator+= (UChar ch); - - /** - * Append operator. Append the code point ch to the UnicodeString - * object. - * @param ch the code point to be appended - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& operator+= (UChar32 ch); - - /** - * Append operator. Append the characters in srcText to the - * UnicodeString object. srcText is not modified. - * @param srcText the source for the new characters - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& operator+= (const UnicodeString& srcText); - - /** - * Append the characters - * in srcText in the range - * [srcStart, srcStart + srcLength) to the - * UnicodeString object at offset start. srcText - * is not modified. - * @param srcText the source for the new characters - * @param srcStart the offset into srcText where new characters - * will be obtained - * @param srcLength the number of characters in srcText in - * the append string - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& append(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength); - - /** - * Append the characters in srcText to the UnicodeString object. - * srcText is not modified. - * @param srcText the source for the new characters - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& append(const UnicodeString& srcText); - - /** - * Append the characters in srcChars in the range - * [srcStart, srcStart + srcLength) to the UnicodeString - * object at offset - * start. srcChars is not modified. - * @param srcChars the source for the new characters - * @param srcStart the offset into srcChars where new characters - * will be obtained - * @param srcLength the number of characters in srcChars in - * the append string; can be -1 if srcChars is NUL-terminated - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& append(const UChar *srcChars, - int32_t srcStart, - int32_t srcLength); - - /** - * Append the characters in srcChars to the UnicodeString object - * at offset start. srcChars is not modified. - * @param srcChars the source for the new characters - * @param srcLength the number of Unicode characters in srcChars; - * can be -1 if srcChars is NUL-terminated - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& append(const UChar *srcChars, - int32_t srcLength); - - /** - * Append the code unit srcChar to the UnicodeString object. - * @param srcChar the code unit to append - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& append(UChar srcChar); - - /** - * Append the code point srcChar to the UnicodeString object. - * @param srcChar the code point to append - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString& append(UChar32 srcChar); - - - /* Insert operations */ - - /** - * Insert the characters in srcText in the range - * [srcStart, srcStart + srcLength) into the UnicodeString - * object at offset start. srcText is not modified. - * @param start the offset where the insertion begins - * @param srcText the source for the new characters - * @param srcStart the offset into srcText where new characters - * will be obtained - * @param srcLength the number of characters in srcText in - * the insert string - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& insert(int32_t start, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength); - - /** - * Insert the characters in srcText into the UnicodeString object - * at offset start. srcText is not modified. - * @param start the offset where the insertion begins - * @param srcText the source for the new characters - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& insert(int32_t start, - const UnicodeString& srcText); - - /** - * Insert the characters in srcChars in the range - * [srcStart, srcStart + srcLength) into the UnicodeString - * object at offset start. srcChars is not modified. - * @param start the offset at which the insertion begins - * @param srcChars the source for the new characters - * @param srcStart the offset into srcChars where new characters - * will be obtained - * @param srcLength the number of characters in srcChars - * in the insert string - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& insert(int32_t start, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength); - - /** - * Insert the characters in srcChars into the UnicodeString object - * at offset start. srcChars is not modified. - * @param start the offset where the insertion begins - * @param srcChars the source for the new characters - * @param srcLength the number of Unicode characters in srcChars. - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& insert(int32_t start, - const UChar *srcChars, - int32_t srcLength); - - /** - * Insert the code unit srcChar into the UnicodeString object at - * offset start. - * @param start the offset at which the insertion occurs - * @param srcChar the code unit to insert - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& insert(int32_t start, - UChar srcChar); - - /** - * Insert the code point srcChar into the UnicodeString object at - * offset start. - * @param start the offset at which the insertion occurs - * @param srcChar the code point to insert - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& insert(int32_t start, - UChar32 srcChar); - - - /* Replace operations */ - - /** - * Replace the characters in the range - * [start, start + length) with the characters in - * srcText in the range - * [srcStart, srcStart + srcLength). - * srcText is not modified. - * @param start the offset at which the replace operation begins - * @param length the number of characters to replace. The character at - * start + length is not modified. - * @param srcText the source for the new characters - * @param srcStart the offset into srcText where new characters - * will be obtained - * @param srcLength the number of characters in srcText in - * the replace string - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString& replace(int32_t start, - int32_t length, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength); - - /** - * Replace the characters in the range - * [start, start + length) - * with the characters in srcText. srcText is - * not modified. - * @param start the offset at which the replace operation begins - * @param length the number of characters to replace. The character at - * start + length is not modified. - * @param srcText the source for the new characters - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString& replace(int32_t start, - int32_t length, - const UnicodeString& srcText); - - /** - * Replace the characters in the range - * [start, start + length) with the characters in - * srcChars in the range - * [srcStart, srcStart + srcLength). srcChars - * is not modified. - * @param start the offset at which the replace operation begins - * @param length the number of characters to replace. The character at - * start + length is not modified. - * @param srcChars the source for the new characters - * @param srcStart the offset into srcChars where new characters - * will be obtained - * @param srcLength the number of characters in srcChars - * in the replace string - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString& replace(int32_t start, - int32_t length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength); - - /** - * Replace the characters in the range - * [start, start + length) with the characters in - * srcChars. srcChars is not modified. - * @param start the offset at which the replace operation begins - * @param length number of characters to replace. The character at - * start + length is not modified. - * @param srcChars the source for the new characters - * @param srcLength the number of Unicode characters in srcChars - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& replace(int32_t start, - int32_t length, - const UChar *srcChars, - int32_t srcLength); - - /** - * Replace the characters in the range - * [start, start + length) with the code unit - * srcChar. - * @param start the offset at which the replace operation begins - * @param length the number of characters to replace. The character at - * start + length is not modified. - * @param srcChar the new code unit - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& replace(int32_t start, - int32_t length, - UChar srcChar); - - /** - * Replace the characters in the range - * [start, start + length) with the code point - * srcChar. - * @param start the offset at which the replace operation begins - * @param length the number of characters to replace. The character at - * start + length is not modified. - * @param srcChar the new code point - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString& replace(int32_t start, int32_t length, UChar32 srcChar); - - /** - * Replace the characters in the range [start, limit) - * with the characters in srcText. srcText is not modified. - * @param start the offset at which the replace operation begins - * @param limit the offset immediately following the replace range - * @param srcText the source for the new characters - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& replaceBetween(int32_t start, - int32_t limit, - const UnicodeString& srcText); - - /** - * Replace the characters in the range [start, limit) - * with the characters in srcText in the range - * [srcStart, srcLimit). srcText is not modified. - * @param start the offset at which the replace operation begins - * @param limit the offset immediately following the replace range - * @param srcText the source for the new characters - * @param srcStart the offset into srcChars where new characters - * will be obtained - * @param srcLimit the offset immediately following the range to copy - * in srcText - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& replaceBetween(int32_t start, - int32_t limit, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLimit); - - /** - * Replace a substring of this object with the given text. - * @param start the beginning index, inclusive; 0 <= start - * <= limit. - * @param limit the ending index, exclusive; start <= limit - * <= length(). - * @param text the text to replace characters start - * to limit - 1 - * @stable ICU 2.0 - */ - virtual void handleReplaceBetween(int32_t start, - int32_t limit, - const UnicodeString& text); - - /** - * Replaceable API - * @return TRUE if it has MetaData - * @stable ICU 2.4 - */ - virtual UBool hasMetaData() const; - - /** - * Copy a substring of this object, retaining attribute (out-of-band) - * information. This method is used to duplicate or reorder substrings. - * The destination index must not overlap the source range. - * - * @param start the beginning index, inclusive; 0 <= start <= - * limit. - * @param limit the ending index, exclusive; start <= limit <= - * length(). - * @param dest the destination index. The characters from - * start..limit-1 will be copied to dest. - * Implementations of this method may assume that dest <= start || - * dest >= limit. - * @stable ICU 2.0 - */ - virtual void copy(int32_t start, int32_t limit, int32_t dest); - - /* Search and replace operations */ - - /** - * Replace all occurrences of characters in oldText with the characters - * in newText - * @param oldText the text containing the search text - * @param newText the text containing the replacement text - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& findAndReplace(const UnicodeString& oldText, - const UnicodeString& newText); - - /** - * Replace all occurrences of characters in oldText with characters - * in newText - * in the range [start, start + length). - * @param start the start of the range in which replace will performed - * @param length the length of the range in which replace will be performed - * @param oldText the text containing the search text - * @param newText the text containing the replacement text - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& findAndReplace(int32_t start, - int32_t length, - const UnicodeString& oldText, - const UnicodeString& newText); - - /** - * Replace all occurrences of characters in oldText in the range - * [oldStart, oldStart + oldLength) with the characters - * in newText in the range - * [newStart, newStart + newLength) - * in the range [start, start + length). - * @param start the start of the range in which replace will performed - * @param length the length of the range in which replace will be performed - * @param oldText the text containing the search text - * @param oldStart the start of the search range in oldText - * @param oldLength the length of the search range in oldText - * @param newText the text containing the replacement text - * @param newStart the start of the replacement range in newText - * @param newLength the length of the replacement range in newText - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString& findAndReplace(int32_t start, - int32_t length, - const UnicodeString& oldText, - int32_t oldStart, - int32_t oldLength, - const UnicodeString& newText, - int32_t newStart, - int32_t newLength); - - - /* Remove operations */ - - /** - * Remove all characters from the UnicodeString object. - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& remove(void); - - /** - * Remove the characters in the range - * [start, start + length) from the UnicodeString object. - * @param start the offset of the first character to remove - * @param length the number of characters to remove - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& remove(int32_t start, - int32_t length = (int32_t)INT32_MAX); - - /** - * Remove the characters in the range - * [start, limit) from the UnicodeString object. - * @param start the offset of the first character to remove - * @param limit the offset immediately following the range to remove - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& removeBetween(int32_t start, - int32_t limit = (int32_t)INT32_MAX); - - /** - * Retain only the characters in the range - * [start, limit) from the UnicodeString object. - * Removes characters before start and at and after limit. - * @param start the offset of the first character to retain - * @param limit the offset immediately following the range to retain - * @return a reference to this - * @stable ICU 4.4 - */ - inline UnicodeString &retainBetween(int32_t start, int32_t limit = INT32_MAX); - - /* Length operations */ - - /** - * Pad the start of this UnicodeString with the character padChar. - * If the length of this UnicodeString is less than targetLength, - * length() - targetLength copies of padChar will be added to the - * beginning of this UnicodeString. - * @param targetLength the desired length of the string - * @param padChar the character to use for padding. Defaults to - * space (U+0020) - * @return TRUE if the text was padded, FALSE otherwise. - * @stable ICU 2.0 - */ - UBool padLeading(int32_t targetLength, - UChar padChar = 0x0020); - - /** - * Pad the end of this UnicodeString with the character padChar. - * If the length of this UnicodeString is less than targetLength, - * length() - targetLength copies of padChar will be added to the - * end of this UnicodeString. - * @param targetLength the desired length of the string - * @param padChar the character to use for padding. Defaults to - * space (U+0020) - * @return TRUE if the text was padded, FALSE otherwise. - * @stable ICU 2.0 - */ - UBool padTrailing(int32_t targetLength, - UChar padChar = 0x0020); - - /** - * Truncate this UnicodeString to the targetLength. - * @param targetLength the desired length of this UnicodeString. - * @return TRUE if the text was truncated, FALSE otherwise - * @stable ICU 2.0 - */ - inline UBool truncate(int32_t targetLength); - - /** - * Trims leading and trailing whitespace from this UnicodeString. - * @return a reference to this - * @stable ICU 2.0 - */ - UnicodeString& trim(void); - - - /* Miscellaneous operations */ - - /** - * Reverse this UnicodeString in place. - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& reverse(void); - - /** - * Reverse the range [start, start + length) in - * this UnicodeString. - * @param start the start of the range to reverse - * @param length the number of characters to to reverse - * @return a reference to this - * @stable ICU 2.0 - */ - inline UnicodeString& reverse(int32_t start, - int32_t length); - - /** - * Convert the characters in this to UPPER CASE following the conventions of - * the default locale. - * @return A reference to this. - * @stable ICU 2.0 - */ - UnicodeString& toUpper(void); - - /** - * Convert the characters in this to UPPER CASE following the conventions of - * a specific locale. - * @param locale The locale containing the conventions to use. - * @return A reference to this. - * @stable ICU 2.0 - */ - UnicodeString& toUpper(const Locale& locale); - - /** - * Convert the characters in this to lower case following the conventions of - * the default locale. - * @return A reference to this. - * @stable ICU 2.0 - */ - UnicodeString& toLower(void); - - /** - * Convert the characters in this to lower case following the conventions of - * a specific locale. - * @param locale The locale containing the conventions to use. - * @return A reference to this. - * @stable ICU 2.0 - */ - UnicodeString& toLower(const Locale& locale); - -#if !UCONFIG_NO_BREAK_ITERATION - - /** - * Titlecase this string, convenience function using the default locale. - * - * Casing is locale-dependent and context-sensitive. - * Titlecasing uses a break iterator to find the first characters of words - * that are to be titlecased. It titlecases those characters and lowercases - * all others. - * - * The titlecase break iterator can be provided to customize for arbitrary - * styles, using rules and dictionaries beyond the standard iterators. - * It may be more efficient to always provide an iterator to avoid - * opening and closing one for each string. - * The standard titlecase iterator for the root locale implements the - * algorithm of Unicode TR 21. - * - * This function uses only the setText(), first() and next() methods of the - * provided break iterator. - * - * @param titleIter A break iterator to find the first characters of words - * that are to be titlecased. - * If none is provided (0), then a standard titlecase - * break iterator is opened. - * Otherwise the provided iterator is set to the string's text. - * @return A reference to this. - * @stable ICU 2.1 - */ - UnicodeString &toTitle(BreakIterator *titleIter); - - /** - * Titlecase this string. - * - * Casing is locale-dependent and context-sensitive. - * Titlecasing uses a break iterator to find the first characters of words - * that are to be titlecased. It titlecases those characters and lowercases - * all others. - * - * The titlecase break iterator can be provided to customize for arbitrary - * styles, using rules and dictionaries beyond the standard iterators. - * It may be more efficient to always provide an iterator to avoid - * opening and closing one for each string. - * The standard titlecase iterator for the root locale implements the - * algorithm of Unicode TR 21. - * - * This function uses only the setText(), first() and next() methods of the - * provided break iterator. - * - * @param titleIter A break iterator to find the first characters of words - * that are to be titlecased. - * If none is provided (0), then a standard titlecase - * break iterator is opened. - * Otherwise the provided iterator is set to the string's text. - * @param locale The locale to consider. - * @return A reference to this. - * @stable ICU 2.1 - */ - UnicodeString &toTitle(BreakIterator *titleIter, const Locale &locale); - - /** - * Titlecase this string, with options. - * - * Casing is locale-dependent and context-sensitive. - * Titlecasing uses a break iterator to find the first characters of words - * that are to be titlecased. It titlecases those characters and lowercases - * all others. (This can be modified with options.) - * - * The titlecase break iterator can be provided to customize for arbitrary - * styles, using rules and dictionaries beyond the standard iterators. - * It may be more efficient to always provide an iterator to avoid - * opening and closing one for each string. - * The standard titlecase iterator for the root locale implements the - * algorithm of Unicode TR 21. - * - * This function uses only the setText(), first() and next() methods of the - * provided break iterator. - * - * @param titleIter A break iterator to find the first characters of words - * that are to be titlecased. - * If none is provided (0), then a standard titlecase - * break iterator is opened. - * Otherwise the provided iterator is set to the string's text. - * @param locale The locale to consider. - * @param options Options bit set, see ucasemap_open(). - * @return A reference to this. - * @see U_TITLECASE_NO_LOWERCASE - * @see U_TITLECASE_NO_BREAK_ADJUSTMENT - * @see ucasemap_open - * @stable ICU 3.8 - */ - UnicodeString &toTitle(BreakIterator *titleIter, const Locale &locale, uint32_t options); - -#endif - - /** - * Case-folds the characters in this string. - * - * Case-folding is locale-independent and not context-sensitive, - * but there is an option for whether to include or exclude mappings for dotted I - * and dotless i that are marked with 'T' in CaseFolding.txt. - * - * The result may be longer or shorter than the original. - * - * @param options Either U_FOLD_CASE_DEFAULT or U_FOLD_CASE_EXCLUDE_SPECIAL_I - * @return A reference to this. - * @stable ICU 2.0 - */ - UnicodeString &foldCase(uint32_t options=0 /*U_FOLD_CASE_DEFAULT*/); - - //======================================== - // Access to the internal buffer - //======================================== - - /** - * Get a read/write pointer to the internal buffer. - * The buffer is guaranteed to be large enough for at least minCapacity UChars, - * writable, and is still owned by the UnicodeString object. - * Calls to getBuffer(minCapacity) must not be nested, and - * must be matched with calls to releaseBuffer(newLength). - * If the string buffer was read-only or shared, - * then it will be reallocated and copied. - * - * An attempted nested call will return 0, and will not further modify the - * state of the UnicodeString object. - * It also returns 0 if the string is bogus. - * - * The actual capacity of the string buffer may be larger than minCapacity. - * getCapacity() returns the actual capacity. - * For many operations, the full capacity should be used to avoid reallocations. - * - * While the buffer is "open" between getBuffer(minCapacity) - * and releaseBuffer(newLength), the following applies: - * - The string length is set to 0. - * - Any read API call on the UnicodeString object will behave like on a 0-length string. - * - Any write API call on the UnicodeString object is disallowed and will have no effect. - * - You can read from and write to the returned buffer. - * - The previous string contents will still be in the buffer; - * if you want to use it, then you need to call length() before getBuffer(minCapacity). - * If the length() was greater than minCapacity, then any contents after minCapacity - * may be lost. - * The buffer contents is not NUL-terminated by getBuffer(). - * If length()(s.length(). - * (See getTerminatedBuffer().) - * - * The buffer may reside in read-only memory. Its contents must not - * be modified. - * - * @return a read-only pointer to the internal string buffer, - * or 0 if the string is empty or bogus - * - * @see getBuffer(int32_t minCapacity) - * @see getTerminatedBuffer() - * @stable ICU 2.0 - */ - inline const UChar *getBuffer() const; - - /** - * Get a read-only pointer to the internal buffer, - * making sure that it is NUL-terminated. - * This can be called at any time on a valid UnicodeString. - * - * It returns 0 if the string is bogus, or - * during an "open" getBuffer(minCapacity), or if the buffer cannot - * be NUL-terminated (because memory allocation failed). - * - * It can be called as many times as desired. - * The pointer that it returns will remain valid until the UnicodeString object is modified, - * at which time the pointer is semantically invalidated and must not be used any more. - * - * The capacity of the buffer can be determined with getCapacity(). - * The part after length()+1 may or may not be initialized and valid, - * depending on the history of the UnicodeString object. - * - * The buffer contents is guaranteed to be NUL-terminated. - * getTerminatedBuffer() may reallocate the buffer if a terminating NUL - * is written. - * For this reason, this function is not const, unlike getBuffer(). - * Note that a UnicodeString may also contain NUL characters as part of its contents. - * - * The buffer may reside in read-only memory. Its contents must not - * be modified. - * - * @return a read-only pointer to the internal string buffer, - * or 0 if the string is empty or bogus - * - * @see getBuffer(int32_t minCapacity) - * @see getBuffer() - * @stable ICU 2.2 - */ - const UChar *getTerminatedBuffer(); - - //======================================== - // Constructors - //======================================== - - /** Construct an empty UnicodeString. - * @stable ICU 2.0 - */ - inline UnicodeString(); - - /** - * Construct a UnicodeString with capacity to hold capacity UChars - * @param capacity the number of UChars this UnicodeString should hold - * before a resize is necessary; if count is greater than 0 and count - * code points c take up more space than capacity, then capacity is adjusted - * accordingly. - * @param c is used to initially fill the string - * @param count specifies how many code points c are to be written in the - * string - * @stable ICU 2.0 - */ - UnicodeString(int32_t capacity, UChar32 c, int32_t count); - - /** - * Single UChar (code unit) constructor. - * - * It is recommended to mark this constructor "explicit" by - * -DUNISTR_FROM_CHAR_EXPLICIT=explicit - * on the compiler command line or similar. - * @param ch the character to place in the UnicodeString - * @stable ICU 2.0 - */ - UNISTR_FROM_CHAR_EXPLICIT UnicodeString(UChar ch); - - /** - * Single UChar32 (code point) constructor. - * - * It is recommended to mark this constructor "explicit" by - * -DUNISTR_FROM_CHAR_EXPLICIT=explicit - * on the compiler command line or similar. - * @param ch the character to place in the UnicodeString - * @stable ICU 2.0 - */ - UNISTR_FROM_CHAR_EXPLICIT UnicodeString(UChar32 ch); - - /** - * UChar* constructor. - * - * It is recommended to mark this constructor "explicit" by - * -DUNISTR_FROM_STRING_EXPLICIT=explicit - * on the compiler command line or similar. - * @param text The characters to place in the UnicodeString. text - * must be NULL (U+0000) terminated. - * @stable ICU 2.0 - */ - UNISTR_FROM_STRING_EXPLICIT UnicodeString(const UChar *text); - - /** - * UChar* constructor. - * @param text The characters to place in the UnicodeString. - * @param textLength The number of Unicode characters in text - * to copy. - * @stable ICU 2.0 - */ - UnicodeString(const UChar *text, - int32_t textLength); - - /** - * Readonly-aliasing UChar* constructor. - * The text will be used for the UnicodeString object, but - * it will not be released when the UnicodeString is destroyed. - * This has copy-on-write semantics: - * When the string is modified, then the buffer is first copied into - * newly allocated memory. - * The aliased buffer is never modified. - * - * In an assignment to another UnicodeString, when using the copy constructor - * or the assignment operator, the text will be copied. - * When using fastCopyFrom(), the text will be aliased again, - * so that both strings then alias the same readonly-text. - * - * @param isTerminated specifies if text is NUL-terminated. - * This must be true if textLength==-1. - * @param text The characters to alias for the UnicodeString. - * @param textLength The number of Unicode characters in text to alias. - * If -1, then this constructor will determine the length - * by calling u_strlen(). - * @stable ICU 2.0 - */ - UnicodeString(UBool isTerminated, - const UChar *text, - int32_t textLength); - - /** - * Writable-aliasing UChar* constructor. - * The text will be used for the UnicodeString object, but - * it will not be released when the UnicodeString is destroyed. - * This has write-through semantics: - * For as long as the capacity of the buffer is sufficient, write operations - * will directly affect the buffer. When more capacity is necessary, then - * a new buffer will be allocated and the contents copied as with regularly - * constructed strings. - * In an assignment to another UnicodeString, the buffer will be copied. - * The extract(UChar *dst) function detects whether the dst pointer is the same - * as the string buffer itself and will in this case not copy the contents. - * - * @param buffer The characters to alias for the UnicodeString. - * @param buffLength The number of Unicode characters in buffer to alias. - * @param buffCapacity The size of buffer in UChars. - * @stable ICU 2.0 - */ - UnicodeString(UChar *buffer, int32_t buffLength, int32_t buffCapacity); - -#if U_CHARSET_IS_UTF8 || !UCONFIG_NO_CONVERSION - - /** - * char* constructor. - * Uses the default converter (and thus depends on the ICU conversion code) - * unless U_CHARSET_IS_UTF8 is set to 1. - * - * For ASCII (really "invariant character") strings it is more efficient to use - * the constructor that takes a US_INV (for its enum EInvariant). - * For ASCII (invariant-character) string literals, see UNICODE_STRING and - * UNICODE_STRING_SIMPLE. - * - * It is recommended to mark this constructor "explicit" by - * -DUNISTR_FROM_STRING_EXPLICIT=explicit - * on the compiler command line or similar. - * @param codepageData an array of bytes, null-terminated, - * in the platform's default codepage. - * @stable ICU 2.0 - * @see UNICODE_STRING - * @see UNICODE_STRING_SIMPLE - */ - UNISTR_FROM_STRING_EXPLICIT UnicodeString(const char *codepageData); - - /** - * char* constructor. - * Uses the default converter (and thus depends on the ICU conversion code) - * unless U_CHARSET_IS_UTF8 is set to 1. - * @param codepageData an array of bytes in the platform's default codepage. - * @param dataLength The number of bytes in codepageData. - * @stable ICU 2.0 - */ - UnicodeString(const char *codepageData, int32_t dataLength); - -#endif - -#if !UCONFIG_NO_CONVERSION - - /** - * char* constructor. - * @param codepageData an array of bytes, null-terminated - * @param codepage the encoding of codepageData. The special - * value 0 for codepage indicates that the text is in the - * platform's default codepage. - * - * If codepage is an empty string (""), - * then a simple conversion is performed on the codepage-invariant - * subset ("invariant characters") of the platform encoding. See utypes.h. - * Recommendation: For invariant-character strings use the constructor - * UnicodeString(const char *src, int32_t length, enum EInvariant inv) - * because it avoids object code dependencies of UnicodeString on - * the conversion code. - * - * @stable ICU 2.0 - */ - UnicodeString(const char *codepageData, const char *codepage); - - /** - * char* constructor. - * @param codepageData an array of bytes. - * @param dataLength The number of bytes in codepageData. - * @param codepage the encoding of codepageData. The special - * value 0 for codepage indicates that the text is in the - * platform's default codepage. - * If codepage is an empty string (""), - * then a simple conversion is performed on the codepage-invariant - * subset ("invariant characters") of the platform encoding. See utypes.h. - * Recommendation: For invariant-character strings use the constructor - * UnicodeString(const char *src, int32_t length, enum EInvariant inv) - * because it avoids object code dependencies of UnicodeString on - * the conversion code. - * - * @stable ICU 2.0 - */ - UnicodeString(const char *codepageData, int32_t dataLength, const char *codepage); - - /** - * char * / UConverter constructor. - * This constructor uses an existing UConverter object to - * convert the codepage string to Unicode and construct a UnicodeString - * from that. - * - * The converter is reset at first. - * If the error code indicates a failure before this constructor is called, - * or if an error occurs during conversion or construction, - * then the string will be bogus. - * - * This function avoids the overhead of opening and closing a converter if - * multiple strings are constructed. - * - * @param src input codepage string - * @param srcLength length of the input string, can be -1 for NUL-terminated strings - * @param cnv converter object (ucnv_resetToUnicode() will be called), - * can be NULL for the default converter - * @param errorCode normal ICU error code - * @stable ICU 2.0 - */ - UnicodeString( - const char *src, int32_t srcLength, - UConverter *cnv, - UErrorCode &errorCode); - -#endif - - /** - * Constructs a Unicode string from an invariant-character char * string. - * About invariant characters see utypes.h. - * This constructor has no runtime dependency on conversion code and is - * therefore recommended over ones taking a charset name string - * (where the empty string "" indicates invariant-character conversion). - * - * Use the macro US_INV as the third, signature-distinguishing parameter. - * - * For example: - * \code - * void fn(const char *s) { - * UnicodeString ustr(s, -1, US_INV); - * // use ustr ... - * } - * \endcode - * - * @param src String using only invariant characters. - * @param length Length of src, or -1 if NUL-terminated. - * @param inv Signature-distinguishing paramater, use US_INV. - * - * @see US_INV - * @stable ICU 3.2 - */ - UnicodeString(const char *src, int32_t length, enum EInvariant inv); - - - /** - * Copy constructor. - * - * Starting with ICU 2.4, the assignment operator and the copy constructor - * allocate a new buffer and copy the buffer contents even for readonly aliases. - * By contrast, the fastCopyFrom() function implements the old, - * more efficient but less safe behavior - * of making this string also a readonly alias to the same buffer. - * - * If the source object has an "open" buffer from getBuffer(minCapacity), - * then the copy is an empty string. - * - * @param that The UnicodeString object to copy. - * @stable ICU 2.0 - * @see fastCopyFrom - */ - UnicodeString(const UnicodeString& that); - -#if U_HAVE_RVALUE_REFERENCES - /** - * Move constructor, might leave src in bogus state. - * This string will have the same contents and state that the source string had. - * @param src source string - * @stable ICU 56 - */ - UnicodeString(UnicodeString &&src) U_NOEXCEPT; -#endif - - /** - * 'Substring' constructor from tail of source string. - * @param src The UnicodeString object to copy. - * @param srcStart The offset into src at which to start copying. - * @stable ICU 2.2 - */ - UnicodeString(const UnicodeString& src, int32_t srcStart); - - /** - * 'Substring' constructor from subrange of source string. - * @param src The UnicodeString object to copy. - * @param srcStart The offset into src at which to start copying. - * @param srcLength The number of characters from src to copy. - * @stable ICU 2.2 - */ - UnicodeString(const UnicodeString& src, int32_t srcStart, int32_t srcLength); - - /** - * Clone this object, an instance of a subclass of Replaceable. - * Clones can be used concurrently in multiple threads. - * If a subclass does not implement clone(), or if an error occurs, - * then NULL is returned. - * The clone functions in all subclasses return a pointer to a Replaceable - * because some compilers do not support covariant (same-as-this) - * return types; cast to the appropriate subclass if necessary. - * The caller must delete the clone. - * - * @return a clone of this object - * - * @see Replaceable::clone - * @see getDynamicClassID - * @stable ICU 2.6 - */ - virtual Replaceable *clone() const; - - /** Destructor. - * @stable ICU 2.0 - */ - virtual ~UnicodeString(); - - /** - * Create a UnicodeString from a UTF-8 string. - * Illegal input is replaced with U+FFFD. Otherwise, errors result in a bogus string. - * Calls u_strFromUTF8WithSub(). - * - * @param utf8 UTF-8 input string. - * Note that a StringPiece can be implicitly constructed - * from a std::string or a NUL-terminated const char * string. - * @return A UnicodeString with equivalent UTF-16 contents. - * @see toUTF8 - * @see toUTF8String - * @stable ICU 4.2 - */ - static UnicodeString fromUTF8(StringPiece utf8); - - /** - * Create a UnicodeString from a UTF-32 string. - * Illegal input is replaced with U+FFFD. Otherwise, errors result in a bogus string. - * Calls u_strFromUTF32WithSub(). - * - * @param utf32 UTF-32 input string. Must not be NULL. - * @param length Length of the input string, or -1 if NUL-terminated. - * @return A UnicodeString with equivalent UTF-16 contents. - * @see toUTF32 - * @stable ICU 4.2 - */ - static UnicodeString fromUTF32(const UChar32 *utf32, int32_t length); - - /* Miscellaneous operations */ - - /** - * Unescape a string of characters and return a string containing - * the result. The following escape sequences are recognized: - * - * \\uhhhh 4 hex digits; h in [0-9A-Fa-f] - * \\Uhhhhhhhh 8 hex digits - * \\xhh 1-2 hex digits - * \\ooo 1-3 octal digits; o in [0-7] - * \\cX control-X; X is masked with 0x1F - * - * as well as the standard ANSI C escapes: - * - * \\a => U+0007, \\b => U+0008, \\t => U+0009, \\n => U+000A, - * \\v => U+000B, \\f => U+000C, \\r => U+000D, \\e => U+001B, - * \\" => U+0022, \\' => U+0027, \\? => U+003F, \\\\ => U+005C - * - * Anything else following a backslash is generically escaped. For - * example, "[a\\-z]" returns "[a-z]". - * - * If an escape sequence is ill-formed, this method returns an empty - * string. An example of an ill-formed sequence is "\\u" followed by - * fewer than 4 hex digits. - * - * This function is similar to u_unescape() but not identical to it. - * The latter takes a source char*, so it does escape recognition - * and also invariant conversion. - * - * @return a string with backslash escapes interpreted, or an - * empty string on error. - * @see UnicodeString#unescapeAt() - * @see u_unescape() - * @see u_unescapeAt() - * @stable ICU 2.0 - */ - UnicodeString unescape() const; - - /** - * Unescape a single escape sequence and return the represented - * character. See unescape() for a listing of the recognized escape - * sequences. The character at offset-1 is assumed (without - * checking) to be a backslash. If the escape sequence is - * ill-formed, or the offset is out of range, U_SENTINEL=-1 is - * returned. - * - * @param offset an input output parameter. On input, it is the - * offset into this string where the escape sequence is located, - * after the initial backslash. On output, it is advanced after the - * last character parsed. On error, it is not advanced at all. - * @return the character represented by the escape sequence at - * offset, or U_SENTINEL=-1 on error. - * @see UnicodeString#unescape() - * @see u_unescape() - * @see u_unescapeAt() - * @stable ICU 2.0 - */ - UChar32 unescapeAt(int32_t &offset) const; - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.2 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - - //======================================== - // Implementation methods - //======================================== - -protected: - /** - * Implement Replaceable::getLength() (see jitterbug 1027). - * @stable ICU 2.4 - */ - virtual int32_t getLength() const; - - /** - * The change in Replaceable to use virtual getCharAt() allows - * UnicodeString::charAt() to be inline again (see jitterbug 709). - * @stable ICU 2.4 - */ - virtual UChar getCharAt(int32_t offset) const; - - /** - * The change in Replaceable to use virtual getChar32At() allows - * UnicodeString::char32At() to be inline again (see jitterbug 709). - * @stable ICU 2.4 - */ - virtual UChar32 getChar32At(int32_t offset) const; - -private: - // For char* constructors. Could be made public. - UnicodeString &setToUTF8(StringPiece utf8); - // For extract(char*). - // We could make a toUTF8(target, capacity, errorCode) public but not - // this version: New API will be cleaner if we make callers create substrings - // rather than having start+length on every method, - // and it should take a UErrorCode&. - int32_t - toUTF8(int32_t start, int32_t len, - char *target, int32_t capacity) const; - - /** - * Internal string contents comparison, called by operator==. - * Requires: this & text not bogus and have same lengths. - */ - UBool doEquals(const UnicodeString &text, int32_t len) const; - - inline int8_t - doCompare(int32_t start, - int32_t length, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const; - - int8_t doCompare(int32_t start, - int32_t length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) const; - - inline int8_t - doCompareCodePointOrder(int32_t start, - int32_t length, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const; - - int8_t doCompareCodePointOrder(int32_t start, - int32_t length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) const; - - inline int8_t - doCaseCompare(int32_t start, - int32_t length, - const UnicodeString &srcText, - int32_t srcStart, - int32_t srcLength, - uint32_t options) const; - - int8_t - doCaseCompare(int32_t start, - int32_t length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength, - uint32_t options) const; - - int32_t doIndexOf(UChar c, - int32_t start, - int32_t length) const; - - int32_t doIndexOf(UChar32 c, - int32_t start, - int32_t length) const; - - int32_t doLastIndexOf(UChar c, - int32_t start, - int32_t length) const; - - int32_t doLastIndexOf(UChar32 c, - int32_t start, - int32_t length) const; - - void doExtract(int32_t start, - int32_t length, - UChar *dst, - int32_t dstStart) const; - - inline void doExtract(int32_t start, - int32_t length, - UnicodeString& target) const; - - inline UChar doCharAt(int32_t offset) const; - - UnicodeString& doReplace(int32_t start, - int32_t length, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength); - - UnicodeString& doReplace(int32_t start, - int32_t length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength); - - UnicodeString& doAppend(const UnicodeString& src, int32_t srcStart, int32_t srcLength); - UnicodeString& doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength); - - UnicodeString& doReverse(int32_t start, - int32_t length); - - // calculate hash code - int32_t doHashCode(void) const; - - // get pointer to start of array - // these do not check for kOpenGetBuffer, unlike the public getBuffer() function - inline UChar* getArrayStart(void); - inline const UChar* getArrayStart(void) const; - - inline UBool hasShortLength() const; - inline int32_t getShortLength() const; - - // A UnicodeString object (not necessarily its current buffer) - // is writable unless it isBogus() or it has an "open" getBuffer(minCapacity). - inline UBool isWritable() const; - - // Is the current buffer writable? - inline UBool isBufferWritable() const; - - // None of the following does releaseArray(). - inline void setZeroLength(); - inline void setShortLength(int32_t len); - inline void setLength(int32_t len); - inline void setToEmpty(); - inline void setArray(UChar *array, int32_t len, int32_t capacity); // sets length but not flags - - // allocate the array; result may be the stack buffer - // sets refCount to 1 if appropriate - // sets fArray, fCapacity, and flags - // sets length to 0 - // returns boolean for success or failure - UBool allocate(int32_t capacity); - - // release the array if owned - void releaseArray(void); - - // turn a bogus string into an empty one - void unBogus(); - - // implements assigment operator, copy constructor, and fastCopyFrom() - UnicodeString ©From(const UnicodeString &src, UBool fastCopy=FALSE); - - // Copies just the fields without memory management. - void copyFieldsFrom(UnicodeString &src, UBool setSrcToBogus) U_NOEXCEPT; - - // Pin start and limit to acceptable values. - inline void pinIndex(int32_t& start) const; - inline void pinIndices(int32_t& start, - int32_t& length) const; - -#if !UCONFIG_NO_CONVERSION - - /* Internal extract() using UConverter. */ - int32_t doExtract(int32_t start, int32_t length, - char *dest, int32_t destCapacity, - UConverter *cnv, - UErrorCode &errorCode) const; - - /* - * Real constructor for converting from codepage data. - * It assumes that it is called with !fRefCounted. - * - * If codepage==0, then the default converter - * is used for the platform encoding. - * If codepage is an empty string (""), - * then a simple conversion is performed on the codepage-invariant - * subset ("invariant characters") of the platform encoding. See utypes.h. - */ - void doCodepageCreate(const char *codepageData, - int32_t dataLength, - const char *codepage); - - /* - * Worker function for creating a UnicodeString from - * a codepage string using a UConverter. - */ - void - doCodepageCreate(const char *codepageData, - int32_t dataLength, - UConverter *converter, - UErrorCode &status); - -#endif - - /* - * This function is called when write access to the array - * is necessary. - * - * We need to make a copy of the array if - * the buffer is read-only, or - * the buffer is refCounted (shared), and refCount>1, or - * the buffer is too small. - * - * Return FALSE if memory could not be allocated. - */ - UBool cloneArrayIfNeeded(int32_t newCapacity = -1, - int32_t growCapacity = -1, - UBool doCopyArray = TRUE, - int32_t **pBufferToDelete = 0, - UBool forceClone = FALSE); - - /** - * Common function for UnicodeString case mappings. - * The stringCaseMapper has the same type UStringCaseMapper - * as in ustr_imp.h for ustrcase_map(). - */ - UnicodeString & - caseMap(const UCaseMap *csm, UStringCaseMapper *stringCaseMapper); - - // ref counting - void addRef(void); - int32_t removeRef(void); - int32_t refCount(void) const; - - // constants - enum { - /** - * Size of stack buffer for short strings. - * Must be at least U16_MAX_LENGTH for the single-code point constructor to work. - * @see UNISTR_OBJECT_SIZE - */ - US_STACKBUF_SIZE=(int32_t)(UNISTR_OBJECT_SIZE-sizeof(void *)-2)/U_SIZEOF_UCHAR, - kInvalidUChar=0xffff, // U+FFFF returned by charAt(invalid index) - kInvalidHashCode=0, // invalid hash code - kEmptyHashCode=1, // hash code for empty string - - // bit flag values for fLengthAndFlags - kIsBogus=1, // this string is bogus, i.e., not valid or NULL - kUsingStackBuffer=2,// using fUnion.fStackFields instead of fUnion.fFields - kRefCounted=4, // there is a refCount field before the characters in fArray - kBufferIsReadonly=8,// do not write to this buffer - kOpenGetBuffer=16, // getBuffer(minCapacity) was called (is "open"), - // and releaseBuffer(newLength) must be called - kAllStorageFlags=0x1f, - - kLengthShift=5, // remaining 11 bits for non-negative short length, or negative if long - kLength1=1<127; else undefined - int32_t fCapacity; // capacity of fArray (in UChars) - // array pointer last to minimize padding for machines with P128 data model - // or pointer sizes that are not a power of 2 - UChar *fArray; // the Unicode data - } fFields; - } fUnion; -}; - -/** - * Create a new UnicodeString with the concatenation of two others. - * - * @param s1 The first string to be copied to the new one. - * @param s2 The second string to be copied to the new one, after s1. - * @return UnicodeString(s1).append(s2) - * @stable ICU 2.8 - */ -U_COMMON_API UnicodeString U_EXPORT2 -operator+ (const UnicodeString &s1, const UnicodeString &s2); - -//======================================== -// Inline members -//======================================== - -//======================================== -// Privates -//======================================== - -inline void -UnicodeString::pinIndex(int32_t& start) const -{ - // pin index - if(start < 0) { - start = 0; - } else if(start > length()) { - start = length(); - } -} - -inline void -UnicodeString::pinIndices(int32_t& start, - int32_t& _length) const -{ - // pin indices - int32_t len = length(); - if(start < 0) { - start = 0; - } else if(start > len) { - start = len; - } - if(_length < 0) { - _length = 0; - } else if(_length > (len - start)) { - _length = (len - start); - } -} - -inline UChar* -UnicodeString::getArrayStart() { - return (fUnion.fFields.fLengthAndFlags&kUsingStackBuffer) ? - fUnion.fStackFields.fBuffer : fUnion.fFields.fArray; -} - -inline const UChar* -UnicodeString::getArrayStart() const { - return (fUnion.fFields.fLengthAndFlags&kUsingStackBuffer) ? - fUnion.fStackFields.fBuffer : fUnion.fFields.fArray; -} - -//======================================== -// Default constructor -//======================================== - -inline -UnicodeString::UnicodeString() { - fUnion.fStackFields.fLengthAndFlags=kShortString; -} - -//======================================== -// Read-only implementation methods -//======================================== -inline UBool -UnicodeString::hasShortLength() const { - return fUnion.fFields.fLengthAndFlags>=0; -} - -inline int32_t -UnicodeString::getShortLength() const { - // fLengthAndFlags must be non-negative -> short length >= 0 - // and arithmetic or logical shift does not matter. - return fUnion.fFields.fLengthAndFlags>>kLengthShift; -} - -inline int32_t -UnicodeString::length() const { - return hasShortLength() ? getShortLength() : fUnion.fFields.fLength; -} - -inline int32_t -UnicodeString::getCapacity() const { - return (fUnion.fFields.fLengthAndFlags&kUsingStackBuffer) ? - US_STACKBUF_SIZE : fUnion.fFields.fCapacity; -} - -inline int32_t -UnicodeString::hashCode() const -{ return doHashCode(); } - -inline UBool -UnicodeString::isBogus() const -{ return (UBool)(fUnion.fFields.fLengthAndFlags & kIsBogus); } - -inline UBool -UnicodeString::isWritable() const -{ return (UBool)!(fUnion.fFields.fLengthAndFlags&(kOpenGetBuffer|kIsBogus)); } - -inline UBool -UnicodeString::isBufferWritable() const -{ - return (UBool)( - !(fUnion.fFields.fLengthAndFlags&(kOpenGetBuffer|kIsBogus|kBufferIsReadonly)) && - (!(fUnion.fFields.fLengthAndFlags&kRefCounted) || refCount()==1)); -} - -inline const UChar * -UnicodeString::getBuffer() const { - if(fUnion.fFields.fLengthAndFlags&(kIsBogus|kOpenGetBuffer)) { - return 0; - } else if(fUnion.fFields.fLengthAndFlags&kUsingStackBuffer) { - return fUnion.fStackFields.fBuffer; - } else { - return fUnion.fFields.fArray; - } -} - -//======================================== -// Read-only alias methods -//======================================== -inline int8_t -UnicodeString::doCompare(int32_t start, - int32_t thisLength, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const -{ - if(srcText.isBogus()) { - return (int8_t)!isBogus(); // 0 if both are bogus, 1 otherwise - } else { - srcText.pinIndices(srcStart, srcLength); - return doCompare(start, thisLength, srcText.getArrayStart(), srcStart, srcLength); - } -} - -inline UBool -UnicodeString::operator== (const UnicodeString& text) const -{ - if(isBogus()) { - return text.isBogus(); - } else { - int32_t len = length(), textLength = text.length(); - return !text.isBogus() && len == textLength && doEquals(text, len); - } -} - -inline UBool -UnicodeString::operator!= (const UnicodeString& text) const -{ return (! operator==(text)); } - -inline UBool -UnicodeString::operator> (const UnicodeString& text) const -{ return doCompare(0, length(), text, 0, text.length()) == 1; } - -inline UBool -UnicodeString::operator< (const UnicodeString& text) const -{ return doCompare(0, length(), text, 0, text.length()) == -1; } - -inline UBool -UnicodeString::operator>= (const UnicodeString& text) const -{ return doCompare(0, length(), text, 0, text.length()) != -1; } - -inline UBool -UnicodeString::operator<= (const UnicodeString& text) const -{ return doCompare(0, length(), text, 0, text.length()) != 1; } - -inline int8_t -UnicodeString::compare(const UnicodeString& text) const -{ return doCompare(0, length(), text, 0, text.length()); } - -inline int8_t -UnicodeString::compare(int32_t start, - int32_t _length, - const UnicodeString& srcText) const -{ return doCompare(start, _length, srcText, 0, srcText.length()); } - -inline int8_t -UnicodeString::compare(const UChar *srcChars, - int32_t srcLength) const -{ return doCompare(0, length(), srcChars, 0, srcLength); } - -inline int8_t -UnicodeString::compare(int32_t start, - int32_t _length, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const -{ return doCompare(start, _length, srcText, srcStart, srcLength); } - -inline int8_t -UnicodeString::compare(int32_t start, - int32_t _length, - const UChar *srcChars) const -{ return doCompare(start, _length, srcChars, 0, _length); } - -inline int8_t -UnicodeString::compare(int32_t start, - int32_t _length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) const -{ return doCompare(start, _length, srcChars, srcStart, srcLength); } - -inline int8_t -UnicodeString::compareBetween(int32_t start, - int32_t limit, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLimit) const -{ return doCompare(start, limit - start, - srcText, srcStart, srcLimit - srcStart); } - -inline int8_t -UnicodeString::doCompareCodePointOrder(int32_t start, - int32_t thisLength, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const -{ - if(srcText.isBogus()) { - return (int8_t)!isBogus(); // 0 if both are bogus, 1 otherwise - } else { - srcText.pinIndices(srcStart, srcLength); - return doCompareCodePointOrder(start, thisLength, srcText.getArrayStart(), srcStart, srcLength); - } -} - -inline int8_t -UnicodeString::compareCodePointOrder(const UnicodeString& text) const -{ return doCompareCodePointOrder(0, length(), text, 0, text.length()); } - -inline int8_t -UnicodeString::compareCodePointOrder(int32_t start, - int32_t _length, - const UnicodeString& srcText) const -{ return doCompareCodePointOrder(start, _length, srcText, 0, srcText.length()); } - -inline int8_t -UnicodeString::compareCodePointOrder(const UChar *srcChars, - int32_t srcLength) const -{ return doCompareCodePointOrder(0, length(), srcChars, 0, srcLength); } - -inline int8_t -UnicodeString::compareCodePointOrder(int32_t start, - int32_t _length, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const -{ return doCompareCodePointOrder(start, _length, srcText, srcStart, srcLength); } - -inline int8_t -UnicodeString::compareCodePointOrder(int32_t start, - int32_t _length, - const UChar *srcChars) const -{ return doCompareCodePointOrder(start, _length, srcChars, 0, _length); } - -inline int8_t -UnicodeString::compareCodePointOrder(int32_t start, - int32_t _length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) const -{ return doCompareCodePointOrder(start, _length, srcChars, srcStart, srcLength); } - -inline int8_t -UnicodeString::compareCodePointOrderBetween(int32_t start, - int32_t limit, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLimit) const -{ return doCompareCodePointOrder(start, limit - start, - srcText, srcStart, srcLimit - srcStart); } - -inline int8_t -UnicodeString::doCaseCompare(int32_t start, - int32_t thisLength, - const UnicodeString &srcText, - int32_t srcStart, - int32_t srcLength, - uint32_t options) const -{ - if(srcText.isBogus()) { - return (int8_t)!isBogus(); // 0 if both are bogus, 1 otherwise - } else { - srcText.pinIndices(srcStart, srcLength); - return doCaseCompare(start, thisLength, srcText.getArrayStart(), srcStart, srcLength, options); - } -} - -inline int8_t -UnicodeString::caseCompare(const UnicodeString &text, uint32_t options) const { - return doCaseCompare(0, length(), text, 0, text.length(), options); -} - -inline int8_t -UnicodeString::caseCompare(int32_t start, - int32_t _length, - const UnicodeString &srcText, - uint32_t options) const { - return doCaseCompare(start, _length, srcText, 0, srcText.length(), options); -} - -inline int8_t -UnicodeString::caseCompare(const UChar *srcChars, - int32_t srcLength, - uint32_t options) const { - return doCaseCompare(0, length(), srcChars, 0, srcLength, options); -} - -inline int8_t -UnicodeString::caseCompare(int32_t start, - int32_t _length, - const UnicodeString &srcText, - int32_t srcStart, - int32_t srcLength, - uint32_t options) const { - return doCaseCompare(start, _length, srcText, srcStart, srcLength, options); -} - -inline int8_t -UnicodeString::caseCompare(int32_t start, - int32_t _length, - const UChar *srcChars, - uint32_t options) const { - return doCaseCompare(start, _length, srcChars, 0, _length, options); -} - -inline int8_t -UnicodeString::caseCompare(int32_t start, - int32_t _length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength, - uint32_t options) const { - return doCaseCompare(start, _length, srcChars, srcStart, srcLength, options); -} - -inline int8_t -UnicodeString::caseCompareBetween(int32_t start, - int32_t limit, - const UnicodeString &srcText, - int32_t srcStart, - int32_t srcLimit, - uint32_t options) const { - return doCaseCompare(start, limit - start, srcText, srcStart, srcLimit - srcStart, options); -} - -inline int32_t -UnicodeString::indexOf(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength, - int32_t start, - int32_t _length) const -{ - if(!srcText.isBogus()) { - srcText.pinIndices(srcStart, srcLength); - if(srcLength > 0) { - return indexOf(srcText.getArrayStart(), srcStart, srcLength, start, _length); - } - } - return -1; -} - -inline int32_t -UnicodeString::indexOf(const UnicodeString& text) const -{ return indexOf(text, 0, text.length(), 0, length()); } - -inline int32_t -UnicodeString::indexOf(const UnicodeString& text, - int32_t start) const { - pinIndex(start); - return indexOf(text, 0, text.length(), start, length() - start); -} - -inline int32_t -UnicodeString::indexOf(const UnicodeString& text, - int32_t start, - int32_t _length) const -{ return indexOf(text, 0, text.length(), start, _length); } - -inline int32_t -UnicodeString::indexOf(const UChar *srcChars, - int32_t srcLength, - int32_t start) const { - pinIndex(start); - return indexOf(srcChars, 0, srcLength, start, length() - start); -} - -inline int32_t -UnicodeString::indexOf(const UChar *srcChars, - int32_t srcLength, - int32_t start, - int32_t _length) const -{ return indexOf(srcChars, 0, srcLength, start, _length); } - -inline int32_t -UnicodeString::indexOf(UChar c, - int32_t start, - int32_t _length) const -{ return doIndexOf(c, start, _length); } - -inline int32_t -UnicodeString::indexOf(UChar32 c, - int32_t start, - int32_t _length) const -{ return doIndexOf(c, start, _length); } - -inline int32_t -UnicodeString::indexOf(UChar c) const -{ return doIndexOf(c, 0, length()); } - -inline int32_t -UnicodeString::indexOf(UChar32 c) const -{ return indexOf(c, 0, length()); } - -inline int32_t -UnicodeString::indexOf(UChar c, - int32_t start) const { - pinIndex(start); - return doIndexOf(c, start, length() - start); -} - -inline int32_t -UnicodeString::indexOf(UChar32 c, - int32_t start) const { - pinIndex(start); - return indexOf(c, start, length() - start); -} - -inline int32_t -UnicodeString::lastIndexOf(const UChar *srcChars, - int32_t srcLength, - int32_t start, - int32_t _length) const -{ return lastIndexOf(srcChars, 0, srcLength, start, _length); } - -inline int32_t -UnicodeString::lastIndexOf(const UChar *srcChars, - int32_t srcLength, - int32_t start) const { - pinIndex(start); - return lastIndexOf(srcChars, 0, srcLength, start, length() - start); -} - -inline int32_t -UnicodeString::lastIndexOf(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength, - int32_t start, - int32_t _length) const -{ - if(!srcText.isBogus()) { - srcText.pinIndices(srcStart, srcLength); - if(srcLength > 0) { - return lastIndexOf(srcText.getArrayStart(), srcStart, srcLength, start, _length); - } - } - return -1; -} - -inline int32_t -UnicodeString::lastIndexOf(const UnicodeString& text, - int32_t start, - int32_t _length) const -{ return lastIndexOf(text, 0, text.length(), start, _length); } - -inline int32_t -UnicodeString::lastIndexOf(const UnicodeString& text, - int32_t start) const { - pinIndex(start); - return lastIndexOf(text, 0, text.length(), start, length() - start); -} - -inline int32_t -UnicodeString::lastIndexOf(const UnicodeString& text) const -{ return lastIndexOf(text, 0, text.length(), 0, length()); } - -inline int32_t -UnicodeString::lastIndexOf(UChar c, - int32_t start, - int32_t _length) const -{ return doLastIndexOf(c, start, _length); } - -inline int32_t -UnicodeString::lastIndexOf(UChar32 c, - int32_t start, - int32_t _length) const { - return doLastIndexOf(c, start, _length); -} - -inline int32_t -UnicodeString::lastIndexOf(UChar c) const -{ return doLastIndexOf(c, 0, length()); } - -inline int32_t -UnicodeString::lastIndexOf(UChar32 c) const { - return lastIndexOf(c, 0, length()); -} - -inline int32_t -UnicodeString::lastIndexOf(UChar c, - int32_t start) const { - pinIndex(start); - return doLastIndexOf(c, start, length() - start); -} - -inline int32_t -UnicodeString::lastIndexOf(UChar32 c, - int32_t start) const { - pinIndex(start); - return lastIndexOf(c, start, length() - start); -} - -inline UBool -UnicodeString::startsWith(const UnicodeString& text) const -{ return compare(0, text.length(), text, 0, text.length()) == 0; } - -inline UBool -UnicodeString::startsWith(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const -{ return doCompare(0, srcLength, srcText, srcStart, srcLength) == 0; } - -inline UBool -UnicodeString::startsWith(const UChar *srcChars, int32_t srcLength) const { - if(srcLength < 0) { - srcLength = u_strlen(srcChars); - } - return doCompare(0, srcLength, srcChars, 0, srcLength) == 0; -} - -inline UBool -UnicodeString::startsWith(const UChar *srcChars, int32_t srcStart, int32_t srcLength) const { - if(srcLength < 0) { - srcLength = u_strlen(srcChars); - } - return doCompare(0, srcLength, srcChars, srcStart, srcLength) == 0; -} - -inline UBool -UnicodeString::endsWith(const UnicodeString& text) const -{ return doCompare(length() - text.length(), text.length(), - text, 0, text.length()) == 0; } - -inline UBool -UnicodeString::endsWith(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) const { - srcText.pinIndices(srcStart, srcLength); - return doCompare(length() - srcLength, srcLength, - srcText, srcStart, srcLength) == 0; -} - -inline UBool -UnicodeString::endsWith(const UChar *srcChars, - int32_t srcLength) const { - if(srcLength < 0) { - srcLength = u_strlen(srcChars); - } - return doCompare(length() - srcLength, srcLength, - srcChars, 0, srcLength) == 0; -} - -inline UBool -UnicodeString::endsWith(const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) const { - if(srcLength < 0) { - srcLength = u_strlen(srcChars + srcStart); - } - return doCompare(length() - srcLength, srcLength, - srcChars, srcStart, srcLength) == 0; -} - -//======================================== -// replace -//======================================== -inline UnicodeString& -UnicodeString::replace(int32_t start, - int32_t _length, - const UnicodeString& srcText) -{ return doReplace(start, _length, srcText, 0, srcText.length()); } - -inline UnicodeString& -UnicodeString::replace(int32_t start, - int32_t _length, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) -{ return doReplace(start, _length, srcText, srcStart, srcLength); } - -inline UnicodeString& -UnicodeString::replace(int32_t start, - int32_t _length, - const UChar *srcChars, - int32_t srcLength) -{ return doReplace(start, _length, srcChars, 0, srcLength); } - -inline UnicodeString& -UnicodeString::replace(int32_t start, - int32_t _length, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) -{ return doReplace(start, _length, srcChars, srcStart, srcLength); } - -inline UnicodeString& -UnicodeString::replace(int32_t start, - int32_t _length, - UChar srcChar) -{ return doReplace(start, _length, &srcChar, 0, 1); } - -inline UnicodeString& -UnicodeString::replaceBetween(int32_t start, - int32_t limit, - const UnicodeString& srcText) -{ return doReplace(start, limit - start, srcText, 0, srcText.length()); } - -inline UnicodeString& -UnicodeString::replaceBetween(int32_t start, - int32_t limit, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLimit) -{ return doReplace(start, limit - start, srcText, srcStart, srcLimit - srcStart); } - -inline UnicodeString& -UnicodeString::findAndReplace(const UnicodeString& oldText, - const UnicodeString& newText) -{ return findAndReplace(0, length(), oldText, 0, oldText.length(), - newText, 0, newText.length()); } - -inline UnicodeString& -UnicodeString::findAndReplace(int32_t start, - int32_t _length, - const UnicodeString& oldText, - const UnicodeString& newText) -{ return findAndReplace(start, _length, oldText, 0, oldText.length(), - newText, 0, newText.length()); } - -// ============================ -// extract -// ============================ -inline void -UnicodeString::doExtract(int32_t start, - int32_t _length, - UnicodeString& target) const -{ target.replace(0, target.length(), *this, start, _length); } - -inline void -UnicodeString::extract(int32_t start, - int32_t _length, - UChar *target, - int32_t targetStart) const -{ doExtract(start, _length, target, targetStart); } - -inline void -UnicodeString::extract(int32_t start, - int32_t _length, - UnicodeString& target) const -{ doExtract(start, _length, target); } - -#if !UCONFIG_NO_CONVERSION - -inline int32_t -UnicodeString::extract(int32_t start, - int32_t _length, - char *dst, - const char *codepage) const - -{ - // This dstSize value will be checked explicitly - return extract(start, _length, dst, dst!=0 ? 0xffffffff : 0, codepage); -} - -#endif - -inline void -UnicodeString::extractBetween(int32_t start, - int32_t limit, - UChar *dst, - int32_t dstStart) const { - pinIndex(start); - pinIndex(limit); - doExtract(start, limit - start, dst, dstStart); -} - -inline UnicodeString -UnicodeString::tempSubStringBetween(int32_t start, int32_t limit) const { - return tempSubString(start, limit - start); -} - -inline UChar -UnicodeString::doCharAt(int32_t offset) const -{ - if((uint32_t)offset < (uint32_t)length()) { - return getArrayStart()[offset]; - } else { - return kInvalidUChar; - } -} - -inline UChar -UnicodeString::charAt(int32_t offset) const -{ return doCharAt(offset); } - -inline UChar -UnicodeString::operator[] (int32_t offset) const -{ return doCharAt(offset); } - -inline UBool -UnicodeString::isEmpty() const { - // Arithmetic or logical right shift does not matter: only testing for 0. - return (fUnion.fFields.fLengthAndFlags>>kLengthShift) == 0; -} - -//======================================== -// Write implementation methods -//======================================== -inline void -UnicodeString::setZeroLength() { - fUnion.fFields.fLengthAndFlags &= kAllStorageFlags; -} - -inline void -UnicodeString::setShortLength(int32_t len) { - // requires 0 <= len <= kMaxShortLength - fUnion.fFields.fLengthAndFlags = - (int16_t)((fUnion.fFields.fLengthAndFlags & kAllStorageFlags) | (len << kLengthShift)); -} - -inline void -UnicodeString::setLength(int32_t len) { - if(len <= kMaxShortLength) { - setShortLength(len); - } else { - fUnion.fFields.fLengthAndFlags |= kLengthIsLarge; - fUnion.fFields.fLength = len; - } -} - -inline void -UnicodeString::setToEmpty() { - fUnion.fFields.fLengthAndFlags = kShortString; -} - -inline void -UnicodeString::setArray(UChar *array, int32_t len, int32_t capacity) { - setLength(len); - fUnion.fFields.fArray = array; - fUnion.fFields.fCapacity = capacity; -} - -inline UnicodeString& -UnicodeString::operator= (UChar ch) -{ return doReplace(0, length(), &ch, 0, 1); } - -inline UnicodeString& -UnicodeString::operator= (UChar32 ch) -{ return replace(0, length(), ch); } - -inline UnicodeString& -UnicodeString::setTo(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) -{ - unBogus(); - return doReplace(0, length(), srcText, srcStart, srcLength); -} - -inline UnicodeString& -UnicodeString::setTo(const UnicodeString& srcText, - int32_t srcStart) -{ - unBogus(); - srcText.pinIndex(srcStart); - return doReplace(0, length(), srcText, srcStart, srcText.length() - srcStart); -} - -inline UnicodeString& -UnicodeString::setTo(const UnicodeString& srcText) -{ - return copyFrom(srcText); -} - -inline UnicodeString& -UnicodeString::setTo(const UChar *srcChars, - int32_t srcLength) -{ - unBogus(); - return doReplace(0, length(), srcChars, 0, srcLength); -} - -inline UnicodeString& -UnicodeString::setTo(UChar srcChar) -{ - unBogus(); - return doReplace(0, length(), &srcChar, 0, 1); -} - -inline UnicodeString& -UnicodeString::setTo(UChar32 srcChar) -{ - unBogus(); - return replace(0, length(), srcChar); -} - -inline UnicodeString& -UnicodeString::append(const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) -{ return doAppend(srcText, srcStart, srcLength); } - -inline UnicodeString& -UnicodeString::append(const UnicodeString& srcText) -{ return doAppend(srcText, 0, srcText.length()); } - -inline UnicodeString& -UnicodeString::append(const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) -{ return doAppend(srcChars, srcStart, srcLength); } - -inline UnicodeString& -UnicodeString::append(const UChar *srcChars, - int32_t srcLength) -{ return doAppend(srcChars, 0, srcLength); } - -inline UnicodeString& -UnicodeString::append(UChar srcChar) -{ return doAppend(&srcChar, 0, 1); } - -inline UnicodeString& -UnicodeString::operator+= (UChar ch) -{ return doAppend(&ch, 0, 1); } - -inline UnicodeString& -UnicodeString::operator+= (UChar32 ch) { - return append(ch); -} - -inline UnicodeString& -UnicodeString::operator+= (const UnicodeString& srcText) -{ return doAppend(srcText, 0, srcText.length()); } - -inline UnicodeString& -UnicodeString::insert(int32_t start, - const UnicodeString& srcText, - int32_t srcStart, - int32_t srcLength) -{ return doReplace(start, 0, srcText, srcStart, srcLength); } - -inline UnicodeString& -UnicodeString::insert(int32_t start, - const UnicodeString& srcText) -{ return doReplace(start, 0, srcText, 0, srcText.length()); } - -inline UnicodeString& -UnicodeString::insert(int32_t start, - const UChar *srcChars, - int32_t srcStart, - int32_t srcLength) -{ return doReplace(start, 0, srcChars, srcStart, srcLength); } - -inline UnicodeString& -UnicodeString::insert(int32_t start, - const UChar *srcChars, - int32_t srcLength) -{ return doReplace(start, 0, srcChars, 0, srcLength); } - -inline UnicodeString& -UnicodeString::insert(int32_t start, - UChar srcChar) -{ return doReplace(start, 0, &srcChar, 0, 1); } - -inline UnicodeString& -UnicodeString::insert(int32_t start, - UChar32 srcChar) -{ return replace(start, 0, srcChar); } - - -inline UnicodeString& -UnicodeString::remove() -{ - // remove() of a bogus string makes the string empty and non-bogus - if(isBogus()) { - setToEmpty(); - } else { - setZeroLength(); - } - return *this; -} - -inline UnicodeString& -UnicodeString::remove(int32_t start, - int32_t _length) -{ - if(start <= 0 && _length == INT32_MAX) { - // remove(guaranteed everything) of a bogus string makes the string empty and non-bogus - return remove(); - } - return doReplace(start, _length, NULL, 0, 0); -} - -inline UnicodeString& -UnicodeString::removeBetween(int32_t start, - int32_t limit) -{ return doReplace(start, limit - start, NULL, 0, 0); } - -inline UnicodeString & -UnicodeString::retainBetween(int32_t start, int32_t limit) { - truncate(limit); - return doReplace(0, start, NULL, 0, 0); -} - -inline UBool -UnicodeString::truncate(int32_t targetLength) -{ - if(isBogus() && targetLength == 0) { - // truncate(0) of a bogus string makes the string empty and non-bogus - unBogus(); - return FALSE; - } else if((uint32_t)targetLength < (uint32_t)length()) { - setLength(targetLength); - return TRUE; - } else { - return FALSE; - } -} - -inline UnicodeString& -UnicodeString::reverse() -{ return doReverse(0, length()); } - -inline UnicodeString& -UnicodeString::reverse(int32_t start, - int32_t _length) -{ return doReverse(start, _length); } - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/unorm.h b/win32/include/spidermonkey/unicode/unorm.h deleted file mode 100755 index f527c263..00000000 --- a/win32/include/spidermonkey/unicode/unorm.h +++ /dev/null @@ -1,472 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (c) 1996-2016, International Business Machines Corporation -* and others. All Rights Reserved. -******************************************************************************* -* File unorm.h -* -* Created by: Vladimir Weinstein 12052000 -* -* Modification history : -* -* Date Name Description -* 02/01/01 synwee Added normalization quickcheck enum and method. -*/ -#ifndef UNORM_H -#define UNORM_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_NORMALIZATION - -#include "unicode/uiter.h" -#include "unicode/unorm2.h" - -/** - * \file - * \brief C API: Unicode Normalization - * - * Old Unicode normalization API. - * - * This API has been replaced by the unorm2.h API and is only available - * for backward compatibility. The functions here simply delegate to the - * unorm2.h functions, for example unorm2_getInstance() and unorm2_normalize(). - * There is one exception: The new API does not provide a replacement for unorm_compare(). - * Its declaration has been moved to unorm2.h. - * - * unorm_normalize transforms Unicode text into an equivalent composed or - * decomposed form, allowing for easier sorting and searching of text. - * unorm_normalize supports the standard normalization forms described in - * - * Unicode Standard Annex #15: Unicode Normalization Forms. - * - * Characters with accents or other adornments can be encoded in - * several different ways in Unicode. For example, take the character A-acute. - * In Unicode, this can be encoded as a single character (the - * "composed" form): - * - * \code - * 00C1 LATIN CAPITAL LETTER A WITH ACUTE - * \endcode - * - * or as two separate characters (the "decomposed" form): - * - * \code - * 0041 LATIN CAPITAL LETTER A - * 0301 COMBINING ACUTE ACCENT - * \endcode - * - * To a user of your program, however, both of these sequences should be - * treated as the same "user-level" character "A with acute accent". When you are searching or - * comparing text, you must ensure that these two sequences are treated - * equivalently. In addition, you must handle characters with more than one - * accent. Sometimes the order of a character's combining accents is - * significant, while in other cases accent sequences in different orders are - * really equivalent. - * - * Similarly, the string "ffi" can be encoded as three separate letters: - * - * \code - * 0066 LATIN SMALL LETTER F - * 0066 LATIN SMALL LETTER F - * 0069 LATIN SMALL LETTER I - * \endcode - * - * or as the single character - * - * \code - * FB03 LATIN SMALL LIGATURE FFI - * \endcode - * - * The ffi ligature is not a distinct semantic character, and strictly speaking - * it shouldn't be in Unicode at all, but it was included for compatibility - * with existing character sets that already provided it. The Unicode standard - * identifies such characters by giving them "compatibility" decompositions - * into the corresponding semantic characters. When sorting and searching, you - * will often want to use these mappings. - * - * unorm_normalize helps solve these problems by transforming text into the - * canonical composed and decomposed forms as shown in the first example above. - * In addition, you can have it perform compatibility decompositions so that - * you can treat compatibility characters the same as their equivalents. - * Finally, unorm_normalize rearranges accents into the proper canonical - * order, so that you do not have to worry about accent rearrangement on your - * own. - * - * Form FCD, "Fast C or D", is also designed for collation. - * It allows to work on strings that are not necessarily normalized - * with an algorithm (like in collation) that works under "canonical closure", i.e., it treats precomposed - * characters and their decomposed equivalents the same. - * - * It is not a normalization form because it does not provide for uniqueness of representation. Multiple strings - * may be canonically equivalent (their NFDs are identical) and may all conform to FCD without being identical - * themselves. - * - * The form is defined such that the "raw decomposition", the recursive canonical decomposition of each character, - * results in a string that is canonically ordered. This means that precomposed characters are allowed for as long - * as their decompositions do not need canonical reordering. - * - * Its advantage for a process like collation is that all NFD and most NFC texts - and many unnormalized texts - - * already conform to FCD and do not need to be normalized (NFD) for such a process. The FCD quick check will - * return UNORM_YES for most strings in practice. - * - * unorm_normalize(UNORM_FCD) may be implemented with UNORM_NFD. - * - * For more details on FCD see the collation design document: - * http://source.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm - * - * ICU collation performs either NFD or FCD normalization automatically if normalization - * is turned on for the collator object. - * Beyond collation and string search, normalized strings may be useful for string equivalence comparisons, - * transliteration/transcription, unique representations, etc. - * - * The W3C generally recommends to exchange texts in NFC. - * Note also that most legacy character encodings use only precomposed forms and often do not - * encode any combining marks by themselves. For conversion to such character encodings the - * Unicode text needs to be normalized to NFC. - * For more usage examples, see the Unicode Standard Annex. - */ - -// Do not conditionalize the following enum with #ifndef U_HIDE_DEPRECATED_API, -// it is needed for layout of Normalizer object. -/** - * Constants for normalization modes. - * @deprecated ICU 56 Use unorm2.h instead. - */ -typedef enum { - /** No decomposition/composition. @deprecated ICU 56 Use unorm2.h instead. */ - UNORM_NONE = 1, - /** Canonical decomposition. @deprecated ICU 56 Use unorm2.h instead. */ - UNORM_NFD = 2, - /** Compatibility decomposition. @deprecated ICU 56 Use unorm2.h instead. */ - UNORM_NFKD = 3, - /** Canonical decomposition followed by canonical composition. @deprecated ICU 56 Use unorm2.h instead. */ - UNORM_NFC = 4, - /** Default normalization. @deprecated ICU 56 Use unorm2.h instead. */ - UNORM_DEFAULT = UNORM_NFC, - /** Compatibility decomposition followed by canonical composition. @deprecated ICU 56 Use unorm2.h instead. */ - UNORM_NFKC =5, - /** "Fast C or D" form. @deprecated ICU 56 Use unorm2.h instead. */ - UNORM_FCD = 6, - - /** One more than the highest normalization mode constant. @deprecated ICU 56 Use unorm2.h instead. */ - UNORM_MODE_COUNT -} UNormalizationMode; - -#ifndef U_HIDE_DEPRECATED_API - -/** - * Constants for options flags for normalization. - * Use 0 for default options, - * including normalization according to the Unicode version - * that is currently supported by ICU (see u_getUnicodeVersion). - * @deprecated ICU 56 Use unorm2.h instead. - */ -enum { - /** - * Options bit set value to select Unicode 3.2 normalization - * (except NormalizationCorrections). - * At most one Unicode version can be selected at a time. - * @deprecated ICU 56 Use unorm2.h instead. - */ - UNORM_UNICODE_3_2=0x20 -}; - -/** - * Lowest-order bit number of unorm_compare() options bits corresponding to - * normalization options bits. - * - * The options parameter for unorm_compare() uses most bits for - * itself and for various comparison and folding flags. - * The most significant bits, however, are shifted down and passed on - * to the normalization implementation. - * (That is, from unorm_compare(..., options, ...), - * options>>UNORM_COMPARE_NORM_OPTIONS_SHIFT will be passed on to the - * internal normalization functions.) - * - * @see unorm_compare - * @deprecated ICU 56 Use unorm2.h instead. - */ -#define UNORM_COMPARE_NORM_OPTIONS_SHIFT 20 - -/** - * Normalize a string. - * The string will be normalized according the specified normalization mode - * and options. - * The source and result buffers must not be the same, nor overlap. - * - * @param source The string to normalize. - * @param sourceLength The length of source, or -1 if NUL-terminated. - * @param mode The normalization mode; one of UNORM_NONE, - * UNORM_NFD, UNORM_NFC, UNORM_NFKC, UNORM_NFKD, UNORM_DEFAULT. - * @param options The normalization options, ORed together (0 for no options). - * @param result A pointer to a buffer to receive the result string. - * The result string is NUL-terminated if possible. - * @param resultLength The maximum size of result. - * @param status A pointer to a UErrorCode to receive any errors. - * @return The total buffer size needed; if greater than resultLength, - * the output was truncated, and the error code is set to U_BUFFER_OVERFLOW_ERROR. - * @deprecated ICU 56 Use unorm2.h instead. - */ -U_STABLE int32_t U_EXPORT2 -unorm_normalize(const UChar *source, int32_t sourceLength, - UNormalizationMode mode, int32_t options, - UChar *result, int32_t resultLength, - UErrorCode *status); - -/** - * Performing quick check on a string, to quickly determine if the string is - * in a particular normalization format. - * Three types of result can be returned UNORM_YES, UNORM_NO or - * UNORM_MAYBE. Result UNORM_YES indicates that the argument - * string is in the desired normalized format, UNORM_NO determines that - * argument string is not in the desired normalized format. A - * UNORM_MAYBE result indicates that a more thorough check is required, - * the user may have to put the string in its normalized form and compare the - * results. - * - * @param source string for determining if it is in a normalized format - * @param sourcelength length of source to test, or -1 if NUL-terminated - * @param mode which normalization form to test for - * @param status a pointer to a UErrorCode to receive any errors - * @return UNORM_YES, UNORM_NO or UNORM_MAYBE - * - * @see unorm_isNormalized - * @deprecated ICU 56 Use unorm2.h instead. - */ -U_STABLE UNormalizationCheckResult U_EXPORT2 -unorm_quickCheck(const UChar *source, int32_t sourcelength, - UNormalizationMode mode, - UErrorCode *status); - -/** - * Performing quick check on a string; same as unorm_quickCheck but - * takes an extra options parameter like most normalization functions. - * - * @param src String that is to be tested if it is in a normalization format. - * @param srcLength Length of source to test, or -1 if NUL-terminated. - * @param mode Which normalization form to test for. - * @param options The normalization options, ORed together (0 for no options). - * @param pErrorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return UNORM_YES, UNORM_NO or UNORM_MAYBE - * - * @see unorm_quickCheck - * @see unorm_isNormalized - * @deprecated ICU 56 Use unorm2.h instead. - */ -U_STABLE UNormalizationCheckResult U_EXPORT2 -unorm_quickCheckWithOptions(const UChar *src, int32_t srcLength, - UNormalizationMode mode, int32_t options, - UErrorCode *pErrorCode); - -/** - * Test if a string is in a given normalization form. - * This is semantically equivalent to source.equals(normalize(source, mode)) . - * - * Unlike unorm_quickCheck(), this function returns a definitive result, - * never a "maybe". - * For NFD, NFKD, and FCD, both functions work exactly the same. - * For NFC and NFKC where quickCheck may return "maybe", this function will - * perform further tests to arrive at a TRUE/FALSE result. - * - * @param src String that is to be tested if it is in a normalization format. - * @param srcLength Length of source to test, or -1 if NUL-terminated. - * @param mode Which normalization form to test for. - * @param pErrorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return Boolean value indicating whether the source string is in the - * "mode" normalization form. - * - * @see unorm_quickCheck - * @deprecated ICU 56 Use unorm2.h instead. - */ -U_STABLE UBool U_EXPORT2 -unorm_isNormalized(const UChar *src, int32_t srcLength, - UNormalizationMode mode, - UErrorCode *pErrorCode); - -/** - * Test if a string is in a given normalization form; same as unorm_isNormalized but - * takes an extra options parameter like most normalization functions. - * - * @param src String that is to be tested if it is in a normalization format. - * @param srcLength Length of source to test, or -1 if NUL-terminated. - * @param mode Which normalization form to test for. - * @param options The normalization options, ORed together (0 for no options). - * @param pErrorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return Boolean value indicating whether the source string is in the - * "mode/options" normalization form. - * - * @see unorm_quickCheck - * @see unorm_isNormalized - * @deprecated ICU 56 Use unorm2.h instead. - */ -U_STABLE UBool U_EXPORT2 -unorm_isNormalizedWithOptions(const UChar *src, int32_t srcLength, - UNormalizationMode mode, int32_t options, - UErrorCode *pErrorCode); - -/** - * Iterative normalization forward. - * This function (together with unorm_previous) is somewhat - * similar to the C++ Normalizer class (see its non-static functions). - * - * Iterative normalization is useful when only a small portion of a longer - * string/text needs to be processed. - * - * For example, the likelihood may be high that processing the first 10% of some - * text will be sufficient to find certain data. - * Another example: When one wants to concatenate two normalized strings and get a - * normalized result, it is much more efficient to normalize just a small part of - * the result around the concatenation place instead of re-normalizing everything. - * - * The input text is an instance of the C character iteration API UCharIterator. - * It may wrap around a simple string, a CharacterIterator, a Replaceable, or any - * other kind of text object. - * - * If a buffer overflow occurs, then the caller needs to reset the iterator to the - * old index and call the function again with a larger buffer - if the caller cares - * for the actual output. - * Regardless of the output buffer, the iterator will always be moved to the next - * normalization boundary. - * - * This function (like unorm_previous) serves two purposes: - * - * 1) To find the next boundary so that the normalization of the part of the text - * from the current position to that boundary does not affect and is not affected - * by the part of the text beyond that boundary. - * - * 2) To normalize the text up to the boundary. - * - * The second step is optional, per the doNormalize parameter. - * It is omitted for operations like string concatenation, where the two adjacent - * string ends need to be normalized together. - * In such a case, the output buffer will just contain a copy of the text up to the - * boundary. - * - * pNeededToNormalize is an output-only parameter. Its output value is only defined - * if normalization was requested (doNormalize) and successful (especially, no - * buffer overflow). - * It is useful for operations like a normalizing transliterator, where one would - * not want to replace a piece of text if it is not modified. - * - * If doNormalize==TRUE and pNeededToNormalize!=NULL then *pNeeded... is set TRUE - * if the normalization was necessary. - * - * If doNormalize==FALSE then *pNeededToNormalize will be set to FALSE. - * - * If the buffer overflows, then *pNeededToNormalize will be undefined; - * essentially, whenever U_FAILURE is true (like in buffer overflows), this result - * will be undefined. - * - * @param src The input text in the form of a C character iterator. - * @param dest The output buffer; can be NULL if destCapacity==0 for pure preflighting. - * @param destCapacity The number of UChars that fit into dest. - * @param mode The normalization mode. - * @param options The normalization options, ORed together (0 for no options). - * @param doNormalize Indicates if the source text up to the next boundary - * is to be normalized (TRUE) or just copied (FALSE). - * @param pNeededToNormalize Output flag indicating if the normalization resulted in - * different text from the input. - * Not defined if an error occurs including buffer overflow. - * Always FALSE if !doNormalize. - * @param pErrorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return Length of output (number of UChars) when successful or buffer overflow. - * - * @see unorm_previous - * @see unorm_normalize - * - * @deprecated ICU 56 Use unorm2.h instead. - */ -U_STABLE int32_t U_EXPORT2 -unorm_next(UCharIterator *src, - UChar *dest, int32_t destCapacity, - UNormalizationMode mode, int32_t options, - UBool doNormalize, UBool *pNeededToNormalize, - UErrorCode *pErrorCode); - -/** - * Iterative normalization backward. - * This function (together with unorm_next) is somewhat - * similar to the C++ Normalizer class (see its non-static functions). - * For all details see unorm_next. - * - * @param src The input text in the form of a C character iterator. - * @param dest The output buffer; can be NULL if destCapacity==0 for pure preflighting. - * @param destCapacity The number of UChars that fit into dest. - * @param mode The normalization mode. - * @param options The normalization options, ORed together (0 for no options). - * @param doNormalize Indicates if the source text up to the next boundary - * is to be normalized (TRUE) or just copied (FALSE). - * @param pNeededToNormalize Output flag indicating if the normalization resulted in - * different text from the input. - * Not defined if an error occurs including buffer overflow. - * Always FALSE if !doNormalize. - * @param pErrorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return Length of output (number of UChars) when successful or buffer overflow. - * - * @see unorm_next - * @see unorm_normalize - * - * @deprecated ICU 56 Use unorm2.h instead. - */ -U_STABLE int32_t U_EXPORT2 -unorm_previous(UCharIterator *src, - UChar *dest, int32_t destCapacity, - UNormalizationMode mode, int32_t options, - UBool doNormalize, UBool *pNeededToNormalize, - UErrorCode *pErrorCode); - -/** - * Concatenate normalized strings, making sure that the result is normalized as well. - * - * If both the left and the right strings are in - * the normalization form according to "mode/options", - * then the result will be - * - * \code - * dest=normalize(left+right, mode, options) - * \endcode - * - * With the input strings already being normalized, - * this function will use unorm_next() and unorm_previous() - * to find the adjacent end pieces of the input strings. - * Only the concatenation of these end pieces will be normalized and - * then concatenated with the remaining parts of the input strings. - * - * It is allowed to have dest==left to avoid copying the entire left string. - * - * @param left Left source string, may be same as dest. - * @param leftLength Length of left source string, or -1 if NUL-terminated. - * @param right Right source string. Must not be the same as dest, nor overlap. - * @param rightLength Length of right source string, or -1 if NUL-terminated. - * @param dest The output buffer; can be NULL if destCapacity==0 for pure preflighting. - * @param destCapacity The number of UChars that fit into dest. - * @param mode The normalization mode. - * @param options The normalization options, ORed together (0 for no options). - * @param pErrorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return Length of output (number of UChars) when successful or buffer overflow. - * - * @see unorm_normalize - * @see unorm_next - * @see unorm_previous - * - * @deprecated ICU 56 Use unorm2.h instead. - */ -U_STABLE int32_t U_EXPORT2 -unorm_concatenate(const UChar *left, int32_t leftLength, - const UChar *right, int32_t rightLength, - UChar *dest, int32_t destCapacity, - UNormalizationMode mode, int32_t options, - UErrorCode *pErrorCode); - -#endif /* U_HIDE_DEPRECATED_API */ -#endif /* #if !UCONFIG_NO_NORMALIZATION */ -#endif diff --git a/win32/include/spidermonkey/unicode/unorm2.h b/win32/include/spidermonkey/unicode/unorm2.h deleted file mode 100755 index 56e99b2a..00000000 --- a/win32/include/spidermonkey/unicode/unorm2.h +++ /dev/null @@ -1,626 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2009-2015, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: unorm2.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2009dec15 -* created by: Markus W. Scherer -*/ - -#ifndef __UNORM2_H__ -#define __UNORM2_H__ - -/** - * \file - * \brief C API: New API for Unicode Normalization. - * - * Unicode normalization functionality for standard Unicode normalization or - * for using custom mapping tables. - * All instances of UNormalizer2 are unmodifiable/immutable. - * Instances returned by unorm2_getInstance() are singletons that must not be deleted by the caller. - * For more details see the Normalizer2 C++ class. - */ - -#include "unicode/utypes.h" -#include "unicode/localpointer.h" -#include "unicode/uset.h" - -/** - * Constants for normalization modes. - * For details about standard Unicode normalization forms - * and about the algorithms which are also used with custom mapping tables - * see http://www.unicode.org/unicode/reports/tr15/ - * @stable ICU 4.4 - */ -typedef enum { - /** - * Decomposition followed by composition. - * Same as standard NFC when using an "nfc" instance. - * Same as standard NFKC when using an "nfkc" instance. - * For details about standard Unicode normalization forms - * see http://www.unicode.org/unicode/reports/tr15/ - * @stable ICU 4.4 - */ - UNORM2_COMPOSE, - /** - * Map, and reorder canonically. - * Same as standard NFD when using an "nfc" instance. - * Same as standard NFKD when using an "nfkc" instance. - * For details about standard Unicode normalization forms - * see http://www.unicode.org/unicode/reports/tr15/ - * @stable ICU 4.4 - */ - UNORM2_DECOMPOSE, - /** - * "Fast C or D" form. - * If a string is in this form, then further decomposition without reordering - * would yield the same form as DECOMPOSE. - * Text in "Fast C or D" form can be processed efficiently with data tables - * that are "canonically closed", that is, that provide equivalent data for - * equivalent text, without having to be fully normalized. - * Not a standard Unicode normalization form. - * Not a unique form: Different FCD strings can be canonically equivalent. - * For details see http://www.unicode.org/notes/tn5/#FCD - * @stable ICU 4.4 - */ - UNORM2_FCD, - /** - * Compose only contiguously. - * Also known as "FCC" or "Fast C Contiguous". - * The result will often but not always be in NFC. - * The result will conform to FCD which is useful for processing. - * Not a standard Unicode normalization form. - * For details see http://www.unicode.org/notes/tn5/#FCC - * @stable ICU 4.4 - */ - UNORM2_COMPOSE_CONTIGUOUS -} UNormalization2Mode; - -/** - * Result values for normalization quick check functions. - * For details see http://www.unicode.org/reports/tr15/#Detecting_Normalization_Forms - * @stable ICU 2.0 - */ -typedef enum UNormalizationCheckResult { - /** - * The input string is not in the normalization form. - * @stable ICU 2.0 - */ - UNORM_NO, - /** - * The input string is in the normalization form. - * @stable ICU 2.0 - */ - UNORM_YES, - /** - * The input string may or may not be in the normalization form. - * This value is only returned for composition forms like NFC and FCC, - * when a backward-combining character is found for which the surrounding text - * would have to be analyzed further. - * @stable ICU 2.0 - */ - UNORM_MAYBE -} UNormalizationCheckResult; - -/** - * Opaque C service object type for the new normalization API. - * @stable ICU 4.4 - */ -struct UNormalizer2; -typedef struct UNormalizer2 UNormalizer2; /**< C typedef for struct UNormalizer2. @stable ICU 4.4 */ - -#if !UCONFIG_NO_NORMALIZATION - -/** - * Returns a UNormalizer2 instance for Unicode NFC normalization. - * Same as unorm2_getInstance(NULL, "nfc", UNORM2_COMPOSE, pErrorCode). - * Returns an unmodifiable singleton instance. Do not delete it. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 49 - */ -U_STABLE const UNormalizer2 * U_EXPORT2 -unorm2_getNFCInstance(UErrorCode *pErrorCode); - -/** - * Returns a UNormalizer2 instance for Unicode NFD normalization. - * Same as unorm2_getInstance(NULL, "nfc", UNORM2_DECOMPOSE, pErrorCode). - * Returns an unmodifiable singleton instance. Do not delete it. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 49 - */ -U_STABLE const UNormalizer2 * U_EXPORT2 -unorm2_getNFDInstance(UErrorCode *pErrorCode); - -/** - * Returns a UNormalizer2 instance for Unicode NFKC normalization. - * Same as unorm2_getInstance(NULL, "nfkc", UNORM2_COMPOSE, pErrorCode). - * Returns an unmodifiable singleton instance. Do not delete it. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 49 - */ -U_STABLE const UNormalizer2 * U_EXPORT2 -unorm2_getNFKCInstance(UErrorCode *pErrorCode); - -/** - * Returns a UNormalizer2 instance for Unicode NFKD normalization. - * Same as unorm2_getInstance(NULL, "nfkc", UNORM2_DECOMPOSE, pErrorCode). - * Returns an unmodifiable singleton instance. Do not delete it. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 49 - */ -U_STABLE const UNormalizer2 * U_EXPORT2 -unorm2_getNFKDInstance(UErrorCode *pErrorCode); - -/** - * Returns a UNormalizer2 instance for Unicode NFKC_Casefold normalization. - * Same as unorm2_getInstance(NULL, "nfkc_cf", UNORM2_COMPOSE, pErrorCode). - * Returns an unmodifiable singleton instance. Do not delete it. - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested Normalizer2, if successful - * @stable ICU 49 - */ -U_STABLE const UNormalizer2 * U_EXPORT2 -unorm2_getNFKCCasefoldInstance(UErrorCode *pErrorCode); - -/** - * Returns a UNormalizer2 instance which uses the specified data file - * (packageName/name similar to ucnv_openPackage() and ures_open()/ResourceBundle) - * and which composes or decomposes text according to the specified mode. - * Returns an unmodifiable singleton instance. Do not delete it. - * - * Use packageName=NULL for data files that are part of ICU's own data. - * Use name="nfc" and UNORM2_COMPOSE/UNORM2_DECOMPOSE for Unicode standard NFC/NFD. - * Use name="nfkc" and UNORM2_COMPOSE/UNORM2_DECOMPOSE for Unicode standard NFKC/NFKD. - * Use name="nfkc_cf" and UNORM2_COMPOSE for Unicode standard NFKC_CF=NFKC_Casefold. - * - * @param packageName NULL for ICU built-in data, otherwise application data package name - * @param name "nfc" or "nfkc" or "nfkc_cf" or name of custom data file - * @param mode normalization mode (compose or decompose etc.) - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested UNormalizer2, if successful - * @stable ICU 4.4 - */ -U_STABLE const UNormalizer2 * U_EXPORT2 -unorm2_getInstance(const char *packageName, - const char *name, - UNormalization2Mode mode, - UErrorCode *pErrorCode); - -/** - * Constructs a filtered normalizer wrapping any UNormalizer2 instance - * and a filter set. - * Both are aliased and must not be modified or deleted while this object - * is used. - * The filter set should be frozen; otherwise the performance will suffer greatly. - * @param norm2 wrapped UNormalizer2 instance - * @param filterSet USet which determines the characters to be normalized - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the requested UNormalizer2, if successful - * @stable ICU 4.4 - */ -U_STABLE UNormalizer2 * U_EXPORT2 -unorm2_openFiltered(const UNormalizer2 *norm2, const USet *filterSet, UErrorCode *pErrorCode); - -/** - * Closes a UNormalizer2 instance from unorm2_openFiltered(). - * Do not close instances from unorm2_getInstance()! - * @param norm2 UNormalizer2 instance to be closed - * @stable ICU 4.4 - */ -U_STABLE void U_EXPORT2 -unorm2_close(UNormalizer2 *norm2); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUNormalizer2Pointer - * "Smart pointer" class, closes a UNormalizer2 via unorm2_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUNormalizer2Pointer, UNormalizer2, unorm2_close); - -U_NAMESPACE_END - -#endif - -/** - * Writes the normalized form of the source string to the destination string - * (replacing its contents) and returns the length of the destination string. - * The source and destination strings must be different buffers. - * @param norm2 UNormalizer2 instance - * @param src source string - * @param length length of the source string, or -1 if NUL-terminated - * @param dest destination string; its contents is replaced with normalized src - * @param capacity number of UChars that can be written to dest - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return dest - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -unorm2_normalize(const UNormalizer2 *norm2, - const UChar *src, int32_t length, - UChar *dest, int32_t capacity, - UErrorCode *pErrorCode); -/** - * Appends the normalized form of the second string to the first string - * (merging them at the boundary) and returns the length of the first string. - * The result is normalized if the first string was normalized. - * The first and second strings must be different buffers. - * @param norm2 UNormalizer2 instance - * @param first string, should be normalized - * @param firstLength length of the first string, or -1 if NUL-terminated - * @param firstCapacity number of UChars that can be written to first - * @param second string, will be normalized - * @param secondLength length of the source string, or -1 if NUL-terminated - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return first - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -unorm2_normalizeSecondAndAppend(const UNormalizer2 *norm2, - UChar *first, int32_t firstLength, int32_t firstCapacity, - const UChar *second, int32_t secondLength, - UErrorCode *pErrorCode); -/** - * Appends the second string to the first string - * (merging them at the boundary) and returns the length of the first string. - * The result is normalized if both the strings were normalized. - * The first and second strings must be different buffers. - * @param norm2 UNormalizer2 instance - * @param first string, should be normalized - * @param firstLength length of the first string, or -1 if NUL-terminated - * @param firstCapacity number of UChars that can be written to first - * @param second string, should be normalized - * @param secondLength length of the source string, or -1 if NUL-terminated - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return first - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -unorm2_append(const UNormalizer2 *norm2, - UChar *first, int32_t firstLength, int32_t firstCapacity, - const UChar *second, int32_t secondLength, - UErrorCode *pErrorCode); - -/** - * Gets the decomposition mapping of c. - * Roughly equivalent to normalizing the String form of c - * on a UNORM2_DECOMPOSE UNormalizer2 instance, but much faster, and except that this function - * returns a negative value and does not write a string - * if c does not have a decomposition mapping in this instance's data. - * This function is independent of the mode of the UNormalizer2. - * @param norm2 UNormalizer2 instance - * @param c code point - * @param decomposition String buffer which will be set to c's - * decomposition mapping, if there is one. - * @param capacity number of UChars that can be written to decomposition - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the non-negative length of c's decomposition, if there is one; otherwise a negative value - * @stable ICU 4.6 - */ -U_STABLE int32_t U_EXPORT2 -unorm2_getDecomposition(const UNormalizer2 *norm2, - UChar32 c, UChar *decomposition, int32_t capacity, - UErrorCode *pErrorCode); - -/** - * Gets the raw decomposition mapping of c. - * - * This is similar to the unorm2_getDecomposition() function but returns the - * raw decomposition mapping as specified in UnicodeData.txt or - * (for custom data) in the mapping files processed by the gennorm2 tool. - * By contrast, unorm2_getDecomposition() returns the processed, - * recursively-decomposed version of this mapping. - * - * When used on a standard NFKC Normalizer2 instance, - * unorm2_getRawDecomposition() returns the Unicode Decomposition_Mapping (dm) property. - * - * When used on a standard NFC Normalizer2 instance, - * it returns the Decomposition_Mapping only if the Decomposition_Type (dt) is Canonical (Can); - * in this case, the result contains either one or two code points (=1..4 UChars). - * - * This function is independent of the mode of the UNormalizer2. - * @param norm2 UNormalizer2 instance - * @param c code point - * @param decomposition String buffer which will be set to c's - * raw decomposition mapping, if there is one. - * @param capacity number of UChars that can be written to decomposition - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return the non-negative length of c's raw decomposition, if there is one; otherwise a negative value - * @stable ICU 49 - */ -U_STABLE int32_t U_EXPORT2 -unorm2_getRawDecomposition(const UNormalizer2 *norm2, - UChar32 c, UChar *decomposition, int32_t capacity, - UErrorCode *pErrorCode); - -/** - * Performs pairwise composition of a & b and returns the composite if there is one. - * - * Returns a composite code point c only if c has a two-way mapping to a+b. - * In standard Unicode normalization, this means that - * c has a canonical decomposition to a+b - * and c does not have the Full_Composition_Exclusion property. - * - * This function is independent of the mode of the UNormalizer2. - * @param norm2 UNormalizer2 instance - * @param a A (normalization starter) code point. - * @param b Another code point. - * @return The non-negative composite code point if there is one; otherwise a negative value. - * @stable ICU 49 - */ -U_STABLE UChar32 U_EXPORT2 -unorm2_composePair(const UNormalizer2 *norm2, UChar32 a, UChar32 b); - -/** - * Gets the combining class of c. - * The default implementation returns 0 - * but all standard implementations return the Unicode Canonical_Combining_Class value. - * @param norm2 UNormalizer2 instance - * @param c code point - * @return c's combining class - * @stable ICU 49 - */ -U_STABLE uint8_t U_EXPORT2 -unorm2_getCombiningClass(const UNormalizer2 *norm2, UChar32 c); - -/** - * Tests if the string is normalized. - * Internally, in cases where the quickCheck() method would return "maybe" - * (which is only possible for the two COMPOSE modes) this method - * resolves to "yes" or "no" to provide a definitive result, - * at the cost of doing more work in those cases. - * @param norm2 UNormalizer2 instance - * @param s input string - * @param length length of the string, or -1 if NUL-terminated - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return TRUE if s is normalized - * @stable ICU 4.4 - */ -U_STABLE UBool U_EXPORT2 -unorm2_isNormalized(const UNormalizer2 *norm2, - const UChar *s, int32_t length, - UErrorCode *pErrorCode); - -/** - * Tests if the string is normalized. - * For the two COMPOSE modes, the result could be "maybe" in cases that - * would take a little more work to resolve definitively. - * Use spanQuickCheckYes() and normalizeSecondAndAppend() for a faster - * combination of quick check + normalization, to avoid - * re-checking the "yes" prefix. - * @param norm2 UNormalizer2 instance - * @param s input string - * @param length length of the string, or -1 if NUL-terminated - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return UNormalizationCheckResult - * @stable ICU 4.4 - */ -U_STABLE UNormalizationCheckResult U_EXPORT2 -unorm2_quickCheck(const UNormalizer2 *norm2, - const UChar *s, int32_t length, - UErrorCode *pErrorCode); - -/** - * Returns the end of the normalized substring of the input string. - * In other words, with end=spanQuickCheckYes(s, ec); - * the substring UnicodeString(s, 0, end) - * will pass the quick check with a "yes" result. - * - * The returned end index is usually one or more characters before the - * "no" or "maybe" character: The end index is at a normalization boundary. - * (See the class documentation for more about normalization boundaries.) - * - * When the goal is a normalized string and most input strings are expected - * to be normalized already, then call this method, - * and if it returns a prefix shorter than the input string, - * copy that prefix and use normalizeSecondAndAppend() for the remainder. - * @param norm2 UNormalizer2 instance - * @param s input string - * @param length length of the string, or -1 if NUL-terminated - * @param pErrorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return "yes" span end index - * @stable ICU 4.4 - */ -U_STABLE int32_t U_EXPORT2 -unorm2_spanQuickCheckYes(const UNormalizer2 *norm2, - const UChar *s, int32_t length, - UErrorCode *pErrorCode); - -/** - * Tests if the character always has a normalization boundary before it, - * regardless of context. - * For details see the Normalizer2 base class documentation. - * @param norm2 UNormalizer2 instance - * @param c character to test - * @return TRUE if c has a normalization boundary before it - * @stable ICU 4.4 - */ -U_STABLE UBool U_EXPORT2 -unorm2_hasBoundaryBefore(const UNormalizer2 *norm2, UChar32 c); - -/** - * Tests if the character always has a normalization boundary after it, - * regardless of context. - * For details see the Normalizer2 base class documentation. - * @param norm2 UNormalizer2 instance - * @param c character to test - * @return TRUE if c has a normalization boundary after it - * @stable ICU 4.4 - */ -U_STABLE UBool U_EXPORT2 -unorm2_hasBoundaryAfter(const UNormalizer2 *norm2, UChar32 c); - -/** - * Tests if the character is normalization-inert. - * For details see the Normalizer2 base class documentation. - * @param norm2 UNormalizer2 instance - * @param c character to test - * @return TRUE if c is normalization-inert - * @stable ICU 4.4 - */ -U_STABLE UBool U_EXPORT2 -unorm2_isInert(const UNormalizer2 *norm2, UChar32 c); - -/** - * Option bit for unorm_compare: - * Both input strings are assumed to fulfill FCD conditions. - * @stable ICU 2.2 - */ -#define UNORM_INPUT_IS_FCD 0x20000 - -/** - * Option bit for unorm_compare: - * Perform case-insensitive comparison. - * @stable ICU 2.2 - */ -#define U_COMPARE_IGNORE_CASE 0x10000 - -#ifndef U_COMPARE_CODE_POINT_ORDER -/* see also unistr.h and ustring.h */ -/** - * Option bit for u_strCaseCompare, u_strcasecmp, unorm_compare, etc: - * Compare strings in code point order instead of code unit order. - * @stable ICU 2.2 - */ -#define U_COMPARE_CODE_POINT_ORDER 0x8000 -#endif - -/** - * Compares two strings for canonical equivalence. - * Further options include case-insensitive comparison and - * code point order (as opposed to code unit order). - * - * Canonical equivalence between two strings is defined as their normalized - * forms (NFD or NFC) being identical. - * This function compares strings incrementally instead of normalizing - * (and optionally case-folding) both strings entirely, - * improving performance significantly. - * - * Bulk normalization is only necessary if the strings do not fulfill the FCD - * conditions. Only in this case, and only if the strings are relatively long, - * is memory allocated temporarily. - * For FCD strings and short non-FCD strings there is no memory allocation. - * - * Semantically, this is equivalent to - * strcmp[CodePointOrder](NFD(foldCase(NFD(s1))), NFD(foldCase(NFD(s2)))) - * where code point order and foldCase are all optional. - * - * UAX 21 2.5 Caseless Matching specifies that for a canonical caseless match - * the case folding must be performed first, then the normalization. - * - * @param s1 First source string. - * @param length1 Length of first source string, or -1 if NUL-terminated. - * - * @param s2 Second source string. - * @param length2 Length of second source string, or -1 if NUL-terminated. - * - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Case-sensitive comparison in code unit order, and the input strings - * are quick-checked for FCD. - * - * - UNORM_INPUT_IS_FCD - * Set if the caller knows that both s1 and s2 fulfill the FCD conditions. - * If not set, the function will quickCheck for FCD - * and normalize if necessary. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_COMPARE_IGNORE_CASE - * Set to compare strings case-insensitively using case folding, - * instead of case-sensitively. - * If set, then the following case folding options are used. - * - * - Options as used with case-insensitive comparisons, currently: - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * (see u_strCaseCompare for details) - * - * - regular normalization options shifted left by UNORM_COMPARE_NORM_OPTIONS_SHIFT - * - * @param pErrorCode ICU error code in/out parameter. - * Must fulfill U_SUCCESS before the function call. - * @return <0 or 0 or >0 as usual for string comparisons - * - * @see unorm_normalize - * @see UNORM_FCD - * @see u_strCompare - * @see u_strCaseCompare - * - * @stable ICU 2.2 - */ -U_STABLE int32_t U_EXPORT2 -unorm_compare(const UChar *s1, int32_t length1, - const UChar *s2, int32_t length2, - uint32_t options, - UErrorCode *pErrorCode); - -#endif /* !UCONFIG_NO_NORMALIZATION */ -#endif /* __UNORM2_H__ */ diff --git a/win32/include/spidermonkey/unicode/unum.h b/win32/include/spidermonkey/unicode/unum.h deleted file mode 100755 index 34d54427..00000000 --- a/win32/include/spidermonkey/unicode/unum.h +++ /dev/null @@ -1,1380 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 1997-2015, International Business Machines Corporation and others. -* All Rights Reserved. -* Modification History: -* -* Date Name Description -* 06/24/99 helena Integrated Alan's NF enhancements and Java2 bug fixes -******************************************************************************* -*/ - -#ifndef _UNUM -#define _UNUM - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/localpointer.h" -#include "unicode/uloc.h" -#include "unicode/ucurr.h" -#include "unicode/umisc.h" -#include "unicode/parseerr.h" -#include "unicode/uformattable.h" -#include "unicode/udisplaycontext.h" - -/** - * \file - * \brief C API: NumberFormat - * - *

Number Format C API

- * - * Number Format C API Provides functions for - * formatting and parsing a number. Also provides methods for - * determining which locales have number formats, and what their names - * are. - *

- * UNumberFormat helps you to format and parse numbers for any locale. - * Your code can be completely independent of the locale conventions - * for decimal points, thousands-separators, or even the particular - * decimal digits used, or whether the number format is even decimal. - * There are different number format styles like decimal, currency, - * percent and spellout. - *

- * To format a number for the current Locale, use one of the static - * factory methods: - *

- * \code
- *    UChar myString[20];
- *    double myNumber = 7.0;
- *    UErrorCode status = U_ZERO_ERROR;
- *    UNumberFormat* nf = unum_open(UNUM_DEFAULT, NULL, -1, NULL, NULL, &status);
- *    unum_formatDouble(nf, myNumber, myString, 20, NULL, &status);
- *    printf(" Example 1: %s\n", austrdup(myString) ); //austrdup( a function used to convert UChar* to char*)
- * \endcode
- * 
- * If you are formatting multiple numbers, it is more efficient to get - * the format and use it multiple times so that the system doesn't - * have to fetch the information about the local language and country - * conventions multiple times. - *
- * \code
- * uint32_t i, resultlength, reslenneeded;
- * UErrorCode status = U_ZERO_ERROR;
- * UFieldPosition pos;
- * uint32_t a[] = { 123, 3333, -1234567 };
- * const uint32_t a_len = sizeof(a) / sizeof(a[0]);
- * UNumberFormat* nf;
- * UChar* result = NULL;
- *
- * nf = unum_open(UNUM_DEFAULT, NULL, -1, NULL, NULL, &status);
- * for (i = 0; i < a_len; i++) {
- *    resultlength=0;
- *    reslenneeded=unum_format(nf, a[i], NULL, resultlength, &pos, &status);
- *    result = NULL;
- *    if(status==U_BUFFER_OVERFLOW_ERROR){
- *       status=U_ZERO_ERROR;
- *       resultlength=reslenneeded+1;
- *       result=(UChar*)malloc(sizeof(UChar) * resultlength);
- *       unum_format(nf, a[i], result, resultlength, &pos, &status);
- *    }
- *    printf( " Example 2: %s\n", austrdup(result));
- *    free(result);
- * }
- * \endcode
- * 
- * To format a number for a different Locale, specify it in the - * call to unum_open(). - *
- * \code
- *     UNumberFormat* nf = unum_open(UNUM_DEFAULT, NULL, -1, "fr_FR", NULL, &success)
- * \endcode
- * 
- * You can use a NumberFormat API unum_parse() to parse. - *
- * \code
- *    UErrorCode status = U_ZERO_ERROR;
- *    int32_t pos=0;
- *    int32_t num;
- *    num = unum_parse(nf, str, u_strlen(str), &pos, &status);
- * \endcode
- * 
- * Use UNUM_DECIMAL to get the normal number format for that country. - * There are other static options available. Use UNUM_CURRENCY - * to get the currency number format for that country. Use UNUM_PERCENT - * to get a format for displaying percentages. With this format, a - * fraction from 0.53 is displayed as 53%. - *

- * Use a pattern to create either a DecimalFormat or a RuleBasedNumberFormat - * formatter. The pattern must conform to the syntax defined for those - * formatters. - *

- * You can also control the display of numbers with such function as - * unum_getAttributes() and unum_setAttributes(), which let you set the - * miminum fraction digits, grouping, etc. - * @see UNumberFormatAttributes for more details - *

- * You can also use forms of the parse and format methods with - * ParsePosition and UFieldPosition to allow you to: - *

    - *
  • (a) progressively parse through pieces of a string. - *
  • (b) align the decimal point and other areas. - *
- *

- * It is also possible to change or set the symbols used for a particular - * locale like the currency symbol, the grouping seperator , monetary seperator - * etc by making use of functions unum_setSymbols() and unum_getSymbols(). - */ - -/** A number formatter. - * For usage in C programs. - * @stable ICU 2.0 - */ -typedef void* UNumberFormat; - -/** The possible number format styles. - * @stable ICU 2.0 - */ -typedef enum UNumberFormatStyle { - /** - * Decimal format defined by a pattern string. - * @stable ICU 3.0 - */ - UNUM_PATTERN_DECIMAL=0, - /** - * Decimal format ("normal" style). - * @stable ICU 2.0 - */ - UNUM_DECIMAL=1, - /** - * Currency format (generic). - * Defaults to UNUM_CURRENCY_STANDARD style - * (using currency symbol, e.g., "$1.00", with non-accounting - * style for negative values e.g. using minus sign). - * The specific style may be specified using the -cf- locale key. - * @stable ICU 2.0 - */ - UNUM_CURRENCY=2, - /** - * Percent format - * @stable ICU 2.0 - */ - UNUM_PERCENT=3, - /** - * Scientific format - * @stable ICU 2.1 - */ - UNUM_SCIENTIFIC=4, - /** - * Spellout rule-based format. The default ruleset can be specified/changed using - * unum_setTextAttribute with UNUM_DEFAULT_RULESET; the available public rulesets - * can be listed using unum_getTextAttribute with UNUM_PUBLIC_RULESETS. - * @stable ICU 2.0 - */ - UNUM_SPELLOUT=5, - /** - * Ordinal rule-based format . The default ruleset can be specified/changed using - * unum_setTextAttribute with UNUM_DEFAULT_RULESET; the available public rulesets - * can be listed using unum_getTextAttribute with UNUM_PUBLIC_RULESETS. - * @stable ICU 3.0 - */ - UNUM_ORDINAL=6, - /** - * Duration rule-based format - * @stable ICU 3.0 - */ - UNUM_DURATION=7, - /** - * Numbering system rule-based format - * @stable ICU 4.2 - */ - UNUM_NUMBERING_SYSTEM=8, - /** - * Rule-based format defined by a pattern string. - * @stable ICU 3.0 - */ - UNUM_PATTERN_RULEBASED=9, - /** - * Currency format with an ISO currency code, e.g., "USD1.00". - * @stable ICU 4.8 - */ - UNUM_CURRENCY_ISO=10, - /** - * Currency format with a pluralized currency name, - * e.g., "1.00 US dollar" and "3.00 US dollars". - * @stable ICU 4.8 - */ - UNUM_CURRENCY_PLURAL=11, - /** - * Currency format for accounting, e.g., "($3.00)" for - * negative currency amount instead of "-$3.00" ({@link #UNUM_CURRENCY}). - * Overrides any style specified using -cf- key in locale. - * @stable ICU 53 - */ - UNUM_CURRENCY_ACCOUNTING=12, - /** - * Currency format with a currency symbol given CASH usage, e.g., - * "NT$3" instead of "NT$3.23". - * @stable ICU 54 - */ - UNUM_CASH_CURRENCY=13, - /** - * Decimal format expressed using compact notation - * (short form, corresponds to UNumberCompactStyle=UNUM_SHORT) - * e.g. "23K", "45B" - * @stable ICU 56 - */ - UNUM_DECIMAL_COMPACT_SHORT=14, - /** - * Decimal format expressed using compact notation - * (long form, corresponds to UNumberCompactStyle=UNUM_LONG) - * e.g. "23 thousand", "45 billion" - * @stable ICU 56 - */ - UNUM_DECIMAL_COMPACT_LONG=15, - /** - * Currency format with a currency symbol, e.g., "$1.00", - * using non-accounting style for negative values (e.g. minus sign). - * Overrides any style specified using -cf- key in locale. - * @stable ICU 56 - */ - UNUM_CURRENCY_STANDARD=16, - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UNumberFormatStyle value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UNUM_FORMAT_STYLE_COUNT=17, -#endif // U_HIDE_DEPRECATED_API - - /** - * Default format - * @stable ICU 2.0 - */ - UNUM_DEFAULT = UNUM_DECIMAL, - /** - * Alias for UNUM_PATTERN_DECIMAL - * @stable ICU 3.0 - */ - UNUM_IGNORE = UNUM_PATTERN_DECIMAL -} UNumberFormatStyle; - -/** The possible number format rounding modes. - * @stable ICU 2.0 - */ -typedef enum UNumberFormatRoundingMode { - UNUM_ROUND_CEILING, - UNUM_ROUND_FLOOR, - UNUM_ROUND_DOWN, - UNUM_ROUND_UP, - /** - * Half-even rounding - * @stable, ICU 3.8 - */ - UNUM_ROUND_HALFEVEN, -#ifndef U_HIDE_DEPRECATED_API - /** - * Half-even rounding, misspelled name - * @deprecated, ICU 3.8 - */ - UNUM_FOUND_HALFEVEN = UNUM_ROUND_HALFEVEN, -#endif /* U_HIDE_DEPRECATED_API */ - UNUM_ROUND_HALFDOWN = UNUM_ROUND_HALFEVEN + 1, - UNUM_ROUND_HALFUP, - /** - * ROUND_UNNECESSARY reports an error if formatted result is not exact. - * @stable ICU 4.8 - */ - UNUM_ROUND_UNNECESSARY -} UNumberFormatRoundingMode; - -/** The possible number format pad positions. - * @stable ICU 2.0 - */ -typedef enum UNumberFormatPadPosition { - UNUM_PAD_BEFORE_PREFIX, - UNUM_PAD_AFTER_PREFIX, - UNUM_PAD_BEFORE_SUFFIX, - UNUM_PAD_AFTER_SUFFIX -} UNumberFormatPadPosition; - -/** - * Constants for specifying short or long format. - * @stable ICU 51 - */ -typedef enum UNumberCompactStyle { - /** @stable ICU 51 */ - UNUM_SHORT, - /** @stable ICU 51 */ - UNUM_LONG - /** @stable ICU 51 */ -} UNumberCompactStyle; - -/** - * Constants for specifying currency spacing - * @stable ICU 4.8 - */ -enum UCurrencySpacing { - /** @stable ICU 4.8 */ - UNUM_CURRENCY_MATCH, - /** @stable ICU 4.8 */ - UNUM_CURRENCY_SURROUNDING_MATCH, - /** @stable ICU 4.8 */ - UNUM_CURRENCY_INSERT, - - // Do not conditionalize the following with #ifndef U_HIDE_DEPRECATED_API, - // it is needed for layout of DecimalFormatSymbols object. - /** - * One more than the highest normal UCurrencySpacing value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UNUM_CURRENCY_SPACING_COUNT -}; -typedef enum UCurrencySpacing UCurrencySpacing; /**< @stable ICU 4.8 */ - - -/** - * FieldPosition and UFieldPosition selectors for format fields - * defined by NumberFormat and UNumberFormat. - * @stable ICU 49 - */ -typedef enum UNumberFormatFields { - /** @stable ICU 49 */ - UNUM_INTEGER_FIELD, - /** @stable ICU 49 */ - UNUM_FRACTION_FIELD, - /** @stable ICU 49 */ - UNUM_DECIMAL_SEPARATOR_FIELD, - /** @stable ICU 49 */ - UNUM_EXPONENT_SYMBOL_FIELD, - /** @stable ICU 49 */ - UNUM_EXPONENT_SIGN_FIELD, - /** @stable ICU 49 */ - UNUM_EXPONENT_FIELD, - /** @stable ICU 49 */ - UNUM_GROUPING_SEPARATOR_FIELD, - /** @stable ICU 49 */ - UNUM_CURRENCY_FIELD, - /** @stable ICU 49 */ - UNUM_PERCENT_FIELD, - /** @stable ICU 49 */ - UNUM_PERMILL_FIELD, - /** @stable ICU 49 */ - UNUM_SIGN_FIELD, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UNumberFormatFields value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UNUM_FIELD_COUNT -#endif // U_HIDE_DEPRECATED_API -} UNumberFormatFields; - - -/** - * Create and return a new UNumberFormat for formatting and parsing - * numbers. A UNumberFormat may be used to format numbers by calling - * {@link #unum_format }, and to parse numbers by calling {@link #unum_parse }. - * The caller must call {@link #unum_close } when done to release resources - * used by this object. - * @param style The type of number format to open: one of - * UNUM_DECIMAL, UNUM_CURRENCY, UNUM_PERCENT, UNUM_SCIENTIFIC, - * UNUM_CURRENCY_ISO, UNUM_CURRENCY_PLURAL, UNUM_SPELLOUT, - * UNUM_ORDINAL, UNUM_DURATION, UNUM_NUMBERING_SYSTEM, - * UNUM_PATTERN_DECIMAL, UNUM_PATTERN_RULEBASED, or UNUM_DEFAULT. - * If UNUM_PATTERN_DECIMAL or UNUM_PATTERN_RULEBASED is passed then the - * number format is opened using the given pattern, which must conform - * to the syntax described in DecimalFormat or RuleBasedNumberFormat, - * respectively. - * @param pattern A pattern specifying the format to use. - * This parameter is ignored unless the style is - * UNUM_PATTERN_DECIMAL or UNUM_PATTERN_RULEBASED. - * @param patternLength The number of characters in the pattern, or -1 - * if null-terminated. This parameter is ignored unless the style is - * UNUM_PATTERN. - * @param locale A locale identifier to use to determine formatting - * and parsing conventions, or NULL to use the default locale. - * @param parseErr A pointer to a UParseError struct to receive the - * details of any parsing errors, or NULL if no parsing error details - * are desired. - * @param status A pointer to an input-output UErrorCode. - * @return A pointer to a newly created UNumberFormat, or NULL if an - * error occurred. - * @see unum_close - * @see DecimalFormat - * @stable ICU 2.0 - */ -U_STABLE UNumberFormat* U_EXPORT2 -unum_open( UNumberFormatStyle style, - const UChar* pattern, - int32_t patternLength, - const char* locale, - UParseError* parseErr, - UErrorCode* status); - - -/** -* Close a UNumberFormat. -* Once closed, a UNumberFormat may no longer be used. -* @param fmt The formatter to close. -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -unum_close(UNumberFormat* fmt); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUNumberFormatPointer - * "Smart pointer" class, closes a UNumberFormat via unum_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUNumberFormatPointer, UNumberFormat, unum_close); - -U_NAMESPACE_END - -#endif - -/** - * Open a copy of a UNumberFormat. - * This function performs a deep copy. - * @param fmt The format to copy - * @param status A pointer to an UErrorCode to receive any errors. - * @return A pointer to a UNumberFormat identical to fmt. - * @stable ICU 2.0 - */ -U_STABLE UNumberFormat* U_EXPORT2 -unum_clone(const UNumberFormat *fmt, - UErrorCode *status); - -/** -* Format an integer using a UNumberFormat. -* The integer will be formatted according to the UNumberFormat's locale. -* @param fmt The formatter to use. -* @param number The number to format. -* @param result A pointer to a buffer to receive the NULL-terminated formatted number. If -* the formatted number fits into dest but cannot be NULL-terminated (length == resultLength) -* then the error code is set to U_STRING_NOT_TERMINATED_WARNING. If the formatted number -* doesn't fit into result then the error code is set to U_BUFFER_OVERFLOW_ERROR. -* @param resultLength The maximum size of result. -* @param pos A pointer to a UFieldPosition. On input, position->field -* is read. On output, position->beginIndex and position->endIndex indicate -* the beginning and ending indices of field number position->field, if such -* a field exists. This parameter may be NULL, in which case no field -* @param status A pointer to an UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see unum_formatInt64 -* @see unum_formatDouble -* @see unum_parse -* @see unum_parseInt64 -* @see unum_parseDouble -* @see UFieldPosition -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -unum_format( const UNumberFormat* fmt, - int32_t number, - UChar* result, - int32_t resultLength, - UFieldPosition *pos, - UErrorCode* status); - -/** -* Format an int64 using a UNumberFormat. -* The int64 will be formatted according to the UNumberFormat's locale. -* @param fmt The formatter to use. -* @param number The number to format. -* @param result A pointer to a buffer to receive the NULL-terminated formatted number. If -* the formatted number fits into dest but cannot be NULL-terminated (length == resultLength) -* then the error code is set to U_STRING_NOT_TERMINATED_WARNING. If the formatted number -* doesn't fit into result then the error code is set to U_BUFFER_OVERFLOW_ERROR. -* @param resultLength The maximum size of result. -* @param pos A pointer to a UFieldPosition. On input, position->field -* is read. On output, position->beginIndex and position->endIndex indicate -* the beginning and ending indices of field number position->field, if such -* a field exists. This parameter may be NULL, in which case no field -* @param status A pointer to an UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see unum_format -* @see unum_formatDouble -* @see unum_parse -* @see unum_parseInt64 -* @see unum_parseDouble -* @see UFieldPosition -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -unum_formatInt64(const UNumberFormat *fmt, - int64_t number, - UChar* result, - int32_t resultLength, - UFieldPosition *pos, - UErrorCode* status); - -/** -* Format a double using a UNumberFormat. -* The double will be formatted according to the UNumberFormat's locale. -* @param fmt The formatter to use. -* @param number The number to format. -* @param result A pointer to a buffer to receive the NULL-terminated formatted number. If -* the formatted number fits into dest but cannot be NULL-terminated (length == resultLength) -* then the error code is set to U_STRING_NOT_TERMINATED_WARNING. If the formatted number -* doesn't fit into result then the error code is set to U_BUFFER_OVERFLOW_ERROR. -* @param resultLength The maximum size of result. -* @param pos A pointer to a UFieldPosition. On input, position->field -* is read. On output, position->beginIndex and position->endIndex indicate -* the beginning and ending indices of field number position->field, if such -* a field exists. This parameter may be NULL, in which case no field -* @param status A pointer to an UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see unum_format -* @see unum_formatInt64 -* @see unum_parse -* @see unum_parseInt64 -* @see unum_parseDouble -* @see UFieldPosition -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -unum_formatDouble( const UNumberFormat* fmt, - double number, - UChar* result, - int32_t resultLength, - UFieldPosition *pos, /* 0 if ignore */ - UErrorCode* status); - -/** -* Format a decimal number using a UNumberFormat. -* The number will be formatted according to the UNumberFormat's locale. -* The syntax of the input number is a "numeric string" -* as defined in the Decimal Arithmetic Specification, available at -* http://speleotrove.com/decimal -* @param fmt The formatter to use. -* @param number The number to format. -* @param length The length of the input number, or -1 if the input is nul-terminated. -* @param result A pointer to a buffer to receive the NULL-terminated formatted number. If -* the formatted number fits into dest but cannot be NULL-terminated (length == resultLength) -* then the error code is set to U_STRING_NOT_TERMINATED_WARNING. If the formatted number -* doesn't fit into result then the error code is set to U_BUFFER_OVERFLOW_ERROR. -* @param resultLength The maximum size of result. -* @param pos A pointer to a UFieldPosition. On input, position->field -* is read. On output, position->beginIndex and position->endIndex indicate -* the beginning and ending indices of field number position->field, if such -* a field exists. This parameter may be NULL, in which case it is ignored. -* @param status A pointer to an UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see unum_format -* @see unum_formatInt64 -* @see unum_parse -* @see unum_parseInt64 -* @see unum_parseDouble -* @see UFieldPosition -* @stable ICU 4.4 -*/ -U_STABLE int32_t U_EXPORT2 -unum_formatDecimal( const UNumberFormat* fmt, - const char * number, - int32_t length, - UChar* result, - int32_t resultLength, - UFieldPosition *pos, /* 0 if ignore */ - UErrorCode* status); - -/** - * Format a double currency amount using a UNumberFormat. - * The double will be formatted according to the UNumberFormat's locale. - * @param fmt the formatter to use - * @param number the number to format - * @param currency the 3-letter null-terminated ISO 4217 currency code - * @param result A pointer to a buffer to receive the NULL-terminated formatted number. If - * the formatted number fits into dest but cannot be NULL-terminated (length == resultLength) - * then the error code is set to U_STRING_NOT_TERMINATED_WARNING. If the formatted number - * doesn't fit into result then the error code is set to U_BUFFER_OVERFLOW_ERROR. - * @param resultLength the maximum number of UChars to write to result - * @param pos a pointer to a UFieldPosition. On input, - * position->field is read. On output, position->beginIndex and - * position->endIndex indicate the beginning and ending indices of - * field number position->field, if such a field exists. This - * parameter may be NULL, in which case it is ignored. - * @param status a pointer to an input-output UErrorCode - * @return the total buffer size needed; if greater than resultLength, - * the output was truncated. - * @see unum_formatDouble - * @see unum_parseDoubleCurrency - * @see UFieldPosition - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -unum_formatDoubleCurrency(const UNumberFormat* fmt, - double number, - UChar* currency, - UChar* result, - int32_t resultLength, - UFieldPosition* pos, - UErrorCode* status); - -/** - * Format a UFormattable into a string. - * @param fmt the formatter to use - * @param number the number to format, as a UFormattable - * @param result A pointer to a buffer to receive the NULL-terminated formatted number. If - * the formatted number fits into dest but cannot be NULL-terminated (length == resultLength) - * then the error code is set to U_STRING_NOT_TERMINATED_WARNING. If the formatted number - * doesn't fit into result then the error code is set to U_BUFFER_OVERFLOW_ERROR. - * @param resultLength the maximum number of UChars to write to result - * @param pos a pointer to a UFieldPosition. On input, - * position->field is read. On output, position->beginIndex and - * position->endIndex indicate the beginning and ending indices of - * field number position->field, if such a field exists. This - * parameter may be NULL, in which case it is ignored. - * @param status a pointer to an input-output UErrorCode - * @return the total buffer size needed; if greater than resultLength, - * the output was truncated. Will return 0 on error. - * @see unum_parseToUFormattable - * @stable ICU 52 - */ -U_STABLE int32_t U_EXPORT2 -unum_formatUFormattable(const UNumberFormat* fmt, - const UFormattable *number, - UChar *result, - int32_t resultLength, - UFieldPosition *pos, - UErrorCode *status); - -/** -* Parse a string into an integer using a UNumberFormat. -* The string will be parsed according to the UNumberFormat's locale. -* Note: parsing is not supported for styles UNUM_DECIMAL_COMPACT_SHORT -* and UNUM_DECIMAL_COMPACT_LONG. -* @param fmt The formatter to use. -* @param text The text to parse. -* @param textLength The length of text, or -1 if null-terminated. -* @param parsePos If not NULL, on input a pointer to an integer specifying the offset at which -* to begin parsing. If not NULL, on output the offset at which parsing ended. -* @param status A pointer to an UErrorCode to receive any errors -* @return The value of the parsed integer -* @see unum_parseInt64 -* @see unum_parseDouble -* @see unum_format -* @see unum_formatInt64 -* @see unum_formatDouble -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -unum_parse( const UNumberFormat* fmt, - const UChar* text, - int32_t textLength, - int32_t *parsePos /* 0 = start */, - UErrorCode *status); - -/** -* Parse a string into an int64 using a UNumberFormat. -* The string will be parsed according to the UNumberFormat's locale. -* Note: parsing is not supported for styles UNUM_DECIMAL_COMPACT_SHORT -* and UNUM_DECIMAL_COMPACT_LONG. -* @param fmt The formatter to use. -* @param text The text to parse. -* @param textLength The length of text, or -1 if null-terminated. -* @param parsePos If not NULL, on input a pointer to an integer specifying the offset at which -* to begin parsing. If not NULL, on output the offset at which parsing ended. -* @param status A pointer to an UErrorCode to receive any errors -* @return The value of the parsed integer -* @see unum_parse -* @see unum_parseDouble -* @see unum_format -* @see unum_formatInt64 -* @see unum_formatDouble -* @stable ICU 2.8 -*/ -U_STABLE int64_t U_EXPORT2 -unum_parseInt64(const UNumberFormat* fmt, - const UChar* text, - int32_t textLength, - int32_t *parsePos /* 0 = start */, - UErrorCode *status); - -/** -* Parse a string into a double using a UNumberFormat. -* The string will be parsed according to the UNumberFormat's locale. -* Note: parsing is not supported for styles UNUM_DECIMAL_COMPACT_SHORT -* and UNUM_DECIMAL_COMPACT_LONG. -* @param fmt The formatter to use. -* @param text The text to parse. -* @param textLength The length of text, or -1 if null-terminated. -* @param parsePos If not NULL, on input a pointer to an integer specifying the offset at which -* to begin parsing. If not NULL, on output the offset at which parsing ended. -* @param status A pointer to an UErrorCode to receive any errors -* @return The value of the parsed double -* @see unum_parse -* @see unum_parseInt64 -* @see unum_format -* @see unum_formatInt64 -* @see unum_formatDouble -* @stable ICU 2.0 -*/ -U_STABLE double U_EXPORT2 -unum_parseDouble( const UNumberFormat* fmt, - const UChar* text, - int32_t textLength, - int32_t *parsePos /* 0 = start */, - UErrorCode *status); - - -/** -* Parse a number from a string into an unformatted numeric string using a UNumberFormat. -* The input string will be parsed according to the UNumberFormat's locale. -* The syntax of the output is a "numeric string" -* as defined in the Decimal Arithmetic Specification, available at -* http://speleotrove.com/decimal -* Note: parsing is not supported for styles UNUM_DECIMAL_COMPACT_SHORT -* and UNUM_DECIMAL_COMPACT_LONG. -* @param fmt The formatter to use. -* @param text The text to parse. -* @param textLength The length of text, or -1 if null-terminated. -* @param parsePos If not NULL, on input a pointer to an integer specifying the offset at which -* to begin parsing. If not NULL, on output the offset at which parsing ended. -* @param outBuf A (char *) buffer to receive the parsed number as a string. The output string -* will be nul-terminated if there is sufficient space. -* @param outBufLength The size of the output buffer. May be zero, in which case -* the outBuf pointer may be NULL, and the function will return the -* size of the output string. -* @param status A pointer to an UErrorCode to receive any errors -* @return the length of the output string, not including any terminating nul. -* @see unum_parse -* @see unum_parseInt64 -* @see unum_format -* @see unum_formatInt64 -* @see unum_formatDouble -* @stable ICU 4.4 -*/ -U_STABLE int32_t U_EXPORT2 -unum_parseDecimal(const UNumberFormat* fmt, - const UChar* text, - int32_t textLength, - int32_t *parsePos /* 0 = start */, - char *outBuf, - int32_t outBufLength, - UErrorCode *status); - -/** - * Parse a string into a double and a currency using a UNumberFormat. - * The string will be parsed according to the UNumberFormat's locale. - * @param fmt the formatter to use - * @param text the text to parse - * @param textLength the length of text, or -1 if null-terminated - * @param parsePos a pointer to an offset index into text at which to - * begin parsing. On output, *parsePos will point after the last - * parsed character. This parameter may be NULL, in which case parsing - * begins at offset 0. - * @param currency a pointer to the buffer to receive the parsed null- - * terminated currency. This buffer must have a capacity of at least - * 4 UChars. - * @param status a pointer to an input-output UErrorCode - * @return the parsed double - * @see unum_parseDouble - * @see unum_formatDoubleCurrency - * @stable ICU 3.0 - */ -U_STABLE double U_EXPORT2 -unum_parseDoubleCurrency(const UNumberFormat* fmt, - const UChar* text, - int32_t textLength, - int32_t* parsePos, /* 0 = start */ - UChar* currency, - UErrorCode* status); - -/** - * Parse a UChar string into a UFormattable. - * Example code: - * \snippet test/cintltst/cnumtst.c unum_parseToUFormattable - * Note: parsing is not supported for styles UNUM_DECIMAL_COMPACT_SHORT - * and UNUM_DECIMAL_COMPACT_LONG. - * @param fmt the formatter to use - * @param result the UFormattable to hold the result. If NULL, a new UFormattable will be allocated (which the caller must close with ufmt_close). - * @param text the text to parse - * @param textLength the length of text, or -1 if null-terminated - * @param parsePos a pointer to an offset index into text at which to - * begin parsing. On output, *parsePos will point after the last - * parsed character. This parameter may be NULL in which case parsing - * begins at offset 0. - * @param status a pointer to an input-output UErrorCode - * @return the UFormattable. Will be ==result unless NULL was passed in for result, in which case it will be the newly opened UFormattable. - * @see ufmt_getType - * @see ufmt_close - * @stable ICU 52 - */ -U_STABLE UFormattable* U_EXPORT2 -unum_parseToUFormattable(const UNumberFormat* fmt, - UFormattable *result, - const UChar* text, - int32_t textLength, - int32_t* parsePos, /* 0 = start */ - UErrorCode* status); - -/** - * Set the pattern used by a UNumberFormat. This can only be used - * on a DecimalFormat, other formats return U_UNSUPPORTED_ERROR - * in the status. - * @param format The formatter to set. - * @param localized TRUE if the pattern is localized, FALSE otherwise. - * @param pattern The new pattern - * @param patternLength The length of pattern, or -1 if null-terminated. - * @param parseError A pointer to UParseError to recieve information - * about errors occurred during parsing, or NULL if no parse error - * information is desired. - * @param status A pointer to an input-output UErrorCode. - * @see unum_toPattern - * @see DecimalFormat - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -unum_applyPattern( UNumberFormat *format, - UBool localized, - const UChar *pattern, - int32_t patternLength, - UParseError *parseError, - UErrorCode *status - ); - -/** -* Get a locale for which decimal formatting patterns are available. -* A UNumberFormat in a locale returned by this function will perform the correct -* formatting and parsing for the locale. The results of this call are not -* valid for rule-based number formats. -* @param localeIndex The index of the desired locale. -* @return A locale for which number formatting patterns are available, or 0 if none. -* @see unum_countAvailable -* @stable ICU 2.0 -*/ -U_STABLE const char* U_EXPORT2 -unum_getAvailable(int32_t localeIndex); - -/** -* Determine how many locales have decimal formatting patterns available. The -* results of this call are not valid for rule-based number formats. -* This function is useful for determining the loop ending condition for -* calls to {@link #unum_getAvailable }. -* @return The number of locales for which decimal formatting patterns are available. -* @see unum_getAvailable -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -unum_countAvailable(void); - -#if UCONFIG_HAVE_PARSEALLINPUT -/* The UNumberFormatAttributeValue type cannot be #ifndef U_HIDE_INTERNAL_API, needed for .h variable declaration */ -/** - * @internal - */ -typedef enum UNumberFormatAttributeValue { -#ifndef U_HIDE_INTERNAL_API - /** @internal */ - UNUM_NO = 0, - /** @internal */ - UNUM_YES = 1, - /** @internal */ - UNUM_MAYBE = 2 -#else - /** @internal */ - UNUM_FORMAT_ATTRIBUTE_VALUE_HIDDEN -#endif /* U_HIDE_INTERNAL_API */ -} UNumberFormatAttributeValue; -#endif - -/** The possible UNumberFormat numeric attributes @stable ICU 2.0 */ -typedef enum UNumberFormatAttribute { - /** Parse integers only */ - UNUM_PARSE_INT_ONLY, - /** Use grouping separator */ - UNUM_GROUPING_USED, - /** Always show decimal point */ - UNUM_DECIMAL_ALWAYS_SHOWN, - /** Maximum integer digits */ - UNUM_MAX_INTEGER_DIGITS, - /** Minimum integer digits */ - UNUM_MIN_INTEGER_DIGITS, - /** Integer digits */ - UNUM_INTEGER_DIGITS, - /** Maximum fraction digits */ - UNUM_MAX_FRACTION_DIGITS, - /** Minimum fraction digits */ - UNUM_MIN_FRACTION_DIGITS, - /** Fraction digits */ - UNUM_FRACTION_DIGITS, - /** Multiplier */ - UNUM_MULTIPLIER, - /** Grouping size */ - UNUM_GROUPING_SIZE, - /** Rounding Mode */ - UNUM_ROUNDING_MODE, - /** Rounding increment */ - UNUM_ROUNDING_INCREMENT, - /** The width to which the output of format() is padded. */ - UNUM_FORMAT_WIDTH, - /** The position at which padding will take place. */ - UNUM_PADDING_POSITION, - /** Secondary grouping size */ - UNUM_SECONDARY_GROUPING_SIZE, - /** Use significant digits - * @stable ICU 3.0 */ - UNUM_SIGNIFICANT_DIGITS_USED, - /** Minimum significant digits - * @stable ICU 3.0 */ - UNUM_MIN_SIGNIFICANT_DIGITS, - /** Maximum significant digits - * @stable ICU 3.0 */ - UNUM_MAX_SIGNIFICANT_DIGITS, - /** Lenient parse mode used by rule-based formats. - * @stable ICU 3.0 - */ - UNUM_LENIENT_PARSE, -#if UCONFIG_HAVE_PARSEALLINPUT - /** Consume all input. (may use fastpath). Set to UNUM_YES (require fastpath), UNUM_NO (skip fastpath), or UNUM_MAYBE (heuristic). - * This is an internal ICU API. Do not use. - * @internal - */ - UNUM_PARSE_ALL_INPUT = 20, -#endif - /** - * Scale, which adjusts the position of the - * decimal point when formatting. Amounts will be multiplied by 10 ^ (scale) - * before they are formatted. The default value for the scale is 0 ( no adjustment ). - * - *

Example: setting the scale to 3, 123 formats as "123,000" - *

Example: setting the scale to -4, 123 formats as "0.0123" - * - * @stable ICU 51 */ - UNUM_SCALE = 21, -#ifndef U_HIDE_INTERNAL_API - /** - * Minimum grouping digits, technology preview. - * See DecimalFormat::getMinimumGroupingDigits(). - * - * @internal technology preview - */ - UNUM_MINIMUM_GROUPING_DIGITS = 22, - /* TODO: test C API when it becomes @draft */ -#endif /* U_HIDE_INTERNAL_API */ - - /** - * if this attribute is set to 0, it is set to UNUM_CURRENCY_STANDARD purpose, - * otherwise it is UNUM_CURRENCY_CASH purpose - * Default: 0 (UNUM_CURRENCY_STANDARD purpose) - * @stable ICU 54 - */ - UNUM_CURRENCY_USAGE = 23, - - /* The following cannot be #ifndef U_HIDE_INTERNAL_API, needed in .h file variable declararions */ - /** One below the first bitfield-boolean item. - * All items after this one are stored in boolean form. - * @internal */ - UNUM_MAX_NONBOOLEAN_ATTRIBUTE = 0x0FFF, - - /** If 1, specifies that if setting the "max integer digits" attribute would truncate a value, set an error status rather than silently truncating. - * For example, formatting the value 1234 with 4 max int digits would succeed, but formatting 12345 would fail. There is no effect on parsing. - * Default: 0 (not set) - * @stable ICU 50 - */ - UNUM_FORMAT_FAIL_IF_MORE_THAN_MAX_DIGITS = 0x1000, - /** - * if this attribute is set to 1, specifies that, if the pattern doesn't contain an exponent, the exponent will not be parsed. If the pattern does contain an exponent, this attribute has no effect. - * Has no effect on formatting. - * Default: 0 (unset) - * @stable ICU 50 - */ - UNUM_PARSE_NO_EXPONENT, - - /** - * if this attribute is set to 1, specifies that, if the pattern contains a - * decimal mark the input is required to have one. If this attribute is set to 0, - * specifies that input does not have to contain a decimal mark. - * Has no effect on formatting. - * Default: 0 (unset) - * @stable ICU 54 - */ - UNUM_PARSE_DECIMAL_MARK_REQUIRED = 0x1002, - - /* The following cannot be #ifndef U_HIDE_INTERNAL_API, needed in .h file variable declararions */ - /** Limit of boolean attributes. - * @internal */ - UNUM_LIMIT_BOOLEAN_ATTRIBUTE = 0x1003 -} UNumberFormatAttribute; - -/** -* Get a numeric attribute associated with a UNumberFormat. -* An example of a numeric attribute is the number of integer digits a formatter will produce. -* @param fmt The formatter to query. -* @param attr The attribute to query; one of UNUM_PARSE_INT_ONLY, UNUM_GROUPING_USED, -* UNUM_DECIMAL_ALWAYS_SHOWN, UNUM_MAX_INTEGER_DIGITS, UNUM_MIN_INTEGER_DIGITS, UNUM_INTEGER_DIGITS, -* UNUM_MAX_FRACTION_DIGITS, UNUM_MIN_FRACTION_DIGITS, UNUM_FRACTION_DIGITS, UNUM_MULTIPLIER, -* UNUM_GROUPING_SIZE, UNUM_ROUNDING_MODE, UNUM_FORMAT_WIDTH, UNUM_PADDING_POSITION, UNUM_SECONDARY_GROUPING_SIZE, -* UNUM_SCALE, UNUM_MINIMUM_GROUPING_DIGITS. -* @return The value of attr. -* @see unum_setAttribute -* @see unum_getDoubleAttribute -* @see unum_setDoubleAttribute -* @see unum_getTextAttribute -* @see unum_setTextAttribute -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -unum_getAttribute(const UNumberFormat* fmt, - UNumberFormatAttribute attr); - -/** -* Set a numeric attribute associated with a UNumberFormat. -* An example of a numeric attribute is the number of integer digits a formatter will produce. If the -* formatter does not understand the attribute, the call is ignored. Rule-based formatters only understand -* the lenient-parse attribute. -* @param fmt The formatter to set. -* @param attr The attribute to set; one of UNUM_PARSE_INT_ONLY, UNUM_GROUPING_USED, -* UNUM_DECIMAL_ALWAYS_SHOWN, UNUM_MAX_INTEGER_DIGITS, UNUM_MIN_INTEGER_DIGITS, UNUM_INTEGER_DIGITS, -* UNUM_MAX_FRACTION_DIGITS, UNUM_MIN_FRACTION_DIGITS, UNUM_FRACTION_DIGITS, UNUM_MULTIPLIER, -* UNUM_GROUPING_SIZE, UNUM_ROUNDING_MODE, UNUM_FORMAT_WIDTH, UNUM_PADDING_POSITION, UNUM_SECONDARY_GROUPING_SIZE, -* UNUM_LENIENT_PARSE, UNUM_SCALE, UNUM_MINIMUM_GROUPING_DIGITS. -* @param newValue The new value of attr. -* @see unum_getAttribute -* @see unum_getDoubleAttribute -* @see unum_setDoubleAttribute -* @see unum_getTextAttribute -* @see unum_setTextAttribute -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -unum_setAttribute( UNumberFormat* fmt, - UNumberFormatAttribute attr, - int32_t newValue); - - -/** -* Get a numeric attribute associated with a UNumberFormat. -* An example of a numeric attribute is the number of integer digits a formatter will produce. -* If the formatter does not understand the attribute, -1 is returned. -* @param fmt The formatter to query. -* @param attr The attribute to query; e.g. UNUM_ROUNDING_INCREMENT. -* @return The value of attr. -* @see unum_getAttribute -* @see unum_setAttribute -* @see unum_setDoubleAttribute -* @see unum_getTextAttribute -* @see unum_setTextAttribute -* @stable ICU 2.0 -*/ -U_STABLE double U_EXPORT2 -unum_getDoubleAttribute(const UNumberFormat* fmt, - UNumberFormatAttribute attr); - -/** -* Set a numeric attribute associated with a UNumberFormat. -* An example of a numeric attribute is the number of integer digits a formatter will produce. -* If the formatter does not understand the attribute, this call is ignored. -* @param fmt The formatter to set. -* @param attr The attribute to set; e.g. UNUM_ROUNDING_INCREMENT. -* @param newValue The new value of attr. -* @see unum_getAttribute -* @see unum_setAttribute -* @see unum_getDoubleAttribute -* @see unum_getTextAttribute -* @see unum_setTextAttribute -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -unum_setDoubleAttribute( UNumberFormat* fmt, - UNumberFormatAttribute attr, - double newValue); - -/** The possible UNumberFormat text attributes @stable ICU 2.0*/ -typedef enum UNumberFormatTextAttribute { - /** Positive prefix */ - UNUM_POSITIVE_PREFIX, - /** Positive suffix */ - UNUM_POSITIVE_SUFFIX, - /** Negative prefix */ - UNUM_NEGATIVE_PREFIX, - /** Negative suffix */ - UNUM_NEGATIVE_SUFFIX, - /** The character used to pad to the format width. */ - UNUM_PADDING_CHARACTER, - /** The ISO currency code */ - UNUM_CURRENCY_CODE, - /** - * The default rule set, such as "%spellout-numbering-year:", "%spellout-cardinal:", - * "%spellout-ordinal-masculine-plural:", "%spellout-ordinal-feminine:", or - * "%spellout-ordinal-neuter:". The available public rulesets can be listed using - * unum_getTextAttribute with UNUM_PUBLIC_RULESETS. This is only available with - * rule-based formatters. - * @stable ICU 3.0 - */ - UNUM_DEFAULT_RULESET, - /** - * The public rule sets. This is only available with rule-based formatters. - * This is a read-only attribute. The public rulesets are returned as a - * single string, with each ruleset name delimited by ';' (semicolon). See the - * CLDR LDML spec for more information about RBNF rulesets: - * http://www.unicode.org/reports/tr35/tr35-numbers.html#Rule-Based_Number_Formatting - * @stable ICU 3.0 - */ - UNUM_PUBLIC_RULESETS -} UNumberFormatTextAttribute; - -/** -* Get a text attribute associated with a UNumberFormat. -* An example of a text attribute is the suffix for positive numbers. If the formatter -* does not understand the attribute, U_UNSUPPORTED_ERROR is returned as the status. -* Rule-based formatters only understand UNUM_DEFAULT_RULESET and UNUM_PUBLIC_RULESETS. -* @param fmt The formatter to query. -* @param tag The attribute to query; one of UNUM_POSITIVE_PREFIX, UNUM_POSITIVE_SUFFIX, -* UNUM_NEGATIVE_PREFIX, UNUM_NEGATIVE_SUFFIX, UNUM_PADDING_CHARACTER, UNUM_CURRENCY_CODE, -* UNUM_DEFAULT_RULESET, or UNUM_PUBLIC_RULESETS. -* @param result A pointer to a buffer to receive the attribute. -* @param resultLength The maximum size of result. -* @param status A pointer to an UErrorCode to receive any errors -* @return The total buffer size needed; if greater than resultLength, the output was truncated. -* @see unum_setTextAttribute -* @see unum_getAttribute -* @see unum_setAttribute -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -unum_getTextAttribute( const UNumberFormat* fmt, - UNumberFormatTextAttribute tag, - UChar* result, - int32_t resultLength, - UErrorCode* status); - -/** -* Set a text attribute associated with a UNumberFormat. -* An example of a text attribute is the suffix for positive numbers. Rule-based formatters -* only understand UNUM_DEFAULT_RULESET. -* @param fmt The formatter to set. -* @param tag The attribute to set; one of UNUM_POSITIVE_PREFIX, UNUM_POSITIVE_SUFFIX, -* UNUM_NEGATIVE_PREFIX, UNUM_NEGATIVE_SUFFIX, UNUM_PADDING_CHARACTER, UNUM_CURRENCY_CODE, -* or UNUM_DEFAULT_RULESET. -* @param newValue The new value of attr. -* @param newValueLength The length of newValue, or -1 if null-terminated. -* @param status A pointer to an UErrorCode to receive any errors -* @see unum_getTextAttribute -* @see unum_getAttribute -* @see unum_setAttribute -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -unum_setTextAttribute( UNumberFormat* fmt, - UNumberFormatTextAttribute tag, - const UChar* newValue, - int32_t newValueLength, - UErrorCode *status); - -/** - * Extract the pattern from a UNumberFormat. The pattern will follow - * the DecimalFormat pattern syntax. - * @param fmt The formatter to query. - * @param isPatternLocalized TRUE if the pattern should be localized, - * FALSE otherwise. This is ignored if the formatter is a rule-based - * formatter. - * @param result A pointer to a buffer to receive the pattern. - * @param resultLength The maximum size of result. - * @param status A pointer to an input-output UErrorCode. - * @return The total buffer size needed; if greater than resultLength, - * the output was truncated. - * @see unum_applyPattern - * @see DecimalFormat - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -unum_toPattern( const UNumberFormat* fmt, - UBool isPatternLocalized, - UChar* result, - int32_t resultLength, - UErrorCode* status); - - -/** - * Constants for specifying a number format symbol. - * @stable ICU 2.0 - */ -typedef enum UNumberFormatSymbol { - /** The decimal separator */ - UNUM_DECIMAL_SEPARATOR_SYMBOL = 0, - /** The grouping separator */ - UNUM_GROUPING_SEPARATOR_SYMBOL = 1, - /** The pattern separator */ - UNUM_PATTERN_SEPARATOR_SYMBOL = 2, - /** The percent sign */ - UNUM_PERCENT_SYMBOL = 3, - /** Zero*/ - UNUM_ZERO_DIGIT_SYMBOL = 4, - /** Character representing a digit in the pattern */ - UNUM_DIGIT_SYMBOL = 5, - /** The minus sign */ - UNUM_MINUS_SIGN_SYMBOL = 6, - /** The plus sign */ - UNUM_PLUS_SIGN_SYMBOL = 7, - /** The currency symbol */ - UNUM_CURRENCY_SYMBOL = 8, - /** The international currency symbol */ - UNUM_INTL_CURRENCY_SYMBOL = 9, - /** The monetary separator */ - UNUM_MONETARY_SEPARATOR_SYMBOL = 10, - /** The exponential symbol */ - UNUM_EXPONENTIAL_SYMBOL = 11, - /** Per mill symbol */ - UNUM_PERMILL_SYMBOL = 12, - /** Escape padding character */ - UNUM_PAD_ESCAPE_SYMBOL = 13, - /** Infinity symbol */ - UNUM_INFINITY_SYMBOL = 14, - /** Nan symbol */ - UNUM_NAN_SYMBOL = 15, - /** Significant digit symbol - * @stable ICU 3.0 */ - UNUM_SIGNIFICANT_DIGIT_SYMBOL = 16, - /** The monetary grouping separator - * @stable ICU 3.6 - */ - UNUM_MONETARY_GROUPING_SEPARATOR_SYMBOL = 17, - /** One - * @stable ICU 4.6 - */ - UNUM_ONE_DIGIT_SYMBOL = 18, - /** Two - * @stable ICU 4.6 - */ - UNUM_TWO_DIGIT_SYMBOL = 19, - /** Three - * @stable ICU 4.6 - */ - UNUM_THREE_DIGIT_SYMBOL = 20, - /** Four - * @stable ICU 4.6 - */ - UNUM_FOUR_DIGIT_SYMBOL = 21, - /** Five - * @stable ICU 4.6 - */ - UNUM_FIVE_DIGIT_SYMBOL = 22, - /** Six - * @stable ICU 4.6 - */ - UNUM_SIX_DIGIT_SYMBOL = 23, - /** Seven - * @stable ICU 4.6 - */ - UNUM_SEVEN_DIGIT_SYMBOL = 24, - /** Eight - * @stable ICU 4.6 - */ - UNUM_EIGHT_DIGIT_SYMBOL = 25, - /** Nine - * @stable ICU 4.6 - */ - UNUM_NINE_DIGIT_SYMBOL = 26, - - /** Multiplication sign - * @stable ICU 54 - */ - UNUM_EXPONENT_MULTIPLICATION_SYMBOL = 27, - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UNumberFormatSymbol value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UNUM_FORMAT_SYMBOL_COUNT = 28 -#endif // U_HIDE_DEPRECATED_API -} UNumberFormatSymbol; - -/** -* Get a symbol associated with a UNumberFormat. -* A UNumberFormat uses symbols to represent the special locale-dependent -* characters in a number, for example the percent sign. This API is not -* supported for rule-based formatters. -* @param fmt The formatter to query. -* @param symbol The UNumberFormatSymbol constant for the symbol to get -* @param buffer The string buffer that will receive the symbol string; -* if it is NULL, then only the length of the symbol is returned -* @param size The size of the string buffer -* @param status A pointer to an UErrorCode to receive any errors -* @return The length of the symbol; the buffer is not modified if -* length>=size -* @see unum_setSymbol -* @stable ICU 2.0 -*/ -U_STABLE int32_t U_EXPORT2 -unum_getSymbol(const UNumberFormat *fmt, - UNumberFormatSymbol symbol, - UChar *buffer, - int32_t size, - UErrorCode *status); - -/** -* Set a symbol associated with a UNumberFormat. -* A UNumberFormat uses symbols to represent the special locale-dependent -* characters in a number, for example the percent sign. This API is not -* supported for rule-based formatters. -* @param fmt The formatter to set. -* @param symbol The UNumberFormatSymbol constant for the symbol to set -* @param value The string to set the symbol to -* @param length The length of the string, or -1 for a zero-terminated string -* @param status A pointer to an UErrorCode to receive any errors. -* @see unum_getSymbol -* @stable ICU 2.0 -*/ -U_STABLE void U_EXPORT2 -unum_setSymbol(UNumberFormat *fmt, - UNumberFormatSymbol symbol, - const UChar *value, - int32_t length, - UErrorCode *status); - - -/** - * Get the locale for this number format object. - * You can choose between valid and actual locale. - * @param fmt The formatter to get the locale from - * @param type type of the locale we're looking for (valid or actual) - * @param status error code for the operation - * @return the locale name - * @stable ICU 2.8 - */ -U_STABLE const char* U_EXPORT2 -unum_getLocaleByType(const UNumberFormat *fmt, - ULocDataLocaleType type, - UErrorCode* status); - -/** - * Set a particular UDisplayContext value in the formatter, such as - * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. - * @param fmt The formatter for which to set a UDisplayContext value. - * @param value The UDisplayContext value to set. - * @param status A pointer to an UErrorCode to receive any errors - * @stable ICU 53 - */ -U_STABLE void U_EXPORT2 -unum_setContext(UNumberFormat* fmt, UDisplayContext value, UErrorCode* status); - -/** - * Get the formatter's UDisplayContext value for the specified UDisplayContextType, - * such as UDISPCTX_TYPE_CAPITALIZATION. - * @param fmt The formatter to query. - * @param type The UDisplayContextType whose value to return - * @param status A pointer to an UErrorCode to receive any errors - * @return The UDisplayContextValue for the specified type. - * @stable ICU 53 - */ -U_STABLE UDisplayContext U_EXPORT2 -unum_getContext(const UNumberFormat *fmt, UDisplayContextType type, UErrorCode* status); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/unumsys.h b/win32/include/spidermonkey/unicode/unumsys.h deleted file mode 100755 index 46289c0f..00000000 --- a/win32/include/spidermonkey/unicode/unumsys.h +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -***************************************************************************************** -* Copyright (C) 2013-2014, International Business Machines -* Corporation and others. All Rights Reserved. -***************************************************************************************** -*/ - -#ifndef UNUMSYS_H -#define UNUMSYS_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/uenum.h" -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: UNumberingSystem, information about numbering systems - * - * Defines numbering systems. A numbering system describes the scheme by which - * numbers are to be presented to the end user. In its simplest form, a numbering - * system describes the set of digit characters that are to be used to display - * numbers, such as Western digits, Thai digits, Arabic-Indic digits, etc., in a - * positional numbering system with a specified radix (typically 10). - * More complicated numbering systems are algorithmic in nature, and require use - * of an RBNF formatter (rule based number formatter), in order to calculate - * the characters to be displayed for a given number. Examples of algorithmic - * numbering systems include Roman numerals, Chinese numerals, and Hebrew numerals. - * Formatting rules for many commonly used numbering systems are included in - * the ICU package, based on the numbering system rules defined in CLDR. - * Alternate numbering systems can be specified to a locale by using the - * numbers locale keyword. - */ - -/** - * Opaque UNumberingSystem object for use in C programs. - * @stable ICU 52 - */ -struct UNumberingSystem; -typedef struct UNumberingSystem UNumberingSystem; /**< C typedef for struct UNumberingSystem. @stable ICU 52 */ - -/** - * Opens a UNumberingSystem object using the default numbering system for the specified - * locale. - * @param locale The locale for which the default numbering system should be opened. - * @param status A pointer to a UErrorCode to receive any errors. For example, this - * may be U_UNSUPPORTED_ERROR for a locale such as "en@numbers=xyz" that - * specifies a numbering system unknown to ICU. - * @return A UNumberingSystem for the specified locale, or NULL if an error - * occurred. - * @stable ICU 52 - */ -U_STABLE UNumberingSystem * U_EXPORT2 -unumsys_open(const char *locale, UErrorCode *status); - -/** - * Opens a UNumberingSystem object using the name of one of the predefined numbering - * systems specified by CLDR and known to ICU, such as "latn", "arabext", or "hanidec"; - * the full list is returned by unumsys_openAvailableNames. Note that some of the names - * listed at http://unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml - e.g. - * default, native, traditional, finance - do not identify specific numbering systems, - * but rather key values that may only be used as part of a locale, which in turn - * defines how they are mapped to a specific numbering system such as "latn" or "hant". - * - * @param name The name of the numbering system for which a UNumberingSystem object - * should be opened. - * @param status A pointer to a UErrorCode to receive any errors. For example, this - * may be U_UNSUPPORTED_ERROR for a numbering system such as "xyz" that - * is unknown to ICU. - * @return A UNumberingSystem for the specified name, or NULL if an error - * occurred. - * @stable ICU 52 - */ -U_STABLE UNumberingSystem * U_EXPORT2 -unumsys_openByName(const char *name, UErrorCode *status); - -/** - * Close a UNumberingSystem object. Once closed it may no longer be used. - * @param unumsys The UNumberingSystem object to close. - * @stable ICU 52 - */ -U_STABLE void U_EXPORT2 -unumsys_close(UNumberingSystem *unumsys); - -#if U_SHOW_CPLUSPLUS_API -U_NAMESPACE_BEGIN - -/** - * \class LocalUNumberingSystemPointer - * "Smart pointer" class, closes a UNumberingSystem via unumsys_close(). - * For most methods see the LocalPointerBase base class. - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 52 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUNumberingSystemPointer, UNumberingSystem, unumsys_close); - -U_NAMESPACE_END -#endif - -/** - * Returns an enumeration over the names of all of the predefined numbering systems known - * to ICU. - * @param status A pointer to a UErrorCode to receive any errors. - * @return A pointer to a UEnumeration that must be closed with uenum_close(), - * or NULL if an error occurred. - * @stable ICU 52 - */ -U_STABLE UEnumeration * U_EXPORT2 -unumsys_openAvailableNames(UErrorCode *status); - -/** - * Returns the name of the specified UNumberingSystem object (if it is one of the - * predefined names known to ICU). - * @param unumsys The UNumberingSystem whose name is desired. - * @return A pointer to the name of the specified UNumberingSystem object, or - * NULL if the name is not one of the ICU predefined names. The pointer - * is only valid for the lifetime of the UNumberingSystem object. - * @stable ICU 52 - */ -U_STABLE const char * U_EXPORT2 -unumsys_getName(const UNumberingSystem *unumsys); - -/** - * Returns whether the given UNumberingSystem object is for an algorithmic (not purely - * positional) system. - * @param unumsys The UNumberingSystem whose algorithmic status is desired. - * @return TRUE if the specified UNumberingSystem object is for an algorithmic - * system. - * @stable ICU 52 - */ -U_STABLE UBool U_EXPORT2 -unumsys_isAlgorithmic(const UNumberingSystem *unumsys); - -/** - * Returns the radix of the specified UNumberingSystem object. Simple positional - * numbering systems typically have radix 10, but might have a radix of e.g. 16 for - * hexadecimal. The radix is less well-defined for non-positional algorithmic systems. - * @param unumsys The UNumberingSystem whose radix is desired. - * @return The radix of the specified UNumberingSystem object. - * @stable ICU 52 - */ -U_STABLE int32_t U_EXPORT2 -unumsys_getRadix(const UNumberingSystem *unumsys); - -/** - * Get the description string of the specified UNumberingSystem object. For simple - * positional systems this is the ordered string of digits (with length matching - * the radix), e.g. "\u3007\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D" - * for "hanidec"; it would be "0123456789ABCDEF" for hexadecimal. For - * algorithmic systems this is the name of the RBNF ruleset used for formatting, - * e.g. "zh/SpelloutRules/%spellout-cardinal" for "hans" or "%greek-upper" for - * "grek". - * @param unumsys The UNumberingSystem whose description string is desired. - * @param result A pointer to a buffer to receive the description string. - * @param resultLength The maximum size of result. - * @param status A pointer to a UErrorCode to receive any errors. - * @return The total buffer size needed; if greater than resultLength, the - * output was truncated. - * @stable ICU 52 - */ -U_STABLE int32_t U_EXPORT2 -unumsys_getDescription(const UNumberingSystem *unumsys, UChar *result, - int32_t resultLength, UErrorCode *status); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/uobject.h b/win32/include/spidermonkey/unicode/uobject.h deleted file mode 100755 index ec231ee2..00000000 --- a/win32/include/spidermonkey/unicode/uobject.h +++ /dev/null @@ -1,322 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 2002-2012, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* file name: uobject.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2002jun26 -* created by: Markus W. Scherer -*/ - -#ifndef __UOBJECT_H__ -#define __UOBJECT_H__ - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: Common ICU base class UObject. - */ - -/** - * @{ - * \def U_NO_THROW - * Define this to define the throw() specification so - * certain functions do not throw any exceptions - * - * UMemory operator new methods should have the throw() specification - * appended to them, so that the compiler adds the additional NULL check - * before calling constructors. Without, if operator new returns NULL the - * constructor is still called, and if the constructor references member - * data, (which it typically does), the result is a segmentation violation. - * - * @stable ICU 4.2 - */ -#ifndef U_NO_THROW -#define U_NO_THROW throw() -#endif - -/** @} */ - -/*===========================================================================*/ -/* UClassID-based RTTI */ -/*===========================================================================*/ - -/** - * UClassID is used to identify classes without using the compiler's RTTI. - * This was used before C++ compilers consistently supported RTTI. - * ICU 4.6 requires compiler RTTI to be turned on. - * - * Each class hierarchy which needs - * to implement polymorphic clone() or operator==() defines two methods, - * described in detail below. UClassID values can be compared using - * operator==(). Nothing else should be done with them. - * - * \par - * In class hierarchies that implement "poor man's RTTI", - * each concrete subclass implements getDynamicClassID() in the same way: - * - * \code - * class Derived { - * public: - * virtual UClassID getDynamicClassID() const - * { return Derived::getStaticClassID(); } - * } - * \endcode - * - * Each concrete class implements getStaticClassID() as well, which allows - * clients to test for a specific type. - * - * \code - * class Derived { - * public: - * static UClassID U_EXPORT2 getStaticClassID(); - * private: - * static char fgClassID; - * } - * - * // In Derived.cpp: - * UClassID Derived::getStaticClassID() - * { return (UClassID)&Derived::fgClassID; } - * char Derived::fgClassID = 0; // Value is irrelevant - * \endcode - * @stable ICU 2.0 - */ -typedef void* UClassID; - -U_NAMESPACE_BEGIN - -/** - * UMemory is the common ICU base class. - * All other ICU C++ classes are derived from UMemory (starting with ICU 2.4). - * - * This is primarily to make it possible and simple to override the - * C++ memory management by adding new/delete operators to this base class. - * - * To override ALL ICU memory management, including that from plain C code, - * replace the allocation functions declared in cmemory.h - * - * UMemory does not contain any virtual functions. - * Common "boilerplate" functions are defined in UObject. - * - * @stable ICU 2.4 - */ -class U_COMMON_API UMemory { -public: - -/* test versions for debugging shaper heap memory problems */ -#ifdef SHAPER_MEMORY_DEBUG - static void * NewArray(int size, int count); - static void * GrowArray(void * array, int newSize ); - static void FreeArray(void * array ); -#endif - -#if U_OVERRIDE_CXX_ALLOCATION - /** - * Override for ICU4C C++ memory management. - * simple, non-class types are allocated using the macros in common/cmemory.h - * (uprv_malloc(), uprv_free(), uprv_realloc()); - * they or something else could be used here to implement C++ new/delete - * for ICU4C C++ classes - * @stable ICU 2.4 - */ - static void * U_EXPORT2 operator new(size_t size) U_NO_THROW; - - /** - * Override for ICU4C C++ memory management. - * See new(). - * @stable ICU 2.4 - */ - static void * U_EXPORT2 operator new[](size_t size) U_NO_THROW; - - /** - * Override for ICU4C C++ memory management. - * simple, non-class types are allocated using the macros in common/cmemory.h - * (uprv_malloc(), uprv_free(), uprv_realloc()); - * they or something else could be used here to implement C++ new/delete - * for ICU4C C++ classes - * @stable ICU 2.4 - */ - static void U_EXPORT2 operator delete(void *p) U_NO_THROW; - - /** - * Override for ICU4C C++ memory management. - * See delete(). - * @stable ICU 2.4 - */ - static void U_EXPORT2 operator delete[](void *p) U_NO_THROW; - -#if U_HAVE_PLACEMENT_NEW - /** - * Override for ICU4C C++ memory management for STL. - * See new(). - * @stable ICU 2.6 - */ - static inline void * U_EXPORT2 operator new(size_t, void *ptr) U_NO_THROW { return ptr; } - - /** - * Override for ICU4C C++ memory management for STL. - * See delete(). - * @stable ICU 2.6 - */ - static inline void U_EXPORT2 operator delete(void *, void *) U_NO_THROW {} -#endif /* U_HAVE_PLACEMENT_NEW */ -#if U_HAVE_DEBUG_LOCATION_NEW - /** - * This method overrides the MFC debug version of the operator new - * - * @param size The requested memory size - * @param file The file where the allocation was requested - * @param line The line where the allocation was requested - */ - static void * U_EXPORT2 operator new(size_t size, const char* file, int line) U_NO_THROW; - /** - * This method provides a matching delete for the MFC debug new - * - * @param p The pointer to the allocated memory - * @param file The file where the allocation was requested - * @param line The line where the allocation was requested - */ - static void U_EXPORT2 operator delete(void* p, const char* file, int line) U_NO_THROW; -#endif /* U_HAVE_DEBUG_LOCATION_NEW */ -#endif /* U_OVERRIDE_CXX_ALLOCATION */ - - /* - * Assignment operator not declared. The compiler will provide one - * which does nothing since this class does not contain any data members. - * API/code coverage may show the assignment operator as present and - * untested - ignore. - * Subclasses need this assignment operator if they use compiler-provided - * assignment operators of their own. An alternative to not declaring one - * here would be to declare and empty-implement a protected or public one. - UMemory &UMemory::operator=(const UMemory &); - */ -}; - -/** - * UObject is the common ICU "boilerplate" class. - * UObject inherits UMemory (starting with ICU 2.4), - * and all other public ICU C++ classes - * are derived from UObject (starting with ICU 2.2). - * - * UObject contains common virtual functions, in particular a virtual destructor. - * - * The clone() function is not available in UObject because it is not - * implemented by all ICU classes. - * Many ICU services provide a clone() function for their class trees, - * defined on the service's C++ base class, and all subclasses within that - * service class tree return a pointer to the service base class - * (which itself is a subclass of UObject). - * This is because some compilers do not support covariant (same-as-this) - * return types; cast to the appropriate subclass if necessary. - * - * @stable ICU 2.2 - */ -class U_COMMON_API UObject : public UMemory { -public: - /** - * Destructor. - * - * @stable ICU 2.2 - */ - virtual ~UObject(); - - /** - * ICU4C "poor man's RTTI", returns a UClassID for the actual ICU class. - * The base class implementation returns a dummy value. - * - * Use compiler RTTI rather than ICU's "poor man's RTTI". - * Since ICU 4.6, new ICU C++ class hierarchies do not implement "poor man's RTTI". - * - * @stable ICU 2.2 - */ - virtual UClassID getDynamicClassID() const; - -protected: - // the following functions are protected to prevent instantiation and - // direct use of UObject itself - - // default constructor - // inline UObject() {} - - // copy constructor - // inline UObject(const UObject &other) {} - -#if 0 - // TODO Sometime in the future. Implement operator==(). - // (This comment inserted in 2.2) - // some or all of the following "boilerplate" functions may be made public - // in a future ICU4C release when all subclasses implement them - - // assignment operator - // (not virtual, see "Taligent's Guide to Designing Programs" pp.73..74) - // commented out because the implementation is the same as a compiler's default - // UObject &operator=(const UObject &other) { return *this; } - - // comparison operators - virtual inline UBool operator==(const UObject &other) const { return this==&other; } - inline UBool operator!=(const UObject &other) const { return !operator==(other); } - - // clone() commented out from the base class: - // some compilers do not support co-variant return types - // (i.e., subclasses would have to return UObject * as well, instead of SubClass *) - // see also UObject class documentation. - // virtual UObject *clone() const; -#endif - - /* - * Assignment operator not declared. The compiler will provide one - * which does nothing since this class does not contain any data members. - * API/code coverage may show the assignment operator as present and - * untested - ignore. - * Subclasses need this assignment operator if they use compiler-provided - * assignment operators of their own. An alternative to not declaring one - * here would be to declare and empty-implement a protected or public one. - UObject &UObject::operator=(const UObject &); - */ -}; - -#ifndef U_HIDE_INTERNAL_API -/** - * This is a simple macro to add ICU RTTI to an ICU object implementation. - * This does not go into the header. This should only be used in *.cpp files. - * - * @param myClass The name of the class that needs RTTI defined. - * @internal - */ -#define UOBJECT_DEFINE_RTTI_IMPLEMENTATION(myClass) \ - UClassID U_EXPORT2 myClass::getStaticClassID() { \ - static char classID = 0; \ - return (UClassID)&classID; \ - } \ - UClassID myClass::getDynamicClassID() const \ - { return myClass::getStaticClassID(); } - - -/** - * This macro adds ICU RTTI to an ICU abstract class implementation. - * This macro should be invoked in *.cpp files. The corresponding - * header should declare getStaticClassID. - * - * @param myClass The name of the class that needs RTTI defined. - * @internal - */ -#define UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(myClass) \ - UClassID U_EXPORT2 myClass::getStaticClassID() { \ - static char classID = 0; \ - return (UClassID)&classID; \ - } - -#endif /* U_HIDE_INTERNAL_API */ - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/upluralrules.h b/win32/include/spidermonkey/unicode/upluralrules.h deleted file mode 100755 index 52e34d8d..00000000 --- a/win32/include/spidermonkey/unicode/upluralrules.h +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -***************************************************************************************** -* Copyright (C) 2010-2013, International Business Machines -* Corporation and others. All Rights Reserved. -***************************************************************************************** -*/ - -#ifndef UPLURALRULES_H -#define UPLURALRULES_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: Plural rules, select plural keywords for numeric values. - * - * A UPluralRules object defines rules for mapping non-negative numeric - * values onto a small set of keywords. Rules are constructed from a text - * description, consisting of a series of keywords and conditions. - * The uplrules_select function examines each condition in order and - * returns the keyword for the first condition that matches the number. - * If none match, the default rule(other) is returned. - * - * For more information, see the LDML spec, C.11 Language Plural Rules: - * http://www.unicode.org/reports/tr35/#Language_Plural_Rules - * - * Keywords: ICU locale data has 6 predefined values - - * 'zero', 'one', 'two', 'few', 'many' and 'other'. Callers need to check - * the value of keyword returned by the uplrules_select function. - * - * These are based on CLDR Language Plural Rules. For these - * predefined rules, see the CLDR page at - * http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html - */ - -/** - * Type of plurals and PluralRules. - * @stable ICU 50 - */ -enum UPluralType { - /** - * Plural rules for cardinal numbers: 1 file vs. 2 files. - * @stable ICU 50 - */ - UPLURAL_TYPE_CARDINAL, - /** - * Plural rules for ordinal numbers: 1st file, 2nd file, 3rd file, 4th file, etc. - * @stable ICU 50 - */ - UPLURAL_TYPE_ORDINAL, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UPluralType value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UPLURAL_TYPE_COUNT -#endif // U_HIDE_DEPRECATED_API -}; -/** - * @stable ICU 50 - */ -typedef enum UPluralType UPluralType; - -/** - * Opaque UPluralRules object for use in C programs. - * @stable ICU 4.8 - */ -struct UPluralRules; -typedef struct UPluralRules UPluralRules; /**< C typedef for struct UPluralRules. @stable ICU 4.8 */ - -/** - * Opens a new UPluralRules object using the predefined cardinal-number plural rules for a - * given locale. - * Same as uplrules_openForType(locale, UPLURAL_TYPE_CARDINAL, status). - * @param locale The locale for which the rules are desired. - * @param status A pointer to a UErrorCode to receive any errors. - * @return A UPluralRules for the specified locale, or NULL if an error occurred. - * @stable ICU 4.8 - */ -U_STABLE UPluralRules* U_EXPORT2 -uplrules_open(const char *locale, UErrorCode *status); - -/** - * Opens a new UPluralRules object using the predefined plural rules for a - * given locale and the plural type. - * @param locale The locale for which the rules are desired. - * @param type The plural type (e.g., cardinal or ordinal). - * @param status A pointer to a UErrorCode to receive any errors. - * @return A UPluralRules for the specified locale, or NULL if an error occurred. - * @stable ICU 50 - */ -U_DRAFT UPluralRules* U_EXPORT2 -uplrules_openForType(const char *locale, UPluralType type, UErrorCode *status); - -/** - * Closes a UPluralRules object. Once closed it may no longer be used. - * @param uplrules The UPluralRules object to close. - * @stable ICU 4.8 - */ -U_STABLE void U_EXPORT2 -uplrules_close(UPluralRules *uplrules); - - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUPluralRulesPointer - * "Smart pointer" class, closes a UPluralRules via uplrules_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.8 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUPluralRulesPointer, UPluralRules, uplrules_close); - -U_NAMESPACE_END - -#endif - - -/** - * Given a number, returns the keyword of the first rule that - * applies to the number, according to the supplied UPluralRules object. - * @param uplrules The UPluralRules object specifying the rules. - * @param number The number for which the rule has to be determined. - * @param keyword The keyword of the rule that applies to number. - * @param capacity The capacity of keyword. - * @param status A pointer to a UErrorCode to receive any errors. - * @return The length of keyword. - * @stable ICU 4.8 - */ -U_STABLE int32_t U_EXPORT2 -uplrules_select(const UPluralRules *uplrules, - double number, - UChar *keyword, int32_t capacity, - UErrorCode *status); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/uregex.h b/win32/include/spidermonkey/unicode/uregex.h deleted file mode 100755 index ab85719d..00000000 --- a/win32/include/spidermonkey/unicode/uregex.h +++ /dev/null @@ -1,1614 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 2004-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* file name: uregex.h -* encoding: US-ASCII -* indentation:4 -* -* created on: 2004mar09 -* created by: Andy Heninger -* -* ICU Regular Expressions, API for C -*/ - -/** - * \file - * \brief C API: Regular Expressions - * - *

This is a C wrapper around the C++ RegexPattern and RegexMatcher classes.

- */ - -#ifndef UREGEX_H -#define UREGEX_H - -#include "unicode/utext.h" -#include "unicode/utypes.h" - -#if !UCONFIG_NO_REGULAR_EXPRESSIONS - -#include "unicode/localpointer.h" -#include "unicode/parseerr.h" - -struct URegularExpression; -/** - * Structure representing a compiled regular expression, plus the results - * of a match operation. - * @stable ICU 3.0 - */ -typedef struct URegularExpression URegularExpression; - - -/** - * Constants for Regular Expression Match Modes. - * @stable ICU 2.4 - */ -typedef enum URegexpFlag{ - -#ifndef U_HIDE_DRAFT_API - /** Forces normalization of pattern and strings. - Not implemented yet, just a placeholder, hence draft. - @draft ICU 2.4 */ - UREGEX_CANON_EQ = 128, -#endif /* U_HIDE_DRAFT_API */ - /** Enable case insensitive matching. @stable ICU 2.4 */ - UREGEX_CASE_INSENSITIVE = 2, - - /** Allow white space and comments within patterns @stable ICU 2.4 */ - UREGEX_COMMENTS = 4, - - /** If set, '.' matches line terminators, otherwise '.' matching stops at line end. - * @stable ICU 2.4 */ - UREGEX_DOTALL = 32, - - /** If set, treat the entire pattern as a literal string. - * Metacharacters or escape sequences in the input sequence will be given - * no special meaning. - * - * The flag UREGEX_CASE_INSENSITIVE retains its impact - * on matching when used in conjunction with this flag. - * The other flags become superfluous. - * - * @stable ICU 4.0 - */ - UREGEX_LITERAL = 16, - - /** Control behavior of "$" and "^" - * If set, recognize line terminators within string, - * otherwise, match only at start and end of input string. - * @stable ICU 2.4 */ - UREGEX_MULTILINE = 8, - - /** Unix-only line endings. - * When this mode is enabled, only \\u000a is recognized as a line ending - * in the behavior of ., ^, and $. - * @stable ICU 4.0 - */ - UREGEX_UNIX_LINES = 1, - - /** Unicode word boundaries. - * If set, \b uses the Unicode TR 29 definition of word boundaries. - * Warning: Unicode word boundaries are quite different from - * traditional regular expression word boundaries. See - * http://unicode.org/reports/tr29/#Word_Boundaries - * @stable ICU 2.8 - */ - UREGEX_UWORD = 256, - - /** Error on Unrecognized backslash escapes. - * If set, fail with an error on patterns that contain - * backslash-escaped ASCII letters without a known special - * meaning. If this flag is not set, these - * escaped letters represent themselves. - * @stable ICU 4.0 - */ - UREGEX_ERROR_ON_UNKNOWN_ESCAPES = 512 - -} URegexpFlag; - -/** - * Open (compile) an ICU regular expression. Compiles the regular expression in - * string form into an internal representation using the specified match mode flags. - * The resulting regular expression handle can then be used to perform various - * matching operations. - * - * - * @param pattern The Regular Expression pattern to be compiled. - * @param patternLength The length of the pattern, or -1 if the pattern is - * NUL terminated. - * @param flags Flags that alter the default matching behavior for - * the regular expression, UREGEX_CASE_INSENSITIVE, for - * example. For default behavior, set this parameter to zero. - * See enum URegexpFlag. All desired flags - * are bitwise-ORed together. - * @param pe Receives the position (line and column numbers) of any syntax - * error within the source regular expression string. If this - * information is not wanted, pass NULL for this parameter. - * @param status Receives error detected by this function. - * @stable ICU 3.0 - * - */ -U_STABLE URegularExpression * U_EXPORT2 -uregex_open( const UChar *pattern, - int32_t patternLength, - uint32_t flags, - UParseError *pe, - UErrorCode *status); - -/** - * Open (compile) an ICU regular expression. Compiles the regular expression in - * string form into an internal representation using the specified match mode flags. - * The resulting regular expression handle can then be used to perform various - * matching operations. - *

- * The contents of the pattern UText will be extracted and saved. Ownership of the - * UText struct itself remains with the caller. This is to match the behavior of - * uregex_open(). - * - * @param pattern The Regular Expression pattern to be compiled. - * @param flags Flags that alter the default matching behavior for - * the regular expression, UREGEX_CASE_INSENSITIVE, for - * example. For default behavior, set this parameter to zero. - * See enum URegexpFlag. All desired flags - * are bitwise-ORed together. - * @param pe Receives the position (line and column numbers) of any syntax - * error within the source regular expression string. If this - * information is not wanted, pass NULL for this parameter. - * @param status Receives error detected by this function. - * - * @stable ICU 4.6 - */ -U_STABLE URegularExpression * U_EXPORT2 -uregex_openUText(UText *pattern, - uint32_t flags, - UParseError *pe, - UErrorCode *status); - -/** - * Open (compile) an ICU regular expression. The resulting regular expression - * handle can then be used to perform various matching operations. - *

- * This function is the same as uregex_open, except that the pattern - * is supplied as an 8 bit char * string in the default code page. - * - * @param pattern The Regular Expression pattern to be compiled, - * NUL terminated. - * @param flags Flags that alter the default matching behavior for - * the regular expression, UREGEX_CASE_INSENSITIVE, for - * example. For default behavior, set this parameter to zero. - * See enum URegexpFlag. All desired flags - * are bitwise-ORed together. - * @param pe Receives the position (line and column numbers) of any syntax - * error within the source regular expression string. If this - * information is not wanted, pass NULL for this parameter. - * @param status Receives errors detected by this function. - * @return The URegularExpression object representing the compiled - * pattern. - * - * @stable ICU 3.0 - */ -#if !UCONFIG_NO_CONVERSION -U_STABLE URegularExpression * U_EXPORT2 -uregex_openC( const char *pattern, - uint32_t flags, - UParseError *pe, - UErrorCode *status); -#endif - - - -/** - * Close the regular expression, recovering all resources (memory) it - * was holding. - * - * @param regexp The regular expression to be closed. - * @stable ICU 3.0 - */ -U_STABLE void U_EXPORT2 -uregex_close(URegularExpression *regexp); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalURegularExpressionPointer - * "Smart pointer" class, closes a URegularExpression via uregex_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalURegularExpressionPointer, URegularExpression, uregex_close); - -U_NAMESPACE_END - -#endif - -/** - * Make a copy of a compiled regular expression. Cloning a regular - * expression is faster than opening a second instance from the source - * form of the expression, and requires less memory. - *

- * Note that the current input string and the position of any matched text - * within it are not cloned; only the pattern itself and the - * match mode flags are copied. - *

- * Cloning can be particularly useful to threaded applications that perform - * multiple match operations in parallel. Each concurrent RE - * operation requires its own instance of a URegularExpression. - * - * @param regexp The compiled regular expression to be cloned. - * @param status Receives indication of any errors encountered - * @return the cloned copy of the compiled regular expression. - * @stable ICU 3.0 - */ -U_STABLE URegularExpression * U_EXPORT2 -uregex_clone(const URegularExpression *regexp, UErrorCode *status); - -/** - * Returns a pointer to the source form of the pattern for this regular expression. - * This function will work even if the pattern was originally specified as a UText. - * - * @param regexp The compiled regular expression. - * @param patLength This output parameter will be set to the length of the - * pattern string. A NULL pointer may be used here if the - * pattern length is not needed, as would be the case if - * the pattern is known in advance to be a NUL terminated - * string. - * @param status Receives errors detected by this function. - * @return a pointer to the pattern string. The storage for the string is - * owned by the regular expression object, and must not be - * altered or deleted by the application. The returned string - * will remain valid until the regular expression is closed. - * @stable ICU 3.0 - */ -U_STABLE const UChar * U_EXPORT2 -uregex_pattern(const URegularExpression *regexp, - int32_t *patLength, - UErrorCode *status); - -/** - * Returns the source text of the pattern for this regular expression. - * This function will work even if the pattern was originally specified as a UChar string. - * - * @param regexp The compiled regular expression. - * @param status Receives errors detected by this function. - * @return the pattern text. The storage for the text is owned by the regular expression - * object, and must not be altered or deleted. - * - * @stable ICU 4.6 - */ -U_STABLE UText * U_EXPORT2 -uregex_patternUText(const URegularExpression *regexp, - UErrorCode *status); - -/** - * Get the match mode flags that were specified when compiling this regular expression. - * @param status Receives errors detected by this function. - * @param regexp The compiled regular expression. - * @return The match mode flags - * @see URegexpFlag - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_flags(const URegularExpression *regexp, - UErrorCode *status); - - -/** - * Set the subject text string upon which the regular expression will look for matches. - * This function may be called any number of times, allowing the regular - * expression pattern to be applied to different strings. - *

- * Regular expression matching operations work directly on the application's - * string data. No copy is made. The subject string data must not be - * altered after calling this function until after all regular expression - * operations involving this string data are completed. - *

- * Zero length strings are permitted. In this case, no subsequent match - * operation will dereference the text string pointer. - * - * @param regexp The compiled regular expression. - * @param text The subject text string. - * @param textLength The length of the subject text, or -1 if the string - * is NUL terminated. - * @param status Receives errors detected by this function. - * @stable ICU 3.0 - */ -U_STABLE void U_EXPORT2 -uregex_setText(URegularExpression *regexp, - const UChar *text, - int32_t textLength, - UErrorCode *status); - - -/** - * Set the subject text string upon which the regular expression will look for matches. - * This function may be called any number of times, allowing the regular - * expression pattern to be applied to different strings. - *

- * Regular expression matching operations work directly on the application's - * string data; only a shallow clone is made. The subject string data must not be - * altered after calling this function until after all regular expression - * operations involving this string data are completed. - * - * @param regexp The compiled regular expression. - * @param text The subject text string. - * @param status Receives errors detected by this function. - * - * @stable ICU 4.6 - */ -U_STABLE void U_EXPORT2 -uregex_setUText(URegularExpression *regexp, - UText *text, - UErrorCode *status); - -/** - * Get the subject text that is currently associated with this - * regular expression object. If the input was supplied using uregex_setText(), - * that pointer will be returned. Otherwise, the characters in the input will - * be extracted to a buffer and returned. In either case, ownership remains - * with the regular expression object. - * - * This function will work even if the input was originally specified as a UText. - * - * @param regexp The compiled regular expression. - * @param textLength The length of the string is returned in this output parameter. - * A NULL pointer may be used here if the - * text length is not needed, as would be the case if - * the text is known in advance to be a NUL terminated - * string. - * @param status Receives errors detected by this function. - * @return Pointer to the subject text string currently associated with - * this regular expression. - * @stable ICU 3.0 - */ -U_STABLE const UChar * U_EXPORT2 -uregex_getText(URegularExpression *regexp, - int32_t *textLength, - UErrorCode *status); - -/** - * Get the subject text that is currently associated with this - * regular expression object. - * - * This function will work even if the input was originally specified as a UChar string. - * - * @param regexp The compiled regular expression. - * @param dest A mutable UText in which to store the current input. - * If NULL, a new UText will be created as an immutable shallow clone - * of the actual input string. - * @param status Receives errors detected by this function. - * @return The subject text currently associated with this regular expression. - * If a pre-allocated UText was provided, it will always be used and returned. - * - * @stable ICU 4.6 - */ -U_STABLE UText * U_EXPORT2 -uregex_getUText(URegularExpression *regexp, - UText *dest, - UErrorCode *status); - -/** - * Set the subject text string upon which the regular expression is looking for matches - * without changing any other aspect of the matching state. - * The new and previous text strings must have the same content. - * - * This function is intended for use in environments where ICU is operating on - * strings that may move around in memory. It provides a mechanism for notifying - * ICU that the string has been relocated, and providing a new UText to access the - * string in its new position. - * - * Note that the regular expression implementation never copies the underlying text - * of a string being matched, but always operates directly on the original text - * provided by the user. Refreshing simply drops the references to the old text - * and replaces them with references to the new. - * - * Caution: this function is normally used only by very specialized - * system-level code. One example use case is with garbage collection - * that moves the text in memory. - * - * @param regexp The compiled regular expression. - * @param text The new (moved) text string. - * @param status Receives errors detected by this function. - * - * @stable ICU 4.8 - */ -U_STABLE void U_EXPORT2 -uregex_refreshUText(URegularExpression *regexp, - UText *text, - UErrorCode *status); - -/** - * Attempts to match the input string against the pattern. - * To succeed, the match must extend to the end of the string, - * or cover the complete match region. - * - * If startIndex >= zero the match operation starts at the specified - * index and must extend to the end of the input string. Any region - * that has been specified is reset. - * - * If startIndex == -1 the match must cover the input region, or the entire - * input string if no region has been set. This directly corresponds to - * Matcher.matches() in Java - * - * @param regexp The compiled regular expression. - * @param startIndex The input string (native) index at which to begin matching, or -1 - * to match the input Region. - * @param status Receives errors detected by this function. - * @return TRUE if there is a match - * @stable ICU 3.0 - */ -U_STABLE UBool U_EXPORT2 -uregex_matches(URegularExpression *regexp, - int32_t startIndex, - UErrorCode *status); - -/** - * 64bit version of uregex_matches. - * Attempts to match the input string against the pattern. - * To succeed, the match must extend to the end of the string, - * or cover the complete match region. - * - * If startIndex >= zero the match operation starts at the specified - * index and must extend to the end of the input string. Any region - * that has been specified is reset. - * - * If startIndex == -1 the match must cover the input region, or the entire - * input string if no region has been set. This directly corresponds to - * Matcher.matches() in Java - * - * @param regexp The compiled regular expression. - * @param startIndex The input string (native) index at which to begin matching, or -1 - * to match the input Region. - * @param status Receives errors detected by this function. - * @return TRUE if there is a match - * @stable ICU 4.6 - */ -U_STABLE UBool U_EXPORT2 -uregex_matches64(URegularExpression *regexp, - int64_t startIndex, - UErrorCode *status); - -/** - * Attempts to match the input string, starting from the specified index, against the pattern. - * The match may be of any length, and is not required to extend to the end - * of the input string. Contrast with uregex_matches(). - * - *

If startIndex is >= 0 any input region that was set for this - * URegularExpression is reset before the operation begins. - * - *

If the specified starting index == -1 the match begins at the start of the input - * region, or at the start of the full string if no region has been specified. - * This corresponds directly with Matcher.lookingAt() in Java. - * - *

If the match succeeds then more information can be obtained via the - * uregexp_start(), uregexp_end(), - * and uregex_group() functions.

- * - * @param regexp The compiled regular expression. - * @param startIndex The input string (native) index at which to begin matching, or - * -1 to match the Input Region - * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if there is a match. - * @stable ICU 3.0 - */ -U_STABLE UBool U_EXPORT2 -uregex_lookingAt(URegularExpression *regexp, - int32_t startIndex, - UErrorCode *status); - -/** - * 64bit version of uregex_lookingAt. - * Attempts to match the input string, starting from the specified index, against the pattern. - * The match may be of any length, and is not required to extend to the end - * of the input string. Contrast with uregex_matches(). - * - *

If startIndex is >= 0 any input region that was set for this - * URegularExpression is reset before the operation begins. - * - *

If the specified starting index == -1 the match begins at the start of the input - * region, or at the start of the full string if no region has been specified. - * This corresponds directly with Matcher.lookingAt() in Java. - * - *

If the match succeeds then more information can be obtained via the - * uregexp_start(), uregexp_end(), - * and uregex_group() functions.

- * - * @param regexp The compiled regular expression. - * @param startIndex The input string (native) index at which to begin matching, or - * -1 to match the Input Region - * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if there is a match. - * @stable ICU 4.6 - */ -U_STABLE UBool U_EXPORT2 -uregex_lookingAt64(URegularExpression *regexp, - int64_t startIndex, - UErrorCode *status); - -/** - * Find the first matching substring of the input string that matches the pattern. - * If startIndex is >= zero the search for a match begins at the specified index, - * and any match region is reset. This corresponds directly with - * Matcher.find(startIndex) in Java. - * - * If startIndex == -1 the search begins at the start of the input region, - * or at the start of the full string if no region has been specified. - * - * If a match is found, uregex_start(), uregex_end(), and - * uregex_group() will provide more information regarding the match. - * - * @param regexp The compiled regular expression. - * @param startIndex The position (native) in the input string to begin the search, or - * -1 to search within the Input Region. - * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if a match is found. - * @stable ICU 3.0 - */ -U_STABLE UBool U_EXPORT2 -uregex_find(URegularExpression *regexp, - int32_t startIndex, - UErrorCode *status); - -/** - * 64bit version of uregex_find. - * Find the first matching substring of the input string that matches the pattern. - * If startIndex is >= zero the search for a match begins at the specified index, - * and any match region is reset. This corresponds directly with - * Matcher.find(startIndex) in Java. - * - * If startIndex == -1 the search begins at the start of the input region, - * or at the start of the full string if no region has been specified. - * - * If a match is found, uregex_start(), uregex_end(), and - * uregex_group() will provide more information regarding the match. - * - * @param regexp The compiled regular expression. - * @param startIndex The position (native) in the input string to begin the search, or - * -1 to search within the Input Region. - * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if a match is found. - * @stable ICU 4.6 - */ -U_STABLE UBool U_EXPORT2 -uregex_find64(URegularExpression *regexp, - int64_t startIndex, - UErrorCode *status); - -/** - * Find the next pattern match in the input string. Begin searching - * the input at the location following the end of he previous match, - * or at the start of the string (or region) if there is no - * previous match. If a match is found, uregex_start(), uregex_end(), and - * uregex_group() will provide more information regarding the match. - * - * @param regexp The compiled regular expression. - * @param status A reference to a UErrorCode to receive any errors. - * @return TRUE if a match is found. - * @see uregex_reset - * @stable ICU 3.0 - */ -U_STABLE UBool U_EXPORT2 -uregex_findNext(URegularExpression *regexp, - UErrorCode *status); - -/** - * Get the number of capturing groups in this regular expression's pattern. - * @param regexp The compiled regular expression. - * @param status A reference to a UErrorCode to receive any errors. - * @return the number of capture groups - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_groupCount(URegularExpression *regexp, - UErrorCode *status); - -/** - * Get the group number corresponding to a named capture group. - * The returned number can be used with any function that access - * capture groups by number. - * - * The function returns an error status if the specified name does not - * appear in the pattern. - * - * @param regexp The compiled regular expression. - * @param groupName The capture group name. - * @param nameLength The length of the name, or -1 if the name is a - * nul-terminated string. - * @param status A pointer to a UErrorCode to receive any errors. - * - * @stable ICU 55 - */ -U_STABLE int32_t U_EXPORT2 -uregex_groupNumberFromName(URegularExpression *regexp, - const UChar *groupName, - int32_t nameLength, - UErrorCode *status); - - -/** - * Get the group number corresponding to a named capture group. - * The returned number can be used with any function that access - * capture groups by number. - * - * The function returns an error status if the specified name does not - * appear in the pattern. - * - * @param regexp The compiled regular expression. - * @param groupName The capture group name, - * platform invariant characters only. - * @param nameLength The length of the name, or -1 if the name is - * nul-terminated. - * @param status A pointer to a UErrorCode to receive any errors. - * - * @stable ICU 55 - */ -U_STABLE int32_t U_EXPORT2 -uregex_groupNumberFromCName(URegularExpression *regexp, - const char *groupName, - int32_t nameLength, - UErrorCode *status); - -/** Extract the string for the specified matching expression or subexpression. - * Group #0 is the complete string of matched text. - * Group #1 is the text matched by the first set of capturing parentheses. - * - * @param regexp The compiled regular expression. - * @param groupNum The capture group to extract. Group 0 is the complete - * match. The value of this parameter must be - * less than or equal to the number of capture groups in - * the pattern. - * @param dest Buffer to receive the matching string data - * @param destCapacity Capacity of the dest buffer. - * @param status A reference to a UErrorCode to receive any errors. - * @return Length of matching data, - * or -1 if no applicable match. - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_group(URegularExpression *regexp, - int32_t groupNum, - UChar *dest, - int32_t destCapacity, - UErrorCode *status); - -/** Returns a shallow immutable clone of the entire input string with the current index set - * to the beginning of the requested capture group. The capture group length is also - * returned via groupLength. - * Group #0 is the complete string of matched text. - * Group #1 is the text matched by the first set of capturing parentheses. - * - * @param regexp The compiled regular expression. - * @param groupNum The capture group to extract. Group 0 is the complete - * match. The value of this parameter must be - * less than or equal to the number of capture groups in - * the pattern. - * @param dest A mutable UText in which to store the current input. - * If NULL, a new UText will be created as an immutable shallow clone - * of the entire input string. - * @param groupLength The group length of the desired capture group. Output parameter. - * @param status A reference to a UErrorCode to receive any errors. - * @return The subject text currently associated with this regular expression. - * If a pre-allocated UText was provided, it will always be used and returned. - - * - * @stable ICU 4.6 - */ -U_STABLE UText * U_EXPORT2 -uregex_groupUText(URegularExpression *regexp, - int32_t groupNum, - UText *dest, - int64_t *groupLength, - UErrorCode *status); - -/** - * Returns the index in the input string of the start of the text matched by the - * specified capture group during the previous match operation. Return -1 if - * the capture group was not part of the last match. - * Group #0 refers to the complete range of matched text. - * Group #1 refers to the text matched by the first set of capturing parentheses. - * - * @param regexp The compiled regular expression. - * @param groupNum The capture group number - * @param status A reference to a UErrorCode to receive any errors. - * @return the starting (native) position in the input of the text matched - * by the specified group. - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_start(URegularExpression *regexp, - int32_t groupNum, - UErrorCode *status); - -/** - * 64bit version of uregex_start. - * Returns the index in the input string of the start of the text matched by the - * specified capture group during the previous match operation. Return -1 if - * the capture group was not part of the last match. - * Group #0 refers to the complete range of matched text. - * Group #1 refers to the text matched by the first set of capturing parentheses. - * - * @param regexp The compiled regular expression. - * @param groupNum The capture group number - * @param status A reference to a UErrorCode to receive any errors. - * @return the starting (native) position in the input of the text matched - * by the specified group. - * @stable ICU 4.6 - */ -U_STABLE int64_t U_EXPORT2 -uregex_start64(URegularExpression *regexp, - int32_t groupNum, - UErrorCode *status); - -/** - * Returns the index in the input string of the position following the end - * of the text matched by the specified capture group. - * Return -1 if the capture group was not part of the last match. - * Group #0 refers to the complete range of matched text. - * Group #1 refers to the text matched by the first set of capturing parentheses. - * - * @param regexp The compiled regular expression. - * @param groupNum The capture group number - * @param status A reference to a UErrorCode to receive any errors. - * @return the (native) index of the position following the last matched character. - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_end(URegularExpression *regexp, - int32_t groupNum, - UErrorCode *status); - -/** - * 64bit version of uregex_end. - * Returns the index in the input string of the position following the end - * of the text matched by the specified capture group. - * Return -1 if the capture group was not part of the last match. - * Group #0 refers to the complete range of matched text. - * Group #1 refers to the text matched by the first set of capturing parentheses. - * - * @param regexp The compiled regular expression. - * @param groupNum The capture group number - * @param status A reference to a UErrorCode to receive any errors. - * @return the (native) index of the position following the last matched character. - * @stable ICU 4.6 - */ -U_STABLE int64_t U_EXPORT2 -uregex_end64(URegularExpression *regexp, - int32_t groupNum, - UErrorCode *status); - -/** - * Reset any saved state from the previous match. Has the effect of - * causing uregex_findNext to begin at the specified index, and causing - * uregex_start(), uregex_end() and uregex_group() to return an error - * indicating that there is no match information available. Clears any - * match region that may have been set. - * - * @param regexp The compiled regular expression. - * @param index The position (native) in the text at which a - * uregex_findNext() should begin searching. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 3.0 - */ -U_STABLE void U_EXPORT2 -uregex_reset(URegularExpression *regexp, - int32_t index, - UErrorCode *status); - -/** - * 64bit version of uregex_reset. - * Reset any saved state from the previous match. Has the effect of - * causing uregex_findNext to begin at the specified index, and causing - * uregex_start(), uregex_end() and uregex_group() to return an error - * indicating that there is no match information available. Clears any - * match region that may have been set. - * - * @param regexp The compiled regular expression. - * @param index The position (native) in the text at which a - * uregex_findNext() should begin searching. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.6 - */ -U_STABLE void U_EXPORT2 -uregex_reset64(URegularExpression *regexp, - int64_t index, - UErrorCode *status); - -/** - * Sets the limits of the matching region for this URegularExpression. - * The region is the part of the input string that will be considered when matching. - * Invoking this method resets any saved state from the previous match, - * then sets the region to start at the index specified by the start parameter - * and end at the index specified by the end parameter. - * - * Depending on the transparency and anchoring being used (see useTransparentBounds - * and useAnchoringBounds), certain constructs such as anchors may behave differently - * at or around the boundaries of the region - * - * The function will fail if start is greater than limit, or if either index - * is less than zero or greater than the length of the string being matched. - * - * @param regexp The compiled regular expression. - * @param regionStart The (native) index to begin searches at. - * @param regionLimit The (native) index to end searches at (exclusive). - * @param status A pointer to a UErrorCode to receive any errors. - * @stable ICU 4.0 - */ -U_STABLE void U_EXPORT2 -uregex_setRegion(URegularExpression *regexp, - int32_t regionStart, - int32_t regionLimit, - UErrorCode *status); - -/** - * 64bit version of uregex_setRegion. - * Sets the limits of the matching region for this URegularExpression. - * The region is the part of the input string that will be considered when matching. - * Invoking this method resets any saved state from the previous match, - * then sets the region to start at the index specified by the start parameter - * and end at the index specified by the end parameter. - * - * Depending on the transparency and anchoring being used (see useTransparentBounds - * and useAnchoringBounds), certain constructs such as anchors may behave differently - * at or around the boundaries of the region - * - * The function will fail if start is greater than limit, or if either index - * is less than zero or greater than the length of the string being matched. - * - * @param regexp The compiled regular expression. - * @param regionStart The (native) index to begin searches at. - * @param regionLimit The (native) index to end searches at (exclusive). - * @param status A pointer to a UErrorCode to receive any errors. - * @stable ICU 4.6 - */ -U_STABLE void U_EXPORT2 -uregex_setRegion64(URegularExpression *regexp, - int64_t regionStart, - int64_t regionLimit, - UErrorCode *status); - -/** - * Set the matching region and the starting index for subsequent matches - * in a single operation. - * This is useful because the usual function for setting the starting - * index, urgex_reset(), also resets any region limits. - * - * @param regexp The compiled regular expression. - * @param regionStart The (native) index to begin searches at. - * @param regionLimit The (native) index to end searches at (exclusive). - * @param startIndex The index in the input text at which the next - * match operation should begin. - * @param status A pointer to a UErrorCode to receive any errors. - * @stable ICU 4.6 - */ -U_STABLE void U_EXPORT2 -uregex_setRegionAndStart(URegularExpression *regexp, - int64_t regionStart, - int64_t regionLimit, - int64_t startIndex, - UErrorCode *status); - -/** - * Reports the start index of the matching region. Any matches found are limited to - * to the region bounded by regionStart (inclusive) and regionEnd (exclusive). - * - * @param regexp The compiled regular expression. - * @param status A pointer to a UErrorCode to receive any errors. - * @return The starting (native) index of this matcher's region. - * @stable ICU 4.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_regionStart(const URegularExpression *regexp, - UErrorCode *status); - -/** - * 64bit version of uregex_regionStart. - * Reports the start index of the matching region. Any matches found are limited to - * to the region bounded by regionStart (inclusive) and regionEnd (exclusive). - * - * @param regexp The compiled regular expression. - * @param status A pointer to a UErrorCode to receive any errors. - * @return The starting (native) index of this matcher's region. - * @stable ICU 4.6 - */ -U_STABLE int64_t U_EXPORT2 -uregex_regionStart64(const URegularExpression *regexp, - UErrorCode *status); - -/** - * Reports the end index (exclusive) of the matching region for this URegularExpression. - * Any matches found are limited to to the region bounded by regionStart (inclusive) - * and regionEnd (exclusive). - * - * @param regexp The compiled regular expression. - * @param status A pointer to a UErrorCode to receive any errors. - * @return The ending point (native) of this matcher's region. - * @stable ICU 4.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_regionEnd(const URegularExpression *regexp, - UErrorCode *status); - -/** - * 64bit version of uregex_regionEnd. - * Reports the end index (exclusive) of the matching region for this URegularExpression. - * Any matches found are limited to to the region bounded by regionStart (inclusive) - * and regionEnd (exclusive). - * - * @param regexp The compiled regular expression. - * @param status A pointer to a UErrorCode to receive any errors. - * @return The ending point (native) of this matcher's region. - * @stable ICU 4.6 - */ -U_STABLE int64_t U_EXPORT2 -uregex_regionEnd64(const URegularExpression *regexp, - UErrorCode *status); - -/** - * Queries the transparency of region bounds for this URegularExpression. - * See useTransparentBounds for a description of transparent and opaque bounds. - * By default, matching boundaries are opaque. - * - * @param regexp The compiled regular expression. - * @param status A pointer to a UErrorCode to receive any errors. - * @return TRUE if this matcher is using opaque bounds, false if it is not. - * @stable ICU 4.0 - */ -U_STABLE UBool U_EXPORT2 -uregex_hasTransparentBounds(const URegularExpression *regexp, - UErrorCode *status); - - -/** - * Sets the transparency of region bounds for this URegularExpression. - * Invoking this function with an argument of TRUE will set matches to use transparent bounds. - * If the boolean argument is FALSE, then opaque bounds will be used. - * - * Using transparent bounds, the boundaries of the matching region are transparent - * to lookahead, lookbehind, and boundary matching constructs. Those constructs can - * see text beyond the boundaries of the region while checking for a match. - * - * With opaque bounds, no text outside of the matching region is visible to lookahead, - * lookbehind, and boundary matching constructs. - * - * By default, opaque bounds are used. - * - * @param regexp The compiled regular expression. - * @param b TRUE for transparent bounds; FALSE for opaque bounds - * @param status A pointer to a UErrorCode to receive any errors. - * @stable ICU 4.0 - **/ -U_STABLE void U_EXPORT2 -uregex_useTransparentBounds(URegularExpression *regexp, - UBool b, - UErrorCode *status); - - -/** - * Return true if this URegularExpression is using anchoring bounds. - * By default, anchoring region bounds are used. - * - * @param regexp The compiled regular expression. - * @param status A pointer to a UErrorCode to receive any errors. - * @return TRUE if this matcher is using anchoring bounds. - * @stable ICU 4.0 - */ -U_STABLE UBool U_EXPORT2 -uregex_hasAnchoringBounds(const URegularExpression *regexp, - UErrorCode *status); - - -/** - * Set whether this URegularExpression is using Anchoring Bounds for its region. - * With anchoring bounds, pattern anchors such as ^ and $ will match at the start - * and end of the region. Without Anchoring Bounds, anchors will only match at - * the positions they would in the complete text. - * - * Anchoring Bounds are the default for regions. - * - * @param regexp The compiled regular expression. - * @param b TRUE if to enable anchoring bounds; FALSE to disable them. - * @param status A pointer to a UErrorCode to receive any errors. - * @stable ICU 4.0 - */ -U_STABLE void U_EXPORT2 -uregex_useAnchoringBounds(URegularExpression *regexp, - UBool b, - UErrorCode *status); - -/** - * Return TRUE if the most recent matching operation touched the - * end of the text being processed. In this case, additional input text could - * change the results of that match. - * - * @param regexp The compiled regular expression. - * @param status A pointer to a UErrorCode to receive any errors. - * @return TRUE if the most recent match hit the end of input - * @stable ICU 4.0 - */ -U_STABLE UBool U_EXPORT2 -uregex_hitEnd(const URegularExpression *regexp, - UErrorCode *status); - -/** - * Return TRUE the most recent match succeeded and additional input could cause - * it to fail. If this function returns false and a match was found, then more input - * might change the match but the match won't be lost. If a match was not found, - * then requireEnd has no meaning. - * - * @param regexp The compiled regular expression. - * @param status A pointer to a UErrorCode to receive any errors. - * @return TRUE if more input could cause the most recent match to no longer match. - * @stable ICU 4.0 - */ -U_STABLE UBool U_EXPORT2 -uregex_requireEnd(const URegularExpression *regexp, - UErrorCode *status); - - - - - -/** - * Replaces every substring of the input that matches the pattern - * with the given replacement string. This is a convenience function that - * provides a complete find-and-replace-all operation. - * - * This method scans the input string looking for matches of the pattern. - * Input that is not part of any match is copied unchanged to the - * destination buffer. Matched regions are replaced in the output - * buffer by the replacement string. The replacement string may contain - * references to capture groups; these take the form of $1, $2, etc. - * - * @param regexp The compiled regular expression. - * @param replacementText A string containing the replacement text. - * @param replacementLength The length of the replacement string, or - * -1 if it is NUL terminated. - * @param destBuf A (UChar *) buffer that will receive the result. - * @param destCapacity The capacity of the destination buffer. - * @param status A reference to a UErrorCode to receive any errors. - * @return The length of the string resulting from the find - * and replace operation. In the event that the - * destination capacity is inadequate, the return value - * is still the full length of the untruncated string. - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_replaceAll(URegularExpression *regexp, - const UChar *replacementText, - int32_t replacementLength, - UChar *destBuf, - int32_t destCapacity, - UErrorCode *status); - -/** - * Replaces every substring of the input that matches the pattern - * with the given replacement string. This is a convenience function that - * provides a complete find-and-replace-all operation. - * - * This method scans the input string looking for matches of the pattern. - * Input that is not part of any match is copied unchanged to the - * destination buffer. Matched regions are replaced in the output - * buffer by the replacement string. The replacement string may contain - * references to capture groups; these take the form of $1, $2, etc. - * - * @param regexp The compiled regular expression. - * @param replacement A string containing the replacement text. - * @param dest A mutable UText that will receive the result. - * If NULL, a new UText will be created (which may not be mutable). - * @param status A reference to a UErrorCode to receive any errors. - * @return A UText containing the results of the find and replace. - * If a pre-allocated UText was provided, it will always be used and returned. - * - * @stable ICU 4.6 - */ -U_STABLE UText * U_EXPORT2 -uregex_replaceAllUText(URegularExpression *regexp, - UText *replacement, - UText *dest, - UErrorCode *status); - -/** - * Replaces the first substring of the input that matches the pattern - * with the given replacement string. This is a convenience function that - * provides a complete find-and-replace operation. - * - * This method scans the input string looking for a match of the pattern. - * All input that is not part of the match is copied unchanged to the - * destination buffer. The matched region is replaced in the output - * buffer by the replacement string. The replacement string may contain - * references to capture groups; these take the form of $1, $2, etc. - * - * @param regexp The compiled regular expression. - * @param replacementText A string containing the replacement text. - * @param replacementLength The length of the replacement string, or - * -1 if it is NUL terminated. - * @param destBuf A (UChar *) buffer that will receive the result. - * @param destCapacity The capacity of the destination buffer. - * @param status a reference to a UErrorCode to receive any errors. - * @return The length of the string resulting from the find - * and replace operation. In the event that the - * destination capacity is inadequate, the return value - * is still the full length of the untruncated string. - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_replaceFirst(URegularExpression *regexp, - const UChar *replacementText, - int32_t replacementLength, - UChar *destBuf, - int32_t destCapacity, - UErrorCode *status); - -/** - * Replaces the first substring of the input that matches the pattern - * with the given replacement string. This is a convenience function that - * provides a complete find-and-replace operation. - * - * This method scans the input string looking for a match of the pattern. - * All input that is not part of the match is copied unchanged to the - * destination buffer. The matched region is replaced in the output - * buffer by the replacement string. The replacement string may contain - * references to capture groups; these take the form of $1, $2, etc. - * - * @param regexp The compiled regular expression. - * @param replacement A string containing the replacement text. - * @param dest A mutable UText that will receive the result. - * If NULL, a new UText will be created (which may not be mutable). - * @param status A reference to a UErrorCode to receive any errors. - * @return A UText containing the results of the find and replace. - * If a pre-allocated UText was provided, it will always be used and returned. - * - * @stable ICU 4.6 - */ -U_STABLE UText * U_EXPORT2 -uregex_replaceFirstUText(URegularExpression *regexp, - UText *replacement, - UText *dest, - UErrorCode *status); - -/** - * Implements a replace operation intended to be used as part of an - * incremental find-and-replace. - * - *

The input string, starting from the end of the previous match and ending at - * the start of the current match, is appended to the destination string. Then the - * replacement string is appended to the output string, - * including handling any substitutions of captured text.

- * - *

A note on preflight computation of buffersize and error handling: - * Calls to uregex_appendReplacement() and uregex_appendTail() are - * designed to be chained, one after another, with the destination - * buffer pointer and buffer capacity updated after each in preparation - * to for the next. If the destination buffer is exhausted partway through such a - * sequence, a U_BUFFER_OVERFLOW_ERROR status will be returned. Normal - * ICU conventions are for a function to perform no action if it is - * called with an error status, but for this one case, uregex_appendRepacement() - * will operate normally so that buffer size computations will complete - * correctly. - * - *

For simple, prepackaged, non-incremental find-and-replace - * operations, see replaceFirst() or replaceAll().

- * - * @param regexp The regular expression object. - * @param replacementText The string that will replace the matched portion of the - * input string as it is copied to the destination buffer. - * The replacement text may contain references ($1, for - * example) to capture groups from the match. - * @param replacementLength The length of the replacement text string, - * or -1 if the string is NUL terminated. - * @param destBuf The buffer into which the results of the - * find-and-replace are placed. On return, this pointer - * will be updated to refer to the beginning of the - * unused portion of buffer, leaving it in position for - * a subsequent call to this function. - * @param destCapacity The size of the output buffer, On return, this - * parameter will be updated to reflect the space remaining - * unused in the output buffer. - * @param status A reference to a UErrorCode to receive any errors. - * @return The length of the result string. In the event that - * destCapacity is inadequate, the full length of the - * untruncated output string is returned. - * - * @stable ICU 3.0 - * - */ -U_STABLE int32_t U_EXPORT2 -uregex_appendReplacement(URegularExpression *regexp, - const UChar *replacementText, - int32_t replacementLength, - UChar **destBuf, - int32_t *destCapacity, - UErrorCode *status); - -/** - * Implements a replace operation intended to be used as part of an - * incremental find-and-replace. - * - *

The input string, starting from the end of the previous match and ending at - * the start of the current match, is appended to the destination string. Then the - * replacement string is appended to the output string, - * including handling any substitutions of captured text.

- * - *

For simple, prepackaged, non-incremental find-and-replace - * operations, see replaceFirst() or replaceAll().

- * - * @param regexp The regular expression object. - * @param replacementText The string that will replace the matched portion of the - * input string as it is copied to the destination buffer. - * The replacement text may contain references ($1, for - * example) to capture groups from the match. - * @param dest A mutable UText that will receive the result. Must not be NULL. - * @param status A reference to a UErrorCode to receive any errors. - * - * @stable ICU 4.6 - */ -U_STABLE void U_EXPORT2 -uregex_appendReplacementUText(URegularExpression *regexp, - UText *replacementText, - UText *dest, - UErrorCode *status); - -/** - * As the final step in a find-and-replace operation, append the remainder - * of the input string, starting at the position following the last match, - * to the destination string. uregex_appendTail() is intended - * to be invoked after one or more invocations of the - * uregex_appendReplacement() function. - * - * @param regexp The regular expression object. This is needed to - * obtain the input string and with the position - * of the last match within it. - * @param destBuf The buffer in which the results of the - * find-and-replace are placed. On return, the pointer - * will be updated to refer to the beginning of the - * unused portion of buffer. - * @param destCapacity The size of the output buffer, On return, this - * value will be updated to reflect the space remaining - * unused in the output buffer. - * @param status A reference to a UErrorCode to receive any errors. - * @return The length of the result string. In the event that - * destCapacity is inadequate, the full length of the - * untruncated output string is returned. - * - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_appendTail(URegularExpression *regexp, - UChar **destBuf, - int32_t *destCapacity, - UErrorCode *status); - -/** - * As the final step in a find-and-replace operation, append the remainder - * of the input string, starting at the position following the last match, - * to the destination string. uregex_appendTailUText() is intended - * to be invoked after one or more invocations of the - * uregex_appendReplacementUText() function. - * - * @param regexp The regular expression object. This is needed to - * obtain the input string and with the position - * of the last match within it. - * @param dest A mutable UText that will receive the result. Must not be NULL. - * - * @param status Error code - * - * @return The destination UText. - * - * @stable ICU 4.6 - */ -U_STABLE UText * U_EXPORT2 -uregex_appendTailUText(URegularExpression *regexp, - UText *dest, - UErrorCode *status); - - /** - * Split a string into fields. Somewhat like split() from Perl. - * The pattern matches identify delimiters that separate the input - * into fields. The input data between the matches becomes the - * fields themselves. - * - * Each of the fields is copied from the input string to the destination - * buffer, and NUL terminated. The position of each field within - * the destination buffer is returned in the destFields array. - * - * If the delimiter pattern includes capture groups, the captured text will - * also appear in the destination array of output strings, interspersed - * with the fields. This is similar to Perl, but differs from Java, - * which ignores the presence of capture groups in the pattern. - * - * Trailing empty fields will always be returned, assuming sufficient - * destination capacity. This differs from the default behavior for Java - * and Perl where trailing empty fields are not returned. - * - * The number of strings produced by the split operation is returned. - * This count includes the strings from capture groups in the delimiter pattern. - * This behavior differs from Java, which ignores capture groups. - * - * @param regexp The compiled regular expression. - * @param destBuf A (UChar *) buffer to receive the fields that - * are extracted from the input string. These - * field pointers will refer to positions within the - * destination buffer supplied by the caller. Any - * extra positions within the destFields array will be - * set to NULL. - * @param destCapacity The capacity of the destBuf. - * @param requiredCapacity The actual capacity required of the destBuf. - * If destCapacity is too small, requiredCapacity will return - * the total capacity required to hold all of the output, and - * a U_BUFFER_OVERFLOW_ERROR will be returned. - * @param destFields An array to be filled with the position of each - * of the extracted fields within destBuf. - * @param destFieldsCapacity The number of elements in the destFields array. - * If the number of fields found is less than destFieldsCapacity, - * the extra destFields elements are set to zero. - * If destFieldsCapacity is too small, the trailing part of the - * input, including any field delimiters, is treated as if it - * were the last field - it is copied to the destBuf, and - * its position is in the destBuf is stored in the last element - * of destFields. This behavior mimics that of Perl. It is not - * an error condition, and no error status is returned when all destField - * positions are used. - * @param status A reference to a UErrorCode to receive any errors. - * @return The number of fields into which the input string was split. - * @stable ICU 3.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_split( URegularExpression *regexp, - UChar *destBuf, - int32_t destCapacity, - int32_t *requiredCapacity, - UChar *destFields[], - int32_t destFieldsCapacity, - UErrorCode *status); - - /** - * Split a string into fields. Somewhat like split() from Perl. - * The pattern matches identify delimiters that separate the input - * into fields. The input data between the matches becomes the - * fields themselves. - *

- * The behavior of this function is not very closely aligned with uregex_split(); - * instead, it is based on (and implemented directly on top of) the C++ split method. - * - * @param regexp The compiled regular expression. - * @param destFields An array of mutable UText structs to receive the results of the split. - * If a field is NULL, a new UText is allocated to contain the results for - * that field. This new UText is not guaranteed to be mutable. - * @param destFieldsCapacity The number of elements in the destination array. - * If the number of fields found is less than destCapacity, the - * extra strings in the destination array are not altered. - * If the number of destination strings is less than the number - * of fields, the trailing part of the input string, including any - * field delimiters, is placed in the last destination string. - * This behavior mimics that of Perl. It is not an error condition, and no - * error status is returned when all destField positions are used. - * @param status A reference to a UErrorCode to receive any errors. - * @return The number of fields into which the input string was split. - * - * @stable ICU 4.6 - */ -U_STABLE int32_t U_EXPORT2 -uregex_splitUText(URegularExpression *regexp, - UText *destFields[], - int32_t destFieldsCapacity, - UErrorCode *status); - -/** - * Set a processing time limit for match operations with this URegularExpression. - * - * Some patterns, when matching certain strings, can run in exponential time. - * For practical purposes, the match operation may appear to be in an - * infinite loop. - * When a limit is set a match operation will fail with an error if the - * limit is exceeded. - *

- * The units of the limit are steps of the match engine. - * Correspondence with actual processor time will depend on the speed - * of the processor and the details of the specific pattern, but will - * typically be on the order of milliseconds. - *

- * By default, the matching time is not limited. - *

- * - * @param regexp The compiled regular expression. - * @param limit The limit value, or 0 for no limit. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.0 - */ -U_STABLE void U_EXPORT2 -uregex_setTimeLimit(URegularExpression *regexp, - int32_t limit, - UErrorCode *status); - -/** - * Get the time limit for for matches with this URegularExpression. - * A return value of zero indicates that there is no limit. - * - * @param regexp The compiled regular expression. - * @param status A reference to a UErrorCode to receive any errors. - * @return the maximum allowed time for a match, in units of processing steps. - * @stable ICU 4.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_getTimeLimit(const URegularExpression *regexp, - UErrorCode *status); - -/** - * Set the amount of heap storage available for use by the match backtracking stack. - *

- * ICU uses a backtracking regular expression engine, with the backtrack stack - * maintained on the heap. This function sets the limit to the amount of memory - * that can be used for this purpose. A backtracking stack overflow will - * result in an error from the match operation that caused it. - *

- * A limit is desirable because a malicious or poorly designed pattern can use - * excessive memory, potentially crashing the process. A limit is enabled - * by default. - *

- * @param regexp The compiled regular expression. - * @param limit The maximum size, in bytes, of the matching backtrack stack. - * A value of zero means no limit. - * The limit must be greater than or equal to zero. - * @param status A reference to a UErrorCode to receive any errors. - * - * @stable ICU 4.0 - */ -U_STABLE void U_EXPORT2 -uregex_setStackLimit(URegularExpression *regexp, - int32_t limit, - UErrorCode *status); - -/** - * Get the size of the heap storage available for use by the back tracking stack. - * - * @return the maximum backtracking stack size, in bytes, or zero if the - * stack size is unlimited. - * @stable ICU 4.0 - */ -U_STABLE int32_t U_EXPORT2 -uregex_getStackLimit(const URegularExpression *regexp, - UErrorCode *status); - - -/** - * Function pointer for a regular expression matching callback function. - * When set, a callback function will be called periodically during matching - * operations. If the call back function returns FALSE, the matching - * operation will be terminated early. - * - * Note: the callback function must not call other functions on this - * URegularExpression. - * - * @param context context pointer. The callback function will be invoked - * with the context specified at the time that - * uregex_setMatchCallback() is called. - * @param steps the accumulated processing time, in match steps, - * for this matching operation. - * @return TRUE to continue the matching operation. - * FALSE to terminate the matching operation. - * @stable ICU 4.0 - */ -U_CDECL_BEGIN -typedef UBool U_CALLCONV URegexMatchCallback ( - const void *context, - int32_t steps); -U_CDECL_END - -/** - * Set a callback function for this URegularExpression. - * During matching operations the function will be called periodically, - * giving the application the opportunity to terminate a long-running - * match. - * - * @param regexp The compiled regular expression. - * @param callback A pointer to the user-supplied callback function. - * @param context User context pointer. The value supplied at the - * time the callback function is set will be saved - * and passed to the callback each time that it is called. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.0 - */ -U_STABLE void U_EXPORT2 -uregex_setMatchCallback(URegularExpression *regexp, - URegexMatchCallback *callback, - const void *context, - UErrorCode *status); - - -/** - * Get the callback function for this URegularExpression. - * - * @param regexp The compiled regular expression. - * @param callback Out parameter, receives a pointer to the user-supplied - * callback function. - * @param context Out parameter, receives the user context pointer that - * was set when uregex_setMatchCallback() was called. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.0 - */ -U_STABLE void U_EXPORT2 -uregex_getMatchCallback(const URegularExpression *regexp, - URegexMatchCallback **callback, - const void **context, - UErrorCode *status); - -/** - * Function pointer for a regular expression find callback function. - * - * When set, a callback function will be called during a find operation - * and for operations that depend on find, such as findNext, split and some replace - * operations like replaceFirst. - * The callback will usually be called after each attempt at a match, but this is not a - * guarantee that the callback will be invoked at each character. For finds where the - * match engine is invoked at each character, this may be close to true, but less likely - * for more optimized loops where the pattern is known to only start, and the match - * engine invoked, at certain characters. - * When invoked, this callback will specify the index at which a match operation is about - * to be attempted, giving the application the opportunity to terminate a long-running - * find operation. - * - * If the call back function returns FALSE, the find operation will be terminated early. - * - * Note: the callback function must not call other functions on this - * URegularExpression - * - * @param context context pointer. The callback function will be invoked - * with the context specified at the time that - * uregex_setFindProgressCallback() is called. - * @param matchIndex the next index at which a match attempt will be attempted for this - * find operation. If this callback interrupts the search, this is the - * index at which a find/findNext operation may be re-initiated. - * @return TRUE to continue the matching operation. - * FALSE to terminate the matching operation. - * @stable ICU 4.6 - */ -U_CDECL_BEGIN -typedef UBool U_CALLCONV URegexFindProgressCallback ( - const void *context, - int64_t matchIndex); -U_CDECL_END - - -/** - * Set the find progress callback function for this URegularExpression. - * - * @param regexp The compiled regular expression. - * @param callback A pointer to the user-supplied callback function. - * @param context User context pointer. The value supplied at the - * time the callback function is set will be saved - * and passed to the callback each time that it is called. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.6 - */ -U_STABLE void U_EXPORT2 -uregex_setFindProgressCallback(URegularExpression *regexp, - URegexFindProgressCallback *callback, - const void *context, - UErrorCode *status); - -/** - * Get the find progress callback function for this URegularExpression. - * - * @param regexp The compiled regular expression. - * @param callback Out parameter, receives a pointer to the user-supplied - * callback function. - * @param context Out parameter, receives the user context pointer that - * was set when uregex_setFindProgressCallback() was called. - * @param status A reference to a UErrorCode to receive any errors. - * @stable ICU 4.6 - */ -U_STABLE void U_EXPORT2 -uregex_getFindProgressCallback(const URegularExpression *regexp, - URegexFindProgressCallback **callback, - const void **context, - UErrorCode *status); - -#endif /* !UCONFIG_NO_REGULAR_EXPRESSIONS */ -#endif /* UREGEX_H */ diff --git a/win32/include/spidermonkey/unicode/uregion.h b/win32/include/spidermonkey/unicode/uregion.h deleted file mode 100755 index 1b0f146e..00000000 --- a/win32/include/spidermonkey/unicode/uregion.h +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -***************************************************************************************** -* Copyright (C) 2014, International Business Machines -* Corporation and others. All Rights Reserved. -***************************************************************************************** -*/ - -#ifndef UREGION_H -#define UREGION_H - -#include "unicode/utypes.h" -#include "unicode/uenum.h" - -/** - * \file - * \brief C API: URegion (territory containment and mapping) - * - * URegion objects represent data associated with a particular Unicode Region Code, also known as a - * Unicode Region Subtag, which is defined based upon the BCP 47 standard. These include: - * * Two-letter codes defined by ISO 3166-1, with special LDML treatment of certain private-use or - * reserved codes; - * * A subset of 3-digit numeric codes defined by UN M.49. - * URegion objects can also provide mappings to and from additional codes. There are different types - * of regions that are important to distinguish: - *

- * Macroregion - A code for a "macro geographical (continental) region, geographical sub-region, or - * selected economic and other grouping" as defined in UN M.49. These are typically 3-digit codes, - * but contain some 2-letter codes for LDML extensions, such as "QO" for Outlying Oceania. - * Macroregions are represented in ICU by one of three region types: WORLD (code 001), - * CONTINENTS (regions contained directly by WORLD), and SUBCONTINENTS (regions contained directly - * by a continent ). - *

- * TERRITORY - A Region that is not a Macroregion. These are typically codes for countries, but also - * include areas that are not separate countries, such as the code "AQ" for Antarctica or the code - * "HK" for Hong Kong (SAR China). Overseas dependencies of countries may or may not have separate - * codes. The codes are typically 2-letter codes aligned with ISO 3166, but BCP47 allows for the use - * of 3-digit codes in the future. - *

- * UNKNOWN - The code ZZ is defined by Unicode LDML for use in indicating that region is unknown, - * or that the value supplied as a region was invalid. - *

- * DEPRECATED - Region codes that have been defined in the past but are no longer in modern usage, - * usually due to a country splitting into multiple territories or changing its name. - *

- * GROUPING - A widely understood grouping of territories that has a well defined membership such - * that a region code has been assigned for it. Some of these are UN M.49 codes that don't fall into - * the world/continent/sub-continent hierarchy, while others are just well-known groupings that have - * their own region code. Region "EU" (European Union) is one such region code that is a grouping. - * Groupings will never be returned by the uregion_getContainingRegion, since a different type of region - * (WORLD, CONTINENT, or SUBCONTINENT) will always be the containing region instead. - * - * URegion objects are const/immutable, owned and maintained by ICU itself, so there are not functions - * to open or close them. - */ - -/** - * URegionType is an enumeration defining the different types of regions. Current possible - * values are URGN_WORLD, URGN_CONTINENT, URGN_SUBCONTINENT, URGN_TERRITORY, URGN_GROUPING, - * URGN_DEPRECATED, and URGN_UNKNOWN. - * - * @stable ICU 51 - */ -typedef enum URegionType { - /** - * Type representing the unknown region. - * @stable ICU 51 - */ - URGN_UNKNOWN, - - /** - * Type representing a territory. - * @stable ICU 51 - */ - URGN_TERRITORY, - - /** - * Type representing the whole world. - * @stable ICU 51 - */ - URGN_WORLD, - - /** - * Type representing a continent. - * @stable ICU 51 - */ - URGN_CONTINENT, - - /** - * Type representing a sub-continent. - * @stable ICU 51 - */ - URGN_SUBCONTINENT, - - /** - * Type representing a grouping of territories that is not to be used in - * the normal WORLD/CONTINENT/SUBCONTINENT/TERRITORY containment tree. - * @stable ICU 51 - */ - URGN_GROUPING, - - /** - * Type representing a region whose code has been deprecated, usually - * due to a country splitting into multiple territories or changing its name. - * @stable ICU 51 - */ - URGN_DEPRECATED, - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal URegionType value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - URGN_LIMIT -#endif // U_HIDE_DEPRECATED_API -} URegionType; - -#if !UCONFIG_NO_FORMATTING - -/** - * Opaque URegion object for use in C programs. - * @stable ICU 52 - */ -struct URegion; -typedef struct URegion URegion; /**< @stable ICU 52 */ - -/** - * Returns a pointer to a URegion for the specified region code: A 2-letter or 3-letter ISO 3166 - * code, UN M.49 numeric code (superset of ISO 3166 numeric codes), or other valid Unicode Region - * Code as defined by the LDML specification. The code will be canonicalized internally. If the - * region code is NULL or not recognized, the appropriate error code will be set - * (U_ILLEGAL_ARGUMENT_ERROR). - * @stable ICU 52 - */ -U_STABLE const URegion* U_EXPORT2 -uregion_getRegionFromCode(const char *regionCode, UErrorCode *status); - -/** - * Returns a pointer to a URegion for the specified numeric region code. If the numeric region - * code is not recognized, the appropriate error code will be set (U_ILLEGAL_ARGUMENT_ERROR). - * @stable ICU 52 - */ -U_STABLE const URegion* U_EXPORT2 -uregion_getRegionFromNumericCode (int32_t code, UErrorCode *status); - -/** - * Returns an enumeration over the canonical codes of all known regions that match the given type. - * The enumeration must be closed with with uenum_close(). - * @stable ICU 52 - */ -U_STABLE UEnumeration* U_EXPORT2 -uregion_getAvailable(URegionType type, UErrorCode *status); - -/** - * Returns true if the specified uregion is equal to the specified otherRegion. - * @stable ICU 52 - */ -U_STABLE UBool U_EXPORT2 -uregion_areEqual(const URegion* uregion, const URegion* otherRegion); - -/** - * Returns a pointer to the URegion that contains the specified uregion. Returns NULL if the - * specified uregion is code "001" (World) or "ZZ" (Unknown region). For example, calling - * this method with region "IT" (Italy) returns the URegion for "039" (Southern Europe). - * @stable ICU 52 - */ -U_STABLE const URegion* U_EXPORT2 -uregion_getContainingRegion(const URegion* uregion); - -/** - * Return a pointer to the URegion that geographically contains this uregion and matches the - * specified type, moving multiple steps up the containment chain if necessary. Returns NULL if no - * containing region can be found that matches the specified type. Will return NULL if URegionType - * is URGN_GROUPING, URGN_DEPRECATED, or URGN_UNKNOWN which are not appropriate for this API. - * For example, calling this method with uregion "IT" (Italy) for type URGN_CONTINENT returns the - * URegion "150" (Europe). - * @stable ICU 52 - */ -U_STABLE const URegion* U_EXPORT2 -uregion_getContainingRegionOfType(const URegion* uregion, URegionType type); - -/** - * Return an enumeration over the canonical codes of all the regions that are immediate children - * of the specified uregion in the region hierarchy. These returned regions could be either macro - * regions, territories, or a mixture of the two, depending on the containment data as defined in - * CLDR. This API returns NULL if this uregion doesn't have any sub-regions. For example, calling - * this function for uregion "150" (Europe) returns an enumeration containing the various - * sub-regions of Europe: "039" (Southern Europe), "151" (Eastern Europe), "154" (Northern Europe), - * and "155" (Western Europe). The enumeration must be closed with with uenum_close(). - * @stable ICU 52 - */ -U_STABLE UEnumeration* U_EXPORT2 -uregion_getContainedRegions(const URegion* uregion, UErrorCode *status); - -/** - * Returns an enumeration over the canonical codes of all the regions that are children of the - * specified uregion anywhere in the region hierarchy and match the given type. This API may return - * an empty enumeration if this uregion doesn't have any sub-regions that match the given type. - * For example, calling this method with region "150" (Europe) and type URGN_TERRITORY" returns an - * enumeration containing all the territories in Europe: "FR" (France), "IT" (Italy), "DE" (Germany), - * etc. The enumeration must be closed with with uenum_close(). - * @stable ICU 52 - */ -U_STABLE UEnumeration* U_EXPORT2 -uregion_getContainedRegionsOfType(const URegion* uregion, URegionType type, UErrorCode *status); - -/** - * Returns true if the specified uregion contains the specified otherRegion anywhere in the region - * hierarchy. - * @stable ICU 52 - */ -U_STABLE UBool U_EXPORT2 -uregion_contains(const URegion* uregion, const URegion* otherRegion); - -/** - * If the specified uregion is deprecated, returns an enumeration over the canonical codes of the - * regions that are the preferred replacement regions for the specified uregion. If the specified - * uregion is not deprecated, returns NULL. For example, calling this method with uregion - * "SU" (Soviet Union) returns a list of the regions containing "RU" (Russia), "AM" (Armenia), - * "AZ" (Azerbaijan), etc... The enumeration must be closed with with uenum_close(). - * @stable ICU 52 - */ -U_STABLE UEnumeration* U_EXPORT2 -uregion_getPreferredValues(const URegion* uregion, UErrorCode *status); - -/** - * Returns the specified uregion's canonical code. - * @stable ICU 52 - */ -U_STABLE const char* U_EXPORT2 -uregion_getRegionCode(const URegion* uregion); - -/** - * Returns the specified uregion's numeric code, or a negative value if there is no numeric code - * for the specified uregion. - * @stable ICU 52 - */ -U_STABLE int32_t U_EXPORT2 -uregion_getNumericCode(const URegion* uregion); - -/** - * Returns the URegionType of the specified uregion. - * @stable ICU 52 - */ -U_STABLE URegionType U_EXPORT2 -uregion_getType(const URegion* uregion); - - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif diff --git a/win32/include/spidermonkey/unicode/ureldatefmt.h b/win32/include/spidermonkey/unicode/ureldatefmt.h deleted file mode 100755 index 40b3d593..00000000 --- a/win32/include/spidermonkey/unicode/ureldatefmt.h +++ /dev/null @@ -1,371 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -***************************************************************************************** -* Copyright (C) 2016, International Business Machines -* Corporation and others. All Rights Reserved. -***************************************************************************************** -*/ - -#ifndef URELDATEFMT_H -#define URELDATEFMT_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_FORMATTING && !UCONFIG_NO_BREAK_ITERATION - -#include "unicode/unum.h" -#include "unicode/udisplaycontext.h" -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: URelativeDateTimeFormatter, relative date formatting of unit + numeric offset. - * - * Provides simple formatting of relative dates, in two ways - *

    - *
  • relative dates with a quantity e.g "in 5 days"
  • - *
  • relative dates without a quantity e.g "next Tuesday"
  • - *
- *

- * This does not provide compound formatting for multiple units, - * other than the ability to combine a time string with a relative date, - * as in "next Tuesday at 3:45 PM". It also does not provide support - * for determining which unit to use, such as deciding between "in 7 days" - * and "in 1 week". - * - * @draft ICU 57 - */ - -/** - * The formatting style - * @stable ICU 54 - */ -typedef enum UDateRelativeDateTimeFormatterStyle { - /** - * Everything spelled out. - * @stable ICU 54 - */ - UDAT_STYLE_LONG, - - /** - * Abbreviations used when possible. - * @stable ICU 54 - */ - UDAT_STYLE_SHORT, - - /** - * Use the shortest possible form. - * @stable ICU 54 - */ - UDAT_STYLE_NARROW, - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UDateRelativeDateTimeFormatterStyle value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UDAT_STYLE_COUNT -#endif // U_HIDE_DEPRECATED_API -} UDateRelativeDateTimeFormatterStyle; - -#ifndef U_HIDE_DRAFT_API -/** - * Represents the unit for formatting a relative date. e.g "in 5 days" - * or "next year" - * @draft ICU 57 - */ -typedef enum URelativeDateTimeUnit { - /** - * Specifies that relative unit is year, e.g. "last year", - * "in 5 years". - * @draft ICU 57 - */ - UDAT_REL_UNIT_YEAR, - /** - * Specifies that relative unit is quarter, e.g. "last quarter", - * "in 5 quarters". - * @draft ICU 57 - */ - UDAT_REL_UNIT_QUARTER, - /** - * Specifies that relative unit is month, e.g. "last month", - * "in 5 months". - * @draft ICU 57 - */ - UDAT_REL_UNIT_MONTH, - /** - * Specifies that relative unit is week, e.g. "last week", - * "in 5 weeks". - * @draft ICU 57 - */ - UDAT_REL_UNIT_WEEK, - /** - * Specifies that relative unit is day, e.g. "yesterday", - * "in 5 days". - * @draft ICU 57 - */ - UDAT_REL_UNIT_DAY, - /** - * Specifies that relative unit is hour, e.g. "1 hour ago", - * "in 5 hours". - * @draft ICU 57 - */ - UDAT_REL_UNIT_HOUR, - /** - * Specifies that relative unit is minute, e.g. "1 minute ago", - * "in 5 minutes". - * @draft ICU 57 - */ - UDAT_REL_UNIT_MINUTE, - /** - * Specifies that relative unit is second, e.g. "1 second ago", - * "in 5 seconds". - * @draft ICU 57 - */ - UDAT_REL_UNIT_SECOND, - /** - * Specifies that relative unit is Sunday, e.g. "last Sunday", - * "this Sunday", "next Sunday", "in 5 Sundays". - * @draft ICU 57 - */ - UDAT_REL_UNIT_SUNDAY, - /** - * Specifies that relative unit is Monday, e.g. "last Monday", - * "this Monday", "next Monday", "in 5 Mondays". - * @draft ICU 57 - */ - UDAT_REL_UNIT_MONDAY, - /** - * Specifies that relative unit is Tuesday, e.g. "last Tuesday", - * "this Tuesday", "next Tuesday", "in 5 Tuesdays". - * @draft ICU 57 - */ - UDAT_REL_UNIT_TUESDAY, - /** - * Specifies that relative unit is Wednesday, e.g. "last Wednesday", - * "this Wednesday", "next Wednesday", "in 5 Wednesdays". - * @draft ICU 57 - */ - UDAT_REL_UNIT_WEDNESDAY, - /** - * Specifies that relative unit is Thursday, e.g. "last Thursday", - * "this Thursday", "next Thursday", "in 5 Thursdays". - * @draft ICU 57 - */ - UDAT_REL_UNIT_THURSDAY, - /** - * Specifies that relative unit is Friday, e.g. "last Friday", - * "this Friday", "next Friday", "in 5 Fridays". - * @draft ICU 57 - */ - UDAT_REL_UNIT_FRIDAY, - /** - * Specifies that relative unit is Saturday, e.g. "last Saturday", - * "this Saturday", "next Saturday", "in 5 Saturdays". - * @draft ICU 57 - */ - UDAT_REL_UNIT_SATURDAY, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal URelativeDateTimeUnit value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UDAT_REL_UNIT_COUNT -#endif // U_HIDE_DEPRECATED_API -} URelativeDateTimeUnit; -#endif /* U_HIDE_DRAFT_API */ - -#ifndef U_HIDE_DRAFT_API - -/** - * Opaque URelativeDateTimeFormatter object for use in C programs. - * @draft ICU 57 - */ -struct URelativeDateTimeFormatter; -typedef struct URelativeDateTimeFormatter URelativeDateTimeFormatter; /**< C typedef for struct URelativeDateTimeFormatter. @draft ICU 57 */ - - -/** - * Open a new URelativeDateTimeFormatter object for a given locale using the - * specified width and capitalizationContext, along with a number formatter - * (if desired) to override the default formatter that would be used for - * display of numeric field offsets. The default formatter typically rounds - * toward 0 and has a minimum of 0 fraction digits and a maximum of 3 - * fraction digits (i.e. it will show as many decimal places as necessary - * up to 3, without showing trailing 0s). - * - * @param locale - * The locale - * @param nfToAdopt - * A number formatter to set for this URelativeDateTimeFormatter - * object (instead of the default decimal formatter). Ownership of - * this UNumberFormat object will pass to the URelativeDateTimeFormatter - * object (the URelativeDateTimeFormatter adopts the UNumberFormat), - * which becomes responsible for closing it. If the caller wishes to - * retain ownership of the UNumberFormat object, the caller must clone - * it (with unum_clone) and pass the clone to ureldatefmt_open. May be - * NULL to use the default decimal formatter. - * @param width - * The width - wide, short, narrow, etc. - * @param capitalizationContext - * A value from UDisplayContext that pertains to capitalization, e.g. - * UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE. - * @param status - * A pointer to a UErrorCode to receive any errors. - * @return - * A pointer to a URelativeDateTimeFormatter object for the specified locale, - * or NULL if an error occurred. - * @draft ICU 57 - */ -U_DRAFT URelativeDateTimeFormatter* U_EXPORT2 -ureldatefmt_open( const char* locale, - UNumberFormat* nfToAdopt, - UDateRelativeDateTimeFormatterStyle width, - UDisplayContext capitalizationContext, - UErrorCode* status ); - -/** - * Close a URelativeDateTimeFormatter object. Once closed it may no longer be used. - * @param reldatefmt - * The URelativeDateTimeFormatter object to close. - * @draft ICU 57 - */ -U_DRAFT void U_EXPORT2 -ureldatefmt_close(URelativeDateTimeFormatter *reldatefmt); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalURelativeDateTimeFormatterPointer - * "Smart pointer" class, closes a URelativeDateTimeFormatter via ureldatefmt_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @draft ICU 57 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalURelativeDateTimeFormatterPointer, URelativeDateTimeFormatter, ureldatefmt_close); - -U_NAMESPACE_END - -#endif - -/** - * Format a combination of URelativeDateTimeUnit and numeric - * offset using a numeric style, e.g. "1 week ago", "in 1 week", - * "5 weeks ago", "in 5 weeks". - * - * @param reldatefmt - * The URelativeDateTimeFormatter object specifying the - * format conventions. - * @param offset - * The signed offset for the specified unit. This will - * be formatted according to this object's UNumberFormat - * object. - * @param unit - * The unit to use when formatting the relative - * date, e.g. UDAT_REL_UNIT_WEEK, UDAT_REL_UNIT_FRIDAY. - * @param result - * A pointer to a buffer to receive the formatted result. - * @param resultCapacity - * The maximum size of result. - * @param status - * A pointer to a UErrorCode to receive any errors. In - * case of error status, the contents of result are - * undefined. - * @return - * The length of the formatted result; may be greater - * than resultCapacity, in which case an error is returned. - * @draft ICU 57 - */ -U_DRAFT int32_t U_EXPORT2 -ureldatefmt_formatNumeric( const URelativeDateTimeFormatter* reldatefmt, - double offset, - URelativeDateTimeUnit unit, - UChar* result, - int32_t resultCapacity, - UErrorCode* status); - -/** - * Format a combination of URelativeDateTimeUnit and numeric offset - * using a text style if possible, e.g. "last week", "this week", - * "next week", "yesterday", "tomorrow". Falls back to numeric - * style if no appropriate text term is available for the specified - * offset in the object's locale. - * - * @param reldatefmt - * The URelativeDateTimeFormatter object specifying the - * format conventions. - * @param offset - * The signed offset for the specified unit. - * @param unit - * The unit to use when formatting the relative - * date, e.g. UDAT_REL_UNIT_WEEK, UDAT_REL_UNIT_FRIDAY. - * @param result - * A pointer to a buffer to receive the formatted result. - * @param resultCapacity - * The maximum size of result. - * @param status - * A pointer to a UErrorCode to receive any errors. In - * case of error status, the contents of result are - * undefined. - * @return - * The length of the formatted result; may be greater - * than resultCapacity, in which case an error is returned. - * @draft ICU 57 - */ -U_DRAFT int32_t U_EXPORT2 -ureldatefmt_format( const URelativeDateTimeFormatter* reldatefmt, - double offset, - URelativeDateTimeUnit unit, - UChar* result, - int32_t resultCapacity, - UErrorCode* status); - -/** - * Combines a relative date string and a time string in this object's - * locale. This is done with the same date-time separator used for the - * default calendar in this locale to produce a result such as - * "yesterday at 3:45 PM". - * - * @param reldatefmt - * The URelativeDateTimeFormatter object specifying the format conventions. - * @param relativeDateString - * The relative date string. - * @param relativeDateStringLen - * The length of relativeDateString; may be -1 if relativeDateString - * is zero-terminated. - * @param timeString - * The time string. - * @param timeStringLen - * The length of timeString; may be -1 if timeString is zero-terminated. - * @param result - * A pointer to a buffer to receive the formatted result. - * @param resultCapacity - * The maximum size of result. - * @param status - * A pointer to a UErrorCode to receive any errors. In case of error status, - * the contents of result are undefined. - * @return - * The length of the formatted result; may be greater than resultCapacity, - * in which case an error is returned. - * @draft ICU 57 - */ -U_DRAFT int32_t U_EXPORT2 -ureldatefmt_combineDateAndTime( const URelativeDateTimeFormatter* reldatefmt, - const UChar * relativeDateString, - int32_t relativeDateStringLen, - const UChar * timeString, - int32_t timeStringLen, - UChar* result, - int32_t resultCapacity, - UErrorCode* status ); - -#endif /* U_HIDE_DRAFT_API */ - -#endif /* !UCONFIG_NO_FORMATTING && !UCONFIG_NO_BREAK_ITERATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/urename.h b/win32/include/spidermonkey/unicode/urename.h deleted file mode 100755 index b220a546..00000000 --- a/win32/include/spidermonkey/unicode/urename.h +++ /dev/null @@ -1,1818 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2002-2016, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* -* file name: urename.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* Created by: Perl script tools/genren.pl written by Vladimir Weinstein -* -* Contains data for renaming ICU exports. -* Gets included by umachine.h -* -* THIS FILE IS MACHINE-GENERATED, DON'T PLAY WITH IT IF YOU DON'T KNOW WHAT -* YOU ARE DOING, OTHERWISE VERY BAD THINGS WILL HAPPEN! -*/ - -#ifndef URENAME_H -#define URENAME_H - -/* U_DISABLE_RENAMING can be defined in the following ways: - * - when running configure, e.g. - * runConfigureICU Linux --disable-renaming - * - by changing the default setting of U_DISABLE_RENAMING in uconfig.h - */ - -#include "unicode/uconfig.h" - -#if !U_DISABLE_RENAMING - -/* We need the U_ICU_ENTRY_POINT_RENAME definition. There's a default one in unicode/uvernum.h we can use, but we will give - the platform a chance to define it first. - Normally (if utypes.h or umachine.h was included first) this will not be necessary as it will already be defined. - */ - -#ifndef U_ICU_ENTRY_POINT_RENAME -#include "unicode/umachine.h" -#endif - -/* If we still don't have U_ICU_ENTRY_POINT_RENAME use the default. */ -#ifndef U_ICU_ENTRY_POINT_RENAME -#include "unicode/uvernum.h" -#endif - -/* Error out before the following defines cause very strange and unexpected code breakage */ -#ifndef U_ICU_ENTRY_POINT_RENAME -#error U_ICU_ENTRY_POINT_RENAME is not defined - cannot continue. Consider defining U_DISABLE_RENAMING if renaming should not be used. -#endif - - -/* C exports renaming data */ - -#define T_CString_int64ToString U_ICU_ENTRY_POINT_RENAME(T_CString_int64ToString) -#define T_CString_integerToString U_ICU_ENTRY_POINT_RENAME(T_CString_integerToString) -#define T_CString_stringToInteger U_ICU_ENTRY_POINT_RENAME(T_CString_stringToInteger) -#define T_CString_toLowerCase U_ICU_ENTRY_POINT_RENAME(T_CString_toLowerCase) -#define T_CString_toUpperCase U_ICU_ENTRY_POINT_RENAME(T_CString_toUpperCase) -#define UCNV_FROM_U_CALLBACK_ESCAPE U_ICU_ENTRY_POINT_RENAME(UCNV_FROM_U_CALLBACK_ESCAPE) -#define UCNV_FROM_U_CALLBACK_SKIP U_ICU_ENTRY_POINT_RENAME(UCNV_FROM_U_CALLBACK_SKIP) -#define UCNV_FROM_U_CALLBACK_STOP U_ICU_ENTRY_POINT_RENAME(UCNV_FROM_U_CALLBACK_STOP) -#define UCNV_FROM_U_CALLBACK_SUBSTITUTE U_ICU_ENTRY_POINT_RENAME(UCNV_FROM_U_CALLBACK_SUBSTITUTE) -#define UCNV_TO_U_CALLBACK_ESCAPE U_ICU_ENTRY_POINT_RENAME(UCNV_TO_U_CALLBACK_ESCAPE) -#define UCNV_TO_U_CALLBACK_SKIP U_ICU_ENTRY_POINT_RENAME(UCNV_TO_U_CALLBACK_SKIP) -#define UCNV_TO_U_CALLBACK_STOP U_ICU_ENTRY_POINT_RENAME(UCNV_TO_U_CALLBACK_STOP) -#define UCNV_TO_U_CALLBACK_SUBSTITUTE U_ICU_ENTRY_POINT_RENAME(UCNV_TO_U_CALLBACK_SUBSTITUTE) -#define UDataMemory_createNewInstance U_ICU_ENTRY_POINT_RENAME(UDataMemory_createNewInstance) -#define UDataMemory_init U_ICU_ENTRY_POINT_RENAME(UDataMemory_init) -#define UDataMemory_isLoaded U_ICU_ENTRY_POINT_RENAME(UDataMemory_isLoaded) -#define UDataMemory_normalizeDataPointer U_ICU_ENTRY_POINT_RENAME(UDataMemory_normalizeDataPointer) -#define UDataMemory_setData U_ICU_ENTRY_POINT_RENAME(UDataMemory_setData) -#define UDatamemory_assign U_ICU_ENTRY_POINT_RENAME(UDatamemory_assign) -#define _ASCIIData U_ICU_ENTRY_POINT_RENAME(_ASCIIData) -#define _Bocu1Data U_ICU_ENTRY_POINT_RENAME(_Bocu1Data) -#define _CESU8Data U_ICU_ENTRY_POINT_RENAME(_CESU8Data) -#define _CompoundTextData U_ICU_ENTRY_POINT_RENAME(_CompoundTextData) -#define _HZData U_ICU_ENTRY_POINT_RENAME(_HZData) -#define _IMAPData U_ICU_ENTRY_POINT_RENAME(_IMAPData) -#define _ISCIIData U_ICU_ENTRY_POINT_RENAME(_ISCIIData) -#define _ISO2022Data U_ICU_ENTRY_POINT_RENAME(_ISO2022Data) -#define _LMBCSData1 U_ICU_ENTRY_POINT_RENAME(_LMBCSData1) -#define _LMBCSData11 U_ICU_ENTRY_POINT_RENAME(_LMBCSData11) -#define _LMBCSData16 U_ICU_ENTRY_POINT_RENAME(_LMBCSData16) -#define _LMBCSData17 U_ICU_ENTRY_POINT_RENAME(_LMBCSData17) -#define _LMBCSData18 U_ICU_ENTRY_POINT_RENAME(_LMBCSData18) -#define _LMBCSData19 U_ICU_ENTRY_POINT_RENAME(_LMBCSData19) -#define _LMBCSData2 U_ICU_ENTRY_POINT_RENAME(_LMBCSData2) -#define _LMBCSData3 U_ICU_ENTRY_POINT_RENAME(_LMBCSData3) -#define _LMBCSData4 U_ICU_ENTRY_POINT_RENAME(_LMBCSData4) -#define _LMBCSData5 U_ICU_ENTRY_POINT_RENAME(_LMBCSData5) -#define _LMBCSData6 U_ICU_ENTRY_POINT_RENAME(_LMBCSData6) -#define _LMBCSData8 U_ICU_ENTRY_POINT_RENAME(_LMBCSData8) -#define _Latin1Data U_ICU_ENTRY_POINT_RENAME(_Latin1Data) -#define _MBCSData U_ICU_ENTRY_POINT_RENAME(_MBCSData) -#define _SCSUData U_ICU_ENTRY_POINT_RENAME(_SCSUData) -#define _UTF16BEData U_ICU_ENTRY_POINT_RENAME(_UTF16BEData) -#define _UTF16Data U_ICU_ENTRY_POINT_RENAME(_UTF16Data) -#define _UTF16LEData U_ICU_ENTRY_POINT_RENAME(_UTF16LEData) -#define _UTF32BEData U_ICU_ENTRY_POINT_RENAME(_UTF32BEData) -#define _UTF32Data U_ICU_ENTRY_POINT_RENAME(_UTF32Data) -#define _UTF32LEData U_ICU_ENTRY_POINT_RENAME(_UTF32LEData) -#define _UTF7Data U_ICU_ENTRY_POINT_RENAME(_UTF7Data) -#define _UTF8Data U_ICU_ENTRY_POINT_RENAME(_UTF8Data) -#define cmemory_cleanup U_ICU_ENTRY_POINT_RENAME(cmemory_cleanup) -#define gTimeZoneFilesInitOnce U_ICU_ENTRY_POINT_RENAME(gTimeZoneFilesInitOnce) -#define izrule_clone U_ICU_ENTRY_POINT_RENAME(izrule_clone) -#define izrule_close U_ICU_ENTRY_POINT_RENAME(izrule_close) -#define izrule_equals U_ICU_ENTRY_POINT_RENAME(izrule_equals) -#define izrule_getDSTSavings U_ICU_ENTRY_POINT_RENAME(izrule_getDSTSavings) -#define izrule_getDynamicClassID U_ICU_ENTRY_POINT_RENAME(izrule_getDynamicClassID) -#define izrule_getFinalStart U_ICU_ENTRY_POINT_RENAME(izrule_getFinalStart) -#define izrule_getFirstStart U_ICU_ENTRY_POINT_RENAME(izrule_getFirstStart) -#define izrule_getName U_ICU_ENTRY_POINT_RENAME(izrule_getName) -#define izrule_getNextStart U_ICU_ENTRY_POINT_RENAME(izrule_getNextStart) -#define izrule_getPreviousStart U_ICU_ENTRY_POINT_RENAME(izrule_getPreviousStart) -#define izrule_getRawOffset U_ICU_ENTRY_POINT_RENAME(izrule_getRawOffset) -#define izrule_getStaticClassID U_ICU_ENTRY_POINT_RENAME(izrule_getStaticClassID) -#define izrule_isEquivalentTo U_ICU_ENTRY_POINT_RENAME(izrule_isEquivalentTo) -#define izrule_open U_ICU_ENTRY_POINT_RENAME(izrule_open) -#define le_close U_ICU_ENTRY_POINT_RENAME(le_close) -#define le_create U_ICU_ENTRY_POINT_RENAME(le_create) -#define le_getCharIndices U_ICU_ENTRY_POINT_RENAME(le_getCharIndices) -#define le_getCharIndicesWithBase U_ICU_ENTRY_POINT_RENAME(le_getCharIndicesWithBase) -#define le_getGlyphCount U_ICU_ENTRY_POINT_RENAME(le_getGlyphCount) -#define le_getGlyphPosition U_ICU_ENTRY_POINT_RENAME(le_getGlyphPosition) -#define le_getGlyphPositions U_ICU_ENTRY_POINT_RENAME(le_getGlyphPositions) -#define le_getGlyphs U_ICU_ENTRY_POINT_RENAME(le_getGlyphs) -#define le_layoutChars U_ICU_ENTRY_POINT_RENAME(le_layoutChars) -#define le_reset U_ICU_ENTRY_POINT_RENAME(le_reset) -#define locale_getKeywords U_ICU_ENTRY_POINT_RENAME(locale_getKeywords) -#define locale_getKeywordsStart U_ICU_ENTRY_POINT_RENAME(locale_getKeywordsStart) -#define locale_get_default U_ICU_ENTRY_POINT_RENAME(locale_get_default) -#define locale_set_default U_ICU_ENTRY_POINT_RENAME(locale_set_default) -#define pl_addFontRun U_ICU_ENTRY_POINT_RENAME(pl_addFontRun) -#define pl_addLocaleRun U_ICU_ENTRY_POINT_RENAME(pl_addLocaleRun) -#define pl_addValueRun U_ICU_ENTRY_POINT_RENAME(pl_addValueRun) -#define pl_close U_ICU_ENTRY_POINT_RENAME(pl_close) -#define pl_closeFontRuns U_ICU_ENTRY_POINT_RENAME(pl_closeFontRuns) -#define pl_closeLine U_ICU_ENTRY_POINT_RENAME(pl_closeLine) -#define pl_closeLocaleRuns U_ICU_ENTRY_POINT_RENAME(pl_closeLocaleRuns) -#define pl_closeValueRuns U_ICU_ENTRY_POINT_RENAME(pl_closeValueRuns) -#define pl_countLineRuns U_ICU_ENTRY_POINT_RENAME(pl_countLineRuns) -#define pl_create U_ICU_ENTRY_POINT_RENAME(pl_create) -#define pl_getAscent U_ICU_ENTRY_POINT_RENAME(pl_getAscent) -#define pl_getDescent U_ICU_ENTRY_POINT_RENAME(pl_getDescent) -#define pl_getFontRunCount U_ICU_ENTRY_POINT_RENAME(pl_getFontRunCount) -#define pl_getFontRunFont U_ICU_ENTRY_POINT_RENAME(pl_getFontRunFont) -#define pl_getFontRunLastLimit U_ICU_ENTRY_POINT_RENAME(pl_getFontRunLastLimit) -#define pl_getFontRunLimit U_ICU_ENTRY_POINT_RENAME(pl_getFontRunLimit) -#define pl_getLeading U_ICU_ENTRY_POINT_RENAME(pl_getLeading) -#define pl_getLineAscent U_ICU_ENTRY_POINT_RENAME(pl_getLineAscent) -#define pl_getLineDescent U_ICU_ENTRY_POINT_RENAME(pl_getLineDescent) -#define pl_getLineLeading U_ICU_ENTRY_POINT_RENAME(pl_getLineLeading) -#define pl_getLineVisualRun U_ICU_ENTRY_POINT_RENAME(pl_getLineVisualRun) -#define pl_getLineWidth U_ICU_ENTRY_POINT_RENAME(pl_getLineWidth) -#define pl_getLocaleRunCount U_ICU_ENTRY_POINT_RENAME(pl_getLocaleRunCount) -#define pl_getLocaleRunLastLimit U_ICU_ENTRY_POINT_RENAME(pl_getLocaleRunLastLimit) -#define pl_getLocaleRunLimit U_ICU_ENTRY_POINT_RENAME(pl_getLocaleRunLimit) -#define pl_getLocaleRunLocale U_ICU_ENTRY_POINT_RENAME(pl_getLocaleRunLocale) -#define pl_getParagraphLevel U_ICU_ENTRY_POINT_RENAME(pl_getParagraphLevel) -#define pl_getTextDirection U_ICU_ENTRY_POINT_RENAME(pl_getTextDirection) -#define pl_getValueRunCount U_ICU_ENTRY_POINT_RENAME(pl_getValueRunCount) -#define pl_getValueRunLastLimit U_ICU_ENTRY_POINT_RENAME(pl_getValueRunLastLimit) -#define pl_getValueRunLimit U_ICU_ENTRY_POINT_RENAME(pl_getValueRunLimit) -#define pl_getValueRunValue U_ICU_ENTRY_POINT_RENAME(pl_getValueRunValue) -#define pl_getVisualRunAscent U_ICU_ENTRY_POINT_RENAME(pl_getVisualRunAscent) -#define pl_getVisualRunDescent U_ICU_ENTRY_POINT_RENAME(pl_getVisualRunDescent) -#define pl_getVisualRunDirection U_ICU_ENTRY_POINT_RENAME(pl_getVisualRunDirection) -#define pl_getVisualRunFont U_ICU_ENTRY_POINT_RENAME(pl_getVisualRunFont) -#define pl_getVisualRunGlyphCount U_ICU_ENTRY_POINT_RENAME(pl_getVisualRunGlyphCount) -#define pl_getVisualRunGlyphToCharMap U_ICU_ENTRY_POINT_RENAME(pl_getVisualRunGlyphToCharMap) -#define pl_getVisualRunGlyphs U_ICU_ENTRY_POINT_RENAME(pl_getVisualRunGlyphs) -#define pl_getVisualRunLeading U_ICU_ENTRY_POINT_RENAME(pl_getVisualRunLeading) -#define pl_getVisualRunPositions U_ICU_ENTRY_POINT_RENAME(pl_getVisualRunPositions) -#define pl_isComplex U_ICU_ENTRY_POINT_RENAME(pl_isComplex) -#define pl_nextLine U_ICU_ENTRY_POINT_RENAME(pl_nextLine) -#define pl_openEmptyFontRuns U_ICU_ENTRY_POINT_RENAME(pl_openEmptyFontRuns) -#define pl_openEmptyLocaleRuns U_ICU_ENTRY_POINT_RENAME(pl_openEmptyLocaleRuns) -#define pl_openEmptyValueRuns U_ICU_ENTRY_POINT_RENAME(pl_openEmptyValueRuns) -#define pl_openFontRuns U_ICU_ENTRY_POINT_RENAME(pl_openFontRuns) -#define pl_openLocaleRuns U_ICU_ENTRY_POINT_RENAME(pl_openLocaleRuns) -#define pl_openValueRuns U_ICU_ENTRY_POINT_RENAME(pl_openValueRuns) -#define pl_reflow U_ICU_ENTRY_POINT_RENAME(pl_reflow) -#define pl_resetFontRuns U_ICU_ENTRY_POINT_RENAME(pl_resetFontRuns) -#define pl_resetLocaleRuns U_ICU_ENTRY_POINT_RENAME(pl_resetLocaleRuns) -#define pl_resetValueRuns U_ICU_ENTRY_POINT_RENAME(pl_resetValueRuns) -#define res_countArrayItems U_ICU_ENTRY_POINT_RENAME(res_countArrayItems) -#define res_findResource U_ICU_ENTRY_POINT_RENAME(res_findResource) -#define res_getAlias U_ICU_ENTRY_POINT_RENAME(res_getAlias) -#define res_getArrayItem U_ICU_ENTRY_POINT_RENAME(res_getArrayItem) -#define res_getBinary U_ICU_ENTRY_POINT_RENAME(res_getBinary) -#define res_getIntVector U_ICU_ENTRY_POINT_RENAME(res_getIntVector) -#define res_getPublicType U_ICU_ENTRY_POINT_RENAME(res_getPublicType) -#define res_getResource U_ICU_ENTRY_POINT_RENAME(res_getResource) -#define res_getString U_ICU_ENTRY_POINT_RENAME(res_getString) -#define res_getTableItemByIndex U_ICU_ENTRY_POINT_RENAME(res_getTableItemByIndex) -#define res_getTableItemByKey U_ICU_ENTRY_POINT_RENAME(res_getTableItemByKey) -#define res_load U_ICU_ENTRY_POINT_RENAME(res_load) -#define res_read U_ICU_ENTRY_POINT_RENAME(res_read) -#define res_unload U_ICU_ENTRY_POINT_RENAME(res_unload) -#define u_UCharsToChars U_ICU_ENTRY_POINT_RENAME(u_UCharsToChars) -#define u_austrcpy U_ICU_ENTRY_POINT_RENAME(u_austrcpy) -#define u_austrncpy U_ICU_ENTRY_POINT_RENAME(u_austrncpy) -#define u_caseInsensitivePrefixMatch U_ICU_ENTRY_POINT_RENAME(u_caseInsensitivePrefixMatch) -#define u_catclose U_ICU_ENTRY_POINT_RENAME(u_catclose) -#define u_catgets U_ICU_ENTRY_POINT_RENAME(u_catgets) -#define u_catopen U_ICU_ENTRY_POINT_RENAME(u_catopen) -#define u_charAge U_ICU_ENTRY_POINT_RENAME(u_charAge) -#define u_charDigitValue U_ICU_ENTRY_POINT_RENAME(u_charDigitValue) -#define u_charDirection U_ICU_ENTRY_POINT_RENAME(u_charDirection) -#define u_charFromName U_ICU_ENTRY_POINT_RENAME(u_charFromName) -#define u_charMirror U_ICU_ENTRY_POINT_RENAME(u_charMirror) -#define u_charName U_ICU_ENTRY_POINT_RENAME(u_charName) -#define u_charType U_ICU_ENTRY_POINT_RENAME(u_charType) -#define u_charsToUChars U_ICU_ENTRY_POINT_RENAME(u_charsToUChars) -#define u_cleanup U_ICU_ENTRY_POINT_RENAME(u_cleanup) -#define u_countChar32 U_ICU_ENTRY_POINT_RENAME(u_countChar32) -#define u_digit U_ICU_ENTRY_POINT_RENAME(u_digit) -#define u_enumCharNames U_ICU_ENTRY_POINT_RENAME(u_enumCharNames) -#define u_enumCharTypes U_ICU_ENTRY_POINT_RENAME(u_enumCharTypes) -#define u_errorName U_ICU_ENTRY_POINT_RENAME(u_errorName) -#define u_fadopt U_ICU_ENTRY_POINT_RENAME(u_fadopt) -#define u_fclose U_ICU_ENTRY_POINT_RENAME(u_fclose) -#define u_feof U_ICU_ENTRY_POINT_RENAME(u_feof) -#define u_fflush U_ICU_ENTRY_POINT_RENAME(u_fflush) -#define u_fgetConverter U_ICU_ENTRY_POINT_RENAME(u_fgetConverter) -#define u_fgetNumberFormat U_ICU_ENTRY_POINT_RENAME(u_fgetNumberFormat) -#define u_fgetc U_ICU_ENTRY_POINT_RENAME(u_fgetc) -#define u_fgetcodepage U_ICU_ENTRY_POINT_RENAME(u_fgetcodepage) -#define u_fgetcx U_ICU_ENTRY_POINT_RENAME(u_fgetcx) -#define u_fgetfile U_ICU_ENTRY_POINT_RENAME(u_fgetfile) -#define u_fgetlocale U_ICU_ENTRY_POINT_RENAME(u_fgetlocale) -#define u_fgets U_ICU_ENTRY_POINT_RENAME(u_fgets) -#define u_file_read U_ICU_ENTRY_POINT_RENAME(u_file_read) -#define u_file_write U_ICU_ENTRY_POINT_RENAME(u_file_write) -#define u_file_write_flush U_ICU_ENTRY_POINT_RENAME(u_file_write_flush) -#define u_finit U_ICU_ENTRY_POINT_RENAME(u_finit) -#define u_flushDefaultConverter U_ICU_ENTRY_POINT_RENAME(u_flushDefaultConverter) -#define u_foldCase U_ICU_ENTRY_POINT_RENAME(u_foldCase) -#define u_fopen U_ICU_ENTRY_POINT_RENAME(u_fopen) -#define u_fopen_u U_ICU_ENTRY_POINT_RENAME(u_fopen_u) -#define u_forDigit U_ICU_ENTRY_POINT_RENAME(u_forDigit) -#define u_formatMessage U_ICU_ENTRY_POINT_RENAME(u_formatMessage) -#define u_formatMessageWithError U_ICU_ENTRY_POINT_RENAME(u_formatMessageWithError) -#define u_fprintf U_ICU_ENTRY_POINT_RENAME(u_fprintf) -#define u_fprintf_u U_ICU_ENTRY_POINT_RENAME(u_fprintf_u) -#define u_fputc U_ICU_ENTRY_POINT_RENAME(u_fputc) -#define u_fputs U_ICU_ENTRY_POINT_RENAME(u_fputs) -#define u_frewind U_ICU_ENTRY_POINT_RENAME(u_frewind) -#define u_fscanf U_ICU_ENTRY_POINT_RENAME(u_fscanf) -#define u_fscanf_u U_ICU_ENTRY_POINT_RENAME(u_fscanf_u) -#define u_fsetcodepage U_ICU_ENTRY_POINT_RENAME(u_fsetcodepage) -#define u_fsetlocale U_ICU_ENTRY_POINT_RENAME(u_fsetlocale) -#define u_fsettransliterator U_ICU_ENTRY_POINT_RENAME(u_fsettransliterator) -#define u_fstropen U_ICU_ENTRY_POINT_RENAME(u_fstropen) -#define u_fungetc U_ICU_ENTRY_POINT_RENAME(u_fungetc) -#define u_getBidiPairedBracket U_ICU_ENTRY_POINT_RENAME(u_getBidiPairedBracket) -#define u_getCombiningClass U_ICU_ENTRY_POINT_RENAME(u_getCombiningClass) -#define u_getDataDirectory U_ICU_ENTRY_POINT_RENAME(u_getDataDirectory) -#define u_getDataVersion U_ICU_ENTRY_POINT_RENAME(u_getDataVersion) -#define u_getDefaultConverter U_ICU_ENTRY_POINT_RENAME(u_getDefaultConverter) -#define u_getFC_NFKC_Closure U_ICU_ENTRY_POINT_RENAME(u_getFC_NFKC_Closure) -#define u_getISOComment U_ICU_ENTRY_POINT_RENAME(u_getISOComment) -#define u_getIntPropertyMaxValue U_ICU_ENTRY_POINT_RENAME(u_getIntPropertyMaxValue) -#define u_getIntPropertyMinValue U_ICU_ENTRY_POINT_RENAME(u_getIntPropertyMinValue) -#define u_getIntPropertyValue U_ICU_ENTRY_POINT_RENAME(u_getIntPropertyValue) -#define u_getMainProperties U_ICU_ENTRY_POINT_RENAME(u_getMainProperties) -#define u_getNumericValue U_ICU_ENTRY_POINT_RENAME(u_getNumericValue) -#define u_getPropertyEnum U_ICU_ENTRY_POINT_RENAME(u_getPropertyEnum) -#define u_getPropertyName U_ICU_ENTRY_POINT_RENAME(u_getPropertyName) -#define u_getPropertyValueEnum U_ICU_ENTRY_POINT_RENAME(u_getPropertyValueEnum) -#define u_getPropertyValueName U_ICU_ENTRY_POINT_RENAME(u_getPropertyValueName) -#define u_getTimeZoneFilesDirectory U_ICU_ENTRY_POINT_RENAME(u_getTimeZoneFilesDirectory) -#define u_getUnicodeProperties U_ICU_ENTRY_POINT_RENAME(u_getUnicodeProperties) -#define u_getUnicodeVersion U_ICU_ENTRY_POINT_RENAME(u_getUnicodeVersion) -#define u_getVersion U_ICU_ENTRY_POINT_RENAME(u_getVersion) -#define u_get_stdout U_ICU_ENTRY_POINT_RENAME(u_get_stdout) -#define u_hasBinaryProperty U_ICU_ENTRY_POINT_RENAME(u_hasBinaryProperty) -#define u_init U_ICU_ENTRY_POINT_RENAME(u_init) -#define u_isIDIgnorable U_ICU_ENTRY_POINT_RENAME(u_isIDIgnorable) -#define u_isIDPart U_ICU_ENTRY_POINT_RENAME(u_isIDPart) -#define u_isIDStart U_ICU_ENTRY_POINT_RENAME(u_isIDStart) -#define u_isISOControl U_ICU_ENTRY_POINT_RENAME(u_isISOControl) -#define u_isJavaIDPart U_ICU_ENTRY_POINT_RENAME(u_isJavaIDPart) -#define u_isJavaIDStart U_ICU_ENTRY_POINT_RENAME(u_isJavaIDStart) -#define u_isJavaSpaceChar U_ICU_ENTRY_POINT_RENAME(u_isJavaSpaceChar) -#define u_isMirrored U_ICU_ENTRY_POINT_RENAME(u_isMirrored) -#define u_isUAlphabetic U_ICU_ENTRY_POINT_RENAME(u_isUAlphabetic) -#define u_isULowercase U_ICU_ENTRY_POINT_RENAME(u_isULowercase) -#define u_isUUppercase U_ICU_ENTRY_POINT_RENAME(u_isUUppercase) -#define u_isUWhiteSpace U_ICU_ENTRY_POINT_RENAME(u_isUWhiteSpace) -#define u_isWhitespace U_ICU_ENTRY_POINT_RENAME(u_isWhitespace) -#define u_isalnum U_ICU_ENTRY_POINT_RENAME(u_isalnum) -#define u_isalnumPOSIX U_ICU_ENTRY_POINT_RENAME(u_isalnumPOSIX) -#define u_isalpha U_ICU_ENTRY_POINT_RENAME(u_isalpha) -#define u_isbase U_ICU_ENTRY_POINT_RENAME(u_isbase) -#define u_isblank U_ICU_ENTRY_POINT_RENAME(u_isblank) -#define u_iscntrl U_ICU_ENTRY_POINT_RENAME(u_iscntrl) -#define u_isdefined U_ICU_ENTRY_POINT_RENAME(u_isdefined) -#define u_isdigit U_ICU_ENTRY_POINT_RENAME(u_isdigit) -#define u_isgraph U_ICU_ENTRY_POINT_RENAME(u_isgraph) -#define u_isgraphPOSIX U_ICU_ENTRY_POINT_RENAME(u_isgraphPOSIX) -#define u_islower U_ICU_ENTRY_POINT_RENAME(u_islower) -#define u_isprint U_ICU_ENTRY_POINT_RENAME(u_isprint) -#define u_isprintPOSIX U_ICU_ENTRY_POINT_RENAME(u_isprintPOSIX) -#define u_ispunct U_ICU_ENTRY_POINT_RENAME(u_ispunct) -#define u_isspace U_ICU_ENTRY_POINT_RENAME(u_isspace) -#define u_istitle U_ICU_ENTRY_POINT_RENAME(u_istitle) -#define u_isupper U_ICU_ENTRY_POINT_RENAME(u_isupper) -#define u_isxdigit U_ICU_ENTRY_POINT_RENAME(u_isxdigit) -#define u_locbund_close U_ICU_ENTRY_POINT_RENAME(u_locbund_close) -#define u_locbund_getNumberFormat U_ICU_ENTRY_POINT_RENAME(u_locbund_getNumberFormat) -#define u_locbund_init U_ICU_ENTRY_POINT_RENAME(u_locbund_init) -#define u_memcasecmp U_ICU_ENTRY_POINT_RENAME(u_memcasecmp) -#define u_memchr U_ICU_ENTRY_POINT_RENAME(u_memchr) -#define u_memchr32 U_ICU_ENTRY_POINT_RENAME(u_memchr32) -#define u_memcmp U_ICU_ENTRY_POINT_RENAME(u_memcmp) -#define u_memcmpCodePointOrder U_ICU_ENTRY_POINT_RENAME(u_memcmpCodePointOrder) -#define u_memcpy U_ICU_ENTRY_POINT_RENAME(u_memcpy) -#define u_memmove U_ICU_ENTRY_POINT_RENAME(u_memmove) -#define u_memrchr U_ICU_ENTRY_POINT_RENAME(u_memrchr) -#define u_memrchr32 U_ICU_ENTRY_POINT_RENAME(u_memrchr32) -#define u_memset U_ICU_ENTRY_POINT_RENAME(u_memset) -#define u_parseMessage U_ICU_ENTRY_POINT_RENAME(u_parseMessage) -#define u_parseMessageWithError U_ICU_ENTRY_POINT_RENAME(u_parseMessageWithError) -#define u_printf U_ICU_ENTRY_POINT_RENAME(u_printf) -#define u_printf_parse U_ICU_ENTRY_POINT_RENAME(u_printf_parse) -#define u_printf_u U_ICU_ENTRY_POINT_RENAME(u_printf_u) -#define u_releaseDefaultConverter U_ICU_ENTRY_POINT_RENAME(u_releaseDefaultConverter) -#define u_scanf_parse U_ICU_ENTRY_POINT_RENAME(u_scanf_parse) -#define u_setAtomicIncDecFunctions U_ICU_ENTRY_POINT_RENAME(u_setAtomicIncDecFunctions) -#define u_setDataDirectory U_ICU_ENTRY_POINT_RENAME(u_setDataDirectory) -#define u_setMemoryFunctions U_ICU_ENTRY_POINT_RENAME(u_setMemoryFunctions) -#define u_setMutexFunctions U_ICU_ENTRY_POINT_RENAME(u_setMutexFunctions) -#define u_setTimeZoneFilesDirectory U_ICU_ENTRY_POINT_RENAME(u_setTimeZoneFilesDirectory) -#define u_shapeArabic U_ICU_ENTRY_POINT_RENAME(u_shapeArabic) -#define u_snprintf U_ICU_ENTRY_POINT_RENAME(u_snprintf) -#define u_snprintf_u U_ICU_ENTRY_POINT_RENAME(u_snprintf_u) -#define u_sprintf U_ICU_ENTRY_POINT_RENAME(u_sprintf) -#define u_sprintf_u U_ICU_ENTRY_POINT_RENAME(u_sprintf_u) -#define u_sscanf U_ICU_ENTRY_POINT_RENAME(u_sscanf) -#define u_sscanf_u U_ICU_ENTRY_POINT_RENAME(u_sscanf_u) -#define u_strCaseCompare U_ICU_ENTRY_POINT_RENAME(u_strCaseCompare) -#define u_strCompare U_ICU_ENTRY_POINT_RENAME(u_strCompare) -#define u_strCompareIter U_ICU_ENTRY_POINT_RENAME(u_strCompareIter) -#define u_strFindFirst U_ICU_ENTRY_POINT_RENAME(u_strFindFirst) -#define u_strFindLast U_ICU_ENTRY_POINT_RENAME(u_strFindLast) -#define u_strFoldCase U_ICU_ENTRY_POINT_RENAME(u_strFoldCase) -#define u_strFromJavaModifiedUTF8WithSub U_ICU_ENTRY_POINT_RENAME(u_strFromJavaModifiedUTF8WithSub) -#define u_strFromPunycode U_ICU_ENTRY_POINT_RENAME(u_strFromPunycode) -#define u_strFromUTF32 U_ICU_ENTRY_POINT_RENAME(u_strFromUTF32) -#define u_strFromUTF32WithSub U_ICU_ENTRY_POINT_RENAME(u_strFromUTF32WithSub) -#define u_strFromUTF8 U_ICU_ENTRY_POINT_RENAME(u_strFromUTF8) -#define u_strFromUTF8Lenient U_ICU_ENTRY_POINT_RENAME(u_strFromUTF8Lenient) -#define u_strFromUTF8WithSub U_ICU_ENTRY_POINT_RENAME(u_strFromUTF8WithSub) -#define u_strFromWCS U_ICU_ENTRY_POINT_RENAME(u_strFromWCS) -#define u_strHasMoreChar32Than U_ICU_ENTRY_POINT_RENAME(u_strHasMoreChar32Than) -#define u_strToJavaModifiedUTF8 U_ICU_ENTRY_POINT_RENAME(u_strToJavaModifiedUTF8) -#define u_strToLower U_ICU_ENTRY_POINT_RENAME(u_strToLower) -#define u_strToPunycode U_ICU_ENTRY_POINT_RENAME(u_strToPunycode) -#define u_strToTitle U_ICU_ENTRY_POINT_RENAME(u_strToTitle) -#define u_strToUTF32 U_ICU_ENTRY_POINT_RENAME(u_strToUTF32) -#define u_strToUTF32WithSub U_ICU_ENTRY_POINT_RENAME(u_strToUTF32WithSub) -#define u_strToUTF8 U_ICU_ENTRY_POINT_RENAME(u_strToUTF8) -#define u_strToUTF8WithSub U_ICU_ENTRY_POINT_RENAME(u_strToUTF8WithSub) -#define u_strToUpper U_ICU_ENTRY_POINT_RENAME(u_strToUpper) -#define u_strToWCS U_ICU_ENTRY_POINT_RENAME(u_strToWCS) -#define u_strcasecmp U_ICU_ENTRY_POINT_RENAME(u_strcasecmp) -#define u_strcat U_ICU_ENTRY_POINT_RENAME(u_strcat) -#define u_strchr U_ICU_ENTRY_POINT_RENAME(u_strchr) -#define u_strchr32 U_ICU_ENTRY_POINT_RENAME(u_strchr32) -#define u_strcmp U_ICU_ENTRY_POINT_RENAME(u_strcmp) -#define u_strcmpCodePointOrder U_ICU_ENTRY_POINT_RENAME(u_strcmpCodePointOrder) -#define u_strcmpFold U_ICU_ENTRY_POINT_RENAME(u_strcmpFold) -#define u_strcpy U_ICU_ENTRY_POINT_RENAME(u_strcpy) -#define u_strcspn U_ICU_ENTRY_POINT_RENAME(u_strcspn) -#define u_strlen U_ICU_ENTRY_POINT_RENAME(u_strlen) -#define u_strncasecmp U_ICU_ENTRY_POINT_RENAME(u_strncasecmp) -#define u_strncat U_ICU_ENTRY_POINT_RENAME(u_strncat) -#define u_strncmp U_ICU_ENTRY_POINT_RENAME(u_strncmp) -#define u_strncmpCodePointOrder U_ICU_ENTRY_POINT_RENAME(u_strncmpCodePointOrder) -#define u_strncpy U_ICU_ENTRY_POINT_RENAME(u_strncpy) -#define u_strpbrk U_ICU_ENTRY_POINT_RENAME(u_strpbrk) -#define u_strrchr U_ICU_ENTRY_POINT_RENAME(u_strrchr) -#define u_strrchr32 U_ICU_ENTRY_POINT_RENAME(u_strrchr32) -#define u_strrstr U_ICU_ENTRY_POINT_RENAME(u_strrstr) -#define u_strspn U_ICU_ENTRY_POINT_RENAME(u_strspn) -#define u_strstr U_ICU_ENTRY_POINT_RENAME(u_strstr) -#define u_strtok_r U_ICU_ENTRY_POINT_RENAME(u_strtok_r) -#define u_terminateChars U_ICU_ENTRY_POINT_RENAME(u_terminateChars) -#define u_terminateUChar32s U_ICU_ENTRY_POINT_RENAME(u_terminateUChar32s) -#define u_terminateUChars U_ICU_ENTRY_POINT_RENAME(u_terminateUChars) -#define u_terminateWChars U_ICU_ENTRY_POINT_RENAME(u_terminateWChars) -#define u_tolower U_ICU_ENTRY_POINT_RENAME(u_tolower) -#define u_totitle U_ICU_ENTRY_POINT_RENAME(u_totitle) -#define u_toupper U_ICU_ENTRY_POINT_RENAME(u_toupper) -#define u_uastrcpy U_ICU_ENTRY_POINT_RENAME(u_uastrcpy) -#define u_uastrncpy U_ICU_ENTRY_POINT_RENAME(u_uastrncpy) -#define u_unescape U_ICU_ENTRY_POINT_RENAME(u_unescape) -#define u_unescapeAt U_ICU_ENTRY_POINT_RENAME(u_unescapeAt) -#define u_versionFromString U_ICU_ENTRY_POINT_RENAME(u_versionFromString) -#define u_versionFromUString U_ICU_ENTRY_POINT_RENAME(u_versionFromUString) -#define u_versionToString U_ICU_ENTRY_POINT_RENAME(u_versionToString) -#define u_vformatMessage U_ICU_ENTRY_POINT_RENAME(u_vformatMessage) -#define u_vformatMessageWithError U_ICU_ENTRY_POINT_RENAME(u_vformatMessageWithError) -#define u_vfprintf U_ICU_ENTRY_POINT_RENAME(u_vfprintf) -#define u_vfprintf_u U_ICU_ENTRY_POINT_RENAME(u_vfprintf_u) -#define u_vfscanf U_ICU_ENTRY_POINT_RENAME(u_vfscanf) -#define u_vfscanf_u U_ICU_ENTRY_POINT_RENAME(u_vfscanf_u) -#define u_vparseMessage U_ICU_ENTRY_POINT_RENAME(u_vparseMessage) -#define u_vparseMessageWithError U_ICU_ENTRY_POINT_RENAME(u_vparseMessageWithError) -#define u_vsnprintf U_ICU_ENTRY_POINT_RENAME(u_vsnprintf) -#define u_vsnprintf_u U_ICU_ENTRY_POINT_RENAME(u_vsnprintf_u) -#define u_vsprintf U_ICU_ENTRY_POINT_RENAME(u_vsprintf) -#define u_vsprintf_u U_ICU_ENTRY_POINT_RENAME(u_vsprintf_u) -#define u_vsscanf U_ICU_ENTRY_POINT_RENAME(u_vsscanf) -#define u_vsscanf_u U_ICU_ENTRY_POINT_RENAME(u_vsscanf_u) -#define u_writeIdenticalLevelRun U_ICU_ENTRY_POINT_RENAME(u_writeIdenticalLevelRun) -#define ubidi_addPropertyStarts U_ICU_ENTRY_POINT_RENAME(ubidi_addPropertyStarts) -#define ubidi_close U_ICU_ENTRY_POINT_RENAME(ubidi_close) -#define ubidi_countParagraphs U_ICU_ENTRY_POINT_RENAME(ubidi_countParagraphs) -#define ubidi_countRuns U_ICU_ENTRY_POINT_RENAME(ubidi_countRuns) -#define ubidi_getBaseDirection U_ICU_ENTRY_POINT_RENAME(ubidi_getBaseDirection) -#define ubidi_getClass U_ICU_ENTRY_POINT_RENAME(ubidi_getClass) -#define ubidi_getClassCallback U_ICU_ENTRY_POINT_RENAME(ubidi_getClassCallback) -#define ubidi_getCustomizedClass U_ICU_ENTRY_POINT_RENAME(ubidi_getCustomizedClass) -#define ubidi_getDirection U_ICU_ENTRY_POINT_RENAME(ubidi_getDirection) -#define ubidi_getJoiningGroup U_ICU_ENTRY_POINT_RENAME(ubidi_getJoiningGroup) -#define ubidi_getJoiningType U_ICU_ENTRY_POINT_RENAME(ubidi_getJoiningType) -#define ubidi_getLength U_ICU_ENTRY_POINT_RENAME(ubidi_getLength) -#define ubidi_getLevelAt U_ICU_ENTRY_POINT_RENAME(ubidi_getLevelAt) -#define ubidi_getLevels U_ICU_ENTRY_POINT_RENAME(ubidi_getLevels) -#define ubidi_getLogicalIndex U_ICU_ENTRY_POINT_RENAME(ubidi_getLogicalIndex) -#define ubidi_getLogicalMap U_ICU_ENTRY_POINT_RENAME(ubidi_getLogicalMap) -#define ubidi_getLogicalRun U_ICU_ENTRY_POINT_RENAME(ubidi_getLogicalRun) -#define ubidi_getMaxValue U_ICU_ENTRY_POINT_RENAME(ubidi_getMaxValue) -#define ubidi_getMemory U_ICU_ENTRY_POINT_RENAME(ubidi_getMemory) -#define ubidi_getMirror U_ICU_ENTRY_POINT_RENAME(ubidi_getMirror) -#define ubidi_getPairedBracket U_ICU_ENTRY_POINT_RENAME(ubidi_getPairedBracket) -#define ubidi_getPairedBracketType U_ICU_ENTRY_POINT_RENAME(ubidi_getPairedBracketType) -#define ubidi_getParaLevel U_ICU_ENTRY_POINT_RENAME(ubidi_getParaLevel) -#define ubidi_getParaLevelAtIndex U_ICU_ENTRY_POINT_RENAME(ubidi_getParaLevelAtIndex) -#define ubidi_getParagraph U_ICU_ENTRY_POINT_RENAME(ubidi_getParagraph) -#define ubidi_getParagraphByIndex U_ICU_ENTRY_POINT_RENAME(ubidi_getParagraphByIndex) -#define ubidi_getProcessedLength U_ICU_ENTRY_POINT_RENAME(ubidi_getProcessedLength) -#define ubidi_getReorderingMode U_ICU_ENTRY_POINT_RENAME(ubidi_getReorderingMode) -#define ubidi_getReorderingOptions U_ICU_ENTRY_POINT_RENAME(ubidi_getReorderingOptions) -#define ubidi_getResultLength U_ICU_ENTRY_POINT_RENAME(ubidi_getResultLength) -#define ubidi_getRuns U_ICU_ENTRY_POINT_RENAME(ubidi_getRuns) -#define ubidi_getSingleton U_ICU_ENTRY_POINT_RENAME(ubidi_getSingleton) -#define ubidi_getText U_ICU_ENTRY_POINT_RENAME(ubidi_getText) -#define ubidi_getVisualIndex U_ICU_ENTRY_POINT_RENAME(ubidi_getVisualIndex) -#define ubidi_getVisualMap U_ICU_ENTRY_POINT_RENAME(ubidi_getVisualMap) -#define ubidi_getVisualRun U_ICU_ENTRY_POINT_RENAME(ubidi_getVisualRun) -#define ubidi_invertMap U_ICU_ENTRY_POINT_RENAME(ubidi_invertMap) -#define ubidi_isBidiControl U_ICU_ENTRY_POINT_RENAME(ubidi_isBidiControl) -#define ubidi_isInverse U_ICU_ENTRY_POINT_RENAME(ubidi_isInverse) -#define ubidi_isJoinControl U_ICU_ENTRY_POINT_RENAME(ubidi_isJoinControl) -#define ubidi_isMirrored U_ICU_ENTRY_POINT_RENAME(ubidi_isMirrored) -#define ubidi_isOrderParagraphsLTR U_ICU_ENTRY_POINT_RENAME(ubidi_isOrderParagraphsLTR) -#define ubidi_open U_ICU_ENTRY_POINT_RENAME(ubidi_open) -#define ubidi_openSized U_ICU_ENTRY_POINT_RENAME(ubidi_openSized) -#define ubidi_orderParagraphsLTR U_ICU_ENTRY_POINT_RENAME(ubidi_orderParagraphsLTR) -#define ubidi_reorderLogical U_ICU_ENTRY_POINT_RENAME(ubidi_reorderLogical) -#define ubidi_reorderVisual U_ICU_ENTRY_POINT_RENAME(ubidi_reorderVisual) -#define ubidi_setClassCallback U_ICU_ENTRY_POINT_RENAME(ubidi_setClassCallback) -#define ubidi_setContext U_ICU_ENTRY_POINT_RENAME(ubidi_setContext) -#define ubidi_setInverse U_ICU_ENTRY_POINT_RENAME(ubidi_setInverse) -#define ubidi_setLine U_ICU_ENTRY_POINT_RENAME(ubidi_setLine) -#define ubidi_setPara U_ICU_ENTRY_POINT_RENAME(ubidi_setPara) -#define ubidi_setReorderingMode U_ICU_ENTRY_POINT_RENAME(ubidi_setReorderingMode) -#define ubidi_setReorderingOptions U_ICU_ENTRY_POINT_RENAME(ubidi_setReorderingOptions) -#define ubidi_writeReordered U_ICU_ENTRY_POINT_RENAME(ubidi_writeReordered) -#define ubidi_writeReverse U_ICU_ENTRY_POINT_RENAME(ubidi_writeReverse) -#define ubiditransform_close U_ICU_ENTRY_POINT_RENAME(ubiditransform_close) -#define ubiditransform_open U_ICU_ENTRY_POINT_RENAME(ubiditransform_open) -#define ubiditransform_transform U_ICU_ENTRY_POINT_RENAME(ubiditransform_transform) -#define ublock_getCode U_ICU_ENTRY_POINT_RENAME(ublock_getCode) -#define ubrk_close U_ICU_ENTRY_POINT_RENAME(ubrk_close) -#define ubrk_countAvailable U_ICU_ENTRY_POINT_RENAME(ubrk_countAvailable) -#define ubrk_current U_ICU_ENTRY_POINT_RENAME(ubrk_current) -#define ubrk_first U_ICU_ENTRY_POINT_RENAME(ubrk_first) -#define ubrk_following U_ICU_ENTRY_POINT_RENAME(ubrk_following) -#define ubrk_getAvailable U_ICU_ENTRY_POINT_RENAME(ubrk_getAvailable) -#define ubrk_getLocaleByType U_ICU_ENTRY_POINT_RENAME(ubrk_getLocaleByType) -#define ubrk_getRuleStatus U_ICU_ENTRY_POINT_RENAME(ubrk_getRuleStatus) -#define ubrk_getRuleStatusVec U_ICU_ENTRY_POINT_RENAME(ubrk_getRuleStatusVec) -#define ubrk_isBoundary U_ICU_ENTRY_POINT_RENAME(ubrk_isBoundary) -#define ubrk_last U_ICU_ENTRY_POINT_RENAME(ubrk_last) -#define ubrk_next U_ICU_ENTRY_POINT_RENAME(ubrk_next) -#define ubrk_open U_ICU_ENTRY_POINT_RENAME(ubrk_open) -#define ubrk_openRules U_ICU_ENTRY_POINT_RENAME(ubrk_openRules) -#define ubrk_preceding U_ICU_ENTRY_POINT_RENAME(ubrk_preceding) -#define ubrk_previous U_ICU_ENTRY_POINT_RENAME(ubrk_previous) -#define ubrk_refreshUText U_ICU_ENTRY_POINT_RENAME(ubrk_refreshUText) -#define ubrk_safeClone U_ICU_ENTRY_POINT_RENAME(ubrk_safeClone) -#define ubrk_setText U_ICU_ENTRY_POINT_RENAME(ubrk_setText) -#define ubrk_setUText U_ICU_ENTRY_POINT_RENAME(ubrk_setUText) -#define ubrk_swap U_ICU_ENTRY_POINT_RENAME(ubrk_swap) -#define ucache_compareKeys U_ICU_ENTRY_POINT_RENAME(ucache_compareKeys) -#define ucache_deleteKey U_ICU_ENTRY_POINT_RENAME(ucache_deleteKey) -#define ucache_hashKeys U_ICU_ENTRY_POINT_RENAME(ucache_hashKeys) -#define ucal_add U_ICU_ENTRY_POINT_RENAME(ucal_add) -#define ucal_clear U_ICU_ENTRY_POINT_RENAME(ucal_clear) -#define ucal_clearField U_ICU_ENTRY_POINT_RENAME(ucal_clearField) -#define ucal_clone U_ICU_ENTRY_POINT_RENAME(ucal_clone) -#define ucal_close U_ICU_ENTRY_POINT_RENAME(ucal_close) -#define ucal_countAvailable U_ICU_ENTRY_POINT_RENAME(ucal_countAvailable) -#define ucal_equivalentTo U_ICU_ENTRY_POINT_RENAME(ucal_equivalentTo) -#define ucal_get U_ICU_ENTRY_POINT_RENAME(ucal_get) -#define ucal_getAttribute U_ICU_ENTRY_POINT_RENAME(ucal_getAttribute) -#define ucal_getAvailable U_ICU_ENTRY_POINT_RENAME(ucal_getAvailable) -#define ucal_getCanonicalTimeZoneID U_ICU_ENTRY_POINT_RENAME(ucal_getCanonicalTimeZoneID) -#define ucal_getDSTSavings U_ICU_ENTRY_POINT_RENAME(ucal_getDSTSavings) -#define ucal_getDayOfWeekType U_ICU_ENTRY_POINT_RENAME(ucal_getDayOfWeekType) -#define ucal_getDefaultTimeZone U_ICU_ENTRY_POINT_RENAME(ucal_getDefaultTimeZone) -#define ucal_getFieldDifference U_ICU_ENTRY_POINT_RENAME(ucal_getFieldDifference) -#define ucal_getGregorianChange U_ICU_ENTRY_POINT_RENAME(ucal_getGregorianChange) -#define ucal_getKeywordValuesForLocale U_ICU_ENTRY_POINT_RENAME(ucal_getKeywordValuesForLocale) -#define ucal_getLimit U_ICU_ENTRY_POINT_RENAME(ucal_getLimit) -#define ucal_getLocaleByType U_ICU_ENTRY_POINT_RENAME(ucal_getLocaleByType) -#define ucal_getMillis U_ICU_ENTRY_POINT_RENAME(ucal_getMillis) -#define ucal_getNow U_ICU_ENTRY_POINT_RENAME(ucal_getNow) -#define ucal_getTZDataVersion U_ICU_ENTRY_POINT_RENAME(ucal_getTZDataVersion) -#define ucal_getTimeZoneDisplayName U_ICU_ENTRY_POINT_RENAME(ucal_getTimeZoneDisplayName) -#define ucal_getTimeZoneID U_ICU_ENTRY_POINT_RENAME(ucal_getTimeZoneID) -#define ucal_getTimeZoneIDForWindowsID U_ICU_ENTRY_POINT_RENAME(ucal_getTimeZoneIDForWindowsID) -#define ucal_getTimeZoneTransitionDate U_ICU_ENTRY_POINT_RENAME(ucal_getTimeZoneTransitionDate) -#define ucal_getType U_ICU_ENTRY_POINT_RENAME(ucal_getType) -#define ucal_getWeekendTransition U_ICU_ENTRY_POINT_RENAME(ucal_getWeekendTransition) -#define ucal_getWindowsTimeZoneID U_ICU_ENTRY_POINT_RENAME(ucal_getWindowsTimeZoneID) -#define ucal_inDaylightTime U_ICU_ENTRY_POINT_RENAME(ucal_inDaylightTime) -#define ucal_isSet U_ICU_ENTRY_POINT_RENAME(ucal_isSet) -#define ucal_isWeekend U_ICU_ENTRY_POINT_RENAME(ucal_isWeekend) -#define ucal_open U_ICU_ENTRY_POINT_RENAME(ucal_open) -#define ucal_openCountryTimeZones U_ICU_ENTRY_POINT_RENAME(ucal_openCountryTimeZones) -#define ucal_openTimeZoneIDEnumeration U_ICU_ENTRY_POINT_RENAME(ucal_openTimeZoneIDEnumeration) -#define ucal_openTimeZones U_ICU_ENTRY_POINT_RENAME(ucal_openTimeZones) -#define ucal_roll U_ICU_ENTRY_POINT_RENAME(ucal_roll) -#define ucal_set U_ICU_ENTRY_POINT_RENAME(ucal_set) -#define ucal_setAttribute U_ICU_ENTRY_POINT_RENAME(ucal_setAttribute) -#define ucal_setDate U_ICU_ENTRY_POINT_RENAME(ucal_setDate) -#define ucal_setDateTime U_ICU_ENTRY_POINT_RENAME(ucal_setDateTime) -#define ucal_setDefaultTimeZone U_ICU_ENTRY_POINT_RENAME(ucal_setDefaultTimeZone) -#define ucal_setGregorianChange U_ICU_ENTRY_POINT_RENAME(ucal_setGregorianChange) -#define ucal_setMillis U_ICU_ENTRY_POINT_RENAME(ucal_setMillis) -#define ucal_setTimeZone U_ICU_ENTRY_POINT_RENAME(ucal_setTimeZone) -#define ucase_addCaseClosure U_ICU_ENTRY_POINT_RENAME(ucase_addCaseClosure) -#define ucase_addPropertyStarts U_ICU_ENTRY_POINT_RENAME(ucase_addPropertyStarts) -#define ucase_addStringCaseClosure U_ICU_ENTRY_POINT_RENAME(ucase_addStringCaseClosure) -#define ucase_fold U_ICU_ENTRY_POINT_RENAME(ucase_fold) -#define ucase_getCaseLocale U_ICU_ENTRY_POINT_RENAME(ucase_getCaseLocale) -#define ucase_getSingleton U_ICU_ENTRY_POINT_RENAME(ucase_getSingleton) -#define ucase_getType U_ICU_ENTRY_POINT_RENAME(ucase_getType) -#define ucase_getTypeOrIgnorable U_ICU_ENTRY_POINT_RENAME(ucase_getTypeOrIgnorable) -#define ucase_hasBinaryProperty U_ICU_ENTRY_POINT_RENAME(ucase_hasBinaryProperty) -#define ucase_isCaseSensitive U_ICU_ENTRY_POINT_RENAME(ucase_isCaseSensitive) -#define ucase_isSoftDotted U_ICU_ENTRY_POINT_RENAME(ucase_isSoftDotted) -#define ucase_toFullFolding U_ICU_ENTRY_POINT_RENAME(ucase_toFullFolding) -#define ucase_toFullLower U_ICU_ENTRY_POINT_RENAME(ucase_toFullLower) -#define ucase_toFullTitle U_ICU_ENTRY_POINT_RENAME(ucase_toFullTitle) -#define ucase_toFullUpper U_ICU_ENTRY_POINT_RENAME(ucase_toFullUpper) -#define ucase_tolower U_ICU_ENTRY_POINT_RENAME(ucase_tolower) -#define ucase_totitle U_ICU_ENTRY_POINT_RENAME(ucase_totitle) -#define ucase_toupper U_ICU_ENTRY_POINT_RENAME(ucase_toupper) -#define ucasemap_close U_ICU_ENTRY_POINT_RENAME(ucasemap_close) -#define ucasemap_getBreakIterator U_ICU_ENTRY_POINT_RENAME(ucasemap_getBreakIterator) -#define ucasemap_getLocale U_ICU_ENTRY_POINT_RENAME(ucasemap_getLocale) -#define ucasemap_getOptions U_ICU_ENTRY_POINT_RENAME(ucasemap_getOptions) -#define ucasemap_internalUTF8ToTitle U_ICU_ENTRY_POINT_RENAME(ucasemap_internalUTF8ToTitle) -#define ucasemap_mapUTF8 U_ICU_ENTRY_POINT_RENAME(ucasemap_mapUTF8) -#define ucasemap_open U_ICU_ENTRY_POINT_RENAME(ucasemap_open) -#define ucasemap_setBreakIterator U_ICU_ENTRY_POINT_RENAME(ucasemap_setBreakIterator) -#define ucasemap_setLocale U_ICU_ENTRY_POINT_RENAME(ucasemap_setLocale) -#define ucasemap_setOptions U_ICU_ENTRY_POINT_RENAME(ucasemap_setOptions) -#define ucasemap_toTitle U_ICU_ENTRY_POINT_RENAME(ucasemap_toTitle) -#define ucasemap_utf8FoldCase U_ICU_ENTRY_POINT_RENAME(ucasemap_utf8FoldCase) -#define ucasemap_utf8ToLower U_ICU_ENTRY_POINT_RENAME(ucasemap_utf8ToLower) -#define ucasemap_utf8ToTitle U_ICU_ENTRY_POINT_RENAME(ucasemap_utf8ToTitle) -#define ucasemap_utf8ToUpper U_ICU_ENTRY_POINT_RENAME(ucasemap_utf8ToUpper) -#define uchar_addPropertyStarts U_ICU_ENTRY_POINT_RENAME(uchar_addPropertyStarts) -#define uchar_swapNames U_ICU_ENTRY_POINT_RENAME(uchar_swapNames) -#define ucln_cleanupOne U_ICU_ENTRY_POINT_RENAME(ucln_cleanupOne) -#define ucln_common_registerCleanup U_ICU_ENTRY_POINT_RENAME(ucln_common_registerCleanup) -#define ucln_i18n_registerCleanup U_ICU_ENTRY_POINT_RENAME(ucln_i18n_registerCleanup) -#define ucln_io_registerCleanup U_ICU_ENTRY_POINT_RENAME(ucln_io_registerCleanup) -#define ucln_lib_cleanup U_ICU_ENTRY_POINT_RENAME(ucln_lib_cleanup) -#define ucln_registerCleanup U_ICU_ENTRY_POINT_RENAME(ucln_registerCleanup) -#define ucnv_MBCSFromUChar32 U_ICU_ENTRY_POINT_RENAME(ucnv_MBCSFromUChar32) -#define ucnv_MBCSFromUnicodeWithOffsets U_ICU_ENTRY_POINT_RENAME(ucnv_MBCSFromUnicodeWithOffsets) -#define ucnv_MBCSGetFilteredUnicodeSetForUnicode U_ICU_ENTRY_POINT_RENAME(ucnv_MBCSGetFilteredUnicodeSetForUnicode) -#define ucnv_MBCSGetType U_ICU_ENTRY_POINT_RENAME(ucnv_MBCSGetType) -#define ucnv_MBCSGetUnicodeSetForUnicode U_ICU_ENTRY_POINT_RENAME(ucnv_MBCSGetUnicodeSetForUnicode) -#define ucnv_MBCSIsLeadByte U_ICU_ENTRY_POINT_RENAME(ucnv_MBCSIsLeadByte) -#define ucnv_MBCSSimpleGetNextUChar U_ICU_ENTRY_POINT_RENAME(ucnv_MBCSSimpleGetNextUChar) -#define ucnv_MBCSToUnicodeWithOffsets U_ICU_ENTRY_POINT_RENAME(ucnv_MBCSToUnicodeWithOffsets) -#define ucnv_bld_countAvailableConverters U_ICU_ENTRY_POINT_RENAME(ucnv_bld_countAvailableConverters) -#define ucnv_bld_getAvailableConverter U_ICU_ENTRY_POINT_RENAME(ucnv_bld_getAvailableConverter) -#define ucnv_canCreateConverter U_ICU_ENTRY_POINT_RENAME(ucnv_canCreateConverter) -#define ucnv_cbFromUWriteBytes U_ICU_ENTRY_POINT_RENAME(ucnv_cbFromUWriteBytes) -#define ucnv_cbFromUWriteSub U_ICU_ENTRY_POINT_RENAME(ucnv_cbFromUWriteSub) -#define ucnv_cbFromUWriteUChars U_ICU_ENTRY_POINT_RENAME(ucnv_cbFromUWriteUChars) -#define ucnv_cbToUWriteSub U_ICU_ENTRY_POINT_RENAME(ucnv_cbToUWriteSub) -#define ucnv_cbToUWriteUChars U_ICU_ENTRY_POINT_RENAME(ucnv_cbToUWriteUChars) -#define ucnv_close U_ICU_ENTRY_POINT_RENAME(ucnv_close) -#define ucnv_compareNames U_ICU_ENTRY_POINT_RENAME(ucnv_compareNames) -#define ucnv_convert U_ICU_ENTRY_POINT_RENAME(ucnv_convert) -#define ucnv_convertEx U_ICU_ENTRY_POINT_RENAME(ucnv_convertEx) -#define ucnv_countAliases U_ICU_ENTRY_POINT_RENAME(ucnv_countAliases) -#define ucnv_countAvailable U_ICU_ENTRY_POINT_RENAME(ucnv_countAvailable) -#define ucnv_countStandards U_ICU_ENTRY_POINT_RENAME(ucnv_countStandards) -#define ucnv_createAlgorithmicConverter U_ICU_ENTRY_POINT_RENAME(ucnv_createAlgorithmicConverter) -#define ucnv_createConverter U_ICU_ENTRY_POINT_RENAME(ucnv_createConverter) -#define ucnv_createConverterFromPackage U_ICU_ENTRY_POINT_RENAME(ucnv_createConverterFromPackage) -#define ucnv_createConverterFromSharedData U_ICU_ENTRY_POINT_RENAME(ucnv_createConverterFromSharedData) -#define ucnv_detectUnicodeSignature U_ICU_ENTRY_POINT_RENAME(ucnv_detectUnicodeSignature) -#define ucnv_extContinueMatchFromU U_ICU_ENTRY_POINT_RENAME(ucnv_extContinueMatchFromU) -#define ucnv_extContinueMatchToU U_ICU_ENTRY_POINT_RENAME(ucnv_extContinueMatchToU) -#define ucnv_extGetUnicodeSet U_ICU_ENTRY_POINT_RENAME(ucnv_extGetUnicodeSet) -#define ucnv_extInitialMatchFromU U_ICU_ENTRY_POINT_RENAME(ucnv_extInitialMatchFromU) -#define ucnv_extInitialMatchToU U_ICU_ENTRY_POINT_RENAME(ucnv_extInitialMatchToU) -#define ucnv_extSimpleMatchFromU U_ICU_ENTRY_POINT_RENAME(ucnv_extSimpleMatchFromU) -#define ucnv_extSimpleMatchToU U_ICU_ENTRY_POINT_RENAME(ucnv_extSimpleMatchToU) -#define ucnv_fixFileSeparator U_ICU_ENTRY_POINT_RENAME(ucnv_fixFileSeparator) -#define ucnv_flushCache U_ICU_ENTRY_POINT_RENAME(ucnv_flushCache) -#define ucnv_fromAlgorithmic U_ICU_ENTRY_POINT_RENAME(ucnv_fromAlgorithmic) -#define ucnv_fromUChars U_ICU_ENTRY_POINT_RENAME(ucnv_fromUChars) -#define ucnv_fromUCountPending U_ICU_ENTRY_POINT_RENAME(ucnv_fromUCountPending) -#define ucnv_fromUWriteBytes U_ICU_ENTRY_POINT_RENAME(ucnv_fromUWriteBytes) -#define ucnv_fromUnicode U_ICU_ENTRY_POINT_RENAME(ucnv_fromUnicode) -#define ucnv_fromUnicode_UTF8 U_ICU_ENTRY_POINT_RENAME(ucnv_fromUnicode_UTF8) -#define ucnv_fromUnicode_UTF8_OFFSETS_LOGIC U_ICU_ENTRY_POINT_RENAME(ucnv_fromUnicode_UTF8_OFFSETS_LOGIC) -#define ucnv_getAlias U_ICU_ENTRY_POINT_RENAME(ucnv_getAlias) -#define ucnv_getAliases U_ICU_ENTRY_POINT_RENAME(ucnv_getAliases) -#define ucnv_getAvailableName U_ICU_ENTRY_POINT_RENAME(ucnv_getAvailableName) -#define ucnv_getCCSID U_ICU_ENTRY_POINT_RENAME(ucnv_getCCSID) -#define ucnv_getCanonicalName U_ICU_ENTRY_POINT_RENAME(ucnv_getCanonicalName) -#define ucnv_getCompleteUnicodeSet U_ICU_ENTRY_POINT_RENAME(ucnv_getCompleteUnicodeSet) -#define ucnv_getDefaultName U_ICU_ENTRY_POINT_RENAME(ucnv_getDefaultName) -#define ucnv_getDisplayName U_ICU_ENTRY_POINT_RENAME(ucnv_getDisplayName) -#define ucnv_getFromUCallBack U_ICU_ENTRY_POINT_RENAME(ucnv_getFromUCallBack) -#define ucnv_getInvalidChars U_ICU_ENTRY_POINT_RENAME(ucnv_getInvalidChars) -#define ucnv_getInvalidUChars U_ICU_ENTRY_POINT_RENAME(ucnv_getInvalidUChars) -#define ucnv_getMaxCharSize U_ICU_ENTRY_POINT_RENAME(ucnv_getMaxCharSize) -#define ucnv_getMinCharSize U_ICU_ENTRY_POINT_RENAME(ucnv_getMinCharSize) -#define ucnv_getName U_ICU_ENTRY_POINT_RENAME(ucnv_getName) -#define ucnv_getNextUChar U_ICU_ENTRY_POINT_RENAME(ucnv_getNextUChar) -#define ucnv_getNonSurrogateUnicodeSet U_ICU_ENTRY_POINT_RENAME(ucnv_getNonSurrogateUnicodeSet) -#define ucnv_getPlatform U_ICU_ENTRY_POINT_RENAME(ucnv_getPlatform) -#define ucnv_getStandard U_ICU_ENTRY_POINT_RENAME(ucnv_getStandard) -#define ucnv_getStandardName U_ICU_ENTRY_POINT_RENAME(ucnv_getStandardName) -#define ucnv_getStarters U_ICU_ENTRY_POINT_RENAME(ucnv_getStarters) -#define ucnv_getSubstChars U_ICU_ENTRY_POINT_RENAME(ucnv_getSubstChars) -#define ucnv_getToUCallBack U_ICU_ENTRY_POINT_RENAME(ucnv_getToUCallBack) -#define ucnv_getType U_ICU_ENTRY_POINT_RENAME(ucnv_getType) -#define ucnv_getUnicodeSet U_ICU_ENTRY_POINT_RENAME(ucnv_getUnicodeSet) -#define ucnv_incrementRefCount U_ICU_ENTRY_POINT_RENAME(ucnv_incrementRefCount) -#define ucnv_io_countKnownConverters U_ICU_ENTRY_POINT_RENAME(ucnv_io_countKnownConverters) -#define ucnv_io_getConverterName U_ICU_ENTRY_POINT_RENAME(ucnv_io_getConverterName) -#define ucnv_io_stripASCIIForCompare U_ICU_ENTRY_POINT_RENAME(ucnv_io_stripASCIIForCompare) -#define ucnv_io_stripEBCDICForCompare U_ICU_ENTRY_POINT_RENAME(ucnv_io_stripEBCDICForCompare) -#define ucnv_isAmbiguous U_ICU_ENTRY_POINT_RENAME(ucnv_isAmbiguous) -#define ucnv_isFixedWidth U_ICU_ENTRY_POINT_RENAME(ucnv_isFixedWidth) -#define ucnv_load U_ICU_ENTRY_POINT_RENAME(ucnv_load) -#define ucnv_loadSharedData U_ICU_ENTRY_POINT_RENAME(ucnv_loadSharedData) -#define ucnv_open U_ICU_ENTRY_POINT_RENAME(ucnv_open) -#define ucnv_openAllNames U_ICU_ENTRY_POINT_RENAME(ucnv_openAllNames) -#define ucnv_openCCSID U_ICU_ENTRY_POINT_RENAME(ucnv_openCCSID) -#define ucnv_openPackage U_ICU_ENTRY_POINT_RENAME(ucnv_openPackage) -#define ucnv_openStandardNames U_ICU_ENTRY_POINT_RENAME(ucnv_openStandardNames) -#define ucnv_openU U_ICU_ENTRY_POINT_RENAME(ucnv_openU) -#define ucnv_reset U_ICU_ENTRY_POINT_RENAME(ucnv_reset) -#define ucnv_resetFromUnicode U_ICU_ENTRY_POINT_RENAME(ucnv_resetFromUnicode) -#define ucnv_resetToUnicode U_ICU_ENTRY_POINT_RENAME(ucnv_resetToUnicode) -#define ucnv_safeClone U_ICU_ENTRY_POINT_RENAME(ucnv_safeClone) -#define ucnv_setDefaultName U_ICU_ENTRY_POINT_RENAME(ucnv_setDefaultName) -#define ucnv_setFallback U_ICU_ENTRY_POINT_RENAME(ucnv_setFallback) -#define ucnv_setFromUCallBack U_ICU_ENTRY_POINT_RENAME(ucnv_setFromUCallBack) -#define ucnv_setSubstChars U_ICU_ENTRY_POINT_RENAME(ucnv_setSubstChars) -#define ucnv_setSubstString U_ICU_ENTRY_POINT_RENAME(ucnv_setSubstString) -#define ucnv_setToUCallBack U_ICU_ENTRY_POINT_RENAME(ucnv_setToUCallBack) -#define ucnv_swap U_ICU_ENTRY_POINT_RENAME(ucnv_swap) -#define ucnv_swapAliases U_ICU_ENTRY_POINT_RENAME(ucnv_swapAliases) -#define ucnv_toAlgorithmic U_ICU_ENTRY_POINT_RENAME(ucnv_toAlgorithmic) -#define ucnv_toUChars U_ICU_ENTRY_POINT_RENAME(ucnv_toUChars) -#define ucnv_toUCountPending U_ICU_ENTRY_POINT_RENAME(ucnv_toUCountPending) -#define ucnv_toUWriteCodePoint U_ICU_ENTRY_POINT_RENAME(ucnv_toUWriteCodePoint) -#define ucnv_toUWriteUChars U_ICU_ENTRY_POINT_RENAME(ucnv_toUWriteUChars) -#define ucnv_toUnicode U_ICU_ENTRY_POINT_RENAME(ucnv_toUnicode) -#define ucnv_unload U_ICU_ENTRY_POINT_RENAME(ucnv_unload) -#define ucnv_unloadSharedDataIfReady U_ICU_ENTRY_POINT_RENAME(ucnv_unloadSharedDataIfReady) -#define ucnv_usesFallback U_ICU_ENTRY_POINT_RENAME(ucnv_usesFallback) -#define ucnvsel_close U_ICU_ENTRY_POINT_RENAME(ucnvsel_close) -#define ucnvsel_open U_ICU_ENTRY_POINT_RENAME(ucnvsel_open) -#define ucnvsel_openFromSerialized U_ICU_ENTRY_POINT_RENAME(ucnvsel_openFromSerialized) -#define ucnvsel_selectForString U_ICU_ENTRY_POINT_RENAME(ucnvsel_selectForString) -#define ucnvsel_selectForUTF8 U_ICU_ENTRY_POINT_RENAME(ucnvsel_selectForUTF8) -#define ucnvsel_serialize U_ICU_ENTRY_POINT_RENAME(ucnvsel_serialize) -#define ucol_cloneBinary U_ICU_ENTRY_POINT_RENAME(ucol_cloneBinary) -#define ucol_close U_ICU_ENTRY_POINT_RENAME(ucol_close) -#define ucol_closeElements U_ICU_ENTRY_POINT_RENAME(ucol_closeElements) -#define ucol_countAvailable U_ICU_ENTRY_POINT_RENAME(ucol_countAvailable) -#define ucol_equal U_ICU_ENTRY_POINT_RENAME(ucol_equal) -#define ucol_equals U_ICU_ENTRY_POINT_RENAME(ucol_equals) -#define ucol_getAttribute U_ICU_ENTRY_POINT_RENAME(ucol_getAttribute) -#define ucol_getAvailable U_ICU_ENTRY_POINT_RENAME(ucol_getAvailable) -#define ucol_getBound U_ICU_ENTRY_POINT_RENAME(ucol_getBound) -#define ucol_getContractions U_ICU_ENTRY_POINT_RENAME(ucol_getContractions) -#define ucol_getContractionsAndExpansions U_ICU_ENTRY_POINT_RENAME(ucol_getContractionsAndExpansions) -#define ucol_getDisplayName U_ICU_ENTRY_POINT_RENAME(ucol_getDisplayName) -#define ucol_getEquivalentReorderCodes U_ICU_ENTRY_POINT_RENAME(ucol_getEquivalentReorderCodes) -#define ucol_getFunctionalEquivalent U_ICU_ENTRY_POINT_RENAME(ucol_getFunctionalEquivalent) -#define ucol_getKeywordValues U_ICU_ENTRY_POINT_RENAME(ucol_getKeywordValues) -#define ucol_getKeywordValuesForLocale U_ICU_ENTRY_POINT_RENAME(ucol_getKeywordValuesForLocale) -#define ucol_getKeywords U_ICU_ENTRY_POINT_RENAME(ucol_getKeywords) -#define ucol_getLocale U_ICU_ENTRY_POINT_RENAME(ucol_getLocale) -#define ucol_getLocaleByType U_ICU_ENTRY_POINT_RENAME(ucol_getLocaleByType) -#define ucol_getMaxExpansion U_ICU_ENTRY_POINT_RENAME(ucol_getMaxExpansion) -#define ucol_getMaxVariable U_ICU_ENTRY_POINT_RENAME(ucol_getMaxVariable) -#define ucol_getOffset U_ICU_ENTRY_POINT_RENAME(ucol_getOffset) -#define ucol_getReorderCodes U_ICU_ENTRY_POINT_RENAME(ucol_getReorderCodes) -#define ucol_getRules U_ICU_ENTRY_POINT_RENAME(ucol_getRules) -#define ucol_getRulesEx U_ICU_ENTRY_POINT_RENAME(ucol_getRulesEx) -#define ucol_getShortDefinitionString U_ICU_ENTRY_POINT_RENAME(ucol_getShortDefinitionString) -#define ucol_getSortKey U_ICU_ENTRY_POINT_RENAME(ucol_getSortKey) -#define ucol_getStrength U_ICU_ENTRY_POINT_RENAME(ucol_getStrength) -#define ucol_getTailoredSet U_ICU_ENTRY_POINT_RENAME(ucol_getTailoredSet) -#define ucol_getUCAVersion U_ICU_ENTRY_POINT_RENAME(ucol_getUCAVersion) -#define ucol_getUnsafeSet U_ICU_ENTRY_POINT_RENAME(ucol_getUnsafeSet) -#define ucol_getVariableTop U_ICU_ENTRY_POINT_RENAME(ucol_getVariableTop) -#define ucol_getVersion U_ICU_ENTRY_POINT_RENAME(ucol_getVersion) -#define ucol_greater U_ICU_ENTRY_POINT_RENAME(ucol_greater) -#define ucol_greaterOrEqual U_ICU_ENTRY_POINT_RENAME(ucol_greaterOrEqual) -#define ucol_keyHashCode U_ICU_ENTRY_POINT_RENAME(ucol_keyHashCode) -#define ucol_looksLikeCollationBinary U_ICU_ENTRY_POINT_RENAME(ucol_looksLikeCollationBinary) -#define ucol_mergeSortkeys U_ICU_ENTRY_POINT_RENAME(ucol_mergeSortkeys) -#define ucol_next U_ICU_ENTRY_POINT_RENAME(ucol_next) -#define ucol_nextSortKeyPart U_ICU_ENTRY_POINT_RENAME(ucol_nextSortKeyPart) -#define ucol_normalizeShortDefinitionString U_ICU_ENTRY_POINT_RENAME(ucol_normalizeShortDefinitionString) -#define ucol_open U_ICU_ENTRY_POINT_RENAME(ucol_open) -#define ucol_openAvailableLocales U_ICU_ENTRY_POINT_RENAME(ucol_openAvailableLocales) -#define ucol_openBinary U_ICU_ENTRY_POINT_RENAME(ucol_openBinary) -#define ucol_openElements U_ICU_ENTRY_POINT_RENAME(ucol_openElements) -#define ucol_openFromShortString U_ICU_ENTRY_POINT_RENAME(ucol_openFromShortString) -#define ucol_openRules U_ICU_ENTRY_POINT_RENAME(ucol_openRules) -#define ucol_prepareShortStringOpen U_ICU_ENTRY_POINT_RENAME(ucol_prepareShortStringOpen) -#define ucol_previous U_ICU_ENTRY_POINT_RENAME(ucol_previous) -#define ucol_primaryOrder U_ICU_ENTRY_POINT_RENAME(ucol_primaryOrder) -#define ucol_reset U_ICU_ENTRY_POINT_RENAME(ucol_reset) -#define ucol_restoreVariableTop U_ICU_ENTRY_POINT_RENAME(ucol_restoreVariableTop) -#define ucol_safeClone U_ICU_ENTRY_POINT_RENAME(ucol_safeClone) -#define ucol_secondaryOrder U_ICU_ENTRY_POINT_RENAME(ucol_secondaryOrder) -#define ucol_setAttribute U_ICU_ENTRY_POINT_RENAME(ucol_setAttribute) -#define ucol_setMaxVariable U_ICU_ENTRY_POINT_RENAME(ucol_setMaxVariable) -#define ucol_setOffset U_ICU_ENTRY_POINT_RENAME(ucol_setOffset) -#define ucol_setReorderCodes U_ICU_ENTRY_POINT_RENAME(ucol_setReorderCodes) -#define ucol_setStrength U_ICU_ENTRY_POINT_RENAME(ucol_setStrength) -#define ucol_setText U_ICU_ENTRY_POINT_RENAME(ucol_setText) -#define ucol_setVariableTop U_ICU_ENTRY_POINT_RENAME(ucol_setVariableTop) -#define ucol_strcoll U_ICU_ENTRY_POINT_RENAME(ucol_strcoll) -#define ucol_strcollIter U_ICU_ENTRY_POINT_RENAME(ucol_strcollIter) -#define ucol_strcollUTF8 U_ICU_ENTRY_POINT_RENAME(ucol_strcollUTF8) -#define ucol_swap U_ICU_ENTRY_POINT_RENAME(ucol_swap) -#define ucol_swapInverseUCA U_ICU_ENTRY_POINT_RENAME(ucol_swapInverseUCA) -#define ucol_tertiaryOrder U_ICU_ENTRY_POINT_RENAME(ucol_tertiaryOrder) -#define ucsdet_close U_ICU_ENTRY_POINT_RENAME(ucsdet_close) -#define ucsdet_detect U_ICU_ENTRY_POINT_RENAME(ucsdet_detect) -#define ucsdet_detectAll U_ICU_ENTRY_POINT_RENAME(ucsdet_detectAll) -#define ucsdet_enableInputFilter U_ICU_ENTRY_POINT_RENAME(ucsdet_enableInputFilter) -#define ucsdet_getAllDetectableCharsets U_ICU_ENTRY_POINT_RENAME(ucsdet_getAllDetectableCharsets) -#define ucsdet_getConfidence U_ICU_ENTRY_POINT_RENAME(ucsdet_getConfidence) -#define ucsdet_getDetectableCharsets U_ICU_ENTRY_POINT_RENAME(ucsdet_getDetectableCharsets) -#define ucsdet_getLanguage U_ICU_ENTRY_POINT_RENAME(ucsdet_getLanguage) -#define ucsdet_getName U_ICU_ENTRY_POINT_RENAME(ucsdet_getName) -#define ucsdet_getUChars U_ICU_ENTRY_POINT_RENAME(ucsdet_getUChars) -#define ucsdet_isInputFilterEnabled U_ICU_ENTRY_POINT_RENAME(ucsdet_isInputFilterEnabled) -#define ucsdet_open U_ICU_ENTRY_POINT_RENAME(ucsdet_open) -#define ucsdet_setDeclaredEncoding U_ICU_ENTRY_POINT_RENAME(ucsdet_setDeclaredEncoding) -#define ucsdet_setDetectableCharset U_ICU_ENTRY_POINT_RENAME(ucsdet_setDetectableCharset) -#define ucsdet_setText U_ICU_ENTRY_POINT_RENAME(ucsdet_setText) -#define ucurr_countCurrencies U_ICU_ENTRY_POINT_RENAME(ucurr_countCurrencies) -#define ucurr_forLocale U_ICU_ENTRY_POINT_RENAME(ucurr_forLocale) -#define ucurr_forLocaleAndDate U_ICU_ENTRY_POINT_RENAME(ucurr_forLocaleAndDate) -#define ucurr_getDefaultFractionDigits U_ICU_ENTRY_POINT_RENAME(ucurr_getDefaultFractionDigits) -#define ucurr_getDefaultFractionDigitsForUsage U_ICU_ENTRY_POINT_RENAME(ucurr_getDefaultFractionDigitsForUsage) -#define ucurr_getKeywordValuesForLocale U_ICU_ENTRY_POINT_RENAME(ucurr_getKeywordValuesForLocale) -#define ucurr_getName U_ICU_ENTRY_POINT_RENAME(ucurr_getName) -#define ucurr_getNumericCode U_ICU_ENTRY_POINT_RENAME(ucurr_getNumericCode) -#define ucurr_getPluralName U_ICU_ENTRY_POINT_RENAME(ucurr_getPluralName) -#define ucurr_getRoundingIncrement U_ICU_ENTRY_POINT_RENAME(ucurr_getRoundingIncrement) -#define ucurr_getRoundingIncrementForUsage U_ICU_ENTRY_POINT_RENAME(ucurr_getRoundingIncrementForUsage) -#define ucurr_isAvailable U_ICU_ENTRY_POINT_RENAME(ucurr_isAvailable) -#define ucurr_openISOCurrencies U_ICU_ENTRY_POINT_RENAME(ucurr_openISOCurrencies) -#define ucurr_register U_ICU_ENTRY_POINT_RENAME(ucurr_register) -#define ucurr_unregister U_ICU_ENTRY_POINT_RENAME(ucurr_unregister) -#define udat_adoptNumberFormat U_ICU_ENTRY_POINT_RENAME(udat_adoptNumberFormat) -#define udat_adoptNumberFormatForFields U_ICU_ENTRY_POINT_RENAME(udat_adoptNumberFormatForFields) -#define udat_applyPattern U_ICU_ENTRY_POINT_RENAME(udat_applyPattern) -#define udat_applyPatternRelative U_ICU_ENTRY_POINT_RENAME(udat_applyPatternRelative) -#define udat_clone U_ICU_ENTRY_POINT_RENAME(udat_clone) -#define udat_close U_ICU_ENTRY_POINT_RENAME(udat_close) -#define udat_countAvailable U_ICU_ENTRY_POINT_RENAME(udat_countAvailable) -#define udat_countSymbols U_ICU_ENTRY_POINT_RENAME(udat_countSymbols) -#define udat_format U_ICU_ENTRY_POINT_RENAME(udat_format) -#define udat_formatCalendar U_ICU_ENTRY_POINT_RENAME(udat_formatCalendar) -#define udat_formatCalendarForFields U_ICU_ENTRY_POINT_RENAME(udat_formatCalendarForFields) -#define udat_formatForFields U_ICU_ENTRY_POINT_RENAME(udat_formatForFields) -#define udat_get2DigitYearStart U_ICU_ENTRY_POINT_RENAME(udat_get2DigitYearStart) -#define udat_getAvailable U_ICU_ENTRY_POINT_RENAME(udat_getAvailable) -#define udat_getBooleanAttribute U_ICU_ENTRY_POINT_RENAME(udat_getBooleanAttribute) -#define udat_getCalendar U_ICU_ENTRY_POINT_RENAME(udat_getCalendar) -#define udat_getContext U_ICU_ENTRY_POINT_RENAME(udat_getContext) -#define udat_getLocaleByType U_ICU_ENTRY_POINT_RENAME(udat_getLocaleByType) -#define udat_getNumberFormat U_ICU_ENTRY_POINT_RENAME(udat_getNumberFormat) -#define udat_getNumberFormatForField U_ICU_ENTRY_POINT_RENAME(udat_getNumberFormatForField) -#define udat_getSymbols U_ICU_ENTRY_POINT_RENAME(udat_getSymbols) -#define udat_isLenient U_ICU_ENTRY_POINT_RENAME(udat_isLenient) -#define udat_open U_ICU_ENTRY_POINT_RENAME(udat_open) -#define udat_parse U_ICU_ENTRY_POINT_RENAME(udat_parse) -#define udat_parseCalendar U_ICU_ENTRY_POINT_RENAME(udat_parseCalendar) -#define udat_registerOpener U_ICU_ENTRY_POINT_RENAME(udat_registerOpener) -#define udat_set2DigitYearStart U_ICU_ENTRY_POINT_RENAME(udat_set2DigitYearStart) -#define udat_setBooleanAttribute U_ICU_ENTRY_POINT_RENAME(udat_setBooleanAttribute) -#define udat_setCalendar U_ICU_ENTRY_POINT_RENAME(udat_setCalendar) -#define udat_setContext U_ICU_ENTRY_POINT_RENAME(udat_setContext) -#define udat_setLenient U_ICU_ENTRY_POINT_RENAME(udat_setLenient) -#define udat_setNumberFormat U_ICU_ENTRY_POINT_RENAME(udat_setNumberFormat) -#define udat_setSymbols U_ICU_ENTRY_POINT_RENAME(udat_setSymbols) -#define udat_toCalendarDateField U_ICU_ENTRY_POINT_RENAME(udat_toCalendarDateField) -#define udat_toPattern U_ICU_ENTRY_POINT_RENAME(udat_toPattern) -#define udat_toPatternRelativeDate U_ICU_ENTRY_POINT_RENAME(udat_toPatternRelativeDate) -#define udat_toPatternRelativeTime U_ICU_ENTRY_POINT_RENAME(udat_toPatternRelativeTime) -#define udat_unregisterOpener U_ICU_ENTRY_POINT_RENAME(udat_unregisterOpener) -#define udata_checkCommonData U_ICU_ENTRY_POINT_RENAME(udata_checkCommonData) -#define udata_close U_ICU_ENTRY_POINT_RENAME(udata_close) -#define udata_closeSwapper U_ICU_ENTRY_POINT_RENAME(udata_closeSwapper) -#define udata_getHeaderSize U_ICU_ENTRY_POINT_RENAME(udata_getHeaderSize) -#define udata_getInfo U_ICU_ENTRY_POINT_RENAME(udata_getInfo) -#define udata_getInfoSize U_ICU_ENTRY_POINT_RENAME(udata_getInfoSize) -#define udata_getLength U_ICU_ENTRY_POINT_RENAME(udata_getLength) -#define udata_getMemory U_ICU_ENTRY_POINT_RENAME(udata_getMemory) -#define udata_getRawMemory U_ICU_ENTRY_POINT_RENAME(udata_getRawMemory) -#define udata_open U_ICU_ENTRY_POINT_RENAME(udata_open) -#define udata_openChoice U_ICU_ENTRY_POINT_RENAME(udata_openChoice) -#define udata_openSwapper U_ICU_ENTRY_POINT_RENAME(udata_openSwapper) -#define udata_openSwapperForInputData U_ICU_ENTRY_POINT_RENAME(udata_openSwapperForInputData) -#define udata_printError U_ICU_ENTRY_POINT_RENAME(udata_printError) -#define udata_readInt16 U_ICU_ENTRY_POINT_RENAME(udata_readInt16) -#define udata_readInt32 U_ICU_ENTRY_POINT_RENAME(udata_readInt32) -#define udata_setAppData U_ICU_ENTRY_POINT_RENAME(udata_setAppData) -#define udata_setCommonData U_ICU_ENTRY_POINT_RENAME(udata_setCommonData) -#define udata_setFileAccess U_ICU_ENTRY_POINT_RENAME(udata_setFileAccess) -#define udata_swapDataHeader U_ICU_ENTRY_POINT_RENAME(udata_swapDataHeader) -#define udata_swapInvStringBlock U_ICU_ENTRY_POINT_RENAME(udata_swapInvStringBlock) -#define udatpg_addPattern U_ICU_ENTRY_POINT_RENAME(udatpg_addPattern) -#define udatpg_clone U_ICU_ENTRY_POINT_RENAME(udatpg_clone) -#define udatpg_close U_ICU_ENTRY_POINT_RENAME(udatpg_close) -#define udatpg_getAppendItemFormat U_ICU_ENTRY_POINT_RENAME(udatpg_getAppendItemFormat) -#define udatpg_getAppendItemName U_ICU_ENTRY_POINT_RENAME(udatpg_getAppendItemName) -#define udatpg_getBaseSkeleton U_ICU_ENTRY_POINT_RENAME(udatpg_getBaseSkeleton) -#define udatpg_getBestPattern U_ICU_ENTRY_POINT_RENAME(udatpg_getBestPattern) -#define udatpg_getBestPatternWithOptions U_ICU_ENTRY_POINT_RENAME(udatpg_getBestPatternWithOptions) -#define udatpg_getDateTimeFormat U_ICU_ENTRY_POINT_RENAME(udatpg_getDateTimeFormat) -#define udatpg_getDecimal U_ICU_ENTRY_POINT_RENAME(udatpg_getDecimal) -#define udatpg_getPatternForSkeleton U_ICU_ENTRY_POINT_RENAME(udatpg_getPatternForSkeleton) -#define udatpg_getSkeleton U_ICU_ENTRY_POINT_RENAME(udatpg_getSkeleton) -#define udatpg_open U_ICU_ENTRY_POINT_RENAME(udatpg_open) -#define udatpg_openBaseSkeletons U_ICU_ENTRY_POINT_RENAME(udatpg_openBaseSkeletons) -#define udatpg_openEmpty U_ICU_ENTRY_POINT_RENAME(udatpg_openEmpty) -#define udatpg_openSkeletons U_ICU_ENTRY_POINT_RENAME(udatpg_openSkeletons) -#define udatpg_replaceFieldTypes U_ICU_ENTRY_POINT_RENAME(udatpg_replaceFieldTypes) -#define udatpg_replaceFieldTypesWithOptions U_ICU_ENTRY_POINT_RENAME(udatpg_replaceFieldTypesWithOptions) -#define udatpg_setAppendItemFormat U_ICU_ENTRY_POINT_RENAME(udatpg_setAppendItemFormat) -#define udatpg_setAppendItemName U_ICU_ENTRY_POINT_RENAME(udatpg_setAppendItemName) -#define udatpg_setDateTimeFormat U_ICU_ENTRY_POINT_RENAME(udatpg_setDateTimeFormat) -#define udatpg_setDecimal U_ICU_ENTRY_POINT_RENAME(udatpg_setDecimal) -#define udict_swap U_ICU_ENTRY_POINT_RENAME(udict_swap) -#define udtitvfmt_close U_ICU_ENTRY_POINT_RENAME(udtitvfmt_close) -#define udtitvfmt_format U_ICU_ENTRY_POINT_RENAME(udtitvfmt_format) -#define udtitvfmt_open U_ICU_ENTRY_POINT_RENAME(udtitvfmt_open) -#define uenum_close U_ICU_ENTRY_POINT_RENAME(uenum_close) -#define uenum_count U_ICU_ENTRY_POINT_RENAME(uenum_count) -#define uenum_next U_ICU_ENTRY_POINT_RENAME(uenum_next) -#define uenum_nextDefault U_ICU_ENTRY_POINT_RENAME(uenum_nextDefault) -#define uenum_openCharStringsEnumeration U_ICU_ENTRY_POINT_RENAME(uenum_openCharStringsEnumeration) -#define uenum_openFromStringEnumeration U_ICU_ENTRY_POINT_RENAME(uenum_openFromStringEnumeration) -#define uenum_openUCharStringsEnumeration U_ICU_ENTRY_POINT_RENAME(uenum_openUCharStringsEnumeration) -#define uenum_reset U_ICU_ENTRY_POINT_RENAME(uenum_reset) -#define uenum_unext U_ICU_ENTRY_POINT_RENAME(uenum_unext) -#define uenum_unextDefault U_ICU_ENTRY_POINT_RENAME(uenum_unextDefault) -#define ufieldpositer_close U_ICU_ENTRY_POINT_RENAME(ufieldpositer_close) -#define ufieldpositer_next U_ICU_ENTRY_POINT_RENAME(ufieldpositer_next) -#define ufieldpositer_open U_ICU_ENTRY_POINT_RENAME(ufieldpositer_open) -#define ufile_close_translit U_ICU_ENTRY_POINT_RENAME(ufile_close_translit) -#define ufile_fill_uchar_buffer U_ICU_ENTRY_POINT_RENAME(ufile_fill_uchar_buffer) -#define ufile_flush_io U_ICU_ENTRY_POINT_RENAME(ufile_flush_io) -#define ufile_flush_translit U_ICU_ENTRY_POINT_RENAME(ufile_flush_translit) -#define ufile_getch U_ICU_ENTRY_POINT_RENAME(ufile_getch) -#define ufile_getch32 U_ICU_ENTRY_POINT_RENAME(ufile_getch32) -#define ufmt_64tou U_ICU_ENTRY_POINT_RENAME(ufmt_64tou) -#define ufmt_close U_ICU_ENTRY_POINT_RENAME(ufmt_close) -#define ufmt_defaultCPToUnicode U_ICU_ENTRY_POINT_RENAME(ufmt_defaultCPToUnicode) -#define ufmt_digitvalue U_ICU_ENTRY_POINT_RENAME(ufmt_digitvalue) -#define ufmt_getArrayItemByIndex U_ICU_ENTRY_POINT_RENAME(ufmt_getArrayItemByIndex) -#define ufmt_getArrayLength U_ICU_ENTRY_POINT_RENAME(ufmt_getArrayLength) -#define ufmt_getDate U_ICU_ENTRY_POINT_RENAME(ufmt_getDate) -#define ufmt_getDecNumChars U_ICU_ENTRY_POINT_RENAME(ufmt_getDecNumChars) -#define ufmt_getDouble U_ICU_ENTRY_POINT_RENAME(ufmt_getDouble) -#define ufmt_getInt64 U_ICU_ENTRY_POINT_RENAME(ufmt_getInt64) -#define ufmt_getLong U_ICU_ENTRY_POINT_RENAME(ufmt_getLong) -#define ufmt_getObject U_ICU_ENTRY_POINT_RENAME(ufmt_getObject) -#define ufmt_getType U_ICU_ENTRY_POINT_RENAME(ufmt_getType) -#define ufmt_getUChars U_ICU_ENTRY_POINT_RENAME(ufmt_getUChars) -#define ufmt_isNumeric U_ICU_ENTRY_POINT_RENAME(ufmt_isNumeric) -#define ufmt_isdigit U_ICU_ENTRY_POINT_RENAME(ufmt_isdigit) -#define ufmt_open U_ICU_ENTRY_POINT_RENAME(ufmt_open) -#define ufmt_ptou U_ICU_ENTRY_POINT_RENAME(ufmt_ptou) -#define ufmt_uto64 U_ICU_ENTRY_POINT_RENAME(ufmt_uto64) -#define ufmt_utop U_ICU_ENTRY_POINT_RENAME(ufmt_utop) -#define ugender_getInstance U_ICU_ENTRY_POINT_RENAME(ugender_getInstance) -#define ugender_getListGender U_ICU_ENTRY_POINT_RENAME(ugender_getListGender) -#define uhash_close U_ICU_ENTRY_POINT_RENAME(uhash_close) -#define uhash_compareCaselessUnicodeString U_ICU_ENTRY_POINT_RENAME(uhash_compareCaselessUnicodeString) -#define uhash_compareChars U_ICU_ENTRY_POINT_RENAME(uhash_compareChars) -#define uhash_compareIChars U_ICU_ENTRY_POINT_RENAME(uhash_compareIChars) -#define uhash_compareLong U_ICU_ENTRY_POINT_RENAME(uhash_compareLong) -#define uhash_compareScriptSet U_ICU_ENTRY_POINT_RENAME(uhash_compareScriptSet) -#define uhash_compareUChars U_ICU_ENTRY_POINT_RENAME(uhash_compareUChars) -#define uhash_compareUnicodeString U_ICU_ENTRY_POINT_RENAME(uhash_compareUnicodeString) -#define uhash_count U_ICU_ENTRY_POINT_RENAME(uhash_count) -#define uhash_deleteHashtable U_ICU_ENTRY_POINT_RENAME(uhash_deleteHashtable) -#define uhash_deleteScriptSet U_ICU_ENTRY_POINT_RENAME(uhash_deleteScriptSet) -#define uhash_equals U_ICU_ENTRY_POINT_RENAME(uhash_equals) -#define uhash_equalsScriptSet U_ICU_ENTRY_POINT_RENAME(uhash_equalsScriptSet) -#define uhash_find U_ICU_ENTRY_POINT_RENAME(uhash_find) -#define uhash_get U_ICU_ENTRY_POINT_RENAME(uhash_get) -#define uhash_geti U_ICU_ENTRY_POINT_RENAME(uhash_geti) -#define uhash_hashCaselessUnicodeString U_ICU_ENTRY_POINT_RENAME(uhash_hashCaselessUnicodeString) -#define uhash_hashChars U_ICU_ENTRY_POINT_RENAME(uhash_hashChars) -#define uhash_hashIChars U_ICU_ENTRY_POINT_RENAME(uhash_hashIChars) -#define uhash_hashLong U_ICU_ENTRY_POINT_RENAME(uhash_hashLong) -#define uhash_hashScriptSet U_ICU_ENTRY_POINT_RENAME(uhash_hashScriptSet) -#define uhash_hashUChars U_ICU_ENTRY_POINT_RENAME(uhash_hashUChars) -#define uhash_hashUnicodeString U_ICU_ENTRY_POINT_RENAME(uhash_hashUnicodeString) -#define uhash_iget U_ICU_ENTRY_POINT_RENAME(uhash_iget) -#define uhash_igeti U_ICU_ENTRY_POINT_RENAME(uhash_igeti) -#define uhash_init U_ICU_ENTRY_POINT_RENAME(uhash_init) -#define uhash_iput U_ICU_ENTRY_POINT_RENAME(uhash_iput) -#define uhash_iputi U_ICU_ENTRY_POINT_RENAME(uhash_iputi) -#define uhash_iremove U_ICU_ENTRY_POINT_RENAME(uhash_iremove) -#define uhash_iremovei U_ICU_ENTRY_POINT_RENAME(uhash_iremovei) -#define uhash_nextElement U_ICU_ENTRY_POINT_RENAME(uhash_nextElement) -#define uhash_open U_ICU_ENTRY_POINT_RENAME(uhash_open) -#define uhash_openSize U_ICU_ENTRY_POINT_RENAME(uhash_openSize) -#define uhash_put U_ICU_ENTRY_POINT_RENAME(uhash_put) -#define uhash_puti U_ICU_ENTRY_POINT_RENAME(uhash_puti) -#define uhash_remove U_ICU_ENTRY_POINT_RENAME(uhash_remove) -#define uhash_removeAll U_ICU_ENTRY_POINT_RENAME(uhash_removeAll) -#define uhash_removeElement U_ICU_ENTRY_POINT_RENAME(uhash_removeElement) -#define uhash_removei U_ICU_ENTRY_POINT_RENAME(uhash_removei) -#define uhash_setKeyComparator U_ICU_ENTRY_POINT_RENAME(uhash_setKeyComparator) -#define uhash_setKeyDeleter U_ICU_ENTRY_POINT_RENAME(uhash_setKeyDeleter) -#define uhash_setKeyHasher U_ICU_ENTRY_POINT_RENAME(uhash_setKeyHasher) -#define uhash_setResizePolicy U_ICU_ENTRY_POINT_RENAME(uhash_setResizePolicy) -#define uhash_setValueComparator U_ICU_ENTRY_POINT_RENAME(uhash_setValueComparator) -#define uhash_setValueDeleter U_ICU_ENTRY_POINT_RENAME(uhash_setValueDeleter) -#define uidna_IDNToASCII U_ICU_ENTRY_POINT_RENAME(uidna_IDNToASCII) -#define uidna_IDNToUnicode U_ICU_ENTRY_POINT_RENAME(uidna_IDNToUnicode) -#define uidna_close U_ICU_ENTRY_POINT_RENAME(uidna_close) -#define uidna_compare U_ICU_ENTRY_POINT_RENAME(uidna_compare) -#define uidna_labelToASCII U_ICU_ENTRY_POINT_RENAME(uidna_labelToASCII) -#define uidna_labelToASCII_UTF8 U_ICU_ENTRY_POINT_RENAME(uidna_labelToASCII_UTF8) -#define uidna_labelToUnicode U_ICU_ENTRY_POINT_RENAME(uidna_labelToUnicode) -#define uidna_labelToUnicodeUTF8 U_ICU_ENTRY_POINT_RENAME(uidna_labelToUnicodeUTF8) -#define uidna_nameToASCII U_ICU_ENTRY_POINT_RENAME(uidna_nameToASCII) -#define uidna_nameToASCII_UTF8 U_ICU_ENTRY_POINT_RENAME(uidna_nameToASCII_UTF8) -#define uidna_nameToUnicode U_ICU_ENTRY_POINT_RENAME(uidna_nameToUnicode) -#define uidna_nameToUnicodeUTF8 U_ICU_ENTRY_POINT_RENAME(uidna_nameToUnicodeUTF8) -#define uidna_openUTS46 U_ICU_ENTRY_POINT_RENAME(uidna_openUTS46) -#define uidna_toASCII U_ICU_ENTRY_POINT_RENAME(uidna_toASCII) -#define uidna_toUnicode U_ICU_ENTRY_POINT_RENAME(uidna_toUnicode) -#define uiter_current32 U_ICU_ENTRY_POINT_RENAME(uiter_current32) -#define uiter_getState U_ICU_ENTRY_POINT_RENAME(uiter_getState) -#define uiter_next32 U_ICU_ENTRY_POINT_RENAME(uiter_next32) -#define uiter_previous32 U_ICU_ENTRY_POINT_RENAME(uiter_previous32) -#define uiter_setCharacterIterator U_ICU_ENTRY_POINT_RENAME(uiter_setCharacterIterator) -#define uiter_setReplaceable U_ICU_ENTRY_POINT_RENAME(uiter_setReplaceable) -#define uiter_setState U_ICU_ENTRY_POINT_RENAME(uiter_setState) -#define uiter_setString U_ICU_ENTRY_POINT_RENAME(uiter_setString) -#define uiter_setUTF16BE U_ICU_ENTRY_POINT_RENAME(uiter_setUTF16BE) -#define uiter_setUTF8 U_ICU_ENTRY_POINT_RENAME(uiter_setUTF8) -#define uldn_close U_ICU_ENTRY_POINT_RENAME(uldn_close) -#define uldn_getContext U_ICU_ENTRY_POINT_RENAME(uldn_getContext) -#define uldn_getDialectHandling U_ICU_ENTRY_POINT_RENAME(uldn_getDialectHandling) -#define uldn_getLocale U_ICU_ENTRY_POINT_RENAME(uldn_getLocale) -#define uldn_keyDisplayName U_ICU_ENTRY_POINT_RENAME(uldn_keyDisplayName) -#define uldn_keyValueDisplayName U_ICU_ENTRY_POINT_RENAME(uldn_keyValueDisplayName) -#define uldn_languageDisplayName U_ICU_ENTRY_POINT_RENAME(uldn_languageDisplayName) -#define uldn_localeDisplayName U_ICU_ENTRY_POINT_RENAME(uldn_localeDisplayName) -#define uldn_open U_ICU_ENTRY_POINT_RENAME(uldn_open) -#define uldn_openForContext U_ICU_ENTRY_POINT_RENAME(uldn_openForContext) -#define uldn_regionDisplayName U_ICU_ENTRY_POINT_RENAME(uldn_regionDisplayName) -#define uldn_scriptCodeDisplayName U_ICU_ENTRY_POINT_RENAME(uldn_scriptCodeDisplayName) -#define uldn_scriptDisplayName U_ICU_ENTRY_POINT_RENAME(uldn_scriptDisplayName) -#define uldn_variantDisplayName U_ICU_ENTRY_POINT_RENAME(uldn_variantDisplayName) -#define ulist_addItemBeginList U_ICU_ENTRY_POINT_RENAME(ulist_addItemBeginList) -#define ulist_addItemEndList U_ICU_ENTRY_POINT_RENAME(ulist_addItemEndList) -#define ulist_close_keyword_values_iterator U_ICU_ENTRY_POINT_RENAME(ulist_close_keyword_values_iterator) -#define ulist_containsString U_ICU_ENTRY_POINT_RENAME(ulist_containsString) -#define ulist_count_keyword_values U_ICU_ENTRY_POINT_RENAME(ulist_count_keyword_values) -#define ulist_createEmptyList U_ICU_ENTRY_POINT_RENAME(ulist_createEmptyList) -#define ulist_deleteList U_ICU_ENTRY_POINT_RENAME(ulist_deleteList) -#define ulist_getListFromEnum U_ICU_ENTRY_POINT_RENAME(ulist_getListFromEnum) -#define ulist_getListSize U_ICU_ENTRY_POINT_RENAME(ulist_getListSize) -#define ulist_getNext U_ICU_ENTRY_POINT_RENAME(ulist_getNext) -#define ulist_next_keyword_value U_ICU_ENTRY_POINT_RENAME(ulist_next_keyword_value) -#define ulist_removeString U_ICU_ENTRY_POINT_RENAME(ulist_removeString) -#define ulist_resetList U_ICU_ENTRY_POINT_RENAME(ulist_resetList) -#define ulist_reset_keyword_values_iterator U_ICU_ENTRY_POINT_RENAME(ulist_reset_keyword_values_iterator) -#define ulistfmt_close U_ICU_ENTRY_POINT_RENAME(ulistfmt_close) -#define ulistfmt_format U_ICU_ENTRY_POINT_RENAME(ulistfmt_format) -#define ulistfmt_open U_ICU_ENTRY_POINT_RENAME(ulistfmt_open) -#define uloc_acceptLanguage U_ICU_ENTRY_POINT_RENAME(uloc_acceptLanguage) -#define uloc_acceptLanguageFromHTTP U_ICU_ENTRY_POINT_RENAME(uloc_acceptLanguageFromHTTP) -#define uloc_addLikelySubtags U_ICU_ENTRY_POINT_RENAME(uloc_addLikelySubtags) -#define uloc_canonicalize U_ICU_ENTRY_POINT_RENAME(uloc_canonicalize) -#define uloc_countAvailable U_ICU_ENTRY_POINT_RENAME(uloc_countAvailable) -#define uloc_forLanguageTag U_ICU_ENTRY_POINT_RENAME(uloc_forLanguageTag) -#define uloc_getAvailable U_ICU_ENTRY_POINT_RENAME(uloc_getAvailable) -#define uloc_getBaseName U_ICU_ENTRY_POINT_RENAME(uloc_getBaseName) -#define uloc_getCharacterOrientation U_ICU_ENTRY_POINT_RENAME(uloc_getCharacterOrientation) -#define uloc_getCountry U_ICU_ENTRY_POINT_RENAME(uloc_getCountry) -#define uloc_getCurrentCountryID U_ICU_ENTRY_POINT_RENAME(uloc_getCurrentCountryID) -#define uloc_getCurrentLanguageID U_ICU_ENTRY_POINT_RENAME(uloc_getCurrentLanguageID) -#define uloc_getDefault U_ICU_ENTRY_POINT_RENAME(uloc_getDefault) -#define uloc_getDisplayCountry U_ICU_ENTRY_POINT_RENAME(uloc_getDisplayCountry) -#define uloc_getDisplayKeyword U_ICU_ENTRY_POINT_RENAME(uloc_getDisplayKeyword) -#define uloc_getDisplayKeywordValue U_ICU_ENTRY_POINT_RENAME(uloc_getDisplayKeywordValue) -#define uloc_getDisplayLanguage U_ICU_ENTRY_POINT_RENAME(uloc_getDisplayLanguage) -#define uloc_getDisplayName U_ICU_ENTRY_POINT_RENAME(uloc_getDisplayName) -#define uloc_getDisplayScript U_ICU_ENTRY_POINT_RENAME(uloc_getDisplayScript) -#define uloc_getDisplayScriptInContext U_ICU_ENTRY_POINT_RENAME(uloc_getDisplayScriptInContext) -#define uloc_getDisplayVariant U_ICU_ENTRY_POINT_RENAME(uloc_getDisplayVariant) -#define uloc_getISO3Country U_ICU_ENTRY_POINT_RENAME(uloc_getISO3Country) -#define uloc_getISO3Language U_ICU_ENTRY_POINT_RENAME(uloc_getISO3Language) -#define uloc_getISOCountries U_ICU_ENTRY_POINT_RENAME(uloc_getISOCountries) -#define uloc_getISOLanguages U_ICU_ENTRY_POINT_RENAME(uloc_getISOLanguages) -#define uloc_getKeywordValue U_ICU_ENTRY_POINT_RENAME(uloc_getKeywordValue) -#define uloc_getLCID U_ICU_ENTRY_POINT_RENAME(uloc_getLCID) -#define uloc_getLanguage U_ICU_ENTRY_POINT_RENAME(uloc_getLanguage) -#define uloc_getLineOrientation U_ICU_ENTRY_POINT_RENAME(uloc_getLineOrientation) -#define uloc_getLocaleForLCID U_ICU_ENTRY_POINT_RENAME(uloc_getLocaleForLCID) -#define uloc_getName U_ICU_ENTRY_POINT_RENAME(uloc_getName) -#define uloc_getParent U_ICU_ENTRY_POINT_RENAME(uloc_getParent) -#define uloc_getScript U_ICU_ENTRY_POINT_RENAME(uloc_getScript) -#define uloc_getTableStringWithFallback U_ICU_ENTRY_POINT_RENAME(uloc_getTableStringWithFallback) -#define uloc_getVariant U_ICU_ENTRY_POINT_RENAME(uloc_getVariant) -#define uloc_isRightToLeft U_ICU_ENTRY_POINT_RENAME(uloc_isRightToLeft) -#define uloc_minimizeSubtags U_ICU_ENTRY_POINT_RENAME(uloc_minimizeSubtags) -#define uloc_openKeywordList U_ICU_ENTRY_POINT_RENAME(uloc_openKeywordList) -#define uloc_openKeywords U_ICU_ENTRY_POINT_RENAME(uloc_openKeywords) -#define uloc_setDefault U_ICU_ENTRY_POINT_RENAME(uloc_setDefault) -#define uloc_setKeywordValue U_ICU_ENTRY_POINT_RENAME(uloc_setKeywordValue) -#define uloc_toLanguageTag U_ICU_ENTRY_POINT_RENAME(uloc_toLanguageTag) -#define uloc_toLegacyKey U_ICU_ENTRY_POINT_RENAME(uloc_toLegacyKey) -#define uloc_toLegacyType U_ICU_ENTRY_POINT_RENAME(uloc_toLegacyType) -#define uloc_toUnicodeLocaleKey U_ICU_ENTRY_POINT_RENAME(uloc_toUnicodeLocaleKey) -#define uloc_toUnicodeLocaleType U_ICU_ENTRY_POINT_RENAME(uloc_toUnicodeLocaleType) -#define ulocdata_close U_ICU_ENTRY_POINT_RENAME(ulocdata_close) -#define ulocdata_getCLDRVersion U_ICU_ENTRY_POINT_RENAME(ulocdata_getCLDRVersion) -#define ulocdata_getDelimiter U_ICU_ENTRY_POINT_RENAME(ulocdata_getDelimiter) -#define ulocdata_getExemplarSet U_ICU_ENTRY_POINT_RENAME(ulocdata_getExemplarSet) -#define ulocdata_getLocaleDisplayPattern U_ICU_ENTRY_POINT_RENAME(ulocdata_getLocaleDisplayPattern) -#define ulocdata_getLocaleSeparator U_ICU_ENTRY_POINT_RENAME(ulocdata_getLocaleSeparator) -#define ulocdata_getMeasurementSystem U_ICU_ENTRY_POINT_RENAME(ulocdata_getMeasurementSystem) -#define ulocdata_getNoSubstitute U_ICU_ENTRY_POINT_RENAME(ulocdata_getNoSubstitute) -#define ulocdata_getPaperSize U_ICU_ENTRY_POINT_RENAME(ulocdata_getPaperSize) -#define ulocdata_open U_ICU_ENTRY_POINT_RENAME(ulocdata_open) -#define ulocdata_setNoSubstitute U_ICU_ENTRY_POINT_RENAME(ulocdata_setNoSubstitute) -#define ulocimp_getCountry U_ICU_ENTRY_POINT_RENAME(ulocimp_getCountry) -#define ulocimp_getLanguage U_ICU_ENTRY_POINT_RENAME(ulocimp_getLanguage) -#define ulocimp_getRegionForSupplementalData U_ICU_ENTRY_POINT_RENAME(ulocimp_getRegionForSupplementalData) -#define ulocimp_getScript U_ICU_ENTRY_POINT_RENAME(ulocimp_getScript) -#define ulocimp_toBcpKey U_ICU_ENTRY_POINT_RENAME(ulocimp_toBcpKey) -#define ulocimp_toBcpType U_ICU_ENTRY_POINT_RENAME(ulocimp_toBcpType) -#define ulocimp_toLegacyKey U_ICU_ENTRY_POINT_RENAME(ulocimp_toLegacyKey) -#define ulocimp_toLegacyType U_ICU_ENTRY_POINT_RENAME(ulocimp_toLegacyType) -#define ultag_isUnicodeLocaleKey U_ICU_ENTRY_POINT_RENAME(ultag_isUnicodeLocaleKey) -#define ultag_isUnicodeLocaleType U_ICU_ENTRY_POINT_RENAME(ultag_isUnicodeLocaleType) -#define umsg_applyPattern U_ICU_ENTRY_POINT_RENAME(umsg_applyPattern) -#define umsg_autoQuoteApostrophe U_ICU_ENTRY_POINT_RENAME(umsg_autoQuoteApostrophe) -#define umsg_clone U_ICU_ENTRY_POINT_RENAME(umsg_clone) -#define umsg_close U_ICU_ENTRY_POINT_RENAME(umsg_close) -#define umsg_format U_ICU_ENTRY_POINT_RENAME(umsg_format) -#define umsg_getLocale U_ICU_ENTRY_POINT_RENAME(umsg_getLocale) -#define umsg_open U_ICU_ENTRY_POINT_RENAME(umsg_open) -#define umsg_parse U_ICU_ENTRY_POINT_RENAME(umsg_parse) -#define umsg_setLocale U_ICU_ENTRY_POINT_RENAME(umsg_setLocale) -#define umsg_toPattern U_ICU_ENTRY_POINT_RENAME(umsg_toPattern) -#define umsg_vformat U_ICU_ENTRY_POINT_RENAME(umsg_vformat) -#define umsg_vparse U_ICU_ENTRY_POINT_RENAME(umsg_vparse) -#define umtx_condBroadcast U_ICU_ENTRY_POINT_RENAME(umtx_condBroadcast) -#define umtx_condSignal U_ICU_ENTRY_POINT_RENAME(umtx_condSignal) -#define umtx_condWait U_ICU_ENTRY_POINT_RENAME(umtx_condWait) -#define umtx_lock U_ICU_ENTRY_POINT_RENAME(umtx_lock) -#define umtx_unlock U_ICU_ENTRY_POINT_RENAME(umtx_unlock) -#define uniset_getUnicode32Instance U_ICU_ENTRY_POINT_RENAME(uniset_getUnicode32Instance) -#define unorm2_append U_ICU_ENTRY_POINT_RENAME(unorm2_append) -#define unorm2_close U_ICU_ENTRY_POINT_RENAME(unorm2_close) -#define unorm2_composePair U_ICU_ENTRY_POINT_RENAME(unorm2_composePair) -#define unorm2_getCombiningClass U_ICU_ENTRY_POINT_RENAME(unorm2_getCombiningClass) -#define unorm2_getDecomposition U_ICU_ENTRY_POINT_RENAME(unorm2_getDecomposition) -#define unorm2_getInstance U_ICU_ENTRY_POINT_RENAME(unorm2_getInstance) -#define unorm2_getNFCInstance U_ICU_ENTRY_POINT_RENAME(unorm2_getNFCInstance) -#define unorm2_getNFDInstance U_ICU_ENTRY_POINT_RENAME(unorm2_getNFDInstance) -#define unorm2_getNFKCCasefoldInstance U_ICU_ENTRY_POINT_RENAME(unorm2_getNFKCCasefoldInstance) -#define unorm2_getNFKCInstance U_ICU_ENTRY_POINT_RENAME(unorm2_getNFKCInstance) -#define unorm2_getNFKDInstance U_ICU_ENTRY_POINT_RENAME(unorm2_getNFKDInstance) -#define unorm2_getRawDecomposition U_ICU_ENTRY_POINT_RENAME(unorm2_getRawDecomposition) -#define unorm2_hasBoundaryAfter U_ICU_ENTRY_POINT_RENAME(unorm2_hasBoundaryAfter) -#define unorm2_hasBoundaryBefore U_ICU_ENTRY_POINT_RENAME(unorm2_hasBoundaryBefore) -#define unorm2_isInert U_ICU_ENTRY_POINT_RENAME(unorm2_isInert) -#define unorm2_isNormalized U_ICU_ENTRY_POINT_RENAME(unorm2_isNormalized) -#define unorm2_normalize U_ICU_ENTRY_POINT_RENAME(unorm2_normalize) -#define unorm2_normalizeSecondAndAppend U_ICU_ENTRY_POINT_RENAME(unorm2_normalizeSecondAndAppend) -#define unorm2_openFiltered U_ICU_ENTRY_POINT_RENAME(unorm2_openFiltered) -#define unorm2_quickCheck U_ICU_ENTRY_POINT_RENAME(unorm2_quickCheck) -#define unorm2_spanQuickCheckYes U_ICU_ENTRY_POINT_RENAME(unorm2_spanQuickCheckYes) -#define unorm2_swap U_ICU_ENTRY_POINT_RENAME(unorm2_swap) -#define unorm_compare U_ICU_ENTRY_POINT_RENAME(unorm_compare) -#define unorm_concatenate U_ICU_ENTRY_POINT_RENAME(unorm_concatenate) -#define unorm_getFCD16 U_ICU_ENTRY_POINT_RENAME(unorm_getFCD16) -#define unorm_getQuickCheck U_ICU_ENTRY_POINT_RENAME(unorm_getQuickCheck) -#define unorm_isNormalized U_ICU_ENTRY_POINT_RENAME(unorm_isNormalized) -#define unorm_isNormalizedWithOptions U_ICU_ENTRY_POINT_RENAME(unorm_isNormalizedWithOptions) -#define unorm_next U_ICU_ENTRY_POINT_RENAME(unorm_next) -#define unorm_normalize U_ICU_ENTRY_POINT_RENAME(unorm_normalize) -#define unorm_previous U_ICU_ENTRY_POINT_RENAME(unorm_previous) -#define unorm_quickCheck U_ICU_ENTRY_POINT_RENAME(unorm_quickCheck) -#define unorm_quickCheckWithOptions U_ICU_ENTRY_POINT_RENAME(unorm_quickCheckWithOptions) -#define unum_applyPattern U_ICU_ENTRY_POINT_RENAME(unum_applyPattern) -#define unum_clone U_ICU_ENTRY_POINT_RENAME(unum_clone) -#define unum_close U_ICU_ENTRY_POINT_RENAME(unum_close) -#define unum_countAvailable U_ICU_ENTRY_POINT_RENAME(unum_countAvailable) -#define unum_format U_ICU_ENTRY_POINT_RENAME(unum_format) -#define unum_formatDecimal U_ICU_ENTRY_POINT_RENAME(unum_formatDecimal) -#define unum_formatDouble U_ICU_ENTRY_POINT_RENAME(unum_formatDouble) -#define unum_formatDoubleCurrency U_ICU_ENTRY_POINT_RENAME(unum_formatDoubleCurrency) -#define unum_formatInt64 U_ICU_ENTRY_POINT_RENAME(unum_formatInt64) -#define unum_formatUFormattable U_ICU_ENTRY_POINT_RENAME(unum_formatUFormattable) -#define unum_getAttribute U_ICU_ENTRY_POINT_RENAME(unum_getAttribute) -#define unum_getAvailable U_ICU_ENTRY_POINT_RENAME(unum_getAvailable) -#define unum_getContext U_ICU_ENTRY_POINT_RENAME(unum_getContext) -#define unum_getDoubleAttribute U_ICU_ENTRY_POINT_RENAME(unum_getDoubleAttribute) -#define unum_getLocaleByType U_ICU_ENTRY_POINT_RENAME(unum_getLocaleByType) -#define unum_getSymbol U_ICU_ENTRY_POINT_RENAME(unum_getSymbol) -#define unum_getTextAttribute U_ICU_ENTRY_POINT_RENAME(unum_getTextAttribute) -#define unum_open U_ICU_ENTRY_POINT_RENAME(unum_open) -#define unum_parse U_ICU_ENTRY_POINT_RENAME(unum_parse) -#define unum_parseDecimal U_ICU_ENTRY_POINT_RENAME(unum_parseDecimal) -#define unum_parseDouble U_ICU_ENTRY_POINT_RENAME(unum_parseDouble) -#define unum_parseDoubleCurrency U_ICU_ENTRY_POINT_RENAME(unum_parseDoubleCurrency) -#define unum_parseInt64 U_ICU_ENTRY_POINT_RENAME(unum_parseInt64) -#define unum_parseToUFormattable U_ICU_ENTRY_POINT_RENAME(unum_parseToUFormattable) -#define unum_setAttribute U_ICU_ENTRY_POINT_RENAME(unum_setAttribute) -#define unum_setContext U_ICU_ENTRY_POINT_RENAME(unum_setContext) -#define unum_setDoubleAttribute U_ICU_ENTRY_POINT_RENAME(unum_setDoubleAttribute) -#define unum_setSymbol U_ICU_ENTRY_POINT_RENAME(unum_setSymbol) -#define unum_setTextAttribute U_ICU_ENTRY_POINT_RENAME(unum_setTextAttribute) -#define unum_toPattern U_ICU_ENTRY_POINT_RENAME(unum_toPattern) -#define unumsys_close U_ICU_ENTRY_POINT_RENAME(unumsys_close) -#define unumsys_getDescription U_ICU_ENTRY_POINT_RENAME(unumsys_getDescription) -#define unumsys_getName U_ICU_ENTRY_POINT_RENAME(unumsys_getName) -#define unumsys_getRadix U_ICU_ENTRY_POINT_RENAME(unumsys_getRadix) -#define unumsys_isAlgorithmic U_ICU_ENTRY_POINT_RENAME(unumsys_isAlgorithmic) -#define unumsys_open U_ICU_ENTRY_POINT_RENAME(unumsys_open) -#define unumsys_openAvailableNames U_ICU_ENTRY_POINT_RENAME(unumsys_openAvailableNames) -#define unumsys_openByName U_ICU_ENTRY_POINT_RENAME(unumsys_openByName) -#define uplrules_close U_ICU_ENTRY_POINT_RENAME(uplrules_close) -#define uplrules_open U_ICU_ENTRY_POINT_RENAME(uplrules_open) -#define uplrules_openForType U_ICU_ENTRY_POINT_RENAME(uplrules_openForType) -#define uplrules_select U_ICU_ENTRY_POINT_RENAME(uplrules_select) -#define uplug_closeLibrary U_ICU_ENTRY_POINT_RENAME(uplug_closeLibrary) -#define uplug_findLibrary U_ICU_ENTRY_POINT_RENAME(uplug_findLibrary) -#define uplug_getConfiguration U_ICU_ENTRY_POINT_RENAME(uplug_getConfiguration) -#define uplug_getContext U_ICU_ENTRY_POINT_RENAME(uplug_getContext) -#define uplug_getCurrentLevel U_ICU_ENTRY_POINT_RENAME(uplug_getCurrentLevel) -#define uplug_getLibrary U_ICU_ENTRY_POINT_RENAME(uplug_getLibrary) -#define uplug_getLibraryName U_ICU_ENTRY_POINT_RENAME(uplug_getLibraryName) -#define uplug_getPlugInternal U_ICU_ENTRY_POINT_RENAME(uplug_getPlugInternal) -#define uplug_getPlugLevel U_ICU_ENTRY_POINT_RENAME(uplug_getPlugLevel) -#define uplug_getPlugLoadStatus U_ICU_ENTRY_POINT_RENAME(uplug_getPlugLoadStatus) -#define uplug_getPlugName U_ICU_ENTRY_POINT_RENAME(uplug_getPlugName) -#define uplug_getPluginFile U_ICU_ENTRY_POINT_RENAME(uplug_getPluginFile) -#define uplug_getSymbolName U_ICU_ENTRY_POINT_RENAME(uplug_getSymbolName) -#define uplug_init U_ICU_ENTRY_POINT_RENAME(uplug_init) -#define uplug_loadPlugFromEntrypoint U_ICU_ENTRY_POINT_RENAME(uplug_loadPlugFromEntrypoint) -#define uplug_loadPlugFromLibrary U_ICU_ENTRY_POINT_RENAME(uplug_loadPlugFromLibrary) -#define uplug_nextPlug U_ICU_ENTRY_POINT_RENAME(uplug_nextPlug) -#define uplug_openLibrary U_ICU_ENTRY_POINT_RENAME(uplug_openLibrary) -#define uplug_removePlug U_ICU_ENTRY_POINT_RENAME(uplug_removePlug) -#define uplug_setContext U_ICU_ENTRY_POINT_RENAME(uplug_setContext) -#define uplug_setPlugLevel U_ICU_ENTRY_POINT_RENAME(uplug_setPlugLevel) -#define uplug_setPlugName U_ICU_ENTRY_POINT_RENAME(uplug_setPlugName) -#define uplug_setPlugNoUnload U_ICU_ENTRY_POINT_RENAME(uplug_setPlugNoUnload) -#define uprops_getSource U_ICU_ENTRY_POINT_RENAME(uprops_getSource) -#define upropsvec_addPropertyStarts U_ICU_ENTRY_POINT_RENAME(upropsvec_addPropertyStarts) -#define uprv_aestrncpy U_ICU_ENTRY_POINT_RENAME(uprv_aestrncpy) -#define uprv_asciiFromEbcdic U_ICU_ENTRY_POINT_RENAME(uprv_asciiFromEbcdic) -#define uprv_asciitolower U_ICU_ENTRY_POINT_RENAME(uprv_asciitolower) -#define uprv_calloc U_ICU_ENTRY_POINT_RENAME(uprv_calloc) -#define uprv_ceil U_ICU_ENTRY_POINT_RENAME(uprv_ceil) -#define uprv_compareASCIIPropertyNames U_ICU_ENTRY_POINT_RENAME(uprv_compareASCIIPropertyNames) -#define uprv_compareEBCDICPropertyNames U_ICU_ENTRY_POINT_RENAME(uprv_compareEBCDICPropertyNames) -#define uprv_compareInvAscii U_ICU_ENTRY_POINT_RENAME(uprv_compareInvAscii) -#define uprv_compareInvEbcdic U_ICU_ENTRY_POINT_RENAME(uprv_compareInvEbcdic) -#define uprv_compareInvEbcdicAsAscii U_ICU_ENTRY_POINT_RENAME(uprv_compareInvEbcdicAsAscii) -#define uprv_convertToLCID U_ICU_ENTRY_POINT_RENAME(uprv_convertToLCID) -#define uprv_convertToPosix U_ICU_ENTRY_POINT_RENAME(uprv_convertToPosix) -#define uprv_copyAscii U_ICU_ENTRY_POINT_RENAME(uprv_copyAscii) -#define uprv_copyEbcdic U_ICU_ENTRY_POINT_RENAME(uprv_copyEbcdic) -#define uprv_decContextClearStatus U_ICU_ENTRY_POINT_RENAME(uprv_decContextClearStatus) -#define uprv_decContextDefault U_ICU_ENTRY_POINT_RENAME(uprv_decContextDefault) -#define uprv_decContextGetRounding U_ICU_ENTRY_POINT_RENAME(uprv_decContextGetRounding) -#define uprv_decContextGetStatus U_ICU_ENTRY_POINT_RENAME(uprv_decContextGetStatus) -#define uprv_decContextRestoreStatus U_ICU_ENTRY_POINT_RENAME(uprv_decContextRestoreStatus) -#define uprv_decContextSaveStatus U_ICU_ENTRY_POINT_RENAME(uprv_decContextSaveStatus) -#define uprv_decContextSetRounding U_ICU_ENTRY_POINT_RENAME(uprv_decContextSetRounding) -#define uprv_decContextSetStatus U_ICU_ENTRY_POINT_RENAME(uprv_decContextSetStatus) -#define uprv_decContextSetStatusFromString U_ICU_ENTRY_POINT_RENAME(uprv_decContextSetStatusFromString) -#define uprv_decContextSetStatusFromStringQuiet U_ICU_ENTRY_POINT_RENAME(uprv_decContextSetStatusFromStringQuiet) -#define uprv_decContextSetStatusQuiet U_ICU_ENTRY_POINT_RENAME(uprv_decContextSetStatusQuiet) -#define uprv_decContextStatusToString U_ICU_ENTRY_POINT_RENAME(uprv_decContextStatusToString) -#define uprv_decContextTestSavedStatus U_ICU_ENTRY_POINT_RENAME(uprv_decContextTestSavedStatus) -#define uprv_decContextTestStatus U_ICU_ENTRY_POINT_RENAME(uprv_decContextTestStatus) -#define uprv_decContextZeroStatus U_ICU_ENTRY_POINT_RENAME(uprv_decContextZeroStatus) -#define uprv_decNumberAbs U_ICU_ENTRY_POINT_RENAME(uprv_decNumberAbs) -#define uprv_decNumberAdd U_ICU_ENTRY_POINT_RENAME(uprv_decNumberAdd) -#define uprv_decNumberAnd U_ICU_ENTRY_POINT_RENAME(uprv_decNumberAnd) -#define uprv_decNumberClass U_ICU_ENTRY_POINT_RENAME(uprv_decNumberClass) -#define uprv_decNumberClassToString U_ICU_ENTRY_POINT_RENAME(uprv_decNumberClassToString) -#define uprv_decNumberCompare U_ICU_ENTRY_POINT_RENAME(uprv_decNumberCompare) -#define uprv_decNumberCompareSignal U_ICU_ENTRY_POINT_RENAME(uprv_decNumberCompareSignal) -#define uprv_decNumberCompareTotal U_ICU_ENTRY_POINT_RENAME(uprv_decNumberCompareTotal) -#define uprv_decNumberCompareTotalMag U_ICU_ENTRY_POINT_RENAME(uprv_decNumberCompareTotalMag) -#define uprv_decNumberCopy U_ICU_ENTRY_POINT_RENAME(uprv_decNumberCopy) -#define uprv_decNumberCopyAbs U_ICU_ENTRY_POINT_RENAME(uprv_decNumberCopyAbs) -#define uprv_decNumberCopyNegate U_ICU_ENTRY_POINT_RENAME(uprv_decNumberCopyNegate) -#define uprv_decNumberCopySign U_ICU_ENTRY_POINT_RENAME(uprv_decNumberCopySign) -#define uprv_decNumberDivide U_ICU_ENTRY_POINT_RENAME(uprv_decNumberDivide) -#define uprv_decNumberDivideInteger U_ICU_ENTRY_POINT_RENAME(uprv_decNumberDivideInteger) -#define uprv_decNumberExp U_ICU_ENTRY_POINT_RENAME(uprv_decNumberExp) -#define uprv_decNumberFMA U_ICU_ENTRY_POINT_RENAME(uprv_decNumberFMA) -#define uprv_decNumberFromInt32 U_ICU_ENTRY_POINT_RENAME(uprv_decNumberFromInt32) -#define uprv_decNumberFromString U_ICU_ENTRY_POINT_RENAME(uprv_decNumberFromString) -#define uprv_decNumberFromUInt32 U_ICU_ENTRY_POINT_RENAME(uprv_decNumberFromUInt32) -#define uprv_decNumberGetBCD U_ICU_ENTRY_POINT_RENAME(uprv_decNumberGetBCD) -#define uprv_decNumberInvert U_ICU_ENTRY_POINT_RENAME(uprv_decNumberInvert) -#define uprv_decNumberIsNormal U_ICU_ENTRY_POINT_RENAME(uprv_decNumberIsNormal) -#define uprv_decNumberIsSubnormal U_ICU_ENTRY_POINT_RENAME(uprv_decNumberIsSubnormal) -#define uprv_decNumberLn U_ICU_ENTRY_POINT_RENAME(uprv_decNumberLn) -#define uprv_decNumberLog10 U_ICU_ENTRY_POINT_RENAME(uprv_decNumberLog10) -#define uprv_decNumberLogB U_ICU_ENTRY_POINT_RENAME(uprv_decNumberLogB) -#define uprv_decNumberMax U_ICU_ENTRY_POINT_RENAME(uprv_decNumberMax) -#define uprv_decNumberMaxMag U_ICU_ENTRY_POINT_RENAME(uprv_decNumberMaxMag) -#define uprv_decNumberMin U_ICU_ENTRY_POINT_RENAME(uprv_decNumberMin) -#define uprv_decNumberMinMag U_ICU_ENTRY_POINT_RENAME(uprv_decNumberMinMag) -#define uprv_decNumberMinus U_ICU_ENTRY_POINT_RENAME(uprv_decNumberMinus) -#define uprv_decNumberMultiply U_ICU_ENTRY_POINT_RENAME(uprv_decNumberMultiply) -#define uprv_decNumberNextMinus U_ICU_ENTRY_POINT_RENAME(uprv_decNumberNextMinus) -#define uprv_decNumberNextPlus U_ICU_ENTRY_POINT_RENAME(uprv_decNumberNextPlus) -#define uprv_decNumberNextToward U_ICU_ENTRY_POINT_RENAME(uprv_decNumberNextToward) -#define uprv_decNumberNormalize U_ICU_ENTRY_POINT_RENAME(uprv_decNumberNormalize) -#define uprv_decNumberOr U_ICU_ENTRY_POINT_RENAME(uprv_decNumberOr) -#define uprv_decNumberPlus U_ICU_ENTRY_POINT_RENAME(uprv_decNumberPlus) -#define uprv_decNumberPower U_ICU_ENTRY_POINT_RENAME(uprv_decNumberPower) -#define uprv_decNumberQuantize U_ICU_ENTRY_POINT_RENAME(uprv_decNumberQuantize) -#define uprv_decNumberReduce U_ICU_ENTRY_POINT_RENAME(uprv_decNumberReduce) -#define uprv_decNumberRemainder U_ICU_ENTRY_POINT_RENAME(uprv_decNumberRemainder) -#define uprv_decNumberRemainderNear U_ICU_ENTRY_POINT_RENAME(uprv_decNumberRemainderNear) -#define uprv_decNumberRescale U_ICU_ENTRY_POINT_RENAME(uprv_decNumberRescale) -#define uprv_decNumberRotate U_ICU_ENTRY_POINT_RENAME(uprv_decNumberRotate) -#define uprv_decNumberSameQuantum U_ICU_ENTRY_POINT_RENAME(uprv_decNumberSameQuantum) -#define uprv_decNumberScaleB U_ICU_ENTRY_POINT_RENAME(uprv_decNumberScaleB) -#define uprv_decNumberSetBCD U_ICU_ENTRY_POINT_RENAME(uprv_decNumberSetBCD) -#define uprv_decNumberShift U_ICU_ENTRY_POINT_RENAME(uprv_decNumberShift) -#define uprv_decNumberSquareRoot U_ICU_ENTRY_POINT_RENAME(uprv_decNumberSquareRoot) -#define uprv_decNumberSubtract U_ICU_ENTRY_POINT_RENAME(uprv_decNumberSubtract) -#define uprv_decNumberToEngString U_ICU_ENTRY_POINT_RENAME(uprv_decNumberToEngString) -#define uprv_decNumberToInt32 U_ICU_ENTRY_POINT_RENAME(uprv_decNumberToInt32) -#define uprv_decNumberToIntegralExact U_ICU_ENTRY_POINT_RENAME(uprv_decNumberToIntegralExact) -#define uprv_decNumberToIntegralValue U_ICU_ENTRY_POINT_RENAME(uprv_decNumberToIntegralValue) -#define uprv_decNumberToString U_ICU_ENTRY_POINT_RENAME(uprv_decNumberToString) -#define uprv_decNumberToUInt32 U_ICU_ENTRY_POINT_RENAME(uprv_decNumberToUInt32) -#define uprv_decNumberTrim U_ICU_ENTRY_POINT_RENAME(uprv_decNumberTrim) -#define uprv_decNumberVersion U_ICU_ENTRY_POINT_RENAME(uprv_decNumberVersion) -#define uprv_decNumberXor U_ICU_ENTRY_POINT_RENAME(uprv_decNumberXor) -#define uprv_decNumberZero U_ICU_ENTRY_POINT_RENAME(uprv_decNumberZero) -#define uprv_deleteConditionalCE32 U_ICU_ENTRY_POINT_RENAME(uprv_deleteConditionalCE32) -#define uprv_deleteUObject U_ICU_ENTRY_POINT_RENAME(uprv_deleteUObject) -#define uprv_dl_close U_ICU_ENTRY_POINT_RENAME(uprv_dl_close) -#define uprv_dl_open U_ICU_ENTRY_POINT_RENAME(uprv_dl_open) -#define uprv_dlsym_func U_ICU_ENTRY_POINT_RENAME(uprv_dlsym_func) -#define uprv_eastrncpy U_ICU_ENTRY_POINT_RENAME(uprv_eastrncpy) -#define uprv_ebcdicFromAscii U_ICU_ENTRY_POINT_RENAME(uprv_ebcdicFromAscii) -#define uprv_ebcdicToLowercaseAscii U_ICU_ENTRY_POINT_RENAME(uprv_ebcdicToLowercaseAscii) -#define uprv_ebcdictolower U_ICU_ENTRY_POINT_RENAME(uprv_ebcdictolower) -#define uprv_fabs U_ICU_ENTRY_POINT_RENAME(uprv_fabs) -#define uprv_floor U_ICU_ENTRY_POINT_RENAME(uprv_floor) -#define uprv_fmax U_ICU_ENTRY_POINT_RENAME(uprv_fmax) -#define uprv_fmin U_ICU_ENTRY_POINT_RENAME(uprv_fmin) -#define uprv_fmod U_ICU_ENTRY_POINT_RENAME(uprv_fmod) -#define uprv_free U_ICU_ENTRY_POINT_RENAME(uprv_free) -#define uprv_getCharNameCharacters U_ICU_ENTRY_POINT_RENAME(uprv_getCharNameCharacters) -#define uprv_getDefaultCodepage U_ICU_ENTRY_POINT_RENAME(uprv_getDefaultCodepage) -#define uprv_getDefaultLocaleID U_ICU_ENTRY_POINT_RENAME(uprv_getDefaultLocaleID) -#define uprv_getInfinity U_ICU_ENTRY_POINT_RENAME(uprv_getInfinity) -#define uprv_getMaxCharNameLength U_ICU_ENTRY_POINT_RENAME(uprv_getMaxCharNameLength) -#define uprv_getMaxValues U_ICU_ENTRY_POINT_RENAME(uprv_getMaxValues) -#define uprv_getNaN U_ICU_ENTRY_POINT_RENAME(uprv_getNaN) -#define uprv_getRawUTCtime U_ICU_ENTRY_POINT_RENAME(uprv_getRawUTCtime) -#define uprv_getStaticCurrencyName U_ICU_ENTRY_POINT_RENAME(uprv_getStaticCurrencyName) -#define uprv_getUTCtime U_ICU_ENTRY_POINT_RENAME(uprv_getUTCtime) -#define uprv_haveProperties U_ICU_ENTRY_POINT_RENAME(uprv_haveProperties) -#define uprv_int32Comparator U_ICU_ENTRY_POINT_RENAME(uprv_int32Comparator) -#define uprv_isASCIILetter U_ICU_ENTRY_POINT_RENAME(uprv_isASCIILetter) -#define uprv_isInfinite U_ICU_ENTRY_POINT_RENAME(uprv_isInfinite) -#define uprv_isInvariantString U_ICU_ENTRY_POINT_RENAME(uprv_isInvariantString) -#define uprv_isInvariantUString U_ICU_ENTRY_POINT_RENAME(uprv_isInvariantUString) -#define uprv_isNaN U_ICU_ENTRY_POINT_RENAME(uprv_isNaN) -#define uprv_isNegativeInfinity U_ICU_ENTRY_POINT_RENAME(uprv_isNegativeInfinity) -#define uprv_isPositiveInfinity U_ICU_ENTRY_POINT_RENAME(uprv_isPositiveInfinity) -#define uprv_itou U_ICU_ENTRY_POINT_RENAME(uprv_itou) -#define uprv_log U_ICU_ENTRY_POINT_RENAME(uprv_log) -#define uprv_malloc U_ICU_ENTRY_POINT_RENAME(uprv_malloc) -#define uprv_mapFile U_ICU_ENTRY_POINT_RENAME(uprv_mapFile) -#define uprv_max U_ICU_ENTRY_POINT_RENAME(uprv_max) -#define uprv_maxMantissa U_ICU_ENTRY_POINT_RENAME(uprv_maxMantissa) -#define uprv_maximumPtr U_ICU_ENTRY_POINT_RENAME(uprv_maximumPtr) -#define uprv_min U_ICU_ENTRY_POINT_RENAME(uprv_min) -#define uprv_modf U_ICU_ENTRY_POINT_RENAME(uprv_modf) -#define uprv_parseCurrency U_ICU_ENTRY_POINT_RENAME(uprv_parseCurrency) -#define uprv_pathIsAbsolute U_ICU_ENTRY_POINT_RENAME(uprv_pathIsAbsolute) -#define uprv_pow U_ICU_ENTRY_POINT_RENAME(uprv_pow) -#define uprv_pow10 U_ICU_ENTRY_POINT_RENAME(uprv_pow10) -#define uprv_realloc U_ICU_ENTRY_POINT_RENAME(uprv_realloc) -#define uprv_round U_ICU_ENTRY_POINT_RENAME(uprv_round) -#define uprv_sortArray U_ICU_ENTRY_POINT_RENAME(uprv_sortArray) -#define uprv_stableBinarySearch U_ICU_ENTRY_POINT_RENAME(uprv_stableBinarySearch) -#define uprv_strCompare U_ICU_ENTRY_POINT_RENAME(uprv_strCompare) -#define uprv_strdup U_ICU_ENTRY_POINT_RENAME(uprv_strdup) -#define uprv_stricmp U_ICU_ENTRY_POINT_RENAME(uprv_stricmp) -#define uprv_strndup U_ICU_ENTRY_POINT_RENAME(uprv_strndup) -#define uprv_strnicmp U_ICU_ENTRY_POINT_RENAME(uprv_strnicmp) -#define uprv_syntaxError U_ICU_ENTRY_POINT_RENAME(uprv_syntaxError) -#define uprv_timezone U_ICU_ENTRY_POINT_RENAME(uprv_timezone) -#define uprv_toupper U_ICU_ENTRY_POINT_RENAME(uprv_toupper) -#define uprv_trunc U_ICU_ENTRY_POINT_RENAME(uprv_trunc) -#define uprv_tzname U_ICU_ENTRY_POINT_RENAME(uprv_tzname) -#define uprv_tzname_clear_cache U_ICU_ENTRY_POINT_RENAME(uprv_tzname_clear_cache) -#define uprv_tzset U_ICU_ENTRY_POINT_RENAME(uprv_tzset) -#define uprv_uint16Comparator U_ICU_ENTRY_POINT_RENAME(uprv_uint16Comparator) -#define uprv_uint32Comparator U_ICU_ENTRY_POINT_RENAME(uprv_uint32Comparator) -#define uprv_unmapFile U_ICU_ENTRY_POINT_RENAME(uprv_unmapFile) -#define upvec_cloneArray U_ICU_ENTRY_POINT_RENAME(upvec_cloneArray) -#define upvec_close U_ICU_ENTRY_POINT_RENAME(upvec_close) -#define upvec_compact U_ICU_ENTRY_POINT_RENAME(upvec_compact) -#define upvec_compactToUTrie2Handler U_ICU_ENTRY_POINT_RENAME(upvec_compactToUTrie2Handler) -#define upvec_compactToUTrie2WithRowIndexes U_ICU_ENTRY_POINT_RENAME(upvec_compactToUTrie2WithRowIndexes) -#define upvec_getArray U_ICU_ENTRY_POINT_RENAME(upvec_getArray) -#define upvec_getRow U_ICU_ENTRY_POINT_RENAME(upvec_getRow) -#define upvec_getValue U_ICU_ENTRY_POINT_RENAME(upvec_getValue) -#define upvec_open U_ICU_ENTRY_POINT_RENAME(upvec_open) -#define upvec_setValue U_ICU_ENTRY_POINT_RENAME(upvec_setValue) -#define uregex_appendReplacement U_ICU_ENTRY_POINT_RENAME(uregex_appendReplacement) -#define uregex_appendReplacementUText U_ICU_ENTRY_POINT_RENAME(uregex_appendReplacementUText) -#define uregex_appendTail U_ICU_ENTRY_POINT_RENAME(uregex_appendTail) -#define uregex_appendTailUText U_ICU_ENTRY_POINT_RENAME(uregex_appendTailUText) -#define uregex_clone U_ICU_ENTRY_POINT_RENAME(uregex_clone) -#define uregex_close U_ICU_ENTRY_POINT_RENAME(uregex_close) -#define uregex_end U_ICU_ENTRY_POINT_RENAME(uregex_end) -#define uregex_end64 U_ICU_ENTRY_POINT_RENAME(uregex_end64) -#define uregex_find U_ICU_ENTRY_POINT_RENAME(uregex_find) -#define uregex_find64 U_ICU_ENTRY_POINT_RENAME(uregex_find64) -#define uregex_findNext U_ICU_ENTRY_POINT_RENAME(uregex_findNext) -#define uregex_flags U_ICU_ENTRY_POINT_RENAME(uregex_flags) -#define uregex_getFindProgressCallback U_ICU_ENTRY_POINT_RENAME(uregex_getFindProgressCallback) -#define uregex_getMatchCallback U_ICU_ENTRY_POINT_RENAME(uregex_getMatchCallback) -#define uregex_getStackLimit U_ICU_ENTRY_POINT_RENAME(uregex_getStackLimit) -#define uregex_getText U_ICU_ENTRY_POINT_RENAME(uregex_getText) -#define uregex_getTimeLimit U_ICU_ENTRY_POINT_RENAME(uregex_getTimeLimit) -#define uregex_getUText U_ICU_ENTRY_POINT_RENAME(uregex_getUText) -#define uregex_group U_ICU_ENTRY_POINT_RENAME(uregex_group) -#define uregex_groupCount U_ICU_ENTRY_POINT_RENAME(uregex_groupCount) -#define uregex_groupNumberFromCName U_ICU_ENTRY_POINT_RENAME(uregex_groupNumberFromCName) -#define uregex_groupNumberFromName U_ICU_ENTRY_POINT_RENAME(uregex_groupNumberFromName) -#define uregex_groupUText U_ICU_ENTRY_POINT_RENAME(uregex_groupUText) -#define uregex_hasAnchoringBounds U_ICU_ENTRY_POINT_RENAME(uregex_hasAnchoringBounds) -#define uregex_hasTransparentBounds U_ICU_ENTRY_POINT_RENAME(uregex_hasTransparentBounds) -#define uregex_hitEnd U_ICU_ENTRY_POINT_RENAME(uregex_hitEnd) -#define uregex_lookingAt U_ICU_ENTRY_POINT_RENAME(uregex_lookingAt) -#define uregex_lookingAt64 U_ICU_ENTRY_POINT_RENAME(uregex_lookingAt64) -#define uregex_matches U_ICU_ENTRY_POINT_RENAME(uregex_matches) -#define uregex_matches64 U_ICU_ENTRY_POINT_RENAME(uregex_matches64) -#define uregex_open U_ICU_ENTRY_POINT_RENAME(uregex_open) -#define uregex_openC U_ICU_ENTRY_POINT_RENAME(uregex_openC) -#define uregex_openUText U_ICU_ENTRY_POINT_RENAME(uregex_openUText) -#define uregex_pattern U_ICU_ENTRY_POINT_RENAME(uregex_pattern) -#define uregex_patternUText U_ICU_ENTRY_POINT_RENAME(uregex_patternUText) -#define uregex_refreshUText U_ICU_ENTRY_POINT_RENAME(uregex_refreshUText) -#define uregex_regionEnd U_ICU_ENTRY_POINT_RENAME(uregex_regionEnd) -#define uregex_regionEnd64 U_ICU_ENTRY_POINT_RENAME(uregex_regionEnd64) -#define uregex_regionStart U_ICU_ENTRY_POINT_RENAME(uregex_regionStart) -#define uregex_regionStart64 U_ICU_ENTRY_POINT_RENAME(uregex_regionStart64) -#define uregex_replaceAll U_ICU_ENTRY_POINT_RENAME(uregex_replaceAll) -#define uregex_replaceAllUText U_ICU_ENTRY_POINT_RENAME(uregex_replaceAllUText) -#define uregex_replaceFirst U_ICU_ENTRY_POINT_RENAME(uregex_replaceFirst) -#define uregex_replaceFirstUText U_ICU_ENTRY_POINT_RENAME(uregex_replaceFirstUText) -#define uregex_requireEnd U_ICU_ENTRY_POINT_RENAME(uregex_requireEnd) -#define uregex_reset U_ICU_ENTRY_POINT_RENAME(uregex_reset) -#define uregex_reset64 U_ICU_ENTRY_POINT_RENAME(uregex_reset64) -#define uregex_setFindProgressCallback U_ICU_ENTRY_POINT_RENAME(uregex_setFindProgressCallback) -#define uregex_setMatchCallback U_ICU_ENTRY_POINT_RENAME(uregex_setMatchCallback) -#define uregex_setRegion U_ICU_ENTRY_POINT_RENAME(uregex_setRegion) -#define uregex_setRegion64 U_ICU_ENTRY_POINT_RENAME(uregex_setRegion64) -#define uregex_setRegionAndStart U_ICU_ENTRY_POINT_RENAME(uregex_setRegionAndStart) -#define uregex_setStackLimit U_ICU_ENTRY_POINT_RENAME(uregex_setStackLimit) -#define uregex_setText U_ICU_ENTRY_POINT_RENAME(uregex_setText) -#define uregex_setTimeLimit U_ICU_ENTRY_POINT_RENAME(uregex_setTimeLimit) -#define uregex_setUText U_ICU_ENTRY_POINT_RENAME(uregex_setUText) -#define uregex_split U_ICU_ENTRY_POINT_RENAME(uregex_split) -#define uregex_splitUText U_ICU_ENTRY_POINT_RENAME(uregex_splitUText) -#define uregex_start U_ICU_ENTRY_POINT_RENAME(uregex_start) -#define uregex_start64 U_ICU_ENTRY_POINT_RENAME(uregex_start64) -#define uregex_ucstr_unescape_charAt U_ICU_ENTRY_POINT_RENAME(uregex_ucstr_unescape_charAt) -#define uregex_useAnchoringBounds U_ICU_ENTRY_POINT_RENAME(uregex_useAnchoringBounds) -#define uregex_useTransparentBounds U_ICU_ENTRY_POINT_RENAME(uregex_useTransparentBounds) -#define uregex_utext_unescape_charAt U_ICU_ENTRY_POINT_RENAME(uregex_utext_unescape_charAt) -#define uregion_areEqual U_ICU_ENTRY_POINT_RENAME(uregion_areEqual) -#define uregion_contains U_ICU_ENTRY_POINT_RENAME(uregion_contains) -#define uregion_getAvailable U_ICU_ENTRY_POINT_RENAME(uregion_getAvailable) -#define uregion_getContainedRegions U_ICU_ENTRY_POINT_RENAME(uregion_getContainedRegions) -#define uregion_getContainedRegionsOfType U_ICU_ENTRY_POINT_RENAME(uregion_getContainedRegionsOfType) -#define uregion_getContainingRegion U_ICU_ENTRY_POINT_RENAME(uregion_getContainingRegion) -#define uregion_getContainingRegionOfType U_ICU_ENTRY_POINT_RENAME(uregion_getContainingRegionOfType) -#define uregion_getNumericCode U_ICU_ENTRY_POINT_RENAME(uregion_getNumericCode) -#define uregion_getPreferredValues U_ICU_ENTRY_POINT_RENAME(uregion_getPreferredValues) -#define uregion_getRegionCode U_ICU_ENTRY_POINT_RENAME(uregion_getRegionCode) -#define uregion_getRegionFromCode U_ICU_ENTRY_POINT_RENAME(uregion_getRegionFromCode) -#define uregion_getRegionFromNumericCode U_ICU_ENTRY_POINT_RENAME(uregion_getRegionFromNumericCode) -#define uregion_getType U_ICU_ENTRY_POINT_RENAME(uregion_getType) -#define ureldatefmt_close U_ICU_ENTRY_POINT_RENAME(ureldatefmt_close) -#define ureldatefmt_combineDateAndTime U_ICU_ENTRY_POINT_RENAME(ureldatefmt_combineDateAndTime) -#define ureldatefmt_format U_ICU_ENTRY_POINT_RENAME(ureldatefmt_format) -#define ureldatefmt_formatNumeric U_ICU_ENTRY_POINT_RENAME(ureldatefmt_formatNumeric) -#define ureldatefmt_open U_ICU_ENTRY_POINT_RENAME(ureldatefmt_open) -#define ures_close U_ICU_ENTRY_POINT_RENAME(ures_close) -#define ures_copyResb U_ICU_ENTRY_POINT_RENAME(ures_copyResb) -#define ures_countArrayItems U_ICU_ENTRY_POINT_RENAME(ures_countArrayItems) -#define ures_findResource U_ICU_ENTRY_POINT_RENAME(ures_findResource) -#define ures_findSubResource U_ICU_ENTRY_POINT_RENAME(ures_findSubResource) -#define ures_getAllItemsWithFallback U_ICU_ENTRY_POINT_RENAME(ures_getAllItemsWithFallback) -#define ures_getBinary U_ICU_ENTRY_POINT_RENAME(ures_getBinary) -#define ures_getByIndex U_ICU_ENTRY_POINT_RENAME(ures_getByIndex) -#define ures_getByKey U_ICU_ENTRY_POINT_RENAME(ures_getByKey) -#define ures_getByKeyWithFallback U_ICU_ENTRY_POINT_RENAME(ures_getByKeyWithFallback) -#define ures_getFunctionalEquivalent U_ICU_ENTRY_POINT_RENAME(ures_getFunctionalEquivalent) -#define ures_getInt U_ICU_ENTRY_POINT_RENAME(ures_getInt) -#define ures_getIntVector U_ICU_ENTRY_POINT_RENAME(ures_getIntVector) -#define ures_getKey U_ICU_ENTRY_POINT_RENAME(ures_getKey) -#define ures_getKeywordValues U_ICU_ENTRY_POINT_RENAME(ures_getKeywordValues) -#define ures_getLocale U_ICU_ENTRY_POINT_RENAME(ures_getLocale) -#define ures_getLocaleByType U_ICU_ENTRY_POINT_RENAME(ures_getLocaleByType) -#define ures_getLocaleInternal U_ICU_ENTRY_POINT_RENAME(ures_getLocaleInternal) -#define ures_getName U_ICU_ENTRY_POINT_RENAME(ures_getName) -#define ures_getNextResource U_ICU_ENTRY_POINT_RENAME(ures_getNextResource) -#define ures_getNextString U_ICU_ENTRY_POINT_RENAME(ures_getNextString) -#define ures_getSize U_ICU_ENTRY_POINT_RENAME(ures_getSize) -#define ures_getString U_ICU_ENTRY_POINT_RENAME(ures_getString) -#define ures_getStringByIndex U_ICU_ENTRY_POINT_RENAME(ures_getStringByIndex) -#define ures_getStringByKey U_ICU_ENTRY_POINT_RENAME(ures_getStringByKey) -#define ures_getStringByKeyWithFallback U_ICU_ENTRY_POINT_RENAME(ures_getStringByKeyWithFallback) -#define ures_getType U_ICU_ENTRY_POINT_RENAME(ures_getType) -#define ures_getUInt U_ICU_ENTRY_POINT_RENAME(ures_getUInt) -#define ures_getUTF8String U_ICU_ENTRY_POINT_RENAME(ures_getUTF8String) -#define ures_getUTF8StringByIndex U_ICU_ENTRY_POINT_RENAME(ures_getUTF8StringByIndex) -#define ures_getUTF8StringByKey U_ICU_ENTRY_POINT_RENAME(ures_getUTF8StringByKey) -#define ures_getVersion U_ICU_ENTRY_POINT_RENAME(ures_getVersion) -#define ures_getVersionByKey U_ICU_ENTRY_POINT_RENAME(ures_getVersionByKey) -#define ures_getVersionNumber U_ICU_ENTRY_POINT_RENAME(ures_getVersionNumber) -#define ures_getVersionNumberInternal U_ICU_ENTRY_POINT_RENAME(ures_getVersionNumberInternal) -#define ures_hasNext U_ICU_ENTRY_POINT_RENAME(ures_hasNext) -#define ures_initStackObject U_ICU_ENTRY_POINT_RENAME(ures_initStackObject) -#define ures_open U_ICU_ENTRY_POINT_RENAME(ures_open) -#define ures_openAvailableLocales U_ICU_ENTRY_POINT_RENAME(ures_openAvailableLocales) -#define ures_openDirect U_ICU_ENTRY_POINT_RENAME(ures_openDirect) -#define ures_openFillIn U_ICU_ENTRY_POINT_RENAME(ures_openFillIn) -#define ures_openNoDefault U_ICU_ENTRY_POINT_RENAME(ures_openNoDefault) -#define ures_openU U_ICU_ENTRY_POINT_RENAME(ures_openU) -#define ures_resetIterator U_ICU_ENTRY_POINT_RENAME(ures_resetIterator) -#define ures_swap U_ICU_ENTRY_POINT_RENAME(ures_swap) -#define uscript_breaksBetweenLetters U_ICU_ENTRY_POINT_RENAME(uscript_breaksBetweenLetters) -#define uscript_closeRun U_ICU_ENTRY_POINT_RENAME(uscript_closeRun) -#define uscript_getCode U_ICU_ENTRY_POINT_RENAME(uscript_getCode) -#define uscript_getName U_ICU_ENTRY_POINT_RENAME(uscript_getName) -#define uscript_getSampleString U_ICU_ENTRY_POINT_RENAME(uscript_getSampleString) -#define uscript_getSampleUnicodeString U_ICU_ENTRY_POINT_RENAME(uscript_getSampleUnicodeString) -#define uscript_getScript U_ICU_ENTRY_POINT_RENAME(uscript_getScript) -#define uscript_getScriptExtensions U_ICU_ENTRY_POINT_RENAME(uscript_getScriptExtensions) -#define uscript_getShortName U_ICU_ENTRY_POINT_RENAME(uscript_getShortName) -#define uscript_getUsage U_ICU_ENTRY_POINT_RENAME(uscript_getUsage) -#define uscript_hasScript U_ICU_ENTRY_POINT_RENAME(uscript_hasScript) -#define uscript_isCased U_ICU_ENTRY_POINT_RENAME(uscript_isCased) -#define uscript_isRightToLeft U_ICU_ENTRY_POINT_RENAME(uscript_isRightToLeft) -#define uscript_nextRun U_ICU_ENTRY_POINT_RENAME(uscript_nextRun) -#define uscript_openRun U_ICU_ENTRY_POINT_RENAME(uscript_openRun) -#define uscript_resetRun U_ICU_ENTRY_POINT_RENAME(uscript_resetRun) -#define uscript_setRunText U_ICU_ENTRY_POINT_RENAME(uscript_setRunText) -#define usearch_close U_ICU_ENTRY_POINT_RENAME(usearch_close) -#define usearch_first U_ICU_ENTRY_POINT_RENAME(usearch_first) -#define usearch_following U_ICU_ENTRY_POINT_RENAME(usearch_following) -#define usearch_getAttribute U_ICU_ENTRY_POINT_RENAME(usearch_getAttribute) -#define usearch_getBreakIterator U_ICU_ENTRY_POINT_RENAME(usearch_getBreakIterator) -#define usearch_getCollator U_ICU_ENTRY_POINT_RENAME(usearch_getCollator) -#define usearch_getMatchedLength U_ICU_ENTRY_POINT_RENAME(usearch_getMatchedLength) -#define usearch_getMatchedStart U_ICU_ENTRY_POINT_RENAME(usearch_getMatchedStart) -#define usearch_getMatchedText U_ICU_ENTRY_POINT_RENAME(usearch_getMatchedText) -#define usearch_getOffset U_ICU_ENTRY_POINT_RENAME(usearch_getOffset) -#define usearch_getPattern U_ICU_ENTRY_POINT_RENAME(usearch_getPattern) -#define usearch_getText U_ICU_ENTRY_POINT_RENAME(usearch_getText) -#define usearch_handleNextCanonical U_ICU_ENTRY_POINT_RENAME(usearch_handleNextCanonical) -#define usearch_handleNextExact U_ICU_ENTRY_POINT_RENAME(usearch_handleNextExact) -#define usearch_handlePreviousCanonical U_ICU_ENTRY_POINT_RENAME(usearch_handlePreviousCanonical) -#define usearch_handlePreviousExact U_ICU_ENTRY_POINT_RENAME(usearch_handlePreviousExact) -#define usearch_last U_ICU_ENTRY_POINT_RENAME(usearch_last) -#define usearch_next U_ICU_ENTRY_POINT_RENAME(usearch_next) -#define usearch_open U_ICU_ENTRY_POINT_RENAME(usearch_open) -#define usearch_openFromCollator U_ICU_ENTRY_POINT_RENAME(usearch_openFromCollator) -#define usearch_preceding U_ICU_ENTRY_POINT_RENAME(usearch_preceding) -#define usearch_previous U_ICU_ENTRY_POINT_RENAME(usearch_previous) -#define usearch_reset U_ICU_ENTRY_POINT_RENAME(usearch_reset) -#define usearch_search U_ICU_ENTRY_POINT_RENAME(usearch_search) -#define usearch_searchBackwards U_ICU_ENTRY_POINT_RENAME(usearch_searchBackwards) -#define usearch_setAttribute U_ICU_ENTRY_POINT_RENAME(usearch_setAttribute) -#define usearch_setBreakIterator U_ICU_ENTRY_POINT_RENAME(usearch_setBreakIterator) -#define usearch_setCollator U_ICU_ENTRY_POINT_RENAME(usearch_setCollator) -#define usearch_setOffset U_ICU_ENTRY_POINT_RENAME(usearch_setOffset) -#define usearch_setPattern U_ICU_ENTRY_POINT_RENAME(usearch_setPattern) -#define usearch_setText U_ICU_ENTRY_POINT_RENAME(usearch_setText) -#define uset_add U_ICU_ENTRY_POINT_RENAME(uset_add) -#define uset_addAll U_ICU_ENTRY_POINT_RENAME(uset_addAll) -#define uset_addAllCodePoints U_ICU_ENTRY_POINT_RENAME(uset_addAllCodePoints) -#define uset_addRange U_ICU_ENTRY_POINT_RENAME(uset_addRange) -#define uset_addString U_ICU_ENTRY_POINT_RENAME(uset_addString) -#define uset_applyIntPropertyValue U_ICU_ENTRY_POINT_RENAME(uset_applyIntPropertyValue) -#define uset_applyPattern U_ICU_ENTRY_POINT_RENAME(uset_applyPattern) -#define uset_applyPropertyAlias U_ICU_ENTRY_POINT_RENAME(uset_applyPropertyAlias) -#define uset_charAt U_ICU_ENTRY_POINT_RENAME(uset_charAt) -#define uset_clear U_ICU_ENTRY_POINT_RENAME(uset_clear) -#define uset_clone U_ICU_ENTRY_POINT_RENAME(uset_clone) -#define uset_cloneAsThawed U_ICU_ENTRY_POINT_RENAME(uset_cloneAsThawed) -#define uset_close U_ICU_ENTRY_POINT_RENAME(uset_close) -#define uset_closeOver U_ICU_ENTRY_POINT_RENAME(uset_closeOver) -#define uset_compact U_ICU_ENTRY_POINT_RENAME(uset_compact) -#define uset_complement U_ICU_ENTRY_POINT_RENAME(uset_complement) -#define uset_complementAll U_ICU_ENTRY_POINT_RENAME(uset_complementAll) -#define uset_contains U_ICU_ENTRY_POINT_RENAME(uset_contains) -#define uset_containsAll U_ICU_ENTRY_POINT_RENAME(uset_containsAll) -#define uset_containsAllCodePoints U_ICU_ENTRY_POINT_RENAME(uset_containsAllCodePoints) -#define uset_containsNone U_ICU_ENTRY_POINT_RENAME(uset_containsNone) -#define uset_containsRange U_ICU_ENTRY_POINT_RENAME(uset_containsRange) -#define uset_containsSome U_ICU_ENTRY_POINT_RENAME(uset_containsSome) -#define uset_containsString U_ICU_ENTRY_POINT_RENAME(uset_containsString) -#define uset_equals U_ICU_ENTRY_POINT_RENAME(uset_equals) -#define uset_freeze U_ICU_ENTRY_POINT_RENAME(uset_freeze) -#define uset_getItem U_ICU_ENTRY_POINT_RENAME(uset_getItem) -#define uset_getItemCount U_ICU_ENTRY_POINT_RENAME(uset_getItemCount) -#define uset_getSerializedRange U_ICU_ENTRY_POINT_RENAME(uset_getSerializedRange) -#define uset_getSerializedRangeCount U_ICU_ENTRY_POINT_RENAME(uset_getSerializedRangeCount) -#define uset_getSerializedSet U_ICU_ENTRY_POINT_RENAME(uset_getSerializedSet) -#define uset_indexOf U_ICU_ENTRY_POINT_RENAME(uset_indexOf) -#define uset_isEmpty U_ICU_ENTRY_POINT_RENAME(uset_isEmpty) -#define uset_isFrozen U_ICU_ENTRY_POINT_RENAME(uset_isFrozen) -#define uset_open U_ICU_ENTRY_POINT_RENAME(uset_open) -#define uset_openEmpty U_ICU_ENTRY_POINT_RENAME(uset_openEmpty) -#define uset_openPattern U_ICU_ENTRY_POINT_RENAME(uset_openPattern) -#define uset_openPatternOptions U_ICU_ENTRY_POINT_RENAME(uset_openPatternOptions) -#define uset_remove U_ICU_ENTRY_POINT_RENAME(uset_remove) -#define uset_removeAll U_ICU_ENTRY_POINT_RENAME(uset_removeAll) -#define uset_removeAllStrings U_ICU_ENTRY_POINT_RENAME(uset_removeAllStrings) -#define uset_removeRange U_ICU_ENTRY_POINT_RENAME(uset_removeRange) -#define uset_removeString U_ICU_ENTRY_POINT_RENAME(uset_removeString) -#define uset_resemblesPattern U_ICU_ENTRY_POINT_RENAME(uset_resemblesPattern) -#define uset_retain U_ICU_ENTRY_POINT_RENAME(uset_retain) -#define uset_retainAll U_ICU_ENTRY_POINT_RENAME(uset_retainAll) -#define uset_serialize U_ICU_ENTRY_POINT_RENAME(uset_serialize) -#define uset_serializedContains U_ICU_ENTRY_POINT_RENAME(uset_serializedContains) -#define uset_set U_ICU_ENTRY_POINT_RENAME(uset_set) -#define uset_setSerializedToOne U_ICU_ENTRY_POINT_RENAME(uset_setSerializedToOne) -#define uset_size U_ICU_ENTRY_POINT_RENAME(uset_size) -#define uset_span U_ICU_ENTRY_POINT_RENAME(uset_span) -#define uset_spanBack U_ICU_ENTRY_POINT_RENAME(uset_spanBack) -#define uset_spanBackUTF8 U_ICU_ENTRY_POINT_RENAME(uset_spanBackUTF8) -#define uset_spanUTF8 U_ICU_ENTRY_POINT_RENAME(uset_spanUTF8) -#define uset_toPattern U_ICU_ENTRY_POINT_RENAME(uset_toPattern) -#define uspoof_areConfusable U_ICU_ENTRY_POINT_RENAME(uspoof_areConfusable) -#define uspoof_areConfusableUTF8 U_ICU_ENTRY_POINT_RENAME(uspoof_areConfusableUTF8) -#define uspoof_areConfusableUnicodeString U_ICU_ENTRY_POINT_RENAME(uspoof_areConfusableUnicodeString) -#define uspoof_check U_ICU_ENTRY_POINT_RENAME(uspoof_check) -#define uspoof_check2 U_ICU_ENTRY_POINT_RENAME(uspoof_check2) -#define uspoof_check2UTF8 U_ICU_ENTRY_POINT_RENAME(uspoof_check2UTF8) -#define uspoof_check2UnicodeString U_ICU_ENTRY_POINT_RENAME(uspoof_check2UnicodeString) -#define uspoof_checkUTF8 U_ICU_ENTRY_POINT_RENAME(uspoof_checkUTF8) -#define uspoof_checkUnicodeString U_ICU_ENTRY_POINT_RENAME(uspoof_checkUnicodeString) -#define uspoof_clone U_ICU_ENTRY_POINT_RENAME(uspoof_clone) -#define uspoof_close U_ICU_ENTRY_POINT_RENAME(uspoof_close) -#define uspoof_closeCheckResult U_ICU_ENTRY_POINT_RENAME(uspoof_closeCheckResult) -#define uspoof_getAllowedChars U_ICU_ENTRY_POINT_RENAME(uspoof_getAllowedChars) -#define uspoof_getAllowedLocales U_ICU_ENTRY_POINT_RENAME(uspoof_getAllowedLocales) -#define uspoof_getAllowedUnicodeSet U_ICU_ENTRY_POINT_RENAME(uspoof_getAllowedUnicodeSet) -#define uspoof_getCheckResultChecks U_ICU_ENTRY_POINT_RENAME(uspoof_getCheckResultChecks) -#define uspoof_getCheckResultNumerics U_ICU_ENTRY_POINT_RENAME(uspoof_getCheckResultNumerics) -#define uspoof_getCheckResultRestrictionLevel U_ICU_ENTRY_POINT_RENAME(uspoof_getCheckResultRestrictionLevel) -#define uspoof_getChecks U_ICU_ENTRY_POINT_RENAME(uspoof_getChecks) -#define uspoof_getInclusionSet U_ICU_ENTRY_POINT_RENAME(uspoof_getInclusionSet) -#define uspoof_getInclusionUnicodeSet U_ICU_ENTRY_POINT_RENAME(uspoof_getInclusionUnicodeSet) -#define uspoof_getRecommendedSet U_ICU_ENTRY_POINT_RENAME(uspoof_getRecommendedSet) -#define uspoof_getRecommendedUnicodeSet U_ICU_ENTRY_POINT_RENAME(uspoof_getRecommendedUnicodeSet) -#define uspoof_getRestrictionLevel U_ICU_ENTRY_POINT_RENAME(uspoof_getRestrictionLevel) -#define uspoof_getSkeleton U_ICU_ENTRY_POINT_RENAME(uspoof_getSkeleton) -#define uspoof_getSkeletonUTF8 U_ICU_ENTRY_POINT_RENAME(uspoof_getSkeletonUTF8) -#define uspoof_getSkeletonUnicodeString U_ICU_ENTRY_POINT_RENAME(uspoof_getSkeletonUnicodeString) -#define uspoof_internalInitStatics U_ICU_ENTRY_POINT_RENAME(uspoof_internalInitStatics) -#define uspoof_open U_ICU_ENTRY_POINT_RENAME(uspoof_open) -#define uspoof_openCheckResult U_ICU_ENTRY_POINT_RENAME(uspoof_openCheckResult) -#define uspoof_openFromSerialized U_ICU_ENTRY_POINT_RENAME(uspoof_openFromSerialized) -#define uspoof_openFromSource U_ICU_ENTRY_POINT_RENAME(uspoof_openFromSource) -#define uspoof_serialize U_ICU_ENTRY_POINT_RENAME(uspoof_serialize) -#define uspoof_setAllowedChars U_ICU_ENTRY_POINT_RENAME(uspoof_setAllowedChars) -#define uspoof_setAllowedLocales U_ICU_ENTRY_POINT_RENAME(uspoof_setAllowedLocales) -#define uspoof_setAllowedUnicodeSet U_ICU_ENTRY_POINT_RENAME(uspoof_setAllowedUnicodeSet) -#define uspoof_setChecks U_ICU_ENTRY_POINT_RENAME(uspoof_setChecks) -#define uspoof_setRestrictionLevel U_ICU_ENTRY_POINT_RENAME(uspoof_setRestrictionLevel) -#define uspoof_swap U_ICU_ENTRY_POINT_RENAME(uspoof_swap) -#define usprep_close U_ICU_ENTRY_POINT_RENAME(usprep_close) -#define usprep_open U_ICU_ENTRY_POINT_RENAME(usprep_open) -#define usprep_openByType U_ICU_ENTRY_POINT_RENAME(usprep_openByType) -#define usprep_prepare U_ICU_ENTRY_POINT_RENAME(usprep_prepare) -#define usprep_swap U_ICU_ENTRY_POINT_RENAME(usprep_swap) -#define ustr_hashCharsN U_ICU_ENTRY_POINT_RENAME(ustr_hashCharsN) -#define ustr_hashICharsN U_ICU_ENTRY_POINT_RENAME(ustr_hashICharsN) -#define ustr_hashUCharsN U_ICU_ENTRY_POINT_RENAME(ustr_hashUCharsN) -#define ustrcase_internalFold U_ICU_ENTRY_POINT_RENAME(ustrcase_internalFold) -#define ustrcase_internalToLower U_ICU_ENTRY_POINT_RENAME(ustrcase_internalToLower) -#define ustrcase_internalToTitle U_ICU_ENTRY_POINT_RENAME(ustrcase_internalToTitle) -#define ustrcase_internalToUpper U_ICU_ENTRY_POINT_RENAME(ustrcase_internalToUpper) -#define ustrcase_map U_ICU_ENTRY_POINT_RENAME(ustrcase_map) -#define ustrcase_setTempCaseMapLocale U_ICU_ENTRY_POINT_RENAME(ustrcase_setTempCaseMapLocale) -#define utext_char32At U_ICU_ENTRY_POINT_RENAME(utext_char32At) -#define utext_clone U_ICU_ENTRY_POINT_RENAME(utext_clone) -#define utext_close U_ICU_ENTRY_POINT_RENAME(utext_close) -#define utext_copy U_ICU_ENTRY_POINT_RENAME(utext_copy) -#define utext_current32 U_ICU_ENTRY_POINT_RENAME(utext_current32) -#define utext_equals U_ICU_ENTRY_POINT_RENAME(utext_equals) -#define utext_extract U_ICU_ENTRY_POINT_RENAME(utext_extract) -#define utext_freeze U_ICU_ENTRY_POINT_RENAME(utext_freeze) -#define utext_getNativeIndex U_ICU_ENTRY_POINT_RENAME(utext_getNativeIndex) -#define utext_getPreviousNativeIndex U_ICU_ENTRY_POINT_RENAME(utext_getPreviousNativeIndex) -#define utext_hasMetaData U_ICU_ENTRY_POINT_RENAME(utext_hasMetaData) -#define utext_isLengthExpensive U_ICU_ENTRY_POINT_RENAME(utext_isLengthExpensive) -#define utext_isWritable U_ICU_ENTRY_POINT_RENAME(utext_isWritable) -#define utext_moveIndex32 U_ICU_ENTRY_POINT_RENAME(utext_moveIndex32) -#define utext_nativeLength U_ICU_ENTRY_POINT_RENAME(utext_nativeLength) -#define utext_next32 U_ICU_ENTRY_POINT_RENAME(utext_next32) -#define utext_next32From U_ICU_ENTRY_POINT_RENAME(utext_next32From) -#define utext_openCharacterIterator U_ICU_ENTRY_POINT_RENAME(utext_openCharacterIterator) -#define utext_openConstUnicodeString U_ICU_ENTRY_POINT_RENAME(utext_openConstUnicodeString) -#define utext_openReplaceable U_ICU_ENTRY_POINT_RENAME(utext_openReplaceable) -#define utext_openUChars U_ICU_ENTRY_POINT_RENAME(utext_openUChars) -#define utext_openUTF8 U_ICU_ENTRY_POINT_RENAME(utext_openUTF8) -#define utext_openUnicodeString U_ICU_ENTRY_POINT_RENAME(utext_openUnicodeString) -#define utext_previous32 U_ICU_ENTRY_POINT_RENAME(utext_previous32) -#define utext_previous32From U_ICU_ENTRY_POINT_RENAME(utext_previous32From) -#define utext_replace U_ICU_ENTRY_POINT_RENAME(utext_replace) -#define utext_setNativeIndex U_ICU_ENTRY_POINT_RENAME(utext_setNativeIndex) -#define utext_setup U_ICU_ENTRY_POINT_RENAME(utext_setup) -#define utf8_appendCharSafeBody U_ICU_ENTRY_POINT_RENAME(utf8_appendCharSafeBody) -#define utf8_back1SafeBody U_ICU_ENTRY_POINT_RENAME(utf8_back1SafeBody) -#define utf8_countTrailBytes U_ICU_ENTRY_POINT_RENAME(utf8_countTrailBytes) -#define utf8_nextCharSafeBody U_ICU_ENTRY_POINT_RENAME(utf8_nextCharSafeBody) -#define utf8_prevCharSafeBody U_ICU_ENTRY_POINT_RENAME(utf8_prevCharSafeBody) -#define utmscale_fromInt64 U_ICU_ENTRY_POINT_RENAME(utmscale_fromInt64) -#define utmscale_getTimeScaleValue U_ICU_ENTRY_POINT_RENAME(utmscale_getTimeScaleValue) -#define utmscale_toInt64 U_ICU_ENTRY_POINT_RENAME(utmscale_toInt64) -#define utrace_cleanup U_ICU_ENTRY_POINT_RENAME(utrace_cleanup) -#define utrace_data U_ICU_ENTRY_POINT_RENAME(utrace_data) -#define utrace_entry U_ICU_ENTRY_POINT_RENAME(utrace_entry) -#define utrace_exit U_ICU_ENTRY_POINT_RENAME(utrace_exit) -#define utrace_format U_ICU_ENTRY_POINT_RENAME(utrace_format) -#define utrace_functionName U_ICU_ENTRY_POINT_RENAME(utrace_functionName) -#define utrace_getFunctions U_ICU_ENTRY_POINT_RENAME(utrace_getFunctions) -#define utrace_getLevel U_ICU_ENTRY_POINT_RENAME(utrace_getLevel) -#define utrace_level U_ICU_ENTRY_POINT_RENAME(utrace_level) -#define utrace_setFunctions U_ICU_ENTRY_POINT_RENAME(utrace_setFunctions) -#define utrace_setLevel U_ICU_ENTRY_POINT_RENAME(utrace_setLevel) -#define utrace_vformat U_ICU_ENTRY_POINT_RENAME(utrace_vformat) -#define utrans_clone U_ICU_ENTRY_POINT_RENAME(utrans_clone) -#define utrans_close U_ICU_ENTRY_POINT_RENAME(utrans_close) -#define utrans_countAvailableIDs U_ICU_ENTRY_POINT_RENAME(utrans_countAvailableIDs) -#define utrans_getAvailableID U_ICU_ENTRY_POINT_RENAME(utrans_getAvailableID) -#define utrans_getID U_ICU_ENTRY_POINT_RENAME(utrans_getID) -#define utrans_getSourceSet U_ICU_ENTRY_POINT_RENAME(utrans_getSourceSet) -#define utrans_getUnicodeID U_ICU_ENTRY_POINT_RENAME(utrans_getUnicodeID) -#define utrans_open U_ICU_ENTRY_POINT_RENAME(utrans_open) -#define utrans_openIDs U_ICU_ENTRY_POINT_RENAME(utrans_openIDs) -#define utrans_openInverse U_ICU_ENTRY_POINT_RENAME(utrans_openInverse) -#define utrans_openU U_ICU_ENTRY_POINT_RENAME(utrans_openU) -#define utrans_register U_ICU_ENTRY_POINT_RENAME(utrans_register) -#define utrans_rep_caseContextIterator U_ICU_ENTRY_POINT_RENAME(utrans_rep_caseContextIterator) -#define utrans_setFilter U_ICU_ENTRY_POINT_RENAME(utrans_setFilter) -#define utrans_stripRules U_ICU_ENTRY_POINT_RENAME(utrans_stripRules) -#define utrans_toRules U_ICU_ENTRY_POINT_RENAME(utrans_toRules) -#define utrans_trans U_ICU_ENTRY_POINT_RENAME(utrans_trans) -#define utrans_transIncremental U_ICU_ENTRY_POINT_RENAME(utrans_transIncremental) -#define utrans_transIncrementalUChars U_ICU_ENTRY_POINT_RENAME(utrans_transIncrementalUChars) -#define utrans_transUChars U_ICU_ENTRY_POINT_RENAME(utrans_transUChars) -#define utrans_transliterator_cleanup U_ICU_ENTRY_POINT_RENAME(utrans_transliterator_cleanup) -#define utrans_unregister U_ICU_ENTRY_POINT_RENAME(utrans_unregister) -#define utrans_unregisterID U_ICU_ENTRY_POINT_RENAME(utrans_unregisterID) -#define utrie2_clone U_ICU_ENTRY_POINT_RENAME(utrie2_clone) -#define utrie2_cloneAsThawed U_ICU_ENTRY_POINT_RENAME(utrie2_cloneAsThawed) -#define utrie2_close U_ICU_ENTRY_POINT_RENAME(utrie2_close) -#define utrie2_enum U_ICU_ENTRY_POINT_RENAME(utrie2_enum) -#define utrie2_enumForLeadSurrogate U_ICU_ENTRY_POINT_RENAME(utrie2_enumForLeadSurrogate) -#define utrie2_freeze U_ICU_ENTRY_POINT_RENAME(utrie2_freeze) -#define utrie2_fromUTrie U_ICU_ENTRY_POINT_RENAME(utrie2_fromUTrie) -#define utrie2_get32 U_ICU_ENTRY_POINT_RENAME(utrie2_get32) -#define utrie2_get32FromLeadSurrogateCodeUnit U_ICU_ENTRY_POINT_RENAME(utrie2_get32FromLeadSurrogateCodeUnit) -#define utrie2_getVersion U_ICU_ENTRY_POINT_RENAME(utrie2_getVersion) -#define utrie2_internalU8NextIndex U_ICU_ENTRY_POINT_RENAME(utrie2_internalU8NextIndex) -#define utrie2_internalU8PrevIndex U_ICU_ENTRY_POINT_RENAME(utrie2_internalU8PrevIndex) -#define utrie2_isFrozen U_ICU_ENTRY_POINT_RENAME(utrie2_isFrozen) -#define utrie2_open U_ICU_ENTRY_POINT_RENAME(utrie2_open) -#define utrie2_openDummy U_ICU_ENTRY_POINT_RENAME(utrie2_openDummy) -#define utrie2_openFromSerialized U_ICU_ENTRY_POINT_RENAME(utrie2_openFromSerialized) -#define utrie2_serialize U_ICU_ENTRY_POINT_RENAME(utrie2_serialize) -#define utrie2_set32 U_ICU_ENTRY_POINT_RENAME(utrie2_set32) -#define utrie2_set32ForLeadSurrogateCodeUnit U_ICU_ENTRY_POINT_RENAME(utrie2_set32ForLeadSurrogateCodeUnit) -#define utrie2_setRange32 U_ICU_ENTRY_POINT_RENAME(utrie2_setRange32) -#define utrie2_swap U_ICU_ENTRY_POINT_RENAME(utrie2_swap) -#define utrie2_swapAnyVersion U_ICU_ENTRY_POINT_RENAME(utrie2_swapAnyVersion) -#define utrie_clone U_ICU_ENTRY_POINT_RENAME(utrie_clone) -#define utrie_close U_ICU_ENTRY_POINT_RENAME(utrie_close) -#define utrie_defaultGetFoldingOffset U_ICU_ENTRY_POINT_RENAME(utrie_defaultGetFoldingOffset) -#define utrie_enum U_ICU_ENTRY_POINT_RENAME(utrie_enum) -#define utrie_get32 U_ICU_ENTRY_POINT_RENAME(utrie_get32) -#define utrie_getData U_ICU_ENTRY_POINT_RENAME(utrie_getData) -#define utrie_open U_ICU_ENTRY_POINT_RENAME(utrie_open) -#define utrie_serialize U_ICU_ENTRY_POINT_RENAME(utrie_serialize) -#define utrie_set32 U_ICU_ENTRY_POINT_RENAME(utrie_set32) -#define utrie_setRange32 U_ICU_ENTRY_POINT_RENAME(utrie_setRange32) -#define utrie_swap U_ICU_ENTRY_POINT_RENAME(utrie_swap) -#define utrie_unserialize U_ICU_ENTRY_POINT_RENAME(utrie_unserialize) -#define utrie_unserializeDummy U_ICU_ENTRY_POINT_RENAME(utrie_unserializeDummy) -#define vzone_clone U_ICU_ENTRY_POINT_RENAME(vzone_clone) -#define vzone_close U_ICU_ENTRY_POINT_RENAME(vzone_close) -#define vzone_countTransitionRules U_ICU_ENTRY_POINT_RENAME(vzone_countTransitionRules) -#define vzone_equals U_ICU_ENTRY_POINT_RENAME(vzone_equals) -#define vzone_getDynamicClassID U_ICU_ENTRY_POINT_RENAME(vzone_getDynamicClassID) -#define vzone_getLastModified U_ICU_ENTRY_POINT_RENAME(vzone_getLastModified) -#define vzone_getNextTransition U_ICU_ENTRY_POINT_RENAME(vzone_getNextTransition) -#define vzone_getOffset U_ICU_ENTRY_POINT_RENAME(vzone_getOffset) -#define vzone_getOffset2 U_ICU_ENTRY_POINT_RENAME(vzone_getOffset2) -#define vzone_getOffset3 U_ICU_ENTRY_POINT_RENAME(vzone_getOffset3) -#define vzone_getPreviousTransition U_ICU_ENTRY_POINT_RENAME(vzone_getPreviousTransition) -#define vzone_getRawOffset U_ICU_ENTRY_POINT_RENAME(vzone_getRawOffset) -#define vzone_getStaticClassID U_ICU_ENTRY_POINT_RENAME(vzone_getStaticClassID) -#define vzone_getTZURL U_ICU_ENTRY_POINT_RENAME(vzone_getTZURL) -#define vzone_hasSameRules U_ICU_ENTRY_POINT_RENAME(vzone_hasSameRules) -#define vzone_inDaylightTime U_ICU_ENTRY_POINT_RENAME(vzone_inDaylightTime) -#define vzone_openData U_ICU_ENTRY_POINT_RENAME(vzone_openData) -#define vzone_openID U_ICU_ENTRY_POINT_RENAME(vzone_openID) -#define vzone_setLastModified U_ICU_ENTRY_POINT_RENAME(vzone_setLastModified) -#define vzone_setRawOffset U_ICU_ENTRY_POINT_RENAME(vzone_setRawOffset) -#define vzone_setTZURL U_ICU_ENTRY_POINT_RENAME(vzone_setTZURL) -#define vzone_useDaylightTime U_ICU_ENTRY_POINT_RENAME(vzone_useDaylightTime) -#define vzone_write U_ICU_ENTRY_POINT_RENAME(vzone_write) -#define vzone_writeFromStart U_ICU_ENTRY_POINT_RENAME(vzone_writeFromStart) -#define vzone_writeSimple U_ICU_ENTRY_POINT_RENAME(vzone_writeSimple) -#define zrule_close U_ICU_ENTRY_POINT_RENAME(zrule_close) -#define zrule_equals U_ICU_ENTRY_POINT_RENAME(zrule_equals) -#define zrule_getDSTSavings U_ICU_ENTRY_POINT_RENAME(zrule_getDSTSavings) -#define zrule_getName U_ICU_ENTRY_POINT_RENAME(zrule_getName) -#define zrule_getRawOffset U_ICU_ENTRY_POINT_RENAME(zrule_getRawOffset) -#define zrule_isEquivalentTo U_ICU_ENTRY_POINT_RENAME(zrule_isEquivalentTo) -#define ztrans_adoptFrom U_ICU_ENTRY_POINT_RENAME(ztrans_adoptFrom) -#define ztrans_adoptTo U_ICU_ENTRY_POINT_RENAME(ztrans_adoptTo) -#define ztrans_clone U_ICU_ENTRY_POINT_RENAME(ztrans_clone) -#define ztrans_close U_ICU_ENTRY_POINT_RENAME(ztrans_close) -#define ztrans_equals U_ICU_ENTRY_POINT_RENAME(ztrans_equals) -#define ztrans_getDynamicClassID U_ICU_ENTRY_POINT_RENAME(ztrans_getDynamicClassID) -#define ztrans_getFrom U_ICU_ENTRY_POINT_RENAME(ztrans_getFrom) -#define ztrans_getStaticClassID U_ICU_ENTRY_POINT_RENAME(ztrans_getStaticClassID) -#define ztrans_getTime U_ICU_ENTRY_POINT_RENAME(ztrans_getTime) -#define ztrans_getTo U_ICU_ENTRY_POINT_RENAME(ztrans_getTo) -#define ztrans_open U_ICU_ENTRY_POINT_RENAME(ztrans_open) -#define ztrans_openEmpty U_ICU_ENTRY_POINT_RENAME(ztrans_openEmpty) -#define ztrans_setFrom U_ICU_ENTRY_POINT_RENAME(ztrans_setFrom) -#define ztrans_setTime U_ICU_ENTRY_POINT_RENAME(ztrans_setTime) -#define ztrans_setTo U_ICU_ENTRY_POINT_RENAME(ztrans_setTo) - -#endif - -#endif diff --git a/win32/include/spidermonkey/unicode/urep.h b/win32/include/spidermonkey/unicode/urep.h deleted file mode 100755 index b559b248..00000000 --- a/win32/include/spidermonkey/unicode/urep.h +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* Copyright (C) 1997-2010, International Business Machines -* Corporation and others. All Rights Reserved. -****************************************************************************** -* Date Name Description -* 06/23/00 aliu Creation. -****************************************************************************** -*/ - -#ifndef __UREP_H -#define __UREP_H - -#include "unicode/utypes.h" - -U_CDECL_BEGIN - -/******************************************************************** - * General Notes - ******************************************************************** - * TODO - * Add usage scenario - * Add test code - * Talk about pinning - * Talk about "can truncate result if out of memory" - */ - -/******************************************************************** - * Data Structures - ********************************************************************/ -/** - * \file - * \brief C API: Callbacks for UReplaceable - */ -/** - * An opaque replaceable text object. This will be manipulated only - * through the caller-supplied UReplaceableFunctor struct. Related - * to the C++ class Replaceable. - * This is currently only used in the Transliterator C API, see utrans.h . - * @stable ICU 2.0 - */ -typedef void* UReplaceable; - -/** - * A set of function pointers that transliterators use to manipulate a - * UReplaceable. The caller should supply the required functions to - * manipulate their text appropriately. Related to the C++ class - * Replaceable. - * @stable ICU 2.0 - */ -typedef struct UReplaceableCallbacks { - - /** - * Function pointer that returns the number of UChar code units in - * this text. - * - * @param rep A pointer to "this" UReplaceable object. - * @return The length of the text. - * @stable ICU 2.0 - */ - int32_t (*length)(const UReplaceable* rep); - - /** - * Function pointer that returns a UChar code units at the given - * offset into this text; 0 <= offset < n, where n is the value - * returned by (*length)(rep). See unistr.h for a description of - * charAt() vs. char32At(). - * - * @param rep A pointer to "this" UReplaceable object. - * @param offset The index at which to fetch the UChar (code unit). - * @return The UChar (code unit) at offset, or U+FFFF if the offset is out of bounds. - * @stable ICU 2.0 - */ - UChar (*charAt)(const UReplaceable* rep, - int32_t offset); - - /** - * Function pointer that returns a UChar32 code point at the given - * offset into this text. See unistr.h for a description of - * charAt() vs. char32At(). - * - * @param rep A pointer to "this" UReplaceable object. - * @param offset The index at which to fetch the UChar32 (code point). - * @return The UChar32 (code point) at offset, or U+FFFF if the offset is out of bounds. - * @stable ICU 2.0 - */ - UChar32 (*char32At)(const UReplaceable* rep, - int32_t offset); - - /** - * Function pointer that replaces text between start and limit in - * this text with the given text. Attributes (out of band info) - * should be retained. - * - * @param rep A pointer to "this" UReplaceable object. - * @param start the starting index of the text to be replaced, - * inclusive. - * @param limit the ending index of the text to be replaced, - * exclusive. - * @param text the new text to replace the UChars from - * start..limit-1. - * @param textLength the number of UChars at text, or -1 if text - * is null-terminated. - * @stable ICU 2.0 - */ - void (*replace)(UReplaceable* rep, - int32_t start, - int32_t limit, - const UChar* text, - int32_t textLength); - - /** - * Function pointer that copies the characters in the range - * [start, limit) into the array dst. - * - * @param rep A pointer to "this" UReplaceable object. - * @param start offset of first character which will be copied - * into the array - * @param limit offset immediately following the last character to - * be copied - * @param dst array in which to copy characters. The length of - * dst must be at least (limit - start). - * @stable ICU 2.1 - */ - void (*extract)(UReplaceable* rep, - int32_t start, - int32_t limit, - UChar* dst); - - /** - * Function pointer that copies text between start and limit in - * this text to another index in the text. Attributes (out of - * band info) should be retained. After this call, there will be - * (at least) two copies of the characters originally located at - * start..limit-1. - * - * @param rep A pointer to "this" UReplaceable object. - * @param start the starting index of the text to be copied, - * inclusive. - * @param limit the ending index of the text to be copied, - * exclusive. - * @param dest the index at which the copy of the UChars should be - * inserted. - * @stable ICU 2.0 - */ - void (*copy)(UReplaceable* rep, - int32_t start, - int32_t limit, - int32_t dest); - -} UReplaceableCallbacks; - -U_CDECL_END - -#endif diff --git a/win32/include/spidermonkey/unicode/ures.h b/win32/include/spidermonkey/unicode/ures.h deleted file mode 100755 index 620d9268..00000000 --- a/win32/include/spidermonkey/unicode/ures.h +++ /dev/null @@ -1,908 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1997-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* -* File URES.H (formerly CRESBUND.H) -* -* Modification History: -* -* Date Name Description -* 04/01/97 aliu Creation. -* 02/22/99 damiba overhaul. -* 04/04/99 helena Fixed internal header inclusion. -* 04/15/99 Madhu Updated Javadoc -* 06/14/99 stephen Removed functions taking a filename suffix. -* 07/20/99 stephen Language-independent ypedef to void* -* 11/09/99 weiv Added ures_getLocale() -* 06/24/02 weiv Added support for resource sharing -****************************************************************************** -*/ - -#ifndef URES_H -#define URES_H - -#include "unicode/utypes.h" -#include "unicode/uloc.h" -#include "unicode/localpointer.h" - -/** - * \file - * \brief C API: Resource Bundle - * - *

C API: Resource Bundle

- * - * C API representing a collection of resource information pertaining to a given - * locale. A resource bundle provides a way of accessing locale- specific information in - * a data file. You create a resource bundle that manages the resources for a given - * locale and then ask it for individual resources. - *

- * Resource bundles in ICU4C are currently defined using text files which conform to the following - * BNF definition. - * More on resource bundle concepts and syntax can be found in the - * Users Guide. - *

- */ - -/** - * UResourceBundle is an opaque type for handles for resource bundles in C APIs. - * @stable ICU 2.0 - */ -struct UResourceBundle; - -/** - * @stable ICU 2.0 - */ -typedef struct UResourceBundle UResourceBundle; - -/** - * Numeric constants for types of resource items. - * @see ures_getType - * @stable ICU 2.0 - */ -typedef enum { - /** Resource type constant for "no resource". @stable ICU 2.6 */ - URES_NONE=-1, - - /** Resource type constant for 16-bit Unicode strings. @stable ICU 2.6 */ - URES_STRING=0, - - /** Resource type constant for binary data. @stable ICU 2.6 */ - URES_BINARY=1, - - /** Resource type constant for tables of key-value pairs. @stable ICU 2.6 */ - URES_TABLE=2, - - /** - * Resource type constant for aliases; - * internally stores a string which identifies the actual resource - * storing the data (can be in a different resource bundle). - * Resolved internally before delivering the actual resource through the API. - * @stable ICU 2.6 - */ - URES_ALIAS=3, - - /** - * Resource type constant for a single 28-bit integer, interpreted as - * signed or unsigned by the ures_getInt() or ures_getUInt() function. - * @see ures_getInt - * @see ures_getUInt - * @stable ICU 2.6 - */ - URES_INT=7, - - /** Resource type constant for arrays of resources. @stable ICU 2.6 */ - URES_ARRAY=8, - - /** - * Resource type constant for vectors of 32-bit integers. - * @see ures_getIntVector - * @stable ICU 2.6 - */ - URES_INT_VECTOR = 14, -#ifndef U_HIDE_DEPRECATED_API - /** @deprecated ICU 2.6 Use the URES_ constant instead. */ - RES_NONE=URES_NONE, - /** @deprecated ICU 2.6 Use the URES_ constant instead. */ - RES_STRING=URES_STRING, - /** @deprecated ICU 2.6 Use the URES_ constant instead. */ - RES_BINARY=URES_BINARY, - /** @deprecated ICU 2.6 Use the URES_ constant instead. */ - RES_TABLE=URES_TABLE, - /** @deprecated ICU 2.6 Use the URES_ constant instead. */ - RES_ALIAS=URES_ALIAS, - /** @deprecated ICU 2.6 Use the URES_ constant instead. */ - RES_INT=URES_INT, - /** @deprecated ICU 2.6 Use the URES_ constant instead. */ - RES_ARRAY=URES_ARRAY, - /** @deprecated ICU 2.6 Use the URES_ constant instead. */ - RES_INT_VECTOR=URES_INT_VECTOR, - /** @deprecated ICU 2.6 Not used. */ - RES_RESERVED=15, - - /** - * One more than the highest normal UResType value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - URES_LIMIT = 16 -#endif // U_HIDE_DEPRECATED_API -} UResType; - -/* - * Functions to create and destroy resource bundles. - */ - -/** - * Opens a UResourceBundle, from which users can extract strings by using - * their corresponding keys. - * Note that the caller is responsible of calling ures_close on each succesfully - * opened resource bundle. - * @param packageName The packageName and locale together point to an ICU udata object, - * as defined by udata_open( packageName, "res", locale, err) - * or equivalent. Typically, packageName will refer to a (.dat) file, or to - * a package registered with udata_setAppData(). Using a full file or directory - * pathname for packageName is deprecated. If NULL, ICU data will be used. - * @param locale specifies the locale for which we want to open the resource - * if NULL, the default locale will be used. If strlen(locale) == 0 - * root locale will be used. - * - * @param status fills in the outgoing error code. - * The UErrorCode err parameter is used to return status information to the user. To - * check whether the construction succeeded or not, you should check the value of - * U_SUCCESS(err). If you wish more detailed information, you can check for - * informational status results which still indicate success. U_USING_FALLBACK_WARNING - * indicates that a fall back locale was used. For example, 'de_CH' was requested, - * but nothing was found there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that - * the default locale data or root locale data was used; neither the requested locale - * nor any of its fall back locales could be found. Please see the users guide for more - * information on this topic. - * @return a newly allocated resource bundle. - * @see ures_close - * @stable ICU 2.0 - */ -U_STABLE UResourceBundle* U_EXPORT2 -ures_open(const char* packageName, - const char* locale, - UErrorCode* status); - - -/** This function does not care what kind of localeID is passed in. It simply opens a bundle with - * that name. Fallback mechanism is disabled for the new bundle. If the requested bundle contains - * an %%ALIAS directive, the results are undefined. - * @param packageName The packageName and locale together point to an ICU udata object, - * as defined by udata_open( packageName, "res", locale, err) - * or equivalent. Typically, packageName will refer to a (.dat) file, or to - * a package registered with udata_setAppData(). Using a full file or directory - * pathname for packageName is deprecated. If NULL, ICU data will be used. - * @param locale specifies the locale for which we want to open the resource - * if NULL, the default locale will be used. If strlen(locale) == 0 - * root locale will be used. - * - * @param status fills in the outgoing error code. Either U_ZERO_ERROR or U_MISSING_RESOURCE_ERROR - * @return a newly allocated resource bundle or NULL if it doesn't exist. - * @see ures_close - * @stable ICU 2.0 - */ -U_STABLE UResourceBundle* U_EXPORT2 -ures_openDirect(const char* packageName, - const char* locale, - UErrorCode* status); - -/** - * Same as ures_open() but takes a const UChar *path. - * This path will be converted to char * using the default converter, - * then ures_open() is called. - * - * @param packageName The packageName and locale together point to an ICU udata object, - * as defined by udata_open( packageName, "res", locale, err) - * or equivalent. Typically, packageName will refer to a (.dat) file, or to - * a package registered with udata_setAppData(). Using a full file or directory - * pathname for packageName is deprecated. If NULL, ICU data will be used. - * @param locale specifies the locale for which we want to open the resource - * if NULL, the default locale will be used. If strlen(locale) == 0 - * root locale will be used. - * @param status fills in the outgoing error code. - * @return a newly allocated resource bundle. - * @see ures_open - * @stable ICU 2.0 - */ -U_STABLE UResourceBundle* U_EXPORT2 -ures_openU(const UChar* packageName, - const char* locale, - UErrorCode* status); - -#ifndef U_HIDE_DEPRECATED_API -/** - * Returns the number of strings/arrays in resource bundles. - * Better to use ures_getSize, as this function will be deprecated. - * - *@param resourceBundle resource bundle containing the desired strings - *@param resourceKey key tagging the resource - *@param err fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * could be a non-failing error - * e.g.: U_USING_FALLBACK_WARNING,U_USING_FALLBACK_WARNING - *@return: for Arrays: returns the number of resources in the array - * Tables: returns the number of resources in the table - * single string: returns 1 - *@see ures_getSize - * @deprecated ICU 2.8 User ures_getSize instead - */ -U_DEPRECATED int32_t U_EXPORT2 -ures_countArrayItems(const UResourceBundle* resourceBundle, - const char* resourceKey, - UErrorCode* err); -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * Close a resource bundle, all pointers returned from the various ures_getXXX calls - * on this particular bundle should be considered invalid henceforth. - * - * @param resourceBundle a pointer to a resourceBundle struct. Can be NULL. - * @see ures_open - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ures_close(UResourceBundle* resourceBundle); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUResourceBundlePointer - * "Smart pointer" class, closes a UResourceBundle via ures_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUResourceBundlePointer, UResourceBundle, ures_close); - -U_NAMESPACE_END - -#endif - -#ifndef U_HIDE_DEPRECATED_API -/** - * Return the version number associated with this ResourceBundle as a string. Please - * use ures_getVersion as this function is going to be deprecated. - * - * @param resourceBundle The resource bundle for which the version is checked. - * @return A version number string as specified in the resource bundle or its parent. - * The caller does not own this string. - * @see ures_getVersion - * @deprecated ICU 2.8 Use ures_getVersion instead. - */ -U_DEPRECATED const char* U_EXPORT2 -ures_getVersionNumber(const UResourceBundle* resourceBundle); -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * Return the version number associated with this ResourceBundle as an - * UVersionInfo array. - * - * @param resB The resource bundle for which the version is checked. - * @param versionInfo A UVersionInfo array that is filled with the version number - * as specified in the resource bundle or its parent. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ures_getVersion(const UResourceBundle* resB, - UVersionInfo versionInfo); - -#ifndef U_HIDE_DEPRECATED_API -/** - * Return the name of the Locale associated with this ResourceBundle. This API allows - * you to query for the real locale of the resource. For example, if you requested - * "en_US_CALIFORNIA" and only "en_US" bundle exists, "en_US" will be returned. - * For subresources, the locale where this resource comes from will be returned. - * If fallback has occured, getLocale will reflect this. - * - * @param resourceBundle resource bundle in question - * @param status just for catching illegal arguments - * @return A Locale name - * @deprecated ICU 2.8 Use ures_getLocaleByType instead. - */ -U_DEPRECATED const char* U_EXPORT2 -ures_getLocale(const UResourceBundle* resourceBundle, - UErrorCode* status); -#endif /* U_HIDE_DEPRECATED_API */ - -/** - * Return the name of the Locale associated with this ResourceBundle. - * You can choose between requested, valid and real locale. - * - * @param resourceBundle resource bundle in question - * @param type You can choose between requested, valid and actual - * locale. For description see the definition of - * ULocDataLocaleType in uloc.h - * @param status just for catching illegal arguments - * @return A Locale name - * @stable ICU 2.8 - */ -U_STABLE const char* U_EXPORT2 -ures_getLocaleByType(const UResourceBundle* resourceBundle, - ULocDataLocaleType type, - UErrorCode* status); - - -#ifndef U_HIDE_INTERNAL_API -/** - * Same as ures_open() but uses the fill-in parameter instead of allocating - * a bundle, if r!=NULL. - * TODO need to revisit usefulness of this function - * and usage model for fillIn parameters without knowing sizeof(UResourceBundle) - * @param r The resourcebundle to open - * @param packageName The packageName and locale together point to an ICU udata object, - * as defined by udata_open( packageName, "res", locale, err) - * or equivalent. Typically, packageName will refer to a (.dat) file, or to - * a package registered with udata_setAppData(). Using a full file or directory - * pathname for packageName is deprecated. If NULL, ICU data will be used. - * @param localeID specifies the locale for which we want to open the resource - * @param status The error code - * @return a newly allocated resource bundle or NULL if it doesn't exist. - * @internal - */ -U_INTERNAL void U_EXPORT2 -ures_openFillIn(UResourceBundle *r, - const char* packageName, - const char* localeID, - UErrorCode* status); -#endif /* U_HIDE_INTERNAL_API */ - -/** - * Returns a string from a string resource type - * - * @param resourceBundle a string resource - * @param len fills in the length of resulting string - * @param status fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * Always check the value of status. Don't count on returning NULL. - * could be a non-failing error - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file. - * @see ures_getBinary - * @see ures_getIntVector - * @see ures_getInt - * @see ures_getUInt - * @stable ICU 2.0 - */ -U_STABLE const UChar* U_EXPORT2 -ures_getString(const UResourceBundle* resourceBundle, - int32_t* len, - UErrorCode* status); - -/** - * Returns a UTF-8 string from a string resource. - * The UTF-8 string may be returnable directly as a pointer, or - * it may need to be copied, or transformed from UTF-16 using u_strToUTF8() - * or equivalent. - * - * If forceCopy==TRUE, then the string is always written to the dest buffer - * and dest is returned. - * - * If forceCopy==FALSE, then the string is returned as a pointer if possible, - * without needing a dest buffer (it can be NULL). If the string needs to be - * copied or transformed, then it may be placed into dest at an arbitrary offset. - * - * If the string is to be written to dest, then U_BUFFER_OVERFLOW_ERROR and - * U_STRING_NOT_TERMINATED_WARNING are set if appropriate, as usual. - * - * If the string is transformed from UTF-16, then a conversion error may occur - * if an unpaired surrogate is encountered. If the function is successful, then - * the output UTF-8 string is always well-formed. - * - * @param resB Resource bundle. - * @param dest Destination buffer. Can be NULL only if capacity=*length==0. - * @param length Input: Capacity of destination buffer. - * Output: Actual length of the UTF-8 string, not counting the - * terminating NUL, even in case of U_BUFFER_OVERFLOW_ERROR. - * Can be NULL, meaning capacity=0 and the string length is not - * returned to the caller. - * @param forceCopy If TRUE, then the output string will always be written to - * dest, with U_BUFFER_OVERFLOW_ERROR and - * U_STRING_NOT_TERMINATED_WARNING set if appropriate. - * If FALSE, then the dest buffer may or may not contain a - * copy of the string. dest may or may not be modified. - * If a copy needs to be written, then the UErrorCode parameter - * indicates overflow etc. as usual. - * @param status Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The pointer to the UTF-8 string. It may be dest, or at some offset - * from dest (only if !forceCopy), or in unrelated memory. - * Always NUL-terminated unless the string was written to dest and - * length==capacity (in which case U_STRING_NOT_TERMINATED_WARNING is set). - * - * @see ures_getString - * @see u_strToUTF8 - * @stable ICU 3.6 - */ -U_STABLE const char * U_EXPORT2 -ures_getUTF8String(const UResourceBundle *resB, - char *dest, int32_t *length, - UBool forceCopy, - UErrorCode *status); - -/** - * Returns a binary data from a binary resource. - * - * @param resourceBundle a string resource - * @param len fills in the length of resulting byte chunk - * @param status fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * Always check the value of status. Don't count on returning NULL. - * could be a non-failing error - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return a pointer to a chunk of unsigned bytes which live in a memory mapped/DLL file. - * @see ures_getString - * @see ures_getIntVector - * @see ures_getInt - * @see ures_getUInt - * @stable ICU 2.0 - */ -U_STABLE const uint8_t* U_EXPORT2 -ures_getBinary(const UResourceBundle* resourceBundle, - int32_t* len, - UErrorCode* status); - -/** - * Returns a 32 bit integer array from a resource. - * - * @param resourceBundle an int vector resource - * @param len fills in the length of resulting byte chunk - * @param status fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * Always check the value of status. Don't count on returning NULL. - * could be a non-failing error - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return a pointer to a chunk of integers which live in a memory mapped/DLL file. - * @see ures_getBinary - * @see ures_getString - * @see ures_getInt - * @see ures_getUInt - * @stable ICU 2.0 - */ -U_STABLE const int32_t* U_EXPORT2 -ures_getIntVector(const UResourceBundle* resourceBundle, - int32_t* len, - UErrorCode* status); - -/** - * Returns an unsigned integer from a resource. - * This integer is originally 28 bits. - * - * @param resourceBundle a string resource - * @param status fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * could be a non-failing error - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return an integer value - * @see ures_getInt - * @see ures_getIntVector - * @see ures_getBinary - * @see ures_getString - * @stable ICU 2.0 - */ -U_STABLE uint32_t U_EXPORT2 -ures_getUInt(const UResourceBundle* resourceBundle, - UErrorCode *status); - -/** - * Returns a signed integer from a resource. - * This integer is originally 28 bit and the sign gets propagated. - * - * @param resourceBundle a string resource - * @param status fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * could be a non-failing error - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return an integer value - * @see ures_getUInt - * @see ures_getIntVector - * @see ures_getBinary - * @see ures_getString - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ures_getInt(const UResourceBundle* resourceBundle, - UErrorCode *status); - -/** - * Returns the size of a resource. Size for scalar types is always 1, - * and for vector/table types is the number of child resources. - * @warning Integer array is treated as a scalar type. There are no - * APIs to access individual members of an integer array. It - * is always returned as a whole. - * @param resourceBundle a resource - * @return number of resources in a given resource. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -ures_getSize(const UResourceBundle *resourceBundle); - -/** - * Returns the type of a resource. Available types are defined in enum UResType - * - * @param resourceBundle a resource - * @return type of the given resource. - * @see UResType - * @stable ICU 2.0 - */ -U_STABLE UResType U_EXPORT2 -ures_getType(const UResourceBundle *resourceBundle); - -/** - * Returns the key associated with a given resource. Not all the resources have a key - only - * those that are members of a table. - * - * @param resourceBundle a resource - * @return a key associated to this resource, or NULL if it doesn't have a key - * @stable ICU 2.0 - */ -U_STABLE const char * U_EXPORT2 -ures_getKey(const UResourceBundle *resourceBundle); - -/* ITERATION API - This API provides means for iterating through a resource -*/ - -/** - * Resets the internal context of a resource so that iteration starts from the first element. - * - * @param resourceBundle a resource - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -ures_resetIterator(UResourceBundle *resourceBundle); - -/** - * Checks whether the given resource has another element to iterate over. - * - * @param resourceBundle a resource - * @return TRUE if there are more elements, FALSE if there is no more elements - * @stable ICU 2.0 - */ -U_STABLE UBool U_EXPORT2 -ures_hasNext(const UResourceBundle *resourceBundle); - -/** - * Returns the next resource in a given resource or NULL if there are no more resources - * to iterate over. Features a fill-in parameter. - * - * @param resourceBundle a resource - * @param fillIn if NULL a new UResourceBundle struct is allocated and must be closed by the caller. - * Alternatively, you can supply a struct to be filled by this function. - * @param status fills in the outgoing error code. You may still get a non NULL result even if an - * error occured. Check status instead. - * @return a pointer to a UResourceBundle struct. If fill in param was NULL, caller must close it - * @stable ICU 2.0 - */ -U_STABLE UResourceBundle* U_EXPORT2 -ures_getNextResource(UResourceBundle *resourceBundle, - UResourceBundle *fillIn, - UErrorCode *status); - -/** - * Returns the next string in a given resource or NULL if there are no more resources - * to iterate over. - * - * @param resourceBundle a resource - * @param len fill in length of the string - * @param key fill in for key associated with this string. NULL if no key - * @param status fills in the outgoing error code. If an error occured, we may return NULL, but don't - * count on it. Check status instead! - * @return a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file. - * @stable ICU 2.0 - */ -U_STABLE const UChar* U_EXPORT2 -ures_getNextString(UResourceBundle *resourceBundle, - int32_t* len, - const char ** key, - UErrorCode *status); - -/** - * Returns the resource in a given resource at the specified index. Features a fill-in parameter. - * - * @param resourceBundle the resource bundle from which to get a sub-resource - * @param indexR an index to the wanted resource. - * @param fillIn if NULL a new UResourceBundle struct is allocated and must be closed by the caller. - * Alternatively, you can supply a struct to be filled by this function. - * @param status fills in the outgoing error code. Don't count on NULL being returned if an error has - * occured. Check status instead. - * @return a pointer to a UResourceBundle struct. If fill in param was NULL, caller must close it - * @stable ICU 2.0 - */ -U_STABLE UResourceBundle* U_EXPORT2 -ures_getByIndex(const UResourceBundle *resourceBundle, - int32_t indexR, - UResourceBundle *fillIn, - UErrorCode *status); - -/** - * Returns the string in a given resource at the specified index. - * - * @param resourceBundle a resource - * @param indexS an index to the wanted string. - * @param len fill in length of the string - * @param status fills in the outgoing error code. If an error occured, we may return NULL, but don't - * count on it. Check status instead! - * @return a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file. - * @stable ICU 2.0 - */ -U_STABLE const UChar* U_EXPORT2 -ures_getStringByIndex(const UResourceBundle *resourceBundle, - int32_t indexS, - int32_t* len, - UErrorCode *status); - -/** - * Returns a UTF-8 string from a resource at the specified index. - * The UTF-8 string may be returnable directly as a pointer, or - * it may need to be copied, or transformed from UTF-16 using u_strToUTF8() - * or equivalent. - * - * If forceCopy==TRUE, then the string is always written to the dest buffer - * and dest is returned. - * - * If forceCopy==FALSE, then the string is returned as a pointer if possible, - * without needing a dest buffer (it can be NULL). If the string needs to be - * copied or transformed, then it may be placed into dest at an arbitrary offset. - * - * If the string is to be written to dest, then U_BUFFER_OVERFLOW_ERROR and - * U_STRING_NOT_TERMINATED_WARNING are set if appropriate, as usual. - * - * If the string is transformed from UTF-16, then a conversion error may occur - * if an unpaired surrogate is encountered. If the function is successful, then - * the output UTF-8 string is always well-formed. - * - * @param resB Resource bundle. - * @param stringIndex An index to the wanted string. - * @param dest Destination buffer. Can be NULL only if capacity=*length==0. - * @param pLength Input: Capacity of destination buffer. - * Output: Actual length of the UTF-8 string, not counting the - * terminating NUL, even in case of U_BUFFER_OVERFLOW_ERROR. - * Can be NULL, meaning capacity=0 and the string length is not - * returned to the caller. - * @param forceCopy If TRUE, then the output string will always be written to - * dest, with U_BUFFER_OVERFLOW_ERROR and - * U_STRING_NOT_TERMINATED_WARNING set if appropriate. - * If FALSE, then the dest buffer may or may not contain a - * copy of the string. dest may or may not be modified. - * If a copy needs to be written, then the UErrorCode parameter - * indicates overflow etc. as usual. - * @param status Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The pointer to the UTF-8 string. It may be dest, or at some offset - * from dest (only if !forceCopy), or in unrelated memory. - * Always NUL-terminated unless the string was written to dest and - * length==capacity (in which case U_STRING_NOT_TERMINATED_WARNING is set). - * - * @see ures_getStringByIndex - * @see u_strToUTF8 - * @stable ICU 3.6 - */ -U_STABLE const char * U_EXPORT2 -ures_getUTF8StringByIndex(const UResourceBundle *resB, - int32_t stringIndex, - char *dest, int32_t *pLength, - UBool forceCopy, - UErrorCode *status); - -/** - * Returns a resource in a given resource that has a given key. This procedure works only with table - * resources. Features a fill-in parameter. - * - * @param resourceBundle a resource - * @param key a key associated with the wanted resource - * @param fillIn if NULL a new UResourceBundle struct is allocated and must be closed by the caller. - * Alternatively, you can supply a struct to be filled by this function. - * @param status fills in the outgoing error code. - * @return a pointer to a UResourceBundle struct. If fill in param was NULL, caller must close it - * @stable ICU 2.0 - */ -U_STABLE UResourceBundle* U_EXPORT2 -ures_getByKey(const UResourceBundle *resourceBundle, - const char* key, - UResourceBundle *fillIn, - UErrorCode *status); - -/** - * Returns a string in a given resource that has a given key. This procedure works only with table - * resources. - * - * @param resB a resource - * @param key a key associated with the wanted string - * @param len fill in length of the string - * @param status fills in the outgoing error code. If an error occured, we may return NULL, but don't - * count on it. Check status instead! - * @return a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file. - * @stable ICU 2.0 - */ -U_STABLE const UChar* U_EXPORT2 -ures_getStringByKey(const UResourceBundle *resB, - const char* key, - int32_t* len, - UErrorCode *status); - -/** - * Returns a UTF-8 string from a resource and a key. - * This function works only with table resources. - * - * The UTF-8 string may be returnable directly as a pointer, or - * it may need to be copied, or transformed from UTF-16 using u_strToUTF8() - * or equivalent. - * - * If forceCopy==TRUE, then the string is always written to the dest buffer - * and dest is returned. - * - * If forceCopy==FALSE, then the string is returned as a pointer if possible, - * without needing a dest buffer (it can be NULL). If the string needs to be - * copied or transformed, then it may be placed into dest at an arbitrary offset. - * - * If the string is to be written to dest, then U_BUFFER_OVERFLOW_ERROR and - * U_STRING_NOT_TERMINATED_WARNING are set if appropriate, as usual. - * - * If the string is transformed from UTF-16, then a conversion error may occur - * if an unpaired surrogate is encountered. If the function is successful, then - * the output UTF-8 string is always well-formed. - * - * @param resB Resource bundle. - * @param key A key associated with the wanted resource - * @param dest Destination buffer. Can be NULL only if capacity=*length==0. - * @param pLength Input: Capacity of destination buffer. - * Output: Actual length of the UTF-8 string, not counting the - * terminating NUL, even in case of U_BUFFER_OVERFLOW_ERROR. - * Can be NULL, meaning capacity=0 and the string length is not - * returned to the caller. - * @param forceCopy If TRUE, then the output string will always be written to - * dest, with U_BUFFER_OVERFLOW_ERROR and - * U_STRING_NOT_TERMINATED_WARNING set if appropriate. - * If FALSE, then the dest buffer may or may not contain a - * copy of the string. dest may or may not be modified. - * If a copy needs to be written, then the UErrorCode parameter - * indicates overflow etc. as usual. - * @param status Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The pointer to the UTF-8 string. It may be dest, or at some offset - * from dest (only if !forceCopy), or in unrelated memory. - * Always NUL-terminated unless the string was written to dest and - * length==capacity (in which case U_STRING_NOT_TERMINATED_WARNING is set). - * - * @see ures_getStringByKey - * @see u_strToUTF8 - * @stable ICU 3.6 - */ -U_STABLE const char * U_EXPORT2 -ures_getUTF8StringByKey(const UResourceBundle *resB, - const char *key, - char *dest, int32_t *pLength, - UBool forceCopy, - UErrorCode *status); - -#if U_SHOW_CPLUSPLUS_API -#include "unicode/unistr.h" - -U_NAMESPACE_BEGIN -/** - * Returns the string value from a string resource bundle. - * - * @param resB a resource, should have type URES_STRING - * @param status: fills in the outgoing error code - * could be U_MISSING_RESOURCE_ERROR if the key is not found - * could be a non-failing error - * e.g.: U_USING_FALLBACK_WARNING,U_USING_DEFAULT_WARNING - * @return The string value, or a bogus string if there is a failure UErrorCode. - * @stable ICU 2.0 - */ -inline UnicodeString -ures_getUnicodeString(const UResourceBundle *resB, UErrorCode* status) { - UnicodeString result; - int32_t len = 0; - const UChar *r = ures_getString(resB, &len, status); - if(U_SUCCESS(*status)) { - result.setTo(TRUE, r, len); - } else { - result.setToBogus(); - } - return result; -} - -/** - * Returns the next string in a resource, or an empty string if there are no more resources - * to iterate over. - * Use ures_getNextString() instead to distinguish between - * the end of the iteration and a real empty string value. - * - * @param resB a resource - * @param key fill in for key associated with this string - * @param status fills in the outgoing error code - * @return The string value, or a bogus string if there is a failure UErrorCode. - * @stable ICU 2.0 - */ -inline UnicodeString -ures_getNextUnicodeString(UResourceBundle *resB, const char ** key, UErrorCode* status) { - UnicodeString result; - int32_t len = 0; - const UChar* r = ures_getNextString(resB, &len, key, status); - if(U_SUCCESS(*status)) { - result.setTo(TRUE, r, len); - } else { - result.setToBogus(); - } - return result; -} - -/** - * Returns the string in a given resource array or table at the specified index. - * - * @param resB a resource - * @param indexS an index to the wanted string. - * @param status fills in the outgoing error code - * @return The string value, or a bogus string if there is a failure UErrorCode. - * @stable ICU 2.0 - */ -inline UnicodeString -ures_getUnicodeStringByIndex(const UResourceBundle *resB, int32_t indexS, UErrorCode* status) { - UnicodeString result; - int32_t len = 0; - const UChar* r = ures_getStringByIndex(resB, indexS, &len, status); - if(U_SUCCESS(*status)) { - result.setTo(TRUE, r, len); - } else { - result.setToBogus(); - } - return result; -} - -/** - * Returns a string in a resource that has a given key. - * This procedure works only with table resources. - * - * @param resB a resource - * @param key a key associated with the wanted string - * @param status fills in the outgoing error code - * @return The string value, or a bogus string if there is a failure UErrorCode. - * @stable ICU 2.0 - */ -inline UnicodeString -ures_getUnicodeStringByKey(const UResourceBundle *resB, const char* key, UErrorCode* status) { - UnicodeString result; - int32_t len = 0; - const UChar* r = ures_getStringByKey(resB, key, &len, status); - if(U_SUCCESS(*status)) { - result.setTo(TRUE, r, len); - } else { - result.setToBogus(); - } - return result; -} - -U_NAMESPACE_END - -#endif - -/** - * Create a string enumerator, owned by the caller, of all locales located within - * the specified resource tree. - * @param packageName name of the tree, such as (NULL) or U_ICUDATA_ALIAS or or "ICUDATA-coll" - * This call is similar to uloc_getAvailable(). - * @param status error code - * @stable ICU 3.2 - */ -U_STABLE UEnumeration* U_EXPORT2 -ures_openAvailableLocales(const char *packageName, UErrorCode *status); - - -#endif /*_URES*/ -/*eof*/ diff --git a/win32/include/spidermonkey/unicode/uscript.h b/win32/include/spidermonkey/unicode/uscript.h deleted file mode 100755 index a20cd157..00000000 --- a/win32/include/spidermonkey/unicode/uscript.h +++ /dev/null @@ -1,668 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ********************************************************************** - * Copyright (C) 1997-2016, International Business Machines - * Corporation and others. All Rights Reserved. - ********************************************************************** - * - * File USCRIPT.H - * - * Modification History: - * - * Date Name Description - * 07/06/2001 Ram Creation. - ****************************************************************************** - */ - -#ifndef USCRIPT_H -#define USCRIPT_H -#include "unicode/utypes.h" - -/** - * \file - * \brief C API: Unicode Script Information - */ - -/** - * Constants for ISO 15924 script codes. - * - * The current set of script code constants supports at least all scripts - * that are encoded in the version of Unicode which ICU currently supports. - * The names of the constants are usually derived from the - * Unicode script property value aliases. - * See UAX #24 Unicode Script Property (http://www.unicode.org/reports/tr24/) - * and http://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt . - * - * In addition, constants for many ISO 15924 script codes - * are included, for use with language tags, CLDR data, and similar. - * Some of those codes are not used in the Unicode Character Database (UCD). - * For example, there are no characters that have a UCD script property value of - * Hans or Hant. All Han ideographs have the Hani script property value in Unicode. - * - * Private-use codes Qaaa..Qabx are not included, except as used in the UCD or in CLDR. - * - * Starting with ICU 55, script codes are only added when their scripts - * have been or will certainly be encoded in Unicode, - * and have been assigned Unicode script property value aliases, - * to ensure that their script names are stable and match the names of the constants. - * Script codes like Latf and Aran that are not subject to separate encoding - * may be added at any time. - * - * @stable ICU 2.2 - */ -typedef enum UScriptCode { - /* - * Note: UScriptCode constants and their ISO script code comments - * are parsed by preparseucd.py. - * It matches lines like - * USCRIPT_ = , / * * / - */ - - /** @stable ICU 2.2 */ - USCRIPT_INVALID_CODE = -1, - /** @stable ICU 2.2 */ - USCRIPT_COMMON = 0, /* Zyyy */ - /** @stable ICU 2.2 */ - USCRIPT_INHERITED = 1, /* Zinh */ /* "Code for inherited script", for non-spacing combining marks; also Qaai */ - /** @stable ICU 2.2 */ - USCRIPT_ARABIC = 2, /* Arab */ - /** @stable ICU 2.2 */ - USCRIPT_ARMENIAN = 3, /* Armn */ - /** @stable ICU 2.2 */ - USCRIPT_BENGALI = 4, /* Beng */ - /** @stable ICU 2.2 */ - USCRIPT_BOPOMOFO = 5, /* Bopo */ - /** @stable ICU 2.2 */ - USCRIPT_CHEROKEE = 6, /* Cher */ - /** @stable ICU 2.2 */ - USCRIPT_COPTIC = 7, /* Copt */ - /** @stable ICU 2.2 */ - USCRIPT_CYRILLIC = 8, /* Cyrl */ - /** @stable ICU 2.2 */ - USCRIPT_DESERET = 9, /* Dsrt */ - /** @stable ICU 2.2 */ - USCRIPT_DEVANAGARI = 10, /* Deva */ - /** @stable ICU 2.2 */ - USCRIPT_ETHIOPIC = 11, /* Ethi */ - /** @stable ICU 2.2 */ - USCRIPT_GEORGIAN = 12, /* Geor */ - /** @stable ICU 2.2 */ - USCRIPT_GOTHIC = 13, /* Goth */ - /** @stable ICU 2.2 */ - USCRIPT_GREEK = 14, /* Grek */ - /** @stable ICU 2.2 */ - USCRIPT_GUJARATI = 15, /* Gujr */ - /** @stable ICU 2.2 */ - USCRIPT_GURMUKHI = 16, /* Guru */ - /** @stable ICU 2.2 */ - USCRIPT_HAN = 17, /* Hani */ - /** @stable ICU 2.2 */ - USCRIPT_HANGUL = 18, /* Hang */ - /** @stable ICU 2.2 */ - USCRIPT_HEBREW = 19, /* Hebr */ - /** @stable ICU 2.2 */ - USCRIPT_HIRAGANA = 20, /* Hira */ - /** @stable ICU 2.2 */ - USCRIPT_KANNADA = 21, /* Knda */ - /** @stable ICU 2.2 */ - USCRIPT_KATAKANA = 22, /* Kana */ - /** @stable ICU 2.2 */ - USCRIPT_KHMER = 23, /* Khmr */ - /** @stable ICU 2.2 */ - USCRIPT_LAO = 24, /* Laoo */ - /** @stable ICU 2.2 */ - USCRIPT_LATIN = 25, /* Latn */ - /** @stable ICU 2.2 */ - USCRIPT_MALAYALAM = 26, /* Mlym */ - /** @stable ICU 2.2 */ - USCRIPT_MONGOLIAN = 27, /* Mong */ - /** @stable ICU 2.2 */ - USCRIPT_MYANMAR = 28, /* Mymr */ - /** @stable ICU 2.2 */ - USCRIPT_OGHAM = 29, /* Ogam */ - /** @stable ICU 2.2 */ - USCRIPT_OLD_ITALIC = 30, /* Ital */ - /** @stable ICU 2.2 */ - USCRIPT_ORIYA = 31, /* Orya */ - /** @stable ICU 2.2 */ - USCRIPT_RUNIC = 32, /* Runr */ - /** @stable ICU 2.2 */ - USCRIPT_SINHALA = 33, /* Sinh */ - /** @stable ICU 2.2 */ - USCRIPT_SYRIAC = 34, /* Syrc */ - /** @stable ICU 2.2 */ - USCRIPT_TAMIL = 35, /* Taml */ - /** @stable ICU 2.2 */ - USCRIPT_TELUGU = 36, /* Telu */ - /** @stable ICU 2.2 */ - USCRIPT_THAANA = 37, /* Thaa */ - /** @stable ICU 2.2 */ - USCRIPT_THAI = 38, /* Thai */ - /** @stable ICU 2.2 */ - USCRIPT_TIBETAN = 39, /* Tibt */ - /** Canadian_Aboriginal script. @stable ICU 2.6 */ - USCRIPT_CANADIAN_ABORIGINAL = 40, /* Cans */ - /** Canadian_Aboriginal script (alias). @stable ICU 2.2 */ - USCRIPT_UCAS = USCRIPT_CANADIAN_ABORIGINAL, - /** @stable ICU 2.2 */ - USCRIPT_YI = 41, /* Yiii */ - /* New scripts in Unicode 3.2 */ - /** @stable ICU 2.2 */ - USCRIPT_TAGALOG = 42, /* Tglg */ - /** @stable ICU 2.2 */ - USCRIPT_HANUNOO = 43, /* Hano */ - /** @stable ICU 2.2 */ - USCRIPT_BUHID = 44, /* Buhd */ - /** @stable ICU 2.2 */ - USCRIPT_TAGBANWA = 45, /* Tagb */ - - /* New scripts in Unicode 4 */ - /** @stable ICU 2.6 */ - USCRIPT_BRAILLE = 46, /* Brai */ - /** @stable ICU 2.6 */ - USCRIPT_CYPRIOT = 47, /* Cprt */ - /** @stable ICU 2.6 */ - USCRIPT_LIMBU = 48, /* Limb */ - /** @stable ICU 2.6 */ - USCRIPT_LINEAR_B = 49, /* Linb */ - /** @stable ICU 2.6 */ - USCRIPT_OSMANYA = 50, /* Osma */ - /** @stable ICU 2.6 */ - USCRIPT_SHAVIAN = 51, /* Shaw */ - /** @stable ICU 2.6 */ - USCRIPT_TAI_LE = 52, /* Tale */ - /** @stable ICU 2.6 */ - USCRIPT_UGARITIC = 53, /* Ugar */ - - /** New script code in Unicode 4.0.1 @stable ICU 3.0 */ - USCRIPT_KATAKANA_OR_HIRAGANA = 54,/*Hrkt */ - - /* New scripts in Unicode 4.1 */ - /** @stable ICU 3.4 */ - USCRIPT_BUGINESE = 55, /* Bugi */ - /** @stable ICU 3.4 */ - USCRIPT_GLAGOLITIC = 56, /* Glag */ - /** @stable ICU 3.4 */ - USCRIPT_KHAROSHTHI = 57, /* Khar */ - /** @stable ICU 3.4 */ - USCRIPT_SYLOTI_NAGRI = 58, /* Sylo */ - /** @stable ICU 3.4 */ - USCRIPT_NEW_TAI_LUE = 59, /* Talu */ - /** @stable ICU 3.4 */ - USCRIPT_TIFINAGH = 60, /* Tfng */ - /** @stable ICU 3.4 */ - USCRIPT_OLD_PERSIAN = 61, /* Xpeo */ - - /* New script codes from Unicode and ISO 15924 */ - /** @stable ICU 3.6 */ - USCRIPT_BALINESE = 62, /* Bali */ - /** @stable ICU 3.6 */ - USCRIPT_BATAK = 63, /* Batk */ - /** @stable ICU 3.6 */ - USCRIPT_BLISSYMBOLS = 64, /* Blis */ - /** @stable ICU 3.6 */ - USCRIPT_BRAHMI = 65, /* Brah */ - /** @stable ICU 3.6 */ - USCRIPT_CHAM = 66, /* Cham */ - /** @stable ICU 3.6 */ - USCRIPT_CIRTH = 67, /* Cirt */ - /** @stable ICU 3.6 */ - USCRIPT_OLD_CHURCH_SLAVONIC_CYRILLIC = 68, /* Cyrs */ - /** @stable ICU 3.6 */ - USCRIPT_DEMOTIC_EGYPTIAN = 69, /* Egyd */ - /** @stable ICU 3.6 */ - USCRIPT_HIERATIC_EGYPTIAN = 70, /* Egyh */ - /** @stable ICU 3.6 */ - USCRIPT_EGYPTIAN_HIEROGLYPHS = 71, /* Egyp */ - /** @stable ICU 3.6 */ - USCRIPT_KHUTSURI = 72, /* Geok */ - /** @stable ICU 3.6 */ - USCRIPT_SIMPLIFIED_HAN = 73, /* Hans */ - /** @stable ICU 3.6 */ - USCRIPT_TRADITIONAL_HAN = 74, /* Hant */ - /** @stable ICU 3.6 */ - USCRIPT_PAHAWH_HMONG = 75, /* Hmng */ - /** @stable ICU 3.6 */ - USCRIPT_OLD_HUNGARIAN = 76, /* Hung */ - /** @stable ICU 3.6 */ - USCRIPT_HARAPPAN_INDUS = 77, /* Inds */ - /** @stable ICU 3.6 */ - USCRIPT_JAVANESE = 78, /* Java */ - /** @stable ICU 3.6 */ - USCRIPT_KAYAH_LI = 79, /* Kali */ - /** @stable ICU 3.6 */ - USCRIPT_LATIN_FRAKTUR = 80, /* Latf */ - /** @stable ICU 3.6 */ - USCRIPT_LATIN_GAELIC = 81, /* Latg */ - /** @stable ICU 3.6 */ - USCRIPT_LEPCHA = 82, /* Lepc */ - /** @stable ICU 3.6 */ - USCRIPT_LINEAR_A = 83, /* Lina */ - /** @stable ICU 4.6 */ - USCRIPT_MANDAIC = 84, /* Mand */ - /** @stable ICU 3.6 */ - USCRIPT_MANDAEAN = USCRIPT_MANDAIC, - /** @stable ICU 3.6 */ - USCRIPT_MAYAN_HIEROGLYPHS = 85, /* Maya */ - /** @stable ICU 4.6 */ - USCRIPT_MEROITIC_HIEROGLYPHS = 86, /* Mero */ - /** @stable ICU 3.6 */ - USCRIPT_MEROITIC = USCRIPT_MEROITIC_HIEROGLYPHS, - /** @stable ICU 3.6 */ - USCRIPT_NKO = 87, /* Nkoo */ - /** @stable ICU 3.6 */ - USCRIPT_ORKHON = 88, /* Orkh */ - /** @stable ICU 3.6 */ - USCRIPT_OLD_PERMIC = 89, /* Perm */ - /** @stable ICU 3.6 */ - USCRIPT_PHAGS_PA = 90, /* Phag */ - /** @stable ICU 3.6 */ - USCRIPT_PHOENICIAN = 91, /* Phnx */ - /** @stable ICU 52 */ - USCRIPT_MIAO = 92, /* Plrd */ - /** @stable ICU 3.6 */ - USCRIPT_PHONETIC_POLLARD = USCRIPT_MIAO, - /** @stable ICU 3.6 */ - USCRIPT_RONGORONGO = 93, /* Roro */ - /** @stable ICU 3.6 */ - USCRIPT_SARATI = 94, /* Sara */ - /** @stable ICU 3.6 */ - USCRIPT_ESTRANGELO_SYRIAC = 95, /* Syre */ - /** @stable ICU 3.6 */ - USCRIPT_WESTERN_SYRIAC = 96, /* Syrj */ - /** @stable ICU 3.6 */ - USCRIPT_EASTERN_SYRIAC = 97, /* Syrn */ - /** @stable ICU 3.6 */ - USCRIPT_TENGWAR = 98, /* Teng */ - /** @stable ICU 3.6 */ - USCRIPT_VAI = 99, /* Vaii */ - /** @stable ICU 3.6 */ - USCRIPT_VISIBLE_SPEECH = 100,/* Visp */ - /** @stable ICU 3.6 */ - USCRIPT_CUNEIFORM = 101,/* Xsux */ - /** @stable ICU 3.6 */ - USCRIPT_UNWRITTEN_LANGUAGES = 102,/* Zxxx */ - /** @stable ICU 3.6 */ - USCRIPT_UNKNOWN = 103,/* Zzzz */ /* Unknown="Code for uncoded script", for unassigned code points */ - - /** @stable ICU 3.8 */ - USCRIPT_CARIAN = 104,/* Cari */ - /** @stable ICU 3.8 */ - USCRIPT_JAPANESE = 105,/* Jpan */ - /** @stable ICU 3.8 */ - USCRIPT_LANNA = 106,/* Lana */ - /** @stable ICU 3.8 */ - USCRIPT_LYCIAN = 107,/* Lyci */ - /** @stable ICU 3.8 */ - USCRIPT_LYDIAN = 108,/* Lydi */ - /** @stable ICU 3.8 */ - USCRIPT_OL_CHIKI = 109,/* Olck */ - /** @stable ICU 3.8 */ - USCRIPT_REJANG = 110,/* Rjng */ - /** @stable ICU 3.8 */ - USCRIPT_SAURASHTRA = 111,/* Saur */ - /** Sutton SignWriting @stable ICU 3.8 */ - USCRIPT_SIGN_WRITING = 112,/* Sgnw */ - /** @stable ICU 3.8 */ - USCRIPT_SUNDANESE = 113,/* Sund */ - /** @stable ICU 3.8 */ - USCRIPT_MOON = 114,/* Moon */ - /** @stable ICU 3.8 */ - USCRIPT_MEITEI_MAYEK = 115,/* Mtei */ - - /** @stable ICU 4.0 */ - USCRIPT_IMPERIAL_ARAMAIC = 116,/* Armi */ - /** @stable ICU 4.0 */ - USCRIPT_AVESTAN = 117,/* Avst */ - /** @stable ICU 4.0 */ - USCRIPT_CHAKMA = 118,/* Cakm */ - /** @stable ICU 4.0 */ - USCRIPT_KOREAN = 119,/* Kore */ - /** @stable ICU 4.0 */ - USCRIPT_KAITHI = 120,/* Kthi */ - /** @stable ICU 4.0 */ - USCRIPT_MANICHAEAN = 121,/* Mani */ - /** @stable ICU 4.0 */ - USCRIPT_INSCRIPTIONAL_PAHLAVI = 122,/* Phli */ - /** @stable ICU 4.0 */ - USCRIPT_PSALTER_PAHLAVI = 123,/* Phlp */ - /** @stable ICU 4.0 */ - USCRIPT_BOOK_PAHLAVI = 124,/* Phlv */ - /** @stable ICU 4.0 */ - USCRIPT_INSCRIPTIONAL_PARTHIAN = 125,/* Prti */ - /** @stable ICU 4.0 */ - USCRIPT_SAMARITAN = 126,/* Samr */ - /** @stable ICU 4.0 */ - USCRIPT_TAI_VIET = 127,/* Tavt */ - /** @stable ICU 4.0 */ - USCRIPT_MATHEMATICAL_NOTATION = 128,/* Zmth */ - /** @stable ICU 4.0 */ - USCRIPT_SYMBOLS = 129,/* Zsym */ - - /** @stable ICU 4.4 */ - USCRIPT_BAMUM = 130,/* Bamu */ - /** @stable ICU 4.4 */ - USCRIPT_LISU = 131,/* Lisu */ - /** @stable ICU 4.4 */ - USCRIPT_NAKHI_GEBA = 132,/* Nkgb */ - /** @stable ICU 4.4 */ - USCRIPT_OLD_SOUTH_ARABIAN = 133,/* Sarb */ - - /** @stable ICU 4.6 */ - USCRIPT_BASSA_VAH = 134,/* Bass */ - /** @stable ICU 54 */ - USCRIPT_DUPLOYAN = 135,/* Dupl */ -#ifndef U_HIDE_DEPRECATED_API - /** @deprecated ICU 54 Typo, use USCRIPT_DUPLOYAN */ - USCRIPT_DUPLOYAN_SHORTAND = USCRIPT_DUPLOYAN, -#endif /* U_HIDE_DEPRECATED_API */ - /** @stable ICU 4.6 */ - USCRIPT_ELBASAN = 136,/* Elba */ - /** @stable ICU 4.6 */ - USCRIPT_GRANTHA = 137,/* Gran */ - /** @stable ICU 4.6 */ - USCRIPT_KPELLE = 138,/* Kpel */ - /** @stable ICU 4.6 */ - USCRIPT_LOMA = 139,/* Loma */ - /** Mende Kikakui @stable ICU 4.6 */ - USCRIPT_MENDE = 140,/* Mend */ - /** @stable ICU 4.6 */ - USCRIPT_MEROITIC_CURSIVE = 141,/* Merc */ - /** @stable ICU 4.6 */ - USCRIPT_OLD_NORTH_ARABIAN = 142,/* Narb */ - /** @stable ICU 4.6 */ - USCRIPT_NABATAEAN = 143,/* Nbat */ - /** @stable ICU 4.6 */ - USCRIPT_PALMYRENE = 144,/* Palm */ - /** @stable ICU 54 */ - USCRIPT_KHUDAWADI = 145,/* Sind */ - /** @stable ICU 4.6 */ - USCRIPT_SINDHI = USCRIPT_KHUDAWADI, - /** @stable ICU 4.6 */ - USCRIPT_WARANG_CITI = 146,/* Wara */ - - /** @stable ICU 4.8 */ - USCRIPT_AFAKA = 147,/* Afak */ - /** @stable ICU 4.8 */ - USCRIPT_JURCHEN = 148,/* Jurc */ - /** @stable ICU 4.8 */ - USCRIPT_MRO = 149,/* Mroo */ - /** @stable ICU 4.8 */ - USCRIPT_NUSHU = 150,/* Nshu */ - /** @stable ICU 4.8 */ - USCRIPT_SHARADA = 151,/* Shrd */ - /** @stable ICU 4.8 */ - USCRIPT_SORA_SOMPENG = 152,/* Sora */ - /** @stable ICU 4.8 */ - USCRIPT_TAKRI = 153,/* Takr */ - /** @stable ICU 4.8 */ - USCRIPT_TANGUT = 154,/* Tang */ - /** @stable ICU 4.8 */ - USCRIPT_WOLEAI = 155,/* Wole */ - - /** @stable ICU 49 */ - USCRIPT_ANATOLIAN_HIEROGLYPHS = 156,/* Hluw */ - /** @stable ICU 49 */ - USCRIPT_KHOJKI = 157,/* Khoj */ - /** @stable ICU 49 */ - USCRIPT_TIRHUTA = 158,/* Tirh */ - - /** @stable ICU 52 */ - USCRIPT_CAUCASIAN_ALBANIAN = 159,/* Aghb */ - /** @stable ICU 52 */ - USCRIPT_MAHAJANI = 160,/* Mahj */ - - /** @stable ICU 54 */ - USCRIPT_AHOM = 161,/* Ahom */ - /** @stable ICU 54 */ - USCRIPT_HATRAN = 162,/* Hatr */ - /** @stable ICU 54 */ - USCRIPT_MODI = 163,/* Modi */ - /** @stable ICU 54 */ - USCRIPT_MULTANI = 164,/* Mult */ - /** @stable ICU 54 */ - USCRIPT_PAU_CIN_HAU = 165,/* Pauc */ - /** @stable ICU 54 */ - USCRIPT_SIDDHAM = 166,/* Sidd */ - - /** @stable ICU 58 */ - USCRIPT_ADLAM = 167,/* Adlm */ - /** @stable ICU 58 */ - USCRIPT_BHAIKSUKI = 168,/* Bhks */ - /** @stable ICU 58 */ - USCRIPT_MARCHEN = 169,/* Marc */ - /** @stable ICU 58 */ - USCRIPT_NEWA = 170,/* Newa */ - /** @stable ICU 58 */ - USCRIPT_OSAGE = 171,/* Osge */ - - /** @stable ICU 58 */ - USCRIPT_HAN_WITH_BOPOMOFO = 172,/* Hanb */ - /** @stable ICU 58 */ - USCRIPT_JAMO = 173,/* Jamo */ - /** @stable ICU 58 */ - USCRIPT_SYMBOLS_EMOJI = 174,/* Zsye */ - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UScriptCode value. - * The highest value is available via u_getIntPropertyMaxValue(UCHAR_SCRIPT). - * - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - USCRIPT_CODE_LIMIT = 175 -#endif // U_HIDE_DEPRECATED_API -} UScriptCode; - -/** - * Gets the script codes associated with the given locale or ISO 15924 abbreviation or name. - * Fills in USCRIPT_MALAYALAM given "Malayam" OR "Mlym". - * Fills in USCRIPT_LATIN given "en" OR "en_US" - * If the required capacity is greater than the capacity of the destination buffer, - * then the error code is set to U_BUFFER_OVERFLOW_ERROR and the required capacity is returned. - * - *

Note: To search by short or long script alias only, use - * u_getPropertyValueEnum(UCHAR_SCRIPT, alias) instead. That does - * a fast lookup with no access of the locale data. - * - * @param nameOrAbbrOrLocale name of the script, as given in - * PropertyValueAliases.txt, or ISO 15924 code or locale - * @param fillIn the UScriptCode buffer to fill in the script code - * @param capacity the capacity (size) fo UScriptCode buffer passed in. - * @param err the error status code. - * @return The number of script codes filled in the buffer passed in - * @stable ICU 2.4 - */ -U_STABLE int32_t U_EXPORT2 -uscript_getCode(const char* nameOrAbbrOrLocale,UScriptCode* fillIn,int32_t capacity,UErrorCode *err); - -/** - * Returns the long Unicode script name, if there is one. - * Otherwise returns the 4-letter ISO 15924 script code. - * Returns "Malayam" given USCRIPT_MALAYALAM. - * - * @param scriptCode UScriptCode enum - * @return long script name as given in PropertyValueAliases.txt, or the 4-letter code, - * or NULL if scriptCode is invalid - * @stable ICU 2.4 - */ -U_STABLE const char* U_EXPORT2 -uscript_getName(UScriptCode scriptCode); - -/** - * Returns the 4-letter ISO 15924 script code, - * which is the same as the short Unicode script name if Unicode has names for the script. - * Returns "Mlym" given USCRIPT_MALAYALAM. - * - * @param scriptCode UScriptCode enum - * @return short script name (4-letter code), or NULL if scriptCode is invalid - * @stable ICU 2.4 - */ -U_STABLE const char* U_EXPORT2 -uscript_getShortName(UScriptCode scriptCode); - -/** - * Gets the script code associated with the given codepoint. - * Returns USCRIPT_MALAYALAM given 0x0D02 - * @param codepoint UChar32 codepoint - * @param err the error status code. - * @return The UScriptCode, or 0 if codepoint is invalid - * @stable ICU 2.4 - */ -U_STABLE UScriptCode U_EXPORT2 -uscript_getScript(UChar32 codepoint, UErrorCode *err); - -/** - * Do the Script_Extensions of code point c contain script sc? - * If c does not have explicit Script_Extensions, then this tests whether - * c has the Script property value sc. - * - * Some characters are commonly used in multiple scripts. - * For more information, see UAX #24: http://www.unicode.org/reports/tr24/. - * @param c code point - * @param sc script code - * @return TRUE if sc is in Script_Extensions(c) - * @stable ICU 49 - */ -U_STABLE UBool U_EXPORT2 -uscript_hasScript(UChar32 c, UScriptCode sc); - -/** - * Writes code point c's Script_Extensions as a list of UScriptCode values - * to the output scripts array and returns the number of script codes. - * - If c does have Script_Extensions, then the Script property value - * (normally Common or Inherited) is not included. - * - If c does not have Script_Extensions, then the one Script code is written to the output array. - * - If c is not a valid code point, then the one USCRIPT_UNKNOWN code is written. - * In other words, if the return value is 1, - * then the output array contains exactly c's single Script code. - * If the return value is n>=2, then the output array contains c's n Script_Extensions script codes. - * - * Some characters are commonly used in multiple scripts. - * For more information, see UAX #24: http://www.unicode.org/reports/tr24/. - * - * If there are more than capacity script codes to be written, then - * U_BUFFER_OVERFLOW_ERROR is set and the number of Script_Extensions is returned. - * (Usual ICU buffer handling behavior.) - * - * @param c code point - * @param scripts output script code array - * @param capacity capacity of the scripts array - * @param errorCode Standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return number of script codes in c's Script_Extensions, or 1 for the single Script value, - * written to scripts unless U_BUFFER_OVERFLOW_ERROR indicates insufficient capacity - * @stable ICU 49 - */ -U_STABLE int32_t U_EXPORT2 -uscript_getScriptExtensions(UChar32 c, - UScriptCode *scripts, int32_t capacity, - UErrorCode *errorCode); - -/** - * Script usage constants. - * See UAX #31 Unicode Identifier and Pattern Syntax. - * http://www.unicode.org/reports/tr31/#Table_Candidate_Characters_for_Exclusion_from_Identifiers - * - * @stable ICU 51 - */ -typedef enum UScriptUsage { - /** Not encoded in Unicode. @stable ICU 51 */ - USCRIPT_USAGE_NOT_ENCODED, - /** Unknown script usage. @stable ICU 51 */ - USCRIPT_USAGE_UNKNOWN, - /** Candidate for Exclusion from Identifiers. @stable ICU 51 */ - USCRIPT_USAGE_EXCLUDED, - /** Limited Use script. @stable ICU 51 */ - USCRIPT_USAGE_LIMITED_USE, - /** Aspirational Use script. @stable ICU 51 */ - USCRIPT_USAGE_ASPIRATIONAL, - /** Recommended script. @stable ICU 51 */ - USCRIPT_USAGE_RECOMMENDED -} UScriptUsage; - -/** - * Writes the script sample character string. - * This string normally consists of one code point but might be longer. - * The string is empty if the script is not encoded. - * - * @param script script code - * @param dest output string array - * @param capacity number of UChars in the dest array - * @param pErrorCode standard ICU in/out error code, must pass U_SUCCESS() on input - * @return the string length, even if U_BUFFER_OVERFLOW_ERROR - * @stable ICU 51 - */ -U_STABLE int32_t U_EXPORT2 -uscript_getSampleString(UScriptCode script, UChar *dest, int32_t capacity, UErrorCode *pErrorCode); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN -class UnicodeString; -U_NAMESPACE_END - -/** - * Returns the script sample character string. - * This string normally consists of one code point but might be longer. - * The string is empty if the script is not encoded. - * - * @param script script code - * @return the sample character string - * @stable ICU 51 - */ -U_COMMON_API icu::UnicodeString U_EXPORT2 -uscript_getSampleUnicodeString(UScriptCode script); - -#endif - -/** - * Returns the script usage according to UAX #31 Unicode Identifier and Pattern Syntax. - * Returns USCRIPT_USAGE_NOT_ENCODED if the script is not encoded in Unicode. - * - * @param script script code - * @return script usage - * @see UScriptUsage - * @stable ICU 51 - */ -U_STABLE UScriptUsage U_EXPORT2 -uscript_getUsage(UScriptCode script); - -/** - * Returns TRUE if the script is written right-to-left. - * For example, Arab and Hebr. - * - * @param script script code - * @return TRUE if the script is right-to-left - * @stable ICU 51 - */ -U_STABLE UBool U_EXPORT2 -uscript_isRightToLeft(UScriptCode script); - -/** - * Returns TRUE if the script allows line breaks between letters (excluding hyphenation). - * Such a script typically requires dictionary-based line breaking. - * For example, Hani and Thai. - * - * @param script script code - * @return TRUE if the script allows line breaks between letters - * @stable ICU 51 - */ -U_STABLE UBool U_EXPORT2 -uscript_breaksBetweenLetters(UScriptCode script); - -/** - * Returns TRUE if in modern (or most recent) usage of the script case distinctions are customary. - * For example, Latn and Cyrl. - * - * @param script script code - * @return TRUE if the script is cased - * @stable ICU 51 - */ -U_STABLE UBool U_EXPORT2 -uscript_isCased(UScriptCode script); - -#endif diff --git a/win32/include/spidermonkey/unicode/usearch.h b/win32/include/spidermonkey/unicode/usearch.h deleted file mode 100755 index b1d53f51..00000000 --- a/win32/include/spidermonkey/unicode/usearch.h +++ /dev/null @@ -1,891 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 2001-2011,2014 IBM and others. All rights reserved. -********************************************************************** -* Date Name Description -* 06/28/2001 synwee Creation. -********************************************************************** -*/ -#ifndef USEARCH_H -#define USEARCH_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION - -#include "unicode/localpointer.h" -#include "unicode/ucol.h" -#include "unicode/ucoleitr.h" -#include "unicode/ubrk.h" - -/** - * \file - * \brief C API: StringSearch - * - * C Apis for an engine that provides language-sensitive text searching based - * on the comparison rules defined in a UCollator data struct, - * see ucol.h. This ensures that language eccentricity can be - * handled, e.g. for the German collator, characters ß and SS will be matched - * if case is chosen to be ignored. - * See the - * "ICU Collation Design Document" for more information. - *

- * The implementation may use a linear search or a modified form of the Boyer-Moore - * search; for more information on the latter see - * - * "Efficient Text Searching in Java", published in Java Report - * in February, 1999. - *

- * There are 2 match options for selection:
- * Let S' be the sub-string of a text string S between the offsets start and - * end . - *
- * A pattern string P matches a text string S at the offsets - * if - *

 
- * option 1. Some canonical equivalent of P matches some canonical equivalent 
- *           of S'
- * option 2. P matches S' and if P starts or ends with a combining mark, 
- *           there exists no non-ignorable combining mark before or after S' 
- *           in S respectively. 
- * 
- * Option 2. will be the default. - *

- * This search has APIs similar to that of other text iteration mechanisms - * such as the break iterators in ubrk.h. Using these - * APIs, it is easy to scan through text looking for all occurances of - * a given pattern. This search iterator allows changing of direction by - * calling a reset followed by a next or previous. - * Though a direction change can occur without calling reset first, - * this operation comes with some speed penalty. - * Generally, match results in the forward direction will match the result - * matches in the backwards direction in the reverse order - *

- * usearch.h provides APIs to specify the starting position - * within the text string to be searched, e.g. usearch_setOffset, - * usearch_preceding and usearch_following. Since the - * starting position will be set as it is specified, please take note that - * there are some dangerous positions which the search may render incorrect - * results: - *

    - *
  • The midst of a substring that requires normalization. - *
  • If the following match is to be found, the position should not be the - * second character which requires to be swapped with the preceding - * character. Vice versa, if the preceding match is to be found, - * position to search from should not be the first character which - * requires to be swapped with the next character. E.g certain Thai and - * Lao characters require swapping. - *
  • If a following pattern match is to be found, any position within a - * contracting sequence except the first will fail. Vice versa if a - * preceding pattern match is to be found, a invalid starting point - * would be any character within a contracting sequence except the last. - *
- *

- * A breakiterator can be used if only matches at logical breaks are desired. - * Using a breakiterator will only give you results that exactly matches the - * boundaries given by the breakiterator. For instance the pattern "e" will - * not be found in the string "\u00e9" if a character break iterator is used. - *

- * Options are provided to handle overlapping matches. - * E.g. In English, overlapping matches produces the result 0 and 2 - * for the pattern "abab" in the text "ababab", where else mutually - * exclusive matches only produce the result of 0. - *

- * Options are also provided to implement "asymmetric search" as described in - * - * UTS #10 Unicode Collation Algorithm, specifically the USearchAttribute - * USEARCH_ELEMENT_COMPARISON and its values. - *

- * Though collator attributes will be taken into consideration while - * performing matches, there are no APIs here for setting and getting the - * attributes. These attributes can be set by getting the collator - * from usearch_getCollator and using the APIs in ucol.h. - * Lastly to update String Search to the new collator attributes, - * usearch_reset() has to be called. - *

- * Restriction:
- * Currently there are no composite characters that consists of a - * character with combining class > 0 before a character with combining - * class == 0. However, if such a character exists in the future, the - * search mechanism does not guarantee the results for option 1. - * - *

- * Example of use:
- *


- * char *tgtstr = "The quick brown fox jumped over the lazy fox";
- * char *patstr = "fox";
- * UChar target[64];
- * UChar pattern[16];
- * UErrorCode status = U_ZERO_ERROR;
- * u_uastrcpy(target, tgtstr);
- * u_uastrcpy(pattern, patstr);
- *
- * UStringSearch *search = usearch_open(pattern, -1, target, -1, "en_US", 
- *                                  NULL, &status);
- * if (U_SUCCESS(status)) {
- *     for (int pos = usearch_first(search, &status); 
- *          pos != USEARCH_DONE; 
- *          pos = usearch_next(search, &status))
- *     {
- *         printf("Found match at %d pos, length is %d\n", pos, 
- *                                        usearch_getMatchLength(search));
- *     }
- * }
- *
- * usearch_close(search);
- * 
- * @stable ICU 2.4 - */ - -/** -* DONE is returned by previous() and next() after all valid matches have -* been returned, and by first() and last() if there are no matches at all. -* @stable ICU 2.4 -*/ -#define USEARCH_DONE -1 - -/** -* Data structure for searching -* @stable ICU 2.4 -*/ -struct UStringSearch; -/** -* Data structure for searching -* @stable ICU 2.4 -*/ -typedef struct UStringSearch UStringSearch; - -/** -* @stable ICU 2.4 -*/ -typedef enum { - /** - * Option for overlapping matches - * @stable ICU 2.4 - */ - USEARCH_OVERLAP = 0, -#ifndef U_HIDE_DEPRECATED_API - /** - * Option for canonical matches; option 1 in header documentation. - * The default value will be USEARCH_OFF. - * Note: Setting this option to USEARCH_ON currently has no effect on - * search behavior, and this option is deprecated. Instead, to control - * canonical match behavior, you must set UCOL_NORMALIZATION_MODE - * appropriately (to UCOL_OFF or UCOL_ON) in the UCollator used by - * the UStringSearch object. - * @see usearch_openFromCollator - * @see usearch_getCollator - * @see usearch_setCollator - * @see ucol_getAttribute - * @deprecated ICU 53 - */ - USEARCH_CANONICAL_MATCH = 1, -#endif /* U_HIDE_DEPRECATED_API */ - /** - * Option to control how collation elements are compared. - * The default value will be USEARCH_STANDARD_ELEMENT_COMPARISON. - * @stable ICU 4.4 - */ - USEARCH_ELEMENT_COMPARISON = 2, - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal USearchAttribute value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - USEARCH_ATTRIBUTE_COUNT = 3 -#endif // U_HIDE_DEPRECATED_API -} USearchAttribute; - -/** -* @stable ICU 2.4 -*/ -typedef enum { - /** - * Default value for any USearchAttribute - * @stable ICU 2.4 - */ - USEARCH_DEFAULT = -1, - /** - * Value for USEARCH_OVERLAP and USEARCH_CANONICAL_MATCH - * @stable ICU 2.4 - */ - USEARCH_OFF, - /** - * Value for USEARCH_OVERLAP and USEARCH_CANONICAL_MATCH - * @stable ICU 2.4 - */ - USEARCH_ON, - /** - * Value (default) for USEARCH_ELEMENT_COMPARISON; - * standard collation element comparison at the specified collator - * strength. - * @stable ICU 4.4 - */ - USEARCH_STANDARD_ELEMENT_COMPARISON, - /** - * Value for USEARCH_ELEMENT_COMPARISON; - * collation element comparison is modified to effectively provide - * behavior between the specified strength and strength - 1. Collation - * elements in the pattern that have the base weight for the specified - * strength are treated as "wildcards" that match an element with any - * other weight at that collation level in the searched text. For - * example, with a secondary-strength English collator, a plain 'e' in - * the pattern will match a plain e or an e with any diacritic in the - * searched text, but an e with diacritic in the pattern will only - * match an e with the same diacritic in the searched text. - * - * This supports "asymmetric search" as described in - * - * UTS #10 Unicode Collation Algorithm. - * - * @stable ICU 4.4 - */ - USEARCH_PATTERN_BASE_WEIGHT_IS_WILDCARD, - /** - * Value for USEARCH_ELEMENT_COMPARISON. - * collation element comparison is modified to effectively provide - * behavior between the specified strength and strength - 1. Collation - * elements in either the pattern or the searched text that have the - * base weight for the specified strength are treated as "wildcards" - * that match an element with any other weight at that collation level. - * For example, with a secondary-strength English collator, a plain 'e' - * in the pattern will match a plain e or an e with any diacritic in the - * searched text, but an e with diacritic in the pattern will only - * match an e with the same diacritic or a plain e in the searched text. - * - * This option is similar to "asymmetric search" as described in - * - * UTS #10 Unicode Collation Algorithmusearch_close. -* @param pattern for matching -* @param patternlength length of the pattern, -1 for null-termination -* @param text text string -* @param textlength length of the text string, -1 for null-termination -* @param locale name of locale for the rules to be used -* @param breakiter A BreakIterator that will be used to restrict the points -* at which matches are detected. If a match is found, but -* the match's start or end index is not a boundary as -* determined by the BreakIterator, the match will -* be rejected and another will be searched for. -* If this parameter is NULL, no break detection is -* attempted. -* @param status for errors if it occurs. If pattern or text is NULL, or if -* patternlength or textlength is 0 then an -* U_ILLEGAL_ARGUMENT_ERROR is returned. -* @return search iterator data structure, or NULL if there is an error. -* @stable ICU 2.4 -*/ -U_STABLE UStringSearch * U_EXPORT2 usearch_open(const UChar *pattern, - int32_t patternlength, - const UChar *text, - int32_t textlength, - const char *locale, - UBreakIterator *breakiter, - UErrorCode *status); - -/** -* Creating a search iterator data struct using the argument collator language -* rule set. Note, user retains the ownership of this collator, thus the -* responsibility of deletion lies with the user. -* NOTE: string search cannot be instantiated from a collator that has -* collate digits as numbers (CODAN) turned on. -* @param pattern for matching -* @param patternlength length of the pattern, -1 for null-termination -* @param text text string -* @param textlength length of the text string, -1 for null-termination -* @param collator used for the language rules -* @param breakiter A BreakIterator that will be used to restrict the points -* at which matches are detected. If a match is found, but -* the match's start or end index is not a boundary as -* determined by the BreakIterator, the match will -* be rejected and another will be searched for. -* If this parameter is NULL, no break detection is -* attempted. -* @param status for errors if it occurs. If collator, pattern or text is NULL, -* or if patternlength or textlength is 0 then an -* U_ILLEGAL_ARGUMENT_ERROR is returned. -* @return search iterator data structure, or NULL if there is an error. -* @stable ICU 2.4 -*/ -U_STABLE UStringSearch * U_EXPORT2 usearch_openFromCollator( - const UChar *pattern, - int32_t patternlength, - const UChar *text, - int32_t textlength, - const UCollator *collator, - UBreakIterator *breakiter, - UErrorCode *status); - -/** -* Destroying and cleaning up the search iterator data struct. -* If a collator is created in usearch_open, it will be destroyed here. -* @param searchiter data struct to clean up -* @stable ICU 2.4 -*/ -U_STABLE void U_EXPORT2 usearch_close(UStringSearch *searchiter); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUStringSearchPointer - * "Smart pointer" class, closes a UStringSearch via usearch_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUStringSearchPointer, UStringSearch, usearch_close); - -U_NAMESPACE_END - -#endif - -/* get and set methods -------------------------------------------------- */ - -/** -* Sets the current position in the text string which the next search will -* start from. Clears previous states. -* This method takes the argument index and sets the position in the text -* string accordingly without checking if the index is pointing to a -* valid starting point to begin searching. -* Search positions that may render incorrect results are highlighted in the -* header comments -* @param strsrch search iterator data struct -* @param position position to start next search from. If position is less -* than or greater than the text range for searching, -* an U_INDEX_OUTOFBOUNDS_ERROR will be returned -* @param status error status if any. -* @stable ICU 2.4 -*/ -U_STABLE void U_EXPORT2 usearch_setOffset(UStringSearch *strsrch, - int32_t position, - UErrorCode *status); - -/** -* Return the current index in the string text being searched. -* If the iteration has gone past the end of the text (or past the beginning -* for a backwards search), USEARCH_DONE is returned. -* @param strsrch search iterator data struct -* @see #USEARCH_DONE -* @stable ICU 2.4 -*/ -U_STABLE int32_t U_EXPORT2 usearch_getOffset(const UStringSearch *strsrch); - -/** -* Sets the text searching attributes located in the enum USearchAttribute -* with values from the enum USearchAttributeValue. -* USEARCH_DEFAULT can be used for all attributes for resetting. -* @param strsrch search iterator data struct -* @param attribute text attribute to be set -* @param value text attribute value -* @param status for errors if it occurs -* @see #usearch_getAttribute -* @stable ICU 2.4 -*/ -U_STABLE void U_EXPORT2 usearch_setAttribute(UStringSearch *strsrch, - USearchAttribute attribute, - USearchAttributeValue value, - UErrorCode *status); - -/** -* Gets the text searching attributes. -* @param strsrch search iterator data struct -* @param attribute text attribute to be retrieve -* @return text attribute value -* @see #usearch_setAttribute -* @stable ICU 2.4 -*/ -U_STABLE USearchAttributeValue U_EXPORT2 usearch_getAttribute( - const UStringSearch *strsrch, - USearchAttribute attribute); - -/** -* Returns the index to the match in the text string that was searched. -* This call returns a valid result only after a successful call to -* usearch_first, usearch_next, usearch_previous, -* or usearch_last. -* Just after construction, or after a searching method returns -* USEARCH_DONE, this method will return USEARCH_DONE. -*

-* Use usearch_getMatchedLength to get the matched string length. -* @param strsrch search iterator data struct -* @return index to a substring within the text string that is being -* searched. -* @see #usearch_first -* @see #usearch_next -* @see #usearch_previous -* @see #usearch_last -* @see #USEARCH_DONE -* @stable ICU 2.4 -*/ -U_STABLE int32_t U_EXPORT2 usearch_getMatchedStart( - const UStringSearch *strsrch); - -/** -* Returns the length of text in the string which matches the search pattern. -* This call returns a valid result only after a successful call to -* usearch_first, usearch_next, usearch_previous, -* or usearch_last. -* Just after construction, or after a searching method returns -* USEARCH_DONE, this method will return 0. -* @param strsrch search iterator data struct -* @return The length of the match in the string text, or 0 if there is no -* match currently. -* @see #usearch_first -* @see #usearch_next -* @see #usearch_previous -* @see #usearch_last -* @see #USEARCH_DONE -* @stable ICU 2.4 -*/ -U_STABLE int32_t U_EXPORT2 usearch_getMatchedLength( - const UStringSearch *strsrch); - -/** -* Returns the text that was matched by the most recent call to -* usearch_first, usearch_next, usearch_previous, -* or usearch_last. -* If the iterator is not pointing at a valid match (e.g. just after -* construction or after USEARCH_DONE has been returned, returns -* an empty string. If result is not large enough to store the matched text, -* result will be filled with the partial text and an U_BUFFER_OVERFLOW_ERROR -* will be returned in status. result will be null-terminated whenever -* possible. If the buffer fits the matched text exactly, a null-termination -* is not possible, then a U_STRING_NOT_TERMINATED_ERROR set in status. -* Pre-flighting can be either done with length = 0 or the API -* usearch_getMatchLength. -* @param strsrch search iterator data struct -* @param result UChar buffer to store the matched string -* @param resultCapacity length of the result buffer -* @param status error returned if result is not large enough -* @return exact length of the matched text, not counting the null-termination -* @see #usearch_first -* @see #usearch_next -* @see #usearch_previous -* @see #usearch_last -* @see #USEARCH_DONE -* @stable ICU 2.4 -*/ -U_STABLE int32_t U_EXPORT2 usearch_getMatchedText(const UStringSearch *strsrch, - UChar *result, - int32_t resultCapacity, - UErrorCode *status); - -#if !UCONFIG_NO_BREAK_ITERATION - -/** -* Set the BreakIterator that will be used to restrict the points at which -* matches are detected. -* @param strsrch search iterator data struct -* @param breakiter A BreakIterator that will be used to restrict the points -* at which matches are detected. If a match is found, but -* the match's start or end index is not a boundary as -* determined by the BreakIterator, the match will -* be rejected and another will be searched for. -* If this parameter is NULL, no break detection is -* attempted. -* @param status for errors if it occurs -* @see #usearch_getBreakIterator -* @stable ICU 2.4 -*/ -U_STABLE void U_EXPORT2 usearch_setBreakIterator(UStringSearch *strsrch, - UBreakIterator *breakiter, - UErrorCode *status); - -/** -* Returns the BreakIterator that is used to restrict the points at which -* matches are detected. This will be the same object that was passed to the -* constructor or to usearch_setBreakIterator. Note that -* NULL -* is a legal value; it means that break detection should not be attempted. -* @param strsrch search iterator data struct -* @return break iterator used -* @see #usearch_setBreakIterator -* @stable ICU 2.4 -*/ -U_STABLE const UBreakIterator * U_EXPORT2 usearch_getBreakIterator( - const UStringSearch *strsrch); - -#endif - -/** -* Set the string text to be searched. Text iteration will hence begin at the -* start of the text string. This method is useful if you want to re-use an -* iterator to search for the same pattern within a different body of text. -* @param strsrch search iterator data struct -* @param text new string to look for match -* @param textlength length of the new string, -1 for null-termination -* @param status for errors if it occurs. If text is NULL, or textlength is 0 -* then an U_ILLEGAL_ARGUMENT_ERROR is returned with no change -* done to strsrch. -* @see #usearch_getText -* @stable ICU 2.4 -*/ -U_STABLE void U_EXPORT2 usearch_setText( UStringSearch *strsrch, - const UChar *text, - int32_t textlength, - UErrorCode *status); - -/** -* Return the string text to be searched. -* @param strsrch search iterator data struct -* @param length returned string text length -* @return string text -* @see #usearch_setText -* @stable ICU 2.4 -*/ -U_STABLE const UChar * U_EXPORT2 usearch_getText(const UStringSearch *strsrch, - int32_t *length); - -/** -* Gets the collator used for the language rules. -*

-* Deleting the returned UCollator before calling -* usearch_close would cause the string search to fail. -* usearch_close will delete the collator if this search owns it. -* @param strsrch search iterator data struct -* @return collator -* @stable ICU 2.4 -*/ -U_STABLE UCollator * U_EXPORT2 usearch_getCollator( - const UStringSearch *strsrch); - -/** -* Sets the collator used for the language rules. User retains the ownership -* of this collator, thus the responsibility of deletion lies with the user. -* This method causes internal data such as Boyer-Moore shift tables to -* be recalculated, but the iterator's position is unchanged. -* @param strsrch search iterator data struct -* @param collator to be used -* @param status for errors if it occurs -* @stable ICU 2.4 -*/ -U_STABLE void U_EXPORT2 usearch_setCollator( UStringSearch *strsrch, - const UCollator *collator, - UErrorCode *status); - -/** -* Sets the pattern used for matching. -* Internal data like the Boyer Moore table will be recalculated, but the -* iterator's position is unchanged. -* @param strsrch search iterator data struct -* @param pattern string -* @param patternlength pattern length, -1 for null-terminated string -* @param status for errors if it occurs. If text is NULL, or textlength is 0 -* then an U_ILLEGAL_ARGUMENT_ERROR is returned with no change -* done to strsrch. -* @stable ICU 2.4 -*/ -U_STABLE void U_EXPORT2 usearch_setPattern( UStringSearch *strsrch, - const UChar *pattern, - int32_t patternlength, - UErrorCode *status); - -/** -* Gets the search pattern -* @param strsrch search iterator data struct -* @param length return length of the pattern, -1 indicates that the pattern -* is null-terminated -* @return pattern string -* @stable ICU 2.4 -*/ -U_STABLE const UChar * U_EXPORT2 usearch_getPattern( - const UStringSearch *strsrch, - int32_t *length); - -/* methods ------------------------------------------------------------- */ - -/** -* Returns the first index at which the string text matches the search -* pattern. -* The iterator is adjusted so that its current index (as returned by -* usearch_getOffset) is the match position if one was found. -* If a match is not found, USEARCH_DONE will be returned and -* the iterator will be adjusted to the index USEARCH_DONE. -* @param strsrch search iterator data struct -* @param status for errors if it occurs -* @return The character index of the first match, or -* USEARCH_DONE if there are no matches. -* @see #usearch_getOffset -* @see #USEARCH_DONE -* @stable ICU 2.4 -*/ -U_STABLE int32_t U_EXPORT2 usearch_first(UStringSearch *strsrch, - UErrorCode *status); - -/** -* Returns the first index equal or greater than position at which -* the string text -* matches the search pattern. The iterator is adjusted so that its current -* index (as returned by usearch_getOffset) is the match position if -* one was found. -* If a match is not found, USEARCH_DONE will be returned and -* the iterator will be adjusted to the index USEARCH_DONE -*

-* Search positions that may render incorrect results are highlighted in the -* header comments. If position is less than or greater than the text range -* for searching, an U_INDEX_OUTOFBOUNDS_ERROR will be returned -* @param strsrch search iterator data struct -* @param position to start the search at -* @param status for errors if it occurs -* @return The character index of the first match following pos, -* or USEARCH_DONE if there are no matches. -* @see #usearch_getOffset -* @see #USEARCH_DONE -* @stable ICU 2.4 -*/ -U_STABLE int32_t U_EXPORT2 usearch_following(UStringSearch *strsrch, - int32_t position, - UErrorCode *status); - -/** -* Returns the last index in the target text at which it matches the search -* pattern. The iterator is adjusted so that its current -* index (as returned by usearch_getOffset) is the match position if -* one was found. -* If a match is not found, USEARCH_DONE will be returned and -* the iterator will be adjusted to the index USEARCH_DONE. -* @param strsrch search iterator data struct -* @param status for errors if it occurs -* @return The index of the first match, or USEARCH_DONE if there -* are no matches. -* @see #usearch_getOffset -* @see #USEARCH_DONE -* @stable ICU 2.4 -*/ -U_STABLE int32_t U_EXPORT2 usearch_last(UStringSearch *strsrch, - UErrorCode *status); - -/** -* Returns the first index less than position at which the string text -* matches the search pattern. The iterator is adjusted so that its current -* index (as returned by usearch_getOffset) is the match position if -* one was found. -* If a match is not found, USEARCH_DONE will be returned and -* the iterator will be adjusted to the index USEARCH_DONE -*

-* Search positions that may render incorrect results are highlighted in the -* header comments. If position is less than or greater than the text range -* for searching, an U_INDEX_OUTOFBOUNDS_ERROR will be returned. -*

-* When USEARCH_OVERLAP option is off, the last index of the -* result match is always less than position. -* When USERARCH_OVERLAP is on, the result match may span across -* position. -* @param strsrch search iterator data struct -* @param position index position the search is to begin at -* @param status for errors if it occurs -* @return The character index of the first match preceding pos, -* or USEARCH_DONE if there are no matches. -* @see #usearch_getOffset -* @see #USEARCH_DONE -* @stable ICU 2.4 -*/ -U_STABLE int32_t U_EXPORT2 usearch_preceding(UStringSearch *strsrch, - int32_t position, - UErrorCode *status); - -/** -* Returns the index of the next point at which the string text matches the -* search pattern, starting from the current position. -* The iterator is adjusted so that its current -* index (as returned by usearch_getOffset) is the match position if -* one was found. -* If a match is not found, USEARCH_DONE will be returned and -* the iterator will be adjusted to the index USEARCH_DONE -* @param strsrch search iterator data struct -* @param status for errors if it occurs -* @return The index of the next match after the current position, or -* USEARCH_DONE if there are no more matches. -* @see #usearch_first -* @see #usearch_getOffset -* @see #USEARCH_DONE -* @stable ICU 2.4 -*/ -U_STABLE int32_t U_EXPORT2 usearch_next(UStringSearch *strsrch, - UErrorCode *status); - -/** -* Returns the index of the previous point at which the string text matches -* the search pattern, starting at the current position. -* The iterator is adjusted so that its current -* index (as returned by usearch_getOffset) is the match position if -* one was found. -* If a match is not found, USEARCH_DONE will be returned and -* the iterator will be adjusted to the index USEARCH_DONE -* @param strsrch search iterator data struct -* @param status for errors if it occurs -* @return The index of the previous match before the current position, -* or USEARCH_DONE if there are no more matches. -* @see #usearch_last -* @see #usearch_getOffset -* @see #USEARCH_DONE -* @stable ICU 2.4 -*/ -U_STABLE int32_t U_EXPORT2 usearch_previous(UStringSearch *strsrch, - UErrorCode *status); - -/** -* Reset the iteration. -* Search will begin at the start of the text string if a forward iteration -* is initiated before a backwards iteration. Otherwise if a backwards -* iteration is initiated before a forwards iteration, the search will begin -* at the end of the text string. -* @param strsrch search iterator data struct -* @see #usearch_first -* @stable ICU 2.4 -*/ -U_STABLE void U_EXPORT2 usearch_reset(UStringSearch *strsrch); - -#ifndef U_HIDE_INTERNAL_API -/** - * Simple forward search for the pattern, starting at a specified index, - * and using using a default set search options. - * - * This is an experimental function, and is not an official part of the - * ICU API. - * - * The collator options, such as UCOL_STRENGTH and UCOL_NORMALIZTION, are honored. - * - * The UStringSearch options USEARCH_CANONICAL_MATCH, USEARCH_OVERLAP and - * any Break Iterator are ignored. - * - * Matches obey the following constraints: - * - * Characters at the start or end positions of a match that are ignorable - * for collation are not included as part of the match, unless they - * are part of a combining sequence, as described below. - * - * A match will not include a partial combining sequence. Combining - * character sequences are considered to be inseperable units, - * and either match the pattern completely, or are considered to not match - * at all. Thus, for example, an A followed a combining accent mark will - * not be found when searching for a plain (unaccented) A. (unless - * the collation strength has been set to ignore all accents). - * - * When beginning a search, the initial starting position, startIdx, - * is assumed to be an acceptable match boundary with respect to - * combining characters. A combining sequence that spans across the - * starting point will not supress a match beginning at startIdx. - * - * Characters that expand to multiple collation elements - * (German sharp-S becoming 'ss', or the composed forms of accented - * characters, for example) also must match completely. - * Searching for a single 's' in a string containing only a sharp-s will - * find no match. - * - * - * @param strsrch the UStringSearch struct, which references both - * the text to be searched and the pattern being sought. - * @param startIdx The index into the text to begin the search. - * @param matchStart An out parameter, the starting index of the matched text. - * This parameter may be NULL. - * A value of -1 will be returned if no match was found. - * @param matchLimit Out parameter, the index of the first position following the matched text. - * The matchLimit will be at a suitable position for beginning a subsequent search - * in the input text. - * This parameter may be NULL. - * A value of -1 will be returned if no match was found. - * - * @param status Report any errors. Note that no match found is not an error. - * @return TRUE if a match was found, FALSE otherwise. - * - * @internal - */ -U_INTERNAL UBool U_EXPORT2 usearch_search(UStringSearch *strsrch, - int32_t startIdx, - int32_t *matchStart, - int32_t *matchLimit, - UErrorCode *status); - -/** - * Simple backwards search for the pattern, starting at a specified index, - * and using using a default set search options. - * - * This is an experimental function, and is not an official part of the - * ICU API. - * - * The collator options, such as UCOL_STRENGTH and UCOL_NORMALIZTION, are honored. - * - * The UStringSearch options USEARCH_CANONICAL_MATCH, USEARCH_OVERLAP and - * any Break Iterator are ignored. - * - * Matches obey the following constraints: - * - * Characters at the start or end positions of a match that are ignorable - * for collation are not included as part of the match, unless they - * are part of a combining sequence, as described below. - * - * A match will not include a partial combining sequence. Combining - * character sequences are considered to be inseperable units, - * and either match the pattern completely, or are considered to not match - * at all. Thus, for example, an A followed a combining accent mark will - * not be found when searching for a plain (unaccented) A. (unless - * the collation strength has been set to ignore all accents). - * - * When beginning a search, the initial starting position, startIdx, - * is assumed to be an acceptable match boundary with respect to - * combining characters. A combining sequence that spans across the - * starting point will not supress a match beginning at startIdx. - * - * Characters that expand to multiple collation elements - * (German sharp-S becoming 'ss', or the composed forms of accented - * characters, for example) also must match completely. - * Searching for a single 's' in a string containing only a sharp-s will - * find no match. - * - * - * @param strsrch the UStringSearch struct, which references both - * the text to be searched and the pattern being sought. - * @param startIdx The index into the text to begin the search. - * @param matchStart An out parameter, the starting index of the matched text. - * This parameter may be NULL. - * A value of -1 will be returned if no match was found. - * @param matchLimit Out parameter, the index of the first position following the matched text. - * The matchLimit will be at a suitable position for beginning a subsequent search - * in the input text. - * This parameter may be NULL. - * A value of -1 will be returned if no match was found. - * - * @param status Report any errors. Note that no match found is not an error. - * @return TRUE if a match was found, FALSE otherwise. - * - * @internal - */ -U_INTERNAL UBool U_EXPORT2 usearch_searchBackwards(UStringSearch *strsrch, - int32_t startIdx, - int32_t *matchStart, - int32_t *matchLimit, - UErrorCode *status); -#endif /* U_HIDE_INTERNAL_API */ - -#endif /* #if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/uset.h b/win32/include/spidermonkey/unicode/uset.h deleted file mode 100755 index 8baabbe9..00000000 --- a/win32/include/spidermonkey/unicode/uset.h +++ /dev/null @@ -1,1130 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2002-2014, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: uset.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2002mar07 -* created by: Markus W. Scherer -* -* C version of UnicodeSet. -*/ - - -/** - * \file - * \brief C API: Unicode Set - * - *

This is a C wrapper around the C++ UnicodeSet class.

- */ - -#ifndef __USET_H__ -#define __USET_H__ - -#include "unicode/utypes.h" -#include "unicode/uchar.h" -#include "unicode/localpointer.h" - -#ifndef UCNV_H -struct USet; -/** - * A UnicodeSet. Use the uset_* API to manipulate. Create with - * uset_open*, and destroy with uset_close. - * @stable ICU 2.4 - */ -typedef struct USet USet; -#endif - -/** - * Bitmask values to be passed to uset_openPatternOptions() or - * uset_applyPattern() taking an option parameter. - * @stable ICU 2.4 - */ -enum { - /** - * Ignore white space within patterns unless quoted or escaped. - * @stable ICU 2.4 - */ - USET_IGNORE_SPACE = 1, - - /** - * Enable case insensitive matching. E.g., "[ab]" with this flag - * will match 'a', 'A', 'b', and 'B'. "[^ab]" with this flag will - * match all except 'a', 'A', 'b', and 'B'. This performs a full - * closure over case mappings, e.g. U+017F for s. - * - * The resulting set is a superset of the input for the code points but - * not for the strings. - * It performs a case mapping closure of the code points and adds - * full case folding strings for the code points, and reduces strings of - * the original set to their full case folding equivalents. - * - * This is designed for case-insensitive matches, for example - * in regular expressions. The full code point case closure allows checking of - * an input character directly against the closure set. - * Strings are matched by comparing the case-folded form from the closure - * set with an incremental case folding of the string in question. - * - * The closure set will also contain single code points if the original - * set contained case-equivalent strings (like U+00DF for "ss" or "Ss" etc.). - * This is not necessary (that is, redundant) for the above matching method - * but results in the same closure sets regardless of whether the original - * set contained the code point or a string. - * - * @stable ICU 2.4 - */ - USET_CASE_INSENSITIVE = 2, - - /** - * Enable case insensitive matching. E.g., "[ab]" with this flag - * will match 'a', 'A', 'b', and 'B'. "[^ab]" with this flag will - * match all except 'a', 'A', 'b', and 'B'. This adds the lower-, - * title-, and uppercase mappings as well as the case folding - * of each existing element in the set. - * @stable ICU 3.2 - */ - USET_ADD_CASE_MAPPINGS = 4 -}; - -/** - * Argument values for whether span() and similar functions continue while - * the current character is contained vs. not contained in the set. - * - * The functionality is straightforward for sets with only single code points, - * without strings (which is the common case): - * - USET_SPAN_CONTAINED and USET_SPAN_SIMPLE work the same. - * - USET_SPAN_CONTAINED and USET_SPAN_SIMPLE are inverses of USET_SPAN_NOT_CONTAINED. - * - span() and spanBack() partition any string the same way when - * alternating between span(USET_SPAN_NOT_CONTAINED) and - * span(either "contained" condition). - * - Using a complemented (inverted) set and the opposite span conditions - * yields the same results. - * - * When a set contains multi-code point strings, then these statements may not - * be true, depending on the strings in the set (for example, whether they - * overlap with each other) and the string that is processed. - * For a set with strings: - * - The complement of the set contains the opposite set of code points, - * but the same set of strings. - * Therefore, complementing both the set and the span conditions - * may yield different results. - * - When starting spans at different positions in a string - * (span(s, ...) vs. span(s+1, ...)) the ends of the spans may be different - * because a set string may start before the later position. - * - span(USET_SPAN_SIMPLE) may be shorter than - * span(USET_SPAN_CONTAINED) because it will not recursively try - * all possible paths. - * For example, with a set which contains the three strings "xy", "xya" and "ax", - * span("xyax", USET_SPAN_CONTAINED) will return 4 but - * span("xyax", USET_SPAN_SIMPLE) will return 3. - * span(USET_SPAN_SIMPLE) will never be longer than - * span(USET_SPAN_CONTAINED). - * - With either "contained" condition, span() and spanBack() may partition - * a string in different ways. - * For example, with a set which contains the two strings "ab" and "ba", - * and when processing the string "aba", - * span() will yield contained/not-contained boundaries of { 0, 2, 3 } - * while spanBack() will yield boundaries of { 0, 1, 3 }. - * - * Note: If it is important to get the same boundaries whether iterating forward - * or backward through a string, then either only span() should be used and - * the boundaries cached for backward operation, or an ICU BreakIterator - * could be used. - * - * Note: Unpaired surrogates are treated like surrogate code points. - * Similarly, set strings match only on code point boundaries, - * never in the middle of a surrogate pair. - * Illegal UTF-8 sequences are treated like U+FFFD. - * When processing UTF-8 strings, malformed set strings - * (strings with unpaired surrogates which cannot be converted to UTF-8) - * are ignored. - * - * @stable ICU 3.8 - */ -typedef enum USetSpanCondition { - /** - * Continues a span() while there is no set element at the current position. - * Increments by one code point at a time. - * Stops before the first set element (character or string). - * (For code points only, this is like while contains(current)==FALSE). - * - * When span() returns, the substring between where it started and the position - * it returned consists only of characters that are not in the set, - * and none of its strings overlap with the span. - * - * @stable ICU 3.8 - */ - USET_SPAN_NOT_CONTAINED = 0, - /** - * Spans the longest substring that is a concatenation of set elements (characters or strings). - * (For characters only, this is like while contains(current)==TRUE). - * - * When span() returns, the substring between where it started and the position - * it returned consists only of set elements (characters or strings) that are in the set. - * - * If a set contains strings, then the span will be the longest substring for which there - * exists at least one non-overlapping concatenation of set elements (characters or strings). - * This is equivalent to a POSIX regular expression for (OR of each set element)*. - * (Java/ICU/Perl regex stops at the first match of an OR.) - * - * @stable ICU 3.8 - */ - USET_SPAN_CONTAINED = 1, - /** - * Continues a span() while there is a set element at the current position. - * Increments by the longest matching element at each position. - * (For characters only, this is like while contains(current)==TRUE). - * - * When span() returns, the substring between where it started and the position - * it returned consists only of set elements (characters or strings) that are in the set. - * - * If a set only contains single characters, then this is the same - * as USET_SPAN_CONTAINED. - * - * If a set contains strings, then the span will be the longest substring - * with a match at each position with the longest single set element (character or string). - * - * Use this span condition together with other longest-match algorithms, - * such as ICU converters (ucnv_getUnicodeSet()). - * - * @stable ICU 3.8 - */ - USET_SPAN_SIMPLE = 2, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the last span condition. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - USET_SPAN_CONDITION_COUNT -#endif // U_HIDE_DEPRECATED_API -} USetSpanCondition; - -enum { - /** - * Capacity of USerializedSet::staticArray. - * Enough for any single-code point set. - * Also provides padding for nice sizeof(USerializedSet). - * @stable ICU 2.4 - */ - USET_SERIALIZED_STATIC_ARRAY_CAPACITY=8 -}; - -/** - * A serialized form of a Unicode set. Limited manipulations are - * possible directly on a serialized set. See below. - * @stable ICU 2.4 - */ -typedef struct USerializedSet { - /** - * The serialized Unicode Set. - * @stable ICU 2.4 - */ - const uint16_t *array; - /** - * The length of the array that contains BMP characters. - * @stable ICU 2.4 - */ - int32_t bmpLength; - /** - * The total length of the array. - * @stable ICU 2.4 - */ - int32_t length; - /** - * A small buffer for the array to reduce memory allocations. - * @stable ICU 2.4 - */ - uint16_t staticArray[USET_SERIALIZED_STATIC_ARRAY_CAPACITY]; -} USerializedSet; - -/********************************************************************* - * USet API - *********************************************************************/ - -/** - * Create an empty USet object. - * Equivalent to uset_open(1, 0). - * @return a newly created USet. The caller must call uset_close() on - * it when done. - * @stable ICU 4.2 - */ -U_STABLE USet* U_EXPORT2 -uset_openEmpty(void); - -/** - * Creates a USet object that contains the range of characters - * start..end, inclusive. If start > end - * then an empty set is created (same as using uset_openEmpty()). - * @param start first character of the range, inclusive - * @param end last character of the range, inclusive - * @return a newly created USet. The caller must call uset_close() on - * it when done. - * @stable ICU 2.4 - */ -U_STABLE USet* U_EXPORT2 -uset_open(UChar32 start, UChar32 end); - -/** - * Creates a set from the given pattern. See the UnicodeSet class - * description for the syntax of the pattern language. - * @param pattern a string specifying what characters are in the set - * @param patternLength the length of the pattern, or -1 if null - * terminated - * @param ec the error code - * @stable ICU 2.4 - */ -U_STABLE USet* U_EXPORT2 -uset_openPattern(const UChar* pattern, int32_t patternLength, - UErrorCode* ec); - -/** - * Creates a set from the given pattern. See the UnicodeSet class - * description for the syntax of the pattern language. - * @param pattern a string specifying what characters are in the set - * @param patternLength the length of the pattern, or -1 if null - * terminated - * @param options bitmask for options to apply to the pattern. - * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE. - * @param ec the error code - * @stable ICU 2.4 - */ -U_STABLE USet* U_EXPORT2 -uset_openPatternOptions(const UChar* pattern, int32_t patternLength, - uint32_t options, - UErrorCode* ec); - -/** - * Disposes of the storage used by a USet object. This function should - * be called exactly once for objects returned by uset_open(). - * @param set the object to dispose of - * @stable ICU 2.4 - */ -U_STABLE void U_EXPORT2 -uset_close(USet* set); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUSetPointer - * "Smart pointer" class, closes a USet via uset_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUSetPointer, USet, uset_close); - -U_NAMESPACE_END - -#endif - -/** - * Returns a copy of this object. - * If this set is frozen, then the clone will be frozen as well. - * Use uset_cloneAsThawed() for a mutable clone of a frozen set. - * @param set the original set - * @return the newly allocated copy of the set - * @see uset_cloneAsThawed - * @stable ICU 3.8 - */ -U_STABLE USet * U_EXPORT2 -uset_clone(const USet *set); - -/** - * Determines whether the set has been frozen (made immutable) or not. - * See the ICU4J Freezable interface for details. - * @param set the set - * @return TRUE/FALSE for whether the set has been frozen - * @see uset_freeze - * @see uset_cloneAsThawed - * @stable ICU 3.8 - */ -U_STABLE UBool U_EXPORT2 -uset_isFrozen(const USet *set); - -/** - * Freeze the set (make it immutable). - * Once frozen, it cannot be unfrozen and is therefore thread-safe - * until it is deleted. - * See the ICU4J Freezable interface for details. - * Freezing the set may also make some operations faster, for example - * uset_contains() and uset_span(). - * A frozen set will not be modified. (It remains frozen.) - * @param set the set - * @return the same set, now frozen - * @see uset_isFrozen - * @see uset_cloneAsThawed - * @stable ICU 3.8 - */ -U_STABLE void U_EXPORT2 -uset_freeze(USet *set); - -/** - * Clone the set and make the clone mutable. - * See the ICU4J Freezable interface for details. - * @param set the set - * @return the mutable clone - * @see uset_freeze - * @see uset_isFrozen - * @see uset_clone - * @stable ICU 3.8 - */ -U_STABLE USet * U_EXPORT2 -uset_cloneAsThawed(const USet *set); - -/** - * Causes the USet object to represent the range start - end. - * If start > end then this USet is set to an empty range. - * A frozen set will not be modified. - * @param set the object to set to the given range - * @param start first character in the set, inclusive - * @param end last character in the set, inclusive - * @stable ICU 3.2 - */ -U_STABLE void U_EXPORT2 -uset_set(USet* set, - UChar32 start, UChar32 end); - -/** - * Modifies the set to represent the set specified by the given - * pattern. See the UnicodeSet class description for the syntax of - * the pattern language. See also the User Guide chapter about UnicodeSet. - * Empties the set passed before applying the pattern. - * A frozen set will not be modified. - * @param set The set to which the pattern is to be applied. - * @param pattern A pointer to UChar string specifying what characters are in the set. - * The character at pattern[0] must be a '['. - * @param patternLength The length of the UChar string. -1 if NUL terminated. - * @param options A bitmask for options to apply to the pattern. - * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE. - * @param status Returns an error if the pattern cannot be parsed. - * @return Upon successful parse, the value is either - * the index of the character after the closing ']' - * of the parsed pattern. - * If the status code indicates failure, then the return value - * is the index of the error in the source. - * - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -uset_applyPattern(USet *set, - const UChar *pattern, int32_t patternLength, - uint32_t options, - UErrorCode *status); - -/** - * Modifies the set to contain those code points which have the given value - * for the given binary or enumerated property, as returned by - * u_getIntPropertyValue. Prior contents of this set are lost. - * A frozen set will not be modified. - * - * @param set the object to contain the code points defined by the property - * - * @param prop a property in the range UCHAR_BIN_START..UCHAR_BIN_LIMIT-1 - * or UCHAR_INT_START..UCHAR_INT_LIMIT-1 - * or UCHAR_MASK_START..UCHAR_MASK_LIMIT-1. - * - * @param value a value in the range u_getIntPropertyMinValue(prop).. - * u_getIntPropertyMaxValue(prop), with one exception. If prop is - * UCHAR_GENERAL_CATEGORY_MASK, then value should not be a UCharCategory, but - * rather a mask value produced by U_GET_GC_MASK(). This allows grouped - * categories such as [:L:] to be represented. - * - * @param ec error code input/output parameter - * - * @stable ICU 3.2 - */ -U_STABLE void U_EXPORT2 -uset_applyIntPropertyValue(USet* set, - UProperty prop, int32_t value, UErrorCode* ec); - -/** - * Modifies the set to contain those code points which have the - * given value for the given property. Prior contents of this - * set are lost. - * A frozen set will not be modified. - * - * @param set the object to contain the code points defined by the given - * property and value alias - * - * @param prop a string specifying a property alias, either short or long. - * The name is matched loosely. See PropertyAliases.txt for names and a - * description of loose matching. If the value string is empty, then this - * string is interpreted as either a General_Category value alias, a Script - * value alias, a binary property alias, or a special ID. Special IDs are - * matched loosely and correspond to the following sets: - * - * "ANY" = [\\u0000-\\U0010FFFF], - * "ASCII" = [\\u0000-\\u007F], - * "Assigned" = [:^Cn:]. - * - * @param propLength the length of the prop, or -1 if NULL - * - * @param value a string specifying a value alias, either short or long. - * The name is matched loosely. See PropertyValueAliases.txt for names - * and a description of loose matching. In addition to aliases listed, - * numeric values and canonical combining classes may be expressed - * numerically, e.g., ("nv", "0.5") or ("ccc", "220"). The value string - * may also be empty. - * - * @param valueLength the length of the value, or -1 if NULL - * - * @param ec error code input/output parameter - * - * @stable ICU 3.2 - */ -U_STABLE void U_EXPORT2 -uset_applyPropertyAlias(USet* set, - const UChar *prop, int32_t propLength, - const UChar *value, int32_t valueLength, - UErrorCode* ec); - -/** - * Return true if the given position, in the given pattern, appears - * to be the start of a UnicodeSet pattern. - * - * @param pattern a string specifying the pattern - * @param patternLength the length of the pattern, or -1 if NULL - * @param pos the given position - * @stable ICU 3.2 - */ -U_STABLE UBool U_EXPORT2 -uset_resemblesPattern(const UChar *pattern, int32_t patternLength, - int32_t pos); - -/** - * Returns a string representation of this set. If the result of - * calling this function is passed to a uset_openPattern(), it - * will produce another set that is equal to this one. - * @param set the set - * @param result the string to receive the rules, may be NULL - * @param resultCapacity the capacity of result, may be 0 if result is NULL - * @param escapeUnprintable if TRUE then convert unprintable - * character to their hex escape representations, \\uxxxx or - * \\Uxxxxxxxx. Unprintable characters are those other than - * U+000A, U+0020..U+007E. - * @param ec error code. - * @return length of string, possibly larger than resultCapacity - * @stable ICU 2.4 - */ -U_STABLE int32_t U_EXPORT2 -uset_toPattern(const USet* set, - UChar* result, int32_t resultCapacity, - UBool escapeUnprintable, - UErrorCode* ec); - -/** - * Adds the given character to the given USet. After this call, - * uset_contains(set, c) will return TRUE. - * A frozen set will not be modified. - * @param set the object to which to add the character - * @param c the character to add - * @stable ICU 2.4 - */ -U_STABLE void U_EXPORT2 -uset_add(USet* set, UChar32 c); - -/** - * Adds all of the elements in the specified set to this set if - * they're not already present. This operation effectively - * modifies this set so that its value is the union of the two - * sets. The behavior of this operation is unspecified if the specified - * collection is modified while the operation is in progress. - * A frozen set will not be modified. - * - * @param set the object to which to add the set - * @param additionalSet the source set whose elements are to be added to this set. - * @stable ICU 2.6 - */ -U_STABLE void U_EXPORT2 -uset_addAll(USet* set, const USet *additionalSet); - -/** - * Adds the given range of characters to the given USet. After this call, - * uset_contains(set, start, end) will return TRUE. - * A frozen set will not be modified. - * @param set the object to which to add the character - * @param start the first character of the range to add, inclusive - * @param end the last character of the range to add, inclusive - * @stable ICU 2.2 - */ -U_STABLE void U_EXPORT2 -uset_addRange(USet* set, UChar32 start, UChar32 end); - -/** - * Adds the given string to the given USet. After this call, - * uset_containsString(set, str, strLen) will return TRUE. - * A frozen set will not be modified. - * @param set the object to which to add the character - * @param str the string to add - * @param strLen the length of the string or -1 if null terminated. - * @stable ICU 2.4 - */ -U_STABLE void U_EXPORT2 -uset_addString(USet* set, const UChar* str, int32_t strLen); - -/** - * Adds each of the characters in this string to the set. Thus "ch" => {"c", "h"} - * If this set already any particular character, it has no effect on that character. - * A frozen set will not be modified. - * @param set the object to which to add the character - * @param str the source string - * @param strLen the length of the string or -1 if null terminated. - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -uset_addAllCodePoints(USet* set, const UChar *str, int32_t strLen); - -/** - * Removes the given character from the given USet. After this call, - * uset_contains(set, c) will return FALSE. - * A frozen set will not be modified. - * @param set the object from which to remove the character - * @param c the character to remove - * @stable ICU 2.4 - */ -U_STABLE void U_EXPORT2 -uset_remove(USet* set, UChar32 c); - -/** - * Removes the given range of characters from the given USet. After this call, - * uset_contains(set, start, end) will return FALSE. - * A frozen set will not be modified. - * @param set the object to which to add the character - * @param start the first character of the range to remove, inclusive - * @param end the last character of the range to remove, inclusive - * @stable ICU 2.2 - */ -U_STABLE void U_EXPORT2 -uset_removeRange(USet* set, UChar32 start, UChar32 end); - -/** - * Removes the given string to the given USet. After this call, - * uset_containsString(set, str, strLen) will return FALSE. - * A frozen set will not be modified. - * @param set the object to which to add the character - * @param str the string to remove - * @param strLen the length of the string or -1 if null terminated. - * @stable ICU 2.4 - */ -U_STABLE void U_EXPORT2 -uset_removeString(USet* set, const UChar* str, int32_t strLen); - -/** - * Removes from this set all of its elements that are contained in the - * specified set. This operation effectively modifies this - * set so that its value is the asymmetric set difference of - * the two sets. - * A frozen set will not be modified. - * @param set the object from which the elements are to be removed - * @param removeSet the object that defines which elements will be - * removed from this set - * @stable ICU 3.2 - */ -U_STABLE void U_EXPORT2 -uset_removeAll(USet* set, const USet* removeSet); - -/** - * Retain only the elements in this set that are contained in the - * specified range. If start > end then an empty range is - * retained, leaving the set empty. This is equivalent to - * a boolean logic AND, or a set INTERSECTION. - * A frozen set will not be modified. - * - * @param set the object for which to retain only the specified range - * @param start first character, inclusive, of range to be retained - * to this set. - * @param end last character, inclusive, of range to be retained - * to this set. - * @stable ICU 3.2 - */ -U_STABLE void U_EXPORT2 -uset_retain(USet* set, UChar32 start, UChar32 end); - -/** - * Retains only the elements in this set that are contained in the - * specified set. In other words, removes from this set all of - * its elements that are not contained in the specified set. This - * operation effectively modifies this set so that its value is - * the intersection of the two sets. - * A frozen set will not be modified. - * - * @param set the object on which to perform the retain - * @param retain set that defines which elements this set will retain - * @stable ICU 3.2 - */ -U_STABLE void U_EXPORT2 -uset_retainAll(USet* set, const USet* retain); - -/** - * Reallocate this objects internal structures to take up the least - * possible space, without changing this object's value. - * A frozen set will not be modified. - * - * @param set the object on which to perfrom the compact - * @stable ICU 3.2 - */ -U_STABLE void U_EXPORT2 -uset_compact(USet* set); - -/** - * Inverts this set. This operation modifies this set so that - * its value is its complement. This operation does not affect - * the multicharacter strings, if any. - * A frozen set will not be modified. - * @param set the set - * @stable ICU 2.4 - */ -U_STABLE void U_EXPORT2 -uset_complement(USet* set); - -/** - * Complements in this set all elements contained in the specified - * set. Any character in the other set will be removed if it is - * in this set, or will be added if it is not in this set. - * A frozen set will not be modified. - * - * @param set the set with which to complement - * @param complement set that defines which elements will be xor'ed - * from this set. - * @stable ICU 3.2 - */ -U_STABLE void U_EXPORT2 -uset_complementAll(USet* set, const USet* complement); - -/** - * Removes all of the elements from this set. This set will be - * empty after this call returns. - * A frozen set will not be modified. - * @param set the set - * @stable ICU 2.4 - */ -U_STABLE void U_EXPORT2 -uset_clear(USet* set); - -/** - * Close this set over the given attribute. For the attribute - * USET_CASE, the result is to modify this set so that: - * - * 1. For each character or string 'a' in this set, all strings or - * characters 'b' such that foldCase(a) == foldCase(b) are added - * to this set. - * - * 2. For each string 'e' in the resulting set, if e != - * foldCase(e), 'e' will be removed. - * - * Example: [aq\\u00DF{Bc}{bC}{Fi}] => [aAqQ\\u00DF\\uFB01{ss}{bc}{fi}] - * - * (Here foldCase(x) refers to the operation u_strFoldCase, and a - * == b denotes that the contents are the same, not pointer - * comparison.) - * - * A frozen set will not be modified. - * - * @param set the set - * - * @param attributes bitmask for attributes to close over. - * Currently only the USET_CASE bit is supported. Any undefined bits - * are ignored. - * @stable ICU 4.2 - */ -U_STABLE void U_EXPORT2 -uset_closeOver(USet* set, int32_t attributes); - -/** - * Remove all strings from this set. - * - * @param set the set - * @stable ICU 4.2 - */ -U_STABLE void U_EXPORT2 -uset_removeAllStrings(USet* set); - -/** - * Returns TRUE if the given USet contains no characters and no - * strings. - * @param set the set - * @return true if set is empty - * @stable ICU 2.4 - */ -U_STABLE UBool U_EXPORT2 -uset_isEmpty(const USet* set); - -/** - * Returns TRUE if the given USet contains the given character. - * This function works faster with a frozen set. - * @param set the set - * @param c The codepoint to check for within the set - * @return true if set contains c - * @stable ICU 2.4 - */ -U_STABLE UBool U_EXPORT2 -uset_contains(const USet* set, UChar32 c); - -/** - * Returns TRUE if the given USet contains all characters c - * where start <= c && c <= end. - * @param set the set - * @param start the first character of the range to test, inclusive - * @param end the last character of the range to test, inclusive - * @return TRUE if set contains the range - * @stable ICU 2.2 - */ -U_STABLE UBool U_EXPORT2 -uset_containsRange(const USet* set, UChar32 start, UChar32 end); - -/** - * Returns TRUE if the given USet contains the given string. - * @param set the set - * @param str the string - * @param strLen the length of the string or -1 if null terminated. - * @return true if set contains str - * @stable ICU 2.4 - */ -U_STABLE UBool U_EXPORT2 -uset_containsString(const USet* set, const UChar* str, int32_t strLen); - -/** - * Returns the index of the given character within this set, where - * the set is ordered by ascending code point. If the character - * is not in this set, return -1. The inverse of this method is - * charAt(). - * @param set the set - * @param c the character to obtain the index for - * @return an index from 0..size()-1, or -1 - * @stable ICU 3.2 - */ -U_STABLE int32_t U_EXPORT2 -uset_indexOf(const USet* set, UChar32 c); - -/** - * Returns the character at the given index within this set, where - * the set is ordered by ascending code point. If the index is - * out of range, return (UChar32)-1. The inverse of this method is - * indexOf(). - * @param set the set - * @param charIndex an index from 0..size()-1 to obtain the char for - * @return the character at the given index, or (UChar32)-1. - * @stable ICU 3.2 - */ -U_STABLE UChar32 U_EXPORT2 -uset_charAt(const USet* set, int32_t charIndex); - -/** - * Returns the number of characters and strings contained in the given - * USet. - * @param set the set - * @return a non-negative integer counting the characters and strings - * contained in set - * @stable ICU 2.4 - */ -U_STABLE int32_t U_EXPORT2 -uset_size(const USet* set); - -/** - * Returns the number of items in this set. An item is either a range - * of characters or a single multicharacter string. - * @param set the set - * @return a non-negative integer counting the character ranges - * and/or strings contained in set - * @stable ICU 2.4 - */ -U_STABLE int32_t U_EXPORT2 -uset_getItemCount(const USet* set); - -/** - * Returns an item of this set. An item is either a range of - * characters or a single multicharacter string. - * @param set the set - * @param itemIndex a non-negative integer in the range 0.. - * uset_getItemCount(set)-1 - * @param start pointer to variable to receive first character - * in range, inclusive - * @param end pointer to variable to receive last character in range, - * inclusive - * @param str buffer to receive the string, may be NULL - * @param strCapacity capacity of str, or 0 if str is NULL - * @param ec error code - * @return the length of the string (>= 2), or 0 if the item is a - * range, in which case it is the range *start..*end, or -1 if - * itemIndex is out of range - * @stable ICU 2.4 - */ -U_STABLE int32_t U_EXPORT2 -uset_getItem(const USet* set, int32_t itemIndex, - UChar32* start, UChar32* end, - UChar* str, int32_t strCapacity, - UErrorCode* ec); - -/** - * Returns true if set1 contains all the characters and strings - * of set2. It answers the question, 'Is set1 a superset of set2?' - * @param set1 set to be checked for containment - * @param set2 set to be checked for containment - * @return true if the test condition is met - * @stable ICU 3.2 - */ -U_STABLE UBool U_EXPORT2 -uset_containsAll(const USet* set1, const USet* set2); - -/** - * Returns true if this set contains all the characters - * of the given string. This is does not check containment of grapheme - * clusters, like uset_containsString. - * @param set set of characters to be checked for containment - * @param str string containing codepoints to be checked for containment - * @param strLen the length of the string or -1 if null terminated. - * @return true if the test condition is met - * @stable ICU 3.4 - */ -U_STABLE UBool U_EXPORT2 -uset_containsAllCodePoints(const USet* set, const UChar *str, int32_t strLen); - -/** - * Returns true if set1 contains none of the characters and strings - * of set2. It answers the question, 'Is set1 a disjoint set of set2?' - * @param set1 set to be checked for containment - * @param set2 set to be checked for containment - * @return true if the test condition is met - * @stable ICU 3.2 - */ -U_STABLE UBool U_EXPORT2 -uset_containsNone(const USet* set1, const USet* set2); - -/** - * Returns true if set1 contains some of the characters and strings - * of set2. It answers the question, 'Does set1 and set2 have an intersection?' - * @param set1 set to be checked for containment - * @param set2 set to be checked for containment - * @return true if the test condition is met - * @stable ICU 3.2 - */ -U_STABLE UBool U_EXPORT2 -uset_containsSome(const USet* set1, const USet* set2); - -/** - * Returns the length of the initial substring of the input string which - * consists only of characters and strings that are contained in this set - * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), - * or only of characters and strings that are not contained - * in this set (USET_SPAN_NOT_CONTAINED). - * See USetSpanCondition for details. - * Similar to the strspn() C library function. - * Unpaired surrogates are treated according to contains() of their surrogate code points. - * This function works faster with a frozen set and with a non-negative string length argument. - * @param set the set - * @param s start of the string - * @param length of the string; can be -1 for NUL-terminated - * @param spanCondition specifies the containment condition - * @return the length of the initial substring according to the spanCondition; - * 0 if the start of the string does not fit the spanCondition - * @stable ICU 3.8 - * @see USetSpanCondition - */ -U_STABLE int32_t U_EXPORT2 -uset_span(const USet *set, const UChar *s, int32_t length, USetSpanCondition spanCondition); - -/** - * Returns the start of the trailing substring of the input string which - * consists only of characters and strings that are contained in this set - * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), - * or only of characters and strings that are not contained - * in this set (USET_SPAN_NOT_CONTAINED). - * See USetSpanCondition for details. - * Unpaired surrogates are treated according to contains() of their surrogate code points. - * This function works faster with a frozen set and with a non-negative string length argument. - * @param set the set - * @param s start of the string - * @param length of the string; can be -1 for NUL-terminated - * @param spanCondition specifies the containment condition - * @return the start of the trailing substring according to the spanCondition; - * the string length if the end of the string does not fit the spanCondition - * @stable ICU 3.8 - * @see USetSpanCondition - */ -U_STABLE int32_t U_EXPORT2 -uset_spanBack(const USet *set, const UChar *s, int32_t length, USetSpanCondition spanCondition); - -/** - * Returns the length of the initial substring of the input string which - * consists only of characters and strings that are contained in this set - * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), - * or only of characters and strings that are not contained - * in this set (USET_SPAN_NOT_CONTAINED). - * See USetSpanCondition for details. - * Similar to the strspn() C library function. - * Malformed byte sequences are treated according to contains(0xfffd). - * This function works faster with a frozen set and with a non-negative string length argument. - * @param set the set - * @param s start of the string (UTF-8) - * @param length of the string; can be -1 for NUL-terminated - * @param spanCondition specifies the containment condition - * @return the length of the initial substring according to the spanCondition; - * 0 if the start of the string does not fit the spanCondition - * @stable ICU 3.8 - * @see USetSpanCondition - */ -U_STABLE int32_t U_EXPORT2 -uset_spanUTF8(const USet *set, const char *s, int32_t length, USetSpanCondition spanCondition); - -/** - * Returns the start of the trailing substring of the input string which - * consists only of characters and strings that are contained in this set - * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE), - * or only of characters and strings that are not contained - * in this set (USET_SPAN_NOT_CONTAINED). - * See USetSpanCondition for details. - * Malformed byte sequences are treated according to contains(0xfffd). - * This function works faster with a frozen set and with a non-negative string length argument. - * @param set the set - * @param s start of the string (UTF-8) - * @param length of the string; can be -1 for NUL-terminated - * @param spanCondition specifies the containment condition - * @return the start of the trailing substring according to the spanCondition; - * the string length if the end of the string does not fit the spanCondition - * @stable ICU 3.8 - * @see USetSpanCondition - */ -U_STABLE int32_t U_EXPORT2 -uset_spanBackUTF8(const USet *set, const char *s, int32_t length, USetSpanCondition spanCondition); - -/** - * Returns true if set1 contains all of the characters and strings - * of set2, and vis versa. It answers the question, 'Is set1 equal to set2?' - * @param set1 set to be checked for containment - * @param set2 set to be checked for containment - * @return true if the test condition is met - * @stable ICU 3.2 - */ -U_STABLE UBool U_EXPORT2 -uset_equals(const USet* set1, const USet* set2); - -/********************************************************************* - * Serialized set API - *********************************************************************/ - -/** - * Serializes this set into an array of 16-bit integers. Serialization - * (currently) only records the characters in the set; multicharacter - * strings are ignored. - * - * The array - * has following format (each line is one 16-bit integer): - * - * length = (n+2*m) | (m!=0?0x8000:0) - * bmpLength = n; present if m!=0 - * bmp[0] - * bmp[1] - * ... - * bmp[n-1] - * supp-high[0] - * supp-low[0] - * supp-high[1] - * supp-low[1] - * ... - * supp-high[m-1] - * supp-low[m-1] - * - * The array starts with a header. After the header are n bmp - * code points, then m supplementary code points. Either n or m - * or both may be zero. n+2*m is always <= 0x7FFF. - * - * If there are no supplementary characters (if m==0) then the - * header is one 16-bit integer, 'length', with value n. - * - * If there are supplementary characters (if m!=0) then the header - * is two 16-bit integers. The first, 'length', has value - * (n+2*m)|0x8000. The second, 'bmpLength', has value n. - * - * After the header the code points are stored in ascending order. - * Supplementary code points are stored as most significant 16 - * bits followed by least significant 16 bits. - * - * @param set the set - * @param dest pointer to buffer of destCapacity 16-bit integers. - * May be NULL only if destCapacity is zero. - * @param destCapacity size of dest, or zero. Must not be negative. - * @param pErrorCode pointer to the error code. Will be set to - * U_INDEX_OUTOFBOUNDS_ERROR if n+2*m > 0x7FFF. Will be set to - * U_BUFFER_OVERFLOW_ERROR if n+2*m+(m!=0?2:1) > destCapacity. - * @return the total length of the serialized format, including - * the header, that is, n+2*m+(m!=0?2:1), or 0 on error other - * than U_BUFFER_OVERFLOW_ERROR. - * @stable ICU 2.4 - */ -U_STABLE int32_t U_EXPORT2 -uset_serialize(const USet* set, uint16_t* dest, int32_t destCapacity, UErrorCode* pErrorCode); - -/** - * Given a serialized array, fill in the given serialized set object. - * @param fillSet pointer to result - * @param src pointer to start of array - * @param srcLength length of array - * @return true if the given array is valid, otherwise false - * @stable ICU 2.4 - */ -U_STABLE UBool U_EXPORT2 -uset_getSerializedSet(USerializedSet* fillSet, const uint16_t* src, int32_t srcLength); - -/** - * Set the USerializedSet to contain the given character (and nothing - * else). - * @param fillSet pointer to result - * @param c The codepoint to set - * @stable ICU 2.4 - */ -U_STABLE void U_EXPORT2 -uset_setSerializedToOne(USerializedSet* fillSet, UChar32 c); - -/** - * Returns TRUE if the given USerializedSet contains the given - * character. - * @param set the serialized set - * @param c The codepoint to check for within the set - * @return true if set contains c - * @stable ICU 2.4 - */ -U_STABLE UBool U_EXPORT2 -uset_serializedContains(const USerializedSet* set, UChar32 c); - -/** - * Returns the number of disjoint ranges of characters contained in - * the given serialized set. Ignores any strings contained in the - * set. - * @param set the serialized set - * @return a non-negative integer counting the character ranges - * contained in set - * @stable ICU 2.4 - */ -U_STABLE int32_t U_EXPORT2 -uset_getSerializedRangeCount(const USerializedSet* set); - -/** - * Returns a range of characters contained in the given serialized - * set. - * @param set the serialized set - * @param rangeIndex a non-negative integer in the range 0.. - * uset_getSerializedRangeCount(set)-1 - * @param pStart pointer to variable to receive first character - * in range, inclusive - * @param pEnd pointer to variable to receive last character in range, - * inclusive - * @return true if rangeIndex is valid, otherwise false - * @stable ICU 2.4 - */ -U_STABLE UBool U_EXPORT2 -uset_getSerializedRange(const USerializedSet* set, int32_t rangeIndex, - UChar32* pStart, UChar32* pEnd); - -#endif diff --git a/win32/include/spidermonkey/unicode/usetiter.h b/win32/include/spidermonkey/unicode/usetiter.h deleted file mode 100755 index 26591d04..00000000 --- a/win32/include/spidermonkey/unicode/usetiter.h +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (c) 2002-2014, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -*/ -#ifndef USETITER_H -#define USETITER_H - -#include "unicode/utypes.h" -#include "unicode/uobject.h" -#include "unicode/unistr.h" - -/** - * \file - * \brief C++ API: UnicodeSetIterator iterates over the contents of a UnicodeSet. - */ - -U_NAMESPACE_BEGIN - -class UnicodeSet; -class UnicodeString; - -/** - * - * UnicodeSetIterator iterates over the contents of a UnicodeSet. It - * iterates over either code points or code point ranges. After all - * code points or ranges have been returned, it returns the - * multicharacter strings of the UnicodeSet, if any. - * - * This class is not intended to be subclassed. Consider any fields - * or methods declared as "protected" to be private. The use of - * protected in this class is an artifact of history. - * - *

To iterate over code points and strings, use a loop like this: - *

- * UnicodeSetIterator it(set);
- * while (it.next()) {
- *     processItem(it.getString());
- * }
- * 
- *

Each item in the set is accessed as a string. Set elements - * consisting of single code points are returned as strings containing - * just the one code point. - * - *

To iterate over code point ranges, instead of individual code points, - * use a loop like this: - *

- * UnicodeSetIterator it(set);
- * while (it.nextRange()) {
- *   if (it.isString()) {
- *     processString(it.getString());
- *   } else {
- *     processCodepointRange(it.getCodepoint(), it.getCodepointEnd());
- *   }
- * }
- * 
- * @author M. Davis - * @stable ICU 2.4 - */ -class U_COMMON_API UnicodeSetIterator : public UObject { - - protected: - - /** - * Value of codepoint if the iterator points to a string. - * If codepoint == IS_STRING, then examine - * string for the current iteration result. - * @stable ICU 2.4 - */ - enum { IS_STRING = -1 }; - - /** - * Current code point, or the special value IS_STRING, if - * the iterator points to a string. - * @stable ICU 2.4 - */ - UChar32 codepoint; - - /** - * When iterating over ranges using nextRange(), - * codepointEnd contains the inclusive end of the - * iteration range, if codepoint != IS_STRING. If - * iterating over code points using next(), or if - * codepoint == IS_STRING, then the value of - * codepointEnd is undefined. - * @stable ICU 2.4 - */ - UChar32 codepointEnd; - - /** - * If codepoint == IS_STRING, then string points - * to the current string. If codepoint != IS_STRING, the - * value of string is undefined. - * @stable ICU 2.4 - */ - const UnicodeString* string; - - public: - - /** - * Create an iterator over the given set. The iterator is valid - * only so long as set is valid. - * @param set set to iterate over - * @stable ICU 2.4 - */ - UnicodeSetIterator(const UnicodeSet& set); - - /** - * Create an iterator over nothing. next() and - * nextRange() return false. This is a convenience - * constructor allowing the target to be set later. - * @stable ICU 2.4 - */ - UnicodeSetIterator(); - - /** - * Destructor. - * @stable ICU 2.4 - */ - virtual ~UnicodeSetIterator(); - - /** - * Returns true if the current element is a string. If so, the - * caller can retrieve it with getString(). If this - * method returns false, the current element is a code point or - * code point range, depending on whether next() or - * nextRange() was called. - * Elements of types string and codepoint can both be retrieved - * with the function getString(). - * Elements of type codepoint can also be retrieved with - * getCodepoint(). - * For ranges, getCodepoint() returns the starting codepoint - * of the range, and getCodepointEnd() returns the end - * of the range. - * @stable ICU 2.4 - */ - inline UBool isString() const; - - /** - * Returns the current code point, if isString() returned - * false. Otherwise returns an undefined result. - * @stable ICU 2.4 - */ - inline UChar32 getCodepoint() const; - - /** - * Returns the end of the current code point range, if - * isString() returned false and nextRange() was - * called. Otherwise returns an undefined result. - * @stable ICU 2.4 - */ - inline UChar32 getCodepointEnd() const; - - /** - * Returns the current string, if isString() returned - * true. If the current iteration item is a code point, a UnicodeString - * containing that single code point is returned. - * - * Ownership of the returned string remains with the iterator. - * The string is guaranteed to remain valid only until the iterator is - * advanced to the next item, or until the iterator is deleted. - * - * @stable ICU 2.4 - */ - const UnicodeString& getString(); - - /** - * Advances the iteration position to the next element in the set, - * which can be either a single code point or a string. - * If there are no more elements in the set, return false. - * - *

- * If isString() == TRUE, the value is a - * string, otherwise the value is a - * single code point. Elements of either type can be retrieved - * with the function getString(), while elements of - * consisting of a single code point can be retrieved with - * getCodepoint() - * - *

The order of iteration is all code points in sorted order, - * followed by all strings sorted order. Do not mix - * calls to next() and nextRange() without - * calling reset() between them. The results of doing so - * are undefined. - * - * @return true if there was another element in the set. - * @stable ICU 2.4 - */ - UBool next(); - - /** - * Returns the next element in the set, either a code point range - * or a string. If there are no more elements in the set, return - * false. If isString() == TRUE, the value is a - * string and can be accessed with getString(). Otherwise the value is a - * range of one or more code points from getCodepoint() to - * getCodepointeEnd() inclusive. - * - *

The order of iteration is all code points ranges in sorted - * order, followed by all strings sorted order. Ranges are - * disjoint and non-contiguous. The value returned from getString() - * is undefined unless isString() == TRUE. Do not mix calls to - * next() and nextRange() without calling - * reset() between them. The results of doing so are - * undefined. - * - * @return true if there was another element in the set. - * @stable ICU 2.4 - */ - UBool nextRange(); - - /** - * Sets this iterator to visit the elements of the given set and - * resets it to the start of that set. The iterator is valid only - * so long as set is valid. - * @param set the set to iterate over. - * @stable ICU 2.4 - */ - void reset(const UnicodeSet& set); - - /** - * Resets this iterator to the start of the set. - * @stable ICU 2.4 - */ - void reset(); - - /** - * ICU "poor man's RTTI", returns a UClassID for this class. - * - * @stable ICU 2.4 - */ - static UClassID U_EXPORT2 getStaticClassID(); - - /** - * ICU "poor man's RTTI", returns a UClassID for the actual class. - * - * @stable ICU 2.4 - */ - virtual UClassID getDynamicClassID() const; - - // ======================= PRIVATES =========================== - - protected: - - // endElement and nextElements are really UChar32's, but we keep - // them as signed int32_t's so we can do comparisons with - // endElement set to -1. Leave them as int32_t's. - /** The set - * @stable ICU 2.4 - */ - const UnicodeSet* set; - /** End range - * @stable ICU 2.4 - */ - int32_t endRange; - /** Range - * @stable ICU 2.4 - */ - int32_t range; - /** End element - * @stable ICU 2.4 - */ - int32_t endElement; - /** Next element - * @stable ICU 2.4 - */ - int32_t nextElement; - //UBool abbreviated; - /** Next string - * @stable ICU 2.4 - */ - int32_t nextString; - /** String count - * @stable ICU 2.4 - */ - int32_t stringCount; - - /** - * Points to the string to use when the caller asks for a - * string and the current iteration item is a code point, not a string. - * @internal - */ - UnicodeString *cpString; - - /** Copy constructor. Disallowed. - * @stable ICU 2.4 - */ - UnicodeSetIterator(const UnicodeSetIterator&); // disallow - - /** Assignment operator. Disallowed. - * @stable ICU 2.4 - */ - UnicodeSetIterator& operator=(const UnicodeSetIterator&); // disallow - - /** Load range - * @stable ICU 2.4 - */ - virtual void loadRange(int32_t range); - -}; - -inline UBool UnicodeSetIterator::isString() const { - return codepoint == (UChar32)IS_STRING; -} - -inline UChar32 UnicodeSetIterator::getCodepoint() const { - return codepoint; -} - -inline UChar32 UnicodeSetIterator::getCodepointEnd() const { - return codepointEnd; -} - - -U_NAMESPACE_END - -#endif diff --git a/win32/include/spidermonkey/unicode/ushape.h b/win32/include/spidermonkey/unicode/ushape.h deleted file mode 100755 index 0ea32316..00000000 --- a/win32/include/spidermonkey/unicode/ushape.h +++ /dev/null @@ -1,476 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -****************************************************************************** -* -* Copyright (C) 2000-2012, International Business Machines -* Corporation and others. All Rights Reserved. -* -****************************************************************************** -* file name: ushape.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2000jun29 -* created by: Markus W. Scherer -*/ - -#ifndef __USHAPE_H__ -#define __USHAPE_H__ - -#include "unicode/utypes.h" - -/** - * \file - * \brief C API: Arabic shaping - * - */ - -/** - * Shape Arabic text on a character basis. - * - *

This function performs basic operations for "shaping" Arabic text. It is most - * useful for use with legacy data formats and legacy display technology - * (simple terminals). All operations are performed on Unicode characters.

- * - *

Text-based shaping means that some character code points in the text are - * replaced by others depending on the context. It transforms one kind of text - * into another. In comparison, modern displays for Arabic text select - * appropriate, context-dependent font glyphs for each text element, which means - * that they transform text into a glyph vector.

- * - *

Text transformations are necessary when modern display technology is not - * available or when text needs to be transformed to or from legacy formats that - * use "shaped" characters. Since the Arabic script is cursive, connecting - * adjacent letters to each other, computers select images for each letter based - * on the surrounding letters. This usually results in four images per Arabic - * letter: initial, middle, final, and isolated forms. In Unicode, on the other - * hand, letters are normally stored abstract, and a display system is expected - * to select the necessary glyphs. (This makes searching and other text - * processing easier because the same letter has only one code.) It is possible - * to mimic this with text transformations because there are characters in - * Unicode that are rendered as letters with a specific shape - * (or cursive connectivity). They were included for interoperability with - * legacy systems and codepages, and for unsophisticated display systems.

- * - *

A second kind of text transformations is supported for Arabic digits: - * For compatibility with legacy codepages that only include European digits, - * it is possible to replace one set of digits by another, changing the - * character code points. These operations can be performed for either - * Arabic-Indic Digits (U+0660...U+0669) or Eastern (Extended) Arabic-Indic - * digits (U+06f0...U+06f9).

- * - *

Some replacements may result in more or fewer characters (code points). - * By default, this means that the destination buffer may receive text with a - * length different from the source length. Some legacy systems rely on the - * length of the text to be constant. They expect extra spaces to be added - * or consumed either next to the affected character or at the end of the - * text.

- * - *

For details about the available operations, see the description of the - * U_SHAPE_... options.

- * - * @param source The input text. - * - * @param sourceLength The number of UChars in source. - * - * @param dest The destination buffer that will receive the results of the - * requested operations. It may be NULL only if - * destSize is 0. The source and destination must not - * overlap. - * - * @param destSize The size (capacity) of the destination buffer in UChars. - * If destSize is 0, then no output is produced, - * but the necessary buffer size is returned ("preflighting"). - * - * @param options This is a 32-bit set of flags that specify the operations - * that are performed on the input text. If no error occurs, - * then the result will always be written to the destination - * buffer. - * - * @param pErrorCode must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * - * @return The number of UChars written to the destination buffer. - * If an error occured, then no output was written, or it may be - * incomplete. If U_BUFFER_OVERFLOW_ERROR is set, then - * the return value indicates the necessary destination buffer size. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_shapeArabic(const UChar *source, int32_t sourceLength, - UChar *dest, int32_t destSize, - uint32_t options, - UErrorCode *pErrorCode); - -/** - * Memory option: allow the result to have a different length than the source. - * Affects: LamAlef options - * @stable ICU 2.0 - */ -#define U_SHAPE_LENGTH_GROW_SHRINK 0 - -/** - * Memory option: allow the result to have a different length than the source. - * Affects: LamAlef options - * This option is an alias to U_SHAPE_LENGTH_GROW_SHRINK - * @stable ICU 4.2 - */ -#define U_SHAPE_LAMALEF_RESIZE 0 - -/** - * Memory option: the result must have the same length as the source. - * If more room is necessary, then try to consume spaces next to modified characters. - * @stable ICU 2.0 - */ -#define U_SHAPE_LENGTH_FIXED_SPACES_NEAR 1 - -/** - * Memory option: the result must have the same length as the source. - * If more room is necessary, then try to consume spaces next to modified characters. - * Affects: LamAlef options - * This option is an alias to U_SHAPE_LENGTH_FIXED_SPACES_NEAR - * @stable ICU 4.2 - */ -#define U_SHAPE_LAMALEF_NEAR 1 - -/** - * Memory option: the result must have the same length as the source. - * If more room is necessary, then try to consume spaces at the end of the text. - * @stable ICU 2.0 - */ -#define U_SHAPE_LENGTH_FIXED_SPACES_AT_END 2 - -/** - * Memory option: the result must have the same length as the source. - * If more room is necessary, then try to consume spaces at the end of the text. - * Affects: LamAlef options - * This option is an alias to U_SHAPE_LENGTH_FIXED_SPACES_AT_END - * @stable ICU 4.2 - */ -#define U_SHAPE_LAMALEF_END 2 - -/** - * Memory option: the result must have the same length as the source. - * If more room is necessary, then try to consume spaces at the beginning of the text. - * @stable ICU 2.0 - */ -#define U_SHAPE_LENGTH_FIXED_SPACES_AT_BEGINNING 3 - -/** - * Memory option: the result must have the same length as the source. - * If more room is necessary, then try to consume spaces at the beginning of the text. - * Affects: LamAlef options - * This option is an alias to U_SHAPE_LENGTH_FIXED_SPACES_AT_BEGINNING - * @stable ICU 4.2 - */ -#define U_SHAPE_LAMALEF_BEGIN 3 - - -/** - * Memory option: the result must have the same length as the source. - * Shaping Mode: For each LAMALEF character found, expand LAMALEF using space at end. - * If there is no space at end, use spaces at beginning of the buffer. If there - * is no space at beginning of the buffer, use spaces at the near (i.e. the space - * after the LAMALEF character). - * If there are no spaces found, an error U_NO_SPACE_AVAILABLE (as defined in utypes.h) - * will be set in pErrorCode - * - * Deshaping Mode: Perform the same function as the flag equals U_SHAPE_LAMALEF_END. - * Affects: LamAlef options - * @stable ICU 4.2 - */ -#define U_SHAPE_LAMALEF_AUTO 0x10000 - -/** Bit mask for memory options. @stable ICU 2.0 */ -#define U_SHAPE_LENGTH_MASK 0x10003 /* Changed old value 3 */ - - -/** - * Bit mask for LamAlef memory options. - * @stable ICU 4.2 - */ -#define U_SHAPE_LAMALEF_MASK 0x10003 /* updated */ - -/** Direction indicator: the source is in logical (keyboard) order. @stable ICU 2.0 */ -#define U_SHAPE_TEXT_DIRECTION_LOGICAL 0 - -/** - * Direction indicator: - * the source is in visual RTL order, - * the rightmost displayed character stored first. - * This option is an alias to U_SHAPE_TEXT_DIRECTION_LOGICAL - * @stable ICU 4.2 - */ -#define U_SHAPE_TEXT_DIRECTION_VISUAL_RTL 0 - -/** - * Direction indicator: - * the source is in visual LTR order, - * the leftmost displayed character stored first. - * @stable ICU 2.0 - */ -#define U_SHAPE_TEXT_DIRECTION_VISUAL_LTR 4 - -/** Bit mask for direction indicators. @stable ICU 2.0 */ -#define U_SHAPE_TEXT_DIRECTION_MASK 4 - - -/** Letter shaping option: do not perform letter shaping. @stable ICU 2.0 */ -#define U_SHAPE_LETTERS_NOOP 0 - -/** Letter shaping option: replace abstract letter characters by "shaped" ones. @stable ICU 2.0 */ -#define U_SHAPE_LETTERS_SHAPE 8 - -/** Letter shaping option: replace "shaped" letter characters by abstract ones. @stable ICU 2.0 */ -#define U_SHAPE_LETTERS_UNSHAPE 0x10 - -/** - * Letter shaping option: replace abstract letter characters by "shaped" ones. - * The only difference with U_SHAPE_LETTERS_SHAPE is that Tashkeel letters - * are always "shaped" into the isolated form instead of the medial form - * (selecting code points from the Arabic Presentation Forms-B block). - * @stable ICU 2.0 - */ -#define U_SHAPE_LETTERS_SHAPE_TASHKEEL_ISOLATED 0x18 - - -/** Bit mask for letter shaping options. @stable ICU 2.0 */ -#define U_SHAPE_LETTERS_MASK 0x18 - - -/** Digit shaping option: do not perform digit shaping. @stable ICU 2.0 */ -#define U_SHAPE_DIGITS_NOOP 0 - -/** - * Digit shaping option: - * Replace European digits (U+0030...) by Arabic-Indic digits. - * @stable ICU 2.0 - */ -#define U_SHAPE_DIGITS_EN2AN 0x20 - -/** - * Digit shaping option: - * Replace Arabic-Indic digits by European digits (U+0030...). - * @stable ICU 2.0 - */ -#define U_SHAPE_DIGITS_AN2EN 0x40 - -/** - * Digit shaping option: - * Replace European digits (U+0030...) by Arabic-Indic digits if the most recent - * strongly directional character is an Arabic letter - * (u_charDirection() result U_RIGHT_TO_LEFT_ARABIC [AL]).
- * The direction of "preceding" depends on the direction indicator option. - * For the first characters, the preceding strongly directional character - * (initial state) is assumed to be not an Arabic letter - * (it is U_LEFT_TO_RIGHT [L] or U_RIGHT_TO_LEFT [R]). - * @stable ICU 2.0 - */ -#define U_SHAPE_DIGITS_ALEN2AN_INIT_LR 0x60 - -/** - * Digit shaping option: - * Replace European digits (U+0030...) by Arabic-Indic digits if the most recent - * strongly directional character is an Arabic letter - * (u_charDirection() result U_RIGHT_TO_LEFT_ARABIC [AL]).
- * The direction of "preceding" depends on the direction indicator option. - * For the first characters, the preceding strongly directional character - * (initial state) is assumed to be an Arabic letter. - * @stable ICU 2.0 - */ -#define U_SHAPE_DIGITS_ALEN2AN_INIT_AL 0x80 - -/** Not a valid option value. May be replaced by a new option. @stable ICU 2.0 */ -#define U_SHAPE_DIGITS_RESERVED 0xa0 - -/** Bit mask for digit shaping options. @stable ICU 2.0 */ -#define U_SHAPE_DIGITS_MASK 0xe0 - - -/** Digit type option: Use Arabic-Indic digits (U+0660...U+0669). @stable ICU 2.0 */ -#define U_SHAPE_DIGIT_TYPE_AN 0 - -/** Digit type option: Use Eastern (Extended) Arabic-Indic digits (U+06f0...U+06f9). @stable ICU 2.0 */ -#define U_SHAPE_DIGIT_TYPE_AN_EXTENDED 0x100 - -/** Not a valid option value. May be replaced by a new option. @stable ICU 2.0 */ -#define U_SHAPE_DIGIT_TYPE_RESERVED 0x200 - -/** Bit mask for digit type options. @stable ICU 2.0 */ -#define U_SHAPE_DIGIT_TYPE_MASK 0x300 /* I need to change this from 0x3f00 to 0x300 */ - -/** - * Tashkeel aggregation option: - * Replaces any combination of U+0651 with one of - * U+064C, U+064D, U+064E, U+064F, U+0650 with - * U+FC5E, U+FC5F, U+FC60, U+FC61, U+FC62 consecutively. - * @stable ICU 3.6 - */ -#define U_SHAPE_AGGREGATE_TASHKEEL 0x4000 -/** Tashkeel aggregation option: do not aggregate tashkeels. @stable ICU 3.6 */ -#define U_SHAPE_AGGREGATE_TASHKEEL_NOOP 0 -/** Bit mask for tashkeel aggregation. @stable ICU 3.6 */ -#define U_SHAPE_AGGREGATE_TASHKEEL_MASK 0x4000 - -/** - * Presentation form option: - * Don't replace Arabic Presentation Forms-A and Arabic Presentation Forms-B - * characters with 0+06xx characters, before shaping. - * @stable ICU 3.6 - */ -#define U_SHAPE_PRESERVE_PRESENTATION 0x8000 -/** Presentation form option: - * Replace Arabic Presentation Forms-A and Arabic Presentationo Forms-B with - * their unshaped correspondants in range 0+06xx, before shaping. - * @stable ICU 3.6 - */ -#define U_SHAPE_PRESERVE_PRESENTATION_NOOP 0 -/** Bit mask for preserve presentation form. @stable ICU 3.6 */ -#define U_SHAPE_PRESERVE_PRESENTATION_MASK 0x8000 - -/* Seen Tail option */ -/** - * Memory option: the result must have the same length as the source. - * Shaping mode: The SEEN family character will expand into two characters using space near - * the SEEN family character(i.e. the space after the character). - * If there are no spaces found, an error U_NO_SPACE_AVAILABLE (as defined in utypes.h) - * will be set in pErrorCode - * - * De-shaping mode: Any Seen character followed by Tail character will be - * replaced by one cell Seen and a space will replace the Tail. - * Affects: Seen options - * @stable ICU 4.2 - */ -#define U_SHAPE_SEEN_TWOCELL_NEAR 0x200000 - -/** - * Bit mask for Seen memory options. - * @stable ICU 4.2 - */ -#define U_SHAPE_SEEN_MASK 0x700000 - -/* YehHamza option */ -/** - * Memory option: the result must have the same length as the source. - * Shaping mode: The YEHHAMZA character will expand into two characters using space near it - * (i.e. the space after the character - * If there are no spaces found, an error U_NO_SPACE_AVAILABLE (as defined in utypes.h) - * will be set in pErrorCode - * - * De-shaping mode: Any Yeh (final or isolated) character followed by Hamza character will be - * replaced by one cell YehHamza and space will replace the Hamza. - * Affects: YehHamza options - * @stable ICU 4.2 - */ -#define U_SHAPE_YEHHAMZA_TWOCELL_NEAR 0x1000000 - - -/** - * Bit mask for YehHamza memory options. - * @stable ICU 4.2 - */ -#define U_SHAPE_YEHHAMZA_MASK 0x3800000 - -/* New Tashkeel options */ -/** - * Memory option: the result must have the same length as the source. - * Shaping mode: Tashkeel characters will be replaced by spaces. - * Spaces will be placed at beginning of the buffer - * - * De-shaping mode: N/A - * Affects: Tashkeel options - * @stable ICU 4.2 - */ -#define U_SHAPE_TASHKEEL_BEGIN 0x40000 - -/** - * Memory option: the result must have the same length as the source. - * Shaping mode: Tashkeel characters will be replaced by spaces. - * Spaces will be placed at end of the buffer - * - * De-shaping mode: N/A - * Affects: Tashkeel options - * @stable ICU 4.2 - */ -#define U_SHAPE_TASHKEEL_END 0x60000 - -/** - * Memory option: allow the result to have a different length than the source. - * Shaping mode: Tashkeel characters will be removed, buffer length will shrink. - * De-shaping mode: N/A - * - * Affect: Tashkeel options - * @stable ICU 4.2 - */ -#define U_SHAPE_TASHKEEL_RESIZE 0x80000 - -/** - * Memory option: the result must have the same length as the source. - * Shaping mode: Tashkeel characters will be replaced by Tatweel if it is connected to adjacent - * characters (i.e. shaped on Tatweel) or replaced by space if it is not connected. - * - * De-shaping mode: N/A - * Affects: YehHamza options - * @stable ICU 4.2 - */ -#define U_SHAPE_TASHKEEL_REPLACE_BY_TATWEEL 0xC0000 - -/** - * Bit mask for Tashkeel replacement with Space or Tatweel memory options. - * @stable ICU 4.2 - */ -#define U_SHAPE_TASHKEEL_MASK 0xE0000 - - -/* Space location Control options */ -/** - * This option affect the meaning of BEGIN and END options. if this option is not used the default - * for BEGIN and END will be as following: - * The Default (for both Visual LTR, Visual RTL and Logical Text) - * 1. BEGIN always refers to the start address of physical memory. - * 2. END always refers to the end address of physical memory. - * - * If this option is used it will swap the meaning of BEGIN and END only for Visual LTR text. - * - * The effect on BEGIN and END Memory Options will be as following: - * A. BEGIN For Visual LTR text: This will be the beginning (right side) of the visual text( - * corresponding to the physical memory address end for Visual LTR text, Same as END in - * default behavior) - * B. BEGIN For Logical text: Same as BEGIN in default behavior. - * C. END For Visual LTR text: This will be the end (left side) of the visual text (corresponding - * to the physical memory address beginning for Visual LTR text, Same as BEGIN in default behavior. - * D. END For Logical text: Same as END in default behavior). - * Affects: All LamAlef BEGIN, END and AUTO options. - * @stable ICU 4.2 - */ -#define U_SHAPE_SPACES_RELATIVE_TO_TEXT_BEGIN_END 0x4000000 - -/** - * Bit mask for swapping BEGIN and END for Visual LTR text - * @stable ICU 4.2 - */ -#define U_SHAPE_SPACES_RELATIVE_TO_TEXT_MASK 0x4000000 - -/** - * If this option is used, shaping will use the new Unicode code point for TAIL (i.e. 0xFE73). - * If this option is not specified (Default), old unofficial Unicode TAIL code point is used (i.e. 0x200B) - * De-shaping will not use this option as it will always search for both the new Unicode code point for the - * TAIL (i.e. 0xFE73) or the old unofficial Unicode TAIL code point (i.e. 0x200B) and de-shape the - * Seen-Family letter accordingly. - * - * Shaping Mode: Only shaping. - * De-shaping Mode: N/A. - * Affects: All Seen options - * @stable ICU 4.8 - */ -#define U_SHAPE_TAIL_NEW_UNICODE 0x8000000 - -/** - * Bit mask for new Unicode Tail option - * @stable ICU 4.8 - */ -#define U_SHAPE_TAIL_TYPE_MASK 0x8000000 - -#endif diff --git a/win32/include/spidermonkey/unicode/uspoof.h b/win32/include/spidermonkey/unicode/uspoof.h deleted file mode 100755 index 40b73380..00000000 --- a/win32/include/spidermonkey/unicode/uspoof.h +++ /dev/null @@ -1,1581 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -*************************************************************************** -* Copyright (C) 2008-2016, International Business Machines Corporation -* and others. All Rights Reserved. -*************************************************************************** -* file name: uspoof.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2008Feb13 -* created by: Andy Heninger -* -* Unicode Spoof Detection -*/ - -#ifndef USPOOF_H -#define USPOOF_H - -#include "unicode/utypes.h" -#include "unicode/uset.h" -#include "unicode/parseerr.h" -#include "unicode/localpointer.h" - -#if !UCONFIG_NO_NORMALIZATION - - -#if U_SHOW_CPLUSPLUS_API -#include "unicode/unistr.h" -#include "unicode/uniset.h" -#endif - - -/** - * \file - * \brief Unicode Security and Spoofing Detection, C API. - * - *

- * This class, based on Unicode Technical Report #36 and - * Unicode Technical Standard #39, has two main functions: - * - *

    - *
  1. Checking whether two strings are visually confusable with each other, such as "Harvest" and - * "Ηarvest", where the second string starts with the Greek capital letter Eta.
  2. - *
  3. Checking whether an individual string is likely to be an attempt at confusing the reader (spoof - * detection), such as "paypal" with some Latin characters substituted with Cyrillic look-alikes.
  4. - *
- * - *

- * Although originally designed as a method for flagging suspicious identifier strings such as URLs, - * USpoofChecker has a number of other practical use cases, such as preventing attempts to evade bad-word - * content filters. - * - *

- * The functions of this class are exposed as C API, with a handful of syntactical conveniences for C++. - * - *

Confusables

- * - *

- * The following example shows how to use USpoofChecker to check for confusability between two strings: - * - * \code{.c} - * UErrorCode status = U_ZERO_ERROR; - * UChar* str1 = (UChar*) u"Harvest"; - * UChar* str2 = (UChar*) u"\u0397arvest"; // with U+0397 GREEK CAPITAL LETTER ETA - * - * USpoofChecker* sc = uspoof_open(&status); - * uspoof_setChecks(sc, USPOOF_CONFUSABLE, &status); - * - * int32_t bitmask = uspoof_areConfusable(sc, str1, -1, str2, -1, &status); - * UBool result = bitmask != 0; - * // areConfusable: 1 (status: U_ZERO_ERROR) - * printf("areConfusable: %d (status: %s)\n", result, u_errorName(status)); - * uspoof_close(sc); - * \endcode - * - *

- * The call to {@link uspoof_open} creates a USpoofChecker object; the call to {@link uspoof_setChecks} - * enables confusable checking and disables all other checks; the call to {@link uspoof_areConfusable} performs the - * confusability test; and the following line extracts the result out of the return value. For best performance, - * the instance should be created once (e.g., upon application startup), and the efficient - * {@link uspoof_areConfusable} method can be used at runtime. - * - *

- * The type {@link LocalUSpoofCheckerPointer} is exposed for C++ programmers. It will automatically call - * {@link uspoof_close} when the object goes out of scope: - * - * \code{.cpp} - * UErrorCode status = U_ZERO_ERROR; - * LocalUSpoofCheckerPointer sc(uspoof_open(&status)); - * uspoof_setChecks(sc.getAlias(), USPOOF_CONFUSABLE, &status); - * // ... - * \endcode - * - *

- * UTS 39 defines two strings to be confusable if they map to the same skeleton string. A skeleton can - * be thought of as a "hash code". {@link uspoof_getSkeleton} computes the skeleton for a particular string, so - * the following snippet is equivalent to the example above: - * - * \code{.c} - * UErrorCode status = U_ZERO_ERROR; - * UChar* str1 = (UChar*) u"Harvest"; - * UChar* str2 = (UChar*) u"\u0397arvest"; // with U+0397 GREEK CAPITAL LETTER ETA - * - * USpoofChecker* sc = uspoof_open(&status); - * uspoof_setChecks(sc, USPOOF_CONFUSABLE, &status); - * - * // Get skeleton 1 - * int32_t skel1Len = uspoof_getSkeleton(sc, 0, str1, -1, NULL, 0, &status); - * UChar* skel1 = (UChar*) malloc(++skel1Len * sizeof(UChar)); - * status = U_ZERO_ERROR; - * uspoof_getSkeleton(sc, 0, str1, -1, skel1, skel1Len, &status); - * - * // Get skeleton 2 - * int32_t skel2Len = uspoof_getSkeleton(sc, 0, str2, -1, NULL, 0, &status); - * UChar* skel2 = (UChar*) malloc(++skel2Len * sizeof(UChar)); - * status = U_ZERO_ERROR; - * uspoof_getSkeleton(sc, 0, str2, -1, skel2, skel2Len, &status); - * - * // Are the skeletons the same? - * UBool result = u_strcmp(skel1, skel2) == 0; - * // areConfusable: 1 (status: U_ZERO_ERROR) - * printf("areConfusable: %d (status: %s)\n", result, u_errorName(status)); - * uspoof_close(sc); - * free(skel1); - * free(skel2); - * \endcode - * - *

- * If you need to check if a string is confusable with any string in a dictionary of many strings, rather than calling - * {@link uspoof_areConfusable} many times in a loop, {@link uspoof_getSkeleton} can be used instead, as shown below: - * - * \code{.c} - * UErrorCode status = U_ZERO_ERROR; - * #define DICTIONARY_LENGTH 2 - * UChar* dictionary[DICTIONARY_LENGTH] = { (UChar*) u"lorem", (UChar*) u"ipsum" }; - * UChar* skeletons[DICTIONARY_LENGTH]; - * UChar* str = (UChar*) u"1orern"; - * - * // Setup: - * USpoofChecker* sc = uspoof_open(&status); - * uspoof_setChecks(sc, USPOOF_CONFUSABLE, &status); - * for (size_t i=0; i - * Note: Since the Unicode confusables mapping table is frequently updated, confusable skeletons are not - * guaranteed to be the same between ICU releases. We therefore recommend that you always compute confusable skeletons - * at runtime and do not rely on creating a permanent, or difficult to update, database of skeletons. - * - *

Spoof Detection

- * - *

- * The following snippet shows a minimal example of using USpoofChecker to perform spoof detection on a - * string: - * - * \code{.c} - * UErrorCode status = U_ZERO_ERROR; - * UChar* str = (UChar*) u"p\u0430ypal"; // with U+0430 CYRILLIC SMALL LETTER A - * - * // Get the default set of allowable characters: - * USet* allowed = uset_openEmpty(); - * uset_addAll(allowed, uspoof_getRecommendedSet(&status)); - * uset_addAll(allowed, uspoof_getInclusionSet(&status)); - * - * USpoofChecker* sc = uspoof_open(&status); - * uspoof_setAllowedChars(sc, allowed, &status); - * uspoof_setRestrictionLevel(sc, USPOOF_MODERATELY_RESTRICTIVE); - * - * int32_t bitmask = uspoof_check(sc, str, -1, NULL, &status); - * UBool result = bitmask != 0; - * // fails checks: 1 (status: U_ZERO_ERROR) - * printf("fails checks: %d (status: %s)\n", result, u_errorName(status)); - * uspoof_close(sc); - * uset_close(allowed); - * \endcode - * - *

- * As in the case for confusability checking, it is good practice to create one USpoofChecker instance at - * startup, and call the cheaper {@link uspoof_check} online. We specify the set of - * allowed characters to be those with type RECOMMENDED or INCLUSION, according to the recommendation in UTS 39. - * - *

- * In addition to {@link uspoof_check}, the function {@link uspoof_checkUTF8} is exposed for UTF8-encoded char* strings, - * and {@link uspoof_checkUnicodeString} is exposed for C++ programmers. - * - *

- * If the {@link USPOOF_AUX_INFO} check is enabled, a limited amount of information on why a string failed the checks - * is available in the returned bitmask. For complete information, use the {@link uspoof_check2} class of functions - * with a {@link USpoofCheckResult} parameter: - * - * \code{.c} - * UErrorCode status = U_ZERO_ERROR; - * UChar* str = (UChar*) u"p\u0430ypal"; // with U+0430 CYRILLIC SMALL LETTER A - * - * // Get the default set of allowable characters: - * USet* allowed = uset_openEmpty(); - * uset_addAll(allowed, uspoof_getRecommendedSet(&status)); - * uset_addAll(allowed, uspoof_getInclusionSet(&status)); - * - * USpoofChecker* sc = uspoof_open(&status); - * uspoof_setAllowedChars(sc, allowed, &status); - * uspoof_setRestrictionLevel(sc, USPOOF_MODERATELY_RESTRICTIVE); - * - * USpoofCheckResult* checkResult = uspoof_openCheckResult(&status); - * int32_t bitmask = uspoof_check2(sc, str, -1, checkResult, &status); - * - * int32_t failures1 = bitmask; - * int32_t failures2 = uspoof_getCheckResultChecks(checkResult, &status); - * assert(failures1 == failures2); - * // checks that failed: 0x00000010 (status: U_ZERO_ERROR) - * printf("checks that failed: %#010x (status: %s)\n", failures1, u_errorName(status)); - * - * // Cleanup: - * uspoof_close(sc); - * uset_close(allowed); - * uspoof_closeCheckResult(checkResult); - * \endcode - * - * C++ users can take advantage of a few syntactical conveniences. The following snippet is functionally - * equivalent to the one above: - * - * \code{.cpp} - * UErrorCode status = U_ZERO_ERROR; - * UnicodeString str((UChar*) u"p\u0430ypal"); // with U+0430 CYRILLIC SMALL LETTER A - * - * // Get the default set of allowable characters: - * UnicodeSet allowed; - * allowed.addAll(*uspoof_getRecommendedUnicodeSet(&status)); - * allowed.addAll(*uspoof_getInclusionUnicodeSet(&status)); - * - * LocalUSpoofCheckerPointer sc(uspoof_open(&status)); - * uspoof_setAllowedChars(sc.getAlias(), allowed.toUSet(), &status); - * uspoof_setRestrictionLevel(sc.getAlias(), USPOOF_MODERATELY_RESTRICTIVE); - * - * LocalUSpoofCheckResultPointer checkResult(uspoof_openCheckResult(&status)); - * int32_t bitmask = uspoof_check2UnicodeString(sc.getAlias(), str, checkResult.getAlias(), &status); - * - * int32_t failures1 = bitmask; - * int32_t failures2 = uspoof_getCheckResultChecks(checkResult.getAlias(), &status); - * assert(failures1 == failures2); - * // checks that failed: 0x00000010 (status: U_ZERO_ERROR) - * printf("checks that failed: %#010x (status: %s)\n", failures1, u_errorName(status)); - * - * // Explicit cleanup not necessary. - * \endcode - * - *

- * The return value is a bitmask of the checks that failed. In this case, there was one check that failed: - * {@link USPOOF_RESTRICTION_LEVEL}, corresponding to the fifth bit (16). The possible checks are: - * - *

    - *
  • RESTRICTION_LEVEL: flags strings that violate the - * Restriction Level test as specified in UTS - * 39; in most cases, this means flagging strings that contain characters from multiple different scripts.
  • - *
  • INVISIBLE: flags strings that contain invisible characters, such as zero-width spaces, or character - * sequences that are likely not to display, such as multiple occurrences of the same non-spacing mark.
  • - *
  • CHAR_LIMIT: flags strings that contain characters outside of a specified set of acceptable - * characters. See {@link uspoof_setAllowedChars} and {@link uspoof_setAllowedLocales}.
  • - *
  • MIXED_NUMBERS: flags strings that contain digits from multiple different numbering systems.
  • - *
- * - *

- * These checks can be enabled independently of each other. For example, if you were interested in checking for only the - * INVISIBLE and MIXED_NUMBERS conditions, you could do: - * - * \code{.c} - * UErrorCode status = U_ZERO_ERROR; - * UChar* str = (UChar*) u"8\u09EA"; // 8 mixed with U+09EA BENGALI DIGIT FOUR - * - * USpoofChecker* sc = uspoof_open(&status); - * uspoof_setChecks(sc, USPOOF_INVISIBLE | USPOOF_MIXED_NUMBERS, &status); - * - * int32_t bitmask = uspoof_check2(sc, str, -1, NULL, &status); - * UBool result = bitmask != 0; - * // fails checks: 1 (status: U_ZERO_ERROR) - * printf("fails checks: %d (status: %s)\n", result, u_errorName(status)); - * uspoof_close(sc); - * \endcode - * - *

- * Here is an example in C++ showing how to compute the restriction level of a string: - * - * \code{.cpp} - * UErrorCode status = U_ZERO_ERROR; - * UnicodeString str((UChar*) u"p\u0430ypal"); // with U+0430 CYRILLIC SMALL LETTER A - * - * // Get the default set of allowable characters: - * UnicodeSet allowed; - * allowed.addAll(*uspoof_getRecommendedUnicodeSet(&status)); - * allowed.addAll(*uspoof_getInclusionUnicodeSet(&status)); - * - * LocalUSpoofCheckerPointer sc(uspoof_open(&status)); - * uspoof_setAllowedChars(sc.getAlias(), allowed.toUSet(), &status); - * uspoof_setRestrictionLevel(sc.getAlias(), USPOOF_MODERATELY_RESTRICTIVE); - * uspoof_setChecks(sc.getAlias(), USPOOF_RESTRICTION_LEVEL | USPOOF_AUX_INFO, &status); - * - * LocalUSpoofCheckResultPointer checkResult(uspoof_openCheckResult(&status)); - * int32_t bitmask = uspoof_check2UnicodeString(sc.getAlias(), str, checkResult.getAlias(), &status); - * - * URestrictionLevel restrictionLevel = uspoof_getCheckResultRestrictionLevel(checkResult.getAlias(), &status); - * // Since USPOOF_AUX_INFO was enabled, the restriction level is also available in the upper bits of the bitmask: - * assert((restrictionLevel & bitmask) == restrictionLevel); - * // Restriction level: 0x50000000 (status: U_ZERO_ERROR) - * printf("Restriction level: %#010x (status: %s)\n", restrictionLevel, u_errorName(status)); - * \endcode - * - *

- * The code '0x50000000' corresponds to the restriction level USPOOF_MINIMALLY_RESTRICTIVE. Since - * USPOOF_MINIMALLY_RESTRICTIVE is weaker than USPOOF_MODERATELY_RESTRICTIVE, the string fails the check. - * - *

- * Note: The Restriction Level is the most powerful of the checks. The full logic is documented in - * UTS 39, but the basic idea is that strings - * are restricted to contain characters from only a single script, except that most scripts are allowed to have - * Latin characters interspersed. Although the default restriction level is HIGHLY_RESTRICTIVE, it is - * recommended that users set their restriction level to MODERATELY_RESTRICTIVE, which allows Latin mixed - * with all other scripts except Cyrillic, Greek, and Cherokee, with which it is often confusable. For more details on - * the levels, see UTS 39 or {@link URestrictionLevel}. The Restriction Level test is aware of the set of - * allowed characters set in {@link uspoof_setAllowedChars}. Note that characters which have script code - * COMMON or INHERITED, such as numbers and punctuation, are ignored when computing whether a string has multiple - * scripts. - * - *

Additional Information

- * - *

- * A USpoofChecker instance may be used repeatedly to perform checks on any number of identifiers. - * - *

- * Thread Safety: The test functions for checking a single identifier, or for testing whether - * two identifiers are possible confusable, are thread safe. They may called concurrently, from multiple threads, - * using the same USpoofChecker instance. - * - *

- * More generally, the standard ICU thread safety rules apply: functions that take a const USpoofChecker parameter are - * thread safe. Those that take a non-const USpoofChecker are not thread safe.. - * - * @stable ICU 4.6 - */ - -struct USpoofChecker; -typedef struct USpoofChecker USpoofChecker; /**< typedef for C of USpoofChecker */ - -#ifndef U_HIDE_DRAFT_API -/** - * @see uspoof_openCheckResult - */ -struct USpoofCheckResult; -/** - * @see uspoof_openCheckResult - */ -typedef struct USpoofCheckResult USpoofCheckResult; -#endif /* U_HIDE_DRAFT_API */ - -/** - * Enum for the kinds of checks that USpoofChecker can perform. - * These enum values are used both to select the set of checks that - * will be performed, and to report results from the check function. - * - * @stable ICU 4.2 - */ -typedef enum USpoofChecks { - /** - * When performing the two-string {@link uspoof_areConfusable} test, this flag in the return value indicates - * that the two strings are visually confusable and that they are from the same script, according to UTS 39 section - * 4. - * - * @see uspoof_areConfusable - * @stable ICU 4.2 - */ - USPOOF_SINGLE_SCRIPT_CONFUSABLE = 1, - - /** - * When performing the two-string {@link uspoof_areConfusable} test, this flag in the return value indicates - * that the two strings are visually confusable and that they are not from the same script, according to UTS - * 39 section 4. - * - * @see uspoof_areConfusable - * @stable ICU 4.2 - */ - USPOOF_MIXED_SCRIPT_CONFUSABLE = 2, - - /** - * When performing the two-string {@link uspoof_areConfusable} test, this flag in the return value indicates - * that the two strings are visually confusable and that they are not from the same script but both of them are - * single-script strings, according to UTS 39 section 4. - * - * @see uspoof_areConfusable - * @stable ICU 4.2 - */ - USPOOF_WHOLE_SCRIPT_CONFUSABLE = 4, - -#ifndef U_HIDE_DRAFT_API - /** - * Enable this flag in {@link uspoof_setChecks} to turn on all types of confusables. You may set - * the checks to some subset of SINGLE_SCRIPT_CONFUSABLE, MIXED_SCRIPT_CONFUSABLE, or WHOLE_SCRIPT_CONFUSABLE to - * make {@link uspoof_areConfusable} return only those types of confusables. - * - * @see uspoof_areConfusable - * @see uspoof_getSkeleton - * @draft ICU 58 - */ - USPOOF_CONFUSABLE = USPOOF_SINGLE_SCRIPT_CONFUSABLE | USPOOF_MIXED_SCRIPT_CONFUSABLE | USPOOF_WHOLE_SCRIPT_CONFUSABLE, -#endif /* U_HIDE_DRAFT_API */ - -#ifndef U_HIDE_DEPRECATED_API - /** - * This flag is deprecated and no longer affects the behavior of SpoofChecker. - * - * @deprecated ICU 58 Any case confusable mappings were removed from UTS 39; the corresponding ICU API was deprecated. - */ - USPOOF_ANY_CASE = 8, -#endif /* U_HIDE_DEPRECATED_API */ - - /** - * Check that an identifier is no looser than the specified RestrictionLevel. - * The default if {@link uspoof_setRestrictionLevel} is not called is HIGHLY_RESTRICTIVE. - * - * If USPOOF_AUX_INFO is enabled the actual restriction level of the - * identifier being tested will also be returned by uspoof_check(). - * - * @see URestrictionLevel - * @see uspoof_setRestrictionLevel - * @see USPOOF_AUX_INFO - * - * @stable ICU 51 - */ - USPOOF_RESTRICTION_LEVEL = 16, - -#ifndef U_HIDE_DEPRECATED_API - /** Check that an identifier contains only characters from a - * single script (plus chars from the common and inherited scripts.) - * Applies to checks of a single identifier check only. - * @deprecated ICU 51 Use RESTRICTION_LEVEL instead. - */ - USPOOF_SINGLE_SCRIPT = USPOOF_RESTRICTION_LEVEL, -#endif /* U_HIDE_DEPRECATED_API */ - - /** Check an identifier for the presence of invisible characters, - * such as zero-width spaces, or character sequences that are - * likely not to display, such as multiple occurrences of the same - * non-spacing mark. This check does not test the input string as a whole - * for conformance to any particular syntax for identifiers. - */ - USPOOF_INVISIBLE = 32, - - /** Check that an identifier contains only characters from a specified set - * of acceptable characters. See {@link uspoof_setAllowedChars} and - * {@link uspoof_setAllowedLocales}. Note that a string that fails this check - * will also fail the {@link USPOOF_RESTRICTION_LEVEL} check. - */ - USPOOF_CHAR_LIMIT = 64, - - /** - * Check that an identifier does not mix numbers from different numbering systems. - * For more information, see UTS 39 section 5.3. - * - * @stable ICU 51 - */ - USPOOF_MIXED_NUMBERS = 128, - - /** - * Enable all spoof checks. - * - * @stable ICU 4.6 - */ - USPOOF_ALL_CHECKS = 0xFFFF, - - /** - * Enable the return of auxillary (non-error) information in the - * upper bits of the check results value. - * - * If this "check" is not enabled, the results of {@link uspoof_check} will be - * zero when an identifier passes all of the enabled checks. - * - * If this "check" is enabled, (uspoof_check() & {@link USPOOF_ALL_CHECKS}) will - * be zero when an identifier passes all checks. - * - * @stable ICU 51 - */ - USPOOF_AUX_INFO = 0x40000000 - - } USpoofChecks; - - - /** - * Constants from UAX #39 for use in {@link uspoof_setRestrictionLevel}, and - * for returned identifier restriction levels in check results. - * - * @stable ICU 51 - * - * @see uspoof_setRestrictionLevel - * @see uspoof_check - */ - typedef enum URestrictionLevel { - /** - * All characters in the string are in the identifier profile and all characters in the string are in the - * ASCII range. - * - * @stable ICU 51 - */ - USPOOF_ASCII = 0x10000000, - /** - * The string classifies as ASCII-Only, or all characters in the string are in the identifier profile and - * the string is single-script, according to the definition in UTS 39 section 5.1. - * - * @stable ICU 53 - */ - USPOOF_SINGLE_SCRIPT_RESTRICTIVE = 0x20000000, - /** - * The string classifies as Single Script, or all characters in the string are in the identifier profile and - * the string is covered by any of the following sets of scripts, according to the definition in UTS 39 - * section 5.1: - *

    - *
  • Latin + Han + Bopomofo (or equivalently: Latn + Hanb)
  • - *
  • Latin + Han + Hiragana + Katakana (or equivalently: Latn + Jpan)
  • - *
  • Latin + Han + Hangul (or equivalently: Latn +Kore)
  • - *
- * This is the default restriction in ICU. - * - * @stable ICU 51 - */ - USPOOF_HIGHLY_RESTRICTIVE = 0x30000000, - /** - * The string classifies as Highly Restrictive, or all characters in the string are in the identifier profile - * and the string is covered by Latin and any one other Recommended or Aspirational script, except Cyrillic, - * Greek, and Cherokee. - * - * @stable ICU 51 - */ - USPOOF_MODERATELY_RESTRICTIVE = 0x40000000, - /** - * All characters in the string are in the identifier profile. Allow arbitrary mixtures of scripts. - * - * @stable ICU 51 - */ - USPOOF_MINIMALLY_RESTRICTIVE = 0x50000000, - /** - * Any valid identifiers, including characters outside of the Identifier Profile. - * - * @stable ICU 51 - */ - USPOOF_UNRESTRICTIVE = 0x60000000, - /** - * Mask for selecting the Restriction Level bits from the return value of {@link uspoof_check}. - * - * @stable ICU 53 - */ - USPOOF_RESTRICTION_LEVEL_MASK = 0x7F000000, -#ifndef U_HIDE_INTERNAL_API - /** - * An undefined restriction level. - * @internal - */ - USPOOF_UNDEFINED_RESTRICTIVE = -1 -#endif /* U_HIDE_INTERNAL_API */ - } URestrictionLevel; - -/** - * Create a Unicode Spoof Checker, configured to perform all - * checks except for USPOOF_LOCALE_LIMIT and USPOOF_CHAR_LIMIT. - * Note that additional checks may be added in the future, - * resulting in the changes to the default checking behavior. - * - * @param status The error code, set if this function encounters a problem. - * @return the newly created Spoof Checker - * @stable ICU 4.2 - */ -U_STABLE USpoofChecker * U_EXPORT2 -uspoof_open(UErrorCode *status); - - -/** - * Open a Spoof checker from its serialized form, stored in 32-bit-aligned memory. - * Inverse of uspoof_serialize(). - * The memory containing the serialized data must remain valid and unchanged - * as long as the spoof checker, or any cloned copies of the spoof checker, - * are in use. Ownership of the memory remains with the caller. - * The spoof checker (and any clones) must be closed prior to deleting the - * serialized data. - * - * @param data a pointer to 32-bit-aligned memory containing the serialized form of spoof data - * @param length the number of bytes available at data; - * can be more than necessary - * @param pActualLength receives the actual number of bytes at data taken up by the data; - * can be NULL - * @param pErrorCode ICU error code - * @return the spoof checker. - * - * @see uspoof_open - * @see uspoof_serialize - * @stable ICU 4.2 - */ -U_STABLE USpoofChecker * U_EXPORT2 -uspoof_openFromSerialized(const void *data, int32_t length, int32_t *pActualLength, - UErrorCode *pErrorCode); - -/** - * Open a Spoof Checker from the source form of the spoof data. - * The input corresponds to the Unicode data file confusables.txt - * as described in Unicode UAX #39. The syntax of the source data - * is as described in UAX #39 for this file, and the content of - * this file is acceptable input. - * - * The character encoding of the (char *) input text is UTF-8. - * - * @param confusables a pointer to the confusable characters definitions, - * as found in file confusables.txt from unicode.org. - * @param confusablesLen The length of the confusables text, or -1 if the - * input string is zero terminated. - * @param confusablesWholeScript - * Deprecated in ICU 58. No longer used. - * @param confusablesWholeScriptLen - * Deprecated in ICU 58. No longer used. - * @param errType In the event of an error in the input, indicates - * which of the input files contains the error. - * The value is one of USPOOF_SINGLE_SCRIPT_CONFUSABLE or - * USPOOF_WHOLE_SCRIPT_CONFUSABLE, or - * zero if no errors are found. - * @param pe In the event of an error in the input, receives the position - * in the input text (line, offset) of the error. - * @param status an in/out ICU UErrorCode. Among the possible errors is - * U_PARSE_ERROR, which is used to report syntax errors - * in the input. - * @return A spoof checker that uses the rules from the input files. - * @stable ICU 4.2 - */ -U_STABLE USpoofChecker * U_EXPORT2 -uspoof_openFromSource(const char *confusables, int32_t confusablesLen, - const char *confusablesWholeScript, int32_t confusablesWholeScriptLen, - int32_t *errType, UParseError *pe, UErrorCode *status); - - -/** - * Close a Spoof Checker, freeing any memory that was being held by - * its implementation. - * @stable ICU 4.2 - */ -U_STABLE void U_EXPORT2 -uspoof_close(USpoofChecker *sc); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUSpoofCheckerPointer - * "Smart pointer" class, closes a USpoofChecker via uspoof_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUSpoofCheckerPointer, USpoofChecker, uspoof_close); - -U_NAMESPACE_END - -#endif - -/** - * Clone a Spoof Checker. The clone will be set to perform the same checks - * as the original source. - * - * @param sc The source USpoofChecker - * @param status The error code, set if this function encounters a problem. - * @return - * @stable ICU 4.2 - */ -U_STABLE USpoofChecker * U_EXPORT2 -uspoof_clone(const USpoofChecker *sc, UErrorCode *status); - - -/** - * Specify the bitmask of checks that will be performed by {@link uspoof_check}. Calling this method - * overwrites any checks that may have already been enabled. By default, all checks are enabled. - * - * To enable specific checks and disable all others, the "whitelisted" checks should be ORed together. For - * example, to fail strings containing characters outside of the set specified by {@link uspoof_setAllowedChars} and - * also strings that contain digits from mixed numbering systems: - * - *
- * {@code
- * uspoof_setChecks(USPOOF_CHAR_LIMIT | USPOOF_MIXED_NUMBERS);
- * }
- * 
- * - * To disable specific checks and enable all others, the "blacklisted" checks should be ANDed away from - * ALL_CHECKS. For example, if you are not planning to use the {@link uspoof_areConfusable} functionality, - * it is good practice to disable the CONFUSABLE check: - * - *
- * {@code
- * uspoof_setChecks(USPOOF_ALL_CHECKS & ~USPOOF_CONFUSABLE);
- * }
- * 
- * - * Note that methods such as {@link uspoof_setAllowedChars}, {@link uspoof_setAllowedLocales}, and - * {@link uspoof_setRestrictionLevel} will enable certain checks when called. Those methods will OR the check they - * enable onto the existing bitmask specified by this method. For more details, see the documentation of those - * methods. - * - * @param sc The USpoofChecker - * @param checks The set of checks that this spoof checker will perform. - * The value is a bit set, obtained by OR-ing together - * values from enum USpoofChecks. - * @param status The error code, set if this function encounters a problem. - * @stable ICU 4.2 - * - */ -U_STABLE void U_EXPORT2 -uspoof_setChecks(USpoofChecker *sc, int32_t checks, UErrorCode *status); - -/** - * Get the set of checks that this Spoof Checker has been configured to perform. - * - * @param sc The USpoofChecker - * @param status The error code, set if this function encounters a problem. - * @return The set of checks that this spoof checker will perform. - * The value is a bit set, obtained by OR-ing together - * values from enum USpoofChecks. - * @stable ICU 4.2 - * - */ -U_STABLE int32_t U_EXPORT2 -uspoof_getChecks(const USpoofChecker *sc, UErrorCode *status); - -/** - * Set the loosest restriction level allowed for strings. The default if this is not called is - * {@link USPOOF_HIGHLY_RESTRICTIVE}. Calling this method enables the {@link USPOOF_RESTRICTION_LEVEL} and - * {@link USPOOF_MIXED_NUMBERS} checks, corresponding to Sections 5.1 and 5.2 of UTS 39. To customize which checks are - * to be performed by {@link uspoof_check}, see {@link uspoof_setChecks}. - * - * @param sc The USpoofChecker - * @param restrictionLevel The loosest restriction level allowed. - * @see URestrictionLevel - * @stable ICU 51 - */ -U_STABLE void U_EXPORT2 -uspoof_setRestrictionLevel(USpoofChecker *sc, URestrictionLevel restrictionLevel); - - -/** - * Get the Restriction Level that will be tested if the checks include {@link USPOOF_RESTRICTION_LEVEL}. - * - * @return The restriction level - * @see URestrictionLevel - * @stable ICU 51 - */ -U_STABLE URestrictionLevel U_EXPORT2 -uspoof_getRestrictionLevel(const USpoofChecker *sc); - -/** - * Limit characters that are acceptable in identifiers being checked to those - * normally used with the languages associated with the specified locales. - * Any previously specified list of locales is replaced by the new settings. - * - * A set of languages is determined from the locale(s), and - * from those a set of acceptable Unicode scripts is determined. - * Characters from this set of scripts, along with characters from - * the "common" and "inherited" Unicode Script categories - * will be permitted. - * - * Supplying an empty string removes all restrictions; - * characters from any script will be allowed. - * - * The {@link USPOOF_CHAR_LIMIT} test is automatically enabled for this - * USpoofChecker when calling this function with a non-empty list - * of locales. - * - * The Unicode Set of characters that will be allowed is accessible - * via the uspoof_getAllowedChars() function. uspoof_setAllowedLocales() - * will replace any previously applied set of allowed characters. - * - * Adjustments, such as additions or deletions of certain classes of characters, - * can be made to the result of uspoof_setAllowedLocales() by - * fetching the resulting set with uspoof_getAllowedChars(), - * manipulating it with the Unicode Set API, then resetting the - * spoof detectors limits with uspoof_setAllowedChars(). - * - * @param sc The USpoofChecker - * @param localesList A list list of locales, from which the language - * and associated script are extracted. The locales - * are comma-separated if there is more than one. - * White space may not appear within an individual locale, - * but is ignored otherwise. - * The locales are syntactically like those from the - * HTTP Accept-Language header. - * If the localesList is empty, no restrictions will be placed on - * the allowed characters. - * - * @param status The error code, set if this function encounters a problem. - * @stable ICU 4.2 - */ -U_STABLE void U_EXPORT2 -uspoof_setAllowedLocales(USpoofChecker *sc, const char *localesList, UErrorCode *status); - -/** - * Get a list of locales for the scripts that are acceptable in strings - * to be checked. If no limitations on scripts have been specified, - * an empty string will be returned. - * - * uspoof_setAllowedChars() will reset the list of allowed to be empty. - * - * The format of the returned list is the same as that supplied to - * uspoof_setAllowedLocales(), but returned list may not be identical - * to the originally specified string; the string may be reformatted, - * and information other than languages from - * the originally specified locales may be omitted. - * - * @param sc The USpoofChecker - * @param status The error code, set if this function encounters a problem. - * @return A string containing a list of locales corresponding - * to the acceptable scripts, formatted like an - * HTTP Accept Language value. - * - * @stable ICU 4.2 - */ -U_STABLE const char * U_EXPORT2 -uspoof_getAllowedLocales(USpoofChecker *sc, UErrorCode *status); - - -/** - * Limit the acceptable characters to those specified by a Unicode Set. - * Any previously specified character limit is - * is replaced by the new settings. This includes limits on - * characters that were set with the uspoof_setAllowedLocales() function. - * - * The USPOOF_CHAR_LIMIT test is automatically enabled for this - * USpoofChecker by this function. - * - * @param sc The USpoofChecker - * @param chars A Unicode Set containing the list of - * characters that are permitted. Ownership of the set - * remains with the caller. The incoming set is cloned by - * this function, so there are no restrictions on modifying - * or deleting the USet after calling this function. - * @param status The error code, set if this function encounters a problem. - * @stable ICU 4.2 - */ -U_STABLE void U_EXPORT2 -uspoof_setAllowedChars(USpoofChecker *sc, const USet *chars, UErrorCode *status); - - -/** - * Get a USet for the characters permitted in an identifier. - * This corresponds to the limits imposed by the Set Allowed Characters - * functions. Limitations imposed by other checks will not be - * reflected in the set returned by this function. - * - * The returned set will be frozen, meaning that it cannot be modified - * by the caller. - * - * Ownership of the returned set remains with the Spoof Detector. The - * returned set will become invalid if the spoof detector is closed, - * or if a new set of allowed characters is specified. - * - * - * @param sc The USpoofChecker - * @param status The error code, set if this function encounters a problem. - * @return A USet containing the characters that are permitted by - * the USPOOF_CHAR_LIMIT test. - * @stable ICU 4.2 - */ -U_STABLE const USet * U_EXPORT2 -uspoof_getAllowedChars(const USpoofChecker *sc, UErrorCode *status); - - -#if U_SHOW_CPLUSPLUS_API -/** - * Limit the acceptable characters to those specified by a Unicode Set. - * Any previously specified character limit is - * is replaced by the new settings. This includes limits on - * characters that were set with the uspoof_setAllowedLocales() function. - * - * The USPOOF_CHAR_LIMIT test is automatically enabled for this - * USoofChecker by this function. - * - * @param sc The USpoofChecker - * @param chars A Unicode Set containing the list of - * characters that are permitted. Ownership of the set - * remains with the caller. The incoming set is cloned by - * this function, so there are no restrictions on modifying - * or deleting the UnicodeSet after calling this function. - * @param status The error code, set if this function encounters a problem. - * @stable ICU 4.2 - */ -U_STABLE void U_EXPORT2 -uspoof_setAllowedUnicodeSet(USpoofChecker *sc, const icu::UnicodeSet *chars, UErrorCode *status); - - -/** - * Get a UnicodeSet for the characters permitted in an identifier. - * This corresponds to the limits imposed by the Set Allowed Characters / - * UnicodeSet functions. Limitations imposed by other checks will not be - * reflected in the set returned by this function. - * - * The returned set will be frozen, meaning that it cannot be modified - * by the caller. - * - * Ownership of the returned set remains with the Spoof Detector. The - * returned set will become invalid if the spoof detector is closed, - * or if a new set of allowed characters is specified. - * - * - * @param sc The USpoofChecker - * @param status The error code, set if this function encounters a problem. - * @return A UnicodeSet containing the characters that are permitted by - * the USPOOF_CHAR_LIMIT test. - * @stable ICU 4.2 - */ -U_STABLE const icu::UnicodeSet * U_EXPORT2 -uspoof_getAllowedUnicodeSet(const USpoofChecker *sc, UErrorCode *status); -#endif - - -/** - * Check the specified string for possible security issues. - * The text to be checked will typically be an identifier of some sort. - * The set of checks to be performed is specified with uspoof_setChecks(). - * - * \note - * Consider using the newer API, {@link uspoof_check2}, instead. - * The newer API exposes additional information from the check procedure - * and is otherwise identical to this method. - * - * @param sc The USpoofChecker - * @param id The identifier to be checked for possible security issues, - * in UTF-16 format. - * @param length the length of the string to be checked, expressed in - * 16 bit UTF-16 code units, or -1 if the string is - * zero terminated. - * @param position Deprecated in ICU 51. Always returns zero. - * Originally, an out parameter for the index of the first - * string position that failed a check. - * This parameter may be NULL. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * Spoofing or security issues detected with the input string are - * not reported here, but through the function's return value. - * @return An integer value with bits set for any potential security - * or spoofing issues detected. The bits are defined by - * enum USpoofChecks. (returned_value & USPOOF_ALL_CHECKS) - * will be zero if the input string passes all of the - * enabled checks. - * @see uspoof_check2 - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -uspoof_check(const USpoofChecker *sc, - const UChar *id, int32_t length, - int32_t *position, - UErrorCode *status); - - -/** - * Check the specified string for possible security issues. - * The text to be checked will typically be an identifier of some sort. - * The set of checks to be performed is specified with uspoof_setChecks(). - * - * \note - * Consider using the newer API, {@link uspoof_check2UTF8}, instead. - * The newer API exposes additional information from the check procedure - * and is otherwise identical to this method. - * - * @param sc The USpoofChecker - * @param id A identifier to be checked for possible security issues, in UTF8 format. - * @param length the length of the string to be checked, or -1 if the string is - * zero terminated. - * @param position Deprecated in ICU 51. Always returns zero. - * Originally, an out parameter for the index of the first - * string position that failed a check. - * This parameter may be NULL. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * Spoofing or security issues detected with the input string are - * not reported here, but through the function's return value. - * If the input contains invalid UTF-8 sequences, - * a status of U_INVALID_CHAR_FOUND will be returned. - * @return An integer value with bits set for any potential security - * or spoofing issues detected. The bits are defined by - * enum USpoofChecks. (returned_value & USPOOF_ALL_CHECKS) - * will be zero if the input string passes all of the - * enabled checks. - * @see uspoof_check2UTF8 - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -uspoof_checkUTF8(const USpoofChecker *sc, - const char *id, int32_t length, - int32_t *position, - UErrorCode *status); - - -#if U_SHOW_CPLUSPLUS_API -/** - * Check the specified string for possible security issues. - * The text to be checked will typically be an identifier of some sort. - * The set of checks to be performed is specified with uspoof_setChecks(). - * - * \note - * Consider using the newer API, {@link uspoof_check2UnicodeString}, instead. - * The newer API exposes additional information from the check procedure - * and is otherwise identical to this method. - * - * @param sc The USpoofChecker - * @param id A identifier to be checked for possible security issues. - * @param position Deprecated in ICU 51. Always returns zero. - * Originally, an out parameter for the index of the first - * string position that failed a check. - * This parameter may be NULL. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * Spoofing or security issues detected with the input string are - * not reported here, but through the function's return value. - * @return An integer value with bits set for any potential security - * or spoofing issues detected. The bits are defined by - * enum USpoofChecks. (returned_value & USPOOF_ALL_CHECKS) - * will be zero if the input string passes all of the - * enabled checks. - * @see uspoof_check2UnicodeString - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -uspoof_checkUnicodeString(const USpoofChecker *sc, - const icu::UnicodeString &id, - int32_t *position, - UErrorCode *status); -#endif - - -#ifndef U_HIDE_DRAFT_API -/** - * Check the specified string for possible security issues. - * The text to be checked will typically be an identifier of some sort. - * The set of checks to be performed is specified with uspoof_setChecks(). - * - * @param sc The USpoofChecker - * @param id The identifier to be checked for possible security issues, - * in UTF-16 format. - * @param length the length of the string to be checked, or -1 if the string is - * zero terminated. - * @param checkResult An instance of USpoofCheckResult to be filled with - * details about the identifier. Can be NULL. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * Spoofing or security issues detected with the input string are - * not reported here, but through the function's return value. - * @return An integer value with bits set for any potential security - * or spoofing issues detected. The bits are defined by - * enum USpoofChecks. (returned_value & USPOOF_ALL_CHECKS) - * will be zero if the input string passes all of the - * enabled checks. Any information in this bitmask will be - * consistent with the information saved in the optional - * checkResult parameter. - * @see uspoof_openCheckResult - * @see uspoof_check2UTF8 - * @see uspoof_check2UnicodeString - * @draft ICU 58 - */ -U_DRAFT int32_t U_EXPORT2 -uspoof_check2(const USpoofChecker *sc, - const UChar* id, int32_t length, - USpoofCheckResult* checkResult, - UErrorCode *status); - -/** - * Check the specified string for possible security issues. - * The text to be checked will typically be an identifier of some sort. - * The set of checks to be performed is specified with uspoof_setChecks(). - * - * This version of {@link uspoof_check} accepts a USpoofCheckResult, which - * returns additional information about the identifier. For more - * information, see {@link uspoof_openCheckResult}. - * - * @param sc The USpoofChecker - * @param id A identifier to be checked for possible security issues, in UTF8 format. - * @param length the length of the string to be checked, or -1 if the string is - * zero terminated. - * @param checkResult An instance of USpoofCheckResult to be filled with - * details about the identifier. Can be NULL. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * Spoofing or security issues detected with the input string are - * not reported here, but through the function's return value. - * @return An integer value with bits set for any potential security - * or spoofing issues detected. The bits are defined by - * enum USpoofChecks. (returned_value & USPOOF_ALL_CHECKS) - * will be zero if the input string passes all of the - * enabled checks. Any information in this bitmask will be - * consistent with the information saved in the optional - * checkResult parameter. - * @see uspoof_openCheckResult - * @see uspoof_check2 - * @see uspoof_check2UnicodeString - * @draft ICU 58 - */ -U_DRAFT int32_t U_EXPORT2 -uspoof_check2UTF8(const USpoofChecker *sc, - const char *id, int32_t length, - USpoofCheckResult* checkResult, - UErrorCode *status); - -#if U_SHOW_CPLUSPLUS_API -/** - * Check the specified string for possible security issues. - * The text to be checked will typically be an identifier of some sort. - * The set of checks to be performed is specified with uspoof_setChecks(). - * - * @param sc The USpoofChecker - * @param id A identifier to be checked for possible security issues. - * @param checkResult An instance of USpoofCheckResult to be filled with - * details about the identifier. Can be NULL. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * Spoofing or security issues detected with the input string are - * not reported here, but through the function's return value. - * @return An integer value with bits set for any potential security - * or spoofing issues detected. The bits are defined by - * enum USpoofChecks. (returned_value & USPOOF_ALL_CHECKS) - * will be zero if the input string passes all of the - * enabled checks. Any information in this bitmask will be - * consistent with the information saved in the optional - * checkResult parameter. - * @see uspoof_openCheckResult - * @see uspoof_check2 - * @see uspoof_check2UTF8 - * @draft ICU 58 - */ -U_DRAFT int32_t U_EXPORT2 -uspoof_check2UnicodeString(const USpoofChecker *sc, - const icu::UnicodeString &id, - USpoofCheckResult* checkResult, - UErrorCode *status); -#endif - -/** - * Create a USpoofCheckResult, used by the {@link uspoof_check2} class of functions to return - * information about the identifier. Information includes: - *
    - *
  • A bitmask of the checks that failed
  • - *
  • The identifier's restriction level (UTS 39 section 5.2)
  • - *
  • The set of numerics in the string (UTS 39 section 5.3)
  • - *
- * The data held in a USpoofCheckResult is cleared whenever it is passed into a new call - * of {@link uspoof_check2}. - * - * @param status The error code, set if this function encounters a problem. - * @return the newly created USpoofCheckResult - * @see uspoof_check2 - * @see uspoof_check2UTF8 - * @see uspoof_check2UnicodeString - * @draft ICU 58 - */ -U_DRAFT USpoofCheckResult* U_EXPORT2 -uspoof_openCheckResult(UErrorCode *status); - -/** - * Close a USpoofCheckResult, freeing any memory that was being held by - * its implementation. - * - * @param checkResult The instance of USpoofCheckResult to close - * @draft ICU 58 - */ -U_DRAFT void U_EXPORT2 -uspoof_closeCheckResult(USpoofCheckResult *checkResult); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUSpoofCheckResultPointer - * "Smart pointer" class, closes a USpoofCheckResult via {@link uspoof_closeCheckResult}. - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @draft ICU 58 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUSpoofCheckResultPointer, USpoofCheckResult, uspoof_closeCheckResult); - -U_NAMESPACE_END - -#endif - -/** - * Indicates which of the spoof check(s) have failed. The value is a bitwise OR of the constants for the tests - * in question: USPOOF_RESTRICTION_LEVEL, USPOOF_CHAR_LIMIT, and so on. - * - * @param checkResult The instance of USpoofCheckResult created by {@link uspoof_openCheckResult} - * @param status The error code, set if an error occurred. - * @return An integer value with bits set for any potential security - * or spoofing issues detected. The bits are defined by - * enum USpoofChecks. (returned_value & USPOOF_ALL_CHECKS) - * will be zero if the input string passes all of the - * enabled checks. - * @see uspoof_setChecks - * @draft ICU 58 - */ -U_DRAFT int32_t U_EXPORT2 -uspoof_getCheckResultChecks(const USpoofCheckResult *checkResult, UErrorCode *status); - -/** - * Gets the restriction level that the text meets, if the USPOOF_RESTRICTION_LEVEL check - * was enabled; otherwise, undefined. - * - * @param checkResult The instance of USpoofCheckResult created by {@link uspoof_openCheckResult} - * @param status The error code, set if an error occurred. - * @return The restriction level contained in the USpoofCheckResult - * @see uspoof_setRestrictionLevel - * @draft ICU 58 - */ -U_DRAFT URestrictionLevel U_EXPORT2 -uspoof_getCheckResultRestrictionLevel(const USpoofCheckResult *checkResult, UErrorCode *status); - -/** - * Gets the set of numerics found in the string, if the USPOOF_MIXED_NUMBERS check was enabled; - * otherwise, undefined. The set will contain the zero digit from each decimal number system found - * in the input string. Ownership of the returned USet remains with the USpoofCheckResult. - * The USet will be free'd when {@link uspoof_closeCheckResult} is called. - * - * @param checkResult The instance of USpoofCheckResult created by {@link uspoof_openCheckResult} - * @return The set of numerics contained in the USpoofCheckResult - * @param status The error code, set if an error occurred. - * @draft ICU 58 - */ -U_DRAFT const USet* U_EXPORT2 -uspoof_getCheckResultNumerics(const USpoofCheckResult *checkResult, UErrorCode *status); -#endif /* U_HIDE_DRAFT_API */ - - -/** - * Check the whether two specified strings are visually confusable. - * - * If the strings are confusable, the return value will be nonzero, as long as - * {@link USPOOF_CONFUSABLE} was enabled in uspoof_setChecks(). - * - * The bits in the return value correspond to flags for each of the classes of - * confusables applicable to the two input strings. According to UTS 39 - * section 4, the possible flags are: - * - *
    - *
  • {@link USPOOF_SINGLE_SCRIPT_CONFUSABLE}
  • - *
  • {@link USPOOF_MIXED_SCRIPT_CONFUSABLE}
  • - *
  • {@link USPOOF_WHOLE_SCRIPT_CONFUSABLE}
  • - *
- * - * If one or more of the above flags were not listed in uspoof_setChecks(), this - * function will never report that class of confusable. The check - * {@link USPOOF_CONFUSABLE} enables all three flags. - * - * - * @param sc The USpoofChecker - * @param id1 The first of the two identifiers to be compared for - * confusability. The strings are in UTF-16 format. - * @param length1 the length of the first identifer, expressed in - * 16 bit UTF-16 code units, or -1 if the string is - * nul terminated. - * @param id2 The second of the two identifiers to be compared for - * confusability. The identifiers are in UTF-16 format. - * @param length2 The length of the second identifiers, expressed in - * 16 bit UTF-16 code units, or -1 if the string is - * nul terminated. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * Confusability of the identifiers is not reported here, - * but through this function's return value. - * @return An integer value with bit(s) set corresponding to - * the type of confusability found, as defined by - * enum USpoofChecks. Zero is returned if the identifiers - * are not confusable. - * - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -uspoof_areConfusable(const USpoofChecker *sc, - const UChar *id1, int32_t length1, - const UChar *id2, int32_t length2, - UErrorCode *status); - - - -/** - * A version of {@link uspoof_areConfusable} accepting strings in UTF-8 format. - * - * @param sc The USpoofChecker - * @param id1 The first of the two identifiers to be compared for - * confusability. The strings are in UTF-8 format. - * @param length1 the length of the first identifiers, in bytes, or -1 - * if the string is nul terminated. - * @param id2 The second of the two identifiers to be compared for - * confusability. The strings are in UTF-8 format. - * @param length2 The length of the second string in bytes, or -1 - * if the string is nul terminated. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * Confusability of the strings is not reported here, - * but through this function's return value. - * @return An integer value with bit(s) set corresponding to - * the type of confusability found, as defined by - * enum USpoofChecks. Zero is returned if the strings - * are not confusable. - * - * @stable ICU 4.2 - * - * @see uspoof_areConfusable - */ -U_STABLE int32_t U_EXPORT2 -uspoof_areConfusableUTF8(const USpoofChecker *sc, - const char *id1, int32_t length1, - const char *id2, int32_t length2, - UErrorCode *status); - - - - -#if U_SHOW_CPLUSPLUS_API -/** - * A version of {@link uspoof_areConfusable} accepting UnicodeStrings. - * - * @param sc The USpoofChecker - * @param s1 The first of the two identifiers to be compared for - * confusability. The strings are in UTF-8 format. - * @param s2 The second of the two identifiers to be compared for - * confusability. The strings are in UTF-8 format. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * Confusability of the identifiers is not reported here, - * but through this function's return value. - * @return An integer value with bit(s) set corresponding to - * the type of confusability found, as defined by - * enum USpoofChecks. Zero is returned if the identifiers - * are not confusable. - * - * @stable ICU 4.2 - * - * @see uspoof_areConfusable - */ -U_STABLE int32_t U_EXPORT2 -uspoof_areConfusableUnicodeString(const USpoofChecker *sc, - const icu::UnicodeString &s1, - const icu::UnicodeString &s2, - UErrorCode *status); -#endif - - -/** - * Get the "skeleton" for an identifier. - * Skeletons are a transformation of the input identifier; - * Two identifiers are confusable if their skeletons are identical. - * See Unicode UAX #39 for additional information. - * - * Using skeletons directly makes it possible to quickly check - * whether an identifier is confusable with any of some large - * set of existing identifiers, by creating an efficiently - * searchable collection of the skeletons. - * - * @param sc The USpoofChecker - * @param type Deprecated in ICU 58. You may pass any number. - * Originally, controlled which of the Unicode confusable data - * tables to use. - * @param id The input identifier whose skeleton will be computed. - * @param length The length of the input identifier, expressed in 16 bit - * UTF-16 code units, or -1 if the string is zero terminated. - * @param dest The output buffer, to receive the skeleton string. - * @param destCapacity The length of the output buffer, in 16 bit units. - * The destCapacity may be zero, in which case the function will - * return the actual length of the skeleton. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * @return The length of the skeleton string. The returned length - * is always that of the complete skeleton, even when the - * supplied buffer is too small (or of zero length) - * - * @stable ICU 4.2 - * @see uspoof_areConfusable - */ -U_STABLE int32_t U_EXPORT2 -uspoof_getSkeleton(const USpoofChecker *sc, - uint32_t type, - const UChar *id, int32_t length, - UChar *dest, int32_t destCapacity, - UErrorCode *status); - -/** - * Get the "skeleton" for an identifier. - * Skeletons are a transformation of the input identifier; - * Two identifiers are confusable if their skeletons are identical. - * See Unicode UAX #39 for additional information. - * - * Using skeletons directly makes it possible to quickly check - * whether an identifier is confusable with any of some large - * set of existing identifiers, by creating an efficiently - * searchable collection of the skeletons. - * - * @param sc The USpoofChecker - * @param type Deprecated in ICU 58. You may pass any number. - * Originally, controlled which of the Unicode confusable data - * tables to use. - * @param id The UTF-8 format identifier whose skeleton will be computed. - * @param length The length of the input string, in bytes, - * or -1 if the string is zero terminated. - * @param dest The output buffer, to receive the skeleton string. - * @param destCapacity The length of the output buffer, in bytes. - * The destCapacity may be zero, in which case the function will - * return the actual length of the skeleton. - * @param status The error code, set if an error occurred while attempting to - * perform the check. Possible Errors include U_INVALID_CHAR_FOUND - * for invalid UTF-8 sequences, and - * U_BUFFER_OVERFLOW_ERROR if the destination buffer is too small - * to hold the complete skeleton. - * @return The length of the skeleton string, in bytes. The returned length - * is always that of the complete skeleton, even when the - * supplied buffer is too small (or of zero length) - * - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -uspoof_getSkeletonUTF8(const USpoofChecker *sc, - uint32_t type, - const char *id, int32_t length, - char *dest, int32_t destCapacity, - UErrorCode *status); - -#if U_SHOW_CPLUSPLUS_API -/** - * Get the "skeleton" for an identifier. - * Skeletons are a transformation of the input identifier; - * Two identifiers are confusable if their skeletons are identical. - * See Unicode UAX #39 for additional information. - * - * Using skeletons directly makes it possible to quickly check - * whether an identifier is confusable with any of some large - * set of existing identifiers, by creating an efficiently - * searchable collection of the skeletons. - * - * @param sc The USpoofChecker. - * @param type Deprecated in ICU 58. You may pass any number. - * Originally, controlled which of the Unicode confusable data - * tables to use. - * @param id The input identifier whose skeleton will be computed. - * @param dest The output identifier, to receive the skeleton string. - * @param status The error code, set if an error occurred while attempting to - * perform the check. - * @return A reference to the destination (skeleton) string. - * - * @stable ICU 4.2 - */ -U_I18N_API icu::UnicodeString & U_EXPORT2 -uspoof_getSkeletonUnicodeString(const USpoofChecker *sc, - uint32_t type, - const icu::UnicodeString &id, - icu::UnicodeString &dest, - UErrorCode *status); -#endif /* U_SHOW_CPLUSPLUS_API */ - -/** - * Get the set of Candidate Characters for Inclusion in Identifiers, as defined - * in http://unicode.org/Public/security/latest/xidmodifications.txt - * and documented in http://www.unicode.org/reports/tr39/, Unicode Security Mechanisms. - * - * The returned set is frozen. Ownership of the set remains with the ICU library; it must not - * be deleted by the caller. - * - * @param status The error code, set if a problem occurs while creating the set. - * - * @stable ICU 51 - */ -U_STABLE const USet * U_EXPORT2 -uspoof_getInclusionSet(UErrorCode *status); - -/** - * Get the set of characters from Recommended Scripts for Inclusion in Identifiers, as defined - * in http://unicode.org/Public/security/latest/xidmodifications.txt - * and documented in http://www.unicode.org/reports/tr39/, Unicode Security Mechanisms. - * - * The returned set is frozen. Ownership of the set remains with the ICU library; it must not - * be deleted by the caller. - * - * @param status The error code, set if a problem occurs while creating the set. - * - * @stable ICU 51 - */ -U_STABLE const USet * U_EXPORT2 -uspoof_getRecommendedSet(UErrorCode *status); - -#if U_SHOW_CPLUSPLUS_API - -/** - * Get the set of Candidate Characters for Inclusion in Identifiers, as defined - * in http://unicode.org/Public/security/latest/xidmodifications.txt - * and documented in http://www.unicode.org/reports/tr39/, Unicode Security Mechanisms. - * - * The returned set is frozen. Ownership of the set remains with the ICU library; it must not - * be deleted by the caller. - * - * @param status The error code, set if a problem occurs while creating the set. - * - * @stable ICU 51 - */ -U_STABLE const icu::UnicodeSet * U_EXPORT2 -uspoof_getInclusionUnicodeSet(UErrorCode *status); - -/** - * Get the set of characters from Recommended Scripts for Inclusion in Identifiers, as defined - * in http://unicode.org/Public/security/latest/xidmodifications.txt - * and documented in http://www.unicode.org/reports/tr39/, Unicode Security Mechanisms. - * - * The returned set is frozen. Ownership of the set remains with the ICU library; it must not - * be deleted by the caller. - * - * @param status The error code, set if a problem occurs while creating the set. - * - * @stable ICU 51 - */ -U_STABLE const icu::UnicodeSet * U_EXPORT2 -uspoof_getRecommendedUnicodeSet(UErrorCode *status); - -#endif /* U_SHOW_CPLUSPLUS_API */ - -/** - * Serialize the data for a spoof detector into a chunk of memory. - * The flattened spoof detection tables can later be used to efficiently - * instantiate a new Spoof Detector. - * - * The serialized spoof checker includes only the data compiled from the - * Unicode data tables by uspoof_openFromSource(); it does not include - * include any other state or configuration that may have been set. - * - * @param sc the Spoof Detector whose data is to be serialized. - * @param data a pointer to 32-bit-aligned memory to be filled with the data, - * can be NULL if capacity==0 - * @param capacity the number of bytes available at data, - * or 0 for preflighting - * @param status an in/out ICU UErrorCode; possible errors include: - * - U_BUFFER_OVERFLOW_ERROR if the data storage block is too small for serialization - * - U_ILLEGAL_ARGUMENT_ERROR the data or capacity parameters are bad - * @return the number of bytes written or needed for the spoof data - * - * @see utrie2_openFromSerialized() - * @stable ICU 4.2 - */ -U_STABLE int32_t U_EXPORT2 -uspoof_serialize(USpoofChecker *sc, - void *data, int32_t capacity, - UErrorCode *status); - - -#endif - -#endif /* USPOOF_H */ diff --git a/win32/include/spidermonkey/unicode/usprep.h b/win32/include/spidermonkey/unicode/usprep.h deleted file mode 100755 index 5bd837e0..00000000 --- a/win32/include/spidermonkey/unicode/usprep.h +++ /dev/null @@ -1,271 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* - ******************************************************************************* - * - * Copyright (C) 2003-2014, International Business Machines - * Corporation and others. All Rights Reserved. - * - ******************************************************************************* - * file name: usprep.h - * encoding: US-ASCII - * tab size: 8 (not used) - * indentation:4 - * - * created on: 2003jul2 - * created by: Ram Viswanadha - */ - -#ifndef __USPREP_H__ -#define __USPREP_H__ - -/** - * \file - * \brief C API: Implements the StringPrep algorithm. - */ - -#include "unicode/utypes.h" -#include "unicode/localpointer.h" - -/** - * - * StringPrep API implements the StingPrep framework as described by RFC 3454. - * StringPrep prepares Unicode strings for use in network protocols. - * Profiles of StingPrep are set of rules and data according to with the - * Unicode Strings are prepared. Each profiles contains tables which describe - * how a code point should be treated. The tables are broadly classied into - *
    - *
  • Unassinged Table: Contains code points that are unassigned - * in the Unicode Version supported by StringPrep. Currently - * RFC 3454 supports Unicode 3.2.
  • - *
  • Prohibited Table: Contains code points that are prohibted from - * the output of the StringPrep processing function.
  • - *
  • Mapping Table: Contains code ponts that are deleted from the output or case mapped.
  • - *
- * - * The procedure for preparing Unicode strings: - *
    - *
  1. Map: For each character in the input, check if it has a mapping - * and, if so, replace it with its mapping.
  2. - *
  3. Normalize: Possibly normalize the result of step 1 using Unicode - * normalization.
  4. - *
  5. Prohibit: Check for any characters that are not allowed in the - * output. If any are found, return an error.
  6. - *
  7. Check bidi: Possibly check for right-to-left characters, and if - * any are found, make sure that the whole string satisfies the - * requirements for bidirectional strings. If the string does not - * satisfy the requirements for bidirectional strings, return an - * error.
  8. - *
- * @author Ram Viswanadha - */ -#if !UCONFIG_NO_IDNA - -#include "unicode/parseerr.h" - -/** - * The StringPrep profile - * @stable ICU 2.8 - */ -typedef struct UStringPrepProfile UStringPrepProfile; - - -/** - * Option to prohibit processing of unassigned code points in the input - * - * @see usprep_prepare - * @stable ICU 2.8 - */ -#define USPREP_DEFAULT 0x0000 - -/** - * Option to allow processing of unassigned code points in the input - * - * @see usprep_prepare - * @stable ICU 2.8 - */ -#define USPREP_ALLOW_UNASSIGNED 0x0001 - -/** - * enums for the standard stringprep profile types - * supported by usprep_openByType. - * @see usprep_openByType - * @stable ICU 4.2 - */ -typedef enum UStringPrepProfileType { - /** - * RFC3491 Nameprep - * @stable ICU 4.2 - */ - USPREP_RFC3491_NAMEPREP, - /** - * RFC3530 nfs4_cs_prep - * @stable ICU 4.2 - */ - USPREP_RFC3530_NFS4_CS_PREP, - /** - * RFC3530 nfs4_cs_prep with case insensitive option - * @stable ICU 4.2 - */ - USPREP_RFC3530_NFS4_CS_PREP_CI, - /** - * RFC3530 nfs4_cis_prep - * @stable ICU 4.2 - */ - USPREP_RFC3530_NFS4_CIS_PREP, - /** - * RFC3530 nfs4_mixed_prep for prefix - * @stable ICU 4.2 - */ - USPREP_RFC3530_NFS4_MIXED_PREP_PREFIX, - /** - * RFC3530 nfs4_mixed_prep for suffix - * @stable ICU 4.2 - */ - USPREP_RFC3530_NFS4_MIXED_PREP_SUFFIX, - /** - * RFC3722 iSCSI - * @stable ICU 4.2 - */ - USPREP_RFC3722_ISCSI, - /** - * RFC3920 XMPP Nodeprep - * @stable ICU 4.2 - */ - USPREP_RFC3920_NODEPREP, - /** - * RFC3920 XMPP Resourceprep - * @stable ICU 4.2 - */ - USPREP_RFC3920_RESOURCEPREP, - /** - * RFC4011 Policy MIB Stringprep - * @stable ICU 4.2 - */ - USPREP_RFC4011_MIB, - /** - * RFC4013 SASLprep - * @stable ICU 4.2 - */ - USPREP_RFC4013_SASLPREP, - /** - * RFC4505 trace - * @stable ICU 4.2 - */ - USPREP_RFC4505_TRACE, - /** - * RFC4518 LDAP - * @stable ICU 4.2 - */ - USPREP_RFC4518_LDAP, - /** - * RFC4518 LDAP for case ignore, numeric and stored prefix - * matching rules - * @stable ICU 4.2 - */ - USPREP_RFC4518_LDAP_CI -} UStringPrepProfileType; - -/** - * Creates a StringPrep profile from the data file. - * - * @param path string containing the full path pointing to the directory - * where the profile reside followed by the package name - * e.g. "/usr/resource/my_app/profiles/mydata" on a Unix system. - * if NULL, ICU default data files will be used. - * @param fileName name of the profile file to be opened - * @param status ICU error code in/out parameter. Must not be NULL. - * Must fulfill U_SUCCESS before the function call. - * @return Pointer to UStringPrepProfile that is opened. Should be closed by - * calling usprep_close() - * @see usprep_close() - * @stable ICU 2.8 - */ -U_STABLE UStringPrepProfile* U_EXPORT2 -usprep_open(const char* path, - const char* fileName, - UErrorCode* status); - -/** - * Creates a StringPrep profile for the specified profile type. - * - * @param type The profile type - * @param status ICU error code in/out parameter. Must not be NULL. - * Must fulfill U_SUCCESS before the function call. - * @return Pointer to UStringPrepProfile that is opened. Should be closed by - * calling usprep_close() - * @see usprep_close() - * @stable ICU 4.2 - */ -U_STABLE UStringPrepProfile* U_EXPORT2 -usprep_openByType(UStringPrepProfileType type, - UErrorCode* status); - -/** - * Closes the profile - * @param profile The profile to close - * @stable ICU 2.8 - */ -U_STABLE void U_EXPORT2 -usprep_close(UStringPrepProfile* profile); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUStringPrepProfilePointer - * "Smart pointer" class, closes a UStringPrepProfile via usprep_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUStringPrepProfilePointer, UStringPrepProfile, usprep_close); - -U_NAMESPACE_END - -#endif - -/** - * Prepare the input buffer for use in applications with the given profile. This operation maps, normalizes(NFKC), - * checks for prohited and BiDi characters in the order defined by RFC 3454 - * depending on the options specified in the profile. - * - * @param prep The profile to use - * @param src Pointer to UChar buffer containing the string to prepare - * @param srcLength Number of characters in the source string - * @param dest Pointer to the destination buffer to receive the output - * @param destCapacity The capacity of destination array - * @param options A bit set of options: - * - * - USPREP_DEFAULT Prohibit processing of unassigned code points in the input - * - * - USPREP_ALLOW_UNASSIGNED Treat the unassigned code points are in the input - * as normal Unicode code points. - * - * @param parseError Pointer to UParseError struct to receive information on position - * of error if an error is encountered. Can be NULL. - * @param status ICU in/out error code parameter. - * U_INVALID_CHAR_FOUND if src contains - * unmatched single surrogates. - * U_INDEX_OUTOFBOUNDS_ERROR if src contains - * too many code points. - * U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough - * @return The number of UChars in the destination buffer - * @stable ICU 2.8 - */ - -U_STABLE int32_t U_EXPORT2 -usprep_prepare( const UStringPrepProfile* prep, - const UChar* src, int32_t srcLength, - UChar* dest, int32_t destCapacity, - int32_t options, - UParseError* parseError, - UErrorCode* status ); - - -#endif /* #if !UCONFIG_NO_IDNA */ - -#endif diff --git a/win32/include/spidermonkey/unicode/ustring.h b/win32/include/spidermonkey/unicode/ustring.h deleted file mode 100755 index e62fef53..00000000 --- a/win32/include/spidermonkey/unicode/ustring.h +++ /dev/null @@ -1,1702 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1998-2014, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* -* File ustring.h -* -* Modification History: -* -* Date Name Description -* 12/07/98 bertrand Creation. -****************************************************************************** -*/ - -#ifndef USTRING_H -#define USTRING_H - -#include "unicode/utypes.h" -#include "unicode/putil.h" -#include "unicode/uiter.h" - -/** - * \def UBRK_TYPEDEF_UBREAK_ITERATOR - * @internal - */ - -#ifndef UBRK_TYPEDEF_UBREAK_ITERATOR -# define UBRK_TYPEDEF_UBREAK_ITERATOR -/** Simple declaration for u_strToTitle() to avoid including unicode/ubrk.h. @stable ICU 2.1*/ - typedef struct UBreakIterator UBreakIterator; -#endif - -/** - * \file - * \brief C API: Unicode string handling functions - * - * These C API functions provide general Unicode string handling. - * - * Some functions are equivalent in name, signature, and behavior to the ANSI C - * functions. (For example, they do not check for bad arguments like NULL string pointers.) - * In some cases, only the thread-safe variant of such a function is implemented here - * (see u_strtok_r()). - * - * Other functions provide more Unicode-specific functionality like locale-specific - * upper/lower-casing and string comparison in code point order. - * - * ICU uses 16-bit Unicode (UTF-16) in the form of arrays of UChar code units. - * UTF-16 encodes each Unicode code point with either one or two UChar code units. - * (This is the default form of Unicode, and a forward-compatible extension of the original, - * fixed-width form that was known as UCS-2. UTF-16 superseded UCS-2 with Unicode 2.0 - * in 1996.) - * - * Some APIs accept a 32-bit UChar32 value for a single code point. - * - * ICU also handles 16-bit Unicode text with unpaired surrogates. - * Such text is not well-formed UTF-16. - * Code-point-related functions treat unpaired surrogates as surrogate code points, - * i.e., as separate units. - * - * Although UTF-16 is a variable-width encoding form (like some legacy multi-byte encodings), - * it is much more efficient even for random access because the code unit values - * for single-unit characters vs. lead units vs. trail units are completely disjoint. - * This means that it is easy to determine character (code point) boundaries from - * random offsets in the string. - * - * Unicode (UTF-16) string processing is optimized for the single-unit case. - * Although it is important to support supplementary characters - * (which use pairs of lead/trail code units called "surrogates"), - * their occurrence is rare. Almost all characters in modern use require only - * a single UChar code unit (i.e., their code point values are <=0xffff). - * - * For more details see the User Guide Strings chapter (http://icu-project.org/userguide/strings.html). - * For a discussion of the handling of unpaired surrogates see also - * Jitterbug 2145 and its icu mailing list proposal on 2002-sep-18. - */ - -/** - * \defgroup ustring_ustrlen String Length - * \ingroup ustring_strlen - */ -/*@{*/ -/** - * Determine the length of an array of UChar. - * - * @param s The array of UChars, NULL (U+0000) terminated. - * @return The number of UChars in chars, minus the terminator. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strlen(const UChar *s); -/*@}*/ - -/** - * Count Unicode code points in the length UChar code units of the string. - * A code point may occupy either one or two UChar code units. - * Counting code points involves reading all code units. - * - * This functions is basically the inverse of the U16_FWD_N() macro (see utf.h). - * - * @param s The input string. - * @param length The number of UChar code units to be checked, or -1 to count all - * code points before the first NUL (U+0000). - * @return The number of code points in the specified code units. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_countChar32(const UChar *s, int32_t length); - -/** - * Check if the string contains more Unicode code points than a certain number. - * This is more efficient than counting all code points in the entire string - * and comparing that number with a threshold. - * This function may not need to scan the string at all if the length is known - * (not -1 for NUL-termination) and falls within a certain range, and - * never needs to count more than 'number+1' code points. - * Logically equivalent to (u_countChar32(s, length)>number). - * A Unicode code point may occupy either one or two UChar code units. - * - * @param s The input string. - * @param length The length of the string, or -1 if it is NUL-terminated. - * @param number The number of code points in the string is compared against - * the 'number' parameter. - * @return Boolean value for whether the string contains more Unicode code points - * than 'number'. Same as (u_countChar32(s, length)>number). - * @stable ICU 2.4 - */ -U_STABLE UBool U_EXPORT2 -u_strHasMoreChar32Than(const UChar *s, int32_t length, int32_t number); - -/** - * Concatenate two ustrings. Appends a copy of src, - * including the null terminator, to dst. The initial copied - * character from src overwrites the null terminator in dst. - * - * @param dst The destination string. - * @param src The source string. - * @return A pointer to dst. - * @stable ICU 2.0 - */ -U_STABLE UChar* U_EXPORT2 -u_strcat(UChar *dst, - const UChar *src); - -/** - * Concatenate two ustrings. - * Appends at most n characters from src to dst. - * Adds a terminating NUL. - * If src is too long, then only n-1 characters will be copied - * before the terminating NUL. - * If n<=0 then dst is not modified. - * - * @param dst The destination string. - * @param src The source string (can be NULL/invalid if n<=0). - * @param n The maximum number of characters to append; no-op if <=0. - * @return A pointer to dst. - * @stable ICU 2.0 - */ -U_STABLE UChar* U_EXPORT2 -u_strncat(UChar *dst, - const UChar *src, - int32_t n); - -/** - * Find the first occurrence of a substring in a string. - * The substring is found at code point boundaries. - * That means that if the substring begins with - * a trail surrogate or ends with a lead surrogate, - * then it is found only if these surrogates stand alone in the text. - * Otherwise, the substring edge units would be matched against - * halves of surrogate pairs. - * - * @param s The string to search (NUL-terminated). - * @param substring The substring to find (NUL-terminated). - * @return A pointer to the first occurrence of substring in s, - * or s itself if the substring is empty, - * or NULL if substring is not in s. - * @stable ICU 2.0 - * - * @see u_strrstr - * @see u_strFindFirst - * @see u_strFindLast - */ -U_STABLE UChar * U_EXPORT2 -u_strstr(const UChar *s, const UChar *substring); - -/** - * Find the first occurrence of a substring in a string. - * The substring is found at code point boundaries. - * That means that if the substring begins with - * a trail surrogate or ends with a lead surrogate, - * then it is found only if these surrogates stand alone in the text. - * Otherwise, the substring edge units would be matched against - * halves of surrogate pairs. - * - * @param s The string to search. - * @param length The length of s (number of UChars), or -1 if it is NUL-terminated. - * @param substring The substring to find (NUL-terminated). - * @param subLength The length of substring (number of UChars), or -1 if it is NUL-terminated. - * @return A pointer to the first occurrence of substring in s, - * or s itself if the substring is empty, - * or NULL if substring is not in s. - * @stable ICU 2.4 - * - * @see u_strstr - * @see u_strFindLast - */ -U_STABLE UChar * U_EXPORT2 -u_strFindFirst(const UChar *s, int32_t length, const UChar *substring, int32_t subLength); - -/** - * Find the first occurrence of a BMP code point in a string. - * A surrogate code point is found only if its match in the text is not - * part of a surrogate pair. - * A NUL character is found at the string terminator. - * - * @param s The string to search (NUL-terminated). - * @param c The BMP code point to find. - * @return A pointer to the first occurrence of c in s - * or NULL if c is not in s. - * @stable ICU 2.0 - * - * @see u_strchr32 - * @see u_memchr - * @see u_strstr - * @see u_strFindFirst - */ -U_STABLE UChar * U_EXPORT2 -u_strchr(const UChar *s, UChar c); - -/** - * Find the first occurrence of a code point in a string. - * A surrogate code point is found only if its match in the text is not - * part of a surrogate pair. - * A NUL character is found at the string terminator. - * - * @param s The string to search (NUL-terminated). - * @param c The code point to find. - * @return A pointer to the first occurrence of c in s - * or NULL if c is not in s. - * @stable ICU 2.0 - * - * @see u_strchr - * @see u_memchr32 - * @see u_strstr - * @see u_strFindFirst - */ -U_STABLE UChar * U_EXPORT2 -u_strchr32(const UChar *s, UChar32 c); - -/** - * Find the last occurrence of a substring in a string. - * The substring is found at code point boundaries. - * That means that if the substring begins with - * a trail surrogate or ends with a lead surrogate, - * then it is found only if these surrogates stand alone in the text. - * Otherwise, the substring edge units would be matched against - * halves of surrogate pairs. - * - * @param s The string to search (NUL-terminated). - * @param substring The substring to find (NUL-terminated). - * @return A pointer to the last occurrence of substring in s, - * or s itself if the substring is empty, - * or NULL if substring is not in s. - * @stable ICU 2.4 - * - * @see u_strstr - * @see u_strFindFirst - * @see u_strFindLast - */ -U_STABLE UChar * U_EXPORT2 -u_strrstr(const UChar *s, const UChar *substring); - -/** - * Find the last occurrence of a substring in a string. - * The substring is found at code point boundaries. - * That means that if the substring begins with - * a trail surrogate or ends with a lead surrogate, - * then it is found only if these surrogates stand alone in the text. - * Otherwise, the substring edge units would be matched against - * halves of surrogate pairs. - * - * @param s The string to search. - * @param length The length of s (number of UChars), or -1 if it is NUL-terminated. - * @param substring The substring to find (NUL-terminated). - * @param subLength The length of substring (number of UChars), or -1 if it is NUL-terminated. - * @return A pointer to the last occurrence of substring in s, - * or s itself if the substring is empty, - * or NULL if substring is not in s. - * @stable ICU 2.4 - * - * @see u_strstr - * @see u_strFindLast - */ -U_STABLE UChar * U_EXPORT2 -u_strFindLast(const UChar *s, int32_t length, const UChar *substring, int32_t subLength); - -/** - * Find the last occurrence of a BMP code point in a string. - * A surrogate code point is found only if its match in the text is not - * part of a surrogate pair. - * A NUL character is found at the string terminator. - * - * @param s The string to search (NUL-terminated). - * @param c The BMP code point to find. - * @return A pointer to the last occurrence of c in s - * or NULL if c is not in s. - * @stable ICU 2.4 - * - * @see u_strrchr32 - * @see u_memrchr - * @see u_strrstr - * @see u_strFindLast - */ -U_STABLE UChar * U_EXPORT2 -u_strrchr(const UChar *s, UChar c); - -/** - * Find the last occurrence of a code point in a string. - * A surrogate code point is found only if its match in the text is not - * part of a surrogate pair. - * A NUL character is found at the string terminator. - * - * @param s The string to search (NUL-terminated). - * @param c The code point to find. - * @return A pointer to the last occurrence of c in s - * or NULL if c is not in s. - * @stable ICU 2.4 - * - * @see u_strrchr - * @see u_memchr32 - * @see u_strrstr - * @see u_strFindLast - */ -U_STABLE UChar * U_EXPORT2 -u_strrchr32(const UChar *s, UChar32 c); - -/** - * Locates the first occurrence in the string string of any of the characters - * in the string matchSet. - * Works just like C's strpbrk but with Unicode. - * - * @param string The string in which to search, NUL-terminated. - * @param matchSet A NUL-terminated string defining a set of code points - * for which to search in the text string. - * @return A pointer to the character in string that matches one of the - * characters in matchSet, or NULL if no such character is found. - * @stable ICU 2.0 - */ -U_STABLE UChar * U_EXPORT2 -u_strpbrk(const UChar *string, const UChar *matchSet); - -/** - * Returns the number of consecutive characters in string, - * beginning with the first, that do not occur somewhere in matchSet. - * Works just like C's strcspn but with Unicode. - * - * @param string The string in which to search, NUL-terminated. - * @param matchSet A NUL-terminated string defining a set of code points - * for which to search in the text string. - * @return The number of initial characters in string that do not - * occur in matchSet. - * @see u_strspn - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strcspn(const UChar *string, const UChar *matchSet); - -/** - * Returns the number of consecutive characters in string, - * beginning with the first, that occur somewhere in matchSet. - * Works just like C's strspn but with Unicode. - * - * @param string The string in which to search, NUL-terminated. - * @param matchSet A NUL-terminated string defining a set of code points - * for which to search in the text string. - * @return The number of initial characters in string that do - * occur in matchSet. - * @see u_strcspn - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strspn(const UChar *string, const UChar *matchSet); - -/** - * The string tokenizer API allows an application to break a string into - * tokens. Unlike strtok(), the saveState (the current pointer within the - * original string) is maintained in saveState. In the first call, the - * argument src is a pointer to the string. In subsequent calls to - * return successive tokens of that string, src must be specified as - * NULL. The value saveState is set by this function to maintain the - * function's position within the string, and on each subsequent call - * you must give this argument the same variable. This function does - * handle surrogate pairs. This function is similar to the strtok_r() - * the POSIX Threads Extension (1003.1c-1995) version. - * - * @param src String containing token(s). This string will be modified. - * After the first call to u_strtok_r(), this argument must - * be NULL to get to the next token. - * @param delim Set of delimiter characters (Unicode code points). - * @param saveState The current pointer within the original string, - * which is set by this function. The saveState - * parameter should the address of a local variable of type - * UChar *. (i.e. defined "Uhar *myLocalSaveState" and use - * &myLocalSaveState for this parameter). - * @return A pointer to the next token found in src, or NULL - * when there are no more tokens. - * @stable ICU 2.0 - */ -U_STABLE UChar * U_EXPORT2 -u_strtok_r(UChar *src, - const UChar *delim, - UChar **saveState); - -/** - * Compare two Unicode strings for bitwise equality (code unit order). - * - * @param s1 A string to compare. - * @param s2 A string to compare. - * @return 0 if s1 and s2 are bitwise equal; a negative - * value if s1 is bitwise less than s2,; a positive - * value if s1 is bitwise greater than s2. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strcmp(const UChar *s1, - const UChar *s2); - -/** - * Compare two Unicode strings in code point order. - * See u_strCompare for details. - * - * @param s1 A string to compare. - * @param s2 A string to compare. - * @return a negative/zero/positive integer corresponding to whether - * the first string is less than/equal to/greater than the second one - * in code point order - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strcmpCodePointOrder(const UChar *s1, const UChar *s2); - -/** - * Compare two Unicode strings (binary order). - * - * The comparison can be done in code unit order or in code point order. - * They differ only in UTF-16 when - * comparing supplementary code points (U+10000..U+10ffff) - * to BMP code points near the end of the BMP (i.e., U+e000..U+ffff). - * In code unit order, high BMP code points sort after supplementary code points - * because they are stored as pairs of surrogates which are at U+d800..U+dfff. - * - * This functions works with strings of different explicitly specified lengths - * unlike the ANSI C-like u_strcmp() and u_memcmp() etc. - * NUL-terminated strings are possible with length arguments of -1. - * - * @param s1 First source string. - * @param length1 Length of first source string, or -1 if NUL-terminated. - * - * @param s2 Second source string. - * @param length2 Length of second source string, or -1 if NUL-terminated. - * - * @param codePointOrder Choose between code unit order (FALSE) - * and code point order (TRUE). - * - * @return <0 or 0 or >0 as usual for string comparisons - * - * @stable ICU 2.2 - */ -U_STABLE int32_t U_EXPORT2 -u_strCompare(const UChar *s1, int32_t length1, - const UChar *s2, int32_t length2, - UBool codePointOrder); - -/** - * Compare two Unicode strings (binary order) - * as presented by UCharIterator objects. - * Works otherwise just like u_strCompare(). - * - * Both iterators are reset to their start positions. - * When the function returns, it is undefined where the iterators - * have stopped. - * - * @param iter1 First source string iterator. - * @param iter2 Second source string iterator. - * @param codePointOrder Choose between code unit order (FALSE) - * and code point order (TRUE). - * - * @return <0 or 0 or >0 as usual for string comparisons - * - * @see u_strCompare - * - * @stable ICU 2.6 - */ -U_STABLE int32_t U_EXPORT2 -u_strCompareIter(UCharIterator *iter1, UCharIterator *iter2, UBool codePointOrder); - -#ifndef U_COMPARE_CODE_POINT_ORDER -/* see also unistr.h and unorm.h */ -/** - * Option bit for u_strCaseCompare, u_strcasecmp, unorm_compare, etc: - * Compare strings in code point order instead of code unit order. - * @stable ICU 2.2 - */ -#define U_COMPARE_CODE_POINT_ORDER 0x8000 -#endif - -/** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to - * u_strCompare(u_strFoldCase(s1, options), - * u_strFoldCase(s2, options), - * (options&U_COMPARE_CODE_POINT_ORDER)!=0). - * - * The comparison can be done in UTF-16 code unit order or in code point order. - * They differ only when comparing supplementary code points (U+10000..U+10ffff) - * to BMP code points near the end of the BMP (i.e., U+e000..U+ffff). - * In code unit order, high BMP code points sort after supplementary code points - * because they are stored as pairs of surrogates which are at U+d800..U+dfff. - * - * This functions works with strings of different explicitly specified lengths - * unlike the ANSI C-like u_strcmp() and u_memcmp() etc. - * NUL-terminated strings are possible with length arguments of -1. - * - * @param s1 First source string. - * @param length1 Length of first source string, or -1 if NUL-terminated. - * - * @param s2 Second source string. - * @param length2 Length of second source string, or -1 if NUL-terminated. - * - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * - * @return <0 or 0 or >0 as usual for string comparisons - * - * @stable ICU 2.2 - */ -U_STABLE int32_t U_EXPORT2 -u_strCaseCompare(const UChar *s1, int32_t length1, - const UChar *s2, int32_t length2, - uint32_t options, - UErrorCode *pErrorCode); - -/** - * Compare two ustrings for bitwise equality. - * Compares at most n characters. - * - * @param ucs1 A string to compare (can be NULL/invalid if n<=0). - * @param ucs2 A string to compare (can be NULL/invalid if n<=0). - * @param n The maximum number of characters to compare; always returns 0 if n<=0. - * @return 0 if s1 and s2 are bitwise equal; a negative - * value if s1 is bitwise less than s2; a positive - * value if s1 is bitwise greater than s2. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strncmp(const UChar *ucs1, - const UChar *ucs2, - int32_t n); - -/** - * Compare two Unicode strings in code point order. - * This is different in UTF-16 from u_strncmp() if supplementary characters are present. - * For details, see u_strCompare(). - * - * @param s1 A string to compare. - * @param s2 A string to compare. - * @param n The maximum number of characters to compare. - * @return a negative/zero/positive integer corresponding to whether - * the first string is less than/equal to/greater than the second one - * in code point order - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strncmpCodePointOrder(const UChar *s1, const UChar *s2, int32_t n); - -/** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to u_strcmp(u_strFoldCase(s1, options), u_strFoldCase(s2, options)). - * - * @param s1 A string to compare. - * @param s2 A string to compare. - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @return A negative, zero, or positive integer indicating the comparison result. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strcasecmp(const UChar *s1, const UChar *s2, uint32_t options); - -/** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to u_strcmp(u_strFoldCase(s1, at most n, options), - * u_strFoldCase(s2, at most n, options)). - * - * @param s1 A string to compare. - * @param s2 A string to compare. - * @param n The maximum number of characters each string to case-fold and then compare. - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @return A negative, zero, or positive integer indicating the comparison result. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strncasecmp(const UChar *s1, const UChar *s2, int32_t n, uint32_t options); - -/** - * Compare two strings case-insensitively using full case folding. - * This is equivalent to u_strcmp(u_strFoldCase(s1, n, options), - * u_strFoldCase(s2, n, options)). - * - * @param s1 A string to compare. - * @param s2 A string to compare. - * @param length The number of characters in each string to case-fold and then compare. - * @param options A bit set of options: - * - U_FOLD_CASE_DEFAULT or 0 is used for default options: - * Comparison in code unit order with default case folding. - * - * - U_COMPARE_CODE_POINT_ORDER - * Set to choose code point order instead of code unit order - * (see u_strCompare for details). - * - * - U_FOLD_CASE_EXCLUDE_SPECIAL_I - * - * @return A negative, zero, or positive integer indicating the comparison result. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_memcasecmp(const UChar *s1, const UChar *s2, int32_t length, uint32_t options); - -/** - * Copy a ustring. Adds a null terminator. - * - * @param dst The destination string. - * @param src The source string. - * @return A pointer to dst. - * @stable ICU 2.0 - */ -U_STABLE UChar* U_EXPORT2 -u_strcpy(UChar *dst, - const UChar *src); - -/** - * Copy a ustring. - * Copies at most n characters. The result will be null terminated - * if the length of src is less than n. - * - * @param dst The destination string. - * @param src The source string (can be NULL/invalid if n<=0). - * @param n The maximum number of characters to copy; no-op if <=0. - * @return A pointer to dst. - * @stable ICU 2.0 - */ -U_STABLE UChar* U_EXPORT2 -u_strncpy(UChar *dst, - const UChar *src, - int32_t n); - -#if !UCONFIG_NO_CONVERSION - -/** - * Copy a byte string encoded in the default codepage to a ustring. - * Adds a null terminator. - * Performs a host byte to UChar conversion - * - * @param dst The destination string. - * @param src The source string. - * @return A pointer to dst. - * @stable ICU 2.0 - */ -U_STABLE UChar* U_EXPORT2 u_uastrcpy(UChar *dst, - const char *src ); - -/** - * Copy a byte string encoded in the default codepage to a ustring. - * Copies at most n characters. The result will be null terminated - * if the length of src is less than n. - * Performs a host byte to UChar conversion - * - * @param dst The destination string. - * @param src The source string. - * @param n The maximum number of characters to copy. - * @return A pointer to dst. - * @stable ICU 2.0 - */ -U_STABLE UChar* U_EXPORT2 u_uastrncpy(UChar *dst, - const char *src, - int32_t n); - -/** - * Copy ustring to a byte string encoded in the default codepage. - * Adds a null terminator. - * Performs a UChar to host byte conversion - * - * @param dst The destination string. - * @param src The source string. - * @return A pointer to dst. - * @stable ICU 2.0 - */ -U_STABLE char* U_EXPORT2 u_austrcpy(char *dst, - const UChar *src ); - -/** - * Copy ustring to a byte string encoded in the default codepage. - * Copies at most n characters. The result will be null terminated - * if the length of src is less than n. - * Performs a UChar to host byte conversion - * - * @param dst The destination string. - * @param src The source string. - * @param n The maximum number of characters to copy. - * @return A pointer to dst. - * @stable ICU 2.0 - */ -U_STABLE char* U_EXPORT2 u_austrncpy(char *dst, - const UChar *src, - int32_t n ); - -#endif - -/** - * Synonym for memcpy(), but with UChars only. - * @param dest The destination string - * @param src The source string (can be NULL/invalid if count<=0) - * @param count The number of characters to copy; no-op if <=0 - * @return A pointer to dest - * @stable ICU 2.0 - */ -U_STABLE UChar* U_EXPORT2 -u_memcpy(UChar *dest, const UChar *src, int32_t count); - -/** - * Synonym for memmove(), but with UChars only. - * @param dest The destination string - * @param src The source string (can be NULL/invalid if count<=0) - * @param count The number of characters to move; no-op if <=0 - * @return A pointer to dest - * @stable ICU 2.0 - */ -U_STABLE UChar* U_EXPORT2 -u_memmove(UChar *dest, const UChar *src, int32_t count); - -/** - * Initialize count characters of dest to c. - * - * @param dest The destination string. - * @param c The character to initialize the string. - * @param count The maximum number of characters to set. - * @return A pointer to dest. - * @stable ICU 2.0 - */ -U_STABLE UChar* U_EXPORT2 -u_memset(UChar *dest, UChar c, int32_t count); - -/** - * Compare the first count UChars of each buffer. - * - * @param buf1 The first string to compare. - * @param buf2 The second string to compare. - * @param count The maximum number of UChars to compare. - * @return When buf1 < buf2, a negative number is returned. - * When buf1 == buf2, 0 is returned. - * When buf1 > buf2, a positive number is returned. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_memcmp(const UChar *buf1, const UChar *buf2, int32_t count); - -/** - * Compare two Unicode strings in code point order. - * This is different in UTF-16 from u_memcmp() if supplementary characters are present. - * For details, see u_strCompare(). - * - * @param s1 A string to compare. - * @param s2 A string to compare. - * @param count The maximum number of characters to compare. - * @return a negative/zero/positive integer corresponding to whether - * the first string is less than/equal to/greater than the second one - * in code point order - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_memcmpCodePointOrder(const UChar *s1, const UChar *s2, int32_t count); - -/** - * Find the first occurrence of a BMP code point in a string. - * A surrogate code point is found only if its match in the text is not - * part of a surrogate pair. - * A NUL character is found at the string terminator. - * - * @param s The string to search (contains count UChars). - * @param c The BMP code point to find. - * @param count The length of the string. - * @return A pointer to the first occurrence of c in s - * or NULL if c is not in s. - * @stable ICU 2.0 - * - * @see u_strchr - * @see u_memchr32 - * @see u_strFindFirst - */ -U_STABLE UChar* U_EXPORT2 -u_memchr(const UChar *s, UChar c, int32_t count); - -/** - * Find the first occurrence of a code point in a string. - * A surrogate code point is found only if its match in the text is not - * part of a surrogate pair. - * A NUL character is found at the string terminator. - * - * @param s The string to search (contains count UChars). - * @param c The code point to find. - * @param count The length of the string. - * @return A pointer to the first occurrence of c in s - * or NULL if c is not in s. - * @stable ICU 2.0 - * - * @see u_strchr32 - * @see u_memchr - * @see u_strFindFirst - */ -U_STABLE UChar* U_EXPORT2 -u_memchr32(const UChar *s, UChar32 c, int32_t count); - -/** - * Find the last occurrence of a BMP code point in a string. - * A surrogate code point is found only if its match in the text is not - * part of a surrogate pair. - * A NUL character is found at the string terminator. - * - * @param s The string to search (contains count UChars). - * @param c The BMP code point to find. - * @param count The length of the string. - * @return A pointer to the last occurrence of c in s - * or NULL if c is not in s. - * @stable ICU 2.4 - * - * @see u_strrchr - * @see u_memrchr32 - * @see u_strFindLast - */ -U_STABLE UChar* U_EXPORT2 -u_memrchr(const UChar *s, UChar c, int32_t count); - -/** - * Find the last occurrence of a code point in a string. - * A surrogate code point is found only if its match in the text is not - * part of a surrogate pair. - * A NUL character is found at the string terminator. - * - * @param s The string to search (contains count UChars). - * @param c The code point to find. - * @param count The length of the string. - * @return A pointer to the last occurrence of c in s - * or NULL if c is not in s. - * @stable ICU 2.4 - * - * @see u_strrchr32 - * @see u_memrchr - * @see u_strFindLast - */ -U_STABLE UChar* U_EXPORT2 -u_memrchr32(const UChar *s, UChar32 c, int32_t count); - -/** - * Unicode String literals in C. - * We need one macro to declare a variable for the string - * and to statically preinitialize it if possible, - * and a second macro to dynamically intialize such a string variable if necessary. - * - * The macros are defined for maximum performance. - * They work only for strings that contain "invariant characters", i.e., - * only latin letters, digits, and some punctuation. - * See utypes.h for details. - * - * A pair of macros for a single string must be used with the same - * parameters. - * The string parameter must be a C string literal. - * The length of the string, not including the terminating - * NUL, must be specified as a constant. - * The U_STRING_DECL macro should be invoked exactly once for one - * such string variable before it is used. - * - * Usage: - *
- *    U_STRING_DECL(ustringVar1, "Quick-Fox 2", 11);
- *    U_STRING_DECL(ustringVar2, "jumps 5%", 8);
- *    static UBool didInit=FALSE;
- * 
- *    int32_t function() {
- *        if(!didInit) {
- *            U_STRING_INIT(ustringVar1, "Quick-Fox 2", 11);
- *            U_STRING_INIT(ustringVar2, "jumps 5%", 8);
- *            didInit=TRUE;
- *        }
- *        return u_strcmp(ustringVar1, ustringVar2);
- *    }
- * 
- * - * Note that the macros will NOT consistently work if their argument is another #define. - * The following will not work on all platforms, don't use it. - * - *
- *     #define GLUCK "Mr. Gluck"
- *     U_STRING_DECL(var, GLUCK, 9)
- *     U_STRING_INIT(var, GLUCK, 9)
- * 
- * - * Instead, use the string literal "Mr. Gluck" as the argument to both macro - * calls. - * - * - * @stable ICU 2.0 - */ -#if defined(U_DECLARE_UTF16) -# define U_STRING_DECL(var, cs, length) static const UChar *var=(const UChar *)U_DECLARE_UTF16(cs) - /**@stable ICU 2.0 */ -# define U_STRING_INIT(var, cs, length) -#elif U_SIZEOF_WCHAR_T==U_SIZEOF_UCHAR && (U_CHARSET_FAMILY==U_ASCII_FAMILY || (U_SIZEOF_UCHAR == 2 && defined(U_WCHAR_IS_UTF16))) -# define U_STRING_DECL(var, cs, length) static const UChar var[(length)+1]=L ## cs - /**@stable ICU 2.0 */ -# define U_STRING_INIT(var, cs, length) -#elif U_SIZEOF_UCHAR==1 && U_CHARSET_FAMILY==U_ASCII_FAMILY -# define U_STRING_DECL(var, cs, length) static const UChar var[(length)+1]=cs - /**@stable ICU 2.0 */ -# define U_STRING_INIT(var, cs, length) -#else -# define U_STRING_DECL(var, cs, length) static UChar var[(length)+1] - /**@stable ICU 2.0 */ -# define U_STRING_INIT(var, cs, length) u_charsToUChars(cs, var, length+1) -#endif - -/** - * Unescape a string of characters and write the resulting - * Unicode characters to the destination buffer. The following escape - * sequences are recognized: - * - * \\uhhhh 4 hex digits; h in [0-9A-Fa-f] - * \\Uhhhhhhhh 8 hex digits - * \\xhh 1-2 hex digits - * \\x{h...} 1-8 hex digits - * \\ooo 1-3 octal digits; o in [0-7] - * \\cX control-X; X is masked with 0x1F - * - * as well as the standard ANSI C escapes: - * - * \\a => U+0007, \\b => U+0008, \\t => U+0009, \\n => U+000A, - * \\v => U+000B, \\f => U+000C, \\r => U+000D, \\e => U+001B, - * \\" => U+0022, \\' => U+0027, \\? => U+003F, \\\\ => U+005C - * - * Anything else following a backslash is generically escaped. For - * example, "[a\\-z]" returns "[a-z]". - * - * If an escape sequence is ill-formed, this method returns an empty - * string. An example of an ill-formed sequence is "\\u" followed by - * fewer than 4 hex digits. - * - * The above characters are recognized in the compiler's codepage, - * that is, they are coded as 'u', '\\', etc. Characters that are - * not parts of escape sequences are converted using u_charsToUChars(). - * - * This function is similar to UnicodeString::unescape() but not - * identical to it. The latter takes a source UnicodeString, so it - * does escape recognition but no conversion. - * - * @param src a zero-terminated string of invariant characters - * @param dest pointer to buffer to receive converted and unescaped - * text and, if there is room, a zero terminator. May be NULL for - * preflighting, in which case no UChars will be written, but the - * return value will still be valid. On error, an empty string is - * stored here (if possible). - * @param destCapacity the number of UChars that may be written at - * dest. Ignored if dest == NULL. - * @return the length of unescaped string. - * @see u_unescapeAt - * @see UnicodeString#unescape() - * @see UnicodeString#unescapeAt() - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_unescape(const char *src, - UChar *dest, int32_t destCapacity); - -U_CDECL_BEGIN -/** - * Callback function for u_unescapeAt() that returns a character of - * the source text given an offset and a context pointer. The context - * pointer will be whatever is passed into u_unescapeAt(). - * - * @param offset pointer to the offset that will be passed to u_unescapeAt(). - * @param context an opaque pointer passed directly into u_unescapeAt() - * @return the character represented by the escape sequence at - * offset - * @see u_unescapeAt - * @stable ICU 2.0 - */ -typedef UChar (U_CALLCONV *UNESCAPE_CHAR_AT)(int32_t offset, void *context); -U_CDECL_END - -/** - * Unescape a single sequence. The character at offset-1 is assumed - * (without checking) to be a backslash. This method takes a callback - * pointer to a function that returns the UChar at a given offset. By - * varying this callback, ICU functions are able to unescape char* - * strings, UnicodeString objects, and UFILE pointers. - * - * If offset is out of range, or if the escape sequence is ill-formed, - * (UChar32)0xFFFFFFFF is returned. See documentation of u_unescape() - * for a list of recognized sequences. - * - * @param charAt callback function that returns a UChar of the source - * text given an offset and a context pointer. - * @param offset pointer to the offset that will be passed to charAt. - * The offset value will be updated upon return to point after the - * last parsed character of the escape sequence. On error the offset - * is unchanged. - * @param length the number of characters in the source text. The - * last character of the source text is considered to be at offset - * length-1. - * @param context an opaque pointer passed directly into charAt. - * @return the character represented by the escape sequence at - * offset, or (UChar32)0xFFFFFFFF on error. - * @see u_unescape() - * @see UnicodeString#unescape() - * @see UnicodeString#unescapeAt() - * @stable ICU 2.0 - */ -U_STABLE UChar32 U_EXPORT2 -u_unescapeAt(UNESCAPE_CHAR_AT charAt, - int32_t *offset, - int32_t length, - void *context); - -/** - * Uppercase the characters in a string. - * Casing is locale-dependent and context-sensitive. - * The result may be longer or shorter than the original. - * The source string and the destination buffer are allowed to overlap. - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the result - * without writing any of the result string. - * @param src The original string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param locale The locale to consider, or "" for the root locale or NULL for the default locale. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The length of the result string. It may be greater than destCapacity. In that case, - * only some of the result was written to the destination buffer. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strToUpper(UChar *dest, int32_t destCapacity, - const UChar *src, int32_t srcLength, - const char *locale, - UErrorCode *pErrorCode); - -/** - * Lowercase the characters in a string. - * Casing is locale-dependent and context-sensitive. - * The result may be longer or shorter than the original. - * The source string and the destination buffer are allowed to overlap. - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the result - * without writing any of the result string. - * @param src The original string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param locale The locale to consider, or "" for the root locale or NULL for the default locale. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The length of the result string. It may be greater than destCapacity. In that case, - * only some of the result was written to the destination buffer. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strToLower(UChar *dest, int32_t destCapacity, - const UChar *src, int32_t srcLength, - const char *locale, - UErrorCode *pErrorCode); - -#if !UCONFIG_NO_BREAK_ITERATION - -/** - * Titlecase a string. - * Casing is locale-dependent and context-sensitive. - * Titlecasing uses a break iterator to find the first characters of words - * that are to be titlecased. It titlecases those characters and lowercases - * all others. - * - * The titlecase break iterator can be provided to customize for arbitrary - * styles, using rules and dictionaries beyond the standard iterators. - * It may be more efficient to always provide an iterator to avoid - * opening and closing one for each string. - * The standard titlecase iterator for the root locale implements the - * algorithm of Unicode TR 21. - * - * This function uses only the setText(), first() and next() methods of the - * provided break iterator. - * - * The result may be longer or shorter than the original. - * The source string and the destination buffer are allowed to overlap. - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the result - * without writing any of the result string. - * @param src The original string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param titleIter A break iterator to find the first characters of words - * that are to be titlecased. - * If none is provided (NULL), then a standard titlecase - * break iterator is opened. - * @param locale The locale to consider, or "" for the root locale or NULL for the default locale. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The length of the result string. It may be greater than destCapacity. In that case, - * only some of the result was written to the destination buffer. - * @stable ICU 2.1 - */ -U_STABLE int32_t U_EXPORT2 -u_strToTitle(UChar *dest, int32_t destCapacity, - const UChar *src, int32_t srcLength, - UBreakIterator *titleIter, - const char *locale, - UErrorCode *pErrorCode); - -#endif - -/** - * Case-folds the characters in a string. - * - * Case-folding is locale-independent and not context-sensitive, - * but there is an option for whether to include or exclude mappings for dotted I - * and dotless i that are marked with 'T' in CaseFolding.txt. - * - * The result may be longer or shorter than the original. - * The source string and the destination buffer are allowed to overlap. - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the result - * without writing any of the result string. - * @param src The original string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param options Either U_FOLD_CASE_DEFAULT or U_FOLD_CASE_EXCLUDE_SPECIAL_I - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The length of the result string. It may be greater than destCapacity. In that case, - * only some of the result was written to the destination buffer. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -u_strFoldCase(UChar *dest, int32_t destCapacity, - const UChar *src, int32_t srcLength, - uint32_t options, - UErrorCode *pErrorCode); - -#if defined(U_WCHAR_IS_UTF16) || defined(U_WCHAR_IS_UTF32) || !UCONFIG_NO_CONVERSION -/** - * Convert a UTF-16 string to a wchar_t string. - * If it is known at compile time that wchar_t strings are in UTF-16 or UTF-32, then - * this function simply calls the fast, dedicated function for that. - * Otherwise, two conversions UTF-16 -> default charset -> wchar_t* are performed. - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of wchar_t's). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param pDestLength A pointer to receive the number of units written to the destination. If - * pDestLength!=NULL then *pDestLength is always set to the - * number of output units corresponding to the transformation of - * all the input units, even in case of a buffer overflow. - * @param src The original source string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The pointer to destination buffer. - * @stable ICU 2.0 - */ -U_STABLE wchar_t* U_EXPORT2 -u_strToWCS(wchar_t *dest, - int32_t destCapacity, - int32_t *pDestLength, - const UChar *src, - int32_t srcLength, - UErrorCode *pErrorCode); -/** - * Convert a wchar_t string to UTF-16. - * If it is known at compile time that wchar_t strings are in UTF-16 or UTF-32, then - * this function simply calls the fast, dedicated function for that. - * Otherwise, two conversions wchar_t* -> default charset -> UTF-16 are performed. - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param pDestLength A pointer to receive the number of units written to the destination. If - * pDestLength!=NULL then *pDestLength is always set to the - * number of output units corresponding to the transformation of - * all the input units, even in case of a buffer overflow. - * @param src The original source string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The pointer to destination buffer. - * @stable ICU 2.0 - */ -U_STABLE UChar* U_EXPORT2 -u_strFromWCS(UChar *dest, - int32_t destCapacity, - int32_t *pDestLength, - const wchar_t *src, - int32_t srcLength, - UErrorCode *pErrorCode); -#endif /* defined(U_WCHAR_IS_UTF16) || defined(U_WCHAR_IS_UTF32) || !UCONFIG_NO_CONVERSION */ - -/** - * Convert a UTF-16 string to UTF-8. - * If the input string is not well-formed, then the U_INVALID_CHAR_FOUND error code is set. - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of chars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param pDestLength A pointer to receive the number of units written to the destination. If - * pDestLength!=NULL then *pDestLength is always set to the - * number of output units corresponding to the transformation of - * all the input units, even in case of a buffer overflow. - * @param src The original source string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The pointer to destination buffer. - * @stable ICU 2.0 - * @see u_strToUTF8WithSub - * @see u_strFromUTF8 - */ -U_STABLE char* U_EXPORT2 -u_strToUTF8(char *dest, - int32_t destCapacity, - int32_t *pDestLength, - const UChar *src, - int32_t srcLength, - UErrorCode *pErrorCode); - -/** - * Convert a UTF-8 string to UTF-16. - * If the input string is not well-formed, then the U_INVALID_CHAR_FOUND error code is set. - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param pDestLength A pointer to receive the number of units written to the destination. If - * pDestLength!=NULL then *pDestLength is always set to the - * number of output units corresponding to the transformation of - * all the input units, even in case of a buffer overflow. - * @param src The original source string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param pErrorCode Must be a valid pointer to an error code value, - * which must not indicate a failure before the function call. - * @return The pointer to destination buffer. - * @stable ICU 2.0 - * @see u_strFromUTF8WithSub - * @see u_strFromUTF8Lenient - */ -U_STABLE UChar* U_EXPORT2 -u_strFromUTF8(UChar *dest, - int32_t destCapacity, - int32_t *pDestLength, - const char *src, - int32_t srcLength, - UErrorCode *pErrorCode); - -/** - * Convert a UTF-16 string to UTF-8. - * - * Same as u_strToUTF8() except for the additional subchar which is output for - * illegal input sequences, instead of stopping with the U_INVALID_CHAR_FOUND error code. - * With subchar==U_SENTINEL, this function behaves exactly like u_strToUTF8(). - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of chars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param pDestLength A pointer to receive the number of units written to the destination. If - * pDestLength!=NULL then *pDestLength is always set to the - * number of output units corresponding to the transformation of - * all the input units, even in case of a buffer overflow. - * @param src The original source string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param subchar The substitution character to use in place of an illegal input sequence, - * or U_SENTINEL if the function is to return with U_INVALID_CHAR_FOUND instead. - * A substitution character can be any valid Unicode code point (up to U+10FFFF) - * except for surrogate code points (U+D800..U+DFFF). - * The recommended value is U+FFFD "REPLACEMENT CHARACTER". - * @param pNumSubstitutions Output parameter receiving the number of substitutions if subchar>=0. - * Set to 0 if no substitutions occur or subchar<0. - * pNumSubstitutions can be NULL. - * @param pErrorCode Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The pointer to destination buffer. - * @see u_strToUTF8 - * @see u_strFromUTF8WithSub - * @stable ICU 3.6 - */ -U_STABLE char* U_EXPORT2 -u_strToUTF8WithSub(char *dest, - int32_t destCapacity, - int32_t *pDestLength, - const UChar *src, - int32_t srcLength, - UChar32 subchar, int32_t *pNumSubstitutions, - UErrorCode *pErrorCode); - -/** - * Convert a UTF-8 string to UTF-16. - * - * Same as u_strFromUTF8() except for the additional subchar which is output for - * illegal input sequences, instead of stopping with the U_INVALID_CHAR_FOUND error code. - * With subchar==U_SENTINEL, this function behaves exactly like u_strFromUTF8(). - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param pDestLength A pointer to receive the number of units written to the destination. If - * pDestLength!=NULL then *pDestLength is always set to the - * number of output units corresponding to the transformation of - * all the input units, even in case of a buffer overflow. - * @param src The original source string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param subchar The substitution character to use in place of an illegal input sequence, - * or U_SENTINEL if the function is to return with U_INVALID_CHAR_FOUND instead. - * A substitution character can be any valid Unicode code point (up to U+10FFFF) - * except for surrogate code points (U+D800..U+DFFF). - * The recommended value is U+FFFD "REPLACEMENT CHARACTER". - * @param pNumSubstitutions Output parameter receiving the number of substitutions if subchar>=0. - * Set to 0 if no substitutions occur or subchar<0. - * pNumSubstitutions can be NULL. - * @param pErrorCode Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The pointer to destination buffer. - * @see u_strFromUTF8 - * @see u_strFromUTF8Lenient - * @see u_strToUTF8WithSub - * @stable ICU 3.6 - */ -U_STABLE UChar* U_EXPORT2 -u_strFromUTF8WithSub(UChar *dest, - int32_t destCapacity, - int32_t *pDestLength, - const char *src, - int32_t srcLength, - UChar32 subchar, int32_t *pNumSubstitutions, - UErrorCode *pErrorCode); - -/** - * Convert a UTF-8 string to UTF-16. - * - * Same as u_strFromUTF8() except that this function is designed to be very fast, - * which it achieves by being lenient about malformed UTF-8 sequences. - * This function is intended for use in environments where UTF-8 text is - * expected to be well-formed. - * - * Its semantics are: - * - Well-formed UTF-8 text is correctly converted to well-formed UTF-16 text. - * - The function will not read beyond the input string, nor write beyond - * the destCapacity. - * - Malformed UTF-8 results in "garbage" 16-bit Unicode strings which may not - * be well-formed UTF-16. - * The function will resynchronize to valid code point boundaries - * within a small number of code points after an illegal sequence. - * - Non-shortest forms are not detected and will result in "spoofing" output. - * - * For further performance improvement, if srcLength is given (>=0), - * then it must be destCapacity>=srcLength. - * - * There is no inverse u_strToUTF8Lenient() function because there is practically - * no performance gain from not checking that a UTF-16 string is well-formed. - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * Unlike for other ICU functions, if srcLength>=0 then it - * must be destCapacity>=srcLength. - * @param pDestLength A pointer to receive the number of units written to the destination. If - * pDestLength!=NULL then *pDestLength is always set to the - * number of output units corresponding to the transformation of - * all the input units, even in case of a buffer overflow. - * Unlike for other ICU functions, if srcLength>=0 but - * destCapacity=0. - * Set to 0 if no substitutions occur or subchar<0. - * pNumSubstitutions can be NULL. - * @param pErrorCode Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The pointer to destination buffer. - * @see u_strToUTF32 - * @see u_strFromUTF32WithSub - * @stable ICU 4.2 - */ -U_STABLE UChar32* U_EXPORT2 -u_strToUTF32WithSub(UChar32 *dest, - int32_t destCapacity, - int32_t *pDestLength, - const UChar *src, - int32_t srcLength, - UChar32 subchar, int32_t *pNumSubstitutions, - UErrorCode *pErrorCode); - -/** - * Convert a UTF-32 string to UTF-16. - * - * Same as u_strFromUTF32() except for the additional subchar which is output for - * illegal input sequences, instead of stopping with the U_INVALID_CHAR_FOUND error code. - * With subchar==U_SENTINEL, this function behaves exactly like u_strFromUTF32(). - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param pDestLength A pointer to receive the number of units written to the destination. If - * pDestLength!=NULL then *pDestLength is always set to the - * number of output units corresponding to the transformation of - * all the input units, even in case of a buffer overflow. - * @param src The original source string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param subchar The substitution character to use in place of an illegal input sequence, - * or U_SENTINEL if the function is to return with U_INVALID_CHAR_FOUND instead. - * A substitution character can be any valid Unicode code point (up to U+10FFFF) - * except for surrogate code points (U+D800..U+DFFF). - * The recommended value is U+FFFD "REPLACEMENT CHARACTER". - * @param pNumSubstitutions Output parameter receiving the number of substitutions if subchar>=0. - * Set to 0 if no substitutions occur or subchar<0. - * pNumSubstitutions can be NULL. - * @param pErrorCode Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The pointer to destination buffer. - * @see u_strFromUTF32 - * @see u_strToUTF32WithSub - * @stable ICU 4.2 - */ -U_STABLE UChar* U_EXPORT2 -u_strFromUTF32WithSub(UChar *dest, - int32_t destCapacity, - int32_t *pDestLength, - const UChar32 *src, - int32_t srcLength, - UChar32 subchar, int32_t *pNumSubstitutions, - UErrorCode *pErrorCode); - -/** - * Convert a 16-bit Unicode string to Java Modified UTF-8. - * See http://java.sun.com/javase/6/docs/api/java/io/DataInput.html#modified-utf-8 - * - * This function behaves according to the documentation for Java DataOutput.writeUTF() - * except that it does not encode the output length in the destination buffer - * and does not have an output length restriction. - * See http://java.sun.com/javase/6/docs/api/java/io/DataOutput.html#writeUTF(java.lang.String) - * - * The input string need not be well-formed UTF-16. - * (Therefore there is no subchar parameter.) - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of chars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param pDestLength A pointer to receive the number of units written to the destination. If - * pDestLength!=NULL then *pDestLength is always set to the - * number of output units corresponding to the transformation of - * all the input units, even in case of a buffer overflow. - * @param src The original source string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param pErrorCode Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The pointer to destination buffer. - * @stable ICU 4.4 - * @see u_strToUTF8WithSub - * @see u_strFromJavaModifiedUTF8WithSub - */ -U_STABLE char* U_EXPORT2 -u_strToJavaModifiedUTF8( - char *dest, - int32_t destCapacity, - int32_t *pDestLength, - const UChar *src, - int32_t srcLength, - UErrorCode *pErrorCode); - -/** - * Convert a Java Modified UTF-8 string to a 16-bit Unicode string. - * If the input string is not well-formed and no substitution char is specified, - * then the U_INVALID_CHAR_FOUND error code is set. - * - * This function behaves according to the documentation for Java DataInput.readUTF() - * except that it takes a length parameter rather than - * interpreting the first two input bytes as the length. - * See http://java.sun.com/javase/6/docs/api/java/io/DataInput.html#readUTF() - * - * The output string may not be well-formed UTF-16. - * - * @param dest A buffer for the result string. The result will be zero-terminated if - * the buffer is large enough. - * @param destCapacity The size of the buffer (number of UChars). If it is 0, then - * dest may be NULL and the function will only return the length of the - * result without writing any of the result string (pre-flighting). - * @param pDestLength A pointer to receive the number of units written to the destination. If - * pDestLength!=NULL then *pDestLength is always set to the - * number of output units corresponding to the transformation of - * all the input units, even in case of a buffer overflow. - * @param src The original source string - * @param srcLength The length of the original string. If -1, then src must be zero-terminated. - * @param subchar The substitution character to use in place of an illegal input sequence, - * or U_SENTINEL if the function is to return with U_INVALID_CHAR_FOUND instead. - * A substitution character can be any valid Unicode code point (up to U+10FFFF) - * except for surrogate code points (U+D800..U+DFFF). - * The recommended value is U+FFFD "REPLACEMENT CHARACTER". - * @param pNumSubstitutions Output parameter receiving the number of substitutions if subchar>=0. - * Set to 0 if no substitutions occur or subchar<0. - * pNumSubstitutions can be NULL. - * @param pErrorCode Pointer to a standard ICU error code. Its input value must - * pass the U_SUCCESS() test, or else the function returns - * immediately. Check for U_FAILURE() on output or use with - * function chaining. (See User Guide for details.) - * @return The pointer to destination buffer. - * @see u_strFromUTF8WithSub - * @see u_strFromUTF8Lenient - * @see u_strToJavaModifiedUTF8 - * @stable ICU 4.4 - */ -U_STABLE UChar* U_EXPORT2 -u_strFromJavaModifiedUTF8WithSub( - UChar *dest, - int32_t destCapacity, - int32_t *pDestLength, - const char *src, - int32_t srcLength, - UChar32 subchar, int32_t *pNumSubstitutions, - UErrorCode *pErrorCode); - -#endif diff --git a/win32/include/spidermonkey/unicode/ustringtrie.h b/win32/include/spidermonkey/unicode/ustringtrie.h deleted file mode 100755 index 50d31ba2..00000000 --- a/win32/include/spidermonkey/unicode/ustringtrie.h +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2010-2012, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* file name: udicttrie.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2010dec17 -* created by: Markus W. Scherer -*/ - -#ifndef __USTRINGTRIE_H__ -#define __USTRINGTRIE_H__ - -/** - * \file - * \brief C API: Helper definitions for dictionary trie APIs. - */ - -#include "unicode/utypes.h" - - -/** - * Return values for BytesTrie::next(), UCharsTrie::next() and similar methods. - * @see USTRINGTRIE_MATCHES - * @see USTRINGTRIE_HAS_VALUE - * @see USTRINGTRIE_HAS_NEXT - * @stable ICU 4.8 - */ -enum UStringTrieResult { - /** - * The input unit(s) did not continue a matching string. - * Once current()/next() return USTRINGTRIE_NO_MATCH, - * all further calls to current()/next() will also return USTRINGTRIE_NO_MATCH, - * until the trie is reset to its original state or to a saved state. - * @stable ICU 4.8 - */ - USTRINGTRIE_NO_MATCH, - /** - * The input unit(s) continued a matching string - * but there is no value for the string so far. - * (It is a prefix of a longer string.) - * @stable ICU 4.8 - */ - USTRINGTRIE_NO_VALUE, - /** - * The input unit(s) continued a matching string - * and there is a value for the string so far. - * This value will be returned by getValue(). - * No further input byte/unit can continue a matching string. - * @stable ICU 4.8 - */ - USTRINGTRIE_FINAL_VALUE, - /** - * The input unit(s) continued a matching string - * and there is a value for the string so far. - * This value will be returned by getValue(). - * Another input byte/unit can continue a matching string. - * @stable ICU 4.8 - */ - USTRINGTRIE_INTERMEDIATE_VALUE -}; - -/** - * Same as (result!=USTRINGTRIE_NO_MATCH). - * @param result A result from BytesTrie::first(), UCharsTrie::next() etc. - * @return true if the input bytes/units so far are part of a matching string/byte sequence. - * @stable ICU 4.8 - */ -#define USTRINGTRIE_MATCHES(result) ((result)!=USTRINGTRIE_NO_MATCH) - -/** - * Equivalent to (result==USTRINGTRIE_INTERMEDIATE_VALUE || result==USTRINGTRIE_FINAL_VALUE) but - * this macro evaluates result exactly once. - * @param result A result from BytesTrie::first(), UCharsTrie::next() etc. - * @return true if there is a value for the input bytes/units so far. - * @see BytesTrie::getValue - * @see UCharsTrie::getValue - * @stable ICU 4.8 - */ -#define USTRINGTRIE_HAS_VALUE(result) ((result)>=USTRINGTRIE_FINAL_VALUE) - -/** - * Equivalent to (result==USTRINGTRIE_NO_VALUE || result==USTRINGTRIE_INTERMEDIATE_VALUE) but - * this macro evaluates result exactly once. - * @param result A result from BytesTrie::first(), UCharsTrie::next() etc. - * @return true if another input byte/unit can continue a matching string. - * @stable ICU 4.8 - */ -#define USTRINGTRIE_HAS_NEXT(result) ((result)&1) - -#endif /* __USTRINGTRIE_H__ */ diff --git a/win32/include/spidermonkey/unicode/utext.h b/win32/include/spidermonkey/unicode/utext.h deleted file mode 100755 index fd119956..00000000 --- a/win32/include/spidermonkey/unicode/utext.h +++ /dev/null @@ -1,1602 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2004-2012, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: utext.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2004oct06 -* created by: Markus W. Scherer -*/ - -#ifndef __UTEXT_H__ -#define __UTEXT_H__ - -/** - * \file - * \brief C API: Abstract Unicode Text API - * - * The Text Access API provides a means to allow text that is stored in alternative - * formats to work with ICU services. ICU normally operates on text that is - * stored in UTF-16 format, in (UChar *) arrays for the C APIs or as type - * UnicodeString for C++ APIs. - * - * ICU Text Access allows other formats, such as UTF-8 or non-contiguous - * UTF-16 strings, to be placed in a UText wrapper and then passed to ICU services. - * - * There are three general classes of usage for UText: - * - * Application Level Use. This is the simplest usage - applications would - * use one of the utext_open() functions on their input text, and pass - * the resulting UText to the desired ICU service. - * - * Second is usage in ICU Services, such as break iteration, that will need to - * operate on input presented to them as a UText. These implementations - * will need to use the iteration and related UText functions to gain - * access to the actual text. - * - * The third class of UText users are "text providers." These are the - * UText implementations for the various text storage formats. An application - * or system with a unique text storage format can implement a set of - * UText provider functions for that format, which will then allow - * ICU services to operate on that format. - * - * - * Iterating over text - * - * Here is sample code for a forward iteration over the contents of a UText - * - * \code - * UChar32 c; - * UText *ut = whatever(); - * - * for (c=utext_next32From(ut, 0); c>=0; c=utext_next32(ut)) { - * // do whatever with the codepoint c here. - * } - * \endcode - * - * And here is similar code to iterate in the reverse direction, from the end - * of the text towards the beginning. - * - * \code - * UChar32 c; - * UText *ut = whatever(); - * int textLength = utext_nativeLength(ut); - * for (c=utext_previous32From(ut, textLength); c>=0; c=utext_previous32(ut)) { - * // do whatever with the codepoint c here. - * } - * \endcode - * - * Characters and Indexing - * - * Indexing into text by UText functions is nearly always in terms of the native - * indexing of the underlying text storage. The storage format could be UTF-8 - * or UTF-32, for example. When coding to the UText access API, no assumptions - * can be made regarding the size of characters, or how far an index - * may move when iterating between characters. - * - * All indices supplied to UText functions are pinned to the length of the - * text. An out-of-bounds index is not considered to be an error, but is - * adjusted to be in the range 0 <= index <= length of input text. - * - * - * When an index position is returned from a UText function, it will be - * a native index to the underlying text. In the case of multi-unit characters, - * it will always refer to the first position of the character, - * never to the interior. This is essentially the same thing as saying that - * a returned index will always point to a boundary between characters. - * - * When a native index is supplied to a UText function, all indices that - * refer to any part of a multi-unit character representation are considered - * to be equivalent. In the case of multi-unit characters, an incoming index - * will be logically normalized to refer to the start of the character. - * - * It is possible to test whether a native index is on a code point boundary - * by doing a utext_setNativeIndex() followed by a utext_getNativeIndex(). - * If the index is returned unchanged, it was on a code point boundary. If - * an adjusted index is returned, the original index referred to the - * interior of a character. - * - * Conventions for calling UText functions - * - * Most UText access functions have as their first parameter a (UText *) pointer, - * which specifies the UText to be used. Unless otherwise noted, the - * pointer must refer to a valid, open UText. Attempting to - * use a closed UText or passing a NULL pointer is a programming error and - * will produce undefined results or NULL pointer exceptions. - * - * The UText_Open family of functions can either open an existing (closed) - * UText, or heap allocate a new UText. Here is sample code for creating - * a stack-allocated UText. - * - * \code - * char *s = whatever(); // A utf-8 string - * U_ErrorCode status = U_ZERO_ERROR; - * UText ut = UTEXT_INITIALIZER; - * utext_openUTF8(ut, s, -1, &status); - * if (U_FAILURE(status)) { - * // error handling - * } else { - * // work with the UText - * } - * \endcode - * - * Any existing UText passed to an open function _must_ have been initialized, - * either by the UTEXT_INITIALIZER, or by having been originally heap-allocated - * by an open function. Passing NULL will cause the open function to - * heap-allocate and fully initialize a new UText. - * - */ - - - -#include "unicode/utypes.h" -#include "unicode/uchar.h" -#if U_SHOW_CPLUSPLUS_API -#include "unicode/localpointer.h" -#include "unicode/rep.h" -#include "unicode/unistr.h" -#include "unicode/chariter.h" -#endif - - -U_CDECL_BEGIN - -struct UText; -typedef struct UText UText; /**< C typedef for struct UText. @stable ICU 3.6 */ - - -/*************************************************************************************** - * - * C Functions for creating UText wrappers around various kinds of text strings. - * - ****************************************************************************************/ - - -/** - * Close function for UText instances. - * Cleans up, releases any resources being held by an open UText. - *

- * If the UText was originally allocated by one of the utext_open functions, - * the storage associated with the utext will also be freed. - * If the UText storage originated with the application, as it would with - * a local or static instance, the storage will not be deleted. - * - * An open UText can be reset to refer to new string by using one of the utext_open() - * functions without first closing the UText. - * - * @param ut The UText to be closed. - * @return NULL if the UText struct was deleted by the close. If the UText struct - * was originally provided by the caller to the open function, it is - * returned by this function, and may be safely used again in - * a subsequent utext_open. - * - * @stable ICU 3.4 - */ -U_STABLE UText * U_EXPORT2 -utext_close(UText *ut); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUTextPointer - * "Smart pointer" class, closes a UText via utext_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUTextPointer, UText, utext_close); - -U_NAMESPACE_END - -#endif - -/** - * Open a read-only UText implementation for UTF-8 strings. - * - * \htmlonly - * Any invalid UTF-8 in the input will be handled in this way: - * a sequence of bytes that has the form of a truncated, but otherwise valid, - * UTF-8 sequence will be replaced by a single unicode replacement character, \uFFFD. - * Any other illegal bytes will each be replaced by a \uFFFD. - * \endhtmlonly - * - * @param ut Pointer to a UText struct. If NULL, a new UText will be created. - * If non-NULL, must refer to an initialized UText struct, which will then - * be reset to reference the specified UTF-8 string. - * @param s A UTF-8 string. Must not be NULL. - * @param length The length of the UTF-8 string in bytes, or -1 if the string is - * zero terminated. - * @param status Errors are returned here. - * @return A pointer to the UText. If a pre-allocated UText was provided, it - * will always be used and returned. - * @stable ICU 3.4 - */ -U_STABLE UText * U_EXPORT2 -utext_openUTF8(UText *ut, const char *s, int64_t length, UErrorCode *status); - - -/** - * Open a read-only UText for UChar * string. - * - * @param ut Pointer to a UText struct. If NULL, a new UText will be created. - * If non-NULL, must refer to an initialized UText struct, which will then - * be reset to reference the specified UChar string. - * @param s A UChar (UTF-16) string - * @param length The number of UChars in the input string, or -1 if the string is - * zero terminated. - * @param status Errors are returned here. - * @return A pointer to the UText. If a pre-allocated UText was provided, it - * will always be used and returned. - * @stable ICU 3.4 - */ -U_STABLE UText * U_EXPORT2 -utext_openUChars(UText *ut, const UChar *s, int64_t length, UErrorCode *status); - - -#if U_SHOW_CPLUSPLUS_API -/** - * Open a writable UText for a non-const UnicodeString. - * - * @param ut Pointer to a UText struct. If NULL, a new UText will be created. - * If non-NULL, must refer to an initialized UText struct, which will then - * be reset to reference the specified input string. - * @param s A UnicodeString. - * @param status Errors are returned here. - * @return Pointer to the UText. If a UText was supplied as input, this - * will always be used and returned. - * @stable ICU 3.4 - */ -U_STABLE UText * U_EXPORT2 -utext_openUnicodeString(UText *ut, icu::UnicodeString *s, UErrorCode *status); - - -/** - * Open a UText for a const UnicodeString. The resulting UText will not be writable. - * - * @param ut Pointer to a UText struct. If NULL, a new UText will be created. - * If non-NULL, must refer to an initialized UText struct, which will then - * be reset to reference the specified input string. - * @param s A const UnicodeString to be wrapped. - * @param status Errors are returned here. - * @return Pointer to the UText. If a UText was supplied as input, this - * will always be used and returned. - * @stable ICU 3.4 - */ -U_STABLE UText * U_EXPORT2 -utext_openConstUnicodeString(UText *ut, const icu::UnicodeString *s, UErrorCode *status); - - -/** - * Open a writable UText implementation for an ICU Replaceable object. - * @param ut Pointer to a UText struct. If NULL, a new UText will be created. - * If non-NULL, must refer to an already existing UText, which will then - * be reset to reference the specified replaceable text. - * @param rep A Replaceable text object. - * @param status Errors are returned here. - * @return Pointer to the UText. If a UText was supplied as input, this - * will always be used and returned. - * @see Replaceable - * @stable ICU 3.4 - */ -U_STABLE UText * U_EXPORT2 -utext_openReplaceable(UText *ut, icu::Replaceable *rep, UErrorCode *status); - -/** - * Open a UText implementation over an ICU CharacterIterator. - * @param ut Pointer to a UText struct. If NULL, a new UText will be created. - * If non-NULL, must refer to an already existing UText, which will then - * be reset to reference the specified replaceable text. - * @param ci A Character Iterator. - * @param status Errors are returned here. - * @return Pointer to the UText. If a UText was supplied as input, this - * will always be used and returned. - * @see Replaceable - * @stable ICU 3.4 - */ -U_STABLE UText * U_EXPORT2 -utext_openCharacterIterator(UText *ut, icu::CharacterIterator *ci, UErrorCode *status); - -#endif - - -/** - * Clone a UText. This is much like opening a UText where the source text is itself - * another UText. - * - * A deep clone will copy both the UText data structures and the underlying text. - * The original and cloned UText will operate completely independently; modifications - * made to the text in one will not affect the other. Text providers are not - * required to support deep clones. The user of clone() must check the status return - * and be prepared to handle failures. - * - * The standard UText implementations for UTF8, UChar *, UnicodeString and - * Replaceable all support deep cloning. - * - * The UText returned from a deep clone will be writable, assuming that the text - * provider is able to support writing, even if the source UText had been made - * non-writable by means of UText_freeze(). - * - * A shallow clone replicates only the UText data structures; it does not make - * a copy of the underlying text. Shallow clones can be used as an efficient way to - * have multiple iterators active in a single text string that is not being - * modified. - * - * A shallow clone operation will not fail, barring truly exceptional conditions such - * as memory allocation failures. - * - * Shallow UText clones should be avoided if the UText functions that modify the - * text are expected to be used, either on the original or the cloned UText. - * Any such modifications can cause unpredictable behavior. Read Only - * shallow clones provide some protection against errors of this type by - * disabling text modification via the cloned UText. - * - * A shallow clone made with the readOnly parameter == FALSE will preserve the - * utext_isWritable() state of the source object. Note, however, that - * write operations must be avoided while more than one UText exists that refer - * to the same underlying text. - * - * A UText and its clone may be safely concurrently accessed by separate threads. - * This is true for read access only with shallow clones, and for both read and - * write access with deep clones. - * It is the responsibility of the Text Provider to ensure that this thread safety - * constraint is met. - * - * @param dest A UText struct to be filled in with the result of the clone operation, - * or NULL if the clone function should heap-allocate a new UText struct. - * If non-NULL, must refer to an already existing UText, which will then - * be reset to become the clone. - * @param src The UText to be cloned. - * @param deep TRUE to request a deep clone, FALSE for a shallow clone. - * @param readOnly TRUE to request that the cloned UText have read only access to the - * underlying text. - - * @param status Errors are returned here. For deep clones, U_UNSUPPORTED_ERROR - * will be returned if the text provider is unable to clone the - * original text. - * @return The newly created clone, or NULL if the clone operation failed. - * @stable ICU 3.4 - */ -U_STABLE UText * U_EXPORT2 -utext_clone(UText *dest, const UText *src, UBool deep, UBool readOnly, UErrorCode *status); - - -/** - * Compare two UText objects for equality. - * UTexts are equal if they are iterating over the same text, and - * have the same iteration position within the text. - * If either or both of the parameters are NULL, the comparison is FALSE. - * - * @param a The first of the two UTexts to compare. - * @param b The other UText to be compared. - * @return TRUE if the two UTexts are equal. - * @stable ICU 3.6 - */ -U_STABLE UBool U_EXPORT2 -utext_equals(const UText *a, const UText *b); - - -/***************************************************************************** - * - * Functions to work with the text represeted by a UText wrapper - * - *****************************************************************************/ - -/** - * Get the length of the text. Depending on the characteristics - * of the underlying text representation, this may be expensive. - * @see utext_isLengthExpensive() - * - * - * @param ut the text to be accessed. - * @return the length of the text, expressed in native units. - * - * @stable ICU 3.4 - */ -U_STABLE int64_t U_EXPORT2 -utext_nativeLength(UText *ut); - -/** - * Return TRUE if calculating the length of the text could be expensive. - * Finding the length of NUL terminated strings is considered to be expensive. - * - * Note that the value of this function may change - * as the result of other operations on a UText. - * Once the length of a string has been discovered, it will no longer - * be expensive to report it. - * - * @param ut the text to be accessed. - * @return TRUE if determining the length of the text could be time consuming. - * @stable ICU 3.4 - */ -U_STABLE UBool U_EXPORT2 -utext_isLengthExpensive(const UText *ut); - -/** - * Returns the code point at the requested index, - * or U_SENTINEL (-1) if it is out of bounds. - * - * If the specified index points to the interior of a multi-unit - * character - one of the trail bytes of a UTF-8 sequence, for example - - * the complete code point will be returned. - * - * The iteration position will be set to the start of the returned code point. - * - * This function is roughly equivalent to the the sequence - * utext_setNativeIndex(index); - * utext_current32(); - * (There is a subtle difference if the index is out of bounds by being less than zero - - * utext_setNativeIndex(negative value) sets the index to zero, after which utext_current() - * will return the char at zero. utext_char32At(negative index), on the other hand, will - * return the U_SENTINEL value of -1.) - * - * @param ut the text to be accessed - * @param nativeIndex the native index of the character to be accessed. If the index points - * to other than the first unit of a multi-unit character, it will be adjusted - * to the start of the character. - * @return the code point at the specified index. - * @stable ICU 3.4 - */ -U_STABLE UChar32 U_EXPORT2 -utext_char32At(UText *ut, int64_t nativeIndex); - - -/** - * - * Get the code point at the current iteration position, - * or U_SENTINEL (-1) if the iteration has reached the end of - * the input text. - * - * @param ut the text to be accessed. - * @return the Unicode code point at the current iterator position. - * @stable ICU 3.4 - */ -U_STABLE UChar32 U_EXPORT2 -utext_current32(UText *ut); - - -/** - * Get the code point at the current iteration position of the UText, and - * advance the position to the first index following the character. - * - * If the position is at the end of the text (the index following - * the last character, which is also the length of the text), - * return U_SENTINEL (-1) and do not advance the index. - * - * This is a post-increment operation. - * - * An inline macro version of this function, UTEXT_NEXT32(), - * is available for performance critical use. - * - * @param ut the text to be accessed. - * @return the Unicode code point at the iteration position. - * @see UTEXT_NEXT32 - * @stable ICU 3.4 - */ -U_STABLE UChar32 U_EXPORT2 -utext_next32(UText *ut); - - -/** - * Move the iterator position to the character (code point) whose - * index precedes the current position, and return that character. - * This is a pre-decrement operation. - * - * If the initial position is at the start of the text (index of 0) - * return U_SENTINEL (-1), and leave the position unchanged. - * - * An inline macro version of this function, UTEXT_PREVIOUS32(), - * is available for performance critical use. - * - * @param ut the text to be accessed. - * @return the previous UChar32 code point, or U_SENTINEL (-1) - * if the iteration has reached the start of the text. - * @see UTEXT_PREVIOUS32 - * @stable ICU 3.4 - */ -U_STABLE UChar32 U_EXPORT2 -utext_previous32(UText *ut); - - -/** - * Set the iteration index and return the code point at that index. - * Leave the iteration index at the start of the following code point. - * - * This function is the most efficient and convenient way to - * begin a forward iteration. The results are identical to the those - * from the sequence - * \code - * utext_setIndex(); - * utext_next32(); - * \endcode - * - * @param ut the text to be accessed. - * @param nativeIndex Iteration index, in the native units of the text provider. - * @return Code point which starts at or before index, - * or U_SENTINEL (-1) if it is out of bounds. - * @stable ICU 3.4 - */ -U_STABLE UChar32 U_EXPORT2 -utext_next32From(UText *ut, int64_t nativeIndex); - - - -/** - * Set the iteration index, and return the code point preceding the - * one specified by the initial index. Leave the iteration position - * at the start of the returned code point. - * - * This function is the most efficient and convenient way to - * begin a backwards iteration. - * - * @param ut the text to be accessed. - * @param nativeIndex Iteration index in the native units of the text provider. - * @return Code point preceding the one at the initial index, - * or U_SENTINEL (-1) if it is out of bounds. - * - * @stable ICU 3.4 - */ -U_STABLE UChar32 U_EXPORT2 -utext_previous32From(UText *ut, int64_t nativeIndex); - -/** - * Get the current iterator position, which can range from 0 to - * the length of the text. - * The position is a native index into the input text, in whatever format it - * may have (possibly UTF-8 for example), and may not always be the same as - * the corresponding UChar (UTF-16) index. - * The returned position will always be aligned to a code point boundary. - * - * @param ut the text to be accessed. - * @return the current index position, in the native units of the text provider. - * @stable ICU 3.4 - */ -U_STABLE int64_t U_EXPORT2 -utext_getNativeIndex(const UText *ut); - -/** - * Set the current iteration position to the nearest code point - * boundary at or preceding the specified index. - * The index is in the native units of the original input text. - * If the index is out of range, it will be pinned to be within - * the range of the input text. - *

- * It will usually be more efficient to begin an iteration - * using the functions utext_next32From() or utext_previous32From() - * rather than setIndex(). - *

- * Moving the index position to an adjacent character is best done - * with utext_next32(), utext_previous32() or utext_moveIndex32(). - * Attempting to do direct arithmetic on the index position is - * complicated by the fact that the size (in native units) of a - * character depends on the underlying representation of the character - * (UTF-8, UTF-16, UTF-32, arbitrary codepage), and is not - * easily knowable. - * - * @param ut the text to be accessed. - * @param nativeIndex the native unit index of the new iteration position. - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -utext_setNativeIndex(UText *ut, int64_t nativeIndex); - -/** - * Move the iterator postion by delta code points. The number of code points - * is a signed number; a negative delta will move the iterator backwards, - * towards the start of the text. - *

- * The index is moved by delta code points - * forward or backward, but no further backward than to 0 and - * no further forward than to utext_nativeLength(). - * The resulting index value will be in between 0 and length, inclusive. - * - * @param ut the text to be accessed. - * @param delta the signed number of code points to move the iteration position. - * @return TRUE if the position could be moved the requested number of positions while - * staying within the range [0 - text length]. - * @stable ICU 3.4 - */ -U_STABLE UBool U_EXPORT2 -utext_moveIndex32(UText *ut, int32_t delta); - -/** - * Get the native index of the character preceeding the current position. - * If the iteration position is already at the start of the text, zero - * is returned. - * The value returned is the same as that obtained from the following sequence, - * but without the side effect of changing the iteration position. - * - * \code - * UText *ut = whatever; - * ... - * utext_previous(ut) - * utext_getNativeIndex(ut); - * \endcode - * - * This function is most useful during forwards iteration, where it will get the - * native index of the character most recently returned from utext_next(). - * - * @param ut the text to be accessed - * @return the native index of the character preceeding the current index position, - * or zero if the current position is at the start of the text. - * @stable ICU 3.6 - */ -U_STABLE int64_t U_EXPORT2 -utext_getPreviousNativeIndex(UText *ut); - - -/** - * - * Extract text from a UText into a UChar buffer. The range of text to be extracted - * is specified in the native indices of the UText provider. These may not necessarily - * be UTF-16 indices. - *

- * The size (number of 16 bit UChars) of the data to be extracted is returned. The - * full number of UChars is returned, even when the extracted text is truncated - * because the specified buffer size is too small. - *

- * The extracted string will (if you are a user) / must (if you are a text provider) - * be NUL-terminated if there is sufficient space in the destination buffer. This - * terminating NUL is not included in the returned length. - *

- * The iteration index is left at the position following the last extracted character. - * - * @param ut the UText from which to extract data. - * @param nativeStart the native index of the first character to extract.\ - * If the specified index is out of range, - * it will be pinned to to be within 0 <= index <= textLength - * @param nativeLimit the native string index of the position following the last - * character to extract. If the specified index is out of range, - * it will be pinned to to be within 0 <= index <= textLength. - * nativeLimit must be >= nativeStart. - * @param dest the UChar (UTF-16) buffer into which the extracted text is placed - * @param destCapacity The size, in UChars, of the destination buffer. May be zero - * for precomputing the required size. - * @param status receives any error status. - * U_BUFFER_OVERFLOW_ERROR: the extracted text was truncated because the - * buffer was too small. Returns number of UChars for preflighting. - * @return Number of UChars in the data to be extracted. Does not include a trailing NUL. - * - * @stable ICU 3.4 - */ -U_STABLE int32_t U_EXPORT2 -utext_extract(UText *ut, - int64_t nativeStart, int64_t nativeLimit, - UChar *dest, int32_t destCapacity, - UErrorCode *status); - - - -/************************************************************************************ - * - * #define inline versions of selected performance-critical text access functions - * Caution: do not use auto increment++ or decrement-- expressions - * as parameters to these macros. - * - * For most use, where there is no extreme performance constraint, the - * normal, non-inline functions are a better choice. The resulting code - * will be smaller, and, if the need ever arises, easier to debug. - * - * These are implemented as #defines rather than real functions - * because there is no fully portable way to do inline functions in plain C. - * - ************************************************************************************/ - -#ifndef U_HIDE_INTERNAL_API -/** - * inline version of utext_current32(), for performance-critical situations. - * - * Get the code point at the current iteration position of the UText. - * Returns U_SENTINEL (-1) if the position is at the end of the - * text. - * - * @internal ICU 4.4 technology preview - */ -#define UTEXT_CURRENT32(ut) \ - ((ut)->chunkOffset < (ut)->chunkLength && ((ut)->chunkContents)[(ut)->chunkOffset]<0xd800 ? \ - ((ut)->chunkContents)[((ut)->chunkOffset)] : utext_current32(ut)) -#endif /* U_HIDE_INTERNAL_API */ - -/** - * inline version of utext_next32(), for performance-critical situations. - * - * Get the code point at the current iteration position of the UText, and - * advance the position to the first index following the character. - * This is a post-increment operation. - * Returns U_SENTINEL (-1) if the position is at the end of the - * text. - * - * @stable ICU 3.4 - */ -#define UTEXT_NEXT32(ut) \ - ((ut)->chunkOffset < (ut)->chunkLength && ((ut)->chunkContents)[(ut)->chunkOffset]<0xd800 ? \ - ((ut)->chunkContents)[((ut)->chunkOffset)++] : utext_next32(ut)) - -/** - * inline version of utext_previous32(), for performance-critical situations. - * - * Move the iterator position to the character (code point) whose - * index precedes the current position, and return that character. - * This is a pre-decrement operation. - * Returns U_SENTINEL (-1) if the position is at the start of the text. - * - * @stable ICU 3.4 - */ -#define UTEXT_PREVIOUS32(ut) \ - ((ut)->chunkOffset > 0 && \ - (ut)->chunkContents[(ut)->chunkOffset-1] < 0xd800 ? \ - (ut)->chunkContents[--((ut)->chunkOffset)] : utext_previous32(ut)) - -/** - * inline version of utext_getNativeIndex(), for performance-critical situations. - * - * Get the current iterator position, which can range from 0 to - * the length of the text. - * The position is a native index into the input text, in whatever format it - * may have (possibly UTF-8 for example), and may not always be the same as - * the corresponding UChar (UTF-16) index. - * The returned position will always be aligned to a code point boundary. - * - * @stable ICU 3.6 - */ -#define UTEXT_GETNATIVEINDEX(ut) \ - ((ut)->chunkOffset <= (ut)->nativeIndexingLimit? \ - (ut)->chunkNativeStart+(ut)->chunkOffset : \ - (ut)->pFuncs->mapOffsetToNative(ut)) - -/** - * inline version of utext_setNativeIndex(), for performance-critical situations. - * - * Set the current iteration position to the nearest code point - * boundary at or preceding the specified index. - * The index is in the native units of the original input text. - * If the index is out of range, it will be pinned to be within - * the range of the input text. - * - * @stable ICU 3.8 - */ -#define UTEXT_SETNATIVEINDEX(ut, ix) \ - { int64_t __offset = (ix) - (ut)->chunkNativeStart; \ - if (__offset>=0 && __offset<=(int64_t)(ut)->nativeIndexingLimit) { \ - (ut)->chunkOffset=(int32_t)__offset; \ - } else { \ - utext_setNativeIndex((ut), (ix)); } } - - - -/************************************************************************************ - * - * Functions related to writing or modifying the text. - * These will work only with modifiable UTexts. Attempting to - * modify a read-only UText will return an error status. - * - ************************************************************************************/ - - -/** - * Return TRUE if the text can be written (modified) with utext_replace() or - * utext_copy(). For the text to be writable, the text provider must - * be of a type that supports writing and the UText must not be frozen. - * - * Attempting to modify text when utext_isWriteable() is FALSE will fail - - * the text will not be modified, and an error will be returned from the function - * that attempted the modification. - * - * @param ut the UText to be tested. - * @return TRUE if the text is modifiable. - * - * @see utext_freeze() - * @see utext_replace() - * @see utext_copy() - * @stable ICU 3.4 - * - */ -U_STABLE UBool U_EXPORT2 -utext_isWritable(const UText *ut); - - -/** - * Test whether there is meta data associated with the text. - * @see Replaceable::hasMetaData() - * - * @param ut The UText to be tested - * @return TRUE if the underlying text includes meta data. - * @stable ICU 3.4 - */ -U_STABLE UBool U_EXPORT2 -utext_hasMetaData(const UText *ut); - - -/** - * Replace a range of the original text with a replacement text. - * - * Leaves the current iteration position at the position following the - * newly inserted replacement text. - * - * This function is only available on UText types that support writing, - * that is, ones where utext_isWritable() returns TRUE. - * - * When using this function, there should be only a single UText opened onto the - * underlying native text string. Behavior after a replace operation - * on a UText is undefined for any other additional UTexts that refer to the - * modified string. - * - * @param ut the UText representing the text to be operated on. - * @param nativeStart the native index of the start of the region to be replaced - * @param nativeLimit the native index of the character following the region to be replaced. - * @param replacementText pointer to the replacement text - * @param replacementLength length of the replacement text, or -1 if the text is NUL terminated. - * @param status receives any error status. Possible errors include - * U_NO_WRITE_PERMISSION - * - * @return The signed number of (native) storage units by which - * the length of the text expanded or contracted. - * - * @stable ICU 3.4 - */ -U_STABLE int32_t U_EXPORT2 -utext_replace(UText *ut, - int64_t nativeStart, int64_t nativeLimit, - const UChar *replacementText, int32_t replacementLength, - UErrorCode *status); - - - -/** - * - * Copy or move a substring from one position to another within the text, - * while retaining any metadata associated with the text. - * This function is used to duplicate or reorder substrings. - * The destination index must not overlap the source range. - * - * The text to be copied or moved is inserted at destIndex; - * it does not replace or overwrite any existing text. - * - * The iteration position is left following the newly inserted text - * at the destination position. - * - * This function is only available on UText types that support writing, - * that is, ones where utext_isWritable() returns TRUE. - * - * When using this function, there should be only a single UText opened onto the - * underlying native text string. Behavior after a copy operation - * on a UText is undefined in any other additional UTexts that refer to the - * modified string. - * - * @param ut The UText representing the text to be operated on. - * @param nativeStart The native index of the start of the region to be copied or moved - * @param nativeLimit The native index of the character position following the region - * to be copied. - * @param destIndex The native destination index to which the source substring is - * copied or moved. - * @param move If TRUE, then the substring is moved, not copied/duplicated. - * @param status receives any error status. Possible errors include U_NO_WRITE_PERMISSION - * - * @stable ICU 3.4 - */ -U_STABLE void U_EXPORT2 -utext_copy(UText *ut, - int64_t nativeStart, int64_t nativeLimit, - int64_t destIndex, - UBool move, - UErrorCode *status); - - -/** - *

- * Freeze a UText. This prevents any modification to the underlying text itself - * by means of functions operating on this UText. - *

- *

- * Once frozen, a UText can not be unfrozen. The intent is to ensure - * that a the text underlying a frozen UText wrapper cannot be modified via that UText. - *

- *

- * Caution: freezing a UText will disable changes made via the specific - * frozen UText wrapper only; it will not have any effect on the ability to - * directly modify the text by bypassing the UText. Any such backdoor modifications - * are always an error while UText access is occuring because the underlying - * text can get out of sync with UText's buffering. - *

- * - * @param ut The UText to be frozen. - * @see utext_isWritable() - * @stable ICU 3.6 - */ -U_STABLE void U_EXPORT2 -utext_freeze(UText *ut); - - -/** - * UText provider properties (bit field indexes). - * - * @see UText - * @stable ICU 3.4 - */ -enum { - /** - * It is potentially time consuming for the provider to determine the length of the text. - * @stable ICU 3.4 - */ - UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE = 1, - /** - * Text chunks remain valid and usable until the text object is modified or - * deleted, not just until the next time the access() function is called - * (which is the default). - * @stable ICU 3.4 - */ - UTEXT_PROVIDER_STABLE_CHUNKS = 2, - /** - * The provider supports modifying the text via the replace() and copy() - * functions. - * @see Replaceable - * @stable ICU 3.4 - */ - UTEXT_PROVIDER_WRITABLE = 3, - /** - * There is meta data associated with the text. - * @see Replaceable::hasMetaData() - * @stable ICU 3.4 - */ - UTEXT_PROVIDER_HAS_META_DATA = 4, - /** - * Text provider owns the text storage. - * Generally occurs as the result of a deep clone of the UText. - * When closing the UText, the associated text must - * also be closed/deleted/freed/ whatever is appropriate. - * @stable ICU 3.6 - */ - UTEXT_PROVIDER_OWNS_TEXT = 5 -}; - -/** - * Function type declaration for UText.clone(). - * - * clone a UText. Much like opening a UText where the source text is itself - * another UText. - * - * A deep clone will copy both the UText data structures and the underlying text. - * The original and cloned UText will operate completely independently; modifications - * made to the text in one will not effect the other. Text providers are not - * required to support deep clones. The user of clone() must check the status return - * and be prepared to handle failures. - * - * A shallow clone replicates only the UText data structures; it does not make - * a copy of the underlying text. Shallow clones can be used as an efficient way to - * have multiple iterators active in a single text string that is not being - * modified. - * - * A shallow clone operation must not fail except for truly exceptional conditions such - * as memory allocation failures. - * - * A UText and its clone may be safely concurrently accessed by separate threads. - * This is true for both shallow and deep clones. - * It is the responsibility of the Text Provider to ensure that this thread safety - * constraint is met. - - * - * @param dest A UText struct to be filled in with the result of the clone operation, - * or NULL if the clone function should heap-allocate a new UText struct. - * @param src The UText to be cloned. - * @param deep TRUE to request a deep clone, FALSE for a shallow clone. - * @param status Errors are returned here. For deep clones, U_UNSUPPORTED_ERROR - * should be returned if the text provider is unable to clone the - * original text. - * @return The newly created clone, or NULL if the clone operation failed. - * - * @stable ICU 3.4 - */ -typedef UText * U_CALLCONV -UTextClone(UText *dest, const UText *src, UBool deep, UErrorCode *status); - - -/** - * Function type declaration for UText.nativeLength(). - * - * @param ut the UText to get the length of. - * @return the length, in the native units of the original text string. - * @see UText - * @stable ICU 3.4 - */ -typedef int64_t U_CALLCONV -UTextNativeLength(UText *ut); - -/** - * Function type declaration for UText.access(). Get the description of the text chunk - * containing the text at a requested native index. The UText's iteration - * position will be left at the requested index. If the index is out - * of bounds, the iteration position will be left at the start or end - * of the string, as appropriate. - * - * Chunks must begin and end on code point boundaries. A single code point - * comprised of multiple storage units must never span a chunk boundary. - * - * - * @param ut the UText being accessed. - * @param nativeIndex Requested index of the text to be accessed. - * @param forward If TRUE, then the returned chunk must contain text - * starting from the index, so that start<=index - * The size (number of 16 bit UChars) in the data to be extracted is returned. The - * full amount is returned, even when the specified buffer size is smaller. - *

- * The extracted string will (if you are a user) / must (if you are a text provider) - * be NUL-terminated if there is sufficient space in the destination buffer. - * - * @param ut the UText from which to extract data. - * @param nativeStart the native index of the first characer to extract. - * @param nativeLimit the native string index of the position following the last - * character to extract. - * @param dest the UChar (UTF-16) buffer into which the extracted text is placed - * @param destCapacity The size, in UChars, of the destination buffer. May be zero - * for precomputing the required size. - * @param status receives any error status. - * If U_BUFFER_OVERFLOW_ERROR: Returns number of UChars for - * preflighting. - * @return Number of UChars in the data. Does not include a trailing NUL. - * - * @stable ICU 3.4 - */ -typedef int32_t U_CALLCONV -UTextExtract(UText *ut, - int64_t nativeStart, int64_t nativeLimit, - UChar *dest, int32_t destCapacity, - UErrorCode *status); - -/** - * Function type declaration for UText.replace(). - * - * Replace a range of the original text with a replacement text. - * - * Leaves the current iteration position at the position following the - * newly inserted replacement text. - * - * This function need only be implemented on UText types that support writing. - * - * When using this function, there should be only a single UText opened onto the - * underlying native text string. The function is responsible for updating the - * text chunk within the UText to reflect the updated iteration position, - * taking into account any changes to the underlying string's structure caused - * by the replace operation. - * - * @param ut the UText representing the text to be operated on. - * @param nativeStart the index of the start of the region to be replaced - * @param nativeLimit the index of the character following the region to be replaced. - * @param replacementText pointer to the replacement text - * @param replacmentLength length of the replacement text in UChars, or -1 if the text is NUL terminated. - * @param status receives any error status. Possible errors include - * U_NO_WRITE_PERMISSION - * - * @return The signed number of (native) storage units by which - * the length of the text expanded or contracted. - * - * @stable ICU 3.4 - */ -typedef int32_t U_CALLCONV -UTextReplace(UText *ut, - int64_t nativeStart, int64_t nativeLimit, - const UChar *replacementText, int32_t replacmentLength, - UErrorCode *status); - -/** - * Function type declaration for UText.copy(). - * - * Copy or move a substring from one position to another within the text, - * while retaining any metadata associated with the text. - * This function is used to duplicate or reorder substrings. - * The destination index must not overlap the source range. - * - * The text to be copied or moved is inserted at destIndex; - * it does not replace or overwrite any existing text. - * - * This function need only be implemented for UText types that support writing. - * - * When using this function, there should be only a single UText opened onto the - * underlying native text string. The function is responsible for updating the - * text chunk within the UText to reflect the updated iteration position, - * taking into account any changes to the underlying string's structure caused - * by the replace operation. - * - * @param ut The UText representing the text to be operated on. - * @param nativeStart The index of the start of the region to be copied or moved - * @param nativeLimit The index of the character following the region to be replaced. - * @param nativeDest The destination index to which the source substring is copied or moved. - * @param move If TRUE, then the substring is moved, not copied/duplicated. - * @param status receives any error status. Possible errors include U_NO_WRITE_PERMISSION - * - * @stable ICU 3.4 - */ -typedef void U_CALLCONV -UTextCopy(UText *ut, - int64_t nativeStart, int64_t nativeLimit, - int64_t nativeDest, - UBool move, - UErrorCode *status); - -/** - * Function type declaration for UText.mapOffsetToNative(). - * Map from the current UChar offset within the current text chunk to - * the corresponding native index in the original source text. - * - * This is required only for text providers that do not use native UTF-16 indexes. - * - * @param ut the UText. - * @return Absolute (native) index corresponding to chunkOffset in the current chunk. - * The returned native index should always be to a code point boundary. - * - * @stable ICU 3.4 - */ -typedef int64_t U_CALLCONV -UTextMapOffsetToNative(const UText *ut); - -/** - * Function type declaration for UText.mapIndexToUTF16(). - * Map from a native index to a UChar offset within a text chunk. - * Behavior is undefined if the native index does not fall within the - * current chunk. - * - * This function is required only for text providers that do not use native UTF-16 indexes. - * - * @param ut The UText containing the text chunk. - * @param nativeIndex Absolute (native) text index, chunk->start<=index<=chunk->limit. - * @return Chunk-relative UTF-16 offset corresponding to the specified native - * index. - * - * @stable ICU 3.4 - */ -typedef int32_t U_CALLCONV -UTextMapNativeIndexToUTF16(const UText *ut, int64_t nativeIndex); - - -/** - * Function type declaration for UText.utextClose(). - * - * A Text Provider close function is only required for provider types that make - * allocations in their open function (or other functions) that must be - * cleaned when the UText is closed. - * - * The allocation of the UText struct itself and any "extra" storage - * associated with the UText is handled by the common UText implementation - * and does not require provider specific cleanup in a close function. - * - * Most UText provider implementations do not need to implement this function. - * - * @param ut A UText object to be closed. - * - * @stable ICU 3.4 - */ -typedef void U_CALLCONV -UTextClose(UText *ut); - - -/** - * (public) Function dispatch table for UText. - * Conceptually very much like a C++ Virtual Function Table. - * This struct defines the organization of the table. - * Each text provider implementation must provide an - * actual table that is initialized with the appropriate functions - * for the type of text being handled. - * @stable ICU 3.6 - */ -struct UTextFuncs { - /** - * (public) Function table size, sizeof(UTextFuncs) - * Intended for use should the table grow to accomodate added - * functions in the future, to allow tests for older format - * function tables that do not contain the extensions. - * - * Fields are placed for optimal alignment on - * 32/64/128-bit-pointer machines, by normally grouping together - * 4 32-bit fields, - * 4 pointers, - * 2 64-bit fields - * in sequence. - * @stable ICU 3.6 - */ - int32_t tableSize; - - /** - * (private) Alignment padding. - * Do not use, reserved for use by the UText framework only. - * @internal - */ - int32_t reserved1, /** @internal */ reserved2, /** @internal */ reserved3; - - - /** - * (public) Function pointer for UTextClone - * - * @see UTextClone - * @stable ICU 3.6 - */ - UTextClone *clone; - - /** - * (public) function pointer for UTextLength - * May be expensive to compute! - * - * @see UTextLength - * @stable ICU 3.6 - */ - UTextNativeLength *nativeLength; - - /** - * (public) Function pointer for UTextAccess. - * - * @see UTextAccess - * @stable ICU 3.6 - */ - UTextAccess *access; - - /** - * (public) Function pointer for UTextExtract. - * - * @see UTextExtract - * @stable ICU 3.6 - */ - UTextExtract *extract; - - /** - * (public) Function pointer for UTextReplace. - * - * @see UTextReplace - * @stable ICU 3.6 - */ - UTextReplace *replace; - - /** - * (public) Function pointer for UTextCopy. - * - * @see UTextCopy - * @stable ICU 3.6 - */ - UTextCopy *copy; - - /** - * (public) Function pointer for UTextMapOffsetToNative. - * - * @see UTextMapOffsetToNative - * @stable ICU 3.6 - */ - UTextMapOffsetToNative *mapOffsetToNative; - - /** - * (public) Function pointer for UTextMapNativeIndexToUTF16. - * - * @see UTextMapNativeIndexToUTF16 - * @stable ICU 3.6 - */ - UTextMapNativeIndexToUTF16 *mapNativeIndexToUTF16; - - /** - * (public) Function pointer for UTextClose. - * - * @see UTextClose - * @stable ICU 3.6 - */ - UTextClose *close; - - /** - * (private) Spare function pointer - * @internal - */ - UTextClose *spare1; - - /** - * (private) Spare function pointer - * @internal - */ - UTextClose *spare2; - - /** - * (private) Spare function pointer - * @internal - */ - UTextClose *spare3; - -}; -/** - * Function dispatch table for UText - * @see UTextFuncs - */ -typedef struct UTextFuncs UTextFuncs; - - /** - * UText struct. Provides the interface between the generic UText access code - * and the UText provider code that works on specific kinds of - * text (UTF-8, noncontiguous UTF-16, whatever.) - * - * Applications that are using predefined types of text providers - * to pass text data to ICU services will have no need to view the - * internals of the UText structs that they open. - * - * @stable ICU 3.6 - */ -struct UText { - /** - * (private) Magic. Used to help detect when UText functions are handed - * invalid or unitialized UText structs. - * utext_openXYZ() functions take an initialized, - * but not necessarily open, UText struct as an - * optional fill-in parameter. This magic field - * is used to check for that initialization. - * Text provider close functions must NOT clear - * the magic field because that would prevent - * reuse of the UText struct. - * @internal - */ - uint32_t magic; - - - /** - * (private) Flags for managing the allocation and freeing of - * memory associated with this UText. - * @internal - */ - int32_t flags; - - - /** - * Text provider properties. This set of flags is maintainted by the - * text provider implementation. - * @stable ICU 3.4 - */ - int32_t providerProperties; - - /** - * (public) sizeOfStruct=sizeof(UText) - * Allows possible backward compatible extension. - * - * @stable ICU 3.4 - */ - int32_t sizeOfStruct; - - /* ------ 16 byte alignment boundary ----------- */ - - - /** - * (protected) Native index of the first character position following - * the current chunk. - * @stable ICU 3.6 - */ - int64_t chunkNativeLimit; - - /** - * (protected) Size in bytes of the extra space (pExtra). - * @stable ICU 3.4 - */ - int32_t extraSize; - - /** - * (protected) The highest chunk offset where native indexing and - * chunk (UTF-16) indexing correspond. For UTF-16 sources, value - * will be equal to chunkLength. - * - * @stable ICU 3.6 - */ - int32_t nativeIndexingLimit; - - /* ---- 16 byte alignment boundary------ */ - - /** - * (protected) Native index of the first character in the text chunk. - * @stable ICU 3.6 - */ - int64_t chunkNativeStart; - - /** - * (protected) Current iteration position within the text chunk (UTF-16 buffer). - * This is the index to the character that will be returned by utext_next32(). - * @stable ICU 3.6 - */ - int32_t chunkOffset; - - /** - * (protected) Length the text chunk (UTF-16 buffer), in UChars. - * @stable ICU 3.6 - */ - int32_t chunkLength; - - /* ---- 16 byte alignment boundary-- */ - - - /** - * (protected) pointer to a chunk of text in UTF-16 format. - * May refer either to original storage of the source of the text, or - * if conversion was required, to a buffer owned by the UText. - * @stable ICU 3.6 - */ - const UChar *chunkContents; - - /** - * (public) Pointer to Dispatch table for accessing functions for this UText. - * @stable ICU 3.6 - */ - const UTextFuncs *pFuncs; - - /** - * (protected) Pointer to additional space requested by the - * text provider during the utext_open operation. - * @stable ICU 3.4 - */ - void *pExtra; - - /** - * (protected) Pointer to string or text-containin object or similar. - * This is the source of the text that this UText is wrapping, in a format - * that is known to the text provider functions. - * @stable ICU 3.4 - */ - const void *context; - - /* --- 16 byte alignment boundary--- */ - - /** - * (protected) Pointer fields available for use by the text provider. - * Not used by UText common code. - * @stable ICU 3.6 - */ - const void *p; - /** - * (protected) Pointer fields available for use by the text provider. - * Not used by UText common code. - * @stable ICU 3.6 - */ - const void *q; - /** - * (protected) Pointer fields available for use by the text provider. - * Not used by UText common code. - * @stable ICU 3.6 - */ - const void *r; - - /** - * Private field reserved for future use by the UText framework - * itself. This is not to be touched by the text providers. - * @internal ICU 3.4 - */ - void *privP; - - - /* --- 16 byte alignment boundary--- */ - - - /** - * (protected) Integer field reserved for use by the text provider. - * Not used by the UText framework, or by the client (user) of the UText. - * @stable ICU 3.4 - */ - int64_t a; - - /** - * (protected) Integer field reserved for use by the text provider. - * Not used by the UText framework, or by the client (user) of the UText. - * @stable ICU 3.4 - */ - int32_t b; - - /** - * (protected) Integer field reserved for use by the text provider. - * Not used by the UText framework, or by the client (user) of the UText. - * @stable ICU 3.4 - */ - int32_t c; - - /* ---- 16 byte alignment boundary---- */ - - - /** - * Private field reserved for future use by the UText framework - * itself. This is not to be touched by the text providers. - * @internal ICU 3.4 - */ - int64_t privA; - /** - * Private field reserved for future use by the UText framework - * itself. This is not to be touched by the text providers. - * @internal ICU 3.4 - */ - int32_t privB; - /** - * Private field reserved for future use by the UText framework - * itself. This is not to be touched by the text providers. - * @internal ICU 3.4 - */ - int32_t privC; -}; - - -/** - * Common function for use by Text Provider implementations to allocate and/or initialize - * a new UText struct. To be called in the implementation of utext_open() functions. - * If the supplied UText parameter is null, a new UText struct will be allocated on the heap. - * If the supplied UText is already open, the provider's close function will be called - * so that the struct can be reused by the open that is in progress. - * - * @param ut pointer to a UText struct to be re-used, or null if a new UText - * should be allocated. - * @param extraSpace The amount of additional space to be allocated as part - * of this UText, for use by types of providers that require - * additional storage. - * @param status Errors are returned here. - * @return pointer to the UText, allocated if necessary, with extra space set up if requested. - * @stable ICU 3.4 - */ -U_STABLE UText * U_EXPORT2 -utext_setup(UText *ut, int32_t extraSpace, UErrorCode *status); - -#ifndef U_HIDE_INTERNAL_API -/** - * @internal - * Value used to help identify correctly initialized UText structs. - * Note: must be publicly visible so that UTEXT_INITIALIZER can access it. - */ -enum { - UTEXT_MAGIC = 0x345ad82c -}; -#endif /* U_HIDE_INTERNAL_API */ - -/** - * initializer to be used with local (stack) instances of a UText - * struct. UText structs must be initialized before passing - * them to one of the utext_open functions. - * - * @stable ICU 3.6 - */ -#define UTEXT_INITIALIZER { \ - UTEXT_MAGIC, /* magic */ \ - 0, /* flags */ \ - 0, /* providerProps */ \ - sizeof(UText), /* sizeOfStruct */ \ - 0, /* chunkNativeLimit */ \ - 0, /* extraSize */ \ - 0, /* nativeIndexingLimit */ \ - 0, /* chunkNativeStart */ \ - 0, /* chunkOffset */ \ - 0, /* chunkLength */ \ - NULL, /* chunkContents */ \ - NULL, /* pFuncs */ \ - NULL, /* pExtra */ \ - NULL, /* context */ \ - NULL, NULL, NULL, /* p, q, r */ \ - NULL, /* privP */ \ - 0, 0, 0, /* a, b, c */ \ - 0, 0, 0 /* privA,B,C, */ \ - } - - -U_CDECL_END - - - -#endif diff --git a/win32/include/spidermonkey/unicode/utf.h b/win32/include/spidermonkey/unicode/utf.h deleted file mode 100755 index ffb094f4..00000000 --- a/win32/include/spidermonkey/unicode/utf.h +++ /dev/null @@ -1,225 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 1999-2011, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: utf.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 1999sep09 -* created by: Markus W. Scherer -*/ - -/** - * \file - * \brief C API: Code point macros - * - * This file defines macros for checking whether a code point is - * a surrogate or a non-character etc. - * - * The UChar and UChar32 data types for Unicode code units and code points - * are defined in umachine.h because they can be machine-dependent. - * - * If U_NO_DEFAULT_INCLUDE_UTF_HEADERS is 0 then utf.h is included by utypes.h - * and itself includes utf8.h and utf16.h after some - * common definitions. - * If U_NO_DEFAULT_INCLUDE_UTF_HEADERS is 1 then each of these headers must be - * included explicitly if their definitions are used. - * - * utf8.h and utf16.h define macros for efficiently getting code points - * in and out of UTF-8/16 strings. - * utf16.h macros have "U16_" prefixes. - * utf8.h defines similar macros with "U8_" prefixes for UTF-8 string handling. - * - * ICU mostly processes 16-bit Unicode strings. - * Most of the time, such strings are well-formed UTF-16. - * Single, unpaired surrogates must be handled as well, and are treated in ICU - * like regular code points where possible. - * (Pairs of surrogate code points are indistinguishable from supplementary - * code points encoded as pairs of supplementary code units.) - * - * In fact, almost all Unicode code points in normal text (>99%) - * are on the BMP (<=U+ffff) and even <=U+d7ff. - * ICU functions handle supplementary code points (U+10000..U+10ffff) - * but are optimized for the much more frequently occurring BMP code points. - * - * umachine.h defines UChar to be an unsigned 16-bit integer. - * Where available, UChar is defined to be a char16_t - * or a wchar_t (if that is an unsigned 16-bit type), otherwise uint16_t. - * - * UChar32 is defined to be a signed 32-bit integer (int32_t), large enough for a 21-bit - * Unicode code point (Unicode scalar value, 0..0x10ffff). - * Before ICU 2.4, the definition of UChar32 was similarly platform-dependent as - * the definition of UChar. For details see the documentation for UChar32 itself. - * - * utf.h defines a small number of C macros for single Unicode code points. - * These are simple checks for surrogates and non-characters. - * For actual Unicode character properties see uchar.h. - * - * By default, string operations must be done with error checking in case - * a string is not well-formed UTF-16. - * The macros will detect if a surrogate code unit is unpaired - * (lead unit without trail unit or vice versa) and just return the unit itself - * as the code point. - * - * The regular "safe" macros require that the initial, passed-in string index - * is within bounds. They only check the index when they read more than one - * code unit. This is usually done with code similar to the following loop: - *

while(i
- *
- * When it is safe to assume that text is well-formed UTF-16
- * (does not contain single, unpaired surrogates), then one can use
- * U16_..._UNSAFE macros.
- * These do not check for proper code unit sequences or truncated text and may
- * yield wrong results or even cause a crash if they are used with "malformed"
- * text.
- * In practice, U16_..._UNSAFE macros will produce slightly less code but
- * should not be faster because the processing is only different when a
- * surrogate code unit is detected, which will be rare.
- *
- * Similarly for UTF-8, there are "safe" macros without a suffix,
- * and U8_..._UNSAFE versions.
- * The performance differences are much larger here because UTF-8 provides so
- * many opportunities for malformed sequences.
- * The unsafe UTF-8 macros are entirely implemented inside the macro definitions
- * and are fast, while the safe UTF-8 macros call functions for all but the
- * trivial (ASCII) cases.
- * (ICU 3.6 optimizes U8_NEXT() and U8_APPEND() to handle most other common
- * characters inline as well.)
- *
- * Unlike with UTF-16, malformed sequences cannot be expressed with distinct
- * code point values (0..U+10ffff). They are indicated with negative values instead.
- *
- * For more information see the ICU User Guide Strings chapter
- * (http://userguide.icu-project.org/strings).
- *
- * Usage:
- * ICU coding guidelines for if() statements should be followed when using these macros.
- * Compound statements (curly braces {}) must be used  for if-else-while... 
- * bodies and all macro statements should be terminated with semicolon.
- *
- * @stable ICU 2.4
- */
-
-#ifndef __UTF_H__
-#define __UTF_H__
-
-#include "unicode/umachine.h"
-/* include the utfXX.h after the following definitions */
-
-/* single-code point definitions -------------------------------------------- */
-
-/**
- * Is this code point a Unicode noncharacter?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U_IS_UNICODE_NONCHAR(c) \
-    ((c)>=0xfdd0 && \
-     ((uint32_t)(c)<=0xfdef || ((c)&0xfffe)==0xfffe) && \
-     (uint32_t)(c)<=0x10ffff)
-
-/**
- * Is c a Unicode code point value (0..U+10ffff)
- * that can be assigned a character?
- *
- * Code points that are not characters include:
- * - single surrogate code points (U+d800..U+dfff, 2048 code points)
- * - the last two code points on each plane (U+__fffe and U+__ffff, 34 code points)
- * - U+fdd0..U+fdef (new with Unicode 3.1, 32 code points)
- * - the highest Unicode code point value is U+10ffff
- *
- * This means that all code points below U+d800 are character code points,
- * and that boundary is tested first for performance.
- *
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U_IS_UNICODE_CHAR(c) \
-    ((uint32_t)(c)<0xd800 || \
-        ((uint32_t)(c)>0xdfff && \
-         (uint32_t)(c)<=0x10ffff && \
-         !U_IS_UNICODE_NONCHAR(c)))
-
-/**
- * Is this code point a BMP code point (U+0000..U+ffff)?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.8
- */
-#define U_IS_BMP(c) ((uint32_t)(c)<=0xffff)
-
-/**
- * Is this code point a supplementary code point (U+10000..U+10ffff)?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.8
- */
-#define U_IS_SUPPLEMENTARY(c) ((uint32_t)((c)-0x10000)<=0xfffff)
- 
-/**
- * Is this code point a lead surrogate (U+d800..U+dbff)?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U_IS_LEAD(c) (((c)&0xfffffc00)==0xd800)
-
-/**
- * Is this code point a trail surrogate (U+dc00..U+dfff)?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U_IS_TRAIL(c) (((c)&0xfffffc00)==0xdc00)
-
-/**
- * Is this code point a surrogate (U+d800..U+dfff)?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U_IS_SURROGATE(c) (((c)&0xfffff800)==0xd800)
-
-/**
- * Assuming c is a surrogate code point (U_IS_SURROGATE(c)),
- * is it a lead surrogate?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U_IS_SURROGATE_LEAD(c) (((c)&0x400)==0)
-
-/**
- * Assuming c is a surrogate code point (U_IS_SURROGATE(c)),
- * is it a trail surrogate?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 4.2
- */
-#define U_IS_SURROGATE_TRAIL(c) (((c)&0x400)!=0)
-
-/* include the utfXX.h ------------------------------------------------------ */
-
-#if !U_NO_DEFAULT_INCLUDE_UTF_HEADERS
-
-#include "unicode/utf8.h"
-#include "unicode/utf16.h"
-
-/* utf_old.h contains deprecated, pre-ICU 2.4 definitions */
-#include "unicode/utf_old.h"
-
-#endif  /* !U_NO_DEFAULT_INCLUDE_UTF_HEADERS */
-
-#endif  /* __UTF_H__ */
diff --git a/win32/include/spidermonkey/unicode/utf16.h b/win32/include/spidermonkey/unicode/utf16.h
deleted file mode 100755
index 6e7d1da7..00000000
--- a/win32/include/spidermonkey/unicode/utf16.h
+++ /dev/null
@@ -1,625 +0,0 @@
-// Copyright (C) 2016 and later: Unicode, Inc. and others.
-// License & terms of use: http://www.unicode.org/copyright.html
-/*
-*******************************************************************************
-*
-*   Copyright (C) 1999-2012, International Business Machines
-*   Corporation and others.  All Rights Reserved.
-*
-*******************************************************************************
-*   file name:  utf16.h
-*   encoding:   US-ASCII
-*   tab size:   8 (not used)
-*   indentation:4
-*
-*   created on: 1999sep09
-*   created by: Markus W. Scherer
-*/
-
-/**
- * \file
- * \brief C API: 16-bit Unicode handling macros
- * 
- * This file defines macros to deal with 16-bit Unicode (UTF-16) code units and strings.
- *
- * For more information see utf.h and the ICU User Guide Strings chapter
- * (http://userguide.icu-project.org/strings).
- *
- * Usage:
- * ICU coding guidelines for if() statements should be followed when using these macros.
- * Compound statements (curly braces {}) must be used  for if-else-while... 
- * bodies and all macro statements should be terminated with semicolon.
- */
-
-#ifndef __UTF16_H__
-#define __UTF16_H__
-
-#include "unicode/umachine.h"
-#ifndef __UTF_H__
-#   include "unicode/utf.h"
-#endif
-
-/* single-code point definitions -------------------------------------------- */
-
-/**
- * Does this code unit alone encode a code point (BMP, not a surrogate)?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U16_IS_SINGLE(c) !U_IS_SURROGATE(c)
-
-/**
- * Is this code unit a lead surrogate (U+d800..U+dbff)?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U16_IS_LEAD(c) (((c)&0xfffffc00)==0xd800)
-
-/**
- * Is this code unit a trail surrogate (U+dc00..U+dfff)?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U16_IS_TRAIL(c) (((c)&0xfffffc00)==0xdc00)
-
-/**
- * Is this code unit a surrogate (U+d800..U+dfff)?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U16_IS_SURROGATE(c) U_IS_SURROGATE(c)
-
-/**
- * Assuming c is a surrogate code point (U16_IS_SURROGATE(c)),
- * is it a lead surrogate?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U16_IS_SURROGATE_LEAD(c) (((c)&0x400)==0)
-
-/**
- * Assuming c is a surrogate code point (U16_IS_SURROGATE(c)),
- * is it a trail surrogate?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 4.2
- */
-#define U16_IS_SURROGATE_TRAIL(c) (((c)&0x400)!=0)
-
-/**
- * Helper constant for U16_GET_SUPPLEMENTARY.
- * @internal
- */
-#define U16_SURROGATE_OFFSET ((0xd800<<10UL)+0xdc00-0x10000)
-
-/**
- * Get a supplementary code point value (U+10000..U+10ffff)
- * from its lead and trail surrogates.
- * The result is undefined if the input values are not
- * lead and trail surrogates.
- *
- * @param lead lead surrogate (U+d800..U+dbff)
- * @param trail trail surrogate (U+dc00..U+dfff)
- * @return supplementary code point (U+10000..U+10ffff)
- * @stable ICU 2.4
- */
-#define U16_GET_SUPPLEMENTARY(lead, trail) \
-    (((UChar32)(lead)<<10UL)+(UChar32)(trail)-U16_SURROGATE_OFFSET)
-
-
-/**
- * Get the lead surrogate (0xd800..0xdbff) for a
- * supplementary code point (0x10000..0x10ffff).
- * @param supplementary 32-bit code point (U+10000..U+10ffff)
- * @return lead surrogate (U+d800..U+dbff) for supplementary
- * @stable ICU 2.4
- */
-#define U16_LEAD(supplementary) (UChar)(((supplementary)>>10)+0xd7c0)
-
-/**
- * Get the trail surrogate (0xdc00..0xdfff) for a
- * supplementary code point (0x10000..0x10ffff).
- * @param supplementary 32-bit code point (U+10000..U+10ffff)
- * @return trail surrogate (U+dc00..U+dfff) for supplementary
- * @stable ICU 2.4
- */
-#define U16_TRAIL(supplementary) (UChar)(((supplementary)&0x3ff)|0xdc00)
-
-/**
- * How many 16-bit code units are used to encode this Unicode code point? (1 or 2)
- * The result is not defined if c is not a Unicode code point (U+0000..U+10ffff).
- * @param c 32-bit code point
- * @return 1 or 2
- * @stable ICU 2.4
- */
-#define U16_LENGTH(c) ((uint32_t)(c)<=0xffff ? 1 : 2)
-
-/**
- * The maximum number of 16-bit code units per Unicode code point (U+0000..U+10ffff).
- * @return 2
- * @stable ICU 2.4
- */
-#define U16_MAX_LENGTH 2
-
-/**
- * Get a code point from a string at a random-access offset,
- * without changing the offset.
- * "Unsafe" macro, assumes well-formed UTF-16.
- *
- * The offset may point to either the lead or trail surrogate unit
- * for a supplementary code point, in which case the macro will read
- * the adjacent matching surrogate as well.
- * The result is undefined if the offset points to a single, unpaired surrogate.
- * Iteration through a string is more efficient with U16_NEXT_UNSAFE or U16_NEXT.
- *
- * @param s const UChar * string
- * @param i string offset
- * @param c output UChar32 variable
- * @see U16_GET
- * @stable ICU 2.4
- */
-#define U16_GET_UNSAFE(s, i, c) { \
-    (c)=(s)[i]; \
-    if(U16_IS_SURROGATE(c)) { \
-        if(U16_IS_SURROGATE_LEAD(c)) { \
-            (c)=U16_GET_SUPPLEMENTARY((c), (s)[(i)+1]); \
-        } else { \
-            (c)=U16_GET_SUPPLEMENTARY((s)[(i)-1], (c)); \
-        } \
-    } \
-}
-
-/**
- * Get a code point from a string at a random-access offset,
- * without changing the offset.
- * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
- *
- * The offset may point to either the lead or trail surrogate unit
- * for a supplementary code point, in which case the macro will read
- * the adjacent matching surrogate as well.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * If the offset points to a single, unpaired surrogate, then that itself
- * will be returned as the code point.
- * Iteration through a string is more efficient with U16_NEXT_UNSAFE or U16_NEXT.
- *
- * @param s const UChar * string
- * @param start starting string offset (usually 0)
- * @param i string offset, must be start<=i(start) && U16_IS_LEAD(__c2=(s)[(i)-1])) { \
-                (c)=U16_GET_SUPPLEMENTARY(__c2, (c)); \
-            } \
-        } \
-    } \
-}
-
-/* definitions with forward iteration --------------------------------------- */
-
-/**
- * Get a code point from a string at a code point boundary offset,
- * and advance the offset to the next code point boundary.
- * (Post-incrementing forward iteration.)
- * "Unsafe" macro, assumes well-formed UTF-16.
- *
- * The offset may point to the lead surrogate unit
- * for a supplementary code point, in which case the macro will read
- * the following trail surrogate as well.
- * If the offset points to a trail surrogate, then that itself
- * will be returned as the code point.
- * The result is undefined if the offset points to a single, unpaired lead surrogate.
- *
- * @param s const UChar * string
- * @param i string offset
- * @param c output UChar32 variable
- * @see U16_NEXT
- * @stable ICU 2.4
- */
-#define U16_NEXT_UNSAFE(s, i, c) { \
-    (c)=(s)[(i)++]; \
-    if(U16_IS_LEAD(c)) { \
-        (c)=U16_GET_SUPPLEMENTARY((c), (s)[(i)++]); \
-    } \
-}
-
-/**
- * Get a code point from a string at a code point boundary offset,
- * and advance the offset to the next code point boundary.
- * (Post-incrementing forward iteration.)
- * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * The offset may point to the lead surrogate unit
- * for a supplementary code point, in which case the macro will read
- * the following trail surrogate as well.
- * If the offset points to a trail surrogate or
- * to a single, unpaired lead surrogate, then that itself
- * will be returned as the code point.
- *
- * @param s const UChar * string
- * @param i string offset, must be i>10)+0xd7c0); \
-        (s)[(i)++]=(uint16_t)(((c)&0x3ff)|0xdc00); \
-    } \
-}
-
-/**
- * Append a code point to a string, overwriting 1 or 2 code units.
- * The offset points to the current end of the string contents
- * and is advanced (post-increment).
- * "Safe" macro, checks for a valid code point.
- * If a surrogate pair is written, checks for sufficient space in the string.
- * If the code point is not valid or a trail surrogate does not fit,
- * then isError is set to TRUE.
- *
- * @param s const UChar * string buffer
- * @param i string offset, must be i>10)+0xd7c0); \
-        (s)[(i)++]=(uint16_t)(((c)&0x3ff)|0xdc00); \
-    } else /* c>0x10ffff or not enough space */ { \
-        (isError)=TRUE; \
-    } \
-}
-
-/**
- * Advance the string offset from one code point boundary to the next.
- * (Post-incrementing iteration.)
- * "Unsafe" macro, assumes well-formed UTF-16.
- *
- * @param s const UChar * string
- * @param i string offset
- * @see U16_FWD_1
- * @stable ICU 2.4
- */
-#define U16_FWD_1_UNSAFE(s, i) { \
-    if(U16_IS_LEAD((s)[(i)++])) { \
-        ++(i); \
-    } \
-}
-
-/**
- * Advance the string offset from one code point boundary to the next.
- * (Post-incrementing iteration.)
- * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * @param s const UChar * string
- * @param i string offset, must be i0) { \
-        U16_FWD_1_UNSAFE(s, i); \
-        --__N; \
-    } \
-}
-
-/**
- * Advance the string offset from one code point boundary to the n-th next one,
- * i.e., move forward by n code points.
- * (Post-incrementing iteration.)
- * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * @param s const UChar * string
- * @param i int32_t string offset, must be i0 && ((i)<(length) || ((length)<0 && (s)[i]!=0))) { \
-        U16_FWD_1(s, i, length); \
-        --__N; \
-    } \
-}
-
-/**
- * Adjust a random-access offset to a code point boundary
- * at the start of a code point.
- * If the offset points to the trail surrogate of a surrogate pair,
- * then the offset is decremented.
- * Otherwise, it is not modified.
- * "Unsafe" macro, assumes well-formed UTF-16.
- *
- * @param s const UChar * string
- * @param i string offset
- * @see U16_SET_CP_START
- * @stable ICU 2.4
- */
-#define U16_SET_CP_START_UNSAFE(s, i) { \
-    if(U16_IS_TRAIL((s)[i])) { \
-        --(i); \
-    } \
-}
-
-/**
- * Adjust a random-access offset to a code point boundary
- * at the start of a code point.
- * If the offset points to the trail surrogate of a surrogate pair,
- * then the offset is decremented.
- * Otherwise, it is not modified.
- * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
- *
- * @param s const UChar * string
- * @param start starting string offset (usually 0)
- * @param i string offset, must be start<=i
- * @see U16_SET_CP_START_UNSAFE
- * @stable ICU 2.4
- */
-#define U16_SET_CP_START(s, start, i) { \
-    if(U16_IS_TRAIL((s)[i]) && (i)>(start) && U16_IS_LEAD((s)[(i)-1])) { \
-        --(i); \
-    } \
-}
-
-/* definitions with backward iteration -------------------------------------- */
-
-/**
- * Move the string offset from one code point boundary to the previous one
- * and get the code point between them.
- * (Pre-decrementing backward iteration.)
- * "Unsafe" macro, assumes well-formed UTF-16.
- *
- * The input offset may be the same as the string length.
- * If the offset is behind a trail surrogate unit
- * for a supplementary code point, then the macro will read
- * the preceding lead surrogate as well.
- * If the offset is behind a lead surrogate, then that itself
- * will be returned as the code point.
- * The result is undefined if the offset is behind a single, unpaired trail surrogate.
- *
- * @param s const UChar * string
- * @param i string offset
- * @param c output UChar32 variable
- * @see U16_PREV
- * @stable ICU 2.4
- */
-#define U16_PREV_UNSAFE(s, i, c) { \
-    (c)=(s)[--(i)]; \
-    if(U16_IS_TRAIL(c)) { \
-        (c)=U16_GET_SUPPLEMENTARY((s)[--(i)], (c)); \
-    } \
-}
-
-/**
- * Move the string offset from one code point boundary to the previous one
- * and get the code point between them.
- * (Pre-decrementing backward iteration.)
- * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
- *
- * The input offset may be the same as the string length.
- * If the offset is behind a trail surrogate unit
- * for a supplementary code point, then the macro will read
- * the preceding lead surrogate as well.
- * If the offset is behind a lead surrogate or behind a single, unpaired
- * trail surrogate, then that itself
- * will be returned as the code point.
- *
- * @param s const UChar * string
- * @param start starting string offset (usually 0)
- * @param i string offset, must be start(start) && U16_IS_LEAD(__c2=(s)[(i)-1])) { \
-            --(i); \
-            (c)=U16_GET_SUPPLEMENTARY(__c2, (c)); \
-        } \
-    } \
-}
-
-/**
- * Move the string offset from one code point boundary to the previous one.
- * (Pre-decrementing backward iteration.)
- * The input offset may be the same as the string length.
- * "Unsafe" macro, assumes well-formed UTF-16.
- *
- * @param s const UChar * string
- * @param i string offset
- * @see U16_BACK_1
- * @stable ICU 2.4
- */
-#define U16_BACK_1_UNSAFE(s, i) { \
-    if(U16_IS_TRAIL((s)[--(i)])) { \
-        --(i); \
-    } \
-}
-
-/**
- * Move the string offset from one code point boundary to the previous one.
- * (Pre-decrementing backward iteration.)
- * The input offset may be the same as the string length.
- * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
- *
- * @param s const UChar * string
- * @param start starting string offset (usually 0)
- * @param i string offset, must be start(start) && U16_IS_LEAD((s)[(i)-1])) { \
-        --(i); \
-    } \
-}
-
-/**
- * Move the string offset from one code point boundary to the n-th one before it,
- * i.e., move backward by n code points.
- * (Pre-decrementing backward iteration.)
- * The input offset may be the same as the string length.
- * "Unsafe" macro, assumes well-formed UTF-16.
- *
- * @param s const UChar * string
- * @param i string offset
- * @param n number of code points to skip
- * @see U16_BACK_N
- * @stable ICU 2.4
- */
-#define U16_BACK_N_UNSAFE(s, i, n) { \
-    int32_t __N=(n); \
-    while(__N>0) { \
-        U16_BACK_1_UNSAFE(s, i); \
-        --__N; \
-    } \
-}
-
-/**
- * Move the string offset from one code point boundary to the n-th one before it,
- * i.e., move backward by n code points.
- * (Pre-decrementing backward iteration.)
- * The input offset may be the same as the string length.
- * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
- *
- * @param s const UChar * string
- * @param start start of string
- * @param i string offset, must be start0 && (i)>(start)) { \
-        U16_BACK_1(s, start, i); \
-        --__N; \
-    } \
-}
-
-/**
- * Adjust a random-access offset to a code point boundary after a code point.
- * If the offset is behind the lead surrogate of a surrogate pair,
- * then the offset is incremented.
- * Otherwise, it is not modified.
- * The input offset may be the same as the string length.
- * "Unsafe" macro, assumes well-formed UTF-16.
- *
- * @param s const UChar * string
- * @param i string offset
- * @see U16_SET_CP_LIMIT
- * @stable ICU 2.4
- */
-#define U16_SET_CP_LIMIT_UNSAFE(s, i) { \
-    if(U16_IS_LEAD((s)[(i)-1])) { \
-        ++(i); \
-    } \
-}
-
-/**
- * Adjust a random-access offset to a code point boundary after a code point.
- * If the offset is behind the lead surrogate of a surrogate pair,
- * then the offset is incremented.
- * Otherwise, it is not modified.
- * The input offset may be the same as the string length.
- * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * @param s const UChar * string
- * @param start int32_t starting string offset (usually 0)
- * @param i int32_t string offset, start<=i<=length
- * @param length int32_t string length
- * @see U16_SET_CP_LIMIT_UNSAFE
- * @stable ICU 2.4
- */
-#define U16_SET_CP_LIMIT(s, start, i, length) { \
-    if((start)<(i) && ((i)<(length) || (length)<0) && U16_IS_LEAD((s)[(i)-1]) && U16_IS_TRAIL((s)[i])) { \
-        ++(i); \
-    } \
-}
-
-#endif
diff --git a/win32/include/spidermonkey/unicode/utf32.h b/win32/include/spidermonkey/unicode/utf32.h
deleted file mode 100755
index f93727c1..00000000
--- a/win32/include/spidermonkey/unicode/utf32.h
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (C) 2016 and later: Unicode, Inc. and others.
-// License & terms of use: http://www.unicode.org/copyright.html
-/*
-*******************************************************************************
-*
-*   Copyright (C) 1999-2001, International Business Machines
-*   Corporation and others.  All Rights Reserved.
-*
-*******************************************************************************
-*   file name:  utf32.h
-*   encoding:   US-ASCII
-*   tab size:   8 (not used)
-*   indentation:4
-*
-*   created on: 1999sep20
-*   created by: Markus W. Scherer
-*/
-/**
- * \file
- * \brief C API: UTF-32 macros
- *
- * This file is obsolete and its contents moved to utf_old.h.
- * See utf_old.h and Jitterbug 2150 and its discussion on the ICU mailing list
- * in September 2002.
- */
diff --git a/win32/include/spidermonkey/unicode/utf8.h b/win32/include/spidermonkey/unicode/utf8.h
deleted file mode 100755
index 55f7b9d2..00000000
--- a/win32/include/spidermonkey/unicode/utf8.h
+++ /dev/null
@@ -1,826 +0,0 @@
-// Copyright (C) 2016 and later: Unicode, Inc. and others.
-// License & terms of use: http://www.unicode.org/copyright.html
-/*
-*******************************************************************************
-*
-*   Copyright (C) 1999-2015, International Business Machines
-*   Corporation and others.  All Rights Reserved.
-*
-*******************************************************************************
-*   file name:  utf8.h
-*   encoding:   US-ASCII
-*   tab size:   8 (not used)
-*   indentation:4
-*
-*   created on: 1999sep13
-*   created by: Markus W. Scherer
-*/
-
-/**
- * \file
- * \brief C API: 8-bit Unicode handling macros
- * 
- * This file defines macros to deal with 8-bit Unicode (UTF-8) code units (bytes) and strings.
- *
- * For more information see utf.h and the ICU User Guide Strings chapter
- * (http://userguide.icu-project.org/strings).
- *
- * Usage:
- * ICU coding guidelines for if() statements should be followed when using these macros.
- * Compound statements (curly braces {}) must be used  for if-else-while... 
- * bodies and all macro statements should be terminated with semicolon.
- */
-
-#ifndef __UTF8_H__
-#define __UTF8_H__
-
-#include "unicode/umachine.h"
-#ifndef __UTF_H__
-#   include "unicode/utf.h"
-#endif
-
-/* internal definitions ----------------------------------------------------- */
-
-/**
- * \var utf8_countTrailBytes
- * Internal array with numbers of trail bytes for any given byte used in
- * lead byte position.
- *
- * This is internal since it is not meant to be called directly by external clients;
- * however it is called by public macros in this file and thus must remain stable,
- * and should not be hidden when other internal functions are hidden (otherwise
- * public macros would fail to compile).
- * @internal
- */
-#ifdef U_UTF8_IMPL
-U_EXPORT const uint8_t 
-#elif defined(U_STATIC_IMPLEMENTATION) || defined(U_COMMON_IMPLEMENTATION)
-U_CFUNC const uint8_t
-#else
-U_CFUNC U_IMPORT const uint8_t /* U_IMPORT2? */ /*U_IMPORT*/ 
-#endif
-utf8_countTrailBytes[256];
-
-/**
- * Counts the trail bytes for a UTF-8 lead byte.
- * Returns 0 for 0..0xbf as well as for 0xfe and 0xff.
- *
- * This is internal since it is not meant to be called directly by external clients;
- * however it is called by public macros in this file and thus must remain stable.
- *
- * Note: Beginning with ICU 50, the implementation uses a multi-condition expression
- * which was shown in 2012 (on x86-64) to compile to fast, branch-free code.
- * leadByte is evaluated multiple times.
- *
- * The pre-ICU 50 implementation used the exported array utf8_countTrailBytes:
- * #define U8_COUNT_TRAIL_BYTES(leadByte) (utf8_countTrailBytes[leadByte])
- * leadByte was evaluated exactly once.
- *
- * @param leadByte The first byte of a UTF-8 sequence. Must be 0..0xff.
- * @internal
- */
-#define U8_COUNT_TRAIL_BYTES(leadByte) \
-    ((uint8_t)(leadByte)<0xf0 ? \
-        ((uint8_t)(leadByte)>=0xc0)+((uint8_t)(leadByte)>=0xe0) : \
-        (uint8_t)(leadByte)<0xfe ? 3+((uint8_t)(leadByte)>=0xf8)+((uint8_t)(leadByte)>=0xfc) : 0)
-
-/**
- * Counts the trail bytes for a UTF-8 lead byte of a valid UTF-8 sequence.
- * The maximum supported lead byte is 0xf4 corresponding to U+10FFFF.
- * leadByte might be evaluated multiple times.
- *
- * This is internal since it is not meant to be called directly by external clients;
- * however it is called by public macros in this file and thus must remain stable.
- *
- * @param leadByte The first byte of a UTF-8 sequence. Must be 0..0xff.
- * @internal
- */
-#define U8_COUNT_TRAIL_BYTES_UNSAFE(leadByte) \
-    (((leadByte)>=0xc0)+((leadByte)>=0xe0)+((leadByte)>=0xf0))
-
-/**
- * Mask a UTF-8 lead byte, leave only the lower bits that form part of the code point value.
- *
- * This is internal since it is not meant to be called directly by external clients;
- * however it is called by public macros in this file and thus must remain stable.
- * @internal
- */
-#define U8_MASK_LEAD_BYTE(leadByte, countTrailBytes) ((leadByte)&=(1<<(6-(countTrailBytes)))-1)
-
-/**
- * Function for handling "next code point" with error-checking.
- *
- * This is internal since it is not meant to be called directly by external clients;
- * however it is U_STABLE (not U_INTERNAL) since it is called by public macros in this
- * file and thus must remain stable, and should not be hidden when other internal
- * functions are hidden (otherwise public macros would fail to compile).
- * @internal
- */
-U_STABLE UChar32 U_EXPORT2
-utf8_nextCharSafeBody(const uint8_t *s, int32_t *pi, int32_t length, UChar32 c, UBool strict);
-
-/**
- * Function for handling "append code point" with error-checking.
- *
- * This is internal since it is not meant to be called directly by external clients;
- * however it is U_STABLE (not U_INTERNAL) since it is called by public macros in this
- * file and thus must remain stable, and should not be hidden when other internal
- * functions are hidden (otherwise public macros would fail to compile).
- * @internal
- */
-U_STABLE int32_t U_EXPORT2
-utf8_appendCharSafeBody(uint8_t *s, int32_t i, int32_t length, UChar32 c, UBool *pIsError);
-
-/**
- * Function for handling "previous code point" with error-checking.
- *
- * This is internal since it is not meant to be called directly by external clients;
- * however it is U_STABLE (not U_INTERNAL) since it is called by public macros in this
- * file and thus must remain stable, and should not be hidden when other internal
- * functions are hidden (otherwise public macros would fail to compile).
- * @internal
- */
-U_STABLE UChar32 U_EXPORT2
-utf8_prevCharSafeBody(const uint8_t *s, int32_t start, int32_t *pi, UChar32 c, UBool strict);
-
-/**
- * Function for handling "skip backward one code point" with error-checking.
- *
- * This is internal since it is not meant to be called directly by external clients;
- * however it is U_STABLE (not U_INTERNAL) since it is called by public macros in this
- * file and thus must remain stable, and should not be hidden when other internal
- * functions are hidden (otherwise public macros would fail to compile).
- * @internal
- */
-U_STABLE int32_t U_EXPORT2
-utf8_back1SafeBody(const uint8_t *s, int32_t start, int32_t i);
-
-/* single-code point definitions -------------------------------------------- */
-
-/**
- * Does this code unit (byte) encode a code point by itself (US-ASCII 0..0x7f)?
- * @param c 8-bit code unit (byte)
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U8_IS_SINGLE(c) (((c)&0x80)==0)
-
-/**
- * Is this code unit (byte) a UTF-8 lead byte?
- * @param c 8-bit code unit (byte)
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U8_IS_LEAD(c) ((uint8_t)((c)-0xc0)<0x3e)
-
-/**
- * Is this code unit (byte) a UTF-8 trail byte?
- * @param c 8-bit code unit (byte)
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define U8_IS_TRAIL(c) (((c)&0xc0)==0x80)
-
-/**
- * How many code units (bytes) are used for the UTF-8 encoding
- * of this Unicode code point?
- * @param c 32-bit code point
- * @return 1..4, or 0 if c is a surrogate or not a Unicode code point
- * @stable ICU 2.4
- */
-#define U8_LENGTH(c) \
-    ((uint32_t)(c)<=0x7f ? 1 : \
-        ((uint32_t)(c)<=0x7ff ? 2 : \
-            ((uint32_t)(c)<=0xd7ff ? 3 : \
-                ((uint32_t)(c)<=0xdfff || (uint32_t)(c)>0x10ffff ? 0 : \
-                    ((uint32_t)(c)<=0xffff ? 3 : 4)\
-                ) \
-            ) \
-        ) \
-    )
-
-/**
- * The maximum number of UTF-8 code units (bytes) per Unicode code point (U+0000..U+10ffff).
- * @return 4
- * @stable ICU 2.4
- */
-#define U8_MAX_LENGTH 4
-
-/**
- * Get a code point from a string at a random-access offset,
- * without changing the offset.
- * The offset may point to either the lead byte or one of the trail bytes
- * for a code point, in which case the macro will read all of the bytes
- * for the code point.
- * The result is undefined if the offset points to an illegal UTF-8
- * byte sequence.
- * Iteration through a string is more efficient with U8_NEXT_UNSAFE or U8_NEXT.
- *
- * @param s const uint8_t * string
- * @param i string offset
- * @param c output UChar32 variable
- * @see U8_GET
- * @stable ICU 2.4
- */
-#define U8_GET_UNSAFE(s, i, c) { \
-    int32_t _u8_get_unsafe_index=(int32_t)(i); \
-    U8_SET_CP_START_UNSAFE(s, _u8_get_unsafe_index); \
-    U8_NEXT_UNSAFE(s, _u8_get_unsafe_index, c); \
-}
-
-/**
- * Get a code point from a string at a random-access offset,
- * without changing the offset.
- * The offset may point to either the lead byte or one of the trail bytes
- * for a code point, in which case the macro will read all of the bytes
- * for the code point.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * If the offset points to an illegal UTF-8 byte sequence, then
- * c is set to a negative value.
- * Iteration through a string is more efficient with U8_NEXT_UNSAFE or U8_NEXT.
- *
- * @param s const uint8_t * string
- * @param start int32_t starting string offset
- * @param i int32_t string offset, must be start<=i=0x80) { \
-        if((c)<0xe0) { \
-            (c)=(((c)&0x1f)<<6)|((s)[(i)++]&0x3f); \
-        } else if((c)<0xf0) { \
-            /* no need for (c&0xf) because the upper bits are truncated after <<12 in the cast to (UChar) */ \
-            (c)=(UChar)(((c)<<12)|(((s)[i]&0x3f)<<6)|((s)[(i)+1]&0x3f)); \
-            (i)+=2; \
-        } else { \
-            (c)=(((c)&7)<<18)|(((s)[i]&0x3f)<<12)|(((s)[(i)+1]&0x3f)<<6)|((s)[(i)+2]&0x3f); \
-            (i)+=3; \
-        } \
-    } \
-}
-
-/**
- * Get a code point from a string at a code point boundary offset,
- * and advance the offset to the next code point boundary.
- * (Post-incrementing forward iteration.)
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * The offset may point to the lead byte of a multi-byte sequence,
- * in which case the macro will read the whole sequence.
- * If the offset points to a trail byte or an illegal UTF-8 sequence, then
- * c is set to a negative value.
- *
- * @param s const uint8_t * string
- * @param i int32_t string offset, must be i=0x80) { \
-        uint8_t __t1, __t2; \
-        if( /* handle U+1000..U+CFFF inline */ \
-            (0xe0<(c) && (c)<=0xec) && \
-            (((i)+1)<(length) || (length)<0) && \
-            (__t1=(uint8_t)((s)[i]-0x80))<=0x3f && \
-            (__t2=(uint8_t)((s)[(i)+1]-0x80))<= 0x3f \
-        ) { \
-            /* no need for (c&0xf) because the upper bits are truncated after <<12 in the cast to (UChar) */ \
-            (c)=(UChar)(((c)<<12)|(__t1<<6)|__t2); \
-            (i)+=2; \
-        } else if( /* handle U+0080..U+07FF inline */ \
-            ((c)<0xe0 && (c)>=0xc2) && \
-            ((i)!=(length)) && \
-            (__t1=(uint8_t)((s)[i]-0x80))<=0x3f \
-        ) { \
-            (c)=(((c)&0x1f)<<6)|__t1; \
-            ++(i); \
-        } else { \
-            /* function call for "complicated" and error cases */ \
-            (c)=utf8_nextCharSafeBody((const uint8_t *)s, &(i), (length), c, -1); \
-        } \
-    } \
-}
-
-/**
- * Get a code point from a string at a code point boundary offset,
- * and advance the offset to the next code point boundary.
- * (Post-incrementing forward iteration.)
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * The offset may point to the lead byte of a multi-byte sequence,
- * in which case the macro will read the whole sequence.
- * If the offset points to a trail byte or an illegal UTF-8 sequence, then
- * c is set to U+FFFD.
- *
- * This macro does not distinguish between a real U+FFFD in the text
- * and U+FFFD returned for an ill-formed sequence.
- * Use U8_NEXT() if that distinction is important.
- *
- * @param s const uint8_t * string
- * @param i int32_t string offset, must be i=0x80) { \
-        uint8_t __t1, __t2; \
-        if( /* handle U+1000..U+CFFF inline */ \
-            (0xe0<(c) && (c)<=0xec) && \
-            (((i)+1)<(length) || (length)<0) && \
-            (__t1=(uint8_t)((s)[i]-0x80))<=0x3f && \
-            (__t2=(uint8_t)((s)[(i)+1]-0x80))<= 0x3f \
-        ) { \
-            /* no need for (c&0xf) because the upper bits are truncated after <<12 in the cast to (UChar) */ \
-            (c)=(UChar)(((c)<<12)|(__t1<<6)|__t2); \
-            (i)+=2; \
-        } else if( /* handle U+0080..U+07FF inline */ \
-            ((c)<0xe0 && (c)>=0xc2) && \
-            ((i)!=(length)) && \
-            (__t1=(uint8_t)((s)[i]-0x80))<=0x3f \
-        ) { \
-            (c)=(((c)&0x1f)<<6)|__t1; \
-            ++(i); \
-        } else { \
-            /* function call for "complicated" and error cases */ \
-            (c)=utf8_nextCharSafeBody((const uint8_t *)s, &(i), (length), c, -3); \
-        } \
-    } \
-}
-
-/**
- * Append a code point to a string, overwriting 1 to 4 bytes.
- * The offset points to the current end of the string contents
- * and is advanced (post-increment).
- * "Unsafe" macro, assumes a valid code point and sufficient space in the string.
- * Otherwise, the result is undefined.
- *
- * @param s const uint8_t * string buffer
- * @param i string offset
- * @param c code point to append
- * @see U8_APPEND
- * @stable ICU 2.4
- */
-#define U8_APPEND_UNSAFE(s, i, c) { \
-    if((uint32_t)(c)<=0x7f) { \
-        (s)[(i)++]=(uint8_t)(c); \
-    } else { \
-        if((uint32_t)(c)<=0x7ff) { \
-            (s)[(i)++]=(uint8_t)(((c)>>6)|0xc0); \
-        } else { \
-            if((uint32_t)(c)<=0xffff) { \
-                (s)[(i)++]=(uint8_t)(((c)>>12)|0xe0); \
-            } else { \
-                (s)[(i)++]=(uint8_t)(((c)>>18)|0xf0); \
-                (s)[(i)++]=(uint8_t)((((c)>>12)&0x3f)|0x80); \
-            } \
-            (s)[(i)++]=(uint8_t)((((c)>>6)&0x3f)|0x80); \
-        } \
-        (s)[(i)++]=(uint8_t)(((c)&0x3f)|0x80); \
-    } \
-}
-
-/**
- * Append a code point to a string, overwriting 1 to 4 bytes.
- * The offset points to the current end of the string contents
- * and is advanced (post-increment).
- * "Safe" macro, checks for a valid code point.
- * If a non-ASCII code point is written, checks for sufficient space in the string.
- * If the code point is not valid or trail bytes do not fit,
- * then isError is set to TRUE.
- *
- * @param s const uint8_t * string buffer
- * @param i int32_t string offset, must be i>6)|0xc0); \
-        (s)[(i)++]=(uint8_t)(((c)&0x3f)|0x80); \
-    } else if((uint32_t)(c)<=0xd7ff && (i)+2<(capacity)) { \
-        (s)[(i)++]=(uint8_t)(((c)>>12)|0xe0); \
-        (s)[(i)++]=(uint8_t)((((c)>>6)&0x3f)|0x80); \
-        (s)[(i)++]=(uint8_t)(((c)&0x3f)|0x80); \
-    } else { \
-        (i)=utf8_appendCharSafeBody(s, (i), (capacity), c, &(isError)); \
-    } \
-}
-
-/**
- * Advance the string offset from one code point boundary to the next.
- * (Post-incrementing iteration.)
- * "Unsafe" macro, assumes well-formed UTF-8.
- *
- * @param s const uint8_t * string
- * @param i string offset
- * @see U8_FWD_1
- * @stable ICU 2.4
- */
-#define U8_FWD_1_UNSAFE(s, i) { \
-    (i)+=1+U8_COUNT_TRAIL_BYTES_UNSAFE((uint8_t)(s)[i]); \
-}
-
-/**
- * Advance the string offset from one code point boundary to the next.
- * (Post-incrementing iteration.)
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * @param s const uint8_t * string
- * @param i int32_t string offset, must be i(length) && (length)>=0) { \
-            __count=(uint8_t)((length)-(i)); \
-        } \
-        while(__count>0 && U8_IS_TRAIL((s)[i])) { \
-            ++(i); \
-            --__count; \
-        } \
-    } \
-}
-
-/**
- * Advance the string offset from one code point boundary to the n-th next one,
- * i.e., move forward by n code points.
- * (Post-incrementing iteration.)
- * "Unsafe" macro, assumes well-formed UTF-8.
- *
- * @param s const uint8_t * string
- * @param i string offset
- * @param n number of code points to skip
- * @see U8_FWD_N
- * @stable ICU 2.4
- */
-#define U8_FWD_N_UNSAFE(s, i, n) { \
-    int32_t __N=(n); \
-    while(__N>0) { \
-        U8_FWD_1_UNSAFE(s, i); \
-        --__N; \
-    } \
-}
-
-/**
- * Advance the string offset from one code point boundary to the n-th next one,
- * i.e., move forward by n code points.
- * (Post-incrementing iteration.)
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * @param s const uint8_t * string
- * @param i int32_t string offset, must be i0 && ((i)<(length) || ((length)<0 && (s)[i]!=0))) { \
-        U8_FWD_1(s, i, length); \
-        --__N; \
-    } \
-}
-
-/**
- * Adjust a random-access offset to a code point boundary
- * at the start of a code point.
- * If the offset points to a UTF-8 trail byte,
- * then the offset is moved backward to the corresponding lead byte.
- * Otherwise, it is not modified.
- * "Unsafe" macro, assumes well-formed UTF-8.
- *
- * @param s const uint8_t * string
- * @param i string offset
- * @see U8_SET_CP_START
- * @stable ICU 2.4
- */
-#define U8_SET_CP_START_UNSAFE(s, i) { \
-    while(U8_IS_TRAIL((s)[i])) { --(i); } \
-}
-
-/**
- * Adjust a random-access offset to a code point boundary
- * at the start of a code point.
- * If the offset points to a UTF-8 trail byte,
- * then the offset is moved backward to the corresponding lead byte.
- * Otherwise, it is not modified.
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * @param s const uint8_t * string
- * @param start int32_t starting string offset (usually 0)
- * @param i int32_t string offset, must be start<=i
- * @see U8_SET_CP_START_UNSAFE
- * @stable ICU 2.4
- */
-#define U8_SET_CP_START(s, start, i) { \
-    if(U8_IS_TRAIL((s)[(i)])) { \
-        (i)=utf8_back1SafeBody(s, start, (i)); \
-    } \
-}
-
-/* definitions with backward iteration -------------------------------------- */
-
-/**
- * Move the string offset from one code point boundary to the previous one
- * and get the code point between them.
- * (Pre-decrementing backward iteration.)
- * "Unsafe" macro, assumes well-formed UTF-8.
- *
- * The input offset may be the same as the string length.
- * If the offset is behind a multi-byte sequence, then the macro will read
- * the whole sequence.
- * If the offset is behind a lead byte, then that itself
- * will be returned as the code point.
- * The result is undefined if the offset is behind an illegal UTF-8 sequence.
- *
- * @param s const uint8_t * string
- * @param i string offset
- * @param c output UChar32 variable
- * @see U8_PREV
- * @stable ICU 2.4
- */
-#define U8_PREV_UNSAFE(s, i, c) { \
-    (c)=(uint8_t)(s)[--(i)]; \
-    if(U8_IS_TRAIL(c)) { \
-        uint8_t __b, __count=1, __shift=6; \
-\
-        /* c is a trail byte */ \
-        (c)&=0x3f; \
-        for(;;) { \
-            __b=(uint8_t)(s)[--(i)]; \
-            if(__b>=0xc0) { \
-                U8_MASK_LEAD_BYTE(__b, __count); \
-                (c)|=(UChar32)__b<<__shift; \
-                break; \
-            } else { \
-                (c)|=(UChar32)(__b&0x3f)<<__shift; \
-                ++__count; \
-                __shift+=6; \
-            } \
-        } \
-    } \
-}
-
-/**
- * Move the string offset from one code point boundary to the previous one
- * and get the code point between them.
- * (Pre-decrementing backward iteration.)
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * The input offset may be the same as the string length.
- * If the offset is behind a multi-byte sequence, then the macro will read
- * the whole sequence.
- * If the offset is behind a lead byte, then that itself
- * will be returned as the code point.
- * If the offset is behind an illegal UTF-8 sequence, then c is set to a negative value.
- *
- * @param s const uint8_t * string
- * @param start int32_t starting string offset (usually 0)
- * @param i int32_t string offset, must be start=0x80) { \
-        (c)=utf8_prevCharSafeBody((const uint8_t *)s, start, &(i), c, -1); \
-    } \
-}
-
-/**
- * Move the string offset from one code point boundary to the previous one
- * and get the code point between them.
- * (Pre-decrementing backward iteration.)
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * The input offset may be the same as the string length.
- * If the offset is behind a multi-byte sequence, then the macro will read
- * the whole sequence.
- * If the offset is behind a lead byte, then that itself
- * will be returned as the code point.
- * If the offset is behind an illegal UTF-8 sequence, then c is set to U+FFFD.
- *
- * This macro does not distinguish between a real U+FFFD in the text
- * and U+FFFD returned for an ill-formed sequence.
- * Use U8_PREV() if that distinction is important.
- *
- * @param s const uint8_t * string
- * @param start int32_t starting string offset (usually 0)
- * @param i int32_t string offset, must be start=0x80) { \
-        (c)=utf8_prevCharSafeBody((const uint8_t *)s, start, &(i), c, -3); \
-    } \
-}
-
-/**
- * Move the string offset from one code point boundary to the previous one.
- * (Pre-decrementing backward iteration.)
- * The input offset may be the same as the string length.
- * "Unsafe" macro, assumes well-formed UTF-8.
- *
- * @param s const uint8_t * string
- * @param i string offset
- * @see U8_BACK_1
- * @stable ICU 2.4
- */
-#define U8_BACK_1_UNSAFE(s, i) { \
-    while(U8_IS_TRAIL((s)[--(i)])) {} \
-}
-
-/**
- * Move the string offset from one code point boundary to the previous one.
- * (Pre-decrementing backward iteration.)
- * The input offset may be the same as the string length.
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * @param s const uint8_t * string
- * @param start int32_t starting string offset (usually 0)
- * @param i int32_t string offset, must be start0) { \
-        U8_BACK_1_UNSAFE(s, i); \
-        --__N; \
-    } \
-}
-
-/**
- * Move the string offset from one code point boundary to the n-th one before it,
- * i.e., move backward by n code points.
- * (Pre-decrementing backward iteration.)
- * The input offset may be the same as the string length.
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * @param s const uint8_t * string
- * @param start int32_t index of the start of the string
- * @param i int32_t string offset, must be start0 && (i)>(start)) { \
-        U8_BACK_1(s, start, i); \
-        --__N; \
-    } \
-}
-
-/**
- * Adjust a random-access offset to a code point boundary after a code point.
- * If the offset is behind a partial multi-byte sequence,
- * then the offset is incremented to behind the whole sequence.
- * Otherwise, it is not modified.
- * The input offset may be the same as the string length.
- * "Unsafe" macro, assumes well-formed UTF-8.
- *
- * @param s const uint8_t * string
- * @param i string offset
- * @see U8_SET_CP_LIMIT
- * @stable ICU 2.4
- */
-#define U8_SET_CP_LIMIT_UNSAFE(s, i) { \
-    U8_BACK_1_UNSAFE(s, i); \
-    U8_FWD_1_UNSAFE(s, i); \
-}
-
-/**
- * Adjust a random-access offset to a code point boundary after a code point.
- * If the offset is behind a partial multi-byte sequence,
- * then the offset is incremented to behind the whole sequence.
- * Otherwise, it is not modified.
- * The input offset may be the same as the string length.
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * The length can be negative for a NUL-terminated string.
- *
- * @param s const uint8_t * string
- * @param start int32_t starting string offset (usually 0)
- * @param i int32_t string offset, must be start<=i<=length
- * @param length int32_t string length
- * @see U8_SET_CP_LIMIT_UNSAFE
- * @stable ICU 2.4
- */
-#define U8_SET_CP_LIMIT(s, start, i, length) { \
-    if((start)<(i) && ((i)<(length) || (length)<0)) { \
-        U8_BACK_1(s, start, i); \
-        U8_FWD_1(s, i, length); \
-    } \
-}
-
-#endif
diff --git a/win32/include/spidermonkey/unicode/utf_old.h b/win32/include/spidermonkey/unicode/utf_old.h
deleted file mode 100755
index c7d5145a..00000000
--- a/win32/include/spidermonkey/unicode/utf_old.h
+++ /dev/null
@@ -1,1171 +0,0 @@
-// Copyright (C) 2016 and later: Unicode, Inc. and others.
-// License & terms of use: http://www.unicode.org/copyright.html
-/*
-*******************************************************************************
-*
-*   Copyright (C) 2002-2012, International Business Machines
-*   Corporation and others.  All Rights Reserved.
-*
-*******************************************************************************
-*   file name:  utf_old.h
-*   encoding:   US-ASCII
-*   tab size:   8 (not used)
-*   indentation:4
-*
-*   created on: 2002sep21
-*   created by: Markus W. Scherer
-*/
-
-/**
- * \file 
- * \brief C API: Deprecated macros for Unicode string handling
- */
-
-/**
- * 
- * The macros in utf_old.h are all deprecated and their use discouraged.
- * Some of the design principles behind the set of UTF macros
- * have changed or proved impractical.
- * Almost all of the old "UTF macros" are at least renamed.
- * If you are looking for a new equivalent to an old macro, please see the
- * comment at the old one.
- *
- * Brief summary of reasons for deprecation:
- * - Switch on UTF_SIZE (selection of UTF-8/16/32 default string processing)
- *   was impractical.
- * - Switch on UTF_SAFE etc. (selection of unsafe/safe/strict default string processing)
- *   was of little use and impractical.
- * - Whole classes of macros became obsolete outside of the UTF_SIZE/UTF_SAFE
- *   selection framework: UTF32_ macros (all trivial)
- *   and UTF_ default and intermediate macros (all aliases).
- * - The selection framework also caused many macro aliases.
- * - Change in Unicode standard: "irregular" sequences (3.0) became illegal (3.2).
- * - Change of language in Unicode standard:
- *   Growing distinction between internal x-bit Unicode strings and external UTF-x
- *   forms, with the former more lenient.
- *   Suggests renaming of UTF16_ macros to U16_.
- * - The prefix "UTF_" without a width number confused some users.
- * - "Safe" append macros needed the addition of an error indicator output.
- * - "Safe" UTF-8 macros used legitimate (if rarely used) code point values
- *   to indicate error conditions.
- * - The use of the "_CHAR" infix for code point operations confused some users.
- *
- * More details:
- *
- * Until ICU 2.2, utf.h theoretically allowed to choose among UTF-8/16/32
- * for string processing, and among unsafe/safe/strict default macros for that.
- *
- * It proved nearly impossible to write non-trivial, high-performance code
- * that is UTF-generic.
- * Unsafe default macros would be dangerous for default string processing,
- * and the main reason for the "strict" versions disappeared:
- * Between Unicode 3.0 and 3.2 all "irregular" UTF-8 sequences became illegal.
- * The only other conditions that "strict" checked for were non-characters,
- * which are valid during processing. Only during text input/output should they
- * be checked, and at that time other well-formedness checks may be
- * necessary or useful as well.
- * This can still be done by using U16_NEXT and U_IS_UNICODE_NONCHAR
- * or U_IS_UNICODE_CHAR.
- *
- * The old UTF8_..._SAFE macros also used some normal Unicode code points
- * to indicate malformed sequences.
- * The new UTF8_ macros without suffix use negative values instead.
- *
- * The entire contents of utf32.h was moved here without replacement
- * because all those macros were trivial and
- * were meaningful only in the framework of choosing the UTF size.
- *
- * See Jitterbug 2150 and its discussion on the ICU mailing list
- * in September 2002.
- *
- * 
- * - * Obsolete part of pre-ICU 2.4 utf.h file documentation: - * - *

The original concept for these files was for ICU to allow - * in principle to set which UTF (UTF-8/16/32) is used internally - * by defining UTF_SIZE to either 8, 16, or 32. utf.h would then define the UChar type - * accordingly. UTF-16 was the default.

- * - *

This concept has been abandoned. - * A lot of the ICU source code assumes UChar strings are in UTF-16. - * This is especially true for low-level code like - * conversion, normalization, and collation. - * The utf.h header enforces the default of UTF-16. - * The UTF-8 and UTF-32 macros remain for now for completeness and backward compatibility.

- * - *

Accordingly, utf.h defines UChar to be an unsigned 16-bit integer. If this matches wchar_t, then - * UChar is defined to be exactly wchar_t, otherwise uint16_t.

- * - *

UChar32 is defined to be a signed 32-bit integer (int32_t), large enough for a 21-bit - * Unicode code point (Unicode scalar value, 0..0x10ffff). - * Before ICU 2.4, the definition of UChar32 was similarly platform-dependent as - * the definition of UChar. For details see the documentation for UChar32 itself.

- * - *

utf.h also defines a number of C macros for handling single Unicode code points and - * for using UTF Unicode strings. It includes utf8.h, utf16.h, and utf32.h for the actual - * implementations of those macros and then aliases one set of them (for UTF-16) for general use. - * The UTF-specific macros have the UTF size in the macro name prefixes (UTF16_...), while - * the general alias macros always begin with UTF_...

- * - *

Many string operations can be done with or without error checking. - * Where such a distinction is useful, there are two versions of the macros, "unsafe" and "safe" - * ones with ..._UNSAFE and ..._SAFE suffixes. The unsafe macros are fast but may cause - * program failures if the strings are not well-formed. The safe macros have an additional, boolean - * parameter "strict". If strict is FALSE, then only illegal sequences are detected. - * Otherwise, irregular sequences and non-characters are detected as well (like single surrogates). - * Safe macros return special error code points for illegal/irregular sequences: - * Typically, U+ffff, or values that would result in a code unit sequence of the same length - * as the erroneous input sequence.
- * Note that _UNSAFE macros have fewer parameters: They do not have the strictness parameter, and - * they do not have start/length parameters for boundary checking.

- * - *

Here, the macros are aliased in two steps: - * In the first step, the UTF-specific macros with UTF16_ prefix and _UNSAFE and _SAFE suffixes are - * aliased according to the UTF_SIZE to macros with UTF_ prefix and the same suffixes and signatures. - * Then, in a second step, the default, general alias macros are set to use either the unsafe or - * the safe/not strict (default) or the safe/strict macro; - * these general macros do not have a strictness parameter.

- * - *

It is possible to change the default choice for the general alias macros to be unsafe, safe/not strict or safe/strict. - * The default is safe/not strict. It is not recommended to select the unsafe macros as the basis for - * Unicode string handling in ICU! To select this, define UTF_SAFE, UTF_STRICT, or UTF_UNSAFE.

- * - *

For general use, one should use the default, general macros with UTF_ prefix and no _SAFE/_UNSAFE suffix. - * Only in some cases it may be necessary to control the choice of macro directly and use a less generic alias. - * For example, if it can be assumed that a string is well-formed and the index will stay within the bounds, - * then the _UNSAFE version may be used. - * If a UTF-8 string is to be processed, then the macros with UTF8_ prefixes need to be used.

- * - *
- * - * @deprecated ICU 2.4. Use the macros in utf.h, utf16.h, utf8.h instead. - */ - -#ifndef __UTF_OLD_H__ -#define __UTF_OLD_H__ - -#ifndef U_HIDE_DEPRECATED_API - -#include "unicode/utf.h" -#include "unicode/utf8.h" -#include "unicode/utf16.h" - -/* Formerly utf.h, part 1 --------------------------------------------------- */ - -#ifdef U_USE_UTF_DEPRECATES -/** - * Unicode string and array offset and index type. - * ICU always counts Unicode code units (UChars) for - * string offsets, indexes, and lengths, not Unicode code points. - * - * @obsolete ICU 2.6. Use int32_t directly instead since this API will be removed in that release. - */ -typedef int32_t UTextOffset; -#endif - -/** Number of bits in a Unicode string code unit - ICU uses 16-bit Unicode. @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF_SIZE 16 - -/** - * The default choice for general Unicode string macros is to use the ..._SAFE macro implementations - * with strict=FALSE. - * - * @deprecated ICU 2.4. Obsolete, see utf_old.h. - */ -#define UTF_SAFE -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#undef UTF_UNSAFE -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#undef UTF_STRICT - -/** - * UTF8_ERROR_VALUE_1 and UTF8_ERROR_VALUE_2 are special error values for UTF-8, - * which need 1 or 2 bytes in UTF-8: - * \code - * U+0015 = NAK = Negative Acknowledge, C0 control character - * U+009f = highest C1 control character - * \endcode - * - * These are used by UTF8_..._SAFE macros so that they can return an error value - * that needs the same number of code units (bytes) as were seen by - * a macro. They should be tested with UTF_IS_ERROR() or UTF_IS_VALID(). - * - * @deprecated ICU 2.4. Obsolete, see utf_old.h. - */ -#define UTF8_ERROR_VALUE_1 0x15 - -/** - * See documentation on UTF8_ERROR_VALUE_1 for details. - * - * @deprecated ICU 2.4. Obsolete, see utf_old.h. - */ -#define UTF8_ERROR_VALUE_2 0x9f - -/** - * Error value for all UTFs. This code point value will be set by macros with error - * checking if an error is detected. - * - * @deprecated ICU 2.4. Obsolete, see utf_old.h. - */ -#define UTF_ERROR_VALUE 0xffff - -/** - * Is a given 32-bit code an error value - * as returned by one of the macros for any UTF? - * - * @deprecated ICU 2.4. Obsolete, see utf_old.h. - */ -#define UTF_IS_ERROR(c) \ - (((c)&0xfffe)==0xfffe || (c)==UTF8_ERROR_VALUE_1 || (c)==UTF8_ERROR_VALUE_2) - -/** - * This is a combined macro: Is c a valid Unicode value _and_ not an error code? - * - * @deprecated ICU 2.4. Obsolete, see utf_old.h. - */ -#define UTF_IS_VALID(c) \ - (UTF_IS_UNICODE_CHAR(c) && \ - (c)!=UTF8_ERROR_VALUE_1 && (c)!=UTF8_ERROR_VALUE_2) - -/** - * Is this code unit or code point a surrogate (U+d800..U+dfff)? - * @deprecated ICU 2.4. Renamed to U_IS_SURROGATE and U16_IS_SURROGATE, see utf_old.h. - */ -#define UTF_IS_SURROGATE(uchar) (((uchar)&0xfffff800)==0xd800) - -/** - * Is a given 32-bit code point a Unicode noncharacter? - * - * @deprecated ICU 2.4. Renamed to U_IS_UNICODE_NONCHAR, see utf_old.h. - */ -#define UTF_IS_UNICODE_NONCHAR(c) \ - ((c)>=0xfdd0 && \ - ((uint32_t)(c)<=0xfdef || ((c)&0xfffe)==0xfffe) && \ - (uint32_t)(c)<=0x10ffff) - -/** - * Is a given 32-bit value a Unicode code point value (0..U+10ffff) - * that can be assigned a character? - * - * Code points that are not characters include: - * - single surrogate code points (U+d800..U+dfff, 2048 code points) - * - the last two code points on each plane (U+__fffe and U+__ffff, 34 code points) - * - U+fdd0..U+fdef (new with Unicode 3.1, 32 code points) - * - the highest Unicode code point value is U+10ffff - * - * This means that all code points below U+d800 are character code points, - * and that boundary is tested first for performance. - * - * @deprecated ICU 2.4. Renamed to U_IS_UNICODE_CHAR, see utf_old.h. - */ -#define UTF_IS_UNICODE_CHAR(c) \ - ((uint32_t)(c)<0xd800 || \ - ((uint32_t)(c)>0xdfff && \ - (uint32_t)(c)<=0x10ffff && \ - !UTF_IS_UNICODE_NONCHAR(c))) - -/* Formerly utf8.h ---------------------------------------------------------- */ - -/** - * Count the trail bytes for a UTF-8 lead byte. - * @deprecated ICU 2.4. Renamed to U8_COUNT_TRAIL_BYTES, see utf_old.h. - */ -#define UTF8_COUNT_TRAIL_BYTES(leadByte) (utf8_countTrailBytes[(uint8_t)leadByte]) - -/** - * Mask a UTF-8 lead byte, leave only the lower bits that form part of the code point value. - * @deprecated ICU 2.4. Renamed to U8_MASK_LEAD_BYTE, see utf_old.h. - */ -#define UTF8_MASK_LEAD_BYTE(leadByte, countTrailBytes) ((leadByte)&=(1<<(6-(countTrailBytes)))-1) - -/** Is this this code point a single code unit (byte)? @deprecated ICU 2.4. Renamed to U8_IS_SINGLE, see utf_old.h. */ -#define UTF8_IS_SINGLE(uchar) (((uchar)&0x80)==0) -/** Is this this code unit the lead code unit (byte) of a code point? @deprecated ICU 2.4. Renamed to U8_IS_LEAD, see utf_old.h. */ -#define UTF8_IS_LEAD(uchar) ((uint8_t)((uchar)-0xc0)<0x3e) -/** Is this this code unit a trailing code unit (byte) of a code point? @deprecated ICU 2.4. Renamed to U8_IS_TRAIL, see utf_old.h. */ -#define UTF8_IS_TRAIL(uchar) (((uchar)&0xc0)==0x80) - -/** Does this scalar Unicode value need multiple code units for storage? @deprecated ICU 2.4. Use U8_LENGTH or test ((uint32_t)(c)>0x7f) instead, see utf_old.h. */ -#define UTF8_NEED_MULTIPLE_UCHAR(c) ((uint32_t)(c)>0x7f) - -/** - * Given the lead character, how many bytes are taken by this code point. - * ICU does not deal with code points >0x10ffff - * unless necessary for advancing in the byte stream. - * - * These length macros take into account that for values >0x10ffff - * the UTF8_APPEND_CHAR_SAFE macros would write the error code point 0xffff - * with 3 bytes. - * Code point comparisons need to be in uint32_t because UChar32 - * may be a signed type, and negative values must be recognized. - * - * @deprecated ICU 2.4. Use U8_LENGTH instead, see utf.h. - */ -#if 1 -# define UTF8_CHAR_LENGTH(c) \ - ((uint32_t)(c)<=0x7f ? 1 : \ - ((uint32_t)(c)<=0x7ff ? 2 : \ - ((uint32_t)((c)-0x10000)>0xfffff ? 3 : 4) \ - ) \ - ) -#else -# define UTF8_CHAR_LENGTH(c) \ - ((uint32_t)(c)<=0x7f ? 1 : \ - ((uint32_t)(c)<=0x7ff ? 2 : \ - ((uint32_t)(c)<=0xffff ? 3 : \ - ((uint32_t)(c)<=0x10ffff ? 4 : \ - ((uint32_t)(c)<=0x3ffffff ? 5 : \ - ((uint32_t)(c)<=0x7fffffff ? 6 : 3) \ - ) \ - ) \ - ) \ - ) \ - ) -#endif - -/** The maximum number of bytes per code point. @deprecated ICU 2.4. Renamed to U8_MAX_LENGTH, see utf_old.h. */ -#define UTF8_MAX_CHAR_LENGTH 4 - -/** Average number of code units compared to UTF-16. @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF8_ARRAY_SIZE(size) ((5*(size))/2) - -/** @deprecated ICU 2.4. Renamed to U8_GET_UNSAFE, see utf_old.h. */ -#define UTF8_GET_CHAR_UNSAFE(s, i, c) { \ - int32_t _utf8_get_char_unsafe_index=(int32_t)(i); \ - UTF8_SET_CHAR_START_UNSAFE(s, _utf8_get_char_unsafe_index); \ - UTF8_NEXT_CHAR_UNSAFE(s, _utf8_get_char_unsafe_index, c); \ -} - -/** @deprecated ICU 2.4. Use U8_GET instead, see utf_old.h. */ -#define UTF8_GET_CHAR_SAFE(s, start, i, length, c, strict) { \ - int32_t _utf8_get_char_safe_index=(int32_t)(i); \ - UTF8_SET_CHAR_START_SAFE(s, start, _utf8_get_char_safe_index); \ - UTF8_NEXT_CHAR_SAFE(s, _utf8_get_char_safe_index, length, c, strict); \ -} - -/** @deprecated ICU 2.4. Renamed to U8_NEXT_UNSAFE, see utf_old.h. */ -#define UTF8_NEXT_CHAR_UNSAFE(s, i, c) { \ - (c)=(s)[(i)++]; \ - if((uint8_t)((c)-0xc0)<0x35) { \ - uint8_t __count=UTF8_COUNT_TRAIL_BYTES(c); \ - UTF8_MASK_LEAD_BYTE(c, __count); \ - switch(__count) { \ - /* each following branch falls through to the next one */ \ - case 3: \ - (c)=((c)<<6)|((s)[(i)++]&0x3f); \ - case 2: \ - (c)=((c)<<6)|((s)[(i)++]&0x3f); \ - case 1: \ - (c)=((c)<<6)|((s)[(i)++]&0x3f); \ - /* no other branches to optimize switch() */ \ - break; \ - } \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U8_APPEND_UNSAFE, see utf_old.h. */ -#define UTF8_APPEND_CHAR_UNSAFE(s, i, c) { \ - if((uint32_t)(c)<=0x7f) { \ - (s)[(i)++]=(uint8_t)(c); \ - } else { \ - if((uint32_t)(c)<=0x7ff) { \ - (s)[(i)++]=(uint8_t)(((c)>>6)|0xc0); \ - } else { \ - if((uint32_t)(c)<=0xffff) { \ - (s)[(i)++]=(uint8_t)(((c)>>12)|0xe0); \ - } else { \ - (s)[(i)++]=(uint8_t)(((c)>>18)|0xf0); \ - (s)[(i)++]=(uint8_t)((((c)>>12)&0x3f)|0x80); \ - } \ - (s)[(i)++]=(uint8_t)((((c)>>6)&0x3f)|0x80); \ - } \ - (s)[(i)++]=(uint8_t)(((c)&0x3f)|0x80); \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U8_FWD_1_UNSAFE, see utf_old.h. */ -#define UTF8_FWD_1_UNSAFE(s, i) { \ - (i)+=1+UTF8_COUNT_TRAIL_BYTES((s)[i]); \ -} - -/** @deprecated ICU 2.4. Renamed to U8_FWD_N_UNSAFE, see utf_old.h. */ -#define UTF8_FWD_N_UNSAFE(s, i, n) { \ - int32_t __N=(n); \ - while(__N>0) { \ - UTF8_FWD_1_UNSAFE(s, i); \ - --__N; \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U8_SET_CP_START_UNSAFE, see utf_old.h. */ -#define UTF8_SET_CHAR_START_UNSAFE(s, i) { \ - while(UTF8_IS_TRAIL((s)[i])) { --(i); } \ -} - -/** @deprecated ICU 2.4. Use U8_NEXT instead, see utf_old.h. */ -#define UTF8_NEXT_CHAR_SAFE(s, i, length, c, strict) { \ - (c)=(s)[(i)++]; \ - if((c)>=0x80) { \ - if(UTF8_IS_LEAD(c)) { \ - (c)=utf8_nextCharSafeBody(s, &(i), (int32_t)(length), c, strict); \ - } else { \ - (c)=UTF8_ERROR_VALUE_1; \ - } \ - } \ -} - -/** @deprecated ICU 2.4. Use U8_APPEND instead, see utf_old.h. */ -#define UTF8_APPEND_CHAR_SAFE(s, i, length, c) { \ - if((uint32_t)(c)<=0x7f) { \ - (s)[(i)++]=(uint8_t)(c); \ - } else { \ - (i)=utf8_appendCharSafeBody(s, (int32_t)(i), (int32_t)(length), c, NULL); \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U8_FWD_1, see utf_old.h. */ -#define UTF8_FWD_1_SAFE(s, i, length) U8_FWD_1(s, i, length) - -/** @deprecated ICU 2.4. Renamed to U8_FWD_N, see utf_old.h. */ -#define UTF8_FWD_N_SAFE(s, i, length, n) U8_FWD_N(s, i, length, n) - -/** @deprecated ICU 2.4. Renamed to U8_SET_CP_START, see utf_old.h. */ -#define UTF8_SET_CHAR_START_SAFE(s, start, i) U8_SET_CP_START(s, start, i) - -/** @deprecated ICU 2.4. Renamed to U8_PREV_UNSAFE, see utf_old.h. */ -#define UTF8_PREV_CHAR_UNSAFE(s, i, c) { \ - (c)=(s)[--(i)]; \ - if(UTF8_IS_TRAIL(c)) { \ - uint8_t __b, __count=1, __shift=6; \ -\ - /* c is a trail byte */ \ - (c)&=0x3f; \ - for(;;) { \ - __b=(s)[--(i)]; \ - if(__b>=0xc0) { \ - UTF8_MASK_LEAD_BYTE(__b, __count); \ - (c)|=(UChar32)__b<<__shift; \ - break; \ - } else { \ - (c)|=(UChar32)(__b&0x3f)<<__shift; \ - ++__count; \ - __shift+=6; \ - } \ - } \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U8_BACK_1_UNSAFE, see utf_old.h. */ -#define UTF8_BACK_1_UNSAFE(s, i) { \ - while(UTF8_IS_TRAIL((s)[--(i)])) {} \ -} - -/** @deprecated ICU 2.4. Renamed to U8_BACK_N_UNSAFE, see utf_old.h. */ -#define UTF8_BACK_N_UNSAFE(s, i, n) { \ - int32_t __N=(n); \ - while(__N>0) { \ - UTF8_BACK_1_UNSAFE(s, i); \ - --__N; \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U8_SET_CP_LIMIT_UNSAFE, see utf_old.h. */ -#define UTF8_SET_CHAR_LIMIT_UNSAFE(s, i) { \ - UTF8_BACK_1_UNSAFE(s, i); \ - UTF8_FWD_1_UNSAFE(s, i); \ -} - -/** @deprecated ICU 2.4. Use U8_PREV instead, see utf_old.h. */ -#define UTF8_PREV_CHAR_SAFE(s, start, i, c, strict) { \ - (c)=(s)[--(i)]; \ - if((c)>=0x80) { \ - if((c)<=0xbf) { \ - (c)=utf8_prevCharSafeBody(s, start, &(i), c, strict); \ - } else { \ - (c)=UTF8_ERROR_VALUE_1; \ - } \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U8_BACK_1, see utf_old.h. */ -#define UTF8_BACK_1_SAFE(s, start, i) U8_BACK_1(s, start, i) - -/** @deprecated ICU 2.4. Renamed to U8_BACK_N, see utf_old.h. */ -#define UTF8_BACK_N_SAFE(s, start, i, n) U8_BACK_N(s, start, i, n) - -/** @deprecated ICU 2.4. Renamed to U8_SET_CP_LIMIT, see utf_old.h. */ -#define UTF8_SET_CHAR_LIMIT_SAFE(s, start, i, length) U8_SET_CP_LIMIT(s, start, i, length) - -/* Formerly utf16.h --------------------------------------------------------- */ - -/** Is uchar a first/lead surrogate? @deprecated ICU 2.4. Renamed to U_IS_LEAD and U16_IS_LEAD, see utf_old.h. */ -#define UTF_IS_FIRST_SURROGATE(uchar) (((uchar)&0xfffffc00)==0xd800) - -/** Is uchar a second/trail surrogate? @deprecated ICU 2.4. Renamed to U_IS_TRAIL and U16_IS_TRAIL, see utf_old.h. */ -#define UTF_IS_SECOND_SURROGATE(uchar) (((uchar)&0xfffffc00)==0xdc00) - -/** Assuming c is a surrogate, is it a first/lead surrogate? @deprecated ICU 2.4. Renamed to U_IS_SURROGATE_LEAD and U16_IS_SURROGATE_LEAD, see utf_old.h. */ -#define UTF_IS_SURROGATE_FIRST(c) (((c)&0x400)==0) - -/** Helper constant for UTF16_GET_PAIR_VALUE. @deprecated ICU 2.4. Renamed to U16_SURROGATE_OFFSET, see utf_old.h. */ -#define UTF_SURROGATE_OFFSET ((0xd800<<10UL)+0xdc00-0x10000) - -/** Get the UTF-32 value from the surrogate code units. @deprecated ICU 2.4. Renamed to U16_GET_SUPPLEMENTARY, see utf_old.h. */ -#define UTF16_GET_PAIR_VALUE(first, second) \ - (((first)<<10UL)+(second)-UTF_SURROGATE_OFFSET) - -/** @deprecated ICU 2.4. Renamed to U16_LEAD, see utf_old.h. */ -#define UTF_FIRST_SURROGATE(supplementary) (UChar)(((supplementary)>>10)+0xd7c0) - -/** @deprecated ICU 2.4. Renamed to U16_TRAIL, see utf_old.h. */ -#define UTF_SECOND_SURROGATE(supplementary) (UChar)(((supplementary)&0x3ff)|0xdc00) - -/** @deprecated ICU 2.4. Renamed to U16_LEAD, see utf_old.h. */ -#define UTF16_LEAD(supplementary) UTF_FIRST_SURROGATE(supplementary) - -/** @deprecated ICU 2.4. Renamed to U16_TRAIL, see utf_old.h. */ -#define UTF16_TRAIL(supplementary) UTF_SECOND_SURROGATE(supplementary) - -/** @deprecated ICU 2.4. Renamed to U16_IS_SINGLE, see utf_old.h. */ -#define UTF16_IS_SINGLE(uchar) !UTF_IS_SURROGATE(uchar) - -/** @deprecated ICU 2.4. Renamed to U16_IS_LEAD, see utf_old.h. */ -#define UTF16_IS_LEAD(uchar) UTF_IS_FIRST_SURROGATE(uchar) - -/** @deprecated ICU 2.4. Renamed to U16_IS_TRAIL, see utf_old.h. */ -#define UTF16_IS_TRAIL(uchar) UTF_IS_SECOND_SURROGATE(uchar) - -/** Does this scalar Unicode value need multiple code units for storage? @deprecated ICU 2.4. Use U16_LENGTH or test ((uint32_t)(c)>0xffff) instead, see utf_old.h. */ -#define UTF16_NEED_MULTIPLE_UCHAR(c) ((uint32_t)(c)>0xffff) - -/** @deprecated ICU 2.4. Renamed to U16_LENGTH, see utf_old.h. */ -#define UTF16_CHAR_LENGTH(c) ((uint32_t)(c)<=0xffff ? 1 : 2) - -/** @deprecated ICU 2.4. Renamed to U16_MAX_LENGTH, see utf_old.h. */ -#define UTF16_MAX_CHAR_LENGTH 2 - -/** Average number of code units compared to UTF-16. @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF16_ARRAY_SIZE(size) (size) - -/** - * Get a single code point from an offset that points to any - * of the code units that belong to that code point. - * Assume 0<=i=(start) && UTF_IS_FIRST_SURROGATE(__c2=(s)[(i)-1])) { \ - (c)=UTF16_GET_PAIR_VALUE(__c2, (c)); \ - /* strict: ((c)&0xfffe)==0xfffe is caught by UTF_IS_ERROR() and UTF_IS_UNICODE_CHAR() */ \ - } else if(strict) {\ - /* unmatched second surrogate */ \ - (c)=UTF_ERROR_VALUE; \ - } \ - } \ - } else if((strict) && !UTF_IS_UNICODE_CHAR(c)) { \ - (c)=UTF_ERROR_VALUE; \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U16_NEXT_UNSAFE, see utf_old.h. */ -#define UTF16_NEXT_CHAR_UNSAFE(s, i, c) { \ - (c)=(s)[(i)++]; \ - if(UTF_IS_FIRST_SURROGATE(c)) { \ - (c)=UTF16_GET_PAIR_VALUE((c), (s)[(i)++]); \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U16_APPEND_UNSAFE, see utf_old.h. */ -#define UTF16_APPEND_CHAR_UNSAFE(s, i, c) { \ - if((uint32_t)(c)<=0xffff) { \ - (s)[(i)++]=(uint16_t)(c); \ - } else { \ - (s)[(i)++]=(uint16_t)(((c)>>10)+0xd7c0); \ - (s)[(i)++]=(uint16_t)(((c)&0x3ff)|0xdc00); \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U16_FWD_1_UNSAFE, see utf_old.h. */ -#define UTF16_FWD_1_UNSAFE(s, i) { \ - if(UTF_IS_FIRST_SURROGATE((s)[(i)++])) { \ - ++(i); \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U16_FWD_N_UNSAFE, see utf_old.h. */ -#define UTF16_FWD_N_UNSAFE(s, i, n) { \ - int32_t __N=(n); \ - while(__N>0) { \ - UTF16_FWD_1_UNSAFE(s, i); \ - --__N; \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U16_SET_CP_START_UNSAFE, see utf_old.h. */ -#define UTF16_SET_CHAR_START_UNSAFE(s, i) { \ - if(UTF_IS_SECOND_SURROGATE((s)[i])) { \ - --(i); \ - } \ -} - -/** @deprecated ICU 2.4. Use U16_NEXT instead, see utf_old.h. */ -#define UTF16_NEXT_CHAR_SAFE(s, i, length, c, strict) { \ - (c)=(s)[(i)++]; \ - if(UTF_IS_FIRST_SURROGATE(c)) { \ - uint16_t __c2; \ - if((i)<(length) && UTF_IS_SECOND_SURROGATE(__c2=(s)[(i)])) { \ - ++(i); \ - (c)=UTF16_GET_PAIR_VALUE((c), __c2); \ - /* strict: ((c)&0xfffe)==0xfffe is caught by UTF_IS_ERROR() and UTF_IS_UNICODE_CHAR() */ \ - } else if(strict) {\ - /* unmatched first surrogate */ \ - (c)=UTF_ERROR_VALUE; \ - } \ - } else if((strict) && !UTF_IS_UNICODE_CHAR(c)) { \ - /* unmatched second surrogate or other non-character */ \ - (c)=UTF_ERROR_VALUE; \ - } \ -} - -/** @deprecated ICU 2.4. Use U16_APPEND instead, see utf_old.h. */ -#define UTF16_APPEND_CHAR_SAFE(s, i, length, c) { \ - if((uint32_t)(c)<=0xffff) { \ - (s)[(i)++]=(uint16_t)(c); \ - } else if((uint32_t)(c)<=0x10ffff) { \ - if((i)+1<(length)) { \ - (s)[(i)++]=(uint16_t)(((c)>>10)+0xd7c0); \ - (s)[(i)++]=(uint16_t)(((c)&0x3ff)|0xdc00); \ - } else /* not enough space */ { \ - (s)[(i)++]=UTF_ERROR_VALUE; \ - } \ - } else /* c>0x10ffff, write error value */ { \ - (s)[(i)++]=UTF_ERROR_VALUE; \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U16_FWD_1, see utf_old.h. */ -#define UTF16_FWD_1_SAFE(s, i, length) U16_FWD_1(s, i, length) - -/** @deprecated ICU 2.4. Renamed to U16_FWD_N, see utf_old.h. */ -#define UTF16_FWD_N_SAFE(s, i, length, n) U16_FWD_N(s, i, length, n) - -/** @deprecated ICU 2.4. Renamed to U16_SET_CP_START, see utf_old.h. */ -#define UTF16_SET_CHAR_START_SAFE(s, start, i) U16_SET_CP_START(s, start, i) - -/** @deprecated ICU 2.4. Renamed to U16_PREV_UNSAFE, see utf_old.h. */ -#define UTF16_PREV_CHAR_UNSAFE(s, i, c) { \ - (c)=(s)[--(i)]; \ - if(UTF_IS_SECOND_SURROGATE(c)) { \ - (c)=UTF16_GET_PAIR_VALUE((s)[--(i)], (c)); \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U16_BACK_1_UNSAFE, see utf_old.h. */ -#define UTF16_BACK_1_UNSAFE(s, i) { \ - if(UTF_IS_SECOND_SURROGATE((s)[--(i)])) { \ - --(i); \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U16_BACK_N_UNSAFE, see utf_old.h. */ -#define UTF16_BACK_N_UNSAFE(s, i, n) { \ - int32_t __N=(n); \ - while(__N>0) { \ - UTF16_BACK_1_UNSAFE(s, i); \ - --__N; \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U16_SET_CP_LIMIT_UNSAFE, see utf_old.h. */ -#define UTF16_SET_CHAR_LIMIT_UNSAFE(s, i) { \ - if(UTF_IS_FIRST_SURROGATE((s)[(i)-1])) { \ - ++(i); \ - } \ -} - -/** @deprecated ICU 2.4. Use U16_PREV instead, see utf_old.h. */ -#define UTF16_PREV_CHAR_SAFE(s, start, i, c, strict) { \ - (c)=(s)[--(i)]; \ - if(UTF_IS_SECOND_SURROGATE(c)) { \ - uint16_t __c2; \ - if((i)>(start) && UTF_IS_FIRST_SURROGATE(__c2=(s)[(i)-1])) { \ - --(i); \ - (c)=UTF16_GET_PAIR_VALUE(__c2, (c)); \ - /* strict: ((c)&0xfffe)==0xfffe is caught by UTF_IS_ERROR() and UTF_IS_UNICODE_CHAR() */ \ - } else if(strict) {\ - /* unmatched second surrogate */ \ - (c)=UTF_ERROR_VALUE; \ - } \ - } else if((strict) && !UTF_IS_UNICODE_CHAR(c)) { \ - /* unmatched first surrogate or other non-character */ \ - (c)=UTF_ERROR_VALUE; \ - } \ -} - -/** @deprecated ICU 2.4. Renamed to U16_BACK_1, see utf_old.h. */ -#define UTF16_BACK_1_SAFE(s, start, i) U16_BACK_1(s, start, i) - -/** @deprecated ICU 2.4. Renamed to U16_BACK_N, see utf_old.h. */ -#define UTF16_BACK_N_SAFE(s, start, i, n) U16_BACK_N(s, start, i, n) - -/** @deprecated ICU 2.4. Renamed to U16_SET_CP_LIMIT, see utf_old.h. */ -#define UTF16_SET_CHAR_LIMIT_SAFE(s, start, i, length) U16_SET_CP_LIMIT(s, start, i, length) - -/* Formerly utf32.h --------------------------------------------------------- */ - -/* -* Old documentation: -* -* This file defines macros to deal with UTF-32 code units and code points. -* Signatures and semantics are the same as for the similarly named macros -* in utf16.h. -* utf32.h is included by utf.h after unicode/umachine.h

-* and some common definitions. -*

Usage: ICU coding guidelines for if() statements should be followed when using these macros. -* Compound statements (curly braces {}) must be used for if-else-while... -* bodies and all macro statements should be terminated with semicolon.

-*/ - -/* internal definitions ----------------------------------------------------- */ - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_IS_SAFE(c, strict) \ - (!(strict) ? \ - (uint32_t)(c)<=0x10ffff : \ - UTF_IS_UNICODE_CHAR(c)) - -/* - * For the semantics of all of these macros, see utf16.h. - * The UTF-32 versions are trivial because any code point is - * encoded using exactly one code unit. - */ - -/* single-code point definitions -------------------------------------------- */ - -/* classes of code unit values */ - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_IS_SINGLE(uchar) 1 -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_IS_LEAD(uchar) 0 -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_IS_TRAIL(uchar) 0 - -/* number of code units per code point */ - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_NEED_MULTIPLE_UCHAR(c) 0 -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_CHAR_LENGTH(c) 1 -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_MAX_CHAR_LENGTH 1 - -/* average number of code units compared to UTF-16 */ - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_ARRAY_SIZE(size) (size) - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_GET_CHAR_UNSAFE(s, i, c) { \ - (c)=(s)[i]; \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_GET_CHAR_SAFE(s, start, i, length, c, strict) { \ - (c)=(s)[i]; \ - if(!UTF32_IS_SAFE(c, strict)) { \ - (c)=UTF_ERROR_VALUE; \ - } \ -} - -/* definitions with forward iteration --------------------------------------- */ - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_NEXT_CHAR_UNSAFE(s, i, c) { \ - (c)=(s)[(i)++]; \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_APPEND_CHAR_UNSAFE(s, i, c) { \ - (s)[(i)++]=(c); \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_FWD_1_UNSAFE(s, i) { \ - ++(i); \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_FWD_N_UNSAFE(s, i, n) { \ - (i)+=(n); \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_SET_CHAR_START_UNSAFE(s, i) { \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_NEXT_CHAR_SAFE(s, i, length, c, strict) { \ - (c)=(s)[(i)++]; \ - if(!UTF32_IS_SAFE(c, strict)) { \ - (c)=UTF_ERROR_VALUE; \ - } \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_APPEND_CHAR_SAFE(s, i, length, c) { \ - if((uint32_t)(c)<=0x10ffff) { \ - (s)[(i)++]=(c); \ - } else /* c>0x10ffff, write 0xfffd */ { \ - (s)[(i)++]=0xfffd; \ - } \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_FWD_1_SAFE(s, i, length) { \ - ++(i); \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_FWD_N_SAFE(s, i, length, n) { \ - if(((i)+=(n))>(length)) { \ - (i)=(length); \ - } \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_SET_CHAR_START_SAFE(s, start, i) { \ -} - -/* definitions with backward iteration -------------------------------------- */ - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_PREV_CHAR_UNSAFE(s, i, c) { \ - (c)=(s)[--(i)]; \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_BACK_1_UNSAFE(s, i) { \ - --(i); \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_BACK_N_UNSAFE(s, i, n) { \ - (i)-=(n); \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_SET_CHAR_LIMIT_UNSAFE(s, i) { \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_PREV_CHAR_SAFE(s, start, i, c, strict) { \ - (c)=(s)[--(i)]; \ - if(!UTF32_IS_SAFE(c, strict)) { \ - (c)=UTF_ERROR_VALUE; \ - } \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_BACK_1_SAFE(s, start, i) { \ - --(i); \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_BACK_N_SAFE(s, start, i, n) { \ - (i)-=(n); \ - if((i)<(start)) { \ - (i)=(start); \ - } \ -} - -/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */ -#define UTF32_SET_CHAR_LIMIT_SAFE(s, i, length) { \ -} - -/* Formerly utf.h, part 2 --------------------------------------------------- */ - -/** - * Estimate the number of code units for a string based on the number of UTF-16 code units. - * - * @deprecated ICU 2.4. Obsolete, see utf_old.h. - */ -#define UTF_ARRAY_SIZE(size) UTF16_ARRAY_SIZE(size) - -/** @deprecated ICU 2.4. Renamed to U16_GET_UNSAFE, see utf_old.h. */ -#define UTF_GET_CHAR_UNSAFE(s, i, c) UTF16_GET_CHAR_UNSAFE(s, i, c) - -/** @deprecated ICU 2.4. Use U16_GET instead, see utf_old.h. */ -#define UTF_GET_CHAR_SAFE(s, start, i, length, c, strict) UTF16_GET_CHAR_SAFE(s, start, i, length, c, strict) - - -/** @deprecated ICU 2.4. Renamed to U16_NEXT_UNSAFE, see utf_old.h. */ -#define UTF_NEXT_CHAR_UNSAFE(s, i, c) UTF16_NEXT_CHAR_UNSAFE(s, i, c) - -/** @deprecated ICU 2.4. Use U16_NEXT instead, see utf_old.h. */ -#define UTF_NEXT_CHAR_SAFE(s, i, length, c, strict) UTF16_NEXT_CHAR_SAFE(s, i, length, c, strict) - - -/** @deprecated ICU 2.4. Renamed to U16_APPEND_UNSAFE, see utf_old.h. */ -#define UTF_APPEND_CHAR_UNSAFE(s, i, c) UTF16_APPEND_CHAR_UNSAFE(s, i, c) - -/** @deprecated ICU 2.4. Use U16_APPEND instead, see utf_old.h. */ -#define UTF_APPEND_CHAR_SAFE(s, i, length, c) UTF16_APPEND_CHAR_SAFE(s, i, length, c) - - -/** @deprecated ICU 2.4. Renamed to U16_FWD_1_UNSAFE, see utf_old.h. */ -#define UTF_FWD_1_UNSAFE(s, i) UTF16_FWD_1_UNSAFE(s, i) - -/** @deprecated ICU 2.4. Renamed to U16_FWD_1, see utf_old.h. */ -#define UTF_FWD_1_SAFE(s, i, length) UTF16_FWD_1_SAFE(s, i, length) - - -/** @deprecated ICU 2.4. Renamed to U16_FWD_N_UNSAFE, see utf_old.h. */ -#define UTF_FWD_N_UNSAFE(s, i, n) UTF16_FWD_N_UNSAFE(s, i, n) - -/** @deprecated ICU 2.4. Renamed to U16_FWD_N, see utf_old.h. */ -#define UTF_FWD_N_SAFE(s, i, length, n) UTF16_FWD_N_SAFE(s, i, length, n) - - -/** @deprecated ICU 2.4. Renamed to U16_SET_CP_START_UNSAFE, see utf_old.h. */ -#define UTF_SET_CHAR_START_UNSAFE(s, i) UTF16_SET_CHAR_START_UNSAFE(s, i) - -/** @deprecated ICU 2.4. Renamed to U16_SET_CP_START, see utf_old.h. */ -#define UTF_SET_CHAR_START_SAFE(s, start, i) UTF16_SET_CHAR_START_SAFE(s, start, i) - - -/** @deprecated ICU 2.4. Renamed to U16_PREV_UNSAFE, see utf_old.h. */ -#define UTF_PREV_CHAR_UNSAFE(s, i, c) UTF16_PREV_CHAR_UNSAFE(s, i, c) - -/** @deprecated ICU 2.4. Use U16_PREV instead, see utf_old.h. */ -#define UTF_PREV_CHAR_SAFE(s, start, i, c, strict) UTF16_PREV_CHAR_SAFE(s, start, i, c, strict) - - -/** @deprecated ICU 2.4. Renamed to U16_BACK_1_UNSAFE, see utf_old.h. */ -#define UTF_BACK_1_UNSAFE(s, i) UTF16_BACK_1_UNSAFE(s, i) - -/** @deprecated ICU 2.4. Renamed to U16_BACK_1, see utf_old.h. */ -#define UTF_BACK_1_SAFE(s, start, i) UTF16_BACK_1_SAFE(s, start, i) - - -/** @deprecated ICU 2.4. Renamed to U16_BACK_N_UNSAFE, see utf_old.h. */ -#define UTF_BACK_N_UNSAFE(s, i, n) UTF16_BACK_N_UNSAFE(s, i, n) - -/** @deprecated ICU 2.4. Renamed to U16_BACK_N, see utf_old.h. */ -#define UTF_BACK_N_SAFE(s, start, i, n) UTF16_BACK_N_SAFE(s, start, i, n) - - -/** @deprecated ICU 2.4. Renamed to U16_SET_CP_LIMIT_UNSAFE, see utf_old.h. */ -#define UTF_SET_CHAR_LIMIT_UNSAFE(s, i) UTF16_SET_CHAR_LIMIT_UNSAFE(s, i) - -/** @deprecated ICU 2.4. Renamed to U16_SET_CP_LIMIT, see utf_old.h. */ -#define UTF_SET_CHAR_LIMIT_SAFE(s, start, i, length) UTF16_SET_CHAR_LIMIT_SAFE(s, start, i, length) - -/* Define default macros (UTF-16 "safe") ------------------------------------ */ - -/** - * Does this code unit alone encode a code point (BMP, not a surrogate)? - * Same as UTF16_IS_SINGLE. - * @deprecated ICU 2.4. Renamed to U_IS_SINGLE and U16_IS_SINGLE, see utf_old.h. - */ -#define UTF_IS_SINGLE(uchar) U16_IS_SINGLE(uchar) - -/** - * Is this code unit the first one of several (a lead surrogate)? - * Same as UTF16_IS_LEAD. - * @deprecated ICU 2.4. Renamed to U_IS_LEAD and U16_IS_LEAD, see utf_old.h. - */ -#define UTF_IS_LEAD(uchar) U16_IS_LEAD(uchar) - -/** - * Is this code unit one of several but not the first one (a trail surrogate)? - * Same as UTF16_IS_TRAIL. - * @deprecated ICU 2.4. Renamed to U_IS_TRAIL and U16_IS_TRAIL, see utf_old.h. - */ -#define UTF_IS_TRAIL(uchar) U16_IS_TRAIL(uchar) - -/** - * Does this code point require multiple code units (is it a supplementary code point)? - * Same as UTF16_NEED_MULTIPLE_UCHAR. - * @deprecated ICU 2.4. Use U16_LENGTH or test ((uint32_t)(c)>0xffff) instead. - */ -#define UTF_NEED_MULTIPLE_UCHAR(c) UTF16_NEED_MULTIPLE_UCHAR(c) - -/** - * How many code units are used to encode this code point (1 or 2)? - * Same as UTF16_CHAR_LENGTH. - * @deprecated ICU 2.4. Renamed to U16_LENGTH, see utf_old.h. - */ -#define UTF_CHAR_LENGTH(c) U16_LENGTH(c) - -/** - * How many code units are used at most for any Unicode code point (2)? - * Same as UTF16_MAX_CHAR_LENGTH. - * @deprecated ICU 2.4. Renamed to U16_MAX_LENGTH, see utf_old.h. - */ -#define UTF_MAX_CHAR_LENGTH U16_MAX_LENGTH - -/** - * Set c to the code point that contains the code unit i. - * i could point to the lead or the trail surrogate for the code point. - * i is not modified. - * Same as UTF16_GET_CHAR. - * \pre 0<=iaverageTime = (time1 + time2)/2, there will be overflow even with dates - * around the present. Moreover, even if these problems don't occur, there is the issue of - * conversion back and forth between different systems. - * - *

- * Binary datetimes differ in a number of ways: the datatype, the unit, - * and the epoch (origin). We'll refer to these as time scales. For example: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Table 1: Binary Time Scales
SourceDatatypeUnitEpoch
UDTS_JAVA_TIMEint64_tmillisecondsJan 1, 1970
UDTS_UNIX_TIMEint32_t or int64_tsecondsJan 1, 1970
UDTS_ICU4C_TIMEdoublemillisecondsJan 1, 1970
UDTS_WINDOWS_FILE_TIMEint64_tticks (100 nanoseconds)Jan 1, 1601
UDTS_DOTNET_DATE_TIMEint64_tticks (100 nanoseconds)Jan 1, 0001
UDTS_MAC_OLD_TIMEint32_t or int64_tsecondsJan 1, 1904
UDTS_MAC_TIMEdoublesecondsJan 1, 2001
UDTS_EXCEL_TIME?daysDec 31, 1899
UDTS_DB2_TIME?daysDec 31, 1899
UDTS_UNIX_MICROSECONDS_TIMEint64_tmicrosecondsJan 1, 1970
- * - *

- * All of the epochs start at 00:00 am (the earliest possible time on the day in question), - * and are assumed to be UTC. - * - *

- * The ranges for different datatypes are given in the following table (all values in years). - * The range of years includes the entire range expressible with positive and negative - * values of the datatype. The range of years for double is the range that would be allowed - * without losing precision to the corresponding unit. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Unitsint64_tdoubleint32_t
1 sec5.84542x1011285,420,920.94136.10
1 millisecond584,542,046.09285,420.920.14
1 microsecond584,542.05285.420.00
100 nanoseconds (tick)58,454.2028.540.00
1 nanosecond584.54204610.28540.00
- * - *

- * These functions implement a universal time scale which can be used as a 'pivot', - * and provide conversion functions to and from all other major time scales. - * This datetimes to be converted to the pivot time, safely manipulated, - * and converted back to any other datetime time scale. - * - *

- * So what to use for this pivot? Java time has plenty of range, but cannot represent - * .NET System.DateTime values without severe loss of precision. ICU4C time addresses this by using a - * double that is otherwise equivalent to the Java time. However, there are disadvantages - * with doubles. They provide for much more graceful degradation in arithmetic operations. - * But they only have 53 bits of accuracy, which means that they will lose precision when - * converting back and forth to ticks. What would really be nice would be a - * long double (80 bits -- 64 bit mantissa), but that is not supported on most systems. - * - *

- * The Unix extended time uses a structure with two components: time in seconds and a - * fractional field (microseconds). However, this is clumsy, slow, and - * prone to error (you always have to keep track of overflow and underflow in the - * fractional field). BigDecimal would allow for arbitrary precision and arbitrary range, - * but we do not want to use this as the normal type, because it is slow and does not - * have a fixed size. - * - *

- * Because of these issues, we ended up concluding that the .NET framework's - * System.DateTime would be the best pivot. However, we use the full range - * allowed by the datatype, allowing for datetimes back to 29,000 BC and up to 29,000 AD. - * This time scale is very fine grained, does not lose precision, and covers a range that - * will meet almost all requirements. It will not handle the range that Java times do, - * but frankly, being able to handle dates before 29,000 BC or after 29,000 AD is of very limited interest. - * - */ - -/** - * UDateTimeScale values are used to specify the time scale used for - * conversion into or out if the universal time scale. - * - * @stable ICU 3.2 - */ -typedef enum UDateTimeScale { - /** - * Used in the JDK. Data is a Java long (int64_t). Value - * is milliseconds since January 1, 1970. - * - * @stable ICU 3.2 - */ - UDTS_JAVA_TIME = 0, - - /** - * Used on Unix systems. Data is int32_t or int64_t. Value - * is seconds since January 1, 1970. - * - * @stable ICU 3.2 - */ - UDTS_UNIX_TIME, - - /** - * Used in IUC4C. Data is a double. Value - * is milliseconds since January 1, 1970. - * - * @stable ICU 3.2 - */ - UDTS_ICU4C_TIME, - - /** - * Used in Windows for file times. Data is an int64_t. Value - * is ticks (1 tick == 100 nanoseconds) since January 1, 1601. - * - * @stable ICU 3.2 - */ - UDTS_WINDOWS_FILE_TIME, - - /** - * Used in the .NET framework's System.DateTime structure. Data is an int64_t. Value - * is ticks (1 tick == 100 nanoseconds) since January 1, 0001. - * - * @stable ICU 3.2 - */ - UDTS_DOTNET_DATE_TIME, - - /** - * Used in older Macintosh systems. Data is int32_t or int64_t. Value - * is seconds since January 1, 1904. - * - * @stable ICU 3.2 - */ - UDTS_MAC_OLD_TIME, - - /** - * Used in newer Macintosh systems. Data is a double. Value - * is seconds since January 1, 2001. - * - * @stable ICU 3.2 - */ - UDTS_MAC_TIME, - - /** - * Used in Excel. Data is an ?unknown?. Value - * is days since December 31, 1899. - * - * @stable ICU 3.2 - */ - UDTS_EXCEL_TIME, - - /** - * Used in DB2. Data is an ?unknown?. Value - * is days since December 31, 1899. - * - * @stable ICU 3.2 - */ - UDTS_DB2_TIME, - - /** - * Data is a long. Value is microseconds since January 1, 1970. - * Similar to Unix time (linear value from 1970) and struct timeval - * (microseconds resolution). - * - * @stable ICU 3.8 - */ - UDTS_UNIX_MICROSECONDS_TIME, - - /** - * The first unused time scale value. The limit of this enum - */ - UDTS_MAX_SCALE -} UDateTimeScale; - -/** - * UTimeScaleValue values are used to specify the time scale values - * to utmscale_getTimeScaleValue. - * - * @see utmscale_getTimeScaleValue - * - * @stable ICU 3.2 - */ -typedef enum UTimeScaleValue { - /** - * The constant used to select the units vale - * for a time scale. - * - * @see utmscale_getTimeScaleValue - * - * @stable ICU 3.2 - */ - UTSV_UNITS_VALUE = 0, - - /** - * The constant used to select the epoch offset value - * for a time scale. - * - * @see utmscale_getTimeScaleValue - * - * @stable ICU 3.2 - */ - UTSV_EPOCH_OFFSET_VALUE=1, - - /** - * The constant used to select the minimum from value - * for a time scale. - * - * @see utmscale_getTimeScaleValue - * - * @stable ICU 3.2 - */ - UTSV_FROM_MIN_VALUE=2, - - /** - * The constant used to select the maximum from value - * for a time scale. - * - * @see utmscale_getTimeScaleValue - * - * @stable ICU 3.2 - */ - UTSV_FROM_MAX_VALUE=3, - - /** - * The constant used to select the minimum to value - * for a time scale. - * - * @see utmscale_getTimeScaleValue - * - * @stable ICU 3.2 - */ - UTSV_TO_MIN_VALUE=4, - - /** - * The constant used to select the maximum to value - * for a time scale. - * - * @see utmscale_getTimeScaleValue - * - * @stable ICU 3.2 - */ - UTSV_TO_MAX_VALUE=5, - -#ifndef U_HIDE_INTERNAL_API - /** - * The constant used to select the epoch plus one value - * for a time scale. - * - * NOTE: This is an internal value. DO NOT USE IT. May not - * actually be equal to the epoch offset value plus one. - * - * @see utmscale_getTimeScaleValue - * - * @internal ICU 3.2 - */ - UTSV_EPOCH_OFFSET_PLUS_1_VALUE=6, - - /** - * The constant used to select the epoch plus one value - * for a time scale. - * - * NOTE: This is an internal value. DO NOT USE IT. May not - * actually be equal to the epoch offset value plus one. - * - * @see utmscale_getTimeScaleValue - * - * @internal ICU 3.2 - */ - UTSV_EPOCH_OFFSET_MINUS_1_VALUE=7, - - /** - * The constant used to select the units round value - * for a time scale. - * - * NOTE: This is an internal value. DO NOT USE IT. - * - * @see utmscale_getTimeScaleValue - * - * @internal ICU 3.2 - */ - UTSV_UNITS_ROUND_VALUE=8, - - /** - * The constant used to select the minimum safe rounding value - * for a time scale. - * - * NOTE: This is an internal value. DO NOT USE IT. - * - * @see utmscale_getTimeScaleValue - * - * @internal ICU 3.2 - */ - UTSV_MIN_ROUND_VALUE=9, - - /** - * The constant used to select the maximum safe rounding value - * for a time scale. - * - * NOTE: This is an internal value. DO NOT USE IT. - * - * @see utmscale_getTimeScaleValue - * - * @internal ICU 3.2 - */ - UTSV_MAX_ROUND_VALUE=10, - -#endif /* U_HIDE_INTERNAL_API */ - - /** - * The number of time scale values, in other words limit of this enum. - * - * @see utmscale_getTimeScaleValue - */ - UTSV_MAX_SCALE_VALUE=11 - -} UTimeScaleValue; - -/** - * Get a value associated with a particular time scale. - * - * @param timeScale The time scale - * @param value A constant representing the value to get - * @param status The status code. Set to U_ILLEGAL_ARGUMENT_ERROR if arguments are invalid. - * @return - the value. - * - * @stable ICU 3.2 - */ -U_STABLE int64_t U_EXPORT2 - utmscale_getTimeScaleValue(UDateTimeScale timeScale, UTimeScaleValue value, UErrorCode *status); - -/* Conversion to 'universal time scale' */ - -/** - * Convert a int64_t datetime from the given time scale to the universal time scale. - * - * @param otherTime The int64_t datetime - * @param timeScale The time scale to convert from - * @param status The status code. Set to U_ILLEGAL_ARGUMENT_ERROR if the conversion is out of range. - * - * @return The datetime converted to the universal time scale - * - * @stable ICU 3.2 - */ -U_STABLE int64_t U_EXPORT2 - utmscale_fromInt64(int64_t otherTime, UDateTimeScale timeScale, UErrorCode *status); - -/* Conversion from 'universal time scale' */ - -/** - * Convert a datetime from the universal time scale to a int64_t in the given time scale. - * - * @param universalTime The datetime in the universal time scale - * @param timeScale The time scale to convert to - * @param status The status code. Set to U_ILLEGAL_ARGUMENT_ERROR if the conversion is out of range. - * - * @return The datetime converted to the given time scale - * - * @stable ICU 3.2 - */ -U_STABLE int64_t U_EXPORT2 - utmscale_toInt64(int64_t universalTime, UDateTimeScale timeScale, UErrorCode *status); - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif - diff --git a/win32/include/spidermonkey/unicode/utrace.h b/win32/include/spidermonkey/unicode/utrace.h deleted file mode 100755 index c55f8c11..00000000 --- a/win32/include/spidermonkey/unicode/utrace.h +++ /dev/null @@ -1,379 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* -* Copyright (C) 2003-2013, International Business Machines -* Corporation and others. All Rights Reserved. -* -******************************************************************************* -* file name: utrace.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* created on: 2003aug06 -* created by: Markus W. Scherer -* -* Definitions for ICU tracing/logging. -* -*/ - -#ifndef __UTRACE_H__ -#define __UTRACE_H__ - -#include -#include "unicode/utypes.h" - -/** - * \file - * \brief C API: Definitions for ICU tracing/logging. - * - * This provides API for debugging the internals of ICU without the use of - * a traditional debugger. - * - * By default, tracing is disabled in ICU. If you need to debug ICU with - * tracing, please compile ICU with the --enable-tracing configure option. - */ - -U_CDECL_BEGIN - -/** - * Trace severity levels. Higher levels increase the verbosity of the trace output. - * @see utrace_setLevel - * @stable ICU 2.8 - */ -typedef enum UTraceLevel { - /** Disable all tracing @stable ICU 2.8*/ - UTRACE_OFF=-1, - /** Trace error conditions only @stable ICU 2.8*/ - UTRACE_ERROR=0, - /** Trace errors and warnings @stable ICU 2.8*/ - UTRACE_WARNING=3, - /** Trace opens and closes of ICU services @stable ICU 2.8*/ - UTRACE_OPEN_CLOSE=5, - /** Trace an intermediate number of ICU operations @stable ICU 2.8*/ - UTRACE_INFO=7, - /** Trace the maximum number of ICU operations @stable ICU 2.8*/ - UTRACE_VERBOSE=9 -} UTraceLevel; - -/** - * These are the ICU functions that will be traced when tracing is enabled. - * @stable ICU 2.8 - */ -typedef enum UTraceFunctionNumber { - UTRACE_FUNCTION_START=0, - UTRACE_U_INIT=UTRACE_FUNCTION_START, - UTRACE_U_CLEANUP, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal collation trace location. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UTRACE_FUNCTION_LIMIT, -#endif // U_HIDE_DEPRECATED_API - - UTRACE_CONVERSION_START=0x1000, - UTRACE_UCNV_OPEN=UTRACE_CONVERSION_START, - UTRACE_UCNV_OPEN_PACKAGE, - UTRACE_UCNV_OPEN_ALGORITHMIC, - UTRACE_UCNV_CLONE, - UTRACE_UCNV_CLOSE, - UTRACE_UCNV_FLUSH_CACHE, - UTRACE_UCNV_LOAD, - UTRACE_UCNV_UNLOAD, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal collation trace location. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UTRACE_CONVERSION_LIMIT, -#endif // U_HIDE_DEPRECATED_API - - UTRACE_COLLATION_START=0x2000, - UTRACE_UCOL_OPEN=UTRACE_COLLATION_START, - UTRACE_UCOL_CLOSE, - UTRACE_UCOL_STRCOLL, - UTRACE_UCOL_GET_SORTKEY, - UTRACE_UCOL_GETLOCALE, - UTRACE_UCOL_NEXTSORTKEYPART, - UTRACE_UCOL_STRCOLLITER, - UTRACE_UCOL_OPEN_FROM_SHORT_STRING, - UTRACE_UCOL_STRCOLLUTF8, /**< @stable ICU 50 */ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal collation trace location. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - UTRACE_COLLATION_LIMIT -#endif // U_HIDE_DEPRECATED_API -} UTraceFunctionNumber; - -/** - * Setter for the trace level. - * @param traceLevel A UTraceLevel value. - * @stable ICU 2.8 - */ -U_STABLE void U_EXPORT2 -utrace_setLevel(int32_t traceLevel); - -/** - * Getter for the trace level. - * @return The UTraceLevel value being used by ICU. - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -utrace_getLevel(void); - -/* Trace function pointers types ----------------------------- */ - -/** - * Type signature for the trace function to be called when entering a function. - * @param context value supplied at the time the trace functions are set. - * @param fnNumber Enum value indicating the ICU function being entered. - * @stable ICU 2.8 - */ -typedef void U_CALLCONV -UTraceEntry(const void *context, int32_t fnNumber); - -/** - * Type signature for the trace function to be called when exiting from a function. - * @param context value supplied at the time the trace functions are set. - * @param fnNumber Enum value indicating the ICU function being exited. - * @param fmt A formatting string that describes the number and types - * of arguments included with the variable args. The fmt - * string has the same form as the utrace_vformat format - * string. - * @param args A variable arguments list. Contents are described by - * the fmt parameter. - * @see utrace_vformat - * @stable ICU 2.8 - */ -typedef void U_CALLCONV -UTraceExit(const void *context, int32_t fnNumber, - const char *fmt, va_list args); - -/** - * Type signature for the trace function to be called from within an ICU function - * to display data or messages. - * @param context value supplied at the time the trace functions are set. - * @param fnNumber Enum value indicating the ICU function being exited. - * @param level The current tracing level - * @param fmt A format string describing the tracing data that is supplied - * as variable args - * @param args The data being traced, passed as variable args. - * @stable ICU 2.8 - */ -typedef void U_CALLCONV -UTraceData(const void *context, int32_t fnNumber, int32_t level, - const char *fmt, va_list args); - -/** - * Set ICU Tracing functions. Installs application-provided tracing - * functions into ICU. After doing this, subsequent ICU operations - * will call back to the installed functions, providing a trace - * of the use of ICU. Passing a NULL pointer for a tracing function - * is allowed, and inhibits tracing action at points where that function - * would be called. - *

- * Tracing and Threads: Tracing functions are global to a process, and - * will be called in response to ICU operations performed by any - * thread. If tracing of an individual thread is desired, the - * tracing functions must themselves filter by checking that the - * current thread is the desired thread. - * - * @param context an uninterpretted pointer. Whatever is passed in - * here will in turn be passed to each of the tracing - * functions UTraceEntry, UTraceExit and UTraceData. - * ICU does not use or alter this pointer. - * @param e Callback function to be called on entry to a - * a traced ICU function. - * @param x Callback function to be called on exit from a - * traced ICU function. - * @param d Callback function to be called from within a - * traced ICU function, for the purpose of providing - * data to the trace. - * - * @stable ICU 2.8 - */ -U_STABLE void U_EXPORT2 -utrace_setFunctions(const void *context, - UTraceEntry *e, UTraceExit *x, UTraceData *d); - -/** - * Get the currently installed ICU tracing functions. Note that a null function - * pointer will be returned if no trace function has been set. - * - * @param context The currently installed tracing context. - * @param e The currently installed UTraceEntry function. - * @param x The currently installed UTraceExit function. - * @param d The currently installed UTraceData function. - * @stable ICU 2.8 - */ -U_STABLE void U_EXPORT2 -utrace_getFunctions(const void **context, - UTraceEntry **e, UTraceExit **x, UTraceData **d); - - - -/* - * - * ICU trace format string syntax - * - * Format Strings are passed to UTraceData functions, and define the - * number and types of the trace data being passed on each call. - * - * The UTraceData function, which is supplied by the application, - * not by ICU, can either forward the trace data (passed via - * varargs) and the format string back to ICU for formatting into - * a displayable string, or it can interpret the format itself, - * and do as it wishes with the trace data. - * - * - * Goals for the format string - * - basic data output - * - easy to use for trace programmer - * - sufficient provision for data types for trace output readability - * - well-defined types and binary portable APIs - * - * Non-goals - * - printf compatibility - * - fancy formatting - * - argument reordering and other internationalization features - * - * ICU trace format strings contain plain text with argument inserts, - * much like standard printf format strings. - * Each insert begins with a '%', then optionally contains a 'v', - * then exactly one type character. - * Two '%' in a row represent a '%' instead of an insert. - * The trace format strings need not have \n at the end. - * - * - * Types - * ----- - * - * Type characters: - * - c A char character in the default codepage. - * - s A NUL-terminated char * string in the default codepage. - * - S A UChar * string. Requires two params, (ptr, length). Length=-1 for nul term. - * - b A byte (8-bit integer). - * - h A 16-bit integer. Also a 16 bit Unicode code unit. - * - d A 32-bit integer. Also a 20 bit Unicode code point value. - * - l A 64-bit integer. - * - p A data pointer. - * - * Vectors - * ------- - * - * If the 'v' is not specified, then one item of the specified type - * is passed in. - * If the 'v' (for "vector") is specified, then a vector of items of the - * specified type is passed in, via a pointer to the first item - * and an int32_t value for the length of the vector. - * Length==-1 means zero or NUL termination. Works for vectors of all types. - * - * Note: %vS is a vector of (UChar *) strings. The strings must - * be nul terminated as there is no way to provide a - * separate length parameter for each string. The length - * parameter (required for all vectors) is the number of - * strings, not the length of the strings. - * - * Examples - * -------- - * - * These examples show the parameters that will be passed to an application's - * UTraceData() function for various formats. - * - * - the precise formatting is up to the application! - * - the examples use type casts for arguments only to _show_ the types of - * arguments without needing variable declarations in the examples; - * the type casts will not be necessary in actual code - * - * UTraceDataFunc(context, fnNumber, level, - * "There is a character %c in the string %s.", // Format String - * (char)c, (const char *)s); // varargs parameters - * -> There is a character 0x42 'B' in the string "Bravo". - * - * UTraceDataFunc(context, fnNumber, level, - * "Vector of bytes %vb vector of chars %vc", - * (const uint8_t *)bytes, (int32_t)bytesLength, - * (const char *)chars, (int32_t)charsLength); - * -> Vector of bytes - * 42 63 64 3f [4] - * vector of chars - * "Bcd?"[4] - * - * UTraceDataFunc(context, fnNumber, level, - * "An int32_t %d and a whole bunch of them %vd", - * (int32_t)-5, (const int32_t *)ints, (int32_t)intsLength); - * -> An int32_t 0xfffffffb and a whole bunch of them - * fffffffb 00000005 0000010a [3] - * - */ - - - -/** - * Trace output Formatter. An application's UTraceData tracing functions may call - * back to this function to format the trace output in a - * human readable form. Note that a UTraceData function may choose - * to not format the data; it could, for example, save it in - * in the raw form it was received (more compact), leaving - * formatting for a later trace analyis tool. - * @param outBuf pointer to a buffer to receive the formatted output. Output - * will be nul terminated if there is space in the buffer - - * if the length of the requested output < the output buffer size. - * @param capacity Length of the output buffer. - * @param indent Number of spaces to indent the output. Intended to allow - * data displayed from nested functions to be indented for readability. - * @param fmt Format specification for the data to output - * @param args Data to be formatted. - * @return Length of formatted output, including the terminating NUL. - * If buffer capacity is insufficient, the required capacity is returned. - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -utrace_vformat(char *outBuf, int32_t capacity, - int32_t indent, const char *fmt, va_list args); - -/** - * Trace output Formatter. An application's UTraceData tracing functions may call - * this function to format any additional trace data, beyond that - * provided by default, in human readable form with the same - * formatting conventions used by utrace_vformat(). - * @param outBuf pointer to a buffer to receive the formatted output. Output - * will be nul terminated if there is space in the buffer - - * if the length of the requested output < the output buffer size. - * @param capacity Length of the output buffer. - * @param indent Number of spaces to indent the output. Intended to allow - * data displayed from nested functions to be indented for readability. - * @param fmt Format specification for the data to output - * @param ... Data to be formatted. - * @return Length of formatted output, including the terminating NUL. - * If buffer capacity is insufficient, the required capacity is returned. - * @stable ICU 2.8 - */ -U_STABLE int32_t U_EXPORT2 -utrace_format(char *outBuf, int32_t capacity, - int32_t indent, const char *fmt, ...); - - - -/* Trace function numbers --------------------------------------------------- */ - -/** - * Get the name of a function from its trace function number. - * - * @param fnNumber The trace number for an ICU function. - * @return The name string for the function. - * - * @see UTraceFunctionNumber - * @stable ICU 2.8 - */ -U_STABLE const char * U_EXPORT2 -utrace_functionName(int32_t fnNumber); - -U_CDECL_END - -#endif diff --git a/win32/include/spidermonkey/unicode/utrans.h b/win32/include/spidermonkey/unicode/utrans.h deleted file mode 100755 index 9d70eeb8..00000000 --- a/win32/include/spidermonkey/unicode/utrans.h +++ /dev/null @@ -1,658 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 1997-2011,2014-2015 International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* Date Name Description -* 06/21/00 aliu Creation. -******************************************************************************* -*/ - -#ifndef UTRANS_H -#define UTRANS_H - -#include "unicode/utypes.h" - -#if !UCONFIG_NO_TRANSLITERATION - -#include "unicode/localpointer.h" -#include "unicode/urep.h" -#include "unicode/parseerr.h" -#include "unicode/uenum.h" -#include "unicode/uset.h" - -/******************************************************************** - * General Notes - ******************************************************************** - */ -/** - * \file - * \brief C API: Transliterator - * - *

Transliteration

- * The data structures and functions described in this header provide - * transliteration services. Transliteration services are implemented - * as C++ classes. The comments and documentation in this header - * assume the reader is familiar with the C++ headers translit.h and - * associated documentation. - * - * A significant but incomplete subset of the C++ transliteration - * services are available to C code through this header. In order to - * access more complex transliteration services, refer to the C++ - * headers and documentation. - * - * There are two sets of functions for working with transliterator IDs: - * - * An old, deprecated set uses char * IDs, which works for true and pure - * identifiers that these APIs were designed for, - * for example "Cyrillic-Latin". - * It does not work when the ID contains filters ("[:Script=Cyrl:]") - * or even a complete set of rules because then the ID string contains more - * than just "invariant" characters (see utypes.h). - * - * A new set of functions replaces the old ones and uses UChar * IDs, - * paralleling the UnicodeString IDs in the C++ API. (New in ICU 2.8.) - */ - -/******************************************************************** - * Data Structures - ********************************************************************/ - -/** - * An opaque transliterator for use in C. Open with utrans_openxxx() - * and close with utrans_close() when done. Equivalent to the C++ class - * Transliterator and its subclasses. - * @see Transliterator - * @stable ICU 2.0 - */ -typedef void* UTransliterator; - -/** - * Direction constant indicating the direction in a transliterator, - * e.g., the forward or reverse rules of a RuleBasedTransliterator. - * Specified when a transliterator is opened. An "A-B" transliterator - * transliterates A to B when operating in the forward direction, and - * B to A when operating in the reverse direction. - * @stable ICU 2.0 - */ -typedef enum UTransDirection { - - /** - * UTRANS_FORWARD means from <source> to <target> for a - * transliterator with ID <source>-<target>. For a transliterator - * opened using a rule, it means forward direction rules, e.g., - * "A > B". - */ - UTRANS_FORWARD, - - /** - * UTRANS_REVERSE means from <target> to <source> for a - * transliterator with ID <source>-<target>. For a transliterator - * opened using a rule, it means reverse direction rules, e.g., - * "A < B". - */ - UTRANS_REVERSE - -} UTransDirection; - -/** - * Position structure for utrans_transIncremental() incremental - * transliteration. This structure defines two substrings of the text - * being transliterated. The first region, [contextStart, - * contextLimit), defines what characters the transliterator will read - * as context. The second region, [start, limit), defines what - * characters will actually be transliterated. The second region - * should be a subset of the first. - * - *

After a transliteration operation, some of the indices in this - * structure will be modified. See the field descriptions for - * details. - * - *

contextStart <= start <= limit <= contextLimit - * - *

Note: All index values in this structure must be at code point - * boundaries. That is, none of them may occur between two code units - * of a surrogate pair. If any index does split a surrogate pair, - * results are unspecified. - * - * @stable ICU 2.0 - */ -typedef struct UTransPosition { - - /** - * Beginning index, inclusive, of the context to be considered for - * a transliteration operation. The transliterator will ignore - * anything before this index. INPUT/OUTPUT parameter: This parameter - * is updated by a transliteration operation to reflect the maximum - * amount of antecontext needed by a transliterator. - * @stable ICU 2.4 - */ - int32_t contextStart; - - /** - * Ending index, exclusive, of the context to be considered for a - * transliteration operation. The transliterator will ignore - * anything at or after this index. INPUT/OUTPUT parameter: This - * parameter is updated to reflect changes in the length of the - * text, but points to the same logical position in the text. - * @stable ICU 2.4 - */ - int32_t contextLimit; - - /** - * Beginning index, inclusive, of the text to be transliteratd. - * INPUT/OUTPUT parameter: This parameter is advanced past - * characters that have already been transliterated by a - * transliteration operation. - * @stable ICU 2.4 - */ - int32_t start; - - /** - * Ending index, exclusive, of the text to be transliteratd. - * INPUT/OUTPUT parameter: This parameter is updated to reflect - * changes in the length of the text, but points to the same - * logical position in the text. - * @stable ICU 2.4 - */ - int32_t limit; - -} UTransPosition; - -/******************************************************************** - * General API - ********************************************************************/ - -/** - * Open a custom transliterator, given a custom rules string - * OR - * a system transliterator, given its ID. - * Any non-NULL result from this function should later be closed with - * utrans_close(). - * - * @param id a valid transliterator ID - * @param idLength the length of the ID string, or -1 if NUL-terminated - * @param dir the desired direction - * @param rules the transliterator rules. See the C++ header rbt.h for - * rules syntax. If NULL then a system transliterator matching - * the ID is returned. - * @param rulesLength the length of the rules, or -1 if the rules - * are NUL-terminated. - * @param parseError a pointer to a UParseError struct to receive the details - * of any parsing errors. This parameter may be NULL if no - * parsing error details are desired. - * @param pErrorCode a pointer to the UErrorCode - * @return a transliterator pointer that may be passed to other - * utrans_xxx() functions, or NULL if the open call fails. - * @stable ICU 2.8 - */ -U_STABLE UTransliterator* U_EXPORT2 -utrans_openU(const UChar *id, - int32_t idLength, - UTransDirection dir, - const UChar *rules, - int32_t rulesLength, - UParseError *parseError, - UErrorCode *pErrorCode); - -/** - * Open an inverse of an existing transliterator. For this to work, - * the inverse must be registered with the system. For example, if - * the Transliterator "A-B" is opened, and then its inverse is opened, - * the result is the Transliterator "B-A", if such a transliterator is - * registered with the system. Otherwise the result is NULL and a - * failing UErrorCode is set. Any non-NULL result from this function - * should later be closed with utrans_close(). - * - * @param trans the transliterator to open the inverse of. - * @param status a pointer to the UErrorCode - * @return a pointer to a newly-opened transliterator that is the - * inverse of trans, or NULL if the open call fails. - * @stable ICU 2.0 - */ -U_STABLE UTransliterator* U_EXPORT2 -utrans_openInverse(const UTransliterator* trans, - UErrorCode* status); - -/** - * Create a copy of a transliterator. Any non-NULL result from this - * function should later be closed with utrans_close(). - * - * @param trans the transliterator to be copied. - * @param status a pointer to the UErrorCode - * @return a transliterator pointer that may be passed to other - * utrans_xxx() functions, or NULL if the clone call fails. - * @stable ICU 2.0 - */ -U_STABLE UTransliterator* U_EXPORT2 -utrans_clone(const UTransliterator* trans, - UErrorCode* status); - -/** - * Close a transliterator. Any non-NULL pointer returned by - * utrans_openXxx() or utrans_clone() should eventually be closed. - * @param trans the transliterator to be closed. - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -utrans_close(UTransliterator* trans); - -#if U_SHOW_CPLUSPLUS_API - -U_NAMESPACE_BEGIN - -/** - * \class LocalUTransliteratorPointer - * "Smart pointer" class, closes a UTransliterator via utrans_close(). - * For most methods see the LocalPointerBase base class. - * - * @see LocalPointerBase - * @see LocalPointer - * @stable ICU 4.4 - */ -U_DEFINE_LOCAL_OPEN_POINTER(LocalUTransliteratorPointer, UTransliterator, utrans_close); - -U_NAMESPACE_END - -#endif - -/** - * Return the programmatic identifier for this transliterator. - * If this identifier is passed to utrans_openU(), it will open - * a transliterator equivalent to this one, if the ID has been - * registered. - * - * @param trans the transliterator to return the ID of. - * @param resultLength pointer to an output variable receiving the length - * of the ID string; can be NULL - * @return the NUL-terminated ID string. This pointer remains - * valid until utrans_close() is called on this transliterator. - * - * @stable ICU 2.8 - */ -U_STABLE const UChar * U_EXPORT2 -utrans_getUnicodeID(const UTransliterator *trans, - int32_t *resultLength); - -/** - * Register an open transliterator with the system. When - * utrans_open() is called with an ID string that is equal to that - * returned by utrans_getID(adoptedTrans,...), then - * utrans_clone(adoptedTrans,...) is returned. - * - *

NOTE: After this call the system owns the adoptedTrans and will - * close it. The user must not call utrans_close() on adoptedTrans. - * - * @param adoptedTrans a transliterator, typically the result of - * utrans_openRules(), to be registered with the system. - * @param status a pointer to the UErrorCode - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -utrans_register(UTransliterator* adoptedTrans, - UErrorCode* status); - -/** - * Unregister a transliterator from the system. After this call the - * system will no longer recognize the given ID when passed to - * utrans_open(). If the ID is invalid then nothing is done. - * - * @param id an ID to unregister - * @param idLength the length of id, or -1 if id is zero-terminated - * @stable ICU 2.8 - */ -U_STABLE void U_EXPORT2 -utrans_unregisterID(const UChar* id, int32_t idLength); - -/** - * Set the filter used by a transliterator. A filter can be used to - * make the transliterator pass certain characters through untouched. - * The filter is expressed using a UnicodeSet pattern. If the - * filterPattern is NULL or the empty string, then the transliterator - * will be reset to use no filter. - * - * @param trans the transliterator - * @param filterPattern a pattern string, in the form accepted by - * UnicodeSet, specifying which characters to apply the - * transliteration to. May be NULL or the empty string to indicate no - * filter. - * @param filterPatternLen the length of filterPattern, or -1 if - * filterPattern is zero-terminated - * @param status a pointer to the UErrorCode - * @see UnicodeSet - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -utrans_setFilter(UTransliterator* trans, - const UChar* filterPattern, - int32_t filterPatternLen, - UErrorCode* status); - -/** - * Return the number of system transliterators. - * It is recommended to use utrans_openIDs() instead. - * - * @return the number of system transliterators. - * @stable ICU 2.0 - */ -U_STABLE int32_t U_EXPORT2 -utrans_countAvailableIDs(void); - -/** - * Return a UEnumeration for the available transliterators. - * - * @param pErrorCode Pointer to the UErrorCode in/out parameter. - * @return UEnumeration for the available transliterators. - * Close with uenum_close(). - * - * @stable ICU 2.8 - */ -U_STABLE UEnumeration * U_EXPORT2 -utrans_openIDs(UErrorCode *pErrorCode); - -/******************************************************************** - * Transliteration API - ********************************************************************/ - -/** - * Transliterate a segment of a UReplaceable string. The string is - * passed in as a UReplaceable pointer rep and a UReplaceableCallbacks - * function pointer struct repFunc. Functions in the repFunc struct - * will be called in order to modify the rep string. - * - * @param trans the transliterator - * @param rep a pointer to the string. This will be passed to the - * repFunc functions. - * @param repFunc a set of function pointers that will be used to - * modify the string pointed to by rep. - * @param start the beginning index, inclusive; 0 <= start <= - * limit. - * @param limit pointer to the ending index, exclusive; start <= - * limit <= repFunc->length(rep). Upon return, *limit will - * contain the new limit index. The text previously occupying - * [start, limit) has been transliterated, possibly to a - * string of a different length, at [start, - * new-limit), where new-limit - * is the return value. - * @param status a pointer to the UErrorCode - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -utrans_trans(const UTransliterator* trans, - UReplaceable* rep, - UReplaceableCallbacks* repFunc, - int32_t start, - int32_t* limit, - UErrorCode* status); - -/** - * Transliterate the portion of the UReplaceable text buffer that can - * be transliterated unambiguosly. This method is typically called - * after new text has been inserted, e.g. as a result of a keyboard - * event. The transliterator will try to transliterate characters of - * rep between index.cursor and - * index.limit. Characters before - * index.cursor will not be changed. - * - *

Upon return, values in index will be updated. - * index.start will be advanced to the first - * character that future calls to this method will read. - * index.cursor and index.limit will - * be adjusted to delimit the range of text that future calls to - * this method may change. - * - *

Typical usage of this method begins with an initial call - * with index.start and index.limit - * set to indicate the portion of text to be - * transliterated, and index.cursor == index.start. - * Thereafter, index can be used without - * modification in future calls, provided that all changes to - * text are made via this method. - * - *

This method assumes that future calls may be made that will - * insert new text into the buffer. As a result, it only performs - * unambiguous transliterations. After the last call to this method, - * there may be untransliterated text that is waiting for more input - * to resolve an ambiguity. In order to perform these pending - * transliterations, clients should call utrans_trans() with a start - * of index.start and a limit of index.end after the last call to this - * method has been made. - * - * @param trans the transliterator - * @param rep a pointer to the string. This will be passed to the - * repFunc functions. - * @param repFunc a set of function pointers that will be used to - * modify the string pointed to by rep. - * @param pos a struct containing the start and limit indices of the - * text to be read and the text to be transliterated - * @param status a pointer to the UErrorCode - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -utrans_transIncremental(const UTransliterator* trans, - UReplaceable* rep, - UReplaceableCallbacks* repFunc, - UTransPosition* pos, - UErrorCode* status); - -/** - * Transliterate a segment of a UChar* string. The string is passed - * in in a UChar* buffer. The string is modified in place. If the - * result is longer than textCapacity, it is truncated. The actual - * length of the result is returned in *textLength, if textLength is - * non-NULL. *textLength may be greater than textCapacity, but only - * textCapacity UChars will be written to *text, including the zero - * terminator. - * - * @param trans the transliterator - * @param text a pointer to a buffer containing the text to be - * transliterated on input and the result text on output. - * @param textLength a pointer to the length of the string in text. - * If the length is -1 then the string is assumed to be - * zero-terminated. Upon return, the new length is stored in - * *textLength. If textLength is NULL then the string is assumed to - * be zero-terminated. - * @param textCapacity a pointer to the length of the text buffer. - * Upon return, - * @param start the beginning index, inclusive; 0 <= start <= - * limit. - * @param limit pointer to the ending index, exclusive; start <= - * limit <= repFunc->length(rep). Upon return, *limit will - * contain the new limit index. The text previously occupying - * [start, limit) has been transliterated, possibly to a - * string of a different length, at [start, - * new-limit), where new-limit - * is the return value. - * @param status a pointer to the UErrorCode - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -utrans_transUChars(const UTransliterator* trans, - UChar* text, - int32_t* textLength, - int32_t textCapacity, - int32_t start, - int32_t* limit, - UErrorCode* status); - -/** - * Transliterate the portion of the UChar* text buffer that can be - * transliterated unambiguosly. See utrans_transIncremental(). The - * string is passed in in a UChar* buffer. The string is modified in - * place. If the result is longer than textCapacity, it is truncated. - * The actual length of the result is returned in *textLength, if - * textLength is non-NULL. *textLength may be greater than - * textCapacity, but only textCapacity UChars will be written to - * *text, including the zero terminator. See utrans_transIncremental() - * for usage details. - * - * @param trans the transliterator - * @param text a pointer to a buffer containing the text to be - * transliterated on input and the result text on output. - * @param textLength a pointer to the length of the string in text. - * If the length is -1 then the string is assumed to be - * zero-terminated. Upon return, the new length is stored in - * *textLength. If textLength is NULL then the string is assumed to - * be zero-terminated. - * @param textCapacity the length of the text buffer - * @param pos a struct containing the start and limit indices of the - * text to be read and the text to be transliterated - * @param status a pointer to the UErrorCode - * @see utrans_transIncremental - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -utrans_transIncrementalUChars(const UTransliterator* trans, - UChar* text, - int32_t* textLength, - int32_t textCapacity, - UTransPosition* pos, - UErrorCode* status); - -/** - * Create a rule string that can be passed to utrans_openU to recreate this - * transliterator. - * - * @param trans The transliterator - * @param escapeUnprintable if TRUE then convert unprintable characters to their - * hex escape representations, \\uxxxx or \\Uxxxxxxxx. - * Unprintable characters are those other than - * U+000A, U+0020..U+007E. - * @param result A pointer to a buffer to receive the rules. - * @param resultLength The maximum size of result. - * @param status A pointer to the UErrorCode. In case of error status, the - * contents of result are undefined. - * @return int32_t The length of the rule string (may be greater than resultLength, - * in which case an error is returned). - * @stable ICU 53 - */ -U_STABLE int32_t U_EXPORT2 -utrans_toRules( const UTransliterator* trans, - UBool escapeUnprintable, - UChar* result, int32_t resultLength, - UErrorCode* status); - -/** - * Returns the set of all characters that may be modified in the input text by - * this UTransliterator, optionally ignoring the transliterator's current filter. - * @param trans The transliterator. - * @param ignoreFilter If FALSE, the returned set incorporates the - * UTransliterator's current filter; if the filter is changed, - * the return value of this function will change. If TRUE, the - * returned set ignores the effect of the UTransliterator's - * current filter. - * @param fillIn Pointer to a USet object to receive the modifiable characters - * set. Previous contents of fillIn are lost. If fillIn is - * NULL, then a new USet is created and returned. The caller - * owns the result and must dispose of it by calling uset_close. - * @param status A pointer to the UErrorCode. - * @return USet* Either fillIn, or if fillIn is NULL, a pointer to a - * newly-allocated USet that the user must close. In case of - * error, NULL is returned. - * @stable ICU 53 - */ -U_STABLE USet* U_EXPORT2 -utrans_getSourceSet(const UTransliterator* trans, - UBool ignoreFilter, - USet* fillIn, - UErrorCode* status); - -/* deprecated API ----------------------------------------------------------- */ - -#ifndef U_HIDE_DEPRECATED_API - -/* see utrans.h documentation for why these functions are deprecated */ - -/** - * Deprecated, use utrans_openU() instead. - * Open a custom transliterator, given a custom rules string - * OR - * a system transliterator, given its ID. - * Any non-NULL result from this function should later be closed with - * utrans_close(). - * - * @param id a valid ID, as returned by utrans_getAvailableID() - * @param dir the desired direction - * @param rules the transliterator rules. See the C++ header rbt.h - * for rules syntax. If NULL then a system transliterator matching - * the ID is returned. - * @param rulesLength the length of the rules, or -1 if the rules - * are zero-terminated. - * @param parseError a pointer to a UParseError struct to receive the - * details of any parsing errors. This parameter may be NULL if no - * parsing error details are desired. - * @param status a pointer to the UErrorCode - * @return a transliterator pointer that may be passed to other - * utrans_xxx() functions, or NULL if the open call fails. - * @deprecated ICU 2.8 Use utrans_openU() instead, see utrans.h - */ -U_DEPRECATED UTransliterator* U_EXPORT2 -utrans_open(const char* id, - UTransDirection dir, - const UChar* rules, /* may be Null */ - int32_t rulesLength, /* -1 if null-terminated */ - UParseError* parseError, /* may be Null */ - UErrorCode* status); - -/** - * Deprecated, use utrans_getUnicodeID() instead. - * Return the programmatic identifier for this transliterator. - * If this identifier is passed to utrans_open(), it will open - * a transliterator equivalent to this one, if the ID has been - * registered. - * @param trans the transliterator to return the ID of. - * @param buf the buffer in which to receive the ID. This may be - * NULL, in which case no characters are copied. - * @param bufCapacity the capacity of the buffer. Ignored if buf is - * NULL. - * @return the actual length of the ID, not including - * zero-termination. This may be greater than bufCapacity. - * @deprecated ICU 2.8 Use utrans_getUnicodeID() instead, see utrans.h - */ -U_DEPRECATED int32_t U_EXPORT2 -utrans_getID(const UTransliterator* trans, - char* buf, - int32_t bufCapacity); - -/** - * Deprecated, use utrans_unregisterID() instead. - * Unregister a transliterator from the system. After this call the - * system will no longer recognize the given ID when passed to - * utrans_open(). If the id is invalid then nothing is done. - * - * @param id a zero-terminated ID - * @deprecated ICU 2.8 Use utrans_unregisterID() instead, see utrans.h - */ -U_DEPRECATED void U_EXPORT2 -utrans_unregister(const char* id); - -/** - * Deprecated, use utrans_openIDs() instead. - * Return the ID of the index-th system transliterator. The result - * is placed in the given buffer. If the given buffer is too small, - * the initial substring is copied to buf. The result in buf is - * always zero-terminated. - * - * @param index the number of the transliterator to return. Must - * satisfy 0 <= index < utrans_countAvailableIDs(). If index is out - * of range then it is treated as if it were 0. - * @param buf the buffer in which to receive the ID. This may be - * NULL, in which case no characters are copied. - * @param bufCapacity the capacity of the buffer. Ignored if buf is - * NULL. - * @return the actual length of the index-th ID, not including - * zero-termination. This may be greater than bufCapacity. - * @deprecated ICU 2.8 Use utrans_openIDs() instead, see utrans.h - */ -U_DEPRECATED int32_t U_EXPORT2 -utrans_getAvailableID(int32_t index, - char* buf, - int32_t bufCapacity); - -#endif /* U_HIDE_DEPRECATED_API */ - -#endif /* #if !UCONFIG_NO_TRANSLITERATION */ - -#endif diff --git a/win32/include/spidermonkey/unicode/utypes.h b/win32/include/spidermonkey/unicode/utypes.h deleted file mode 100755 index 3d19c503..00000000 --- a/win32/include/spidermonkey/unicode/utypes.h +++ /dev/null @@ -1,701 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -********************************************************************** -* Copyright (C) 1996-2016, International Business Machines -* Corporation and others. All Rights Reserved. -********************************************************************** -* -* FILE NAME : UTYPES.H (formerly ptypes.h) -* -* Date Name Description -* 12/11/96 helena Creation. -* 02/27/97 aliu Added typedefs for UClassID, int8, int16, int32, -* uint8, uint16, and uint32. -* 04/01/97 aliu Added XP_CPLUSPLUS and modified to work under C as -* well as C++. -* Modified to use memcpy() for uprv_arrayCopy() fns. -* 04/14/97 aliu Added TPlatformUtilities. -* 05/07/97 aliu Added import/export specifiers (replacing the old -* broken EXT_CLASS). Added version number for our -* code. Cleaned up header. -* 6/20/97 helena Java class name change. -* 08/11/98 stephen UErrorCode changed from typedef to enum -* 08/12/98 erm Changed T_ANALYTIC_PACKAGE_VERSION to 3 -* 08/14/98 stephen Added uprv_arrayCopy() for int8_t, int16_t, int32_t -* 12/09/98 jfitz Added BUFFER_OVERFLOW_ERROR (bug 1100066) -* 04/20/99 stephen Cleaned up & reworked for autoconf. -* Renamed to utypes.h. -* 05/05/99 stephen Changed to use -* 12/07/99 helena Moved copyright notice string from ucnv_bld.h here. -******************************************************************************* -*/ - -#ifndef UTYPES_H -#define UTYPES_H - - -#include "unicode/umachine.h" -#include "unicode/uversion.h" -#include "unicode/uconfig.h" -#include - -#if !U_NO_DEFAULT_INCLUDE_UTF_HEADERS -# include "unicode/utf.h" -#endif - -/*! - * \file - * \brief Basic definitions for ICU, for both C and C++ APIs - * - * This file defines basic types, constants, and enumerations directly or - * indirectly by including other header files, especially utf.h for the - * basic character and string definitions and umachine.h for consistent - * integer and other types. - */ - - -/** - * \def U_SHOW_CPLUSPLUS_API - * @internal - */ -#ifdef __cplusplus -# ifndef U_SHOW_CPLUSPLUS_API -# define U_SHOW_CPLUSPLUS_API 1 -# endif -#else -# undef U_SHOW_CPLUSPLUS_API -# define U_SHOW_CPLUSPLUS_API 0 -#endif - -/** @{ API visibility control */ - -/** - * \def U_HIDE_DRAFT_API - * Define this to 1 to request that draft API be "hidden" - * @internal - */ -/** - * \def U_HIDE_INTERNAL_API - * Define this to 1 to request that internal API be "hidden" - * @internal - */ -#if !U_DEFAULT_SHOW_DRAFT && !defined(U_SHOW_DRAFT_API) -#define U_HIDE_DRAFT_API 1 -#endif -#if !U_DEFAULT_SHOW_DRAFT && !defined(U_SHOW_INTERNAL_API) -#define U_HIDE_INTERNAL_API 1 -#endif - -/** @} */ - -/*===========================================================================*/ -/* ICUDATA naming scheme */ -/*===========================================================================*/ - -/** - * \def U_ICUDATA_TYPE_LETTER - * - * This is a platform-dependent string containing one letter: - * - b for big-endian, ASCII-family platforms - * - l for little-endian, ASCII-family platforms - * - e for big-endian, EBCDIC-family platforms - * This letter is part of the common data file name. - * @stable ICU 2.0 - */ - -/** - * \def U_ICUDATA_TYPE_LITLETTER - * The non-string form of U_ICUDATA_TYPE_LETTER - * @stable ICU 2.0 - */ -#if U_CHARSET_FAMILY -# if U_IS_BIG_ENDIAN - /* EBCDIC - should always be BE */ -# define U_ICUDATA_TYPE_LETTER "e" -# define U_ICUDATA_TYPE_LITLETTER e -# else -# error "Don't know what to do with little endian EBCDIC!" -# define U_ICUDATA_TYPE_LETTER "x" -# define U_ICUDATA_TYPE_LITLETTER x -# endif -#else -# if U_IS_BIG_ENDIAN - /* Big-endian ASCII */ -# define U_ICUDATA_TYPE_LETTER "b" -# define U_ICUDATA_TYPE_LITLETTER b -# else - /* Little-endian ASCII */ -# define U_ICUDATA_TYPE_LETTER "l" -# define U_ICUDATA_TYPE_LITLETTER l -# endif -#endif - -/** - * A single string literal containing the icudata stub name. i.e. 'icudt18e' for - * ICU 1.8.x on EBCDIC, etc.. - * @stable ICU 2.0 - */ -#define U_ICUDATA_NAME "icudt" U_ICU_VERSION_SHORT U_ICUDATA_TYPE_LETTER -#ifndef U_HIDE_INTERNAL_API -#define U_USRDATA_NAME "usrdt" U_ICU_VERSION_SHORT U_ICUDATA_TYPE_LETTER /**< @internal */ -#define U_USE_USRDATA 0 /**< @internal */ -#endif /* U_HIDE_INTERNAL_API */ - -/** - * U_ICU_ENTRY_POINT is the name of the DLL entry point to the ICU data library. - * Defined as a literal, not a string. - * Tricky Preprocessor use - ## operator replaces macro paramters with the literal string - * from the corresponding macro invocation, _before_ other macro substitutions. - * Need a nested \#defines to get the actual version numbers rather than - * the literal text U_ICU_VERSION_MAJOR_NUM into the name. - * The net result will be something of the form - * \#define U_ICU_ENTRY_POINT icudt19_dat - * @stable ICU 2.4 - */ -#define U_ICUDATA_ENTRY_POINT U_DEF2_ICUDATA_ENTRY_POINT(U_ICU_VERSION_MAJOR_NUM,U_LIB_SUFFIX_C_NAME) - -#ifndef U_HIDE_INTERNAL_API -/** - * Do not use. Note that it's OK for the 2nd argument to be undefined (literal). - * @internal - */ -#define U_DEF2_ICUDATA_ENTRY_POINT(major,suff) U_DEF_ICUDATA_ENTRY_POINT(major,suff) - -/** - * Do not use. - * @internal - */ -#ifndef U_DEF_ICUDATA_ENTRY_POINT -/* affected by symbol renaming. See platform.h */ -#ifndef U_LIB_SUFFIX_C_NAME -#define U_DEF_ICUDATA_ENTRY_POINT(major, suff) icudt##major##_dat -#else -#define U_DEF_ICUDATA_ENTRY_POINT(major, suff) icudt##suff ## major##_dat -#endif -#endif -#endif /* U_HIDE_INTERNAL_API */ - -/** - * \def NULL - * Define NULL if necessary, to 0 for C++ and to ((void *)0) for C. - * @stable ICU 2.0 - */ -#ifndef NULL -#ifdef __cplusplus -#define NULL 0 -#else -#define NULL ((void *)0) -#endif -#endif - -/*===========================================================================*/ -/* Calendar/TimeZone data types */ -/*===========================================================================*/ - -/** - * Date and Time data type. - * This is a primitive data type that holds the date and time - * as the number of milliseconds since 1970-jan-01, 00:00 UTC. - * UTC leap seconds are ignored. - * @stable ICU 2.0 - */ -typedef double UDate; - -/** The number of milliseconds per second @stable ICU 2.0 */ -#define U_MILLIS_PER_SECOND (1000) -/** The number of milliseconds per minute @stable ICU 2.0 */ -#define U_MILLIS_PER_MINUTE (60000) -/** The number of milliseconds per hour @stable ICU 2.0 */ -#define U_MILLIS_PER_HOUR (3600000) -/** The number of milliseconds per day @stable ICU 2.0 */ -#define U_MILLIS_PER_DAY (86400000) - -/** - * Maximum UDate value - * @stable ICU 4.8 - */ -#define U_DATE_MAX DBL_MAX - -/** - * Minimum UDate value - * @stable ICU 4.8 - */ -#define U_DATE_MIN -U_DATE_MAX - -/*===========================================================================*/ -/* Shared library/DLL import-export API control */ -/*===========================================================================*/ - -/* - * Control of symbol import/export. - * ICU is separated into three libraries. - */ - -/** - * \def U_COMBINED_IMPLEMENTATION - * Set to export library symbols from inside the ICU library - * when all of ICU is in a single library. - * This can be set as a compiler option while building ICU, and it - * needs to be the first one tested to override U_COMMON_API, U_I18N_API, etc. - * @stable ICU 2.0 - */ - -/** - * \def U_DATA_API - * Set to export library symbols from inside the stubdata library, - * and to import them from outside. - * @stable ICU 3.0 - */ - -/** - * \def U_COMMON_API - * Set to export library symbols from inside the common library, - * and to import them from outside. - * @stable ICU 2.0 - */ - -/** - * \def U_I18N_API - * Set to export library symbols from inside the i18n library, - * and to import them from outside. - * @stable ICU 2.0 - */ - -/** - * \def U_LAYOUT_API - * Set to export library symbols from inside the layout engine library, - * and to import them from outside. - * @stable ICU 2.0 - */ - -/** - * \def U_LAYOUTEX_API - * Set to export library symbols from inside the layout extensions library, - * and to import them from outside. - * @stable ICU 2.6 - */ - -/** - * \def U_IO_API - * Set to export library symbols from inside the ustdio library, - * and to import them from outside. - * @stable ICU 2.0 - */ - -/** - * \def U_TOOLUTIL_API - * Set to export library symbols from inside the toolutil library, - * and to import them from outside. - * @stable ICU 3.4 - */ - -#if defined(U_COMBINED_IMPLEMENTATION) -#define U_DATA_API U_EXPORT -#define U_COMMON_API U_EXPORT -#define U_I18N_API U_EXPORT -#define U_LAYOUT_API U_EXPORT -#define U_LAYOUTEX_API U_EXPORT -#define U_IO_API U_EXPORT -#define U_TOOLUTIL_API U_EXPORT -#elif defined(U_STATIC_IMPLEMENTATION) -#define U_DATA_API -#define U_COMMON_API -#define U_I18N_API -#define U_LAYOUT_API -#define U_LAYOUTEX_API -#define U_IO_API -#define U_TOOLUTIL_API -#elif defined(U_COMMON_IMPLEMENTATION) -#define U_DATA_API U_IMPORT -#define U_COMMON_API U_EXPORT -#define U_I18N_API U_IMPORT -#define U_LAYOUT_API U_IMPORT -#define U_LAYOUTEX_API U_IMPORT -#define U_IO_API U_IMPORT -#define U_TOOLUTIL_API U_IMPORT -#elif defined(U_I18N_IMPLEMENTATION) -#define U_DATA_API U_IMPORT -#define U_COMMON_API U_IMPORT -#define U_I18N_API U_EXPORT -#define U_LAYOUT_API U_IMPORT -#define U_LAYOUTEX_API U_IMPORT -#define U_IO_API U_IMPORT -#define U_TOOLUTIL_API U_IMPORT -#elif defined(U_LAYOUT_IMPLEMENTATION) -#define U_DATA_API U_IMPORT -#define U_COMMON_API U_IMPORT -#define U_I18N_API U_IMPORT -#define U_LAYOUT_API U_EXPORT -#define U_LAYOUTEX_API U_IMPORT -#define U_IO_API U_IMPORT -#define U_TOOLUTIL_API U_IMPORT -#elif defined(U_LAYOUTEX_IMPLEMENTATION) -#define U_DATA_API U_IMPORT -#define U_COMMON_API U_IMPORT -#define U_I18N_API U_IMPORT -#define U_LAYOUT_API U_IMPORT -#define U_LAYOUTEX_API U_EXPORT -#define U_IO_API U_IMPORT -#define U_TOOLUTIL_API U_IMPORT -#elif defined(U_IO_IMPLEMENTATION) -#define U_DATA_API U_IMPORT -#define U_COMMON_API U_IMPORT -#define U_I18N_API U_IMPORT -#define U_LAYOUT_API U_IMPORT -#define U_LAYOUTEX_API U_IMPORT -#define U_IO_API U_EXPORT -#define U_TOOLUTIL_API U_IMPORT -#elif defined(U_TOOLUTIL_IMPLEMENTATION) -#define U_DATA_API U_IMPORT -#define U_COMMON_API U_IMPORT -#define U_I18N_API U_IMPORT -#define U_LAYOUT_API U_IMPORT -#define U_LAYOUTEX_API U_IMPORT -#define U_IO_API U_IMPORT -#define U_TOOLUTIL_API U_EXPORT -#else -#define U_DATA_API U_IMPORT -#define U_COMMON_API U_IMPORT -#define U_I18N_API U_IMPORT -#define U_LAYOUT_API U_IMPORT -#define U_LAYOUTEX_API U_IMPORT -#define U_IO_API U_IMPORT -#define U_TOOLUTIL_API U_IMPORT -#endif - -/** - * \def U_STANDARD_CPP_NAMESPACE - * Control of C++ Namespace - * @stable ICU 2.0 - */ -#ifdef __cplusplus -#define U_STANDARD_CPP_NAMESPACE :: -#else -#define U_STANDARD_CPP_NAMESPACE -#endif - -/*===========================================================================*/ -/* UErrorCode */ -/*===========================================================================*/ - -/** - * Error code to replace exception handling, so that the code is compatible with all C++ compilers, - * and to use the same mechanism for C and C++. - * - * \par - * ICU functions that take a reference (C++) or a pointer (C) to a UErrorCode - * first test if(U_FAILURE(errorCode)) { return immediately; } - * so that in a chain of such functions the first one that sets an error code - * causes the following ones to not perform any operations. - * - * \par - * Error codes should be tested using U_FAILURE() and U_SUCCESS(). - * @stable ICU 2.0 - */ -typedef enum UErrorCode { - /* The ordering of U_ERROR_INFO_START Vs U_USING_FALLBACK_WARNING looks weird - * and is that way because VC++ debugger displays first encountered constant, - * which is not the what the code is used for - */ - - U_USING_FALLBACK_WARNING = -128, /**< A resource bundle lookup returned a fallback result (not an error) */ - - U_ERROR_WARNING_START = -128, /**< Start of information results (semantically successful) */ - - U_USING_DEFAULT_WARNING = -127, /**< A resource bundle lookup returned a result from the root locale (not an error) */ - - U_SAFECLONE_ALLOCATED_WARNING = -126, /**< A SafeClone operation required allocating memory (informational only) */ - - U_STATE_OLD_WARNING = -125, /**< ICU has to use compatibility layer to construct the service. Expect performance/memory usage degradation. Consider upgrading */ - - U_STRING_NOT_TERMINATED_WARNING = -124,/**< An output string could not be NUL-terminated because output length==destCapacity. */ - - U_SORT_KEY_TOO_SHORT_WARNING = -123, /**< Number of levels requested in getBound is higher than the number of levels in the sort key */ - - U_AMBIGUOUS_ALIAS_WARNING = -122, /**< This converter alias can go to different converter implementations */ - - U_DIFFERENT_UCA_VERSION = -121, /**< ucol_open encountered a mismatch between UCA version and collator image version, so the collator was constructed from rules. No impact to further function */ - - U_PLUGIN_CHANGED_LEVEL_WARNING = -120, /**< A plugin caused a level change. May not be an error, but later plugins may not load. */ - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal UErrorCode warning value. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_ERROR_WARNING_LIMIT, -#endif // U_HIDE_DEPRECATED_API - - U_ZERO_ERROR = 0, /**< No error, no warning. */ - - U_ILLEGAL_ARGUMENT_ERROR = 1, /**< Start of codes indicating failure */ - U_MISSING_RESOURCE_ERROR = 2, /**< The requested resource cannot be found */ - U_INVALID_FORMAT_ERROR = 3, /**< Data format is not what is expected */ - U_FILE_ACCESS_ERROR = 4, /**< The requested file cannot be found */ - U_INTERNAL_PROGRAM_ERROR = 5, /**< Indicates a bug in the library code */ - U_MESSAGE_PARSE_ERROR = 6, /**< Unable to parse a message (message format) */ - U_MEMORY_ALLOCATION_ERROR = 7, /**< Memory allocation error */ - U_INDEX_OUTOFBOUNDS_ERROR = 8, /**< Trying to access the index that is out of bounds */ - U_PARSE_ERROR = 9, /**< Equivalent to Java ParseException */ - U_INVALID_CHAR_FOUND = 10, /**< Character conversion: Unmappable input sequence. In other APIs: Invalid character. */ - U_TRUNCATED_CHAR_FOUND = 11, /**< Character conversion: Incomplete input sequence. */ - U_ILLEGAL_CHAR_FOUND = 12, /**< Character conversion: Illegal input sequence/combination of input units. */ - U_INVALID_TABLE_FORMAT = 13, /**< Conversion table file found, but corrupted */ - U_INVALID_TABLE_FILE = 14, /**< Conversion table file not found */ - U_BUFFER_OVERFLOW_ERROR = 15, /**< A result would not fit in the supplied buffer */ - U_UNSUPPORTED_ERROR = 16, /**< Requested operation not supported in current context */ - U_RESOURCE_TYPE_MISMATCH = 17, /**< an operation is requested over a resource that does not support it */ - U_ILLEGAL_ESCAPE_SEQUENCE = 18, /**< ISO-2022 illlegal escape sequence */ - U_UNSUPPORTED_ESCAPE_SEQUENCE = 19, /**< ISO-2022 unsupported escape sequence */ - U_NO_SPACE_AVAILABLE = 20, /**< No space available for in-buffer expansion for Arabic shaping */ - U_CE_NOT_FOUND_ERROR = 21, /**< Currently used only while setting variable top, but can be used generally */ - U_PRIMARY_TOO_LONG_ERROR = 22, /**< User tried to set variable top to a primary that is longer than two bytes */ - U_STATE_TOO_OLD_ERROR = 23, /**< ICU cannot construct a service from this state, as it is no longer supported */ - U_TOO_MANY_ALIASES_ERROR = 24, /**< There are too many aliases in the path to the requested resource. - It is very possible that a circular alias definition has occured */ - U_ENUM_OUT_OF_SYNC_ERROR = 25, /**< UEnumeration out of sync with underlying collection */ - U_INVARIANT_CONVERSION_ERROR = 26, /**< Unable to convert a UChar* string to char* with the invariant converter. */ - U_INVALID_STATE_ERROR = 27, /**< Requested operation can not be completed with ICU in its current state */ - U_COLLATOR_VERSION_MISMATCH = 28, /**< Collator version is not compatible with the base version */ - U_USELESS_COLLATOR_ERROR = 29, /**< Collator is options only and no base is specified */ - U_NO_WRITE_PERMISSION = 30, /**< Attempt to modify read-only or constant data. */ - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest standard error code. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_STANDARD_ERROR_LIMIT, -#endif // U_HIDE_DEPRECATED_API - - /* - * Error codes in the range 0x10000 0x10100 are reserved for Transliterator. - */ - U_BAD_VARIABLE_DEFINITION=0x10000,/**< Missing '$' or duplicate variable name */ - U_PARSE_ERROR_START = 0x10000, /**< Start of Transliterator errors */ - U_MALFORMED_RULE, /**< Elements of a rule are misplaced */ - U_MALFORMED_SET, /**< A UnicodeSet pattern is invalid*/ - U_MALFORMED_SYMBOL_REFERENCE, /**< UNUSED as of ICU 2.4 */ - U_MALFORMED_UNICODE_ESCAPE, /**< A Unicode escape pattern is invalid*/ - U_MALFORMED_VARIABLE_DEFINITION, /**< A variable definition is invalid */ - U_MALFORMED_VARIABLE_REFERENCE, /**< A variable reference is invalid */ - U_MISMATCHED_SEGMENT_DELIMITERS, /**< UNUSED as of ICU 2.4 */ - U_MISPLACED_ANCHOR_START, /**< A start anchor appears at an illegal position */ - U_MISPLACED_CURSOR_OFFSET, /**< A cursor offset occurs at an illegal position */ - U_MISPLACED_QUANTIFIER, /**< A quantifier appears after a segment close delimiter */ - U_MISSING_OPERATOR, /**< A rule contains no operator */ - U_MISSING_SEGMENT_CLOSE, /**< UNUSED as of ICU 2.4 */ - U_MULTIPLE_ANTE_CONTEXTS, /**< More than one ante context */ - U_MULTIPLE_CURSORS, /**< More than one cursor */ - U_MULTIPLE_POST_CONTEXTS, /**< More than one post context */ - U_TRAILING_BACKSLASH, /**< A dangling backslash */ - U_UNDEFINED_SEGMENT_REFERENCE, /**< A segment reference does not correspond to a defined segment */ - U_UNDEFINED_VARIABLE, /**< A variable reference does not correspond to a defined variable */ - U_UNQUOTED_SPECIAL, /**< A special character was not quoted or escaped */ - U_UNTERMINATED_QUOTE, /**< A closing single quote is missing */ - U_RULE_MASK_ERROR, /**< A rule is hidden by an earlier more general rule */ - U_MISPLACED_COMPOUND_FILTER, /**< A compound filter is in an invalid location */ - U_MULTIPLE_COMPOUND_FILTERS, /**< More than one compound filter */ - U_INVALID_RBT_SYNTAX, /**< A "::id" rule was passed to the RuleBasedTransliterator parser */ - U_INVALID_PROPERTY_PATTERN, /**< UNUSED as of ICU 2.4 */ - U_MALFORMED_PRAGMA, /**< A 'use' pragma is invlalid */ - U_UNCLOSED_SEGMENT, /**< A closing ')' is missing */ - U_ILLEGAL_CHAR_IN_SEGMENT, /**< UNUSED as of ICU 2.4 */ - U_VARIABLE_RANGE_EXHAUSTED, /**< Too many stand-ins generated for the given variable range */ - U_VARIABLE_RANGE_OVERLAP, /**< The variable range overlaps characters used in rules */ - U_ILLEGAL_CHARACTER, /**< A special character is outside its allowed context */ - U_INTERNAL_TRANSLITERATOR_ERROR, /**< Internal transliterator system error */ - U_INVALID_ID, /**< A "::id" rule specifies an unknown transliterator */ - U_INVALID_FUNCTION, /**< A "&fn()" rule specifies an unknown transliterator */ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal Transliterator error code. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_PARSE_ERROR_LIMIT, -#endif // U_HIDE_DEPRECATED_API - - /* - * Error codes in the range 0x10100 0x10200 are reserved for the formatting API. - */ - U_UNEXPECTED_TOKEN=0x10100, /**< Syntax error in format pattern */ - U_FMT_PARSE_ERROR_START=0x10100, /**< Start of format library errors */ - U_MULTIPLE_DECIMAL_SEPARATORS, /**< More than one decimal separator in number pattern */ - U_MULTIPLE_DECIMAL_SEPERATORS = U_MULTIPLE_DECIMAL_SEPARATORS, /**< Typo: kept for backward compatibility. Use U_MULTIPLE_DECIMAL_SEPARATORS */ - U_MULTIPLE_EXPONENTIAL_SYMBOLS, /**< More than one exponent symbol in number pattern */ - U_MALFORMED_EXPONENTIAL_PATTERN, /**< Grouping symbol in exponent pattern */ - U_MULTIPLE_PERCENT_SYMBOLS, /**< More than one percent symbol in number pattern */ - U_MULTIPLE_PERMILL_SYMBOLS, /**< More than one permill symbol in number pattern */ - U_MULTIPLE_PAD_SPECIFIERS, /**< More than one pad symbol in number pattern */ - U_PATTERN_SYNTAX_ERROR, /**< Syntax error in format pattern */ - U_ILLEGAL_PAD_POSITION, /**< Pad symbol misplaced in number pattern */ - U_UNMATCHED_BRACES, /**< Braces do not match in message pattern */ - U_UNSUPPORTED_PROPERTY, /**< UNUSED as of ICU 2.4 */ - U_UNSUPPORTED_ATTRIBUTE, /**< UNUSED as of ICU 2.4 */ - U_ARGUMENT_TYPE_MISMATCH, /**< Argument name and argument index mismatch in MessageFormat functions */ - U_DUPLICATE_KEYWORD, /**< Duplicate keyword in PluralFormat */ - U_UNDEFINED_KEYWORD, /**< Undefined Plural keyword */ - U_DEFAULT_KEYWORD_MISSING, /**< Missing DEFAULT rule in plural rules */ - U_DECIMAL_NUMBER_SYNTAX_ERROR, /**< Decimal number syntax error */ - U_FORMAT_INEXACT_ERROR, /**< Cannot format a number exactly and rounding mode is ROUND_UNNECESSARY @stable ICU 4.8 */ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal formatting API error code. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_FMT_PARSE_ERROR_LIMIT, -#endif // U_HIDE_DEPRECATED_API - - /* - * Error codes in the range 0x10200 0x102ff are reserved for BreakIterator. - */ - U_BRK_INTERNAL_ERROR=0x10200, /**< An internal error (bug) was detected. */ - U_BRK_ERROR_START=0x10200, /**< Start of codes indicating Break Iterator failures */ - U_BRK_HEX_DIGITS_EXPECTED, /**< Hex digits expected as part of a escaped char in a rule. */ - U_BRK_SEMICOLON_EXPECTED, /**< Missing ';' at the end of a RBBI rule. */ - U_BRK_RULE_SYNTAX, /**< Syntax error in RBBI rule. */ - U_BRK_UNCLOSED_SET, /**< UnicodeSet witing an RBBI rule missing a closing ']'. */ - U_BRK_ASSIGN_ERROR, /**< Syntax error in RBBI rule assignment statement. */ - U_BRK_VARIABLE_REDFINITION, /**< RBBI rule $Variable redefined. */ - U_BRK_MISMATCHED_PAREN, /**< Mis-matched parentheses in an RBBI rule. */ - U_BRK_NEW_LINE_IN_QUOTED_STRING, /**< Missing closing quote in an RBBI rule. */ - U_BRK_UNDEFINED_VARIABLE, /**< Use of an undefined $Variable in an RBBI rule. */ - U_BRK_INIT_ERROR, /**< Initialization failure. Probable missing ICU Data. */ - U_BRK_RULE_EMPTY_SET, /**< Rule contains an empty Unicode Set. */ - U_BRK_UNRECOGNIZED_OPTION, /**< !!option in RBBI rules not recognized. */ - U_BRK_MALFORMED_RULE_TAG, /**< The {nnn} tag on a rule is mal formed */ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal BreakIterator error code. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_BRK_ERROR_LIMIT, -#endif // U_HIDE_DEPRECATED_API - - /* - * Error codes in the range 0x10300-0x103ff are reserved for regular expression related errors. - */ - U_REGEX_INTERNAL_ERROR=0x10300, /**< An internal error (bug) was detected. */ - U_REGEX_ERROR_START=0x10300, /**< Start of codes indicating Regexp failures */ - U_REGEX_RULE_SYNTAX, /**< Syntax error in regexp pattern. */ - U_REGEX_INVALID_STATE, /**< RegexMatcher in invalid state for requested operation */ - U_REGEX_BAD_ESCAPE_SEQUENCE, /**< Unrecognized backslash escape sequence in pattern */ - U_REGEX_PROPERTY_SYNTAX, /**< Incorrect Unicode property */ - U_REGEX_UNIMPLEMENTED, /**< Use of regexp feature that is not yet implemented. */ - U_REGEX_MISMATCHED_PAREN, /**< Incorrectly nested parentheses in regexp pattern. */ - U_REGEX_NUMBER_TOO_BIG, /**< Decimal number is too large. */ - U_REGEX_BAD_INTERVAL, /**< Error in {min,max} interval */ - U_REGEX_MAX_LT_MIN, /**< In {min,max}, max is less than min. */ - U_REGEX_INVALID_BACK_REF, /**< Back-reference to a non-existent capture group. */ - U_REGEX_INVALID_FLAG, /**< Invalid value for match mode flags. */ - U_REGEX_LOOK_BEHIND_LIMIT, /**< Look-Behind pattern matches must have a bounded maximum length. */ - U_REGEX_SET_CONTAINS_STRING, /**< Regexps cannot have UnicodeSets containing strings.*/ -#ifndef U_HIDE_DEPRECATED_API - U_REGEX_OCTAL_TOO_BIG, /**< Octal character constants must be <= 0377. @deprecated ICU 54. This error cannot occur. */ -#endif /* U_HIDE_DEPRECATED_API */ - U_REGEX_MISSING_CLOSE_BRACKET=U_REGEX_SET_CONTAINS_STRING+2, /**< Missing closing bracket on a bracket expression. */ - U_REGEX_INVALID_RANGE, /**< In a character range [x-y], x is greater than y. */ - U_REGEX_STACK_OVERFLOW, /**< Regular expression backtrack stack overflow. */ - U_REGEX_TIME_OUT, /**< Maximum allowed match time exceeded */ - U_REGEX_STOPPED_BY_CALLER, /**< Matching operation aborted by user callback fn. */ - U_REGEX_PATTERN_TOO_BIG, /**< Pattern exceeds limits on size or complexity. @stable ICU 55 */ - U_REGEX_INVALID_CAPTURE_GROUP_NAME, /**< Invalid capture group name. @stable ICU 55 */ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal regular expression error code. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_REGEX_ERROR_LIMIT=U_REGEX_STOPPED_BY_CALLER+3, -#endif // U_HIDE_DEPRECATED_API - - /* - * Error codes in the range 0x10400-0x104ff are reserved for IDNA related error codes. - */ - U_IDNA_PROHIBITED_ERROR=0x10400, - U_IDNA_ERROR_START=0x10400, - U_IDNA_UNASSIGNED_ERROR, - U_IDNA_CHECK_BIDI_ERROR, - U_IDNA_STD3_ASCII_RULES_ERROR, - U_IDNA_ACE_PREFIX_ERROR, - U_IDNA_VERIFICATION_ERROR, - U_IDNA_LABEL_TOO_LONG_ERROR, - U_IDNA_ZERO_LENGTH_LABEL_ERROR, - U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR, -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal IDNA error code. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_IDNA_ERROR_LIMIT, -#endif // U_HIDE_DEPRECATED_API - /* - * Aliases for StringPrep - */ - U_STRINGPREP_PROHIBITED_ERROR = U_IDNA_PROHIBITED_ERROR, - U_STRINGPREP_UNASSIGNED_ERROR = U_IDNA_UNASSIGNED_ERROR, - U_STRINGPREP_CHECK_BIDI_ERROR = U_IDNA_CHECK_BIDI_ERROR, - - /* - * Error codes in the range 0x10500-0x105ff are reserved for Plugin related error codes. - */ - U_PLUGIN_ERROR_START=0x10500, /**< Start of codes indicating plugin failures */ - U_PLUGIN_TOO_HIGH=0x10500, /**< The plugin's level is too high to be loaded right now. */ - U_PLUGIN_DIDNT_SET_LEVEL, /**< The plugin didn't call uplug_setPlugLevel in response to a QUERY */ -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal plug-in error code. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_PLUGIN_ERROR_LIMIT, -#endif // U_HIDE_DEPRECATED_API - -#ifndef U_HIDE_DEPRECATED_API - /** - * One more than the highest normal error code. - * @deprecated ICU 58 The numeric value may change over time, see ICU ticket #12420. - */ - U_ERROR_LIMIT=U_PLUGIN_ERROR_LIMIT -#endif // U_HIDE_DEPRECATED_API -} UErrorCode; - -/* Use the following to determine if an UErrorCode represents */ -/* operational success or failure. */ - -#ifdef __cplusplus - /** - * Does the error code indicate success? - * @stable ICU 2.0 - */ - static - inline UBool U_SUCCESS(UErrorCode code) { return (UBool)(code<=U_ZERO_ERROR); } - /** - * Does the error code indicate a failure? - * @stable ICU 2.0 - */ - static - inline UBool U_FAILURE(UErrorCode code) { return (UBool)(code>U_ZERO_ERROR); } -#else - /** - * Does the error code indicate success? - * @stable ICU 2.0 - */ -# define U_SUCCESS(x) ((x)<=U_ZERO_ERROR) - /** - * Does the error code indicate a failure? - * @stable ICU 2.0 - */ -# define U_FAILURE(x) ((x)>U_ZERO_ERROR) -#endif - -/** - * Return a string for a UErrorCode value. - * The string will be the same as the name of the error code constant - * in the UErrorCode enum above. - * @stable ICU 2.0 - */ -U_STABLE const char * U_EXPORT2 -u_errorName(UErrorCode code); - - -#endif /* _UTYPES */ diff --git a/win32/include/spidermonkey/unicode/uvernum.h b/win32/include/spidermonkey/unicode/uvernum.h deleted file mode 100755 index 5590f9a5..00000000 --- a/win32/include/spidermonkey/unicode/uvernum.h +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2000-2016, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* -* file name: uvernum.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* Created by: Vladimir Weinstein -* Updated by: Steven R. Loomis -* -*/ - -/** - * \file - * \brief C API: definitions of ICU version numbers - * - * This file is included by uversion.h and other files. This file contains only - * macros and definitions. The actual version numbers are defined here. - */ - - /* - * IMPORTANT: When updating version, the following things need to be done: - * source/common/unicode/uvernum.h - this file: update major, minor, - * patchlevel, suffix, version, short version constants, namespace, - * renaming macro, and copyright - * - * The following files need to be updated as well, which can be done - * by running the UNIX makefile target 'update-windows-makefiles' in icu/source. - * - * - * source/common/common.vcxproj - update 'Output file name' on the link tab so - * that it contains the new major/minor combination - * source/i18n/i18n.vcxproj - same as for the common.vcxproj - * source/layoutex/layoutex.vcproj - same - * source/stubdata/stubdata.vcproj - same as for the common.vcxproj - * source/io/io.vcproj - same as for the common.vcxproj - * source/data/makedata.mak - change U_ICUDATA_NAME so that it contains - * the new major/minor combination and the Unicode version. - */ - -#ifndef UVERNUM_H -#define UVERNUM_H - -/** The standard copyright notice that gets compiled into each library. - * This value will change in the subsequent releases of ICU - * @stable ICU 2.4 - */ -#define U_COPYRIGHT_STRING \ - " Copyright (C) 2016 and later: Unicode, Inc. and others. License & terms of use: http://www.unicode.org/copyright.html " - -/** The current ICU major version as an integer. - * This value will change in the subsequent releases of ICU - * @stable ICU 2.4 - */ -#define U_ICU_VERSION_MAJOR_NUM 58 - -/** The current ICU minor version as an integer. - * This value will change in the subsequent releases of ICU - * @stable ICU 2.6 - */ -#define U_ICU_VERSION_MINOR_NUM 2 - -/** The current ICU patchlevel version as an integer. - * This value will change in the subsequent releases of ICU - * @stable ICU 2.4 - */ -#define U_ICU_VERSION_PATCHLEVEL_NUM 0 - -/** The current ICU build level version as an integer. - * This value is for use by ICU clients. It defaults to 0. - * @stable ICU 4.0 - */ -#ifndef U_ICU_VERSION_BUILDLEVEL_NUM -#define U_ICU_VERSION_BUILDLEVEL_NUM 0 -#endif - -/** Glued version suffix for renamers - * This value will change in the subsequent releases of ICU - * @stable ICU 2.6 - */ -#define U_ICU_VERSION_SUFFIX _58 - -/** - * \def U_DEF2_ICU_ENTRY_POINT_RENAME - * @internal - */ -/** - * \def U_DEF_ICU_ENTRY_POINT_RENAME - * @internal - */ -/** Glued version suffix function for renamers - * This value will change in the subsequent releases of ICU. - * If a custom suffix (such as matching library suffixes) is desired, this can be modified. - * Note that if present, platform.h may contain an earlier definition of this macro. - * \def U_ICU_ENTRY_POINT_RENAME - * @stable ICU 4.2 - */ - -#ifndef U_ICU_ENTRY_POINT_RENAME -#ifdef U_HAVE_LIB_SUFFIX -#define U_DEF_ICU_ENTRY_POINT_RENAME(x,y,z) x ## y ## z -#define U_DEF2_ICU_ENTRY_POINT_RENAME(x,y,z) U_DEF_ICU_ENTRY_POINT_RENAME(x,y,z) -#define U_ICU_ENTRY_POINT_RENAME(x) U_DEF2_ICU_ENTRY_POINT_RENAME(x,U_ICU_VERSION_SUFFIX,U_LIB_SUFFIX_C_NAME) -#else -#define U_DEF_ICU_ENTRY_POINT_RENAME(x,y) x ## y -#define U_DEF2_ICU_ENTRY_POINT_RENAME(x,y) U_DEF_ICU_ENTRY_POINT_RENAME(x,y) -#define U_ICU_ENTRY_POINT_RENAME(x) U_DEF2_ICU_ENTRY_POINT_RENAME(x,U_ICU_VERSION_SUFFIX) -#endif -#endif - -/** The current ICU library version as a dotted-decimal string. The patchlevel - * only appears in this string if it non-zero. - * This value will change in the subsequent releases of ICU - * @stable ICU 2.4 - */ -#define U_ICU_VERSION "58.2" - -/** The current ICU library major/minor version as a string without dots, for library name suffixes. - * This value will change in the subsequent releases of ICU - * @stable ICU 2.6 - */ -#define U_ICU_VERSION_SHORT "58" - -#ifndef U_HIDE_INTERNAL_API -/** Data version in ICU4C. - * @internal ICU 4.4 Internal Use Only - **/ -#define U_ICU_DATA_VERSION "58.2" -#endif /* U_HIDE_INTERNAL_API */ - -/*=========================================================================== - * ICU collation framework version information - * Version info that can be obtained from a collator is affected by these - * numbers in a secret and magic way. Please use collator version as whole - *=========================================================================== - */ - -/** - * Collation runtime version (sort key generator, strcoll). - * If the version is different, sort keys for the same string could be different. - * This value may change in subsequent releases of ICU. - * @stable ICU 2.4 - */ -#define UCOL_RUNTIME_VERSION 9 - -/** - * Collation builder code version. - * When this is different, the same tailoring might result - * in assigning different collation elements to code points. - * This value may change in subsequent releases of ICU. - * @stable ICU 2.4 - */ -#define UCOL_BUILDER_VERSION 9 - -#ifndef U_HIDE_DEPRECATED_API -/** - * Constant 1. - * This was intended to be the version of collation tailorings, - * but instead the tailoring data carries a version number. - * @deprecated ICU 54 - */ -#define UCOL_TAILORINGS_VERSION 1 -#endif /* U_HIDE_DEPRECATED_API */ - -#endif diff --git a/win32/include/spidermonkey/unicode/uversion.h b/win32/include/spidermonkey/unicode/uversion.h deleted file mode 100755 index 3f8ad360..00000000 --- a/win32/include/spidermonkey/unicode/uversion.h +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2000-2011, International Business Machines -* Corporation and others. All Rights Reserved. -******************************************************************************* -* -* file name: uversion.h -* encoding: US-ASCII -* tab size: 8 (not used) -* indentation:4 -* -* Created by: Vladimir Weinstein -* -* Gets included by utypes.h and Windows .rc files -*/ - -/** - * \file - * \brief C API: API for accessing ICU version numbers. - */ -/*===========================================================================*/ -/* Main ICU version information */ -/*===========================================================================*/ - -#ifndef UVERSION_H -#define UVERSION_H - -#include "unicode/umachine.h" - -/* Actual version info lives in uvernum.h */ -#include "unicode/uvernum.h" - -/** Maximum length of the copyright string. - * @stable ICU 2.4 - */ -#define U_COPYRIGHT_STRING_LENGTH 128 - -/** An ICU version consists of up to 4 numbers from 0..255. - * @stable ICU 2.4 - */ -#define U_MAX_VERSION_LENGTH 4 - -/** In a string, ICU version fields are delimited by dots. - * @stable ICU 2.4 - */ -#define U_VERSION_DELIMITER '.' - -/** The maximum length of an ICU version string. - * @stable ICU 2.4 - */ -#define U_MAX_VERSION_STRING_LENGTH 20 - -/** The binary form of a version on ICU APIs is an array of 4 uint8_t. - * To compare two versions, use memcmp(v1,v2,sizeof(UVersionInfo)). - * @stable ICU 2.4 - */ -typedef uint8_t UVersionInfo[U_MAX_VERSION_LENGTH]; - -/*===========================================================================*/ -/* C++ namespace if supported. Versioned unless versioning is disabled. */ -/*===========================================================================*/ - -/** - * \def U_NAMESPACE_BEGIN - * This is used to begin a declaration of a public ICU C++ API. - * When not compiling for C++, it does nothing. - * When compiling for C++, it begins an extern "C++" linkage block (to protect - * against cases in which an external client includes ICU header files inside - * an extern "C" linkage block). - * - * It also begins a versioned-ICU-namespace block. - * @stable ICU 2.4 - */ - -/** - * \def U_NAMESPACE_END - * This is used to end a declaration of a public ICU C++ API. - * When not compiling for C++, it does nothing. - * When compiling for C++, it ends the extern "C++" block begun by - * U_NAMESPACE_BEGIN. - * - * It also ends the versioned-ICU-namespace block begun by U_NAMESPACE_BEGIN. - * @stable ICU 2.4 - */ - -/** - * \def U_NAMESPACE_USE - * This is used to specify that the rest of the code uses the - * public ICU C++ API namespace. - * This is invoked by default; we recommend that you turn it off: - * See the "Recommended Build Options" section of the ICU4C readme - * (http://source.icu-project.org/repos/icu/icu/trunk/readme.html#RecBuild) - * @stable ICU 2.4 - */ - -/** - * \def U_NAMESPACE_QUALIFIER - * This is used to qualify that a function or class is part of - * the public ICU C++ API namespace. - * - * This macro is unnecessary since ICU 49 requires namespace support. - * You can just use "icu::" instead. - * @stable ICU 2.4 - */ - -/* Define namespace symbols if the compiler supports it. */ -#ifdef __cplusplus -# if U_DISABLE_RENAMING -# define U_ICU_NAMESPACE icu - namespace U_ICU_NAMESPACE { } -# else -# define U_ICU_NAMESPACE U_ICU_ENTRY_POINT_RENAME(icu) - namespace U_ICU_NAMESPACE { } - namespace icu = U_ICU_NAMESPACE; -# endif - -# define U_NAMESPACE_BEGIN extern "C++" { namespace U_ICU_NAMESPACE { -# define U_NAMESPACE_END } } -# define U_NAMESPACE_USE using namespace U_ICU_NAMESPACE; -# define U_NAMESPACE_QUALIFIER U_ICU_NAMESPACE:: - -# ifndef U_USING_ICU_NAMESPACE -# define U_USING_ICU_NAMESPACE 1 -# endif -# if U_USING_ICU_NAMESPACE - U_NAMESPACE_USE -# endif -#else -# define U_NAMESPACE_BEGIN -# define U_NAMESPACE_END -# define U_NAMESPACE_USE -# define U_NAMESPACE_QUALIFIER -#endif - -/*===========================================================================*/ -/* General version helper functions. Definitions in putil.c */ -/*===========================================================================*/ - -/** - * Parse a string with dotted-decimal version information and - * fill in a UVersionInfo structure with the result. - * Definition of this function lives in putil.c - * - * @param versionArray The destination structure for the version information. - * @param versionString A string with dotted-decimal version information, - * with up to four non-negative number fields with - * values of up to 255 each. - * @stable ICU 2.4 - */ -U_STABLE void U_EXPORT2 -u_versionFromString(UVersionInfo versionArray, const char *versionString); - -/** - * Parse a Unicode string with dotted-decimal version information and - * fill in a UVersionInfo structure with the result. - * Definition of this function lives in putil.c - * - * @param versionArray The destination structure for the version information. - * @param versionString A Unicode string with dotted-decimal version - * information, with up to four non-negative number - * fields with values of up to 255 each. - * @stable ICU 4.2 - */ -U_STABLE void U_EXPORT2 -u_versionFromUString(UVersionInfo versionArray, const UChar *versionString); - - -/** - * Write a string with dotted-decimal version information according - * to the input UVersionInfo. - * Definition of this function lives in putil.c - * - * @param versionArray The version information to be written as a string. - * @param versionString A string buffer that will be filled in with - * a string corresponding to the numeric version - * information in versionArray. - * The buffer size must be at least U_MAX_VERSION_STRING_LENGTH. - * @stable ICU 2.4 - */ -U_STABLE void U_EXPORT2 -u_versionToString(const UVersionInfo versionArray, char *versionString); - -/** - * Gets the ICU release version. The version array stores the version information - * for ICU. For example, release "1.3.31.2" is then represented as 0x01031F02. - * Definition of this function lives in putil.c - * - * @param versionArray the version # information, the result will be filled in - * @stable ICU 2.0 - */ -U_STABLE void U_EXPORT2 -u_getVersion(UVersionInfo versionArray); -#endif diff --git a/win32/include/spidermonkey/unicode/vtzone.h b/win32/include/spidermonkey/unicode/vtzone.h deleted file mode 100755 index 75a5fca9..00000000 --- a/win32/include/spidermonkey/unicode/vtzone.h +++ /dev/null @@ -1,457 +0,0 @@ -// Copyright (C) 2016 and later: Unicode, Inc. and others. -// License & terms of use: http://www.unicode.org/copyright.html -/* -******************************************************************************* -* Copyright (C) 2007-2013, International Business Machines Corporation and -* others. All Rights Reserved. -******************************************************************************* -*/ -#ifndef VTZONE_H -#define VTZONE_H - -#include "unicode/utypes.h" - -/** - * \file - * \brief C++ API: RFC2445 VTIMEZONE support - */ - -#if !UCONFIG_NO_FORMATTING - -#include "unicode/basictz.h" - -U_NAMESPACE_BEGIN - -class VTZWriter; -class VTZReader; -class UVector; - -/** - * VTimeZone is a class implementing RFC2445 VTIMEZONE. You can create a - * VTimeZone instance from a time zone ID supported by TimeZone. - * With the VTimeZone instance created from the ID, you can write out the rule - * in RFC2445 VTIMEZONE format. Also, you can create a VTimeZone instance - * from RFC2445 VTIMEZONE data stream, which allows you to calculate time - * zone offset by the rules defined by the data. Or, you can create a - * VTimeZone from any other ICU BasicTimeZone. - *

- * Note: The consumer of this class reading or writing VTIMEZONE data is responsible to - * decode or encode Non-ASCII text. Methods reading/writing VTIMEZONE data in this class - * do nothing with MIME encoding. - * @stable ICU 3.8 - */ -class U_I18N_API VTimeZone : public BasicTimeZone { -public: - /** - * Copy constructor. - * @param source The VTimeZone object to be copied. - * @stable ICU 3.8 - */ - VTimeZone(const VTimeZone& source); - - /** - * Destructor. - * @stable ICU 3.8 - */ - virtual ~VTimeZone(); - - /** - * Assignment operator. - * @param right The object to be copied. - * @stable ICU 3.8 - */ - VTimeZone& operator=(const VTimeZone& right); - - /** - * Return true if the given TimeZone objects are - * semantically equal. Objects of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZone objects are - *semantically equal. - * @stable ICU 3.8 - */ - virtual UBool operator==(const TimeZone& that) const; - - /** - * Return true if the given TimeZone objects are - * semantically unequal. Objects of different subclasses are considered unequal. - * @param that The object to be compared with. - * @return true if the given TimeZone objects are - * semantically unequal. - * @stable ICU 3.8 - */ - virtual UBool operator!=(const TimeZone& that) const; - - /** - * Create a VTimeZone instance by the time zone ID. - * @param ID The time zone ID, such as America/New_York - * @return A VTimeZone object initialized by the time zone ID, - * or NULL when the ID is unknown. - * @stable ICU 3.8 - */ - static VTimeZone* createVTimeZoneByID(const UnicodeString& ID); - - /** - * Create a VTimeZone instance using a basic time zone. - * @param basicTZ The basic time zone instance - * @param status Output param to filled in with a success or an error. - * @return A VTimeZone object initialized by the basic time zone. - * @stable ICU 4.6 - */ - static VTimeZone* createVTimeZoneFromBasicTimeZone(const BasicTimeZone& basicTZ, - UErrorCode &status); - - /** - * Create a VTimeZone instance by RFC2445 VTIMEZONE data - * - * @param vtzdata The string including VTIMEZONE data block - * @param status Output param to filled in with a success or an error. - * @return A VTimeZone initialized by the VTIMEZONE data or - * NULL if failed to load the rule from the VTIMEZONE data. - * @stable ICU 3.8 - */ - static VTimeZone* createVTimeZone(const UnicodeString& vtzdata, UErrorCode& status); - - /** - * Gets the RFC2445 TZURL property value. When a VTimeZone instance was - * created from VTIMEZONE data, the initial value is set by the TZURL property value - * in the data. Otherwise, the initial value is not set. - * @param url Receives the RFC2445 TZURL property value. - * @return TRUE if TZURL attribute is available and value is set. - * @stable ICU 3.8 - */ - UBool getTZURL(UnicodeString& url) const; - - /** - * Sets the RFC2445 TZURL property value. - * @param url The TZURL property value. - * @stable ICU 3.8 - */ - void setTZURL(const UnicodeString& url); - - /** - * Gets the RFC2445 LAST-MODIFIED property value. When a VTimeZone instance - * was created from VTIMEZONE data, the initial value is set by the LAST-MODIFIED property - * value in the data. Otherwise, the initial value is not set. - * @param lastModified Receives the last modified date. - * @return TRUE if lastModified attribute is available and value is set. - * @stable ICU 3.8 - */ - UBool getLastModified(UDate& lastModified) const; - - /** - * Sets the RFC2445 LAST-MODIFIED property value. - * @param lastModified The LAST-MODIFIED date. - * @stable ICU 3.8 - */ - void setLastModified(UDate lastModified); - - /** - * Writes RFC2445 VTIMEZONE data for this time zone - * @param result Output param to filled in with the VTIMEZONE data. - * @param status Output param to filled in with a success or an error. - * @stable ICU 3.8 - */ - void write(UnicodeString& result, UErrorCode& status) const; - - /** - * Writes RFC2445 VTIMEZONE data for this time zone applicalbe - * for dates after the specified start time. - * @param start The start date. - * @param result Output param to filled in with the VTIMEZONE data. - * @param status Output param to filled in with a success or an error. - * @stable ICU 3.8 - */ - void write(UDate start, UnicodeString& result, UErrorCode& status) const; - - /** - * Writes RFC2445 VTIMEZONE data applicalbe for the specified date. - * Some common iCalendar implementations can only handle a single time - * zone property or a pair of standard and daylight time properties using - * BYDAY rule with day of week (such as BYDAY=1SUN). This method produce - * the VTIMEZONE data which can be handled these implementations. The rules - * produced by this method can be used only for calculating time zone offset - * around the specified date. - * @param time The date used for rule extraction. - * @param result Output param to filled in with the VTIMEZONE data. - * @param status Output param to filled in with a success or an error. - * @stable ICU 3.8 - */ - void writeSimple(UDate time, UnicodeString& result, UErrorCode& status) const; - - /** - * Clones TimeZone objects polymorphically. Clients are responsible for deleting - * the TimeZone object cloned. - * @return A new copy of this TimeZone object. - * @stable ICU 3.8 - */ - virtual TimeZone* clone(void) const; - - /** - * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time in this time zone, taking daylight savings time into - * account) as of a particular reference date. The reference date is used to determine - * whether daylight savings time is in effect and needs to be figured into the offset - * that is returned (in other words, what is the adjusted GMT offset in this time zone - * at this particular date and time?). For the time zones produced by createTimeZone(), - * the reference data is specified according to the Gregorian calendar, and the date - * and time fields are local standard time. - * - *

Note: Don't call this method. Instead, call the getOffset(UDate...) overload, - * which returns both the raw and the DST offset for a given time. This method - * is retained only for backward compatibility. - * - * @param era The reference date's era - * @param year The reference date's year - * @param month The reference date's month (0-based; 0 is January) - * @param day The reference date's day-in-month (1-based) - * @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday) - * @param millis The reference date's milliseconds in day, local standard time - * @param status Output param to filled in with a success or an error. - * @return The offset in milliseconds to add to GMT to get local time. - * @stable ICU 3.8 - */ - virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, - uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const; - - /** - * Gets the time zone offset, for current date, modified in case of - * daylight savings. This is the offset to add *to* UTC to get local time. - * - *

Note: Don't call this method. Instead, call the getOffset(UDate...) overload, - * which returns both the raw and the DST offset for a given time. This method - * is retained only for backward compatibility. - * - * @param era The reference date's era - * @param year The reference date's year - * @param month The reference date's month (0-based; 0 is January) - * @param day The reference date's day-in-month (1-based) - * @param dayOfWeek The reference date's day-of-week (1-based; 1 is Sunday) - * @param millis The reference date's milliseconds in day, local standard time - * @param monthLength The length of the given month in days. - * @param status Output param to filled in with a success or an error. - * @return The offset in milliseconds to add to GMT to get local time. - * @stable ICU 3.8 - */ - virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day, - uint8_t dayOfWeek, int32_t millis, - int32_t monthLength, UErrorCode& status) const; - - /** - * Returns the time zone raw and GMT offset for the given moment - * in time. Upon return, local-millis = GMT-millis + rawOffset + - * dstOffset. All computations are performed in the proleptic - * Gregorian calendar. The default implementation in the TimeZone - * class delegates to the 8-argument getOffset(). - * - * @param date moment in time for which to return offsets, in - * units of milliseconds from January 1, 1970 0:00 GMT, either GMT - * time or local wall time, depending on `local'. - * @param local if true, `date' is local wall time; otherwise it - * is in GMT time. - * @param rawOffset output parameter to receive the raw offset, that - * is, the offset not including DST adjustments - * @param dstOffset output parameter to receive the DST offset, - * that is, the offset to be added to `rawOffset' to obtain the - * total offset between local and GMT time. If DST is not in - * effect, this value is zero; otherwise it is a positive value, - * typically one hour. - * @param ec input-output error code - * @stable ICU 3.8 - */ - virtual void getOffset(UDate date, UBool local, int32_t& rawOffset, - int32_t& dstOffset, UErrorCode& ec) const; - - /** - * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time, before taking daylight savings time into account). - * - * @param offsetMillis The new raw GMT offset for this time zone. - * @stable ICU 3.8 - */ - virtual void setRawOffset(int32_t offsetMillis); - - /** - * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add - * to GMT to get local time, before taking daylight savings time into account). - * - * @return The TimeZone's raw GMT offset. - * @stable ICU 3.8 - */ - virtual int32_t getRawOffset(void) const; - - /** - * Queries if this time zone uses daylight savings time. - * @return true if this time zone uses daylight savings time, - * false, otherwise. - * @stable ICU 3.8 - */ - virtual UBool useDaylightTime(void) const; - - /** - * Queries if the given date is in daylight savings time in - * this time zone. - * This method is wasteful since it creates a new GregorianCalendar and - * deletes it each time it is called. This is a deprecated method - * and provided only for Java compatibility. - * - * @param date the given UDate. - * @param status Output param filled in with success/error code. - * @return true if the given date is in daylight savings time, - * false, otherwise. - * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead. - */ - virtual UBool inDaylightTime(UDate date, UErrorCode& status) const; - - /** - * Returns true if this zone has the same rule and offset as another zone. - * That is, if this zone differs only in ID, if at all. - * @param other the TimeZone object to be compared with - * @return true if the given zone is the same as this one, - * with the possible exception of the ID - * @stable ICU 3.8 - */ - virtual UBool hasSameRules(const TimeZone& other) const; - - /** - * Gets the first time zone transition after the base time. - * @param base The base time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives the first transition after the base time. - * @return TRUE if the transition is found. - * @stable ICU 3.8 - */ - virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const; - - /** - * Gets the most recent time zone transition before the base time. - * @param base The base time. - * @param inclusive Whether the base time is inclusive or not. - * @param result Receives the most recent transition before the base time. - * @return TRUE if the transition is found. - * @stable ICU 3.8 - */ - virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) const; - - /** - * Returns the number of TimeZoneRules which represents time transitions, - * for this time zone, that is, all TimeZoneRules for this time zone except - * InitialTimeZoneRule. The return value range is 0 or any positive value. - * @param status Receives error status code. - * @return The number of TimeZoneRules representing time transitions. - * @stable ICU 3.8 - */ - virtual int32_t countTransitionRules(UErrorCode& status) const; - - /** - * Gets the InitialTimeZoneRule and the set of TimeZoneRule - * which represent time transitions for this time zone. On successful return, - * the argument initial points to non-NULL InitialTimeZoneRule and - * the array trsrules is filled with 0 or multiple TimeZoneRule - * instances up to the size specified by trscount. The results are referencing the - * rule instance held by this time zone instance. Therefore, after this time zone - * is destructed, they are no longer available. - * @param initial Receives the initial timezone rule - * @param trsrules Receives the timezone transition rules - * @param trscount On input, specify the size of the array 'transitions' receiving - * the timezone transition rules. On output, actual number of - * rules filled in the array will be set. - * @param status Receives error status code. - * @stable ICU 3.8 - */ - virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial, - const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) const; - -private: - enum { DEFAULT_VTIMEZONE_LINES = 100 }; - - /** - * Default constructor. - */ - VTimeZone(); - static VTimeZone* createVTimeZone(VTZReader* reader); - void write(VTZWriter& writer, UErrorCode& status) const; - void write(UDate start, VTZWriter& writer, UErrorCode& status) const; - void writeSimple(UDate time, VTZWriter& writer, UErrorCode& status) const; - void load(VTZReader& reader, UErrorCode& status); - void parse(UErrorCode& status); - - void writeZone(VTZWriter& w, BasicTimeZone& basictz, UVector* customProps, - UErrorCode& status) const; - - void writeHeaders(VTZWriter& w, UErrorCode& status) const; - void writeFooter(VTZWriter& writer, UErrorCode& status) const; - - void writeZonePropsByTime(VTZWriter& writer, UBool isDst, const UnicodeString& zonename, - int32_t fromOffset, int32_t toOffset, UDate time, UBool withRDATE, - UErrorCode& status) const; - void writeZonePropsByDOM(VTZWriter& writer, UBool isDst, const UnicodeString& zonename, - int32_t fromOffset, int32_t toOffset, - int32_t month, int32_t dayOfMonth, UDate startTime, UDate untilTime, - UErrorCode& status) const; - void writeZonePropsByDOW(VTZWriter& writer, UBool isDst, const UnicodeString& zonename, - int32_t fromOffset, int32_t toOffset, - int32_t month, int32_t weekInMonth, int32_t dayOfWeek, - UDate startTime, UDate untilTime, UErrorCode& status) const; - void writeZonePropsByDOW_GEQ_DOM(VTZWriter& writer, UBool isDst, const UnicodeString& zonename, - int32_t fromOffset, int32_t toOffset, - int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, - UDate startTime, UDate untilTime, UErrorCode& status) const; - void writeZonePropsByDOW_GEQ_DOM_sub(VTZWriter& writer, int32_t month, int32_t dayOfMonth, - int32_t dayOfWeek, int32_t numDays, - UDate untilTime, int32_t fromOffset, UErrorCode& status) const; - void writeZonePropsByDOW_LEQ_DOM(VTZWriter& writer, UBool isDst, const UnicodeString& zonename, - int32_t fromOffset, int32_t toOffset, - int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, - UDate startTime, UDate untilTime, UErrorCode& status) const; - void writeFinalRule(VTZWriter& writer, UBool isDst, const AnnualTimeZoneRule* rule, - int32_t fromRawOffset, int32_t fromDSTSavings, - UDate startTime, UErrorCode& status) const; - - void beginZoneProps(VTZWriter& writer, UBool isDst, const UnicodeString& zonename, - int32_t fromOffset, int32_t toOffset, UDate startTime, UErrorCode& status) const; - void endZoneProps(VTZWriter& writer, UBool isDst, UErrorCode& status) const; - void beginRRULE(VTZWriter& writer, int32_t month, UErrorCode& status) const; - void appendUNTIL(VTZWriter& writer, const UnicodeString& until, UErrorCode& status) const; - - BasicTimeZone *tz; - UVector *vtzlines; - UnicodeString tzurl; - UDate lastmod; - UnicodeString olsonzid; - UnicodeString icutzver; - -public: - /** - * Return the class ID for this class. This is useful only for comparing to - * a return value from getDynamicClassID(). For example: - *

-     * .   Base* polymorphic_pointer = createPolymorphicObject();
-     * .   if (polymorphic_pointer->getDynamicClassID() ==
-     * .       erived::getStaticClassID()) ...
-     * 
- * @return The class ID for all objects of this class. - * @stable ICU 3.8 - */ - static UClassID U_EXPORT2 getStaticClassID(void); - - /** - * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This - * method is to implement a simple version of RTTI, since not all C++ - * compilers support genuine RTTI. Polymorphic operator==() and clone() - * methods call this method. - * - * @return The class ID for this object. All objects of a - * given class have the same class ID. Objects of - * other classes have different class IDs. - * @stable ICU 3.8 - */ - virtual UClassID getDynamicClassID(void) const; -}; - -U_NAMESPACE_END - -#endif /* #if !UCONFIG_NO_FORMATTING */ - -#endif // VTZONE_H -//eof diff --git a/win32/include/spidermonkey/zconf.h b/win32/include/spidermonkey/zconf.h deleted file mode 100755 index fa0950b9..00000000 --- a/win32/include/spidermonkey/zconf.h +++ /dev/null @@ -1,514 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2013 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* This header does prefixing as below, but with an updated set of names. */ -#include "mozzconf.h" - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - * Even better than compiling with -DZ_PREFIX would be to use configure to set - * this permanently in zconf.h using "./configure --zprefix". - */ -#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ -# define Z_PREFIX_SET - -/* all linked symbols */ -# define _dist_code z__dist_code -# define _length_code z__length_code -# define _tr_align z__tr_align -# define _tr_flush_bits z__tr_flush_bits -# define _tr_flush_block z__tr_flush_block -# define _tr_init z__tr_init -# define _tr_stored_block z__tr_stored_block -# define _tr_tally z__tr_tally -# define adler32 z_adler32 -# define adler32_combine z_adler32_combine -# define adler32_combine64 z_adler32_combine64 -# ifndef Z_SOLO -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# endif -# define crc32 z_crc32 -# define crc32_combine z_crc32_combine -# define crc32_combine64 z_crc32_combine64 -# define deflate z_deflate -# define deflateBound z_deflateBound -# define deflateCopy z_deflateCopy -# define deflateEnd z_deflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateInit_ z_deflateInit_ -# define deflateParams z_deflateParams -# define deflatePending z_deflatePending -# define deflatePrime z_deflatePrime -# define deflateReset z_deflateReset -# define deflateResetKeep z_deflateResetKeep -# define deflateSetDictionary z_deflateSetDictionary -# define deflateSetHeader z_deflateSetHeader -# define deflateTune z_deflateTune -# define deflate_copyright z_deflate_copyright -# define get_crc_table z_get_crc_table -# ifndef Z_SOLO -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzgetc z_gzgetc -# define gzgetc_ z_gzgetc_ -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# ifdef _WIN32 -# define gzopen_w z_gzopen_w -# endif -# define gzprintf z_gzprintf -# define gzvprintf z_gzvprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzwrite z_gzwrite -# endif -# define inflate z_inflate -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define inflateBackInit_ z_inflateBackInit_ -# define inflateCopy z_inflateCopy -# define inflateEnd z_inflateEnd -# define inflateGetHeader z_inflateGetHeader -# define inflateInit2_ z_inflateInit2_ -# define inflateInit_ z_inflateInit_ -# define inflateMark z_inflateMark -# define inflatePrime z_inflatePrime -# define inflateReset z_inflateReset -# define inflateReset2 z_inflateReset2 -# define inflateSetDictionary z_inflateSetDictionary -# define inflateGetDictionary z_inflateGetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateUndermine z_inflateUndermine -# define inflateResetKeep z_inflateResetKeep -# define inflate_copyright z_inflate_copyright -# define inflate_fast z_inflate_fast -# define inflate_table z_inflate_table -# ifndef Z_SOLO -# define uncompress z_uncompress -# endif -# define zError z_zError -# ifndef Z_SOLO -# define zcalloc z_zcalloc -# define zcfree z_zcfree -# endif -# define zlibCompileFlags z_zlibCompileFlags -# define zlibVersion z_zlibVersion - -/* all zlib typedefs in zlib.h and zconf.h */ -# define Byte z_Byte -# define Bytef z_Bytef -# define alloc_func z_alloc_func -# define charf z_charf -# define free_func z_free_func -# ifndef Z_SOLO -# define gzFile z_gzFile -# endif -# define gz_header z_gz_header -# define gz_headerp z_gz_headerp -# define in_func z_in_func -# define intf z_intf -# define out_func z_out_func -# define uInt z_uInt -# define uIntf z_uIntf -# define uLong z_uLong -# define uLongf z_uLongf -# define voidp z_voidp -# define voidpc z_voidpc -# define voidpf z_voidpf - -/* all zlib structs in zlib.h and zconf.h */ -# define gz_header_s z_gz_header_s -# define internal_state z_internal_state - -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -#if defined(ZLIB_CONST) && !defined(z_const) -# define z_const const -#else -# define z_const -#endif - -/* Some Mac compilers merge all .h files incorrectly: */ -#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -#ifndef Z_ARG /* function prototypes for stdarg */ -# if defined(STDC) || defined(Z_HAVE_STDARG_H) -# define Z_ARG(args) args -# else -# define Z_ARG(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) || (defined(__OS2__) && defined(__declspec)) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) -# include -# if (UINT_MAX == 0xffffffffUL) -# define Z_U4 unsigned -# elif (ULONG_MAX == 0xffffffffUL) -# define Z_U4 unsigned long -# elif (USHRT_MAX == 0xffffffffUL) -# define Z_U4 unsigned short -# endif -#endif - -#ifdef Z_U4 - typedef Z_U4 z_crc_t; -#else - typedef unsigned long z_crc_t; -#endif - -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_UNISTD_H -#endif - -#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_STDARG_H -#endif - -#ifdef STDC -# ifndef Z_SOLO -# include /* for off_t */ -# endif -#endif - -#if defined(STDC) || defined(Z_HAVE_STDARG_H) -# ifndef Z_SOLO -# include /* for va_list */ -# endif -#endif - -#ifdef _WIN32 -# ifndef Z_SOLO -# include /* for wchar_t */ -# endif -#endif - -/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and - * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even - * though the former does not conform to the LFS document), but considering - * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as - * equivalently requesting no 64-bit operations - */ -#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 -# undef _LARGEFILE64_SOURCE -#endif - -#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) -# define Z_HAVE_UNISTD_H -#endif -#ifndef Z_SOLO -# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t -# endif -# endif -#endif - -#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 -# define Z_LFS64 -#endif - -#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) -# define Z_LARGE64 -#endif - -#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) -# define Z_WANT64 -#endif - -#if !defined(SEEK_SET) && !defined(Z_SOLO) -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#ifndef z_off_t -# define z_off_t long -#endif - -#if !defined(_WIN32) && defined(Z_LARGE64) -# define z_off64_t off64_t -#else -# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) -# define z_off64_t __int64 -# else -# define z_off64_t z_off_t -# endif -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) - #pragma map(deflateInit_,"DEIN") - #pragma map(deflateInit2_,"DEIN2") - #pragma map(deflateEnd,"DEEND") - #pragma map(deflateBound,"DEBND") - #pragma map(inflateInit_,"ININ") - #pragma map(inflateInit2_,"ININ2") - #pragma map(inflateEnd,"INEND") - #pragma map(inflateSync,"INSY") - #pragma map(inflateSetDictionary,"INSEDI") - #pragma map(compressBound,"CMBND") - #pragma map(inflate_table,"INTABL") - #pragma map(inflate_fast,"INFA") - #pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/win32/include/spidermonkey/zlib.h b/win32/include/spidermonkey/zlib.h deleted file mode 100755 index b6ce7f1b..00000000 --- a/win32/include/spidermonkey/zlib.h +++ /dev/null @@ -1,1769 +0,0 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.8, April 28th, 2013 - - Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 - (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). -*/ - -#ifndef ZLIB_H -#define ZLIB_H - -#include "zconf.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define ZLIB_VERSION "1.2.8" -#define ZLIB_VERNUM 0x1280 -#define ZLIB_VER_MAJOR 1 -#define ZLIB_VER_MINOR 2 -#define ZLIB_VER_REVISION 8 -#define ZLIB_VER_SUBREVISION 0 - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed data. - This version of the library supports only one compression method (deflation) - but other algorithms will be added later and will have the same stream - interface. - - Compression can be done in a single step if the buffers are large enough, - or can be done by repeated calls of the compression function. In the latter - case, the application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never crash - even in case of corrupted input. -*/ - -typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); -typedef void (*free_func) OF((voidpf opaque, voidpf address)); - -struct internal_state; - -typedef struct z_stream_s { - z_const Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total number of input bytes read so far */ - - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total number of bytes output so far */ - - z_const char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream FAR *z_streamp; - -/* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ -typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ -} gz_header; - -typedef gz_header FAR *gz_headerp; - -/* - The application must update next_in and avail_in when avail_in has dropped - to zero. It must update next_out and avail_out when avail_out has dropped - to zero. The application must initialize zalloc, zfree and opaque before - calling the init function. All other fields are set by the compression - library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this if - the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers - returned by zalloc for objects of exactly 65536 bytes *must* have their - offset normalized to zero. The default allocation function provided by this - library ensures this (see zutil.c). To reduce memory requirements and avoid - any allocation of 64K objects, at the expense of compression ratio, compile - the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or progress - reports. After compression, total_in holds the total size of the - uncompressed data and may be saved for use in the decompressor (particularly - if the decompressor wants to decompress everything in a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 -#define Z_TREES 6 -/* Allowed flush values; see deflate() and inflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 -/* Possible values of the data_type field (though see inflate()) */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - - /* basic functions */ - -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is not - compatible with the zlib.h header file used by the application. This check - is automatically made by deflateInit and inflateInit. - */ - -/* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. If - zalloc and zfree are set to Z_NULL, deflateInit updates them to use default - allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at all - (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION - requests a default compromise between speed and compression (currently - equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if level is not a valid compression level, or - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). msg is set to null - if there is no error message. deflateInit does not perform any compression: - this will be done by deflate(). -*/ - - -ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). Some - output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating avail_in or avail_out accordingly; avail_out should - never be zero before the call. The application can consume the compressed - output when it wants, for example when the output buffer is full (avail_out - == 0), or after each call of deflate(). If deflate returns Z_OK and with - zero avail_out, it must be called again after making room in the output - buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumulate before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In - particular avail_in is zero after the call if enough output space has been - provided before the call.) Flushing may degrade compression for some - compression algorithms and so it should be used only when necessary. This - completes the current deflate block and follows it with an empty stored block - that is three bits plus filler bits to the next byte, followed by four bytes - (00 00 ff ff). - - If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the - output buffer, but the output is not aligned to a byte boundary. All of the - input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. - This completes the current deflate block and follows it with an empty fixed - codes block that is 10 bits long. This assures that enough bytes are output - in order for the decompressor to finish the block before the empty fixed code - block. - - If flush is set to Z_BLOCK, a deflate block is completed and emitted, as - for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to - seven bits of the current block are held to be written as the next byte after - the next deflate block is completed. In this case, the decompressor may not - be provided enough bits at this point in order to complete decompression of - the data provided so far to the compressor. It may need to wait for the next - block to be emitted. This is for advanced applications that need to control - the emission of deflate blocks. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there was - enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the stream - are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least the - value returned by deflateBound (see below). Then deflate is guaranteed to - return Z_STREAM_END. If not enough output space is provided, deflate will - not return Z_STREAM_END, and it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect the - compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ - - -ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, msg - may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the - exact value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit() does not process any header information -- that is deferred - until inflate() is called. -*/ - - -ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing will - resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there is - no more input data or no more space in the output buffer (see below about - the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating the next_* and avail_* values accordingly. The - application can consume the uncompressed output when it wants, for example - when the output buffer is full (avail_out == 0), or after each call of - inflate(). If inflate returns Z_OK and with zero avail_out, it must be - called again after making room in the output buffer because there might be - more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, - Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() - stop if and when it gets to the next deflate block boundary. When decoding - the zlib or gzip format, this will cause inflate() to return immediately - after the header and before the first block. When doing a raw inflate, - inflate() will go ahead and process the first block, and will return when it - gets to the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 if - inflate() is currently decoding the last block in the deflate stream, plus - 128 if inflate() returned immediately after decoding an end-of-block code or - decoding the complete header up to just before the first byte of the deflate - stream. The end-of-block will not be indicated until all of the uncompressed - data from that block has been written to strm->next_out. The number of - unused bits may in general be greater than seven, except when bit 7 of - data_type is set, in which case the number of unused bits will be less than - eight. data_type is set as noted here every time inflate() returns for all - flush options, and so can be used to determine the amount of currently - consumed input in bits. - - The Z_TREES option behaves as Z_BLOCK does, but it also returns when the - end of each deflate block header is reached, before any actual data in that - block is decoded. This allows the caller to determine the length of the - deflate block header for later use in random access within a deflate block. - 256 is added to the value of strm->data_type when inflate() returns - immediately after reaching the end of the deflate block header. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step (a - single call of inflate), the parameter flush should be set to Z_FINISH. In - this case all pending input is processed and all pending output is flushed; - avail_out must be large enough to hold all of the uncompressed data for the - operation to complete. (The size of the uncompressed data may have been - saved by the compressor for this purpose.) The use of Z_FINISH is not - required to perform an inflation in one step. However it may be used to - inform inflate that a faster approach can be used for the single inflate() - call. Z_FINISH also informs inflate to not maintain a sliding window if the - stream completes, which reduces inflate's memory footprint. If the stream - does not complete, either because not all of the stream is provided or not - enough output space is provided, then a sliding window will be allocated and - inflate() can be called again to continue the operation as if Z_NO_FLUSH had - been used. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the effects of the flush parameter in this implementation are - on the return value of inflate() as noted below, when inflate() returns early - when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of - memory for a sliding window when Z_FINISH is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the Adler-32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the Adler-32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() can decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically, if requested when - initializing with inflateInit2(). Any information contained in the gzip - header is not retained, so applications that need that information should - instead use raw inflate, see inflateInit2() below, or inflateBack() and - perform their own processing of the gzip header and trailer. When processing - gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output - producted so far. The CRC-32 is checked against the gzip trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may - then call inflateSync() to look for a good compression block if a partial - recovery of the data is desired. -*/ - - -ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by the - caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), no - header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but is - slow and reduces compression ratio; memLevel=9 uses maximum memory for - optimal speed. The default value is 8. See zconf.h for total memory usage - as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as - fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The - strategy parameter only affects the compression ratio but not the - correctness of the compressed output even if it is not set appropriately. - Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler - decoder for special applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid - method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is - incompatible with the version assumed by the caller (ZLIB_VERSION). msg is - set to null if there is no error message. deflateInit2 does not perform any - compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. When using the zlib format, this - function must be called immediately after deflateInit, deflateInit2 or - deflateReset, and before any call of deflate. When doing raw deflate, this - function must be called either before any call of deflate, or immediately - after the completion of a deflate block, i.e. after all input has been - consumed and all output has been delivered when using any of the flush - options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The - compressor and decompressor must use exactly the same dictionary (see - inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size - provided in deflateInit or deflateInit2. Thus the strings most likely to be - useful should be put at the end of the dictionary, not at the front. In - addition, the current implementation of deflate will use at most the window - size minus 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if not at a block boundary for raw deflate). deflateSetDictionary does - not perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and can - consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); -/* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. The - stream will keep the same compression level and any other attributes that - may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different strategy. - If the compression level is changed, the input available so far is - compressed with the old level (and may be flushed); the new level will take - effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to be - compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if - strm->avail_out was zero. -*/ - -ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); -/* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - -ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); -/* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() or - deflateInit2(), and after deflateSetHeader(), if used. This would be used - to allocate an output buffer for deflation in a single pass, and so would be - called before deflate(). If that first deflate() call is provided the - sourceLen input bytes, an output buffer allocated to the size returned by - deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed - to return Z_STREAM_END. Note that it is possible for the compressed size to - be larger than the value returned by deflateBound() if flush options other - than Z_FINISH or Z_NO_FLUSH are used. -*/ - -ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, - unsigned *pending, - int *bits)); -/* - deflatePending() returns the number of bytes and bits of output that have - been generated, but not yet provided in the available output. The bytes not - provided would be due to the available output space having being consumed. - The number of bits of output not provided are between 0 and 7, where they - await more bits to join them in order to fill out a full byte. If pending - or bits are Z_NULL, then those values are not set. - - deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. - */ - -ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the bits - leftover from a previous deflate stream when appending to it. As such, this - function can only be used for raw deflate, and must be used before the first - deflate() call after a deflateInit2() or deflateReset(). bits must be less - than or equal to 16, and that many of the least significant bits of value - will be inserted in the output. - - deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough - room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the - source stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be zero to request that inflate use the window size in - the zlib header of the compressed stream. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a - crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit2 does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit2() does not process any header information -- that is - deferred until inflate() is called. -*/ - -ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called at any - time to set the dictionary. If the provided dictionary is smaller than the - window and there is already data in the window, then the provided dictionary - will amend what's there. The application must insure that the dictionary - that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, - Bytef *dictionary, - uInt *dictLength)); -/* - Returns the sliding dictionary being maintained by inflate. dictLength is - set to the number of bytes in the dictionary, and that many bytes are copied - to dictionary. dictionary must have enough space, where 32768 bytes is - always enough. If inflateGetDictionary() is called with dictionary equal to - Z_NULL, then only the dictionary length is returned, and nothing is copied. - Similary, if dictLength is Z_NULL, then it is not set. - - inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the - stream state is inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); -/* - Skips invalid compressed data until a possible full flush point (see above - for the description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync searches for a 00 00 FF FF pattern in the compressed data. - All full flush points have this pattern, but not all occurrences of this - pattern are full flush points. - - inflateSync returns Z_OK if a possible full flush point has been found, - Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point - has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. - In the success case, the application may save the current current value of - total_in which indicates where valid compressed data was found. In the - error case, the application may repeatedly call inflateSync, providing more - input each time, until success or end of the input data. -*/ - -ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. The - stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, - int windowBits)); -/* - This function is the same as inflateReset, but it also permits changing - the wrap and window size requests. The windowBits parameter is interpreted - the same as it is for inflateInit2. - - inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL), or if - the windowBits parameter is invalid. -*/ - -ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - If bits is negative, then the input stream bit buffer is emptied. Then - inflatePrime() can be called again to put bits in the buffer. This is used - to clear out bits leftover after feeding inflate a block description prior - to feeding inflate codes. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); -/* - This function returns two values, one in the lower 16 bits of the return - value, and the other in the remaining upper bits, obtained by shifting the - return value down 16 bits. If the upper value is -1 and the lower value is - zero, then inflate() is currently decoding information outside of a block. - If the upper value is -1 and the lower value is non-zero, then inflate is in - the middle of a stored block, with the lower value equaling the number of - bytes from the input remaining to copy. If the upper value is not -1, then - it is the number of bits back from the current bit position in the input of - the code (literal or length/distance pair) currently being processed. In - that case the lower value is the number of bytes already emitted for that - code. - - A code is being processed if inflate is waiting for more input to complete - decoding of the code, or if it has completed decoding but is waiting for - more output space to write the literal or match data. - - inflateMark() is used to mark locations in the input data for random - access, which may be at bit positions, and to note those cases where the - output of a code may span boundaries of random access blocks. The current - location in the input stream can be determined from avail_in and data_type - as noted in the description for the Z_BLOCK flush parameter for inflate. - - inflateMark returns the value noted above or -1 << 16 if the provided - source stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be - used to force inflate() to return immediately after header processing is - complete and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When any - of extra, name, or comment are not Z_NULL and the respective field is not - present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the parameters are invalid, Z_MEM_ERROR if the internal state could not be - allocated, or Z_VERSION_ERROR if the version of the library does not match - the version of the header file. -*/ - -typedef unsigned (*in_func) OF((void FAR *, - z_const unsigned char FAR * FAR *)); -typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); - -ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is potentially more efficient than - inflate() for file i/o applications, in that it avoids copying between the - output and the sliding window by simply making the window itself the output - buffer. inflate() can be faster on modern CPUs when used with large - buffers. inflateBack() trusts the application to not change the output - buffer passed by the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free the - allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects only - the raw deflate stream to decompress. This is different from the normal - behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format error - in the deflate stream (in which case strm->msg is set to indicate the nature - of the error), or Z_STREAM_ERROR if the stream was not properly initialized. - In the case of Z_BUF_ERROR, an input or output error can be distinguished - using strm->next_in which will be Z_NULL only if in() returned an error. If - strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning - non-zero. (in() will always be called before out(), so strm->next_in is - assured to be defined if out() returns non-zero.) Note that inflateBack() - cannot return Z_OK. -*/ - -ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); -/* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ - -ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) - */ - -#ifndef Z_SOLO - - /* utility functions */ - -/* - The following utility functions are implemented on top of the basic - stream-oriented functions. To simplify the interface, some default options - are assumed (compression level and memory usage, standard memory allocation - functions). The source code of these utility functions can be modified if - you need special options. -*/ - -ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); -/* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before a - compress() or compress2() call to allocate the destination buffer. -*/ - -ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be large enough to hold the entire - uncompressed data. (The size of the uncompressed data must have been saved - previously by the compressor and transmitted to the decompressor by some - mechanism outside the scope of this compression library.) Upon exit, destLen - is the actual size of the uncompressed buffer. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In - the case where there is not enough room, uncompress() will fill the output - buffer with the uncompressed data up to that point. -*/ - - /* gzip file access functions */ - -/* - This library supports reading and writing files in gzip (.gz) format with - an interface similar to that of stdio, using the functions that start with - "gz". The gzip format is different from the zlib format. gzip is a gzip - wrapper, documented in RFC 1952, wrapped around a deflate stream. -*/ - -typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ - -/* -ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); - - Opens a gzip (.gz) file for reading or writing. The mode parameter is as - in fopen ("rb" or "wb") but can also include a compression level ("wb9") or - a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only - compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' - for fixed code compression as in "wb9F". (See the description of - deflateInit2 for more information about the strategy parameter.) 'T' will - request transparent writing or appending with no compression and not using - the gzip format. - - "a" can be used instead of "w" to request that the gzip stream that will - be written be appended to the file. "+" will result in an error, since - reading and writing to the same gzip file is not supported. The addition of - "x" when writing will create the file exclusively, which fails if the file - already exists. On systems that support it, the addition of "e" when - reading or writing will set the flag to close the file on an execve() call. - - These functions, as well as gzip, will read and decode a sequence of gzip - streams in a file. The append function of gzopen() can be used to create - such a file. (Also see gzflush() for another way to do this.) When - appending, gzopen does not test whether the file begins with a gzip stream, - nor does it look for the end of the gzip streams to begin appending. gzopen - will simply append a gzip stream to the existing file. - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. When - reading, this will be detected automatically by looking for the magic two- - byte gzip header. - - gzopen returns NULL if the file could not be opened, if there was - insufficient memory to allocate the gzFile state, or if an invalid mode was - specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). - errno can be checked to determine if the reason gzopen failed was that the - file could not be opened. -*/ - -ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); -/* - gzdopen associates a gzFile with the file descriptor fd. File descriptors - are obtained from calls like open, dup, creat, pipe or fileno (if the file - has been previously opened with fopen). The mode parameter is as in gzopen. - - The next call of gzclose on the returned gzFile will also close the file - descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor - fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, - mode);. The duplicated descriptor should be saved to avoid a leak, since - gzdopen does not close fd if it fails. If you are using fileno() to get the - file descriptor from a FILE *, then you will have to use dup() to avoid - double-close()ing the file descriptor. Both gzclose() and fclose() will - close the associated file descriptor, so they need to have different file - descriptors. - - gzdopen returns NULL if there was insufficient memory to allocate the - gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not - provided, or '+' was provided), or if fd is -1. The file descriptor is not - used until the next gz* read, write, seek, or close operation, so gzdopen - will not detect if fd is invalid (unless fd is -1). -*/ - -ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); -/* - Set the internal buffer size used by this library's functions. The - default buffer size is 8192 bytes. This function must be called after - gzopen() or gzdopen(), and before any other calls that read or write the - file. The buffer memory allocation is always deferred to the first read or - write. Two buffers are allocated, either both of the specified size when - writing, or one of the specified size and the other twice that size when - reading. A larger buffer size of, for example, 64K or 128K bytes will - noticeably increase the speed of decompression (reading). - - The new buffer size also affects the maximum length for gzprintf(). - - gzbuffer() returns 0 on success, or -1 on failure, such as being called - too late. -*/ - -ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); -/* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ - -ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); -/* - Reads the given number of uncompressed bytes from the compressed file. If - the input file is not in gzip format, gzread copies the given number of - bytes into the buffer directly from the file. - - After reaching the end of a gzip stream in the input, gzread will continue - to read, looking for another gzip stream. Any number of gzip streams may be - concatenated in the input file, and will all be decompressed by gzread(). - If something other than a gzip stream is encountered after a gzip stream, - that remaining trailing garbage is ignored (and no error is returned). - - gzread can be used to read a gzip file that is being concurrently written. - Upon reaching the end of the input, gzread will return with the available - data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then - gzclearerr can be used to clear the end of file indicator in order to permit - gzread to be tried again. Z_OK indicates that a gzip stream was completed - on the last gzread. Z_BUF_ERROR indicates that the input file ended in the - middle of a gzip stream. Note that gzread does not return -1 in the event - of an incomplete gzip stream. This error is deferred until gzclose(), which - will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip - stream. Alternatively, gzerror can be used before gzclose to detect this - case. - - gzread returns the number of uncompressed bytes actually read, less than - len for end of file, or -1 for error. -*/ - -ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); -/* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes written or 0 in case of - error. -*/ - -ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); -/* - Converts, formats, and writes the arguments to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written, or 0 in case of error. The number of - uncompressed bytes written is limited to 8191, or one less than the buffer - size given to gzbuffer(). The caller should assure that this limit is not - exceeded. If it is exceeded, then gzprintf() will return an error (0) with - nothing written. In this case, there may also be a buffer overflow with - unpredictable consequences, which is possible only if zlib was compiled with - the insecure functions sprintf() or vsprintf() because the secure snprintf() - or vsnprintf() functions were not available. This can be determined using - zlibCompileFlags(). -*/ - -ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); -/* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - - gzputs returns the number of characters written, or -1 in case of error. -*/ - -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); -/* - Reads bytes from the compressed file until len-1 characters are read, or a - newline character is read and transferred to buf, or an end-of-file - condition is encountered. If any characters are read or if len == 1, the - string is terminated with a null character. If no characters are read due - to an end-of-file or len < 1, then the buffer is left untouched. - - gzgets returns buf which is a null-terminated string, or it returns NULL - for end-of-file or in case of error. If there was an error, the contents at - buf are indeterminate. -*/ - -ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); -/* - Writes c, converted to an unsigned char, into the compressed file. gzputc - returns the value that was written, or -1 in case of error. -*/ - -ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); -/* - Reads one byte from the compressed file. gzgetc returns this byte or -1 - in case of end of file or error. This is implemented as a macro for speed. - As such, it does not do all of the checking the other functions do. I.e. - it does not check to see if file is NULL, nor whether the structure file - points to has been clobbered or not. -*/ - -ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); -/* - Push one character back onto the stream to be read as the first character - on the next read. At least one character of push-back is allowed. - gzungetc() returns the character pushed, or -1 on failure. gzungetc() will - fail if c is -1, and may fail if a character has been pushed but not read - yet. If gzungetc is used immediately after gzopen or gzdopen, at least the - output buffer size of pushed characters is allowed. (See gzbuffer above.) - The pushed character will be discarded if the stream is repositioned with - gzseek() or gzrewind(). -*/ - -ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); -/* - Flushes all pending output into the compressed file. The parameter flush - is as in the deflate() function. The return value is the zlib error number - (see function gzerror below). gzflush is only permitted when writing. - - If the flush parameter is Z_FINISH, the remaining data is written and the - gzip stream is completed in the output. If gzwrite() is called again, a new - gzip stream will be started in the output. gzread() is able to read such - concatented gzip streams. - - gzflush should be called only when strictly necessary because it will - degrade compression if called too often. -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); - - Sets the starting position for the next gzread or gzwrite on the given - compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); -/* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); - - Returns the starting position for the next gzread or gzwrite on the given - compressed file. This position represents a number of bytes in the - uncompressed data stream, and is zero when starting, even if appending or - reading a gzip stream from the middle of a file using gzdopen(). - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); - - Returns the current offset in the file being read or written. This offset - includes the count of bytes that precede the gzip stream, for example when - appending or when using gzdopen() for reading. When reading, the offset - does not include as yet unused buffered input. This information can be used - for a progress indicator. On error, gzoffset() returns -1. -*/ - -ZEXTERN int ZEXPORT gzeof OF((gzFile file)); -/* - Returns true (1) if the end-of-file indicator has been set while reading, - false (0) otherwise. Note that the end-of-file indicator is set only if the - read tried to go past the end of the input, but came up short. Therefore, - just like feof(), gzeof() may return false even if there is no more data to - read, in the event that the last read request was for the exact number of - bytes remaining in the input file. This will happen if the input file size - is an exact multiple of the buffer size. - - If gzeof() returns true, then the read functions will return no more data, - unless the end-of-file indicator is reset by gzclearerr() and the input file - has grown since the previous end of file was detected. -*/ - -ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); -/* - Returns true (1) if file is being copied directly while reading, or false - (0) if file is a gzip stream being decompressed. - - If the input file is empty, gzdirect() will return true, since the input - does not contain a gzip stream. - - If gzdirect() is used immediately after gzopen() or gzdopen() it will - cause buffers to be allocated to allow reading the file to determine if it - is a gzip file. Therefore if gzbuffer() is used, it should be called before - gzdirect(). - - When writing, gzdirect() returns true (1) if transparent writing was - requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: - gzdirect() is not needed when writing. Transparent writing must be - explicitly requested, so the application already knows the answer. When - linking statically, using gzdirect() will include all of the zlib code for - gzip file reading and decompression, which may not be desired.) -*/ - -ZEXTERN int ZEXPORT gzclose OF((gzFile file)); -/* - Flushes all pending output if necessary, closes the compressed file and - deallocates the (de)compression state. Note that once file is closed, you - cannot call gzerror with file, since its structures have been deallocated. - gzclose must not be called more than once on the same file, just as free - must not be called more than once on the same allocation. - - gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a - file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the - last read ended in the middle of a gzip stream, or Z_OK on success. -*/ - -ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); -ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); -/* - Same as gzclose(), but gzclose_r() is only for use when reading, and - gzclose_w() is only for use when writing or appending. The advantage to - using these instead of gzclose() is that they avoid linking in zlib - compression or decompression code that is not used when only reading or only - writing respectively. If gzclose() is used, then both compression and - decompression code will be included the application when linking to a static - zlib library. -*/ - -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); -/* - Returns the error message for the last error which occurred on the given - compressed file. errnum is set to zlib error number. If an error occurred - in the file system and not in the compression library, errnum is set to - Z_ERRNO and the application may consult errno to get the exact error code. - - The application must not modify the returned string. Future calls to - this function may invalidate the previously returned string. If file is - closed, then the string previously returned by gzerror will no longer be - available. - - gzerror() should be used to distinguish errors from end-of-file for those - functions above that do not distinguish those cases in their return values. -*/ - -ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); -/* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ - -#endif /* !Z_SOLO */ - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the compression - library. -*/ - -ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is Z_NULL, this function returns the - required initial value for the checksum. - - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. - - Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -/* -ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); - - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note - that the z_off_t type (like off_t) is a signed integer. If len2 is - negative, the result has no meaning or utility. -*/ - -ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); -/* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is Z_NULL, this function returns the required - initial value for the crc. Pre- and post-conditioning (one's complement) is - performed within this function so it shouldn't be done by the application. - - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -/* -ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); - - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); -ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ - (int)sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, (int)sizeof(z_stream)) - -#ifndef Z_SOLO - -/* gzgetc() macro and its supporting function and exposed data structure. Note - * that the real internal state is much larger than the exposed structure. - * This abbreviated structure exposes just enough for the gzgetc() macro. The - * user should not mess with these exposed elements, since their names or - * behavior could change in the future, perhaps even capriciously. They can - * only be used by the gzgetc() macro. You have been warned. - */ -struct gzFile_s { - unsigned have; - unsigned char *next; - z_off64_t pos; -}; -ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ -#ifdef Z_PREFIX_SET -# undef z_gzgetc -# define z_gzgetc(g) \ - ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) -#else -# undef gzgetc -# define gzgetc(g) \ - ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) -#endif - -/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or - * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if - * both are true, the application gets the *64 functions, and the regular - * functions are changed to 64 bits) -- in case these are set on systems - * without large file support, _LFS64_LARGEFILE must also be true - */ -#ifdef Z_LARGE64 - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); - ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); -#endif - -#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) -# ifdef Z_PREFIX_SET -# define z_gzopen z_gzopen64 -# define z_gzseek z_gzseek64 -# define z_gztell z_gztell64 -# define z_gzoffset z_gzoffset64 -# define z_adler32_combine z_adler32_combine64 -# define z_crc32_combine z_crc32_combine64 -# else -# define gzopen gzopen64 -# define gzseek gzseek64 -# define gztell gztell64 -# define gzoffset gzoffset64 -# define adler32_combine adler32_combine64 -# define crc32_combine crc32_combine64 -# endif -# ifndef Z_LARGE64 - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); - ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); -# endif -#else - ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); - ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); - ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); - ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); -#endif - -#else /* Z_SOLO */ - - ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); - -#endif /* !Z_SOLO */ - -/* hack for buggy compilers */ -#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; -#endif - -/* undocumented functions */ -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); -ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); -ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); -ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); -ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); -#if defined(_WIN32) && !defined(Z_SOLO) -ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, - const char *mode)); -#endif -#if defined(STDC) || defined(Z_HAVE_STDARG_H) -# ifndef Z_SOLO -ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, - const char *format, - va_list va)); -# endif -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* ZLIB_H */ diff --git a/win32/libs/glfw3-2015.lib b/win32/libs/glfw3-2015.lib deleted file mode 100644 index 0e4510eb..00000000 Binary files a/win32/libs/glfw3-2015.lib and /dev/null differ diff --git a/win32/libs/glfw3.lib b/win32/libs/glfw3.lib deleted file mode 100644 index 471d9325..00000000 Binary files a/win32/libs/glfw3.lib and /dev/null differ diff --git a/win32/libs/mozglue.lib b/win32/libs/mozglue.lib deleted file mode 100755 index 63b43b4d..00000000 Binary files a/win32/libs/mozglue.lib and /dev/null differ diff --git a/win32/libs/mozjs-52.dll b/win32/libs/mozjs-52.dll deleted file mode 100755 index 10bdd5f2..00000000 Binary files a/win32/libs/mozjs-52.dll and /dev/null differ diff --git a/win32/libs/mozjs-52.lib b/win32/libs/mozjs-52.lib deleted file mode 100755 index 44c241fe..00000000 Binary files a/win32/libs/mozjs-52.lib and /dev/null differ